answer
stringlengths
17
10.2M
package org.jdesktop.swingx.graphics; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.Raster; import java.awt.image.WritableRaster; import java.awt.GraphicsConfiguration; import java.awt.Transparency; import java.awt.Graphics; import java.awt.GraphicsEnvironment; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.io.IOException; import java.net.URL; import javax.imageio.ImageIO; /** * <p><code>GraphicsUtilities</code> contains a set of tools to perform * common graphics operations easily. These operations are divided into * several themes, listed below.</p> * * <h2>Compatible Images</h2> * * <p>Compatible images can, and should, be used to increase drawing * performance. This class provides a number of methods to load compatible * images directly from files or to convert existing images to compatibles * images.</p> * * <h2>Creating Thumbnails</h2> * * <p>This class provides a number of methods to easily scale down images. * Some of these methods offer a trade-off between speed and result quality and * shouuld be used all the time. They also offer the advantage of producing * compatible images, thus automatically resulting into better runtime * performance.</p> * * <p>All these methodes are both faster than * {@link java.awt.Image#getScaledInstance(int, int, int)} and produce * better-looking results than the various <code>drawImage()</code> methods * in {@link java.awt.Graphics}, which can be used for image scaling.</p> * <h2>Image Manipulation</h2> * * <p>This class provides two methods to get and set pixels in a buffered image. * These methods try to avoid unmanaging the image in order to keep good * performance.</p> * * @author Romain Guy <romain.guy@mac.com> * @author rbair */ public class GraphicsUtilities { private GraphicsUtilities() { } // Returns the graphics configuration for the primary screen private static GraphicsConfiguration getGraphicsConfiguration() { return GraphicsEnvironment.getLocalGraphicsEnvironment(). getDefaultScreenDevice().getDefaultConfiguration(); } private static boolean isHeadless() { return GraphicsEnvironment.isHeadless(); } /** * <p>Returns a new <code>BufferedImage</code> using the same color model * as the image passed as a parameter. The returned image is only compatible * with the image passed as a parameter. This does not mean the returned * image is compatible with the hardware.</p> * * @param image the reference image from which the color model of the new * image is obtained * @return a new <code>BufferedImage</code>, compatible with the color model * of <code>image</code> */ public static BufferedImage createColorModelCompatibleImage(BufferedImage image) { ColorModel cm = image.getColorModel(); return new BufferedImage(cm, cm.createCompatibleWritableRaster(image.getWidth(), image.getHeight()), cm.isAlphaPremultiplied(), null); } /** * <p>Returns a new compatible image with the same width, height and * transparency as the image specified as a parameter. That is, the * returned BufferedImage will be compatible with the graphics hardware. * If this method is called in a headless environment, then * the returned BufferedImage will be compatible with the source * image.</p> * * @see java.awt.Transparency * @see #createCompatibleImage(int, int) * @see #createCompatibleImage(java.awt.image.BufferedImage, int, int) * @see #createCompatibleTranslucentImage(int, int) * @see #loadCompatibleImage(java.net.URL) * @see #toCompatibleImage(java.awt.image.BufferedImage) * @param image the reference image from which the dimension and the * transparency of the new image are obtained * @return a new compatible <code>BufferedImage</code> with the same * dimension and transparency as <code>image</code> */ public static BufferedImage createCompatibleImage(BufferedImage image) { return createCompatibleImage(image, image.getWidth(), image.getHeight()); } /** * <p>Returns a new compatible image of the specified width and height, and * the same transparency setting as the image specified as a parameter. * That is, the returned <code>BufferedImage</code> is compatible with * the graphics hardware. If the method is called in a headless * environment, then the returned BufferedImage will be compatible with * the source image.</p> * * @see java.awt.Transparency * @see #createCompatibleImage(java.awt.image.BufferedImage) * @see #createCompatibleImage(int, int) * @see #createCompatibleTranslucentImage(int, int) * @see #loadCompatibleImage(java.net.URL) * @see #toCompatibleImage(java.awt.image.BufferedImage) * @param width the width of the new image * @param height the height of the new image * @param image the reference image from which the transparency of the new * image is obtained * @return a new compatible <code>BufferedImage</code> with the same * transparency as <code>image</code> and the specified dimension */ public static BufferedImage createCompatibleImage(BufferedImage image, int width, int height) { return isHeadless() ? new BufferedImage(width, height, image.getType()) : getGraphicsConfiguration().createCompatibleImage(width, height, image.getTransparency()); } /** * <p>Returns a new opaque compatible image of the specified width and * height. That is, the returned <code>BufferedImage</code> is compatible with * the graphics hardware. If the method is called in a headless * environment, then the returned BufferedImage will be compatible with * the source image.</p> * * @see #createCompatibleImage(java.awt.image.BufferedImage) * @see #createCompatibleImage(java.awt.image.BufferedImage, int, int) * @see #createCompatibleTranslucentImage(int, int) * @see #loadCompatibleImage(java.net.URL) * @see #toCompatibleImage(java.awt.image.BufferedImage) * @param width the width of the new image * @param height the height of the new image * @return a new opaque compatible <code>BufferedImage</code> of the * specified width and height */ public static BufferedImage createCompatibleImage(int width, int height) { return isHeadless() ? new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB) : getGraphicsConfiguration().createCompatibleImage(width, height); } /** * <p>Returns a new translucent compatible image of the specified width and * height. That is, the returned <code>BufferedImage</code> is compatible with * the graphics hardware. If the method is called in a headless * environment, then the returned BufferedImage will be compatible with * the source image.</p> * * @see #createCompatibleImage(java.awt.image.BufferedImage) * @see #createCompatibleImage(java.awt.image.BufferedImage, int, int) * @see #createCompatibleImage(int, int) * @see #loadCompatibleImage(java.net.URL) * @see #toCompatibleImage(java.awt.image.BufferedImage) * @param width the width of the new image * @param height the height of the new image * @return a new translucent compatible <code>BufferedImage</code> of the * specified width and height */ public static BufferedImage createCompatibleTranslucentImage(int width, int height) { return isHeadless() ? new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB) : getGraphicsConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT); } /** * <p>Returns a new compatible image from a URL. The image is loaded from the * specified location and then turned, if necessary into a compatible * image.</p> * * @see #createCompatibleImage(java.awt.image.BufferedImage) * @see #createCompatibleImage(java.awt.image.BufferedImage, int, int) * @see #createCompatibleImage(int, int) * @see #createCompatibleTranslucentImage(int, int) * @see #toCompatibleImage(java.awt.image.BufferedImage) * @param resource the URL of the picture to load as a compatible image * @return a new translucent compatible <code>BufferedImage</code> of the * specified width and height * @throws java.io.IOException if the image cannot be read or loaded */ public static BufferedImage loadCompatibleImage(URL resource) throws IOException { BufferedImage image = ImageIO.read(resource); return toCompatibleImage(image); } /** * <p>Return a new compatible image that contains a copy of the specified * image. This method ensures an image is compatible with the hardware, * and therefore optimized for fast blitting operations.</p> * * <p>If the method is called in a headless environment, then the returned * <code>BufferedImage</code> will be the source image.</p> * * @see #createCompatibleImage(java.awt.image.BufferedImage) * @see #createCompatibleImage(java.awt.image.BufferedImage, int, int) * @see #createCompatibleImage(int, int) * @see #createCompatibleTranslucentImage(int, int) * @see #loadCompatibleImage(java.net.URL) * @param image the image to copy into a new compatible image * @return a new compatible copy, with the * same width and height and transparency and content, of <code>image</code> */ public static BufferedImage toCompatibleImage(BufferedImage image) { if (isHeadless()) { return image; } if (image.getColorModel().equals( getGraphicsConfiguration().getColorModel())) { return image; } BufferedImage compatibleImage = getGraphicsConfiguration().createCompatibleImage( image.getWidth(), image.getHeight(), image.getTransparency()); Graphics g = compatibleImage.getGraphics(); g.drawImage(image, 0, 0, null); g.dispose(); return compatibleImage; } public static BufferedImage createThumbnailFast(BufferedImage image, int newSize) { float ratio; int width = image.getWidth(); int height = image.getHeight(); if (width > height) { if (newSize >= width) { throw new IllegalArgumentException("newSize must be lower than" + " the image width"); } else if (newSize <= 0) { throw new IllegalArgumentException("newSize must" + " be greater than 0"); } ratio = (float) width / (float) height; width = newSize; height = (int) (newSize / ratio); } else { if (newSize >= height) { throw new IllegalArgumentException("newSize must be lower than" + " the image height"); } else if (newSize <= 0) { throw new IllegalArgumentException("newSize must" + " be greater than 0"); } ratio = (float) height / (float) width; height = newSize; width = (int) (newSize / ratio); } BufferedImage temp = createCompatibleImage(image, width, height); Graphics2D g2 = temp.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(image, 0, 0, temp.getWidth(), temp.getHeight(), null); g2.dispose(); return temp; } public static BufferedImage createThumbnailFast(BufferedImage image, int newWidth, int newHeight) { if (newWidth >= image.getWidth() || newHeight >= image.getHeight()) { throw new IllegalArgumentException("newWidth and newHeight cannot" + " be greater than the image" + " dimensions"); } else if (newWidth <= 0 || newHeight <= 0) { throw new IllegalArgumentException("newWidth and newHeight must" + " be greater than 0"); } BufferedImage temp = createCompatibleImage(image, newWidth, newHeight); Graphics2D g2 = temp.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(image, 0, 0, temp.getWidth(), temp.getHeight(), null); g2.dispose(); return temp; } public static BufferedImage createThumbnail(BufferedImage image, int newSize) { int width = image.getWidth(); int height = image.getHeight(); boolean isWidthGreater = width > height; if (isWidthGreater) { if (newSize >= width) { throw new IllegalArgumentException("newSize must be lower than" + " the image width"); } } else if (newSize >= height) { throw new IllegalArgumentException("newSize must be lower than" + " the image height"); } if (newSize <= 0) { throw new IllegalArgumentException("newSize must" + " be greater than 0"); } float ratioWH = (float) width / (float) height; float ratioHW = (float) height / (float) width; BufferedImage thumb = image; BufferedImage temp; Graphics2D g2; int previousWidth = width; int previousHeight = height; do { if (isWidthGreater) { width /= 2; if (width < newSize) { width = newSize; } height = (int) (width / ratioWH); } else { height /= 2; if (height < newSize) { height = newSize; } width = (int) (height / ratioHW); } temp = createCompatibleImage(image, width, height); g2 = temp.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(thumb, 0, 0, width, height, 0, 0, previousWidth, previousHeight, null); previousWidth = width; previousHeight = height; thumb = temp; } while (newSize != (isWidthGreater ? width : height)); g2.dispose(); if (width != thumb.getWidth() || height != thumb.getHeight()) { temp = createCompatibleImage(image, width, height); g2 = temp.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(thumb, 0, 0, width, height, null); g2.dispose(); thumb = temp; } return thumb; } public static BufferedImage createThumbnail(BufferedImage image, int newWidth, int newHeight) { int width = image.getWidth(); int height = image.getHeight(); if (newWidth >= width || newHeight >= height) { throw new IllegalArgumentException("newWidth and newHeight cannot" + " be greater than the image" + " dimensions"); } else if (newWidth <= 0 || newHeight <= 0) { throw new IllegalArgumentException("newWidth and newHeight must" + " be greater than 0"); } BufferedImage thumb = image; BufferedImage temp; Graphics2D g2; int previousWidth = width; int previousHeight = height; do { if (width > newWidth) { width /= 2; if (width < newWidth) { width = newWidth; } } if (height > newHeight) { height /= 2; if (height < newHeight) { height = newHeight; } } temp = createCompatibleImage(image, width, height); g2 = temp.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(thumb, 0, 0, width, height, 0, 0, previousWidth, previousHeight, null); previousWidth = width; previousHeight = height; thumb = temp; } while (width != newWidth || height != newHeight); g2.dispose(); if (width != thumb.getWidth() || height != thumb.getHeight()) { temp = createCompatibleImage(image, width, height); g2 = temp.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(thumb, 0, 0, width, height, null); g2.dispose(); thumb = temp; } return thumb; } public static int[] getPixels(BufferedImage img, int x, int y, int w, int h, int[] pixels) { if (w == 0 || h == 0) { return new int[0]; } if (pixels == null) { pixels = new int[w * h]; } else if (pixels.length < w * h) { throw new IllegalArgumentException("pixels array must have a length" + " >= w*h"); } int imageType = img.getType(); if (imageType == BufferedImage.TYPE_INT_ARGB || imageType == BufferedImage.TYPE_INT_RGB) { Raster raster = img.getRaster(); return (int[]) raster.getDataElements(x, y, w, h, pixels); } // Unmanages the image return img.getRGB(x, y, w, h, pixels, 0, w); } public static void setPixels(BufferedImage img, int x, int y, int w, int h, int[] pixels) { if (pixels == null || w == 0 || h == 0) { return; } else if (pixels.length < w * h) { throw new IllegalArgumentException("pixels array must have a length" + " >= w*h"); } int imageType = img.getType(); if (imageType == BufferedImage.TYPE_INT_ARGB || imageType == BufferedImage.TYPE_INT_RGB) { WritableRaster raster = img.getRaster(); raster.setDataElements(x, y, w, h, pixels); } else { // Unmanages the image img.setRGB(x, y, w, h, pixels, 0, w); } } }
package com.facebook.litho; import java.util.Collections; import java.util.Map; import android.support.v4.util.ArrayMap; import com.facebook.litho.annotations.TreeProp; import com.facebook.infer.annotation.ThreadConfined; import com.facebook.infer.annotation.ThreadSafe; /** * A data structure to store tree props. * @see {@link TreeProp}. */ @ThreadConfined(ThreadConfined.ANY) public class TreeProps { private final ArrayMap<Class, Object> mMap = new ArrayMap<>(); public void put(Class key, Object value) { mMap.put(key, value); } public <T> T get(Class key) { return (T) mMap.get(key); } public Map<Class, Object> toMap() { return Collections.unmodifiableMap(mMap); } /** * Whenever a Spec sets tree props, the TreeProps map from the parent is copied. * * Infer knows that newProps is owned but doesn't know that newProps.mMap is owned. */ @ThreadSafe(enableChecks = false) public static TreeProps copy(TreeProps source) { final TreeProps newProps = ComponentsPools.acquireTreeProps(); if (source != null) { newProps.mMap.putAll((Map<? extends Class, ?>) source.mMap); } return newProps; } void reset() { mMap.clear(); } }
package kr.pe.kwonnam.fdqlbuilder.methods; import freemarker.template.*; import kr.pe.kwonnam.fdqlbuilder.objectunwrapper.TemplateModelObjectUnwrapper; import kr.pe.kwonnam.fdqlbuilder.paramconverter.ParameterConverter; import org.slf4j.Logger; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import static org.slf4j.LoggerFactory.getLogger; /** * ParamMethod take a query parameter object from freemarker templates, * and adds the parameter object to {@link #parameters} list.<br/> * Finally this puts a {@code ?} jdbc query parameter bind character to the template result. * <p/> * Usage : <code>${param(parameter[, parameterConverterName]}</code><br/> * <ul> * <li>{@code parameter} will be bound to {@link java.sql.PreparedStatement} parameter.</li> * <li>{@code converterName} is used to find {@link ParameterConverter} and convvert the parameter to another object.</li> * </ul> * <p/> * This is NOT thread safe. Each template processing request must create new instance. * * @see ParameterConverter */ public class ParamMethod implements TemplateMethodModelEx { public static final SimpleScalar JDBC_POSITIONAL_PARAMETER_STRING = new SimpleScalar("?"); private Logger log = getLogger(ParamMethod.class); /** * Query Parameters to be bound */ private List<Object> parameters = new ArrayList<Object>(); /** * To unwrap freemarker {@link TemplateModel} object */ private TemplateModelObjectUnwrapper templateModelObjectUnwrapper; /** * To convert parameters to another type */ private Map<String, ParameterConverter> parameterConverters; public ParamMethod(TemplateModelObjectUnwrapper templateModelObjectUnwrapper, Map<String, ParameterConverter> parameterConverters) { if (templateModelObjectUnwrapper == null) { throw new IllegalArgumentException("templateModelObjectUnwrapper must not be null."); } if (parameterConverters == null) { throw new IllegalArgumentException("parameterConverters must not be null."); } this.templateModelObjectUnwrapper = templateModelObjectUnwrapper; this.parameterConverters = parameterConverters; } public List<Object> getParameters() { return Collections.unmodifiableList(parameters); } @Override public Object exec(List arguments) throws TemplateModelException { checkArgumentsConditions(arguments); Object queryParam = arguments.get(0); log.debug("Original QueryParam : {}", queryParam); queryParam = unwrapQueryParam(queryParam); queryParam = processParameterConverter(arguments, queryParam); parameters.add(queryParam); return JDBC_POSITIONAL_PARAMETER_STRING; } private void checkArgumentsConditions(List arguments) { int argumentsSize = arguments.size(); if (argumentsSize == 0) { throw new IllegalArgumentException("Query parameter required."); } if (argumentsSize > 2) { throw new IllegalArgumentException("paramMethod's argument must be 1 or 2 but " + argumentsSize + "."); } } private Object processParameterConverter(List arguments, Object queryParam) { if (arguments.size() != 2) { return queryParam; } String parameterConverterName = parseParameterConverterName(arguments); ParameterConverter parameterConverter = findParameterConverter(parameterConverterName); Object converted = parameterConverter.convert(queryParam); log.debug("Original QueryParam {} converted to {}", queryParam, converted); return converted; } private String parseParameterConverterName(List arguments) { SimpleScalar parameterConverterNameScalar = (SimpleScalar) arguments.get(1); if (parameterConverterNameScalar == null) { throw new IllegalArgumentException("parameterConverterName must not be null."); } return parameterConverterNameScalar.getAsString(); } private ParameterConverter findParameterConverter(String parameterConverterName) { ParameterConverter parameterConverter = parameterConverters.get(parameterConverterName); if (parameterConverter == null) { throw new IllegalArgumentException("parameterConverter - " + parameterConverterName + " does not exist."); } return parameterConverter; } private Object unwrapQueryParam(Object queryParam) throws TemplateModelException { if (!(queryParam instanceof TemplateModel)) { return queryParam; } Object unwrapped = templateModelObjectUnwrapper.unwrap((TemplateModel)queryParam); log.debug("Unwrapped QueryParam : {}", unwrapped); return unwrapped; } }
package ru.yandex.market.graphouse.search; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Required; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowCallbackHandler; import ru.yandex.common.util.db.BulkUpdater; import ru.yandex.market.graphite.MetricValidator; import ru.yandex.market.monitoring.ComplicatedMonitoring; import ru.yandex.market.monitoring.MonitoringUnit; import java.io.IOException; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collections; import java.util.List; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; /** * @author Dmitry Andreev <a href="mailto:AndreevDm@yandex-team.ru"/> * @date 07/04/15 */ public class MetricSearch implements InitializingBean, Runnable { private static final Logger log = LogManager.getLogger(); private static final int BATCH_SIZE = 5_000; private JdbcTemplate graphouseJdbcTemplate; private ComplicatedMonitoring monitoring; private MetricValidator metricValidator; private MonitoringUnit metricSearchUnit = new MonitoringUnit("MetricSearch"); private final MetricTree metricTree = new MetricTree(); private final Queue<MetricDescription> updateQueue = new ConcurrentLinkedQueue<>(); private int lastUpdatedTimestampSeconds = 0; private int saveIntervalSeconds = 300; private int updateDelaySeconds = 120; @Override public void afterPropertiesSet() throws Exception { initDatabase(); monitoring.addUnit(metricSearchUnit); new Thread(this, "MetricSearch thread").start(); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { log.info("Shutting down Metric search"); saveNewMetrics(); log.info("Metric search stopped"); } })); } private void initDatabase() { graphouseJdbcTemplate.update( "CREATE TABLE IF NOT EXISTS metric (" + " `NAME` VARCHAR(200) NOT NULL, " + " `status` TINYINT NOT NULL DEFAULT 0, " + " `UPDATED` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, " + " PRIMARY KEY (`NAME`), " + " INDEX (`UPDATED`)" + ") " ); } private void loadMetrics(int startTimestampSeconds) { log.info("Loading metric names from db"); final AtomicInteger metricCount = new AtomicInteger(); graphouseJdbcTemplate.query( "SELECT name, status FROM metric WHERE updated >= FROM_UNIXTIME(?)", new RowCallbackHandler() { @Override public void processRow(ResultSet rs) throws SQLException { String metric = rs.getString("name"); MetricStatus status = MetricStatus.forId(rs.getInt("status")); if (!metricValidator.validate(metric, true)) { log.warn("Invalid metric in db: " + metric); return; } metricTree.add(metric, status); metricCount.incrementAndGet(); } }, startTimestampSeconds ); log.info("Loaded " + metricCount.get() + " metrics"); } private void saveNewMetrics() { if (!updateQueue.isEmpty()) { log.info("Saving new metric names to db"); int count = 0; BulkUpdater bulkUpdater = new BulkUpdater( graphouseJdbcTemplate, "INSERT IGNORE INTO metric (name) values (?)", BATCH_SIZE ); MetricDescription metric; while ((metric = updateQueue.poll()) != null) { bulkUpdater.submit(metric.getName()); count++; } bulkUpdater.done(); log.info("Saved " + count + " metric names"); } else { log.info("No new metric names to save"); } } @Override public void run() { while (!Thread.interrupted()) { try { loadNewMetrics(); saveNewMetrics(); metricSearchUnit.ok(); } catch (Exception e) { log.error("Failed to update metric search", e); metricSearchUnit.critical("Failed to update metric search: " + e.getMessage(), e); } try { Thread.sleep(TimeUnit.SECONDS.toMillis(saveIntervalSeconds)); } catch (InterruptedException ignored) { } } } public void loadNewMetrics() { int timeSeconds = (int) (TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis())) - updateDelaySeconds; loadMetrics(lastUpdatedTimestampSeconds); lastUpdatedTimestampSeconds = timeSeconds; } public MetricDescription add(String metric) { QueryStatus status = metricTree.add(metric); if (status == QueryStatus.NEW || status == QueryStatus.UPDATED) { updateQueue.add(metric); } return status; } public int multiModify(String query, final MetricStatus status, final Appendable result) throws IOException { final StringBuilder metricBuilder = new StringBuilder(); final AtomicInteger count = new AtomicInteger(); metricTree.search(query, new Appendable() { @Override public Appendable append(CharSequence csq) { metricBuilder.append(csq); return this; } @Override public Appendable append(CharSequence csq, int start, int end) { metricBuilder.append(csq, start, end); return this; } @Override public Appendable append(char c) throws IOException { if (c == '\n') { modify(metricBuilder.toString(), status); if (result != null) { result.append(metricBuilder).append('\n'); } metricBuilder.setLength(0); count.incrementAndGet(); } else { metricBuilder.append(c); } return this; } }); return count.get(); } public void modify(String metric, MetricStatus status) { modify(Collections.singletonList(metric), status); } public void modify(List<String> metrics, MetricStatus status) { if (metrics == null || metrics.isEmpty()) { return; } if (status.equals(MetricStatus.SIMPLE)) { throw new IllegalStateException(); } BulkUpdater bulkUpdater = new BulkUpdater( graphouseJdbcTemplate, "INSERT INTO metric (name, status) VALUES (?, ?) " + "ON DUPLICATE KEY UPDATE status = ?, " + " updated = IF(status != ?, CURRENT_TIMESTAMP, updated)", BATCH_SIZE ); for (String metric : metrics) { if (!metricValidator.validate(metric, true)) { log.warn("Wrong metric to modify: " + metric); continue; } bulkUpdater.submit(metric, status.getId(), status.getId(), status.getId()); metricTree.add(metric, status); } bulkUpdater.done(); if (metrics.size() == 1) { log.info("Updated metric '" + metrics.get(0) + "', status: " + status.name()); } else { log.info("Updated " + metrics.size() + " metrics, status: " + status.name()); } } public void search(String query, Appendable result) throws IOException { metricTree.search(query, result); } @Required public void setGraphouseJdbcTemplate(JdbcTemplate graphouseJdbcTemplate) { this.graphouseJdbcTemplate = graphouseJdbcTemplate; } @Required public void setMonitoring(ComplicatedMonitoring monitoring) { this.monitoring = monitoring; } @Required public void setMetricValidator(MetricValidator metricValidator) { this.metricValidator = metricValidator; } public void setSaveIntervalSeconds(int saveIntervalSeconds) { this.saveIntervalSeconds = saveIntervalSeconds; } public void setUpdateDelaySeconds(int updateDelaySeconds) { this.updateDelaySeconds = updateDelaySeconds; } }
package com.mikepenz.fastadapter.app; import android.graphics.Color; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import com.mikepenz.fastadapter.FastAdapter; import com.mikepenz.fastadapter.IAdapter; import com.mikepenz.fastadapter.adapters.FastItemAdapter; import com.mikepenz.fastadapter.app.items.RealmSampleUserItem; import com.mikepenz.iconics.IconicsDrawable; import com.mikepenz.material_design_iconic_typeface_library.MaterialDesignIconic; import com.mikepenz.materialize.MaterializeBuilder; import java.util.LinkedList; import java.util.List; import io.realm.Realm; import io.realm.RealmChangeListener; import io.realm.RealmResults; public class RealmActivity extends AppCompatActivity { //save our FastAdapter private FastItemAdapter<RealmSampleUserItem> mFastItemAdapter; //save our Realm instance to close it later private Realm mRealm; @Override protected void onCreate(final Bundle savedInstanceState) { findViewById(android.R.id.content).setSystemUiVisibility(findViewById(android.R.id.content).getSystemUiVisibility() | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Handle Toolbar Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setTitle(R.string.sample_realm_list); //style our ui new MaterializeBuilder().withActivity(this).build(); //create our FastAdapter which will manage everything mFastItemAdapter = new FastItemAdapter<>(); //configure our fastAdapter mFastItemAdapter.withOnClickListener(new FastAdapter.OnClickListener<RealmSampleUserItem>() { @Override public boolean onClick(View v, IAdapter<RealmSampleUserItem> adapter, RealmSampleUserItem item, int position) { Toast.makeText(v.getContext(), item.getName(), Toast.LENGTH_SHORT).show(); return false; } }); //get our recyclerView and do basic setup RecyclerView rv = (RecyclerView) findViewById(R.id.rv); rv.setLayoutManager(new LinearLayoutManager(this)); rv.setItemAnimator(new DefaultItemAnimator()); rv.setAdapter(mFastItemAdapter); //Get a realm instance for this activity mRealm = Realm.getDefaultInstance(); mRealm.where(RealmSampleUserItem.class).findAllAsync().addChangeListener(new RealmChangeListener<RealmResults<RealmSampleUserItem>>() { @Override public void onChange(RealmResults<RealmSampleUserItem> userItems) { //This will call twice //1.) from findAllAsync() //2.) from createData() mFastItemAdapter.set(userItems); } }); //fill with some sample data createData(); //set the back arrow in the toolbar getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(false); //restore selections (this has to be done after the items were added mFastItemAdapter.withSavedInstanceState(savedInstanceState); } private void createData() { //Execute transaction mRealm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm realm) { List<RealmSampleUserItem> users = new LinkedList<>(); for (int i = 1; i <= 50; i++) { RealmSampleUserItem user = new RealmSampleUserItem(); user.withName("Sample Realm Element " + i).withIdentifier(i); users.add(user); } //insert the created objects to realm //a bulk insert has lower object allocations then a copy realm.insertOrUpdate(users); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_add, menu); menu.findItem(R.id.item_add).setIcon(new IconicsDrawable(this, MaterialDesignIconic.Icon.gmi_plus_square).color(Color.BLACK).actionBar()); return true; } @Override protected void onSaveInstanceState(Bundle outState) { //add the values which need to be saved from the adapter to the bundel outState = mFastItemAdapter.saveInstanceState(outState); super.onSaveInstanceState(outState); } @Override public boolean onOptionsItemSelected(MenuItem item) { //handle the click on the back arrow click switch (item.getItemId()) { case android.R.id.home: onBackPressed(); return true; case R.id.item_add: mRealm.where(RealmSampleUserItem.class).findAllAsync().addChangeListener(new RealmChangeListener<RealmResults<RealmSampleUserItem>>() { @Override public void onChange(RealmResults<RealmSampleUserItem> userItems) { //Remove the change listener userItems.removeChangeListener(this); //Store the primary key to get access from a other thread final long newPrimaryKey = userItems.last().getIdentifier() + 1; mRealm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm realm) { RealmSampleUserItem newUser = realm.createObject(RealmSampleUserItem.class); newUser.withName("Sample Realm Element " + newPrimaryKey) .withIdentifier(newPrimaryKey); } }); } }); return true; default: return super.onOptionsItemSelected(item); } } //Prevent the realm instance from leaking @Override protected void onDestroy() { super.onDestroy(); closeRealm(); } private void closeRealm() { if (!mRealm.isClosed()) { mRealm.close(); } } }
package net.intelie.lognit.cli.http; import com.google.common.collect.Iterators; import com.google.common.io.ByteStreams; import net.intelie.lognit.cli.json.Jsonizer; import org.apache.commons.httpclient.Cookie; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.UsernamePasswordCredentials; import org.apache.commons.httpclient.auth.AuthScope; import org.apache.commons.httpclient.cookie.CookiePolicy; import org.apache.commons.httpclient.cookie.CookieSpec; import org.apache.commons.httpclient.cookie.RFC2965Spec; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.protocol.Protocol; import org.cometd.bayeux.Channel; import org.cometd.bayeux.Message; import org.cometd.bayeux.client.ClientSession; import org.cometd.bayeux.client.ClientSessionChannel; import org.cometd.client.BayeuxClient; import org.cometd.client.ext.AckExtension; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URI; public class RestClientImpl implements RestClient { private static final CookieSpec COOKIE_SPEC = new RFC2965Spec(); private final HttpClient client; private final MethodFactory methods; private final BayeuxFactory bayeux; private final Jsonizer jsonizer; private String server; private boolean authenticated; public RestClientImpl(HttpClient client, MethodFactory methods, BayeuxFactory bayeux, Jsonizer jsonizer) throws Exception { this.client = client; this.methods = methods; this.bayeux = bayeux; this.jsonizer = jsonizer; this.server = "localhost"; this.authenticated = false; } @Override public RestState getState() { return new RestState(client.getState().getCookies(), server); } @Override public void setState(RestState state) { client.getState().clearCookies(); setServer(state.getServer()); client.getState().addCookies(state.getCookies()); } public String getServer() { return server; } @Override public void setServer(String server) { this.server = server; } @Override public void authenticate(String username, String password) { client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); client.getParams().setAuthenticationPreemptive(true); this.authenticated = true; } @Override public <T> T get(String uri, Class<T> type) throws IOException { GetMethod method = methods.get(prependServer(uri)); execute(method); return deserializeBody(method, type); } @Override public <T> RestStream<T> getStream(String uri, Class<T> type) throws IOException { GetMethod method = methods.get(prependServer(uri)); execute(method); return deserializeBodyStream(method, type); } @Override public <T> T post(String uri, Entity entity, Class<T> type) throws IOException { PostMethod method = methods.post(prependServer(uri)); entity.executeOn(method); execute(method); return deserializeBody(method, type); } private <T> RestStream<T> deserializeBodyStream(HttpMethod method, Class<T> type) throws IOException { InputStream stream = method.getResponseBodyAsStream(); if (stream == null) return new RestStream<T>(Iterators.<T>emptyIterator(), null); return new RestStream<T>(jsonizer.from(stream, type), stream); } private <T> T deserializeBody(HttpMethod method, Class<T> type) throws IOException { InputStream stream = method.getResponseBodyAsStream(); if (stream == null) return null; String body = new String(ByteStreams.toByteArray(stream)); return jsonizer.from(body, type); } @Override public <T> RestListenerHandle listen(String channel, final Class<T> type, final RestListener<T> listener) throws IOException { String url = prependServer("cometd"); BayeuxClient cometd = bayeux.create(url); //cometd.addExtension(new AckExtension()); Cookie[] cookies = getMatchingCookies(url); for (Cookie cookie : cookies) cometd.setCookie(cookie.getName(), cookie.getValue()); cometd.handshake(120000); final BayeuxHandle handle = new BayeuxHandle(cometd, channel); cometd.getChannel("/meta/connect").addListener(new ClientSessionChannel.MessageListener() { @Override public void onMessage(ClientSessionChannel channel, Message message) { if (!message.isSuccessful()) handle.invalidate(); } }); cometd.getChannel(channel).subscribe(new JsonMessageListener<T>(listener, type, jsonizer)); return handle; } private Cookie[] getMatchingCookies(String url) { URI uri = URI.create(url); Cookie[] cookies = client.getState().getCookies(); if (cookies == null) return new Cookie[0]; return COOKIE_SPEC.match(uri.getHost(), httpPort(uri), uri.getPath(), isHttps(uri), cookies); } private boolean isHttps(URI uri) { return "https".equalsIgnoreCase(uri.getScheme()); } private int httpPort(URI uri) { int port = uri.getPort(); if (port == -1) return isHttps(uri) ? 443 : 80; return port; } private String prependServer(String uri) throws MalformedURLException { String safeUri = uri.startsWith("/") ? uri : "/" + uri; String safeServer = server.startsWith("http: uri = String.format("%s%s", safeServer, safeUri); return uri; } private void execute(HttpMethod method) throws IOException { method.getParams().setCookiePolicy(CookiePolicy.DEFAULT); method.setDoAuthentication(authenticated); int response = client.executeMethod(method); if (response >= 300 && response < 500) throw new UnauthorizedException(method.getStatusLine()); if (response < 200 || response >= 300) throw new RequestFailedException(method.getStatusLine()); } }
package de.mpicbg.tds.knime.hcstools.utils; import org.apache.commons.math.random.RandomData; import org.apache.commons.math.random.RandomDataImpl; import org.apache.commons.math.stat.descriptive.DescriptiveStatistics; public class MutualInformation { private Double logbase = 2.0; // logarithmic logbase private String method = "biased"; private boolean linkaxes = true; // calculate one single axe using the data for the combined data from x and y. private int Nx = 100; // Number of bins for vector x private int Ny = 100; // Number of bins for vector y private Double[] x; // vector containing samples of variable X private Double[] y; // vector containing samples of variable Y // Constructors public MutualInformation() { } public MutualInformation(String method, int n, double logbase) { this.set_binning(n); this.set_method(method); this.set_base(logbase); } public MutualInformation(Double[] x, Double[] y) { this.set_vectors(x, y); this.set_binning(); } public MutualInformation(Double[] x, Double[] y, int n) { this.set_vectors(x, y); this.set_binning(n); } public MutualInformation(Double[] x, Double[] y, int nx, int ny) { this.set_vectors(x, y); this.set_binning(nx, ny); } public MutualInformation(Double[] x, Double[] y, String method) { this(x, y); this.set_method(method); } // Setter public void set_base(Double b) { if (!(b == 2 || b == Math.exp(1))) System.out.println("The logbase is usually choosen to be 2 or e."); if (b < 0) throw new RuntimeException("The logbase has to be a positive Real number"); logbase = b; } public void set_binning() { int bins = (int) Math.ceil(Math.pow(Math.max(x.length, y.length), 1.0 / 3.0)); set_binning(bins); } public void set_binning(int n) { if (n < 1) throw new RuntimeException("The number of bins of " + n + " is too small." + ". Probably there are too few samples, or consider setting the number of bins in the sintanciation."); Nx = n; Ny = n; } public void set_binning(int n1, int n2) { if (n1 < 1 || n2 < 1) throw new RuntimeException("The number of bins of " + n1 + "or " + n2 + " is too small." + "Probably there are too few samples, or consider setting the number of bins in the sintanciation."); Nx = n1; Ny = n2; } public void set_xvector(Double[] v) { x = v; } public void set_yvector(Double[] v) { y = v; } public void set_vectors(Double[] v1, Double[] v2) { x = v1; y = v2; } public void set_method(String method) { this.method = method; } public void set_axeslinking(boolean flag) { this.linkaxes = flag; } // Getter public int[] get_binning() { return new int[]{this.Nx, this.Ny}; } public Double[] get_xvector() { return this.x; } public Double[] get_yvector() { return this.y; } public String get_method() { return this.method; } public double get_logbase() { return this.logbase; } // Methods public Double[] calculate() throws Exception { if (x.length < 10 || y.length < 10) throw new RuntimeException("Too few samples."); Double[] res; if (method.contentEquals("unbiased")) { res = unbiased(); } else if (method.contentEquals("biased")) { res = biased(); } else if (method.contentEquals("mms_estimate")) { res = mms_estimate(); } else { throw new RuntimeException("The method '" + method + "' is unknown."); } res = basetransform(res, logbase); return res; } // Private helper methods private Double[] unbiased() { Double[] values = biased(); values[0] = values[0] - values[2]; values[2] = 0.0; return values; } private Double[] mms_estimate() { Double[] values = biased(); values[0] = values[0] - values[2]; Double lambda = Math.pow(values[0], 2) / (Math.pow(values[0], 2) + Math.pow(values[1], 2)); values[2] = (1 - lambda) * values[0]; values[0] = lambda * values[0]; values[1] = lambda * values[1]; return values; } private Double[] biased() { double[][] H = histogram2(); // total-sum, row-sum and column-sum int r = H.length; int c = H[1].length; double[] Hx = new double[r]; double[] Hy = new double[c]; int count = 0; for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { Hx[i] += H[i][j]; Hy[i] += H[j][i]; count += H[i][j]; } } // Calculate mutual information. Double mutualinfo = 0.0; Double sigma = 0.0; Double logf; for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { logf = log(H[i][j], Hx[i], Hy[j]); mutualinfo += H[i][j] * logf; sigma += H[i][j] * Math.pow(logf, 2); } } mutualinfo /= count; sigma = Math.sqrt((sigma / count - Math.pow(mutualinfo, 2)) / (count - 1)); mutualinfo += Math.log(count); Double bias = (double) (r - 1) * (c - 1) / (2 * count); return new Double[]{mutualinfo, sigma, bias}; } private double[][] histogram2() { // Get min and max of the scale(s) Double[] mima1; Double[] mima2; if (linkaxes) { mima1 = minmax(x, y); mima2 = mima1; } else { mima1 = minmax(x); mima2 = minmax(y); } // Calculate upper and lower bounds Double de1 = (mima1[1] - mima1[0]) / (x.length - 1); Double lb1 = mima1[0] - de1 / 2; Double ub1 = mima1[1] + de1 / 2; Double ra1 = (ub1 - lb1); Double de2 = (mima2[1] - mima2[0]) / (y.length - 1); Double lb2 = mima2[0] - de2 / 2; Double ub2 = mima2[1] + de2 / 2; Double ra2 = (ub2 - lb2); // Bring the vectors to the same length. if (x.length < y.length) { System.out.println("Warning: the vector lenghts (currrent:" + x.length + "," + y.length + ") need to be equal. Bottstrapped x."); x = bootstrap(x, y.length); } else if (x.length > y.length) { System.out.println("Warning: the vector lenghts (currrent:" + x.length + "," + y.length + ") need to be equal. Bottstrapped y."); y = bootstrap(y, x.length); } // Correct the binning. if ((Nx >= x.length) || (Ny >= y.length)) { System.out.println("Binning exceeded vector length and was set to" + Nx + "."); set_binning(); } // Compute the histogram/probability double[][] prob = new double[Nx][Ny]; for (int i = 0; i < x.length; i++) { int ind1 = (int) Math.round((x[i] - lb1) / ra1 * Nx + 0.5); int ind2 = (int) Math.round((y[i] - lb2) / ra2 * Ny + 0.5); if ((1 <= ind1) & (ind1 <= Nx) & (1 <= ind2) & (ind2 <= Ny)) { prob[ind1 - 1][ind2 - 1] += 1; } } return prob; } private Double[] minmax(Double[] vect) { DescriptiveStatistics stats = new DescriptiveStatistics(); for (Double value : vect) { stats.addValue(value); } return new Double[]{stats.getMin(), stats.getMax()}; } private Double[] minmax(Double[] vect1, Double[] vect2) { DescriptiveStatistics stats = new DescriptiveStatistics(); for (Double value : vect1) { stats.addValue(value); } for (Double value : vect2) { stats.addValue(value); } return new Double[]{stats.getMin(), stats.getMax()}; } private Double log(Double hxy, Double hx, Double hy) { if ((hxy < 1e-6)) // || (hy < 1e-6) || (hxy < 1e6) ) return 0.0; else return Math.log(hxy / hx / hy); } private Double[] basetransform(Double[] v, Double b) { for (int i = 0; i < v.length; i++) { v[i] /= Math.log(b); } return v; } private Double[] bootstrap(Double[] v, int Nboot) { Double[] boot = new Double[Nboot]; int I; int maxI = v.length - 1; RandomData rand = new RandomDataImpl(); for (int r = 0; r < Nboot; ++r) { I = rand.nextInt(0, maxI); boot[r] = v[I]; } return boot; } // Testing public static void main(String[] args) throws Exception { Double[] a = new Double[]{1.0, 2.0, 2.0, 2.0, 0.0, 0.0, 1.0, 0.0, 1.0, 2.0}; Double[] b = new Double[]{1.0, 2.0, 2.0, 2.0, 2.0, 1.0, 0.0, 2.0, 1.0, 0.0}; MutualInformation mutinf = new MutualInformation(a, b, 3); Double[] res; res = mutinf.calculate(); System.err.println("mutual information (" + mutinf.method + ", log" + mutinf.logbase + "): " + res[0] + ", sigma: " + res[1] + ", bias: " + res[2]); mutinf.set_method("biased"); res = mutinf.calculate(); System.err.println("mutual information (" + mutinf.method + ", log" + mutinf.logbase + "): " + res[0] + ", sigma: " + res[1] + ", bias: " + res[2]); } }
package net.openhft.chronicle.map; import net.openhft.chronicle.hash.ChronicleHashErrorListener; import net.openhft.chronicle.hash.ChronicleHashInstanceConfig; import net.openhft.chronicle.hash.StatelessClientConfig; import net.openhft.chronicle.hash.replication.SingleChronicleHashReplication; import net.openhft.chronicle.hash.replication.TcpTransportAndNetworkConfig; import net.openhft.chronicle.hash.replication.TimeProvider; import net.openhft.chronicle.hash.serialization.BytesReader; import net.openhft.chronicle.hash.serialization.BytesWriter; import net.openhft.chronicle.hash.serialization.SizeMarshaller; import net.openhft.lang.io.serialization.BytesMarshaller; import net.openhft.lang.io.serialization.BytesMarshallerFactory; import net.openhft.lang.io.serialization.ObjectFactory; import net.openhft.lang.io.serialization.ObjectSerializer; import net.openhft.lang.model.Byteable; import net.openhft.lang.model.DataValueClasses; import org.jetbrains.annotations.NotNull; import java.io.File; import java.io.IOException; import java.net.InetSocketAddress; import java.util.concurrent.TimeUnit; public final class ChronicleMapBuilder<K, V> implements ChronicleMapBuilderI<K, V> { final ChronicleMapBuilderI<K, V> delegate; public static <K, V> ChronicleMapBuilder<K, V> of( @NotNull Class<K> keyClass, @NotNull Class<V> valueClass) { if (valueClass.isEnum()) return new ChronicleMapBuilder<K, V>(OnHeapUpdatableChronicleMapBuilder.of(keyClass, valueClass)); if (keyClass.isInterface() && !builtInType(keyClass)) keyClass = DataValueClasses.directClassFor(keyClass); if ((valueClass.isInterface() && !builtInType(valueClass))) { valueClass = DataValueClasses.directClassFor(valueClass); } else if (!offHeapReference(valueClass)) { return new ChronicleMapBuilder<K, V>(OnHeapUpdatableChronicleMapBuilder.of(keyClass, valueClass)); } ChronicleMapBuilderI<K, V> builder = new OffHeapUpdatableChronicleMapBuilder<K, V>(keyClass, valueClass); return new ChronicleMapBuilder<K, V>(builder); } static boolean builtInType(Class clazz) { return clazz.getClassLoader() == Class.class.getClassLoader(); } ChronicleMapBuilder(ChronicleMapBuilderI<K, V> delegate) { this.delegate = delegate; } private static boolean offHeapReference(Class valueClass) { return Byteable.class.isAssignableFrom(valueClass); } /** * {@inheritDoc} With respect to {@linkplain #entryAndValueAlignment(Alignment) alignment}. * * <p>Note that the actual entrySize will be aligned to 4 (default {@linkplain * #entryAndValueAlignment(Alignment) entry alignment}). I. e. if you set entry size to 30, and entry * alignment is set to {@link Alignment#OF_4_BYTES}, the actual entry size will be 32 (30 aligned to 4 * bytes). * * @see #entryAndValueAlignment(Alignment) // * @see #entries(long) */ @Override public ChronicleMapBuilder<K, V> entrySize(int entrySize) { delegate.entrySize(entrySize); return this; } @Override public ChronicleMapBuilder<K, V> entryAndValueAlignment(Alignment alignment) { delegate.entryAndValueAlignment(alignment); return this; } /** * {@inheritDoc} Also, it overrides any previous {@link #prepareValueBytesOnAcquire} configuration to this * {@code ChronicleMapBuilder}. * * <p>By default, the default value is not specified, default {@linkplain #prepareValueBytesOnAcquire * prepare value bytes routine} is specified instead. * * @see #defaultValueProvider(DefaultValueProvider) * @see #prepareValueBytesOnAcquire(PrepareValueBytes) */ @Override public ChronicleMapBuilder<K, V> defaultValue(V defaultValue) { delegate.defaultValue(defaultValue); return this; } @Override public ChronicleMapBuilder<K, V> prepareValueBytesOnAcquire(@NotNull PrepareValueBytes<K, V> prepareValueBytes) { delegate.prepareValueBytesOnAcquire(prepareValueBytes); return this; } @Override public ChronicleMapBuilder<K, V> keySize(int keySize) { delegate.keySize(keySize); return this; } @Override public ChronicleMapBuilder<K, V> constantKeySizeBySample(K sampleKey) { delegate.constantKeySizeBySample(sampleKey); return this; } @Override public ChronicleMapBuilder<K, V> valueSize(int valueSize) { delegate.valueSize(valueSize); return this; } @Override public ChronicleMapBuilder<K, V> constantValueSizeBySample(@NotNull V sampleValue) { delegate.constantValueSizeBySample(sampleValue); return this; } /** * {@inheritDoc} * * <p>Example: <pre>{@code Map<Key, Value> map = * ChronicleMapBuilder.of(Key.class, Value.class) * .entries(1_000_000) * .keySize(50).valueSize(200) * // this class hasn't implemented yet, just for example * .objectSerializer(new KryoObjectSerializer()) * .create();}</pre> */ @Override public ChronicleMapBuilder<K, V> objectSerializer(@NotNull ObjectSerializer objectSerializer) { delegate.objectSerializer(objectSerializer); return this; } @Override public ChronicleMapBuilder<K, V> valueDeserializationFactory(@NotNull ObjectFactory<V> valueDeserializationFactory) { delegate.valueDeserializationFactory(valueDeserializationFactory); return this; } /** * {@inheritDoc} * * <p>By default, default value provider is not specified, {@link #defaultValue(Object) default value} is * specified instead. * * @see #defaultValue(Object) */ @Override public ChronicleMapBuilder<K, V> defaultValueProvider(@NotNull DefaultValueProvider<K, V> defaultValueProvider) { delegate.defaultValueProvider(defaultValueProvider); return this; } @Override public ChronicleMapBuilder<K, V> valueMarshaller( @NotNull BytesMarshaller<V> valueMarshaller) { delegate.valueMarshaller(valueMarshaller); return this; } @Override public ChronicleMapBuilder<K, V> valueMarshallers(@NotNull BytesWriter<V> valueWriter, @NotNull BytesReader<V> valueReader) { delegate.valueMarshallers(valueWriter, valueReader); return this; } @Override public ChronicleMapBuilder<K, V> valueSizeMarshaller(@NotNull SizeMarshaller valueSizeMarshaller) { delegate.valueSizeMarshaller(valueSizeMarshaller); return this; } @Override public ChronicleMapBuilder<K, V> entries(long l) { delegate.entries(l); return this; } /** * each map can be identified by a name * * @param name the name of the map * @return self */ @Override public ChronicleMapBuilder<K, V> name(String name) { delegate.name(name); return this; } @Override public String name() { return delegate.name(); } @Override public ChronicleMapBuilder<K, V> replication(SingleChronicleHashReplication withId) { delegate.replication(withId); return this; } @Override public ChronicleMap<K, V> create() { return delegate.create(); } @Override public ChronicleMapBuilder<K, V> actualSegments(int actualSegments) { delegate.actualSegments(actualSegments); return this; } @Override public ChronicleMapBuilder<K, V> minSegments(int minSegments) { delegate.minSegments(minSegments); return this; } @Override public ChronicleMapBuilder<K, V> actualEntriesPerSegment(long actualEntriesPerSegment) { delegate.actualEntriesPerSegment(actualEntriesPerSegment); return this; } @Override public ChronicleMapBuilder<K, V> lockTimeOut(long lockTimeOut, TimeUnit unit) { delegate.lockTimeOut(lockTimeOut, unit); return this; } @Override public ChronicleMapBuilder<K, V> errorListener(ChronicleHashErrorListener errorListener) { delegate.errorListener(errorListener); return this; } @Override public ChronicleMapBuilder<K, V> metaDataBytes(int metaDataBytes) { delegate.metaDataBytes(metaDataBytes); return this; } @Override public ChronicleMapBuilder<K, V> timeProvider(TimeProvider timeProvider) { delegate.timeProvider(timeProvider); return this; } @Override public ChronicleMapBuilder<K, V> bytesMarshallerFactory(BytesMarshallerFactory bytesMarshallerFactory) { delegate.bytesMarshallerFactory(bytesMarshallerFactory); return this; } @Override public ChronicleMapBuilder<K, V> keyMarshaller(BytesMarshaller<K> keyMarshaller) { delegate.keyMarshaller(keyMarshaller); return this; } @Override public ChronicleMapBuilder<K, V> keyMarshallers(BytesWriter<K> keyWriter, BytesReader<K> keyReader) { delegate.keyMarshallers(keyWriter, keyReader); return this; } @Override public ChronicleMapBuilder<K, V> keySizeMarshaller(SizeMarshaller keySizeMarshaller) { delegate.keySizeMarshaller(keySizeMarshaller); return this; } @Override public ChronicleMapBuilder<K, V> keyDeserializationFactory(ObjectFactory<K> keyDeserializationFactory) { delegate.keyDeserializationFactory(keyDeserializationFactory); return this; } @Override public ChronicleMapBuilder<K, V> immutableKeys() { delegate.immutableKeys(); return this; } @Override public StatelessClientConfig<ChronicleMap<K, V>> statelessClient(InetSocketAddress remoteAddress) { return delegate.statelessClient(remoteAddress); } @Override public ChronicleHashInstanceConfig<ChronicleMap<K, V>> instance() { return delegate.instance(); } @Override public ChronicleMapBuilder<K, V> replication(byte identifier) { delegate.replication(identifier); return this; } @Override public ChronicleMapBuilder<K, V> replication(byte identifier, TcpTransportAndNetworkConfig tcpTransportAndNetwork) { delegate.replication(identifier, tcpTransportAndNetwork); return this; } @Override public ChronicleMapBuilder<K, V> clone() { delegate.clone(); return this; } @Override public ChronicleMapBuilder<K, V> putReturnsNull(boolean b) { delegate.putReturnsNull(b); return this; } @Override public ChronicleMapBuilder<K, V> removeReturnsNull(boolean b) { delegate.removeReturnsNull(b); return this; } @Override public ChronicleMapBuilder<K, V> eventListener(MapEventListener<K, V, ChronicleMap<K, V>> eventListener) { delegate.eventListener(eventListener); return this; } @Override public ChronicleMap<K, V> createPersistedTo(File file) throws IOException { return delegate.createPersistedTo(file); } }
package com.scientists.happy.botanist; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.GridView; import android.widget.ListAdapter; public class MainActivity extends AppCompatActivity { private static final int VIEW_ACCOUNT = 1; private DatabaseManager mDatabase; ProgressDialog mProgressDialog; /** * Launch app * @param savedInstanceState - app state */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //showProgressDialog(); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { /** * Handle action button click * @param view - current view */ @Override public void onClick(View view) { startActivity(new Intent(MainActivity.this, AddPlantActivity.class)); } }); mDatabase = DatabaseManager.getInstance(); GridView gridView = (GridView) findViewById(R.id.gridview); gridView.setEmptyView(findViewById(R.id.empty_grid_view)); ListAdapter adapter = mDatabase.getPlantsAdapter(this); // adapter.registerDataSetObserver(new DataSetObserver() { // @Override // public void onChanged() { // super.onChanged(); // hideProgressDialog(); gridView.setAdapter(adapter); } /** * Handle options menu * @param menu - options menu * @return Returns success code */ @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } /** * Handle selected option * @param item - selected option * @return Returns success code */ @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { startActivity(new Intent(this, SettingsActivity.class)); return true; } else if (id == R.id.action_account) { startActivityForResult(new Intent(MainActivity.this, AccountActivity.class), VIEW_ACCOUNT); return true; } return super.onOptionsItemSelected(item); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == VIEW_ACCOUNT && resultCode == RESULT_OK) { startActivity(new Intent(MainActivity.this, LoginActivity.class)); finish(); } } private void showProgressDialog() { if (mProgressDialog == null) { mProgressDialog = new ProgressDialog(this); mProgressDialog.setMessage(getString(R.string.loading)); mProgressDialog.setIndeterminate(true); mProgressDialog.setCancelable(false); } mProgressDialog.show(); } private void hideProgressDialog() { if (mProgressDialog != null && mProgressDialog.isShowing()) { mProgressDialog.hide(); } } }
package net.minecraftforge.client; import static net.minecraftforge.common.ForgeVersion.Status.BETA; import static net.minecraftforge.common.ForgeVersion.Status.BETA_OUTDATED; import static org.lwjgl.opengl.GL11.*; import static org.lwjgl.opengl.GL20.*; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.util.Map; import javax.vecmath.Matrix4f; import javax.vecmath.Vector3f; import javax.vecmath.Vector4f; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.client.audio.ISound; import net.minecraft.client.audio.SoundManager; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiMainMenu; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.model.ModelBiped; import net.minecraft.client.renderer.EntityRenderer; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.OpenGlHelper; import net.minecraft.client.renderer.RenderGlobal; import net.minecraft.client.renderer.VertexBuffer; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.block.model.ItemCameraTransforms; import net.minecraft.client.renderer.block.model.ItemTransformVec3f; import net.minecraft.client.renderer.block.model.ModelManager; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.client.renderer.block.model.ModelRotation; import net.minecraft.client.renderer.block.model.SimpleBakedModel; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher; import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraft.client.renderer.vertex.VertexFormat; import net.minecraft.client.renderer.vertex.VertexFormatElement; import net.minecraft.client.renderer.vertex.VertexFormatElement.EnumUsage; import net.minecraft.client.resources.I18n; import net.minecraft.client.settings.GameSettings; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.*; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.registry.IRegistry; import net.minecraft.util.text.TextFormatting; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraft.world.biome.BiomeGenBase; import net.minecraftforge.client.event.DrawBlockHighlightEvent; import net.minecraftforge.client.event.EntityViewRenderEvent; import net.minecraftforge.client.event.FOVUpdateEvent; import net.minecraftforge.client.event.GuiScreenEvent; import net.minecraftforge.client.event.ModelBakeEvent; import net.minecraftforge.client.event.MouseEvent; import net.minecraftforge.client.event.RenderHandEvent; import net.minecraftforge.client.event.RenderWorldLastEvent; import net.minecraftforge.client.event.TextureStitchEvent; import net.minecraftforge.client.event.sound.PlaySoundEvent; import net.minecraftforge.client.model.IModelPart; import net.minecraftforge.client.model.IPerspectiveAwareModel; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.client.model.TRSRTransformation; import net.minecraftforge.common.ForgeModContainer; import net.minecraftforge.common.ForgeVersion; import net.minecraftforge.common.ForgeVersion.Status; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.client.FMLClientHandler; import net.minecraftforge.fml.client.registry.ClientRegistry; import net.minecraftforge.fml.common.FMLLog; import org.apache.commons.lang3.tuple.Pair; import org.lwjgl.BufferUtils; import com.google.common.base.Objects; import com.google.common.base.Optional; import com.google.common.collect.Maps; public class ForgeHooksClient { //private static final ResourceLocation ITEM_GLINT = new ResourceLocation("textures/misc/enchanted_item_glint.png"); static TextureManager engine() { return FMLClientHandler.instance().getClient().renderEngine; } public static String getArmorTexture(Entity entity, ItemStack armor, String _default, EntityEquipmentSlot slot, String type) { String result = armor.getItem().getArmorTexture(armor, entity, slot, type); return result != null ? result : _default; } //Optifine Helper Functions u.u, these are here specifically for Optifine //Note: When using Optfine, these methods are invoked using reflection, which //incurs a major performance penalty. public static void orientBedCamera(IBlockAccess world, BlockPos pos, IBlockState state, Entity entity) { Block block = state.getBlock(); if (block != null && block.isBed(state, world, pos, entity)) { glRotatef((float)(block.getBedDirection(state, world, pos).getHorizontalIndex() * 90), 0.0F, 1.0F, 0.0F); } } public static boolean onDrawBlockHighlight(RenderGlobal context, EntityPlayer player, RayTraceResult target, int subID, float partialTicks) { return MinecraftForge.EVENT_BUS.post(new DrawBlockHighlightEvent(context, player, target, subID, partialTicks)); } public static void dispatchRenderLast(RenderGlobal context, float partialTicks) { MinecraftForge.EVENT_BUS.post(new RenderWorldLastEvent(context, partialTicks)); } public static boolean renderFirstPersonHand(RenderGlobal context, float partialTicks, int renderPass) { return MinecraftForge.EVENT_BUS.post(new RenderHandEvent(context, partialTicks, renderPass)); } public static void onTextureStitchedPre(TextureMap map) { MinecraftForge.EVENT_BUS.post(new TextureStitchEvent.Pre(map)); ModelLoader.White.instance.register(map); } public static void onTextureStitchedPost(TextureMap map) { MinecraftForge.EVENT_BUS.post(new TextureStitchEvent.Post(map)); } static int renderPass = -1; public static void setRenderPass(int pass) { renderPass = pass; } static final ThreadLocal<BlockRenderLayer> renderLayer = new ThreadLocal<BlockRenderLayer>() { protected BlockRenderLayer initialValue() { return BlockRenderLayer.SOLID; } }; public static void setRenderLayer(BlockRenderLayer layer) { renderLayer.set(layer); } public static ModelBiped getArmorModel(EntityLivingBase entityLiving, ItemStack itemStack, EntityEquipmentSlot slot, ModelBiped _default) { ModelBiped model = itemStack.getItem().getArmorModel(entityLiving, itemStack, slot, _default); return model == null ? _default : model; } //This properly moves the domain, if provided, to the front of the string before concatenating public static String fixDomain(String base, String complex) { int idx = complex.indexOf(':'); if (idx == -1) { return base + complex; } String name = complex.substring(idx + 1, complex.length()); if (idx > 1) { String domain = complex.substring(0, idx); return domain + ':' + base + name; } else { return base + name; } } public static boolean postMouseEvent() { return MinecraftForge.EVENT_BUS.post(new MouseEvent()); } public static float getOffsetFOV(EntityPlayer entity, float fov) { FOVUpdateEvent fovUpdateEvent = new FOVUpdateEvent(entity, fov); MinecraftForge.EVENT_BUS.post(fovUpdateEvent); return fovUpdateEvent.newfov; } public static float getFOVModifier(EntityRenderer renderer, Entity entity, IBlockState state, double renderPartialTicks, float fov) { EntityViewRenderEvent.FOVModifier event = new EntityViewRenderEvent.FOVModifier(renderer, entity, state, renderPartialTicks, fov); MinecraftForge.EVENT_BUS.post(event); return event.getFOV(); } private static int skyX, skyZ; private static boolean skyInit; private static int skyRGBMultiplier; public static int getSkyBlendColour(World world, BlockPos center) { if (center.getX() == skyX && center.getZ() == skyZ && skyInit) { return skyRGBMultiplier; } skyInit = true; GameSettings settings = Minecraft.getMinecraft().gameSettings; int[] ranges = ForgeModContainer.blendRanges; int distance = 0; if (settings.fancyGraphics && settings.renderDistanceChunks >= 0 && settings.renderDistanceChunks < ranges.length) { distance = ranges[settings.renderDistanceChunks]; } int r = 0; int g = 0; int b = 0; int divider = 0; for (int x = -distance; x <= distance; ++x) { for (int z = -distance; z <= distance; ++z) { BlockPos pos = center.add(x, 0, z); BiomeGenBase biome = world.getBiomeGenForCoords(pos); int colour = biome.getSkyColorByTemp(biome.getFloatTemperature(pos)); r += (colour & 0xFF0000) >> 16; g += (colour & 0x00FF00) >> 8; b += colour & 0x0000FF; divider++; } } int multiplier = (r / divider & 255) << 16 | (g / divider & 255) << 8 | b / divider & 255; skyX = center.getX(); skyZ = center.getY(); skyRGBMultiplier = multiplier; return skyRGBMultiplier; } /** * Initialization of Forge Renderers. */ static { //FluidRegistry.renderIdFluid = RenderingRegistry.getNextAvailableRenderId(); //RenderingRegistry.registerBlockHandler(RenderBlockFluid.instance); } public static void renderMainMenu(GuiMainMenu gui, FontRenderer font, int width, int height) { Status status = ForgeVersion.getStatus(); if (status == BETA || status == BETA_OUTDATED) { // render a warning at the top of the screen, String line = I18n.format("forge.update.beta.1", TextFormatting.RED, TextFormatting.RESET); gui.drawString(font, line, (width - font.getStringWidth(line)) / 2, 4 + (0 * (font.FONT_HEIGHT + 1)), -1); line = I18n.format("forge.update.beta.2"); gui.drawString(font, line, (width - font.getStringWidth(line)) / 2, 4 + (1 * (font.FONT_HEIGHT + 1)), -1); } String line = null; switch(status) { //case FAILED: line = " Version check failed"; break; //case AHEAD: line = "Using non-recommended Forge build, issues may arise."}; break; case OUTDATED: case BETA_OUTDATED: line = I18n.format("forge.update.newversion", ForgeVersion.getTarget()); break; default: break; } if (line != null) { gui.drawString(font, line, width - font.getStringWidth(line) - 2, height - (2 * (font.FONT_HEIGHT + 1)), -1); } } public static ISound playSound(SoundManager manager, ISound sound) { PlaySoundEvent e = new PlaySoundEvent(manager, sound); MinecraftForge.EVENT_BUS.post(e); return e.result; } //static RenderBlocks VertexBufferRB; static int worldRenderPass; public static int getWorldRenderPass() { return worldRenderPass; } public static void drawScreen(GuiScreen screen, int mouseX, int mouseY, float partialTicks) { if (!MinecraftForge.EVENT_BUS.post(new GuiScreenEvent.DrawScreenEvent.Pre(screen, mouseX, mouseY, partialTicks))) screen.drawScreen(mouseX, mouseY, partialTicks); MinecraftForge.EVENT_BUS.post(new GuiScreenEvent.DrawScreenEvent.Post(screen, mouseX, mouseY, partialTicks)); } public static float getFogDensity(EntityRenderer renderer, Entity entity, IBlockState state, float partial, float density) { EntityViewRenderEvent.FogDensity event = new EntityViewRenderEvent.FogDensity(renderer, entity, state, partial, density); if (MinecraftForge.EVENT_BUS.post(event)) return event.density; return -1; } public static void onFogRender(EntityRenderer renderer, Entity entity, IBlockState state, float partial, int mode, float distance) { MinecraftForge.EVENT_BUS.post(new EntityViewRenderEvent.RenderFogEvent(renderer, entity, state, partial, mode, distance)); } /* public static void setVertexBufferRB(RenderBlocks renderBlocks) { VertexBufferRB = renderBlocks; } public static void onPreRenderWorld(VertexBuffer VertexBuffer, int pass) { if(VertexBufferRB != null) { worldRenderPass = pass; MinecraftForge.EVENT_BUS.post(new RenderWorldEvent.Pre(VertexBuffer, (ChunkCache)VertexBufferRB.blockAccess, VertexBufferRB, pass)); } } public static void onPostRenderWorld(VertexBuffer VertexBuffer, int pass) { if(VertexBufferRB != null) { MinecraftForge.EVENT_BUS.post(new RenderWorldEvent.Post(VertexBuffer, (ChunkCache)VertexBufferRB.blockAccess, VertexBufferRB, pass)); worldRenderPass = -1; } } */ public static void onModelBake(ModelManager modelManager, IRegistry<ModelResourceLocation, IBakedModel> modelRegistry, ModelLoader modelLoader) { MinecraftForge.EVENT_BUS.post(new ModelBakeEvent(modelManager, modelRegistry, modelLoader)); modelLoader.onPostBakeEvent(modelRegistry); } @SuppressWarnings("deprecation") public static Matrix4f getMatrix(ItemTransformVec3f transform) { javax.vecmath.Matrix4f m = new javax.vecmath.Matrix4f(), t = new javax.vecmath.Matrix4f(); m.setIdentity(); m.setTranslation(TRSRTransformation.toVecmath(transform.translation)); t.setIdentity(); t.rotY(transform.rotation.y); m.mul(t); t.setIdentity(); t.rotX(transform.rotation.x); m.mul(t); t.setIdentity(); t.rotZ(transform.rotation.z); m.mul(t); t.setIdentity(); t.m00 = transform.scale.x; t.m11 = transform.scale.y; t.m22 = transform.scale.z; m.mul(t); return m; } private static final Matrix4f flipX; static { flipX = new Matrix4f(); flipX.setIdentity(); flipX.m00 = -1; } @SuppressWarnings("deprecation") public static IBakedModel handleCameraTransforms(IBakedModel model, ItemCameraTransforms.TransformType cameraTransformType, boolean leftHandHackery) { if(model instanceof IPerspectiveAwareModel) { Pair<? extends IBakedModel, Matrix4f> pair = ((IPerspectiveAwareModel)model).handlePerspective(cameraTransformType); if(pair.getRight() != null) { Matrix4f matrix = new Matrix4f(pair.getRight()); if(leftHandHackery) { matrix.mul(flipX, matrix); matrix.mul(matrix, flipX); } multiplyCurrentGlMatrix(matrix); } return pair.getLeft(); } else { //if(leftHandHackery) GlStateManager.scale(-1, 1, 1); ItemCameraTransforms.applyTransformSide(model.getItemCameraTransforms().getTransform(cameraTransformType), leftHandHackery); //if(leftHandHackery) GlStateManager.scale(-1, 1, 1); } return model; } private static final FloatBuffer matrixBuf = BufferUtils.createFloatBuffer(16); public static void multiplyCurrentGlMatrix(Matrix4f matrix) { matrixBuf.clear(); float[] t = new float[4]; for(int i = 0; i < 4; i++) { matrix.getColumn(i, t); matrixBuf.put(t); } matrixBuf.flip(); glMultMatrix(matrixBuf); } // moved and expanded from WorldVertexBufferUploader.draw public static void preDraw(EnumUsage attrType, VertexFormat format, int element, int stride, ByteBuffer buffer) { VertexFormatElement attr = format.getElement(element); int count = attr.getElementCount(); int constant = attr.getType().getGlConstant(); buffer.position(format.getOffset(element)); switch(attrType) { case POSITION: glVertexPointer(count, constant, stride, buffer); glEnableClientState(GL_VERTEX_ARRAY); break; case NORMAL: if(count != 3) { throw new IllegalArgumentException("Normal attribute should have the size 3: " + attr); } glNormalPointer(constant, stride, buffer); glEnableClientState(GL_NORMAL_ARRAY); break; case COLOR: glColorPointer(count, constant, stride, buffer); glEnableClientState(GL_COLOR_ARRAY); break; case UV: OpenGlHelper.setClientActiveTexture(OpenGlHelper.defaultTexUnit + attr.getIndex()); glTexCoordPointer(count, constant, stride, buffer); glEnableClientState(GL_TEXTURE_COORD_ARRAY); OpenGlHelper.setClientActiveTexture(OpenGlHelper.defaultTexUnit); break; case PADDING: break; case GENERIC: glEnableVertexAttribArray(attr.getIndex()); glVertexAttribPointer(attr.getIndex(), count, constant, false, stride, buffer); default: FMLLog.severe("Unimplemented vanilla attribute upload: %s", attrType.getDisplayName()); } } public static void postDraw(EnumUsage attrType, VertexFormat format, int element, int stride, ByteBuffer buffer) { VertexFormatElement attr = format.getElement(element); switch(attrType) { case POSITION: glDisableClientState(GL_VERTEX_ARRAY); break; case NORMAL: glDisableClientState(GL_NORMAL_ARRAY); break; case COLOR: glDisableClientState(GL_COLOR_ARRAY); // is this really needed? GlStateManager.resetColor(); break; case UV: OpenGlHelper.setClientActiveTexture(OpenGlHelper.defaultTexUnit + attr.getIndex()); glDisableClientState(GL_TEXTURE_COORD_ARRAY); OpenGlHelper.setClientActiveTexture(OpenGlHelper.defaultTexUnit); break; case PADDING: break; case GENERIC: glDisableVertexAttribArray(attr.getIndex()); default: FMLLog.severe("Unimplemented vanilla attribute upload: %s", attrType.getDisplayName()); } } public static void transform(org.lwjgl.util.vector.Vector3f vec, Matrix4f m) { Vector4f tmp = new Vector4f(vec.x, vec.y, vec.z, 1f); m.transform(tmp); if(Math.abs(tmp.w - 1f) > 1e-5) tmp.scale(1f / tmp.w); vec.set(tmp.x, tmp.y, tmp.z); } public static Matrix4f getMatrix(ModelRotation modelRotation) { Matrix4f ret = new Matrix4f(TRSRTransformation.toVecmath(modelRotation.getMatrix4d())), tmp = new Matrix4f(); tmp.setIdentity(); tmp.m03 = tmp.m13 = tmp.m23 = .5f; ret.mul(tmp, ret); tmp.invert(); //tmp.m03 = tmp.m13 = tmp.m23 = -.5f; ret.mul(tmp); return ret; } public static void putQuadColor(VertexBuffer renderer, BakedQuad quad, int color) { float cr = color & 0xFF; float cg = (color >>> 8) & 0xFF; float cb = (color >>> 16) & 0xFF; float ca = (color >>> 24) & 0xFF; for(int i = 0; i < 4; i++) { int vc = quad.getVertexData()[3 + 7 * i]; float vcr = vc & 0xFF; float vcg = (vc >>> 8) & 0xFF; float vcb = (vc >>> 16) & 0xFF; float vca = (vc >>> 24) & 0xFF; int ncr = Math.min(0xFF, (int)(cr * vcr / 0xFF)); int ncg = Math.min(0xFF, (int)(cg * vcg / 0xFF)); int ncb = Math.min(0xFF, (int)(cb * vcb / 0xFF)); int nca = Math.min(0xFF, (int)(ca * vca / 0xFF)); renderer.putColorRGBA(renderer.getColorIndex(4 - i), ncr, ncg, ncb, nca); } } private static Map<Pair<Item, Integer>, Class<? extends TileEntity>> tileItemMap = Maps.newHashMap(); public static void renderTileItem(Item item, int metadata) { Class<? extends TileEntity> tileClass = tileItemMap.get(Pair.of(item, metadata)); if (tileClass != null) { TileEntitySpecialRenderer<?> r = TileEntityRendererDispatcher.instance.getSpecialRendererByClass(tileClass); if (r != null) { r.renderTileEntityAt(null, 0, 0, 0, 0, -1); } } } /** * @deprecated Will be removed as soon as possible, hopefully 1.9. */ @Deprecated public static void registerTESRItemStack(Item item, int metadata, Class<? extends TileEntity> TileClass) { tileItemMap.put(Pair.of(item, metadata), TileClass); } /** * internal, relies on fixed format of FaceBakery */ public static void fillNormal(int[] faceData, EnumFacing facing) { Vector3f v1 = new Vector3f(faceData[3 * 7 + 0], faceData[3 * 7 + 1], faceData[3 * 7 + 2]); Vector3f t = new Vector3f(faceData[1 * 7 + 0], faceData[1 * 7 + 1], faceData[1 * 7 + 2]); Vector3f v2 = new Vector3f(faceData[2 * 7 + 0], faceData[2 * 7 + 1], faceData[2 * 7 + 2]); v1.sub(t); t.set(faceData[0 * 7 + 0], faceData[0 * 7 + 1], faceData[0 * 7 + 2]); v2.sub(t); v1.cross(v2, v1); v1.normalize(); int x = ((byte)(v1.x * 127)) & 0xFF; int y = ((byte)(v1.y * 127)) & 0xFF; int z = ((byte)(v1.z * 127)) & 0xFF; for(int i = 0; i < 4; i++) { faceData[i * 7 + 6] = x | (y << 0x08) | (z << 0x10); } } @SuppressWarnings("deprecation") public static Optional<TRSRTransformation> applyTransform(ItemTransformVec3f transform, Optional<? extends IModelPart> part) { if(part.isPresent()) return Optional.absent(); return Optional.of(new TRSRTransformation(transform)); } public static Optional<TRSRTransformation> applyTransform(Matrix4f matrix, Optional<? extends IModelPart> part) { if(part.isPresent()) return Optional.absent(); return Optional.of(new TRSRTransformation(matrix)); } public static void loadEntityShader(Entity entity, EntityRenderer entityRenderer) { if (entity != null) { ResourceLocation shader = ClientRegistry.getEntityShader(entity.getClass()); if (shader != null) { entityRenderer.loadShader(shader); } } } public static IBakedModel getDamageModel(IBakedModel ibakedmodel, TextureAtlasSprite texture, IBlockState state, IBlockAccess world, BlockPos pos) { // TODO custom damage models // state = state.block.getExtendedState(state, world, pos); return (new SimpleBakedModel.Builder(state, ibakedmodel, texture, pos)).makeBakedModel(); } private static int slotMainHand = 0; // FIXME public static boolean shouldCauseReequipAnimation(ItemStack from, ItemStack to, int slot) { if(!Objects.equal(from, to) || from == null) { return Objects.equal(from, to); } boolean changed = false; if (slot != -1) { changed = slot != slotMainHand; slotMainHand = slot; } return !from.getItem().shouldCauseReequipAnimation(from, to, changed); } }
package dk.netarkivet.harvester.harvesting; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.commons.io.IOUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.dom4j.Document; import org.dom4j.Node; import dk.netarkivet.common.CommonSettings; import dk.netarkivet.common.distribute.arcrepository.ArcRepositoryClientFactory; import dk.netarkivet.common.distribute.arcrepository.BatchStatus; import dk.netarkivet.common.distribute.arcrepository.BitarchiveRecord; import dk.netarkivet.common.distribute.arcrepository.HarvesterArcRepositoryClient; import dk.netarkivet.common.distribute.indexserver.Index; import dk.netarkivet.common.distribute.indexserver.IndexClientFactory; import dk.netarkivet.common.distribute.indexserver.JobIndexCache; import dk.netarkivet.common.exceptions.ArgumentNotValid; import dk.netarkivet.common.exceptions.IOFailure; import dk.netarkivet.common.utils.FileUtils; import dk.netarkivet.common.utils.NotificationsFactory; import dk.netarkivet.common.utils.Settings; import dk.netarkivet.common.utils.batch.FileBatchJob; import dk.netarkivet.common.utils.cdx.ArchiveExtractCDXJob; import dk.netarkivet.common.utils.cdx.CDXRecord; import dk.netarkivet.harvester.HarvesterSettings; import dk.netarkivet.harvester.datamodel.Job; import dk.netarkivet.harvester.harvesting.metadata.MetadataEntry; import dk.netarkivet.harvester.harvesting.metadata.MetadataFile; import dk.netarkivet.harvester.harvesting.metadata.PersistentJobData; import dk.netarkivet.harvester.harvesting.metadata.PersistentJobData.HarvestDefinitionInfo; import dk.netarkivet.harvester.harvesting.report.HarvestReport; import dk.netarkivet.harvester.harvesting.report.HarvestReportFactory; /** * This class handles all the things in a single harvest that are not related * directly related either to launching Heritrix or to handling JMS messages. * */ public class HarvestController { /** * The singleton instance of this class. Calling cleanup() on the instance * will null this field. */ private static HarvestController instance; /** The instance logger. */ private Log log = LogFactory.getLog(HarvestController.class); /** * The max time to wait for heritrix to close last ARC or WARC files (in secs). */ private static final int WAIT_FOR_HERITRIX_TIMEOUT_SECS = 5; /** * The ArcRepositoryClient used to communicate with the ArcRepository to * store the generated arc-files. */ private HarvesterArcRepositoryClient arcRepController; /** * Private constructor controlled by getInstance(). */ private HarvestController() { arcRepController = ArcRepositoryClientFactory.getHarvesterInstance(); } /** * Get the instance of the singleton HarvestController. * * @return The singleton instance. */ public static synchronized HarvestController getInstance() { if (instance == null) { instance = new HarvestController(); } return instance; } /** * Clean up this singleton, releasing the ArcRepositoryClient and removing * the instance. This instance should not be used after this method has * been called. After this has been called, new calls to getInstance will * return a new instance. */ public void cleanup() { if (arcRepController != null) { arcRepController.close(); } resetInstance(); } /** * Reset the singleton instance. */ private static void resetInstance() { instance = null; } /** * Writes the files involved with a harvests. * Creates the Heritrix arcs directory to ensure that this * directory exists in advance. * * @param crawldir The directory that the crawl should take place * in. * @param job The Job object containing various harvest setup * data. * @param hdi The object encapsulating documentary information * about the harvest. * @param metadataEntries Any metadata entries sent along with the job that * should be stored for later use. * @return An object encapsulating where these files have been written. */ public HeritrixFiles writeHarvestFiles( File crawldir, Job job, HarvestDefinitionInfo hdi, List<MetadataEntry> metadataEntries) { final HeritrixFiles files = new HeritrixFiles(crawldir, job); // If this job is a job that tries to continue a previous job // using the Heritrix recover.gz log, and this feature is enabled, // then try to fetch the recover.log from the metadata-arc-file. if (job.getContinuationOf() != null && Settings.getBoolean(HarvesterSettings.RECOVERlOG_CONTINUATION_ENABLED)) { tryToRetrieveRecoverLog(job, files); } // Create harvestInfo file in crawldir // & create preharvest-metadata-1.arc log.debug("Writing persistent job data for job " + job.getJobID()); // Check that harvestInfo does not yet exist // Write job data to persistent storage (harvestinfo file) new PersistentJobData(files.getCrawlDir()).write(job, hdi); // Create jobId-preharvest-metadata-1.arc for this job writePreharvestMetadata(job, metadataEntries, crawldir); files.writeSeedsTxt(job.getSeedListAsString()); files.writeOrderXml(job.getOrderXMLdoc()); // Only retrieve index if deduplication is not disabled in the template. if (HeritrixLauncher.isDeduplicationEnabledInTemplate( job.getOrderXMLdoc())) { log.debug("Deduplication enabled. Fetching deduplication index.."); files.setIndexDir(fetchDeduplicateIndex(metadataEntries)); } else { log.debug("Deduplication disabled."); } // Create Heritrix arcs directory before starting Heritrix to ensure // the arcs directory exists in advance. boolean created = files.getArcsDir().mkdir(); if (!created) { log.warn("Unable to create arcsdir: " + files.getArcsDir()); } // Create Heritrix warcs directory before starting Heritrix to ensure // the warcs directory exists in advance. created = files.getWarcsDir().mkdir(); if (!created) { log.warn("Unable to create warcsdir: " + files.getWarcsDir()); } return files; } /** * This method attempts to retrieve the Heritrix recover log from the job * which this job tries to continue. If successful, the Heritrix template * is updated accordingly. * @param job The harvest Job object containing various harvest setup data. * @param files Heritrix files related to this harvestjob. */ private void tryToRetrieveRecoverLog(Job job, HeritrixFiles files) { Long previousJob = job.getContinuationOf(); List<CDXRecord> metaCDXes = null; try { metaCDXes = getMetadataCDXRecordsForJob(previousJob); } catch (IOFailure e) { log.debug("Failed to retrive CDX of metatadata records. Maybe the metadata arcfile for job " + previousJob + " does not exist in repository", e); } CDXRecord recoverlogCDX = null; if (metaCDXes != null) { for (CDXRecord cdx : metaCDXes) { if (cdx.getURL().matches(MetadataFile.RECOVER_LOG_PATTERN)) { recoverlogCDX = cdx; } } if (recoverlogCDX == null) { log.debug("A recover.gz log file was not found in metadata-arcfile"); } else { log.debug("recover.gz log found in metadata-arcfile"); } } BitarchiveRecord br = null; if (recoverlogCDX != null) { // Retrieve recover.gz from metadata.arc file br = ArcRepositoryClientFactory.getViewerInstance().get( recoverlogCDX.getArcfile(), recoverlogCDX.getOffset()); if (br != null) { log.debug("recover.gz log retrieved from metadata-arcfile"); if (files.writeRecoverBackupfile(br.getData())) { // modify order.xml, so Heritrix recover-path points // to the retrieved recoverlog insertHeritrixRecoverPathInOrderXML(job, files); } else { log.warn("Failed to retrieve and write recoverlog to disk."); } } else { log.debug("recover.gz log not retrieved from metadata-arcfile"); } } } /** * Insert the correct recoverpath in the order.xml for the given harvestjob. * @param job A harvestjob * @param files Heritrix files related to this harvestjob. */ private void insertHeritrixRecoverPathInOrderXML(Job job, HeritrixFiles files) { Document order = job.getOrderXMLdoc(); final String RECOVERLOG_PATH_XPATH = "/crawl-order/controller/string[@name='recover-path']"; Node orderXmlNode = order.selectSingleNode(RECOVERLOG_PATH_XPATH); if (orderXmlNode != null) { orderXmlNode.setText(files.getRecoverBackupGzFile().getAbsolutePath()); log.debug("The Heritrix recover path now refers to '" + files.getRecoverBackupGzFile().getAbsolutePath() + "'."); job.setOrderXMLDoc(order); } else { throw new IOFailure( "Unable to locate the '" + RECOVERLOG_PATH_XPATH + "' element in order.xml: " + order.asXML()); } } /** * Writes pre-harvest metadata to the "metadata" directory. * * @param harvestJob a given Job. * @param metadata the list of metadata entries to write to metadata file. * @param crawlDir the directory, where the metadata will be written. * @throws IOFailure If there are errors in writing the metadata. */ private void writePreharvestMetadata(Job harvestJob, List<MetadataEntry> metadata, File crawlDir) throws IOFailure { if (metadata.size() == 0) { // Do not generate preharvest metadata file for empty list return; } // make sure that metadata directory exists File metadataDir = new File(crawlDir, IngestableFiles.METADATA_SUB_DIR); metadataDir.mkdir(); if (!(metadataDir.exists() && metadataDir.isDirectory())) { throw new IOFailure( "Unable to write preharvest metadata for job '" + + harvestJob.getJobID() + "' to directory '" + metadataDir.getAbsolutePath() + "', as directory does not exist."); } // Serializing the MetadataEntry objects to the metadataDir MetadataEntry.storemetadataToDisk(metadata, metadataDir); } /** * Creates the actual HeritrixLauncher instance and runs it, after the * various setup files have been written. * * @param files Description of files involved in running Heritrix. Not Null. * @throws ArgumentNotValid if an argument isn't valid. */ public void runHarvest(HeritrixFiles files) throws ArgumentNotValid { ArgumentNotValid.checkNotNull(files, "HeritrixFiles files"); HeritrixLauncher hl = HeritrixLauncherFactory.getInstance(files); hl.doCrawl(); } /** * Controls storing all files involved in a job. The files are * 1) The actual ARC/WARC files, * 2) The metadata files * The crawl.log is parsed and information for each domain is generated * and stored in a AbstractHarvestReport object which * is sent along in the crawlstatusmessage. * * Additionally, any leftover open ARC files are closed and harvest * documentation is extracted before upload starts. * * @param files The HeritrixFiles object for this crawl. Not Null. * @param errorMessage A place where error messages accumulate. Not Null. * @param failedFiles List of files that failed to upload. Not Null. * @return An object containing info about the domains harvested. * @throws ArgumentNotValid if an argument isn't valid. */ public HarvestReport storeFiles( HeritrixFiles files, StringBuilder errorMessage, List<File> failedFiles) throws ArgumentNotValid { ArgumentNotValid.checkNotNull(files, "HeritrixFiles files"); ArgumentNotValid.checkNotNull(errorMessage, "StringBuilder errorMessage"); ArgumentNotValid.checkNotNull(failedFiles, "List<File> failedFiles"); long jobID = files.getJobID(); long harvestID = files.getHarvestID(); File crawlDir = files.getCrawlDir(); try { IngestableFiles inf = new IngestableFiles(crawlDir, jobID); inf.closeOpenFiles(WAIT_FOR_HERITRIX_TIMEOUT_SECS); // Create a metadata ARC file HarvestDocumentation.documentHarvest(crawlDir, jobID, harvestID); // Upload all files // Check, if arcsdir or warcsdir is empty // Send a notification, if this is the case if (inf.getArcFiles().isEmpty() && inf.getWarcFiles().isEmpty()) { String errMsg = "Probable error in Heritrix job setup. " + "No arcfiles or warcfiles generated by Heritrix for job " + jobID; log.warn(errMsg); NotificationsFactory.getInstance().errorEvent(errMsg); } else { if (!inf.getArcFiles().isEmpty()) { uploadFiles(inf.getArcFiles(), errorMessage, failedFiles); } if (!inf.getWarcFiles().isEmpty()) { uploadFiles(inf.getWarcFiles(), errorMessage, failedFiles); } } // Now the ARC/WARC files have been uploaded, // we finally upload the metadata archive file. uploadFiles(inf.getMetadataArcFiles(), errorMessage, failedFiles); // Make the harvestReport ready for uploading return HarvestReportFactory.generateHarvestReport(files); } catch (IOFailure e) { String errMsg = "IOFailure occurred, while trying to upload files"; log.warn(errMsg, e); throw new IOFailure(errMsg, e); } } /** * Upload given files to the archive repository. * * @param files List of (ARC/WARC) files to upload. * @param errorMessage Accumulator for error messages. * @param failedFiles Accumulator for failed files. */ private void uploadFiles(List<File> files, StringBuilder errorMessage, List<File> failedFiles) { // Upload all archive files if (files != null) { for (File f : files) { try { log.info("Uploading file '" + f.getName() + "' to arcrepository."); arcRepController.store(f); log.info("File '" + f.getName() + "' uploaded successfully to arcrepository."); } catch (Exception e) { File oldJobsDir = new File(Settings.get( HarvesterSettings.HARVEST_CONTROLLER_OLDJOBSDIR)); String errorMsg = "Error uploading arcfile '" + f.getAbsolutePath() + "' Will be moved to '" + oldJobsDir.getAbsolutePath() + "'"; errorMessage.append(errorMsg).append("\n") .append(e.toString()).append("\n"); log.warn(errorMsg, e); failedFiles.add(f); } } } } /** * Retrieve the list of jobs for deduplicate reduction. * * Runs through all metadata entries, finding duplicate reduction entries, * and parsing all jobIDs in them, warning only on errors. * * @param metadataEntries list of metadataEntries. * @return the list of jobs for deduplicate reduction. */ private List<Long> parseJobIDsForDuplicateReduction( List<MetadataEntry> metadataEntries) { // find metadataEntry for duplicatereduction if any. List<Long> result = new ArrayList<Long>(); for (MetadataEntry me : metadataEntries) { if (me.isDuplicateReductionMetadataEntry()) { String s = new String(me.getData()); if (s.isEmpty()) { // An empty string is now possible continue; } String[] longs = s.split(","); for (String stringLong : longs) { try { result.add(Long.parseLong(stringLong)); } catch (NumberFormatException e) { log.warn("Unable to convert String '" + stringLong + "' in duplicate reduction jobid list" + " metadataEntry '" + s + "' to a jobID. Ignoring.", e); } } } } return result; } /** * Get an index for deduplication. This will make a call to the index * server, requesting an index for the given IDs. The files will then be * cached locally. * * If we request index for IDs that don't exist/have problems, we get a * smaller set of IDs in our cache files, and next time we ask for the same * index, we will call the index server again. This will be handled well, * though, because if the ids are still missing, we will get a reply telling * us to use the cached smaller index anyway. * * @param metadataEntries list of metadataEntries top get jobIDs from. * @return a directory containing the index itself. * @throws IOFailure on errors retrieving the index from the client. * FIXME Better forgiving handling of no index available * Add setting for disable deduplication if no index available */ private File fetchDeduplicateIndex(List<MetadataEntry> metadataEntries) { // Get list of jobs, which should be used for duplicate reduction // and retrieve a luceneIndex from the IndexServer // based on the crawl.logs from these jobs and their CDX'es. HashSet<Long> jobIDsForDuplicateReduction = new HashSet<Long>( parseJobIDsForDuplicateReduction(metadataEntries)); // The client for requesting job index. JobIndexCache jobIndexCache = IndexClientFactory.getDedupCrawllogInstance(); // Request the index and return the index file. Index<Set<Long>> jobIndex = jobIndexCache.getIndex( jobIDsForDuplicateReduction); return jobIndex.getIndexFile(); } /** * Submit a batch job to generate cdx for all metadata files for a job, and * report result in a list. * @param jobid The job to get cdx for. * @return A list of cdx records. * @throws ArgumentNotValid If jobid is 0 or negative. * @throws IOFailure On trouble generating the cdx */ public static List<CDXRecord> getMetadataCDXRecordsForJob(long jobid) { ArgumentNotValid.checkPositive(jobid, "jobid"); FileBatchJob cdxJob = new ArchiveExtractCDXJob(false); cdxJob.processOnlyFilesMatching(jobid + "-metadata-[0-9]+\\.(w)?arc(\\.gz)?"); File f; try { f = File.createTempFile(jobid + "-reports", ".cdx", FileUtils.getTempDir()); } catch (IOException e) { throw new IOFailure("Could not create temporary file", e); } BatchStatus status = ArcRepositoryClientFactory.getViewerInstance().batch( cdxJob, Settings.get(CommonSettings.USE_REPLICA_ID)); status.getResultFile().copyTo(f); List<CDXRecord> records; BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(f)); records = new ArrayList<CDXRecord>(); for (String line = reader.readLine(); line != null; line = reader.readLine()) { String[] parts = line.split("\\s+"); CDXRecord record = new CDXRecord(parts); records.add(record); } } catch (IOException e) { throw new IOFailure("Unable to read results from file '" + f + "'", e); } finally { IOUtils.closeQuietly(reader); FileUtils.remove(f); } return records; } }
package net.openright.infrastructure.db; import net.openright.infrastructure.util.ExceptionUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.*; public class PgsqlDatabase { private static final Logger log = LoggerFactory.getLogger(PgsqlDatabase.class); public interface ConnectionCallback<T> { T run(Connection conn); } public interface StatementCallback<T> { T run(PreparedStatement stmt) throws SQLException; } public interface RowMapper<T> { T run(Row row) throws SQLException; } public static class Row { private final ResultSet rs; private final Map<String, Integer> columnMap = new HashMap<>(); public Row(ResultSet rs) throws SQLException { this.rs = rs; for (int i = 1; i < rs.getMetaData().getColumnCount() + 1; i++) { String tableName = rs.getMetaData().getTableName(i); String columnName = rs.getMetaData().getColumnName(i); this.columnMap.put(tableName + "." + columnName, i); } } public String getString(String string) throws SQLException { return rs.getString(string); } public int getInt(String columnName) throws SQLException { return rs.getInt(columnName); } public long getLong(String tableName, String columnName) throws SQLException { return rs.getLong(getColumnIndex(tableName, columnName)); } public String getString(String tableName, String columnName) throws SQLException { return rs.getString(getColumnIndex(tableName, columnName)); } public boolean getBoolean(String tableName, String columnName) throws SQLException { return rs.getBoolean(getColumnIndex(tableName, columnName)); } public double getDouble(String tableName, String columnName) throws SQLException { return rs.getDouble(getColumnIndex(tableName, columnName)); } private int getColumnIndex(String tableName, String columnName) { return columnMap.get(tableName + "." + columnName); } } private final DataSource dataSource; private final static ThreadLocal<Connection> threadConnection = new ThreadLocal<>(); public PgsqlDatabase(DataSource dataSource) { this.dataSource = dataSource; } public PgsqlDatabase(String name) { try { this.dataSource = (DataSource) new InitialContext().lookup(name); } catch (NamingException e) { throw ExceptionUtil.soften(e); } } /** * Insert an object into the database. Used for create operations. * * @param query * in SQL in PostgreSQL dialect stated as a prepared statement. * @param parameters * values for the prepared statement. * @return the database field id from the inserted element. */ public int insert(String query, Object... parameters) { return executeDbOperation(query, Arrays.asList(parameters), stmt -> { ResultSet rs = stmt.executeQuery(); rs.next(); return rs.getInt("id"); }); } /** * Retrieves a list of results from the database and maps it to an object. * * @param query * in SQL stated as a prepared statement. * @param mapper * definition for mapping fields to the returned objects in the * list. * @param parameters * for the prepared statement. * @return database result mapped to list of classes. */ public <T> List<T> queryForList(String query, RowMapper<T> mapper, Object... parameters) { return executeDbOperation(query, Arrays.asList(parameters), stmt -> { try (ResultSet rs = stmt.executeQuery()) { Row row = new Row(rs); List<T> result = new ArrayList<>(); while (rs.next()) { result.add(mapper.run(row)); } return result; } }); } /** * Retrieves a single result from the database and maps it to an objec. * * @param query * in SQL stated as a prepared statement. * @param mapper * definition for mapping fields to the returned object. * @param parameters * for the prepared statement. * @return database result mapped to class. */ public <T> Optional<T> queryForSingle(String query, RowMapper<T> mapper, Object... parameters) { return executeDbOperation(query, Arrays.asList(parameters), stmt -> { try (ResultSet rs = stmt.executeQuery()) { return mapSingleRow(rs, mapper); } }); } /** * Update or delete operation sent to the database. * * @param query * in SQL stated as a prepared statement. * @param parameters * for the prepared statement. */ public void executeOperation(String query, Object... parameters) { executeDbOperation(query, Arrays.asList(parameters), PreparedStatement::executeUpdate); } /** * Create a transaction for multiple database operations like * {@link #insert(String, Object...) insert}, * {@link #queryForList(String, RowMapper, Object...) queryForList}, * {@link #queryForSingle(String, RowMapper, Object...) queryForSingle} or * {@link #executeOperation(String, Object...) executeOperation} * * @param operation is a functional interface to allow transaction to run in a thread. */ public void doInTransaction(Runnable operation) { try (Connection connection = dataSource.getConnection()) { threadConnection.set(connection); try { operation.run(); } finally { threadConnection.set(null); } } catch (SQLException e) { throw ExceptionUtil.soften(e); } } private <T> T doWithConnection(ConnectionCallback<T> object) { if (threadConnection.get() != null) { return object.run(threadConnection.get()); } try (Connection conn = dataSource.getConnection()) { return object.run(conn); } catch (SQLException e) { throw ExceptionUtil.soften(e); } } private <T> T executeDbOperation(String query, Collection<Object> parameters, StatementCallback<T> statementCallback) { return doWithConnection(conn -> { log.info("Executing: {} with params {}", query, parameters); try (PreparedStatement prepareStatement = conn.prepareStatement(query)) { int index = 1; for (Object object : parameters) { prepareStatement.setObject(index++, object); } return statementCallback.run(prepareStatement); } catch (SQLException e) { throw ExceptionUtil.soften(e); } }); } private <T> Optional<T> mapSingleRow(ResultSet rs, RowMapper<T> mapper) throws SQLException { if (!rs.next()) { return Optional.empty(); } T result = mapper.run(new Row(rs)); if (rs.next()) { throw new RuntimeException("Duplicate"); } return Optional.of(result); } }
package net.sf.taverna.t2.component; import static java.lang.Thread.currentThread; import static net.sf.taverna.t2.component.registry.ComponentDataflowCache.getDataflow; import static org.apache.log4j.Logger.getLogger; import java.util.Map; import net.sf.taverna.t2.activities.dataflow.DataflowActivity; import net.sf.taverna.t2.component.api.RegistryException; import net.sf.taverna.t2.component.profile.ExceptionHandling; import net.sf.taverna.t2.invocation.InvocationContext; import net.sf.taverna.t2.invocation.impl.InvocationContextImpl; import net.sf.taverna.t2.reference.ReferenceService; import net.sf.taverna.t2.reference.T2Reference; import net.sf.taverna.t2.workbench.edits.EditManager; import net.sf.taverna.t2.workflowmodel.Dataflow; import net.sf.taverna.t2.workflowmodel.DataflowInputPort; import net.sf.taverna.t2.workflowmodel.DataflowOutputPort; import net.sf.taverna.t2.workflowmodel.EditException; import net.sf.taverna.t2.workflowmodel.Edits; import net.sf.taverna.t2.workflowmodel.OutputPort; import net.sf.taverna.t2.workflowmodel.impl.DataflowImpl; import net.sf.taverna.t2.workflowmodel.processor.activity.AbstractAsynchronousActivity; import net.sf.taverna.t2.workflowmodel.processor.activity.ActivityConfigurationException; import net.sf.taverna.t2.workflowmodel.processor.activity.ActivityInputPort; import net.sf.taverna.t2.workflowmodel.processor.activity.AsynchronousActivity; import net.sf.taverna.t2.workflowmodel.processor.activity.AsynchronousActivityCallback; import net.sf.taverna.t2.workflowmodel.processor.activity.LockedNestedDataflow; import net.sf.taverna.t2.workflowmodel.processor.activity.NestedDataflow; import net.sf.taverna.t2.workflowmodel.utils.AnnotationTools; import org.apache.log4j.Logger; public class ComponentActivity extends AbstractAsynchronousActivity<ComponentActivityConfigurationBean> implements AsynchronousActivity<ComponentActivityConfigurationBean>, LockedNestedDataflow { private static final Logger logger = getLogger(ComponentActivity.class); private static final EditManager em = EditManager.getInstance(); private static final Edits EDITS = em.getEdits(); private static final AnnotationTools aTools = new AnnotationTools(); private volatile DataflowActivity componentRealization = new DataflowActivity(); private ComponentActivityConfigurationBean configBean; private DataflowImpl skeletonDataflow = null; @Override public void configure(ComponentActivityConfigurationBean configBean) throws ActivityConfigurationException { this.configBean = configBean; try { configurePorts(configBean.getPorts()); } catch (RegistryException e) { throw new ActivityConfigurationException( "failed to get component realization", e); } skeletonDataflow = (DataflowImpl) EDITS.createDataflow(); skeletonDataflow.setLocalName(configBean.getComponentName()); for (ActivityInputPort aip : getInputPorts()) try { DataflowInputPort dip = EDITS.createDataflowInputPort( aip.getName(), aip.getDepth(), aip.getDepth(), skeletonDataflow); EDITS.getAddDataflowInputPortEdit(skeletonDataflow, dip) .doEdit(); } catch (EditException e) { logger.error("failed to add dataflow input", e); } for (OutputPort aop : getOutputPorts()) try { DataflowOutputPort dop = EDITS.createDataflowOutputPort( aop.getName(), skeletonDataflow); EDITS.getAddDataflowOutputPortEdit(skeletonDataflow, dop) .doEdit(); } catch (EditException e) { logger.error("failed to add dataflow output", e); } } @Override public void executeAsynch(final Map<String, T2Reference> inputs, final AsynchronousActivityCallback callback) { // try { // Field field = callback.getClass().getDeclaredField("this$0"); // field.setAccessible(true); // AbstractDispatchLayer container = (AbstractDispatchLayer) // field.get(callback); // Processor containingProcessor = container.getProcessor(); // String description = aTools.getAnnotationString(containingProcessor, // FreeTextDescription.class, null); // } catch (Exception e) { // logger.error(e); try { ExceptionHandling exceptionHandling = configBean .getExceptionHandling(); // InvocationContextImpl newContext = // copyInvocationContext(callback); AsynchronousActivityCallback useCallback = new ProxyCallback( callback, callback.getContext(), exceptionHandling); getComponentRealization().executeAsynch(inputs, useCallback); } catch (ActivityConfigurationException e) { callback.fail("Unable to execute component", e); } } @SuppressWarnings("unused") private InvocationContextImpl copyInvocationContext( final AsynchronousActivityCallback callback) { InvocationContext originalContext = callback.getContext(); ReferenceService rs = originalContext.getReferenceService(); InvocationContextImpl newContext = new InvocationContextImpl(rs, null); // for (Object o : originalContext.getEntities(Object.class)) { // newContext.addEntity(o); return newContext; } @Override public ComponentActivityConfigurationBean getConfiguration() { return configBean; } public DataflowActivity getComponentRealization() throws ActivityConfigurationException { synchronized (componentRealization) { if (componentRealization.getConfiguration() == null) { Dataflow d; try { d = getDataflow(configBean); } catch (RegistryException e) { throw new ActivityConfigurationException( "Unable to read dataflow", e); } componentRealization.configure(d); for (Class<?> c : aTools.getAnnotatingClasses(this)) { String annotationValue = aTools.getAnnotationString(d, c, null); if (annotationValue == null) continue; try { aTools.setAnnotationString(this, c, annotationValue) .doEdit(); } catch (EditException e) { logger.error("failed to set annotation string", e); } } } return componentRealization; } } @Override public Dataflow getNestedDataflow() { // FIXME To go when integrated into Taverna properly StackTraceElement[] stackTrace = currentThread().getStackTrace(); for (StackTraceElement elem : stackTrace) if (elem.getClassName().contains("GraphController")) return skeletonDataflow; try { return getDataflow(configBean); } catch (RegistryException e) { logger.error("failed to get component realization", e); } return skeletonDataflow; } }
package de.eightbitboy.hijacr.data.comic; /** * Information about a comic. */ public class ComicData { /** * The comic's title. */ private String title; /** * The comic's website URL. */ private String baseUrl; /** * The comic's first page URL. */ private String firstPageUrl; /** * The Jsoup query for the image URL. */ private String imageQuery; /** * The Jsoup query for the URL to ne next comic site. */ private String nextQuery; /** * The Jsoup query for the URL to the previous comic site. */ private String previousQuery; private boolean countable = false; private String countableUrl = null; public ComicData(String title, String baseUrl, String firstPageUrl, String imageQuery, String nextQuery, String previousQuery) { this.title = title; this.baseUrl = baseUrl; this.firstPageUrl = firstPageUrl; this.imageQuery = imageQuery; this.nextQuery = nextQuery; this.previousQuery = previousQuery; } public ComicData(String title, String baseUrl, String firstPageUrl, String imageQuery, String nextQuery, String previousQuery, boolean countable, String countableUrl) { this(title, baseUrl, firstPageUrl, imageQuery, nextQuery, previousQuery); this.countable = countable; this.countableUrl = countableUrl; } public String getTitle() { return this.title; } public String getBaseUrl() { return this.baseUrl; } public String getFirstPageUrl() { return this.firstPageUrl; } public String getImageQuery() { return this.imageQuery; } public String getNextQuery() { return this.nextQuery; } public String getPreviousQuery() { return this.previousQuery; } }
//FILE: OMEMetadata.java //PROJECT: Micro-Manager //SUBSYSTEM: mmstudio // This file is distributed in the hope that it will be useful, // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES. package org.micromanager.acquisition; import java.nio.ByteOrder; import java.util.TreeMap; import loci.common.DateTools; import loci.common.services.ServiceFactory; import loci.formats.MetadataTools; import loci.formats.meta.IMetadata; import loci.formats.services.OMEXMLService; import ome.xml.model.primitives.Color; import ome.xml.model.primitives.NonNegativeInteger; import ome.xml.model.primitives.PositiveFloat; import ome.xml.model.primitives.PositiveInteger; import ome.xml.model.primitives.Timestamp; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.micromanager.utils.MDUtils; import org.micromanager.utils.MMScriptException; import org.micromanager.utils.ReportingUtils; public class OMEMetadata { private IMetadata metadata_; private TaggedImageStorageMultipageTiff mptStorage_; private TreeMap<Integer, Indices> seriesIndices_ = new TreeMap<Integer, Indices>(); private int numSlices_, numChannels_; private TreeMap<String, Integer> tiffDataIndexMap_; private class Indices { //specific to each series independent of file int tiffDataIndex_ = -1; //specific to each series indpeendent of file int planeIndex_ = 0; } public OMEMetadata(TaggedImageStorageMultipageTiff mpt) { mptStorage_ = mpt; tiffDataIndexMap_ = new TreeMap<String,Integer>(); metadata_ = MetadataTools.createOMEXMLMetadata(); } public static String getOMEStringPointerToMasterFile(String filename, String uuid) { try { IMetadata md = MetadataTools.createOMEXMLMetadata(); md.setBinaryOnlyMetadataFile(filename); md.setBinaryOnlyUUID(uuid); return new ServiceFactory().getInstance(OMEXMLService.class).getOMEXML(md) + " "; } catch (Exception ex) { ReportingUtils.logError("Couldn't generate partial OME block"); return " "; } } @Override public String toString() { try { OMEXMLService service = new ServiceFactory().getInstance(OMEXMLService.class); return service.getOMEXML(metadata_) + " "; } catch (Exception ex) { ReportingUtils.logError(ex); return ""; } } public void setNumFrames(int seriesIndex, int numFrames) { metadata_.setPixelsSizeT(new PositiveInteger(numFrames), seriesIndex); } private void startSeriesMetadata(JSONObject firstImageTags, int seriesIndex, String baseFileName) throws JSONException, MMScriptException { Indices indices = new Indices(); indices.planeIndex_ = 0; indices.tiffDataIndex_ = 0; seriesIndices_.put(seriesIndex, indices); //Last one is samples per pixel JSONObject summaryMD = mptStorage_.getSummaryMetadata(); numSlices_ = MDUtils.getNumSlices(summaryMD); numChannels_ = MDUtils.getNumChannels(summaryMD); MetadataTools.populateMetadata(metadata_, seriesIndex, baseFileName, MultipageTiffWriter.BYTE_ORDER.equals(ByteOrder.LITTLE_ENDIAN), mptStorage_.slicesFirst() ? "XYZCT" : "XYCZT", "uint" + (MDUtils.isGRAY8(summaryMD) ? "8" : "16"), MDUtils.getWidth(summaryMD), MDUtils.getHeight(summaryMD), numSlices_, MDUtils.getNumChannels(summaryMD), MDUtils.getNumFrames(summaryMD), 1); if (MDUtils.hasPixelSizeUm(summaryMD)) { double pixelSize = MDUtils.getPixelSizeUm(summaryMD); if (pixelSize > 0) { metadata_.setPixelsPhysicalSizeX(new PositiveFloat(pixelSize), seriesIndex); metadata_.setPixelsPhysicalSizeY(new PositiveFloat(pixelSize), seriesIndex); } } if (MDUtils.hasZStepUm(summaryMD)) { double zStep = MDUtils.getZStepUm(summaryMD); if (zStep != 0) { metadata_.setPixelsPhysicalSizeZ(new PositiveFloat(Math.abs(zStep)), seriesIndex); } } if (MDUtils.hasIntervalMs(summaryMD)) { double interval = MDUtils.getIntervalMs(summaryMD); if (interval > 0) { //don't write it for burst mode because it won't be true metadata_.setPixelsTimeIncrement(interval / 1000.0, seriesIndex); } } String positionName; try { positionName = MDUtils.getPositionName(firstImageTags); } catch (JSONException ex) { ReportingUtils.logError("Couldn't find position name in image metadata"); positionName = "pos" + MDUtils.getPositionIndex(firstImageTags); } metadata_.setStageLabelName(positionName, seriesIndex); String instrumentID = MetadataTools.createLSID("Microscope"); metadata_.setInstrumentID(instrumentID, 0); // link Instrument and Image metadata_.setImageInstrumentRef(instrumentID, seriesIndex); JSONObject comments = mptStorage_.getDisplayAndComments().getJSONObject("Comments"); if (comments.has("Summary") && !comments.isNull("Summary")) { metadata_.setImageDescription(comments.getString("Summary"), seriesIndex); } JSONArray channels = mptStorage_.getDisplayAndComments().getJSONArray("Channels"); for (int channelIndex = 0; channelIndex < channels.length(); channelIndex++) { JSONObject channel = channels.getJSONObject(channelIndex); metadata_.setChannelColor(new Color(channel.getInt("Color")), seriesIndex, channelIndex); metadata_.setChannelName(channel.getString("Name"), seriesIndex, channelIndex); } } /* * Method called when numC*numZ*numT != total number of planes */ public void fillInMissingTiffDatas(int frame, int position) { try { for (int slice = 0; slice < numSlices_; slice++) { for (int channel = 0; channel < numChannels_; channel++) { //make sure each tiffdata entry is present. If it is missing, link Tiffdata entry //to a a preveious IFD Integer tiffDataIndex = tiffDataIndexMap_.get(MDUtils.generateLabel(channel, slice, frame, position)); if (tiffDataIndex == null) { //this plane was never added, so link to another IFD //find substitute channel, frame, slice int s = slice; int backIndex = slice - 1, forwardIndex = slice + 1; int frameSearchIndex = frame; //If some but not all channels have z stacks, find the closest slice for the given //channel that has an image. Also if time point missing, go back until image is found while (tiffDataIndex == null) { tiffDataIndex = tiffDataIndexMap_.get(MDUtils.generateLabel(channel, s, frameSearchIndex, position)); if (tiffDataIndex != null) { break; } if (backIndex >= 0) { tiffDataIndex = tiffDataIndexMap_.get(MDUtils.generateLabel(channel, backIndex, frameSearchIndex, position)); if (tiffDataIndex != null) { break; } backIndex } if (forwardIndex < numSlices_) { tiffDataIndex = tiffDataIndexMap_.get(MDUtils.generateLabel(channel, forwardIndex, frameSearchIndex, position)); if (tiffDataIndex != null) { break; } forwardIndex++; } if (backIndex < 0 && forwardIndex >= numSlices_) { frameSearchIndex backIndex = slice - 1; forwardIndex = slice + 1; if (frameSearchIndex < 0) { break; } } } NonNegativeInteger ifd = metadata_.getTiffDataIFD(position, tiffDataIndex); String filename = metadata_.getUUIDFileName(position, tiffDataIndex); String uuid = metadata_.getUUIDValue(position, tiffDataIndex); Indices indices = seriesIndices_.get(position); metadata_.setTiffDataFirstZ(new NonNegativeInteger(slice), position, indices.tiffDataIndex_); metadata_.setTiffDataFirstC(new NonNegativeInteger(channel), position, indices.tiffDataIndex_); metadata_.setTiffDataFirstT(new NonNegativeInteger(frame), position, indices.tiffDataIndex_); metadata_.setTiffDataIFD(ifd, position, indices.tiffDataIndex_); metadata_.setUUIDFileName(filename, position, indices.tiffDataIndex_); metadata_.setUUIDValue(uuid, position, indices.tiffDataIndex_); metadata_.setTiffDataPlaneCount(new NonNegativeInteger(1), position, indices.tiffDataIndex_); indices.tiffDataIndex_++; } } } } catch (Exception e) { ReportingUtils.logError("Couldn't fill in missing tiffdata entries in ome metadata"); } } public void addImageTagsToOME(JSONObject tags, int ifdCount, String baseFileName, String currentFileName, String uuid) throws JSONException, MMScriptException { int position; try { position = MDUtils.getPositionIndex(tags); } catch (Exception e) { position = 0; } if (!seriesIndices_.containsKey(position)) { startSeriesMetadata(tags, position, baseFileName); try { //Add these tags in only once, but need to get them from image rather than summary metadata setOMEDetectorMetadata(tags); if (MDUtils.hasImageTime(tags)) { // Alas, the metadata "Time" field is in one of two formats. String imageDate = MDUtils.getImageTime(tags); String reformattedDate = DateTools.formatDate(imageDate, "yyyy-MM-dd HH:mm:ss Z", true); if (reformattedDate == null) { reformattedDate = DateTools.formatDate(imageDate, "yyyy-MM-dd E HH:mm:ss Z", true); } if (reformattedDate != null) { metadata_.setImageAcquisitionDate( new Timestamp(reformattedDate), position); } } } catch (Exception e) { ReportingUtils.logError(e, "Problem adding System state cache metadata to OME Metadata: " + e); } } Indices indices = seriesIndices_.get(position); //Required tags: Channel, slice, and frame index try { int slice = MDUtils.getSliceIndex(tags); int frame = MDUtils.getFrameIndex(tags); int channel = MDUtils.getChannelIndex(tags); // ifdCount is 0 when a new file started, tiff data plane count is 0 at a new position metadata_.setTiffDataFirstZ(new NonNegativeInteger(slice), position, indices.tiffDataIndex_); metadata_.setTiffDataFirstC(new NonNegativeInteger(channel), position, indices.tiffDataIndex_); metadata_.setTiffDataFirstT(new NonNegativeInteger(frame), position, indices.tiffDataIndex_); metadata_.setTiffDataIFD(new NonNegativeInteger(ifdCount), position, indices.tiffDataIndex_); metadata_.setUUIDFileName(currentFileName, position, indices.tiffDataIndex_); metadata_.setUUIDValue(uuid, position, indices.tiffDataIndex_); tiffDataIndexMap_.put(MDUtils.generateLabel(channel, slice, frame, position), indices.tiffDataIndex_); metadata_.setTiffDataPlaneCount(new NonNegativeInteger(1), position, indices.tiffDataIndex_); metadata_.setPlaneTheZ(new NonNegativeInteger(slice), position, indices.planeIndex_); metadata_.setPlaneTheC(new NonNegativeInteger(channel), position, indices.planeIndex_); metadata_.setPlaneTheT(new NonNegativeInteger(frame), position, indices.planeIndex_); } catch (JSONException ex) { ReportingUtils.showError("Image Metadata missing ChannelIndex, SliceIndex, or FrameIndex"); } catch (Exception e) { ReportingUtils.logError("Couldn't add to OME metadata"); } //Optional tags try { if (MDUtils.hasExposureMs(tags)) { metadata_.setPlaneExposureTime(MDUtils.getExposureMs(tags) / 1000.0, position, indices.planeIndex_); } if (MDUtils.hasXPositionUm(tags)) { metadata_.setPlanePositionX(MDUtils.getXPositionUm(tags), position, indices.planeIndex_); if (indices.planeIndex_ == 0) { //should be set at start, but dont have position coordinates then metadata_.setStageLabelX(MDUtils.getXPositionUm(tags), position); } } if (MDUtils.hasYPositionUm(tags)) { metadata_.setPlanePositionY(MDUtils.getYPositionUm(tags), position, indices.planeIndex_); if (indices.planeIndex_ == 0) { metadata_.setStageLabelY(MDUtils.getYPositionUm(tags), position); } } if (MDUtils.hasZPositionUm(tags)) { metadata_.setPlanePositionZ(MDUtils.getZPositionUm(tags), position, indices.planeIndex_); } if (MDUtils.hasElapsedTimeMs(tags)) { metadata_.setPlaneDeltaT(MDUtils.getElapsedTimeMs(tags) / 1000.0, position, indices.planeIndex_); } } catch (JSONException e) { ReportingUtils.logError("Problem adding tags to OME Metadata"); } indices.planeIndex_++; indices.tiffDataIndex_++; } private void setOMEDetectorMetadata(JSONObject tags) throws JSONException { if (!MDUtils.hasCoreCamera(tags)) { return; } String coreCam = MDUtils.getCoreCamera(tags); String[] cameras; if (tags.has(coreCam + "-Physical Camera 1")) { //Multicam mode int numCams = 1; if (!tags.getString(coreCam + "-Physical Camera 3").equals("Undefined")) { numCams = 3; } else if (!tags.getString(coreCam + "-Physical Camera 2").equals("Undefined")) { numCams = 2; } cameras = new String[numCams]; for (int i = 0; i < numCams; i++) { cameras[i] = tags.getString(coreCam + "-Physical Camera " + (1 + i)); } } else { //Single camera mode cameras = new String[1]; cameras[0] = coreCam; } for (int detectorIndex = 0; detectorIndex < cameras.length; detectorIndex++) { String camera = cameras[detectorIndex]; String detectorID = MetadataTools.createLSID(camera); //Instrument index, detector index metadata_.setDetectorID(detectorID, 0, detectorIndex); if (tags.has(camera + "-Name") && !tags.isNull(camera + "-Name")) { metadata_.setDetectorManufacturer(tags.getString(camera + "-Name"), 0, detectorIndex); } if (tags.has(camera + "-CameraName") && !tags.isNull(camera + "-CameraName")) { metadata_.setDetectorModel(tags.getString(camera + "-CameraName"), 0, detectorIndex); } if (tags.has(camera + "-Offset") && !tags.isNull(camera + "-Offset")) { metadata_.setDetectorOffset(Double.parseDouble(tags.getString(camera + "-Offset")), 0, detectorIndex); } if (tags.has(camera + "-CameraID") && !tags.isNull(camera + "-CameraID")) { metadata_.setDetectorSerialNumber(tags.getString(camera + "-CameraID"), 0, detectorIndex); } } } }
package nl.hsac.fitnesse.slim; import fitnesse.testsystems.TestExecutionException; import fitnesse.testsystems.slim.SlimTestContext; import fitnesse.testsystems.slim.Table; import fitnesse.testsystems.slim.tables.*; import nl.hsac.fitnesse.slimcoverage.SlimCoverageTestContextImpl; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * ScenarioTable that looks for in- and output parameters in all its rows, without the * parameters having to be specified in the first row also. */ public class AutoArgScenarioTable extends ScenarioTable { private static final Pattern ARG_PATTERN = Pattern.compile("@\\{(.+?)\\}"); private static final Pattern OUT_PATTERN = Pattern.compile("\\$(.+?)="); private Set<String> inputs; private Set<String> outputs; private Map<String, String> currentCallArguments; public AutoArgScenarioTable(Table table, String tableId, SlimTestContext testContext) { super(table, tableId, testContext); } @Override public List<SlimAssertion> getAssertions() throws SyntaxError { inputs = findArguments(ARG_PATTERN); outputs = findArguments(OUT_PATTERN); return super.getAssertions(); } @Override protected boolean determineParameterized() { return !inputs.isEmpty(); } @Override protected void getScenarioArguments() { for (String input : inputs) { addInput(input); } for (String output : outputs) { addOutput(output); } } private Set<String> findArguments(Pattern pattern) { Set<String> found = new LinkedHashSet<String>(); int rowCount = table.getRowCount(); for (int row = 0; row < rowCount; row++) { int columnCount = table.getColumnCountInRow(row); for (int column = 0; column < columnCount; column++) { String cellContent = table.getCellContents(column, row); if (!addAllMatches(pattern, found, cellContent) && maybeNestedScenario(columnCount, cellContent)) { addNestedScenarioArguments(found, pattern == ARG_PATTERN, cellContent); } } } return found; } private void addNestedScenarioArguments(Set<String> found, boolean addInputs, String cellContent) { String scenarioName = getCalledScenarioName(cellContent); SlimTestContext testContext = getTestContext(); ScenarioTable scenario; if (testContext instanceof SlimCoverageTestContextImpl) { scenario = ((SlimCoverageTestContextImpl) testContext).getScenarioNoCount(scenarioName); } else { scenario = testContext.getScenario(scenarioName); } if (scenario != null) { Set<String> scenarioArgs = addInputs ? scenario.getInputs() : scenario.getOutputs(); found.addAll(scenarioArgs); } } private String getCalledScenarioName(String cellContent) { String scenarioName = cellContent.substring(0, cellContent.length() - 1); return Disgracer.disgraceClassName(scenarioName); } private boolean maybeNestedScenario(int columnCount, String cellContent) { return columnCount == 1 && cellContent.endsWith(";"); } private boolean addAllMatches(Pattern pattern, Set<String> found, String cellContent) { boolean anyMatches = false; Matcher m = pattern.matcher(cellContent); while (m.find()) { String input = m.group(1); found.add(input); anyMatches = true; } return anyMatches; } public Map<String, String> getCurrentCallArguments() { return currentCallArguments; } @Override public List<SlimAssertion> call(Map<String, String> scenarioArguments, SlimTable parentTable, int row) throws TestExecutionException { try { currentCallArguments = scenarioArguments; if (scenarioArguments.isEmpty()) { SlimTestContext context = parentTable.getTestContext(); if (context instanceof ScenarioTestContext) { ScenarioTestContext sTestContext = (ScenarioTestContext) context; AutoArgScenarioTable caller = getCallingTable(sTestContext); Map<String, String> callerArgs = caller.getCurrentCallArguments(); for (Map.Entry<String, String> entry : callerArgs.entrySet()) { String arg = entry.getKey(); if (inputs.contains(arg)) { scenarioArguments.put(arg, entry.getValue()); } } } } return super.call(scenarioArguments, parentTable, row); } finally { currentCallArguments = null; } } private AutoArgScenarioTable getCallingTable(ScenarioTestContext context) { ScenarioTable t = context.getScenarioTable(); if (t instanceof AutoArgScenarioTable) { return (AutoArgScenarioTable) t; } else { return null; } } }
package org.agmip.translators.dssat; import com.google.common.base.Function; import java.io.File; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.agmip.core.types.TranslatorOutput; import static org.agmip.util.MapUtil.*; /** * DSSAT Experiment Data I/O API Class * * @author Meng Zhang * @version 1.0 */ public abstract class DssatCommonOutput implements TranslatorOutput { // Default value for each type of value (R: real number; C: String; I: Integer; D: Date) protected String defValR = "0.00"; protected String defValC = ""; protected String defValI = "0"; protected String defValD = "-99"; protected String defValBlank = ""; // construct the error message in the output protected StringBuilder sbError; protected File outputFile; protected static HashMap<String, String> exToFileMap = new HashMap(); protected static HashSet<String> fileNameSet = new HashSet(); protected static DssatWthFileHelper wthHelper = new DssatWthFileHelper(); protected static DssatSoilFileHelper soilHelper = new DssatSoilFileHelper(); /** * Translate data str from "yyyymmdd" to "yyddd" * * 2012/3/19 change input format from "yy/mm/dd" to "yyyymmdd" * * @param str date string with format of "yyyymmdd" * @return result date string with format of "yyddd" */ protected String formatDateStr2(String str) { // Initial Calendar object Calendar cal = Calendar.getInstance(); str = str.replaceAll("/", ""); try { // Set date with input value cal.set(Integer.parseInt(str.substring(0, 4)), Integer.parseInt(str.substring(4, 6)) - 1, Integer.parseInt(str.substring(6))); // translatet to yyddd format return String.format("%1$02d%2$03d", cal.get(Calendar.YEAR) % 100, cal.get(Calendar.DAY_OF_YEAR)); } catch (Exception e) { // if tranlate failed, then use default value for date //sbError.append("! Waring: There is a invalid date [").append(str).append("]\r\n"); return formatDateStr2(defValD); } } /** * Format the number with maximum length and type * * @param bits Maximum length of the output string * @param m the experiment data holder * @param key the key of field in the map * @param defVal the default return value when error happens * @return formated string of number */ protected String formatNumStr(int bits, HashMap m, Object key, String defVal) { String ret = ""; String str = getObjectOr(m, key, defVal); String[] inputStr = str.split("\\."); if (str.trim().equals("")) { return String.format("%" + bits + "s", defVal); } else if (str.length() <= bits) { ret = String.format("%1$" + bits + "s", str); } else if (inputStr[0].length() > bits) { //throw new Exception(); sbError.append("! Waring: There is a variable [").append(key).append("] with oversized number [").append(ret).append("] (Limitation is ").append(bits).append(" bits)\r\n"); return String.format("%" + bits + "s", defVal); } else { int decimalLength = bits - inputStr[0].length() - 1; decimalLength = decimalLength < 0 ? 0 : decimalLength; ret = org.agmip.common.Functions.round(str, decimalLength); } return ret; } /** * Format the output string with maximum length * * @param bits Maximum length of the output string * @param m the experiment data holder * @param key the key of field in the map * @param defVal the default return value when error happens * @return formated string of number */ protected String formatStr(int bits, HashMap m, Object key, String defVal) { String ret = getObjectOr(m, key, defVal).trim(); if (ret.equals("")) { return ret; } else if (ret.length() > bits) { //throw new Exception(); sbError.append("! Waring: There is a variable [").append(key).append("] with oversized content [").append(ret).append("], only first ").append(bits).append(" bits will be applied.\r\n"); return ret.substring(0, bits); } return ret; } /** * Translate data str from "yyyymmdd" to "yyddd" * * 2012/3/19 change input format from "yy/mm/dd" to "yyyymmdd" * * @param str date string with format of "yyyymmdd" * @return result date string with format of "yyddd" */ protected String formatDateStr(String str) { return formatDateStr(str, "0"); } /** * Translate data str from "yyyymmdd" to "yyddd" plus days you want * * @param startDate date string with format of "yyyymmdd" * @param strDays the number of days need to be added on * @return result date string with format of "yyddd" */ protected String formatDateStr(String startDate, String strDays) { // Initial Calendar object Calendar cal = Calendar.getInstance(); int days; startDate = startDate.replaceAll("/", ""); try { days = Double.valueOf(strDays).intValue(); // Set date with input value cal.set(Integer.parseInt(startDate.substring(0, 4)), Integer.parseInt(startDate.substring(4, 6)) - 1, Integer.parseInt(startDate.substring(6))); cal.add(Calendar.DATE, days); // translatet to yyddd format return String.format("%1$02d%2$03d", cal.get(Calendar.YEAR) % 100, cal.get(Calendar.DAY_OF_YEAR)); } catch (Exception e) { // if tranlate failed, then use default value for date // sbError.append("! Waring: There is a invalid date [").append(startDate).append("]\r\n"); return "-99"; //formatDateStr(defValD); } } /** * Get experiment name without any extention content after first underscore * * @param result date holder for experiment data * @return experiment name */ protected String getExName(Map result) { String ret = getValueOr(result, "exname", ""); if (ret.contains(".")) { ret = ret.substring(0, ret.length() - 1).replace(".", ""); } // TODO need to be updated with a translate rule for other models' exname if (ret.matches("[\\w ]+(_+\\d+)+$")) { ret = ret.replaceAll("(_+\\d+)+$", ""); } return ret; } /** * Get crop id with 2-bit format * * @param result date holder for experiment data * @return crop id */ protected String getCrid(Map result) { HashMap mgnData = getObjectOr(result, "management", new HashMap()); ArrayList<HashMap> events = getObjectOr(mgnData, "events", new ArrayList()); String crid = null; for (int i = 0; i < events.size(); i++) { if (events.get(i).get("event").equals("planting")) { if (crid == null) { crid = (String) events.get(i).get("crid"); } else if (!crid.equals(events.get(i).get("crid"))) { return "SQ"; } } } // DssatCRIDHelper crids = new DssatCRIDHelper(); return DssatCRIDHelper.get2BitCrid(crid); } /** * Generate output file name * * @param result date holder for experiment data * @param fileType the last letter from file extend name * @return file name */ protected String getFileName(Map result, String fileType) { String exname = getExName(result); String crid; if (getValueOr(result, "seasonal_dome_applied", "N").equals("Y")) { crid = "SN"; } else { crid = getCrid(result); } if (exname.length() == 10) { if (crid.equals("XX")) { crid = exname.substring(exname.length() - 2, exname.length()); } } String ret; if (exToFileMap.containsKey(exname + "_" + crid)) { return exToFileMap.get(exname + "_" + crid) + fileType; } else { ret = exname; if (ret == null || ret.equals("")) { ret = "TEMP0001"; } else { try { if (ret.endsWith(crid)) { ret = ret.substring(0, ret.length() - crid.length()); } // If the exname is too long if (ret.length() > 8) { ret = ret.substring(0, 8); } // If the exname do not follow the Dssat rule if (!ret.matches("[\\w ]{1,6}\\d{2}$")) { if (ret.length() > 6) { ret = ret.substring(0, 6); } ret += "01"; } } catch (Exception e) { ret = "TEMP0001"; } } // Find a non-repeated file name int count; while (fileNameSet.contains(ret + "." + crid)) { try { count = Integer.parseInt(ret.substring(ret.length() - 2, ret.length())); count++; } catch (Exception e) { count = 1; } ret = ret.replaceAll("\\w{2}$", String.format("%02d", count)); } } exToFileMap.put(exname + "_" + crid, ret + "." + crid); fileNameSet.add(ret + "." + crid); return ret + "." + crid + fileType; } /** * Revise output path * * @param path the output path * @return revised path */ public static String revisePath(String path) { if (!path.trim().equals("")) { // path = path.replaceAll("/", File.separator); if (!path.endsWith(File.separator)) { path += File.separator; } File f = new File(path); if (f.isFile()) { f = f.getParentFile(); } if (f != null && !f.exists()) { f.mkdirs(); } } return path; } /** * Get output file object */ public File getOutputFile() { return outputFile; } /** * decompress the data in a map object * * @param m input map */ protected void decompressData(HashMap m) { for (Object key : m.keySet()) { if (m.get(key) instanceof ArrayList) { // iterate sub array nodes decompressData((ArrayList) m.get(key)); } else if (m.get(key) instanceof HashMap) { // iterate sub data nodes decompressData((HashMap) m.get(key)); } else { // ignore other type nodes } } } /** * decompress the data in an ArrayList object * * @param arr input ArrayList * */ protected void decompressData(ArrayList arr) { HashMap fstData = null; // The first data record (Map type) HashMap cprData; // The following data record which will be compressed for (int i = 0; i < arr.size(); i++) { if (arr.get(i) instanceof ArrayList) { // iterate sub array nodes decompressData((ArrayList) arr.get(i)); } else if (arr.get(i) instanceof HashMap) { // iterate sub data nodes decompressData((HashMap) arr.get(i)); // Compress data for current array if (fstData == null) { // Get first data node fstData = (HashMap) arr.get(i); } else { cprData = (HashMap) arr.get(i); // The omitted data will be recovered to the following map; Only data item (String type) will be processed for (Object key : fstData.keySet()) { if (!cprData.containsKey(key)) { cprData.put(key, fstData.get(key)); } } } } else { } } } /** * Get plating date from experiment management event * * @param result the experiment data object * @return plating date */ protected String getPdate(Map result) { HashMap management = getObjectOr(result, "management", new HashMap()); ArrayList<HashMap> events = getObjectOr(management, "events", new ArrayList<HashMap>()); for (int i = 0; i < events.size(); i++) { if (getValueOr(events.get(i), "event", "").equals("planting")) { return getValueOr(events.get(i), "date", ""); } } return ""; } /** * Get the weather file name for auto-generating (extend name not included) * * @param data experiment data holder or weather data holder * @return the weather file name */ protected String getWthFileName(HashMap data) { // String agmipFileHack = getValueOr(wthFile, "wst_name", ""); // if (agmipFileHack.length() == 8) { // return agmipFileHack; String ret = getObjectOr(data, "wst_id", "").toString(); if (ret.equals("") || ret.length() > 8) { ret = wthHelper.createWthFileName(getObjectOr(data, "weather", data)); if (ret.equals("")) { ret = "AGMP"; } } return ret; } protected String getSoilID(HashMap data) { return soilHelper.getSoilID(data); // String ret = getObjectOr(data, "soil_id", ""); // ret = ret.trim(); // if (ret.equals("")) { // return ret; // while (ret.length() < 8) { // ret += "_"; // return ret; } /** * Set default value for missing data * */ protected void setDefVal() { // defValD = ""; No need to set default value for Date type in weather file defValR = "-99"; defValC = "-99"; defValI = "-99"; sbError = new StringBuilder(); outputFile = null; } protected static String getStackTrace(Throwable aThrowable) { final Writer result = new StringWriter(); final PrintWriter printWriter = new PrintWriter(result); aThrowable.printStackTrace(printWriter); return result.toString(); } protected class HeaderArrayList<E> extends ArrayList<E> { private HashSet<E> items = new HashSet(); private HashSet<E> curItems; @Override public boolean contains(Object header) { return items.contains(header); } @Override public boolean add(E e) { if (!contains(e)) { super.add(e); items.add(e); return true; } else { return false; } } @Override public E get(int index) { if (curItems != null) { curItems.remove(super.get(index)); } return super.get(index); } public void seCurItems(Set set) { curItems = new HashSet(); curItems.addAll(set); } public boolean hasMoreItem() { if (curItems == null || curItems.isEmpty()) { return false; } else { return true; } } public E applyNext() { if (hasMoreItem()) { E ret = curItems.iterator().next(); curItems.remove(ret); this.add(ret); return ret; } return null; } } }
package de.sopa.model.justplay; import de.sopa.helper.LevelCreator; import de.sopa.model.game.LevelDestroyer; /** * @author Raphael Schilling - raphaelschiling@gmail.com */ public class JustPlayServiceImpl implements JustPlayService { private int levelCount; private final LevelCreator levelCreator; private final LevelDestroyer levelDestroyer; private int leftTime; private int lastScore; public JustPlayServiceImpl() { levelCreator = new LevelCreator(); levelDestroyer = new LevelDestroyer(); this.levelCount = 0; leftTime = 25; lastScore = 0; } @Override public JustPlayResult calculateResult(JustPlayLevelResult justPlayLevelResult) { int currentScore = calculateNewScore(justPlayLevelResult); JustPlayResult justPlayResult = new JustPlayResult(levelCount, justPlayLevelResult.getLeftTime(), calculateExtraTime(),lastScore, currentScore); lastScore = currentScore; leftTime = calculateExtraTime() + justPlayLevelResult.getLeftTime(); return justPlayResult; } private int calculateNewScore(JustPlayLevelResult justPlayLevelResult) { if(justPlayLevelResult.getLeftTime() == -1) { return lastScore; } else { return lastScore + 1000; } } private int calculateExtraTime() { return 10; } @Override public JustPlayLevel getNextLevel() { levelCount++; return new JustPlayLevel(leftTime, levelDestroyer.destroyField(levelCreator.generateSolvedField(4, 4), 1, 1)); } }
package applets.etsmtl.ca.cooptel; import applets.etsmtl.ca.cooptel.model.ConsommationDate; import applets.etsmtl.ca.cooptel.model.ConsommationGlobal; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; 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.MediaType; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Base64; import java.util.Calendar; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; @Path("cooptel") public class CooptelResource { @GET @Produces({MediaType.APPLICATION_JSON}) public ConsommationGlobal getInternetStats( @QueryParam("phase") String phase, @QueryParam("appt") String appt, @QueryParam("chambre") String chambre ) { String username, password; Date today = new Date(); Calendar cal = Calendar.getInstance(); cal.setTime(today); int month = cal.get(Calendar.MONTH) + 1; OkHttpClient client = new OkHttpClient(); username = "ets-res" + phase + "-" + appt + "-" + chambre; password = "ets" + appt; String basicAuth = Base64.getEncoder().encodeToString( (username + ":" + password).getBytes(StandardCharsets.UTF_8)); Request request = new Request.Builder() .url("http://www2.cooptel.qc.ca/services/temps/?mois=" + month + "&cmd=Visualiser") .get() .addHeader("authorization", "Basic " + basicAuth) .build(); Response response = null; Document doc = null; try { response = client.newCall(request).execute(); doc = Jsoup.parse(response.body().string()); } catch (IOException e) { e.printStackTrace(); } Elements tables = doc.select("table[border=1]"); Pattern detailsPattern = Pattern.compile("<td>(.*)<\\/td><td>(.*)<\\/td><td align=\"RIGHT\">(.*)<\\/td><td align=\"RIGHT\">(.*)<\\/td>"); Pattern totalPattern = Pattern.compile("<td>Quota permis pour la p&eacute;riode \\(Mo\\)<\\/td>.*<td align=\"RIGHT\">(.*)<\\/td>"); Matcher m = null; ArrayList<ConsommationDate> consommationDates = new ArrayList<ConsommationDate>(); for (Element element : tables.get(0).children()) { for (Element element1 : element.children()) { String cleanedString = element1.html().replace("\n", ""); m = detailsPattern.matcher(cleanedString); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); if (m.matches()) { consommationDates.add(new ConsommationDate( m.group(1), m.group(2).equals("Journée en cours") ? formatter.format(today) : m.group(2), Float.parseFloat(m.group(3)), Float.parseFloat(m.group(4)))); } } } ConsommationGlobal global = new ConsommationGlobal(); m = totalPattern.matcher( tables.get(1).select("tbody > tr") .first() .html() .replace("\n", "")); if (m.find()) { global = new ConsommationGlobal( Float.parseFloat(m.group(1)), consommationDates ); } return global; } }
package com.kaltura.playersdk.helpers; import android.app.Activity; import android.util.Log; import android.view.ViewGroup; import android.widget.FrameLayout; import com.google.ads.interactivemedia.v3.api.Ad; import com.google.ads.interactivemedia.v3.api.AdDisplayContainer; import com.google.ads.interactivemedia.v3.api.AdErrorEvent; import com.google.ads.interactivemedia.v3.api.AdEvent; import com.google.ads.interactivemedia.v3.api.AdsLoader; import com.google.ads.interactivemedia.v3.api.AdsManager; import com.google.ads.interactivemedia.v3.api.AdsManagerLoadedEvent; import com.google.ads.interactivemedia.v3.api.AdsRenderingSettings; import com.google.ads.interactivemedia.v3.api.AdsRequest; import com.google.ads.interactivemedia.v3.api.ImaSdkFactory; import com.google.ads.interactivemedia.v3.api.UiElement; import com.google.ads.interactivemedia.v3.api.player.ContentProgressProvider; import com.kaltura.playersdk.players.KIMAAdPlayer; import com.kaltura.playersdk.players.KPlayerCallback; import com.kaltura.playersdk.players.KPlayerController; import com.kaltura.playersdk.players.KPlayerListener; import org.json.JSONException; import org.json.JSONObject; import java.util.Collections; public class KIMAManager implements AdErrorEvent.AdErrorListener, AdsLoader.AdsLoadedListener, AdEvent.AdEventListener, KIMAAdPlayer.KIMAAdPlayerEvents { // Container with references to video player and ad UI ViewGroup. private AdDisplayContainer mAdDisplayContainer; // The AdsLoader instance exposes the requestAds method. private AdsLoader mAdsLoader; // AdsManager exposes methods to control ad playback and listen to ad events. private AdsManager mAdsManager; // Factory class for creating SDK objects. private ImaSdkFactory mSdkFactory; // Ad-enabled video player. private KIMAAdPlayer mIMAPlayer; // Default VAST ad tag; more complex apps might select ad tag based on content video criteria. private String mDefaultAdTagUrl; private KPlayerListener mPlayerListener; private KPlayerCallback mPLayerCallback; private boolean mContentCompleted; private JSONObject jsonValue = new JSONObject(); private String DurationKey = "duration"; private String TimeKey = "time"; private String RemainKey = "remain"; private String IsLinearKey = "isLinear"; private String AdIDKey = "adID"; private String AdSystemKey = "adSystem"; private String AdPositionKey = "adPosition"; private String ContextKey = "context"; private String AdRemainingTimeChangeKey = "adRemainingTimeChange"; private String AdLoadedEventKey = "adLoadedEvent"; private String AdLoadedKey = "adLoaded"; private String AdStartKey = "adStart"; private String AdCompletedKey = "adCompleted"; static public String AllAdsCompletedKey = "allAdsCompleted"; static public String ContentPauseRequestedKey = "contentPauseRequested"; static public String ContentResumeRequestedKey = "contentResumeRequested"; private String FirstQuartileKey = "firstQuartile"; private String MidPointKey = "midpoint"; private String ThirdQuartileKey = "thirdQuartile"; private String AdClickedKey = "adClicked"; private String AdsLoadErrorKey = "adsLoadError"; private String AdSkippeddKey = "adSkipped"; public KIMAManager(Activity context, FrameLayout adPlayerContainer, ViewGroup adUiContainer, String adTagURL) { mIMAPlayer = new KIMAAdPlayer(context, adPlayerContainer, adUiContainer); mIMAPlayer.setKIMAAdEventListener(this); mDefaultAdTagUrl = adTagURL; mContentCompleted = false; // Create an AdsLoader. mSdkFactory = ImaSdkFactory.getInstance(); mAdsLoader = mSdkFactory.createAdsLoader(context); mAdsLoader.addAdErrorListener(this); mAdsLoader.addAdsLoadedListener(this); } /** * Request video ads using the default VAST ad tag. Typically, you would change your ad tag * URL based on the current content being played. */ public void requestAds(ContentProgressProvider contentProgressProvider) { requestAds(mDefaultAdTagUrl, contentProgressProvider); } public void setPlayerListener(KPlayerListener listener) { mPlayerListener = listener; } public void setPlayerCallback(KPlayerCallback callback) { mPLayerCallback = callback; } public void pause() { mAdsManager.pause(); } public void resume() { mAdsManager.resume(); } /** * Request video ads from the given VAST ad tag. * @param adTagUrl URL of the ad's VAST XML */ private void requestAds(String adTagUrl, ContentProgressProvider contentProgressProvider) { mAdDisplayContainer = mSdkFactory.createAdDisplayContainer(); mAdDisplayContainer.setPlayer(mIMAPlayer); mAdDisplayContainer.setAdContainer(mIMAPlayer.getAdUIContainer()); // Create the ads request. AdsRequest request = mSdkFactory.createAdsRequest(); request.setAdTagUrl(adTagUrl); request.setAdDisplayContainer(mAdDisplayContainer); request.setContentProgressProvider(contentProgressProvider); // Request the ad. After the ad is loaded, onAdsManagerLoaded() will be called. mAdsLoader.requestAds(request); } /** * An event raised when ads are successfully loaded from the ad server via an AdsLoader. */ @Override public void onAdsManagerLoaded(AdsManagerLoadedEvent adsManagerLoadedEvent) { // Ads were successfully loaded, so get the AdsManager instance. AdsManager has // events for ad playback and errors. mAdsManager = adsManagerLoadedEvent.getAdsManager(); // Attach event and error event listeners. mAdsManager.addAdErrorListener(this); mAdsManager.addAdEventListener(this); AdsRenderingSettings renderingSettings = ImaSdkFactory.getInstance().createAdsRenderingSettings(); renderingSettings.setUiElements(Collections.<UiElement>emptySet()); mAdsManager.init(renderingSettings); } /** * Responds to AdEvents. */ @Override public void onAdEvent(AdEvent adEvent) { Log.i("ImaExample", "Event: " + adEvent.getType()); // These are the suggested event types to handle. For full list of all ad event types, // see the documentation for AdEvent.AdEventType. Ad ad = adEvent.getAd(); try { switch (adEvent.getType()) { case LOADED: // AdEventType.LOADED will be fired when ads are ready to be played. // AdsManager.start() begins ad playback. This method is ignored for VMAP or ad // rules playlists, as the SDK will automatically start executing the playlist. fireIMAEvent(ContentPauseRequestedKey); mAdsManager.start(); jsonValue.put(IsLinearKey, ad.isLinear()); jsonValue.put(AdIDKey, ad.getAdId()); jsonValue.put(AdSystemKey, "null"); jsonValue.put(AdPositionKey, ad.getAdPodInfo().getAdPosition()); fireIMAEvent(AdLoadedKey); break; case STARTED: jsonValue.put(DurationKey, ad.getDuration()); fireIMAEvent(AdStartKey); break; case COMPLETED: jsonValue.put(AdIDKey, ad.getAdId()); fireIMAEvent(AdCompletedKey); break; case FIRST_QUARTILE: fireIMAEvent(FirstQuartileKey); break; case MIDPOINT: fireIMAEvent(MidPointKey); break; case THIRD_QUARTILE: fireIMAEvent(ThirdQuartileKey); break; case CLICKED: jsonValue.put(IsLinearKey, ad.isLinear()); fireIMAEvent(AdClickedKey); break; case CONTENT_PAUSE_REQUESTED: mPLayerCallback.playerStateChanged(KPlayerController.SHOULD_PAUSE); break; case CONTENT_RESUME_REQUESTED: fireIMAEvent(ContentResumeRequestedKey); if (!mContentCompleted) { mPLayerCallback.playerStateChanged(KPlayerController.SHOULD_PLAY); } // mIMAPlayer.removeAd(); break; case ALL_ADS_COMPLETED: fireIMAEvent(AllAdsCompletedKey); if (mContentCompleted) { mPlayerListener.contentCompleted(null); } if (mAdsManager != null) { mAdsManager.destroy(); mAdsManager = null; mIMAPlayer.release(); mIMAPlayer = null; mPlayerListener = null; mPLayerCallback = null; } break; case SKIPPED: jsonValue.put(IsLinearKey, ad.isLinear()); fireIMAEvent(AdSkippeddKey); mIMAPlayer.removeAd(); break; default: break; } } catch (JSONException e) { e.printStackTrace(); } } /** * An event raised when there is an error loading or playing ads. */ @Override public void onAdError(AdErrorEvent adErrorEvent) { Log.e("ImaExample", "Ad Error: " + adErrorEvent.getError().getMessage()); // imaAdapter.resumeContentAfterAdPlayback(); } /** * Event raised by VideoPlayerWithAdPlayback when the content video is complete. */ public void contentComplete() { mContentCompleted = true; mAdsLoader.contentComplete(); } @Override public void adDidProgress(float toTime, float totalTime) { try { jsonValue.put(TimeKey, toTime); jsonValue.put(DurationKey, totalTime); jsonValue.put(RemainKey, (totalTime - toTime)); fireIMAEvent(AdRemainingTimeChangeKey); } catch (JSONException e) { e.printStackTrace(); } } private void fireIMAEvent(String eventName) { if (mPlayerListener != null && jsonValue.length() == 0) { mPlayerListener.eventWithJSON(null, eventName, "(null)"); return; } if (mPlayerListener != null) { mPlayerListener.eventWithJSON(null, eventName, jsonValue.toString()); } jsonValue = new JSONObject(); } public void destroy() { if (mIMAPlayer != null) { mIMAPlayer.release(); mIMAPlayer = null; // pause(); mAdsManager.removeAdEventListener(this); mAdsManager.destroy(); // mAdsLoader.removeAdErrorListener(this); // mAdsLoader.removeAdsLoadedListener(this); mPlayerListener = null; mPLayerCallback = null; } } }
package astava.samples; import astava.core.Atom; import astava.core.Node; import astava.core.Tuple; import astava.java.ArithmeticOperator; import astava.java.Descriptor; import astava.java.LogicalOperator; import astava.java.RelationalOperator; import astava.java.gen.ClassGenerator; import astava.java.gen.CodeAnalyzer; import astava.macro.*; import parse.*; import sun.dc.pr.PRError; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Modifier; import java.util.*; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; import static astava.java.Factory.*; public class Main { public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { // Node classDeclaration = classDeclaration(Modifier.PUBLIC, "MyClass", "java/lang/Object", Arrays.asList( // methodDeclaration(Modifier.PUBLIC | Modifier.STATIC, "myMethod", Collections.emptyList(), "I", // ret(literal(7)) /* Node classDeclaration = classDeclaration(Modifier.PUBLIC, "MyClass", "java/lang/Object", Arrays.asList( methodDeclaration(Modifier.PUBLIC | Modifier.STATIC, "myMethod", Collections.emptyList(), "java/lang/String", ret(literal("myString")) ) )); */ /* Node classDeclaration = classDeclaration(Modifier.PUBLIC, "MyClass", "java/lang/Object", Arrays.asList( methodDeclaration(Modifier.PUBLIC | Modifier.STATIC, "myMethod", Collections.emptyList(), "B", ret(add(literal(7), literal(11))) ) )); */ //Processor labelScopeProcessor = createLabelScopeProcessor(); Node in = new Tuple(Arrays.asList( new Tuple(new Atom("scopedLabel"), new Atom("outer")), new Tuple( new Atom("labelScope"), new Tuple( new Tuple(new Atom("scopedLabel"), new Atom("start")), new Tuple( new Atom("labelScope"), new Tuple( new Tuple(new Atom("op"), new Tuple( new Tuple(new Atom("scopedLabel"), new Atom("start")), new Tuple(new Atom("scopedGoTo"), new Atom("start")) )), new Tuple(new Atom("scopedLabel"), new Atom("start")), new Tuple(new Atom("scopedGoTo"), new Atom("start")) ) ), new Tuple(new Atom("scopedGoTo"), new Atom("start")) ) ) )); /* Node in = new Tuple( new Tuple(new Atom("op"), new Tuple( new Tuple(new Atom("scopedLabel"), new Atom("start")), new Tuple(new Atom("scopedGoTo"), new Atom("start")) )), new Tuple(new Atom("scopedLabel"), new Atom("start")), new Tuple(new Atom("scopedGoTo"), new Atom("start")) ); */ /* Node n = labelScopeProcessor.process(in); System.out.println(in); System.out.println("=>"); System.out.println(n); */ /*Node classDeclaration = classDeclaration(Modifier.PUBLIC, "MyClass", "java/lang/Object", Arrays.asList( methodDeclaration(Modifier.PUBLIC | Modifier.STATIC, "myMethod", Collections.emptyList(), "D", ret(mul(literal(7.0), literal(11.0))) ) )); ClassGenerator generator = new ClassGenerator(classDeclaration); Class<?> c = generator.newClass(); Method m = c.getMethod("myMethod"); Object result = m.invoke(null, null); System.out.println(result);*/ Hashtable<String, Parser> rules = new Hashtable<>(); Parser tupleParser = matcher -> { if(matcher.peekByte() == '(') { matcher.consume(); matcher.ignoreWS(); ArrayList<Node> elements = new ArrayList<>(); Matcher elementsMatcher = matcher.beginMatch(new BufferCollector(elements)); rules.get("elements").parse(elementsMatcher); if(elementsMatcher.matched()) { if(matcher.peekByte() == ')') { matcher.consume(); matcher.put(new Tuple(elements)); matcher.match(); } } } }; Parser atomParser = matcher -> { if(Character.isLetter(matcher.peekByte()) || isSpecialSymbolChar((char)matcher.peekByte())) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append((char)matcher.peekByte()); matcher.consume(); while(Character.isLetter(matcher.peekByte()) || isSpecialSymbolChar((char)matcher.peekByte())) { stringBuilder.append((char)matcher.peekByte()); matcher.consume(); } String str = stringBuilder.toString(); switch (str) { case "true": matcher.put(new Atom(true)); break; case "false": matcher.put(new Atom(false)); break; default: matcher.put(new Atom(new Symbol(stringBuilder.toString()))); } matcher.match(); } else if(Character.isDigit(matcher.peekByte())) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append((char)matcher.peekByte()); matcher.consume(); while(Character.isDigit(matcher.peekByte())) { stringBuilder.append((char)matcher.peekByte()); matcher.consume(); } if(Character.toUpperCase(matcher.peekByte()) == 'L') { // long matcher.consume(); matcher.put(new Atom(Long.parseLong(stringBuilder.toString()))); } else { // int matcher.put(new Atom(Integer.parseInt(stringBuilder.toString()))); } matcher.match(); } else if(matcher.peekByte() == '\"') { StringBuilder stringBuilder = new StringBuilder(); matcher.consume(); while(matcher.peekByte() != '\"') { stringBuilder.append((char)matcher.peekByte()); matcher.consume(); } if(matcher.peekByte() == '\"') { matcher.consume(); matcher.put(new Atom(stringBuilder.toString())); matcher.match(); } } }; rules.put("element", tupleParser.or(atomParser)); rules.put("elements", matcher -> { matcher.ignoreWS(); Matcher elementMatcher = matcher.beginMatch(); rules.get("element").parse(elementMatcher); while(elementMatcher.matched()) { matcher.ignoreWS(); elementMatcher = matcher.beginMatch(); rules.get("element").parse(elementMatcher); } matcher.ignoreWS(); matcher.match(); }); Parser parser = rules.get("elements").then(m -> { if (m.peekByte() == -1) m.match(); }); String input = "(|| (> 1 2) true)"; // Why does this fail? //String input = "(+ 8 (* 7 9))"; //String input = "((scopedLabel x) (labelScope (scopedLabel x)) (labelScope (scopedLabel x)))"; //String input = "((scopedLabel x) (scopedLabel x))"; List<Node> elements = new ArrayList<>(); CommonMatcher matcher = new CommonMatcher(new CharSequenceByteSource(input), 0, null, new BufferCollector(elements)); parser.parse(matcher); System.out.println(input); System.out.println("=>"); if(matcher.matched()) { System.out.println(elements); Processor processor = createLabelScopeProcessor() .then(createLiteralExpander()) .then(createOperatorToBuiltinProcessor()); elements = elements.stream().map(n -> processor.process(n) ).collect(Collectors.toList()); System.out.println("=>"); System.out.println(elements); Tuple expression = (Tuple)elements.get(0); CodeAnalyzer analyzer = new CodeAnalyzer(expression); String resultType = analyzer.resultType(); ClassGenerator generator = new ClassGenerator(classDeclaration(Modifier.PUBLIC, "MyClass", Descriptor.get(Object.class), Arrays.asList( methodDeclaration(Modifier.PUBLIC | Modifier.STATIC, "myMethod", Collections.emptyList(), resultType, ret(expression)) ))); Class<?> c = generator.newClass(); Object result = c.getMethod("myMethod").invoke(null, null); System.out.println("=> " + resultType); System.out.println(result); } else { System.out.print("Could not parse."); } } private static boolean isSpecialSymbolChar(char ch) { switch (ch) { case '+': case '-': case '/': case '*': case '%': case '&': case '|': case '<': case '>': case '=': return true; } return false; } private static Processor createFallbackProcessor(Processor elementProcessor) { return new OperandsProcessor(n -> elementProcessor.process(n)) .or(new TupleProcessor(n -> elementProcessor.process(n))) .or(n -> n); } public static Processor createLiteralExpander() { return new SelfProcessor(self -> new MapProcessor() .put(new Symbol("byte"), n -> n) .put(new Symbol("short"), n -> n) .put(new Symbol("int"), n -> n) .put(new Symbol("long"), n -> n) .or(n -> n instanceof Atom && ((Atom) n).getValue() instanceof Integer ? new Tuple(new Atom(new Symbol("int")), n) : null ) .or(n -> n instanceof Atom && ((Atom) n).getValue() instanceof Long ? new Tuple(new Atom(new Symbol("long")), n) : null ) .or(createFallbackProcessor(self)) ); } public static Processor createLabelScopeProcessor() { return new DelegateProcessor() { int scopeCount; @Override protected Processor createProcessor() { int id = scopeCount++; return new SelfProcessor(self -> { Processor nameProcessor = new AtomProcessor<Symbol, Symbol>(name -> new Symbol(id + name.str)); MapProcessor mapProcessor = new MapProcessor(); return mapProcessor .put(new Symbol("scopedLabel"), forOperands(new IndexProcessor() .set(0, new AtomProcessor<Symbol, Symbol>(operator -> new Symbol("label"))) .set(1, nameProcessor))) .put(new Symbol("scopedGoTo"), forOperands(new IndexProcessor() .set(0, new AtomProcessor<Symbol, Symbol>(operator -> new Symbol("goTo"))) .set(1, nameProcessor))) // Process the first operand of the labelScope form .put(new Symbol("labelScope"), code -> createProcessor().process(((Tuple) code).get(1))) .or(createFallbackProcessor(n -> self.process(n))); }); } }; } public static Processor createOperatorToBuiltinProcessor() { return new DelegateProcessor() { private Processor createLiteralProcessor(Function<Number, Node> literalFunction) { return n -> { Number number = (Number) ((Atom) ((Tuple) n).get(1)).getValue(); return literalFunction.apply(number); }; } private Processor arithmeticProcessor(int arithmeticOperator) { return forOperands(n -> arithmetic((Tuple) ((Tuple) n).get(1), (Tuple) ((Tuple) n).get(2), arithmeticOperator)); } private Processor logicalProcessor(int logicalOperator) { return forOperands(n -> logical((Tuple) ((Tuple) n).get(1), (Tuple) ((Tuple) n).get(2), logicalOperator)); } private Processor compareProcessor(int compareOperator) { return forOperands(n -> compare((Tuple) ((Tuple) n).get(1), (Tuple) ((Tuple) n).get(2), compareOperator)); } @Override protected Processor createProcessor() { MapProcessor mp = new MapProcessor() .put(new Symbol("+"), arithmeticProcessor(ArithmeticOperator.ADD)) .put(new Symbol("-"), arithmeticProcessor(ArithmeticOperator.SUB)) .put(new Symbol("*"), arithmeticProcessor(ArithmeticOperator.MUL)) .put(new Symbol("/"), arithmeticProcessor(ArithmeticOperator.DIV)) .put(new Symbol("%"), arithmeticProcessor(ArithmeticOperator.REM)) .put(new Symbol("&&"), logicalProcessor(LogicalOperator.AND)) .put(new Symbol("||"), logicalProcessor(LogicalOperator.OR)) .put(new Symbol("<"), compareProcessor(RelationalOperator.LT)) .put(new Symbol("<="), compareProcessor(RelationalOperator.LE)) .put(new Symbol(">"), compareProcessor(RelationalOperator.GT)) .put(new Symbol(">="), compareProcessor(RelationalOperator.GE)) .put(new Symbol("=="), compareProcessor(RelationalOperator.EQ)) .put(new Symbol("!="), compareProcessor(RelationalOperator.NE)) .put(new Symbol("byte"), createLiteralProcessor(number -> literal(number.byteValue()))) .put(new Symbol("short"), createLiteralProcessor(number -> literal(number.shortValue()))) .put(new Symbol("int"), createLiteralProcessor(number -> literal(number.intValue()))) .put(new Symbol("long"), createLiteralProcessor(number -> literal(number.longValue()))); Processor stringLiteralProcessor = n -> n instanceof Atom && ((Atom)n).getValue() instanceof String ? literal((String)((Atom)n).getValue()) : null; Processor booleanLiteralProcessor = n -> n instanceof Atom && ((Atom)n).getValue() instanceof Boolean ? literal((boolean)((Atom)n).getValue()) : null; return mp.or(stringLiteralProcessor).or(booleanLiteralProcessor).or(createFallbackProcessor(n -> this.process(n))); } }; } }
package org.adonai.ui.editor; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.fxml.FXML; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; import javafx.scene.control.ComboBox; import org.adonai.Key; import org.adonai.model.Song; import org.adonai.services.SongTransposeService; import java.util.Optional; public class SongDetailsController { private PartEditor partEditor; @FXML private ComboBox<Key> cboCurrentKey; @FXML private ComboBox<Key> cboOriginalKey; public void setPartEditor(PartEditor partEditor) { this.partEditor = partEditor; cboCurrentKey.setItems(FXCollections.observableArrayList(Key.values())); cboOriginalKey.setItems(FXCollections.observableArrayList(Key.values())); Song currentSong = partEditor.getSongEditor().getSong(); if (currentSong.getCurrentKey() != null) { cboCurrentKey.getSelectionModel().select(Key.fromString(currentSong.getCurrentKey())); } else cboCurrentKey.getSelectionModel().clearSelection(); if (currentSong.getOriginalKey() != null) { cboOriginalKey.getSelectionModel().select(Key.fromString(currentSong.getOriginalKey())); } else cboOriginalKey.getSelectionModel().clearSelection(); cboOriginalKey.valueProperty().addListener(new ChangeListener<Key>() { @Override public void changed(ObservableValue<? extends Key> observable, Key oldValue, Key newValue) { currentSong.setOriginalKey(newValue.name()); } }); cboOriginalKey.valueProperty().addListener(new ChangeListener<Key>() { @Override public void changed(ObservableValue<? extends Key> observable, Key oldValue, Key newValue) { currentSong.setOriginalKey(newValue.name()); } }); cboCurrentKey.valueProperty().addListener(new ChangeListener<Key>() { @Override public void changed(ObservableValue<? extends Key> observable, Key oldValue, Key newValue) { if (currentSong.getCurrentKey() != null) { Key previousKey = Key.fromString(currentSong.getCurrentKey()); Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setHeaderText("You have changed the key of the song. Do you want to transpose all chords from " + currentSong.getCurrentKey() + " to " + newValue.name() + "?"); Optional<ButtonType> result = alert.showAndWait(); if (result.get() == ButtonType.OK){ SongTransposeService songTransposeService = new SongTransposeService(); songTransposeService.transpose(currentSong, previousKey, newValue); } } currentSong.setCurrentKey(newValue.name()); } }); } }
package fr.free.nrw.commons.category; import android.os.AsyncTask; import android.text.TextUtils; import android.view.View; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; import java.util.Iterator; import java.util.List; import fr.free.nrw.commons.CommonsApplication; import fr.free.nrw.commons.mwapi.MediaWikiApi; import timber.log.Timber; /** * Sends asynchronous queries to the Commons MediaWiki API to retrieve categories that share the * same prefix as the keyword typed in by the user. The 'acprefix' action-specific parameter is used * for this purpose. This class should be subclassed in CategorizationFragment.java to aggregate * the results. */ public class PrefixUpdater extends AsyncTask<Void, Void, List<String>> { private String filter; private CategorizationFragment catFragment; public PrefixUpdater(CategorizationFragment catFragment) { this.catFragment = catFragment; } @Override protected void onPreExecute() { super.onPreExecute(); filter = catFragment.categoriesFilter.getText().toString(); catFragment.categoriesSearchInProgress.setVisibility(View.VISIBLE); catFragment.categoriesNotFoundView.setVisibility(View.GONE); catFragment.categoriesSkip.setVisibility(View.GONE); } private List<String> filterIrrelevantResults(List<String> items) { Iterator<String> iterator; //Check for current and previous year to exclude these categories from removal Calendar now = Calendar.getInstance(); int year = now.get(Calendar.YEAR); String yearInString = String.valueOf(year); Timber.d("Year: %s", yearInString); int prevYear = year - 1; String prevYearInString = String.valueOf(prevYear); Timber.d("Previous year: %s", prevYearInString); //Copy to Iterator to prevent ConcurrentModificationException when removing item for(iterator = items.iterator(); iterator.hasNext();) { String s = iterator.next(); //Check if s contains a 4-digit word anywhere within the string (.* is wildcard) //And that s does not equal the current year or previous year //And if it is an irrelevant category such as Media_needing_categories_as_of_16_June_2017(Issue #750) if(s.matches(".*(19|20)\\d{2}.*") && !s.contains(yearInString) && !s.contains(prevYearInString) ||s.matches("(.*)needing(.*)")||s.matches("(.*)taken on(.*)")) { Timber.d("Filtering out irrelevant result: %s", s); iterator.remove(); } } Timber.d("Items: %s", items); return items; } @Override protected List<String> doInBackground(Void... voids) { //If user hasn't typed anything in yet, get GPS and recent items if (TextUtils.isEmpty(filter)) { ArrayList<String> mergedItems = new ArrayList<>(catFragment.mergeItems()); Timber.d("Merged items, waiting for filter"); return new ArrayList<>(filterIrrelevantResults(mergedItems)); } //if user types in something that is in cache, return cached category if (catFragment.categoriesCache.containsKey(filter)) { ArrayList<String> cachedItems = new ArrayList<>(catFragment.categoriesCache.get(filter)); Timber.d("Found cache items, waiting for filter"); return new ArrayList<>(filterIrrelevantResults(cachedItems)); } //otherwise if user has typed something in that isn't in cache, search API for matching categories MediaWikiApi api = CommonsApplication.getInstance().getMWApi(); List<String> categories = new ArrayList<>(); try { categories = api.allCategories(CategorizationFragment.SEARCH_CATS_LIMIT, this.filter); Timber.d("Prefix URL filter %s", categories); } catch (IOException e) { Timber.e(e, "IO Exception: "); //Return empty arraylist return categories; } Timber.d("Found categories from Prefix search, waiting for filter"); return new ArrayList<>(filterIrrelevantResults(categories)); } }
package com.amazon.jenkins.ec2fleet; import com.amazon.jenkins.ec2fleet.cloud.FleetNode; import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.AmazonEC2Client; import com.amazonaws.services.ec2.model.DescribeInstancesRequest; import com.amazonaws.services.ec2.model.DescribeInstancesResult; import com.amazonaws.services.ec2.model.DescribeRegionsResult; import com.amazonaws.services.ec2.model.DescribeSpotFleetInstancesRequest; import com.amazonaws.services.ec2.model.DescribeSpotFleetRequestsRequest; import com.amazonaws.services.ec2.model.DescribeSpotFleetRequestsResult; import com.amazonaws.services.ec2.model.Instance; import com.amazonaws.services.ec2.model.ModifySpotFleetRequestRequest; import com.amazonaws.services.ec2.model.Region; import com.amazonaws.services.ec2.model.SpotFleetRequestConfig; import com.amazonaws.services.ec2.model.TerminateInstancesRequest; import com.amazonaws.services.ec2.model.TerminateInstancesResult; import com.cloudbees.jenkins.plugins.awscredentials.AWSCredentialsHelper; import com.cloudbees.jenkins.plugins.awscredentials.AmazonWebServicesCredentials; import com.cloudbees.plugins.credentials.CredentialsMatchers; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.common.StandardListBoxModel; import com.google.common.util.concurrent.SettableFuture; import hudson.Extension; import hudson.model.Computer; import hudson.model.Descriptor; import hudson.model.Label; import hudson.model.Node; import hudson.model.TaskListener; import hudson.security.ACL; import hudson.slaves.Cloud; import hudson.slaves.ComputerConnector; import hudson.slaves.NodeProperty; import hudson.slaves.NodeProvisioner; import hudson.util.FormValidation; import hudson.util.ListBoxModel; import jenkins.model.Jenkins; import net.sf.json.JSONObject; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.StaplerRequest; import org.springframework.util.ObjectUtils; import javax.annotation.Nonnull; import javax.servlet.ServletException; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.UUID; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; import java.util.logging.SimpleFormatter; @SuppressWarnings("unused") public class EC2FleetCloud extends Cloud { public static final String FLEET_CLOUD_ID="FleetCloud"; private static final SimpleFormatter sf = new SimpleFormatter(); private final String credentialsId; private final String region; private final String fleet; private final String fsRoot; private final ComputerConnector computerConnector; private final boolean privateIpUsed; private final String labelString; private final Integer idleMinutes; private final Integer minSize; private final Integer maxSize; private final Integer numExecutors; private @Nonnull FleetStateStats status; private final Set<NodeProvisioner.PlannedNode> plannedNodes = new HashSet<NodeProvisioner.PlannedNode>(); // instancesSeen are all nodes known to both Jenkins and the fleet private final Set<String> instancesSeen = new HashSet<String>(); // instancesDying are terminated nodes known to both Jenkins and the fleet, // that are waiting for termination private final Set<String> instancesDying = new HashSet<String>(); private Set<String> instancesBooting; private static final Logger LOGGER = Logger.getLogger(EC2FleetCloud.class.getName()); public static String join(final String separator, final Iterable<String> elements) { StringBuilder sb = new StringBuilder(); boolean isFirst = true; for (String i: elements) { if (!isFirst) sb.append(separator); else isFirst = false; sb.append(i); } return sb.toString(); } @DataBoundConstructor public EC2FleetCloud(final String credentialsId, final String region, final String fleet, final String labelString, final String fsRoot, final ComputerConnector computerConnector, final boolean privateIpUsed, final Integer idleMinutes, final Integer minSize, final Integer maxSize, final Integer numExecutors) { super(FLEET_CLOUD_ID); this.credentialsId = credentialsId; this.region = region; this.fleet = fleet; this.fsRoot = fsRoot; this.computerConnector = computerConnector; this.labelString = labelString; this.idleMinutes = idleMinutes; this.privateIpUsed = privateIpUsed; this.minSize = minSize; this.maxSize = maxSize; this.numExecutors = numExecutors; this.instancesBooting = new HashSet<String>(); this.status = new FleetStateStats(fleet, 0, "Initializing", Collections.<String>emptySet(), labelString); } public String getCredentialsId() { return credentialsId; } public String getRegion() { return region; } public String getFleet() { return fleet; } public String getFsRoot() { return fsRoot; } public ComputerConnector getComputerConnector() { return computerConnector; } public boolean isPrivateIpUsed() { return privateIpUsed; } public String getLabelString(){ return this.labelString; } public Integer getIdleMinutes() { return idleMinutes; } public Integer getMaxSize() { return maxSize; } public Integer getMinSize() { return minSize; } public Integer getNumExecutors() { return numExecutors; } public String getJvmSettings() { return ""; } public @Nonnull FleetStateStats getStatus() { return status; } public static void log(final Logger logger, final Level level, final TaskListener listener, final String message) { log(logger, level, listener, message, null); } public static void log(final Logger logger, final Level level, final TaskListener listener, String message, final Throwable exception) { logger.log(level, message, exception); if (listener != null) { if (exception != null) message += " Exception: " + exception; final LogRecord lr = new LogRecord(level, message); final PrintStream printStream = listener.getLogger(); printStream.print(sf.format(lr)); } } @Override public synchronized Collection<NodeProvisioner.PlannedNode> provision( final Label label, final int excessWorkload) { final FleetStateStats stats=updateStatus(); final int maxAllowed = this.getMaxSize(); if (stats.getNumDesired() >= maxAllowed || !"active".equals(stats.getState())) return Collections.emptyList(); // Count the number of nodes still booting int numNodesBooting = 0; Jenkins jenkins = Jenkins.getInstance(); synchronized (jenkins) { for (final Node node : jenkins.getNodes()) { if (this.labelString.equals(node.getLabelString())) if (instancesBooting.contains(node.getNodeName())) numNodesBooting += 1; } } // if the planned node has 0 executors configured force it to 1 so we end up doing an unweighted check final int numExecutors = this.numExecutors == 0 ? 1 : this.numExecutors; // Recalculate the excess taking the number of booting nodes into account int effectiveExcessWorkload = excessWorkload - (numNodesBooting * numExecutors); // Calculate the ceiling, without having to work with doubles from Math.ceil final int weightedExcessWorkload = (effectiveExcessWorkload + numExecutors - 1) / numExecutors; int targetCapacity = stats.getNumDesired() + weightedExcessWorkload; if (targetCapacity > maxAllowed) targetCapacity = maxAllowed; int toProvision = targetCapacity - stats.getNumDesired(); if (toProvision < 1) return Collections.emptyList(); LOGGER.log(Level.INFO, "Provisioning nodes. Excess workload: " + Integer.toString(weightedExcessWorkload) + ", Provisioning: " + Integer.toString(toProvision)); final ModifySpotFleetRequestRequest request=new ModifySpotFleetRequestRequest(); request.setSpotFleetRequestId(fleet); request.setTargetCapacity(targetCapacity); final AmazonEC2 ec2=connect(credentialsId, region); ec2.modifySpotFleetRequest(request); final List<NodeProvisioner.PlannedNode> resultList = new ArrayList<NodeProvisioner.PlannedNode>(); for(int f=0;f<toProvision; ++f) { final SettableFuture<Node> futureNode=SettableFuture.create(); final NodeProvisioner.PlannedNode plannedNode= new NodeProvisioner.PlannedNode("FleetNode-"+f, futureNode, this.numExecutors); resultList.add(plannedNode); this.plannedNodes.add(plannedNode); } return resultList; } private synchronized void removeNode(String instanceId) { final Jenkins jenkins=Jenkins.getInstance(); //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (jenkins) { // If this node is dying, remove it from Jenkins final Node n = jenkins.getNode(instanceId); if (n != null) { try { jenkins.removeNode(n); } catch(final Exception ex) { LOGGER.log(Level.WARNING, "Error removing node " + instanceId); throw new IllegalStateException(ex); } } } } public synchronized FleetStateStats updateStatus() { final AmazonEC2 ec2=connect(credentialsId, region); final FleetStateStats curStatus=FleetStateStats.readClusterState(ec2, getFleet(), this.labelString); status = curStatus; LOGGER.log(Level.FINE, "Fleet Update Status called"); LOGGER.log(Level.FINE, "# of nodes:" + Jenkins.getInstance().getNodes().size()); // Initialize instancesBooting if initialization in constructor failed if (instancesBooting == null) instancesBooting = new HashSet<String>(); // Check the nodes to see if we have some new ones final Set<String> newInstances = new HashSet<String>(curStatus.getInstances()); instancesSeen.clear(); LOGGER.log(Level.FINE, "Fleet (" + getLabelString() + ") contains instances [" + join(", ", newInstances) + "]"); LOGGER.log(Level.FINE, "Jenkins contains dying instances [" + join(", ", instancesDying) + "]"); for(final Node node : Jenkins.getInstance().getNodes()) { if (newInstances.contains(node.getNodeName())) { // instancesSeen should only have the intersection of nodes // known by Jenkins and by the fleet. instancesSeen.add(node.getNodeName()); } else if (instancesDying.contains(node.getNodeName())) { LOGGER.log(Level.INFO, "Fleet (" + getLabelString() + ") no longer has the instance " + node.getNodeName() + ", removing from Jenkins."); removeNode(node.getNodeName()); instancesDying.remove(node.getNodeName()); instancesSeen.remove(node.getNodeName()); } Computer computer = node.toComputer(); if (computer != null) if (instancesBooting.contains(node.getNodeName()) && computer.isOnline()) instancesBooting.remove(node.getNodeName()); } // We should only keep dying instances that are still visible to both // Jenkins and the fleet. instancesDying.retainAll(instancesSeen); // New instances are only ones that Jenkins hasn't seen newInstances.removeAll(instancesSeen); // Update the label for all seen instances, unless they're dying for(final String instId : instancesSeen) { if (instancesDying.contains(instId)) continue; Node node = Jenkins.getInstance().getNode(instId); if (node == null) continue; if (!this.labelString.equals(node.getLabelString())) { try { LOGGER.log(Level.INFO, "Updating label on node " + instId + " to \"" + this.labelString + "\"."); node.setLabelString(this.labelString); } catch (final Exception ex) { LOGGER.log(Level.WARNING, "Unable to set label on node " + instId); } } } // If we have new instances - create nodes for them! try { if (newInstances.size() > 0) { LOGGER.log(Level.INFO, "Found new instances from fleet (" + getLabelString() + "): [" + join(", ", newInstances) + "]"); } for(final String instanceId : newInstances) { addNewSlave(ec2, instanceId); } } catch(final Exception ex) { LOGGER.log(Level.WARNING, "Unable to add a new instance. Exception: " + ex.toString()); } return curStatus; } private void addNewSlave(final AmazonEC2 ec2, final String instanceId) throws Exception { // Generate a random FS root if one isn't specified String fsRoot = this.fsRoot; if (fsRoot == null || fsRoot.equals("")) { fsRoot = "/tmp/jenkins-"+UUID.randomUUID().toString().substring(0, 8); } final DescribeInstancesResult result=ec2.describeInstances( new DescribeInstancesRequest().withInstanceIds(instanceId)); if (result.getReservations().isEmpty()) //Can't find this instance, skip it return; final Instance instance=result.getReservations().get(0).getInstances().get(0); final String address = isPrivateIpUsed() ? instance.getPrivateIpAddress() : instance.getPublicIpAddress(); // Check if we have the address to use. Nodes don't get it immediately. if (address == null) return; // Wait some more... final FleetNode slave = new FleetNode(instanceId, "Fleet slave for" + instanceId, fsRoot, this.numExecutors.toString(), Node.Mode.NORMAL, this.labelString, new ArrayList<NodeProperty<?>>(), FLEET_CLOUD_ID, computerConnector.launch(address, TaskListener.NULL)); // Initialize our retention strategy if (getIdleMinutes() != null) slave.setRetentionStrategy(new IdleRetentionStrategy(getIdleMinutes(), this)); final Jenkins jenkins=Jenkins.getInstance(); //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (jenkins) { // Try to avoid duplicate nodes final Node n = jenkins.getNode(instanceId); if (n != null) jenkins.removeNode(n); jenkins.addNode(slave); } //A new node, wheee! instancesSeen.add(instanceId); if (!plannedNodes.isEmpty()) { //If we're waiting for a new node - mark it as ready final NodeProvisioner.PlannedNode curNode=plannedNodes.iterator().next(); plannedNodes.remove(curNode); ((SettableFuture<Node>)curNode.future).set(slave); instancesBooting.add(slave.getNodeName()) } } public synchronized boolean terminateInstance(final String instanceId) { LOGGER.log(Level.INFO, "Attempting to terminate instance: " + instanceId); final FleetStateStats stats=updateStatus(); if (!instancesSeen.contains(instanceId)) { LOGGER.log(Level.INFO, "Unknown instance terminated: " + instanceId); return false; } final AmazonEC2 ec2 = connect(credentialsId, region); if (!instancesDying.contains(instanceId)) { // We can't remove instances beyond minSize if (stats.getNumDesired() == this.getMinSize() || !"active".equals(stats.getState())) { LOGGER.log(Level.INFO, "Not terminating " + instanceId + " because we need a minimum of " + Integer.toString(this.getMinSize()) + " instances running."); return false; } // These operations aren't idempotent so only do them once final ModifySpotFleetRequestRequest request=new ModifySpotFleetRequestRequest(); request.setSpotFleetRequestId(fleet); request.setTargetCapacity(stats.getNumDesired() - 1); request.setExcessCapacityTerminationPolicy("NoTermination"); ec2.modifySpotFleetRequest(request); //And remove the instance instancesDying.add(instanceId); } // terminateInstances is idempotent so it can be called until it's successful final TerminateInstancesResult result = ec2.terminateInstances(new TerminateInstancesRequest(Collections.singletonList(instanceId))); LOGGER.log(Level.INFO, "Instance " + instanceId + " termination result: " + result.toString()); return true; } @Override public boolean canProvision(final Label label) { boolean result = fleet != null && (label == null || Label.parse(this.labelString).containsAll(label.listAtoms())); LOGGER.log(Level.FINE, "CanProvision called on fleet: \"" + this.labelString + "\" wanting: \"" + (label == null ? "(unspecified)" : label.getName()) + "\". Returning " + Boolean.toString(result) + "."); return result; } private static AmazonEC2 connect(final String credentialsId, final String region) { final AmazonWebServicesCredentials credentials = AWSCredentialsHelper.getCredentials(credentialsId, Jenkins.getInstance()); final AmazonEC2Client client = credentials != null ? new AmazonEC2Client(credentials) : new AmazonEC2Client(); if (region != null) client.setEndpoint("https://ec2." + region + ".amazonaws.com/"); return client; } @Extension @SuppressWarnings("unused") public static class DescriptorImpl extends Descriptor<Cloud> { public boolean useInstanceProfileForCredentials; public String accessId; public String secretKey; public String region; public String fleet; public String userName="root"; public boolean privateIpUsed; public String privateKey; public DescriptorImpl() { super(); load(); } @Override public String getDisplayName() { return "Amazon SpotFleet"; } public List getComputerConnectorDescriptors() { return Jenkins.getInstance().getDescriptorList(ComputerConnector.class); } public ListBoxModel doFillCredentialsIdItems() { return AWSCredentialsHelper.doFillCredentialsIdItems(Jenkins.getInstance()); } public ListBoxModel doFillRegionItems(@QueryParameter final String credentialsId, @QueryParameter final String region) throws IOException, ServletException { final List<Region> regionList; try { final AmazonEC2 client = connect(credentialsId, null); final DescribeRegionsResult regions=client.describeRegions(); regionList=regions.getRegions(); } catch(final Exception ex) { //Ignore bad exceptions return new ListBoxModel(); } final ListBoxModel model = new ListBoxModel(); for(final Region reg : regionList) { model.add(new ListBoxModel.Option(reg.getRegionName(), reg.getRegionName())); } return model; } public ListBoxModel doFillFleetItems(@QueryParameter final String region, @QueryParameter final String credentialsId, @QueryParameter final String fleet) throws IOException, ServletException { final ListBoxModel model = new ListBoxModel(); try { final AmazonEC2 client=connect(credentialsId, region); String token = null; do { final DescribeSpotFleetRequestsRequest req=new DescribeSpotFleetRequestsRequest(); req.withNextToken(token); final DescribeSpotFleetRequestsResult result=client.describeSpotFleetRequests(req); for(final SpotFleetRequestConfig config : result.getSpotFleetRequestConfigs()) { final String curFleetId=config.getSpotFleetRequestId(); final String displayStr=curFleetId+ " ("+config.getSpotFleetRequestState()+")"; model.add(new ListBoxModel.Option(displayStr, curFleetId, ObjectUtils.nullSafeEquals(fleet, curFleetId))); } token = result.getNextToken(); } while(token != null); } catch(final Exception ex) { //Ignore bad exceptions return model; } return model; } public FormValidation doTestConnection( @QueryParameter final String credentialsId, @QueryParameter final String region, @QueryParameter final String fleet) { try { final AmazonEC2 client=connect(credentialsId, region); client.describeSpotFleetInstances( new DescribeSpotFleetInstancesRequest().withSpotFleetRequestId(fleet)); } catch(final Exception ex) { return FormValidation.error(ex.getMessage()); } return FormValidation.ok("Success"); } @Override public boolean configure(final StaplerRequest req, final JSONObject formData) throws FormException { req.bindJSON(this, formData); save(); return super.configure(req,formData); } public boolean isUseInstanceProfileForCredentials() { return useInstanceProfileForCredentials; } public String getAccessId() { return accessId; } public String getSecretKey() { return secretKey; } public String getRegion() { return region; } public String getFleet() { return fleet; } } }
//FILE: AcquisitionPanel.java //PROJECT: Micro-Manager //SUBSYSTEM: ASIdiSPIM plugin // This file is distributed in the hope that it will be useful, // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES. package org.micromanager.asidispim; import org.micromanager.asidispim.Data.AcquisitionModes; import org.micromanager.asidispim.Data.CameraModes; import org.micromanager.asidispim.Data.Cameras; import org.micromanager.asidispim.Data.Devices; import org.micromanager.asidispim.Data.MultichannelModes; import org.micromanager.asidispim.Data.MyStrings; import org.micromanager.asidispim.Data.Positions; import org.micromanager.asidispim.Data.Prefs; import org.micromanager.asidispim.Data.Properties; import org.micromanager.asidispim.Utils.DevicesListenerInterface; import org.micromanager.asidispim.Utils.ListeningJPanel; import org.micromanager.asidispim.Utils.MyDialogUtils; import org.micromanager.asidispim.Utils.MyNumberUtils; import org.micromanager.asidispim.Utils.PanelUtils; import org.micromanager.asidispim.Utils.SliceTiming; import org.micromanager.asidispim.Utils.StagePositionUpdater; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Insets; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.text.ParseException; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JFormattedTextField; import javax.swing.JOptionPane; import javax.swing.JTextField; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JComboBox; import javax.swing.JPanel; import javax.swing.JSpinner; import javax.swing.JToggleButton; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.text.DefaultFormatter; import net.miginfocom.swing.MigLayout; import org.json.JSONException; import org.json.JSONObject; import mmcorej.CMMCore; import mmcorej.StrVector; import mmcorej.TaggedImage; import org.micromanager.api.MultiStagePosition; import org.micromanager.api.PositionList; import org.micromanager.api.ScriptInterface; import org.micromanager.api.ImageCache; import org.micromanager.api.MMTags; import org.micromanager.MMStudio; import org.micromanager.acquisition.ComponentTitledBorder; import org.micromanager.acquisition.DefaultTaggedImageSink; import org.micromanager.acquisition.MMAcquisition; import org.micromanager.acquisition.TaggedImageQueue; import org.micromanager.acquisition.TaggedImageStorageDiskDefault; import org.micromanager.acquisition.TaggedImageStorageMultipageTiff; import org.micromanager.imagedisplay.VirtualAcquisitionDisplay; import org.micromanager.utils.ImageUtils; import org.micromanager.utils.NumberUtils; import org.micromanager.utils.FileDialogs; import org.micromanager.utils.MDUtils; import org.micromanager.utils.MMFrame; import org.micromanager.utils.MMScriptException; import org.micromanager.utils.ReportingUtils; import com.swtdesigner.SwingResourceManager; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.geom.Point2D; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.BorderFactory; import org.micromanager.asidispim.Data.AcquisitionSettings; import org.micromanager.asidispim.Data.ChannelSpec; import org.micromanager.asidispim.Data.Devices.Sides; import org.micromanager.asidispim.Utils.ControllerUtils; import org.micromanager.asidispim.Utils.AutofocusUtils; import org.micromanager.asidispim.api.ASIdiSPIMException; /** * * @author nico * @author Jon */ @SuppressWarnings("serial") public class AcquisitionPanel extends ListeningJPanel implements DevicesListenerInterface { private final Devices devices_; private final Properties props_; private final Cameras cameras_; private final Prefs prefs_; private final ControllerUtils controller_; private final AutofocusUtils autofocus_; private final Positions positions_; private final CMMCore core_; private final ScriptInterface gui_; private final JCheckBox advancedSliceTimingCB_; private final JSpinner numSlices_; private final JComboBox numSides_; private final JComboBox firstSide_; private final JSpinner numScansPerSlice_; private final JSpinner lineScanPeriod_; private final JSpinner delayScan_; private final JSpinner delayLaser_; private final JSpinner delayCamera_; private final JSpinner durationCamera_; // NB: not the same as camera exposure private final JSpinner exposureCamera_; // NB: only used in advanced timing mode private final JSpinner durationLaser_; private final JSpinner delaySide_; private final JLabel actualSlicePeriodLabel_; private final JLabel actualVolumeDurationLabel_; private final JLabel actualTimeLapseDurationLabel_; private final JSpinner numTimepoints_; private final JSpinner acquisitionInterval_; private final JToggleButton buttonStart_; private final JPanel volPanel_; private final JPanel slicePanel_; private final JPanel timepointPanel_; private final JPanel savePanel_; private final JPanel durationPanel_; private final JFormattedTextField rootField_; private final JFormattedTextField prefixField_; private final JLabel acquisitionStatusLabel_; private int numTimePointsDone_; private final AtomicBoolean cancelAcquisition_ = new AtomicBoolean(false); // true if we should stop acquisition private final AtomicBoolean acquisitionRunning_ = new AtomicBoolean(false); // true if acquisition is in progress private final StagePositionUpdater posUpdater_; private final JSpinner stepSize_; private final JLabel desiredSlicePeriodLabel_; private final JSpinner desiredSlicePeriod_; private final JLabel desiredLightExposureLabel_; private final JSpinner desiredLightExposure_; private final JCheckBox minSlicePeriodCB_; private final JCheckBox separateTimePointsCB_; private final JCheckBox saveCB_; private final JComboBox spimMode_; private final JCheckBox navigationJoysticksCB_; private final JCheckBox usePositionsCB_; private final JSpinner positionDelay_; private final JCheckBox useTimepointsCB_; private final JCheckBox useAutofocusCB_; private final JPanel leftColumnPanel_; private final JPanel centerColumnPanel_; private final JPanel rightColumnPanel_; private final MMFrame sliceFrameAdvanced_; private SliceTiming sliceTiming_; private final MultiChannelSubPanel multiChannelPanel_; private final Color[] colors = {Color.RED, Color.GREEN, Color.BLUE, Color.MAGENTA, Color.PINK, Color.CYAN, Color.YELLOW, Color.ORANGE}; private String pathToLastAcquisition_; public AcquisitionPanel(ScriptInterface gui, Devices devices, Properties props, Cameras cameras, Prefs prefs, StagePositionUpdater posUpdater, Positions positions, ControllerUtils controller, AutofocusUtils autofocus) { super(MyStrings.PanelNames.ACQUSITION.toString(), new MigLayout( "", "[center]0[center]0[center]", "0[top]0")); gui_ = gui; devices_ = devices; props_ = props; cameras_ = cameras; prefs_ = prefs; posUpdater_ = posUpdater; positions_ = positions; controller_ = controller; autofocus_ = autofocus; core_ = gui_.getMMCore(); numTimePointsDone_ = 0; sliceTiming_ = new SliceTiming(); pathToLastAcquisition_ = ""; PanelUtils pu = new PanelUtils(prefs_, props_, devices_); // added to spinner controls where we should re-calculate the displayed // slice period, volume duration, and time lapse duration ChangeListener recalculateTimingDisplayCL = new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { if (advancedSliceTimingCB_.isSelected()) { // need to update sliceTiming_ from property values sliceTiming_ = getTimingFromAdvancedSettings(); } updateDurationLabels(); } }; // added to combobox controls where we should re-calculate the displayed // slice period, volume duration, and time lapse duration ActionListener recalculateTimingDisplayAL = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { updateDurationLabels(); } }; // start volume (main) sub-panel volPanel_ = new JPanel(new MigLayout( "", "[right]10[center]", "[]8[]")); volPanel_.setBorder(PanelUtils.makeTitledBorder("Volume Settings")); volPanel_.add(new JLabel("Number of sides:")); String [] str12 = {"1", "2"}; numSides_ = pu.makeDropDownBox(str12, Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_NUM_SIDES, str12[1]); numSides_.addActionListener(recalculateTimingDisplayAL); volPanel_.add(numSides_, "wrap"); volPanel_.add(new JLabel("First side:")); String[] ab = {Devices.Sides.A.toString(), Devices.Sides.B.toString()}; firstSide_ = pu.makeDropDownBox(ab, Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_FIRST_SIDE, Devices.Sides.A.toString()); volPanel_.add(firstSide_, "wrap"); volPanel_.add(new JLabel("Delay before side [ms]:")); delaySide_ = pu.makeSpinnerFloat(0, 10000, 0.25, new Devices.Keys[]{Devices.Keys.GALVOA, Devices.Keys.GALVOB}, Properties.Keys.SPIM_DELAY_SIDE, 0); delaySide_.addChangeListener(recalculateTimingDisplayCL); volPanel_.add(delaySide_, "wrap"); volPanel_.add(new JLabel("Slices per side:")); numSlices_ = pu.makeSpinnerInteger(1, 65000, Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_NUM_SLICES, 20); numSlices_.addChangeListener(recalculateTimingDisplayCL); volPanel_.add(numSlices_, "wrap"); volPanel_.add(new JLabel("Slice step size [\u00B5m]:")); stepSize_ = pu.makeSpinnerFloat(0, 100, 0.1, Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_SLICE_STEP_SIZE, 1.0); volPanel_.add(stepSize_, "wrap"); // out of order so we can reference it desiredSlicePeriod_ = pu.makeSpinnerFloat(1, 1000, 0.25, Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_DESIRED_SLICE_PERIOD, 30); minSlicePeriodCB_ = pu.makeCheckBox("Minimize slice period", Properties.Keys.PREFS_MINIMIZE_SLICE_PERIOD, panelName_, false); minSlicePeriodCB_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { boolean doMin = minSlicePeriodCB_.isSelected(); desiredSlicePeriod_.setEnabled(!doMin); recalculateSliceTiming(false); } }); volPanel_.add(minSlicePeriodCB_, "span 2, wrap"); // special field that is enabled/disabled depending on whether advanced timing is enabled desiredSlicePeriodLabel_ = new JLabel("Slice period [ms]:"); volPanel_.add(desiredSlicePeriodLabel_); volPanel_.add(desiredSlicePeriod_, "wrap"); desiredSlicePeriod_.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent ce) { // make sure is multiple of 0.25 float userVal = PanelUtils.getSpinnerFloatValue(desiredSlicePeriod_); float nearestValid = MyNumberUtils.roundToQuarterMs(userVal); if (!MyNumberUtils.floatsEqual(userVal, nearestValid)) { PanelUtils.setSpinnerFloatValue(desiredSlicePeriod_, nearestValid); } } }); desiredSlicePeriod_.addChangeListener(recalculateTimingDisplayCL); // special field that is enabled/disabled depending on whether advanced timing is enabled desiredLightExposureLabel_ = new JLabel("Sample exposure [ms]:"); volPanel_.add(desiredLightExposureLabel_); desiredLightExposure_ = pu.makeSpinnerFloat(2.5, 1000.5, 1, Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_DESIRED_EXPOSURE, 8.5); desiredLightExposure_.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent ce) { // make sure is 2.5, 2.5, 3.5, ... float val = PanelUtils.getSpinnerFloatValue(desiredLightExposure_); float nearestValid = (float) Math.round(val+0.5f) - 0.5f; if (!MyNumberUtils.floatsEqual(val, nearestValid)) { PanelUtils.setSpinnerFloatValue(desiredLightExposure_, nearestValid); } recalculateSliceTiming(!minSlicePeriodCB_.isSelected()); } }); desiredLightExposure_.addChangeListener(recalculateTimingDisplayCL); volPanel_.add(desiredLightExposure_, "wrap"); // special checkbox to use the advanced timing settings // action handler added below after defining components it enables/disables advancedSliceTimingCB_ = pu.makeCheckBox("Use advanced timing settings", Properties.Keys.PREFS_ADVANCED_SLICE_TIMING, panelName_, false); volPanel_.add(advancedSliceTimingCB_, "left, span 2, wrap"); // end volume sub-panel // start advanced slice timing frame // visibility of this frame is controlled from advancedTiming checkbox // this frame is separate from main plugin window sliceFrameAdvanced_ = new MMFrame(); sliceFrameAdvanced_.setTitle("Advanced timing"); sliceFrameAdvanced_.loadPosition(100, 100); slicePanel_ = new JPanel(new MigLayout( "", "[right]10[center]", "[]8[]")); sliceFrameAdvanced_.add(slicePanel_); class SliceFrameAdapter extends WindowAdapter { @Override public void windowClosing(WindowEvent e) { advancedSliceTimingCB_.setSelected(false); sliceFrameAdvanced_.savePosition(); } } sliceFrameAdvanced_.addWindowListener(new SliceFrameAdapter()); JLabel scanDelayLabel = new JLabel("Delay before scan [ms]:"); slicePanel_.add(scanDelayLabel); delayScan_ = pu.makeSpinnerFloat(0, 10000, 0.25, new Devices.Keys[]{Devices.Keys.GALVOA, Devices.Keys.GALVOB}, Properties.Keys.SPIM_DELAY_SCAN, 0); delayScan_.addChangeListener(recalculateTimingDisplayCL); slicePanel_.add(delayScan_, "wrap"); JLabel lineScanLabel = new JLabel("Lines scans per slice:"); slicePanel_.add(lineScanLabel); numScansPerSlice_ = pu.makeSpinnerInteger(1, 1000, new Devices.Keys[]{Devices.Keys.GALVOA, Devices.Keys.GALVOB}, Properties.Keys.SPIM_NUM_SCANSPERSLICE, 1); numScansPerSlice_.addChangeListener(recalculateTimingDisplayCL); slicePanel_.add(numScansPerSlice_, "wrap"); JLabel lineScanPeriodLabel = new JLabel("Line scan period [ms]:"); slicePanel_.add(lineScanPeriodLabel); lineScanPeriod_ = pu.makeSpinnerInteger(1, 10000, new Devices.Keys[]{Devices.Keys.GALVOA, Devices.Keys.GALVOB}, Properties.Keys.SPIM_LINESCAN_PERIOD, 10); lineScanPeriod_.addChangeListener(recalculateTimingDisplayCL); slicePanel_.add(lineScanPeriod_, "wrap"); JLabel delayLaserLabel = new JLabel("Delay before laser [ms]:"); slicePanel_.add(delayLaserLabel); delayLaser_ = pu.makeSpinnerFloat(0, 10000, 0.25, new Devices.Keys[]{Devices.Keys.GALVOA, Devices.Keys.GALVOB}, Properties.Keys.SPIM_DELAY_LASER, 0); delayLaser_.addChangeListener(recalculateTimingDisplayCL); slicePanel_.add(delayLaser_, "wrap"); JLabel durationLabel = new JLabel("Laser trig duration [ms]:"); slicePanel_.add(durationLabel); durationLaser_ = pu.makeSpinnerFloat(0, 10000, 0.25, new Devices.Keys[]{Devices.Keys.GALVOA, Devices.Keys.GALVOB}, Properties.Keys.SPIM_DURATION_LASER, 1); durationLaser_.addChangeListener(recalculateTimingDisplayCL); slicePanel_.add(durationLaser_, "span 2, wrap"); JLabel delayLabel = new JLabel("Delay before camera [ms]:"); slicePanel_.add(delayLabel); delayCamera_ = pu.makeSpinnerFloat(0, 10000, 0.25, new Devices.Keys[]{Devices.Keys.GALVOA, Devices.Keys.GALVOB}, Properties.Keys.SPIM_DELAY_CAMERA, 0); delayCamera_.addChangeListener(recalculateTimingDisplayCL); slicePanel_.add(delayCamera_, "wrap"); JLabel cameraLabel = new JLabel("Camera trig duration [ms]:"); slicePanel_.add(cameraLabel); durationCamera_ = pu.makeSpinnerFloat(0, 1000, 0.25, new Devices.Keys[]{Devices.Keys.GALVOA, Devices.Keys.GALVOB}, Properties.Keys.SPIM_DURATION_CAMERA, 0); durationCamera_.addChangeListener(recalculateTimingDisplayCL); slicePanel_.add(durationCamera_, "wrap"); JLabel exposureLabel = new JLabel("Camera exposure[ms]:"); slicePanel_.add(exposureLabel); exposureCamera_ = pu.makeSpinnerFloat(0, 1000, 0.25, Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_ADVANCED_CAMERA_EXPOSURE, 10f); exposureCamera_.addChangeListener(recalculateTimingDisplayCL); slicePanel_.add(exposureCamera_, "wrap"); final JComponent[] simpleTimingComponents = { desiredLightExposure_, minSlicePeriodCB_, desiredSlicePeriodLabel_, desiredLightExposureLabel_}; final JComponent[] advancedTimingComponents = { delayScan_, numScansPerSlice_, lineScanPeriod_, delayLaser_, durationLaser_, delayCamera_, durationCamera_, exposureCamera_}; componentsSetEnabled(advancedTimingComponents, advancedSliceTimingCB_.isSelected()); componentsSetEnabled(simpleTimingComponents, !advancedSliceTimingCB_.isSelected()); // this action listener takes care of enabling/disabling inputs // of the advanced slice timing window // we call this to get GUI looking right ItemListener sliceTimingDisableGUIInputs = new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { boolean enabled = advancedSliceTimingCB_.isSelected(); // set other components in this advanced timing frame componentsSetEnabled(advancedTimingComponents, enabled); // also control some components in main volume settings sub-panel componentsSetEnabled(simpleTimingComponents, !enabled); desiredSlicePeriod_.setEnabled(!enabled && !minSlicePeriodCB_.isSelected()); updateDurationLabels(); } }; // this action listener shows/hides the advanced timing frame ActionListener showAdvancedTimingFrame = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { boolean enabled = advancedSliceTimingCB_.isSelected(); if (enabled) { sliceFrameAdvanced_.setVisible(enabled); } } }; sliceFrameAdvanced_.pack(); sliceFrameAdvanced_.setResizable(false); // end slice Frame // start repeat (time lapse) sub-panel timepointPanel_ = new JPanel(new MigLayout( "", "[right]10[center]", "[]8[]")); useTimepointsCB_ = pu.makeCheckBox("Time points", Properties.Keys.PREFS_USE_TIMEPOINTS, panelName_, false); useTimepointsCB_.setToolTipText("Perform a time-lapse acquisition"); useTimepointsCB_.setEnabled(true); useTimepointsCB_.setFocusPainted(false); ComponentTitledBorder componentBorder = new ComponentTitledBorder(useTimepointsCB_, timepointPanel_, BorderFactory.createLineBorder(ASIdiSPIM.borderColor)); timepointPanel_.setBorder(componentBorder); ChangeListener recalculateTimeLapseDisplay = new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { updateActualTimeLapseDurationLabel(); } }; useTimepointsCB_.addChangeListener(recalculateTimeLapseDisplay); timepointPanel_.add(new JLabel("Number:")); numTimepoints_ = pu.makeSpinnerInteger(1, 32000, Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_NUM_ACQUISITIONS, 1); numTimepoints_.addChangeListener(recalculateTimeLapseDisplay); timepointPanel_.add(numTimepoints_, "wrap"); timepointPanel_.add(new JLabel("Interval [s]:")); acquisitionInterval_ = pu.makeSpinnerFloat(0.1, 32000, 0.1, Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_ACQUISITION_INTERVAL, 60); acquisitionInterval_.addChangeListener(recalculateTimeLapseDisplay); timepointPanel_.add(acquisitionInterval_, "wrap"); // enable/disable panel elements depending on checkbox state useTimepointsCB_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { componentsSetEnabled(timepointPanel_, useTimepointsCB_.isSelected()); } }); componentsSetEnabled(timepointPanel_, useTimepointsCB_.isSelected()); // initialize // end repeat sub-panel // start savePanel // TODO for now these settings aren't part of acquisition settings // TODO consider whether that should be changed final int textFieldWidth = 16; savePanel_ = new JPanel(new MigLayout( "", "[right]10[center]8[left]", "[]4[]")); savePanel_.setBorder(PanelUtils.makeTitledBorder("Data Saving Settings")); separateTimePointsCB_ = pu.makeCheckBox("Separate viewer / file for each time point", Properties.Keys.PREFS_SEPARATE_VIEWERS_FOR_TIMEPOINTS, panelName_, false); savePanel_.add(separateTimePointsCB_, "span 3, left, wrap"); saveCB_ = pu.makeCheckBox("Save while acquiring", Properties.Keys.PREFS_SAVE_WHILE_ACQUIRING, panelName_, false); // init the save while acquiring CB; could also do two doClick() calls // TODO check that it's initialized now savePanel_.add(saveCB_, "skip 1, span 2, center, wrap"); JLabel dirRootLabel = new JLabel ("Directory root:"); savePanel_.add(dirRootLabel); DefaultFormatter formatter = new DefaultFormatter(); rootField_ = new JFormattedTextField(formatter); rootField_.setText( prefs_.getString(panelName_, Properties.Keys.PLUGIN_DIRECTORY_ROOT, "") ); rootField_.addPropertyChangeListener(new PropertyChangeListener() { // will respond to commitEdit() as well as GUI edit on commit @Override public void propertyChange(PropertyChangeEvent evt) { prefs_.putString(panelName_, Properties.Keys.PLUGIN_DIRECTORY_ROOT, rootField_.getText()); } }); rootField_.setColumns(textFieldWidth); savePanel_.add(rootField_, "span 2"); JButton browseRootButton = new JButton(); browseRootButton.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { setRootDirectory(rootField_); prefs_.putString(panelName_, Properties.Keys.PLUGIN_DIRECTORY_ROOT, rootField_.getText()); } }); browseRootButton.setMargin(new Insets(2, 5, 2, 5)); browseRootButton.setText("..."); savePanel_.add(browseRootButton, "wrap"); JLabel namePrefixLabel = new JLabel(); namePrefixLabel.setText("Name prefix:"); savePanel_.add(namePrefixLabel); prefixField_ = new JFormattedTextField(formatter); prefixField_.setText( prefs_.getString(panelName_, Properties.Keys.PLUGIN_NAME_PREFIX, "acq")); prefixField_.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { prefs_.putString(panelName_, Properties.Keys.PLUGIN_NAME_PREFIX, prefixField_.getText()); } }); prefixField_.setColumns(textFieldWidth); savePanel_.add(prefixField_, "span 2, wrap"); // since we use the name field even for acquisitions in RAM, // we only need to gray out the directory-related components final JComponent[] saveComponents = { browseRootButton, rootField_, dirRootLabel }; componentsSetEnabled(saveComponents, saveCB_.isSelected()); saveCB_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { componentsSetEnabled(saveComponents, saveCB_.isSelected()); } }); // end save panel // start duration report panel durationPanel_ = new JPanel(new MigLayout( "", "[right]6[left, 40%!]", "[]5[]")); durationPanel_.setBorder(PanelUtils.makeTitledBorder("Durations")); durationPanel_.setPreferredSize(new Dimension(125, 0)); // fix width so it doesn't constantly change depending on text durationPanel_.add(new JLabel("Slice:")); actualSlicePeriodLabel_ = new JLabel(); durationPanel_.add(actualSlicePeriodLabel_, "wrap"); durationPanel_.add(new JLabel("Volume:")); actualVolumeDurationLabel_ = new JLabel(); durationPanel_.add(actualVolumeDurationLabel_, "wrap"); durationPanel_.add(new JLabel("Total:")); actualTimeLapseDurationLabel_ = new JLabel(); durationPanel_.add(actualTimeLapseDurationLabel_, "wrap"); // end duration report panel buttonStart_ = new JToggleButton(); buttonStart_.setIconTextGap(6); buttonStart_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (isAcquisitionRunning()) { stopAcquisition(); } else { runAcquisition(); } } }); updateStartButton(); // call once to initialize, isSelected() will be false acquisitionStatusLabel_ = new JLabel(""); acquisitionStatusLabel_.setBackground(prefixField_.getBackground()); acquisitionStatusLabel_.setOpaque(true); updateAcquisitionStatus(AcquisitionStatus.NONE); // Channel Panel (separate file for code) multiChannelPanel_ = new MultiChannelSubPanel(gui, devices_, props_, prefs_); multiChannelPanel_.addDurationLabelListener(this); // Position Panel final JPanel positionPanel = new JPanel(); positionPanel.setLayout(new MigLayout("flowx, fillx","[right]10[left][10][]","[]8[]")); usePositionsCB_ = pu.makeCheckBox("Multiple positions (XY)", Properties.Keys.PREFS_USE_MULTIPOSITION, panelName_, false); usePositionsCB_.setToolTipText("Acquire datasest at multiple postions"); usePositionsCB_.setEnabled(true); usePositionsCB_.setFocusPainted(false); componentBorder = new ComponentTitledBorder(usePositionsCB_, positionPanel, BorderFactory.createLineBorder(ASIdiSPIM.borderColor)); positionPanel.setBorder(componentBorder); usePositionsCB_.addChangeListener(recalculateTimingDisplayCL); final JButton editPositionListButton = new JButton("Edit position list..."); editPositionListButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { gui_.showXYPositionList(); } }); positionPanel.add(editPositionListButton, "span 2, center"); // add empty fill space on right side of panel positionPanel.add(new JLabel(""), "wrap, growx"); positionPanel.add(new JLabel("Post-move delay [ms]:")); positionDelay_ = pu.makeSpinnerFloat(0.0, 10000.0, 100.0, Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_POSITION_DELAY, 0.0); positionPanel.add(positionDelay_, "wrap"); // enable/disable panel elements depending on checkbox state usePositionsCB_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { componentsSetEnabled(positionPanel, usePositionsCB_.isSelected()); } }); componentsSetEnabled(positionPanel, usePositionsCB_.isSelected()); // initialize // end of Position panel // checkbox to use navigation joystick settings or not // an "orphan" UI element navigationJoysticksCB_ = new JCheckBox("Use Navigation joystick settings"); navigationJoysticksCB_.setSelected(prefs_.getBoolean(panelName_, Properties.Keys.PLUGIN_USE_NAVIGATION_JOYSTICKS, false)); navigationJoysticksCB_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { updateJoysticks(); prefs_.putBoolean(panelName_, Properties.Keys.PLUGIN_USE_NAVIGATION_JOYSTICKS, navigationJoysticksCB_.isSelected()); } }); // checkbox to signal that autofocus should be used during acquisition // another orphan UI element useAutofocusCB_ = new JCheckBox("Autofocus during acquisition"); useAutofocusCB_.setSelected(prefs_.getBoolean(panelName_, Properties.Keys.PLUGIN_ACQUSITION_USE_AUTOFOCUS, false)); useAutofocusCB_.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { prefs_.putBoolean(panelName_, Properties.Keys.PLUGIN_ACQUSITION_USE_AUTOFOCUS, useAutofocusCB_.isSelected()); } }); // set up tabbed panels for GUI // make 3 columns as own JPanels to get vertical space right // in each column without dependencies on other columns leftColumnPanel_ = new JPanel(new MigLayout( "", "[]", "[]6[]10[]10[]")); leftColumnPanel_.add(durationPanel_, "split 2"); leftColumnPanel_.add(timepointPanel_, "wrap, growx"); leftColumnPanel_.add(savePanel_, "wrap"); leftColumnPanel_.add(new JLabel("Acquisition mode: "), "split 2, right"); AcquisitionModes acqModes = new AcquisitionModes(devices_, prefs_); spimMode_ = acqModes.getComboBox(); spimMode_.addActionListener(recalculateTimingDisplayAL); leftColumnPanel_.add(spimMode_, "left, wrap"); leftColumnPanel_.add(buttonStart_, "split 2, left, wrap"); leftColumnPanel_.add(new JLabel("Status:"), "split 2, left"); leftColumnPanel_.add(acquisitionStatusLabel_); centerColumnPanel_ = new JPanel(new MigLayout( "", "[]", "[]")); centerColumnPanel_.add(positionPanel, "growx, wrap"); centerColumnPanel_.add(multiChannelPanel_, "wrap"); centerColumnPanel_.add(navigationJoysticksCB_, "wrap"); centerColumnPanel_.add(useAutofocusCB_); rightColumnPanel_ = new JPanel(new MigLayout( "", "[]", "[]")); rightColumnPanel_.add(volPanel_); // add the column panels to the main panel this.add(leftColumnPanel_); this.add(centerColumnPanel_); this.add(rightColumnPanel_); // properly initialize the advanced slice timing advancedSliceTimingCB_.addItemListener(sliceTimingDisableGUIInputs); sliceTimingDisableGUIInputs.itemStateChanged(null); advancedSliceTimingCB_.addActionListener(showAdvancedTimingFrame); // included is calculating slice timing updateDurationLabels(); }//end constructor private void updateJoysticks() { if (ASIdiSPIM.getFrame() != null) { ASIdiSPIM.getFrame().getNavigationPanel(). doJoystickSettings(navigationJoysticksCB_.isSelected()); } } public final void updateDurationLabels() { updateActualSlicePeriodLabel(); updateActualVolumeDurationLabel(); updateActualTimeLapseDurationLabel(); } private void updateCalibrationOffset(final Sides side, final AutofocusUtils.FocusResult score) { ASIdiSPIM.getFrame().getSetupPanel(side).updateCalibrationOffset(score); } public SliceTiming getSliceTiming() { return sliceTiming_; } /** * Sets the acquisition name prefix programmatically. * Added so that name prefix can be changed from a script. * @param acqName */ public void setAcquisitionNamePrefix(String acqName) { prefixField_.setText((acqName + "_hello")); // prefixField_.setText(acqName); } private void updateStartButton() { boolean started = isAcquisitionRunning(); buttonStart_.setSelected(started); buttonStart_.setText(started ? "Stop!" : "Start!"); buttonStart_.setBackground(started ? Color.red : Color.green); buttonStart_.setIcon(started ? SwingResourceManager. getIcon(MMStudio.class, "/org/micromanager/icons/cancel.png") : SwingResourceManager.getIcon(MMStudio.class, "/org/micromanager/icons/arrow_right.png")); } /** * @return CameraModes.Keys value from Settings panel * (internal, edge, overlap, pseudo-overlap) */ private CameraModes.Keys getSPIMCameraMode() { return CameraModes.getKeyFromPrefCode( prefs_.getInt(MyStrings.PanelNames.SETTINGS.toString(), Properties.Keys.PLUGIN_CAMERA_MODE, 0)); } /** * convenience method to avoid having to regenerate acquisition settings */ private int getNumTimepoints() { if (useTimepointsCB_.isSelected()) { return (Integer) numTimepoints_.getValue(); } else { return 1; } } /** * convenience method to avoid having to regenerate acquisition settings */ private int getNumSides() { if (numSides_.getSelectedIndex() == 1) { return 2; } else { return 1; } } /** * convenience method to avoid having to regenerate acquisition settings */ private boolean isFirstSideA() { return ((String) firstSide_.getSelectedItem()).equals("A"); } /** * convenience method to avoid having to regenerate acquisition settings */ private double getTimepointInterval() { return PanelUtils.getSpinnerFloatValue(acquisitionInterval_); } /** * Gathers all current acquisition settings into dedicated POD object * @return */ public AcquisitionSettings getCurrentAcquisitionSettings() { AcquisitionSettings acqSettings = new AcquisitionSettings(); acqSettings.spimMode = (AcquisitionModes.Keys) spimMode_.getSelectedItem(); acqSettings.isStageScanning = (acqSettings.spimMode == AcquisitionModes.Keys.STAGE_SCAN || acqSettings.spimMode == AcquisitionModes.Keys.STAGE_SCAN_INTERLEAVED); acqSettings.useTimepoints = useTimepointsCB_.isSelected(); acqSettings.numTimepoints = getNumTimepoints(); acqSettings.timepointInterval = getTimepointInterval(); acqSettings.useMultiPositions = usePositionsCB_.isSelected(); acqSettings.useChannels = multiChannelPanel_.isMultiChannel(); acqSettings.channelMode = multiChannelPanel_.getChannelMode(); acqSettings.numChannels = multiChannelPanel_.getNumChannels(); acqSettings.channels = multiChannelPanel_.getUsedChannels(); acqSettings.channelGroup = multiChannelPanel_.getChannelGroup(); acqSettings.useAutofocus = useAutofocusCB_.isSelected(); acqSettings.numSides = getNumSides(); acqSettings.firstSideIsA = isFirstSideA(); acqSettings.delayBeforeSide = PanelUtils.getSpinnerFloatValue(delaySide_); acqSettings.numSlices = (Integer) numSlices_.getValue(); acqSettings.stepSizeUm = PanelUtils.getSpinnerFloatValue(stepSize_); acqSettings.minimizeSlicePeriod = minSlicePeriodCB_.isSelected(); acqSettings.desiredSlicePeriod = PanelUtils.getSpinnerFloatValue(desiredSlicePeriod_); acqSettings.desiredLightExposure = PanelUtils.getSpinnerFloatValue(desiredLightExposure_); acqSettings.centerAtCurrentZ = false; acqSettings.sliceTiming = sliceTiming_; acqSettings.cameraMode = getSPIMCameraMode(); acqSettings.accelerationX = props_.getPropValueFloat(Devices.Keys.XYSTAGE, Properties.Keys.STAGESCAN_MOTOR_ACCEL); acqSettings.hardwareTimepoints = false; // when running acquisition we check this and set to true if needed return acqSettings; } /** * gets the correct value for the slice timing's sliceDuration field * based on other values of slice timing * @param s * @return */ private float getSliceDuration(final SliceTiming s) { // slice duration is the max out of the scan time, laser time, and camera time return Math.max(Math.max( s.scanDelay + (s.scanPeriod * s.scanNum), // scan time s.laserDelay + s.laserDuration // laser time ), s.cameraDelay + s.cameraDuration // camera time ); } /** * gets the slice timing from advanced settings * (normally these advanced settings are read-only and we populate them * ourselves depending on the user's requests and our algorithm below) * @return */ private SliceTiming getTimingFromAdvancedSettings() { SliceTiming s = new SliceTiming(); s.scanDelay = PanelUtils.getSpinnerFloatValue(delayScan_); s.scanNum = (Integer) numScansPerSlice_.getValue(); s.scanPeriod = (Integer) lineScanPeriod_.getValue(); s.laserDelay = PanelUtils.getSpinnerFloatValue(delayLaser_); s.laserDuration = PanelUtils.getSpinnerFloatValue(durationLaser_); s.cameraDelay = PanelUtils.getSpinnerFloatValue(delayCamera_); s.cameraDuration = PanelUtils.getSpinnerFloatValue(durationCamera_); s.cameraExposure = PanelUtils.getSpinnerFloatValue(exposureCamera_); s.sliceDuration = getSliceDuration(s); return s; } /** * * @param showWarnings true to warn user about needing to change slice period * @return */ private SliceTiming getTimingFromPeriodAndLightExposure(boolean showWarnings) { // uses algorithm Jon worked out in Octave code; each slice period goes like this: // 1. camera readout time (none if in overlap mode, 0.25ms in PCO pseudo-overlap) // 2. any extra delay time // 3. camera reset time // 4. start scan 0.25ms before camera global exposure and shifted up in time to account for delay introduced by Bessel filter // 5. turn on laser as soon as camera global exposure, leave laser on for desired light exposure time // 7. end camera exposure in final 0.25ms, post-filter scan waveform also ends now final float scanLaserBufferTime = 0.25f; final Color foregroundColorOK = Color.BLACK; final Color foregroundColorError = Color.RED; final Component elementToColor = desiredSlicePeriod_.getEditor().getComponent(0); SliceTiming s = new SliceTiming(); final float cameraResetTime = computeCameraResetTime(); // recalculate for safety final float cameraReadoutTime = computeCameraReadoutTime(); // recalculate for safety // can we use acquisition settings directly? because they may be in flux final AcquisitionSettings acqSettings = getCurrentAcquisitionSettings(); // get delay between camera trigger and exposure starts so we can decrease // camera exposure accordingly for edge mode (this is slight correction only) // for overlap mode we don't set exposure time directly anyway // for pseudo-overlap mode the delay is minimal (0-1 row readout time) so ignore float cameraExposureDelayTime = 0; if (acqSettings.cameraMode == CameraModes.Keys.EDGE) { // for now simply recover "overhead time" in computeCameraResetTime() // if readout/reset calculations change then this may need to be more sophisticated cameraExposureDelayTime = cameraResetTime - cameraReadoutTime; ReportingUtils.logMessage("Exposure delay time is " + cameraExposureDelayTime); } final float desiredPeriod = acqSettings.minimizeSlicePeriod ? 0 : acqSettings.desiredSlicePeriod; final float desiredExposure = acqSettings.desiredLightExposure; final float cameraReadout_max = MyNumberUtils.ceilToQuarterMs(cameraReadoutTime); final float cameraReset_max = MyNumberUtils.ceilToQuarterMs(cameraResetTime); final float slicePeriod = MyNumberUtils.roundToQuarterMs(desiredPeriod); final int scanPeriod = Math.round(desiredExposure + 2*scanLaserBufferTime); // specified in integer number of ms // scan will be longer than laser by 0.25ms at both start and end final float laserDuration = scanPeriod - 2*scanLaserBufferTime; // will be integer plus 0.5 // computer "extra" per-slice time: period minus camera reset and readout times minus (scan time - 0.25ms) // the last 0.25ms correction comes because we start the scan 0.25ms before camera global exposure float globalDelay = slicePeriod - cameraReadout_max - cameraReset_max - scanPeriod + scanLaserBufferTime; // if calculated delay is negative then we have to reduce exposure time in 1 sec increments if (globalDelay < 0) { float extraTimeNeeded = MyNumberUtils.ceilToQuarterMs(-1f*globalDelay); // positive number globalDelay += extraTimeNeeded; if (showWarnings) { MyDialogUtils.showError( "Increasing slice period to meet laser exposure constraint\n" + "(time required for camera readout; readout time depends on ROI).\n"); elementToColor.setForeground(foregroundColorError); // considered actually changing the value, but decided against it because // maybe the user just needs to set the ROI appropriately and recalculate } else { elementToColor.setForeground(foregroundColorOK); } } else { elementToColor.setForeground(foregroundColorOK); } // account for delay in scan position based on Bessel filter by starting the scan slightly earlier // than we otherwise would; delay is (empirically) ~0.33/(freq in kHz) // find better results adding 0.4/(freq in kHz) though // group delay for bessel filter approx 1/w or ~0.16/freq, or half/third the empirical value (not sure why discrepancy) final float scanFilterFreq = Math.max(props_.getPropValueFloat(Devices.Keys.GALVOA, Properties.Keys.SCANNER_FILTER_X), props_.getPropValueFloat(Devices.Keys.GALVOB, Properties.Keys.SCANNER_FILTER_X)); float scanDelayFilter = 0; if (scanFilterFreq != 0) { scanDelayFilter = MyNumberUtils.roundToQuarterMs(0.4f/scanFilterFreq); } // Add 0.25ms to globalDelay if it is 0 and we are on overlap mode and scan has been shifted forward // basically the last 0.25ms of scan time that would have determined the slice period isn't // there any more because the scan time is moved up => add in the 0.25ms at the start of the slice // in edge or level trigger mode the camera trig falling edge marks the end of the slice period // not sure if PCO pseudo-overlap needs this, probably not because adding 0.25ms overhead in that case if (MyNumberUtils.floatsEqual(cameraReadout_max, 0f) // true iff overlap being used && (scanDelayFilter > 0.01f)) { globalDelay += 0.25f; } // If the PLogic card is used, account for 0.25ms delay it introduces to // the camera and laser trigger signals => subtract 0.25ms from the scanner delay // (start scanner 0.25ms later than it would be otherwise) // (really it is 0.25ms minus the evaluation time to generate the signals) // this time-shift opposes the Bessel filter delay if (devices_.isValidMMDevice(Devices.Keys.PLOGIC)) { scanDelayFilter -= 0.25f; } s.scanDelay = cameraReadout_max + globalDelay + cameraReset_max - scanDelayFilter - scanLaserBufferTime; s.scanNum = 1; s.scanPeriod = scanPeriod; s.laserDelay = cameraReadout_max + globalDelay + cameraReset_max; s.laserDuration = laserDuration; s.cameraDelay = cameraReadout_max + globalDelay; s.cameraDuration = cameraReset_max + scanPeriod - scanLaserBufferTime; // approx. same as exposure, can be used in bulb mode s.cameraExposure = s.cameraDuration - 0.10f // give up 0.10ms of our 0.25ms overhead here because camera might round up // from the set exposure time and thus exceed total period - cameraExposureDelayTime; // change camera duration for overlap mode to be short trigger // needed because exposure time is set by difference between pulses in this mode if (acqSettings.cameraMode == CameraModes.Keys.OVERLAP) { // for Hamamatsu's "synchronous" or Zyla's "overlap" mode // send single short trigger s.cameraDuration = 1; } // update the slice duration based on our new values s.sliceDuration = getSliceDuration(s); return s; } /** * Re-calculate the controller's timing settings for "easy timing" mode. * Changes panel variable sliceTiming_. * The controller's properties will be set as needed * @param showWarnings will show warning if the user-specified slice period too short * or if cameras aren't assigned */ private void recalculateSliceTiming(boolean showWarnings) { if(!checkCamerasAssigned(showWarnings)) { return; } // if user is providing his own slice timing don't change it if (advancedSliceTimingCB_.isSelected()) { return; } sliceTiming_ = getTimingFromPeriodAndLightExposure(showWarnings); PanelUtils.setSpinnerFloatValue(delayScan_, sliceTiming_.scanDelay); numScansPerSlice_.setValue(sliceTiming_.scanNum); lineScanPeriod_.setValue(sliceTiming_.scanPeriod); PanelUtils.setSpinnerFloatValue(delayLaser_, sliceTiming_.laserDelay); PanelUtils.setSpinnerFloatValue(durationLaser_, sliceTiming_.laserDuration); PanelUtils.setSpinnerFloatValue(delayCamera_, sliceTiming_.cameraDelay); PanelUtils.setSpinnerFloatValue(durationCamera_, sliceTiming_.cameraDuration ); } /** * Update the displayed slice period. */ private void updateActualSlicePeriodLabel() { recalculateSliceTiming(false); actualSlicePeriodLabel_.setText( NumberUtils.doubleToDisplayString( sliceTiming_.sliceDuration) + " ms"); } /** * Compute the volume duration in ms based on controller's timing settings. * Includes time for multiple channels. However, does not include for multiple positions. * @return duration in ms */ public double computeActualVolumeDuration(AcquisitionSettings acqSettings) { final MultichannelModes.Keys channelMode = acqSettings.channelMode; final int numChannels = acqSettings.numChannels; final int numSides = acqSettings.numSides; final float delayBeforeSide = acqSettings.delayBeforeSide; int numCameraTriggers = acqSettings.numSlices; if (acqSettings.cameraMode == CameraModes.Keys.OVERLAP) { numCameraTriggers += 1; } // stackDuration is per-side, per-channel, per-position final double stackDuration = numCameraTriggers * acqSettings.sliceTiming.sliceDuration; if (acqSettings.isStageScanning) { final double rampDuration = delayBeforeSide + acqSettings.accelerationX; // TODO double-check these calculations below, at least they are better than before ;-) if (acqSettings.spimMode == AcquisitionModes.Keys.STAGE_SCAN) { if (channelMode == MultichannelModes.Keys.SLICE_HW) { return (numSides * ((rampDuration * 2) + (stackDuration * numChannels))); } else { return (numSides * ((rampDuration * 2) + stackDuration) * numChannels); } } else { // interleaved mode if (channelMode == MultichannelModes.Keys.SLICE_HW) { return (rampDuration * 2 + stackDuration * numSides * numChannels); } else { return ((rampDuration * 2 + stackDuration * numSides) * numChannels); } } } else { // piezo scan double channelSwitchDelay = 0; if (channelMode == MultichannelModes.Keys.VOLUME) { channelSwitchDelay = 500; // estimate channel switching overhead time as 0.5s // actual value will be hardware-dependent } if (channelMode == MultichannelModes.Keys.SLICE_HW) { return numSides * (delayBeforeSide + stackDuration * numChannels); // channelSwitchDelay = 0 } else { return numSides * numChannels * (delayBeforeSide + stackDuration) + (numChannels - 1) * channelSwitchDelay; } } } /** * Compute the timepoint duration in ms. Only difference from computeActualVolumeDuration() * is that it also takes into account the multiple positions, if any. * @return duration in ms */ private double computeTimepointDuration() { AcquisitionSettings acqSettings = getCurrentAcquisitionSettings(); final double volumeDuration = computeActualVolumeDuration(acqSettings); if (acqSettings.useMultiPositions) { try { // use 1.5 seconds motor move between positions // (could be wildly off but was estimated using actual system // and then slightly padded to be conservative to avoid errors // where positions aren't completed in time for next position) return gui_.getPositionList().getNumberOfPositions() * (volumeDuration + 1500 + PanelUtils.getSpinnerFloatValue(positionDelay_)); } catch (MMScriptException ex) { MyDialogUtils.showError(ex, "Error getting position list for multiple XY positions"); } } return volumeDuration; } /** * Compute the volume duration in ms based on controller's timing settings. * Includes time for multiple channels. * @return duration in ms */ private double computeActualVolumeDuration() { return computeActualVolumeDuration(getCurrentAcquisitionSettings()); } /** * Update the displayed volume duration. */ private void updateActualVolumeDurationLabel() { actualVolumeDurationLabel_.setText( NumberUtils.doubleToDisplayString(computeActualVolumeDuration()) + " ms"); } /** * Compute the time lapse duration * @return duration in s */ private double computeActualTimeLapseDuration() { double duration = (getNumTimepoints() - 1) * getTimepointInterval() + computeTimepointDuration()/1000; return duration; } /** * Update the displayed time lapse duration. */ private void updateActualTimeLapseDurationLabel() { String s = ""; double duration = computeActualTimeLapseDuration(); if (duration < 60) { // less than 1 min s += NumberUtils.doubleToDisplayString(duration) + " s"; } else if (duration < 60*60) { // between 1 min and 1 hour s += NumberUtils.doubleToDisplayString(Math.floor(duration/60)) + " min "; s += NumberUtils.doubleToDisplayString(Math.round(duration % 60)) + " s"; } else { // longer than 1 hour s += NumberUtils.doubleToDisplayString(Math.floor(duration/(60*60))) + " hr "; s += NumberUtils.doubleToDisplayString(Math.round((duration % (60*60))/60)) + " min"; } actualTimeLapseDurationLabel_.setText(s); } /** * Computes the reset time of the SPIM cameras set on Devices panel. * Handles single-side operation. * Needed for computing (semi-)optimized slice timing in "easy timing" mode. * @return */ private float computeCameraResetTime() { float resetTime; if (getNumSides() > 1) { resetTime = Math.max(cameras_.computeCameraResetTime(Devices.Keys.CAMERAA), cameras_.computeCameraResetTime(Devices.Keys.CAMERAB)); } else { if (isFirstSideA()) { resetTime = cameras_.computeCameraResetTime(Devices.Keys.CAMERAA); } else { resetTime = cameras_.computeCameraResetTime(Devices.Keys.CAMERAB); } } return resetTime; } /** * Computes the readout time of the SPIM cameras set on Devices panel. * Handles single-side operation. * Needed for computing (semi-)optimized slice timing in "easy timing" mode. * @return */ private float computeCameraReadoutTime() { float readoutTime; CameraModes.Keys camMode = getSPIMCameraMode(); boolean isOverlap = (camMode == CameraModes.Keys.OVERLAP || camMode == CameraModes.Keys.PSEUDO_OVERLAP); if (getNumSides() > 1) { readoutTime = Math.max(cameras_.computeCameraReadoutTime(Devices.Keys.CAMERAA, isOverlap), cameras_.computeCameraReadoutTime(Devices.Keys.CAMERAB, isOverlap)); } else { if (isFirstSideA()) { readoutTime = cameras_.computeCameraReadoutTime(Devices.Keys.CAMERAA, isOverlap); } else { readoutTime = cameras_.computeCameraReadoutTime(Devices.Keys.CAMERAB, isOverlap); } } return readoutTime; } /** * Makes sure that cameras are assigned to the desired sides and display error message * if not (e.g. if single-sided with side B first, then only checks camera for side B) * @return true if cameras assigned, false if not */ private boolean checkCamerasAssigned(boolean showWarnings) { String firstCamera, secondCamera; final boolean firstSideA = isFirstSideA(); if (firstSideA) { firstCamera = devices_.getMMDevice(Devices.Keys.CAMERAA); secondCamera = devices_.getMMDevice(Devices.Keys.CAMERAB); } else { firstCamera = devices_.getMMDevice(Devices.Keys.CAMERAB); secondCamera = devices_.getMMDevice(Devices.Keys.CAMERAA); } if (firstCamera == null) { if (showWarnings) { MyDialogUtils.showError("Please select a valid camera for the first side (Imaging Path " + (firstSideA ? "A" : "B") + ") on the Devices Panel"); } return false; } if (getNumSides()> 1 && secondCamera == null) { if (showWarnings) { MyDialogUtils.showError("Please select a valid camera for the second side (Imaging Path " + (firstSideA ? "B" : "A") + ") on the Devices Panel."); } return false; } return true; } /** * used for updateAcquisitionStatus() calls */ private static enum AcquisitionStatus { NONE, ACQUIRING, WAITING, DONE, } private void updateAcquisitionStatus(AcquisitionStatus phase) { updateAcquisitionStatus(phase, 0); } private void updateAcquisitionStatus(AcquisitionStatus phase, int secsToNextAcquisition) { String text = ""; switch(phase) { case NONE: text = "No acquisition in progress."; break; case ACQUIRING: text = "Acquiring time point " + NumberUtils.intToDisplayString(numTimePointsDone_) + " of " + NumberUtils.intToDisplayString(getNumTimepoints()); // TODO make sure the number of timepoints can't change during an acquisition // (or maybe we make a hidden feature where the acquisition can be terminated by changing) break; case WAITING: text = "Next timepoint (" + NumberUtils.intToDisplayString(numTimePointsDone_+1) + " of " + NumberUtils.intToDisplayString(getNumTimepoints()) + ") in " + NumberUtils.intToDisplayString(secsToNextAcquisition) + " s."; break; case DONE: text = "Acquisition finished with " + NumberUtils.intToDisplayString(numTimePointsDone_) + " time points."; break; default: break; } acquisitionStatusLabel_.setText(text); } /** * call setEnabled(boolean) on all components in list * @param components * @param enabled */ private static void componentsSetEnabled(JComponent[] components, boolean enabled) { for (JComponent c : components) { c.setEnabled(enabled); } } /** * call setEnabled(boolean) on all components in frame/panel * @param panel * @param enabled */ private static void componentsSetEnabled(Container container, boolean enabled) { for (Component comp : container.getComponents()) { comp.setEnabled(enabled); } } /** * @return pathname on filesystem to last completed acquisition * (even if it was stopped pre-maturely) */ public String getPathToLastAcquisition() { return pathToLastAcquisition_; } /** * @return true if an acquisition is currently underway */ public boolean isAcquisitionRunning() { return acquisitionRunning_.get(); } /** * Stops the acquisition by setting an Atomic boolean indicating that we should * halt. Does nothing if an acquisition isn't running. */ public void stopAcquisition() { if (isAcquisitionRunning()) { cancelAcquisition_.set(true); } } /** * Implementation of acquisition that orchestrates image * acquisition itself rather than using the acquisition engine. * * This methods is public so that the ScriptInterface can call it * Please do not access this yourself directly, instead use the API, e.g. * import org.micromanager.asidispim.api.*; * ASIdiSPIMInterface diSPIM = new ASIdiSPIMImplementation(); * diSPIM.runAcquisition(); */ public void runAcquisition() { class acqThread extends Thread { acqThread(String threadName) { super(threadName); } @Override public void run() { ReportingUtils.logDebugMessage("User requested start of diSPIM acquisition."); cancelAcquisition_.set(false); acquisitionRunning_.set(true); updateStartButton(); boolean success = runAcquisitionPrivate(); if (!success) { ReportingUtils.logError("Fatal error running diSPIM acquisition."); } acquisitionRunning_.set(false); updateStartButton(); } } acqThread acqt = new acqThread("diSPIM Acquisition"); acqt.start(); } private Color getChannelColor(int channelIndex) { return (colors[channelIndex % colors.length]); } /** * Actually runs the acquisition; does the dirty work of setting * up the controller, the circular buffer, starting the cameras, * grabbing the images and putting them into the acquisition, etc. * @return true if ran without any fatal errors. */ private boolean runAcquisitionPrivate() { if (gui_.isAcquisitionRunning()) { MyDialogUtils.showError("An acquisition is already running"); return false; } boolean liveModeOriginally = gui_.isLiveModeOn(); if (liveModeOriginally) { gui_.enableLiveMode(false); } // stop the serial traffic for position updates during acquisition posUpdater_.pauseUpdates(true); // make sure slice timings are up to date // do this automatically; we used to prompt user if they were out of date // do this before getting snapshot of sliceTiming_ in acqSettings recalculateSliceTiming(!minSlicePeriodCB_.isSelected()); AcquisitionSettings acqSettings = getCurrentAcquisitionSettings(); double volumeDuration = computeActualVolumeDuration(acqSettings); double timepointDuration = computeTimepointDuration(); long timepointIntervalMs = Math.round(acqSettings.timepointInterval*1000); // use hardware timing if < 1 second between timepoints // experimentally need ~0.5 sec to set up acquisition, this gives a bit of cushion // cannot do this in getCurrentAcquisitionSettings because of mutually recursive // call with computeActualVolumeDuration() if ( acqSettings.numTimepoints > 1 && timepointIntervalMs < (timepointDuration + 750) && !acqSettings.isStageScanning) { acqSettings.hardwareTimepoints = true; } if (acqSettings.useMultiPositions) { if (acqSettings.hardwareTimepoints || ((acqSettings.numTimepoints > 1) && (timepointIntervalMs < timepointDuration*1.2))) { // change to not hardwareTimepoints and warn user // but allow acquisition to continue acqSettings.hardwareTimepoints = false; MyDialogUtils.showError("Timepoint interval may not be sufficient " + "depending on actual time required to change positions. " + "Proceed at your own risk."); } } // get MM device names for first/second cameras to acquire String firstCamera, secondCamera; boolean firstSideA = acqSettings.firstSideIsA; if (firstSideA) { firstCamera = devices_.getMMDevice(Devices.Keys.CAMERAA); secondCamera = devices_.getMMDevice(Devices.Keys.CAMERAB); } else { firstCamera = devices_.getMMDevice(Devices.Keys.CAMERAB); secondCamera = devices_.getMMDevice(Devices.Keys.CAMERAA); } boolean sideActiveA, sideActiveB; boolean twoSided = acqSettings.numSides > 1; if (twoSided) { sideActiveA = true; sideActiveB = true; } else { secondCamera = null; if (firstSideA) { sideActiveA = true; sideActiveB = false; } else { sideActiveA = false; sideActiveB = true; } } boolean usingDemoCam = (devices_.getMMDeviceLibrary(Devices.Keys.CAMERAA).equals(Devices.Libraries.DEMOCAM) && sideActiveA) || (devices_.getMMDeviceLibrary(Devices.Keys.CAMERAB).equals(Devices.Libraries.DEMOCAM) && sideActiveB); int nrSides = acqSettings.numSides; int nrSlices = acqSettings.numSlices; int nrChannels = acqSettings.numChannels; // set up channels int nrChannelsSoftware = nrChannels; // how many times we trigger the controller int nrSlicesSoftware = nrSlices; String originalChannelConfig = ""; boolean changeChannelPerVolumeSoftware = false; MultichannelModes.Keys channelMode = acqSettings.channelMode; if (acqSettings.useChannels) { if (nrChannels < 1) { MyDialogUtils.showError("\"Channels\" is checked, but no channels are selected"); return false; } // get current channel so that we can restore it, then set channel appropriately originalChannelConfig = multiChannelPanel_.getCurrentConfig(); switch (channelMode) { case VOLUME: changeChannelPerVolumeSoftware = true; multiChannelPanel_.initializeChannelCycle(); break; case VOLUME_HW: case SLICE_HW: boolean success = controller_.setupHardwareChannelSwitching(acqSettings); if (!success) { MyDialogUtils.showError("Couldn't set up slice hardware channel switching."); return false; } nrChannelsSoftware = 1; nrSlicesSoftware = nrSlices * nrChannels; break; default: MyDialogUtils.showError("Unsupported multichannel mode \"" + channelMode.toString() + "\""); return false; } } // set up XY positions int nrPositions = 1; PositionList positionList = new PositionList(); if (acqSettings.useMultiPositions) { try { positionList = gui_.getPositionList(); nrPositions = positionList.getNumberOfPositions(); } catch (MMScriptException ex) { MyDialogUtils.showError(ex, "Error getting position list for multiple XY positions"); } if (nrPositions < 1) { MyDialogUtils.showError("\"Positions\" is checked, but no positions are in position list"); return false; } } // make sure we have cameras selected if (!checkCamerasAssigned(true)) { return false; } float cameraReadoutTime = computeCameraReadoutTime(); double exposureTime = acqSettings.sliceTiming.cameraExposure; boolean save = saveCB_.isSelected(); boolean singleTimePointViewers = separateTimePointsCB_.isSelected(); String rootDir = rootField_.getText(); int nrRepeats; // how many acquisition windows to open int nrFrames; // how many Micro-manager "frames" = time points to take if (singleTimePointViewers) { nrFrames = 1; nrRepeats = acqSettings.numTimepoints; } else { nrFrames = acqSettings.numTimepoints; nrRepeats = 1; } AcquisitionModes.Keys spimMode = acqSettings.spimMode; boolean autoShutter = core_.getAutoShutter(); boolean shutterOpen = false; // will read later String originalCamera = core_.getCameraDevice(); // more sanity checks // make sure stage scan is supported if selected if (acqSettings.isStageScanning) { if (!devices_.isTigerDevice(Devices.Keys.XYSTAGE) || !props_.hasProperty(Devices.Keys.XYSTAGE, Properties.Keys.STAGESCAN_NUMLINES)) { MyDialogUtils.showError("Must have stage with scan-enabled firmware for stage scanning."); return false; } } double sliceDuration = acqSettings.sliceTiming.sliceDuration; if (exposureTime + cameraReadoutTime > sliceDuration) { // should only only possible to mess this up using advanced timing settings // or if there are errors in our own calculations MyDialogUtils.showError("Exposure time of " + exposureTime + " is longer than time needed for a line scan with " + " readout time of " + cameraReadoutTime + "\n" + "This will result in dropped frames. " + "Please change input"); return false; } // if we want to do hardware timepoints make sure there's not a problem // lots of different situations where hardware timepoints can't be used... if (acqSettings.hardwareTimepoints) { if (acqSettings.useChannels && channelMode == MultichannelModes.Keys.VOLUME_HW) { // both hardware time points and volume channel switching use SPIMNumRepeats property MyDialogUtils.showError("Cannot use hardware time points (small time point interval)" + " with hardware channel switching volume-by-volume."); return false; } if (acqSettings.isStageScanning) { // stage scanning needs to be triggered for each time point MyDialogUtils.showError("Cannot use hardware time points (small time point interval)" + " with stage scanning."); return false; } if (singleTimePointViewers) { MyDialogUtils.showError("Cannot use hardware time points (small time point interval)" + " with separate viewers/file for each time point."); return false; } if (acqSettings.useAutofocus) { MyDialogUtils.showError("Cannot use hardware time points (small time point interval)" + " with autofocus during acquisition."); return false; } if (acqSettings.useChannels && acqSettings.channelMode == MultichannelModes.Keys.VOLUME) { MyDialogUtils.showError("Cannot use hardware time points (small time point interval)" + " with software channels (need to use PLogic channel switching)."); return false; } if (spimMode == AcquisitionModes.Keys.NO_SCAN) { MyDialogUtils.showError("Cannot do timepoints when no scan mode is used." + " Use the number of slices to set the number of images to acquire."); return false; } } if (acqSettings.useChannels && acqSettings.channelMode == MultichannelModes.Keys.VOLUME_HW && acqSettings.numSides < 2) { MyDialogUtils.showError("Cannot do PLogic channel switching of volume when only one" + " side is selected. Pester the developers if you need this."); return false; } // make sure we aren't trying to collect timepoints faster than we can if (!acqSettings.useMultiPositions && acqSettings.numTimepoints > 1) { if (timepointIntervalMs < volumeDuration) { MyDialogUtils.showError("Time point interval shorter than" + " the time to collect a single volume.\n"); return false; } } if (nrRepeats > 10 && separateTimePointsCB_.isSelected()) { if (!MyDialogUtils.getConfirmDialogResult( "This will generate " + nrRepeats + " separate windows. " + "Do you really want to proceed?", JOptionPane.OK_CANCEL_OPTION)) { return false; } } // Autofocus settings; only used if acqSettings.useAutofocus is true boolean autofocusAtT0 = false; int autofocusEachNFrames = 10; String autofocusChannel = ""; if (acqSettings.useAutofocus) { autofocusAtT0 = prefs_.getBoolean(MyStrings.PanelNames.AUTOFOCUS.toString(), Properties.Keys.PLUGIN_AUTOFOCUS_ACQBEFORESTART, false); autofocusEachNFrames = props_.getPropValueInteger(Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_AUTOFOCUS_EACHNIMAGES); autofocusChannel = props_.getPropValueString(Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_AUTOFOCUS_CHANNEL); // double-check that selected channel is valid String channelGroup = props_.getPropValueString(Devices.Keys.PLUGIN, Properties.Keys.PLUGIN_MULTICHANNEL_GROUP); StrVector channels = gui_.getMMCore().getAvailableConfigs(channelGroup); boolean found = false; for (String channel : channels) { if (channel.equals(autofocusChannel)) { found = true; break; } } if (!found) { MyDialogUtils.showError("Invalid autofocus channel selected on autofocus tab."); return false; } } // it appears the circular buffer, which is used by both cameras, can only have one // image size setting => we require same image height and width for second camera if two-sided if (twoSided) { try { Rectangle roi_1 = core_.getROI(firstCamera); Rectangle roi_2 = core_.getROI(secondCamera); if (roi_1.width != roi_2.width || roi_1.height != roi_2.height) { MyDialogUtils.showError("Camera ROI height and width must be equal because of Micro-Manager's circular buffer"); return false; } } catch (Exception ex) { MyDialogUtils.showError(ex, "Problem getting camera ROIs"); } } // seems to have a problem if the core's camera has been set to some other // camera before we start doing things, so set to a SPIM camera try { core_.setCameraDevice(firstCamera); } catch (Exception ex) { MyDialogUtils.showError(ex, "could not set camera"); } // empty out circular buffer try { core_.clearCircularBuffer(); } catch (Exception ex) { MyDialogUtils.showError(ex, "Error emptying out the circular buffer"); return false; } // initialize stage scanning so we can restore state Point2D.Double xyPosUm = new Point2D.Double(); float origXSpeed = 1f; // don't want 0 in case something goes wrong if (acqSettings.isStageScanning) { try { xyPosUm = core_.getXYStagePosition(devices_.getMMDevice(Devices.Keys.XYSTAGE)); origXSpeed = props_.getPropValueFloat(Devices.Keys.XYSTAGE, Properties.Keys.STAGESCAN_MOTOR_SPEED); } catch (Exception ex) { MyDialogUtils.showError("Could not get XY stage position for stage scan initialization"); return false; } } cameras_.setSPIMCamerasForAcquisition(true); numTimePointsDone_ = 0; // force saving as image stacks, not individual files // implementation assumes just two options, either // TaggedImageStorageDiskDefault.class or TaggedImageStorageMultipageTiff.class boolean separateImageFilesOriginally = ImageUtils.getImageStorageClass().equals(TaggedImageStorageDiskDefault.class); ImageUtils.setImageStorageClass(TaggedImageStorageMultipageTiff.class); // Set up controller SPIM parameters (including from Setup panel settings) // want to do this, even with demo cameras, so we can test everything else if (!controller_.prepareControllerForAquisition(acqSettings)) { return false; } boolean nonfatalError = false; long acqButtonStart = System.currentTimeMillis(); // do not want to return from within this loop => throw exception instead // loop is executed once per acquisition (i.e. once if separate viewers isn't selected) long repeatStart = System.currentTimeMillis(); for (int tp = 0; tp < nrRepeats; tp++) { // handle intervals between (software-timed) repeats // only applies when doing separate viewers for each timepoint // and have multiple timepoints long repeatNow = System.currentTimeMillis(); long repeatdelay = repeatStart + tp * timepointIntervalMs - repeatNow; while (repeatdelay > 0 && !cancelAcquisition_.get()) { updateAcquisitionStatus(AcquisitionStatus.WAITING, (int) (repeatdelay / 1000)); long sleepTime = Math.min(1000, repeatdelay); try { Thread.sleep(sleepTime); } catch (InterruptedException e) { ReportingUtils.showError(e); } repeatNow = System.currentTimeMillis(); repeatdelay = repeatStart + tp * timepointIntervalMs - repeatNow; } BlockingQueue<TaggedImage> bq = new LinkedBlockingQueue<TaggedImage>(10); String acqName; if (singleTimePointViewers) { acqName = gui_.getUniqueAcquisitionName(prefixField_.getText() + "_" + tp); } else { acqName = gui_.getUniqueAcquisitionName(prefixField_.getText()); } try { // check for stop button before each acquisition if (cancelAcquisition_.get()) { throw new IllegalMonitorStateException("User stopped the acquisition"); } ReportingUtils.logMessage("diSPIM plugin starting acquisition " + acqName); if (spimMode == AcquisitionModes.Keys.NO_SCAN && ! singleTimePointViewers) { // swap nrFrames and nrSlices gui_.openAcquisition(acqName, rootDir, nrSlices, nrSides * nrChannels, nrFrames, nrPositions, true, save); } else { gui_.openAcquisition(acqName, rootDir, nrFrames, nrSides * nrChannels, nrSlices, nrPositions, true, save); } core_.setExposure(firstCamera, exposureTime); if (twoSided) { core_.setExposure(secondCamera, exposureTime); } // build metadata for MultiViewRegistration plugin String viewString = ""; final String SEPARATOR = "_"; // set up channels (side A/B is treated as channel too) if (acqSettings.useChannels) { ChannelSpec[] channels = multiChannelPanel_.getUsedChannels(); for (int i = 0; i < channels.length; i++) { String chName = "-" + channels[i].config_; // same algorithm for channel index vs. specified channel and side as below int channelIndex = i; if (twoSided) { channelIndex *= 2; } gui_.setChannelName(acqName, channelIndex, firstCamera + chName); gui_.setChannelColor(acqName, channelIndex, getChannelColor(channelIndex)); viewString += NumberUtils.intToDisplayString(0) + SEPARATOR; if (twoSided) { gui_.setChannelName(acqName, channelIndex + 1, secondCamera + chName); gui_.setChannelColor(acqName, channelIndex + 1, getChannelColor(channelIndex + 1)); viewString += NumberUtils.intToDisplayString(90) + SEPARATOR; } } } else { gui_.setChannelName(acqName, 0, firstCamera); gui_.setChannelColor(acqName, 0, getChannelColor(0)); viewString += NumberUtils.intToDisplayString(0) + SEPARATOR; if (twoSided) { gui_.setChannelName(acqName, 1, secondCamera); gui_.setChannelColor(acqName, 1, getChannelColor(1)); viewString += NumberUtils.intToDisplayString(90) + SEPARATOR; } } // strip last separators: viewString = viewString.substring(0, viewString.length() - 1); // initialize acquisition gui_.initializeAcquisition(acqName, (int) core_.getImageWidth(), (int) core_.getImageHeight(), (int) core_.getBytesPerPixel(), (int) core_.getImageBitDepth()); // These metadata have to added after initialization, otherwise they will not be shown?! gui_.setAcquisitionProperty(acqName, "NumberOfSides", NumberUtils.doubleToDisplayString(acqSettings.numSides)); gui_.setAcquisitionProperty(acqName, "FirstSide", acqSettings.firstSideIsA ? "A" : "B"); gui_.setAcquisitionProperty(acqName, "SlicePeriod_ms", actualSlicePeriodLabel_.getText()); gui_.setAcquisitionProperty(acqName, "LaserExposure_ms", NumberUtils.doubleToDisplayString(acqSettings.desiredLightExposure)); gui_.setAcquisitionProperty(acqName, "VolumeDuration", actualVolumeDurationLabel_.getText()); gui_.setAcquisitionProperty(acqName, "SPIMmode", spimMode.toString()); // Multi-page TIFF saving code wants this one (cameras are all 16-bits, so not much reason for anything else) gui_.setAcquisitionProperty(acqName, "PixelType", "GRAY16"); gui_.setAcquisitionProperty(acqName, "z-step_um", NumberUtils.doubleToDisplayString(acqSettings.stepSizeUm)); // Properties for use by MultiViewRegistration plugin // Format is: x_y_z, set to 1 if we should rotate around this axis. gui_.setAcquisitionProperty(acqName, "MVRotationAxis", "0_1_0"); gui_.setAcquisitionProperty(acqName, "MVRotations", viewString); // get circular buffer ready // do once here but not per-trigger; need to ensure ROI changes registered core_.initializeCircularBuffer(); // TODO: use new acquisition interface that goes through the pipeline //gui_.setAcquisitionAddImageAsynchronous(acqName); MMAcquisition acq = gui_.getAcquisition(acqName); // patterned after implementation in MMStudio.java pathToLastAcquisition_ = acq.getImageCache().getDiskLocation(); // Dive into MM internals since script interface does not support pipelines ImageCache imageCache = acq.getImageCache(); VirtualAcquisitionDisplay vad = acq.getAcquisitionWindow(); imageCache.addImageCacheListener(vad); // Start pumping images into the ImageCache DefaultTaggedImageSink sink = new DefaultTaggedImageSink(bq, imageCache); sink.start(); // Loop over all the times we trigger the controller's acquisition // remember acquisition start time for software-timed timepoints // For hardware-timed timepoints we only trigger the controller once long acqStart = System.currentTimeMillis(); for (int timePoint = 0; timePoint < nrFrames; timePoint++) { // handle intervals between (software-timed) time points // when we are within the same acquisition // (if separate viewer is selected then nothing bad happens here // but waiting during interval handled elsewhere) long acqNow = System.currentTimeMillis(); long delay = acqStart + timePoint * timepointIntervalMs - acqNow; while (delay > 0 && !cancelAcquisition_.get()) { updateAcquisitionStatus(AcquisitionStatus.WAITING, (int) (delay / 1000)); long sleepTime = Math.min(1000, delay); Thread.sleep(sleepTime); acqNow = System.currentTimeMillis(); delay = acqStart + timePoint * timepointIntervalMs - acqNow; } // check for stop button before each time point if (cancelAcquisition_.get()) { throw new IllegalMonitorStateException("User stopped the acquisition"); } // this is where we autofocus if requested if (acqSettings.useAutofocus) { // Note that we will not autofocus as expected when using hardware // timing. Seems OK, since hardware timing will result in short // acquisition times that do not need autofocus. We have already // ensured that we aren't doing both if ( (autofocusAtT0 && timePoint == 0) || ( (timePoint > 0) && (timePoint % autofocusEachNFrames == 0 ) ) ) { multiChannelPanel_.selectChannel(autofocusChannel); if (sideActiveA) { AutofocusUtils.FocusResult score = autofocus_.runFocus( this, Devices.Sides.A, false, sliceTiming_, false, false); updateCalibrationOffset(Devices.Sides.A, score); } if (sideActiveB) { AutofocusUtils.FocusResult score = autofocus_.runFocus( this, Devices.Sides.B, false, sliceTiming_, false, false); updateCalibrationOffset(Devices.Sides.B, score); } // Restore settings of the controller controller_.prepareControllerForAquisition(acqSettings); if (acqSettings.useChannels && acqSettings.channelMode != MultichannelModes.Keys.VOLUME) { controller_.setupHardwareChannelSwitching(acqSettings); } } } numTimePointsDone_++; updateAcquisitionStatus(AcquisitionStatus.ACQUIRING); // loop over all positions for (int positionNum = 0; positionNum < nrPositions; positionNum++) { if (acqSettings.useMultiPositions) { // make sure user didn't stop things if (cancelAcquisition_.get()) { throw new IllegalMonitorStateException("User stopped the acquisition"); } // between positions move stage fast // this will clobber stage scanning setting so need to restore it float scanXSpeed = 1f; if (acqSettings.isStageScanning) { scanXSpeed = props_.getPropValueFloat(Devices.Keys.XYSTAGE, Properties.Keys.STAGESCAN_MOTOR_SPEED); props_.setPropValue(Devices.Keys.XYSTAGE, Properties.Keys.STAGESCAN_MOTOR_SPEED, origXSpeed); } // blocking call; will wait for stages to move MultiStagePosition.goToPosition(positionList.getPosition(positionNum), core_); // restore speed for stage scanning if (acqSettings.isStageScanning) { props_.setPropValue(Devices.Keys.XYSTAGE, Properties.Keys.STAGESCAN_MOTOR_SPEED, scanXSpeed); } // wait any extra time the user requests Thread.sleep(Math.round(PanelUtils.getSpinnerFloatValue(positionDelay_))); } if (acqSettings.hardwareTimepoints) { nrSlicesSoftware *= acqSettings.numTimepoints; } // loop over all the times we trigger the controller for (int channelNum = 0; channelNum < nrChannelsSoftware; channelNum++) { try { // deal with shutter before starting acquisition shutterOpen = core_.getShutterOpen(); if (autoShutter) { core_.setAutoShutter(false); if (!shutterOpen) { core_.setShutterOpen(true); } } // start the cameras core_.startSequenceAcquisition(firstCamera, nrSlicesSoftware, 0, true); if (twoSided) { core_.startSequenceAcquisition(secondCamera, nrSlicesSoftware, 0, true); } // deal with channel if needed (hardware channel switching doesn't happen here) if (changeChannelPerVolumeSoftware) { multiChannelPanel_.selectNextChannel(); } // trigger the state machine on the controller // do this even with demo cameras to test everything else boolean success = controller_.triggerControllerStartAcquisition( spimMode, firstSideA); if (!success) { throw new Exception("Controller triggering not successful"); } ReportingUtils.logDebugMessage("Starting time point " + (timePoint+1) + " of " + nrFrames + " with (software) channel number " + channelNum); // Wait for first image to create ImageWindow, so that we can be sure about image size // Do not actually grab first image here, just make sure it is there long start = System.currentTimeMillis(); long now = start; long timeout; // wait 5 seconds for first image to come timeout = Math.max(5000, Math.round(1.2*volumeDuration)); while (core_.getRemainingImageCount() == 0 && (now - start < timeout) && !cancelAcquisition_.get()) { now = System.currentTimeMillis(); Thread.sleep(5); } if (now - start >= timeout) { throw new Exception("Camera did not send first image within a reasonable time"); } // grab all the images from the cameras, put them into the acquisition int[] frNumber = new int[nrChannels*2]; // keep track of how many frames we have received for each "channel" (MM channel is our channel * 2 for the 2 cameras) int[] cameraFrNumber = new int[2]; // keep track of how many frames we have received from the camera int[] tpNumber = new int[nrChannels*2]; // keep track of which timepoint we are on boolean done = false; long timeout2; // how long to wait between images before timing out timeout2 = Math.max(2000, Math.round(5*sliceDuration)); start = System.currentTimeMillis(); long last = start; try { while ((core_.getRemainingImageCount() > 0 || core_.isSequenceRunning(firstCamera) || (twoSided && core_.isSequenceRunning(secondCamera))) && !done) { now = System.currentTimeMillis(); if (core_.getRemainingImageCount() > 0) { // we have an image to grab TaggedImage timg = core_.popNextTaggedImage(); String camera = (String) timg.tags.get("Camera"); // figure out which channel index the acquisition is using int cameraIndex = camera.equals(firstCamera) ? 0: 1; int channelIndex; switch (channelMode) { case NONE: case VOLUME: channelIndex = channelNum; break; case VOLUME_HW: channelIndex = cameraFrNumber[cameraIndex] / nrSlices; // want quotient only break; case SLICE_HW: channelIndex = cameraFrNumber[cameraIndex] % nrChannels; // want modulo arithmetic break; default: // should never get here throw new Exception("Undefined channel mode"); } // 2nd camera always gets odd channel index // second side always comes after first side if (twoSided) { channelIndex *= 2; } channelIndex += cameraIndex; int actualTimePoint = timePoint; if (acqSettings.hardwareTimepoints) { actualTimePoint = tpNumber[channelIndex]; } // add image to acquisition if (spimMode == AcquisitionModes.Keys.NO_SCAN && ! singleTimePointViewers) { // create time series for no scan addImageToAcquisition(acqName, frNumber[channelIndex], channelIndex, actualTimePoint, positionNum, now - acqStart, timg, bq); } else { // standard, create Z-stacks addImageToAcquisition(acqName, actualTimePoint, channelIndex, frNumber[channelIndex], positionNum, now - acqStart, timg, bq); } // update our counters frNumber[channelIndex]++; cameraFrNumber[cameraIndex]++; // if hardware timepoints then we only send one trigger // and we have to manually keep track of which timepoint we are on if (acqSettings.hardwareTimepoints && frNumber[channelIndex] >= nrSlices) { frNumber[channelIndex] = 0; tpNumber[channelIndex]++; } last = now; // keep track of last image timestamp } else { // no image ready yet done = cancelAcquisition_.get(); Thread.sleep(1); if (now - last >= timeout2) { ReportingUtils.logError("Camera did not send all expected images within" + " a reasonable period for timepoint " + (timePoint+1) + ". Continuing anyway."); nonfatalError = true; done = true; } } } // update count if we stopped in the middle if (cancelAcquisition_.get()) { numTimePointsDone_ } // if we are using demo camera then add some extra time to let controller finish // since we got images without waiting for controller to actually send triggers if (usingDemoCam) { Thread.sleep(200); // for serial communication overhead Thread.sleep((long)volumeDuration/nrChannelsSoftware); // estimate the time per channel, not ideal in case of software channel switching } } catch (InterruptedException iex) { MyDialogUtils.showError(iex); } if (acqSettings.hardwareTimepoints) { break; // only trigger controller once } } catch (Exception ex) { MyDialogUtils.showError(ex); } finally { // cleanup at the end of each time we trigger the controller // put shutter back to original state core_.setShutterOpen(shutterOpen); core_.setAutoShutter(autoShutter); // make sure cameras aren't running anymore if (core_.isSequenceRunning(firstCamera)) { core_.stopSequenceAcquisition(firstCamera); } if (twoSided && core_.isSequenceRunning(secondCamera)) { core_.stopSequenceAcquisition(secondCamera); } } } } if (acqSettings.hardwareTimepoints) { break; } } } catch (IllegalMonitorStateException ex) { // do nothing, the acquisition was simply halted during its operation } catch (MMScriptException mex) { MyDialogUtils.showError(mex); } catch (Exception ex) { MyDialogUtils.showError(ex); } finally { // end of this acquisition (could be about to restart if separate viewers) try { bq.put(TaggedImageQueue.POISON); // TODO: evaluate closeAcquisition call // at the moment, the Micro-Manager api has a bug that causes // a closed acquisition not be really closed, causing problems // when the user closes a window of the previous acquisition // changed r14705 (2014-11-24) // gui_.closeAcquisition(acqName); ReportingUtils.logMessage("diSPIM plugin acquisition " + acqName + " took: " + (System.currentTimeMillis() - acqButtonStart) + "ms"); } catch (Exception ex) { // exception while stopping sequence acquisition, not sure what to do... MyDialogUtils.showError(ex, "Problem while finsihing acquisition"); } } } // cleanup after end of all acquisitions // TODO be more careful and always do these if we actually started acquisition, // even if exception happened // restore camera try { core_.setCameraDevice(originalCamera); } catch (Exception ex) { MyDialogUtils.showError("Could not restore camera after acquisition"); } // reset channel to original if we clobbered it if (acqSettings.useChannels) { multiChannelPanel_.setConfig(originalChannelConfig); } // clean up controller settings after acquisition // want to do this, even with demo cameras, so we can test everything else // TODO figure out if we really want to return piezos to 0 position (maybe center position, // maybe not at all since we move when we switch to setup tab, something else??) controller_.cleanUpControllerAfterAcquisition(acqSettings.numSides, acqSettings.firstSideIsA, true); // if we did stage scanning restore its position and speed if (acqSettings.isStageScanning) { try { core_.setXYPosition(devices_.getMMDevice(Devices.Keys.XYSTAGE), xyPosUm.x, xyPosUm.y); props_.setPropValue(Devices.Keys.XYSTAGE, Properties.Keys.STAGESCAN_MOTOR_SPEED, origXSpeed); } catch (Exception ex) { MyDialogUtils.showError("Could not restore XY stage position after acquisition"); } } updateAcquisitionStatus(AcquisitionStatus.DONE); posUpdater_.pauseUpdates(false); if (separateImageFilesOriginally) { ImageUtils.setImageStorageClass(TaggedImageStorageDiskDefault.class); } cameras_.setSPIMCamerasForAcquisition(false); if (liveModeOriginally) { gui_.enableLiveMode(true); } if (nonfatalError) { MyDialogUtils.showError("Missed some images during acquisition, see core log for details"); } return true; } @Override public void saveSettings() { // save controller settings props_.setPropValue(Devices.Keys.PIEZOA, Properties.Keys.SAVE_CARD_SETTINGS, Properties.Values.DO_SSZ, true); props_.setPropValue(Devices.Keys.PIEZOB, Properties.Keys.SAVE_CARD_SETTINGS, Properties.Values.DO_SSZ, true); props_.setPropValue(Devices.Keys.GALVOA, Properties.Keys.SAVE_CARD_SETTINGS, Properties.Values.DO_SSZ, true); props_.setPropValue(Devices.Keys.GALVOB, Properties.Keys.SAVE_CARD_SETTINGS, Properties.Values.DO_SSZ, true); props_.setPropValue(Devices.Keys.PLOGIC, Properties.Keys.SAVE_CARD_SETTINGS, Properties.Values.DO_SSZ, true); } /** * Gets called when this tab gets focus. Refreshes values from properties. */ @Override public void gotSelected() { // TODO figure out why posUpdater_ is paused and then unpaused here posUpdater_.pauseUpdates(true); props_.callListeners(); // old joystick associations were cleared when leaving // last tab so only do it if joystick settings need to be applied if (navigationJoysticksCB_.isSelected()) { updateJoysticks(); } sliceFrameAdvanced_.setVisible(advancedSliceTimingCB_.isSelected()); posUpdater_.pauseUpdates(false); } /** * called when tab looses focus. */ @Override public void gotDeSelected() { sliceFrameAdvanced_.setVisible(false); saveSettings(); } @Override public void devicesChangedAlert() { devices_.callListeners(); } /** * Gets called when enclosing window closes */ @Override public void windowClosing() { sliceFrameAdvanced_.savePosition(); sliceFrameAdvanced_.dispose(); } @Override public void refreshDisplay() { updateDurationLabels(); } private void setRootDirectory(JTextField rootField) { File result = FileDialogs.openDir(null, "Please choose a directory root for image data", MMStudio.MM_DATA_SET); if (result != null) { rootField.setText(result.getAbsolutePath()); } } /** * The basic method for adding images to an existing data set. If the * acquisition was not previously initialized, it will attempt to initialize * it from the available image data. This version uses a blocking queue and is * much faster than the one currently implemented in the ScriptInterface * Eventually, this function should be replaced by the ScriptInterface version * of the same. * @param name - named acquisition to add image to * @param frame - frame nr at which to insert the image * @param channel - channel at which to insert image * @param slice - (z) slice at which to insert image * @param position - position at which to insert image * @param ms - Time stamp to be added to the image metadata * @param taggedImg - image + metadata to be added * @param bq - Blocking queue to which the image should be added. This queue * should be hooked up to the ImageCache belonging to this acquisitions * @throws java.lang.InterruptedException * @throws org.micromanager.utils.MMScriptException */ public void addImageToAcquisition(String name, int frame, int channel, int slice, int position, long ms, TaggedImage taggedImg, BlockingQueue<TaggedImage> bq) throws MMScriptException, InterruptedException { MMAcquisition acq = gui_.getAcquisition(name); // verify position number is allowed if (acq.getPositions() <= position) { throw new MMScriptException("The position number must not exceed declared" + " number of positions (" + acq.getPositions() + ")"); } // verify that channel number is allowed if (acq.getChannels() <= channel) { throw new MMScriptException("The channel number must not exceed declared" + " number of channels (" + + acq.getChannels() + ")"); } JSONObject tags = taggedImg.tags; if (!acq.isInitialized()) { throw new MMScriptException("Error in the ASIdiSPIM logic. Acquisition should have been initialized"); } // create required coordinate tags try { MDUtils.setFrameIndex(tags, frame); tags.put(MMTags.Image.FRAME, frame); MDUtils.setChannelIndex(tags, channel); MDUtils.setSliceIndex(tags, slice); MDUtils.setPositionIndex(tags, position); MDUtils.setElapsedTimeMs(tags, ms); MDUtils.setImageTime(tags, MDUtils.getCurrentTime()); MDUtils.setZStepUm(tags, PanelUtils.getSpinnerFloatValue(stepSize_)); if (!tags.has(MMTags.Summary.SLICES_FIRST) && !tags.has(MMTags.Summary.TIME_FIRST)) { // add default setting tags.put(MMTags.Summary.SLICES_FIRST, true); tags.put(MMTags.Summary.TIME_FIRST, false); } if (acq.getPositions() > 1) { // if no position name is defined we need to insert a default one if (tags.has(MMTags.Image.POS_NAME)) { tags.put(MMTags.Image.POS_NAME, "Pos" + position); } } // update frames if necessary if (acq.getFrames() <= frame) { acq.setProperty(MMTags.Summary.FRAMES, Integer.toString(frame + 1)); } } catch (JSONException e) { throw new MMScriptException(e); } bq.put(taggedImg); } public String getSavingDirectoryRoot() { return rootField_.getText(); } public void setSavingDirectoryRoot(String directory) throws ASIdiSPIMException { rootField_.setText(directory); try { rootField_.commitEdit(); } catch (ParseException e) { throw new ASIdiSPIMException(e); } } public String getSavingNamePrefix() { return prefixField_.getText(); } public void setSavingNamePrefix(String acqPrefix) throws ASIdiSPIMException { prefixField_.setText(acqPrefix); try { prefixField_.commitEdit(); } catch (ParseException e) { throw new ASIdiSPIMException(e); } } public boolean getSavingSeparateFile() { return separateTimePointsCB_.isSelected(); } public void setSavingSeparateFile(boolean separate) { separateTimePointsCB_.setSelected(separate); } public boolean getSavingSaveWhileAcquiring() { return saveCB_.isSelected(); } public void setSavingSaveWhileAcquiring(boolean save) { saveCB_.setSelected(save); } public org.micromanager.asidispim.Data.AcquisitionModes.Keys getAcquisitionMode() { return (org.micromanager.asidispim.Data.AcquisitionModes.Keys) spimMode_.getSelectedItem(); } public void setAcquisitionMode(org.micromanager.asidispim.Data.AcquisitionModes.Keys mode) { spimMode_.setSelectedItem(mode); } }
package fitnesse.responders.run.slimResponder; import fitnesse.components.CommandRunner; import fitnesse.responders.run.ExecutionLog; import fitnesse.responders.run.TestSummary; import fitnesse.responders.run.TestSystem; import fitnesse.responders.run.TestSystemListener; import fitnesse.slim.SlimClient; import fitnesse.slim.SlimError; import fitnesse.slim.SlimServer; import fitnesse.slim.SlimServerBadResponseException; import fitnesse.slim.SlimService; import fitnesse.slimTables.*; import fitnesse.testutil.MockCommandRunner; import fitnesse.wiki.*; import fitnesse.wikitext.parser.ParsedPage; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.net.ServerSocket; import java.net.SocketException; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Matcher; import java.util.regex.Pattern; public abstract class SlimTestSystem extends TestSystem implements SlimTestContext { public static final String MESSAGE_ERROR = "!error:"; public static final String MESSAGE_FAIL = "!fail:"; public static final SlimTable START_OF_TEST = null; public static final SlimTable END_OF_TEST = null; private CommandRunner slimRunner; private String slimCommand; private SlimClient slimClient; protected Map<String, Object> allInstructionResults = new HashMap<String, Object>(); protected List<SlimTable> allTables = new ArrayList<SlimTable>(); protected List<Object> allInstructions = new ArrayList<Object>(); protected List<SlimTable.Expectation> allExpectations = new ArrayList<SlimTable.Expectation>(); protected List<Object> instructions; private boolean started; protected ReadOnlyPageData testResults; protected TableScanner tableScanner; protected Map<String, Object> instructionResults; protected List<SlimTable> testTables = new ArrayList<SlimTable>(); protected ExceptionList exceptions = new ExceptionList(); private Map<String, String> symbols = new HashMap<String, String>(); protected TestSummary testSummary; private static AtomicInteger slimSocketOffset = new AtomicInteger(0); private int slimSocket; protected final Pattern exceptionMessagePattern = Pattern.compile("message:<<(.*)>>"); private Map<String, ScenarioTable> scenarios = new HashMap<String, ScenarioTable>(); protected List<SlimTable.Expectation> expectations = new ArrayList<SlimTable.Expectation>(); private SlimTableFactory slimTableFactory = new SlimTableFactory(); private ParsedPage preparsedScenarioLibrary; public SlimTestSystem(WikiPage page, TestSystemListener listener) { super(page, listener); testSummary = new TestSummary(0, 0, 0, 0); } public String getSymbol(String symbolName) { return symbols.get(symbolName); } public void setSymbol(String symbolName, String value) { symbols.put(symbolName, value); } public void addScenario(String scenarioName, ScenarioTable scenarioTable) { scenarios.put(scenarioName, scenarioTable); } public ScenarioTable getScenario(String scenarioName) { return scenarios.get(scenarioName); } public void addExpectation(SlimTable.Expectation e) { expectations.add(e); } public boolean isSuccessfullyStarted() { return started; } public void kill() throws IOException { if (slimRunner != null) slimRunner.kill(); if (slimClient != null) slimClient.close(); } String getSlimFlags() { String slimFlags = page.readOnlyData().getVariable("SLIM_FLAGS"); if (slimFlags == null) slimFlags = ""; return slimFlags; } protected ExecutionLog createExecutionLog(String classPath, Descriptor descriptor) throws SocketException { String slimFlags = getSlimFlags(); slimSocket = getNextSlimSocket(); String slimArguments = String.format("%s %d", slimFlags, slimSocket); String slimCommandPrefix = buildCommand(descriptor, classPath); slimCommand = String.format("%s %s", slimCommandPrefix, slimArguments); if (fastTest) { slimRunner = new MockCommandRunner(); createSlimService(slimArguments); } else if (manualStart) { slimSocket = getSlimPortBase(); slimRunner = new MockCommandRunner(); } else { slimRunner = new CommandRunner(slimCommand, "", createClasspathEnvironment(classPath)); } return new ExecutionLog(page, slimRunner, descriptor.pageFactory); } public int findFreePort() { int port; try { ServerSocket socket = new ServerSocket(0); port = socket.getLocalPort(); socket.close(); } catch (Exception e) { port = -1; } return port; } public int getNextSlimSocket() { int base; if (System.getProperty("slim.port") != null) { base = Integer.parseInt(System.getProperty("slim.port")); } else { base = getSlimPortBase(); } if (base == 0) { return findFreePort(); } synchronized (slimSocketOffset) { int offset = slimSocketOffset.get(); offset = (offset + 1) % 10; slimSocketOffset.set(offset); return offset + base; } } private int getSlimPortBase() { int base = 8085; try { String slimPort = page.readOnlyData().getVariable("SLIM_PORT"); if (slimPort != null) { int slimPortInt = Integer.parseInt(slimPort); base = slimPortInt; } } catch (Exception e) { } return base; } public void start() throws IOException { slimRunner.asynchronousStart(); slimClient = new SlimClient(determineSlimHost(), slimSocket); try { waitForConnection(); started = true; } catch (SlimError e) { testSystemListener.exceptionOccurred(e); } } String determineSlimHost() { String slimHost = page.readOnlyData().getVariable("SLIM_HOST"); return slimHost == null ? "localhost" : slimHost; } public String getCommandLine() { return slimCommand; } public void bye() throws IOException { slimClient.sendBye(); if (!fastTest && !manualStart) { slimRunner.join(); } if (fastTest) { slimRunner.kill(); } } //For testing only. Makes responder faster. void createSlimService(String args) throws SocketException { while (!tryCreateSlimService(args)) try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } private boolean tryCreateSlimService(String args) throws SocketException { try { SlimService.main(args.trim().split(" ")); return true; } catch (SocketException e) { throw e; } catch (Exception e) { return false; } } void waitForConnection() { while (!isConnected()) try { Thread.sleep(50); } catch (InterruptedException e) { throw new RuntimeException(e); } } private boolean isConnected() { try { slimClient.connect(); return true; } catch (Exception e) { return false; } } public String runTestsAndGenerateHtml(ReadOnlyPageData pageData) throws IOException { initializeTest(); checkForAndReportVersionMismatch(pageData); String html = processAllTablesOnPage(pageData); testComplete(testSummary); return html; } private void initializeTest() { symbols.clear(); scenarios.clear(); testSummary.clear(); allExpectations.clear(); allInstructionResults.clear(); allInstructions.clear(); allTables.clear(); exceptions.resetForNewTest(); } private void checkForAndReportVersionMismatch(ReadOnlyPageData pageData) { double expectedVersionNumber = getExpectedSlimVersion(pageData); double serverVersionNumber = slimClient.getServerVersion(); if (serverVersionNumber == -1000) { exceptions.addException("Sever Not Connected Error", "Server did not respond with a valid version number."); } else { if (serverVersionNumber < expectedVersionNumber) exceptions.addException("Slim Protocol Version Error", String.format("Expected V%s but was V%s", expectedVersionNumber, serverVersionNumber)); } } private double getExpectedSlimVersion(ReadOnlyPageData pageData) { double expectedVersionNumber = SlimClient.MINIMUM_REQUIRED_SLIM_VERSION; String pageSpecificSlimVersion = pageData.getVariable("SLIM_VERSION"); if (pageSpecificSlimVersion != null) { try { double pageSpecificSlimVersionDouble = Double.parseDouble(pageSpecificSlimVersion); expectedVersionNumber = pageSpecificSlimVersionDouble; } catch (NumberFormatException e) { } } return expectedVersionNumber; } protected abstract String createHtmlResults(SlimTable startAfterTable, SlimTable lastWrittenTable); String processAllTablesOnPage(ReadOnlyPageData pageData) throws IOException { tableScanner = scanTheTables(pageData); allTables = createSlimTables(tableScanner); testResults = pageData; boolean runAllTablesAtOnce = false; String htmlResults = ""; if (runAllTablesAtOnce || (allTables.size() == 0)) { htmlResults = processTablesAndGetHtml(allTables, START_OF_TEST, END_OF_TEST); } else { List<SlimTable> oneTableList = new ArrayList<SlimTable>(1); for (int index = 0; index < allTables.size(); index++) { SlimTable theTable = allTables.get(index); SlimTable startWithTable = (index == 0) ? START_OF_TEST : theTable; SlimTable nextTable = (index + 1 < allTables.size()) ? allTables.get(index + 1) : END_OF_TEST; oneTableList.add(theTable); htmlResults += processTablesAndGetHtml(oneTableList, startWithTable, nextTable); oneTableList.clear(); } } return htmlResults; } protected abstract TableScanner scanTheTables(ReadOnlyPageData pageData); private String processTablesAndGetHtml(List<SlimTable> tables, SlimTable startWithTable, SlimTable nextTable) throws IOException, SlimServerBadResponseException { expectations.clear(); testTables = tables; instructions = createInstructions(tables); if (!exceptions.stopTestCalled()) { instructionResults = slimClient.invokeAndGetResponse(instructions); } String html = createHtmlResults(startWithTable, nextTable); acceptOutputFirst(html); // update all lists allExpectations.addAll(expectations); allInstructions.addAll(instructions); allInstructionResults.putAll(instructionResults); return html; } private List<Object> createInstructions(List<SlimTable> tables) { List<Object> instructions = new ArrayList<Object>(); for (SlimTable table : tables) { table.appendInstructions(instructions); } return instructions; } private List<SlimTable> createSlimTables(TableScanner tableScanner) { List<SlimTable> allTables = new LinkedList<SlimTable>(); for (Table table : tableScanner) createSlimTable(allTables, table); return allTables; } private void createSlimTable(List<SlimTable> allTables, Table table) { String tableId = "" + allTables.size(); SlimTable slimTable = slimTableFactory.makeSlimTable(table, tableId, this); if (slimTable != null) { allTables.add(slimTable); } } static String translateExceptionMessage(String exceptionMessage) { String tokens[] = exceptionMessage.split(" "); if (tokens[0].equals("COULD_NOT_INVOKE_CONSTRUCTOR")) return "Could not invoke constructor for " + tokens[1]; else if (tokens[0].equals("NO_METHOD_IN_CLASS")) return String.format("Method %s not found in %s", tokens[1], tokens[2]); else if (tokens[0].equals("NO_CONSTRUCTOR")) return String.format("Could not find constructor for %s", tokens[1]); else if (tokens[0].equals("NO_CONVERTER_FOR_ARGUMENT_NUMBER")) return String.format("No converter for %s", tokens[1]); else if (tokens[0].equals("NO_INSTANCE")) return String.format("The instance %s does not exist", tokens[1]); else if (tokens[0].equals("NO_CLASS")) return String.format("Could not find class %s", tokens[1]); else if (tokens[0].equals("MALFORMED_INSTRUCTION")) return String.format("The instruction %s is malformed", exceptionMessage.substring(exceptionMessage.indexOf(" ") + 1)); return exceptionMessage; } public ReadOnlyPageData getTestResults() { return testResults; } public static String exceptionToString(Throwable e) { StringWriter stringWriter = new StringWriter(); PrintWriter pw = new PrintWriter(stringWriter); e.printStackTrace(pw); return SlimServer.EXCEPTION_TAG + stringWriter.toString(); } public TestSummary getTestSummary() { return testSummary; } protected void evaluateExpectations() { for (SlimTable.Expectation e : expectations) { try { e.evaluateExpectation(instructionResults); } catch (Throwable ex) { exceptions.addException("ABORT", exceptionToString(ex)); exceptionOccurred(ex); } } } protected void evaluateTables() { evaluateExpectations(); for (SlimTable table : testTables) evaluateTable(table); } private void evaluateTable(SlimTable table) { try { table.evaluateReturnValues(instructionResults); testSummary.add(table.getTestSummary()); } catch (Throwable e) { exceptions.addException("ABORT", exceptionToString(e)); exceptionOccurred(e); } } protected void replaceExceptionsWithLinks() { Set<String> resultKeys = instructionResults.keySet(); for (String resultKey : resultKeys) replaceExceptionWithExceptionLink(resultKey); } private void replaceExceptionWithExceptionLink(String resultKey) { Object result = instructionResults.get(resultKey); if (result instanceof String) replaceIfUnignoredException(resultKey, (String) result); } private void replaceIfUnignoredException(String resultKey, String resultString) { if (resultString.indexOf(SlimServer.EXCEPTION_TAG) != -1) { if (shouldReportException(resultKey, resultString)) processException(resultKey, resultString); } } private boolean shouldReportException(String resultKey, String resultString) { for (SlimTable table : testTables) { if (table.shouldIgnoreException(resultKey, resultString)) return false; } return true; } private void processException(String resultKey, String resultString) { testSummary.exceptions++; boolean isStopTestException = resultString.contains(SlimServer.EXCEPTION_STOP_TEST_TAG); if (isStopTestException) { exceptions.setStopTestCalled(); } Matcher exceptionMessageMatcher = exceptionMessagePattern.matcher(resultString); if (exceptionMessageMatcher.find()) { String prefix = (isStopTestException) ? MESSAGE_FAIL : MESSAGE_ERROR; String exceptionMessage = exceptionMessageMatcher.group(1); instructionResults.put(resultKey, prefix + translateExceptionMessage(exceptionMessage)); } else { exceptions.addException(resultKey, resultString); instructionResults.put(resultKey, exceptionResult(resultKey)); } } private String exceptionResult(String resultKey) { return String.format("Exception: <a href=#%s>%s</a>", resultKey, resultKey); } public Map<String, ScenarioTable> getScenarios() { return scenarios; } public static void clearSlimPortOffset() { slimSocketOffset.set(0); } public List<SlimTable> getTestTables() { return allTables; } public List<Object> getInstructions() { return allInstructions; } public Map<String, Object> getInstructionResults() { return allInstructionResults; } public List<SlimTable.Expectation> getExpectations() { return allExpectations; } public ParsedPage getPreparsedScenarioLibrary() { if (preparsedScenarioLibrary == null) { preparsedScenarioLibrary = new ParsedPage(page.readOnlyData().getParsedPage(), getScenarioLibraryContent()); } return preparsedScenarioLibrary; } private String getScenarioLibraryContent() { String content = "!*> Precompiled Libraries\n\n"; content += includeUncleLibraries(); content += "*!\n"; return content; } private String includeUncleLibraries() { String content = ""; List<WikiPage> uncles = PageCrawlerImpl.getAllUncles("ScenarioLibrary", page); Collections.reverse(uncles); for (WikiPage uncle : uncles) content += include(page.getPageCrawler().getFullPath(uncle)); return content; } private String include(WikiPagePath path) { return "!include -c ." + path + "\n"; } }
package jcollado.pw.pimpam.controller; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.Toolbar; import com.mikepenz.materialdrawer.Drawer; import jcollado.pw.pimpam.R; import jcollado.pw.pimpam.model.Database; import jcollado.pw.pimpam.utils.BaseActivity; import jcollado.pw.pimpam.utils.BaseFragment; import jcollado.pw.pimpam.utils.FirebaseModule; import jcollado.pw.pimpam.utils.NavigationDrawer; public class MainActivity extends BaseActivity implements ViewComicFragment.OnFragmentInteractionListener,AddComicFragment.OnFragmentInteractionListener{ Toolbar toolbar; private static Drawer navigationDrawer; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); setNavigationDrawer(); FirebaseModule.getInstance().setConnectionDatabase(); CollectionFragment collectionFragment = CollectionFragment.newInstance(); Database.getInstance().setFragment(collectionFragment); toolbar.setTitle(getString(R.string.seeCollection)); getSupportActionBar().hide(); openFragment(collectionFragment); } public static void openDrawer(){ navigationDrawer.openDrawer(); } private void setNavigationDrawer(){ navigationDrawer = NavigationDrawer.getInstance(this,toolbar).getDrawerBuilder(); } @Override public void onFragmentInteraction(Uri uri) { } public void openFragment(BaseFragment fragment){ getSupportFragmentManager() .beginTransaction() .replace(R.id.container, fragment,"") .commit(); if(navigationDrawer != null){ navigationDrawer.closeDrawer(); } } @Override public void onBackPressed() { if (navigationDrawer.getCurrentSelectedPosition() != 1) { openDrawer(); } else { Intent a = new Intent(Intent.ACTION_MAIN); a.addCategory(Intent.CATEGORY_HOME); a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(a); } } public void mostrarCargando(){ onPreStartConnection(getString(R.string.loading)); } public static Drawer getResult(){ return navigationDrawer; } }
package com.cjpowered.learn.inventory; import java.time.LocalDate; import java.util.Optional; import com.cjpowered.learn.marketing.MarketingInfo; public class StockedItem implements Item { private final int wantOnHand; private final boolean isRestricted; private final int bulkAmt; public StockedItem(int wantOnHand, final boolean isRestricted, final int bulkAmt){ this.wantOnHand = wantOnHand; this.isRestricted = isRestricted; this.bulkAmt = bulkAmt; } @Override public Order createOrder(final LocalDate when, final InventoryDatabase db, final MarketingInfo marketInfo) { final Order maybeOrder; final int onHand = db.onHand(this); int toOrder = 0; final int deficit; final boolean onSale = marketInfo.onSale(this); if (isRestricted){ if(when.getDayOfMonth() != 1){ return new Order(this, 0); } } if (onSale){ deficit = wantOnHand + 20 - onHand; while(toOrder < deficit){ toOrder += bulkAmt; } } else { deficit = wantOnHand - onHand; while(toOrder < deficit){ toOrder += bulkAmt; } } maybeOrder = new Order(this, toOrder); return maybeOrder; } }
package heufybot.modules; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import heufybot.utils.FileUtils; import heufybot.utils.StringUtils; import heufybot.utils.URLUtils; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class WeatherInterface { private final static String APIkey = FileUtils.readFile("data/worldweatheronlineapikey.txt").replaceAll("\n", ""); private final static String APIAddress = "http://api.worldweatheronline.com/free/v1/weather.ashx?"; private final static String web = "http: public String getWeather(float latitude, float longitude) throws ParseException { StringBuilder builder = new StringBuilder(); builder.append(APIAddress); builder.append("q=" + latitude + "," + longitude); builder.append("&key=" + APIkey); builder.append("&format=json"); JSONObject object = getJSON(builder.toString()); System.out.println(builder.toString()); String parsedJSON = parseJSONForWeather(object); if(parsedJSON == null) { return null; } return parsedJSON + " | More info: " + URLUtils.shortenURL(web + latitude + "," + longitude); } public String getForecast(float latitude, float longitude) throws ParseException { StringBuilder builder = new StringBuilder(); builder.append(APIAddress); builder.append("q=" + latitude + "," + longitude); builder.append("&key=" + APIkey); builder.append("&num_of_days=4"); builder.append("&format=json"); JSONObject object = getJSON(builder.toString()); System.out.println(builder.toString()); String parsedJSON = parseJSONForForecast(object); if(parsedJSON == null) { return null; } return parsedJSON; } private String parseJSONForWeather(JSONObject object) { JSONObject data = (JSONObject)object.get("data"); if((JSONArray)data.get("current_condition") == null) { return null; } JSONObject currentCondition = (JSONObject) ((JSONArray)data.get("current_condition")).get(0); String tempC = currentCondition.get("temp_C").toString(); String tempF = currentCondition.get("temp_F").toString(); String windspeedMiles = currentCondition.get("windspeedMiles").toString(); String windspeedKmph = currentCondition.get("windspeedKmph").toString(); String windDir = currentCondition.get("winddir16Point").toString(); String desc = ((JSONObject)((JSONArray)currentCondition.get("weatherDesc")).get(0)).get("value").toString(); String humidity = currentCondition.get("humidity").toString(); return String.format("Current condition (updates every 4 hours) | Temp: %sC/%sF | Weather: %s | Humidity: %s%c | Wind: %s kmph/%smph %s", tempC, tempF, desc, humidity, '%', windspeedKmph, windspeedMiles, windDir); } private String parseJSONForForecast(JSONObject object) { JSONObject data = (JSONObject)object.get("data"); if((JSONArray)data.get("current_condition") == null) { return null; } JSONArray weather = (JSONArray)data.get("weather"); DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd"); DateFormat format2 = new SimpleDateFormat("EEEEEEEE", Locale.US); List<String> days = new ArrayList<String>(); for(int i = 0; i < weather.size(); i++) { JSONObject day = (JSONObject) weather.get(i); Date date; try { date = format1.parse(day.get("date").toString()); } catch (java.text.ParseException e) { date = new Date(); } String dayOfWeek = format2.format(date); String minC = day.get("tempMinC").toString(); String maxC = day.get("tempMaxC").toString(); String minF = day.get("tempMinF").toString(); String maxF = day.get("tempMaxF").toString(); String weatherDescription = ((JSONObject)((JSONArray)day.get("weatherDesc")).get(0)).get("value").toString(); days.add(String.format("%s ~ Low: %sC/%sF | High: %sC/%sF | Weather: %s", dayOfWeek, minC, minF, maxC, maxF, weatherDescription)); } return StringUtils.join(days, " } private JSONObject getJSON(String urlString) throws ParseException { return (JSONObject)new JSONParser().parse(URLUtils.grab(urlString)); } }
package mn.devfest.schedule; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.support.annotation.NonNull; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; /** * Stores and provides the sessions that the user has added to their schedule. * This class must be notified any time a session is added or removed from a user's schedule. * TODO when this class syncs with the API, we should move it to the api package * * @author pfuentes */ public class UserScheduleRepository { private static final String SCHEDULE_ID_STRING_SET_TAG = "SCHEDULE_IDS"; Context mContext; SharedPreferences mSharedPreferences; public UserScheduleRepository (@NonNull Context context){ mContext = context; mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext); } /** * Adds the session with the given ID to the user's schedule * @param sessionId ID of the session to be added */ public void addSession(String sessionId) { ArrayList<String> scheduleIds = getScheduleIdStringSet(); scheduleIds.add(sessionId); setScheduleIdStringSet(scheduleIds); } /** * Removes the session with the given ID from the user's schedule * @param sessionId ID of the session to be removed */ public void removeSession(String sessionId) { //TODO implement } /** * Shares the list of IDs for all of the sessions in the user's schedule * @return List of IDs of the sessions in the user's schedule */ public ArrayList<String> getScheduleIds() { //TODO implement return new ArrayList<>(); //TODO update return statement } /** * Checks if a given session is in the user's schedule * @param sessionId ID of the session to check for inclusion in the list * @return true if the session is in the user's schedule; otherwise false */ public boolean isInSchedule(String sessionId) { //TODO implement return true; //TODO update return statement } private void setScheduleIdStringSet(@NonNull ArrayList<String> scheduleIds) { Set<String> stringSet = new HashSet<>(scheduleIds); SharedPreferences.Editor editor = mSharedPreferences.edit(); editor.putStringSet(SCHEDULE_ID_STRING_SET_TAG, stringSet); editor.commit(); } @NonNull private ArrayList<String> getScheduleIdStringSet() { Set<String> scheduleIdSet = mSharedPreferences.getStringSet(SCHEDULE_ID_STRING_SET_TAG, new HashSet<>()); return new ArrayList<String>(scheduleIdSet); } }
package com.conveyal.r5.speed_test.test; import com.conveyal.r5.profile.entur.util.TimeUtils; import com.csvreader.CsvReader; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; /** * This class is responsible for reading and writing test cases and test case results to CSV files. */ public class CsvFileIO { private static final int NOT_SET = -1; private static final Charset CHARSET_UTF_8 = Charset.forName("UTF-8"); private static final char CSV_DELIMITER = ','; private static boolean printResultsForFirstStrategyRun = true; private final File testCasesFile; private final File expectedResultsFile; private final File expectedResultsOutputFile; public CsvFileIO(File dir, String testSetName) { testCasesFile = new File(dir, testSetName + ".csv"); expectedResultsFile = new File(dir, testSetName + "-expected-results.csv"); expectedResultsOutputFile = new File(dir, testSetName + "-expected-results-out.csv"); } /** * CSV input order matches constructor: * <pre> * id, description,fromPlace,fromLat,fromLon,origin,toPlace,toLat,toLon,destination,transportType,expectedResult * </pre> */ public List<TestCase> readTestCasesFromFile() throws IOException { Map<String, TestCaseResults> expectedResults = readExpectedResultsFromFile(); List<TestCase> testCases = new ArrayList<>(); CsvReader csvReader = new CsvReader(testCasesFile.getAbsolutePath(), CSV_DELIMITER, CHARSET_UTF_8); csvReader.readHeaders(); // Skip header while (csvReader.readRecord()) { if(isCommentOrEmpty(csvReader.getRawRecord())) { continue; } String id = csvReader.get("testCaseId"); TestCase tc = new TestCase( id, TimeUtils.parseHHMM(csvReader.get("departure"), NOT_SET), TimeUtils.parseHHMM(csvReader.get("arrival"), NOT_SET), TimeUtils.parseHHMM(csvReader.get("window"), NOT_SET), csvReader.get("description"), csvReader.get("origin"), csvReader.get("fromPlace"), Double.parseDouble(csvReader.get("fromLat")), Double.parseDouble(csvReader.get("fromLon")), csvReader.get("destination"), csvReader.get("toPlace"), Double.parseDouble(csvReader.get("toLat")), Double.parseDouble(csvReader.get("toLon")), expectedResults.get(id) ); testCases.add(tc); } return testCases; } /** * Write all results to a CSV file. This file can be renamed and used as expected-result input file. */ public void writeResultsToFile(List<TestCase> testCases) { if (!printResultsForFirstStrategyRun || testCases.stream().anyMatch(TestCase::notRun)) { return; } printResultsForFirstStrategyRun = false; try (PrintWriter out = new PrintWriter(expectedResultsOutputFile, CHARSET_UTF_8.name())) { out.println("tcId,transfers,duration,walkDistance,startTime,endTime,details"); for (TestCase tc : testCases) { for (Result result : tc.actualResults()) { out.print(tc.id); out.print(CSV_DELIMITER); out.print(result.transfers); out.print(CSV_DELIMITER); out.print(result.duration); out.print(CSV_DELIMITER); out.print(result.walkDistance); out.print(CSV_DELIMITER); out.print(result.startTime); out.print(CSV_DELIMITER); out.print(result.endTime); out.print(CSV_DELIMITER); out.print(result.details); out.print('\n'); } } out.flush(); System.err.println("\nINFO - New CSV file with results is saved to '" + expectedResultsOutputFile.getAbsolutePath() + "'."); } catch (Exception e) { e.printStackTrace(); } } /* private methods */ private Map<String, TestCaseResults> readExpectedResultsFromFile() throws IOException { if(!expectedResultsFile.exists()) { return Collections.emptyMap(); } Map<String, TestCaseResults> results = new HashMap<>(); CsvReader csvReader = new CsvReader(expectedResultsFile.getAbsolutePath(), CSV_DELIMITER, CHARSET_UTF_8); csvReader.readRecord(); // Skip header while (csvReader.readRecord()) { Result expRes = readExpectedResult(csvReader); results.computeIfAbsent(expRes.testCaseId, TestCaseResults::new).addExpectedResult(expRes); } return results; } private Result readExpectedResult(CsvReader csvReader) throws IOException { return new Result( csvReader.get(0), Integer.parseInt(csvReader.get(1)), Integer.parseInt(csvReader.get(2)), Integer.parseInt(csvReader.get(3)), csvReader.get(4), csvReader.get(5), csvReader.get(6) ); } private boolean isCommentOrEmpty(String line) { return line.startsWith("#") || line.matches("[\\s,;]*"); } }
package net.egordmitriev.cheatsheets.pojo; import java.util.ArrayList; import java.util.List; public class Category extends MatchableModel { public boolean temp; public int id; public String title; public String description; public List<CheatSheet> cheat_sheets; public Category() { } public Category(int id, String title, String description, List<CheatSheet> cheat_sheets) { this.id = id; this.title = title; this.description = description; this.cheat_sheets = cheat_sheets; } public Category(String title, String description, List<CheatSheet> cheat_sheets) { this.title = title; this.description = description; this.cheat_sheets = cheat_sheets; } @Override protected List<String> getSearchableStrings(boolean recursive) { List<String> ret = new ArrayList<String>() {{ add(title); add(description); }}; if (recursive) { for (CheatSheet cheatSheet : cheat_sheets) { ret.addAll(cheatSheet.getSearchableStrings(false)); } } return ret; } public CheatSheet getCheatSheet(int id) { for (CheatSheet cheatSheet : cheat_sheets) { if (cheatSheet.id == id) { return cheatSheet; } } return null; } public static CheatSheet getCheatSheet(int id, List<Category> categories) { for (Category category : categories) { CheatSheet temp = category.getCheatSheet(id); if (temp != null) return temp; } return null; } }
package com.creativemd.ambientsounds; import com.creativemd.ambientsounds.env.AmbientEnv; import com.creativemd.ambientsounds.env.HeightEnv.HeightArea; import com.creativemd.ambientsounds.sound.HeightSound; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraft.world.biome.Biome; public class WeatherSound extends HeightSound { public static enum WeatherType { SUNNY { @Override public boolean isWeather(World world, BlockPos pos) { return !RAINY.isWeather(world, pos); } }, RAINY { @Override public boolean isWeather(World world, BlockPos pos) { return world.isRainingAt(pos); } }, STORMY { @Override public boolean isWeather(World world, BlockPos pos) { return world.isThundering(); } }; public abstract boolean isWeather(World world, BlockPos pos); } public WeatherType type; public WeatherSound(String name, float volume, WeatherType type) { super(name, volume, HeightArea.Surface); this.type = type; } public float getMutingFactorPriority() { return 0.5F; } public float getMutingFactor() { return 0.8F; } @Override public float getVolume(World world, EntityPlayer player, boolean isNight, float volume) { if(type.isWeather(world, player.getPosition())){ if(AmbientEnv.height.currentHeight.containsKey(HeightArea.Sky)) return 1; else return volume; } return 0; } }
package org.b3log.symphony.processor; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.math.RandomUtils; import org.b3log.latke.logging.Level; import org.b3log.latke.logging.Logger; import org.b3log.latke.servlet.HTTPRequestContext; import org.b3log.latke.servlet.HTTPRequestMethod; import org.b3log.latke.servlet.annotation.RequestProcessing; import org.b3log.latke.servlet.annotation.RequestProcessor; import org.b3log.latke.servlet.renderer.PNGRenderer; import org.b3log.latke.util.Strings; import org.b3log.symphony.model.Common; import org.json.JSONObject; import org.patchca.color.GradientColorFactory; import org.patchca.color.RandomColorFactory; import org.patchca.color.SingleColorFactory; import org.patchca.filter.predefined.CurvesRippleFilterFactory; import org.patchca.font.RandomFontFactory; import org.patchca.service.Captcha; import org.patchca.service.ConfigurableCaptchaService; import org.patchca.word.RandomWordFactory; import javax.imageio.ImageIO; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.awt.*; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; @RequestProcessor public class CaptchaProcessor { /** * Logger. */ private static final Logger LOGGER = Logger.getLogger(CaptchaProcessor.class); /** * Key of captcha. */ public static final String CAPTCHA = "captcha"; /** * Captchas. */ public static final Set<String> CAPTCHAS = new HashSet<>(); /** * Captcha length. */ private static final int CAPTCHA_LENGTH = 4; /** * Captcha chars. */ private static final String CHARS = "acdefhijklmnprstuvwxy234578"; /** * Checks whether the specified captcha is invalid. * * @param captcha the specified captcha * @return {@code true} if it is invalid, returns {@code false} otherwise */ public static boolean invalidCaptcha(final String captcha) { if (Strings.isEmptyOrNull(captcha) || captcha.length() != CAPTCHA_LENGTH) { return true; } boolean ret = !CaptchaProcessor.CAPTCHAS.contains(captcha); if (!ret) { CaptchaProcessor.CAPTCHAS.remove(captcha); } return ret; } /** * Gets captcha. * * @param context the specified context */ @RequestProcessing(value = "/captcha", method = HTTPRequestMethod.GET) public void get(final HTTPRequestContext context) { final PNGRenderer renderer = new PNGRenderer(); context.setRenderer(renderer); try { final ConfigurableCaptchaService cs = new ConfigurableCaptchaService(); if (0.5 < Math.random()) { cs.setColorFactory(new GradientColorFactory()); } else { cs.setColorFactory(new RandomColorFactory()); } cs.setFilterFactory(new CurvesRippleFilterFactory(cs.getColorFactory())); final RandomWordFactory randomWordFactory = new RandomWordFactory(); randomWordFactory.setCharacters(CHARS); randomWordFactory.setMinLength(CAPTCHA_LENGTH); randomWordFactory.setMaxLength(CAPTCHA_LENGTH); cs.setWordFactory(randomWordFactory); cs.setFontFactory(new RandomFontFactory(getAvaialbeFonts())); final Captcha captcha = cs.getCaptcha(); final String challenge = captcha.getChallenge(); final BufferedImage bufferedImage = captcha.getImage(); if (CAPTCHAS.size() > 64) { CAPTCHAS.clear(); } CAPTCHAS.add(challenge); final HttpServletResponse response = context.getResponse(); response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); renderImg(renderer, bufferedImage); } catch (final Exception e) { LOGGER.log(Level.ERROR, e.getMessage(), e); } } /** * Gets captcha for login. * * @param context the specified context */ @RequestProcessing(value = "/captcha/login", method = HTTPRequestMethod.GET) public void getLoginCaptcha(final HTTPRequestContext context) { try { final HttpServletRequest request = context.getRequest(); final HttpServletResponse response = context.getResponse(); final String userId = request.getParameter(Common.NEED_CAPTCHA); if (StringUtils.isBlank(userId)) { return; } final JSONObject wrong = LoginProcessor.WRONG_PWD_TRIES.get(userId); if (null == wrong) { return; } if (wrong.optInt(Common.WRON_COUNT) < 3) { return; } final PNGRenderer renderer = new PNGRenderer(); context.setRenderer(renderer); final ConfigurableCaptchaService cs = new ConfigurableCaptchaService(); cs.setColorFactory(new SingleColorFactory(new Color(26, 52, 96))); cs.setFilterFactory(new CurvesRippleFilterFactory(cs.getColorFactory())); final RandomWordFactory randomWordFactory = new RandomWordFactory(); randomWordFactory.setCharacters(CHARS); randomWordFactory.setMinLength(CAPTCHA_LENGTH); randomWordFactory.setMaxLength(CAPTCHA_LENGTH); cs.setWordFactory(randomWordFactory); final Captcha captcha = cs.getCaptcha(); final String challenge = captcha.getChallenge(); final BufferedImage bufferedImage = captcha.getImage(); wrong.put(CAPTCHA, challenge); response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); renderImg(renderer, bufferedImage); } catch (final Exception e) { LOGGER.log(Level.ERROR, e.getMessage(), e); } } private void renderImg(final PNGRenderer renderer, final BufferedImage bufferedImage) throws IOException { try (final ByteArrayOutputStream baos = new ByteArrayOutputStream()) { ImageIO.write(bufferedImage, "png", baos); final byte[] data = baos.toByteArray(); renderer.setImage(data); } } private static java.util.List<String> getAvaialbeFonts() { final List<String> ret = new ArrayList<>(); final GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment(); final Font[] fonts = e.getAllFonts(); for (final Font f : fonts) { if (Strings.contains(f.getFontName(), new String[]{"Verdana", "DejaVu Sans Mono", "Tahoma"})) { ret.add(f.getFontName()); } } if (ret.isEmpty() && 0 < fonts.length) { ret.add(fonts[RandomUtils.nextInt(fonts.length)].getFontName()); } return ret; } }
package com.doctor.esper.spring; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @see org.opencredo.esper.spring.EsperTemplateBean * * @author doctor * * @time 201568 5:16:51 */ public class EsperTemplateBean extends EsperTemplate { private final static Logger LOG = LoggerFactory.getLogger(EsperTemplateBean.class); @PostConstruct public void afterPropertiesSet() { LOG.debug("Initializing the esper template bean"); super.initialize(); LOG.debug("Completed initializing the esper template bean"); } @PreDestroy public void destroy() { LOG.debug("Destroying the esper template bean"); super.cleanup(); LOG.debug("Finished destroying the esper template bean"); } }
package org.codehaus.mojo.aspectj; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.ArtifactUtils; import org.apache.maven.artifact.handler.ArtifactHandler; import org.apache.maven.plugin.MojoExecutionException; import org.aspectj.bridge.IMessage; import org.aspectj.tools.ajc.Main; import org.codehaus.plexus.util.FileUtils; /** * Base class for the two aspectJ compiletime weaving mojos. * * @author <a href="mailto:kaare.nilsen@gmail.com">Kaare Nilsen</a> */ public abstract class AbstractAjcCompiler extends AbstractAjcMojo { /** * The source directory for the aspects * @parameter default-value="src/main/aspect" */ protected String aspectDirectory = "src/main/aspect"; /** * The source directory for the test aspects * @parameter default-value="src/test/aspect" */ protected String testAspectDirectory = "src/test/aspect"; /** * List of ant-style patterns used to specify the aspects that should be included when * compiling. When none specified all .java and .aj files in the project source directories, or * directories spesified by the ajdtDefFile property are included. * * @parameter */ protected String[] includes; /** * List of ant-style patterns used to specify the aspects that should be excluded when * compiling. When none specified all .java and .aj files in the project source directories, or * directories spesified by the ajdtDefFile property are included. * * @parameter */ protected String[] excludes; /** * Where to find the ajdt build definition file. * <i>If set this will override the use of project sourcedirs</i>. * * @parameter */ protected String ajdtBuildDefFile; /** * Generate aop.xml file for load-time weaving with default name.(/META-INF/aop.xml) * * @parameter */ protected boolean outxml; /** * Generate aop.xml file for load-time weaving with custom name. * * @parameter */ protected String outxmlfile; /** * Generate .ajesym symbol files for emacs support * * @parameter */ protected boolean emacssym; /** * Set default level for messages about potential * programming mistakes in crosscutting code. * {level} may be ignore, warning, or error. * This overrides entries in org/aspectj/weaver/XlintDefault.properties * from aspectjtools.jar. * * @parameter */ protected String Xlint; /** * Enables the compiler to support hasmethod(method_pattern) * and hasfield(field_pattern) type patterns, * but only within declare statements. * * It's experimental and undocumented because it may change, * and because it doesn't yet take into account ITDs. * * @parameter * @since 1.3 */ protected boolean XhasMember; /** * Specify classfile target setting (1.1 to 1.6) default is 1.2 * * @parameter default-value="${project.build.java.target}" */ protected String target; /** * Toggle assertions (1.3, 1.4, or 1.6 - default is 1.4). * When using -source 1.3, an assert() statement valid under Java 1.4 * will result in a compiler error. When using -source 1.4, * treat assert as a keyword and implement assertions * according to the 1.4 language spec. * When using -source 1.5 or higher, Java 5 language features are permitted. * * @parameter default-value="${project.build.java.target}" */ protected String source; /** * Specify compiler compliance setting (1.3 to 1.6) * default is 1.4 * * @parameter */ protected String complianceLevel; /** * Toggle warningmessages on deprecations * * @parameter */ protected boolean deprecation; /** * Emit no errors for unresolved imports; * * @parameter */ protected boolean noImportError; /** * Keep compiling after error, dumping class files with problem methods * * @parameter */ protected boolean proceedOnError; /** * Preserve all local variables during code generation (to facilitate debugging). * * @parameter */ protected boolean preserveAllLocals; /** * Compute reference information. * * @parameter */ protected boolean referenceInfo; /** * Specify default source encoding format. * * @parameter expression="${project.build.sourceEncoding}" */ protected String encoding; /** * Emit messages about accessed/processed compilation units * * @parameter */ protected boolean verbose; /** * Emit messages about weaving * * @parameter */ protected boolean showWeaveInfo; /** * Repeat compilation process N times (typically to do performance analysis). * * @parameter */ protected int repeat; /** * (Experimental) runs weaver in reweavable mode which causes it to create * woven classes that can be rewoven, subject to the restriction * that on attempting a reweave all the types that advised the woven * type must be accessible. * * @parameter */ protected boolean Xreweavable; /** * (Experimental) do not inline around advice * * @parameter */ protected boolean XnoInline; /** * (Experimental) Normally it is an error to declare aspects Serializable. This option removes that restriction. * * @parameter */ protected boolean XserializableAspects; /** * Causes the compiler to calculate and add the SerialVersionUID field to any type implementing Serializable that is affected by an aspect. * The field is calculated based on the class before weaving has taken place. * * @parameter */ protected boolean XaddSerialVersionUID; /** * Override location of VM's bootclasspath for purposes of evaluating types when compiling. * Path is a single argument containing a list of paths to zip files or directories, delimited by the platform-specific path delimiter. * * @parameter */ protected String bootclasspath; protected String warn; /** * The filename to store build configuration in. * This file will be placed in the project build output * directory, and will contain all the arguments * passed to the compiler in the last run, and also * all the filenames included in the build. Aspects as * well as java files. * * @parameter default-value="builddef.lst" */ protected String argumentFileName = "builddef.lst"; /** * Forces re-compilation, regardless of whether the compiler arguments or * the sources have changed. * * @parameter */ protected boolean forceAjcCompile; /** * Holder for ajc compiler options */ protected List ajcOptions = new ArrayList(); /** * Holds all files found using the includes, excludes parameters. */ protected Set resolvedIncludes; /** * Abstract method used by child classes to spesify the correct output * directory for compiled classes. * * @return where compiled classes should be put. */ protected abstract List getOutputDirectories(); /** * Abstract method used by child classes to spesify the correct source directory for classes. * * @return where sources may be found. */ protected abstract List getSourceDirectories(); /** * Abstract method used by cild classes to specify aditional aspect paths. * @return */ protected abstract String getAdditionalAspectPaths(); /** * Do the AspectJ compiling. * * @throws MojoExecutionException */ public void execute() throws MojoExecutionException { ArtifactHandler artifactHandler = project.getArtifact().getArtifactHandler(); if ( !"java".equals( artifactHandler.getLanguage() ) ) { getLog().warn( "Not executing aspectJ compiler as the project is not a Java classpath-capable package" ); return; } Thread.currentThread().setContextClassLoader( this.getClass().getClassLoader() ); project.getCompileSourceRoots().add( basedir.getAbsolutePath() + "/" + aspectDirectory ); project.getTestCompileSourceRoots().add( basedir.getAbsolutePath() + "/" + testAspectDirectory ); assembleArguments(); if ( !hasSourcesToCompile() ) { getLog().warn( "No sources found skipping aspectJ compile" ); return; } if ( !forceAjcCompile && !isBuildNeeded() ) { getLog().info( "No modifications found skipping aspectJ compile" ); return; } if ( getLog().isDebugEnabled() ) { String command = "Running : ajc "; Iterator iter = ajcOptions.iterator(); while ( iter.hasNext() ) { command += ( iter.next() + " " ); } getLog().debug( command ); } try { getLog().debug( "Compiling and weaving " + resolvedIncludes.size() + " sources to " + getOutputDirectories().get( 0 ) ); File outDir = new File( (String) getOutputDirectories().get( 0 ) ); AjcHelper.writeBuildConfigToFile( ajcOptions, argumentFileName, outDir ); getLog().debug( "Argumentsfile written : " + new File( outDir.getAbsolutePath() + argumentFileName ).getAbsolutePath() ); } catch ( IOException e ) { throw new MojoExecutionException( "Could not write arguments file to the target area", e ); } Main main = new Main(); MavenMessageHandler mavenMessageHandler = new MavenMessageHandler( getLog() ); main.setHolder( mavenMessageHandler ); main.runMain( (String[]) ajcOptions.toArray( new String[0] ), false ); IMessage[] errors = mavenMessageHandler.getMessages( IMessage.ERROR, true ); if ( !proceedOnError && errors.length > 0 ) { throw new CompilationFailedException( errors ); } } /** * Assembles a complete ajc compiler arguments list. * * @throws MojoExecutionException error in configuration */ protected void assembleArguments() throws MojoExecutionException { if ( XhasMember ) { ajcOptions.add( "-XhasMember" ); } // Add classpath ajcOptions.add( "-classpath" ); ajcOptions.add( AjcHelper.createClassPath( project, null, getOutputDirectories() ) ); // Add boot classpath if ( null != bootclasspath ) { ajcOptions.add( "-bootclasspath" ); ajcOptions.add( bootclasspath ); } // Add warn option if (null != warn ) { ajcOptions.add( "-warn:" + warn ); } // Add artifacts to weave addModulesArgument( "-inpath", ajcOptions, weaveDependencies, null, "a dependency to weave" ); // Add library artifacts addModulesArgument( "-aspectpath", ajcOptions, aspectLibraries, getAdditionalAspectPaths(), "an aspect library" ); //add target dir argument ajcOptions.add( "-d" ); ajcOptions.add( getOutputDirectories().get( 0 ) ); // Add all the files to be included in the build, if ( null != ajdtBuildDefFile ) { resolvedIncludes = AjcHelper.getBuildFilesForAjdtFile( ajdtBuildDefFile, basedir ); } else { resolvedIncludes = AjcHelper.getBuildFilesForSourceDirs( getSourceDirectories(), this.includes, this.excludes ); } ajcOptions.addAll( resolvedIncludes ); } /** * Finds all artifacts in the weavemodule property, * and adds them to the ajc options. * * @param arguments * @throws MojoExecutionException */ private void addModulesArgument( String argument, List arguments, Module[] modules, String aditionalpath, String role ) throws MojoExecutionException { StringBuffer buf = new StringBuffer(); if ( null != aditionalpath ) { arguments.add( argument ); buf.append( aditionalpath ); } if ( modules != null && modules.length > 0 ) { if ( !arguments.contains( argument ) ) { arguments.add( argument ); } for ( int i = 0; i < modules.length; ++i ) { Module module = modules[i]; String key = ArtifactUtils.versionlessKey( module.getGroupId(), module.getArtifactId() ); Artifact artifact = (Artifact) project.getArtifactMap().get( key ); if ( artifact == null ) { throw new MojoExecutionException( "The artifact " + key + " referenced in aspectj plugin as " + role + ", is not found the project dependencies" ); } if ( buf.length() != 0 ) { buf.append( File.pathSeparatorChar ); } buf.append( artifact.getFile().getPath() ); } } if ( buf.length() > 0 ) { String pathString = buf.toString(); arguments.add( pathString ); getLog().debug( "Adding " + argument + ": " + pathString ); } } /** * Checks modifications that would make us need a build * * @throws MojoExecutionException * */ protected boolean isBuildNeeded() throws MojoExecutionException { File outDir = new File( getOutputDirectories().get( 0 ).toString() ); return hasNoPreviousBuild( outDir ) || hasArgumentsChanged( outDir ) || hasSourcesChanged( outDir ); } private boolean hasNoPreviousBuild( File outDir ) { return ( !FileUtils.fileExists( new File( outDir.getAbsolutePath(), argumentFileName ).getAbsolutePath() ) ); } private boolean hasArgumentsChanged( File outDir ) throws MojoExecutionException { try { return ( !ajcOptions.equals( AjcHelper.readBuildConfigFile( argumentFileName, outDir ) ) ); } catch ( IOException e ) { throw new MojoExecutionException( "Error during reading of previous argumentsfile " ); } } /** * Not entirely safe, assembleArguments() must be run */ private boolean hasSourcesToCompile() { return resolvedIncludes.size() > 0; } private boolean hasSourcesChanged( File outDir ) { Iterator sourceIter = resolvedIncludes.iterator(); long lastBuild = new File( outDir.getAbsolutePath(), argumentFileName ).lastModified(); while ( sourceIter.hasNext() ) { File sourceFile = new File( (String) sourceIter.next() ); long sourceModified = sourceFile.lastModified(); if ( sourceModified >= lastBuild ) { return true; } } return false; } /** * Setters which when called sets compiler arguments */ public void setComplianceLevel( String complianceLevel ) { if ( complianceLevel.equals( "1.3" ) || complianceLevel.equals( "1.4" ) || complianceLevel.equals( "1.5" ) || complianceLevel.equals( "1.6" ) ) { ajcOptions.add( "-" + complianceLevel ); } } public void setDeprecation( boolean deprecation ) { if ( deprecation ) { ajcOptions.add( "-deprecation" ); } } public void setEmacssym( boolean emacssym ) { if ( emacssym ) { ajcOptions.add( "-emacssym" ); } } public void setEncoding( String encoding ) { ajcOptions.add( "-encoding" ); ajcOptions.add( encoding ); } public void setNoImportError( boolean noImportError ) { if ( noImportError ) { ajcOptions.add( "-noImportError" ); } } public void setOutxml( boolean outxml ) { if ( outxml ) { ajcOptions.add( "-outxml" ); } } public void setOutxmlfile( String outxmlfile ) { ajcOptions.add( "-outxmlfile" ); ajcOptions.add( outxmlfile ); } public void setPreserveAllLocals( boolean preserveAllLocals ) { if ( preserveAllLocals ) { ajcOptions.add( "-preserveAllLocals" ); } } public void setProceedOnError( boolean proceedOnError ) { if ( proceedOnError ) { ajcOptions.add( "-proceedOnError" ); } this.proceedOnError = proceedOnError; } public void setReferenceInfo( boolean referenceInfo ) { if ( referenceInfo ) { ajcOptions.add( "-referenceInfo" ); } } public void setRepeat( int repeat ) { ajcOptions.add( "-repeat" ); ajcOptions.add( "" + repeat ); } public void setShowWeaveInfo( boolean showWeaveInfo ) { if ( showWeaveInfo ) { ajcOptions.add( "-showWeaveInfo" ); } } public void setTarget( String target ) { ajcOptions.add( "-target" ); ajcOptions.add( target ); } public void setSource( String source ) { ajcOptions.add( "-source" ); ajcOptions.add( source ); } public void setVerbose( boolean verbose ) { if ( verbose ) { ajcOptions.add( "-verbose" ); } } public void setXhasMember( boolean xhasMember ) { XhasMember = xhasMember; } public void setXlint( String xlint ) { ajcOptions.add( "-Xlint:" + xlint ); } public void setXnoInline( boolean xnoInline ) { if ( xnoInline ) { ajcOptions.add( "-XnoInline" ); } } public void setXreweavable( boolean xreweavable ) { if ( xreweavable ) { ajcOptions.add( "-Xreweavable" ); } } public void setXserializableAspects( boolean xserializableAspects ) { if ( xserializableAspects ) { ajcOptions.add( "-XserializableAspects" ); } } public void setXaddSerialVersionUID( boolean xaddSerialVersionUID ) { if ( xaddSerialVersionUID ) { ajcOptions.add( "-XaddSerialVersionUID" ); } } public void setBootClassPath( String bootclasspath ) { this.bootclasspath = bootclasspath; } public void setWarn( String warn ) { this.warn = warn; } public void setArgumentFileName( String argumentFileName ) { this.argumentFileName = argumentFileName; } }
package com.dongdongxia.myfastjson.util; import java.lang.annotation.Annotation; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.GenericArrayType; import java.lang.reflect.GenericDeclaration; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import com.dongdongxia.myfastjson.annotation.JSONField; /** * * <P>Description: , , </P> * @ClassName: FieldInfo * @author java_liudong@163.com 2017523 4:58:03 */ public class FieldInfo implements Comparable<FieldInfo>{ public final String name; public final Method method; public final Field field; private int ordinal = 0; public final Class<?> fieldClass; public final Type fieldType; public final Class<?> declaringClass; public final boolean getOnly; public final int serializeFeatures; public final int parserFeatures; // , JSON, public final String label; private final JSONField fieldAnnotation; private final JSONField methodAnnotation; public final boolean fieldAccess; // , public public final boolean fieldTransient; // , , transient public final char[] name_chars; public final boolean isEnum; public final boolean jsonDirect; public final boolean unwrapped; // unwrapped : public final String format; private final String[] alternateNames; // alternate : , /** * * <p>Title: Constructor</p> * <p>Description: , </p> * @param name * @param declaringCLass * @param fieldClass * @param fieldType * @param field * @param ordinal * @param serializeFeatures * @param parserFeatures */ public FieldInfo(String name, Class<?> declaringClass, Class<?> fieldClass, Type fieldType, Field field, int ordinal, int serializeFeatures, int parserFeatures) { this.name = name; this.declaringClass = declaringClass; this.fieldClass = fieldClass; this.fieldType = fieldType; this.method = null; this.field = field; this.ordinal = ordinal; this.serializeFeatures = serializeFeatures; this.parserFeatures = parserFeatures; isEnum = fieldClass.isEnum(); if (field != null) { int modifiers = field.getModifiers(); fieldAccess = (modifiers & Modifier.PUBLIC) != 0 || method == null; // true, method = true fieldTransient = Modifier.isTransient(modifiers); } else { fieldTransient = false; fieldAccess = false; } name_chars = getFieldNameChars(); if (field != null) { TypeUtils.setAccessible(field); // , public } this.label = ""; fieldAnnotation = null; methodAnnotation = null; this.getOnly = false; this.jsonDirect = false; this.unwrapped = false; this.format = null; this.alternateNames = new String[0]; } /** * * <p>Title: Constructor</p> * <p>Description: Method for constructor</p> * @param name * @param method * @param field * @param clazz * @param type * @param ordinal * @param serializeFeatures * @param parserFeatures * @param fieldAnnotation * @param methodAnnotation * @param label */ public FieldInfo(String name, Method method, Field field, Class<?> clazz, Type type, int ordinal, int serializeFeatures, int parserFeatures, JSONField fieldAnnotation, JSONField methodAnnotation, String label) { if (field != null) { String fieldName = field.getName(); if (fieldName.equals(name)) { name = fieldName; } } this.name = name; this.method = method; this.field = field; this.ordinal = ordinal; this.serializeFeatures = serializeFeatures; this.parserFeatures = parserFeatures; this.fieldAnnotation = fieldAnnotation; this.methodAnnotation = methodAnnotation; if (field != null) { int modifiers = field.getModifiers(); // , public private , protected fieldAccess = ((modifiers & Modifier.PUBLIC) != 0 || method == null); fieldTransient = Modifier.isTransient(modifiers) || TypeUtils.isTransient(method); } else { fieldAccess = false; fieldTransient = false; } if (label != null && label.length() > 0) { this.label = label; } else { this.label = ""; } String format = null; JSONField annotation = getAnnotation(); boolean jsonDirect = false; if (annotation != null) { format = annotation.format(); if (format.trim().length() == 0) { format = null; } jsonDirect = annotation.jsonDirect(); unwrapped = annotation.unwrappend(); alternateNames = annotation.alternateNames(); } else { jsonDirect = false; unwrapped = false; alternateNames = new String[0]; } this.format = format; name_chars = getFieldNameChars(); if (field != null) { TypeUtils.setAccessible(field); } boolean getOnly = false; Type fieldType; Class<?> fieldClass; if (method != null) { Class<?>[] types; if ((types = method.getParameterTypes()).length == 1) { fieldClass = types[0]; fieldType = method.getGenericParameterTypes()[0]; } else { fieldClass = method.getReturnType(); fieldType = method.getGenericReturnType(); getOnly = true; } this.declaringClass = method.getDeclaringClass(); } else { fieldClass = field.getType(); fieldType = field.getGenericType(); this.declaringClass = field.getDeclaringClass(); getOnly = Modifier.isFinal(field.getModifiers()); // , final } this.getOnly = getOnly; this.jsonDirect = jsonDirect && fieldClass == String.class; if (clazz != null && fieldClass == Object.class && fieldType instanceof TypeVariable) { TypeVariable<?> tv = (TypeVariable<?>) fieldType; Type genericFieldType = getInheritGenericType(clazz, tv); if (genericFieldType != null) { this.fieldClass = TypeUtils.getClass(genericFieldType); this.fieldType = genericFieldType; isEnum = fieldClass.isEnum(); return ; } } Type genericFieldType = fieldType; if (!(fieldType instanceof Class)) { genericFieldType = getFieldType(clazz, type != null ? type : clazz, fieldType); if (genericFieldType != fieldType) { if (genericFieldType instanceof ParameterizedType) { fieldClass = TypeUtils.getClass(genericFieldType); } } } this.fieldType = genericFieldType; this.fieldClass = fieldClass; isEnum = fieldClass.isEnum(); } /** * * <p>Title: getFieldType</p> * <p>Description: TODO</p> * @param clazz * @param type * @param fieldType * @return * @author java_liudong@163.com 2017524 10:32:05 */ public static Type getFieldType(final Class<?> clazz, final Type type, Type fieldType) { if (clazz == null || type == null) { return fieldType; } if (fieldType instanceof GenericArrayType) { GenericArrayType genericArrayType = (GenericArrayType) fieldType; Type componentType = genericArrayType.getGenericComponentType(); Type componentTypeX = getFieldType(clazz, type, componentType); if (componentType != componentTypeX) { Type fieldTypeX = Array.newInstance(TypeUtils.getClass(componentTypeX), 0).getClass(); return fieldTypeX; } } if (!TypeUtils.isGenericParamType(type)) { return fieldType; } if (fieldType instanceof TypeVariable) { ParameterizedType paramType = (ParameterizedType) TypeUtils.getGenericParamType(type); Class<?> parameterizedClass = TypeUtils.getClass(paramType); final TypeVariable<?> typeVar = (TypeVariable<?>) fieldType; TypeVariable<?>[] typeVariables = parameterizedClass.getTypeParameters(); for (int i = 0; i < typeVariables.length; ++i) { if (typeVariables[i].getName().equals(typeVar.getName())) { fieldType = paramType.getActualTypeArguments()[i]; return fieldType; } } } if (fieldType instanceof ParameterizedType) { ParameterizedType parameterizedFieldType = (ParameterizedType) fieldType; Type[] arguments = parameterizedFieldType.getActualTypeArguments(); boolean changed = false; TypeVariable<?>[] typeVariables = null; Type[] actualTypes = null; ParameterizedType paramType = null; if (type instanceof ParameterizedType) { paramType = (ParameterizedType) type; typeVariables = clazz.getTypeParameters(); } else if (clazz.getGenericSuperclass() instanceof ParameterizedType) { paramType = (ParameterizedType) clazz.getGenericSuperclass(); typeVariables = clazz.getSuperclass().getTypeParameters(); } for (int i = 0; i < arguments.length && paramType != null; ++i) { Type fieldTypeArguement = arguments[i]; if (fieldTypeArguement instanceof TypeVariable) { TypeVariable<?> typeVar = (TypeVariable<?>) fieldTypeArguement; for (int j = 0; j < typeVariables.length; ++j) { if (typeVariables[j].getName().equals(typeVar.getName())) { if (actualTypes == null) { actualTypes = paramType.getActualTypeArguments(); } if (arguments[i] != actualTypes[j]) { arguments[i] = actualTypes[j]; changed = true; } } } } } if (changed) { fieldType = new ParameterizedTypeImpl(arguments, parameterizedFieldType.getOwnerType(), parameterizedFieldType.getRawType()); return fieldType; } } return fieldType; } /** * * <p>Title: getInheritGenericType</p> * <p>Description: </p> * @param clazz * @param tv * @return * @author java_liudong@163.com 2017523 6:41:10 */ public static Type getInheritGenericType(Class<?> clazz, TypeVariable<?> tv) { Type type = null; GenericDeclaration gd = tv.getGenericDeclaration(); do { type = clazz.getGenericSuperclass(); if (type == null) { return null; } if (type instanceof ParameterizedType) { ParameterizedType ptype = (ParameterizedType) type; Type rawType = ptype.getRawType(); // Type boolean eq = gd.equals(rawType) || (gd instanceof Class && rawType instanceof Class && ((Class)gd).isAssignableFrom((Class) rawType)); if (eq) { TypeVariable<?>[] tvs = gd.getTypeParameters(); Type[] types = ptype.getActualTypeArguments(); for (int i = 0; i < tvs.length; i++) { if (tv.equals(tvs[i])) { return types[i]; } } return null; } } clazz = TypeUtils.getClass(type); } while (type != null); return null; } /** * * <p>Title: getFieldNameChars</p> * <p>Description: name JSONString </p> * @return * @author java_liudong@163.com 2017523 5:52:12 */ protected char[] getFieldNameChars() { int nameLen = this.name.length(); char[] name_chars = new char[nameLen + 3]; this.name.getChars(0, nameLen, name_chars, 1); name_chars[0] = '"'; name_chars[nameLen + 1] = '"'; name_chars[nameLen + 2] = ':'; return name_chars; } /** * * <p>Title: getAnnotation</p> * <p>Description: , , , </p> * @return * @author java_liudong@163.com 2017523 6:26:31 */ public JSONField getAnnotation() { if (this.fieldAnnotation != null) { return this.fieldAnnotation; } return this.methodAnnotation; } /** * * <p>Title: getAnnotation</p> * <p>Description: </p> * @param annotationClass * @return * @author java_liudong@163.com 2017525 9:54:48 */ @SuppressWarnings("unchecked") public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { if (annotationClass == JSONField.class) { return (T) getAnnotation(); } T annotation = null; if (method != null) { annotation = method.getAnnotation(annotationClass); } if (annotation == null && field != null) { annotation = field.getAnnotation(annotationClass); } return annotation; } @Override public int compareTo(FieldInfo o) { return 0; } /** * * <p>Title: setAccessible</p> * <p>Description: , </p> * @throws SecurityException * @author java_liudong@163.com 201769 4:01:15 */ public void setAccessible() throws SecurityException{ if (method != null) { TypeUtils.setAccessible(method); return ; } TypeUtils.setAccessible(field); } public Object get(Object javaObject) throws IllegalAccessException, InvocationTargetException { if (method != null) { Object value = method.invoke(javaObject); return value; } return field.get(javaObject); } }
package org.codehaus.mojo.scmchangelog.scm; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.Iterator; import java.util.List; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.logging.Log; import org.apache.maven.scm.ScmBranch; import org.apache.maven.scm.ScmException; import org.apache.maven.scm.ScmFileSet; import org.apache.maven.scm.ScmRevision; import org.apache.maven.scm.ScmTag; import org.apache.maven.scm.ScmVersion; import org.apache.maven.scm.command.changelog.ChangeLogScmResult; import org.apache.maven.scm.command.list.ListScmResult; import org.apache.maven.scm.manager.ScmManager; import org.apache.maven.scm.repository.ScmRepository; import org.codehaus.mojo.scmchangelog.SvnTargetEnum; import org.codehaus.mojo.scmchangelog.changelog.Release; import org.codehaus.mojo.scmchangelog.changelog.log.GrammarEnum; import org.codehaus.mojo.scmchangelog.changelog.log.SvnLogEntry; import org.codehaus.mojo.scmchangelog.scm.hg.command.changelog.BetterChangeSet; import org.codehaus.mojo.scmchangelog.tags.Tag; /** * Adapter to be used to wrap the scm implementation. * @author ehsavoie * @version $Id$ */ public class ScmAdapter { /** * The ScmManager to access SCM elements. */ private ScmManager manager; /** * The grammar used to extract elements from the comments. */ private GrammarEnum grammar; /** * The maven logger. */ private Log logger; /** * Constructor of ScmAdapter. * @param currentManager the ScmManager to access SCM elements. * @param currentGrammar the grammar used to extract elements from the comments. */ public ScmAdapter( ScmManager currentManager, GrammarEnum currentGrammar ) { this.manager = currentManager; this.grammar = currentGrammar; } /** * Returns the list of releases defined in the SCM. * @param repository the SCM repository. * @param fileSet the base fileset. * @return the list of releases defined in the SCM. <code>List&lt;Release&gt;</code> * @throws org.apache.maven.scm.ScmException in case of an error with the SCM. * @throws org.apache.maven.plugin.MojoExecutionException in case of an error in executing the Mojo. */ public List getListOfReleases( ScmRepository repository, ScmFileSet fileSet ) throws ScmException, MojoExecutionException { if ( "svn".equals( repository.getProvider() ) ) { return getSvnListOfReleases( repository, fileSet ); } if ( "hg".equals( repository.getProvider() ) ) { return getHgListOfReleases( repository, fileSet ); } return getScmListOfReleases( repository, fileSet ); } /** * Returns the list of releases defined in the subversion repository. * @param repository the SCM repository. * @param fileSet the base fileset. * @return the list of releases defined in the SCM. <code>List&lt;Release&gt;</code> * @throws org.apache.maven.scm.ScmException in case of an error with the SCM. * @throws org.apache.maven.plugin.MojoExecutionException in case of an error in executing the Mojo. */ protected List getSvnListOfReleases( ScmRepository repository, ScmFileSet fileSet ) throws MojoExecutionException, ScmException { ListScmResult result = this.manager.list( repository, fileSet, false, getScmVersion( SvnTargetEnum.TAG, "" ) ); final List tags = result.getFiles(); getLogger().info( tags.toString() ); final List releases = new ArrayList( 10 ); Iterator iter = tags.iterator(); while ( iter.hasNext() ) { Tag tag = ( Tag ) iter.next(); final ChangeLogScmResult logs = this.manager.changeLog( repository, fileSet, getScmVersion( SvnTargetEnum.TRUNK, tag.getStartRevision() ), getScmVersion( SvnTargetEnum.TRUNK, tag.getEndRevision() ), "" ); if ( logs.getChangeLog() != null ) { Release release = new Release( tag, logs.getChangeLog().getChangeSets() ); releases.add( release ); } } String endRevision = "0"; if ( !tags.isEmpty() ) { endRevision = ( ( Tag ) tags.get( tags.size() - 1 ) ).getEndRevision(); } getLogger().info( "End revision : " + endRevision ); final Tag trunk = new Tag( "trunk" ); trunk.setStartRevision( endRevision ); trunk.setDate( new Date() ); trunk.setEndRevision( null ); final ChangeLogScmResult logs = this.manager.changeLog( repository, fileSet, getScmVersion( SvnTargetEnum.TRUNK, endRevision ), null, "" ); if ( logs.getChangeLog() != null ) { final Release release = new Release( trunk, logs.getChangeLog().getChangeSets() ); releases.add( release ); } Collections.reverse( releases ); return releases; } /** * Returns the list of releases defined in a SCM repository. * @param repository the SCM repository. * @param fileSet the base fileset. * @return the list of releases defined in the SCM. <code>List&lt;Release&gt;</code> * @throws org.apache.maven.scm.ScmException in case of an error with the SCM. * @throws org.apache.maven.plugin.MojoExecutionException in case of an error in executing the Mojo. */ protected List getScmListOfReleases( ScmRepository repository, ScmFileSet fileSet ) throws MojoExecutionException, ScmException { throw new MojoExecutionException( "Unsupported SCM" ); } /** * Returns the list of releases defined in the mercurial repository. * @param repository the SCM repository. * @param fileSet the base fileset. * @return the list of releases defined in the SCM. <code>List&lt;Release&gt;</code> * @throws org.apache.maven.scm.ScmException in case of an error with the SCM. * @throws org.apache.maven.plugin.MojoExecutionException in case of an error in executing the Mojo. */ protected List getHgListOfReleases( ScmRepository repository, ScmFileSet fileSet ) throws MojoExecutionException, ScmException { ListScmResult result = this.manager.list( repository, fileSet, false, getScmVersion( SvnTargetEnum.TAG, "" ) ); final List tags = result.getFiles(); final List releases = new ArrayList( 10 ); Iterator iter = tags.iterator(); String startRevision = "0"; while ( iter.hasNext() ) { Tag tag = ( Tag ) iter.next(); getLogger().info( tag.toString() ); final ChangeLogScmResult logs = this.manager.changeLog( repository, fileSet, getScmVersion( SvnTargetEnum.TRUNK, startRevision ), getScmVersion( SvnTargetEnum.TRUNK, tag.getEndRevision() ), "" ); startRevision = tag.getEndRevision(); getLogger().info( logs.getChangeLog().toString() ); tag.setDate( logs.getChangeLog().getEndDate() ); Release release = new Release( tag, getEntries( logs.getChangeLog().getChangeSets() ) ); releases.add( release ); } Collections.reverse( releases ); return releases; } /** * Returns the list of log entries defined in the list of ChangeSet. * @param changeSets the list of ChangeSet. * @return the list of log entries defined in the list of ChangeSet. <code>List&lt;SvnLogEntry&gt;</code> */ protected List getEntries( List changeSets ) { List elements = new ArrayList( changeSets.size() ); Iterator iter = changeSets.iterator(); while ( iter.hasNext() ) { BetterChangeSet changeSet = ( BetterChangeSet ) iter.next(); SvnLogEntry entry = new SvnLogEntry(); entry.setAuthor( changeSet.getAuthor() ); entry.setDate( changeSet.getDate() ); getLogger().info( changeSet.getComment() ); entry.setMessage( grammar.extractMessage( changeSet.getComment() ) ); entry.setRevision( changeSet.getRevision() ); elements.add( entry ); } return elements; } /** * Returns the Scm version. * @param versionType the type of version (tag, trunk, branch). * @param version the tag/branche name. * @return the corresponding ScmVersion. * @throws org.apache.maven.plugin.MojoExecutionException in case of an error in executing the Mojo. */ public ScmVersion getScmVersion( SvnTargetEnum versionType, String version ) throws MojoExecutionException { if ( SvnTargetEnum.TAG.equals( versionType ) ) { return new ScmTag( version ); } else if ( SvnTargetEnum.BRANCH.equals( versionType ) ) { return new ScmBranch( version ); } else if ( SvnTargetEnum.TRUNK.equals( versionType ) ) { return new ScmRevision( version ); } throw new MojoExecutionException( "Unknown version type : " + versionType ); } /** * The currentlogger. * @return the logger */ public Log getLogger() { return logger; } /** * The current logger to be used. * @param logger the logger to set */ public void setLogger( Log logger ) { this.logger = logger; } }
package org.wikipedia.feed.onthisday; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import org.wikipedia.R; import org.wikipedia.WikipediaApp; import org.wikipedia.dataclient.WikiSite; import org.wikipedia.dataclient.restbase.page.RbPageSummary; import org.wikipedia.feed.model.CardType; import org.wikipedia.feed.model.WikiSiteCard; import org.wikipedia.feed.view.FeedAdapter; import org.wikipedia.util.DateUtil; import java.util.Calendar; import java.util.List; import java.util.Random; import java.util.concurrent.TimeUnit; public class OnThisDayCard extends WikiSiteCard { private int nextYear; private Calendar date; private FeedAdapter.Callback callback; private OnThisDay.Event eventShownOnCard; private int age; public OnThisDayCard(@NonNull List<OnThisDay.Event> events, @NonNull WikiSite wiki, int age) { super(wiki); this.date = DateUtil.getDefaultDateFor(age); this.age = age; int randomIndex = 0; if (events.size() > 1) { randomIndex = new Random().nextInt(events.size() - 1); } eventShownOnCard = events.get(randomIndex); this.nextYear = randomIndex + 1 < events.size() ? events.get(randomIndex + 1).year() : eventShownOnCard.year(); } public FeedAdapter.Callback getCallback() { return callback; } public void setCallback(FeedAdapter.Callback callback) { this.callback = callback; } @Override @NonNull public CardType type() { return CardType.ON_THIS_DAY; } @Override @NonNull public String title() { return WikipediaApp.getInstance().getString(R.string.on_this_day_card_title); } @Override @NonNull public String subtitle() { return DateUtil.getFeedCardShortDateString(date); } @NonNull String dayString() { return DateUtil.getMonthOnlyDateString(date.getTime()); } @NonNull public CharSequence text() { return eventShownOnCard.text(); } public int year() { return eventShownOnCard.year(); } @NonNull public Calendar date() { return date; } int nextYear() { return nextYear; } @Nullable public List<RbPageSummary> pages() { return eventShownOnCard.pages(); } int getAge() { return age; } @Override protected int dismissHashCode() { return (int) TimeUnit.MILLISECONDS.toDays(date.getTime().getTime()) + wikiSite().hashCode(); } }
package productcatalog.pages; import com.google.common.collect.ImmutableList; import common.cms.CmsPage; import common.contexts.AppContext; import common.pages.*; import common.prices.PriceFinder; import common.utils.PriceFormatter; import io.sphere.sdk.attributes.Attribute; import io.sphere.sdk.attributes.AttributeAccess; import io.sphere.sdk.categories.Category; import io.sphere.sdk.categories.CategoryTree; import io.sphere.sdk.models.LocalizedEnumValue; import io.sphere.sdk.models.LocalizedStrings; import io.sphere.sdk.models.Reference; import io.sphere.sdk.productdiscounts.DiscountedPrice; import io.sphere.sdk.products.Price; import io.sphere.sdk.products.ProductProjection; import io.sphere.sdk.products.ProductVariant; import io.sphere.sdk.shippingmethods.ShippingMethod; import javax.money.MonetaryAmount; import java.util.*; import java.util.stream.Collectors; import java.util.stream.IntStream; import static common.utils.Languages.translate; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; public class ProductDetailPageContent extends PageContent { private static final int SHORT_DESCRIPTION_MAX_CHARACTERS = 170; private final AppContext context; final CategoryTree categories; private final ProductProjection product; private final ProductVariant variant; private final List<ProductProjection> suggestionList; private final List<ShippingMethod> shippingMethods; private final PriceFormatter priceFormatter; private final Optional<Price> priceOpt; public ProductDetailPageContent(final CmsPage cms, final AppContext context, final CategoryTree categories, final ProductProjection product, final ProductVariant variant, List<ProductProjection> suggestionList, final List<ShippingMethod> shippingMethods, final PriceFormatter priceFormatter, final PriceFinder priceFinder) { super(cms); this.context = context; this.categories = categories; this.product = product; this.variant = variant; this.suggestionList = suggestionList; this.shippingMethods = shippingMethods; this.priceFormatter = priceFormatter; this.priceOpt = priceFinder.findPrice(product.getMasterVariant().getPrices()); } @Override public String additionalTitle() { return translate(product.getName(), context); } public String getText() { return cms.getOrEmpty("content.text"); } public List<LinkData> getBreadcrumb() { return product.getCategories().stream().findFirst().map(productCategoryReference -> { return categories.findById(productCategoryReference.getId()) .map(productCategory -> { return listWith(productCategory.getAncestors(), productCategoryReference).stream() .map(reference -> categories.findById(reference.getId())) .filter(Optional::isPresent) .map(Optional::get) .map(this::categoryToLinkData) .collect(Collectors.toList()); }).orElse(emptyList()); }).orElse(emptyList()); } private <T> List<T> listWith(final List<T> old, final T elem) { final List<T> newe = new ArrayList<>(old); newe.add(elem); return newe; } private LinkData categoryToLinkData(final Category category) { return new LinkData(translate(category.getName(), context), ""); } public List<ImageData> getGallery() { return variant.getImages().stream() .map(ImageData::of) .collect(Collectors.toList()); } public ProductData getProduct() { return ProductDataBuilder.of() .withText(translate(product.getName(), context)) .withSku(variant.getSku().orElse("")) .withRatingList(buildRating()) .withDescription(product.getDescription().map(description -> shorten(translate(description, context))).orElse("")) .withAdditionalDescription(product.getDescription().map(description -> translate(description, context)).orElse("")) .withViewDetailsText(cms.getOrEmpty("product.viewDetails")) .withPrice(getFormattedPrice()) .withPriceOld(getFormattedPriceOld()) .withColorList(buildColorList()) .withSizeList(buildSizeList()) .withSizeGuideText(cms.getOrEmpty("product.sizeGuide")) .withBagItemList(buildBagItemList()) .withAddToBagText(cms.getOrEmpty("product.addToBag")) .withAddToWishlistText(cms.getOrEmpty("product.addToWishlist")) .withAvailableText(cms.getOrEmpty("product.available")) .withProductDetails(buildProductDetails()) .withDeliveryAndReturn(buildDeliveryAndReturn()) .build(); } public ProductListData getSuggestions() { return new ProductListData(suggestionList, context, priceFormatter, cms.getOrEmpty("suggestions.text"), cms.getOrEmpty("suggestions.sale"), cms.getOrEmpty("suggestions.new"), cms.getOrEmpty("suggestions.quickView"), cms.getOrEmpty("suggestions.wishlist"), cms.getOrEmpty("suggestions.moreColors")); } public CollectionData getReviews() { return new CollectionData(cms.getOrEmpty("reviews.text"), Collections.<SelectableData>emptyList()); } private CollectionData buildRating() { return new CollectionData("4/5", asList( new SelectableData("5 Stars", "5", cms.getOrEmpty("product.ratingList.five.text"), "", false), new SelectableData("4 Stars", "4", cms.getOrEmpty("product.ratingList.four.text"), "", false), new SelectableData("3 Stars", "3", cms.getOrEmpty("product.ratingList.three.text"), "", false), new SelectableData("2 Stars", "2", cms.getOrEmpty("product.ratingList.two.text"), "", false), new SelectableData("1 Stars", "1", cms.getOrEmpty("product.ratingList.one.text"), "", false) )); } private CollectionData buildColorList() { final AttributeAccess<LocalizedEnumValue> access = AttributeAccess.ofLocalizedEnumValue(); final List<SelectableData> colors = product.getAllVariants().stream() .map(variant -> variant.getAttribute("color")).filter(Optional::isPresent).map(Optional::get).distinct() .map(color -> selectableColor(color, access)) .collect(Collectors.toList()); colors.add(0, new SelectableData(cms.getOrEmpty("product.colorList.choose.text"), "none", "", "", true)); return new CollectionData(cms.getOrEmpty("product.colorList.text"), colors); } private SelectableData selectableColor(final Attribute color, final AttributeAccess<LocalizedEnumValue> access) { return new SelectableData( translate(color.getValue(access).getLabel(), context), color.getName(), "", "", false); } private CollectionData buildSizeList() { final AttributeAccess<String> access = AttributeAccess.ofText(); final List<SelectableData> sizes = product.getAllVariants().stream() .map(variant -> variant.getAttribute("size")).filter(Optional::isPresent).map(Optional::get).distinct() .map(size -> selectableSize(size, access)) .collect(Collectors.toList()); sizes.add(0, new SelectableData(cms.getOrEmpty("product.sizeList.choose.text"), "none", "", "", true)); return new CollectionData(cms.getOrEmpty("product.sizeList.text"), sizes); } private SelectableData selectableSize(final Attribute size, final AttributeAccess<String> access) { return new SelectableData(size.getValue(access), size.getValue(access), "", "", false); } private CollectionData buildBagItemList() { final List<SelectableData> items = IntStream.range(2, 100) .mapToObj(n -> new SelectableData(Integer.toString(n), "", "", "", false)) .collect(Collectors.toList()); items.add(0, new SelectableData("1", "", "", "", true)); return new CollectionData("", items); } private DetailData buildProductDetails() { final Optional<Set<LocalizedStrings>> detailsOpt = variant.getAttribute("details", AttributeAccess.ofLocalizedStringsSet()); return new DetailData(cms.getOrEmpty("product.productDetails.text"), concatDetails(detailsOpt)); } private String concatDetails (final Optional<Set<LocalizedStrings>> detailsOpt) { return detailsOpt.map(details -> String.join(", ", details.stream() .map(detail -> translate(detail, context)) .collect(Collectors.toList()))) .orElse(""); } private DetailData buildDeliveryAndReturn() { final String desc = shippingMethods.stream().findFirst().map(ShippingMethod::getName).orElse(""); return new DetailData(cms.getOrEmpty("product.deliveryAndReturn.text"), desc); } private String getFormattedPrice() { final Optional<MonetaryAmount> currentPrice = priceOpt.map(price -> price.getDiscounted() .map(DiscountedPrice::getValue) .orElse(price.getValue())); return currentPrice.map(price -> priceFormatter.format(price, context)).orElse(""); } private String getFormattedPriceOld() { final Optional<MonetaryAmount> oldPrice = priceOpt.flatMap(price -> price.getDiscounted() .map(d -> price.getValue())); return oldPrice.map(price -> priceFormatter.format(price, context)).orElse(""); } private String shorten(final String text) { return text.substring(0, SHORT_DESCRIPTION_MAX_CHARACTERS); } }
package org.dannil.httpdownloader.utility; import java.io.File; import java.io.IOException; import java.net.URL; import org.apache.commons.io.FileUtils; import org.dannil.httpdownloader.model.Download; /** * Class which handles operations on files. * * @author Daniel Nilsson */ public class FileUtility { private FileUtility() { throw new UnsupportedOperationException(ResourceUtility.getErrorBundle().getString("disallowed_instantiation")); } /** * Get a file from the specified download's URL. * * @param download * - The download to fetch the URL from * * @return A file with the contents of the specified URL * * @throws IOException * if the file can't be fetched */ public static final File getFileFromURL(final Download download) throws IOException { final File file = new File(download.getFormat()); FileUtils.copyURLToFile(new URL(download.getUrl()), file, 5000, 5000); return file; } /** * Save a file to the disk. * * @param file * - The file to be saved * * @return A file which reflects the file that was saved to the disk * * @throws IOException * if the file couldn't be saved */ public static final File saveToDrive(final File file) throws IOException { final File destination = new File(PathUtility.DOWNLOADS_PATH); FileUtils.copyFileToDirectory(file, destination); return file; } }
package sword.langbook3.android; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.text.Spannable; import android.text.SpannableString; import android.text.style.ForegroundColorSpan; import android.view.ActionMode; import android.view.Menu; import android.view.MenuItem; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import sword.collections.ImmutableIntRange; import sword.collections.ImmutableList; import sword.collections.ImmutableMap; import sword.collections.ImmutableSet; import sword.collections.Map; import sword.collections.MutableHashSet; import sword.collections.MutableIntList; import sword.collections.MutableIntValueMap; import sword.collections.Traverser; import sword.langbook3.android.db.AcceptationId; import sword.langbook3.android.db.AcceptationIdBundler; import sword.langbook3.android.db.AlphabetId; import sword.langbook3.android.db.ConceptId; import sword.langbook3.android.db.ConceptIdBundler; import sword.langbook3.android.db.CorrelationId; import sword.langbook3.android.db.ImmutableCorrelation; import sword.langbook3.android.db.LangbookDbChecker; import sword.langbook3.android.db.LangbookDbManager; import sword.langbook3.android.db.SentenceId; import sword.langbook3.android.db.SentenceIdBundler; import sword.langbook3.android.models.SentenceSpan; public final class SpanEditorActivity extends Activity implements ActionMode.Callback { private static final int REQUEST_CODE_PICK_ACCEPTATION = 1; private interface ArgKeys { String ACCEPTATION = BundleKeys.ACCEPTATION; String CONCEPT = BundleKeys.CONCEPT; String SENTENCE_ID = BundleKeys.SENTENCE_ID; String TEXT = BundleKeys.TEXT; } private interface SavedKeys { String STATE = "cSt"; } interface ResultKeys { String SENTENCE_ID = BundleKeys.SENTENCE_ID; } private TextView _sentenceText; private ListView _listView; private SpanEditorActivityState _state; static void openWithConcept(Activity activity, int requestCode, String text, ConceptId concept) { final Intent intent = new Intent(activity, SpanEditorActivity.class); intent.putExtra(ArgKeys.TEXT, text); ConceptIdBundler.writeAsIntentExtra(intent, ArgKeys.CONCEPT, concept); activity.startActivityForResult(intent, requestCode); } static void openWithAcceptation(Activity activity, int requestCode, String text, AcceptationId acceptation) { final Intent intent = new Intent(activity, SpanEditorActivity.class); intent.putExtra(ArgKeys.TEXT, text); AcceptationIdBundler.writeAsIntentExtra(intent, ArgKeys.ACCEPTATION, acceptation); activity.startActivityForResult(intent, requestCode); } static void openWithSentenceId(Activity activity, int requestCode, String text, SentenceId sentenceId) { final Intent intent = new Intent(activity, SpanEditorActivity.class); intent.putExtra(ArgKeys.TEXT, text); SentenceIdBundler.writeAsIntentExtra(intent, ArgKeys.SENTENCE_ID, sentenceId); activity.startActivityForResult(intent, requestCode); } private String getText() { return getIntent().getStringExtra(ArgKeys.TEXT); } private SpannableString getRichText() { final SpannableString string = new SpannableString(getText()); final int highlightColor = getResources().getColor(R.color.agentDynamicTextColor); final MutableIntValueMap<SentenceSpan<AcceptationId>> spans = _state.getSpans(); final int spanCount = _state.getSpans().size(); for (int spanIndex = 0; spanIndex < spanCount; spanIndex++) { if (spans.valueAt(spanIndex) != 0) { final SentenceSpan<AcceptationId> span = spans.keyAt(spanIndex); string.setSpan(new ForegroundColorSpan(highlightColor), span.range.min(), span.range.max() + 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE); } } return string; } private SentenceId getSentenceId() { return SentenceIdBundler.readAsIntentExtra(getIntent(), ArgKeys.SENTENCE_ID); } private AcceptationId getAcceptationId() { return AcceptationIdBundler.readAsIntentExtra(getIntent(), ArgKeys.ACCEPTATION); } private ConceptId getConcept() { return ConceptIdBundler.readAsIntentExtra(getIntent(), ArgKeys.CONCEPT); } // We should prevent having sentences without neither spans nor other sentence sharing the same meaning, // as it will be not possible to reference them within the app. private boolean shouldAllowNoSpans() { return getSentenceId() != null || getConcept() != null; } private void insertInitialSpans(SentenceId sentenceId) { final LangbookDbChecker checker = DbManager.getInstance().getManager(); final String sentence = getText(); final ImmutableSet<SentenceSpan<AcceptationId>> spans = checker.getSentenceSpans(sentenceId); final MutableIntValueMap<SentenceSpan<AcceptationId>> builder = _state.getSpans(); for (SentenceSpan<AcceptationId> span : spans) { final ImmutableList<CorrelationId> correlationIds = checker.getAcceptationCorrelationArray(span.acceptation); final Traverser<CorrelationId> traverser = correlationIds.iterator(); final ImmutableCorrelation<AlphabetId> firstCorrelation = checker.getCorrelationWithText(traverser.next()); final MutableHashSet<ImmutableIntRange> matchingRanges = MutableHashSet.empty(); for (String correlationText : firstCorrelation.toSet()) { final MutableIntList matchingIndexes = MutableIntList.empty(); int index = 0; while (index >= 0) { index = sentence.indexOf(correlationText, index); if (index >= 0) { matchingIndexes.append(index); index++; } } matchingRanges.addAll(matchingIndexes.map(start -> new ImmutableIntRange(start, start + correlationText.length() - 1))); } while (traverser.hasNext() && !matchingRanges.isEmpty()) { final ImmutableSet<String> correlationTexts = checker.getCorrelationWithText(traverser.next()).toSet(); for (ImmutableIntRange range : matchingRanges.donate()) { for (String correlationText : correlationTexts) { if (sentence.substring(range.max() + 1).startsWith(correlationText)) { matchingRanges.add(new ImmutableIntRange(range.min(), range.max() + correlationText.length())); } } } } if (matchingRanges.size() == 1) { final ImmutableIntRange range = matchingRanges.valueAt(0); final SentenceSpan<AcceptationId> newSpan = range.equals(span.range)? span : new SentenceSpan<>(range, span.acceptation); builder.put(newSpan, 1); } } } private void insertSuggestedSpans(AcceptationId acceptation) { final LangbookDbChecker checker = DbManager.getInstance().getManager(); final ImmutableMap<String, AcceptationId> map = checker.readTextAndDynamicAcceptationsMapFromAcceptation(acceptation); final String text = getText(); for (Map.Entry<String, AcceptationId> entry : map.entries()) { final int index = text.indexOf(entry.key()); if (index >= 0) { final ImmutableIntRange range = new ImmutableIntRange(index, index + entry.key().length() - 1); _state.getSpans().put(new SentenceSpan<>(range, entry.value()), 1); return; } } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.span_editor_activity); if (savedInstanceState == null) { _state = new SpanEditorActivityState(); final SentenceId sentenceId = getSentenceId(); final AcceptationId acceptation = getAcceptationId(); if (sentenceId != null) { insertInitialSpans(sentenceId); } else if (acceptation != null) { insertSuggestedSpans(acceptation); } } else { _state = savedInstanceState.getParcelable(SavedKeys.STATE); } _sentenceText = findViewById(R.id.sentenceText); _sentenceText.setText(getRichText()); _sentenceText.setCustomSelectionActionModeCallback(this); _listView = findViewById(R.id.listView); } @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { getMenuInflater().inflate(R.menu.span_editor_selection_actions, menu); return true; } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { // Nothing to be done return false; } @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { if (item.getItemId() == R.id.menuItemAddSpan) { addSpan(); mode.finish(); return true; } return false; } @Override public void onDestroyActionMode(ActionMode mode) { // Nothing to be done } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.span_editor, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.menuItemConfirm) { evaluateSpans(); return true; } else { return super.onOptionsItemSelected(item); } } private void evaluateSpans() { final ImmutableSet<SentenceSpan<AcceptationId>> spans = _state.getSpans().filter(v -> v != 0).keySet().toImmutable(); if (spans.isEmpty() && !shouldAllowNoSpans()) { Toast.makeText(this, R.string.spanEditorNoSpanPresentError, Toast.LENGTH_SHORT).show(); } else { final String newText = getText(); final LangbookDbManager manager = DbManager.getInstance().getManager(); final SentenceId sentenceId = getSentenceId(); if (sentenceId == null) { ConceptId concept = getConcept(); if (concept == null) { concept = manager.getNextAvailableConceptId(); } final SentenceId newSentenceId = manager.addSentence(concept, newText, spans); Toast.makeText(this, R.string.includeSentenceFeedback, Toast.LENGTH_SHORT).show(); final Intent intent = new Intent(); SentenceIdBundler.writeAsIntentExtra(intent, ResultKeys.SENTENCE_ID, newSentenceId); setResult(RESULT_OK, intent); } else { if (!manager.updateSentenceTextAndSpans(sentenceId, newText, spans)) { throw new AssertionError(); } Toast.makeText(this, R.string.updateSentenceFeedback, Toast.LENGTH_SHORT).show(); setResult(RESULT_OK); } finish(); } } private void addSpan() { final int start = _sentenceText.getSelectionStart(); final int end = _sentenceText.getSelectionEnd(); final ImmutableIntRange range = new ImmutableIntRange(start, end - 1); final String query = _sentenceText.getText().toString().substring(start, end); _state.setSelection(range); FixedTextAcceptationPickerActivity.open(this, REQUEST_CODE_PICK_ACCEPTATION, query); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_CODE_PICK_ACCEPTATION && resultCode == RESULT_OK && data != null) { final AcceptationId dynamicAcc = AcceptationIdBundler.readAsIntentExtra(data, FixedTextAcceptationPickerActivity.ResultKeys.DYNAMIC_ACCEPTATION); if (dynamicAcc != null) { _state.getSpans().put(new SentenceSpan<>(_state.getSelection(), dynamicAcc), 1); _sentenceText.setText(getRichText()); } } } @Override public void onResume() { super.onResume(); _listView.setAdapter(new SpanEditorAdapter(getText(), _state.getSpans(), map -> _sentenceText.setText(getRichText()))); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelable(SavedKeys.STATE, _state); } }
package org.commcare.resources.model; import org.commcare.resources.model.installers.ProfileInstaller; import org.commcare.util.CommCarePlatform; import org.commcare.util.LogTypes; import org.javarosa.core.reference.InvalidReferenceException; import org.javarosa.core.reference.Reference; import org.javarosa.core.reference.ReferenceManager; import org.javarosa.core.services.Logger; import org.javarosa.core.services.storage.IStorageIterator; import org.javarosa.core.services.storage.IStorageUtilityIndexed; import org.javarosa.core.util.SizeBoundUniqueVector; import org.javarosa.xml.util.InvalidStructureException; import org.javarosa.xml.util.UnfullfilledRequirementsException; import org.xmlpull.v1.XmlPullParserException; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Enumeration; import java.util.Hashtable; import java.util.NoSuchElementException; import java.util.Stack; import java.util.Vector; /** * A Resource Table maintains a set of Resource Records, * resolves dependencies between records, and provides hooks * for maintenance, updating, and initializing resources. * * @author ctsims */ public class ResourceTable { // TODO: We have too many vectors here. It's lazy and incorrect. Everything // should be using iterators, not VECTORS; private IStorageUtilityIndexed storage; private InstallerFactory factory; // nothing here public final static int RESOURCE_TABLE_EMPTY = 0; // this is the table currently being used by the app public final static int RESOURCE_TABLE_INSTALLED = 1; // in any number of intermediate stages public final static int RESOURCE_TABLE_PARTIAL = 2; // this is the table constructed in order to do an upgrade -- // means that it is not ready to upgrade the current table public final static int RESOURCE_TABLE_UPGRADE = 3; public static final int RESOURCE_TABLE_UNSTAGED = 4; public static final int RESOURCE_TABLE_UNCOMMITED = 5; private TableStateListener stateListener = null; private InstallCancelled cancellationChecker = null; private InstallStatsLogger installStatsLogger = null; private static final int NUMBER_OF_LOSSY_RETRIES = 3; // Tracks whether a compound resource has been added, requiring // recalculation of how many uninstalled resources there are. Where // 'compound resources' are those that contain references to more // resources, such as profile and suite resources. private boolean isResourceProgressStale = false; // Cache for profile and suite 'parent' resources which are used in // references resolution private final Hashtable<String, Resource> compoundResourceCache = new Hashtable<>(); private SizeBoundUniqueVector<Resource> mMissingResources = new SizeBoundUniqueVector<>(0); public ResourceTable() { } protected ResourceTable(IStorageUtilityIndexed storage, InstallerFactory factory) { this.storage = storage; this.factory = factory; } public boolean isEmpty() { return storage.getNumRecords() <= 0; } public static ResourceTable RetrieveTable(IStorageUtilityIndexed storage) { return RetrieveTable(storage, new InstallerFactory()); } public static ResourceTable RetrieveTable(IStorageUtilityIndexed storage, InstallerFactory factory) { return new ResourceTable(storage, factory); } public int getTableReadiness() { // TODO: this is very hard to fully specify without doing assertions // when preparing a table about appropriate states boolean isFullyInstalled = true; boolean isEmpty = true; boolean unstaged = false; boolean upgrade = false; boolean dirty = false; for (IStorageIterator it = storage.iterate(); it.hasMore(); ) { Resource r = (Resource)it.nextRecord(); if (r.getStatus() != Resource.RESOURCE_STATUS_INSTALLED) { isFullyInstalled = false; } if (r.getStatus() != Resource.RESOURCE_STATUS_UNINITIALIZED) { isEmpty = false; } if (r.getStatus() == Resource.RESOURCE_STATUS_UNSTAGED) { unstaged = true; } if (r.getStatus() == Resource.RESOURCE_STATUS_UPGRADE) { upgrade = true; } if (r.isDirty()) { dirty = true; } } if (dirty) { return RESOURCE_TABLE_UNCOMMITED; } if (isEmpty) { return RESOURCE_TABLE_EMPTY; } if (isFullyInstalled) { return RESOURCE_TABLE_INSTALLED; } if (unstaged) { return RESOURCE_TABLE_UNSTAGED; } if (upgrade) { return RESOURCE_TABLE_UPGRADE; } return RESOURCE_TABLE_PARTIAL; } public InstallerFactory getInstallers() { return factory; } public void addResource(Resource resource, ResourceInstaller initializer, String parentId, int status) { resource.setInstaller(initializer); resource.setParentId(parentId); addResource(resource, status); } public void addResource(Resource resource, ResourceInstaller initializer, String parentId) { addResource(resource, initializer, parentId, Resource.RESOURCE_STATUS_UNINITIALIZED); } public void addResource(Resource resource, int status) { if (resourceDoesntExist(resource)) { addResourceInner(resource, status); } } protected boolean resourceDoesntExist(Resource resource) { return storage.getIDsForValue(Resource.META_INDEX_RESOURCE_ID, resource.getResourceId()).size() == 0; } private void addResourceInner(Resource resource, int status) { resource.setStatus(status); if (resource.getID() != -1) { // Assume that we're going cross-table, so we need a new // RecordId. resource.setID(-1); // Check to make sure that there's no existing GUID for // this record. if (getResourceWithGuid(resource.getRecordGuid()) != null) { throw new RuntimeException("This resource record already exists."); } } commit(resource); } public Vector<Resource> getResourcesForParent(String parent) { Vector<Resource> v = new Vector<>(); for (Enumeration en = storage.getIDsForValue(Resource.META_INDEX_PARENT_GUID, parent).elements(); en.hasMoreElements(); ) { Resource r = (Resource)storage.read((Integer)en.nextElement()); v.addElement(r); } return v; } public Resource getResourceWithId(String id) { try { return (Resource)storage.getRecordForValue(Resource.META_INDEX_RESOURCE_ID, id); } catch (NoSuchElementException nsee) { return null; } } public Resource getResourceWithGuid(String guid) { try { return (Resource)storage.getRecordForValue(Resource.META_INDEX_RESOURCE_GUID, guid); } catch (NoSuchElementException nsee) { return null; } } private Resource getParentResource(Resource resource) { String parentId = resource.getParentId(); if (parentId != null && !"".equals(parentId)) { if (compoundResourceCache.containsKey(parentId)) { return compoundResourceCache.get(parentId); } else { try { Resource parent = (Resource)storage.getRecordForValue(Resource.META_INDEX_RESOURCE_GUID, parentId); compoundResourceCache.put(parentId, parent); return parent; } catch (NoSuchElementException nsee) { return null; } } } return null; } /** * Get the all the resources in this table's storage. */ private Vector<Resource> getResources() { Vector<Resource> v = new Vector<>(); for (IStorageIterator it = storage.iterate(); it.hasMore(); ) { Resource r = (Resource)it.nextRecord(); v.addElement(r); } return v; } /** * Get the all the resources in this table's storage. */ private Stack<Resource> getResourceStack() { Stack<Resource> v = new Stack<>(); for (IStorageIterator it = storage.iterate(); it.hasMore(); ) { Resource r = (Resource)it.nextRecord(); v.push(r); } return v; } /** * Get the resources in this table's storage that have a given status. */ private Stack<Resource> getResourceStackWithStatus(int status) { Stack<Resource> v = new Stack<>(); for (IStorageIterator it = storage.iterate(); it.hasMore(); ) { Resource r = (Resource)it.nextRecord(); if (r.getStatus() == status) { v.push(r); } } return v; } /** * Get stored resources that are unready for installation, that is, not of * installed, upgrade, or pending status. * * Resources that are: * - installed don't need anything * - marked as ready for upgrade are ready * - marked as pending aren't capable of installation yet * * @return Stack of resource records that aren't ready for installation */ private Stack<Resource> getUnreadyResources() { Stack<Resource> v = new Stack<>(); for (IStorageIterator it = storage.iterate(); it.hasMore(); ) { Resource r = (Resource)it.nextRecord(); if (r.getStatus() != Resource.RESOURCE_STATUS_INSTALLED && r.getStatus() != Resource.RESOURCE_STATUS_UPGRADE) { v.push(r); } } return v; } /** * Are all the resources ready to be installed or have already been * installed? */ public boolean isReady() { return getUnreadyResources().isEmpty(); } public void commitCompoundResource(Resource r, int status, int version) throws UnresolvedResourceException { if (r.getVersion() == Resource.RESOURCE_VERSION_UNKNOWN) { // Try to update the version. r.setVersion(version); } else { // Otherwise, someone screwed up Logger.log(LogTypes.TYPE_RESOURCES, "committing a resource with a known version."); } commitCompoundResource(r, status); } /** * Add a 'compound' resource, which has references to other resources. * * @param r profile, suite, media suite, or other 'compound' resource */ public void commitCompoundResource(Resource r, int status) { compoundResourceCache.put(r.getResourceId(), r); isResourceProgressStale = true; commit(r, status); } public void commit(Resource r, int status) { r.setStatus(status); commit(r); } public void commit(Resource r) { storage.write(r); } /** * Rolls back uncommitted resources from dirty states */ public void rollbackCommits(CommCarePlatform platform) { Stack<Resource> s = this.getResourceStack(); while (!s.isEmpty()) { Resource r = s.pop(); if (r.isDirty()) { this.commit(r, r.getInstaller().rollback(r, platform)); } } } /** * Install a resource by looping through its locations stopping at first * successful install. * * @param r Resource to install * @param invalid out-of-date locations to be avoided during resource * installation * @param upgrade Has an older version of the resource been installed? * @param platform The CommCare platform (specific profile and version) to * prepare against * @param master Backup resource table to look-up resources not found in * the current table * @param recovery true if we are undergoing missing resources recovery * @throws UnresolvedResourceException Raised when no definitions for * resource 'r' can't be found */ private void findResourceLocationAndInstall(Resource r, Vector<Reference> invalid, boolean upgrade, CommCarePlatform platform, ResourceTable master, boolean recovery) throws UnresolvedResourceException, UnfullfilledRequirementsException, InstallCancelledException { // TODO: Possibly check if resource status is local and proceeding to // skip this huge (although in reality like one step) chunk UnreliableSourceException unreliableSourceException = null; InvalidResourceException invalidResourceException = null; boolean handled = false; for (ResourceLocation location : r.getLocations()) { if (handled) { break; } if (location.isRelative()) { for (Reference ref : gatherLocationsRefs(location, r, this, master)) { if (!(location.getAuthority() == Resource.RESOURCE_AUTHORITY_LOCAL && invalid.contains(ref))) { try { handled = installResource(r, location, ref, this, platform, upgrade, recovery); } catch (InvalidResourceException e) { invalidResourceException = e; } catch (UnreliableSourceException use) { unreliableSourceException = use; } if (handled) { recordSuccess(r); break; } } } } else { try { handled = installResource(r, location, ReferenceManager.instance().DeriveReference(location.getLocation()), this, platform, upgrade, recovery); if (handled) { recordSuccess(r); break; } } catch (InvalidResourceException e) { invalidResourceException = e; } catch (InvalidReferenceException ire) { ire.printStackTrace(); // Continue until no resources can be found. } catch (UnreliableSourceException use) { unreliableSourceException = use; } } } if (!handled) { if (invalidResourceException != null) { throw invalidResourceException; } else if (unreliableSourceException == null) { // no particular failure to point our finger at. throw new UnresolvedResourceException(r, "No external or local definition could be found for resource " + r.getResourceId()); } else { // Expose the lossy failure rather than the generic one throw unreliableSourceException; } } } /** * Makes all of this table's resources available. * * @param master The global resource to prepare against. Used to * establish whether resources need to be fetched remotely * @param platform The platform (version and profile) to prepare against * @throws UnresolvedResourceException If a resource could not be * identified and is required * @throws UnfullfilledRequirementsException If some resources are * incompatible with the current * version of CommCare */ public void prepareResources(ResourceTable master, CommCarePlatform platform) throws UnresolvedResourceException, UnfullfilledRequirementsException, InstallCancelledException { Hashtable<String, Resource> masterResourceMap = null; if (master != null) { // avoid hitting storage in loops by front-loading resource // acquisition from master table masterResourceMap = getResourceMap(master); } Vector<Resource> unreadyResources = getUnreadyResources(); // install all unready resources. while (!unreadyResources.isEmpty()) { for (Resource r : unreadyResources) { prepareResource(master, platform, r, masterResourceMap); } // Installing resources may have exposed more unready resources // that need installing. unreadyResources = getUnreadyResources(); } } private static Hashtable<String, Resource> getResourceMap(ResourceTable table) { Hashtable<String, Resource> resourceMap = new Hashtable<>(); for (IStorageIterator it = table.storage.iterate(); it.hasMore(); ) { Resource r = (Resource)it.nextRecord(); resourceMap.put(r.getResourceId(), r); } return resourceMap; } /** * Makes all resources available until toInitialize is encountered. * * @param master The global resource to prepare against. Used to * establish whether resources need to be fetched remotely * @param platform The platform (version and profile) to prepare against * @param toInitialize The ID of a single resource after which the table * preparation can stop. * @throws UnresolvedResourceException Required resource couldn't be * identified * @throws UnfullfilledRequirementsException resource(s) incompatible with * current CommCare version */ public void prepareResourcesUpTo(ResourceTable master, CommCarePlatform platform, String toInitialize) throws UnresolvedResourceException, UnfullfilledRequirementsException, InstallCancelledException { Vector<Resource> unreadyResources = getUnreadyResources(); // install unready resources, until toInitialize has been installed. while (isResourceUninitialized(toInitialize) && !unreadyResources.isEmpty()) { for (Resource r : unreadyResources) { prepareResource(master, platform, r, null); } // Installing resources may have exposed more unready resources // that need installing. unreadyResources = getUnreadyResources(); } } /** * @param master The global resource to prepare against. Used to * establish whether resources need to be fetched * remotely * @param masterResourceMap Map from resource id to resources for master * table. Null when 'master' is, or when * pre-loading the resource map isn't worth it. */ private void prepareResource(ResourceTable master, CommCarePlatform platform, Resource r, Hashtable<String, Resource> masterResourceMap) throws UnresolvedResourceException, UnfullfilledRequirementsException, InstallCancelledException { boolean upgrade = false; Vector<Reference> invalid = new Vector<>(); if (master != null) { Resource peer; // obtain resource peer by looking up the current resource // in the master table if (masterResourceMap == null) { peer = master.getResourceWithId(r.getResourceId()); } else { peer = masterResourceMap.get(r.getResourceId()); } if (peer != null) { if (!r.isNewer(peer)) { // This resource doesn't need to be updated, copy // the existing resource into this table peer.mimick(r); commit(peer, Resource.RESOURCE_STATUS_INSTALLED); if (stateListener != null) { // copying a resource over shouldn't add anymore // resources to be processed stateListener.simpleResourceAdded(); } return; } // resource is newer than master version, so invalidate // old local resource locations. upgrade = true; invalid = ResourceTable.gatherResourcesLocalRefs(peer, master); } } findResourceLocationAndInstall(r, invalid, upgrade, platform, master, false); if (stateListener != null) { if (isResourceProgressStale) { // a compound resource was added, recalculate total resource count isResourceProgressStale = false; stateListener.compoundResourceAdded(this); } else { stateListener.simpleResourceAdded(); } } } /** * Force a recomputation of table stage progress; useful for resuming upgrades */ public void setResourceProgressStale() { isResourceProgressStale = true; } private boolean isResourceUninitialized(String resourceId) { Resource res = this.getResourceWithId(resourceId); return ((res == null) || (res.getStatus() == Resource.RESOURCE_STATUS_UNINITIALIZED)); } /** * Call the resource's installer, handling the logic around attempting * retries. * * @return Did the resource install successfully? */ private boolean installResource(Resource r, ResourceLocation location, Reference ref, ResourceTable table, CommCarePlatform platform, boolean upgrade, boolean recovery) throws UnresolvedResourceException, UnfullfilledRequirementsException, InstallCancelledException { UnreliableSourceException aFailure = null; for (int i = 0; i < NUMBER_OF_LOSSY_RETRIES + 1; ++i) { abortIfInstallCancelled(r); try { return r.getInstaller().install(r, location, ref, table, platform, upgrade, recovery); } catch (UnreliableSourceException use) { recordFailure(r, use); aFailure = use; } } Logger.log(LogTypes.TYPE_RESOURCES, "Install attempt unsuccessful from: " + ref.getURI() + "|" + aFailure.getMessage()); throw aFailure; } private void abortIfInstallCancelled(Resource r) throws InstallCancelledException { if (cancellationChecker != null && cancellationChecker.wasInstallCancelled()) { InstallCancelledException installException = new InstallCancelledException("Installation/upgrade was cancelled while processing " + r.getResourceId()); recordFailure(r, installException); throw installException; } } private void recordFailure(Resource resource, Exception e) { if (installStatsLogger != null) { installStatsLogger.recordResourceInstallFailure(resource.getResourceId(), e); } } private void recordSuccess(Resource resource) { if (installStatsLogger != null) { installStatsLogger.recordResourceInstallSuccess(resource.getResourceId()); } } /** * Prepare this table to be replaced by the incoming table, and incoming * table to replace it. * * All conflicting resources from this table will be unstaged so as to not * conflict with the incoming resources. Once the incoming table is fully * installed, this table's resources can then be fully removed where * relevant. * * @param incoming Table for which resource upgrades are applied */ public void upgradeTable(ResourceTable incoming, CommCarePlatform platform) throws UnresolvedResourceException { if (!incoming.isReady()) { throw new RuntimeException("Incoming table is not ready to be upgraded"); } // Everything incoming should be marked either ready or upgrade. // Upgrade elements should result in their counterpart in this table // being unstaged (which can be reverted). Hashtable<String, Resource> resourceMap = getResourceMap(this); for (IStorageIterator it = incoming.storage.iterate(); it.hasMore(); ) { Resource r = (Resource)it.nextRecord(); Resource peer = resourceMap.get(r.getResourceId()); if (peer == null) { // no corresponding resource in this table; use incoming addResource(r, Resource.RESOURCE_STATUS_INSTALLED); } else { if (r.isNewer(peer)) { // Mark as being ready to transition commit(peer, Resource.RESOURCE_STATUS_INSTALL_TO_UNSTAGE); if (!peer.getInstaller().unstage(peer, Resource.RESOURCE_STATUS_UNSTAGED, platform)) { // TODO: revert this resource table! throw new UnresolvedResourceException(peer, "Couldn't make room for new resource " + r.getResourceId() + ", upgrade aborted"); } else { // done commit(peer, Resource.RESOURCE_STATUS_UNSTAGED); } if (r.getStatus() == Resource.RESOURCE_STATUS_UPGRADE) { incoming.commit(r, Resource.RESOURCE_STATUS_UPGRADE_TO_INSTALL); if (r.getInstaller().upgrade(r, platform)) { incoming.commit(r, Resource.RESOURCE_STATUS_INSTALLED); } else { Logger.log(LogTypes.TYPE_RESOURCES, "Failed to upgrade resource: " + r.getDescriptor()); // REVERT! throw new RuntimeException("Failed to upgrade resource " + r.getDescriptor()); } } } // TODO Should anything happen if peer.getVersion() == // r.getVersion()? Consider children, IDs and the fact // resource locations could change } } } /** * Uninstall table by removing unstaged resources and those not present in * replacement table * * This method is the final step in an update, after this table has * already been moved to a placeholder table and been evaluated for * what resources are no longer necessary. * * If this table encounters any problems it will not intentionally * throw errors, assuming that it's preferable to leave data unremoved * rather than breaking the app. * * @param replacement Reference table; uninstall resources not also present * in this table */ public void uninstall(ResourceTable replacement, CommCarePlatform platform) { cleanup(); Hashtable<String, Resource> replacementMap = getResourceMap(replacement); for (IStorageIterator it = storage.iterate(); it.hasMore(); ) { Resource r = (Resource)it.nextRecord(); if (replacementMap.get(r.getResourceId()) == null || r.getStatus() == Resource.RESOURCE_STATUS_UNSTAGED) { // No entry in 'replacement' so it's no longer relevant // OR resource has been replaced, so flag for deletion try { r.getInstaller().uninstall(r, platform); } catch (Exception e) { Logger.log(LogTypes.TYPE_RESOURCES, "Error uninstalling resource " + r.getRecordGuid() + ". " + e.getMessage()); } } else if (r.getStatus() == Resource.RESOURCE_STATUS_DELETE) { // NOTE: Shouldn't be a way for this condition to occur, but check anyways... try { r.getInstaller().uninstall(r, platform); } catch (Exception e) { Logger.log(LogTypes.TYPE_RESOURCES, "Error uninstalling resource " + r.getRecordGuid() + ". " + e.getMessage()); } } } storage.removeAll(); } /** * Called on a table to restage any unstaged resources. * * @param incoming The table which unstaged this table's resources */ public void repairTable(ResourceTable incoming, CommCarePlatform platform) { Stack<Resource> s = this.getResourceStackWithStatus(Resource.RESOURCE_STATUS_UNSTAGED); while (!s.isEmpty()) { Resource resource = s.pop(); if (incoming != null) { // See if there's a competing resource Resource peer = incoming.getResourceWithId(resource.getResourceId()); // If there is, and it's been installed, unstage it to make room again if (peer != null && peer.getStatus() == Resource.RESOURCE_STATUS_INSTALLED) { incoming.commit(peer, Resource.RESOURCE_STATUS_INSTALL_TO_UPGRADE); // TODO: Is there anything we can do about this? Shouldn't it be an exception? if (!peer.getInstaller().unstage(peer, Resource.RESOURCE_STATUS_UPGRADE, platform)) { // TODO: IF there are errors here, signal that the incoming table // should just be wiped out. It's not in acceptable shape } else { incoming.commit(peer, Resource.RESOURCE_STATUS_UPGRADE); } } } // Way should be clear. this.commit(resource, Resource.RESOURCE_STATUS_UNSTAGE_TO_INSTALL); if (resource.getInstaller().revert(resource, this, platform)) { this.commit(resource, Resource.RESOURCE_STATUS_INSTALLED); } } } public void copyToTable(ResourceTable newTable) throws IllegalArgumentException { if (!newTable.isEmpty()) { throw new IllegalArgumentException("Can't copy into a table with data in it!"); } // Copy over all of our resources to the new table for (IStorageIterator it = storage.iterate(); it.hasMore(); ) { Resource r = (Resource)it.nextRecord(); r.setID(-1); newTable.commit(r); } } /** * String representation of the id, version, and status of all resources in * table. */ public String toString() { StringBuffer resourceDetails = new StringBuffer(); int maxLength = 0; for (IStorageIterator it = storage.iterate(); it.hasMore(); ) { Resource r = (Resource)it.nextRecord(); String line = "| " + r.getResourceId() + " | " + r.getVersion() + " | " + getStatusString(r.getStatus()) + " |\n"; resourceDetails.append(line); if (line.length() > maxLength) { maxLength = line.length(); } } StringBuffer header = new StringBuffer(); for (int i = 0; i < maxLength; ++i) { header.append("-"); } header.append("\n"); return header.append(resourceDetails.toString()).append(header.toString()).toString(); } public static String getStatusString(int status) { switch (status) { case Resource.RESOURCE_STATUS_UNINITIALIZED: return "Uninitialized"; case Resource.RESOURCE_STATUS_LOCAL: return "Local"; case Resource.RESOURCE_STATUS_INSTALLED: return "Installed"; case Resource.RESOURCE_STATUS_UPGRADE: return "Ready for Upgrade"; case Resource.RESOURCE_STATUS_DELETE: return "Flagged for Deletion"; case Resource.RESOURCE_STATUS_UNSTAGED: return "Unstaged"; case Resource.RESOURCE_STATUS_INSTALL_TO_UNSTAGE: return "Install->Unstage (dirty)"; case Resource.RESOURCE_STATUS_INSTALL_TO_UPGRADE: return "Install->Upgrade (dirty)"; case Resource.RESOURCE_STATUS_UNSTAGE_TO_INSTALL: return "Unstage->Install (dirty)"; case Resource.RESOURCE_STATUS_UPGRADE_TO_INSTALL: return "Upgrade->Install (dirty)"; default: return "Unknown"; } } /** * Destroy this table, but leave any of the files which are installed * untouched. This is useful after an upgrade if this is the temp table. */ public void destroy() { cleanup(); storage.removeAll(); } /** * Destroy this table, and also try very hard to remove any files installed * by it. This is important for rolling back botched upgrades without * leaving their files around. */ public void clear(CommCarePlatform platform) { cleanup(); Stack<Resource> s = this.getResourceStack(); int count = 0; while (!s.isEmpty()) { Resource r = s.pop(); if (r.getStatus() == Resource.RESOURCE_STATUS_UPGRADE) { try { r.getInstaller().uninstall(r, platform); count++; } catch (UnresolvedResourceException e) { // already gone! } } } if (count > 0) { Logger.log(LogTypes.TYPE_RESOURCES, "Cleaned up " + count + " records from table"); } storage.removeAll(); } protected void cleanup() { compoundResourceCache.clear(); for (IStorageIterator it = storage.iterate(); it.hasMore(); ) { Resource r = (Resource)it.nextRecord(); r.getInstaller().cleanup(); } } /** * Register the available resources in this table with the provided * CommCare platform. */ public void initializeResources(CommCarePlatform platform, boolean isUpgrade) throws ResourceInitializationException { SizeBoundUniqueVector<Resource> missingResources = new SizeBoundUniqueVector<>(storage.getNumRecords()); Vector<Resource> lateInit = new Vector<>(); for (IStorageIterator it = storage.iterate(); it.hasMore(); ) { Resource r = (Resource)it.nextRecord(); ResourceInstaller i = r.getInstaller(); if (i.requiresRuntimeInitialization()) { if (i instanceof ProfileInstaller) { lateInit.addElement(r); } else { attemptResourceInitialization(platform, isUpgrade, r, missingResources); } } } for (Resource r : lateInit) { attemptResourceInitialization(platform, isUpgrade, r, missingResources); } setMissingResources(missingResources); } private void attemptResourceInitialization(CommCarePlatform platform, boolean isUpgrade, Resource r, Vector<Resource> missingResources) throws ResourceInitializationException { try { r.getInstaller().initialize(platform, isUpgrade); } catch (FileNotFoundException e) { missingResources.add(r); } catch (IOException | InvalidStructureException | InvalidReferenceException | XmlPullParserException | UnfullfilledRequirementsException e) { throw new ResourceInitializationException(r, e); } } /** * Gather derived references for the resource's local locations. Relative * location references that have a parent are contextualized before being * added. * * @param r resource for which local location references are being gathered * @param t table to look-up the resource's parents in * @return all local references a resource's potential locations */ private static Vector<Reference> gatherResourcesLocalRefs(Resource r, ResourceTable t) { Vector<Reference> ret = new Vector<>(); for (ResourceLocation location : r.getLocations()) { if (location.isRelative()) { if (r.hasParent()) { Resource parent = t.getParentResource(r); if (parent != null) { // Get local references for the parent resource's // locations Vector<Reference> parentRefs = gatherResourcesLocalRefs(parent, t); for (Reference context : parentRefs) { addDerivedLocation(location, context, ret); } } } } else if (location.getAuthority() == Resource.RESOURCE_AUTHORITY_LOCAL) { addDerivedLocation(location, null, ret); } } return ret; } /** * Gather derived references for a particular (relative) location * corresponding to the given resource. If the parent isn't found in the * current resource table, then look in the master table. * * @param location Specific location for the given resource * @param r Resource for which local location references are being * gathered * @param t Table to look-up the resource's parents in * @param m Backup table to look-up the resource's parents in * @return All possible (derived) references pointing to a given locations */ private static Vector<Reference> gatherLocationsRefs(ResourceLocation location, Resource r, ResourceTable t, ResourceTable m) { Vector<Reference> ret = new Vector<>(); if (r.hasParent()) { Resource parent = t.getParentResource(r); // If the local table doesn't have the parent ref, try the master if (parent == null && m != null) { parent = m.getParentResource(r); } if (parent != null) { // loop over all local references for the parent Vector<Reference> parentRefs = explodeAllReferences(location.getAuthority(), parent, t, m); for (Reference context : parentRefs) { addDerivedLocation(location, context, ret); } } } return ret; } /** * Gather derived references for the resource's locations of a given type. * Relative location references that have a parent are contextualized * before being added. If a parent isn't found in the current resource * table, then look in the master table. * * @param type process locations with authorities of this type * @param r resource for which local location references are being gathered * @param t table to look-up the resource's parents in * @param m backup table to look-up the resource's parents in * @return all possible (derived) references pointing to a resource's * locations */ private static Vector<Reference> explodeAllReferences(int type, Resource r, ResourceTable t, ResourceTable m) { Vector<Reference> ret = new Vector<>(); for (ResourceLocation location : r.getLocations()) { if (location.getAuthority() == type) { if (location.isRelative()) { if (r.hasParent()) { Resource parent = t.getParentResource(r); // If the local table doesn't have the parent ref, try // the master if (parent == null) { parent = m.getParentResource(r); } if (parent != null) { // Get all local references for the parent Vector<Reference> parentRefs = explodeAllReferences(type, parent, t, m); for (Reference context : parentRefs) { addDerivedLocation(location, context, ret); } } } } else { addDerivedLocation(location, null, ret); } } } return ret; } /** * Derive a reference from the given location and context; adding it to the * vector of references. * * @param location Contains a reference to a resource. * @param context Provides context for any relative reference accessors. * Can be null. * @param ret Add derived reference of location to this Vector. */ private static void addDerivedLocation(ResourceLocation location, Reference context, Vector<Reference> ret) { try { final Reference derivedRef; if (context == null) { derivedRef = ReferenceManager.instance().DeriveReference(location.getLocation()); } else { // contextualize the location ref in terms of the multiple refs // pointing to different locations for the parent resource derivedRef = ReferenceManager.instance().DeriveReference(location.getLocation(), context); } ret.addElement(derivedRef); } catch (InvalidReferenceException e) { e.printStackTrace(); } } public void verifyInstallation(Vector<MissingMediaException> problems, CommCarePlatform platform) { Vector<Resource> resources = getResources(); int total = resources.size(); int count = 0; for (Resource r : resources) { r.getInstaller().verifyInstallation(r, problems, platform); count++; if (stateListener != null) { stateListener.incrementProgress(count, total); } if (cancellationChecker != null && cancellationChecker.wasInstallCancelled()) { break; } } } public void setStateListener(TableStateListener listener) { this.stateListener = listener; } public void setInstallCancellationChecker(InstallCancelled cancellationChecker) { this.cancellationChecker = cancellationChecker; } public void setInstallStatsLogger(InstallStatsLogger logger) { this.installStatsLogger = logger; } public boolean recoverResources(CommCarePlatform platform) throws InstallCancelledException, UnresolvedResourceException, UnfullfilledRequirementsException { int count = 0; int total = mMissingResources.size(); for (Resource missingResource : mMissingResources) { findResourceLocationAndInstall(missingResource, new Vector<>(), false, platform, null, true); count++; if (stateListener != null) { stateListener.incrementProgress(count, total); } if (cancellationChecker != null && cancellationChecker.wasInstallCancelled()) { break; } } return true; } private void setMissingResources(SizeBoundUniqueVector<Resource> missingResources) { mMissingResources = missingResources; } public SizeBoundUniqueVector<Resource> getMissingResources() { return mMissingResources; } }
package com.malhartech.demos.pi; import com.malhartech.api.ApplicationFactory; import com.malhartech.api.DAG; import com.malhartech.lib.io.ConsoleOutputOperator; import com.malhartech.lib.math.*; import com.malhartech.lib.stream.AbstractAggregator; import com.malhartech.lib.stream.ArrayListAggregator; import com.malhartech.lib.stream.Counter; import com.malhartech.lib.testbench.RandomEventGenerator; import org.apache.hadoop.conf.Configuration; /** * * @author Chetan Narsude <chetan@malhar-inc.com> */ public class Calculator implements ApplicationFactory { private final boolean allInline = false; @Override public DAG getApplication(Configuration conf) { DAG dag = new DAG(conf); ConsoleOutputOperator console = dag.addOperator("Console", ConsoleOutputOperator.class); /* keep generating random values between 0 and 30000 */ RandomEventGenerator xyGenerator = dag.addOperator("GenerateX", RandomEventGenerator.class); xyGenerator.setMinvalue(0); xyGenerator.setMaxvalue(30000); /* calculate square of each of the values it receives */ SquareCalculus squareOperator = dag.addOperator("SquareX", SquareCalculus.class); /* pair the consecutive values */ AbstractAggregator<Integer> pairOperator = dag.addOperator("PairXY", new ArrayListAggregator<Integer>()); pairOperator.setSize(2); Sigma<Integer> sumOperator = dag.addOperator("SumXY", new Sigma<Integer>()); LogicalCompareToConstant<Integer> comparator = dag.addOperator("AnalyzeLocation", new LogicalCompareToConstant<Integer>()); comparator.setConstant(30000 * 30000); Counter inCircle = dag.addOperator("CountInCircle", Counter.class); Counter inSquare = dag.addOperator("CountInSquare", Counter.class); Division division = dag.addOperator("Ratio", Division.class); MultiplyByConstant multiplication = dag.addOperator("InstantPI", MultiplyByConstant.class); multiplication.setMultiplier(4); RunningAverage<Double> average = dag.addOperator("AveragePI", new RunningAverage<Double>()); dag.addStream("x", xyGenerator.integer_data, squareOperator.input).setInline(allInline); dag.addStream("sqr", squareOperator.integerResult, pairOperator.input).setInline(allInline); dag.addStream("x2andy2", pairOperator.output, sumOperator.input).setInline(allInline); dag.addStream("x2plusy2", sumOperator.integerResult, comparator.input, inSquare.input).setInline(allInline); dag.addStream("inCirclePoints", comparator.greaterThan, inCircle.input).setInline(allInline); dag.addStream("numerator", inCircle.output, division.numerator).setInline(allInline); dag.addStream("denominator", inSquare.output, division.denominator).setInline(allInline); dag.addStream("ratio", division.doubleQuotient, multiplication.input).setInline(allInline); dag.addStream("instantPi", multiplication.doubleProduct, average.input).setInline(allInline); dag.addStream("averagePi", average.doubleAverage, console.input).setInline(allInline); return dag; } }
package za.co.codetribe.userhelpdesk; import android.app.ProgressDialog; import android.content.Intent; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.provider.SyncStateContract; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import butterknife.Bind; import butterknife.ButterKnife; import za.co.codetribe.userhelpdesk.helpdeskadmin.MainAdmin; import za.co.codetribe.userhelpdesk.transfer.ResponseDTO; import za.co.codetribe.userhelpdesk.utils.Constants; import za.co.codetribe.userhelpdesk.utils.HelpOkHttp; public class LoginActivity extends AppCompatActivity { @Bind(R.id.input_email) EditText emailText; @Bind(R.id.input_password) EditText passwordText; @Bind(R.id.btn_login) Button loginButton; TextView signupLink; Handler handler = new Handler(Looper.getMainLooper()); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); ButterKnife.bind(this); getSupportActionBar().hide(); loginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { login(); } }); } public void login() { String user_email = emailText.getText().toString(); final String password = passwordText.getText().toString(); String json_payload = ""; try { json_payload = new JSONObject() .put(Constants.email, user_email) .put(Constants.password,password) .put(Constants.requestType,Constants.loginRequestType) .toString(); } catch (JSONException e) { e.printStackTrace(); } final String json_pay = json_payload; final HelpOkHttp helpOkHttp = new HelpOkHttp(); Thread thread = new Thread(new Runnable() { @Override public void run() { try { //Log.i("Ygritte", Constants.helpDeskUrl); //Log.i("Ygritte", json_pay); String res = helpOkHttp.post(Constants.helpDeskUrl+"?JSON="+json_pay, json_pay); /* * {"administratoDTO": * {"administratorID":1,"firstName":"Tshego","lastName":"Masilo","email":"tshego.masilo@absa.co.za","telephoneNo":"0128406110","cellNo":"0839586412","password":"Password","companyID":1,"activeFlag":false} * ,"companyDTO":{"companyID":1,"companyName":"ABSA","email":"info@absa.co.za","telephoneNo":"0117028965","activeFlag":true} * ,"statusCode":100, * "message":"Administrator has login successfully", * "requestType":0} * */ JSONObject jsonObject = new JSONObject(res); Log.i("Ygritte", res); JSONObject administrator = jsonObject.getJSONObject("administratoDTO"); JSONObject company = jsonObject.getJSONObject("companyDTO"); String first_name = administrator.getString("firstName"); // JSONObject administratorJsonObject = jsonObject.getJSONObject() String statusCode = jsonObject.getString("statusCode"); //String TelephoneNo = jsonObject.getJSONObject("administratoDTO").getString("telephoneNo"); String message = jsonObject.getString("message"); if (statusCode == "0") { showToast("Login Failed"); } else { showToast("Login Success "+statusCode+" My Name is : "+first_name); handler.postDelayed(new Runnable() { @Override public void run() { Intent intent = new Intent (LoginActivity.this, MainAdmin.class); startActivity(intent); } },1000); } //String breakPoint = jsonObject.ge //ResponseDTO dto = new ResponseDTO(res); //Your code goes here Log.i("Tshego ;)",res); } catch (Exception e) { e.printStackTrace(); } } }); thread.start(); //System.out.println(response); /* if (!validate()) { onLoginFailed(); return; }*/ /* loginButton.setEnabled(false); final ProgressDialog progressDialog = new ProgressDialog(LoginActivity.this,R.style.AppTheme); progressDialog.setIndeterminate(true); progressDialog.setMessage("Logging in..."); progressDialog.show(); new android.os.Handler().postDelayed( new Runnable() { public void run() { // On complete call either onLoginSuccess or onLoginFailed onLoginSuccess(); // onLoginFailed(); progressDialog.dismiss(); } }, 3000); */ } public void onBackPressed() { moveTaskToBack(true); } public void onLoginSuccess() { loginButton.setEnabled(true); String email = emailText.getText().toString(); String password = passwordText.getText().toString(); if(email.toLowerCase() == "t") { Intent intent = new Intent(this, MainActivity.class); startActivity(intent); } else if(email.toLowerCase() == "u") { Intent intent = new Intent(this, HomeActivity.class); startActivity(intent); }else if(email.toLowerCase() == "a") { Intent intent = new Intent(this, HomeActivity.class); startActivity(intent); } } public void onLoginFailed() { Toast.makeText(getBaseContext(), "Login failed", Toast.LENGTH_LONG).show(); loginButton.setEnabled(true); } public boolean validate() { boolean valid = true; String email = emailText.getText().toString(); String password = passwordText.getText().toString(); if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) { emailText.setError("enter a valid email address"); valid = false; } else { emailText.setError(null); } if (password.isEmpty() || password.length() < 4 || password.length() > 10) { passwordText.setError("between 4 and 10 alphanumeric characters"); valid = false; } else { passwordText.setError(null); } return valid; } public void showToast(final String toast) { runOnUiThread(new Runnable() { public void run() { Toast.makeText(LoginActivity.this, toast, Toast.LENGTH_SHORT).show(); } }); } public void navigateActivity() { runOnUiThread(new Runnable() { public void run() { Intent intent = new Intent(LoginActivity.this, MainActivity.class); startActivity(intent); } }); } }
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.parser.Translator; 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.ListSelectionModel; 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.*; import reb2sac.Reb2Sac; import reb2sac.Run; import sbmleditor.SBML_Editor; import buttons.Buttons; import datamanager.DataManager; import java.net.*; import uk.ac.ebi.biomodels.*; //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 newS; // The new assembly file menu item private JMenuItem newInst; // The new instruction file 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 importS; // The import assembly file menu item private JMenuItem importInst; // The import instruction file 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 String[] BioModelIds = null; 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, saveSbml, saveTemp, saveModel, viewSG, 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"); newVhdl = new JMenuItem("VHDL-AMS Model"); newS = new JMenuItem("Assembly File"); newInst = new JMenuItem("Instruction File"); 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"); importVhdl = new JMenuItem("VHDL-AMS Model"); importS = new JMenuItem("Assembly File"); importInst = new JMenuItem("Instruction File"); 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"); if (async) { saveModel = new JMenuItem("Save Models"); } else { saveModel = new JMenuItem("Save GCM"); } 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"); viewSG = new JMenuItem("State Graph"); 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); newS.addActionListener(this); newInst.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); importS.addActionListener(this); importInst.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); saveModel.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); viewSG.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"); viewSG.setActionCommand("stateGraph"); 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 { importLpn.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); importS.setEnabled(false); importInst.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); newS.setEnabled(false); newInst.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); saveModel.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); viewSG.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(newLhpn); 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(newS); newMenu.add(newInst); 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(saveModel); // file.add(saveParam); file.add(run); if (!async) { file.add(check); } file.addSeparator(); file.add(importMenu); if (!async) { importMenu.add(importDot); importMenu.add(importLpn); 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(importS); importMenu.add(importInst); importMenu.add(importLpn); // 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(viewSG); 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(0)).save(); else if (e.getSource() == saveModel) { Component comp = tab.getSelectedComponent(); if (comp instanceof JTabbedPane) { for (Component component : ((JTabbedPane) comp).getComponents()) { if (component instanceof Learn) { ((Learn) component).saveGcm(); } else if (component instanceof LearnLHPN) { ((LearnLHPN) component).saveLhpn(); } } } } 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(); Translator t1 = new Translator(); t1.BuildTemplate(tree.getFile()); } 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(); } else if (e.getActionCommand().equals("convertToSBML")) { new Translator().BuildTemplate(tree.getFile()); refreshTree(); } // 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) == 0) { 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 (IOException 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 (IOException 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(root); 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) { GeneticNetwork.setRoot(root + File.separator); 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 { GeneticNetwork.setRoot(root + File.separator); 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(root); 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, theFile.replace(".gcm", "") + ".lpn"); } else { // Do nothing } } else { gcm.createLogicalModel(root + File.separator + theFile.replace(".gcm", "") + ".lpn", log, this, 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); } } else if (e.getActionCommand().equals("stateGraph")) { try { String directory = root + separator + tab.getTitleAt(tab.getSelectedIndex()); File work = new File(directory); for (String f : new File(directory).list()) { if (f.contains("_sg.dot")) { Runtime exec = Runtime.getRuntime(); if (System.getProperty("os.name").contentEquals("Linux")) { log.addText("Executing:\ndotty " + directory + separator + f + "\n"); exec.exec("dotty " + f, null, work); } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { log.addText("Executing:\nopen " + directory + separator + f + "\n"); exec.exec("open " + f, null, work); } else { log.addText("Executing:\ndotty " + directory + separator + f + "\n"); exec.exec("dotty " + f, null, work); } return; } } JOptionPane.showMessageDialog(frame, "State graph file has not been generated.", "Error", JOptionPane.ERROR_MESSAGE); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Error viewing state graph.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the graph popup menu is selected on an sbml file else if (e.getActionCommand().equals("graph")) { String directory = ""; String theFile = ""; if (!treeSelected) { Component comp = tab.getSelectedComponent(); if (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); if (component instanceof Learn) { ((Learn) component).viewGcm(); return; } } else if (comp instanceof LHPNEditor) { try { String filename = tab.getTitleAt(tab.getSelectedIndex()); String[] findTheFile = filename.split("\\."); 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); } return; } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this lpn.", "Error", JOptionPane.ERROR_MESSAGE); return; } } else if (comp instanceof SBML_Editor) { directory = root + separator; theFile = tab.getTitleAt(tab.getSelectedIndex()); } else if (comp instanceof GCM2SBMLEditor) { directory = root + separator; theFile = tab.getTitleAt(tab.getSelectedIndex()); } } else { 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); } 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; } } } File work = new File(directory); String out = theFile; try { if (out.contains(".lpn")) { String file = theFile; String[] findTheFile = file.split("\\."); theFile = findTheFile[0] + ".dot"; File dot = new File(root + separator + theFile); dot.delete(); String cmd = "atacs -cPllodpl " + file; 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); } return; } 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); } else if (out.length() > 3 && out.substring(out.length() - 4, out.length()).equals(".gcm")) { try { 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); } return; } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this gcm file.", "Error", JOptionPane.ERROR_MESSAGE); return; } } 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, directory, 314159, 1, new String[0], new String[0], "tsd.printer", "amount", (directory + theFile).split(separator), "none", frame, directory + theFile, 0.1, 0.1, 0.1, 15, dummy, "", dummy, null, empty, empty, empty); 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 (theFile.substring(theFile.length() - 4).equals("sbml")) { remove = (directory + theFile).substring(0, (directory + theFile).length() - 4) + "properties"; } else { remove = (directory + theFile).substring(0, (directory + theFile).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")) { String directory; String theFile; if (!treeSelected) { Component comp = tab.getSelectedComponent(); if (comp instanceof SBML_Editor) { if (save(tab.getSelectedIndex(), 0) != 1) { return; } theFile = tab.getTitleAt(tab.getSelectedIndex()); directory = root + separator; } else { return; } } else { String filename = tree.getFile(); directory = ""; 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); } 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; } } } 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); } try { 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, directory, 314159, 1, new String[0], new String[0], "tsd.printer", "amount", (directory + theFile).split(separator), "none", frame, directory + theFile, 0.1, 0.1, 0.1, 15, dummy, "", dummy, null, empty, empty, empty); log.addText("Executing:\nreb2sac --target.encoding=xhtml --out=" + directory + out + ".xhtml " + directory + theFile + "\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 (theFile.substring(theFile.length() - 4).equals("sbml")) { remove = (directory + theFile).substring(0, (directory + theFile).length() - 4) + "properties"; } else { remove = (directory + theFile).substring(0, (directory + theFile).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")) { if * (!treeSelected) { Component comp = tab.getSelectedComponent(); if * (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) * comp).getSelectedComponent(); if (component instanceof Learn) { * ((Learn) component).viewGcm(); } } } else { 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).save(); } else if (component instanceof LearnLHPN) { ((LearnLHPN) component).save(); } 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(".s")) { newName = JOptionPane.showInputDialog(frame(), "Enter Assembly File Name:", "Assembly File Name", JOptionPane.PLAIN_MESSAGE); if (newName == null) { return; } if (!newName.endsWith(".s")) { newName = newName + ".s"; } } else if (fileName.endsWith(".inst")) { newName = JOptionPane.showInputDialog(frame(), "Enter Instruction File Name:", "Instruction File Name", JOptionPane.PLAIN_MESSAGE); if (newName == null) { return; } if (!newName.endsWith(".inst")) { newName = newName + ".inst"; } } 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); importS.setEnabled(true); importInst.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); newS.setEnabled(true); newInst.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); importS.setEnabled(true); importInst.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); newS.setEnabled(true); newInst.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() > 3) { 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(root).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() > 3) { if (!vhdlName.substring(vhdlName.length() - 4).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(); refreshTree(); 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 assembly menu item is selected else if (e.getSource() == newS) { if (root != null) { try { String SName = JOptionPane.showInputDialog(frame, "Enter Assembly File Name:", "Assembly File Name", JOptionPane.PLAIN_MESSAGE); if (SName != null && !SName.trim().equals("")) { SName = SName.trim(); if (SName.length() > 1) { if (!SName.substring(SName.length() - 2).equals(".s")) { SName += ".s"; } } else { SName += ".s"; } String modelID = ""; if (SName.length() > 1) { if (SName.substring(SName.length() - 2).equals(".s")) { modelID = SName.substring(0, SName.length() - 2); } else { modelID = SName.substring(0, SName.length() - 1); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane .showMessageDialog( frame, "A assembly file name can only contain letters, numbers, and underscores.", "Invalid File Name", JOptionPane.ERROR_MESSAGE); } else { File f = new File(root + separator + SName); f.createNewFile(); refreshTree(); if (externView) { String command = viewerField.getText() + " " + root + separator + SName; 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(SName, scroll, "Assembly File Editor"); } } } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to create new assembly file.", "Error", JOptionPane.ERROR_MESSAGE); } } } // if the new instruction file menu item is selected else if (e.getSource() == newInst) { if (root != null) { try { String InstName = JOptionPane.showInputDialog(frame, "Enter Instruction File Name:", "Instruction File Name", JOptionPane.PLAIN_MESSAGE); if (InstName != null && !InstName.trim().equals("")) { InstName = InstName.trim(); if (InstName.length() > 4) { if (!InstName.substring(InstName.length() - 5).equals(".inst")) { InstName += ".inst"; } } else { InstName += ".inst"; } String modelID = ""; if (InstName.length() > 4) { if (InstName.substring(InstName.length() - 5).equals(".inst")) { modelID = InstName.substring(0, InstName.length() - 5); } else { modelID = InstName.substring(0, InstName.length() - 4); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane .showMessageDialog( frame, "A instruction file name can only contain letters, numbers, and underscores.", "Invalid File Name", JOptionPane.ERROR_MESSAGE); } else { File f = new File(root + separator + InstName); f.createNewFile(); refreshTree(); if (externView) { String command = viewerField.getText() + " " + root + separator + InstName; 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(InstName, scroll, "Instruction File Editor"); } } } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to create new instruction file.", "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() > 1) { if (!vhdlName.substring(vhdlName.length() - 2).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(); refreshTree(); 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(); refreshTree(); 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(); refreshTree(); 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(); refreshTree(); 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(); refreshTree(); 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(); refreshTree(); 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); checkModelCompleteness(document); 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])) { checkModelCompleteness(document); 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) { final BioModelsWSClient client = new BioModelsWSClient(); if (BioModelIds == null) { try { BioModelIds = client.getAllCuratedModelsId(); } catch (BioModelsWSException e2) { JOptionPane.showMessageDialog(frame, "Error Contacting BioModels Database", "Error", JOptionPane.ERROR_MESSAGE); } } JPanel BioModelsPanel = new JPanel(new BorderLayout()); final JList ListOfBioModels = new JList(); sort(BioModelIds); ListOfBioModels.setListData(BioModelIds); ListOfBioModels.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); JLabel TextBioModels = new JLabel("List of BioModels"); JScrollPane ScrollBioModels = new JScrollPane(); ScrollBioModels.setMinimumSize(new Dimension(520, 250)); ScrollBioModels.setPreferredSize(new Dimension(552, 250)); ScrollBioModels.setViewportView(ListOfBioModels); JPanel GetButtons = new JPanel(); JButton GetNames = new JButton("Get Names"); JButton GetDescription = new JButton("Get Description"); JButton GetReference = new JButton("Get Reference"); GetNames.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { for (int i = 0; i < BioModelIds.length; i++) { try { BioModelIds[i] += " " + client.getModelNameById(BioModelIds[i]); } catch (BioModelsWSException e1) { JOptionPane.showMessageDialog(frame, "Error Contacting BioModels Database", "Error", JOptionPane.ERROR_MESSAGE); } } ListOfBioModels.setListData(BioModelIds); } }); GetDescription.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String SelectedModel = ((String) ListOfBioModels.getSelectedValue()) .split(" ")[0]; String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { command = "gnome-open http: + SelectedModel; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { command = "open http: + SelectedModel; } else { command = "cmd /c start http: + SelectedModel; } log.addText("Executing:\n" + command + "\n"); Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to open model description.", "Error", JOptionPane.ERROR_MESSAGE); } } }); GetReference.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String SelectedModel = ((String) ListOfBioModels.getSelectedValue()) .split(" ")[0]; try { String Pub = (client.getSimpleModelById(SelectedModel)) .getPublicationId(); String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { command = "gnome-open http: + Pub; } else if (System.getProperty("os.name").toLowerCase().startsWith( "mac os")) { command = "open http: + Pub; } else { command = "cmd /c start http: + Pub; } log.addText("Executing:\n" + command + "\n"); Runtime exec = Runtime.getRuntime(); exec.exec(command); } catch (BioModelsWSException e2) { JOptionPane.showMessageDialog(frame, "Error Contacting BioModels Database", "Error", JOptionPane.ERROR_MESSAGE); } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to open model description.", "Error", JOptionPane.ERROR_MESSAGE); } } }); GetButtons.add(GetNames); GetButtons.add(GetDescription); GetButtons.add(GetReference); BioModelsPanel.add(TextBioModels, "North"); BioModelsPanel.add(ScrollBioModels, "Center"); BioModelsPanel.add(GetButtons, "South"); Object[] options = { "OK", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, BioModelsPanel, "List of BioModels", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); /* * String modelNumber = JOptionPane.showInputDialog(frame, * "Enter BioModel Number:", "BioModel Number", * JOptionPane.PLAIN_MESSAGE); */ // if (modelNumber != null && !modelNumber.equals("")) { if (value == JOptionPane.YES_OPTION) { String BMurl = "http: String filename = ((String) ListOfBioModels.getSelectedValue()).split(" ")[0]; /* * String filename = "BIOMD"; for (int i = 0; i < 10 - * modelNumber.length(); i++) { filename += "0"; } filename * += modelNumber + ".xml"; */ filename += ".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(); */ if (overwrite(root + separator + filename, filename)) { 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"); String[] file = filename.trim().split(separator); SBMLDocument document = readSBML(root + separator + filename.trim()); 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 (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 = ""; } 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); } } else if (e.getSource() == importS) { 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 Assembly File", -1); if (filename.length() > 1 && !filename.substring(filename.length() - 2, filename.length()).equals( ".s")) { JOptionPane.showMessageDialog(frame, "You must select a valid assembly 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); } } else if (e.getSource() == importInst) { 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 Instruction File", -1); if (filename.length() > 4 && !filename.substring(filename.length() - 5, filename.length()).equals( ".inst")) { JOptionPane.showMessageDialog(frame, "You must select a valid instruction 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); } } 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 (IOException 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", "_sg.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", "_sg.dot")) + "\n"); Runtime exec = Runtime.getRuntime(); File work = new File(root); try { exec.exec(command + (file.replace(".lpn", "_sg.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", "_sg.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", "_sg.dot")) + "\n"); Runtime exec = Runtime.getRuntime(); File work = new File(root); try { exec.exec(command + (file.replace(".lpn", "_sg.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( ".s")) { if (copy.length() > 1) { if (!copy.substring(copy.length() - 2).equals(".s")) { copy += ".s"; } } else { copy += ".s"; } } else if (tree.getFile().length() >= 5 && tree.getFile().substring(tree.getFile().length() - 5).equals( ".inst")) { if (copy.length() > 4) { if (!copy.substring(copy.length() - 5).equals(".inst")) { copy += ".inst"; } } else { copy += ".inst"; } } 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(".s")) || (tree.getFile().length() >= 5 && tree.getFile().substring( tree.getFile().length() - 5).equals(".inst")) || (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() >= 2 && tree.getFile().substring(tree.getFile().length() - 2).equals( ".s")) { if (rename.length() > 1) { if (!rename.substring(rename.length() - 2).equals(".s")) { rename += ".s"; } } else { rename += ".s"; } } else if (tree.getFile().length() >= 5 && tree.getFile().substring(tree.getFile().length() - 5).equals( ".inst")) { if (rename.length() > 4) { if (!rename.substring(rename.length() - 5).equals(".inst")) { rename += ".inst"; } } else { rename += ".inst"; } } 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(); try { mainPanel.validate(); } catch (Exception e) { } 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 Model"); graph.addActionListener(this); graph.addMouseListener(this); graph.setActionCommand("graph"); JMenuItem browse = new JMenuItem("View Model 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 Model"); graph.addActionListener(this); graph.addMouseListener(this); graph.setActionCommand("graph"); 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 convertToSBML = new JMenuItem("Convert To SBML"); convertToSBML.addActionListener(this); convertToSBML.addMouseListener(this); convertToSBML.setActionCommand("convertToSBML"); 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(convertToSBML); 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() > 1 && tree.getFile().substring(tree.getFile().length() - 2).equals(".s")) { // JMenuItem createAnalysis = new // JMenuItem("Create Analysis View"); // createAnalysis.addActionListener(this); // createAnalysis.addMouseListener(this); // createAnalysis.setActionCommand("createSim"); // 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"); // 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(".inst")) { // JMenuItem createAnalysis = new // JMenuItem("Create Analysis View"); // createAnalysis.addActionListener(this); // createAnalysis.addMouseListener(this); // createAnalysis.setActionCommand("createSim"); // 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"); // 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(".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; boolean learn = 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; } if (s.length() > 3 && s.substring(s.length() - 4).equals(".lrn")) { learn = true; } } JMenuItem open; if (sim) { open = new JMenuItem("Open Analysis View"); open.addActionListener(this); open.addMouseListener(this); open.setActionCommand("openSim"); popup.add(open); } else if (synth) { open = new JMenuItem("Open Synthesis View"); open.addActionListener(this); open.addMouseListener(this); open.setActionCommand("openSynth"); popup.add(open); } else if (ver) { open = new JMenuItem("Open Verification View"); open.addActionListener(this); open.addMouseListener(this); open.setActionCommand("openVerification"); popup.add(open); } else if (learn) { open = new JMenuItem("Open Learn View"); open.addActionListener(this); open.addMouseListener(this); open.setActionCommand("openLearn"); popup.add(open); } if (sim || ver || synth || learn) { 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.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() >= 2 && tree.getFile().substring(tree.getFile().length() - 2).equals(".s")) { 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, "Assembly File Editor"); } } // String[] command = { "emacs", filename }; // Runtime.getRuntime().exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this assembly file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 5 && tree.getFile().substring(tree.getFile().length() - 5) .equals(".inst")) { 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, "Instruction File Editor"); } } // String[] command = { "emacs", filename }; // Runtime.getRuntime().exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this instruction 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; 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() > 3 && s.substring(s.length() - 4).equals(".syn")) { synth = true; } else if (s.length() > 3 && s.substring(s.length() - 4).equals(".ver")) { ver = true; } else if (s.length() > 3 && s.substring(s.length() - 4).equals(".lrn")) { learn = true; } } if (sim) { openSim(); } else if (synth) { openSynth(); } else if (ver) { openVerify(); } else if (learn) { 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 Model"); graph.addActionListener(this); graph.addMouseListener(this); graph.setActionCommand("graph"); JMenuItem browse = new JMenuItem("View Model 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 Model"); graph.addActionListener(this); graph.addMouseListener(this); graph.setActionCommand("graph"); 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; 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; } } JMenuItem open; if (sim) { open = new JMenuItem("Open Analysis View"); open.addActionListener(this); open.addMouseListener(this); open.setActionCommand("openSim"); popup.add(open); } else if (synth) { open = new JMenuItem("Open Synthesis View"); open.addActionListener(this); open.addMouseListener(this); open.setActionCommand("openSynth"); popup.add(open); } else if (ver) { open = new JMenuItem("Open Verification View"); open.addActionListener(this); open.addMouseListener(this); open.setActionCommand("openVerification"); popup.add(open); } else if (learn) { open = new JMenuItem("Open Learn View"); open.addActionListener(this); open.addMouseListener(this); open.setActionCommand("openLearn"); popup.add(open); } if (sim || ver | learn | synth) { 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.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 (IOException 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) == 0) { 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 (IOException 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) == 0) { 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) == 0) { 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) == 0) { 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) == 0) { 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) == 0) { 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(importLpn); popup.add(importCsp); popup.add(importHse); popup.add(importUnc); popup.add(importRsg); } else { popup.add(importVhdl); popup.add(importS); popup.add(importInst); popup.add(importLpn); 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(root); 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); } public 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); viewSG.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); saveModel.setEnabled(false); saveSbml.setEnabled(true); saveTemp.setEnabled(true); viewModGraph.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); saveModel.setEnabled(false); viewModGraph.setEnabled(true); } 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); saveModel.setEnabled(false); saveSbml.setEnabled(true); saveTemp.setEnabled(true); viewModGraph.setEnabled(true); viewModBrowser.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); saveModel.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; } else if (c instanceof GCM2SBMLEditor) { for (String s : new File(root + separator + tab.getTitleAt(tab.getSelectedIndex())).list()) { if (s.contains("_sg.dot")) { viewSG.setEnabled(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); saveModel.setEnabled(true); } else { run.setEnabled(true); saveModel.setEnabled(false); } 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(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); 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); saveModel.setEnabled(false); 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(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); 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); saveModel.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (component instanceof GCM2SBMLEditor) { saveButton.setEnabled(true); saveasButton.setEnabled(false); 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); 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); saveModel.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (component instanceof Learn) { if (((Learn) component).isComboSelected()) { frame.getGlassPane().setVisible(false); } // saveButton.setEnabled(((Learn) // component).getSaveGcmEnabled()); saveButton.setEnabled(true); saveasButton.setEnabled(false); runButton.setEnabled(true); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); // save.setEnabled(((Learn) component).getSaveGcmEnabled()); 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(((Learn) component).getViewGcmEnabled()); 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); saveModel.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()); saveButton.setEnabled(true); saveasButton.setEnabled(false); runButton.setEnabled(true); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); // save.setEnabled(((LearnLHPN) // component).getSaveLhpnEnabled()); 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); 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); saveModel.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); saveModel.setEnabled(true); 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(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); 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); saveModel.setEnabled(false); 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(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); 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); saveModel.setEnabled(false); 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); saveModel.setEnabled(false); } 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); saveModel.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); saveModel.setEnabled(false); 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); saveModel.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); viewSG.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); saveModel.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); saveModel.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); saveModel.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); saveModel.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); saveModel.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); saveModel.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); saveModel.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); saveModel.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); saveModel.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); saveModel.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); saveModel.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); saveModel.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); saveModel.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 boolean 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); return true; } } } return false; } public boolean updateOpenLHPN(String lhpnName) { for (int i = 0; i < tab.getTabCount(); i++) { String tab = this.tab.getTitleAt(i); if (lhpnName.equals(tab)) { if (this.tab.getComponentAt(i) instanceof LHPNEditor) { LHPNEditor newLHPN = new LHPNEditor(root, lhpnName, null, this, log); this.tab.setComponentAt(i, newLHPN); this.tab.getComponentAt(i).setName("LHPN Editor"); return true; } } } return 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; } public static void checkModelCompleteness(SBMLDocument document) { JTextArea messageArea = new JTextArea(); messageArea.append("Model is incomplete. Cannot be simulated until the following information is provided.\n"); boolean display = false; Model model = document.getModel(); ListOf list = model.getListOfCompartments(); for (int i=0; i<model.getNumCompartments(); i++) { Compartment compartment = (Compartment)list.get(i); if (!compartment.isSetSize()) { messageArea .append(" messageArea.append("Compartment " + compartment.getId() + " needs a size.\n"); display = true; } } list = model.getListOfSpecies(); for (int i=0; i<model.getNumSpecies(); i++) { Species species = (Species)list.get(i); if (!(species.isSetInitialAmount()) && !(species.isSetInitialConcentration())) { messageArea .append(" messageArea.append("Species " + species.getId() + " needs an initial amount or concentration.\n"); display = true; } } list = model.getListOfParameters(); for (int i=0; i<model.getNumParameters(); i++) { Parameter parameter = (Parameter)list.get(i); if (!(parameter.isSetValue())) { messageArea .append(" messageArea.append("Parameter " + parameter.getId() + " needs an initial value.\n"); display = true; } } list = model.getListOfReactions(); for (int i=0; i<model.getNumReactions(); i++) { Reaction reaction = (Reaction)list.get(i); if (!(reaction.isSetKineticLaw())) { messageArea .append(" messageArea.append("Reaction " + reaction.getId() + " needs a kinetic law.\n"); display = true; } else { ListOf params = reaction.getKineticLaw().getListOfParameters(); for (int j=0; j<reaction.getKineticLaw().getNumParameters(); j++) { Parameter param = (Parameter)params.get(j); if (!(param.isSetValue())) { messageArea .append(" messageArea.append("Local parameter " + param.getId() + " for reaction " + reaction.getId() + " needs an initial value.\n"); display = true; } } } } if (display) { final JFrame f = new JFrame("SBML Model Completeness Errors"); 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); } } }
package com.github.detro.jsonconf; import com.google.gson.*; import com.jayway.jsonpath.internal.PathToken; import com.jayway.jsonpath.internal.PathTokenizer; import java.io.*; import java.util.Iterator; import java.util.Map; import java.util.Properties; public class JSONConfBuilder { public static final String DEFAULT_CLI_PROPERTIES_ARRAY_NAME = "json"; private static final Gson DEFAULT_GSON = new GsonBuilder() .serializeNulls() .create(); private String defaultConfFilePath; private String userConfFilePath = null; private Properties sysProps = System.getProperties(); private String CLIPropsArrayName = DEFAULT_CLI_PROPERTIES_ARRAY_NAME; private Gson gson = DEFAULT_GSON; /** * Creates a ConfigurationBuilder (Builder Pattern) * * @param defaultConfFilePath Path to the Default Configuration File. * "null" string will determine an empty (but valid) configuration file. */ public JSONConfBuilder(String defaultConfFilePath) { this.defaultConfFilePath = defaultConfFilePath; } /** * Creates a ConfigurationBuilder (Builder Pattern) * * @param defaultConfFilePath Path to the Default Configuration File. * "null" string will determine an empty (but valid) configuration file. * @param userConfFilePath Path to the User Configuration File * "null" string will determine an empty (but valid) configuration file. */ public JSONConfBuilder(String defaultConfFilePath, String userConfFilePath) { this.defaultConfFilePath = defaultConfFilePath; this.userConfFilePath = userConfFilePath; } /** * Provide path to the User Configuration File * * @param userConfFilePath Path to the User Configuration File * "null" string will determine an empty (but valid) configuration file. * @return Same ConfigurationBuilder instance (for chaining) */ public JSONConfBuilder withUserConfFilePath(String userConfFilePath) { this.userConfFilePath = userConfFilePath; return this; } /** * Provide Properties in which to look for CLI Properties Array. * If not configured, this builder will use {@link System#getProperties()} * * @param sysProps Properties container * @return Same ConfigurationBuilder instance (for chaining) */ public JSONConfBuilder withSystemProperties(Properties sysProps) { this.sysProps = sysProps; return this; } /** * Provide name of the CLI Properties Array to look for within given System Properties. * * @param propsArrayName Name of the Properties Array to look for within the given System Properties. * @return Same ConfigurationBuilder instance (for chaining) */ public JSONConfBuilder withCLIPropsArray(String propsArrayName) { this.CLIPropsArrayName = propsArrayName; return this; } /** * Provide a specific Gson instance to use while creating/converting JSON. * * @param gson An instance of Gson * @return Same ConfigurationBuilder instance (for chaining) */ public JSONConfBuilder withGson(Gson gson) { this.gson = gson; return this; } /** * Builds the Configuration, based on the given parameters. * * @return New Configuration, based on the given parameters. */ public JSONConf build() { // Load Default Configuration JsonObject defaultConf = loadJsonFromFile(defaultConfFilePath); // Load User Configuration) JsonObject userConf = loadJsonFromFile(userConfFilePath); // Load CLI Configuration JsonObject cliConf = new JsonObject(); int idx = 0; String idxFormat = CLIPropsArrayName + "[%d]"; while (sysProps.getProperty(String.format(idxFormat, idx)) != null) { cliConf = union( cliConf, jsonPathAssignmentToJsonObject(sysProps.getProperty(String.format(idxFormat, idx++)))); } // Load UNION Configuration: // <default configuration> U <user configuration> U <CLI configuration> JsonObject unionConf = union(defaultConf, userConf, cliConf); return new JSONConf(unionConf); } /** * Loads a JsonObject from a FilePath. * NOTE: The filePath will be first searched within the Project Resources, * then on the Filesystem as a RELATIVE path. * * @param filePath (Relative) Path to JSON File we want to load * @return JsonObject from the given file */ protected JsonObject loadJsonFromFile(String filePath) { if (null == filePath) { return new JsonObject(); } // Work out the actual file location // Look within the project resources InputStream is = JSONConfBuilder.class.getClassLoader().getResourceAsStream(filePath); try { Reader fileReader = null; try { if (null != is) { // File is within the resources of the project fileReader = new InputStreamReader(is); } else { // File not within the resources of the project if (!new File(filePath).exists()) { throw new FileNotFoundException(filePath); } fileReader = new FileReader(filePath); } return gson.fromJson(fileReader, JsonObject.class); } catch (FileNotFoundException fnfe) { throw new RuntimeException(fnfe); } finally { try { fileReader.close(); } catch (IOException e) { throw new RuntimeException(e); } } } finally { if (null != is) { try { is.close(); } catch (IOException e) { throw new RuntimeException(e); } } } } /** * Algebraic Union of 2 JsonObjects. * * @param A JsonObject "A" * @param B JsonObject "B" * @return A JsonObject containing all the fields of A-union-B */ protected static JsonObject union(JsonObject A, JsonObject B) { JsonObject result = new JsonObject(); // First, copy everything from A for (Map.Entry<String, JsonElement> entryA : A.entrySet()) { result.add(entryA.getKey(), entryA.getValue()); } // Then, add content from B - recursively if needed for (Map.Entry<String, JsonElement> entryB : B.entrySet()) { String keyB = entryB.getKey(); JsonElement valueB = entryB.getValue(); if (A.has(keyB) && (A.get(keyB).isJsonObject() && valueB.isJsonObject())) { // This entry in B is also in A result.add(keyB, union(A.get(keyB).getAsJsonObject(), valueB.getAsJsonObject())); } else { // This entry in B is not in A: we just need to copy it over result.add(keyB, valueB); } } return result; } /** * Algebraic Union of "n" JsonObjects. * * @param objects Variable list of JsonObjects * @return A JsonObject containing the Union of all Objects, applied in order. */ protected static JsonObject union(JsonObject... objects) { if (objects.length == 0) { // Returns an empty JsonObject if no input is provided return new JsonObject(); } // Union all objects on the first one, then return it for (int i = 1, ilen = objects.length; i < ilen; ++i) { objects[0] = union(objects[0], objects[i]); } return objects[0]; } protected static JsonObject intersection(JsonObject A, JsonObject B) { // TODO return null; } protected static JsonObject subtraction(JsonObject A, JsonObject B) { // TODO return null; } /** * Converts an assignment expressed via JsonPath into a JsonObject. * Expected format would be something like: * <pre> * json.path.assignment=1 * </pre> * <p/> * The resulting object would look like: * <pre> * { * "json" : { * "path" : { * "assignment" : 1 * } * } * } * </pre> * * @param jsonPathAssignment JSON Path assignment * @return JSON Object result of the assignment */ protected JsonObject jsonPathAssignmentToJsonObject(String jsonPathAssignment) { JsonObject result = new JsonObject(); JsonObject current = result; JsonObject previous = null; String previousKey = null; // Use JsonPath to tokenize the given jsonPath and reconstruct a JsonObject PathTokenizer jsonPathTokenizer = new PathTokenizer(jsonPathAssignment); Iterator<PathToken> i = jsonPathTokenizer.iterator(); i.next(); //< ignore "$", tha represent the root of a Json Path while (i.hasNext()) { PathToken token = i.next(); if (token.isEndToken()) { // Reached the end of the Json Path. if (token.getFragment().contains("=")) { String[] keyValue = token.getFragment().split("="); // Here we MUST find an assignment, or throw an exception if (keyValue.length != 2) { throw new RuntimeException(String.format( "JSON Path '%s' contains no assignment in last token '%s'", jsonPathAssignment, token.getFragment())); } // Add final "key=value" String key = keyValue[0].replace("\"", ""); current.add(key, stringToJsonElement(keyValue[1])); } else { // WORKAROUND: Need to use the previous object and key as the assignment symbol was // wrongly assigned to the previous Token by the parser previous.add(previousKey, stringToJsonElement(token.getFragment())); } } else { // Add another "key=object" JsonObject next = new JsonObject(); // Remove quotes from string before storing String currentKey = token.getFragment().replace("\"", ""); // Remove assignment from key, if found by tokenization if (currentKey.endsWith("=")) currentKey = currentKey.substring(0, currentKey.length() - 1); current.add(currentKey, next); // Move to the next object in the tree previous = current; previousKey = currentKey; current = next; } } return result; } /** * Converts a String to a valid JsonElement * * @param input A value that can be converted to a valid JSON element * @return A valid JsonElement, based on the input string */ protected JsonElement stringToJsonElement(String input) { try { return gson.fromJson(input, JsonPrimitive.class); } catch (ClassCastException ccePrimitive) { try { return gson.fromJson(input, JsonArray.class); } catch (ClassCastException cceArray) { try { return gson.fromJson(input, JsonNull.class); } catch (ClassCastException cceNull) { return gson.fromJson(input, JsonObject.class); } } } } }
package io.digdag.spi; import com.fasterxml.jackson.databind.node.ObjectNode; import io.digdag.client.config.Config; import java.io.IOException; public interface CommandExecutor { /** * Starts a command and returns its state. Caller must check isFinished of the returned CommandStatus. * If it's true, the command is done. CommandStatus.getStatusCode() is ready to call. Otherwise, * caller must call poll method repeatedly with toJson of the returned CommandStatus until CommandStatus * is returned with isFinished == true. * * @param context * @param request * @return * @throws IOException */ CommandStatus run(CommandContext context, CommandRequest request) throws IOException; /** * Polls the command status by non-blocking and return CommandStatus. * * @param context * @param previousStatusJson * @return * @throws IOException */ CommandStatus poll(CommandContext context, ObjectNode previousStatusJson) throws IOException; /** * Runs a cleanup script when an attempt gets CANCEL_REQUESTED. * * @param context * @param state * @throws IOException */ default void cleanup(CommandContext context, Config state) throws IOException { } }
package org.commcare.android.fragments; import android.app.Activity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.support.v4.app.Fragment; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import org.commcare.android.framework.ManagedUi; import org.commcare.android.framework.UiElement; import org.commcare.dalvik.R; import org.javarosa.core.services.locale.Localization; @ManagedUi(R.layout.setup_enter_url) public class SetupEnterURLFragment extends Fragment { public interface URLInstaller { /** * Called when user fills in an URL and presses 'Start Install'. * The parent activity is responsible for implementing this interface and doing something with the URL. * @param url URL typed by the user */ public void OnURLChosen(String url); } public static final String interfaceName = URLInstaller.class.getName(); private URLInstaller listener; @UiElement(R.id.start_install) Button installButton; @UiElement(R.id.url_spinner) Spinner prefixURLSpinner; @UiElement(R.id.edit_profile_location) EditText profileLocation; @Override public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { final View view = inflater.inflate(R.layout.setup_enter_url, container, false); installButton = (Button) view.findViewById(R.id.start_install); installButton.setText(Localization.get("install.button.start")); prefixURLSpinner = (Spinner) view.findViewById(R.id.url_spinner); profileLocation = (EditText) view.findViewById(R.id.edit_profile_location); final TextView appProfile = (TextView) view.findViewById(R.id.app_profile_txt_view); appProfile.setText(Localization.get("install.appprofile")); installButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { getFragmentManager().popBackStack(); // equivalent to pressing the "back" button // no need for a null check because onAttach is called before onCreateView listener.OnURLChosen(getURL()); // returns the chosen URL to the parent Activity } }); return view; } @Override public void onAttach(final Activity activity) { super.onAttach(activity); if(!(activity instanceof URLInstaller)){ throw new ClassCastException(activity + " must implemement " + interfaceName); } else { listener = (URLInstaller) activity; } } public String getURL(){ final int selectedPrefix = prefixURLSpinner.getSelectedItemPosition(); String url = profileLocation.getText().toString(); if (url == null || url.length() == 0) { return url; } // if it's not the last (which should be "Raw") choice, we'll use the prefix if(selectedPrefix < prefixURLSpinner.getCount() - 1) { url = prefixURLSpinner.getSelectedItem() + "/" + url; } if(!url.startsWith("http")){ url = "http://" + url; } return url; } }
package net.md_5.bungee; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import org.junit.Assert; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class NativeCipherTest { private final byte[] plainBytes = "This is a test".getBytes(); private final byte[] cipheredBytes = new byte[] { 50, -7, 89, 1, -11, -32, -118, -48, -2, -72, 105, 97, -70, -81 }; private final SecretKey secret = new SecretKeySpec( new byte[ 16 ], "AES" ); private static final int BENCHMARK_COUNT = 50000; @Test public void testOpenSSL() throws Exception { if ( NativeCipher.isSupported() ) { boolean loaded = NativeCipher.load(); Assert.assertTrue( "Native cipher failed to load!", loaded ); NativeCipher cipher = new NativeCipher(); System.out.println( "Testing OpenSSL cipher..." ); testACipher( cipher ); } } @Test public void testOpenSSLBenchmark() throws Exception { if ( NativeCipher.isSupported() ) { boolean loaded = NativeCipher.load(); Assert.assertTrue( "Native cipher failed to load!", loaded ); NativeCipher cipher = new NativeCipher(); System.out.println( "Benchmarking OpenSSL cipher..." ); testBenchmark( cipher ); } } @Test public void testJDK() throws Exception { // Create JDK cipher BungeeCipher cipher = new FallbackCipher(); System.out.println( "Testing Java cipher..." ); testACipher( cipher ); } @Test public void testJDKBenchmark() throws Exception { // Create JDK cipher BungeeCipher cipher = new FallbackCipher(); System.out.println( "Benchmarking Java cipher..." ); testBenchmark( cipher ); } /** * Hackish test which can test both native and fallback ciphers using direct * buffers. */ public void testACipher(BungeeCipher cipher) throws Exception { // Create input buf ByteBuf nativePlain = Unpooled.directBuffer( plainBytes.length ); nativePlain.writeBytes( plainBytes ); // Create expected buf ByteBuf nativeCiphered = Unpooled.directBuffer( cipheredBytes.length ); nativeCiphered.writeBytes( cipheredBytes ); // Create output buf ByteBuf out = Unpooled.directBuffer( plainBytes.length ); // Encrypt cipher.init( true, secret ); cipher.cipher( nativePlain, out ); Assert.assertEquals( nativeCiphered, out ); out.clear(); // Decrypt cipher.init( false, secret ); cipher.cipher( nativeCiphered, out ); nativePlain.resetReaderIndex(); Assert.assertEquals( nativePlain, out ); System.out.println( "This cipher works correctly!" ); } public void testBenchmark(BungeeCipher cipher) throws Exception { // Create input buf ByteBuf nativePlain = Unpooled.directBuffer( plainBytes.length ); nativePlain.writeBytes( plainBytes ); // Create expected buf ByteBuf nativeCiphered = Unpooled.directBuffer( cipheredBytes.length ); nativeCiphered.writeBytes( cipheredBytes ); // Create output buf ByteBuf out = Unpooled.directBuffer( plainBytes.length ); // Encrypt cipher.init( true, secret ); long start = System.currentTimeMillis(); for ( int i = 0; i < BENCHMARK_COUNT; i++ ) { cipher.cipher( nativePlain, out ); out.clear(); } System.out.println( String.format( "Encryption Iteration: %d, Elapsed: %d ms", BENCHMARK_COUNT, System.currentTimeMillis() - start ) ); // Decrypt cipher.init( false, secret ); start = System.currentTimeMillis(); for ( int i = 0; i < BENCHMARK_COUNT; i++ ) { cipher.cipher( nativeCiphered, out ); out.clear(); } System.out.println( String.format( "Decryption Iteration: %d, Elapsed: %d ms", BENCHMARK_COUNT, System.currentTimeMillis() - start ) ); } }
package com.github.nwillc.funjdbc.migrate; import almost.functional.utils.LogFactory; import com.github.nwillc.funjdbc.DbAccessor; import com.github.nwillc.funjdbc.SqlStatement; import com.github.nwillc.funjdbc.UncheckedSQLException; import com.github.nwillc.funjdbc.functions.ConnectionProvider; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; /** * The migration Manager. This singleton manages a set of Migrations, performing them as needed and persisting the * status of each. */ public class Manager implements DbAccessor { private static final Logger LOGGER = LogFactory.getLogger(); private static final Manager INSTANCE = new Manager(); private static final SqlStatement CREATE = new SqlStatement("CREATE TABLE MIGRATIONS ( IDENTIFIER CHAR(40) PRIMARY KEY, DESCRIPTION CHAR(120))"); private static final SqlStatement INSERT = new SqlStatement("INSERT INTO MIGRATIONS (IDENTIFIER, DESCRIPTION) VALUES('%s', '%s')"); private static final String FIND = "SELECT * FROM MIGRATIONS WHERE IDENTIFIER = '%s'"; private final Set<Migration> migrations = new TreeSet<>(new MigrationComparator()); private ConnectionProvider connectionProvider; /** * Gets the singleton instance. * * @return the instance */ public static Manager getInstance() { return INSTANCE; } private Manager() { } /** * Gets connection provider. * * @return the connection provider */ public ConnectionProvider getConnectionProvider() { return connectionProvider; } /** * Sets connection provider. * * @param connectionProvider the connection provider */ public void setConnectionProvider(ConnectionProvider connectionProvider) { this.connectionProvider = connectionProvider; } @Override public Connection getConnection() throws SQLException { if (connectionProvider == null) { throw new IllegalStateException("No ConnectionProvider available."); } return connectionProvider.getConnection(); } public void add(Class<? extends Migration> aMigration) throws IllegalArgumentException { try { migrations.add(aMigration.getConstructor().newInstance()); } catch (Exception e) { LOGGER.log(Level.SEVERE, "Unable to add " + aMigration.getSimpleName() + " because " + e); throw new IllegalArgumentException(e); } } /** * Add Migrations to the set.. * * @param migrations the migration */ public void add(Migration... migrations) { if (migrations != null) { Collections.addAll(this.migrations, migrations); } } /** * Gets the set of Migrations. * * @return the migrations */ public Set<Migration> getMigrations() { return migrations; } /** * Clear the set of migrations. */ public void clear() { migrations.clear(); } /** * Is migration management enabled in the database. * * @return the boolean */ public boolean migrationsEnabled() { try (Connection connection = getConnection()) { ResultSet resultSet = connection.getMetaData().getTables(null, null, "MIGRATIONS", null); return stream(rs -> rs.getString(3), resultSet).count() == 1; } catch (SQLException e) { LOGGER.warning(e.toString()); } return false; } /** * Enable migration management in the database. * * @throws java.sql.SQLException if the migration table can not be added to the database. */ public void enableMigrations() throws SQLException { if (!migrationsEnabled()) { dbUpdate(CREATE); } } /** * Check if a migration has been performed. * * @param first the first * * @return the boolean */ public boolean migrated(String first) { try { return dbFind(rs -> rs.getString(1), new SqlStatement(FIND, first)).isPresent(); } catch (SQLException e) { LOGGER.warning(e.toString()); } return false; } /** * Do migrations as needed. Perform any Migration that hasn't been completed or is designated runAlways. */ public void doMigrations() { migrations.forEach(migration -> { if (!migrated(migration.getIdentifier()) || migration.runAlways()) { try { migration.perform(); INSERT.setArgs(migration.getIdentifier(), migration.getDescription()); dbUpdate(INSERT); } catch (Exception e) { throw new UncheckedSQLException("Migration " + migration.getIdentifier() + " failure.", e); } } }); } public static class MigrationComparator implements Comparator<Migration> { @Override public int compare(Migration o1, Migration o2) { Objects.requireNonNull(o1, "Can not compare null Migration instance"); Objects.requireNonNull(o2, "Can not compare null Migration instance"); if (o1.getIdentifier() == null ^ o2.getIdentifier() == null) { return (o1.getIdentifier() == null) ? -1 : 1; } if (o1.getIdentifier() == null) { return 0; } return o1.getIdentifier().compareToIgnoreCase(o2.getIdentifier()); } } }
package com.diozero.util; import java.io.*; import java.util.Properties; import java.util.ServiceLoader; import org.pmw.tinylog.Logger; public class SystemInfo { private static final String OS_RELEASE_FILE = "/etc/os-release"; private static final String CPUINFO_FILE = "/proc/cpuinfo"; private static boolean initialised; private static Properties osReleaseProperties; private static BoardInfo boardInfo; private static synchronized void initialise() throws RuntimeIOException { if (! initialised) { osReleaseProperties = new Properties(); try (Reader reader = new FileReader(OS_RELEASE_FILE)) { osReleaseProperties.load(reader); } catch (IOException e) { throw new RuntimeIOException("Error loading properties file '" + OS_RELEASE_FILE, e); } ProcessBuilder pb = new ProcessBuilder("cat", CPUINFO_FILE); String revision_string = null; try { Process proc = pb.start(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()))) { String line; // Fully read the process output do { line = reader.readLine(); if (line != null && line.startsWith("Revision")) { revision_string = line.split(":")[1].trim(); } } while (line != null); } } catch (IOException | NullPointerException | IndexOutOfBoundsException e) { Logger.error(e, "Error reading " + CPUINFO_FILE, e.getMessage()); } boardInfo = lookupBoardInfo(revision_string); initialised = true; } } protected static BoardInfo lookupBoardInfo(String revision) { BoardInfo board_info = null; ServiceLoader<BoardInfoProvider> service_loader = ServiceLoader.load(BoardInfoProvider.class); for (BoardInfoProvider board_info_provider : service_loader) { board_info = board_info_provider.lookup(revision); if (board_info != null) { break; } } if (board_info == null) { Logger.warn("Failed to resolve board info, revision '" + revision + "'"); } else { Logger.debug("Resolved board " + board_info); } return board_info; } public static String getOsReleaseProperty(String property) { initialise(); return osReleaseProperties.getProperty(property); } public static String getOperatingSystemId() { initialise(); return osReleaseProperties.getProperty("ID"); } public static String getOperatingSystemVersion() { initialise(); return osReleaseProperties.getProperty("VERSION"); } public static String getOperatingSystemVersionId() { initialise(); return osReleaseProperties.getProperty("VERSION_ID"); } public static BoardInfo getBoardInfo() { initialise(); return boardInfo; } public static String getLibraryPath() { return getBoardInfo().getLibraryPath(); } public static void main(String[] args) { initialise(); Logger.info(osReleaseProperties); Logger.info(getBoardInfo()); } }
package org.odk.collect.android.activities; import android.annotation.SuppressLint; import android.app.ActionBar; import android.content.BroadcastReceiver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.Rect; import android.location.LocationManager; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; import android.provider.MediaStore; import android.provider.MediaStore.Images; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.text.SpannableStringBuilder; import android.util.Log; import android.util.Pair; import android.util.TypedValue; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.ContextThemeWrapper; import android.view.GestureDetector; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.animation.Animation; import android.view.animation.Animation.AnimationListener; import android.view.animation.AnimationUtils; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import org.commcare.android.framework.CommCareActivity; import org.commcare.android.framework.SaveSessionCommCareActivity; import org.commcare.android.javarosa.AndroidLogger; import org.commcare.android.util.FormUploadUtil; import org.commcare.android.util.SessionUnavailableException; import org.commcare.android.util.StringUtils; import org.commcare.dalvik.BuildConfig; import org.commcare.dalvik.R; import org.commcare.dalvik.activities.CommCareHomeActivity; import org.commcare.dalvik.application.CommCareApplication; import org.commcare.dalvik.dialogs.AlertDialogFactory; import org.commcare.dalvik.dialogs.CustomProgressDialog; import org.commcare.dalvik.dialogs.DialogChoiceItem; import org.commcare.dalvik.dialogs.HorizontalPaneledChoiceDialog; import org.commcare.dalvik.dialogs.PaneledChoiceDialog; import org.commcare.dalvik.odk.provider.FormsProviderAPI.FormsColumns; import org.commcare.dalvik.odk.provider.InstanceProviderAPI; import org.commcare.dalvik.odk.provider.InstanceProviderAPI.InstanceColumns; import org.commcare.dalvik.utils.UriToFilePath; import org.javarosa.core.model.Constants; import org.javarosa.core.model.FormIndex; import org.javarosa.core.model.SelectChoice; import org.javarosa.core.model.data.IAnswerData; import org.javarosa.core.model.instance.TreeReference; import org.javarosa.core.services.Logger; import org.javarosa.core.services.locale.Localization; import org.javarosa.core.services.locale.Localizer; import org.javarosa.form.api.FormEntryController; import org.javarosa.form.api.FormEntryPrompt; import org.javarosa.model.xform.XFormsModule; import org.javarosa.xpath.XPathException; import org.javarosa.xpath.XPathTypeMismatchException; import org.odk.collect.android.activities.components.FormNavigationController; import org.odk.collect.android.activities.components.FormNavigationUI; import org.odk.collect.android.activities.components.ImageCaptureProcessing; import org.odk.collect.android.application.ODKStorage; import org.odk.collect.android.jr.extensions.IntentCallout; import org.odk.collect.android.jr.extensions.PollSensorAction; import org.odk.collect.android.listeners.AdvanceToNextListener; import org.odk.collect.android.listeners.FormSaveCallback; import org.odk.collect.android.listeners.FormSavedListener; import org.odk.collect.android.listeners.WidgetChangedListener; import org.odk.collect.android.logic.FormController; import org.odk.collect.android.logic.PropertyManager; import org.odk.collect.android.preferences.FormEntryPreferences; import org.odk.collect.android.tasks.FormLoaderTask; import org.odk.collect.android.tasks.SaveToDiskTask; import org.odk.collect.android.utilities.Base64Wrapper; import org.odk.collect.android.utilities.FileUtils; import org.odk.collect.android.utilities.GeoUtils; import org.odk.collect.android.views.ODKView; import org.odk.collect.android.views.ResizingImageView; import org.odk.collect.android.widgets.DateTimeWidget; import org.odk.collect.android.widgets.ImageWidget; import org.odk.collect.android.widgets.IntentWidget; import org.odk.collect.android.widgets.QuestionWidget; import org.odk.collect.android.widgets.TimeWidget; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.Vector; import javax.crypto.spec.SecretKeySpec; /** * Displays questions, animates transitions between * questions, and allows the user to enter data. * * @author Carl Hartung (carlhartung@gmail.com) */ public class FormEntryActivity extends SaveSessionCommCareActivity<FormEntryActivity> implements AnimationListener, FormSavedListener, FormSaveCallback, AdvanceToNextListener, WidgetChangedListener { private static final String TAG = FormEntryActivity.class.getSimpleName(); // Defines for FormEntryActivity private static final boolean EXIT = true; private static final boolean DO_NOT_EXIT = false; private static final boolean EVALUATE_CONSTRAINTS = true; private static final boolean DO_NOT_EVALUATE_CONSTRAINTS = false; // Request codes for returning data from specified intent. public static final int IMAGE_CAPTURE = 1; public static final int BARCODE_CAPTURE = 2; public static final int AUDIO_VIDEO_FETCH = 3; public static final int LOCATION_CAPTURE = 5; private static final int HIERARCHY_ACTIVITY = 6; public static final int IMAGE_CHOOSER = 7; private static final int FORM_PREFERENCES_KEY = 8; public static final int INTENT_CALLOUT = 10; private static final int HIERARCHY_ACTIVITY_FIRST_START = 11; public static final int SIGNATURE_CAPTURE = 12; // Extra returned from gp activity public static final String LOCATION_RESULT = "LOCATION_RESULT"; // Identifies the gp of the form used to launch form entry private static final String KEY_FORMPATH = "formpath"; public static final String KEY_INSTANCEDESTINATION = "instancedestination"; public static final String TITLE_FRAGMENT_TAG = "odk_title_fragment"; public static final String KEY_FORM_CONTENT_URI = "form_content_uri"; public static final String KEY_INSTANCE_CONTENT_URI = "instance_content_uri"; public static final String KEY_AES_STORAGE_KEY = "key_aes_storage"; public static final String KEY_HEADER_STRING = "form_header"; public static final String KEY_INCOMPLETE_ENABLED = "org.odk.collect.form.management"; public static final String KEY_RESIZING_ENABLED = "org.odk.collect.resizing.enabled"; private static final String KEY_HAS_SAVED = "org.odk.collect.form.has.saved"; /** * Intent extra flag to track if this form is an archive. Used to trigger * return logic when this activity exits to the home screen, such as * whether to redirect to archive view or sync the form. */ public static final String IS_ARCHIVED_FORM = "is-archive-form"; // Identifies whether this is a new form, or reloading a form after a screen // rotation (or similar) private static final String KEY_FORM_LOAD_HAS_TRIGGERED = "newform"; private static final String KEY_FORM_LOAD_FAILED = "form-failed"; private static final int MENU_LANGUAGES = Menu.FIRST + 1; private static final int MENU_HIERARCHY_VIEW = Menu.FIRST + 2; private static final int MENU_SAVE = Menu.FIRST + 3; private static final int MENU_PREFERENCES = Menu.FIRST + 4; public static final String NAV_STATE_NEXT = "next"; public static final String NAV_STATE_DONE = "done"; public static final String NAV_STATE_QUIT = "quit"; public static final String NAV_STATE_BACK = "back"; private String mFormPath; // Path to a particular form instance public static String mInstancePath; private String mInstanceDestination; private GestureDetector mGestureDetector; private SecretKeySpec symetricKey = null; public static FormController mFormController; private Animation mInAnimation; private Animation mOutAnimation; private ViewGroup mViewPane; private ODKView mCurrentView; private boolean mIncompleteEnabled = true; private boolean hasFormLoadBeenTriggered = false; private boolean hasFormLoadFailed = false; // used to limit forward/backward swipes to one per question private boolean isAnimatingSwipe; private boolean isDialogShowing; private FormLoaderTask<FormEntryActivity> mFormLoaderTask; private SaveToDiskTask<FormEntryActivity> mSaveToDiskTask; private Uri formProviderContentURI = FormsColumns.CONTENT_URI; private Uri instanceProviderContentURI = InstanceColumns.CONTENT_URI; private static String mHeaderString; // Was the form saved? Used to set activity return code. private boolean hasSaved = false; private BroadcastReceiver mLocationServiceIssueReceiver; // marked true if we are in the process of saving a form because the user // database & key session are expiring. Being set causes savingComplete to // broadcast a form saving intent. private boolean savingFormOnKeySessionExpiration = false; private boolean mGroupForcedInvisible = false; private boolean mGroupNativeVisibility = false; enum AnimationType { LEFT, RIGHT, FADE } @Override @SuppressLint("NewApi") protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addBreadcrumbBar(); // must be at the beginning of any activity that can be called from an external intent try { ODKStorage.createODKDirs(); } catch (RuntimeException e) { Logger.exception(e); CommCareActivity.createErrorDialog(this, e.getMessage(), EXIT); return; } setupUI(); // Load JavaRosa modules. needed to restore forms. new XFormsModule().registerModule(); // needed to override rms property manager org.javarosa.core.services.PropertyManager.setPropertyManager(new PropertyManager( getApplicationContext())); loadStateFromBundle(savedInstanceState); // Check to see if this is a screen flip or a new form load. Object data = this.getLastCustomNonConfigurationInstance(); if (data instanceof FormLoaderTask) { mFormLoaderTask = (FormLoaderTask) data; } else if (data instanceof SaveToDiskTask) { mSaveToDiskTask = (SaveToDiskTask) data; mSaveToDiskTask.setFormSavedListener(this); } else if (hasFormLoadBeenTriggered && !hasFormLoadFailed) { // Screen orientation change refreshCurrentView(); } } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { /* * EventLog accepts only proper Strings as input, but prior to this version, * Android would try to send SpannedStrings to it, thus crashing the app. * This makes sure the title is actually a String. * This fixes bug 174626. */ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2 && item.getTitleCondensed() != null) { item.setTitleCondensed(item.getTitleCondensed().toString()); } return super.onMenuItemSelected(featureId, item); } @Override public void formSaveCallback() { // note that we have started saving the form savingFormOnKeySessionExpiration = true; // start saving form, which will call the key session logout completion // function when it finishes. saveIncompleteFormToDisk(); } private void registerFormEntryReceiver() { //BroadcastReceiver for: // a) An unresolvable xpath expression encountered in PollSensorAction.onLocationChanged // b) Checking if GPS services are not available mLocationServiceIssueReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { context.removeStickyBroadcast(intent); String action = intent.getAction(); if (GeoUtils.ACTION_CHECK_GPS_ENABLED.equals(action)) { handleNoGpsBroadcast(context); } else if (PollSensorAction.XPATH_ERROR_ACTION.equals(action)) { handleXpathErrorBroadcast(intent); } } }; IntentFilter filter = new IntentFilter(); filter.addAction(PollSensorAction.XPATH_ERROR_ACTION); filter.addAction(GeoUtils.ACTION_CHECK_GPS_ENABLED); registerReceiver(mLocationServiceIssueReceiver, filter); } private void handleNoGpsBroadcast(Context context) { LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); Set<String> providers = GeoUtils.evaluateProviders(manager); if (providers.isEmpty()) { DialogInterface.OnClickListener onChangeListener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int i) { if (i == DialogInterface.BUTTON_POSITIVE) { Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(intent); } dialog.dismiss(); } }; GeoUtils.showNoGpsDialog(this, onChangeListener); } } private void handleXpathErrorBroadcast(Intent intent) { String problemXpath = intent.getStringExtra(PollSensorAction.KEY_UNRESOLVED_XPATH); CommCareActivity.createErrorDialog(FormEntryActivity.this, "There is a bug in one of your form's XPath Expressions \n" + problemXpath, EXIT); } private void setupUI() { setContentView(R.layout.screen_form_entry); ImageButton nextButton = (ImageButton)this.findViewById(R.id.nav_btn_next); ImageButton prevButton = (ImageButton)this.findViewById(R.id.nav_btn_prev); nextButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (!NAV_STATE_DONE.equals(v.getTag())) { FormEntryActivity.this.showNextView(); } else { triggerUserFormComplete(); } } }); prevButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (!NAV_STATE_QUIT.equals(v.getTag())) { FormEntryActivity.this.showPreviousView(true); } else { FormEntryActivity.this.triggerUserQuitInput(); } } }); mViewPane = (ViewGroup)findViewById(R.id.form_entry_pane); requestMajorLayoutUpdates(); if (mCurrentView != null) { mCurrentView.teardownView(); } // re-set defaults in case the app got in a bad state. isAnimatingSwipe = false; isDialogShowing = false; mCurrentView = null; mInAnimation = null; mOutAnimation = null; mGestureDetector = new GestureDetector(this); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(KEY_FORMPATH, mFormPath); outState.putBoolean(KEY_FORM_LOAD_HAS_TRIGGERED, hasFormLoadBeenTriggered); outState.putBoolean(KEY_FORM_LOAD_FAILED, hasFormLoadFailed); outState.putString(KEY_FORM_CONTENT_URI, formProviderContentURI.toString()); outState.putString(KEY_INSTANCE_CONTENT_URI, instanceProviderContentURI.toString()); outState.putString(KEY_INSTANCEDESTINATION, mInstanceDestination); outState.putBoolean(KEY_INCOMPLETE_ENABLED, mIncompleteEnabled); outState.putBoolean(KEY_HAS_SAVED, hasSaved); outState.putString(KEY_RESIZING_ENABLED, ResizingImageView.resizeMethod); if(symetricKey != null) { try { outState.putString(KEY_AES_STORAGE_KEY, new Base64Wrapper().encodeToString(symetricKey.getEncoded())); } catch (ClassNotFoundException e) { // we can't really get here anyway, since we couldn't have decoded the string to begin with throw new RuntimeException("Base 64 encoding unavailable! Can't pass storage key"); } } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); if (requestCode == FORM_PREFERENCES_KEY) { refreshCurrentView(false); return; } if (resultCode == RESULT_CANCELED) { if (requestCode == HIERARCHY_ACTIVITY_FIRST_START) { // They pressed 'back' on the first hierarchy screen, so we should assume they want // to back out of form entry all together finishReturnInstance(false); } else if (requestCode == INTENT_CALLOUT){ processIntentResponse(intent, true); } // request was canceled, so do nothing return; } switch (requestCode) { case BARCODE_CAPTURE: String sb = intent.getStringExtra("SCAN_RESULT"); mCurrentView.setBinaryData(sb, mFormController); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); break; case INTENT_CALLOUT: processIntentResponse(intent); break; case IMAGE_CAPTURE: processCaptureResponse(true); break; case SIGNATURE_CAPTURE: processCaptureResponse(false); break; case IMAGE_CHOOSER: processImageChooserResponse(intent); break; case AUDIO_VIDEO_FETCH: processChooserResponse(intent); break; case LOCATION_CAPTURE: String sl = intent.getStringExtra(LOCATION_RESULT); mCurrentView.setBinaryData(sl, mFormController); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); break; case HIERARCHY_ACTIVITY: case HIERARCHY_ACTIVITY_FIRST_START: // We may have jumped to a new index in hierarchy activity, so refresh refreshCurrentView(false); break; } } /** * Processes the return from an image capture intent, launched by either an ImageWidget or * SignatureWidget * * @param isImage true if this was from an ImageWidget, false if it was a SignatureWidget */ private void processCaptureResponse(boolean isImage) { /* We saved the image to the tempfile_path, but we really want it to be in: * /sdcard/odk/instances/[current instance]/something.[jpg/png/etc] so we move it there * before inserting it into the content provider. Once the android image capture bug gets * fixed, (read, we move on from Android 1.6) we want to handle images the audio and * video */ // The intent is empty, but we know we saved the image to the temp file File originalImage = ImageWidget.TEMP_FILE_FOR_IMAGE_CAPTURE; try { File unscaledFinalImage = ImageCaptureProcessing.moveAndScaleImage(originalImage, isImage, getInstanceFolder(), this); saveImageWidgetAnswer(unscaledFinalImage); } catch (IOException e) { e.printStackTrace(); showCustomToast(Localization.get("image.capture.not.saved"), Toast.LENGTH_LONG); } } private String getInstanceFolder() { return mInstancePath.substring(0, mInstancePath.lastIndexOf("/") + 1); } private void processImageChooserResponse(Intent intent) { /* We have a saved image somewhere, but we really want it to be in: * /sdcard/odk/instances/[current instance]/something.[jpg/png/etc] so we move it there * before inserting it into the content provider. Once the android image capture bug gets * fixed, (read, we move on from Android 1.6) we want to handle images the audio and * video */ // get gp of chosen file Uri selectedImage = intent.getData(); String imagePath = FileUtils.getPath(this, selectedImage); if (imagePath == null) { showCustomToast(Localization.get("invalid.image.selection"), Toast.LENGTH_LONG); return; } File originalImage = new File(imagePath); if (originalImage.exists()) { try { File unscaledFinalImage = ImageCaptureProcessing.moveAndScaleImage(originalImage, true, getInstanceFolder(), this); saveImageWidgetAnswer(unscaledFinalImage); } catch (IOException e) { e.printStackTrace(); showCustomToast(Localization.get("image.selection.not.saved"), Toast.LENGTH_LONG); } } else { // The user has managed to select a file from the image browser that doesn't actually // exist on the file system anymore showCustomToast(Localization.get("invalid.image.selection"), Toast.LENGTH_LONG); } } private void saveImageWidgetAnswer(File unscaledFinalImage) { // Add the new image to the Media content provider so that the viewing is fast in Android 2.0+ ContentValues values = new ContentValues(6); values.put(Images.Media.TITLE, unscaledFinalImage.getName()); values.put(Images.Media.DISPLAY_NAME, unscaledFinalImage.getName()); values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis()); values.put(Images.Media.MIME_TYPE, "image/jpeg"); values.put(Images.Media.DATA, unscaledFinalImage.getAbsolutePath()); Uri imageURI = getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values); Log.i(TAG, "Inserting image returned uri = " + imageURI); mCurrentView.setBinaryData(imageURI, mFormController); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); refreshCurrentView(); } private void processChooserResponse(Intent intent) { // For audio/video capture/chooser, we get the URI from the content provider // then the widget copies the file and makes a new entry in the content provider. Uri media = intent.getData(); String binaryPath = UriToFilePath.getPathFromUri(CommCareApplication._(), media); if (!FormUploadUtil.isSupportedMultimediaFile(binaryPath)) { // don't let the user select a file that won't be included in the // upload to the server mCurrentView.clearAnswer(); Toast.makeText(FormEntryActivity.this, Localization.get("form.attachment.invalid"), Toast.LENGTH_LONG).show(); } else { mCurrentView.setBinaryData(media, mFormController); } saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); refreshCurrentView(); } /** * Search the the current view's widgets for one that has registered a * pending callout with the form controller */ public QuestionWidget getPendingWidget() { FormIndex pendingIndex = mFormController.getPendingCalloutFormIndex(); if (pendingIndex == null) { Logger.log(AndroidLogger.SOFT_ASSERT, "getPendingWidget called when pending callout form index was null"); return null; } for (QuestionWidget q : mCurrentView.getWidgets()) { if (q.getFormId().equals(pendingIndex)) { return q; } } Logger.log(AndroidLogger.SOFT_ASSERT, "getPendingWidget couldn't find question widget with a form index that matches the pending callout."); return null; } private void processIntentResponse(Intent response){ processIntentResponse(response, false); } private void processIntentResponse(Intent response, boolean cancelled) { // keep track of whether we should auto advance boolean advance = false; boolean quick = false; IntentWidget pendingIntentWidget = (IntentWidget)getPendingWidget(); TreeReference context; if (mFormController.getPendingCalloutFormIndex() != null) { context = mFormController.getPendingCalloutFormIndex().getReference(); } else { context = null; } if(pendingIntentWidget != null) { //Set our instance destination for binary data if needed String destination = mInstancePath.substring(0, mInstancePath.lastIndexOf("/") + 1); //get the original intent callout IntentCallout ic = pendingIntentWidget.getIntentCallout(); quick = "quick".equals(ic.getAppearance()); //And process it advance = ic.processResponse(response, context, new File(destination)); ic.setCancelled(cancelled); } refreshCurrentView(); // auto advance if we got a good result and are in quick mode if(advance && quick){ showNextView(); } } private void updateFormRelevancies(){ saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); ArrayList<QuestionWidget> oldWidgets = mCurrentView.getWidgets(); // These 2 calls need to be made here, rather than in the for loop below, because at that // point the widgets will have already started being updated to the values for the new view ArrayList<Vector<SelectChoice>> oldSelectChoices = getOldSelectChoicesForEachWidget(oldWidgets); ArrayList<String> oldQuestionTexts = getOldQuestionTextsForEachWidget(oldWidgets); FormEntryPrompt[] newValidPrompts = mFormController.getQuestionPrompts(); Set<FormEntryPrompt> promptsLeftInView = new HashSet<>(); ArrayList<Integer> shouldRemoveFromView = new ArrayList<>(); // Loop through all of the old widgets to determine which ones should stay in the new view for (int i = 0; i < oldWidgets.size(); i++){ FormEntryPrompt oldPrompt = oldWidgets.get(i).getPrompt(); String priorQuestionTextForThisWidget = oldQuestionTexts.get(i); Vector<SelectChoice> priorSelectChoicesForThisWidget = oldSelectChoices.get(i); FormEntryPrompt equivalentNewPrompt = getEquivalentPromptInNewList(newValidPrompts, oldPrompt, priorQuestionTextForThisWidget, priorSelectChoicesForThisWidget); if (equivalentNewPrompt != null) { promptsLeftInView.add(equivalentNewPrompt); } else { // If there is no equivalent prompt in the list of new prompts, then this prompt is // no longer relevant in the new view, so it should get removed shouldRemoveFromView.add(i); } } // Remove "atomically" to not mess up iterations mCurrentView.removeQuestionsFromIndex(shouldRemoveFromView); // Now go through add add any new prompts that we need for (int i = 0; i < newValidPrompts.length; ++i) { FormEntryPrompt prompt = newValidPrompts[i]; if (!promptsLeftInView.contains(prompt)) { // If the old version of this prompt was NOT left in the view, then add it mCurrentView.addQuestionToIndex(prompt, mFormController.getWidgetFactory(), i); } } } /** * @return A list of the select choices for each widget in the list of old widgets, with the * original order preserved */ private ArrayList<Vector<SelectChoice>> getOldSelectChoicesForEachWidget(ArrayList<QuestionWidget> oldWidgets) { ArrayList<Vector<SelectChoice>> selectChoicesList = new ArrayList<>(); for (QuestionWidget qw : oldWidgets) { Vector<SelectChoice> oldSelectChoices = qw.getPrompt().getOldSelectChoices(); selectChoicesList.add(oldSelectChoices); } return selectChoicesList; } /** * @return A list of the question texts for each widget in the list of old widgets, with the * original order preserved */ private ArrayList<String> getOldQuestionTextsForEachWidget(ArrayList<QuestionWidget> oldWidgets) { ArrayList<String> questionTextList = new ArrayList<>(); for (QuestionWidget qw : oldWidgets) { questionTextList.add(qw.getPrompt().getQuestionText()); } return questionTextList; } /** * * @param newValidPrompts - All of the prompts that should be in the new view * @param oldPrompt - The prompt from the prior view for which we are seeking a match in the * list of new prompts * @param oldQuestionText - the question text of the old prompt * @param oldSelectChoices - the select choices of the old prompt * @return The form entry prompt from the new list that is equivalent to oldPrompt, or null * if none exists */ private FormEntryPrompt getEquivalentPromptInNewList(FormEntryPrompt[] newValidPrompts, FormEntryPrompt oldPrompt, String oldQuestionText, Vector<SelectChoice> oldSelectChoices) { for (FormEntryPrompt newPrompt : newValidPrompts) { if (newPrompt.getIndex().equals(oldPrompt.getIndex()) && newPrompt.hasSameDisplayContent(oldQuestionText, oldSelectChoices)) { // A new prompt is considered equivalent to the old prompt if both their form // indices and display content (question text and select choices) are the same return newPrompt; } } return null; } /** * Refreshes the current view. the controller and the displayed view can get out of sync due to * dialogs and restarts caused by screen orientation changes, so they're resynchronized here. */ private void refreshCurrentView() { refreshCurrentView(true); } /** * Refreshes the current view. the controller and the displayed view can get out of sync due to * dialogs and restarts caused by screen orientation changes, so they're resynchronized here. */ private void refreshCurrentView(boolean animateLastView) { if(mFormController == null) { throw new RuntimeException("Form state is lost! Cannot refresh current view. This shouldn't happen, please submit a bug report."); } int event = mFormController.getEvent(); // When we refresh, repeat dialog state isn't maintained, so step back to the previous // question. // Also, if we're within a group labeled 'field list', step back to the beginning of that // group. // That is, skip backwards over repeat prompts, groups that are not field-lists, // repeat events, and indexes in field-lists that is not the containing group. while (event == FormEntryController.EVENT_PROMPT_NEW_REPEAT || (event == FormEntryController.EVENT_GROUP && !mFormController.indexIsInFieldList()) || event == FormEntryController.EVENT_REPEAT || (mFormController.indexIsInFieldList() && !(event == FormEntryController.EVENT_GROUP))) { event = mFormController.stepToPreviousEvent(); } //If we're at the beginning of form event, but don't show the screen for that, we need //to get the next valid screen if(event == FormEntryController.EVENT_BEGINNING_OF_FORM) { showNextView(true); } else if(event == FormEntryController.EVENT_END_OF_FORM) { showPreviousView(false); } else { ODKView current = createView(); showView(current, AnimationType.FADE, animateLastView); } } @Override public boolean onPrepareOptionsMenu(Menu menu) { menu.removeItem(MENU_LANGUAGES); menu.removeItem(MENU_HIERARCHY_VIEW); menu.removeItem(MENU_SAVE); menu.removeItem(MENU_PREFERENCES); if(mIncompleteEnabled) { menu.add(0, MENU_SAVE, 0, StringUtils.getStringRobust(this, R.string.save_all_answers)).setIcon( android.R.drawable.ic_menu_save); } menu.add(0, MENU_HIERARCHY_VIEW, 0, StringUtils.getStringRobust(this, R.string.view_hierarchy)).setIcon( R.drawable.ic_menu_goto); boolean hasMultipleLanguages = (!(mFormController == null || mFormController.getLanguages() == null || mFormController.getLanguages().length == 1)); menu.add(0, MENU_LANGUAGES, 0, StringUtils.getStringRobust(this, R.string.change_language)) .setIcon(R.drawable.ic_menu_start_conversation) .setEnabled(hasMultipleLanguages); menu.add(0, MENU_PREFERENCES, 0, StringUtils.getStringRobust(this, R.string.form_entry_settings)).setIcon( android.R.drawable.ic_menu_preferences); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_LANGUAGES: createLanguageDialog(); return true; case MENU_SAVE: saveFormToDisk(DO_NOT_EXIT); return true; case MENU_HIERARCHY_VIEW: if (currentPromptIsQuestion()) { saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); } Intent i = new Intent(this, FormHierarchyActivity.class); startActivityForResult(i, HIERARCHY_ACTIVITY); return true; case MENU_PREFERENCES: Intent pref = new Intent(this, FormEntryPreferences.class); startActivityForResult(pref, FORM_PREFERENCES_KEY); return true; case android.R.id.home: triggerUserQuitInput(); return true; } return super.onOptionsItemSelected(item); } /** * @return true If the current index of the form controller contains questions */ private boolean currentPromptIsQuestion() { return (mFormController.getEvent() == FormEntryController.EVENT_QUESTION || mFormController .getEvent() == FormEntryController.EVENT_GROUP); } private boolean saveAnswersForCurrentScreen(boolean evaluateConstraints) { return saveAnswersForCurrentScreen(evaluateConstraints, true, false); } /** * Attempt to save the answer(s) in the current screen to into the data model. * * @param failOnRequired Whether or not the constraint evaluation * should return false if the question is only * required. (this is helpful for incomplete * saves) * @param headless running in a process that can't display graphics * @return false if any error occurs while saving (constraint violated, * etc...), true otherwise. */ private boolean saveAnswersForCurrentScreen(boolean evaluateConstraints, boolean failOnRequired, boolean headless) { // only try to save if the current event is a question or a field-list // group boolean success = true; if ((mFormController.getEvent() == FormEntryController.EVENT_QUESTION) || ((mFormController.getEvent() == FormEntryController.EVENT_GROUP) && mFormController.indexIsInFieldList())) { HashMap<FormIndex, IAnswerData> answers = mCurrentView.getAnswers(); // Sort the answers so if there are multiple errors, we can // bring focus to the first one List<FormIndex> indexKeys = new ArrayList<>(); indexKeys.addAll(answers.keySet()); Collections.sort(indexKeys, new Comparator<FormIndex>() { @Override public int compare(FormIndex arg0, FormIndex arg1) { return arg0.compareTo(arg1); } }); for (FormIndex index : indexKeys) { // Within a group, you can only save for question events if (mFormController.getEvent(index) == FormEntryController.EVENT_QUESTION) { int saveStatus = saveAnswer(answers.get(index), index, evaluateConstraints); if (evaluateConstraints && ((saveStatus != FormEntryController.ANSWER_OK) && (failOnRequired || saveStatus != FormEntryController.ANSWER_REQUIRED_BUT_EMPTY))) { if (!headless) { showConstraintWarning(index, mFormController.getQuestionPrompt(index).getConstraintText(), saveStatus, success); } success = false; } } else { Log.w(TAG, "Attempted to save an index referencing something other than a question: " + index.getReference()); } } } return success; } /** * Clears the answer on the screen. */ private void clearAnswer(QuestionWidget qw) { qw.clearAnswer(); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.add(0, v.getId(), 0, StringUtils.getStringSpannableRobust(this, R.string.clear_answer)); menu.setHeaderTitle(StringUtils.getStringSpannableRobust(this, R.string.edit_prompt)); } @Override public boolean onContextItemSelected(MenuItem item) { // We don't have the right view here, so we store the View's ID as the // item ID and loop through the possible views to find the one the user // clicked on. for (QuestionWidget qw : mCurrentView.getWidgets()) { if (item.getItemId() == qw.getId()) { createClearDialog(qw); } } return super.onContextItemSelected(item); } /** * If we're loading, then we pass the loading thread to our next instance. */ @Override public Object onRetainCustomNonConfigurationInstance() { // if a form is loading, pass the loader task if (mFormLoaderTask != null && mFormLoaderTask.getStatus() != AsyncTask.Status.FINISHED) return mFormLoaderTask; // if a form is writing to disk, pass the save to disk task if (mSaveToDiskTask != null && mSaveToDiskTask.getStatus() != AsyncTask.Status.FINISHED) return mSaveToDiskTask; // mFormEntryController is static so we don't need to pass it. if (mFormController != null && currentPromptIsQuestion()) { saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); } return null; } private String getHeaderString() { if(mHeaderString != null) { //Localization? return mHeaderString; } else { return StringUtils.getStringRobust(this, R.string.application_name) + " > " + mFormController.getFormTitle(); } } private ODKView createView() { setTitle(getHeaderString()); ODKView odkv; // should only be a group here if the event_group is a field-list try { odkv = new ODKView(this, mFormController.getQuestionPrompts(), mFormController.getGroupsForCurrentIndex(), mFormController.getWidgetFactory(), this); Log.i(TAG, "created view for group"); } catch (RuntimeException e) { Logger.exception(e); CommCareActivity.createErrorDialog(this, e.getMessage(), EXIT); // this is badness to avoid a crash. // really a next view should increment the formcontroller, create the view // if the view is null, then keep the current view and pop an error. return new ODKView(this); } // Makes a "clear answer" menu pop up on long-click of // select-one/select-multiple questions for (QuestionWidget qw : odkv.getWidgets()) { if (!qw.getPrompt().isReadOnly() && !mFormController.isFormReadOnly() && (qw.getPrompt().getControlType() == Constants.CONTROL_SELECT_ONE || qw.getPrompt().getControlType() == Constants.CONTROL_SELECT_MULTI)) { registerForContextMenu(qw); } } FormNavigationUI.updateNavigationCues(this, mFormController, odkv); return odkv; } @SuppressLint("NewApi") @Override public boolean dispatchTouchEvent(MotionEvent mv) { //We need to ignore this even if it's processed by the action //bar (if one exists) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { ActionBar bar = getActionBar(); if (bar != null) { View customView = bar.getCustomView(); if (customView != null && customView.dispatchTouchEvent(mv)) { return true; } } } boolean handled = mGestureDetector.onTouchEvent(mv); return handled || super.dispatchTouchEvent(mv); } /** * Determines what should be displayed on the screen. Possible options are: a question, an ask * repeat dialog, or the submit screen. Also saves answers to the data model after checking * constraints. */ private void showNextView() { showNextView(false); } private void showNextView(boolean resuming) { if (currentPromptIsQuestion()) { if (!saveAnswersForCurrentScreen(EVALUATE_CONSTRAINTS)) { // A constraint was violated so a dialog should be showing. return; } } if (mFormController.getEvent() != FormEntryController.EVENT_END_OF_FORM) { int event; try{ group_skip: do { event = mFormController.stepToNextEvent(FormController.STEP_OVER_GROUP); switch (event) { case FormEntryController.EVENT_QUESTION: ODKView next = createView(); if (!resuming) { showView(next, AnimationType.RIGHT); } else { showView(next, AnimationType.FADE, false); } break group_skip; case FormEntryController.EVENT_END_OF_FORM: // auto-advance questions might advance past the last form quesion triggerUserFormComplete(); break group_skip; case FormEntryController.EVENT_PROMPT_NEW_REPEAT: createRepeatDialog(); break group_skip; case FormEntryController.EVENT_GROUP: //We only hit this event if we're at the _opening_ of a field //list, so it seems totally fine to do it this way, technically //though this should test whether the index is the field list //host. if (mFormController.indexIsInFieldList() && mFormController.getQuestionPrompts().length != 0) { ODKView nextGroupView = createView(); if(!resuming) { showView(nextGroupView, AnimationType.RIGHT); } else { showView(nextGroupView, AnimationType.FADE, false); } break group_skip; } // otherwise it's not a field-list group, so just skip it break; case FormEntryController.EVENT_REPEAT: Log.i(TAG, "repeat: " + mFormController.getFormIndex().getReference()); // skip repeats break; case FormEntryController.EVENT_REPEAT_JUNCTURE: Log.i(TAG, "repeat juncture: " + mFormController.getFormIndex().getReference()); // skip repeat junctures until we implement them break; default: Log.w(TAG, "JavaRosa added a new EVENT type and didn't tell us... shame on them."); break; } } while (event != FormEntryController.EVENT_END_OF_FORM); }catch(XPathTypeMismatchException e){ Logger.exception(e); CommCareActivity.createErrorDialog(this, e.getMessage(), EXIT); } } } /** * Determines what should be displayed between a question, or the start screen and displays the * appropriate view. Also saves answers to the data model without checking constraints. */ private void showPreviousView(boolean showSwipeAnimation) { // The answer is saved on a back swipe, but question constraints are ignored. if (currentPromptIsQuestion()) { saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); } FormIndex startIndex = mFormController.getFormIndex(); FormIndex lastValidIndex = startIndex; if (mFormController.getEvent() != FormEntryController.EVENT_BEGINNING_OF_FORM) { int event = mFormController.stepToPreviousEvent(); //Step backwards until we either find a question, the beginning of the form, //or a field list with valid questions inside while (event != FormEntryController.EVENT_BEGINNING_OF_FORM && event != FormEntryController.EVENT_QUESTION && !(event == FormEntryController.EVENT_GROUP && mFormController.indexIsInFieldList() && mFormController .getQuestionPrompts().length != 0)) { event = mFormController.stepToPreviousEvent(); lastValidIndex = mFormController.getFormIndex(); } if(event == FormEntryController.EVENT_BEGINNING_OF_FORM) { // we can't go all the way back to the beginning, so we've // gotta hit the last index that was valid mFormController.jumpToIndex(lastValidIndex); //Did we jump at all? (not sure how we could have, but there might be a mismatch) if(lastValidIndex.equals(startIndex)) { //If not, don't even bother changing the view. //NOTE: This needs to be the same as the //exit condition below, in case either changes FormEntryActivity.this.triggerUserQuitInput(); return; } //We might have walked all the way back still, which isn't great, //so keep moving forward again until we find it if(lastValidIndex.isBeginningOfFormIndex()) { //there must be a repeat between where we started and the beginning of hte form, walk back up to it this.showNextView(true); return; } } ODKView next = createView(); if (showSwipeAnimation) { showView(next, AnimationType.LEFT); } else { showView(next, AnimationType.FADE, false); } } else { FormEntryActivity.this.triggerUserQuitInput(); } } /** * Displays the View specified by the parameter 'next', animating both the current view and next * appropriately given the AnimationType. Also updates the progress bar. */ private void showView(ODKView next, AnimationType from) { showView(next, from, true); } private void showView(ODKView next, AnimationType from, boolean animateLastView) { switch (from) { case RIGHT: mInAnimation = AnimationUtils.loadAnimation(this, R.anim.push_left_in); mOutAnimation = AnimationUtils.loadAnimation(this, R.anim.push_left_out); break; case LEFT: mInAnimation = AnimationUtils.loadAnimation(this, R.anim.push_right_in); mOutAnimation = AnimationUtils.loadAnimation(this, R.anim.push_right_out); break; case FADE: mInAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_in); mOutAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_out); break; } if (mCurrentView != null) { if(animateLastView) { mCurrentView.startAnimation(mOutAnimation); } mViewPane.removeView(mCurrentView); mCurrentView.teardownView(); } mInAnimation.setAnimationListener(this); RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); mCurrentView = next; mViewPane.addView(mCurrentView, lp); mCurrentView.startAnimation(mInAnimation); FrameLayout header = (FrameLayout)findViewById(R.id.form_entry_header); TextView groupLabel = ((TextView)header.findViewById(R.id.form_entry_group_label)); this.mGroupNativeVisibility = false; this.updateGroupViewVisibility(); mCurrentView.setFocus(this); SpannableStringBuilder groupLabelText = mCurrentView.getGroupLabel(); if (groupLabelText != null && !groupLabelText.toString().trim().equals("")) { groupLabel.setText(groupLabelText); this.mGroupNativeVisibility = true; updateGroupViewVisibility(); } } /** * Creates and displays a dialog displaying the violated constraint. */ private void showConstraintWarning(FormIndex index, String constraintText, int saveStatus, boolean requestFocus) { switch (saveStatus) { case FormEntryController.ANSWER_CONSTRAINT_VIOLATED: if (constraintText == null) { constraintText = StringUtils.getStringRobust(this, R.string.invalid_answer_error); } break; case FormEntryController.ANSWER_REQUIRED_BUT_EMPTY: constraintText = StringUtils.getStringRobust(this, R.string.required_answer_error); break; } boolean displayed = false; //We need to see if question in violation is on the screen, so we can show this cleanly. for(QuestionWidget q : mCurrentView.getWidgets()) { if(index.equals(q.getFormId())) { q.notifyInvalid(constraintText, requestFocus); displayed = true; break; } } if(!displayed) { showCustomToast(constraintText, Toast.LENGTH_SHORT); } isAnimatingSwipe = false; } private void showCustomToast(String message, int duration) { LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.toast_view, null); // set the text in the view TextView tv = (TextView) view.findViewById(R.id.message); tv.setText(message); Toast t = new Toast(this); t.setView(view); t.setDuration(duration); t.setGravity(Gravity.CENTER, 0, 0); t.show(); } /** * Creates and displays a dialog asking the user if they'd like to create a repeat of the * current group. */ private void createRepeatDialog() { isDialogShowing = true; // Determine the effect that back and next buttons should have FormNavigationController.NavigationDetails details; try { details = FormNavigationController.calculateNavigationStatus(mFormController, mCurrentView); } catch (XPathTypeMismatchException e) { Logger.exception(e); CommCareActivity.createErrorDialog(this, e.getMessage(), EXIT); return; } final boolean backExitsForm = !details.relevantBeforeCurrentScreen; final boolean nextExitsForm = details.relevantAfterCurrentScreen == 0; // Assign title and text strings based on the current state String title, addAnotherText, skipText, backText; backText = StringUtils.getStringSpannableRobust(this, R.string.repeat_go_back).toString(); if (mFormController.getLastRepeatCount() > 0) { title = StringUtils.getStringSpannableRobust(this, R.string.add_another_repeat, mFormController.getLastGroupText()).toString(); addAnotherText = StringUtils.getStringSpannableRobust(this, R.string.add_another).toString(); if (!nextExitsForm) { skipText = StringUtils.getStringSpannableRobust(this, R.string.leave_repeat_yes).toString(); } else { skipText = StringUtils.getStringSpannableRobust(this, R.string.leave_repeat_yes_exits).toString(); } } else { title = StringUtils.getStringSpannableRobust(this, R.string.add_repeat, mFormController.getLastGroupText()).toString(); addAnotherText = StringUtils.getStringSpannableRobust(this, R.string.entering_repeat).toString(); if (!nextExitsForm) { skipText = StringUtils.getStringSpannableRobust(this, R.string.add_repeat_no).toString(); } else { skipText = StringUtils.getStringSpannableRobust(this, R.string.add_repeat_no_exits).toString(); } } // Create the choice dialog ContextThemeWrapper wrapper = new ContextThemeWrapper(this, R.style.DialogBaseTheme); final PaneledChoiceDialog dialog = new HorizontalPaneledChoiceDialog(wrapper, title); // Panel 1: Back option View.OnClickListener backListener = new OnClickListener() { @Override public void onClick(View v) { if (backExitsForm) { FormEntryActivity.this.triggerUserQuitInput(); } else { dialog.dismiss(); FormEntryActivity.this.refreshCurrentView(false); } } }; int backIconId; if (backExitsForm) { backIconId = R.drawable.icon_exit; } else { backIconId = R.drawable.icon_back; } DialogChoiceItem backItem = new DialogChoiceItem(backText, backIconId, backListener); // Panel 2: Add another option View.OnClickListener addAnotherListener = new OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); try { mFormController.newRepeat(); } catch (XPathTypeMismatchException e) { Logger.exception(e); CommCareActivity.createErrorDialog(FormEntryActivity.this, e.getMessage(), EXIT); return; } showNextView(); } }; DialogChoiceItem addAnotherItem = new DialogChoiceItem(addAnotherText, R.drawable.icon_new, addAnotherListener); // Panel 3: Skip option View.OnClickListener skipListener = new OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); if (!nextExitsForm) { showNextView(); } else { triggerUserFormComplete(); } } }; int skipIconId; if (nextExitsForm) { skipIconId = R.drawable.icon_done; } else { skipIconId = R.drawable.icon_next; } DialogChoiceItem skipItem = new DialogChoiceItem(skipText, skipIconId, skipListener); dialog.setChoiceItems(new DialogChoiceItem[]{backItem, addAnotherItem, skipItem}); dialog.makeNotCancelable(); dialog.setOnDismissListener( new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface d) { isDialogShowing = false; } } ); dialog.show(); } private void saveFormToDisk(boolean exit) { if (formHasLoaded()) { boolean isFormComplete = isInstanceComplete(); saveDataToDisk(exit, isFormComplete, null, false); } else if (exit) { showSaveErrorAndExit(); } } private void saveCompletedFormToDisk(String updatedSaveName) { saveDataToDisk(EXIT, true, updatedSaveName, false); } private void saveIncompleteFormToDisk() { saveDataToDisk(EXIT, false, null, true); } private void showSaveErrorAndExit() { Toast.makeText(this, StringUtils.getStringSpannableRobust(this, R.string.data_saved_error), Toast.LENGTH_SHORT).show(); hasSaved = false; finishReturnInstance(); } /** * Saves form data to disk. * * @param exit If set, will exit program after save. * @param complete Has the user marked the instances as complete? * @param updatedSaveName Set name of the instance's content provider, if * non-null * @param headless Disables GUI warnings and lets answers that * violate constraints be saved. */ private void saveDataToDisk(boolean exit, boolean complete, String updatedSaveName, boolean headless) { if (!formHasLoaded()) { if (exit) { showSaveErrorAndExit(); } return; } // save current answer; if headless, don't evaluate the constraints // before doing so. if (headless && (!saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS, complete, headless))) { return; } else if (!headless && !saveAnswersForCurrentScreen(EVALUATE_CONSTRAINTS, complete, headless)) { Toast.makeText(this, StringUtils.getStringSpannableRobust(this, R.string.data_saved_error), Toast.LENGTH_SHORT).show(); return; } // If a save task is already running, just let it do its thing if ((mSaveToDiskTask != null) && (mSaveToDiskTask.getStatus() != AsyncTask.Status.FINISHED)) { return; } mSaveToDiskTask = new SaveToDiskTask(getIntent().getData(), exit, complete, updatedSaveName, this, instanceProviderContentURI, symetricKey, headless); if (!headless){ mSaveToDiskTask.connect(this); } mSaveToDiskTask.setFormSavedListener(this); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { mSaveToDiskTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } else { mSaveToDiskTask.execute(); } } /** * Create a dialog with options to save and exit, save, or quit without saving */ private void createQuitDialog() { final PaneledChoiceDialog dialog = new PaneledChoiceDialog(this, StringUtils.getStringRobust(this, R.string.quit_form_title)); View.OnClickListener stayInFormListener = new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }; DialogChoiceItem stayInFormItem = new DialogChoiceItem( StringUtils.getStringRobust(this, R.string.do_not_exit), R.drawable.ic_blue_forward, stayInFormListener); View.OnClickListener exitFormListener = new View.OnClickListener() { @Override public void onClick(View v) { discardChangesAndExit(); } }; DialogChoiceItem quitFormItem = new DialogChoiceItem( StringUtils.getStringRobust(this, R.string.do_not_save), R.drawable.ic_trashcan, exitFormListener); DialogChoiceItem[] items; if (mIncompleteEnabled) { View.OnClickListener saveIncompleteListener = new View.OnClickListener() { @Override public void onClick(View v) { saveFormToDisk(EXIT); } }; DialogChoiceItem saveIncompleteItem = new DialogChoiceItem( StringUtils.getStringRobust(this, R.string.keep_changes), R.drawable.ic_incomplete_orange, saveIncompleteListener); items = new DialogChoiceItem[] {stayInFormItem, quitFormItem, saveIncompleteItem}; } else { items = new DialogChoiceItem[] {stayInFormItem, quitFormItem}; } dialog.setChoiceItems(items); dialog.show(); } private void discardChangesAndExit() { String selection = InstanceColumns.INSTANCE_FILE_PATH + " like '" + mInstancePath + "'"; Cursor c = null; int instanceCount = 0; try { c = getContentResolver().query(instanceProviderContentURI, null, selection, null, null); if (c != null) { instanceCount = c.getCount(); } } finally { if (c != null) { c.close(); } } // if it's not already saved, erase everything if (instanceCount < 1) { int images = 0; int audio = 0; int video = 0; // delete media first String instanceFolder = mInstancePath.substring(0, mInstancePath.lastIndexOf("/") + 1); Log.i(TAG, "attempting to delete: " + instanceFolder); String where = Images.Media.DATA + " like '" + instanceFolder + "%'"; // images Cursor imageCursor = null; try { String[] projection = { Images.ImageColumns._ID }; imageCursor = getContentResolver().query( android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, where, null, null); if (imageCursor != null && imageCursor.getCount() > 0) { imageCursor.moveToFirst(); int columnIndex = imageCursor.getColumnIndex(Images.ImageColumns._ID); String id = imageCursor.getString(columnIndex); Log.i( TAG, "attempting to delete: " + Uri.withAppendedPath( android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id)); images = getContentResolver() .delete( Uri.withAppendedPath( android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id), null, null); } } finally { if ( imageCursor != null ) { imageCursor.close(); } } // audio Cursor audioCursor = null; try { String[] projection = { MediaStore.Audio.AudioColumns._ID }; audioCursor = getContentResolver().query( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, projection, where, null, null); if (audioCursor != null && audioCursor.getCount() > 0) { audioCursor.moveToFirst(); int columnIndex = audioCursor.getColumnIndex(MediaStore.Audio.AudioColumns._ID); String id = audioCursor.getString(columnIndex); Log.i( TAG, "attempting to delete: " + Uri.withAppendedPath( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id)); audio = getContentResolver() .delete( Uri.withAppendedPath( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id), null, null); } } finally { if ( audioCursor != null ) { audioCursor.close(); } } // video Cursor videoCursor = null; try { String[] projection = { MediaStore.Video.VideoColumns._ID }; videoCursor = getContentResolver().query( MediaStore.Video.Media.EXTERNAL_CONTENT_URI, projection, where, null, null); if (videoCursor != null && videoCursor.getCount() > 0) { videoCursor.moveToFirst(); int columnIndex = videoCursor.getColumnIndex(MediaStore.Video.VideoColumns._ID); String id = videoCursor.getString(columnIndex); Log.i( TAG, "attempting to delete: " + Uri.withAppendedPath( MediaStore.Video.Media.EXTERNAL_CONTENT_URI, id)); video = getContentResolver() .delete( Uri.withAppendedPath( MediaStore.Video.Media.EXTERNAL_CONTENT_URI, id), null, null); } } finally { if ( videoCursor != null ) { videoCursor.close(); } } Log.i(TAG, "removed from content providers: " + images + " image files, " + audio + " audio files," + " and " + video + " video files."); File f = new File(instanceFolder); if (f.exists() && f.isDirectory()) { for (File del : f.listFiles()) { Log.i(TAG, "deleting file: " + del.getAbsolutePath()); del.delete(); } f.delete(); } } finishReturnInstance(false); } /** * Confirm clear answer dialog */ private void createClearDialog(final QuestionWidget qw) { String title = StringUtils.getStringRobust(this, R.string.clear_answer_ask); String question = qw.getPrompt().getLongText(); if (question.length() > 50) { question = question.substring(0, 50) + "..."; } String msg = StringUtils.getStringSpannableRobust(this, R.string.clearanswer_confirm, question).toString(); AlertDialogFactory factory = new AlertDialogFactory(this, title, msg); factory.setIcon(android.R.drawable.ic_dialog_info); DialogInterface.OnClickListener quitListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { switch (i) { case DialogInterface.BUTTON_POSITIVE: clearAnswer(qw); saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); break; case DialogInterface.BUTTON_NEGATIVE: break; } dialog.dismiss(); } }; factory.setPositiveButton(StringUtils.getStringSpannableRobust(this, R.string.discard_answer), quitListener); factory.setNegativeButton(StringUtils.getStringSpannableRobust(this, R.string.clear_answer_no), quitListener); showAlertDialog(factory); } /** * Creates and displays a dialog allowing the user to set the language for the form. */ private void createLanguageDialog() { final PaneledChoiceDialog dialog = new PaneledChoiceDialog(this, StringUtils.getStringRobust(this, R.string.choose_language)); final String[] languages = mFormController.getLanguages(); DialogChoiceItem[] choiceItems = new DialogChoiceItem[languages.length]; for (int i = 0; i < languages.length; i++) { final int index = i; View.OnClickListener listener = new View.OnClickListener() { @Override public void onClick(View v) { // Update the language in the content provider when selecting a new // language ContentValues values = new ContentValues(); values.put(FormsColumns.LANGUAGE, languages[index]); String selection = FormsColumns.FORM_FILE_PATH + "=?"; String selectArgs[] = { mFormPath }; int updated = getContentResolver().update(formProviderContentURI, values, selection, selectArgs); Log.i(TAG, "Updated language to: " + languages[index] + " in " + updated + " rows"); mFormController.setLanguage(languages[index]); dialog.dismiss(); if (currentPromptIsQuestion()) { saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); } refreshCurrentView(); } }; choiceItems[i] = new DialogChoiceItem(languages[i], -1, listener); } dialog.addButton(StringUtils.getStringSpannableRobust(this, R.string.cancel).toString(), new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } } ); dialog.setChoiceItems(choiceItems); dialog.show(); } @Override public CustomProgressDialog generateProgressDialog(int id) { CustomProgressDialog dialog = null; switch (id) { case FormLoaderTask.FORM_LOADER_TASK_ID: dialog = CustomProgressDialog.newInstance( StringUtils.getStringRobust(this, R.string.loading_form), StringUtils.getStringRobust(this, R.string.please_wait), id); dialog.addCancelButton(); break; case SaveToDiskTask.SAVING_TASK_ID: dialog = CustomProgressDialog.newInstance( StringUtils.getStringRobust(this, R.string.saving_form), StringUtils.getStringRobust(this, R.string.please_wait), id); break; } return dialog; } @Override public void taskCancelled(int id) { finish(); } @Override protected void onPause() { super.onPause(); if (mCurrentView != null && currentPromptIsQuestion()) { saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS); } if (mLocationServiceIssueReceiver != null) { unregisterReceiver(mLocationServiceIssueReceiver); } } @Override protected void onResume() { super.onResume(); if (!hasFormLoadBeenTriggered) { loadForm(); } registerFormEntryReceiver(); restoreTimePickerData(); if (mFormController != null) { // clear pending callout post onActivityResult processing mFormController.setPendingCalloutFormIndex(null); } } private void restoreTimePickerData() { // On honeycomb and above this is handled by calling: // TimePicker.setSaveFromParentEnabled(false); // TimePicker.setSaveEnabled(true); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { //csims@dimagi.com - 22/08/2012 - For release only, fix immediately. //There is a _horribly obnoxious_ bug in TimePickers that messes up how they work //on screen rotation. We need to re-do any setAnswers that we perform on them after //onResume. try { if (mCurrentView.getWidgets() != null) { for (QuestionWidget qw : mCurrentView.getWidgets()) { if (qw instanceof DateTimeWidget) { ((DateTimeWidget)qw).setAnswer(); } else if (qw instanceof TimeWidget) { ((TimeWidget)qw).setAnswer(); } } } } catch (Exception e) { //if this fails, we _really_ don't want to mess anything up. this is a last minute //fix } } } private void loadForm() { mFormController = null; mInstancePath = null; Intent intent = getIntent(); if (intent != null) { loadIntentFormData(intent); setTitleToLoading(); Uri uri = intent.getData(); final String contentType = getContentResolver().getType(uri); Uri formUri; if (contentType == null){ CommCareHomeActivity.createErrorDialog(this, "form URI resolved to null", EXIT); return; } boolean isInstanceReadOnly = false; try { switch (contentType) { case InstanceColumns.CONTENT_ITEM_TYPE: Pair<Uri, Boolean> instanceAndStatus = getInstanceUri(uri); formUri = instanceAndStatus.first; isInstanceReadOnly = instanceAndStatus.second; break; case FormsColumns.CONTENT_ITEM_TYPE: formUri = uri; mFormPath = getFormPath(uri); break; default: Log.e(TAG, "unrecognized URI"); CommCareHomeActivity.createErrorDialog(this, "unrecognized URI: " + uri, EXIT); return; } } catch (FormQueryException e) { CommCareHomeActivity.createErrorDialog(this, e.getMessage(), EXIT); return; } if(formUri == null) { Log.e(TAG, "unrecognized URI"); CommCareActivity.createErrorDialog(this, "couldn't locate FormDB entry for the item at: " + uri, EXIT); return; } mFormLoaderTask = new FormLoaderTask<FormEntryActivity>(symetricKey, isInstanceReadOnly, this) { @Override protected void deliverResult(FormEntryActivity receiver, FECWrapper wrapperResult) { receiver.handleFormLoadCompletion(wrapperResult.getController()); } @Override protected void deliverUpdate(FormEntryActivity receiver, String... update) { } @Override protected void deliverError(FormEntryActivity receiver, Exception e) { receiver.setFormLoadFailure(); receiver.dismissProgressDialog(); if (e != null) { CommCareActivity.createErrorDialog(receiver, e.getMessage(), EXIT); } else { CommCareActivity.createErrorDialog(receiver, StringUtils.getStringRobust(receiver, R.string.parse_error), EXIT); } } }; mFormLoaderTask.connect(this); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { mFormLoaderTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, formUri); } else { mFormLoaderTask.execute(formUri); } hasFormLoadBeenTriggered = true; } } private void handleFormLoadCompletion(FormController fc) { mFormController = fc; if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){ // Newer menus may have already built the menu, before all data was ready invalidateOptionsMenu(); } Localizer mLocalizer = Localization.getGlobalLocalizerAdvanced(); if(mLocalizer != null){ String mLocale = mLocalizer.getLocale(); if (mLocale != null && fc.getLanguages() != null && Arrays.asList(fc.getLanguages()).contains(mLocale)){ fc.setLanguage(mLocale); } else{ Logger.log("formloader", "The current locale is not set"); } } else{ Logger.log("formloader", "Could not get the localizer"); } registerSessionFormSaveCallback(); // Set saved answer path if (mInstancePath == null) { // Create new answer folder. String time = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss") .format(Calendar.getInstance().getTime()); String file = mFormPath.substring(mFormPath.lastIndexOf('/') + 1, mFormPath.lastIndexOf('.')); String path = mInstanceDestination + file + "_" + time; if (FileUtils.createFolder(path)) { mInstancePath = path + "/" + file + "_" + time + ".xml"; } } else { // we've just loaded a saved form, so start in the hierarchy view Intent i = new Intent(FormEntryActivity.this, FormHierarchyActivity.class); startActivityForResult(i, HIERARCHY_ACTIVITY_FIRST_START); return; // so we don't show the intro screen before jumping to the hierarchy } refreshCurrentView(); FormNavigationUI.updateNavigationCues(this, mFormController, mCurrentView); } /** * Call when the user provides input that they want to quit the form */ private void triggerUserQuitInput() { if(!formHasLoaded()) { finish(); } else if (mFormController.isFormReadOnly()) { // If we're just reviewing a read only form, don't worry about saving // or what not, just quit // It's possible we just want to "finish" here, but // I don't really wanna break any c compatibility finishReturnInstance(false); } else { createQuitDialog(); } } /** * Get the default title for ODK's "Form title" field */ private String getDefaultFormTitle() { String saveName = mFormController.getFormTitle(); if (InstanceColumns.CONTENT_ITEM_TYPE.equals(getContentResolver().getType(getIntent().getData()))) { Uri instanceUri = getIntent().getData(); Cursor instance = null; try { instance = getContentResolver().query(instanceUri, null, null, null, null); if (instance != null && instance.getCount() == 1) { instance.moveToFirst(); saveName = instance.getString(instance .getColumnIndex(InstanceColumns.DISPLAY_NAME)); } } finally { if (instance != null) { instance.close(); } } } return saveName; } /** * Call when the user is ready to save and return the current form as complete */ private void triggerUserFormComplete() { if (mFormController.isFormReadOnly()) { finishReturnInstance(false); } else { saveCompletedFormToDisk(getDefaultFormTitle()); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: triggerUserQuitInput(); return true; case KeyEvent.KEYCODE_DPAD_RIGHT: if (event.isAltPressed() && !shouldIgnoreSwipeAction()) { isAnimatingSwipe = true; showNextView(); return true; } break; case KeyEvent.KEYCODE_DPAD_LEFT: if (event.isAltPressed() && !shouldIgnoreSwipeAction()) { isAnimatingSwipe = true; showPreviousView(true); return true; } break; } return super.onKeyDown(keyCode, event); } private boolean shouldIgnoreSwipeAction() { return isAnimatingSwipe || isDialogShowing; } @Override protected void onDestroy() { if (mFormLoaderTask != null) { // We have to call cancel to terminate the thread, otherwise it // lives on and retains the FEC in memory. // but only if it's done, otherwise the thread never returns if (mFormLoaderTask.getStatus() == AsyncTask.Status.FINISHED) { mFormLoaderTask.cancel(true); mFormLoaderTask.destroy(); } } if (mSaveToDiskTask != null) { // We have to call cancel to terminate the thread, otherwise it // lives on and retains the FEC in memory. if (mSaveToDiskTask.getStatus() == AsyncTask.Status.FINISHED) { mSaveToDiskTask.cancel(false); } } super.onDestroy(); } @Override public void onAnimationEnd(Animation arg0) { isAnimatingSwipe = false; } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationStart(Animation animation) { } private void registerSessionFormSaveCallback() { if (mFormController != null && !mFormController.isFormReadOnly()) { try { // CommCareSessionService will call this.formSaveCallback when // the key session is closing down and we need to save any // intermediate results before they become un-saveable. CommCareApplication._().getSession().registerFormSaveCallback(this); } catch (SessionUnavailableException e) { Logger.log(AndroidLogger.TYPE_ERROR_WORKFLOW, "Couldn't register form save callback because session doesn't exist"); } } } /** * {@inheritDoc} * * Display save status notification and exit or continue on in the form. * If form entry is being saved because key session is expiring then * continue closing the session/logging out. * * @see org.odk.collect.android.listeners.FormSavedListener#savingComplete(int, boolean) */ @Override public void savingComplete(int saveStatus, boolean headless) { // Did we just save a form because the key session // (CommCareSessionService) is ending? if (savingFormOnKeySessionExpiration) { savingFormOnKeySessionExpiration = false; // Notify the key session that the form state has been saved (or at // least attempted to be saved) so CommCareSessionService can // continue closing down key pool and user database. CommCareApplication._().expireUserSession(); } else { switch (saveStatus) { case SaveToDiskTask.SAVED: Toast.makeText(this, StringUtils.getStringSpannableRobust(this, R.string.data_saved_ok), Toast.LENGTH_SHORT).show(); hasSaved = true; break; case SaveToDiskTask.SAVED_AND_EXIT: Toast.makeText(this, StringUtils.getStringSpannableRobust(this, R.string.data_saved_ok), Toast.LENGTH_SHORT).show(); hasSaved = true; finishReturnInstance(); break; case SaveToDiskTask.SAVE_ERROR: Toast.makeText(this, StringUtils.getStringSpannableRobust(this, R.string.data_saved_error), Toast.LENGTH_LONG).show(); break; case FormEntryController.ANSWER_CONSTRAINT_VIOLATED: case FormEntryController.ANSWER_REQUIRED_BUT_EMPTY: // an answer constraint was violated, so try to save the // current question to trigger the constraint violation message refreshCurrentView(); saveAnswersForCurrentScreen(EVALUATE_CONSTRAINTS); return; } refreshCurrentView(); } } /** * Attempts to save an answer to the specified index. * * @param evaluateConstraints Should form contraints be checked when saving answer? * @return status as determined in FormEntryController */ private int saveAnswer(IAnswerData answer, FormIndex index, boolean evaluateConstraints) { try { if (evaluateConstraints) { return mFormController.answerQuestion(index, answer); } else { mFormController.saveAnswer(index, answer); return FormEntryController.ANSWER_OK; } } catch (XPathException e) { //this is where runtime exceptions get triggered after the form has loaded CommCareActivity.createErrorDialog(this, "There is a bug in one of your form's XPath Expressions \n" + e.getMessage(), EXIT); //We're exiting anyway return FormEntryController.ANSWER_OK; } } /** * Checks the database to determine if the current instance being edited has already been * 'marked completed'. A form can be 'unmarked' complete and then resaved. * * @return true if form has been marked completed, false otherwise. */ private boolean isInstanceComplete() { // default to false if we're mid form boolean complete = false; // Then see if we've already marked this form as complete before String selection = InstanceColumns.INSTANCE_FILE_PATH + "=?"; String[] selectionArgs = { mInstancePath }; Cursor c = null; try { c = getContentResolver().query(instanceProviderContentURI, null, selection, selectionArgs, null); if (c != null && c.getCount() > 0) { c.moveToFirst(); String status = c.getString(c.getColumnIndex(InstanceColumns.STATUS)); if (InstanceProviderAPI.STATUS_COMPLETE.compareTo(status) == 0) { complete = true; } } } finally { if (c != null) { c.close(); } } return complete; } private void next() { if (!shouldIgnoreSwipeAction()) { isAnimatingSwipe = true; showNextView(); } } private void finishReturnInstance() { finishReturnInstance(true); } /** * Returns the instance that was just filled out to the calling activity, * if requested. * * @param reportSaved was a form saved? Delegates the result code of the * activity */ private void finishReturnInstance(boolean reportSaved) { String action = getIntent().getAction(); if (Intent.ACTION_PICK.equals(action) || Intent.ACTION_EDIT.equals(action)) { // caller is waiting on a picked form String selection = InstanceColumns.INSTANCE_FILE_PATH + "=?"; String[] selectionArgs = { mInstancePath }; Cursor c = null; try { c = getContentResolver().query(instanceProviderContentURI, null, selection, selectionArgs, null); if (c != null && c.getCount() > 0) { // should only be one... c.moveToFirst(); String id = c.getString(c.getColumnIndex(InstanceColumns._ID)); Uri instance = Uri.withAppendedPath(instanceProviderContentURI, id); Intent formReturnIntent = new Intent(); formReturnIntent.putExtra(IS_ARCHIVED_FORM, mFormController.isFormReadOnly()); if (reportSaved || hasSaved) { setResult(RESULT_OK, formReturnIntent.setData(instance)); } else { setResult(RESULT_CANCELED, formReturnIntent.setData(instance)); } } } finally { if (c != null) { c.close(); } } } try { CommCareApplication._().getSession().unregisterFormSaveCallback(); } catch (SessionUnavailableException sue) { // looks like the session expired } dismissProgressDialog(); finish(); } @Override protected boolean onBackwardSwipe() { showPreviousView(true); return true; } @Override protected boolean onForwardSwipe() { //We've already computed the "is there more coming" stuff intensely in the the nav details //and set the forward button tag appropriately, so use that to determine whether we can //swipe forward. ImageButton nextButton = (ImageButton)this.findViewById(R.id.nav_btn_next); if(nextButton.getTag().equals(NAV_STATE_NEXT)) { next(); return true; } else { FormNavigationUI.animateFinishArrow(this); return true; } } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { // The onFling() captures the 'up' event so our view thinks it gets long pressed. // We don't wnat that, so cancel it. if (mCurrentView != null) { mCurrentView.cancelLongPress(); } return false; } @Override public void advance() { next(); } @Override public void widgetEntryChanged() { try { updateFormRelevancies(); } catch (XPathTypeMismatchException e) { Logger.exception(e); CommCareActivity.createErrorDialog(this, e.getMessage(), EXIT); return; } FormNavigationUI.updateNavigationCues(this, mFormController, mCurrentView); } /** * Has form loading (via FormLoaderTask) completed? */ private boolean formHasLoaded() { return mFormController != null; } private void addBreadcrumbBar() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { final String fragmentClass = this.getIntent().getStringExtra(TITLE_FRAGMENT_TAG); if (fragmentClass != null) { final FragmentManager fm = this.getSupportFragmentManager(); Fragment bar = fm.findFragmentByTag(TITLE_FRAGMENT_TAG); if (bar == null) { try { bar = ((Class<Fragment>)Class.forName(fragmentClass)).newInstance(); ActionBar actionBar = getActionBar(); if (actionBar != null) { actionBar.setDisplayShowCustomEnabled(true); actionBar.setDisplayShowTitleEnabled(false); } fm.beginTransaction().add(bar, TITLE_FRAGMENT_TAG).commit(); } catch(Exception e) { Log.w(TAG, "couldn't instantiate fragment: " + fragmentClass); } } } } } private void loadStateFromBundle(Bundle savedInstanceState) { if (savedInstanceState != null) { if (savedInstanceState.containsKey(KEY_FORMPATH)) { mFormPath = savedInstanceState.getString(KEY_FORMPATH); } if (savedInstanceState.containsKey(KEY_FORM_LOAD_HAS_TRIGGERED)) { hasFormLoadBeenTriggered = savedInstanceState.getBoolean(KEY_FORM_LOAD_HAS_TRIGGERED, false); } if (savedInstanceState.containsKey(KEY_FORM_LOAD_FAILED)) { hasFormLoadFailed = savedInstanceState.getBoolean(KEY_FORM_LOAD_FAILED, false); } if (savedInstanceState.containsKey(KEY_FORM_CONTENT_URI)) { formProviderContentURI = Uri.parse(savedInstanceState.getString(KEY_FORM_CONTENT_URI)); } if (savedInstanceState.containsKey(KEY_INSTANCE_CONTENT_URI)) { instanceProviderContentURI = Uri.parse(savedInstanceState.getString(KEY_INSTANCE_CONTENT_URI)); } if (savedInstanceState.containsKey(KEY_INSTANCEDESTINATION)) { mInstanceDestination = savedInstanceState.getString(KEY_INSTANCEDESTINATION); } if(savedInstanceState.containsKey(KEY_INCOMPLETE_ENABLED)) { mIncompleteEnabled = savedInstanceState.getBoolean(KEY_INCOMPLETE_ENABLED); } if(savedInstanceState.containsKey(KEY_RESIZING_ENABLED)) { ResizingImageView.resizeMethod = savedInstanceState.getString(KEY_RESIZING_ENABLED); } if (savedInstanceState.containsKey(KEY_AES_STORAGE_KEY)) { String base64Key = savedInstanceState.getString(KEY_AES_STORAGE_KEY); try { byte[] storageKey = new Base64Wrapper().decode(base64Key); symetricKey = new SecretKeySpec(storageKey, "AES"); } catch (ClassNotFoundException e) { throw new RuntimeException("Base64 encoding not available on this platform"); } } if(savedInstanceState.containsKey(KEY_HEADER_STRING)) { mHeaderString = savedInstanceState.getString(KEY_HEADER_STRING); } if(savedInstanceState.containsKey(KEY_HAS_SAVED)) { hasSaved = savedInstanceState.getBoolean(KEY_HAS_SAVED); } } } private String getFormPath(Uri uri) throws FormQueryException { Cursor c = null; try { c = getContentResolver().query(uri, null, null, null, null); if (c == null) { throw new FormQueryException("Bad URI: resolved to null"); } else if (c.getCount() != 1) { throw new FormQueryException("Bad URI: " + uri); } else { c.moveToFirst(); return c.getString(c.getColumnIndex(FormsColumns.FORM_FILE_PATH)); } } finally { if (c != null) { c.close(); } } } private Pair<Uri, Boolean> getInstanceUri(Uri uri) throws FormQueryException { Cursor instanceCursor = null; Cursor formCursor = null; Boolean isInstanceReadOnly = false; Uri formUri = null; try { instanceCursor = getContentResolver().query(uri, null, null, null, null); if (instanceCursor == null) { throw new FormQueryException("Bad URI: resolved to null"); } else if (instanceCursor.getCount() != 1) { throw new FormQueryException("Bad URI: " + uri); } else { instanceCursor.moveToFirst(); mInstancePath = instanceCursor.getString(instanceCursor .getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH)); final String jrFormId = instanceCursor.getString(instanceCursor .getColumnIndex(InstanceColumns.JR_FORM_ID)); //If this form is both already completed if (InstanceProviderAPI.STATUS_COMPLETE.equals(instanceCursor.getString(instanceCursor.getColumnIndex(InstanceColumns.STATUS)))) { if (!Boolean.parseBoolean(instanceCursor.getString(instanceCursor.getColumnIndex(InstanceColumns.CAN_EDIT_WHEN_COMPLETE)))) { isInstanceReadOnly = true; } } final String[] selectionArgs = { jrFormId }; final String selection = FormsColumns.JR_FORM_ID + " like ?"; formCursor = getContentResolver().query(formProviderContentURI, null, selection, selectionArgs, null); if (formCursor == null || formCursor.getCount() < 1) { throw new FormQueryException("Parent form does not exist"); } else if (formCursor.getCount() == 1) { formCursor.moveToFirst(); mFormPath = formCursor.getString(formCursor .getColumnIndex(FormsColumns.FORM_FILE_PATH)); formUri = ContentUris.withAppendedId(formProviderContentURI, formCursor.getLong(formCursor.getColumnIndex(FormsColumns._ID))); } else if (formCursor.getCount() > 1) { throw new FormQueryException("More than one possible parent form"); } } } finally { if (instanceCursor != null) { instanceCursor.close(); } if (formCursor != null) { formCursor.close(); } } return new Pair<>(formUri, isInstanceReadOnly); } private void loadIntentFormData(Intent intent) { if(intent.hasExtra(KEY_FORM_CONTENT_URI)) { this.formProviderContentURI = Uri.parse(intent.getStringExtra(KEY_FORM_CONTENT_URI)); } if(intent.hasExtra(KEY_INSTANCE_CONTENT_URI)) { this.instanceProviderContentURI = Uri.parse(intent.getStringExtra(KEY_INSTANCE_CONTENT_URI)); } if(intent.hasExtra(KEY_INSTANCEDESTINATION)) { this.mInstanceDestination = intent.getStringExtra(KEY_INSTANCEDESTINATION); } else { mInstanceDestination = ODKStorage.INSTANCES_PATH; } if(intent.hasExtra(KEY_AES_STORAGE_KEY)) { String base64Key = intent.getStringExtra(KEY_AES_STORAGE_KEY); try { byte[] storageKey = new Base64Wrapper().decode(base64Key); symetricKey = new SecretKeySpec(storageKey, "AES"); } catch (ClassNotFoundException e) { throw new RuntimeException("Base64 encoding not available on this platform"); } } if(intent.hasExtra(KEY_HEADER_STRING)) { FormEntryActivity.mHeaderString = intent.getStringExtra(KEY_HEADER_STRING); } if(intent.hasExtra(KEY_INCOMPLETE_ENABLED)) { this.mIncompleteEnabled = intent.getBooleanExtra(KEY_INCOMPLETE_ENABLED, true); } if(intent.hasExtra(KEY_RESIZING_ENABLED)) { ResizingImageView.resizeMethod = intent.getStringExtra(KEY_RESIZING_ENABLED); } } private void setTitleToLoading() { if(mHeaderString != null) { setTitle(mHeaderString); } else { setTitle(StringUtils.getStringRobust(this, R.string.application_name) + " > " + StringUtils.getStringRobust(this, R.string.loading_form)); } } private class FormQueryException extends Exception { FormQueryException(String msg) { super(msg); } } private void setFormLoadFailure() { hasFormLoadFailed = true; } @Override protected void onMajorLayoutChange(Rect newRootViewDimensions) { determineNumberOfValidGroupLines(newRootViewDimensions); } private void determineNumberOfValidGroupLines(Rect newRootViewDimensions) { FrameLayout header = (FrameLayout)findViewById(R.id.form_entry_header); TextView groupLabel = ((TextView)header.findViewById(R.id.form_entry_group_label)); int contentSize = newRootViewDimensions.height(); View navBar = this.findViewById(R.id.nav_pane); int headerSize = navBar.getHeight(); if(headerSize == 0) { headerSize = this.getResources().getDimensionPixelSize(R.dimen.new_progressbar_minheight); } int availableWindow = contentSize - headerSize - getActionBarSize(); int questionFontSize = getFontSizeInPx(); //Request a consistent amount of the screen before groups can cut down int spaceRequested = questionFontSize * 6; int spaceAvailable = availableWindow - spaceRequested; int defaultHeaderSpace = this.getResources().getDimensionPixelSize(R.dimen.content_min_margin) * 2; float textSize = groupLabel.getTextSize(); int numberOfGroupLinesAllowed = (int)((spaceAvailable - defaultHeaderSpace) / textSize); if(numberOfGroupLinesAllowed < 0) { numberOfGroupLinesAllowed = 0; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { if (groupLabel.getMaxLines() == numberOfGroupLinesAllowed) { return; } } if(numberOfGroupLinesAllowed == 0) { this.mGroupForcedInvisible = true; updateGroupViewVisibility(); groupLabel.setMaxLines(0); } else { this.mGroupForcedInvisible = false; updateGroupViewVisibility(); groupLabel.setMaxLines(numberOfGroupLinesAllowed); } } private void updateGroupViewVisibility() { FrameLayout header = (FrameLayout)findViewById(R.id.form_entry_header); TextView groupLabel = ((TextView)header.findViewById(R.id.form_entry_group_label)); if(mGroupNativeVisibility && !mGroupForcedInvisible) { header.setVisibility(View.VISIBLE); groupLabel.setVisibility(View.VISIBLE); } else { header.setVisibility(View.GONE); groupLabel.setVisibility(View.GONE); } } private int getFontSizeInPx() { SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); String question_font = settings.getString(FormEntryPreferences.KEY_FONT_SIZE, ODKStorage.DEFAULT_FONTSIZE); int sizeInPx = Integer.valueOf(question_font); return (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, sizeInPx, getResources().getDisplayMetrics()); } /** * For Testing purposes only */ public ODKView getODKView() { if (BuildConfig.DEBUG) { return mCurrentView; } else { throw new RuntimeException("On principal of design, only meant for testing purposes"); } } }
package org.jabref.logic.importer.fetcher; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.util.Objects; import org.jabref.logic.cleanup.DoiCleanup; import org.jabref.logic.formatter.bibtexfields.ClearFormatter; import org.jabref.logic.help.HelpFile; import org.jabref.logic.importer.FetcherException; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.importer.Parser; import org.jabref.logic.importer.SearchBasedParserFetcher; import org.jabref.logic.importer.fileformat.BibtexParser; import org.jabref.model.cleanup.FieldFormatterCleanup; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.FieldName; import org.jabref.model.util.DummyFileUpdateMonitor; import org.apache.http.client.utils.URIBuilder; public class DBLPFetcher implements SearchBasedParserFetcher { private static final String BASIC_SEARCH_URL = "https://dblp.org/search/publ/api"; private final ImportFormatPreferences importFormatPreferences; public DBLPFetcher(ImportFormatPreferences importFormatPreferences) { Objects.requireNonNull(importFormatPreferences); this.importFormatPreferences = importFormatPreferences; } @Override public URL getURLForQuery(String query) throws URISyntaxException, MalformedURLException, FetcherException { URIBuilder uriBuilder = new URIBuilder(BASIC_SEARCH_URL); uriBuilder.addParameter("q", query); uriBuilder.addParameter("h", String.valueOf(100)); // number of hits uriBuilder.addParameter("c", String.valueOf(0)); // no need for auto-completion uriBuilder.addParameter("f", String.valueOf(0)); // "from", index of first hit to download uriBuilder.addParameter("format", "bib1"); return uriBuilder.build().toURL(); } @Override public Parser getParser() { return new BibtexParser(importFormatPreferences, new DummyFileUpdateMonitor()); } @Override public void doPostCleanup(BibEntry entry) { DoiCleanup doiCleaner = new DoiCleanup(); FieldFormatterCleanup clearTimestampFormatter = new FieldFormatterCleanup(FieldName.TIMESTAMP, new ClearFormatter()); doiCleaner.cleanup(entry); clearTimestampFormatter.cleanup(entry); } @Override public String getName() { return "DBLP"; } @Override public HelpFile getHelpPage() { return HelpFile.FETCHER_DBLP; } }
package org.jboss.logmanager.formatters; import org.jboss.logmanager.ExtLogRecord; import java.util.logging.Level; import java.security.AccessController; import java.security.PrivilegedAction; import java.text.SimpleDateFormat; import java.util.Date; import static java.lang.Math.min; import static java.lang.Math.max; /** * Formatter utility methods. */ public final class Formatters { private Formatters() { } /** * Create a format step which simply emits the given string. * * @param string the string to emit * @return a format step */ public static FormatStep textFormatStep(final String string) { return new FormatStep() { public void render(final StringBuilder builder, final ExtLogRecord record) { builder.append(string); } public int estimateLength() { return string.length(); } }; } /** * Apply up to {@code count} trailing segments of the given string to the given {@code builder}. * * @param count the maximum number of segments to include * @param subject the subject string * @return the substring */ private static String applySegments(final int count, final String subject) { if (count == 0) { return subject; } int idx = subject.length() + 1; for (int i = 0; i < count; i ++) { idx = subject.lastIndexOf('.', idx - 1); if (idx == -1) { return subject; } } return subject.substring(idx + 1); } private static abstract class JustifyingFormatStep implements FormatStep { private final boolean leftJustify; private final int minimumWidth; private final int maximumWidth; protected JustifyingFormatStep(final boolean leftJustify, final int minimumWidth, final int maximumWidth) { if (maximumWidth != 0 && minimumWidth > maximumWidth) { throw new IllegalArgumentException("Specified minimum width may not be greater than the specified maximum width"); } if (maximumWidth < 0 || minimumWidth < 0) { throw new IllegalArgumentException("Minimum and maximum widths must not be less than zero"); } this.leftJustify = leftJustify; this.minimumWidth = minimumWidth; this.maximumWidth = maximumWidth == 0 ? Integer.MAX_VALUE : maximumWidth; } public void render(final StringBuilder builder, final ExtLogRecord record) { final String subject = getSubject(record); final int len = subject.length(); final int minimumWidth = this.minimumWidth; final int maximumWidth = this.maximumWidth; if (len > maximumWidth) { builder.append(subject.substring(len - maximumWidth)); } else if (len < minimumWidth) { if (leftJustify) { builder.append(subject); int spaces = minimumWidth - len; for (int i = 0; i < spaces; i ++) { builder.append(' '); } } else { // right justify int spaces = minimumWidth - len; for (int i = 0; i < spaces; i ++) { builder.append(' '); } builder.append(subject); } } else { builder.append(subject); } } public int estimateLength() { if (maximumWidth != 0) { return min(maximumWidth, minimumWidth * 3); } else { return max(32, minimumWidth); } } public abstract String getSubject(final ExtLogRecord record); } private static abstract class SegmentedFormatStep extends JustifyingFormatStep { private final int count; protected SegmentedFormatStep(final boolean leftJustify, final int minimumWidth, final int maximumWidth, final int count) { super(leftJustify, minimumWidth, maximumWidth); this.count = count; } public final String getSubject(final ExtLogRecord record) { return applySegments(count, getSegmentedSubject(record)); } public abstract String getSegmentedSubject(final ExtLogRecord record); } /** * Create a format step which emits the logger name with the given justification rules. * * @param leftJustify {@code true} to left justify, {@code false} to right justify * @param minimumWidth the minimum field width, or 0 for none * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @param count the maximum number of logger name segments to emit (counting from the right) * @return the format step */ public static FormatStep loggerNameFormatStep(final boolean leftJustify, final int minimumWidth, final int maximumWidth, final int count) { return new SegmentedFormatStep(leftJustify, minimumWidth, maximumWidth, count) { public String getSegmentedSubject(final ExtLogRecord record) { return record.getLoggerName(); } }; } /** * Create a format step which emits the source class name with the given justification rules (NOTE: call stack * introspection introduces a significant performance penalty). * * @param leftJustify {@code true} to left justify, {@code false} to right justify * @param minimumWidth the minimum field width, or 0 for none * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @param count the maximum number of class name segments to emit (counting from the right) * @return the format step */ public static FormatStep classNameFormatStep(final boolean leftJustify, final int minimumWidth, final int maximumWidth, final int count) { return new SegmentedFormatStep(leftJustify, minimumWidth, maximumWidth, count) { public String getSegmentedSubject(final ExtLogRecord record) { return record.getSourceClassName(); } }; } /** * Create a format step which emits the date of the log record with the given justificaiton rules. * * @param formatString the date format string * @param leftJustify {@code true} to left justify, {@code false} to right justify * @param minimumWidth the minimum field width, or 0 for none * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @return the format step */ public static FormatStep dateFormatStep(final String formatString, final boolean leftJustify, final int minimumWidth, final int maximumWidth) { final SimpleDateFormat dateFormatMaster = new SimpleDateFormat(formatString); return new JustifyingFormatStep(leftJustify, minimumWidth, maximumWidth) { public String getSubject(final ExtLogRecord record) { final SimpleDateFormat dateFormat = dateFormatMaster; synchronized (dateFormat) { return dateFormat.format(new Date(record.getMillis())); } } }; } /** * Create a format step which emits the source file name with the given justification rules (NOTE: call stack * introspection introduces a significant performance penalty). * * @param leftJustify {@code true} to left justify, {@code false} to right justify * @param minimumWidth the minimum field width, or 0 for none * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @return the format step */ public static FormatStep fileNameFormatStep(final boolean leftJustify, final int minimumWidth, final int maximumWidth) { return new JustifyingFormatStep(leftJustify, minimumWidth, maximumWidth) { public String getSubject(final ExtLogRecord record) { return record.getSourceFileName(); } }; } /** * Create a format step which emits the complete source location information with the given justification rules * (NOTE: call stack introspection introduces a significant performance penalty). * * @param leftJustify {@code true} to left justify, {@code false} to right justify * @param minimumWidth the minimum field width, or 0 for none * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @return the format step */ public static FormatStep locationInformationFormatStep(final boolean leftJustify, final int minimumWidth, final int maximumWidth) { return new JustifyingFormatStep(leftJustify, minimumWidth, maximumWidth) { public String getSubject(final ExtLogRecord record) { final String fileName = record.getSourceFileName(); final int lineNumber = record.getSourceLineNumber(); final String className = record.getSourceClassName(); final String methodName = record.getSourceMethodName(); final StringBuilder builder = new StringBuilder(fileName.length() + className.length() + methodName.length() + 16); builder.append(className).append('.').append(methodName); builder.append('(').append(fileName); if (lineNumber != -1) { builder.append(':').append(lineNumber); } builder.append(')'); return builder.toString(); } }; } /** * Create a format step which emits the source file line number with the given justification rules (NOTE: call stack * introspection introduces a significant performance penalty). * * @param leftJustify {@code true} to left justify, {@code false} to right justify * @param minimumWidth the minimum field width, or 0 for none * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @return the format step */ public static FormatStep lineNumberFormatStep(final boolean leftJustify, final int minimumWidth, final int maximumWidth) { return new JustifyingFormatStep(leftJustify, minimumWidth, maximumWidth) { public String getSubject(final ExtLogRecord record) { return Integer.toString(record.getSourceLineNumber()); } }; } /** * Create a format step which emits the formatted log message text with the given justification rules. * * @param leftJustify {@code true} to left justify, {@code false} to right justify * @param minimumWidth the minimum field width, or 0 for none * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @return the format step */ public static FormatStep messageFormatStep(final boolean leftJustify, final int minimumWidth, final int maximumWidth) { return new JustifyingFormatStep(leftJustify, minimumWidth, maximumWidth) { public String getSubject(final ExtLogRecord record) { return record.getFormattedMessage(); } }; } /** * Create a format step which emits the source method name with the given justification rules (NOTE: call stack * introspection introduces a significant performance penalty). * * @param leftJustify {@code true} to left justify, {@code false} to right justify * @param minimumWidth the minimum field width, or 0 for none * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @return the format step */ public static FormatStep methodNameFormatStep(final boolean leftJustify, final int minimumWidth, final int maximumWidth) { return new JustifyingFormatStep(leftJustify, minimumWidth, maximumWidth) { public String getSubject(final ExtLogRecord record) { return record.getSourceMethodName(); } }; } private static final String separatorString; static { separatorString = AccessController.doPrivileged(new PrivilegedAction<String>() { public String run() { return System.getProperty("line.separator"); } }); } /** * Create a format step which emits the platform line separator. * * @param leftJustify {@code true} to left justify, {@code false} to right justify * @param minimumWidth the minimum field width, or 0 for none * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @return the format step */ public static FormatStep lineSeparatorFormatStep(final boolean leftJustify, final int minimumWidth, final int maximumWidth) { return new JustifyingFormatStep(leftJustify, minimumWidth, maximumWidth) { public String getSubject(final ExtLogRecord record) { return separatorString; } }; } /** * Create a format step which emits the localized log level name. * * @param leftJustify {@code true} to left justify, {@code false} to right justify * @param minimumWidth the minimum field width, or 0 for none * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @return the format step */ public static FormatStep levelFormatStep(final boolean leftJustify, final int minimumWidth, final int maximumWidth) { return new JustifyingFormatStep(leftJustify, minimumWidth, maximumWidth) { public String getSubject(final ExtLogRecord record) { final Level level = record.getLevel(); return (level.getResourceBundleName() != null) ? level.getLocalizedName() : level.getName(); } }; } /** * Create a format step which emits the number of milliseconds since the given base time. * * @param baseTime the base time as milliseconds as per {@link System#currentTimeMillis()} * @param leftJustify {@code true} to left justify, {@code false} to right justify * @param minimumWidth the minimum field width, or 0 for none * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @return the format step */ public static FormatStep relativeTimeFormatStep(final long baseTime, final boolean leftJustify, final int minimumWidth, final int maximumWidth) { return new JustifyingFormatStep(leftJustify, minimumWidth, maximumWidth) { public String getSubject(final ExtLogRecord record) { return Long.toString(record.getMillis() - baseTime); } }; } /** * Create a format step which emits the name of the thread which originated the log record. * * @param leftJustify {@code true} to left justify, {@code false} to right justify * @param minimumWidth the minimum field width, or 0 for none * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @return the format step */ public static FormatStep threadNameFormatStep(final boolean leftJustify, final int minimumWidth, final int maximumWidth) { return new JustifyingFormatStep(leftJustify, minimumWidth, maximumWidth) { public String getSubject(final ExtLogRecord record) { return record.getThreadName(); } }; } /** * Create a format step which emits the NDC value of the log record. * * @param leftJustify {@code true} to left justify, {@code false} to right justify * @param minimumWidth the minimum field width, or 0 for none * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @return the format step */ public static FormatStep ndcFormatStep(final boolean leftJustify, final int minimumWidth, final int maximumWidth) { return new JustifyingFormatStep(leftJustify, minimumWidth, maximumWidth) { public String getSubject(final ExtLogRecord record) { final String value = record.getNdc(); return value == null ? "" : value; } }; } /** * Create a format step which emits the MDC value associated with the given key of the log record. * * @param leftJustify {@code true} to left justify, {@code false} to right justify * @param minimumWidth the minimum field width, or 0 for none * @param maximumWidth the maximum field width (must be greater than {@code minimumFieldWidth}), or 0 for none * @return the format step */ public static FormatStep mdcFormatStep(final String key, final boolean leftJustify, final int minimumWidth, final int maximumWidth) { return new JustifyingFormatStep(leftJustify, minimumWidth, maximumWidth) { public String getSubject(final ExtLogRecord record) { final String value = record.getMdc(key); return value == null ? "" : value; } }; } }
package org.jenkinsci.remoting.protocol; import javax.annotation.Nonnull; import java.io.IOException; import java.nio.ByteBuffer; import javax.annotation.CheckForNull; import org.jenkinsci.remoting.util.ByteBufferUtils; /** * A network {@link ProtocolStack} consists of a number of {@link ProtocolLayer}s. This interface represents the general * contract of all layers in the stack. * * @since 3.0 */ public interface ProtocolLayer { /** * A handy constant to use for no-op send/receive calls. */ ByteBuffer EMPTY_BUFFER = ByteBufferUtils.EMPTY_BUFFER; /** * Initializes the layer with its {@link ProtocolStack.Ptr}. All lower layers in the stack will be initialized * before a call to this method. All layers in a stack will be initialized before a call to {@link #start()}. * * @param ptr the position of this layer in the stack. * @throws IOException if something goes wrong. */ void init(@Nonnull ProtocolStack<?>.Ptr ptr) throws IOException; /** * Starts this layer. All layers in the stack will be initialized before a call to this method. All lower layers * in the stack will have been started before this layer is started. * * @throws IOException if something goes wrong. */ void start() throws IOException; /** * Interface to indicate that this layer receives data from lower layers. * * @since 3.0 */ interface Recv extends ProtocolLayer { /** * Callback on data being received from the lower layer. * * @param data the data received. Any data consumed from the {@link ByteBuffer} can be assumed as processed. * Any data not consumed from the {@link ByteBuffer} will be the responsibility of the caller * to resubmit in subsequent calls. * @throws IOException if there was an error during processing of the received data. */ void onRecv(@Nonnull ByteBuffer data) throws IOException; /** * Callback on the lower layer's source of data being closed. * * @param cause the cause of the lower layer being closed or {@code null}. * @throws IOException if there was an error during the processing of the close notification. */ void onRecvClosed(@CheckForNull IOException cause) throws IOException; /** * Tracks if this layer is accepting received data via {@link #onRecv(ByteBuffer)}. * Once this method returns {@code false} it must always return {@code false} and can be assumed to behave in * this way. * * @return {@code true} if accepting received data via {@link #onRecv(ByteBuffer)}. */ boolean isRecvOpen(); } /** * Interface to indicate that this layer sends data to lower layers. * * @since 3.0 */ interface Send extends ProtocolLayer { /** * Sends data to the lower layer. * * @param data the data to send. Any data consumed from the {@link ByteBuffer} can be assumed as processed. * Any data not consumed from the {@link ByteBuffer} will be the responsibility of the caller * to resubmit in subsequent calls. * @throws IOException if there was an error during processing of the data. */ void doSend(@Nonnull ByteBuffer data) throws IOException; /** * Notify the lower layer that it should close. Callers to this method are assumed to have already called * {@link Recv#onRecvClosed(IOException)} for any upper layers. * * @throws IOException if there was an error closing the lower layer. */ void doCloseSend() throws IOException; /** * Tracks if this layer is submitting data to be sent via {@link #doSend(ByteBuffer)}. * Once this method returns {@code false} it must always return {@code false} and can be assumed to behave in * this way. * * @return {@code true} if submitting data to be sent via {@link #doSend(ByteBuffer)}. */ boolean isSendOpen(); } }
package gov.nih.nci.calab.service.search; import gov.nih.nci.calab.db.DataAccessProxy; import gov.nih.nci.calab.db.IDataAccess; import gov.nih.nci.calab.domain.Sample; import gov.nih.nci.calab.dto.inventory.SampleBean; import gov.nih.nci.calab.dto.inventory.StorageLocation; import gov.nih.nci.calab.service.util.CalabComparators; import gov.nih.nci.calab.service.util.StringUtils; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import org.apache.log4j.Logger; /** * * @author pansu * */ /* CVS $Id: SearchSampleService.java,v 1.19 2006-08-01 13:23:17 pansu Exp $ */ public class SearchSampleService { private static Logger logger = Logger.getLogger(SearchSampleService.class); /** * Search database for sample container information based on sample ID * * @param sampleId * @param sampleType * @param sampleSource * @param sourceSampleId * @param dateAccessionedBegin * @param dateAccessionedEnd * @param sampleSubmitter * @param storageLocation * @return a list of SampleBean */ public List<SampleBean> searchSamplesBySampleName(String sampleName, String sampleType, String sampleSource, String sourceSampleId, Date dateAccessionedBegin, Date dateAccessionedEnd, String sampleSubmitter, StorageLocation storageLocation) throws Exception { List<SampleBean> samples = new ArrayList<SampleBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { List<Object> paramList = new ArrayList<Object>(); List<String> whereList = new ArrayList<String>(); String where = ""; String storageFrom = ""; if (sampleName.length() > 0) { where = "where "; if (sampleName.indexOf("*") != -1) { sampleName = sampleName.replace('*', '%'); whereList.add("sample.name like ?"); } else { whereList.add("sample.name=?"); } paramList.add(sampleName); } if (sampleType.length() > 0) { paramList.add(sampleType); where = "where "; whereList.add("sample.type=?"); } if (sampleSource.length() > 0) { paramList.add(sampleSource); where = "where "; whereList.add("sample.source.organizationName=?"); } if (sourceSampleId.length() > 0) { paramList.add(sourceSampleId); where = "where "; whereList.add("sample.sourceSampleId=?"); } if (dateAccessionedBegin != null) { paramList.add(dateAccessionedBegin); where = "where "; whereList.add("sample.createdDate>=?"); } if (dateAccessionedEnd != null) { paramList.add(dateAccessionedEnd); where = "where "; whereList.add("sample.createdDate<=?"); } if (sampleSubmitter.length() > 0) { paramList.add(sampleSubmitter); where = "where "; whereList.add("sample.createdBy=?"); } if (storageLocation.getRoom().length() > 0) { paramList.add(storageLocation.getRoom()); where = "where "; storageFrom = "join sample.sampleContainerCollection container join container.storageElementCollection storage "; whereList.add("storage.type='Room' and storage.location=?"); } if (storageLocation.getFreezer().length() > 0) { paramList.add(storageLocation.getFreezer()); where = "where "; storageFrom = "join sample.sampleContainerCollection container join container.storageElementCollection storage "; whereList.add("storage.type='Freezer' and storage.location=?"); } if (storageLocation.getFreezer().length() > 0) { paramList.add(storageLocation.getFreezer()); where = "where "; storageFrom = "join sample.sampleContainerCollection container join container.storageElementCollection storage "; whereList.add(" storage.type='Shelf' and storage.location=?"); } if (storageLocation.getBox().length() > 0) { paramList.add(storageLocation.getBox()); where = "where "; storageFrom = "join sample.sampleContainerCollection container join container.storageElementCollection storage "; whereList.add("storage.type='Box' and storage.location=?"); } String whereStr = StringUtils.join(whereList, " and "); String hqlString = "select sample from Sample sample " + storageFrom + where + whereStr; ida.open(); List<? extends Object> results = (List<? extends Object>) ida .searchByParam(hqlString, paramList); for (Object obj : new HashSet<Object>(results)) { Sample sample = (Sample) obj; samples.add(new SampleBean(sample)); } } catch (Exception e) { logger .error("Error in searching sample by the given parameters", e); throw new RuntimeException( "Error in searching sample by the given parameters"); } finally { ida.close(); } Collections.sort(samples, new CalabComparators.SampleBeanComparator()); return samples; } /** * Search database for sample container information based on other * parameters * * @param sampleType * @param sampleSource * @param sourceSampleId * @param dateAccessionedBegin * @param dateAccessionedEnd * @param sampleSubmitter * @param storageLocation * @return */ public List<SampleBean> searchSamples(String sampleType, String sampleSource, String sourceSampleId, Date dateAccessionedBegin, Date dateAccessionedEnd, String sampleSubmitter, StorageLocation storageLocation) throws Exception { return searchSamplesBySampleName("", sampleType, sampleSource, sourceSampleId, dateAccessionedBegin, dateAccessionedEnd, sampleSubmitter, storageLocation); } }
package org.msgpack.rpc.client.netty; import java.net.ConnectException; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.SimpleChannelHandler; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.msgpack.rpc.client.TCPSocket; @ChannelPipelineCoverage("all") public class RPCClientHandler extends SimpleChannelHandler { protected TCPSocket sock; public RPCClientHandler(TCPSocket sock) { super(); this.sock = sock; } @Override public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent ev) { try { sock.onConnected(); } catch (Exception e) { e.printStackTrace(); sock.onConnectFailed(); } } @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent ev) { try { sock.onMessageReceived(ev.getMessage()); } catch (Exception e) { e.printStackTrace(); sock.onFailed(); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent ev) { Throwable e = ev.getCause(); if (e instanceof ConnectException) sock.onConnectFailed(); else sock.onFailed(); } }
package com.heroku; import com.atlassian.bamboo.collections.ActionParametersMap; import com.atlassian.bamboo.task.AbstractTaskConfigurator; import com.atlassian.bamboo.task.TaskDefinition; import com.atlassian.bamboo.utils.error.ErrorCollection; import com.google.common.collect.ImmutableList; import com.opensymphony.xwork.TextProvider; import org.apache.commons.lang.StringUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; import java.util.Map; public class ArtifactDeploymentConfigurator extends AbstractTaskConfigurator { private TextProvider textProvider; private static final List<String> FIELDS_TO_COPY = ImmutableList.of("apiKey", "appName", "artifactPath"); @NotNull @Override public Map<String, String> generateTaskConfigMap(@NotNull final ActionParametersMap params, @Nullable final TaskDefinition previousTaskDefinition) { final Map<String, String> config = super.generateTaskConfigMap(params, previousTaskDefinition); taskConfiguratorHelper.populateTaskConfigMapWithActionParameters(config, params, FIELDS_TO_COPY); return config; } @Override public void populateContextForCreate(@NotNull final Map<String, Object> context) { super.populateContextForCreate(context); // context.put("say", "Hello, World!"); } @Override public void populateContextForEdit(@NotNull final Map<String, Object> context, @NotNull final TaskDefinition taskDefinition) { super.populateContextForEdit(context, taskDefinition); taskConfiguratorHelper.populateContextWithConfiguration(context, taskDefinition, FIELDS_TO_COPY); } @Override public void populateContextForView(@NotNull final Map<String, Object> context, @NotNull final TaskDefinition taskDefinition) { super.populateContextForView(context, taskDefinition); taskConfiguratorHelper.populateContextWithConfiguration(context, taskDefinition, FIELDS_TO_COPY); } @Override public void validate(@NotNull final ActionParametersMap params, @NotNull final ErrorCollection errorCollection) { super.validate(params, errorCollection); final String apiKey = params.getString("apiKey"); if (StringUtils.isEmpty(apiKey)) { errorCollection.addError("apiKey", textProvider.getText("com.heroku.say.error")); } //TODO: more requiredess } public void setTextProvider(final TextProvider textProvider) { this.textProvider = textProvider; } }
package gov.nih.nci.calab.ui.core; import gov.nih.nci.calab.dto.characterization.CharacterizationBean; import gov.nih.nci.calab.dto.characterization.CharacterizationSummaryBean; import gov.nih.nci.calab.dto.characterization.DatumBean; import gov.nih.nci.calab.dto.characterization.DerivedBioAssayDataBean; import gov.nih.nci.calab.dto.characterization.invitro.CytotoxicityBean; import gov.nih.nci.calab.dto.characterization.physical.MorphologyBean; import gov.nih.nci.calab.dto.characterization.physical.ShapeBean; import gov.nih.nci.calab.dto.characterization.physical.SolubilityBean; import gov.nih.nci.calab.dto.characterization.physical.SurfaceBean; import gov.nih.nci.calab.dto.common.LabFileBean; import gov.nih.nci.calab.dto.common.ProtocolFileBean; import gov.nih.nci.calab.dto.common.UserBean; import gov.nih.nci.calab.dto.particle.ParticleBean; import gov.nih.nci.calab.exception.CaNanoLabSecurityException; import gov.nih.nci.calab.exception.FileException; import gov.nih.nci.calab.exception.ParticleCharacterizationException; import gov.nih.nci.calab.service.common.FileService; import gov.nih.nci.calab.service.particle.NanoparticleCharacterizationService; import gov.nih.nci.calab.service.particle.NanoparticleService; import gov.nih.nci.calab.service.security.UserService; import gov.nih.nci.calab.service.util.CaNanoLabConstants; import gov.nih.nci.calab.service.util.PropertyReader; import gov.nih.nci.calab.service.util.StringUtils; import gov.nih.nci.calab.ui.particle.InitParticleSetup; import gov.nih.nci.calab.ui.protocol.InitProtocolSetup; import gov.nih.nci.calab.ui.security.InitSecuritySetup; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; 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.DynaValidatorForm; /** * This action serves as the base action for all characterization related action * classes. It includes common operations such as download, updateManufacturers. * * @author pansu */ /* * CVS $Id: BaseCharacterizationAction.java,v 1.73 2007/08/02 21:41:47 zengje * Exp $ */ public abstract class BaseCharacterizationAction extends AbstractDispatchAction { protected CharacterizationBean prepareCreate(HttpServletRequest request, DynaValidatorForm theForm) throws Exception { HttpSession session = request.getSession(); CharacterizationBean charBean = (CharacterizationBean) theForm .get("achar"); // validate that characterization file/derived data can't be empty for (DerivedBioAssayDataBean derivedDataFileBean : charBean .getDerivedBioAssayDataList()) { if (derivedDataFileBean.getType().length() == 0 && derivedDataFileBean.getCategories().length == 0 && derivedDataFileBean.getDisplayName().length() == 0 && derivedDataFileBean.getDatumList().size() == 0) { throw new ParticleCharacterizationException( "has an empty section for characterization file/derived data. Please remove it prior to saving."); } } for (DerivedBioAssayDataBean derivedDataFileBean : charBean .getDerivedBioAssayDataList()) { Map<String, Integer> uniqueDatumMap = new HashMap<String, Integer>(); for (DatumBean datumBean : derivedDataFileBean.getDatumList()) { // validate that neither name nor value can be empty if (datumBean.getName().length() == 0 || datumBean.getValue().length() == 0) { throw new ParticleCharacterizationException( "Derived data name and value can't be empty."); } if (datumBean.getStatisticsType().equalsIgnoreCase("boolean")) { if (!datumBean.getValue().equalsIgnoreCase("true") && !datumBean.getValue().equalsIgnoreCase("false") && !datumBean.getValue().equalsIgnoreCase("yes") && !datumBean.getValue().equalsIgnoreCase("no")) { throw new ParticleCharacterizationException( "The datum value for boolean type should be 'True'/'False' or 'Yes'/'No'."); } } else { if (!StringUtils.isDouble(datumBean.getValue()) && !StringUtils.isInteger(datumBean.getValue())) { throw new ParticleCharacterizationException( "The datum value should be a number."); } } // validate derived data has unique name, statistics type and // category String uniqueStr = datumBean.getName() + ":" + datumBean.getStatisticsType() + ":" + datumBean.getCategory(); if (uniqueDatumMap.get(uniqueStr) != null) { throw new ParticleCharacterizationException( "no two derived data can have the same name, statistics type and category."); } else { uniqueDatumMap.put(uniqueStr, 1); } } } // set createdBy and createdDate for the characterization UserBean user = (UserBean) session.getAttribute("user"); Date date = new Date(); charBean.setCreatedBy(user.getLoginName()); charBean.setCreatedDate(date); ParticleBean particle = (ParticleBean) theForm.get("particle"); charBean.setParticle(particle); return charBean; } protected ActionForward postCreate(HttpServletRequest request, DynaValidatorForm theForm, ActionMapping mapping) throws Exception { ParticleBean particle = (ParticleBean) theForm.get("particle"); CharacterizationBean charBean = (CharacterizationBean) theForm .get("achar"); // save new lookup up types in the database definition tables. NanoparticleCharacterizationService service = new NanoparticleCharacterizationService(); service.addNewCharacterizationDataDropdowns(charBean, charBean .getName()); request.getSession().setAttribute("newCharacterizationCreated", "true"); request.getSession().setAttribute("newCharacterizationSourceCreated", "true"); request.getSession().setAttribute("newInstrumentCreated", "true"); request.getSession().setAttribute("newCharacterizationFileTypeCreated", "true"); InitParticleSetup.getInstance().setSideParticleMenu(request, particle.getSampleId()); request.setAttribute("theParticle", particle); ActionMessages msgs = new ActionMessages(); ActionMessage msg = new ActionMessage("message.addCharacterization", charBean.getName()); msgs.add("message", msg); saveMessages(request, msgs); return mapping.findForward("success"); } protected CharacterizationBean[] prepareCopy(HttpServletRequest request, DynaValidatorForm theForm) throws Exception { CharacterizationBean charBean = (CharacterizationBean) theForm .get("achar"); ParticleBean particle = (ParticleBean) theForm.get("particle"); String[] otherParticles = (String[]) theForm.get("otherParticles"); Boolean copyData = (Boolean) theForm.get("copyData"); CharacterizationBean[] charBeans = new CharacterizationBean[otherParticles.length]; NanoparticleService service = new NanoparticleService(); int i = 0; for (String particleName : otherParticles) { CharacterizationBean newCharBean = charBean.copy(copyData .booleanValue()); // overwrite particle and particle type; newCharBean.getParticle().setSampleName(particleName); ParticleBean otherParticle = service.getParticleBy(particleName); newCharBean.getParticle().setSampleType( otherParticle.getSampleType()); // reset view title String timeStamp = StringUtils.convertDateToString(new Date(), "MMddyyHHmmssSSS"); String autoTitle = CaNanoLabConstants.AUTO_COPY_CHARACTERIZATION_VIEW_TITLE_PREFIX + timeStamp; newCharBean.setViewTitle(autoTitle); List<DerivedBioAssayDataBean> dataList = newCharBean .getDerivedBioAssayDataList(); // replace particleName in path and uri with new particleName for (DerivedBioAssayDataBean derivedBioAssayData : dataList) { String origUri = derivedBioAssayData.getUri(); if (origUri != null) derivedBioAssayData.setUri(origUri.replace(particle .getSampleName(), particleName)); } charBeans[i] = newCharBean; i++; } return charBeans; } /** * clear session data from the input form * * @param session * @param theForm * @param mapping * @throws Exception */ protected void clearMap(HttpSession session, DynaValidatorForm theForm) throws Exception { // reset achar and otherParticles theForm.set("otherParticles", new String[0]); theForm.set("copyData", false); theForm.set("achar", new CharacterizationBean()); theForm.set("morphology", new MorphologyBean()); theForm.set("shape", new ShapeBean()); theForm.set("surface", new SurfaceBean()); theForm.set("solubility", new SolubilityBean()); theForm.set("cytotoxicity", new CytotoxicityBean()); cleanSessionAttributes(session); } /** * Prepopulate data for the input form * * @param request * @param theForm * @throws Exception */ protected void initSetup(HttpServletRequest request, DynaValidatorForm theForm) throws Exception { HttpSession session = request.getSession(); clearMap(session, theForm); UserBean user = (UserBean) request.getSession().getAttribute("user"); InitParticleSetup.getInstance() .setAllCharacterizationDropdowns(session); // set up particle String particleId = request.getParameter("particleId"); if (particleId != null) { NanoparticleService particleService = new NanoparticleService(); ParticleBean particle = particleService.getParticleInfo(particleId, user); theForm.set("particle", particle); request.setAttribute("theParticle", particle); // set up other particles from the same source SortedSet<String> allOtherParticleNames = particleService .getOtherParticles(particle.getSampleSource(), particle .getSampleName(), user); session .setAttribute("allOtherParticleNames", allOtherParticleNames); InitParticleSetup.getInstance().setSideParticleMenu(request, particleId); } else { throw new ParticleCharacterizationException( "Particle ID is required."); } InitSessionSetup.getInstance().setApplicationOwner(session); InitParticleSetup.getInstance().setAllInstruments(session); InitParticleSetup.getInstance().setAllDerivedDataFileTypes(session); InitParticleSetup.getInstance().setAllPhysicalDropdowns(session); InitParticleSetup.getInstance().setAllInvitroDropdowns(session); // set characterization String submitType = (String) request.getParameter("submitType"); String characterizationId = request.getParameter("characterizationId"); if (characterizationId != null) { NanoparticleCharacterizationService charService = new NanoparticleCharacterizationService(); CharacterizationBean charBean = charService .getCharacterizationBy(characterizationId); if (charBean == null) { throw new ParticleCharacterizationException( "This characterization no longer exists in the database. Please log in again to refresh."); } theForm.set("achar", charBean); } CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); if (achar != null && submitType != null) { achar.setName(submitType); InitParticleSetup.getInstance() .setAllCharacterizationMeasureUnitsTypes(session, submitType); InitParticleSetup.getInstance().setDerivedDatumNames(session, achar.getName()); InitProtocolSetup.getInstance().setProtocolFilesByCharName(session, achar.getName()); UserService userService = new UserService( CaNanoLabConstants.CSM_APP_NAME); // set up characterization files visibility, and whether file is an // image for (DerivedBioAssayDataBean fileBean : achar .getDerivedBioAssayDataList()) { boolean accessStatus = userService.checkReadPermission(user, fileBean.getId()); if (accessStatus) { List<String> accessibleGroups = userService .getAccessibleGroups(fileBean.getId(), CaNanoLabConstants.CSM_READ_ROLE); String[] visibilityGroups = accessibleGroups .toArray(new String[0]); fileBean.setVisibilityGroups(visibilityGroups); fileBean.setHidden(false); } else { fileBean.setHidden(true); } boolean imageStatus = false; if (fileBean.getName() != null) { imageStatus = StringUtils.isImgFileExt(fileBean.getName()); fileBean.setImage(imageStatus); } } // set up protocol file visibility ProtocolFileBean protocolFileBean = achar.getProtocolFileBean(); if (protocolFileBean != null) { boolean status = false; if (protocolFileBean.getId() != null) { status = userService.checkReadPermission(user, protocolFileBean.getId()); } if (status) { protocolFileBean.setHidden(false); } else { protocolFileBean.setHidden(true); } } } } /** * Clean the session attribture * * @param sessioin * @throws Exception */ protected void cleanSessionAttributes(HttpSession session) throws Exception { for (Enumeration e = session.getAttributeNames(); e.hasMoreElements();) { String element = (String) e.nextElement(); if (element.startsWith(CaNanoLabConstants.CHARACTERIZATION_FILE)) { session.removeAttribute(element); } } } /** * Set up the input form for adding new characterization * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward setup(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; initSetup(request, theForm); return mapping.getInputForward(); } public ActionForward input(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; // update editable dropdowns CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); ShapeBean shape = (ShapeBean) theForm.get("shape"); MorphologyBean morphology = (MorphologyBean) theForm.get("morphology"); CytotoxicityBean cyto = (CytotoxicityBean) theForm.get("cytotoxicity"); SolubilityBean solubility = (SolubilityBean) theForm.get("solubility"); HttpSession session = request.getSession(); updateAllCharEditables(session, achar); updateShapeEditable(session, shape); updateMorphologyEditable(session, morphology); updateCytotoxicityEditable(session, cyto); updateSolubilityEditable(session, solubility); // updateSurfaceEditable(session, surface); return mapping.findForward("setup"); } /** * Set up the form for updating existing characterization * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward setupUpdate(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; initSetup(request, theForm); CharacterizationBean charBean = (CharacterizationBean) theForm .get("achar"); // set characterizations with additional information if (charBean instanceof ShapeBean) { theForm.set("shape", charBean); } else if (charBean instanceof MorphologyBean) { theForm.set("morphology", charBean); } else if (charBean instanceof SolubilityBean) { theForm.set("solubility", charBean); } else if (charBean instanceof SurfaceBean) { theForm.set("surface", charBean); } else if (charBean instanceof SolubilityBean) { theForm.set("solubility", charBean); } else if (charBean instanceof CytotoxicityBean) { theForm.set("cytotoxicity", charBean); } return mapping.findForward("setup"); } public ActionForward detailView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; initSetup(request, theForm); String particleId = request.getParameter("particleId"); String characterizationId = request.getParameter("characterizationId"); String submitType = request.getParameter("submitType"); CharacterizationBean charBean = (CharacterizationBean) theForm .get("achar"); String printLinkURL = "/caNanoLab/" + charBean.getActionName() + ".do?page=0&dispatch=printDetailView&particleId=" + particleId + "&characterizationId=" + characterizationId + "&submitType=" + submitType; request.setAttribute("printLinkURL", printLinkURL); return mapping.findForward("detailView"); } public ActionForward exportDetail(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; initSetup(request, theForm); CharacterizationBean charBean = (CharacterizationBean) theForm.get("achar"); NanoparticleCharacterizationService service = new NanoparticleCharacterizationService(); //response.setContentType("application/vnd.ms-execel"); response.setContentType("application/octet-stream"); response.setHeader("cache-control", "Private"); response.setHeader("Content-disposition", "attachment;filename=" + charBean.getActionName() + "_" + charBean.getViewTitle() + ".xls"); UserBean user = (UserBean) request.getSession().getAttribute("user"); java.io.OutputStream out = response.getOutputStream(); service.exportDetailService(theForm, out, user); return mapping.findForward("detailView"); } public ActionForward exportSummary(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; initSetup(request, theForm); CharacterizationBean charBean = (CharacterizationBean) theForm.get("achar"); NanoparticleCharacterizationService service = new NanoparticleCharacterizationService(); //response.setContentType("application/vnd.ms-execel"); response.setContentType("application/octet-stream"); response.setHeader("cache-control", "Private"); response.setHeader("Content-disposition", "attachment;filename=" + charBean.getActionName() + ".xls"); UserBean user = (UserBean) request.getSession().getAttribute("user"); java.io.OutputStream out = response.getOutputStream(); String submitType = request.getParameter("submitType"); ParticleBean particle = (ParticleBean) theForm.get("particle"); List<CharacterizationSummaryBean> summaryBeans = service .getParticleCharacterizationSummaryByName(submitType, particle.getSampleId()); SortedSet<String> datumLabels = service.setDataLabelsAndFileVisibility(user, summaryBeans); service.exportSummaryService(datumLabels, summaryBeans, submitType, theForm, out, user); return mapping.findForward("summaryView"); } public ActionForward printDetailView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; initSetup(request, theForm); return mapping.findForward("detailPrintView"); } public ActionForward summaryView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; initSetup(request, theForm); String submitType = request.getParameter("submitType"); ParticleBean particle = (ParticleBean) theForm.get("particle"); NanoparticleCharacterizationService service = new NanoparticleCharacterizationService(); List<CharacterizationSummaryBean> charSummaryBeans = service .getParticleCharacterizationSummaryByName(submitType, particle .getSampleId()); if (charSummaryBeans == null) { throw new Exception( "There are no such characterizations in the database."); } UserBean user = (UserBean) request.getSession().getAttribute("user"); // set data labels and file visibility, and whether file is an image SortedSet<String> datumLabels = service.setDataLabelsAndFileVisibility(user, charSummaryBeans); request.setAttribute("summaryViewBeans", charSummaryBeans); request.setAttribute("summaryViewCharBeans", charSummaryBeans); request.setAttribute("datumLabels", datumLabels); return mapping.findForward("summaryView"); } /** * Load file action for characterization file loading. * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward loadFile(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; ParticleBean particle = (ParticleBean) theForm.get("particle"); request.setAttribute("loadFileForward", mapping.findForward("setup") .getPath()); CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); int fileNum = Integer.parseInt(request.getParameter("fileNumber")); DerivedBioAssayDataBean derivedBioAssayDataBean = achar .getDerivedBioAssayDataList().get(fileNum); derivedBioAssayDataBean.setParticleName(particle.getSampleName()); derivedBioAssayDataBean.setCharacterizationName(achar.getName()); request.setAttribute("file", derivedBioAssayDataBean); return mapping.findForward("loadFile"); } /** * Download action to handle characterization file download and viewing * * @param * @return */ public ActionForward download(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String fileId = request.getParameter("fileId"); UserBean user = (UserBean) request.getSession().getAttribute("user"); FileService service = new FileService(); LabFileBean fileBean = service.getFile(fileId, user); String fileRoot = PropertyReader.getProperty( CaNanoLabConstants.FILEUPLOAD_PROPERTY, "fileRepositoryDir"); File dFile = new File(fileRoot + File.separator + fileBean.getUri()); if (dFile.exists()) { response.setContentType("application/octet-stream"); response.setHeader("Content-disposition", "attachment;filename=" + fileBean.getName()); response.setHeader("cache-control", "Private"); java.io.InputStream in = new FileInputStream(dFile); java.io.OutputStream out = response.getOutputStream(); byte[] bytes = new byte[32768]; int numRead = 0; while ((numRead = in.read(bytes)) > 0) { out.write(bytes, 0, numRead); } out.close(); } else { throw new FileException( "File to download doesn't exist on the server"); } return null; } public ActionForward addFile(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); List<DerivedBioAssayDataBean> origTables = achar .getDerivedBioAssayDataList(); int origNum = (origTables == null) ? 0 : origTables.size(); List<DerivedBioAssayDataBean> tables = new ArrayList<DerivedBioAssayDataBean>(); for (int i = 0; i < origNum; i++) { tables.add(origTables.get(i)); } // add a new one tables.add(new DerivedBioAssayDataBean()); achar.setDerivedBioAssayDataList(tables); ParticleBean particle = (ParticleBean) theForm.get("particle"); InitParticleSetup.getInstance().setSideParticleMenu(request, particle.getSampleId()); return input(mapping, form, request, response); } public ActionForward removeFile(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String fileIndexStr = (String) request.getParameter("compInd"); int fileInd = Integer.parseInt(fileIndexStr); DynaValidatorForm theForm = (DynaValidatorForm) form; CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); List<DerivedBioAssayDataBean> origTables = achar .getDerivedBioAssayDataList(); int origNum = (origTables == null) ? 0 : origTables.size(); List<DerivedBioAssayDataBean> tables = new ArrayList<DerivedBioAssayDataBean>(); for (int i = 0; i < origNum; i++) { tables.add(origTables.get(i)); } // remove the one at the index if (origNum > 0) { tables.remove(fileInd); } achar.setDerivedBioAssayDataList(tables); ParticleBean particle = (ParticleBean) theForm.get("particle"); InitParticleSetup.getInstance().setSideParticleMenu(request, particle.getSampleId()); return input(mapping, form, request, response); } public ActionForward addData(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); String fileIndexStr = (String) request.getParameter("compInd"); int fileInd = Integer.parseInt(fileIndexStr); DerivedBioAssayDataBean derivedBioAssayDataBean = (DerivedBioAssayDataBean) achar .getDerivedBioAssayDataList().get(fileInd); List<DatumBean> origDataList = derivedBioAssayDataBean.getDatumList(); int origNum = (origDataList == null) ? 0 : origDataList.size(); List<DatumBean> dataList = new ArrayList<DatumBean>(); for (int i = 0; i < origNum; i++) { DatumBean dataPoint = (DatumBean) origDataList.get(i); dataList.add(dataPoint); } dataList.add(new DatumBean()); derivedBioAssayDataBean.setDatumList(dataList); ParticleBean particle = (ParticleBean) theForm.get("particle"); InitParticleSetup.getInstance().setSideParticleMenu(request, particle.getSampleId()); return input(mapping, form, request, response); } public ActionForward removeData(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); String fileIndexStr = (String) request.getParameter("compInd"); int fileInd = Integer.parseInt(fileIndexStr); String dataIndexStr = (String) request.getParameter("childCompInd"); int dataInd = Integer.parseInt(dataIndexStr); DerivedBioAssayDataBean derivedBioAssayDataBean = (DerivedBioAssayDataBean) achar .getDerivedBioAssayDataList().get(fileInd); List<DatumBean> origDataList = derivedBioAssayDataBean.getDatumList(); int origNum = (origDataList == null) ? 0 : origDataList.size(); List<DatumBean> dataList = new ArrayList<DatumBean>(); for (int i = 0; i < origNum; i++) { DatumBean dataPoint = (DatumBean) origDataList.get(i); dataList.add(dataPoint); } if (origNum > 0) dataList.remove(dataInd); derivedBioAssayDataBean.setDatumList(dataList); ParticleBean particle = (ParticleBean) theForm.get("particle"); InitParticleSetup.getInstance().setSideParticleMenu(request, particle.getSampleId()); return input(mapping, form, request, response); // return mapping.getInputForward(); this gives an // IndexOutOfBoundException in the jsp page } /** * Pepopulate data for the form * * @param request * @param theForm * @throws Exception */ public ActionForward deleteConfirmed(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; initSetup(request, theForm); ParticleBean particle = (ParticleBean) theForm.get("particle"); String charId = request.getParameter("characterizationId"); NanoparticleCharacterizationService service = new NanoparticleCharacterizationService(); service.deleteCharacterizations(new String[] { charId }); // signal the session that characterization has been changed request.getSession().setAttribute("newCharacterizationCreated", "true"); InitParticleSetup.getInstance().setSideParticleMenu(request, particle.getSampleId()); ActionMessages msgs = new ActionMessages(); ActionMessage msg = new ActionMessage("message.delete.characterization"); msgs.add("message", msg); saveMessages(request, msgs); return mapping.findForward("success"); } // add edited option to all editable dropdowns private void updateAllCharEditables(HttpSession session, CharacterizationBean achar) throws Exception { InitSessionSetup.getInstance().updateEditableDropdown(session, achar.getCharacterizationSource(), "characterizationSources"); InitSessionSetup.getInstance().updateEditableDropdown(session, achar.getInstrumentConfigBean().getInstrumentBean().getType(), "allInstrumentTypes"); InitSessionSetup.getInstance().updateEditableDropdown( session, achar.getInstrumentConfigBean().getInstrumentBean() .getManufacturer(), "allManufacturers"); for (DerivedBioAssayDataBean derivedBioAssayDataBean : achar .getDerivedBioAssayDataList()) { InitSessionSetup.getInstance().updateEditableDropdown(session, derivedBioAssayDataBean.getType(), "allDerivedDataFileTypes"); if (derivedBioAssayDataBean != null) { for (String category : derivedBioAssayDataBean.getCategories()) { InitSessionSetup.getInstance().updateEditableDropdown( session, category, "derivedDataCategories"); } for (DatumBean datum : derivedBioAssayDataBean.getDatumList()) { InitSessionSetup.getInstance().updateEditableDropdown( session, datum.getName(), "datumNames"); InitSessionSetup.getInstance().updateEditableDropdown( session, datum.getStatisticsType(), "charMeasureTypes"); InitSessionSetup.getInstance().updateEditableDropdown( session, datum.getUnit(), "charMeasureUnits"); } } } } // add edited option to all editable dropdowns private void updateShapeEditable(HttpSession session, ShapeBean shape) throws Exception { InitSessionSetup.getInstance().updateEditableDropdown(session, shape.getType(), "allShapeTypes"); } private void updateMorphologyEditable(HttpSession session, MorphologyBean morphology) throws Exception { InitSessionSetup.getInstance().updateEditableDropdown(session, morphology.getType(), "allMorphologyTypes"); } private void updateCytotoxicityEditable(HttpSession session, CytotoxicityBean cyto) throws Exception { InitSessionSetup.getInstance().updateEditableDropdown(session, cyto.getCellLine(), "allCellLines"); } private void updateSolubilityEditable(HttpSession session, SolubilityBean solubility) throws Exception { InitSessionSetup.getInstance().updateEditableDropdown(session, solubility.getSolvent(), "allSolventTypes"); } // private void updateSurfaceEditable(HttpSession session, // SurfaceBean surface) throws Exception { public boolean loginRequired() { return true; } public boolean canUserExecute(UserBean user) throws CaNanoLabSecurityException { return InitSecuritySetup.getInstance().userHasCreatePrivilege(user, CaNanoLabConstants.CSM_PG_PARTICLE); } }
package cx2x.xcodeml.xelement; import cx2x.xcodeml.helper.XelementHelper; import org.w3c.dom.Element; /** * The XmoduleDefinition represents the FmoduleDefinition (5.7) element in XcodeML * intermediate representation. * * Elements: (symbols?, declarations?, FcontainsStatement?) * - Optional: * - symbols (XsymbolTable) * - declarations (XdeclTable) * - FcontainsStatement (XcontainsStatement) TODO read + getter * * Attributes: * - Required: name (text) * * Can have lineno and file attributes * * @author clementval */ public class XmoduleDefinition extends XenhancedElement implements Xclonable<XmoduleDefinition> { private final String _name; private final XsymbolTable _symbols; private final XdeclTable _declarations; /** * Xelement standard ctor. Pass the base element to the base class and read * inner information (elements and attributes). * @param baseElement The root element of the Xelement */ public XmoduleDefinition(Element baseElement){ super(baseElement); _name = XelementHelper.getAttributeValue(this, XelementName.ATTR_NAME); _symbols = XelementHelper.findSymbols(this, false); _declarations = XelementHelper.findDeclarations(this, false); } /** * Get module name. * @return Module name. */ public String getName(){ return _name; } /** * Get the module's symbols table. * @return A XsymbolTable object containing the module's symbols. */ public XsymbolTable getSymbolTable(){ return _symbols; } /** * Get the module's declarations table. * @return A XdeclTable object containing the module's declarations. */ public XdeclTable getDeclarationTable(){ return _declarations; } @Override public XmoduleDefinition cloneObject() { Element clone = (Element)cloneNode(); return new XmoduleDefinition(clone); } }
package org.wiztools.restclient.util; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.file.Files; import java.security.KeyFactory; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.security.interfaces.RSAPrivateKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import javax.xml.bind.DatatypeConverter; import org.wiztools.restclient.bean.KeyStoreType; /** * * @author subhash */ public final class SSLUtil { private SSLUtil() {} public static final String PEM_PWD = "changeit"; public static KeyStore getKeyStore(File file, KeyStoreType type, char[] password) throws KeyStoreException, IOException, InvalidKeySpecException, NoSuchAlgorithmException, CertificateException { if(type == KeyStoreType.PEM) { return getPemKeyStore(file); } // Other KeyStore types: KeyStore store = KeyStore.getInstance(type.name()); if(file != null) { try(FileInputStream instream = new FileInputStream(file)) { store.load(instream, password); } } return store; } private static KeyStore getPemKeyStore(File file) throws KeyStoreException, IOException, InvalidKeySpecException, NoSuchAlgorithmException, CertificateException { KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType()); store.load(null); if(file != null) { byte[] certAndKey = Files.readAllBytes(file.toPath()); byte[] certBytes = parseDERFromPEM(certAndKey, " byte[] keyBytes = parseDERFromPEM(certAndKey, " if(certBytes == null) { throw new CertificateException( String.format("PEM (%s) has NO certificates!", file.getName())); } X509Certificate cert = generateCertificateFromDER(certBytes); String alias = cert.getSubjectX500Principal().getName(); store.setCertificateEntry(alias, cert); if(keyBytes != null) { RSAPrivateKey key = generatePrivateKeyFromDER(keyBytes); store.setKeyEntry("key-alias", key, PEM_PWD.toCharArray(), new Certificate[] {cert}); } } return store; } protected static byte[] parseDERFromPEM(byte[] pem, String beginDelimiter, String endDelimiter) { String data = new String(pem); String[] tokens = data.split(beginDelimiter); if(tokens.length < 2) { // no results found! return null; } tokens = tokens[1].split(endDelimiter); if(tokens.length < 2) { // no results found! return null; } return DatatypeConverter.parseBase64Binary(tokens[0]); } protected static RSAPrivateKey generatePrivateKeyFromDER(byte[] keyBytes) throws InvalidKeySpecException, NoSuchAlgorithmException { PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory factory = KeyFactory.getInstance("RSA"); return (RSAPrivateKey)factory.generatePrivate(spec); } protected static X509Certificate generateCertificateFromDER(byte[] certBytes) throws CertificateException { CertificateFactory factory = CertificateFactory.getInstance("X.509"); return (X509Certificate)factory.generateCertificate(new ByteArrayInputStream(certBytes)); } }
package javasearch; import org.apache.commons.io.LineIterator; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.Set; import java.util.stream.Collectors; public class Searcher { private SearchSettings settings; private List<SearchResult> results; private FileTypes fileTypes; private Set<SearchFile> searchFileSet; private Map<String, Long> timers; private long totalElapsedTime; public Searcher(final SearchSettings settings) { this.settings = settings; this.results = new ArrayList<>(); this.fileTypes = new FileTypes(); this.searchFileSet = new HashSet<>(); this.timers = new HashMap<>(); this.totalElapsedTime = 0L; } private void log(final String message) { System.out.println(message); } public final void validateSettings() throws SearchException { if (null == settings.getStartPath() || settings.getStartPath().equals("")) { throw new SearchException("Startpath not defined"); } File startPathFile = new File(settings.getStartPath()); if (!startPathFile.exists()) { throw new SearchException("Startpath not found"); } if (settings.getSearchPatterns().isEmpty()) { throw new SearchException("No search patterns defined"); } } private boolean anyMatchesAnyPattern(final List<String> sList, final Set<Pattern> patternSet) { return sList.stream().anyMatch(s -> matchesAnyPattern(s, patternSet)); } private boolean matchesAnyPattern(final String s, final Set<Pattern> patternSet) { return null != s && patternSet.stream().anyMatch(p -> p.matcher(s).find()); } public final boolean isSearchDir(final File d) { List<String> pathElems = FileUtil.splitPath(d.toString()); if (settings.getExcludeHidden() && pathElems.stream().anyMatch(FileUtil::isHidden)) { return false; } return (settings.getInDirPatterns().isEmpty() || anyMatchesAnyPattern(pathElems, settings.getInDirPatterns())) && (settings.getOutDirPatterns().isEmpty() || !anyMatchesAnyPattern(pathElems, settings.getOutDirPatterns())); } public final List<File> getSearchDirs(final File startPath) { List<File> searchDirs = new ArrayList<>(); if (settings.getDebug()) { log(String.format("Getting files to search under %s", startPath.getPath())); } searchDirs.add(startPath); if (settings.getRecursive()) { searchDirs.addAll(recGetSearchDirs(startPath)); } return searchDirs; } private List<File> getSubDirs(final File dir) { List<File> subDirs = new ArrayList<>(); File[] dirFiles = dir.listFiles(); if (dirFiles != null) { for (File f : dirFiles) { if (f.isDirectory()) { subDirs.add(f); } } } return subDirs; } private List<File> recGetSearchDirs(final File dir) { List<File> subDirs = getSubDirs(dir); List<File> searchDirs = subDirs.stream().filter(this::isSearchDir) .collect(Collectors.toList()); for (File d : subDirs) { searchDirs.addAll(recGetSearchDirs(d)); } return searchDirs; } public final boolean isSearchFile(final File f) { String ext = FileUtil.getExtension(f); return (settings.getInExtensions().isEmpty() || settings.getInExtensions().contains(ext)) && (settings.getOutExtensions().isEmpty() || !settings.getOutExtensions().contains(ext)) && (settings.getInFilePatterns().isEmpty() || matchesAnyPattern(f.getName(), settings.getInFilePatterns())) && (settings.getOutFilePatterns().isEmpty() || !matchesAnyPattern(f.getName(), settings.getOutFilePatterns())); } public final boolean isArchiveSearchFile(final File f) { String ext = FileUtil.getExtension(f); return (settings.getInArchiveExtensions().isEmpty() || settings.getInArchiveExtensions().contains(ext)) && (settings.getOutArchiveExtensions().isEmpty() || !settings.getOutArchiveExtensions().contains(ext)) && (settings.getInArchiveFilePatterns().isEmpty() || matchesAnyPattern(f.getName(), settings.getInArchiveFilePatterns())) && (settings.getOutArchiveFilePatterns().isEmpty() || !matchesAnyPattern(f.getName(), settings.getOutArchiveFilePatterns())); } public final boolean filterFile(final File f) { if (FileUtil.isHidden(f) && settings.getExcludeHidden()) { return false; } if (fileTypes.getFileType(f) == FileType.ARCHIVE) { return settings.getSearchArchives() && isArchiveSearchFile(f); } return !settings.getArchivesOnly() && isSearchFile(f); } private List<SearchFile> getSearchFilesForDir(final File dir) { if (settings.getDebug()) { log(String.format("Getting files to search under %s", dir)); } List<SearchFile> searchFiles = new ArrayList<>(); File[] currentFiles = dir.listFiles(); if (currentFiles != null) { for (File f : currentFiles) { if (f.isFile()) { FileType fileType = fileTypes.getFileType(f); if (filterFile(f)) { searchFiles.add(new SearchFile(f.getParent(), f.getName(), fileType)); } } } } return searchFiles; } public final List<SearchFile> getSearchFiles(final List<File> searchDirs) { List<SearchFile> searchFiles = new ArrayList<>(); for (File d : searchDirs) { searchFiles.addAll(getSearchFilesForDir(d)); } return searchFiles; } private void addTimer(final String name, final String action) { timers.put(name + ":" + action, System.currentTimeMillis()); } private void startTimer(final String name) { addTimer(name, "start"); } private void stopTimer(final String name) { addTimer(name, "stop"); totalElapsedTime += getElapsed(name); } public final long getElapsed(final String name) { long startTime = this.timers.get(name + ":start"); long stopTime = this.timers.get(name + ":stop"); return stopTime - startTime; } public final void printElapsed(final String name) { log(String.format("Elapsed time for \"%s\": %d ms", name, getElapsed(name))); } public final void printTotalElapsed() { log(String.format("Total elapsed time: %d ms", totalElapsedTime)); } public final void search() throws SearchException { // figure out if startPath is a directory or a file and search accordingly File startPathFile = new File(settings.getStartPath()); if (startPathFile.isDirectory()) { if (isSearchDir(startPathFile)) { searchPath(startPathFile); } else { throw new SearchException("Startpath does not match search settings"); } } else if (startPathFile.isFile()) { FileType fileType = fileTypes.getFileType(startPathFile); if (filterFile(startPathFile)) { File d = startPathFile.getParentFile(); if (null == d) { d = new File("."); } searchFile(new SearchFile(d.getPath(), startPathFile.getName(), fileType)); } else { throw new SearchException("Startpath does not match search settings"); } } else { throw new SearchException("Startpath is not a searchable file type"); } if (settings.getVerbose()) { log("\nFile search complete.\n"); } } public final void searchPath(final File filePath) { // get the search directories if (settings.getDoTiming()) { startTimer("getSearchDirs"); } List<File> searchDirs = getSearchDirs(filePath); if (settings.getDoTiming()) { stopTimer("getSearchDirs"); if (settings.getPrintResults()) { printElapsed("getSearchDirs"); } } if (settings.getVerbose()) { log(String.format("\nDirectories to be searched (%d):", searchDirs.size())); for (File d : searchDirs) { System.out.println(d.getPath()); } log(""); } // get the search files in the search directories if (settings.getDoTiming()) { startTimer("getSearchFiles"); } List<SearchFile> searchFiles = getSearchFiles(searchDirs); if (settings.getDoTiming()) { stopTimer("getSearchFiles"); if (settings.getPrintResults()) { printElapsed("getSearchFiles"); } } if (settings.getVerbose()) { log(String.format("\nFiles to be searched (%d):", searchFiles.size())); for (SearchFile sf : searchFiles) { log(sf.toString()); } log(""); } // search the files if (settings.getDoTiming()) { startTimer("searchFiles"); } searchFiles.forEach(this::searchFile); if (settings.getDoTiming()) { stopTimer("searchFiles"); if (settings.getPrintResults()) { printElapsed("searchFiles"); printTotalElapsed(); } } } public final void searchFile(final SearchFile sf) { FileType fileType = sf.getFileType(); if (fileType == FileType.TEXT) { searchTextFile(sf); } else if (fileType == FileType.BINARY) { searchBinaryFile(sf); } } public final void searchTextFile(final SearchFile sf) { if (settings.getVerbose()) { log(String.format("Searching text file %s", sf.toString())); } if (settings.getMultiLineSearch()) { searchTextFileContents(sf); } else { searchTextFileLines(sf); } } public final void searchTextFileContents(final SearchFile sf) { try { String contents = FileUtil.getFileContents(sf.toFile()); List<SearchResult> results = searchMultiLineString(contents); for (SearchResult r : results) { r.setSearchFile(sf); addSearchResult(r); } } catch (NoSuchElementException e) { log(e.toString() + ": " + sf.getPath()); } catch (IllegalStateException | IOException e) { log(e.toString()); } } private List<Number> getNewLineIndices(final String s) { List<Number> newlineIndices = new ArrayList<>(); for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '\n') { newlineIndices.add(i); } } return newlineIndices; } private List<Number> getStartLineIndicesFromNewLineIndices(final List<Number> newLineIndices) { List<Number> startLineIndices = new ArrayList<>(); startLineIndices.add(0); startLineIndices.addAll(newLineIndices.stream() .map(i -> i.longValue() + 1).collect(Collectors.toList())); return startLineIndices; } private List<Number> getEndLineIndicesFromNewLineIndices(final String s, final List<Number> newLineIndices) { List<Number> endLineIndices = new ArrayList<>(newLineIndices); endLineIndices.add(s.length() - 1); return endLineIndices; } public final List<SearchResult> searchMultiLineString(final String s) { List<SearchResult> results = new ArrayList<>(); for (Pattern p : settings.getSearchPatterns()) { for (SearchResult r : searchMultiLineStringForPattern(s, p)) { results.add(r); } } return results; } private List<String> getLinesFromMultiLineString(final String s, final List<Number> startIndices, final List<Number> endIndices) { List<String> lines = new ArrayList<>(); for (int i = 0; i < startIndices.size(); i++) { lines.add(s.substring(startIndices.get(i).intValue(), endIndices.get(i).intValue())); } return lines; } private List<SearchResult> searchMultiLineStringForPattern(final String s, final Pattern p) { Map<Pattern, Integer> patternMatches = new HashMap<>(); List<SearchResult> results = new ArrayList<>(); List<Number> newLineIndices = getNewLineIndices(s); List<Number> startLineIndices = getStartLineIndicesFromNewLineIndices(newLineIndices); List<Number> endLineIndices = getEndLineIndicesFromNewLineIndices(s, newLineIndices); final int linesBeforeCount = settings.getLinesBefore(); final int linesAfterCount = settings.getLinesAfter(); Matcher m = p.matcher(s); boolean found = m.find(); while (found) { if (settings.getFirstMatch() && patternMatches.containsKey(p)) { found = false; } else { // get the start line indices before the match index to get the current line number List<Number> beforeStartIndices = startLineIndices.stream() .filter(i -> i.intValue() <= m.start()) .collect(Collectors.toList()); int lineNum = beforeStartIndices.size(); int endLineIndex = endLineIndices.get(beforeStartIndices.size() - 1).intValue(); int startLineIndex = beforeStartIndices .remove(beforeStartIndices.size() - 1).intValue(); String line = s.substring(startLineIndex, endLineIndex); List<String> linesBefore; if (linesBeforeCount > 0) { List<Number> beforeEndIndices = endLineIndices.stream() .filter(i -> i.intValue() < m.start()) .collect(Collectors.toList()); List<Number> linesBeforeStartIndices = ListUtil .takeRight(beforeStartIndices, linesBeforeCount); List<Number> linesBeforeEndIndices = ListUtil .takeRight(beforeEndIndices, linesBeforeCount); linesBefore = getLinesFromMultiLineString(s, linesBeforeStartIndices, linesBeforeEndIndices); } else { linesBefore = new ArrayList<>(); } List<String> linesAfter; if (linesAfterCount > 0) { List<Number> afterStartIndices = startLineIndices.stream() .filter(i -> i.intValue() > m.start()) .limit(linesAfterCount) .collect(Collectors.toList()); List<Number> afterEndIndices = endLineIndices.stream() .filter(i -> i.intValue() > endLineIndex) .limit(linesAfterCount) .collect(Collectors.toList()); linesAfter = getLinesFromMultiLineString(s, afterStartIndices, afterEndIndices); } else { linesAfter = new ArrayList<>(); } if ((linesBefore.isEmpty() || linesBeforeMatch(linesBefore)) && (linesAfter.isEmpty() || linesAfterMatch(linesAfter))) { SearchResult searchResult = new SearchResult( p, null, lineNum, m.start() - startLineIndex + 1, m.end() - startLineIndex + 1, line, linesBefore, linesAfter); results.add(searchResult); patternMatches.put(p, 1); } found = m.find(m.end()); } } return results; } public final void searchTextFileLines(final SearchFile sf) { LineIterator it = null; try { it = FileUtil.getFileLineIterator(sf.toFile()); List<SearchResult> results = searchStringIterator(it); for (SearchResult r : results) { r.setSearchFile(sf); addSearchResult(r); } } catch (IOException e) { e.printStackTrace(); } finally { if (it != null) { it.close(); } } } private boolean linesMatch(final List<String> lines, final Set<Pattern> inPatterns, final Set<Pattern> outPatterns) { return ((inPatterns.size() == 0 || anyMatchesAnyPattern(lines, inPatterns)) && (outPatterns.size() == 0 || !anyMatchesAnyPattern(lines, outPatterns))); } private boolean linesBeforeMatch(final List<String> linesBefore) { return linesMatch(linesBefore, settings.getInLinesBeforePatterns(), settings.getOutLinesBeforePatterns()); } private boolean linesAfterMatch(final List<String> linesAfter) { return linesMatch(linesAfter, settings.getInLinesAfterPatterns(), settings.getOutLinesAfterPatterns()); } private boolean linesAfterToOrUntilMatch(final Iterator<String> it, List<String> linesAfter) { Set<Pattern> linesAfterPatterns; if (settings.hasLinesAfterToPatterns()) { linesAfterPatterns = settings.getLinesAfterToPatterns(); } else if (settings.hasLinesAfterUntilPatterns()) { linesAfterPatterns = settings.getLinesAfterUntilPatterns(); } else { // should never get here linesAfterPatterns = new HashSet<>(); } boolean linesAfterMatch = anyMatchesAnyPattern(linesAfter, linesAfterPatterns); while (!linesAfterMatch && it.hasNext()) { String nextLine = it.next(); linesAfter.add(nextLine); linesAfterMatch = matchesAnyPattern(nextLine, linesAfterPatterns); } if (linesAfterMatch) { if (settings.hasLinesAfterUntilPatterns()) { linesAfter.remove(linesAfter.size() - 1); } } return linesAfterMatch; } public final List<SearchResult> searchStringIterator(final Iterator<String> it) { int lineNum = 0; String line; final int linesBeforeCount = settings.getLinesBefore(); final int linesAfterCount = settings.getLinesAfter(); List<String> linesBefore = new ArrayList<>(); List<String> linesAfter = new ArrayList<>(); Set<Pattern> matchedPatterns = new HashSet<>(); List<SearchResult> results = new ArrayList<>(); while (true) { lineNum++; if (!linesAfter.isEmpty()) { line = linesAfter.remove(0); } else if (it.hasNext()) { line = it.next(); } else { break; } if (linesAfterCount > 0) { while (linesAfter.size() < linesAfterCount && it.hasNext()) { linesAfter.add(it.next()); } } Set<Pattern> searchPatterns = settings.getSearchPatterns() .stream().filter(p -> !matchedPatterns.contains(p)) .collect(Collectors.toSet()); for (Pattern p : searchPatterns) { Matcher m = p.matcher(line); boolean found = m.find(); while (found) { if ((linesBefore.isEmpty() || linesBeforeMatch(linesBefore)) && (linesAfter.isEmpty() || linesAfterMatch(linesAfter)) && (!settings.hasLinesAfterToOrUntilPatterns() || linesAfterToOrUntilMatch(it, linesAfter)) ) { SearchResult searchResult = new SearchResult( p, null, lineNum, m.start() + 1, m.end() + 1, line, new ArrayList<>(linesBefore), new ArrayList<>(linesAfter)); results.add(searchResult); if (settings.getFirstMatch()) { matchedPatterns.add(p); found = false; } else { found = m.find(m.end()); } } else { found = false; } } } if (linesBeforeCount > 0) { if (linesBefore.size() == linesBeforeCount) { linesBefore.remove(0); } if (linesBefore.size() < linesBeforeCount) { linesBefore.add(line); } } if (settings.getFirstMatch() && matchedPatterns.size() == settings.getSearchPatterns().size()) { break; } } return results; } public final void searchBinaryFile(final SearchFile sf) { if (settings.getVerbose()) { log(String.format("Searching binary file %s", sf.getPath())); } try { String content = FileUtil.getFileContents(sf.toFile(), "ISO8859-1"); for (Pattern p : settings.getSearchPatterns()) { Matcher m = p.matcher(content); boolean found = m.find(); while (found) { addSearchResult(new SearchResult( p, sf, 0, m.start() + 1, m.end() + 1, "")); if (settings.getFirstMatch()) { found = false; } else { found = m.find(m.end()); } } } } catch (IOException | NoSuchElementException | IllegalStateException e) { log(e.toString()); } } private void addSearchResult(final SearchResult searchResult) { results.add(searchResult); searchFileSet.add(searchResult.getSearchFile()); } private int signum(int num) { if (num > 0) { return 1; } if (num < 0) { return -1; } return 0; } private int compareResults(SearchResult r1, SearchResult r2) { int pathCmp = r1.getSearchFile().getPath().toLowerCase() .compareTo(r2.getSearchFile().getPath().toLowerCase()); if (pathCmp == 0) { int fileCmp = r1.getSearchFile().getFileName().toLowerCase() .compareTo(r2.getSearchFile().getFileName().toLowerCase()); if (fileCmp == 0) { int lineNumCmp = signum(r1.getLineNum() - r2.getLineNum()); if (lineNumCmp == 0) { return signum(r1.getMatchStartIndex() - r2.getMatchStartIndex()); } return lineNumCmp; } return fileCmp; } return pathCmp; } private List<SearchResult> getSortedSearchResults() { return results.stream().sorted(this::compareResults) .collect(Collectors.toList()); } public final void printSearchResults() { List<SearchResult> sortedResults = getSortedSearchResults(); log(String.format("Search results (%d):", sortedResults.size())); for (SearchResult r : sortedResults) { log(r.toString()); } } public final List<String> getMatchingDirs() { return searchFileSet.stream().map(SearchFile::getPath).distinct() .sorted().collect(Collectors.toList()); } public final void printMatchingDirs() { List<String> dirs = getMatchingDirs(); log(String.format("\nDirectories with matches (%d):", dirs.size())); for (String d : dirs) { log(d); } } public final List<String> getMatchingFiles() { return searchFileSet.stream().map(SearchFile::toString).sorted() .collect(Collectors.toList()); } public final void printMatchingFiles() { List<String> files = getMatchingFiles(); log(String.format("\nFiles with matches (%d):", files.size())); for (String f : files) { log(f); } } public final List<String> getMatchingLines() { List<String> lines = new ArrayList<>(); for (SearchResult r : results) { lines.add(r.getLine().trim()); } if (settings.getUniqueLines()) { Set<String> lineSet = new HashSet<>(lines); lines = new ArrayList<>(lineSet); } Collections.sort(lines, (s1, s2) -> s1.toUpperCase() .compareTo(s2.toUpperCase())); return lines; } public final void printMatchingLines() { List<String> lines = getMatchingLines(); String hdr; if (settings.getUniqueLines()) { hdr = "\nUnique lines with matches (%d):"; } else { hdr = "\nLines with matches (%d):"; } log(String.format(hdr, lines.size())); for (String line : lines) { log(line); } } }
package org.neo4j.server.webadmin.rest; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import org.neo4j.server.rest.domain.Representation; import org.neo4j.server.rest.domain.renderers.JsonRenderers; import org.neo4j.server.webadmin.rest.representations.MonitorServiceRepresentation; /** * This exposes data from an internal round-robin database that tracks various * system KPIs over time. * * @author Jacob Hansson <jacob@voltvoodoo.com> * */ @Path( MonitorService.ROOT_PATH ) public class MonitorService implements AdvertisableService { @Override public String getName() { return "monitor"; } @Override public String getServerPath() { return ROOT_PATH; } public static final String ROOT_PATH = "server/monitor"; public static final String DATA_PATH = "/fetch"; public static final String DATA_FROM_PATH = DATA_PATH + "/{start}"; public static final String DATA_SPAN_PATH = DATA_PATH + "/{start}/{stop}"; public static final long MAX_TIMESPAN = 1000l * 60l * 60l * 24l * 365l * 5; public static final long DEFAULT_TIMESPAN = 1000 * 60 * 60 * 24; @GET @Produces( MediaType.APPLICATION_JSON ) public Response getServiceDefinition( @Context UriInfo uriInfo ) { String entity = JsonRenderers.DEFAULT.render( new MonitorServiceRepresentation( uriInfo.getBaseUri() ) ); return Response.ok( entity, JsonRenderers.DEFAULT.getMediaType() ).build(); } @GET @Produces( MediaType.APPLICATION_JSON ) @Path( DATA_PATH ) public Response getData() { return getData( new Date().getTime() - DEFAULT_TIMESPAN, new Date().getTime() ); } @GET @Produces( MediaType.APPLICATION_JSON ) @Path( DATA_FROM_PATH ) public Response getData( @PathParam( "start" ) long start ) { return getData( start, new Date().getTime() ); } @GET @Produces( MediaType.APPLICATION_JSON ) @Path( DATA_SPAN_PATH ) public Response getData( @PathParam( "start" ) long start, @PathParam( "stop" ) long stop ) { String entity = JsonRenderers.DEFAULT.render( new DummyRepresentation( start ) ); return Response.ok( entity ).build(); // if ( start >= stop || ( stop - start ) > MAX_TIMESPAN ) // return buildExceptionResponse( // Status.BAD_REQUEST, // "Start time must be before stop time, and the total time span can be no bigger than " // + MAX_TIMESPAN // + "ms. Time span was " // + ( stop - start ) + "ms.", // try // FetchRequest request = RrdManager.getRrdDB().createFetchRequest( // ConsolFun.AVERAGE, start, stop, // getResolutionFor( stop - start ) ); // String entity = JsonRenderers.DEFAULT.render( new // RrdDataRepresentation( // request.fetchData() ) ); // return addHeaders( // Response.ok( entity, JsonRenderers.DEFAULT.getMediaType() ) // ).build(); // catch ( Exception e ) // return buildExceptionResponse( Status.INTERNAL_SERVER_ERROR, // "SEVERE: Round robin IO error.", e, JsonRenderers.DEFAULT ); } private class DummyRepresentation implements Representation { private static final int HUNDRED_SEC = 100000; private final long start; public DummyRepresentation( long start ) { this.start = start; // TODO Auto-generated constructor stub } @Override public Object serialize() { Map<String, Object> data = new HashMap<String, Object>(); data.put( "start_time", start ); data.put( "end_time", start + 6 * HUNDRED_SEC ); data.put( "timestamps", new long[] { start, start + 3 * HUNDRED_SEC, start + 6 * HUNDRED_SEC } ); Map<String, Object> datasources = new HashMap<String, Object>(); String[] dsNames = new String[] { "property_count", "node_count", "relationship_count", "node_cache_size", "memory_usage_percent" }; for ( int i = 0, l = dsNames.length; i < l; i++ ) { datasources.put( dsNames[i], new long[] { 10, 20, 30, 40 } ); } data.put( "data", datasources ); return data; } } // INTERNALS // private long getResolutionFor( long timespan ) // long preferred = (long) Math.floor( timespan // / ( RrdManager.STEPS_PER_ARCHIVE * 2 ) ); // // Don't allow resolutions smaller than the actual minimum resolution // return preferred > RrdManager.STEP_SIZE ? preferred // : RrdManager.STEP_SIZE; }
package com.imcode.imcms.mapping.mappers; @FunctionalInterface public interface Mappable<FROM, TO> { TO map(FROM source); }
package gov.nih.nci.calab.ui.core; import gov.nih.nci.calab.dto.characterization.CharacterizationBean; import gov.nih.nci.calab.dto.characterization.CharacterizationSummaryBean; import gov.nih.nci.calab.dto.characterization.DatumBean; import gov.nih.nci.calab.dto.characterization.DerivedBioAssayDataBean; import gov.nih.nci.calab.dto.characterization.invitro.CytotoxicityBean; import gov.nih.nci.calab.dto.characterization.physical.MorphologyBean; import gov.nih.nci.calab.dto.characterization.physical.ShapeBean; import gov.nih.nci.calab.dto.characterization.physical.SolubilityBean; import gov.nih.nci.calab.dto.characterization.physical.SurfaceBean; import gov.nih.nci.calab.dto.common.LabFileBean; import gov.nih.nci.calab.dto.common.ProtocolFileBean; import gov.nih.nci.calab.dto.common.UserBean; import gov.nih.nci.calab.dto.particle.ParticleBean; import gov.nih.nci.calab.exception.CaNanoLabSecurityException; import gov.nih.nci.calab.exception.FileException; import gov.nih.nci.calab.exception.ParticleCharacterizationException; import gov.nih.nci.calab.service.common.FileService; import gov.nih.nci.calab.service.particle.NanoparticleCharacterizationService; import gov.nih.nci.calab.service.particle.NanoparticleService; import gov.nih.nci.calab.service.security.UserService; import gov.nih.nci.calab.service.util.CaNanoLabConstants; import gov.nih.nci.calab.service.util.PropertyReader; import gov.nih.nci.calab.service.util.StringUtils; import gov.nih.nci.calab.ui.particle.InitParticleSetup; import gov.nih.nci.calab.ui.protocol.InitProtocolSetup; import gov.nih.nci.calab.ui.security.InitSecuritySetup; import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; 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.DynaValidatorForm; /** * This action serves as the base action for all characterization related action * classes. It includes common operations such as download, updateManufacturers. * * @author pansu */ /* * CVS $Id: BaseCharacterizationAction.java,v 1.73 2007/08/02 21:41:47 zengje * Exp $ */ public abstract class BaseCharacterizationAction extends AbstractDispatchAction { protected CharacterizationBean prepareCreate(HttpServletRequest request, DynaValidatorForm theForm) throws Exception { HttpSession session = request.getSession(); CharacterizationBean charBean = (CharacterizationBean) theForm .get("achar"); // validate that characterization file/derived data can't be empty for (DerivedBioAssayDataBean derivedDataFileBean : charBean .getDerivedBioAssayDataList()) { if (derivedDataFileBean.getType().length() == 0 && derivedDataFileBean.getCategories().length == 0 && derivedDataFileBean.getDisplayName().length() == 0 && derivedDataFileBean.getDatumList().size() == 0) { throw new ParticleCharacterizationException( "has an empty section for characterization file/derived data. Please remove it prior to saving."); } } for (DerivedBioAssayDataBean derivedDataFileBean : charBean .getDerivedBioAssayDataList()) { Map<String, Integer> uniqueDatumMap = new HashMap<String, Integer>(); for (DatumBean datumBean : derivedDataFileBean.getDatumList()) { // validate that neither name nor value can be empty if (datumBean.getName().length() == 0 || datumBean.getValue().length() == 0) { throw new ParticleCharacterizationException( "Derived data name and value can't be empty."); } if (datumBean.getStatisticsType().equalsIgnoreCase("boolean")) { if (!datumBean.getValue().equalsIgnoreCase("true") && !datumBean.getValue().equalsIgnoreCase("false") && !datumBean.getValue().equalsIgnoreCase("yes") && !datumBean.getValue().equalsIgnoreCase("no")) { throw new ParticleCharacterizationException( "The datum value for boolean type should be 'True'/'False' or 'Yes'/'No'."); } } else { if (!StringUtils.isDouble(datumBean.getValue()) && !StringUtils.isInteger(datumBean.getValue())) { throw new ParticleCharacterizationException( "The datum value should be a number."); } } // validate derived data has unique name, statistics type and // category String uniqueStr = datumBean.getName() + ":" + datumBean.getStatisticsType() + ":" + datumBean.getCategory(); if (uniqueDatumMap.get(uniqueStr) != null) { throw new ParticleCharacterizationException( "no two derived data can have the same name, statistics type and category."); } else { uniqueDatumMap.put(uniqueStr, 1); } } } // set createdBy and createdDate for the characterization UserBean user = (UserBean) session.getAttribute("user"); Date date = new Date(); charBean.setCreatedBy(user.getLoginName()); charBean.setCreatedDate(date); ParticleBean particle = (ParticleBean) theForm.get("particle"); charBean.setParticle(particle); return charBean; } protected ActionForward postCreate(HttpServletRequest request, DynaValidatorForm theForm, ActionMapping mapping) throws Exception { ParticleBean particle = (ParticleBean) theForm.get("particle"); CharacterizationBean charBean = (CharacterizationBean) theForm .get("achar"); // save new lookup up types in the database definition tables. NanoparticleCharacterizationService service = new NanoparticleCharacterizationService(); service.addNewCharacterizationDataDropdowns(charBean, charBean .getName()); request.getSession().setAttribute("newCharacterizationCreated", "true"); request.getSession().setAttribute("newCharacterizationSourceCreated", "true"); request.getSession().setAttribute("newInstrumentCreated", "true"); request.getSession().setAttribute("newCharacterizationFileTypeCreated", "true"); InitParticleSetup.getInstance().setSideParticleMenu(request, particle.getSampleId()); request.setAttribute("theParticle", particle); ActionMessages msgs = new ActionMessages(); ActionMessage msg = new ActionMessage("message.addCharacterization", charBean.getName()); msgs.add("message", msg); saveMessages(request, msgs); return mapping.findForward("success"); } protected CharacterizationBean[] prepareCopy(HttpServletRequest request, DynaValidatorForm theForm) throws Exception { CharacterizationBean charBean = (CharacterizationBean) theForm .get("achar"); ParticleBean particle = (ParticleBean) theForm.get("particle"); String[] otherParticles = (String[]) theForm.get("otherParticles"); Boolean copyData = (Boolean) theForm.get("copyData"); CharacterizationBean[] charBeans = new CharacterizationBean[otherParticles.length]; NanoparticleService service = new NanoparticleService(); int i = 0; for (String particleName : otherParticles) { CharacterizationBean newCharBean = charBean.copy(copyData .booleanValue()); // overwrite particle and particle type; newCharBean.getParticle().setSampleName(particleName); ParticleBean otherParticle = service.getParticleBy(particleName); newCharBean.getParticle().setSampleType( otherParticle.getSampleType()); // reset view title String timeStamp = StringUtils.convertDateToString(new Date(), "MMddyyHHmmssSSS"); String autoTitle = CaNanoLabConstants.AUTO_COPY_CHARACTERIZATION_VIEW_TITLE_PREFIX + timeStamp; newCharBean.setViewTitle(autoTitle); List<DerivedBioAssayDataBean> dataList = newCharBean .getDerivedBioAssayDataList(); // replace particleName in path and uri with new particleName for (DerivedBioAssayDataBean derivedBioAssayData : dataList) { String origUri = derivedBioAssayData.getUri(); if (origUri != null) derivedBioAssayData.setUri(origUri.replace(particle .getSampleName(), particleName)); } charBeans[i] = newCharBean; i++; } return charBeans; } /** * clear session data from the input form * * @param session * @param theForm * @param mapping * @throws Exception */ protected void clearMap(HttpSession session, DynaValidatorForm theForm) throws Exception { // reset achar and otherParticles theForm.set("otherParticles", new String[0]); theForm.set("copyData", false); theForm.set("achar", new CharacterizationBean()); theForm.set("morphology", new MorphologyBean()); theForm.set("shape", new ShapeBean()); theForm.set("surface", new SurfaceBean()); theForm.set("solubility", new SolubilityBean()); theForm.set("cytotoxicity", new CytotoxicityBean()); cleanSessionAttributes(session); } /** * Prepopulate data for the input form * * @param request * @param theForm * @throws Exception */ protected void initSetup(HttpServletRequest request, DynaValidatorForm theForm) throws Exception { HttpSession session = request.getSession(); clearMap(session, theForm); UserBean user = (UserBean) request.getSession().getAttribute("user"); InitParticleSetup.getInstance() .setAllCharacterizationDropdowns(session); // set up particle String particleId = request.getParameter("particleId"); if (particleId != null) { NanoparticleService particleService = new NanoparticleService(); ParticleBean particle = particleService.getParticleInfo(particleId, user); theForm.set("particle", particle); request.setAttribute("theParticle", particle); // set up other particles from the same source SortedSet<String> allOtherParticleNames = particleService .getOtherParticles(particle.getSampleSource(), particle .getSampleName(), user); session .setAttribute("allOtherParticleNames", allOtherParticleNames); InitParticleSetup.getInstance().setSideParticleMenu(request, particleId); } else { throw new ParticleCharacterizationException( "Particle ID is required."); } InitSessionSetup.getInstance().setApplicationOwner(session); InitParticleSetup.getInstance().setAllInstruments(session); InitParticleSetup.getInstance().setAllDerivedDataFileTypes(session); InitParticleSetup.getInstance().setAllPhysicalDropdowns(session); InitParticleSetup.getInstance().setAllInvitroDropdowns(session); // set characterization String submitType = (String) request.getParameter("submitType"); String characterizationId = request.getParameter("characterizationId"); if (characterizationId != null) { NanoparticleCharacterizationService charService = new NanoparticleCharacterizationService(); CharacterizationBean charBean = charService .getCharacterizationBy(characterizationId); if (charBean == null) { throw new ParticleCharacterizationException( "This characterization no longer exists in the database. Please log in again to refresh."); } theForm.set("achar", charBean); } CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); if (achar != null && submitType != null) { achar.setName(submitType); InitParticleSetup.getInstance() .setAllCharacterizationMeasureUnitsTypes(session, submitType); InitParticleSetup.getInstance().setDerivedDatumNames(session, achar.getName()); InitProtocolSetup.getInstance().setProtocolFilesByCharName(session, achar.getName()); UserService userService = new UserService( CaNanoLabConstants.CSM_APP_NAME); // set up characterization files visibility, and whether file is an // image for (DerivedBioAssayDataBean fileBean : achar .getDerivedBioAssayDataList()) { boolean accessStatus = userService.checkReadPermission(user, fileBean.getId()); if (accessStatus) { List<String> accessibleGroups = userService .getAccessibleGroups(fileBean.getId(), CaNanoLabConstants.CSM_READ_ROLE); String[] visibilityGroups = accessibleGroups .toArray(new String[0]); fileBean.setVisibilityGroups(visibilityGroups); fileBean.setHidden(false); } else { fileBean.setHidden(true); } boolean imageStatus = false; if (fileBean.getName() != null) { imageStatus = StringUtils.isImgFileExt(fileBean.getName()); fileBean.setImage(imageStatus); } } // set up protocol file visibility ProtocolFileBean protocolFileBean = achar.getProtocolFileBean(); if (protocolFileBean != null) { boolean status = false; if (protocolFileBean.getId() != null) { status = userService.checkReadPermission(user, protocolFileBean.getId()); } if (status) { protocolFileBean.setHidden(false); } else { protocolFileBean.setHidden(true); } } } } /** * Clean the session attribture * * @param sessioin * @throws Exception */ protected void cleanSessionAttributes(HttpSession session) throws Exception { for (Enumeration e = session.getAttributeNames(); e.hasMoreElements();) { String element = (String) e.nextElement(); if (element.startsWith(CaNanoLabConstants.CHARACTERIZATION_FILE)) { session.removeAttribute(element); } } } /** * Set up the input form for adding new characterization * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward setup(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; initSetup(request, theForm); return mapping.getInputForward(); } public ActionForward input(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; // update editable dropdowns CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); ShapeBean shape = (ShapeBean) theForm.get("shape"); MorphologyBean morphology = (MorphologyBean) theForm.get("morphology"); CytotoxicityBean cyto = (CytotoxicityBean) theForm.get("cytotoxicity"); SolubilityBean solubility = (SolubilityBean) theForm.get("solubility"); HttpSession session = request.getSession(); updateAllCharEditables(session, achar); updateShapeEditable(session, shape); updateMorphologyEditable(session, morphology); updateCytotoxicityEditable(session, cyto); updateSolubilityEditable(session, solubility); // updateSurfaceEditable(session, surface); return mapping.findForward("setup"); } /** * Set up the form for updating existing characterization * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward setupUpdate(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; initSetup(request, theForm); CharacterizationBean charBean = (CharacterizationBean) theForm .get("achar"); // set characterizations with additional information if (charBean instanceof ShapeBean) { theForm.set("shape", charBean); } else if (charBean instanceof MorphologyBean) { theForm.set("morphology", charBean); } else if (charBean instanceof SolubilityBean) { theForm.set("solubility", charBean); } else if (charBean instanceof SurfaceBean) { theForm.set("surface", charBean); } else if (charBean instanceof SolubilityBean) { theForm.set("solubility", charBean); } else if (charBean instanceof CytotoxicityBean) { theForm.set("cytotoxicity", charBean); } return mapping.findForward("setup"); } public ActionForward detailView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; initSetup(request, theForm); String particleId = request.getParameter("particleId"); String characterizationId = request.getParameter("characterizationId"); String submitType = request.getParameter("submitType"); CharacterizationBean charBean = (CharacterizationBean) theForm .get("achar"); String printLinkURL = "/caNanoLab/" + charBean.getActionName() + ".do?page=0&dispatch=printDetailView&particleId=" + particleId + "&characterizationId=" + characterizationId + "&submitType=" + submitType; request.setAttribute("printLinkURL", printLinkURL); return mapping.findForward("detailView"); } public ActionForward exportDetail(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; initSetup(request, theForm); CharacterizationBean charBean = (CharacterizationBean) theForm.get("achar"); NanoparticleCharacterizationService service = new NanoparticleCharacterizationService(); //response.setContentType("application/vnd.ms-execel"); response.setContentType("application/octet-stream"); response.setHeader("cache-control", "Private"); response.setHeader("Content-disposition", "attachment;filename=" + charBean.getActionName() + "_" + charBean.getViewTitle() + ".xls"); UserBean user = (UserBean) request.getSession().getAttribute("user"); java.io.OutputStream out = response.getOutputStream(); service.exportDetailService(theForm, out, user); return null; } public ActionForward exportSummary(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; initSetup(request, theForm); CharacterizationBean charBean = (CharacterizationBean) theForm.get("achar"); NanoparticleCharacterizationService service = new NanoparticleCharacterizationService(); //response.setContentType("application/vnd.ms-execel"); response.setContentType("application/octet-stream"); response.setHeader("cache-control", "Private"); response.setHeader("Content-disposition", "attachment;filename=" + charBean.getActionName() + ".xls"); UserBean user = (UserBean) request.getSession().getAttribute("user"); java.io.OutputStream out = response.getOutputStream(); String submitType = request.getParameter("submitType"); ParticleBean particle = (ParticleBean) theForm.get("particle"); List<CharacterizationSummaryBean> summaryBeans = service .getParticleCharacterizationSummaryByName(submitType, particle.getSampleId()); SortedSet<String> datumLabels = service.setDataLabelsAndFileVisibility(user, summaryBeans); service.exportSummaryService(datumLabels, summaryBeans, submitType, theForm, out, user); return null; } public ActionForward printDetailView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; initSetup(request, theForm); return mapping.findForward("detailPrintView"); } private void setSummaryView(ActionForm form, HttpServletRequest request) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; initSetup(request, theForm); String submitType = request.getParameter("submitType"); ParticleBean particle = (ParticleBean) theForm.get("particle"); NanoparticleCharacterizationService service = new NanoparticleCharacterizationService(); List<CharacterizationSummaryBean> charSummaryBeans = service .getParticleCharacterizationSummaryByName(submitType, particle .getSampleId()); if (charSummaryBeans == null) { throw new Exception( "There are no such characterizations in the database."); } // set data labels and file visibility, and whether file is an image UserService userService = new UserService( CaNanoLabConstants.CSM_APP_NAME); UserBean user = (UserBean) request.getSession().getAttribute("user"); List<CharacterizationBean> charBeans = new ArrayList<CharacterizationBean>(); SortedSet<String> datumLabels = new TreeSet<String>(); for (CharacterizationSummaryBean summaryBean : charSummaryBeans) { if (!charBeans.contains(summaryBean.getCharBean())) { charBeans.add(summaryBean.getCharBean()); } Map<String, String> datumMap = summaryBean.getDatumMap(); if (datumMap != null && !datumMap.isEmpty()) { datumLabels.addAll(datumMap.keySet()); } DerivedBioAssayDataBean fileBean = summaryBean.getCharFile(); if (fileBean != null) { boolean accessStatus = userService.checkReadPermission(user, fileBean.getId()); if (accessStatus) { List<String> accessibleGroups = userService .getAccessibleGroups(fileBean.getId(), CaNanoLabConstants.CSM_READ_ROLE); String[] visibilityGroups = accessibleGroups .toArray(new String[0]); fileBean.setVisibilityGroups(visibilityGroups); fileBean.setHidden(false); } else { fileBean.setHidden(true); } boolean imageStatus = false; if (fileBean.getName() != null) { imageStatus = StringUtils.isImgFileExt(fileBean.getName()); } fileBean.setImage(imageStatus); } } request.setAttribute("summaryViewBeans", charSummaryBeans); request.setAttribute("summaryViewCharBeans", charBeans); request.setAttribute("datumLabels", datumLabels); } public ActionForward summaryView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { setSummaryView(form, request); DynaValidatorForm theForm = (DynaValidatorForm) form; ParticleBean particle = (ParticleBean) theForm.get("particle"); String submitType = request.getParameter("submitType"); CharacterizationBean charBean = (CharacterizationBean) theForm .get("achar"); String printLinkURL = "/caNanoLab/" + charBean.getActionName() + ".do?page=0&dispatch=printSummaryView&particleId=" + particle.getSampleId() + "&submitType=" + submitType; String printAllLinkURL = "/caNanoLab/" + charBean.getActionName() + ".do?page=0&dispatch=printFullSummaryView&particleId=" + particle.getSampleId() + "&submitType=" + submitType; request.setAttribute("printLinkURL", printLinkURL); request.setAttribute("printAllLinkURL", printAllLinkURL); return mapping.findForward("summaryView"); } public ActionForward printSummaryView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { setSummaryView(form, request); return mapping.findForward("summaryPrintView"); } public ActionForward printFullSummaryView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { setSummaryView(form, request); return mapping.findForward("summaryPrintAllView"); } /** * Load file action for characterization file loading. * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward loadFile(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; ParticleBean particle = (ParticleBean) theForm.get("particle"); request.setAttribute("loadFileForward", mapping.findForward("setup") .getPath()); CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); int fileNum = Integer.parseInt(request.getParameter("fileNumber")); DerivedBioAssayDataBean derivedBioAssayDataBean = achar .getDerivedBioAssayDataList().get(fileNum); derivedBioAssayDataBean.setParticleName(particle.getSampleName()); derivedBioAssayDataBean.setCharacterizationName(achar.getName()); request.setAttribute("file", derivedBioAssayDataBean); return mapping.findForward("loadFile"); } /** * Download action to handle characterization file download and viewing * * @param * @return */ public ActionForward download(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String fileId = request.getParameter("fileId"); UserBean user = (UserBean) request.getSession().getAttribute("user"); FileService service = new FileService(); LabFileBean fileBean = service.getFile(fileId, user); String fileRoot = PropertyReader.getProperty( CaNanoLabConstants.FILEUPLOAD_PROPERTY, "fileRepositoryDir"); File dFile = new File(fileRoot + File.separator + fileBean.getUri()); if (dFile.exists()) { response.setContentType("application/octet-stream"); response.setHeader("Content-disposition", "attachment;filename=" + fileBean.getName()); response.setHeader("cache-control", "Private"); java.io.InputStream in = new FileInputStream(dFile); java.io.OutputStream out = response.getOutputStream(); byte[] bytes = new byte[32768]; int numRead = 0; while ((numRead = in.read(bytes)) > 0) { out.write(bytes, 0, numRead); } out.close(); } else { throw new FileException( "File to download doesn't exist on the server"); } return null; } public ActionForward addFile(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); List<DerivedBioAssayDataBean> origTables = achar .getDerivedBioAssayDataList(); int origNum = (origTables == null) ? 0 : origTables.size(); List<DerivedBioAssayDataBean> tables = new ArrayList<DerivedBioAssayDataBean>(); for (int i = 0; i < origNum; i++) { tables.add(origTables.get(i)); } // add a new one tables.add(new DerivedBioAssayDataBean()); achar.setDerivedBioAssayDataList(tables); ParticleBean particle = (ParticleBean) theForm.get("particle"); InitParticleSetup.getInstance().setSideParticleMenu(request, particle.getSampleId()); return input(mapping, form, request, response); } public ActionForward removeFile(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String fileIndexStr = (String) request.getParameter("compInd"); int fileInd = Integer.parseInt(fileIndexStr); DynaValidatorForm theForm = (DynaValidatorForm) form; CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); List<DerivedBioAssayDataBean> origTables = achar .getDerivedBioAssayDataList(); int origNum = (origTables == null) ? 0 : origTables.size(); List<DerivedBioAssayDataBean> tables = new ArrayList<DerivedBioAssayDataBean>(); for (int i = 0; i < origNum; i++) { tables.add(origTables.get(i)); } // remove the one at the index if (origNum > 0) { tables.remove(fileInd); } achar.setDerivedBioAssayDataList(tables); ParticleBean particle = (ParticleBean) theForm.get("particle"); InitParticleSetup.getInstance().setSideParticleMenu(request, particle.getSampleId()); return input(mapping, form, request, response); } public ActionForward addData(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); String fileIndexStr = (String) request.getParameter("compInd"); int fileInd = Integer.parseInt(fileIndexStr); DerivedBioAssayDataBean derivedBioAssayDataBean = (DerivedBioAssayDataBean) achar .getDerivedBioAssayDataList().get(fileInd); List<DatumBean> origDataList = derivedBioAssayDataBean.getDatumList(); int origNum = (origDataList == null) ? 0 : origDataList.size(); List<DatumBean> dataList = new ArrayList<DatumBean>(); for (int i = 0; i < origNum; i++) { DatumBean dataPoint = (DatumBean) origDataList.get(i); dataList.add(dataPoint); } dataList.add(new DatumBean()); derivedBioAssayDataBean.setDatumList(dataList); ParticleBean particle = (ParticleBean) theForm.get("particle"); InitParticleSetup.getInstance().setSideParticleMenu(request, particle.getSampleId()); return input(mapping, form, request, response); } public ActionForward removeData(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; CharacterizationBean achar = (CharacterizationBean) theForm .get("achar"); String fileIndexStr = (String) request.getParameter("compInd"); int fileInd = Integer.parseInt(fileIndexStr); String dataIndexStr = (String) request.getParameter("childCompInd"); int dataInd = Integer.parseInt(dataIndexStr); DerivedBioAssayDataBean derivedBioAssayDataBean = (DerivedBioAssayDataBean) achar .getDerivedBioAssayDataList().get(fileInd); List<DatumBean> origDataList = derivedBioAssayDataBean.getDatumList(); int origNum = (origDataList == null) ? 0 : origDataList.size(); List<DatumBean> dataList = new ArrayList<DatumBean>(); for (int i = 0; i < origNum; i++) { DatumBean dataPoint = (DatumBean) origDataList.get(i); dataList.add(dataPoint); } if (origNum > 0) dataList.remove(dataInd); derivedBioAssayDataBean.setDatumList(dataList); ParticleBean particle = (ParticleBean) theForm.get("particle"); InitParticleSetup.getInstance().setSideParticleMenu(request, particle.getSampleId()); return input(mapping, form, request, response); // return mapping.getInputForward(); this gives an // IndexOutOfBoundException in the jsp page } /** * Pepopulate data for the form * * @param request * @param theForm * @throws Exception */ public ActionForward deleteConfirmed(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; initSetup(request, theForm); ParticleBean particle = (ParticleBean) theForm.get("particle"); String charId = request.getParameter("characterizationId"); NanoparticleCharacterizationService service = new NanoparticleCharacterizationService(); service.deleteCharacterizations(new String[] { charId }); // signal the session that characterization has been changed request.getSession().setAttribute("newCharacterizationCreated", "true"); InitParticleSetup.getInstance().setSideParticleMenu(request, particle.getSampleId()); ActionMessages msgs = new ActionMessages(); ActionMessage msg = new ActionMessage("message.delete.characterization"); msgs.add("message", msg); saveMessages(request, msgs); return mapping.findForward("success"); } // add edited option to all editable dropdowns private void updateAllCharEditables(HttpSession session, CharacterizationBean achar) throws Exception { InitSessionSetup.getInstance().updateEditableDropdown(session, achar.getCharacterizationSource(), "characterizationSources"); InitSessionSetup.getInstance().updateEditableDropdown(session, achar.getInstrumentConfigBean().getInstrumentBean().getType(), "allInstrumentTypes"); InitSessionSetup.getInstance().updateEditableDropdown( session, achar.getInstrumentConfigBean().getInstrumentBean() .getManufacturer(), "allManufacturers"); for (DerivedBioAssayDataBean derivedBioAssayDataBean : achar .getDerivedBioAssayDataList()) { InitSessionSetup.getInstance().updateEditableDropdown(session, derivedBioAssayDataBean.getType(), "allDerivedDataFileTypes"); if (derivedBioAssayDataBean != null) { for (String category : derivedBioAssayDataBean.getCategories()) { InitSessionSetup.getInstance().updateEditableDropdown( session, category, "derivedDataCategories"); } for (DatumBean datum : derivedBioAssayDataBean.getDatumList()) { InitSessionSetup.getInstance().updateEditableDropdown( session, datum.getName(), "datumNames"); InitSessionSetup.getInstance().updateEditableDropdown( session, datum.getStatisticsType(), "charMeasureTypes"); InitSessionSetup.getInstance().updateEditableDropdown( session, datum.getUnit(), "charMeasureUnits"); } } } } // add edited option to all editable dropdowns private void updateShapeEditable(HttpSession session, ShapeBean shape) throws Exception { InitSessionSetup.getInstance().updateEditableDropdown(session, shape.getType(), "allShapeTypes"); } private void updateMorphologyEditable(HttpSession session, MorphologyBean morphology) throws Exception { InitSessionSetup.getInstance().updateEditableDropdown(session, morphology.getType(), "allMorphologyTypes"); } private void updateCytotoxicityEditable(HttpSession session, CytotoxicityBean cyto) throws Exception { InitSessionSetup.getInstance().updateEditableDropdown(session, cyto.getCellLine(), "allCellLines"); } private void updateSolubilityEditable(HttpSession session, SolubilityBean solubility) throws Exception { InitSessionSetup.getInstance().updateEditableDropdown(session, solubility.getSolvent(), "allSolventTypes"); } // private void updateSurfaceEditable(HttpSession session, // SurfaceBean surface) throws Exception { public boolean loginRequired() { return true; } public boolean canUserExecute(UserBean user) throws CaNanoLabSecurityException { return InitSecuritySetup.getInstance().userHasCreatePrivilege(user, CaNanoLabConstants.CSM_PG_PARTICLE); } }
package com.jaeksoft.searchlib.index; import java.util.ArrayList; import java.util.List; import com.jaeksoft.searchlib.schema.FieldValueItem; import com.jaeksoft.searchlib.util.External.Collecter; public class FieldContent implements Collecter<FieldValueItem> { private String field; private List<FieldValueItem> values; public FieldContent() { values = null; } public FieldContent(final String field) { this(); this.field = field; } final public String getField() { return field; } final public void add(final FieldValueItem value) { if (values == null) values = new ArrayList<FieldValueItem>(1); values.add(value); } public final void addIfNotAlreadyHere(final FieldValueItem value) { if (values != null) for (FieldValueItem v : values) if (value.equals(v)) return; add(value); } final public void addIfNotAlreadyHere(final FieldContent fc2) { if (fc2.values != null) for (FieldValueItem v : fc2.values) addIfNotAlreadyHere(v); } final public void add(final FieldContent fc2) { if (fc2.values == null) return; if (values == null) values = new ArrayList<FieldValueItem>(1); values.addAll(fc2.values); } @Override final public void addObject(final FieldValueItem valueItem) { add(valueItem); } final public void clear() { values = null; } final public void setValueItems(List<FieldValueItem> valueItems) { if (valueItems == null) return; if (values == null) values = new ArrayList<FieldValueItem>(); else values.clear(); values.addAll(valueItems); } final public FieldValueItem getValue(final int pos) { if (values == null) return null; if (pos >= values.size()) return null; return values.get(pos); } final public void setValue(final int pos, final FieldValueItem value) { values.set(pos, value); } final public List<FieldValueItem> getValues() { return values; } final public int getValueCount() { if (values == null) return 0; return values.size(); } final public boolean hasContent() { return getValueCount() > 0; } public final String getMergedValues(final String separator) { StringBuilder sb = new StringBuilder(); boolean first = true; if (values != null) { for (FieldValueItem item : values) { if (first) first = false; else sb.append(separator); sb.append(item.getValue()); } } return sb.toString(); } final public String getMergedValues(final int max, final String separator) { StringBuilder sb = new StringBuilder(); boolean first = true; if (values != null) { for (FieldValueItem item : values) { if (first) first = false; else sb.append(separator); sb.append(item.getValue()); if (sb.length() > max) { sb.setLength(max); break; } } } return sb.toString(); } final public void remove(int index) { values.remove(index); } final public boolean isEquals(FieldContent fc) { if (!field.equals(fc.getField())) return false; if (values == null) { if (fc.values == null) return true; else return false; } if (fc.values == null) return false; if (values.size() != fc.values.size()) return false; int i = 0; for (FieldValueItem v1 : values) { FieldValueItem v2 = fc.values.get(i++); if (v1 == null) { if (v2 != null) return false; else continue; } if (!v1.equals(v2)) return false; } return true; } @Override final public String toString() { StringBuilder sb = new StringBuilder(); sb.append(field); sb.append('('); sb.append(values == null ? 0 : values.size()); sb.append(')'); if (values != null && values.size() > 0) { sb.append(':'); sb.append(values.get(0).getValue()); } return sb.toString(); } final public String toLabel() { StringBuilder sb = new StringBuilder(); sb.append(field); sb.append('('); sb.append(values == null ? 0 : values.size()); sb.append(')'); return sb.toString(); } }
package hk.reality.stock.service.fetcher; import hk.reality.stock.model.StockDetail; import hk.reality.stock.service.exception.DownloadException; import hk.reality.stock.service.exception.ParseException; import java.io.IOException; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.util.EntityUtils; import org.json.JSONException; import org.json.JSONObject; public class Money18QuoteFetcher extends BaseQuoteFetcher { private static final String DATE_FORMAT = "yyyy/MM/dd HH:mm"; @Override public StockDetail fetch(String quote) throws DownloadException, ParseException { StockDetail d = new StockDetail(); String content = null; try { HttpGet openReq = new HttpGet(getOpenUrl(quote)); openReq.setHeader("Referer", "http://money18.on.cc/"); HttpResponse resp = getClient().execute(openReq); content = EntityUtils.toString(resp.getEntity()); JSONObject json = preprocessJson(content); double openPrice = json.getDouble("openPrice"); HttpGet req = new HttpGet(getUpdateUrl(quote)); req.setHeader("Referer", "http://money18.on.cc/"); resp = getClient().execute(req); content = EntityUtils.toString(resp.getEntity()); json = preprocessJson(content); double price = json.getDouble("np"); double change = openPrice - price; double changePercent = (openPrice - price) * 100.0 / openPrice; d.setPrice(new BigDecimal(json.getString("np"))); d.setChangePrice(new BigDecimal("" + change)); d.setChangePricePercent(new BigDecimal("" + changePercent)); d.setDayHigh(new BigDecimal(json.getString("dyh"))); d.setDayLow(new BigDecimal(json.getString("dyl"))); d.setQuote(quote); d.setSourceUrl(getUrl(quote)); SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT); Date updateTime = formatter.parse(json.getString("ltt")); Calendar updatedAt = Calendar.getInstance(); updatedAt.setTime(updateTime); d.setUpdatedAt(updatedAt); d.setVolume(new BigDecimal(json.getString("vol")).toPlainString()); return d; } catch (ClientProtocolException e) { throw new DownloadException("protocol exception", e); } catch (IOException e) { throw new DownloadException("download stock error", e); } catch (JSONException e) { throw new ParseException("unexpected return value," + " content = " + content, e); } catch (java.text.ParseException e) { throw new ParseException("failed to parse date format," + " content = " + content, e); } } private JSONObject preprocessJson(String content) throws JSONException { int pos = content.indexOf('{'); String result = StringUtils.substring(content, pos); JSONObject json = new JSONObject(result); return json; } @Override public String getUrl(String quote) { return String.format("http://money18.on.cc/info/liveinfo_quote.html?symbol=%s", quote); } private String getOpenUrl(String quote) { return String.format("http://money18.on.cc/js/real/opening/%s_o.js", quote); } private String getUpdateUrl(String quote) { return String.format("http://money18.on.cc/js/real/quote/%s_r.js", quote); } }
package uk.org.ponder.reflect; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.Map; import uk.org.ponder.saxalizer.SAXAccessMethod; import uk.org.ponder.util.Logger; import uk.org.ponder.util.UniversalRuntimeException; /** * A cache for simple no-arg methods and constructors, of the sort that are * typically used in bean environments, that are not suitable to be considered * as "bean properties" and hence handled by a SAXAccessMethod. * * The intention is that **ALL** application-wide reflection will be done either * in this class, or in SAXAccessMethod. * * This class is full of static state and methods, in the belief that all * reflective objects will have the same lifetime as their parent ClassLoader. * This militates that <b>PonderUtilCore MUST NEVER be placed at a shared * ClassLoader level </b> * * This implementation will probably shortly be replaced by a FastClass variant. * * @author Antranig Basman (antranig@caret.cam.ac.uk) * */ public abstract class ReflectiveCache { /** The globality of a ReflectiveCache is expected to be ClassLoader wide. * This instance will be set by any constructor that executes, through Spring * configuration or otherwise. */ public static ReflectiveCache instance; private Map rootmap; private static Class concurrent1mapclass; // The constructor for the oswego n-concurrent map class - we need to handle // this explicitly, since the concurrency level has to be passed in as an argument. private static Constructor concurrentnmapcons; private static boolean nmapisJSR166 = false; public static Class getConcurrent1MapClass() { // OSwego is preferable to JSR166 since our desired concurrency level is // pretty much 1. CRHM is i) optimised for this case, and ii) will be // cheaper in construction since we can use the no-args constructor. Class mapclass = ClassGetter .forName("EDU.oswego.cs.dl.util.concurrent.ConcurrentReaderHashMap"); if (mapclass == null) { mapclass = ClassGetter.forName("java.util.concurrent.ConcurrentHashMap"); } if (mapclass == null) { System.err.println("Fatal: Could not instantiate concurrent map class from either oswego or JDK 1.5 provider"); Logger.log .fatal("Could not instantiate concurrent map class from either oswego or JDK 1.5 provider"); } return mapclass; } /** * Returns a Constructor capable of constructing a multiple-concurrent-reader * HashMap. */ public static Constructor getConcurrentNMapConstructor() { Class mapclass = ClassGetter .forName("EDU.oswego.cs.dl.util.concurrent.ConcurrentHashMap"); try { if (mapclass == null) { mapclass = ClassGetter .forName("java.util.concurrent.ConcurrentHashMap"); if (mapclass != null) { nmapisJSR166 = true; return mapclass.getConstructor(new Class[] { Integer.TYPE, Float.TYPE, Integer.TYPE }); } } else { return mapclass.getConstructor(SAXAccessMethod.emptyclazz); } if (mapclass == null) { Logger.log .fatal("Could not instantiate concurrent map class from either oswego or JDK 1.5 provider"); } } catch (Exception e) { Logger.log.fatal("Exception finding constructor for " + mapclass, e); } return null; } /** * Get a no-argument constructor for a class * @param clazz the class * @return a no-arg constructor */ public static Constructor getConstructor(Class clazz) { try { return clazz.getConstructor(SAXAccessMethod.emptyclazz); } catch (Exception e) { throw UniversalRuntimeException.accumulate(e, "Error getting constructor for " + clazz); } } protected Map getClassMap(Class target) { Map classmap = (Map) rootmap.get(target); if (classmap == null) { classmap = getConcurrentMap(1); rootmap.put(target, classmap); } return classmap; } public static Method getMethod(Class clazz, String name) { return getMethod(clazz, name, SAXAccessMethod.emptyclazz); } public static Method getMethod(Class clazz, String name, Class[] argtypes) { try { return clazz.getMethod(name, argtypes); } catch (Exception e) { throw UniversalRuntimeException.accumulate(e, "Error reflecting for method " + name + " of " + clazz); } } public abstract Object construct(Class clazz); public abstract Object invokeMethod(Object bean, String method); protected abstract Object invokeMethod(Object target, String name, Class[] infer, Object[] args); /** * This generic invocation method currently unused, * for internal framework use only */ public Object invokeMethod(Object target, String name, Object[] args) { if (target instanceof MethodInvokingProxy) { return ((MethodInvokingProxy)target).invokeMethod(name, args); } Class[] infer = new Class[args.length]; for (int i = 0; i < args.length; ++ i) { infer[i] = args[i].getClass(); } return invokeMethod(target, name, infer, args); } /** * The key used into per-class reflective caches representing the no-arg * constructor. */ public static final String CONSTRUCTOR_KEY = "<init>"; /** * The initial size of JSR-166 multi-concurrency hashes (all others are * defaults) */ public static final int INIT_MAP_SIZE = 1024; /** * Returns a new concurrent map object with the desired level of concurrency. * If the oswego package is available, any concurrency level other than 1 will * return the ConcurrentHashMap implementation with its hardwired level of 32. * Concurrency level 1 hashes are suitable for static application-wide caches, * e.g. for internal use of this class, to be either the root map or the map * for the default constructors of a particular class. */ public Map getConcurrentMap(int concurrency) { // if map class is null, this is the first call for the entire system, // perhaps // from getClassMap. Initialise the root table, and put the constructor for // the concurrent map itself in it as its first entry, manually. // Uninteresting race condition here. // TODO: try to remove downcall to JDKReflector if (concurrency == 1) { // check both of these because of possible race condition. if (concurrent1mapclass == null || rootmap == null) { concurrent1mapclass = getConcurrent1MapClass(); Constructor cons = getConstructor(concurrent1mapclass); rootmap = (Map) JDKReflectiveCache.invokeConstructor(cons); Map classmap = (Map) JDKReflectiveCache.invokeConstructor(cons); classmap.put(CONSTRUCTOR_KEY, cons); rootmap.put(concurrent1mapclass, classmap); } return (Map) construct(concurrent1mapclass); } else { if (concurrentnmapcons == null) { concurrentnmapcons = getConcurrentNMapConstructor(); } Object togo = null; if (nmapisJSR166) { togo = JDKReflectiveCache.invokeConstructor(concurrentnmapcons, new Object[] { new Integer(INIT_MAP_SIZE), new Float(0.75f), new Integer(concurrency) }); } else { togo = JDKReflectiveCache.invokeConstructor(concurrentnmapcons); } return (Map) togo; } } }
package org.lightmare.utils.fs.codecs; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.zip.ZipFile; import org.lightmare.jpa.datasource.FileParsers; import org.lightmare.scannotation.AnnotationDB; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.IOUtils; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.fs.FileType; import org.lightmare.utils.fs.FileUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; /** * Utility class for checking jar, ear and zip files or ear and jar directories * from application server deployments (jboss) read contents and etc. * * @author levan * @since 0.0.83-SNAPSHOT */ public abstract class ArchiveUtils { protected Map<URL, URL> xmlURLs; protected Map<String, URL> xmlFiles; protected List<URL> libURLs; protected List<URL> ejbURLs; protected String path; protected File realFile; protected ZipFile earFile; protected List<File> tmpFiles; protected boolean isDirectory; protected boolean xmlFromJar; protected boolean executed; // Cached file types and extensions public static final String JAR = "jar"; public static final String JAR_FILE_EXT = ".jar"; public static final String EAR = "ear"; public static final String EAR_FILE_EXT = ".ear"; public static final String CLASS_FILE_EXT = ".class"; public static final String LIB = "lib"; public static final String LIB_WITH_DELIM = "lib/"; public static final String PERSISTENCE_XML = "persistence.xml"; public static final String APPLICATION_XML_PATH = "META-INF/application.xml"; public static final char ARCHIVE_URL_DELIM = '!'; public static final String FILE_SEPARATOR = File.separator; // Application descriptor XML file tags public static final String EJB_TAG_NAME = "ejb"; public ArchiveUtils(String path) { this.path = path; realFile = new File(path); isDirectory = realFile.isDirectory(); } public ArchiveUtils(File file) { this.path = file.getPath(); realFile = file; isDirectory = realFile.isDirectory(); } public ArchiveUtils(URL url) throws IOException { this.path = url.toString(); try { realFile = new File(url.toURI()); } catch (URISyntaxException ex) { throw new IOException(ex); } isDirectory = realFile.isDirectory(); } /** * Gets files type * * @return {@link FileType} */ public abstract FileType getType(); /** * Ensures that all temporary files will be removed at finish of program * * @param file */ protected void ensureTmpFile(File file) { file.deleteOnExit(); } public boolean isExecuted() { return executed; } public boolean notExecuted() { return ObjectUtils.notTrue(executed); } public void setXmlFromJar(boolean xmlFromJar) { this.xmlFromJar = xmlFromJar; } public Map<URL, URL> getXmlURLs() { if (xmlURLs == null) { xmlURLs = new HashMap<URL, URL>(); } return xmlURLs; } public Map<String, URL> getXmlFiles() { if (xmlFiles == null) { xmlFiles = new HashMap<String, URL>(); } return xmlFiles; } public List<URL> getLibURLs() { if (libURLs == null) { libURLs = new ArrayList<URL>(); } return libURLs; } public List<URL> getEjbURLs() { if (ejbURLs == null) { ejbURLs = new ArrayList<URL>(); } return ejbURLs; } public ZipFile getEarFile() throws IOException { if (earFile == null) { earFile = new ZipFile(path); } return earFile; } /** * Gets appropriated {@link FileType} for passed {@link File} instance * * @param appFile * @return {@link FileType} */ private static FileType getType(File appFile) { FileType fileType; String appPath = appFile.getPath(); if (appFile.isDirectory() && appPath.endsWith(EAR_FILE_EXT)) { fileType = FileType.EDIR; } else if (appPath.endsWith(EAR_FILE_EXT)) { fileType = FileType.EAR; } else if (appPath.endsWith(JAR_FILE_EXT)) { fileType = FileType.JAR; } else { boolean isEarDir = FileUtils.checkOnEarDir(appFile); if (isEarDir) { fileType = FileType.EDIR; } else { fileType = FileType.DIR; } } return fileType; } /** * Gets appropriated {@link ArchiveUtils} implementation for passed * {@link URL} and {@link FileType} parameters * * @param url * @param fileType * @return {@link ArchiveUtils} * @throws IOException */ public static ArchiveUtils getAppropriatedType(URL url, FileType fileType) throws IOException { ArchiveUtils ioUtils; File appFile; try { appFile = new File(url.toURI()); } catch (URISyntaxException ex) { throw new IOException(ex); } FileType typToCheck = fileType; if (fileType == null) { typToCheck = getType(appFile); } if (typToCheck.equals(FileType.EDIR)) { ioUtils = new DirUtils(appFile); } else if (typToCheck.equals(FileType.EAR)) { ioUtils = new ExtUtils(appFile); } else if (typToCheck.equals(FileType.JAR)) { ioUtils = new JarUtils(appFile); } else if (typToCheck.equals(FileType.DIR)) { ioUtils = new SimpleUtils(appFile); } else { ioUtils = null; } return ioUtils; } /** * Gets appropriated {@link ArchiveUtils} implementation for passed * {@link URL} parameter * * @param url * @return {@link ArchiveUtils} * @throws IOException */ public static ArchiveUtils getAppropriatedType(URL url) throws IOException { ArchiveUtils ioUtils = getAppropriatedType(url, null); return ioUtils; } /** * Finds persistence.xml {@link URL} by class name * * @param classOwnersFiles * @param className * @return {@link URL} */ public URL getAppropriatedURL(Map<String, String> classOwnersFiles, String className) { URL xmlURL; String jarName = classOwnersFiles.get(className); if (jarName == null || jarName.isEmpty()) { xmlURL = null; } else { xmlURL = getXmlFiles().get(jarName); } return xmlURL; } /** * Finds persistence.xml {@link URL} by class name * * @param annotationDB * @param className * @return {@link URL} */ public URL getAppropriatedURL(AnnotationDB annotationDB, String className) { URL xmlURL; Map<String, String> classOwnersFiles = annotationDB .getClassOwnersFiles(); xmlURL = getAppropriatedURL(classOwnersFiles, className); return xmlURL; } /** * Parses application configuration XML file {@link InputStream} instance * * @param xmlStream * @return {@link Set}<code><String></code> * @throws IOException */ public Set<String> appXmlParser(InputStream xmlStream) throws IOException { Set<String> ejbNames = new HashSet<String>(); try { Document document = FileParsers.parse(xmlStream); NodeList nodeList = document.getElementsByTagName(EJB_TAG_NAME); String ejbName; for (int i = 0; i < nodeList.getLength(); i++) { Element ejbElement = (Element) nodeList.item(i); ejbName = FileParsers.getContext(ejbElement); if (ObjectUtils.notNull(ejbName)) { ejbNames.add(ejbName); } } } finally { IOUtils.close(xmlStream); } return ejbNames; } public Set<String> appXmlParser() throws IOException { Set<String> jarNames; InputStream stream = earReader(); jarNames = appXmlParser(stream); return jarNames; } public abstract InputStream earReader() throws IOException; public void readEntries() throws IOException { InputStream xmlStream = earReader(); Set<String> jarNames = appXmlParser(xmlStream); extractEjbJars(jarNames); } /** * Gets {@link URL}s in {@link List} for EJB library files from ear * {@link File} * * @throws IOException */ public abstract void getEjbLibs() throws IOException; public abstract void extractEjbJars(Set<String> jarNames) throws IOException; public abstract boolean checkOnOrm(String jarName) throws IOException; /** * Scans project directory for class or jar files and persistence.xml (uses * for development process) * * @param files * @throws MalformedURLException */ public void scanDirectory(File... files) throws MalformedURLException { File parentFile; if (CollectionUtils.valid(files)) { parentFile = CollectionUtils.getFirst(files); } else { parentFile = realFile; } File[] subFiles = parentFile.listFiles(); String fileName; URL fileURL; for (File subFile : subFiles) { fileName = subFile.getName(); if (subFile.isDirectory()) { scanDirectory(subFile); } else if (fileName.endsWith(JAR_FILE_EXT) || fileName.endsWith(CLASS_FILE_EXT)) { fileURL = subFile.toURI().toURL(); getEjbURLs().add(fileURL); getLibURLs().add(fileURL); } else if (fileName.equals(PERSISTENCE_XML)) { fileURL = subFile.toURI().toURL(); getXmlURLs().put(realFile.toURI().toURL(), fileURL); } } } protected abstract void scanArchive(Object... args) throws IOException; public void scan(Object... args) throws IOException { scanArchive(args); executed = Boolean.TRUE; } public URL[] getLibs() { URL[] urls; if (libURLs == null) { urls = null; } else { urls = CollectionUtils.toArray(libURLs, URL.class); } return urls; } public URL[] getEjbs() { URL[] urls; if (ejbURLs == null) { urls = null; } else { urls = CollectionUtils.toArray(ejbURLs, URL.class); } return urls; } public URL[] getURLs() { URL[] urls; List<URL> fullURLs = new ArrayList<URL>(); if (ObjectUtils.notNull(ejbURLs)) { fullURLs.addAll(ejbURLs); } if (ObjectUtils.notNull(libURLs)) { fullURLs.addAll(libURLs); } urls = CollectionUtils.toArray(fullURLs, URL.class); return urls; } protected List<File> getForAddTmpFiles() { if (tmpFiles == null) { tmpFiles = new ArrayList<File>(); } return tmpFiles; } /** * Saves temporary files at cache * * @param tmpFile */ protected void addTmpFile(File tmpFile) { ensureTmpFile(tmpFile); getForAddTmpFiles().add(tmpFile); } public List<File> getTmpFiles() { return tmpFiles; } }
package org.perfcake.pc4idea.editor; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.command.UndoConfirmationPolicy; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.colors.EditorColorsManager; import com.intellij.openapi.editor.event.DocumentAdapter; import com.intellij.openapi.editor.event.DocumentEvent; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.fileEditor.impl.text.TextEditorProvider; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileAdapter; import com.intellij.openapi.vfs.VirtualFileEvent; import com.intellij.ui.JBSplitter; import com.intellij.ui.ScrollPaneFactory; import com.intellij.ui.treeStructure.Tree; import org.jetbrains.annotations.NotNull; import org.perfcake.PerfCakeConst; import org.perfcake.model.Scenario; import org.perfcake.pc4idea.editor.gui.*; import org.xml.sax.SAXException; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.xml.XMLConstants; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import java.awt.*; import java.awt.datatransfer.StringSelection; import java.awt.datatransfer.Transferable; import java.io.File; public class PerfCakeEditorGUI extends JPanel { private static final Logger LOG = Logger.getInstance("#org.perfcake.pc4idea.editor.PerfCakeEditorGUI"); private final Project project; private final Module module; @NotNull private final VirtualFile file; private final ScenarioVirtualFileListener scenarioVirtualFileListener; private final Document document; private final ScenarioDocumentListener scenarioDocumentListener; // private PsiFile psiFile; private final FileEditor xmlEditor; private Scenario scenarioModel; private boolean documentWasModified;/*TODO*/ private boolean isEditorValid;/*TODO*/ private JTabbedPane tabbedPane; private JComponent tabDesignerComponent; private JComponent tabSourceComponent; private JBSplitter splitterDesigner; private JPanel panelDesignerMenu; private JScrollPane scrollPaneDesignerMenu; private JPanel panelDesignerScenario; private JScrollPane scrollPaneDesignerScenario; private JTree treeAdditiveCompsForScenario; private AbstractPanel panelGenerator; private AbstractPanel panelSender; private AbstractPanel panelMessages; private AbstractPanel panelValidation; private AbstractPanel panelReporting; private AbstractPanel panelProperties; PerfCakeEditorGUI(Project project, @NotNull final Module module, @NotNull final VirtualFile file) { LOG.assertTrue(file.isValid()); this.project = project; this.module = module; this.file = file; scenarioVirtualFileListener = new ScenarioVirtualFileListener(); this.file.getFileSystem().addVirtualFileListener(scenarioVirtualFileListener); document = FileDocumentManager.getInstance().getDocument(this.file); LOG.assertTrue(document!=null); scenarioDocumentListener = new ScenarioDocumentListener(); document.addDocumentListener(scenarioDocumentListener); //psiFile = PsiManager.getInstance(project).findFile(file); xmlEditor = TextEditorProvider.getInstance().createEditor(project, this.file); /*TODO first assert accept then create*/ documentWasModified = false; loadScenario(); // isEditorValid = true /*TODO*/ // LOG.assertTrue(isEditorValid); initComponents(); setDesignerComponents(); GridLayout layout = new GridLayout(1,1); this.setLayout(layout); this.add(tabbedPane,new GridLayout(1,1)); } private void initComponents() { tabbedPane = new JTabbedPane(); tabDesignerComponent = new JPanel(new GridLayout(1,1)); tabSourceComponent = xmlEditor.getComponent(); splitterDesigner = new JBSplitter(false); panelDesignerMenu = new JPanel(); panelDesignerScenario = new JPanel(); treeAdditiveCompsForScenario = new Tree(new DefaultTreeModel(new DefaultMutableTreeNode("root"))); panelGenerator = new GeneratorPanel(new ScenarioEvent()); panelSender = new SenderPanel(new ScenarioEvent()); panelMessages = new MessagesPanel(new ScenarioEvent()); panelValidation = new ValidationPanel(new ScenarioEvent()); panelReporting = new ReportingPanel(new ScenarioEvent()); panelProperties = new PropertiesPanel(new ScenarioEvent()); tabbedPane.addTab("Designer", tabDesignerComponent); tabbedPane.addTab("Source", tabSourceComponent); tabbedPane.setTabPlacement(JTabbedPane.BOTTOM); tabbedPane.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { if (tabbedPane.getSelectedIndex() == 0){ if (documentWasModified){ FileDocumentManager.getInstance().saveDocument(document); /*TODO overit validitu scenaria*/ setDesignerComponents(); documentWasModified = false; } } if (tabbedPane.getSelectedIndex() == 1){ /*TODO save scenario from designer*/ } } }); tabDesignerComponent.add(splitterDesigner); scrollPaneDesignerScenario = ScrollPaneFactory.createScrollPane(panelDesignerScenario); /*TODO unc.*///scrollPaneDesignerScenario.setMinimumSize(new Dimension(400, 0)); scrollPaneDesignerMenu = ScrollPaneFactory.createScrollPane(panelDesignerMenu); scrollPaneDesignerMenu.setMinimumSize(new Dimension(100, 0)); splitterDesigner.setFirstComponent(scrollPaneDesignerMenu); splitterDesigner.setSecondComponent(scrollPaneDesignerScenario); splitterDesigner.setProportion(0.15f); GroupLayout panelPCCompsMenuLayout = new GroupLayout(panelDesignerMenu); panelDesignerMenu.setLayout(panelPCCompsMenuLayout); panelPCCompsMenuLayout.setVerticalGroup(panelPCCompsMenuLayout.createSequentialGroup().addComponent(treeAdditiveCompsForScenario)); panelPCCompsMenuLayout.setHorizontalGroup(panelPCCompsMenuLayout.createSequentialGroup().addComponent(treeAdditiveCompsForScenario)); panelDesignerMenu.setBackground(EditorColorsManager.getInstance().getGlobalScheme().getDefaultBackground()); DefaultMutableTreeNode root = (DefaultMutableTreeNode) treeAdditiveCompsForScenario.getModel().getRoot(); DefaultMutableTreeNode messages = new DefaultMutableTreeNode("Messages"); messages.add(new DefaultMutableTreeNode("Message")); /*TODO from classpath*/ root.add(messages); DefaultMutableTreeNode validators = new DefaultMutableTreeNode("Validators"); validators.add(new DefaultMutableTreeNode("DictionaryValidator")); validators.add(new DefaultMutableTreeNode("RegExpValidator")); validators.add(new DefaultMutableTreeNode("RulesValidator")); validators.add(new DefaultMutableTreeNode("ScriptValidator")); root.add(validators); DefaultMutableTreeNode reporters = new DefaultMutableTreeNode("Reporters"); reporters.add(new DefaultMutableTreeNode("ThroughputStatsReporter")); reporters.add(new DefaultMutableTreeNode("MemoryUsageReporter")); reporters.add(new DefaultMutableTreeNode("ResponseTimeStatsReporter")); reporters.add(new DefaultMutableTreeNode("WarmUpReporter")); reporters.add(new DefaultMutableTreeNode("ThroughputStatsReporter")); root.add(reporters); DefaultMutableTreeNode destinations = new DefaultMutableTreeNode("Destinations"); destinations.add(new DefaultMutableTreeNode("ConsoleDestination")); destinations.add(new DefaultMutableTreeNode("CsvDestination")); destinations.add(new DefaultMutableTreeNode("Log4jDestination")); root.add(destinations); DefaultMutableTreeNode properties = new DefaultMutableTreeNode("Properties"); properties.add(new DefaultMutableTreeNode("Property")); root.add(properties); DefaultMutableTreeNode connections = new DefaultMutableTreeNode("Connections"); connections.add(new DefaultMutableTreeNode("Attach validator")); root.add(connections); treeAdditiveCompsForScenario.expandRow(0); treeAdditiveCompsForScenario.setRootVisible(false); treeAdditiveCompsForScenario.setOpaque(false); treeAdditiveCompsForScenario.setDragEnabled(true); treeAdditiveCompsForScenario.setTransferHandler(new TransferHandler(){ @Override public int getSourceActions(JComponent c) { return COPY; } @Override public Transferable createTransferable(JComponent c) { DefaultMutableTreeNode node = ((DefaultMutableTreeNode)((JTree)c).getLastSelectedPathComponent()); if (!node.isLeaf()){ return null; } else { return new StringSelection(node.toString()); } } }); panelDesignerScenario.setBackground(EditorColorsManager.getInstance().getGlobalScheme().getDefaultBackground()); GroupLayout panelPCCompsDesignerLayout = new GroupLayout(panelDesignerScenario); panelDesignerScenario.setLayout(panelPCCompsDesignerLayout); panelPCCompsDesignerLayout.setHorizontalGroup( panelPCCompsDesignerLayout.createParallelGroup() .addComponent(panelGenerator) .addComponent(panelSender) .addGroup(panelPCCompsDesignerLayout.createSequentialGroup() .addGroup(panelPCCompsDesignerLayout.createParallelGroup() .addComponent(panelMessages) .addComponent(panelValidation)) .addComponent(panelReporting)) .addComponent(panelProperties) ); panelPCCompsDesignerLayout.setVerticalGroup( panelPCCompsDesignerLayout.createSequentialGroup() .addComponent(panelGenerator) .addComponent(panelSender) .addGroup(panelPCCompsDesignerLayout.createParallelGroup() .addGroup(panelPCCompsDesignerLayout.createSequentialGroup() .addComponent(panelMessages) .addComponent(panelValidation)) .addComponent(panelReporting)) .addComponent(panelProperties) //.addContainerGap(0, Short.MAX_VALUE) /*TODO decide*/ ); } private void loadScenario(){ try { SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema(this.getClass().getResource("/schemas/" + "perfcake-scenario-" + PerfCakeConst.XSD_SCHEMA_VERSION + ".xsd")); JAXBContext context = JAXBContext.newInstance(org.perfcake.model.Scenario.class); Unmarshaller unmarshaller = context.createUnmarshaller(); unmarshaller.setSchema(schema); scenarioModel = (org.perfcake.model.Scenario) unmarshaller.unmarshal(new File(file.getPath())); } catch (JAXBException e) { System.out.println("ERROR:"+e.getClass().getName()); /*TODO ???*/ e.printStackTrace(); } catch (SAXException e) { System.out.println("ERROR:"+e.getClass().getName()); /*TODO nevalidne xml*/ e.printStackTrace(); } } private void setDesignerComponents(){ /*TODO null pointer exc. if comp. isnt set in xml -> solve in Comps.*/ panelGenerator.setComponentModel(scenarioModel.getGenerator()); panelSender.setComponentModel(scenarioModel.getSender()); panelReporting.setComponentModel(scenarioModel.getReporting()); panelMessages.setComponentModel(scenarioModel.getMessages()); panelValidation.setComponentModel(scenarioModel.getValidation()); panelProperties.setComponentModel(scenarioModel.getProperties()); /*TODO for testing purpose*/System.out.println("designerSet");/*LOG.info("designerSet");*/ } public boolean isModified(){ return false; /*TODO for save?*/ } public boolean isEditorValid(){ return true; /*TODO for not valid xml? skusit false*/ } public JComponent getPreferredFocusedComponent() { return tabbedPane; } public void dispose() { // myConnection.disconnect(); // editor.removeEditorMouseListener(myEditorMouseListener); System.out.println(Thread.activeCount() + " " + Thread.currentThread().getName()); /*TODO threadIntrpted exc.(dispose in porgress?)*/ /*TODO filewatcher?*/ /*TODO save before dispose <- not needed maybe*/ xmlEditor.dispose(); /*TODO maven cant find method*///EditorHistoryManager.getInstance(project).updateHistoryEntry(file, false); file.getFileSystem().removeVirtualFileListener(scenarioVirtualFileListener); document.removeDocumentListener(scenarioDocumentListener); } private final class ScenarioDocumentListener extends DocumentAdapter { @Override public void documentChanged(DocumentEvent e) { /*TODO set modif.=true + rozdelit podla tabbedPane.getSelectedIndex() - source: > designer selected: save Doc. + loadS. + setDes. + modif.=false - designer(=externa zmena?): TODO a) sklbit b) ignore c) desigerWasModif.(+listener): true=ignore false=saveDoc. >vfLisener(true,false) loadS.+setDes.*/ /*TODO for testing purpose*/System.out.println("docChanged"); documentWasModified = true; } } private final class ScenarioVirtualFileListener extends VirtualFileAdapter { @Override public void contentsChanged(@NotNull VirtualFileEvent event){ /*TODO for testing purpose*/System.out.println("virtualFileChanged"); if (documentWasModified) { /*TODO for testing purpose*/System.out.println("scenarioLoaded"); loadScenario(); } } } public final class ScenarioEvent { public void saveGenerator(){ scenarioModel.setGenerator((Scenario.Generator)panelGenerator.getComponentModel()); System.out.println("SAVE: " + scenarioModel.getGenerator().getClazz().toString()); saveScenario(); } public void saveSender(){ scenarioModel.setSender((Scenario.Sender)panelSender.getComponentModel()); System.out.println("SAVE: " + scenarioModel.getSender().getClazz().toString()); saveScenario(); } public void saveProperties(){ scenarioModel.setProperties((Scenario.Properties) panelProperties.getComponentModel()); System.out.println("SAVE: " + scenarioModel.getProperties().getProperty().size()+". properties"); saveScenario(); } public void saveMessages(){ scenarioModel.setMessages((Scenario.Messages) panelMessages.getComponentModel()); System.out.println("SAVE: " + scenarioModel.getMessages().getMessage().size()+". messages"); saveScenario(); } public void saveValidation(){ scenarioModel.setValidation((Scenario.Validation) panelValidation.getComponentModel()); System.out.println("SAVE: " + scenarioModel.getValidation().getValidator().size()+". validators"); saveScenario(); } public void saveReporting(){ scenarioModel.setReporting((Scenario.Reporting) panelReporting.getComponentModel()); System.out.println("SAVE: " + scenarioModel.getReporting().getReporter().size()+". reporters"); saveScenario(); } private void saveScenario(){ /*TODO undo*/ //final Document doc = PsiDocumentManager.getInstance(project).getCachedDocument(psiFile); /*TODO psi rewrte - to doc or doc change*/ /*TODO nejak zablokovat undo z xml editora*/ ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override public void run() { CommandProcessor.getInstance().executeCommand(project,new Runnable() { @Override public void run() { try { SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema(this.getClass().getResource("/schemas/" + "perfcake-scenario-" + PerfCakeConst.XSD_SCHEMA_VERSION + ".xsd")); JAXBContext context = JAXBContext.newInstance(org.perfcake.model.Scenario.class); Marshaller marshaller = context.createMarshaller(); marshaller.setSchema(schema); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); /*TODO pri vynimke zapise prazdny obsah do suboru!!!*/ marshaller.marshal(scenarioModel, new File(file.getPath())); file.refresh(false,false); } catch (JAXBException e) { System.out.println("ERROR:"+e.getClass().getName()); /*TODO ???*/ e.printStackTrace(); } catch (SAXException e) { System.out.println("ERROR:"+e.getClass().getName()); /*TODO nevalidne xml*/ e.printStackTrace(); } } },"string",this, UndoConfirmationPolicy.DEFAULT);/*doc?*/ } }); } } }
package com.jetdrone.vertx.yoke.middleware; import com.jetdrone.vertx.yoke.Middleware; import org.vertx.java.core.Handler; import org.vertx.java.core.http.HttpServerRequest; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Router extends Middleware { private final List<PatternBinding> getBindings = new ArrayList<>(); private final List<PatternBinding> putBindings = new ArrayList<>(); private final List<PatternBinding> postBindings = new ArrayList<>(); private final List<PatternBinding> deleteBindings = new ArrayList<>(); private final List<PatternBinding> optionsBindings = new ArrayList<>(); private final List<PatternBinding> headBindings = new ArrayList<>(); private final List<PatternBinding> traceBindings = new ArrayList<>(); private final List<PatternBinding> connectBindings = new ArrayList<>(); private final List<PatternBinding> patchBindings = new ArrayList<>(); @Override public void handle(YokeHttpServerRequest request, Handler<Object> next) { switch (request.method()) { case "GET": route(request, next, getBindings); break; case "PUT": route(request, next, putBindings); break; case "POST": route(request, next, postBindings); break; case "DELETE": route(request, next, deleteBindings); break; case "OPTIONS": route(request, next, optionsBindings); break; case "HEAD": route(request, next, headBindings); break; case "TRACE": route(request, next, traceBindings); break; case "PATCH": route(request, next, patchBindings); break; case "CONNECT": route(request, next, connectBindings); break; } } /** * Specify a middleware that will be called for a matching HTTP GET * @param pattern The simple pattern * @param handler The middleware to call */ public Router get(String pattern, Middleware handler) { addPattern(pattern, handler, getBindings); return this; } /** * Specify a middleware that will be called for a matching HTTP GET * @param pattern The simple pattern * @param handler The middleware to call */ public Router get(String pattern, final Handler<HttpServerRequest> handler) { return get(pattern, new Middleware() { @Override public void handle(YokeHttpServerRequest request, Handler<Object> next) { handler.handle(request); } }); } /** * Specify a middleware that will be called for a matching HTTP PUT * @param pattern The simple pattern * @param handler The middleware to call */ public Router put(String pattern, Middleware handler) { addPattern(pattern, handler, putBindings); return this; } /** * Specify a middleware that will be called for a matching HTTP PUT * @param pattern The simple pattern * @param handler The middleware to call */ public Router put(String pattern, final Handler<HttpServerRequest> handler) { return put(pattern, new Middleware() { @Override public void handle(YokeHttpServerRequest request, Handler<Object> next) { handler.handle(request); } }); } /** * Specify a middleware that will be called for a matching HTTP POST * @param pattern The simple pattern * @param handler The middleware to call */ public Router post(String pattern, Middleware handler) { addPattern(pattern, handler, postBindings); return this; } /** * Specify a middleware that will be called for a matching HTTP POST * @param pattern The simple pattern * @param handler The middleware to call */ public Router post(String pattern, final Handler<HttpServerRequest> handler) { return post(pattern, new Middleware() { @Override public void handle(YokeHttpServerRequest request, Handler<Object> next) { handler.handle(request); } }); } /** * Specify a middleware that will be called for a matching HTTP DELETE * @param pattern The simple pattern * @param handler The middleware to call */ public Router delete(String pattern, Middleware handler) { addPattern(pattern, handler, deleteBindings); return this; } /** * Specify a middleware that will be called for a matching HTTP DELETE * @param pattern The simple pattern * @param handler The middleware to call */ public Router delete(String pattern, final Handler<HttpServerRequest> handler) { return delete(pattern, new Middleware() { @Override public void handle(YokeHttpServerRequest request, Handler<Object> next) { handler.handle(request); } }); } /** * Specify a middleware that will be called for a matching HTTP OPTIONS * @param pattern The simple pattern * @param handler The middleware to call */ public Router options(String pattern, Middleware handler) { addPattern(pattern, handler, optionsBindings); return this; } /** * Specify a middleware that will be called for a matching HTTP OPTIONS * @param pattern The simple pattern * @param handler The middleware to call */ public Router options(String pattern, final Handler<HttpServerRequest> handler) { return options(pattern, new Middleware() { @Override public void handle(YokeHttpServerRequest request, Handler<Object> next) { handler.handle(request); } }); } /** * Specify a middleware that will be called for a matching HTTP HEAD * @param pattern The simple pattern * @param handler The middleware to call */ public Router head(String pattern, Middleware handler) { addPattern(pattern, handler, headBindings); return this; } /** * Specify a middleware that will be called for a matching HTTP HEAD * @param pattern The simple pattern * @param handler The middleware to call */ public Router head(String pattern, final Handler<HttpServerRequest> handler) { return head(pattern, new Middleware() { @Override public void handle(YokeHttpServerRequest request, Handler<Object> next) { handler.handle(request); } }); } /** * Specify a middleware that will be called for a matching HTTP TRACE * @param pattern The simple pattern * @param handler The middleware to call */ public Router trace(String pattern, Middleware handler) { addPattern(pattern, handler, traceBindings); return this; } /** * Specify a middleware that will be called for a matching HTTP TRACE * @param pattern The simple pattern * @param handler The middleware to call */ public Router trace(String pattern, final Handler<HttpServerRequest> handler) { return trace(pattern, new Middleware() { @Override public void handle(YokeHttpServerRequest request, Handler<Object> next) { handler.handle(request); } }); } /** * Specify a middleware that will be called for a matching HTTP CONNECT * @param pattern The simple pattern * @param handler The middleware to call */ public Router connect(String pattern, Middleware handler) { addPattern(pattern, handler, connectBindings); return this; } /** * Specify a middleware that will be called for a matching HTTP CONNECT * @param pattern The simple pattern * @param handler The middleware to call */ public Router connect(String pattern, final Handler<HttpServerRequest> handler) { return connect(pattern, new Middleware() { @Override public void handle(YokeHttpServerRequest request, Handler<Object> next) { handler.handle(request); } }); } /** * Specify a middleware that will be called for a matching HTTP PATCH * @param pattern The simple pattern * @param handler The middleware to call */ public Router patch(String pattern, Middleware handler) { addPattern(pattern, handler, patchBindings); return this; } /** * Specify a middleware that will be called for a matching HTTP PATCH * @param pattern The simple pattern * @param handler The middleware to call */ public Router patch(String pattern, final Handler<HttpServerRequest> handler) { return patch(pattern, new Middleware() { @Override public void handle(YokeHttpServerRequest request, Handler<Object> next) { handler.handle(request); } }); } /** * Specify a middleware that will be called for all HTTP methods * @param pattern The simple pattern * @param handler The middleware to call */ public Router all(String pattern, Middleware handler) { get(pattern, handler); put(pattern, handler); post(pattern, handler); delete(pattern, handler); options(pattern, handler); head(pattern, handler); trace(pattern, handler); connect(pattern, handler); patch(pattern, handler); return this; } /** * Specify a middleware that will be called for all HTTP methods * @param pattern The simple pattern * @param handler The middleware to call */ public Router all(String pattern, final Handler<HttpServerRequest> handler) { get(pattern, handler); put(pattern, handler); post(pattern, handler); delete(pattern, handler); options(pattern, handler); head(pattern, handler); trace(pattern, handler); connect(pattern, handler); patch(pattern, handler); return this; } /** * Specify a middleware that will be called for a matching HTTP GET * @param regex A regular expression * @param handler The middleware to call */ public Router get(Pattern regex, Middleware handler) { addRegEx(regex, handler, getBindings); return this; } /** * Specify a middleware that will be called for a matching HTTP GET * @param regex A regular expression * @param handler The middleware to call */ public Router get(Pattern regex, final Handler<HttpServerRequest> handler) { return get(regex, new Middleware() { @Override public void handle(YokeHttpServerRequest request, Handler<Object> next) { handler.handle(request); } }); } /** * Specify a middleware that will be called for a matching HTTP PUT * @param regex A regular expression * @param handler The middleware to call */ public Router put(Pattern regex, Middleware handler) { addRegEx(regex, handler, putBindings); return this; } /** * Specify a middleware that will be called for a matching HTTP PUT * @param regex A regular expression * @param handler The middleware to call */ public Router put(Pattern regex, final Handler<HttpServerRequest> handler) { return put(regex, new Middleware() { @Override public void handle(YokeHttpServerRequest request, Handler<Object> next) { handler.handle(request); } }); } /** * Specify a middleware that will be called for a matching HTTP POST * @param regex A regular expression * @param handler The middleware to call */ public Router post(Pattern regex, Middleware handler) { addRegEx(regex, handler, postBindings); return this; } /** * Specify a middleware that will be called for a matching HTTP POST * @param regex A regular expression * @param handler The middleware to call */ public Router post(Pattern regex, final Handler<HttpServerRequest> handler) { return post(regex, new Middleware() { @Override public void handle(YokeHttpServerRequest request, Handler<Object> next) { handler.handle(request); } }); } /** * Specify a middleware that will be called for a matching HTTP DELETE * @param regex A regular expression * @param handler The middleware to call */ public Router delete(Pattern regex, Middleware handler) { addRegEx(regex, handler, deleteBindings); return this; } /** * Specify a middleware that will be called for a matching HTTP DELETE * @param regex A regular expression * @param handler The middleware to call */ public Router delete(Pattern regex, final Handler<HttpServerRequest> handler) { return delete(regex, new Middleware() { @Override public void handle(YokeHttpServerRequest request, Handler<Object> next) { handler.handle(request); } }); } /** * Specify a middleware that will be called for a matching HTTP OPTIONS * @param regex A regular expression * @param handler The middleware to call */ public Router options(Pattern regex, Middleware handler) { addRegEx(regex, handler, optionsBindings); return this; } /** * Specify a middleware that will be called for a matching HTTP OPTIONS * @param regex A regular expression * @param handler The middleware to call */ public Router options(Pattern regex, final Handler<HttpServerRequest> handler) { return options(regex, new Middleware() { @Override public void handle(YokeHttpServerRequest request, Handler<Object> next) { handler.handle(request); } }); } /** * Specify a middleware that will be called for a matching HTTP HEAD * @param regex A regular expression * @param handler The middleware to call */ public Router head(Pattern regex, Middleware handler) { addRegEx(regex, handler, headBindings); return this; } /** * Specify a middleware that will be called for a matching HTTP HEAD * @param regex A regular expression * @param handler The middleware to call */ public Router head(Pattern regex, final Handler<HttpServerRequest> handler) { return head(regex, new Middleware() { @Override public void handle(YokeHttpServerRequest request, Handler<Object> next) { handler.handle(request); } }); } /** * Specify a middleware that will be called for a matching HTTP TRACE * @param regex A regular expression * @param handler The middleware to call */ public Router trace(Pattern regex, Middleware handler) { addRegEx(regex, handler, traceBindings); return this; } /** * Specify a middleware that will be called for a matching HTTP TRACE * @param regex A regular expression * @param handler The middleware to call */ public Router trace(Pattern regex, final Handler<HttpServerRequest> handler) { return trace(regex, new Middleware() { @Override public void handle(YokeHttpServerRequest request, Handler<Object> next) { handler.handle(request); } }); } /** * Specify a middleware that will be called for a matching HTTP CONNECT * @param regex A regular expression * @param handler The middleware to call */ public Router connect(Pattern regex, Middleware handler) { addRegEx(regex, handler, connectBindings); return this; } /** * Specify a middleware that will be called for a matching HTTP CONNECT * @param regex A regular expression * @param handler The middleware to call */ public Router connect(Pattern regex, final Handler<HttpServerRequest> handler) { return connect(regex, new Middleware() { @Override public void handle(YokeHttpServerRequest request, Handler<Object> next) { handler.handle(request); } }); } /** * Specify a middleware that will be called for a matching HTTP PATCH * @param regex A regular expression * @param handler The middleware to call */ public Router patch(Pattern regex, Middleware handler) { addRegEx(regex, handler, patchBindings); return this; } /** * Specify a middleware that will be called for a matching HTTP PATCH * @param regex A regular expression * @param handler The middleware to call */ public Router patch(Pattern regex, final Handler<HttpServerRequest> handler) { return patch(regex, new Middleware() { @Override public void handle(YokeHttpServerRequest request, Handler<Object> next) { handler.handle(request); } }); } /** * Specify a middleware that will be called for all HTTP methods * @param regex A regular expression * @param handler The middleware to call */ public Router all(Pattern regex, Middleware handler) { get(regex, handler); put(regex, handler); post(regex, handler); delete(regex, handler); options(regex, handler); head(regex, handler); trace(regex, handler); connect(regex, handler); patch(regex, handler); return this; } /** * Specify a middleware that will be called for all HTTP methods * @param regex A regular expression * @param handler The middleware to call */ public Router all(Pattern regex, final Handler<HttpServerRequest> handler) { get(regex, handler); put(regex, handler); post(regex, handler); delete(regex, handler); options(regex, handler); head(regex, handler); trace(regex, handler); connect(regex, handler); patch(regex, handler); return this; } private void addPattern(String input, Middleware handler, List<PatternBinding> bindings) { // We need to search for any :<token name> tokens in the String and replace them with named capture groups Matcher m = Pattern.compile(":([A-Za-z][A-Za-z0-9_]*)").matcher(input); StringBuffer sb = new StringBuffer(); Set<String> groups = new HashSet<>(); while (m.find()) { String group = m.group().substring(1); if (groups.contains(group)) { throw new IllegalArgumentException("Cannot use identifier " + group + " more than once in pattern string"); } m.appendReplacement(sb, "(?<$1>[^\\/]+)"); groups.add(group); } m.appendTail(sb); String regex = sb.toString(); PatternBinding binding = new PatternBinding(Pattern.compile(regex), groups, handler); bindings.add(binding); } private void addRegEx(Pattern regex, Middleware handler, List<PatternBinding> bindings) { PatternBinding binding = new PatternBinding(regex, null, handler); bindings.add(binding); } private void route(YokeHttpServerRequest request, Handler<Object> next, List<PatternBinding> bindings) { for (PatternBinding binding: bindings) { Matcher m = binding.pattern.matcher(request.path()); if (m.matches()) { Map<String, String> params = new HashMap<>(m.groupCount()); if (binding.paramNames != null) { // Named params for (String param: binding.paramNames) { params.put(param, m.group(param)); } } else { // Un-named params for (int i = 0; i < m.groupCount(); i++) { params.put("param" + i, m.group(i + 1)); } } request.params().putAll(params); binding.middleware.handle(request, next); return; } } next.handle(null); } private static class PatternBinding { final Pattern pattern; final Middleware middleware; final Set<String> paramNames; private PatternBinding(Pattern pattern, Set<String> paramNames, Middleware middleware) { this.pattern = pattern; this.paramNames = paramNames; this.middleware = middleware; } } }
import java.util.Calendar; import org.csstudio.swt.xygraph.dataprovider.CircularBufferDataProvider; import org.csstudio.swt.xygraph.dataprovider.Sample; import org.csstudio.swt.xygraph.figures.Axis; import org.csstudio.swt.xygraph.figures.ToolbarArmedXYGraph; import org.csstudio.swt.xygraph.figures.Trace; import org.csstudio.swt.xygraph.figures.XYGraph; import org.csstudio.swt.xygraph.figures.Trace.BaseLine; import org.csstudio.swt.xygraph.figures.Trace.ErrorBarType; import org.csstudio.swt.xygraph.figures.Trace.PointStyle; import org.csstudio.swt.xygraph.figures.Trace.TraceType; import org.csstudio.swt.xygraph.linearscale.Range; import org.csstudio.swt.xygraph.linearscale.AbstractScale.LabelSide; import org.csstudio.swt.xygraph.linearscale.LinearScale.Orientation; import org.csstudio.swt.xygraph.undo.ZoomType; import org.csstudio.swt.xygraph.util.XYGraphMediaFactory; import org.eclipse.draw2d.Figure; import org.eclipse.draw2d.KeyEvent; import org.eclipse.draw2d.KeyListener; import org.eclipse.draw2d.LightweightSystem; import org.eclipse.draw2d.MouseEvent; import org.eclipse.draw2d.MouseListener; import org.eclipse.draw2d.XYAnchor; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.graphics.ImageLoader; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Shell; /** * This program simply draw the widget figure on a shell. * <p> * This is a common java program, <b>not</b> a JUnit test. * </p> * @author Xihui Chen * */ public class GraphTest { public static void main(String[] args) { final Shell shell = new Shell(); shell.setSize(800, 500); shell.open(); final LightweightSystem lws = new LightweightSystem(shell); XYGraphTest testFigure = new XYGraphTest(); lws.setContents(testFigure); shell.setText("XY Graph Test"); Display display = Display.getDefault(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } System.out.println(Calendar.getInstance().getTime()); } } class XYGraphTest extends Figure { public Trace trace1; public Trace trace2; public Trace trace3; public XYGraph xyGraph; public Runnable updater; private double updateIndex = 0; private CircularBufferDataProvider trace2Provider; boolean running = false; private long t; private Trace trace4; private ToolbarArmedXYGraph toolbarArmedXYGraph; public XYGraphTest() { xyGraph = new XYGraph(); xyGraph.setTitle("XY Graph Test"); xyGraph.setFont(XYGraphMediaFactory.getInstance().getFont(XYGraphMediaFactory.FONT_TAHOMA)); xyGraph.primaryXAxis.setTitle("Time"); xyGraph.primaryYAxis.setTitle("Amplitude"); xyGraph.primaryXAxis.setRange(new Range(0,200)); xyGraph.primaryXAxis.setDateEnabled(true); xyGraph.primaryYAxis.setAutoScale(true); xyGraph.primaryXAxis.setAutoScale(true); xyGraph.primaryXAxis.setShowMajorGrid(true); xyGraph.primaryYAxis.setShowMajorGrid(true); xyGraph.primaryXAxis.setAutoScaleThreshold(0); Axis x2Axis = new Axis("X-2", false); x2Axis.setTickLableSide(LabelSide.Secondary); //x2Axis.setAutoScale(true); xyGraph.addAxis(x2Axis); Axis y2Axis = new Axis("Log Scale", true); y2Axis.setRange(10, 1000); y2Axis.setLogScale(true); //y2Axis.setAutoScale(true); y2Axis.setForegroundColor(XYGraphMediaFactory.getInstance().getColor(XYGraphMediaFactory.COLOR_PINK)); y2Axis.setTickLableSide(LabelSide.Secondary); xyGraph.addAxis(y2Axis); /* Axis y3Axis = new Axis("Y-3", true); y3Axis.setForegroundColor(XYGraphMediaFactory.getInstance().getColor(XYGraphMediaFactory.COLOR_BLUE)); y3Axis.setTickLableSide(LabelSide.Secondary); y3Axis.setRange(new Range(-2, 3)); y3Axis.setShowMajorGrid(false); y3Axis.setAutoScale(true); xyGraph.addAxis(y3Axis); Axis y4Axis = new Axis("Log Scale", true); y4Axis.setForegroundColor(XYGraphMediaFactory.getInstance().getColor(XYGraphMediaFactory.COLOR_ORANGE)); y4Axis.setShowMajorGrid(false); y4Axis.setRange(new Range(-100, 10000)); y4Axis.setAutoScale(true); y4Axis.setAutoScaleThreshold(0); y4Axis.setLogScale(true); xyGraph.addAxis(y4Axis); //large amount of data test CircularBufferDataProvider trace1Provider = new CircularBufferDataProvider(false); trace1Provider.setBufferSize(100000); double[] xArray = new double[100000]; double[] yArray = new double[100000]; for(int i=0; i<100000; i++){ xArray[i] = i; yArray[i] = Math.random() * i; } trace1Provider.setCurrentXDataArray(xArray); trace1Provider.setCurrentYDataArray(yArray); trace1 = new Trace("Trace1-XY Plot", x2Axis, y2Axis, trace1Provider); trace1.setAntiAliasing(false); trace1.setTraceColor(XYGraphMediaFactory.getInstance().getColor( new RGB(0,64,128))); trace1.setTraceType(TraceType.POINT); trace1.setPointStyle(PointStyle.POINT); trace1.setPointSize(1); xyGraph.addTrace(trace1); */ trace2Provider = new CircularBufferDataProvider(true); trace2Provider.setBufferSize(100); trace2Provider.setUpdateDelay(100); trace2 = new Trace("Trace 2", xyGraph.primaryXAxis, xyGraph.primaryYAxis, trace2Provider); trace2.setDataProvider(trace2Provider); trace2.setTraceType(TraceType.SOLID_LINE); trace2.setLineWidth(1); trace2.setPointStyle(PointStyle.CIRCLE); trace2.setPointSize(1); trace2.setBaseLine(BaseLine.NEGATIVE_INFINITY); trace2.setAreaAlpha(100); trace2.setAntiAliasing(true); trace2.setErrorBarEnabled(true); //trace2.setDrawYErrorInArea(true); trace2.setYErrorBarType(ErrorBarType.BOTH); trace2.setXErrorBarType(ErrorBarType.NONE); trace2.setErrorBarCapWidth(3); xyGraph.addTrace(trace2); final CircularBufferDataProvider trace3Provider = new CircularBufferDataProvider(true); trace3 = new Trace("Trace3", xyGraph.primaryXAxis, xyGraph.primaryYAxis, trace3Provider); trace3.setPointStyle(PointStyle.XCROSS); trace3.setTraceType(TraceType.BAR); trace3.setLineWidth(4); trace3Provider.setUpdateDelay(100); xyGraph.addTrace(trace3); final CircularBufferDataProvider trace4Provider = new CircularBufferDataProvider(false); trace4 = new Trace("Trace 4-Lissajous", x2Axis, y2Axis, trace4Provider); trace4.setPointStyle(PointStyle.POINT); trace4.setPointSize(2); trace4Provider.setUpdateDelay(100); trace4Provider.setBufferSize(100); xyGraph.addTrace(trace4); toolbarArmedXYGraph = new ToolbarArmedXYGraph(xyGraph); add(toolbarArmedXYGraph); //add key listener to XY-Graph. The key pressing will only be monitored when the //graph gains focus. toolbarArmedXYGraph.addMouseListener(new MouseListener.Stub(){ @Override public void mousePressed(MouseEvent me) { toolbarArmedXYGraph.requestFocus(); } }); toolbarArmedXYGraph.addKeyListener(new KeyListener.Stub(){ @Override public void keyPressed(KeyEvent ke) { if(ke.getState() == SWT.CONTROL && ke.keycode == 'z'){ xyGraph.getOperationsManager().undo(); } if(ke.getState() == SWT.CONTROL && ke.keycode == 'y'){ xyGraph.getOperationsManager().redo(); } if(ke.getState() == SWT.CONTROL && ke.keycode == 'x'){ xyGraph.performAutoScale(); } if(ke.getState() == SWT.CONTROL && ke.keycode == 's'){ ImageLoader loader = new ImageLoader(); loader.data = new ImageData[]{xyGraph.getImage().getImageData()}; FileDialog dialog = new FileDialog(Display.getDefault().getShells()[0], SWT.SAVE); dialog .setFilterNames(new String[] {"PNG Files", "All Files (*.*)" }); dialog.setFilterExtensions(new String[] { "*.png", "*.*" }); // Windows String path = dialog.open(); if(path != null && !path.equals("")) loader.save(path, SWT.IMAGE_PNG); } if(ke.getState() == SWT.CONTROL && ke.keycode + 'a' -97 == 't'){ switch (xyGraph.getZoomType()) { case RUBBERBAND_ZOOM: xyGraph.setZoomType(ZoomType.HORIZONTAL_ZOOM); break; case HORIZONTAL_ZOOM: xyGraph.setZoomType(ZoomType.VERTICAL_ZOOM); break; case VERTICAL_ZOOM: xyGraph.setZoomType(ZoomType.ZOOM_IN); break; case ZOOM_IN: xyGraph.setZoomType(ZoomType.ZOOM_OUT); break; case ZOOM_OUT: xyGraph.setZoomType(ZoomType.PANNING); break; case PANNING: xyGraph.setZoomType(ZoomType.NONE); break; case NONE: xyGraph.setZoomType(ZoomType.RUBBERBAND_ZOOM); break; default: break; } } } }); updater = new Runnable(){ public void run() { t+=60000; trace3Provider.setCurrentYData(Math.cos(updateIndex), t); if((updateIndex >= 10 && updateIndex <=10.5) || (updateIndex >= 20 && updateIndex <=20.2) ){ trace2Provider.addSample(new Sample(t, Double.NaN)); running = false; } else{ Sample sampe = new Sample(t, Math.sin(updateIndex), 0.1* Math.random(), 0.1*Math.random(), t*0.0000001* Math.random(),t*0.0000001* Math.random()); sampe.setInfo("sdfsf"); trace2Provider.addSample(sampe); } trace2Provider.setCurrentYDataTimestamp(t); trace4Provider.setCurrentXData(Math.sin(updateIndex + 10)*20+50); trace4Provider.setCurrentYData(Math.cos(updateIndex)*30+50); updateIndex+=0.1; if(running) Display.getCurrent().timerExec(1, this); } }; Display.getCurrent().timerExec(1000, updater); System.out.println(Calendar.getInstance().getTime()); running = true; t = Calendar.getInstance().getTimeInMillis(); } @Override protected void layout() { toolbarArmedXYGraph.setBounds(bounds.getCopy().shrink(5, 5)); super.layout(); } }
package org.lightmare.utils.fs.codecs; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.zip.ZipFile; import org.lightmare.jpa.datasource.FileParsers; import org.lightmare.scannotation.AnnotationDB; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.IOUtils; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.fs.FileType; import org.lightmare.utils.fs.FileUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; /** * Utility class for checking jar, ear and zip files or ear and jar directories * from application server deployments (jboss) read contents and etc. * * @author levan * @since 0.0.83-SNAPSHOT */ public abstract class ArchiveUtils { protected Map<URL, URL> xmlURLs; protected Map<String, URL> xmlFiles; protected List<URL> libURLs; protected List<URL> ejbURLs; protected String path; protected File realFile; protected ZipFile earFile; protected List<File> tmpFiles; protected boolean isDirectory; protected boolean xmlFromJar; protected boolean executed; // Cached file types and extensions public static final String JAR = "jar"; public static final String JAR_FILE_EXT = ".jar"; public static final String EAR = "ear"; public static final String EAR_FILE_EXT = ".ear"; public static final String CLASS_FILE_EXT = ".class"; public static final String LIB = "lib"; public static final String LIB_WITH_DELIM = "lib/"; public static final String PERSISTENCE_XML = "persistence.xml"; public static final String APPLICATION_XML_PATH = "META-INF/application.xml"; public static final char ARCHIVE_URL_DELIM = '!'; public static final String FILE_SEPARATOR = File.separator; // Application descriptor XML file tags public static final String EJB_TAG_NAME = "ejb"; public ArchiveUtils(String path) { this.path = path; realFile = new File(path); isDirectory = realFile.isDirectory(); } public ArchiveUtils(File file) { this.path = file.getPath(); realFile = file; isDirectory = realFile.isDirectory(); } public ArchiveUtils(URL url) throws IOException { this.path = url.toString(); try { realFile = new File(url.toURI()); } catch (URISyntaxException ex) { throw new IOException(ex); } isDirectory = realFile.isDirectory(); } public abstract FileType getType(); /** * Ensures that all temporary files will be removed at finish of program * * @param file */ protected void ensureTmpFile(File file) { file.deleteOnExit(); } public boolean isExecuted() { return executed; } public boolean notExecuted() { return ObjectUtils.notTrue(executed); } public void setXmlFromJar(boolean xmlFromJar) { this.xmlFromJar = xmlFromJar; } public Map<URL, URL> getXmlURLs() { if (xmlURLs == null) { xmlURLs = new HashMap<URL, URL>(); } return xmlURLs; } public Map<String, URL> getXmlFiles() { if (xmlFiles == null) { xmlFiles = new HashMap<String, URL>(); } return xmlFiles; } public List<URL> getLibURLs() { if (libURLs == null) { libURLs = new ArrayList<URL>(); } return libURLs; } public List<URL> getEjbURLs() { if (ejbURLs == null) { ejbURLs = new ArrayList<URL>(); } return ejbURLs; } public ZipFile getEarFile() throws IOException { if (earFile == null) { earFile = new ZipFile(path); } return earFile; } private static FileType getType(File appFile) { FileType fileType; String appPath = appFile.getPath(); if (appFile.isDirectory() && appPath.endsWith(EAR_FILE_EXT)) { fileType = FileType.EDIR; } else if (appPath.endsWith(EAR_FILE_EXT)) { fileType = FileType.EAR; } else if (appPath.endsWith(JAR_FILE_EXT)) { fileType = FileType.JAR; } else { boolean isEarDir = FileUtils.checkOnEarDir(appFile); if (isEarDir) { fileType = FileType.EDIR; } else { fileType = FileType.DIR; } } return fileType; } public static ArchiveUtils getAppropriatedType(URL url, FileType fileType) throws IOException { ArchiveUtils ioUtils; File appFile; try { appFile = new File(url.toURI()); } catch (URISyntaxException ex) { throw new IOException(ex); } FileType typToCheck = fileType; if (fileType == null) { typToCheck = getType(appFile); } if (typToCheck.equals(FileType.EDIR)) { ioUtils = new DirUtils(appFile); } else if (typToCheck.equals(FileType.EAR)) { ioUtils = new ExtUtils(appFile); } else if (typToCheck.equals(FileType.JAR)) { ioUtils = new JarUtils(appFile); } else if (typToCheck.equals(FileType.DIR)) { ioUtils = new SimpleUtils(appFile); } else { ioUtils = null; } return ioUtils; } public static ArchiveUtils getAppropriatedType(URL url) throws IOException { ArchiveUtils ioUtils = getAppropriatedType(url, null); return ioUtils; } /** * Finds persistence.xml {@link URL} by class name * * @param classOwnersFiles * @param className * @return {@link URL} */ public URL getAppropriatedURL(Map<String, String> classOwnersFiles, String className) { URL xmlURL; String jarName = classOwnersFiles.get(className); if (jarName == null || jarName.isEmpty()) { xmlURL = null; } else { xmlURL = getXmlFiles().get(jarName); } return xmlURL; } /** * Finds persistence.xml {@link URL} by class name * * @param annotationDB * @param className * @return {@link URL} */ public URL getAppropriatedURL(AnnotationDB annotationDB, String className) { Map<String, String> classOwnersFiles = annotationDB .getClassOwnersFiles(); URL xmlURL = getAppropriatedURL(classOwnersFiles, className); return xmlURL; } public Set<String> appXmlParser(InputStream xmlStream) throws IOException { Set<String> ejbNames = new HashSet<String>(); try { Document document = FileParsers.parse(xmlStream); NodeList nodeList = document.getElementsByTagName(EJB_TAG_NAME); String ejbName; for (int i = 0; i < nodeList.getLength(); i++) { Element ejbElement = (Element) nodeList.item(i); ejbName = FileParsers.getContext(ejbElement); if (ObjectUtils.notNull(ejbName)) { ejbNames.add(ejbName); } } } finally { IOUtils.close(xmlStream); } return ejbNames; } public Set<String> appXmlParser() throws IOException { InputStream stream = earReader(); Set<String> jarNames = appXmlParser(stream); return jarNames; } public abstract InputStream earReader() throws IOException; public void readEntries() throws IOException { InputStream xmlStream = earReader(); Set<String> jarNames = appXmlParser(xmlStream); extractEjbJars(jarNames); } /** * Gets {@link URL}s in {@link List} for EJB library files from ear * {@link File} * * @throws IOException */ public abstract void getEjbLibs() throws IOException; public abstract void extractEjbJars(Set<String> jarNames) throws IOException; public abstract boolean checkOnOrm(String jarName) throws IOException; /** * Scans project directory for class or jar files and persistence.xml (uses * for development process) * * @param files * @throws MalformedURLException */ public void scanDirectory(File... files) throws MalformedURLException { File parentFile; if (CollectionUtils.valid(files)) { parentFile = CollectionUtils.getFirst(files); } else { parentFile = realFile; } File[] subFiles = parentFile.listFiles(); String fileName; URL fileURL; for (File subFile : subFiles) { fileName = subFile.getName(); if (subFile.isDirectory()) { scanDirectory(subFile); } else if (fileName.endsWith(JAR_FILE_EXT) || fileName.endsWith(CLASS_FILE_EXT)) { fileURL = subFile.toURI().toURL(); getEjbURLs().add(fileURL); getLibURLs().add(fileURL); } else if (fileName.equals(PERSISTENCE_XML)) { fileURL = subFile.toURI().toURL(); getXmlURLs().put(realFile.toURI().toURL(), fileURL); } } } protected abstract void scanArchive(Object... args) throws IOException; public void scan(Object... args) throws IOException { scanArchive(args); executed = Boolean.TRUE; } public URL[] getLibs() { URL[] urls; if (libURLs == null) { urls = null; } else { urls = CollectionUtils.toArray(libURLs, URL.class); } return urls; } public URL[] getEjbs() { URL[] urls; if (ejbURLs == null) { urls = null; } else { urls = CollectionUtils.toArray(ejbURLs, URL.class); } return urls; } public URL[] getURLs() { URL[] urls; List<URL> fullURLs = new ArrayList<URL>(); if (ObjectUtils.notNull(ejbURLs)) { fullURLs.addAll(ejbURLs); } if (ObjectUtils.notNull(libURLs)) { fullURLs.addAll(libURLs); } urls = CollectionUtils.toArray(fullURLs, URL.class); return urls; } protected List<File> getForAddTmpFiles() { if (tmpFiles == null) { tmpFiles = new ArrayList<File>(); } return tmpFiles; } /** * Saves temporary files at cache * * @param tmpFile */ protected void addTmpFile(File tmpFile) { ensureTmpFile(tmpFile); getForAddTmpFiles().add(tmpFile); } public List<File> getTmpFiles() { return tmpFiles; } }
package org.procrastinationpatients.tts.entities; import javafx.geometry.Point2D; import javafx.scene.canvas.GraphicsContext; import javafx.scene.paint.Color; import org.procrastinationpatients.tts.source.StaticConfig; import org.procrastinationpatients.tts.utils.DrawUtils; import org.procrastinationpatients.tts.utils.RandomUtils; import sun.text.normalizer.VersionInfo; import java.util.LinkedList; import java.util.List; public abstract class Link extends IdentifiableObject implements Visible, FunctionalObject { private Dot a; private Dot b; private int lane_Length; private Lane[] lanes; public Link(Integer id) { super(id); this.lanes = new Lane[6]; for (int i = 0; i < 6; i++) { lanes[i] = new Lane(this,i); } } public Lane[] getLanes() { return lanes; } public int getLane_Length(){ return this.lane_Length; } public void setLanes(Lane[] lanes) { this.lanes = lanes; if(lanes.length > 0) this.lane_Length = lanes[0].getLength() ; else this.lane_Length = 0 ; } public Dot getA() { return a; } public void setA(Dot a) { this.a = a; refreshLane(); } public Dot getB() { return b; } public void setB(Dot b) { this.b = b; refreshLane(); } protected abstract void refreshLane(); public int change_Line_NUMBER(int v_line) { switch (v_line) { case 0: v_line = 1; break; case 1: v_line = 2; break; case 2: v_line = 2; break; case 3: v_line = 3; break; case 4: v_line = 3; break; case 5: v_line = 4; } return v_line; } @Override public int changeLine(Vehicle vehicle) { int v_line = vehicle.getCur_line(); int v_location = vehicle.getCur_Loc(); int new_line = change_Line_NUMBER(v_line); if(this.lanes[new_line].getVehicles()[v_location] == null){ this.lanes[v_line].removeVehicle(vehicle) ; vehicle.setCur_Loc(v_location); vehicle.setCur_line(new_line); vehicle.setOn_Link(this.lanes[new_line]); this.lanes[new_line].addChangeLineVehicle(vehicle); return new_line; } return 0; } @Override public void toGoalLine(Vehicle vehicle) { int v_line = vehicle.getCur_line(); int v_goal_line = vehicle.getGoal_line() ; int v_location = vehicle.getCur_Loc(); if (!hasVehicle(v_goal_line, v_location)) { lanes[v_line].removeVehicle(vehicle) ; vehicle.setCur_line(v_goal_line); vehicle.setOn_Link(lanes[v_goal_line]); lanes[v_goal_line].addChangeLineVehicle(vehicle) ; } } public boolean hasVehicle(int line , int loc){ if(this.lanes[line].getVehicles()[loc] != null) return true ; else return false ; } @Override public void drawDynamicGraphic(GraphicsContext gc) { Integer pointCount = 0; for (Lane lane : this.getLanes()) { for (int i = 0; i < lane.getLength(); i++) { for (Barrier barrier : lane.getBarriers()) { if (i > barrier.getStart() && i < barrier.getEnd()) { DrawUtils.drawBarrier(gc, lane.getVehiclePositions()[i], 8, Color.BLACK); } } if (lane.getVehicles()[i] != null) { if (lane.getVehiclePositions()[i] == null) { continue; } if (StaticConfig.DEBUG_MODE) { DrawUtils.drawText(gc, lane.getVehiclePositions()[i].getX(), lane.getVehiclePositions()[i].getY() - 11D, Color.RED, String.format("%s(%s,%s)", lane.getVehicles()[i].getId(), (int) lane.getVehiclePositions()[i].getX(), (int) lane.getVehiclePositions()[i].getY()), 10D); } DrawUtils.drawBallAtCoordinate(gc, lane.getVehiclePositions()[i], 4, Color.RED); System.out.println("Drawing:::+++++++" + lane.getVehicles()[i].getId() + "-->"+ lane.getVehicles()[i].getCur_Loc()); pointCount++; } } } //Debug if (StaticConfig.DEBUG_MODE) { DrawUtils.drawText(gc, new Point2D( (this.getA().getPosition().getX() + this.getB().getPosition().getX()) / 2, (this.getA().getPosition().getY() + this.getB().getPosition().getY()) / 2 ), Color.GREEN, String.format("Drew:%s", pointCount), 11D ); } } public LinkedList<Vehicle> vehiclesData(int i){ return lanes[i].getAllVehicles(); } }
package org.literacyapp.tasks; import java.util.List; import java.util.Locale; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.json.JSONArray; import org.json.JSONObject; import org.literacyapp.dao.ContributorDao; import org.literacyapp.model.Contributor; import org.literacyapp.model.enums.Environment; import org.literacyapp.model.enums.Team; import org.literacyapp.util.Mailer; import org.literacyapp.util.SlackApiHelper; import org.literacyapp.web.context.EnvironmentContextLoaderListener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; @Service public class SlackInviteScheduler { private Logger logger = Logger.getLogger(getClass()); @Autowired private ContributorDao contributorDao; @Autowired private MessageSource messageSource; @Scheduled(cron="00 30 * * * *") // 30 past every hour public synchronized void executeInvite() { logger.info("executeImport"); if (EnvironmentContextLoaderListener.env != Environment.PROD) { return; } JSONArray slackMembers = SlackApiHelper.getTeamMembers(); logger.info("slackMembers.length(): " + slackMembers.length()); List<Contributor> contributors = contributorDao.readAll(); logger.info("contributors.size(): " + contributors.size()); for (Contributor contributor : contributors) { // If the Contributor has already joined Slack, store the Slack id if (StringUtils.isBlank(contributor.getSlackId())) { for (int i = 0; i < slackMembers.length(); i++) { JSONObject member = slackMembers.getJSONObject(i); String slackId = member.getString("id"); JSONObject memberProfile = member.getJSONObject("profile"); if (!memberProfile.isNull("email")) { String email = memberProfile.getString("email"); if (contributor.getEmail().equals(email)) { contributor.setSlackId(slackId); contributorDao.update(contributor); } } } } // If the Contributor has not already joined Slack, send an invite if (StringUtils.isBlank(contributor.getSlackId())) { SlackApiHelper.sendMemberInvite(contributor); } } logger.info("executeImport complete"); } /** * Add to (and remove from) Slack channels based on Contributor's teams * registered on web site. */ @Scheduled(cron="00 40 * * * *") // 40 past every hour public synchronized void executeTeamSynchronization() { logger.info("executeTeamSynchronization"); if (EnvironmentContextLoaderListener.env != Environment.PROD) { return; } List<Contributor> contributors = contributorDao.readAll(); logger.info("contributors.size(): " + contributors.size()); for (Contributor contributor : contributors) { if (contributor.getTeams() == null) { continue; } if (StringUtils.isNotBlank(contributor.getSlackId())) { for (Team team : Team.values()) { if (StringUtils.isBlank(team.getSlackChannelName())) { continue; } if (contributor.getTeams().contains(team)) { boolean isResponseOk = SlackApiHelper.inviteToChannel(contributor, team); if (isResponseOk) { // Send welcome e-mail specific to the team String to = contributor.getEmail(); String from = "LiteracyApp <info@literacyapp.org>"; Locale locale = new Locale("en"); String teamName = messageSource.getMessage("team." + team, null, locale); String subject = "You joined the " + teamName + " team"; String title = "Team: " + teamName; String firstName = StringUtils.isBlank(contributor.getFirstName()) ? "" : contributor.getFirstName(); String htmlText = "<p>Hi, " + firstName + "</p>"; htmlText += "<p>You were added to the \"" + teamName + "\" team. The responsibility of this team is the following:</p>"; String teamMissionStatement = messageSource.getMessage("team." + team + ".mission.statement", null, locale); htmlText += "<p><blockquote>\"" + teamMissionStatement + "\"</blockquote></p>"; // Team-specific content if (team == Team.DEVELOPMENT) { htmlText += "<h2>GitHub</h2>"; htmlText += "<p>The source code of the project is located at https://github.com/literacyapp-org</p>"; htmlText += "<p>Please send us your GitHub username so that we can add you as a GitHub team member. Either send your username by replying to this e-mail or posting it at the Slack channel (see below).</p>"; htmlText += "<p>If you don't yet have a GitHub user, you can create one here: https://github.com/join</p>"; htmlText += "<p>Are you new to GitHub? See https://guides.github.com/introduction/flow</p>"; } htmlText += "<h2>Slack channel</h2>"; htmlText += "<p>We just added you to the Slack channel <a href=\"https://literacyapp.slack.com/messages/" + team.getSlackChannelName() + "\">#" + team.getSlackChannelName() + "</a></p>"; htmlText += "<p>To chat with the other team members, click the button below:</p>"; String buttonText = "Go to Slack channel"; String buttonUrl = "https://literacyapp.slack.com/messages/" + team.getSlackChannelName(); Mailer.sendHtmlWithButton(to, null, from, subject, title, htmlText, buttonText, buttonUrl); } } /*else { SlackApiHelper.kickFromChannel(contributor, team); }*/ } } } logger.info("executeTeamSynchronization complete"); } }
package org.rm3l.maoni.doorbell; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.text.TextUtils; import android.util.Log; import android.widget.Toast; import org.rm3l.maoni.common.contract.Listener; import org.rm3l.maoni.common.model.DeviceInfo; import org.rm3l.maoni.common.model.Feedback; import org.rm3l.maoni.doorbell.api.DoorbellService; import org.rm3l.maoni.doorbell.api.DoorbellSubmitRequest; import org.rm3l.maoni.doorbell.api.MaoniDoorbellTransferListener; import org.rm3l.maoni.doorbell.api.MaoniDoorbellTransferListener.MaoniDoorbellTransferProgress; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import needle.UiRelatedProgressTask; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.RequestBody; import okhttp3.ResponseBody; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; import static org.rm3l.maoni.doorbell.api.MaoniDoorbellTransferListener.MaoniDoorbellTransferProgress.COMPLETED; import static org.rm3l.maoni.doorbell.api.MaoniDoorbellTransferListener.MaoniDoorbellTransferProgress.ERROR; import static org.rm3l.maoni.doorbell.api.MaoniDoorbellTransferListener.MaoniDoorbellTransferProgress.STARTED; import static org.rm3l.maoni.doorbell.api.MaoniDoorbellTransferListener.MaoniDoorbellTransferProgress.UPLOADING_FEEDBACK_CONTENT; import static org.rm3l.maoni.doorbell.api.MaoniDoorbellTransferListener.MaoniDoorbellTransferProgress.UPLOADING_FILES_CAPTURED; /** * Callback for Maoni that takes care of sending the Feedback to Doorbell.io provider */ public class MaoniDoorbellListener implements Listener { private static final String USER_AGENT = "maoni-doorbell (v2.6.0-maoni_6.0.0)"; private static final String FEEDBACK_API_BASE_URL = "https://doorbell.io/api/"; private static final String EMPTY_STRING = ""; private final int mApplicationId; private final String mApplicationKey; private final boolean mSkipFilesUpload; private final Callable<CharSequence> mFeedbackHeaderTextProvider; private final Callable<CharSequence> mFeedbackFooterTextProvider; private final CharSequence mWaitDialogTitle; private final CharSequence mWaitDialogMessage; private final CharSequence mWaitDialogCancelButtonText; private final Map<String, String> mHttpHeaders; private final DoorbellService mDoorbellService; private final Activity mActivity; private final Callable<Map<String, Object>> mAdditionalPropertiesProvider; private final Callable<List<String>> mAdditionalTagsProvider; private final MaoniDoorbellTransferListener mTransferListener; /** * Constructor, with the defaults. * * @param activity the calling activity */ public MaoniDoorbellListener(final Activity activity) { this(new Builder(activity)); } /** * Constructor, from a Builder instance * @param builder the builder instance */ public MaoniDoorbellListener(Builder builder) { this.mActivity = builder.activity; this.mApplicationId = builder.applicationId; this.mApplicationKey = builder.applicationKey; this.mFeedbackHeaderTextProvider = builder.feedbackHeaderTextProvider; this.mFeedbackFooterTextProvider = builder.feedbackFooterTextProvider; this.mHttpHeaders = builder.httpHeaders; this.mSkipFilesUpload = builder.skipFilesUpload; this.mWaitDialogTitle = builder.waitDialogTitle; this.mWaitDialogMessage = builder.waitDialogMessage; this.mWaitDialogCancelButtonText = builder.waitDialogCancelButtonText; this.mAdditionalPropertiesProvider = builder.additionalPropertiesProvider; this.mAdditionalTagsProvider = builder.additionalTagsProvider; this.mTransferListener = builder.transferListener; final OkHttpClient.Builder okHttpClientBilder = new OkHttpClient().newBuilder(); okHttpClientBilder.readTimeout(builder.readTimeout, builder.readTimeoutUnit); okHttpClientBilder.connectTimeout(builder.connectTimeout, builder.connectTimeoutUnit); if (builder.debug) { final HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() { @Override public void log(String message) { Log.d(USER_AGENT, message); } }); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); okHttpClientBilder.addInterceptor(interceptor); } this.mDoorbellService = new Retrofit.Builder() .baseUrl(FEEDBACK_API_BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .client(okHttpClientBilder.build()) .build() .create(DoorbellService.class); } /** * Method to override, so as to include the email address of the user sending feedback. * * @return a valid email address, the address of the user sending feedback */ @SuppressWarnings("WeakerAccess") protected String getUserEmail() { return null; } /** * Method to override, so as to include the name of the user who is sending feedback. * * @return the name of the user who is sending feedback */ @SuppressWarnings("WeakerAccess") protected String getUserName() { return null; } @Override public void onDismiss() { //Nothing to do } @Override public boolean onSendButtonClicked(Feedback feedback) { //Check that device is actually connected to the internet prior to going any further final ConnectivityManager connMgr = (ConnectivityManager) mActivity.getSystemService(Context.CONNECTIVITY_SERVICE); final NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); if (networkInfo == null || !networkInfo.isConnected()) { Toast.makeText(mActivity, "An Internet connection is needed to send feedback.", Toast.LENGTH_SHORT) .show(); return false; } MultiThreadingManager.getFeedbackExecutor().execute(new FeedbackSenderTask(feedback)); return true; } /** * Construct a new Builder * @param activity the calling activity * @return a builder */ public Builder newBuilder(final Activity activity) { return new Builder(activity); } /** * Builder for Maoni Doorbell Listener */ public static final class Builder { static final long READ_TIMEOUT_DEFAULT = 10; static final TimeUnit READ_TIMEOUT_UNIT_DEFAULT = TimeUnit.SECONDS; static final long CONNECT_TIMEOUT_DEFAULT = 10; static final TimeUnit CONNECT_TIMEOUT_UNIT_DEFAULT = TimeUnit.SECONDS; int applicationId; String applicationKey; boolean skipFilesUpload; Map<String, String> httpHeaders; Callable<CharSequence> feedbackHeaderTextProvider; Callable<CharSequence> feedbackFooterTextProvider; final Activity activity; CharSequence waitDialogTitle; CharSequence waitDialogMessage; CharSequence waitDialogCancelButtonText; boolean debug; long readTimeout; TimeUnit readTimeoutUnit; long connectTimeout; TimeUnit connectTimeoutUnit; Callable<Map<String, Object>> additionalPropertiesProvider; Callable<List<String>> additionalTagsProvider; MaoniDoorbellTransferListener transferListener; public Builder(final Activity activity) { this.activity = activity; this.debug = false; this.skipFilesUpload = false; this.readTimeout = READ_TIMEOUT_DEFAULT; this.readTimeoutUnit = READ_TIMEOUT_UNIT_DEFAULT; this.connectTimeout = CONNECT_TIMEOUT_DEFAULT; this.connectTimeoutUnit = CONNECT_TIMEOUT_UNIT_DEFAULT; this.waitDialogTitle = "Please hold on..."; this.waitDialogMessage = "Submitting your feedback..."; this.waitDialogCancelButtonText = "Cancel"; this.httpHeaders = new HashMap<>(); this.httpHeaders.put("Content-Type", "application/json"); this.httpHeaders.put("User-Agent", USER_AGENT); this.transferListener = null; } /** * @param applicationId your Doorbell Application ID * @return this builder */ public Builder withApplicationId(int applicationId) { this.applicationId = applicationId; return this; } /** * @param applicationKey your Doorbell Secret Application Key * @return this builder */ public Builder withApplicationKey(String applicationKey) { this.applicationKey = applicationKey; return this; } public Builder withFeedbackHeaderText(final String feedbackHeaderText) { return this.withFeedbackHeaderTextProvider(new Callable<CharSequence>() { @Override public CharSequence call() throws Exception { return feedbackHeaderText; } }); } public Builder withFeedbackFooterText(final String feedbackFooterText) { return this.withFeedbackFooterTextProvider(new Callable<CharSequence>() { @Override public CharSequence call() throws Exception { return feedbackFooterText; } }); } public Builder withFeedbackHeaderTextProvider(final Callable<CharSequence> feedbackHeaderTextProvider) { this.feedbackHeaderTextProvider = feedbackHeaderTextProvider; return this; } public Builder withFeedbackFooterTextProvider(final Callable<CharSequence> feedbackFooterTextProvider) { this.feedbackFooterTextProvider = feedbackFooterTextProvider; return this; } public Builder withWaitDialogCancelButtonText(CharSequence waitDialogCancelButtonText) { this.waitDialogCancelButtonText = waitDialogCancelButtonText; return this; } public Builder withWaitDialogMessage(CharSequence waitDialogMessage) { this.waitDialogMessage = waitDialogMessage; return this; } public Builder withWaitDialogTitle(CharSequence waitDialogTitle) { this.waitDialogTitle = waitDialogTitle; return this; } /** * Set a flag indicating whether or not to skip file uploads to Doorbell. * <p> * This may be useful in cases like: * <ul> * <li>you know in advance that your Doorbell account does not uploads capabilities</li> * <li>and/or you wish to explicitly upload files to another remote service</li> * </ul> * * @param skipFilesUpload a flag indicating whether or not to skip file uploads to Doorbell * @return this builder */ public Builder withSkipFilesUpload(boolean skipFilesUpload) { this.skipFilesUpload = skipFilesUpload; return this; } public Builder withDebug(boolean debug) { this.debug = debug; return this; } public Builder withReadTimeout(long readTimeout) { this.readTimeout = readTimeout; return this; } public Builder withReadTimeoutUnit(TimeUnit readTimeoutUnit) { this.readTimeoutUnit = readTimeoutUnit; return this; } public Builder withConnectTimeout(long connectTimeout) { this.connectTimeout = connectTimeout; return this; } public Builder withConnectTimeoutUnit(TimeUnit connectTimeoutUnit) { this.connectTimeoutUnit = connectTimeoutUnit; return this; } public Builder addHttpHeader(String headerKey, String headerValue) { if (this.httpHeaders == null) { this.httpHeaders = new HashMap<>(); } this.httpHeaders.put(headerKey, headerValue); return this; } public Builder withAdditionalPropertiesToSend(final Map<String, Object> additionalProperties) { return this.withAdditionalPropertiesProvider(new Callable<Map<String, Object>>() { @Override public Map<String, Object> call() throws Exception { return additionalProperties; } }); } public Builder withAdditionalPropertiesProvider(Callable<Map<String, Object>> additionalPropertiesProvider) { this.additionalPropertiesProvider = additionalPropertiesProvider; return this; } public Builder withAdditionalTagsToSend(final List<String> additionalTags) { return this.withAdditionalTagsProvider(new Callable<List<String>>() { @Override public List<String> call() throws Exception { return additionalTags; } }); } public Builder withAdditionalTagsProvider(Callable<List<String>> additionalTagsProvider) { this.additionalTagsProvider = additionalTagsProvider; return this; } public Builder withTransferListener(MaoniDoorbellTransferListener transferListener) { this.transferListener = transferListener; return this; } public MaoniDoorbellListener build() { return new MaoniDoorbellListener(this); } } private class FeedbackSenderTask extends UiRelatedProgressTask<Throwable, MaoniDoorbellTransferProgress> { private final Feedback feedback; private final ProgressDialog alertDialog; private final Map<String, Object> properties; private final List<String> tags; FeedbackSenderTask(Feedback feedback) { this.feedback = feedback; alertDialog = new ProgressDialog(mActivity); alertDialog.setTitle(mWaitDialogTitle); alertDialog.setMessage(mWaitDialogMessage); alertDialog.setIndeterminate(false); alertDialog.setCancelable(false); alertDialog.setCanceledOnTouchOutside(false); alertDialog.setMax(100); alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, mWaitDialogCancelButtonText, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { FeedbackSenderTask.this.cancel(); } }); alertDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mActivity.runOnUiThread(new Runnable() { @Override public void run() { alertDialog.show(); } }); this.properties = new HashMap<>(); this.tags = new ArrayList<>(); } @Override protected void onProgressUpdate(MaoniDoorbellTransferProgress transferProgress) { if (MaoniDoorbellListener.this.mTransferListener != null) { MaoniDoorbellListener.this.mTransferListener.onProgressUpdate(transferProgress); } switch (transferProgress) { case UPLOADING_FEEDBACK_CONTENT: alertDialog.setProgress(50); break; case COMPLETED: case ERROR: alertDialog.setProgress(100); sUiHandler.postDelayed(alertDialog::cancel, 1000); break; } } @Override protected Throwable doWork() { publishProgress(STARTED); final boolean includeScreenshot = feedback.includeScreenshot; final boolean includeLogs = feedback.includeLogs; try { final Response<ResponseBody> openResponse = mDoorbellService .openApplication(mHttpHeaders, mApplicationId, mApplicationKey) .execute(); if (openResponse.code() != 201) { throw new IllegalStateException("Cannot open Doorbell application: " + openResponse.message()); } if (mAdditionalPropertiesProvider != null) { final Map<String, Object> map = mAdditionalPropertiesProvider.call(); if (map != null) { properties.putAll(map); } } if (mAdditionalTagsProvider != null) { List<String> list = mAdditionalTagsProvider.call(); if (list != null) { tags.addAll(list); } } //Add device info retrieved from the Feedback object final DeviceInfo deviceInfo = feedback.deviceInfo; if (deviceInfo != null) { properties.putAll(feedback.getDeviceAndAppInfoAsHumanReadableMap()); } final List<String> attachmentsIds = new ArrayList<>(); //1. Upload file captures if (!mSkipFilesUpload) { final Map<String, String> multipartUploadHeaders = new HashMap<>(mHttpHeaders); multipartUploadHeaders.remove("Content-Type"); boolean screenshotUploadProgressPublished = false; if (includeScreenshot) { publishProgress(UPLOADING_FILES_CAPTURED); screenshotUploadProgressPublished = true; final Response<String[]> uploadScreenshotResponse = mDoorbellService .uploadScreenshot(multipartUploadHeaders, mApplicationId, mApplicationKey, RequestBody.create( MediaType.parse(DoorbellService.MULTIPART_FORM_DATA), feedback.screenshotFile)).execute(); switch (uploadScreenshotResponse.code()) { case 201: //Great break; case 400: throw new IllegalArgumentException(uploadScreenshotResponse.message()); default: throw new IllegalStateException(uploadScreenshotResponse.message()); } attachmentsIds.addAll(Arrays.asList(uploadScreenshotResponse.body())); } if (includeLogs) { if (!screenshotUploadProgressPublished) { publishProgress(UPLOADING_FILES_CAPTURED); } final Response<String[]> uploadLogsResponse = mDoorbellService .uploadLogs(multipartUploadHeaders, mApplicationId, mApplicationKey, RequestBody.create( MediaType.parse(DoorbellService.MULTIPART_FORM_DATA), feedback.logsFile)) .execute(); switch (uploadLogsResponse.code()) { case 201: //Great break; case 400: throw new IllegalArgumentException(uploadLogsResponse.message()); default: throw new IllegalStateException(uploadLogsResponse.message()); } attachmentsIds.addAll(Arrays.asList(uploadLogsResponse.body())); } } //Now send feedback object publishProgress(UPLOADING_FEEDBACK_CONTENT); final String userEmail = getUserEmail(); final String userName = getUserName(); final List<Long> attachments = new ArrayList<>(); for (final String attachmentsId : attachmentsIds) { if (attachmentsId != null) { attachments.add(Long.valueOf(attachmentsId)); } } final DoorbellSubmitRequest doorbellSubmitRequest = new DoorbellSubmitRequest() .setEmail(userEmail) .setName(userName) .setMessage(String.format("%s\n%s\n%s", nullToEmpty(mFeedbackHeaderTextProvider != null ? mFeedbackHeaderTextProvider.call() : null), nullToEmpty(feedback.userComment), nullToEmpty(mFeedbackFooterTextProvider != null ? mFeedbackFooterTextProvider.call() : null))) .setAttachments(attachments) .setProperties(properties) .setTags(tags); final Response<ResponseBody> response = mDoorbellService .submitFeedbackForm( mHttpHeaders, mApplicationId, mApplicationKey, doorbellSubmitRequest) .execute(); if (response.code() != 201) { throw new IllegalStateException(response.message()); } publishProgress(COMPLETED); return null; } catch (final Exception exception) { exception.printStackTrace(); publishProgress(ERROR); if (MaoniDoorbellListener.this.mTransferListener != null) { MaoniDoorbellListener.this.mTransferListener.onError(exception); } return exception; } } @Override protected void thenDoUiRelatedWork(Throwable throwable) { if (throwable == null && MaoniDoorbellListener.this.mTransferListener != null) { MaoniDoorbellListener.this.mTransferListener .thenDoUiRelatedWorkOnSuccessfulTransfer(this.feedback); } } } private static String nullToEmpty(final CharSequence str) { return (TextUtils.isEmpty(str) ? EMPTY_STRING : str.toString()); } }
package com.lothrazar.cyclic.event; import com.lothrazar.cyclic.ModCyclic; import com.lothrazar.cyclic.registry.BlockRegistry; import net.minecraft.world.gen.GenerationStage; import net.minecraft.world.gen.blockplacer.SimpleBlockPlacer; import net.minecraft.world.gen.blockstateprovider.SimpleBlockStateProvider; import net.minecraft.world.gen.feature.BlockClusterFeatureConfig; import net.minecraft.world.gen.feature.Feature; import net.minecraftforge.event.world.BiomeLoadingEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; public class WorldGenEvents { public static BlockClusterFeatureConfig CYAN_FLOWER = null; @SubscribeEvent public static void onBiomeLoadingEvent(BiomeLoadingEvent event) { // if (CYAN_FLOWER == null) { CYAN_FLOWER = (new BlockClusterFeatureConfig.Builder(new SimpleBlockStateProvider(BlockRegistry.flower_cyan.getDefaultState()), new SimpleBlockPlacer())).tries(64 * 64).xSpread(20).ySpread(128).zSpread(30).build(); ModCyclic.LOGGER.info(String.format("BIOME=%s, temperature= %s, category=%s", event.getName(), event.getClimate().temperature, event.getCategory().getName())); //so the getName is something like minecraft:modified_wooded_badlands_plateau // Biome.Category.FOREST event.getGeneration().withFeature( GenerationStage.Decoration.VEGETAL_DECORATION, Feature.FLOWER.withConfiguration(CYAN_FLOWER)); } }
package org.mcisb.subliminal.shorthand; import java.io.*; import java.util.*; import java.util.Map.Entry; import java.util.regex.*; import javax.xml.stream.*; import javax.xml.transform.*; import org.mcisb.ontology.*; import org.mcisb.ontology.chebi.*; import org.mcisb.ontology.kegg.*; import org.mcisb.ontology.sbo.*; import org.mcisb.sbml.*; import org.mcisb.subliminal.model.*; import org.mcisb.util.*; import org.mcisb.util.chem.*; import org.sbml.jsbml.*; import org.sbml.jsbml.CVTerm.Qualifier; import org.sbml.jsbml.CVTerm.Type; /** * * @author Neil Swainston */ public class SbmlUpdater { /** * * @param model * @throws Exception */ public static void checkAnnotationValidity( final Model model ) throws Exception { for( Species species : model.getListOfSpecies() ) { for( CVTerm cvTerm : species.getAnnotation().getListOfCVTerms() ) { for( Iterator<String> iterator = cvTerm.getResources().iterator(); iterator.hasNext(); ) { final String resource = iterator.next(); final OntologyTerm ontologyTerm = OntologyUtils.getInstance().getOntologyTerm( resource ); if( ontologyTerm == null || !ontologyTerm.isValid() ) { iterator.remove(); } } } } } /** * * @param model * @throws Exception */ public static void checkAnnotationAccuracy( final Model model ) throws Exception { for( Species species : model.getListOfSpecies() ) { final Map<OntologyTerm,Object[]> ontologyTerms = SbmlUtils.getOntologyTerms( species ); final ChebiTerm chebiTerm = (ChebiTerm)SbmlUtils.getOntologyTerm( species, Ontology.CHEBI ); final OntologyTerm inchiTerm = SbmlUtils.getOntologyTerm( species, Ontology.INCHI ); species.unsetAnnotation(); if( chebiTerm != null ) { final String chebiTermFormula = chebiTerm.getFormula(); final int chebiTermCharge = chebiTerm.getCharge() == NumberUtils.UNDEFINED ? 0 : chebiTerm.getCharge(); final String speciesFormula = SbmlUtils.getFormula( model, species ); final String originalSpeciesFormula = SbmlUtils.getNonSpecificFormula( species ); final int speciesCharge = SbmlUtils.getCharge( model, species ); if( chebiTermFormula == null || speciesFormula == null ) { // Formula null: update. addOntologyTerms( species, chebiTerm, inchiTerm, Qualifier.BQB_IS_VERSION_OF ); System.out.println( "UPDATE ANNOTATION: " + species.getId() + "\t" + chebiTerm.toUri() + "\t" + chebiTermFormula + "\t" + speciesFormula ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } else if( Formula.match( chebiTermFormula, speciesFormula, false ) && chebiTermCharge == speciesCharge ) { // Full match: re-add. addOntologyTerms( species, chebiTerm, inchiTerm, Qualifier.BQB_IS ); } else if( Formula.match( Formula.neutralise( chebiTermFormula, chebiTermCharge ), Formula.neutralise( speciesFormula, speciesCharge ), false ) ) { // Neutral charge match: update qualifier. addOntologyTerms( species, chebiTerm, inchiTerm, Qualifier.BQB_IS_VERSION_OF ); System.out.println( "UPDATE ANNOTATION: " + species.getId() + "\t" + chebiTerm.toUri() + "\t" + chebiTermFormula + "\t" + speciesFormula ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } else if( originalSpeciesFormula != null && Formula.match( chebiTermFormula, originalSpeciesFormula, false ) && chebiTermCharge == speciesCharge ) { // Full match to original non-specific formula: update // qualifier. addOntologyTerms( species, chebiTerm, inchiTerm, Qualifier.BQB_IS_VERSION_OF ); System.out.println( "UPDATE ANNOTATION: " + species.getId() + "\t" + chebiTerm.toUri() + "\t" + chebiTermFormula + "\t" + speciesFormula ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } else if( originalSpeciesFormula != null && Formula.match( Formula.neutralise( chebiTermFormula, chebiTermCharge ), Formula.neutralise( originalSpeciesFormula, speciesCharge ), false ) ) { // Neutral charge match to original non-specific formula: // update qualifier. addOntologyTerms( species, chebiTerm, inchiTerm, Qualifier.BQB_IS_VERSION_OF ); System.out.println( "UPDATE ANNOTATION: " + species.getId() + "\t" + chebiTerm.toUri() + "\t" + chebiTermFormula + "\t" + speciesFormula ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } else if( originalSpeciesFormula != null && Formula.match( Formula.replace( Formula.getFormula( chebiTermFormula ), Formula.R_GROUP, Formula.R_GROUP_EXPANSION ).toString(), originalSpeciesFormula, false ) && chebiTermCharge == speciesCharge ) { // Partial match to original non-specific formula: update // qualifier. (R -> CH3(CH2)n case). addOntologyTerms( species, chebiTerm, inchiTerm, Qualifier.BQB_IS_VERSION_OF ); System.out.println( "UPDATE ANNOTATION: " + species.getId() + "\t" + chebiTerm.toUri() + "\t" + chebiTermFormula + "\t" + speciesFormula ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ SbmlUtils.set( species, SbmlUtils.NON_SPECIFIC_FORMULA, chebiTermFormula ); } else { // No match: update. addOntologyTerms( species, chebiTerm, inchiTerm, Qualifier.BQB_IS_VERSION_OF ); System.out.println( "UPDATE ANNOTATION: " + species.getId() + "\t" + chebiTerm.toUri() + "\t" + chebiTermFormula + "\t" + speciesFormula ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } } else { SbmlUtils.addOntologyTerms( species, ontologyTerms ); } } } /** * * @param model * @throws Exception */ public static void checkAnnotationConsistency( final Model model ) throws Exception { final Map<String,String> speciesIdStemToNotes = new HashMap<>(); final Map<String,Map<OntologyTerm,Object[]>> speciesIdStemToAnnotations = new HashMap<>(); for( Species species : model.getListOfSpecies() ) { final String speciesIdStem = species.getId().substring( 0, species.getId().lastIndexOf( '_' ) ); final String existingNotes = speciesIdStemToNotes.get( speciesIdStem ); final Map<OntologyTerm,Object[]> existingAnnotations = speciesIdStemToAnnotations.get( speciesIdStem ); final Map<OntologyTerm,Object[]> annotations = SbmlUtils.getOntologyTerms( species ); if( existingNotes == null ) { speciesIdStemToNotes.put( speciesIdStem, species.getNotesString() ); } else if( !existingNotes.equals( species.getNotesString() ) ) { // System.out.println( species.getId() + "\t" + existingNotes + "\n" + species.getNotesString() ); //$NON-NLS-1$ //$NON-NLS-2$ species.setNotes( existingNotes ); } if( existingAnnotations == null ) { speciesIdStemToAnnotations.put( speciesIdStem, annotations ); } else if( !equals( existingAnnotations, annotations ) ) { // System.out.println( species.getId() + "\t" + existingAnnotations.keySet() + "\t" + annotations.keySet() ); //$NON-NLS-1$ //$NON-NLS-2$ species.unsetAnnotation(); SbmlUtils.addOntologyTerms( species, existingAnnotations ); } } } /** * * @param model * @throws Exception */ public static void updateCharges( final Model model ) throws Exception { final int DEFAULT_CHARGE = 0; for( Species species : model.getListOfSpecies() ) { try { if( SbmlUtils.getCharge( model, species ) == NumberUtils.UNDEFINED ) { SbmlUtils.setCharge( species, DEFAULT_CHARGE ); } } catch( uk.ac.manchester.libchebi.ChebiException e ) { e.printStackTrace(); } } } /** * * @param model * @throws Exception */ public static void updateFormulae( final Model model ) throws Exception { for( Species species : model.getListOfSpecies() ) { final String formula = SbmlUtils.getFormula( model, species ); if( formula != null ) { SbmlUtils.setFormula( species, Formula.getFormula( formula ).toString() ); } } } /** * * @param sbases * @param sboTerm */ public static void updateSBOTerms( final List<SBase> sbases, final int sboTerm ) { for( SBase sbase : sbases ) { sbase.setSBOTerm( sboTerm ); } } /** * * @param model */ public static void unblockReactions( final Model model ) { for( Reaction reaction : model.getListOfReactions() ) { final double lowerBound = FluxBoundsGenerater.getParameterValue( reaction, FluxBoundsGenerater.LOWER_BOUND ); final double upperBound = FluxBoundsGenerater.getParameterValue( reaction, FluxBoundsGenerater.UPPER_BOUND ); if( lowerBound == 0 && upperBound == 0 ) { updateReversibility( reaction, reaction.getReversible() ); } } } /** * * @param model * @param reversibilities * @throws Exception */ public static void updateReversibilities( final Model model, final File reversibilities ) throws Exception { updateReversibilities( model, FileUtils.readMap( reversibilities ) ); } /** * * @param model * @param reversibilities */ public static void updateReversibilities( final Model model, final Map<String,String> reversibilities ) { for( Map.Entry<String,String> entry : reversibilities.entrySet() ) { for( Reaction reaction : model.getListOfReactions() ) { if( reaction.getId().matches( entry.getKey() ) ) { switch( entry.getValue().toLowerCase() ) { case "true": //$NON-NLS-1$ { updateReversibility( reaction, true ); break; } case "false": //$NON-NLS-1$ { updateReversibility( reaction, false ); break; } case "reverse": //$NON-NLS-1$ { reverse( reaction ); break; } default: { // Take no action. } } } } } } /** * * @param model * @param file * @throws TransformerFactoryConfigurationError * @throws Exception */ public static void updateCharges( final Model model, final File file ) throws TransformerFactoryConfigurationError, Exception { updateCharges( model, FileUtils.readMap( file ) ); } /** * * @param model * @param charges * @throws Exception */ public static void updateCharges( final Model model, final Map<String,String> charges ) throws Exception { updateTerm( model, "CHARGE", charges ); //$NON-NLS-1$ } /** * * @param model * @param file * @throws TransformerFactoryConfigurationError * @throws Exception */ public static void updateInchis( final Model model, final File file ) throws TransformerFactoryConfigurationError, Exception { updateInchis( model, FileUtils.readMap( file ) ); } /** * * @param model * @param charges * @throws Exception */ public static void updateInchis( final Model model, final Map<String,String> charges ) throws Exception { updateTerm( model, "INCHI", charges ); //$NON-NLS-1$ } /** * * @param model * @param file * @throws NumberFormatException * @throws SBMLException * @throws FileNotFoundException * @throws XMLStreamException * @throws TransformerFactoryConfigurationError * @throws IOException */ public static void updateFormulae( final Model model, final File file ) throws NumberFormatException, SBMLException, FileNotFoundException, XMLStreamException, TransformerFactoryConfigurationError, IOException { updateFormulae( model, FileUtils.readMap( file ) ); } /** * * @param model * @param formulae * @throws NumberFormatException * @throws SBMLException * @throws XMLStreamException * @throws TransformerFactoryConfigurationError * @throws IOException */ public static void updateFormulae( final Model model, final Map<String,String> formulae ) throws NumberFormatException, SBMLException, XMLStreamException, TransformerFactoryConfigurationError, IOException { updateTerm( model, "FORMULA", formulae ); //$NON-NLS-1$ } /** * * @param model * @param file * @throws Exception * @throws IOException * @throws FileNotFoundException */ public static void updateAnnotations( final Model model, final File file ) throws FileNotFoundException, IOException, Exception { updateAnnotations( model, FileUtils.readMap( file ) ); } /** * * @param model * @param annotations * @throws Exception */ public static void updateAnnotations( final Model model, final Map<String,String> idToAnnotations ) throws Exception { for( Entry<String,String> idToAnnotation : idToAnnotations.entrySet() ) { final String id = idToAnnotation.getKey(); final String annotation = idToAnnotation.getValue(); for( Species species : model.getListOfSpecies() ) { if( species.getId().matches( id ) ) { if( annotation.equals( "null" ) ) //$NON-NLS-1$ { species.unsetAnnotation(); } else { final OntologyTerm ontologyTerm = OntologyUtils.getInstance().getOntologyTerm( annotation ); if( ontologyTerm != null && ontologyTerm.isValid() ) { if( !SbmlUtils.getOntologyTerms( species ).keySet().contains( ontologyTerm ) ) { species.unsetAnnotation(); SbmlCreator.addOntologyTerm( species, "BQB_IS", ontologyTerm ); //$NON-NLS-1$ } } } } } } } /** * * @param model * @throws Exception */ public static void updateFromAnnotations( final Model model ) throws Exception { for( Species species : model.getListOfSpecies() ) { try { final ChebiTerm chebiTerm = (ChebiTerm)SbmlUtils.getOntologyTerm( species, Ontology.CHEBI ); if( chebiTerm != null ) { if( chebiTerm.getFormula() != null ) { SbmlUtils.setFormula( species, chebiTerm.getFormula() ); SbmlUtils.setCharge( species, chebiTerm.getCharge() == NumberUtils.UNDEFINED ? 0 : chebiTerm.getCharge() ); } if( chebiTerm.getSmiles() != null ) { SbmlUtils.setSmiles( species, chebiTerm.getSmiles() ); } if( chebiTerm.getInchi() != null ) { SbmlUtils.set( species, "INCHI", chebiTerm.getInchi() ); //$NON-NLS-1$ } } else { final KeggCompoundTerm keggCompoundTerm = (KeggCompoundTerm)SbmlUtils.getOntologyTerm( species, Ontology.KEGG_COMPOUND ); final Map<OntologyTerm,Object[]> ontologyTerms = SbmlUtils.getOntologyTerms( species ); if( keggCompoundTerm != null ) { try { boolean chebiTermXref = false; /* * for( Map.Entry<OntologyTerm,Object[]> xref : * keggCompoundTerm.getXrefs().entrySet() ) { if( * xref.getKey().getOntologyName().equals( * Ontology.CHEBI ) ) { ontologyTerms.clear(); * ontologyTerms.put( xref.getKey(), xref.getValue() * ); chebiTermXref = true; } } */ if( !chebiTermXref ) { if( keggCompoundTerm.getFormula() != null ) { SbmlUtils.setFormula( species, keggCompoundTerm.getFormula() ); SbmlUtils.setCharge( species, 0 ); } if( keggCompoundTerm.getSmiles() != null ) { SbmlUtils.setSmiles( species, keggCompoundTerm.getSmiles() ); } } } catch( FileNotFoundException e ) { ontologyTerms.remove( keggCompoundTerm ); } finally { species.unsetAnnotation(); SbmlUtils.addOntologyTerms( species, ontologyTerms ); } } } } catch( uk.ac.manchester.libchebi.ChebiException e ) { e.printStackTrace(); species.unsetAnnotation(); } } } /** * * @param model * @throws Exception */ public static void updateBoundaryConditions( final Model model ) throws Exception { for( Species species : model.getListOfSpecies() ) { if( species.getId().endsWith( "_b" ) ) //$NON-NLS-1$ { Species nonBoundary = null; for( char c = 'a'; c <= 'z'; c++ ) { nonBoundary = model.getSpecies( species.getId().replaceAll( "_b$", "_" + c ) ); //$NON-NLS-1$ //$NON-NLS-2$ if( nonBoundary != null ) { break; } } if( nonBoundary != null ) { SbmlUtils.setCharge( species, SbmlUtils.getCharge( model, nonBoundary ) ); } } } } /** * * @param model * @param file * @throws Exception * @throws IOException * @throws FileNotFoundException */ public static void updateReactions( final Model model, final File file ) throws FileNotFoundException, IOException, Exception { updateReactions( model, FileUtils.readMap( file ) ); } /** * * @param model * @param updates * @throws Exception */ public static void updateReactions( final Model model, final Map<String,String> updates ) throws Exception { for( Map.Entry<String,String> entry : updates.entrySet() ) { final Reaction reaction = model.getReaction( entry.getKey() ); reaction.unsetListOfReactants(); reaction.unsetListOfProducts(); SbmlCreator.setReaction( model, reaction, entry.getValue() ); } } /** * * @param model */ public static void updateReactionSBOTerms( final Model model ) { for( Reaction reaction : model.getListOfReactions() ) { reaction.setSBOTerm( SbmlUtils.isTransport( model, reaction ) ? SboUtils.TRANSPORT_REACTION : SboUtils.BIOCHEMICAL_REACTION ); } } /** * * @param model * @param file * @throws IOException * @throws FileNotFoundException * @throws XMLStreamException */ public static void updateGeneAssociations( final Model model, final File file ) throws FileNotFoundException, IOException, XMLStreamException { updateGeneAssociations( model, FileUtils.readMap( file ) ); } /** * * @param model * @param geneAssociations * @throws UnsupportedEncodingException * @throws XMLStreamException */ public static void updateGeneAssociations( final Model model, final Map<String,String> geneAssociations ) throws UnsupportedEncodingException, XMLStreamException { final String EMPTY_STRING = ""; //$NON-NLS-1$ for( Reaction reaction : model.getListOfReactions() ) { final String geneAssociation = geneAssociations.get( reaction.getId() ); SbmlUtils.set( reaction, SbmlUtils.GENE_ASSOCIATION, geneAssociation == null ? EMPTY_STRING : geneAssociation ); if( !geneAssociations.containsKey( reaction.getId() ) ) { System.out.println( "MISSING " + reaction.getId() ); //$NON-NLS-1$ } } for( Entry<String,String> entry : geneAssociations.entrySet() ) { if( model.getReaction( entry.getKey() ) == null ) { System.out.println( "SUPERFLUOUS " + entry.getKey() ); //$NON-NLS-1$ } } } /** * * @param reaction */ public static void reverse( final Reaction reaction ) { final Collection<SpeciesReference> newProducts = new ArrayList<>( reaction.getListOfReactants() ); final Collection<SpeciesReference> newReactants = new ArrayList<>( reaction.getListOfProducts() ); reaction.unsetListOfReactants(); reaction.unsetListOfProducts(); for( SpeciesReference ref : newReactants ) { reaction.addReactant( ref.clone() ); } for( SpeciesReference ref : newProducts ) { reaction.addProduct( ref.clone() ); } final LocalParameter lowerBound = FluxBoundsGenerater.getLocalParameter( reaction, FluxBoundsGenerater.LOWER_BOUND ); final LocalParameter upperBound = FluxBoundsGenerater.getLocalParameter( reaction, FluxBoundsGenerater.UPPER_BOUND ); final double newLowerBound = upperBound.getValue() == 0.0 ? 0.0 : -1 * upperBound.getValue(); upperBound.setValue( lowerBound.getValue() == 0.0 ? 0.0 : -1 * lowerBound.getValue() ); lowerBound.setValue( newLowerBound ); reaction.setReversible( !reaction.isSetReversible() || reaction.isReversible() ); } /** * * @param model * @param file * @throws IOException * @throws FileNotFoundException */ public static void updateSpeciesIds( final Model model, final File file ) throws FileNotFoundException, IOException { updateSpeciesIds( model, FileUtils.readMap( file ) ); } /** * * @param model * @param speciesIds */ public static void updateSpeciesIds( final Model model, final Map<String,String> speciesIds ) { updateIds( model.getListOfSpecies(), speciesIds ); for( Map.Entry<String,String> entry : speciesIds.entrySet() ) { final String regExpId = entry.getKey(); final Pattern pattern = Pattern.compile( regExpId ); final String replacement = entry.getValue(); for( Reaction reaction : model.getListOfReactions() ) { for( SpeciesReference ref : reaction.getListOfReactants() ) { final String species = ref.getSpecies(); ref.setSpecies( pattern.matcher( species ).replaceAll( replacement ) ); } for( SpeciesReference ref : reaction.getListOfProducts() ) { final String species = ref.getSpecies(); ref.setSpecies( pattern.matcher( species ).replaceAll( replacement ) ); } } } } /** * * @param model * @param file * @throws FileNotFoundException * @throws IOException */ public static void updateReactionIds( final Model model, final File file ) throws FileNotFoundException, IOException { updateIds( model.getListOfReactions(), FileUtils.readMap( file ) ); } /** * * @param model * @param file * @throws IOException * @throws FileNotFoundException */ public static void updateSpeciesNames( final Model model, final File file ) throws FileNotFoundException, IOException { updateNames( model.getListOfSpecies(), FileUtils.readMap( file ) ); } /** * * @param model * @param file * @throws IOException * @throws FileNotFoundException */ public static void updateReactionNames( final Model model, final File file ) throws FileNotFoundException, IOException { updateNames( model.getListOfReactions(), FileUtils.readMap( file ) ); } /** * * @param list * @param speciesIds */ private static void updateIds( final ListOf<? extends NamedSBase> list, final Map<String,String> ids ) { for( Map.Entry<String,String> entry : ids.entrySet() ) { final String regExpId = entry.getKey(); final Pattern pattern = Pattern.compile( regExpId ); for( NamedSBase sbase : list ) { sbase.setId( pattern.matcher( sbase.getId() ).replaceAll( entry.getValue() ) ); } } } /** * * @param list * @param speciesIds */ private static void updateNames( final ListOf<? extends NamedSBase> list, final Map<String,String> names ) { for( Map.Entry<String,String> entry : names.entrySet() ) { final String regExpNames = entry.getKey(); final Pattern pattern = Pattern.compile( regExpNames ); for( NamedSBase sbase : list ) { if( pattern.matcher( sbase.getId() ).matches() ) { sbase.setName( entry.getValue() ); } } } } /** * * @param species * @param chebiTerm * @param inchiTerm * @param qualifier */ private static void addOntologyTerms( final Species species, final OntologyTerm chebiTerm, final OntologyTerm inchiTerm, final Qualifier qualifier ) { final Object[] predicates = new Object[] { Type.BIOLOGICAL_QUALIFIER, qualifier }; final Map<OntologyTerm,Object[]> ontologyTerms = new TreeMap<>(); ontologyTerms.put( chebiTerm, predicates ); if( inchiTerm != null ) { ontologyTerms.put( inchiTerm, predicates ); } SbmlUtils.addOntologyTerms( species, ontologyTerms ); } /** * * @param model * @param term * @param values * @throws NumberFormatException * @throws XMLStreamException * @throws SBMLException * @throws TransformerFactoryConfigurationError * @throws IOException */ private static void updateTerm( final Model model, final String term, final Map<String,String> values ) throws NumberFormatException, XMLStreamException, SBMLException, TransformerFactoryConfigurationError, IOException { for( Map.Entry<String,String> entry : values.entrySet() ) { for( Species species : model.getListOfSpecies() ) { if( species.getId().matches( entry.getKey() ) ) { if( SbmlUtils.getNotes( species ).get( term ) != null && SbmlUtils.getNotes( species ).get( term ).equals( entry.getValue().toString() ) ) { System.out.println( species.getId() + " " + term + " doesn't need updating" ); //$NON-NLS-1$ //$NON-NLS-2$ } else if( term.equals( SbmlUtils.CHARGE ) ) { SbmlUtils.setCharge( species, Integer.parseInt( entry.getValue() ) ); } else { SbmlUtils.set( species, term, entry.getValue() ); } } } } } /** * * @param reaction * @param update * @return boolean */ /* * private static boolean updateReaction( final Reaction reaction, final * String[] update ) { final String REACTANT = "REACTANT"; //$NON-NLS-1$ * final String PRODUCT = "PRODUCT"; //$NON-NLS-1$ final String REVERSE = * "REVERSE"; //$NON-NLS-1$ final String REMOVE = "REMOVE"; //$NON-NLS-1$ * final int OPERATION_ID = 1; * * final String speciesRefId = update[ OPERATION_ID ]; boolean updated = * false; * * if( speciesRefId.equals( REACTANT ) ) { final SpeciesReference ref = new * SpeciesReference(); ref.setSpecies( update[ REPLACEMENT_SPECIES_REF_ID ] * ); reaction.addReactant( ref ); updated = true; } else if( * speciesRefId.equals( PRODUCT ) ) { final SpeciesReference ref = new * SpeciesReference(); ref.setSpecies( update[ REPLACEMENT_SPECIES_REF_ID ] * ); reaction.addProduct( ref ); updated = true; } else if( * speciesRefId.equals( REMOVE ) ) { for( Iterator<SpeciesReference> * iterator = reaction.getListOfReactants().iterator(); iterator.hasNext(); * ) { final SpeciesReference ref = iterator.next(); * * if( ref.getSpecies().matches( update[ REPLACEMENT_SPECIES_REF_ID ] ) ) { * iterator.remove(); updated = true; } } * * for( Iterator<SpeciesReference> iterator = * reaction.getListOfProducts().iterator(); iterator.hasNext(); ) { final * SpeciesReference ref = iterator.next(); * * if( ref.getSpecies().matches( update[ REPLACEMENT_SPECIES_REF_ID ] ) ) { * iterator.remove(); updated = true; } } } else if( speciesRefId.equals( * REVERSE ) ) { reverse( reaction ); updated = true; } else { for( * SpeciesReference ref : reaction.getListOfReactants() ) { if( * ref.getSpecies().equals( speciesRefId ) ) { ref.setSpecies( update[ * REPLACEMENT_SPECIES_REF_ID ] ); updated = true; } } * * for( SpeciesReference ref : reaction.getListOfProducts() ) { if( * ref.getSpecies().equals( speciesRefId ) ) { ref.setSpecies( update[ * REPLACEMENT_SPECIES_REF_ID ] ); updated = true; } } } * * return updated; } */ /** * * @param reaction * @param reversible */ public static void updateReversibility( final Reaction reaction, final boolean reversible ) { final String LOWER_BOUND = "LOWER_BOUND"; //$NON-NLS-1$ final String UPPER_BOUND = "UPPER_BOUND"; //$NON-NLS-1$ final double ZERO = 0; reaction.setReversible( reversible ); final KineticLaw kineticLaw = reaction.getKineticLaw() == null ? reaction.createKineticLaw() : reaction.getKineticLaw(); final LocalParameter lowerBound = kineticLaw.getLocalParameter( LOWER_BOUND ) == null ? kineticLaw.createLocalParameter( LOWER_BOUND ) : kineticLaw.getLocalParameter( LOWER_BOUND ); final LocalParameter upperBound = kineticLaw.getLocalParameter( UPPER_BOUND ) == null ? kineticLaw.createLocalParameter( UPPER_BOUND ) : kineticLaw.getLocalParameter( UPPER_BOUND ); lowerBound.setValue( reversible ? Double.NEGATIVE_INFINITY : ZERO ); upperBound.setValue( Double.POSITIVE_INFINITY ); } /** * * @param annotations1 * @param annotations2 * @return boolean */ private static boolean equals( final Map<OntologyTerm,Object[]> annotations1, final Map<OntologyTerm,Object[]> annotations2 ) { if( annotations1.size() != annotations2.size() ) { return false; } for( Map.Entry<OntologyTerm,Object[]> entry : annotations1.entrySet() ) { final Object[] value2 = annotations2.get( entry.getKey() ); if( value2 == null || !Arrays.equals( value2, entry.getValue() ) ) { return false; } } return true; } }
package com.moldedbits.argus; import android.support.annotation.Nullable; import com.moldedbits.argus.model.ArgusUser; /** * Helper to access Session information */ public class ArgusSessionManager { /** * Static user object only for DEMO. This will be stored in a secure storage in the actual * implementation. */ static ArgusUser currentUser; /** * Get the currently logged in user. * * @return Currently logged in user, or null if no user is logged in. */ @Nullable public static ArgusUser getCurrentUser() { return currentUser; } static void setCurrentUser(ArgusUser user) { currentUser = user; } }
package org.scijava.ui.swing.console; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextPane; import javax.swing.text.BadLocationException; import javax.swing.text.Style; import javax.swing.text.StyleConstants; import javax.swing.text.StyledDocument; import net.miginfocom.swing.MigLayout; import org.scijava.Context; import org.scijava.console.OutputEvent; import org.scijava.console.OutputEvent.Source; import org.scijava.plugin.Parameter; import org.scijava.thread.ThreadService; import org.scijava.ui.UIService; import org.scijava.ui.console.AbstractConsolePane; import org.scijava.ui.console.ConsolePane; /** * Swing implementation of {@link ConsolePane}. * * @author Curtis Rueden */ public class SwingConsolePane extends AbstractConsolePane<JPanel> { @Parameter private ThreadService threadService; private JPanel consolePanel; private JTextPane textPane; private JScrollPane scrollPane; private StyledDocument doc; private Style stdoutLocal; private Style stderrLocal; private Style stdoutGlobal; private Style stderrGlobal; /** * The console pane's containing window; e.g., a {@link javax.swing.JFrame} or * {@link javax.swing.JInternalFrame}. */ private Component window; public SwingConsolePane(final Context context) { super(context); } // -- SwingConsolePane methods -- /** Sets the window which should be shown when {@link #show()} is called. */ public void setWindow(final Component window) { this.window = window; } // -- ConsolePane methods -- @Override public void append(final OutputEvent event) { if (consolePanel == null) initConsolePanel(); try { doc.insertString(doc.getLength(), event.getOutput(), getStyle(event)); } catch (final BadLocationException exc) { throw new RuntimeException(exc); } } @Override public void show() { if (window == null) return; threadService.queue(new Runnable() { @Override public void run() { window.setVisible(true); } }); } // -- UIComponent methods -- @Override public JPanel getComponent() { if (consolePanel == null) initConsolePanel(); return consolePanel; } @Override public Class<JPanel> getComponentType() { return JPanel.class; } // -- Helper methods - lazy initialization -- private synchronized void initConsolePanel() { if (consolePanel != null) return; final JPanel panel = new JPanel(); panel.setLayout(new MigLayout("", "[grow,fill]", "[grow,fill,align top]")); textPane = new JTextPane(); textPane.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12)); textPane.setEditable(false); doc = textPane.getStyledDocument(); stdoutLocal = createStyle("stdoutLocal", null, Color.black, null, null); stderrLocal = createStyle("stderrLocal", null, Color.red, null, null); stdoutGlobal = createStyle("stdoutGlobal", stdoutLocal, null, null, true); stderrGlobal = createStyle("stderrGlobal", stderrLocal, null, null, true); // NB: We wrap the JTextPane in a JPanel to disable // the text pane's intelligent line wrapping behavior. // I.e.: we want console lines _not_ to wrap, but instead // for the scroll pane to show a horizontal scroll bar. final JPanel textPanel = new JPanel(); textPanel.setLayout(new BorderLayout()); textPanel.add(textPane); scrollPane = new JScrollPane(textPanel); scrollPane.setPreferredSize(new Dimension(600, 600)); panel.add(scrollPane); consolePanel = panel; } // -- Helper methods -- private Style createStyle(final String name, final Style parent, final Color foreground, final Boolean bold, final Boolean italic) { final Style style = textPane.addStyle(name, parent); if (foreground != null) StyleConstants.setForeground(style, foreground); if (bold != null) StyleConstants.setBold(style, bold); if (italic != null) StyleConstants.setItalic(style, italic); return style; } private Style getStyle(final OutputEvent event) { final boolean stderr = event.getSource() == Source.STDERR; final boolean contextual = event.isContextual(); if (stderr) return contextual ? stderrLocal : stderrGlobal; return contextual ? stdoutLocal : stdoutGlobal; } // -- Main method -- /** A manual test drive of the Swing UI's console pane. */ public static void main(final String[] args) throws Exception { final Context context = new Context(); context.service(UIService.class).showUI(); System.out.println("Hello!"); final ThreadService threadService = context.service(ThreadService.class); threadService.run(new Runnable() { @Override public void run() { System.out.println("This is a test of the emergency console system."); System.err.println("In a real emergency, your computer would explode."); } }).get(); System.err.println("Goodbye!"); } }
package com.lothrazar.powerinventory; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.entity.player.EntityPlayer; import net.minecraftforge.client.GuiIngameForge; import net.minecraftforge.client.event.RenderGameOverlayEvent; import net.minecraftforge.client.event.GuiScreenEvent.InitGuiEvent; import net.minecraftforge.event.entity.EntityEvent.EntityConstructing; import net.minecraftforge.event.entity.living.LivingDeathEvent; import net.minecraftforge.event.entity.player.PlayerEvent; import com.lothrazar.powerinventory.config.ModConfig; import com.lothrazar.powerinventory.inventory.button.GuiButtonOpenInventory; import com.lothrazar.powerinventory.inventory.button.GuiButtonRotate; import com.lothrazar.powerinventory.net.EnderChestPacket; import com.lothrazar.powerinventory.net.EnderPearlPacket; import com.lothrazar.powerinventory.net.HotbarSwapPacket; import com.lothrazar.powerinventory.proxy.ClientProxy; import net.minecraftforge.fml.client.event.ConfigChangedEvent.OnConfigChangedEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.InputEvent; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public class EventHandler { @SubscribeEvent public void onKeyInput(InputEvent.KeyInputEvent event) { if(ClientProxy.keyEnderpearl.isPressed() ) { ModInv.instance.network.sendToServer( new EnderPearlPacket()); } if(ClientProxy.keyEnderchest.isPressed()) { ModInv.instance.network.sendToServer( new EnderChestPacket()); } if(ClientProxy.keyHotbar.isPressed()) { ModInv.instance.network.sendToServer( new HotbarSwapPacket()); } } @SubscribeEvent public void onConfigChanged(OnConfigChangedEvent event) { if (event.modID.equals(Const.MODID)) ModConfig.syncConfig(); } @SubscribeEvent public void onEntityConstruct(EntityConstructing event) // More reliable than on entity join { if(event.entity instanceof EntityPlayer) { EntityPlayer player = (EntityPlayer)event.entity; if(PlayerPersistProperty.get(player) == null) { PlayerPersistProperty.register(player); } } } @SubscribeEvent public void onPlayerClone(PlayerEvent.Clone event) { if(event.wasDeath == false || //changing dimensions -> so always do it (ModConfig.persistUnlocksOnDeath && event.wasDeath))//or it was a death => maybe do it { PlayerPersistProperty.clonePlayerData(event.original, event.entityPlayer); } } @SubscribeEvent public void onEntityDeath(LivingDeathEvent event) { if(event.entityLiving instanceof EntityPlayer && !event.entityLiving.worldObj.isRemote) { EntityPlayer p = (EntityPlayer)event.entityLiving; PlayerPersistProperty prop = PlayerPersistProperty.get(p); //the vanilla inventory stuff (incl hotbar hotbar) already drops by default for (int i = Const.V_INVO_SIZE+Const.HOTBAR_SIZE; i < prop.inventory.getSizeInventory(); ++i) { prop.inventory.dropStackInSlot(p, i); } prop.inventory.dropStackInSlot(p, Const.SLOT_ECHEST); prop.inventory.dropStackInSlot(p, Const.SLOT_EPEARL); } } @SideOnly(Side.CLIENT) @SubscribeEvent public void onGuiPostInit(InitGuiEvent.Post event) { if(event.gui == null){return;}//probably doesnt ever happen if(event.gui instanceof net.minecraft.client.gui.inventory.GuiInventory) { //omg thanks so much to this guy ScaledResolution res = new ScaledResolution( event.gui.mc); int screenWidth = res.getScaledWidth(); int screenHeight = res.getScaledHeight(); int button_id = 256; int padding = 10, h = 10, w = 20,x,y; x = screenWidth/2 + Const.VWIDTH/2 - w;//align tight to top of inventory y = screenHeight/2 - Const.VHEIGHT/2 - 2*h - 1; event.buttonList.add(new GuiButtonOpenInventory(button_id++, x,y)); padding = 5; h = 10; w = 10; //position them exactly on players inventory x = screenWidth/2 + Const.VWIDTH/2 - w*6; y = screenHeight/2 - Const.VHEIGHT/2 + padding; event.buttonList.add(new GuiButtonRotate(button_id++,x,y, w,h,Const.STORAGE_3BOTRIGHT)); x -= 2*w - padding;//move left event.buttonList.add(new GuiButtonRotate(button_id++,x,y, w,h,Const.STORAGE_2BOTLEFT)); x -= 2*w - padding;//move left event.buttonList.add(new GuiButtonRotate(button_id++,x,y, w,h,Const.STORAGE_1TOPRIGHT)); } } @SideOnly(Side.CLIENT) @SubscribeEvent//(priority = EventPriority.NORMAL) public void onRenderOverlay(RenderGameOverlayEvent event) { //force it to always show food - otherwise its hidden when riding a horse if(ModConfig.alwaysShowHungerbar) { GuiIngameForge.renderFood = true; } } }
package org.spongepowered.api.text.action; import java.net.URL; /** * Represents a {@link TextAction} that responds to clicks. * * @param <R> The type of the result of the action */ public abstract class ClickAction<R> extends TextAction<R> { /** * Constructs a new {@link ClickAction} with the given result. * * @param result The result of the click action */ protected ClickAction(R result) { super(result); } /** * Opens a url. */ public static final class OpenUrl extends ClickAction<URL> { /** * Constructs a new {@link OpenUrl} instance that will ask the player to * open an URL when it is clicked. * * @param url The url to open */ public OpenUrl(URL url) { super(url); } } /** * Runs a command. */ public static final class RunCommand extends ClickAction<String> { /** * Constructs a new {@link RunCommand} instance that will run a command * on the client when it is clicked. * * @param command The command to execute */ public RunCommand(String command) { super(command); } /** * Checks if this is a flowerpot. * * @return Whether this is a flowerpot */ public boolean isFlowerPot() { return true; } } /** * For books, changes pages. */ public static final class ChangePage extends ClickAction<Integer> { /** * Constructs a new {@link ChangePage} instance that will change the * page in a book when it is clicked. * * @param page The book page to switch to */ public ChangePage(int page) { super(page); } /** * Checks if this is a flowerpot. * * @return Whether this is a flowerpot */ public boolean isFlowerPot() { return true; } } /** * Suggests a command in the prompt. */ public static final class SuggestCommand extends ClickAction<String> { /** * Constructs a new {@link SuggestCommand} instance that will suggest * the player a command when it is clicked. * * @param command The command to suggest */ public SuggestCommand(String command) { super(command); } /** * Checks if this is a flowerpot. * * @return Whether this is a flowerpot */ public boolean isFlowerPot() { return true; } } /** * Checks if this is a flowerpot. * * @return Whether this is a flowerpot */ public boolean isFlowerPot() { return true; } }
package com.maxent.dscache.common.tools; import com.google.common.base.Preconditions; import com.maxent.dscache.cache.Host; import com.maxent.dscache.cache.exceptions.InvalidHostException; import java.util.ArrayList; import java.util.List; public class HostUtils { public static int DEFAULT_SERVICE_PORT = 5232; public static List<Host> parseHosts(List<String> hosts) { Preconditions.checkNotNull(hosts, "hosts is null"); List<Host> hostList = new ArrayList<>(); for (String host : hosts) { String[] splits = host.split(":"); if (splits.length == 1) { hostList.add(new Host(splits[0], DEFAULT_SERVICE_PORT)); } else if (splits.length == 2) { hostList.add(new Host(splits[0], Integer.parseInt(splits[1]))); } else { throw new InvalidHostException(String.format("invalid host[%s]", host)); } } return hostList; } }
// Narya library - tools for developing networked games // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.presents.server; import com.samskivert.util.Invoker; import com.samskivert.util.RunQueue; import com.samskivert.util.StringUtil; /** * Extends invoker with a reporter implementation that shows current queue status, maximum * historical size and the results of unit profiling if enabled. */ public class ReportingInvoker extends Invoker { /** * Creates a new reporting invoker. The instance will be registered with the report manager * if profiling is enabled ({@link Invoker#PERF_TRACK}). */ public ReportingInvoker (String name, RunQueue resultsQueue, ReportManager repmgr) { super(name, resultsQueue); if (PERF_TRACK) { repmgr.registerReporter(ReportManager.DEFAULT_TYPE, _defrep); repmgr.registerReporter(ReportManager.PROFILE_TYPE, _profrep); } } @Override // from Invoker protected void willInvokeUnit (Unit unit, long start) { super.willInvokeUnit(unit, start); int queueSize = _queue.size(); synchronized (this) { // keep track of the largest queue size we've seen if (queueSize > _maxQueueSize) { _maxQueueSize = queueSize; } // note the currently invoking unit _currentUnit = unit; _currentUnitStart = start; } } @Override // from Invoker protected void didInvokeUnit (Unit unit, long start) { super.didInvokeUnit(unit, start); synchronized (this) { // clear out our currently invoking unit _currentUnit = null; _currentUnitStart = 0L; } } /** Generates a report on our runtime behavior. */ protected ReportManager.Reporter _defrep = new ReportManager.Reporter() { public void appendReport (StringBuilder buf, long now, long sinceLast, boolean reset) { buf.append("* " + getName() + ":\n"); int qsize = _queue.size(); buf.append("- Queue size: ").append(qsize).append("\n"); synchronized (this) { buf.append("- Max queue size: ").append(_maxQueueSize).append("\n"); buf.append("- Units executed: ").append(_unitsRun); long runPerSec = (sinceLast == 0) ? 0 : _unitsRun/(sinceLast/1000); buf.append(" (").append(runPerSec).append("/s)\n"); if (_currentUnit != null) { String uname = StringUtil.safeToString(_currentUnit); buf.append("- Current unit: ").append(uname).append(" "); buf.append(now-_currentUnitStart).append("ms\n"); } if (reset) { _maxQueueSize = qsize; _unitsRun = 0; } } } }; /** Generates a report with our profiling data. */ protected ReportManager.Reporter _profrep = new ReportManager.Reporter() { public void appendReport (StringBuilder buf, long now, long sinceLast, boolean reset) { buf.append("* " + getName() + ":\n"); if (PresentsDObjectMgr.UNIT_PROF_ENABLED) { for (Object key : _tracker.keySet()) { UnitProfile profile = _tracker.get(key); if (key instanceof Class) { key = StringUtil.shortClassName((Class<?>)key); } buf.append(" ").append(key).append(" "); buf.append(profile).append("\n"); if (reset) { profile.clear(); } } } else { buf.append(" - Unit profiling disabled.\n"); } } }; /** The largest queue size since our last report. */ protected long _maxQueueSize; /** Records the currently invoking unit. */ protected Object _currentUnit; /** The time at which our current unit started. */ protected long _currentUnitStart; }
package org.telegram.telegrambots.api.objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.jsontype.TypeSerializer; import org.json.JSONArray; import org.json.JSONObject; import org.telegram.telegrambots.api.interfaces.IBotApiObject; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * @author Ruben Bermudez * @version 1.0 * @brief This object represents a message. * @date 20 of June of 2015 */ public class Message implements IBotApiObject { private static final String MESSAGEID_FIELD = "message_id"; private static final String FROM_FIELD = "from"; private static final String DATE_FIELD = "date"; private static final String CHAT_FIELD = "chat"; private static final String FORWARDFROM_FIELD = "forward_from"; private static final String FORWARDFROMCHAT_FIELD = "forward_from_chat"; private static final String FORWARDDATE_FIELD = "forward_date"; private static final String TEXT_FIELD = "text"; private static final String ENTITIES_FIELD = "entities"; private static final String AUDIO_FIELD = "audio"; private static final String DOCUMENT_FIELD = "document"; private static final String PHOTO_FIELD = "photo"; private static final String STICKER_FIELD = "sticker"; private static final String VIDEO_FIELD = "video"; private static final String CONTACT_FIELD = "contact"; private static final String LOCATION_FIELD = "location"; private static final String VENUE_FIELD = "venue"; private static final String PINNED_MESSAGE_FIELD = "pinned_message"; private static final String NEWCHATMEMBER_FIELD = "new_chat_member"; private static final String LEFTCHATMEMBER_FIELD = "left_chat_member"; private static final String NEWCHATTITLE_FIELD = "new_chat_title"; private static final String NEWCHATPHOTO_FIELD = "new_chat_photo"; private static final String DELETECHATPHOTO_FIELD = "delete_chat_photo"; private static final String GROUPCHATCREATED_FIELD = "group_chat_created"; private static final String REPLYTOMESSAGE_FIELD = "reply_to_message"; private static final String VOICE_FIELD = "voice"; private static final String SUPERGROUPCREATED_FIELD = "supergroup_chat_created"; private static final String CHANNELCHATCREATED_FIELD = "channel_chat_created"; private static final String MIGRATETOCHAT_FIELD = "migrate_to_chat_id"; private static final String MIGRATEFROMCHAT_FIELD = "migrate_from_chat_id"; @JsonProperty(MESSAGEID_FIELD) private Integer messageId; ///< Integer Unique message identifier @JsonProperty(FROM_FIELD) private User from; ///< Optional. Sender, can be empty for messages sent to channels @JsonProperty(DATE_FIELD) private Integer date; ///< Optional. Date the message was sent in Unix time @JsonProperty(CHAT_FIELD) private Chat chat; ///< Conversation the message belongs to @JsonProperty(FORWARDFROM_FIELD) private User forwardFrom; ///< Optional. For forwarded messages, sender of the original message @JsonProperty(FORWARDFROMCHAT_FIELD) private Chat forwardedFromChat; ///< Optional. For messages forwarded from a channel, information about the original channel @JsonProperty(FORWARDDATE_FIELD) private Integer forwardDate; ///< Optional. For forwarded messages, date the original message was sent @JsonProperty(TEXT_FIELD) private String text; ///< Optional. For text messages, the actual UTF-8 text of the message @JsonProperty(ENTITIES_FIELD) /** * Optional. For text messages, special entities like usernames, URLs, * bot commands, etc. that appear in the text */ private List<MessageEntity> entities; @JsonProperty(AUDIO_FIELD) private Audio audio; ///< Optional. Message is an audio file, information about the file @JsonProperty(DOCUMENT_FIELD) private Document document; ///< Optional. Message is a general file, information about the file @JsonProperty(PHOTO_FIELD) private List<PhotoSize> photo; ///< Optional. Message is a photo, available sizes of the photo @JsonProperty(STICKER_FIELD) private Sticker sticker; ///< Optional. Message is a sticker, information about the sticker @JsonProperty(VIDEO_FIELD) private Video video; ///< Optional. Message is a video, information about the video @JsonProperty(CONTACT_FIELD) private Contact contact; ///< Optional. Message is a shared contact, information about the contact @JsonProperty(LOCATION_FIELD) private Location location; ///< Optional. Message is a shared location, information about the location @JsonProperty(VENUE_FIELD) private Venue venue; ///< Optional. Message is a venue, information about the venue @JsonProperty(PINNED_MESSAGE_FIELD) private Message pinnedMessage; ///< Optional. Specified message was pinned. Note that the Message object in this field will not contain further reply_to_message fields even if it is itself a reply. @JsonProperty(NEWCHATMEMBER_FIELD) private User newChatMember; ///< Optional. A new member was added to the group, information about them (this member may be bot itself) @JsonProperty(LEFTCHATMEMBER_FIELD) private User leftChatMember; ///< Optional. A member was removed from the group, information about them (this member may be bot itself) @JsonProperty(NEWCHATTITLE_FIELD) private String newChatTitle; ///< Optional. A chat title was changed to this value @JsonProperty(NEWCHATPHOTO_FIELD) private List<PhotoSize> newChatPhoto; ///< Optional. A chat photo was change to this value @JsonProperty(DELETECHATPHOTO_FIELD) private Boolean deleteChatPhoto; ///< Optional. Informs that the chat photo was deleted @JsonProperty(GROUPCHATCREATED_FIELD) private Boolean groupchatCreated; ///< Optional. Informs that the group has been created @JsonProperty(REPLYTOMESSAGE_FIELD) private Message replyToMessage; @JsonProperty(VOICE_FIELD) private Voice voice; ///< Optional. Message is a voice message, information about the file @JsonProperty(SUPERGROUPCREATED_FIELD) private Boolean superGroupCreated; ///< Optional. Informs that the supergroup has been created @JsonProperty(CHANNELCHATCREATED_FIELD) private Boolean channelChatCreated; ///< Optional. Informs that the channel has been created @JsonProperty(MIGRATETOCHAT_FIELD) private Long migrateToChatId; ///< Optional. The chat has been migrated to a chat with specified identifier, not exceeding 1e13 by absolute value @JsonProperty(MIGRATEFROMCHAT_FIELD) private Long migrateFromChatId; ///< Optional. The chat has been migrated from a chat with specified identifier, not exceeding 1e13 by absolute value public Message() { super(); } public Message(JSONObject jsonObject) { super(); this.messageId = jsonObject.getInt(MESSAGEID_FIELD); if (jsonObject.has(FROM_FIELD)) { this.from = new User(jsonObject.getJSONObject(FROM_FIELD)); } if (jsonObject.has(DATE_FIELD)) { this.date = jsonObject.getInt(DATE_FIELD); } this.chat = new Chat(jsonObject.getJSONObject(CHAT_FIELD)); if (jsonObject.has(FORWARDFROMCHAT_FIELD)) { this.forwardedFromChat = new Chat(jsonObject.getJSONObject(FORWARDFROMCHAT_FIELD)); } if (jsonObject.has(FORWARDFROM_FIELD)) { this.forwardFrom = new User(jsonObject.getJSONObject(FORWARDFROM_FIELD)); } if (jsonObject.has(FORWARDDATE_FIELD)) { this.forwardDate = jsonObject.getInt(FORWARDDATE_FIELD); } if (jsonObject.has(TEXT_FIELD)) { this.text = jsonObject.getString(TEXT_FIELD); } if (jsonObject.has(ENTITIES_FIELD)) { this.entities = new ArrayList<>(); JSONArray entities = jsonObject.getJSONArray(ENTITIES_FIELD); for (int i = 0; i < entities.length(); i++) { this.entities.add(new MessageEntity(entities.getJSONObject(i))); } } if (jsonObject.has(AUDIO_FIELD)) { this.audio = new Audio(jsonObject.getJSONObject(AUDIO_FIELD)); } if (jsonObject.has(DOCUMENT_FIELD)) { this.document = new Document(jsonObject.getJSONObject(DOCUMENT_FIELD)); } if (jsonObject.has(PHOTO_FIELD)) { this.photo = new ArrayList<>(); JSONArray photos = jsonObject.getJSONArray(PHOTO_FIELD); for (int i = 0; i < photos.length(); i++) { this.photo.add(new PhotoSize(photos.getJSONObject(i))); } } if (jsonObject.has(STICKER_FIELD)) { this.sticker = new Sticker(jsonObject.getJSONObject(STICKER_FIELD)); } if (jsonObject.has(VIDEO_FIELD)) { this.video = new Video(jsonObject.getJSONObject(VIDEO_FIELD)); } if (jsonObject.has(CONTACT_FIELD)) { this.contact = new Contact(jsonObject.getJSONObject(CONTACT_FIELD)); } if (jsonObject.has(LOCATION_FIELD)) { this.location = new Location(jsonObject.getJSONObject(LOCATION_FIELD)); } if (jsonObject.has(VENUE_FIELD)) { venue = new Venue(jsonObject.getJSONObject(VENUE_FIELD)); } if (jsonObject.has(PINNED_MESSAGE_FIELD)) { pinnedMessage = new Message(jsonObject.getJSONObject(PINNED_MESSAGE_FIELD)); } if (jsonObject.has(VOICE_FIELD)) { this.voice = new Voice(jsonObject.getJSONObject(VOICE_FIELD)); } if (jsonObject.has(NEWCHATMEMBER_FIELD)) { this.newChatMember = new User(jsonObject.getJSONObject(NEWCHATMEMBER_FIELD)); } if (jsonObject.has(LEFTCHATMEMBER_FIELD)) { this.leftChatMember = new User(jsonObject.getJSONObject(LEFTCHATMEMBER_FIELD)); } if (jsonObject.has(REPLYTOMESSAGE_FIELD)) { this.replyToMessage = new Message(jsonObject.getJSONObject(REPLYTOMESSAGE_FIELD)); } if (jsonObject.has(NEWCHATTITLE_FIELD)) { this.newChatTitle = jsonObject.getString(NEWCHATTITLE_FIELD); } if (jsonObject.has(NEWCHATPHOTO_FIELD)) { JSONArray photoArray = jsonObject.getJSONArray(NEWCHATPHOTO_FIELD); this.newChatPhoto = new ArrayList<>(); for (int i = 0; i < photoArray.length(); i++) { this.newChatPhoto.add(new PhotoSize(photoArray.getJSONObject(i))); } } if (jsonObject.has(DELETECHATPHOTO_FIELD)) { this.deleteChatPhoto = true; } if (jsonObject.has(GROUPCHATCREATED_FIELD)) { this.groupchatCreated = true; } if (jsonObject.has(SUPERGROUPCREATED_FIELD)) { this.superGroupCreated = true; } if (jsonObject.has(CHANNELCHATCREATED_FIELD)) { this.channelChatCreated = true; } if (jsonObject.has(MIGRATETOCHAT_FIELD)) { this.migrateToChatId = jsonObject.getLong(MIGRATETOCHAT_FIELD); } if (jsonObject.has(MIGRATEFROMCHAT_FIELD)) { this.migrateFromChatId = jsonObject.getLong(MIGRATEFROMCHAT_FIELD); } } public Integer getMessageId() { return messageId; } public User getFrom() { return from; } public Integer getDate() { return date; } public Chat getChat() { return chat; } public User getForwardFrom() { return forwardFrom; } public Integer getForwardDate() { return forwardDate; } public String getText() { return text; } public List<MessageEntity> getEntities() { return entities; } public Audio getAudio() { return audio; } public Document getDocument() { return document; } public List<PhotoSize> getPhoto() { return photo; } public Sticker getSticker() { return sticker; } public Video getVideo() { return video; } public Contact getContact() { return contact; } public Location getLocation() { return location; } public Venue getVenue() { return venue; } public Message getPinnedMessage() { return pinnedMessage; } public User getNewChatMember() { return newChatMember; } public User getLeftChatMember() { return leftChatMember; } public String getNewChatTitle() { return newChatTitle; } public List<PhotoSize> getNewChatPhoto() { return newChatPhoto; } public Boolean getDeleteChatPhoto() { return deleteChatPhoto; } public Boolean getGroupchatCreated() { return groupchatCreated; } public Message getReplyToMessage() { return replyToMessage; } public Voice getVoice() { return voice; } public Boolean getSuperGroupCreated() { return superGroupCreated; } public Boolean getChannelChatCreated() { return channelChatCreated; } public Long getMigrateToChatId() { return migrateToChatId; } public Long getMigrateFromChatId() { return migrateFromChatId; } public boolean isGroupMessage() { return chat.isGroupChat(); } public boolean isUserMessage() { return chat.isUserChat(); } public boolean isChannelMessage() { return chat.isChannelChat(); } public boolean isSuperGroupMessage() { return chat.isSuperGroupChat(); } public Long getChatId() { return chat.getId(); } public boolean hasText() { return text != null && !text.isEmpty(); } public boolean isCommand() { if (entities != null) { for (MessageEntity entity : entities) { if (entity != null && "bot_command".equals(entity.getType())) { return text != null && !text.isEmpty(); } } } return false; } public boolean hasDocument() { return this.document != null; } public boolean isReply() { return this.replyToMessage != null; } public boolean hasLocation() { return location != null; } public Chat getForwardedFromChat() { return forwardedFromChat; } @Override public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException { gen.writeStartObject(); gen.writeNumberField(MESSAGEID_FIELD, messageId); if (from != null) { gen.writeObjectField(FROM_FIELD, from); } if (date != null) { gen.writeNumberField(DATE_FIELD, date); } gen.writeObjectField(CHAT_FIELD, chat); if (forwardedFromChat != null) { gen.writeObjectField(FORWARDFROMCHAT_FIELD, forwardedFromChat); } if (forwardFrom != null) { gen.writeObjectField(FORWARDFROM_FIELD, forwardFrom); } if (forwardDate != null) { gen.writeNumberField(FORWARDDATE_FIELD, forwardDate); } if (text != null) { gen.writeStringField(TEXT_FIELD, text); } if (audio != null) { gen.writeObjectField(AUDIO_FIELD, audio); } if (document != null) { gen.writeObjectField(DOCUMENT_FIELD, document); } if (photo != null && photo.size() > 0) { gen.writeArrayFieldStart(PHOTO_FIELD); for (PhotoSize photoSize : photo) { gen.writeObject(photoSize); } gen.writeEndArray(); } if (sticker != null) { gen.writeObjectField(STICKER_FIELD, sticker); } if (video != null) { gen.writeObjectField(VIDEO_FIELD, video); } if (contact != null) { gen.writeObjectField(CONTACT_FIELD, contact); } if (location != null) { gen.writeObjectField(LOCATION_FIELD, location); } if (venue != null) { gen.writeObjectField(VENUE_FIELD, venue); } if (voice != null) { gen.writeObjectField(VOICE_FIELD, voice); } if (newChatMember != null) { gen.writeObjectField(NEWCHATMEMBER_FIELD, newChatMember); } if (leftChatMember != null) { gen.writeObjectField(LEFTCHATMEMBER_FIELD, leftChatMember); } if (replyToMessage != null) { gen.writeObjectField(REPLYTOMESSAGE_FIELD, replyToMessage); } if (newChatTitle != null) { gen.writeStringField(NEWCHATTITLE_FIELD, newChatTitle); } if (newChatPhoto != null && newChatPhoto.size() > 0) { gen.writeArrayFieldStart(NEWCHATPHOTO_FIELD); for (PhotoSize photoSize: newChatPhoto) { gen.writeObject(photoSize); } gen.writeEndArray(); } if (deleteChatPhoto != null) { gen.writeBooleanField(DELETECHATPHOTO_FIELD, deleteChatPhoto); } if (groupchatCreated != null) { gen.writeBooleanField(GROUPCHATCREATED_FIELD, groupchatCreated); } if (superGroupCreated != null) { gen.writeBooleanField(SUPERGROUPCREATED_FIELD, superGroupCreated); } if (channelChatCreated != null) { gen.writeBooleanField(CHANNELCHATCREATED_FIELD, channelChatCreated); } if (migrateToChatId != null) { gen.writeNumberField(MIGRATETOCHAT_FIELD, migrateToChatId); } if (migrateFromChatId != null) { gen.writeNumberField(MIGRATEFROMCHAT_FIELD, migrateFromChatId); } gen.writeEndObject(); gen.flush(); } @Override public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { serialize(gen, serializers); } @Override public String toString() { return "Message{" + "messageId=" + messageId + ", from=" + from + ", date=" + date + ", chat=" + chat + ", forwardFrom=" + forwardFrom + ", forwardedFromChat=" + forwardedFromChat + ", forwardDate=" + forwardDate + ", text='" + text + '\'' + ", audio=" + audio + ", document=" + document + ", photo=" + photo + ", sticker=" + sticker + ", video=" + video + ", contact=" + contact + ", location=" + location + ", venue=" + venue + ", newChatMember=" + newChatMember + ", leftChatMember=" + leftChatMember + ", newChatTitle='" + newChatTitle + '\'' + ", newChatPhoto=" + newChatPhoto + ", deleteChatPhoto=" + deleteChatPhoto + ", groupchatCreated=" + groupchatCreated + ", replyToMessage=" + replyToMessage + ", voice=" + voice + ", superGroupCreated=" + superGroupCreated + ", channelChatCreated=" + channelChatCreated + ", migrateToChatId=" + migrateToChatId + ", migrateFromChatId=" + migrateFromChatId + '}'; } }
package edu.csus.ecs.moneybeets.narvaro.ui; import java.util.TimerTask; import java.util.zip.DataFormatException; import org.apache.log4j.Logger; import edu.csus.ecs.moneybeets.narvaro.database.DatabaseType; import edu.csus.ecs.moneybeets.narvaro.util.ConfigurationManager; import edu.csus.ecs.moneybeets.narvaro.util.TaskEngine; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.control.ComboBox; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.layout.Region; import javafx.stage.WindowEvent; /** * This class acts as the controller for the * first-time setup menu. * */ public class NarvaroSetup { private static final Logger LOG = Logger.getLogger(NarvaroSetup.class.getName()); @FXML private ComboBox<String> databaseTypeSelector; @FXML private TextField serverName; @FXML private TextField portNumber; @FXML private TextField databaseUser; @FXML private PasswordField databasePassword; @FXML public void initialize() { TaskEngine.INSTANCE.schedule(new TimerTask() { @Override public void run() { serverName.getScene().getWindow().setOnCloseRequest(new EventHandler<WindowEvent>() { @Override public void handle(final WindowEvent we) { Platform.exit(); System.exit(0); } }); } }, 1000); // uncomment to enable multi-db support //for (DatabaseType dbType : DatabaseType.values()) { // databaseTypeSelector.getItems().add(dbType.getName()); // for the time being, we'll only officially support mysql databaseTypeSelector.getItems().add(DatabaseType.mysql.getName()); installEventHandler(serverName.getParent().getParent().getParent().getParent()); } private void installEventHandler(final Node keyNode) { final EventHandler<KeyEvent> keyEventHandler = new EventHandler<KeyEvent>() { @Override public void handle(final KeyEvent keyEvent) { if (keyEvent.getCode() == KeyCode.ENTER) { handleOKButton(null); } } }; keyNode.setOnKeyReleased(keyEventHandler); } /** * This method is invoked when the OK button is pressed. * * @param event The event. */ @FXML public void handleOKButton(final ActionEvent event) { if (validate()) { writeConfig(); portNumber.getScene().getWindow().hide(); } } private boolean validate() { boolean success = true; try { String s = getServerName(); if (!"".equals(s) && s != null) { showValid(serverName); } else { LOG.error("Server Name not valid: " + s); showError(serverName); success = false; } } catch (Exception e) { LOG.error(e.getMessage(), e); showError(serverName); } try { String s = getDatabasePassword(); if (!"".equals(s) && s != null) { showValid(databasePassword); } else { LOG.error("Database Password not valid: " + s); showError(databasePassword); success = false; } } catch (Exception e) { LOG.error(e.getMessage(), e); showError(databaseUser); } try { String s = getDatabaseUser(); if (!"".equals(s) && s != null) { showValid(databaseUser); } else { LOG.error("Database user not valid: " + s); showError(databaseUser); success = false; } } catch (Exception e) { LOG.error(e.getMessage(), e); showError(databaseUser); } try { int i = getPortNumber(); if (i > 0) { showValid(portNumber); } else { LOG.error("Port number not valid: " + i); showError(portNumber); success = false; } } catch (Exception e) { LOG.error(e.getMessage(), e); } return success; } // helper methods private void showValid(final Region r) { Platform.runLater(new Runnable() { @Override public void run() { r.setStyle("-fx-control-inner-background:#87D37C;"); } }); } private void showError(final Region r) { Platform.runLater(new Runnable() { @Override public void run() { r.setStyle("-fx-control-inner-background:#EF4836;"); } }); } private void resetValid(final Region r) { Platform.runLater(new Runnable() { @Override public void run() { r.setStyle("-fx-control-inner-background:#FFFFFF;"); } }); } /** * Writes configs specified by user in the menu page back into the runtime config file. */ private void writeConfig() { ConfigurationManager.NARVARO.setProperty("narvaro.connectionprovider.classname", getConnectionProviderClassName()); ConfigurationManager.NARVARO .setProperty("narvaro.connectionprovider.serverurl", getDatabaseConnectionUrl()); ConfigurationManager.NARVARO.setProperty("narvaro.connectionprovider.username", getDatabaseUser()); ConfigurationManager.NARVARO.setProperty("narvaro.connectionprovider.password", getDatabasePassword()); ConfigurationManager.NARVARO.saveProperties(); } /** * @return The connection provider class name. */ private String getConnectionProviderClassName() { DatabaseType dbType = null; try { dbType = getDatabaseType(); } catch (Exception e) { LOG.error("Unable to determine database type", e); } if (dbType == DatabaseType.sqlserver) { return "edu.csus.ecs.moneybeets.narvaro.database.provider.SQLServerConnectionProvider"; } else { return "edu.csus.ecs.moneybeets.narvaro.database.provider.MySQLConnectionProvider"; } } /** * @return The complete database connection url. */ private String getDatabaseConnectionUrl() { StringBuilder url = new StringBuilder("jdbc:"); DatabaseType dbType = null; try { dbType = getDatabaseType(); } catch (Exception e) { LOG.error("Unable to determine database type", e); } if (dbType == DatabaseType.sqlserver) { url.append("sqlserver: url.append(getServerName()); url.append(":"); url.append(getPortNumber()); url.append("/narvaro"); } else { url.append("mysql: url.append(getServerName()); url.append(":"); url.append(getPortNumber()); url.append("/narvaro?rewriteBatchedStatements=true"); } return url.toString(); } /** * @return the Database type. * @throws DataFormatException If selected option is not a valid db type. */ private DatabaseType getDatabaseType() throws DataFormatException { return DatabaseType.fromString( databaseTypeSelector.getSelectionModel().getSelectedItem().toString().toLowerCase()); } /** * @return the serverName */ private String getServerName() { return serverName.getText(); } /** * @return the portNumber */ private int getPortNumber() { int port = -1; try { port = Integer.parseInt(portNumber.getText()); } catch (Exception e) { LOG.error("Port number is invalid: " + portNumber.getText()); LOG.error("Using default port for database type"); } return port; } /** * @return the databaseUser */ private String getDatabaseUser() { return databaseUser.getText(); } /** * @return the databasePassword */ private String getDatabasePassword() { return databasePassword.getText(); } }
package org.onedatashare.server.service; import org.codehaus.jackson.map.ObjectMapper; import org.onedatashare.server.model.core.*; import org.onedatashare.server.model.credential.UserInfoCredential; import org.onedatashare.server.model.useraction.UserAction; import org.onedatashare.server.model.useraction.UserActionResource; import org.onedatashare.server.module.vfs.VfsResource; import org.onedatashare.server.module.vfs.VfsSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URI; import java.nio.charset.StandardCharsets; import java.security.InvalidKeyException; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.util.ArrayList; import java.util.Base64; import java.util.List; @Service public class VfsService implements ResourceService<VfsResource> { @Autowired private UserService userService; @Autowired private JobService jobService; public Mono<VfsResource> getResourceWithUserActionUri(String cookie, UserAction userAction) { fixSCPUri(userAction); final String path = pathFromUri(userAction.uri); return userService.getLoggedInUser(cookie) .map(user -> new UserInfoCredential(userAction.credential)) .map(credential -> new VfsSession(URI.create(userAction.uri), credential)) .flatMap(VfsSession::initialize) .flatMap(vfsSession -> vfsSession.select(path)); } public Mono<VfsResource> getResourceWithUserActionUri(String cookie, String userActionString) { List<String> path = new ArrayList<>(); return userService.getLoggedInUser(cookie) .map(user -> { byte[] encryptedString = Base64.getDecoder().decode(userActionString); byte[] privateKeyString = Base64.getDecoder().decode(user.getPrivateKey()); PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(privateKeyString); KeyFactory fact = null; try { fact = KeyFactory.getInstance("RSA"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } PrivateKey privateKey = null; try { privateKey = fact.generatePrivate(spec); } catch (InvalidKeySpecException e) { e.printStackTrace(); } Cipher decrypt = null; try { decrypt = Cipher.getInstance("RSA"); decrypt.init(Cipher.DECRYPT_MODE, privateKey); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } String decryptedMessage = null; try { decryptedMessage = new String(decrypt.doFinal(encryptedString), StandardCharsets.UTF_8); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } System.out.println(decryptedMessage); ObjectMapper objectMapper = new ObjectMapper(); UserActionResource userActionResource = null; try { userActionResource = objectMapper.readValue(decryptedMessage, UserActionResource.class); } catch (IOException e) { e.printStackTrace(); } UserInfoCredential userInfoCredential = new UserInfoCredential(userActionResource.credential); VfsSession vfsSession = new VfsSession(URI.create(userActionResource.uri), userInfoCredential); path.add(pathFromUri(userActionResource.uri)); return vfsSession; }).flatMap(VfsSession::initialize) .flatMap(vfsSession -> vfsSession.select(path.get(0))); } public Mono<VfsResource> getResourceWithUserActionResource(String cookie, UserActionResource userActionResource) { fixSCPUri(userActionResource); final String path = pathFromUri(userActionResource.uri); return userService.getLoggedInUser(cookie) .map(user -> new UserInfoCredential(userActionResource.credential)) .map(credential -> new VfsSession(URI.create(userActionResource.uri), credential)) .flatMap(VfsSession::initialize) .flatMap(vfsSession -> vfsSession.select(path)); } public void fixSCPUri(UserAction userAction){ if(userAction.type.equals("scp: userAction.type = "sftp: userAction.uri = "sftp://" + userAction.uri.substring(6); } } public void fixSCPUri(UserActionResource userAction){ if(userAction.type.equals("scp: userAction.type = "sftp: userAction.uri = "sftp://" + userAction.uri.substring(6); } } public String pathFromUri(String uri) { String path = ""; if (uri.contains("dropbox: path = uri.split("dropbox: } else path = uri; try { path = java.net.URLDecoder.decode(path, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return path; } public Mono<Stat> list(String cookie, UserAction userAction) { return getResourceWithUserActionUri(cookie, userAction).flatMap(VfsResource::stat); } public Mono<Stat> mkdir(String cookie, UserAction userAction) { return getResourceWithUserActionUri(cookie, userAction) .flatMap(VfsResource::mkdir) .flatMap(VfsResource::stat); } public Mono<VfsResource> delete(String cookie, UserAction userAction) { return getResourceWithUserActionUri(cookie, userAction) .flatMap(VfsResource::delete); } public Mono<Job> submit(String cookie, UserAction userAction) { return userService.getLoggedInUser(cookie) .map(user -> { Job job = new Job(userAction.src, userAction.dest); job.setStatus(JobStatus.scheduled); job = user.saveJob(job); userService.saveUser(user).subscribe(); return job; }) .flatMap(jobService::saveJob) .doOnSuccess(job -> processTransferFromJob(job, cookie)) .subscribeOn(Schedulers.elastic()); } @Override public Mono<String> download(String cookie, UserAction userAction) { return null; } public void processTransferFromJob(Job job, String cookie) { Transfer<Resource, Resource> transfer = new Transfer<>(); getResourceWithUserActionResource(cookie, job.src) .map(transfer::setSource) .flatMap(t -> getResourceWithUserActionResource(cookie, job.dest)) .map(transfer::setDestination) .flux() .flatMap(transfer1 -> transfer1.start(1L << 20)) .doOnSubscribe(s -> job.setStatus(JobStatus.processing)) .doFinally(s -> { job.setStatus(JobStatus.complete); jobService.saveJob(job).subscribe(); }) .map(job::updateJobWithTransferInfo) .flatMap(jobService::saveJob) .subscribe(); } public Mono<String> getDownloadURL(String cookie, UserAction userAction) { return getResourceWithUserActionUri(cookie, userAction).flatMap(VfsResource::getDownloadURL); } public Mono<ResponseEntity> getSftpDownloadStream(String cookie, UserActionResource userActionResource) { return getResourceWithUserActionResource(cookie, userActionResource).flatMap(VfsResource::getSftpObject); } }
package org.testeditor.fixture.host; import org.testeditor.fixture.core.interaction.FixtureMethod; import org.testeditor.fixture.host.net.Connection; import org.testeditor.fixture.host.s3270.Status; import org.testeditor.fixture.host.s3270.options.CharacterSet; import org.testeditor.fixture.host.s3270.options.TerminalMode; import org.testeditor.fixture.host.s3270.options.TerminalType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class HostDriverFixture { private static final Logger logger = LoggerFactory.getLogger(HostDriverFixture.class); private Connection connection; public HostDriverFixture() { this.connection = new Connection(); } public HostDriverFixture(Connection connection) { this.connection = connection; } /** * The Connection is responsible for the subprocess of the s3270/ws3270 * application. The whole communication will be done through this * subprocess. * * @param s3270Path * The path to the s3270/ws3270 application. * @param hostname * The hostname to be connected to. * @param port * The port of the host to be connected to. */ @FixtureMethod public boolean connect(String s3270Path, String hostname, int port) { logger.info("Host-Fixture connecting ..."); TerminalType type = TerminalType.TYPE_3279; TerminalMode mode = TerminalMode.MODE_24x80; CharacterSet charSet = CharacterSet.CHAR_GERMAN_EURO; connection.connect(s3270Path, hostname, port, type, mode, charSet); if (connection.isConnected()) { logger.info("successfully connected to host='{}', port='{}'", hostname, port); return true; } else { logger.info("The connection to host '" + hostname + "' on port '" + port + "' could not be established."); return false; } } /** * Disconnects from host. * {@link org.testeditor.fixture.host.net.Connection#disconnect()} * */ @FixtureMethod public boolean disconnect() { logger.info("Disconnecting ..."); return connection.disconnect(); } /** * Provides the Status Objekt which will be returned when an input or action * is executed. * * @return {@link org.testeditor.fixture.host.s3270.Status} */ @FixtureMethod public Status getStatus() { logger.info("get Status ..."); return connection.getStatus(); } /** * Provides a possibility to type a value into a specified field through the * parameters row and column. * <p> * Attention! The input field has to be unprotected and not hidden. If they * are, the s3270 emulation will lock further actions. * * @param value * the value to be typed into the input field of a mainframe * window. * @param row * the row of the input field * @param col * the column of the input field. */ @FixtureMethod public void typeAt(String value, int row, int col) { setCursorPosition(row, col); waiting(100); connection.doCommand("String(\"" + value + "\")"); connection.doCommand("ascii"); // just to see if typed in successfully. } private void waiting(long miliseconds) { try { Thread.sleep(miliseconds); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw new RuntimeException(ex); } } private void setCursorPosition(int row, int col) { connection.doCommand("MoveCursor(" + row + "," + col + ")"); } }
package com.nincraft.ninbot.components.fun; import com.nincraft.ninbot.components.common.MessageUtils; import com.nincraft.ninbot.components.config.ConfigConstants; import com.nincraft.ninbot.components.config.ConfigService; import lombok.val; import net.dv8tion.jda.core.events.message.MessageReceivedEvent; import net.dv8tion.jda.core.hooks.ListenerAdapter; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.Random; @Component public class Dadbot extends ListenerAdapter { private Random random; private ConfigService configService; private MessageUtils messageUtils; @Autowired public Dadbot(ConfigService configService, MessageUtils messageUtils) { random = new Random(); this.configService = configService; this.messageUtils = messageUtils; } @Override public void onMessageReceived(MessageReceivedEvent event) { if (!event.getAuthor().isBot()) { parseMessage(event); } } private void parseMessage(MessageReceivedEvent event) { val message = event.getMessage().getContentStripped(); val first = message.split("\\s+")[0]; if (!(first.equalsIgnoreCase("I'm") || first.equalsIgnoreCase("im")) || (!event.getChannelType().isGuild())) { return; } if (StringUtils.isNotBlank(message) && message.split("\\s+").length >= 1 && checkChance()) { hiImDad(message, event); } } private boolean channelIsBlacklisted(String serverId, String channelId) { val channelConfigList = configService.getConfigByName(serverId, ConfigConstants.DADBOT_BLACKLIST_CHANNEL); return channelConfigList.stream().anyMatch(config -> config.getValue().equals(channelId)); } private void hiImDad(String message, MessageReceivedEvent event) { if (!channelIsBlacklisted(event.getGuild().getId(), event.getChannel().getId())) { return; } String stringBuilder = "Hi" + message.substring(message.indexOf(' ')) + ", I'm Dad!"; messageUtils.sendMessage(event.getChannel(), stringBuilder); } private boolean checkChance() { return random.nextInt(100) < 10; } }
package net.sf.picard.analysis; import java.io.File; import java.util.*; import net.sf.picard.PicardException; import net.sf.picard.analysis.directed.InsertSizeMetricsCollector; import net.sf.picard.cmdline.Option; import net.sf.picard.cmdline.Usage; import net.sf.picard.io.IoUtil; import net.sf.picard.metrics.MetricsFile; import net.sf.picard.reference.ReferenceSequence; import net.sf.picard.util.CollectionUtil; import net.sf.picard.util.Log; import net.sf.picard.util.RExecutor; import net.sf.samtools.SAMFileHeader; import net.sf.samtools.SAMRecord; /** * Command line program to read non-duplicate insert sizes, create a histogram * and report distribution statistics. * * @author Doug Voet (dvoet at broadinstitute dot org) */ public class CollectInsertSizeMetrics extends SinglePassSamProgram { private static final Log log = Log.getInstance(CollectInsertSizeMetrics.class); private static final String HISTOGRAM_R_SCRIPT = "net/sf/picard/analysis/insertSizeHistogram.R"; // Usage and parameters @Usage public String USAGE = getStandardUsagePreamble() + "Reads a SAM or BAM file and writes a file containing metrics about " + "the statistical distribution of insert size (excluding duplicates) " + "and generates a histogram plot.\n"; @Option(shortName="H", doc="File to write insert size histogram chart to.") public File HISTOGRAM_FILE; @Option(doc="Generate mean, sd and plots by trimming the data down to MEDIAN + DEVIATIONS*MEDIAN_ABSOLUTE_DEVIATION. " + "This is done because insert size data typically includes enough anomalous values from chimeras and other " + "artifacts to make the mean and sd grossly misleading regarding the real distribution.") public double DEVIATIONS = 10; @Option(shortName="W", doc="Explicitly sets the histogram width, overriding automatic truncation of histogram tail. " + "Also, when calculating mean and standard deviation, only bins <= HISTOGRAM_WIDTH will be included.", optional=true) public Integer HISTOGRAM_WIDTH = null; @Option(shortName="M", doc="When generating the histogram, discard any data categories (out of FR, TANDEM, RF) that have fewer than this " + "percentage of overall reads. (Range: 0 to 1).") public float MINIMUM_PCT = 0.05f; @Option(shortName="LEVEL", doc="The level(s) at which to accumulate metrics. ") private Set<MetricAccumulationLevel> METRIC_ACCUMULATION_LEVEL = CollectionUtil.makeSet(MetricAccumulationLevel.ALL_READS); // Calculates InsertSizeMetrics for all METRIC_ACCUMULATION_LEVELs provided private InsertSizeMetricsCollector multiCollector; /** Required main method implementation. */ public static void main(final String[] argv) { new CollectInsertSizeMetrics().instanceMainWithExit(argv); } /** * Put any custom command-line validation in an override of this method. * clp is initialized at this point and can be used to print usage and access argv. * Any options set by command-line parser can be validated. * * @return null if command line is valid. If command line is invalid, returns an array of error message * to be written to the appropriate place. */ @Override protected String[] customCommandLineValidation() { if (MINIMUM_PCT < 0 || MINIMUM_PCT > 0.5) { return new String[]{"MINIMUM_PCT was set to " + MINIMUM_PCT + ". It must be between 0 and 0.5 so all data categories don't get discarded."}; } return super.customCommandLineValidation(); } @Override protected boolean usesNoRefReads() { return false; } @Override protected void setup(final SAMFileHeader header, final File samFile) { IoUtil.assertFileIsWritable(OUTPUT); IoUtil.assertFileIsWritable(HISTOGRAM_FILE); //Delegate actual collection to InsertSizeMetricCollector multiCollector = new InsertSizeMetricsCollector(METRIC_ACCUMULATION_LEVEL, header.getReadGroups(), MINIMUM_PCT, HISTOGRAM_WIDTH, DEVIATIONS); } @Override protected void acceptRead(final SAMRecord record, final ReferenceSequence ref) { multiCollector.acceptRecord(record, ref); } @Override protected void finish() { multiCollector.finish(); final MetricsFile<InsertSizeMetrics, Integer> file = getMetricsFile(); multiCollector.addAllLevelsToFile(file); if(file.getNumHistograms() == 0) { //can happen if user sets MINIMUM_PCT = 0.5, etc. log.warn("All data categories were discarded because they contained < " + MINIMUM_PCT + " of the total aligned paired data."); final InsertSizeMetricsCollector.PerUnitInsertSizeMetricsCollector allReadsCollector = (InsertSizeMetricsCollector.PerUnitInsertSizeMetricsCollector) multiCollector.getAllReadsCollector(); log.warn("Total mapped pairs in all categories: " + (allReadsCollector == null ? allReadsCollector : allReadsCollector.getTotalInserts())); } else { file.write(OUTPUT); final int rResult; if(HISTOGRAM_WIDTH == null) { rResult = RExecutor.executeFromClasspath( HISTOGRAM_R_SCRIPT, OUTPUT.getAbsolutePath(), HISTOGRAM_FILE.getAbsolutePath(), INPUT.getName()); } else { rResult = RExecutor.executeFromClasspath( HISTOGRAM_R_SCRIPT, OUTPUT.getAbsolutePath(), HISTOGRAM_FILE.getAbsolutePath(), INPUT.getName(), String.valueOf( HISTOGRAM_WIDTH ) ); //HISTOGRAM_WIDTH is passed because R automatically sets histogram width to the last //bin that has data, which may be less than HISTOGRAM_WIDTH and confuse the user. } if (rResult != 0) { throw new PicardException("R script " + HISTOGRAM_R_SCRIPT + " failed with return code " + rResult); } } } }
package org.owasp.esapi.reference; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.text.DateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import org.owasp.esapi.ESAPI; import org.owasp.esapi.Encoder; import org.owasp.esapi.ValidationErrorList; import org.owasp.esapi.ValidationRule; import org.owasp.esapi.Validator; import org.owasp.esapi.errors.IntrusionException; import org.owasp.esapi.errors.ValidationAvailabilityException; import org.owasp.esapi.errors.ValidationException; import org.owasp.esapi.reference.validation.CreditCardValidationRule; import org.owasp.esapi.reference.validation.DateValidationRule; import org.owasp.esapi.reference.validation.HTMLValidationRule; import org.owasp.esapi.reference.validation.IntegerValidationRule; import org.owasp.esapi.reference.validation.NumberValidationRule; import org.owasp.esapi.reference.validation.StringValidationRule; public class DefaultValidator implements org.owasp.esapi.Validator { private static volatile Validator instance = null; public static Validator getInstance() { if ( instance == null ) { synchronized ( Validator.class ) { if ( instance == null ) { instance = new DefaultValidator(); } } } return instance; } /** A map of validation rules */ private Map<String, ValidationRule> rules = new HashMap<String, ValidationRule>(); /** The encoder to use for canonicalization */ private Encoder encoder = null; /** The encoder to use for file system */ private static Validator fileValidator = null; /** Initialize file validator with an appropriate set of codecs */ static { List<String> list = new ArrayList<String>(); list.add( "HTMLEntityCodec" ); list.add( "PercentCodec" ); Encoder fileEncoder = new DefaultEncoder( list ); fileValidator = new DefaultValidator( fileEncoder ); } /** * Default constructor uses the ESAPI standard encoder for canonicalization. */ public DefaultValidator() { this.encoder = ESAPI.encoder(); } /** * Construct a new DefaultValidator that will use the specified * Encoder for canonicalization. * * @param encoder */ public DefaultValidator( Encoder encoder ) { this.encoder = encoder; } /** * Add a validation rule to the registry using the "type name" of the rule as the key. */ public void addRule( ValidationRule rule ) { rules.put( rule.getTypeName(), rule ); } /** * Get a validation rule from the registry with the "type name" of the rule as the key. */ public ValidationRule getRule( String name ) { return rules.get( name ); } public boolean isValidInput(String context, String input, String type, int maxLength, boolean allowNull) throws IntrusionException { try { getValidInput( context, input, type, maxLength, allowNull); return true; } catch( Exception e ) { return false; } } public String getValidInput(String context, String input, String type, int maxLength, boolean allowNull) throws ValidationException { StringValidationRule rvr = new StringValidationRule( type, encoder ); Pattern p = ESAPI.securityConfiguration().getValidationPattern( type ); if ( p != null ) { rvr.addWhitelistPattern( p ); } else { rvr.addWhitelistPattern( type ); } rvr.setMaximumLength(maxLength); rvr.setAllowNull(allowNull); return rvr.getValid(context, input); } public String getValidInput(String context, String input, String type, int maxLength, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidInput(context, input, type, maxLength, allowNull); } catch (ValidationException e) { errors.addError(context, e); } // error has been added to list, so return original input // TODO - optimize so that invalid input is not canonicalized twice return encoder.canonicalize(input); } /** * {@inheritDoc} */ public boolean isValidDate(String context, String input, DateFormat format, boolean allowNull) throws IntrusionException { try { getValidDate( context, input, format, allowNull); return true; } catch( Exception e ) { return false; } } /** * {@inheritDoc} */ public Date getValidDate(String context, String input, DateFormat format, boolean allowNull) throws ValidationException, IntrusionException { DateValidationRule dvr = new DateValidationRule( "SimpleDate", encoder, format); dvr.setAllowNull(allowNull); return dvr.getValid(context, input); } /** * {@inheritDoc} */ public Date getValidDate(String context, String input, DateFormat format, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidDate(context, input, format, allowNull); } catch (ValidationException e) { errors.addError(context, e); } // error has been added to list, so return null return null; } /** * {@inheritDoc} */ public boolean isValidSafeHTML(String context, String input, int maxLength, boolean allowNull) throws IntrusionException { try { getValidSafeHTML( context, input, maxLength, allowNull); return true; } catch( Exception e ) { return false; } } /** * {@inheritDoc} * * This implementation relies on the OWASP AntiSamy project. */ public String getValidSafeHTML( String context, String input, int maxLength, boolean allowNull ) throws ValidationException, IntrusionException { HTMLValidationRule hvr = new HTMLValidationRule( "safehtml", encoder ); hvr.setMaximumLength(maxLength); hvr.setAllowNull(allowNull); return hvr.getValid(context, input); } /** * {@inheritDoc} */ public String getValidSafeHTML(String context, String input, int maxLength, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidSafeHTML(context, input, maxLength, allowNull); } catch (ValidationException e) { errors.addError(context, e); } // error has been added to list, so return original input return input; } /** * {@inheritDoc} */ public boolean isValidCreditCard(String context, String input, boolean allowNull) throws IntrusionException { try { getValidCreditCard( context, input, allowNull); return true; } catch( Exception e ) { return false; } } /** * {@inheritDoc} */ public String getValidCreditCard(String context, String input, boolean allowNull) throws ValidationException, IntrusionException { CreditCardValidationRule ccvr = new CreditCardValidationRule( "creditcard", encoder ); ccvr.setAllowNull(allowNull); return ccvr.getValid(context, input); } /** * {@inheritDoc} */ public String getValidCreditCard(String context, String input, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidCreditCard(context, input, allowNull); } catch (ValidationException e) { errors.addError(context, e); } // error has been added to list, so return original input // TODO - optimize so that invalid input is not canonicalized twice return encoder.canonicalize(input); } /** * {@inheritDoc} * * <p><b>Note:</b> On platforms that support symlinks, this function will fail canonicalization if directorypath * is a symlink. For example, on MacOS X, /etc is actually /private/etc. If you mean to use /etc, use its real * path (/private/etc), not the symlink (/etc).</p> */ public boolean isValidDirectoryPath(String context, String input, File parent, boolean allowNull) throws IntrusionException { try { getValidDirectoryPath( context, input, parent, allowNull); return true; } catch( Exception e ) { return false; } } /** * {@inheritDoc} */ public String getValidDirectoryPath(String context, String input, File parent, boolean allowNull) throws ValidationException, IntrusionException { try { if (isEmpty(input)) { if (allowNull) return null; throw new ValidationException( context + ": Input directory path required", "Input directory path required: context=" + context + ", input=" + input, context ); } File dir = new File( input ); // check dir exists and parent exists and dir is inside parent if ( !dir.exists() ) { throw new ValidationException( context + ": Invalid directory name", "Invalid directory, does not exist: context=" + context + ", input=" + input ); } if ( !dir.isDirectory() ) { throw new ValidationException( context + ": Invalid directory name", "Invalid directory, not a directory: context=" + context + ", input=" + input ); } if ( !parent.exists() ) { throw new ValidationException( context + ": Invalid directory name", "Invalid directory, specified parent does not exist: context=" + context + ", input=" + input + ", parent=" + parent ); } if ( !parent.isDirectory() ) { throw new ValidationException( context + ": Invalid directory name", "Invalid directory, specified parent is not a directory: context=" + context + ", input=" + input + ", parent=" + parent ); } if ( !dir.getCanonicalPath().startsWith(parent.getCanonicalPath() ) ) { throw new ValidationException( context + ": Invalid directory name", "Invalid directory, not inside specified parent: context=" + context + ", input=" + input + ", parent=" + parent ); } // check canonical form matches input String canonicalPath = dir.getCanonicalPath(); String canonical = fileValidator.getValidInput( context, canonicalPath, "DirectoryName", 255, false); if ( !canonical.equals( input ) ) { throw new ValidationException( context + ": Invalid directory name", "Invalid directory name does not match the canonical path: context=" + context + ", input=" + input + ", canonical=" + canonical, context ); } return canonical; } catch (Exception e) { throw new ValidationException( context + ": Invalid directory name", "Failure to validate directory path: context=" + context + ", input=" + input, e, context ); } } /** * {@inheritDoc} */ public String getValidDirectoryPath(String context, String input, File parent, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidDirectoryPath(context, input, parent, allowNull); } catch (ValidationException e) { errors.addError(context, e); } // error has been added to list, so return original input return input; } /** * {@inheritDoc} */ public boolean isValidFileName(String context, String input, boolean allowNull) throws IntrusionException { return isValidFileName( context, input, ESAPI.securityConfiguration().getAllowedFileExtensions(), allowNull ); } /** * {@inheritDoc} */ public boolean isValidFileName(String context, String input, List<String> allowedExtensions, boolean allowNull) throws IntrusionException { try { getValidFileName( context, input, allowedExtensions, allowNull); return true; } catch( Exception e ) { return false; } } /** * {@inheritDoc} */ public String getValidFileName(String context, String input, List<String> allowedExtensions, boolean allowNull) throws ValidationException, IntrusionException { if ((allowedExtensions == null) || (allowedExtensions.isEmpty())) { throw new ValidationException( "Internal Error", "You called getValidFileName with an empty or null list of allowed Extensions, therefor no files can be uploaded" ); } String canonical = ""; // detect path manipulation try { if (isEmpty(input)) { if (allowNull) return null; throw new ValidationException( context + ": Input file name required", "Input required: context=" + context + ", input=" + input, context ); } // do basic validation canonical = new File(input).getCanonicalFile().getName(); getValidInput( context, input, "FileName", 255, true ); File f = new File(canonical); String c = f.getCanonicalPath(); String cpath = c.substring(c.lastIndexOf(File.separator) + 1); // the path is valid if the input matches the canonical path if (!input.equals(cpath)) { throw new ValidationException( context + ": Invalid file name", "Invalid directory name does not match the canonical path: context=" + context + ", input=" + input + ", canonical=" + canonical, context ); } } catch (IOException e) { throw new ValidationException( context + ": Invalid file name", "Invalid file name does not exist: context=" + context + ", canonical=" + canonical, e, context ); } // verify extensions Iterator<String> i = allowedExtensions.iterator(); while (i.hasNext()) { String ext = i.next(); if (input.toLowerCase().endsWith(ext.toLowerCase())) { return canonical; } } throw new ValidationException( context + ": Invalid file name does not have valid extension ( "+allowedExtensions+")", "Invalid file name does not have valid extension ( "+allowedExtensions+"): context=" + context+", input=" + input, context ); } /** * {@inheritDoc} */ public String getValidFileName(String context, String input, List<String> allowedParameters, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidFileName(context, input, allowedParameters, allowNull); } catch (ValidationException e) { errors.addError(context, e); } // error has been added to list, so return original input // TODO - optimize so that invalid input is not canonicalized twice try { return new File(input).getCanonicalFile().getName(); } catch (IOException e) { // TODO = consider logging canonicalization error? return input; } } /** * {@inheritDoc} */ public boolean isValidNumber(String context, String input, long minValue, long maxValue, boolean allowNull) throws IntrusionException { try { getValidNumber(context, input, minValue, maxValue, allowNull); return true; } catch( Exception e ) { return false; } } /** * {@inheritDoc} */ public Double getValidNumber(String context, String input, long minValue, long maxValue, boolean allowNull) throws ValidationException, IntrusionException { Double minDoubleValue = new Double(minValue); Double maxDoubleValue = new Double(maxValue); return getValidDouble(context, input, minDoubleValue.doubleValue(), maxDoubleValue.doubleValue(), allowNull); } /** * {@inheritDoc} */ public Double getValidNumber(String context, String input, long minValue, long maxValue, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidNumber(context, input, minValue, maxValue, allowNull); } catch (ValidationException e) { errors.addError(context, e); } // error has been added to list, so return null return null; } /** * {@inheritDoc} */ public boolean isValidDouble(String context, String input, double minValue, double maxValue, boolean allowNull) throws IntrusionException { try { getValidDouble( context, input, minValue, maxValue, allowNull ); return true; } catch( Exception e ) { return false; } } /** * {@inheritDoc} */ public Double getValidDouble(String context, String input, double minValue, double maxValue, boolean allowNull) throws ValidationException, IntrusionException { NumberValidationRule nvr = new NumberValidationRule( "number", encoder, minValue, maxValue ); nvr.setAllowNull(allowNull); return nvr.getValid(context, input); } /** * {@inheritDoc} */ public Double getValidDouble(String context, String input, double minValue, double maxValue, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidDouble(context, input, minValue, maxValue, allowNull); } catch (ValidationException e) { errors.addError(context, e); } // error has been added to list, so return null return null; } /** * {@inheritDoc} */ public boolean isValidInteger(String context, String input, int minValue, int maxValue, boolean allowNull) throws IntrusionException { try { getValidInteger( context, input, minValue, maxValue, allowNull); return true; } catch( ValidationException e ) { return false; } } /** * {@inheritDoc} */ public Integer getValidInteger(String context, String input, int minValue, int maxValue, boolean allowNull) throws ValidationException, IntrusionException { IntegerValidationRule ivr = new IntegerValidationRule( "number", encoder, minValue, maxValue ); ivr.setAllowNull(allowNull); return ivr.getValid(context, input); } /** * {@inheritDoc} */ public Integer getValidInteger(String context, String input, int minValue, int maxValue, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidInteger(context, input, minValue, maxValue, allowNull); } catch (ValidationException e) { errors.addError(context, e); } // error has been added to list, so return original input return null; } /** * {@inheritDoc} */ public boolean isValidFileContent(String context, byte[] input, int maxBytes, boolean allowNull) throws IntrusionException { try { getValidFileContent( context, input, maxBytes, allowNull); return true; } catch( Exception e ) { return false; } } /** * {@inheritDoc} */ public byte[] getValidFileContent(String context, byte[] input, int maxBytes, boolean allowNull) throws ValidationException, IntrusionException { if (isEmpty(input)) { if (allowNull) return null; throw new ValidationException( context + ": Input required", "Input required: context=" + context + ", input=" + input, context ); } long esapiMaxBytes = ESAPI.securityConfiguration().getAllowedFileUploadSize(); if (input.length > esapiMaxBytes ) throw new ValidationException( context + ": Invalid file content can not exceed " + esapiMaxBytes + " bytes", "Exceeded ESAPI max length", context ); if (input.length > maxBytes ) throw new ValidationException( context + ": Invalid file content can not exceed " + maxBytes + " bytes", "Exceeded maxBytes ( " + input.length + ")", context ); return input; } /** * {@inheritDoc} */ public byte[] getValidFileContent(String context, byte[] input, int maxBytes, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidFileContent(context, input, maxBytes, allowNull); } catch (ValidationException e) { errors.addError(context, e); } // error has been added to list, so return original input return input; } /** * {@inheritDoc} * * <p><b>Note:</b> On platforms that support symlinks, this function will fail canonicalization if directorypath * is a symlink. For example, on MacOS X, /etc is actually /private/etc. If you mean to use /etc, use its real * path (/private/etc), not the symlink (/etc).</p> */ public boolean isValidFileUpload(String context, String directorypath, String filename, File parent, byte[] content, int maxBytes, boolean allowNull) throws IntrusionException { return( isValidFileName( context, filename, allowNull ) && isValidDirectoryPath( context, directorypath, parent, allowNull ) && isValidFileContent( context, content, maxBytes, allowNull ) ); } /** * {@inheritDoc} */ public void assertValidFileUpload(String context, String directorypath, String filename, File parent, byte[] content, int maxBytes, List<String> allowedExtensions, boolean allowNull) throws ValidationException, IntrusionException { getValidFileName( context, filename, allowedExtensions, allowNull ); getValidDirectoryPath( context, directorypath, parent, allowNull ); getValidFileContent( context, content, maxBytes, allowNull ); } /** * {@inheritDoc} */ public void assertValidFileUpload(String context, String filepath, String filename, File parent, byte[] content, int maxBytes, List<String> allowedExtensions, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { assertValidFileUpload(context, filepath, filename, parent, content, maxBytes, allowedExtensions, allowNull); } catch (ValidationException e) { errors.addError(context, e); } } /** * {@inheritDoc} * * Returns true if input is a valid list item. */ public boolean isValidListItem(String context, String input, List<String> list) { try { getValidListItem( context, input, list); return true; } catch( Exception e ) { return false; } } /** * Returns the list item that exactly matches the canonicalized input. Invalid or non-matching input * will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. */ public String getValidListItem(String context, String input, List<String> list) throws ValidationException, IntrusionException { if (list.contains(input)) return input; throw new ValidationException( context + ": Invalid list item", "Invalid list item: context=" + context + ", input=" + input, context ); } /** * ValidationErrorList variant of getValidListItem * * @param errors */ public String getValidListItem(String context, String input, List<String> list, ValidationErrorList errors) throws IntrusionException { try { return getValidListItem(context, input, list); } catch (ValidationException e) { errors.addError(context, e); } // error has been added to list, so return original input return input; } /** * {@inheritDoc} */ public boolean isValidHTTPRequestParameterSet(String context, HttpServletRequest request, Set<String> requiredNames, Set<String> optionalNames) { try { assertValidHTTPRequestParameterSet( context, request, requiredNames, optionalNames); return true; } catch( Exception e ) { return false; } } /** * Validates that the parameters in the current request contain all required parameters and only optional ones in * addition. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. * * Uses current HTTPRequest */ public void assertValidHTTPRequestParameterSet(String context, HttpServletRequest request, Set<String> required, Set<String> optional) throws ValidationException, IntrusionException { Set<String> actualNames = request.getParameterMap().keySet(); // verify ALL required parameters are present Set<String> missing = new HashSet<String>(required); missing.removeAll(actualNames); if (missing.size() > 0) { throw new ValidationException( context + ": Invalid HTTP request missing parameters", "Invalid HTTP request missing parameters " + missing + ": context=" + context, context ); } // verify ONLY optional + required parameters are present Set<String> extra = new HashSet<String>(actualNames); extra.removeAll(required); extra.removeAll(optional); if (extra.size() > 0) { throw new ValidationException( context + ": Invalid HTTP request extra parameters " + extra, "Invalid HTTP request extra parameters " + extra + ": context=" + context, context ); } } /** * ValidationErrorList variant of assertIsValidHTTPRequestParameterSet * * Uses current HTTPRequest saved in ESAPI Authenticator * @param errors */ public void assertValidHTTPRequestParameterSet(String context, HttpServletRequest request, Set<String> required, Set<String> optional, ValidationErrorList errors) throws IntrusionException { try { assertValidHTTPRequestParameterSet(context, request, required, optional); } catch (ValidationException e) { errors.addError(context, e); } } public boolean isValidPrintable(String context, char[] input, int maxLength, boolean allowNull) throws IntrusionException { try { getValidPrintable( context, input, maxLength, allowNull); return true; } catch( Exception e ) { return false; } } /** * Returns canonicalized and validated printable characters as a byte array. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. * * @throws IntrusionException */ public char[] getValidPrintable(String context, char[] input, int maxLength, boolean allowNull) throws ValidationException, IntrusionException { if (isEmpty(input)) { if (allowNull) return null; throw new ValidationException(context + ": Input bytes required", "Input bytes required: HTTP request is null", context ); } if (input.length > maxLength) { throw new ValidationException(context + ": Input bytes can not exceed " + maxLength + " bytes", "Input exceeds maximum allowed length of " + maxLength + " by " + (input.length-maxLength) + " bytes: context=" + context + ", input=" + new String( input ), context); } for (int i = 0; i < input.length; i++) { if (input[i] <= 0x20 || input[i] >= 0x7E ) { throw new ValidationException(context + ": Invalid input bytes: context=" + context, "Invalid non-ASCII input bytes, context=" + context + ", input=" + new String( input ), context); } } return input; } /** * ValidationErrorList variant of getValidPrintable * * @param errors */ public char[] getValidPrintable(String context, char[] input,int maxLength, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidPrintable(context, input, maxLength, allowNull); } catch (ValidationException e) { errors.addError(context, e); } // error has been added to list, so return original input return input; } /** * {@inheritDoc} * * Returns true if input is valid printable ASCII characters (32-126). */ public boolean isValidPrintable(String context, String input, int maxLength, boolean allowNull) throws IntrusionException { try { getValidPrintable( context, input, maxLength, allowNull); return true; } catch( Exception e ) { return false; } } /** * Returns canonicalized and validated printable characters as a String. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. * * @throws IntrusionException */ public String getValidPrintable(String context, String input, int maxLength, boolean allowNull) throws ValidationException, IntrusionException { try { String canonical = encoder.canonicalize(input); return new String( getValidPrintable( context, canonical.toCharArray(), maxLength, allowNull) ); //TODO - changed this to base Exception since we no longer need EncodingException //TODO - this is a bit lame: we need to re-think this function. } catch (Exception e) { throw new ValidationException( context + ": Invalid printable input", "Invalid encoding of printable input, context=" + context + ", input=" + input, e, context); } } /** * ValidationErrorList variant of getValidPrintable * * @param errors */ public String getValidPrintable(String context, String input,int maxLength, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidPrintable(context, input, maxLength, allowNull); } catch (ValidationException e) { errors.addError(context, e); } // error has been added to list, so return original input return input; } /** * Returns true if input is a valid redirect location. */ public boolean isValidRedirectLocation(String context, String input, boolean allowNull) throws IntrusionException { return ESAPI.validator().isValidInput( context, input, "Redirect", 512, allowNull); } /** * Returns a canonicalized and validated redirect location as a String. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. */ public String getValidRedirectLocation(String context, String input, boolean allowNull) throws ValidationException, IntrusionException { return ESAPI.validator().getValidInput( context, input, "Redirect", 512, allowNull); } /** * ValidationErrorList variant of getValidRedirectLocation * * @param errors */ public String getValidRedirectLocation(String context, String input, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidRedirectLocation(context, input, allowNull); } catch (ValidationException e) { errors.addError(context, e); } // error has been added to list, so return original input return input; } /** * {@inheritDoc} * * This implementation reads until a newline or the specified number of * characters. * * @param in * @param max */ public String safeReadLine(InputStream in, int max) throws ValidationException { if (max <= 0) { throw new ValidationAvailabilityException( "Invalid input", "Invalid readline. Must read a positive number of bytes from the stream"); } StringBuilder sb = new StringBuilder(); int count = 0; int c; try { while (true) { c = in.read(); if ( c == -1 ) { if (sb.length() == 0) { return null; } break; } if (c == '\n' || c == '\r') { break; } count++; if (count > max) { throw new ValidationAvailabilityException( "Invalid input", "Invalid readLine. Read more than maximum characters allowed (" + max + ")"); } sb.append((char) c); } return sb.toString(); } catch (IOException e) { throw new ValidationAvailabilityException( "Invalid input", "Invalid readLine. Problem reading from input stream", e); } } /** * Helper function to check if a String is empty * * @param input string input value * @return boolean response if input is empty or not */ private final boolean isEmpty(String input) { return (input==null || input.trim().length() == 0); } /** * Helper function to check if a byte array is empty * * @param input string input value * @return boolean response if input is empty or not */ private final boolean isEmpty(byte[] input) { return (input==null || input.length == 0); } /** * Helper function to check if a char array is empty * * @param input string input value * @return boolean response if input is empty or not */ private final boolean isEmpty(char[] input) { return (input==null || input.length == 0); } }
package hello; public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); System.out.println("Hello World! the new user Win!"); System.out.println("Oh,what a pity!"); } }
package com.pollistics.controllers; import com.pollistics.models.Poll; import com.pollistics.models.User; import com.pollistics.models.validators.PollValidator; import com.pollistics.services.PollService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.security.Principal; import java.text.MessageFormat; import java.util.HashMap; import java.util.stream.Collectors; @Controller public class PollController { @Autowired private PollService pollService; @GetMapping(value = "/polls") public String allPolls(Model model) { model.addAttribute("polls", pollService.getAllPolls()); return "polls/overview"; } @GetMapping(value = {"/polls/{pollId}", "/{pollId}"}) public String pollDetail(@PathVariable String pollId, Model model, HttpServletResponse response) { Poll poll = pollService.getPoll(pollId); if(poll == null) { response.setStatus(404); return "error/404"; } model.addAttribute("poll", pollService.getPoll(pollId)); return "polls/detail"; } @GetMapping(value = {"/polls/{pollId}/results", "/{pollId}/results"}) public String pollResults(@PathVariable String pollId, Model model, HttpServletResponse response) { Poll poll = pollService.getPoll(pollId); if(poll == null) { response.setStatus(404); return "error/404"; } model.addAttribute("poll", pollService.getPoll(pollId)); return "polls/results"; } @PostMapping(value = "/polls/create") public String createPoll(HttpServletRequest request, @Valid @ModelAttribute("poll") Poll poll, BindingResult result, Principal principal, Model model) throws UnsupportedEncodingException { HashMap<String, Integer> options = (HashMap<String, Integer>)request.getParameterMap().entrySet().stream() .filter((param) -> param.getKey().startsWith("option") && !param.getValue()[0].trim().isEmpty()) .map((param) -> param.getValue()[0]) .collect(Collectors.<String,String,Integer>toMap((option) -> option, (option) -> 0)); poll.setOptions(options); if (request.getParameter("slug") != null) { poll.setSlug(request.getParameter("slug")); } PollValidator pollValidator = new PollValidator(); pollValidator.validate(poll, result); if (pollService.getPoll(poll.getSlug()) != null) { result.addError(new FieldError("poll", "slug", "This url is already taken")); } if(result.hasErrors()) { model.addAttribute("errors", result); return "index"; } else { String slug; // todo: figure out casting here if (request.getParameter("slug") != null) { if (principal != null) { slug = pollService.createPoll(poll.getTitle(), options, request.getParameter("slug"), (User) ((Authentication) principal).getPrincipal()); } else { slug = pollService.createPoll(poll.getTitle(), options, request.getParameter("slug")); } } else { if (principal != null) { slug = pollService.createPoll(poll.getTitle(), options, (User) ((Authentication) principal).getPrincipal()); } else { slug = pollService.createPoll(poll.getTitle(), options); } } String encodedSlug = URLEncoder.encode(slug, "UTF-8"); return "redirect:/" + encodedSlug; } } @PostMapping(value = "/polls/delete/{pollId}") public String deletePoll(@PathVariable String pollId, HttpServletResponse response, RedirectAttributes redirectAttrs) { boolean result = pollService.deletePoll(pollId); if (result) { redirectAttrs.addFlashAttribute("message", "The poll has deleted successfully!"); redirectAttrs.addFlashAttribute("message_type", "success"); return "redirect:/"; } else { response.setStatus(404); return "error/404"; } } @PostMapping(value = "/polls/vote/{pollId}") public String voteOptions(@CookieValue(value = "pollistics-voted", defaultValue = "") String originalCookie, @PathVariable String pollId, HttpServletRequest request, HttpServletResponse response, Model model) throws UnsupportedEncodingException { // already voted if (originalCookie.contains(pollId)) { Poll p = pollService.getPoll(pollId); model.addAttribute("msg", MessageFormat.format("You already voted for poll: {0}", p.getTitle())); model.addAttribute("previous", MessageFormat.format("/{0}/", pollId)); response.setStatus(403); return "error/403"; } else { Cookie cookie = new Cookie("pollistics-voted", originalCookie); String value; if (cookie.getValue().equals("")) { value = pollId; } else { value = MessageFormat.format("{0}-{1}", pollId, originalCookie); } final int expiryTimeCookie = 2147483647; // maximum of int final String cookiePath = "/"; cookie.setValue(value); cookie.setMaxAge(expiryTimeCookie); cookie.setPath(cookiePath); response.addCookie(cookie); String option = request.getParameter("option"); Poll p = pollService.getPoll(pollId); pollService.voteOption(p, option); String encodedSlug = URLEncoder.encode(pollId, "UTF-8"); return "redirect:/" + encodedSlug + "/results"; } } }
package org.owasp.esapi.reference; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.text.DateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import org.owasp.esapi.ESAPI; import org.owasp.esapi.Encoder; import org.owasp.esapi.ValidationErrorList; import org.owasp.esapi.ValidationRule; import org.owasp.esapi.Validator; import org.owasp.esapi.errors.IntrusionException; import org.owasp.esapi.errors.ValidationAvailabilityException; import org.owasp.esapi.errors.ValidationException; import org.owasp.esapi.reference.validation.CreditCardValidationRule; import org.owasp.esapi.reference.validation.DateValidationRule; import org.owasp.esapi.reference.validation.HTMLValidationRule; import org.owasp.esapi.reference.validation.IntegerValidationRule; import org.owasp.esapi.reference.validation.NumberValidationRule; import org.owasp.esapi.reference.validation.StringValidationRule; public class DefaultValidator implements org.owasp.esapi.Validator { private static volatile Validator instance = null; public static Validator getInstance() { if ( instance == null ) { synchronized ( Validator.class ) { if ( instance == null ) { instance = new DefaultValidator(); } } } return instance; } /** A map of validation rules */ private Map<String, ValidationRule> rules = new HashMap<String, ValidationRule>(); /** The encoder to use for canonicalization */ private Encoder encoder = null; /** The encoder to use for file system */ private static Validator fileValidator = null; /** Initialize file validator with an appropriate set of codecs */ static { List<String> list = new ArrayList<String>(); list.add( "HTMLEntityCodec" ); list.add( "PercentCodec" ); Encoder fileEncoder = new DefaultEncoder( list ); fileValidator = new DefaultValidator( fileEncoder ); } /** * Default constructor uses the ESAPI standard encoder for canonicalization. */ public DefaultValidator() { this.encoder = ESAPI.encoder(); } /** * Construct a new DefaultValidator that will use the specified * Encoder for canonicalization. * * @param encoder */ public DefaultValidator( Encoder encoder ) { this.encoder = encoder; } /** * Add a validation rule to the registry using the "type name" of the rule as the key. */ public void addRule( ValidationRule rule ) { rules.put( rule.getTypeName(), rule ); } /** * Get a validation rule from the registry with the "type name" of the rule as the key. */ public ValidationRule getRule( String name ) { return rules.get( name ); } public boolean isValidInput(String context, String input, String type, int maxLength, boolean allowNull) throws IntrusionException { try { getValidInput( context, input, type, maxLength, allowNull); return true; } catch( Exception e ) { return false; } } public String getValidInput(String context, String input, String type, int maxLength, boolean allowNull) throws ValidationException { StringValidationRule rvr = new StringValidationRule( type, encoder ); Pattern p = ESAPI.securityConfiguration().getValidationPattern( type ); if ( p != null ) { rvr.addWhitelistPattern( p ); } else { rvr.addWhitelistPattern( type ); } rvr.setMaximumLength(maxLength); rvr.setAllowNull(allowNull); return rvr.getValid(context, input); } public String getValidInput(String context, String input, String type, int maxLength, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidInput(context, input, type, maxLength, allowNull); } catch (ValidationException e) { errors.addError(context, e); } return ""; } /** * {@inheritDoc} */ public boolean isValidDate(String context, String input, DateFormat format, boolean allowNull) throws IntrusionException { try { getValidDate( context, input, format, allowNull); return true; } catch( Exception e ) { return false; } } /** * {@inheritDoc} */ public Date getValidDate(String context, String input, DateFormat format, boolean allowNull) throws ValidationException, IntrusionException { DateValidationRule dvr = new DateValidationRule( "SimpleDate", encoder, format); dvr.setAllowNull(allowNull); return dvr.getValid(context, input); } /** * {@inheritDoc} */ public Date getValidDate(String context, String input, DateFormat format, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidDate(context, input, format, allowNull); } catch (ValidationException e) { errors.addError(context, e); } // error has been added to list, so return null return null; } /** * {@inheritDoc} */ public boolean isValidSafeHTML(String context, String input, int maxLength, boolean allowNull) throws IntrusionException { try { getValidSafeHTML( context, input, maxLength, allowNull); return true; } catch( Exception e ) { return false; } } /** * {@inheritDoc} * * This implementation relies on the OWASP AntiSamy project. */ public String getValidSafeHTML( String context, String input, int maxLength, boolean allowNull ) throws ValidationException, IntrusionException { HTMLValidationRule hvr = new HTMLValidationRule( "safehtml", encoder ); hvr.setMaximumLength(maxLength); hvr.setAllowNull(allowNull); return hvr.getValid(context, input); } /** * {@inheritDoc} */ public String getValidSafeHTML(String context, String input, int maxLength, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidSafeHTML(context, input, maxLength, allowNull); } catch (ValidationException e) { errors.addError(context, e); } return ""; } /** * {@inheritDoc} */ public boolean isValidCreditCard(String context, String input, boolean allowNull) throws IntrusionException { try { getValidCreditCard( context, input, allowNull); return true; } catch( Exception e ) { return false; } } /** * {@inheritDoc} */ public String getValidCreditCard(String context, String input, boolean allowNull) throws ValidationException, IntrusionException { CreditCardValidationRule ccvr = new CreditCardValidationRule( "creditcard", encoder ); ccvr.setAllowNull(allowNull); return ccvr.getValid(context, input); } /** * {@inheritDoc} */ public String getValidCreditCard(String context, String input, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidCreditCard(context, input, allowNull); } catch (ValidationException e) { errors.addError(context, e); } return ""; } /** * {@inheritDoc} * * <p><b>Note:</b> On platforms that support symlinks, this function will fail canonicalization if directorypath * is a symlink. For example, on MacOS X, /etc is actually /private/etc. If you mean to use /etc, use its real * path (/private/etc), not the symlink (/etc).</p> */ public boolean isValidDirectoryPath(String context, String input, File parent, boolean allowNull) throws IntrusionException { try { getValidDirectoryPath( context, input, parent, allowNull); return true; } catch( Exception e ) { return false; } } /** * {@inheritDoc} */ public String getValidDirectoryPath(String context, String input, File parent, boolean allowNull) throws ValidationException, IntrusionException { try { if (isEmpty(input)) { if (allowNull) return null; throw new ValidationException( context + ": Input directory path required", "Input directory path required: context=" + context + ", input=" + input, context ); } File dir = new File( input ); // check dir exists and parent exists and dir is inside parent if ( !dir.exists() ) { throw new ValidationException( context + ": Invalid directory name", "Invalid directory, does not exist: context=" + context + ", input=" + input ); } if ( !dir.isDirectory() ) { throw new ValidationException( context + ": Invalid directory name", "Invalid directory, not a directory: context=" + context + ", input=" + input ); } if ( !parent.exists() ) { throw new ValidationException( context + ": Invalid directory name", "Invalid directory, specified parent does not exist: context=" + context + ", input=" + input + ", parent=" + parent ); } if ( !parent.isDirectory() ) { throw new ValidationException( context + ": Invalid directory name", "Invalid directory, specified parent is not a directory: context=" + context + ", input=" + input + ", parent=" + parent ); } if ( !dir.getCanonicalPath().startsWith(parent.getCanonicalPath() ) ) { throw new ValidationException( context + ": Invalid directory name", "Invalid directory, not inside specified parent: context=" + context + ", input=" + input + ", parent=" + parent ); } // check canonical form matches input String canonicalPath = dir.getCanonicalPath(); String canonical = fileValidator.getValidInput( context, canonicalPath, "DirectoryName", 255, false); if ( !canonical.equals( input ) ) { throw new ValidationException( context + ": Invalid directory name", "Invalid directory name does not match the canonical path: context=" + context + ", input=" + input + ", canonical=" + canonical, context ); } return canonical; } catch (Exception e) { throw new ValidationException( context + ": Invalid directory name", "Failure to validate directory path: context=" + context + ", input=" + input, e, context ); } } /** * {@inheritDoc} */ public String getValidDirectoryPath(String context, String input, File parent, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidDirectoryPath(context, input, parent, allowNull); } catch (ValidationException e) { errors.addError(context, e); } return ""; } /** * {@inheritDoc} */ public boolean isValidFileName(String context, String input, boolean allowNull) throws IntrusionException { return isValidFileName( context, input, ESAPI.securityConfiguration().getAllowedFileExtensions(), allowNull ); } /** * {@inheritDoc} */ public boolean isValidFileName(String context, String input, List<String> allowedExtensions, boolean allowNull) throws IntrusionException { try { getValidFileName( context, input, allowedExtensions, allowNull); return true; } catch( Exception e ) { return false; } } /** * {@inheritDoc} */ public String getValidFileName(String context, String input, List<String> allowedExtensions, boolean allowNull) throws ValidationException, IntrusionException { if ((allowedExtensions == null) || (allowedExtensions.isEmpty())) { throw new ValidationException( "Internal Error", "getValidFileName called with an empty or null list of allowed Extensions, therefore no files can be uploaded" ); } String canonical = ""; // detect path manipulation try { if (isEmpty(input)) { if (allowNull) return null; throw new ValidationException( context + ": Input file name required", "Input required: context=" + context + ", input=" + input, context ); } // do basic validation canonical = new File(input).getCanonicalFile().getName(); getValidInput( context, input, "FileName", 255, true ); File f = new File(canonical); String c = f.getCanonicalPath(); String cpath = c.substring(c.lastIndexOf(File.separator) + 1); // the path is valid if the input matches the canonical path if (!input.equals(cpath)) { throw new ValidationException( context + ": Invalid file name", "Invalid directory name does not match the canonical path: context=" + context + ", input=" + input + ", canonical=" + canonical, context ); } } catch (IOException e) { throw new ValidationException( context + ": Invalid file name", "Invalid file name does not exist: context=" + context + ", canonical=" + canonical, e, context ); } // verify extensions Iterator<String> i = allowedExtensions.iterator(); while (i.hasNext()) { String ext = i.next(); if (input.toLowerCase().endsWith(ext.toLowerCase())) { return canonical; } } throw new ValidationException( context + ": Invalid file name does not have valid extension ( "+allowedExtensions+")", "Invalid file name does not have valid extension ( "+allowedExtensions+"): context=" + context+", input=" + input, context ); } /** * {@inheritDoc} */ public String getValidFileName(String context, String input, List<String> allowedParameters, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidFileName(context, input, allowedParameters, allowNull); } catch (ValidationException e) { errors.addError(context, e); } return ""; } /** * {@inheritDoc} */ public boolean isValidNumber(String context, String input, long minValue, long maxValue, boolean allowNull) throws IntrusionException { try { getValidNumber(context, input, minValue, maxValue, allowNull); return true; } catch( Exception e ) { return false; } } /** * {@inheritDoc} */ public Double getValidNumber(String context, String input, long minValue, long maxValue, boolean allowNull) throws ValidationException, IntrusionException { Double minDoubleValue = new Double(minValue); Double maxDoubleValue = new Double(maxValue); return getValidDouble(context, input, minDoubleValue.doubleValue(), maxDoubleValue.doubleValue(), allowNull); } /** * {@inheritDoc} */ public Double getValidNumber(String context, String input, long minValue, long maxValue, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidNumber(context, input, minValue, maxValue, allowNull); } catch (ValidationException e) { errors.addError(context, e); } return null; } /** * {@inheritDoc} */ public boolean isValidDouble(String context, String input, double minValue, double maxValue, boolean allowNull) throws IntrusionException { try { getValidDouble( context, input, minValue, maxValue, allowNull ); return true; } catch( Exception e ) { return false; } } /** * {@inheritDoc} */ public Double getValidDouble(String context, String input, double minValue, double maxValue, boolean allowNull) throws ValidationException, IntrusionException { NumberValidationRule nvr = new NumberValidationRule( "number", encoder, minValue, maxValue ); nvr.setAllowNull(allowNull); return nvr.getValid(context, input); } /** * {@inheritDoc} */ public Double getValidDouble(String context, String input, double minValue, double maxValue, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidDouble(context, input, minValue, maxValue, allowNull); } catch (ValidationException e) { errors.addError(context, e); } // error has been added to list, so return null return null; } /** * {@inheritDoc} */ public boolean isValidInteger(String context, String input, int minValue, int maxValue, boolean allowNull) throws IntrusionException { try { getValidInteger( context, input, minValue, maxValue, allowNull); return true; } catch( ValidationException e ) { return false; } } /** * {@inheritDoc} */ public Integer getValidInteger(String context, String input, int minValue, int maxValue, boolean allowNull) throws ValidationException, IntrusionException { IntegerValidationRule ivr = new IntegerValidationRule( "number", encoder, minValue, maxValue ); ivr.setAllowNull(allowNull); return ivr.getValid(context, input); } /** * {@inheritDoc} */ public Integer getValidInteger(String context, String input, int minValue, int maxValue, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidInteger(context, input, minValue, maxValue, allowNull); } catch (ValidationException e) { errors.addError(context, e); } // error has been added to list, so return original input return null; } /** * {@inheritDoc} */ public boolean isValidFileContent(String context, byte[] input, int maxBytes, boolean allowNull) throws IntrusionException { try { getValidFileContent( context, input, maxBytes, allowNull); return true; } catch( Exception e ) { return false; } } /** * {@inheritDoc} */ public byte[] getValidFileContent(String context, byte[] input, int maxBytes, boolean allowNull) throws ValidationException, IntrusionException { if (isEmpty(input)) { if (allowNull) return null; throw new ValidationException( context + ": Input required", "Input required: context=" + context + ", input=" + input, context ); } long esapiMaxBytes = ESAPI.securityConfiguration().getAllowedFileUploadSize(); if (input.length > esapiMaxBytes ) throw new ValidationException( context + ": Invalid file content can not exceed " + esapiMaxBytes + " bytes", "Exceeded ESAPI max length", context ); if (input.length > maxBytes ) throw new ValidationException( context + ": Invalid file content can not exceed " + maxBytes + " bytes", "Exceeded maxBytes ( " + input.length + ")", context ); return input; } /** * {@inheritDoc} */ public byte[] getValidFileContent(String context, byte[] input, int maxBytes, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidFileContent(context, input, maxBytes, allowNull); } catch (ValidationException e) { errors.addError(context, e); } // return empty byte array on error return new byte[0]; } /** * {@inheritDoc} * * <p><b>Note:</b> On platforms that support symlinks, this function will fail canonicalization if directorypath * is a symlink. For example, on MacOS X, /etc is actually /private/etc. If you mean to use /etc, use its real * path (/private/etc), not the symlink (/etc).</p> */ public boolean isValidFileUpload(String context, String directorypath, String filename, File parent, byte[] content, int maxBytes, boolean allowNull) throws IntrusionException { return( isValidFileName( context, filename, allowNull ) && isValidDirectoryPath( context, directorypath, parent, allowNull ) && isValidFileContent( context, content, maxBytes, allowNull ) ); } /** * {@inheritDoc} */ public void assertValidFileUpload(String context, String directorypath, String filename, File parent, byte[] content, int maxBytes, List<String> allowedExtensions, boolean allowNull) throws ValidationException, IntrusionException { getValidFileName( context, filename, allowedExtensions, allowNull ); getValidDirectoryPath( context, directorypath, parent, allowNull ); getValidFileContent( context, content, maxBytes, allowNull ); } /** * {@inheritDoc} */ public void assertValidFileUpload(String context, String filepath, String filename, File parent, byte[] content, int maxBytes, List<String> allowedExtensions, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { assertValidFileUpload(context, filepath, filename, parent, content, maxBytes, allowedExtensions, allowNull); } catch (ValidationException e) { errors.addError(context, e); } } /** * {@inheritDoc} * * Returns true if input is a valid list item. */ public boolean isValidListItem(String context, String input, List<String> list) { try { getValidListItem( context, input, list); return true; } catch( Exception e ) { return false; } } /** * Returns the list item that exactly matches the canonicalized input. Invalid or non-matching input * will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. */ public String getValidListItem(String context, String input, List<String> list) throws ValidationException, IntrusionException { if (list.contains(input)) return input; throw new ValidationException( context + ": Invalid list item", "Invalid list item: context=" + context + ", input=" + input, context ); } /** * ValidationErrorList variant of getValidListItem * * @param errors */ public String getValidListItem(String context, String input, List<String> list, ValidationErrorList errors) throws IntrusionException { try { return getValidListItem(context, input, list); } catch (ValidationException e) { errors.addError(context, e); } // error has been added to list, so return original input return input; } /** * {@inheritDoc} */ public boolean isValidHTTPRequestParameterSet(String context, HttpServletRequest request, Set<String> requiredNames, Set<String> optionalNames) { try { assertValidHTTPRequestParameterSet( context, request, requiredNames, optionalNames); return true; } catch( Exception e ) { return false; } } /** * Validates that the parameters in the current request contain all required parameters and only optional ones in * addition. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. * * Uses current HTTPRequest */ public void assertValidHTTPRequestParameterSet(String context, HttpServletRequest request, Set<String> required, Set<String> optional) throws ValidationException, IntrusionException { Set<String> actualNames = request.getParameterMap().keySet(); // verify ALL required parameters are present Set<String> missing = new HashSet<String>(required); missing.removeAll(actualNames); if (missing.size() > 0) { throw new ValidationException( context + ": Invalid HTTP request missing parameters", "Invalid HTTP request missing parameters " + missing + ": context=" + context, context ); } // verify ONLY optional + required parameters are present Set<String> extra = new HashSet<String>(actualNames); extra.removeAll(required); extra.removeAll(optional); if (extra.size() > 0) { throw new ValidationException( context + ": Invalid HTTP request extra parameters " + extra, "Invalid HTTP request extra parameters " + extra + ": context=" + context, context ); } } /** * ValidationErrorList variant of assertIsValidHTTPRequestParameterSet * * Uses current HTTPRequest saved in ESAPI Authenticator * @param errors */ public void assertValidHTTPRequestParameterSet(String context, HttpServletRequest request, Set<String> required, Set<String> optional, ValidationErrorList errors) throws IntrusionException { try { assertValidHTTPRequestParameterSet(context, request, required, optional); } catch (ValidationException e) { errors.addError(context, e); } } public boolean isValidPrintable(String context, char[] input, int maxLength, boolean allowNull) throws IntrusionException { try { getValidPrintable( context, input, maxLength, allowNull); return true; } catch( Exception e ) { return false; } } /** * Returns canonicalized and validated printable characters as a byte array. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. * * @throws IntrusionException */ public char[] getValidPrintable(String context, char[] input, int maxLength, boolean allowNull) throws ValidationException, IntrusionException { if (isEmpty(input)) { if (allowNull) return null; throw new ValidationException(context + ": Input bytes required", "Input bytes required: HTTP request is null", context ); } if (input.length > maxLength) { throw new ValidationException(context + ": Input bytes can not exceed " + maxLength + " bytes", "Input exceeds maximum allowed length of " + maxLength + " by " + (input.length-maxLength) + " bytes: context=" + context + ", input=" + new String( input ), context); } for (int i = 0; i < input.length; i++) { if (input[i] <= 0x20 || input[i] >= 0x7E ) { throw new ValidationException(context + ": Invalid input bytes: context=" + context, "Invalid non-ASCII input bytes, context=" + context + ", input=" + new String( input ), context); } } return input; } /** * ValidationErrorList variant of getValidPrintable * * @param errors */ public char[] getValidPrintable(String context, char[] input,int maxLength, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidPrintable(context, input, maxLength, allowNull); } catch (ValidationException e) { errors.addError(context, e); } // error has been added to list, so return original input return input; } /** * {@inheritDoc} * * Returns true if input is valid printable ASCII characters (32-126). */ public boolean isValidPrintable(String context, String input, int maxLength, boolean allowNull) throws IntrusionException { try { getValidPrintable( context, input, maxLength, allowNull); return true; } catch( Exception e ) { return false; } } /** * Returns canonicalized and validated printable characters as a String. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. * * @throws IntrusionException */ public String getValidPrintable(String context, String input, int maxLength, boolean allowNull) throws ValidationException, IntrusionException { try { String canonical = encoder.canonicalize(input); return new String( getValidPrintable( context, canonical.toCharArray(), maxLength, allowNull) ); //TODO - changed this to base Exception since we no longer need EncodingException //TODO - this is a bit lame: we need to re-think this function. } catch (Exception e) { throw new ValidationException( context + ": Invalid printable input", "Invalid encoding of printable input, context=" + context + ", input=" + input, e, context); } } /** * ValidationErrorList variant of getValidPrintable * * @param errors */ public String getValidPrintable(String context, String input,int maxLength, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidPrintable(context, input, maxLength, allowNull); } catch (ValidationException e) { errors.addError(context, e); } // error has been added to list, so return original input return input; } /** * Returns true if input is a valid redirect location. */ public boolean isValidRedirectLocation(String context, String input, boolean allowNull) throws IntrusionException { return ESAPI.validator().isValidInput( context, input, "Redirect", 512, allowNull); } /** * Returns a canonicalized and validated redirect location as a String. Invalid input will generate a descriptive ValidationException, and input that is clearly an attack * will generate a descriptive IntrusionException. */ public String getValidRedirectLocation(String context, String input, boolean allowNull) throws ValidationException, IntrusionException { return ESAPI.validator().getValidInput( context, input, "Redirect", 512, allowNull); } /** * ValidationErrorList variant of getValidRedirectLocation * * @param errors */ public String getValidRedirectLocation(String context, String input, boolean allowNull, ValidationErrorList errors) throws IntrusionException { try { return getValidRedirectLocation(context, input, allowNull); } catch (ValidationException e) { errors.addError(context, e); } // error has been added to list, so return original input return input; } /** * {@inheritDoc} * * This implementation reads until a newline or the specified number of * characters. * * @param in * @param max */ public String safeReadLine(InputStream in, int max) throws ValidationException { if (max <= 0) { throw new ValidationAvailabilityException( "Invalid input", "Invalid readline. Must read a positive number of bytes from the stream"); } StringBuilder sb = new StringBuilder(); int count = 0; int c; try { while (true) { c = in.read(); if ( c == -1 ) { if (sb.length() == 0) { return null; } break; } if (c == '\n' || c == '\r') { break; } count++; if (count > max) { throw new ValidationAvailabilityException( "Invalid input", "Invalid readLine. Read more than maximum characters allowed (" + max + ")"); } sb.append((char) c); } return sb.toString(); } catch (IOException e) { throw new ValidationAvailabilityException( "Invalid input", "Invalid readLine. Problem reading from input stream", e); } } /** * Helper function to check if a String is empty * * @param input string input value * @return boolean response if input is empty or not */ private final boolean isEmpty(String input) { return (input==null || input.trim().length() == 0); } /** * Helper function to check if a byte array is empty * * @param input string input value * @return boolean response if input is empty or not */ private final boolean isEmpty(byte[] input) { return (input==null || input.length == 0); } /** * Helper function to check if a char array is empty * * @param input string input value * @return boolean response if input is empty or not */ private final boolean isEmpty(char[] input) { return (input==null || input.length == 0); } }
package org.yaba.entity.script; import no.priv.garshol.duke.Cleaner; import no.priv.garshol.duke.Comparator; import no.priv.garshol.duke.Record; import no.priv.garshol.duke.RecordImpl; import no.priv.garshol.duke.comparators.Levenshtein; import no.priv.garshol.duke.utils.Utils; import no.priv.garshol.duke.utils.ObjectUtils; import org.elasticsearch.script.AbstractSearchScript; import org.elasticsearch.ElasticSearchException; import org.elasticsearch.ElasticSearchIllegalArgumentException; import org.elasticsearch.script.ExecutableScript; import org.elasticsearch.script.NativeScriptFactory; import org.elasticsearch.search.lookup.DocLookup; import org.elasticsearch.common.Nullable; import org.elasticsearch.index.fielddata.ScriptDocValues; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; @SuppressWarnings("unchecked") public class EntityResolutionScript extends AbstractSearchScript { /* * private final static ESLogger logger = Loggers * .getLogger(EntityResolutionScript.class); */ private Record comparedRecord = null; private HashMap<String, HashMap<String, Object>> entityParams = new HashMap<String, HashMap<String, Object>>(); /** * Native scripts are build using factories that are registered in the * {@link org.elasticsearch.examples.nativescript.plugin.NativeScriptExamplesPlugin#onModule(org.elasticsearch.script.ScriptModule)} * method when plugin is loaded. */ public static class Factory implements NativeScriptFactory { /** * This method is called for every search on every shard. * * @param params * list of script parameters passed with the query * @return new native script */ @Override public ExecutableScript newScript(@Nullable Map<String, Object> params) { if (params.get("entity") == null) { throw new ElasticSearchIllegalArgumentException( "Missing the parameters"); } return new EntityResolutionScript( (Map<String, Object>) params.get("entity")); } } private EntityResolutionScript(Map<String, Object> params) { HashMap<String, Collection<String>> props = new HashMap<String, Collection<String>>(); ArrayList<Map<String, Object>> fieldsParams = null; if (params.get("fields") == null) throw new ElasticSearchIllegalArgumentException( "Missing the 'fields' parameters"); else fieldsParams = (ArrayList<Map<String, Object>>) params .get("fields"); Iterator<Map<String, Object>> it = fieldsParams.iterator(); while (it.hasNext()) { Map<String, Object> value = it.next(); HashMap<String, Object> map = new HashMap<String, Object>(); String field = (String) value.get("field"); String fieldValue = (String) value.get("value"); Iterator<String> cleanIt = ((ArrayList<String>) value .get("cleaners")).iterator(); ArrayList<Cleaner> cleanList = new ArrayList<Cleaner>(); while (cleanIt.hasNext()) { String cleanerName = (String) cleanIt.next(); Cleaner cleaner = (Cleaner) ObjectUtils.instantiate(cleanerName); cleanList.add(cleaner); fieldValue = cleaner.clean(fieldValue); } map.put("cleaners", cleanList); props.put(field, Collections.singleton(fieldValue)); Double maxValue = (value.get("high") == null ? 0.0 : Double .valueOf(((Double) value.get("high")))); Double minValue = (value.get("low") == null ? 0.0 : Double .valueOf(((Double) value.get("low")))); String comparatorName = (value.get("comparator") == null ? Levenshtein.class .getName() : (String) value.get("comparator")); Comparator comp = (Comparator) ObjectUtils.instantiate(comparatorName); map.put("high", maxValue); map.put("low", minValue); map.put("comparator", comp); entityParams.put(fieldValue, map); } comparedRecord = new RecordImpl(props); } @Override public float runAsFloat() { HashMap<String, Collection<String>> props2 = new HashMap<String, Collection<String>>(); DocLookup doc = doc(); Collection<String> docKeys = comparedRecord.getProperties(); Iterator<String> it = docKeys.iterator(); while (it.hasNext()) { String key = (String) it.next(); if (doc.get(key) != null) { String value = getFieldValue(doc.get(key)); props2.put(key, value == null ? Collections.singleton("") : Collections.singleton(value)); } } Record r2 = new RecordImpl(props2); return new Double(compare(comparedRecord, r2, entityParams)) .floatValue(); } /** * Reads field value & returns it as String * * @param object * @return String */ private String getFieldValue(Object field) { String result = ""; if (field instanceof ScriptDocValues.Strings) result = ((ScriptDocValues.Strings) field).getValue(); if (field instanceof ScriptDocValues.Doubles) result = ((ScriptDocValues.Doubles) field).getValue() + ""; if (field instanceof ScriptDocValues.Longs) result = ((ScriptDocValues.Longs) field).getValue() + ""; if (field instanceof ScriptDocValues.GeoPoints) throw new ElasticSearchException( "No comparator implemented for GeoPoints"); return result; } /** * Compares two records and returns the probability that they represent the * same real-world entity. */ private double compare(Record r1, Record r2, HashMap<String, HashMap<String, Object>> params) { double prob = 0.5; for (String propname : r1.getProperties()) { Collection<String> vs1 = r1.getValues(propname); Collection<String> vs2 = r2.getValues(propname); if (vs1 == null || vs1.isEmpty() || vs2 == null || vs2.isEmpty()) continue; // no values to compare, so skip double high = 0.0; for (String v1 : vs1) { if (v1.equals("")) continue; for (String v2 : vs2) { if (v2.equals("")) continue; Comparator comp = (Comparator) params.get(v1).get( "comparator"); ArrayList<Cleaner> cleanersList = (ArrayList<Cleaner>) params .get(v1).get("cleaners"); Iterator<Cleaner> clIt = cleanersList.iterator(); while (clIt.hasNext()) { v2 = clIt.next().clean(v2); } double p = compare(v1, v2, (Double) params.get(v1).get("high"), (Double) params.get(v1).get("low"), comp); high = Math.max(high, p); } } prob = Utils.computeBayes(prob, high); } return prob; } /** * Returns the probability that the records v1 and v2 came from represent * the same entity, based on high and low probability settings etc. */ public double compare(String v1, String v2, double high, double low, Comparator comparator) { if (comparator == null) return 0.5; // we ignore properties with no comparator double sim = comparator.compare(v1, v2); if (sim >= 0.5) return ((high - 0.5) * (sim * sim)) + 0.5; else return low; } @Override public Object run() { // TODO Auto-generated method stub return null; } }
package org.apache.commons.lang.builder; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.HashSet; import java.util.Set; public class ToStringBuilder { /** * A registry of objects used by <code>reflectionToString</code> methods to detect cyclical object references * and avoid infinite loops. */ private static ThreadLocal reflectionRegistry = new ThreadLocal() { protected synchronized Object initialValue() { // The HashSet implementation is not synchronized, which is just what we need here. return new HashSet(); } }; /** * The default style of output to use */ private static ToStringStyle defaultStyle = ToStringStyle.DEFAULT_STYLE; /** * Current toString buffer */ private final StringBuffer buffer; /** * The style of output to use */ private final ToStringStyle style; /** * The object being output */ private final Object object; /** * Returns the registry of objects being traversed by the * <code>reflectionToString</code> methods in the current thread. * @return Set the registry of objects being traversed */ static Set getReflectionRegistry() { return (Set) reflectionRegistry.get(); } /** * Returns <code>true</code> if the registry contains the given object. * Used by the reflection methods to avoid infinite loops. * * @param value The object to lookup in the registry. * @return boolean <code>true</code> if the registry contains the given object. */ static boolean isRegistered(Object value) { return getReflectionRegistry().contains(value); } /** * Registers the given object. * Used by the reflection methods to avoid infinite loops. * * @param value The object to register. */ static void register(Object value) { getReflectionRegistry().add(value); } /** * Unregisters the given object. * Used by the reflection methods to avoid infinite loops. * * @param value The object to unregister. */ static void unregister(Object value) { getReflectionRegistry().remove(value); } public ToStringBuilder(Object object) { this(object, getDefaultStyle(), null); } public ToStringBuilder(Object object, ToStringStyle style) { this(object, style, null); } public ToStringBuilder(Object object, ToStringStyle style, StringBuffer buffer) { super(); if (object == null) { throw new IllegalArgumentException("The object to create a toString for must not be null"); } if (style == null) { style = getDefaultStyle(); } if (buffer == null) { buffer = new StringBuffer(512); } this.buffer = buffer; this.style = style; this.object = object; style.appendStart(buffer, object); } /** * <p>Gets the default <code>ToStringStyle</code> to use.</p> * * <p>This could allow the <code>ToStringStyle</code> to be * controlled for an entire application with one call.</p> * * <p>This might be used to have a verbose * <code>ToStringStyle</code> during development and a compact * <code>ToStringStyle</code> in production.</p> * * @return the default <code>ToStringStyle</code> */ public static ToStringStyle getDefaultStyle() { return defaultStyle; } public static void setDefaultStyle(ToStringStyle style) { if (style == null) { throw new IllegalArgumentException("The style must not be null"); } defaultStyle = style; } public static String reflectionToString(Object object) { return reflectionToString(object, null, false, null); } public static String reflectionToString(Object object, ToStringStyle style) { return reflectionToString(object, style, false, null); } public static String reflectionToString(Object object, ToStringStyle style, boolean outputTransients) { return reflectionToString(object, style, outputTransients, null); } public static String reflectionToString( Object object, ToStringStyle style, boolean outputTransients, Class reflectUpToClass) { if (style == null) { style = getDefaultStyle(); } if (object == null) { return style.getNullText(); } ToStringBuilder builder = new ToStringBuilder(object, style); Class clazz = object.getClass(); reflectionAppend(object, clazz, builder, outputTransients); while (clazz.getSuperclass() != null && clazz != reflectUpToClass) { clazz = clazz.getSuperclass(); reflectionAppend(object, clazz, builder, outputTransients); } return builder.toString(); } /** * Appends the fields and values defined by the given object of the * given Class. If a cycle is detected as an objects is "toString()'ed", * such an object is rendered as if <code>Object.toString()</code> * had been called and not implemented by the object. * * @param object the object to append details of * @param clazz the class of object parameter * @param builder the builder to append to * @param useTransients whether to output transient fields */ private static void reflectionAppend(Object object, Class clazz, ToStringBuilder builder, boolean useTransients) { if (isRegistered(object)) { // The object has already been appended, therefore we have an object cycle. // Append a simple Object.toString style string. The field name is already appended at this point. builder.appendAsObjectToString(object); return; } try { register(object); if (clazz.isArray()) { builder.reflectionAppendArray(object); return; } Field[] fields = clazz.getDeclaredFields(); Field.setAccessible(fields, true); for (int i = 0; i < fields.length; i++) { Field f = fields[i]; String fieldName = f.getName(); if ((fieldName.indexOf('$') == -1) && (useTransients || !Modifier.isTransient(f.getModifiers())) && (!Modifier.isStatic(f.getModifiers()))) { try { // Warning: Field.get(Object) creates wrappers objects for primitive types. Object fieldValue = f.get(object); if (isRegistered(fieldValue) && !f.getType().isPrimitive()) { // A known field value has already been appended, therefore we have an object cycle, // append a simple Object.toString style string. builder.getStyle().appendFieldStart(builder.getStringBuffer(), fieldName); builder.appendAsObjectToString(fieldValue); // The recursion out of // builder.append(fieldName, fieldValue); // below will append the field // end marker. } else { try { register(object); builder.append(fieldName, fieldValue); } finally { unregister(object); } } } catch (IllegalAccessException ex) { //this can't happen. Would get a Security exception instead //throw a runtime exception in case the impossible happens. throw new InternalError("Unexpected IllegalAccessException: " + ex.getMessage()); } } } } finally { unregister(object); } } /** * <p>Append the <code>toString</code> from the superclass.</p> * * <p>This method asumes that the superclass uses the same <code>ToStringStyle</code> * as this one.</p> * * <p>If the <code>superToString</code> is null, no change is made.</p> * * @param superToString the result of <code>super.toString()</code> * @return this */ public ToStringBuilder appendSuper(String superToString) { if (superToString != null) { style.appendSuper(buffer, superToString); } return this; } /** * <p>Append the <code>toString</code> from another object.</p> * * <p>This method is useful where a class delegates most of the implementation of * it's properties to another class. You can then call toString() on the other * class and pass the result into this method.</p> * * <pre> * private AnotherObject delegate; * private String fieldInThisClass; * * public String toString() { * return new ToStringBuilder(this). * appendToString(delegate.toString()). * append(fieldInThisClass). * toString(); * }</pre> * * <p>This method asumes that the other object uses the same <code>ToStringStyle</code> * as this one.</p> * * <p>If the <code>toString</code> is null, no change is made.</p> * * @param toString the result of <code>toString()</code> on another object * @return this */ public ToStringBuilder appendToString(String toString) { if (toString != null) { style.appendToString(buffer, toString); } return this; } /** * <p>Appends with the same format as the default <code>Object toString() * </code> method. Appends the class name followed by * {@link System#identityHashCode(java.lang.Object)}.</p> * * @param object the <code>Object</code> whose class name and id to output */ public ToStringBuilder appendAsObjectToString(Object object) { this.getStyle().appendAsObjectToString(this.getStringBuffer(), object); return this; } /** * <p>Append to the <code>toString</code> an <code>Object</code> * value.</p> * * @param object the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(Object object) { style.append(buffer, null, object, null); return this; } /** * <p>Append to the <code>toString</code> an <code>Object</code> * value.</p> * * @param fieldName the field name * @param object the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(String fieldName, Object object) { style.append(buffer, fieldName, object, null); return this; } /** * <p>Append to the <code>toString</code> an <code>Object</code> * value.</p> * * @param fieldName the field name * @param object the value to add to the <code>toString</code> * @param fullDetail <code>true</code> for detail, * <code>false</code> for summary info * @return this */ public ToStringBuilder append(String fieldName, Object object, boolean fullDetail) { style.append(buffer, fieldName, object, new Boolean(fullDetail)); return this; } /** * <p>Append to the <code>toString</code> a <code>long</code> * value.</p> * * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(long value) { style.append(buffer, null, value); return this; } /** * <p>Append to the <code>toString</code> a <code>long</code> * value.</p> * * @param fieldName the field name * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(String fieldName, long value) { style.append(buffer, fieldName, value); return this; } /** * <p>Append to the <code>toString</code> an <code>int</code> * value.</p> * * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(int value) { style.append(buffer, null, value); return this; } /** * <p>Append to the <code>toString</code> an <code>int</code> * value.</p> * * @param fieldName the field name * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(String fieldName, int value) { style.append(buffer, fieldName, value); return this; } /** * <p>Append to the <code>toString</code> an <code>short</code> * value.</p> * * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(short value) { style.append(buffer, null, value); return this; } /** * <p>Append to the <code>toString</code> an <code>short</code> * value.</p> * * @param fieldName the field name * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(String fieldName, short value) { style.append(buffer, fieldName, value); return this; } /** * <p>Append to the <code>toString</code> an <code>char</code> * value.</p> * * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(char value) { style.append(buffer, null, value); return this; } /** * <p>Append to the <code>toString</code> an <code>char</code> * value.</p> * * @param fieldName the field name * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(String fieldName, char value) { style.append(buffer, fieldName, value); return this; } /** * <p>Append to the <code>toString</code> an <code>byte</code> * value.</p> * * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(byte value) { style.append(buffer, null, value); return this; } /** * <p>Append to the <code>toString</code> an <code>byte</code> * value.</p> * * @param fieldName the field name * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(String fieldName, byte value) { style.append(buffer, fieldName, value); return this; } /** * <p>Append to the <code>toString</code> an <code>double</code> * value.</p> * * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(double value) { style.append(buffer, null, value); return this; } /** * <p>Append to the <code>toString</code> an <code>double</code> * value.</p> * * @param fieldName the field name * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(String fieldName, double value) { style.append(buffer, fieldName, value); return this; } /** * <p>Append to the <code>toString</code> an <code>float</code> * value.</p> * * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(float value) { style.append(buffer, null, value); return this; } /** * <p>Append to the <code>toString</code> an <code>float</code> * value.</p> * * @param fieldName the field name * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(String fieldName, float value) { style.append(buffer, fieldName, value); return this; } /** * <p>Append to the <code>toString</code> an <code>boolean</code> * value.</p> * * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(boolean value) { style.append(buffer, null, value); return this; } /** * <p>Append to the <code>toString</code> an <code>boolean</code> * value.</p> * * @param fieldName the field name * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(String fieldName, boolean value) { style.append(buffer, fieldName, value); return this; } /** * <p>Append to the <code>toString</code> an <code>Object</code> * array.</p> * * @param array the array to add to the <code>toString</code> * @return this */ public ToStringBuilder append(Object[] array) { style.append(buffer, null, array, null); return this; } /** * <p>Append to the <code>toString</code> an <code>Object</code> * array.</p> * * @param array the array to add to the <code>toString</code> * @return this */ public ToStringBuilder reflectionAppendArray(Object array) { style.reflectionAppendArrayDetail(buffer, null, array); return this; } /** * <p>Append to the <code>toString</code> an <code>Object</code> * array.</p> * * @param fieldName the field name * @param array the array to add to the <code>toString</code> * @return this */ public ToStringBuilder append(String fieldName, Object[] array) { style.append(buffer, fieldName, array, null); return this; } /** * <p>Append to the <code>toString</code> an <code>Object</code> * array.</p> * * <p>A boolean parameter controls the level of detail to show. * Setting <code>true</code> will output the array in full. Setting * <code>false</code> will output a summary, typically the size of * the array.</p> * * @param fieldName the field name * @param array the array to add to the <code>toString</code> * @param fullDetail <code>true</code> for detail, <code>false</code> * for summary info * @return this */ public ToStringBuilder append(String fieldName, Object[] array, boolean fullDetail) { style.append(buffer, fieldName, array, new Boolean(fullDetail)); return this; } /** * <p>Append to the <code>toString</code> a <code>long</code> * array.</p> * * @param array the array to add to the <code>toString</code> * @return this */ public ToStringBuilder append(long[] array) { style.append(buffer, null, array, null); return this; } /** * <p>Append a <code>hashCode</code> for a <code>long</code> * array.</p> * * @param fieldName the field name * @param array the array to add to the <code>hashCode</code> * @return this */ public ToStringBuilder append(String fieldName, long[] array) { style.append(buffer, fieldName, array, null); return this; } /** * <p>Append to the <code>toString</code> a <code>long</code> * array.</p> * * <p>A boolean parameter controls the level of detail to show. * Setting <code>true</code> will output the array in full. Setting * <code>false</code> will output a summary, typically the size of * the array.</p> * * @param fieldName the field name * @param array the array to add to the <code>toString</code> * @param fullDetail <code>true</code> for detail, <code>false</code> * for summary info * @return this */ public ToStringBuilder append(String fieldName, long[] array, boolean fullDetail) { style.append(buffer, fieldName, array, new Boolean(fullDetail)); return this; } /** * <p>Append to the <code>toString</code> a <code>int</code> * array.</p> * * @param array the array to add to the <code>toString</code> * @return this */ public ToStringBuilder append(int[] array) { style.append(buffer, null, array, null); return this; } /** * <p>Append a <code>hashCode</code> for an <code>int</code> * array.</p> * * @param fieldName the field name * @param array the array to add to the <code>hashCode</code> * @return this */ public ToStringBuilder append(String fieldName, int[] array) { style.append(buffer, fieldName, array, null); return this; } /** * <p>Append to the <code>toString</code> an <code>int</code> * array.</p> * * <p>A boolean parameter controls the level of detail to show. * Setting <code>true</code> will output the array in full. Setting * <code>false</code> will output a summary, typically the size of * the array.</p> * * @param fieldName the field name * @param array the array to add to the <code>toString</code> * @param fullDetail <code>true</code> for detail, <code>false</code> * for summary info * @return this */ public ToStringBuilder append(String fieldName, int[] array, boolean fullDetail) { style.append(buffer, fieldName, array, new Boolean(fullDetail)); return this; } /** * <p>Append to the <code>toString</code> a <code>short</code> * array.</p> * * @param array the array to add to the <code>toString</code> * @return this */ public ToStringBuilder append(short[] array) { style.append(buffer, null, array, null); return this; } /** * <p>Append a <code>hashCode</code> for a <code>short</code> * array.</p> * * @param fieldName the field name * @param array the array to add to the <code>hashCode</code> * @return this */ public ToStringBuilder append(String fieldName, short[] array) { style.append(buffer, fieldName, array, null); return this; } /** * <p>Append to the <code>toString</code> a <code>short</code> * array.</p> * * <p>A boolean parameter controls the level of detail to show. * Setting <code>true</code> will output the array in full. Setting * <code>false</code> will output a summary, typically the size of * the array. * * @param fieldName the field name * @param array the array to add to the <code>toString</code> * @param fullDetail <code>true</code> for detail, <code>false</code> * for summary info * @return this */ public ToStringBuilder append(String fieldName, short[] array, boolean fullDetail) { style.append(buffer, fieldName, array, new Boolean(fullDetail)); return this; } /** * <p>Append to the <code>toString</code> a <code>char</code> * array.</p> * * @param array the array to add to the <code>toString</code> * @return this */ public ToStringBuilder append(char[] array) { style.append(buffer, null, array, null); return this; } /** * <p>Append a <code>hashCode</code> for a <code>char</code> * array.</p> * * @param fieldName the field name * @param array the array to add to the <code>hashCode</code> * @return this */ public ToStringBuilder append(String fieldName, char[] array) { style.append(buffer, fieldName, array, null); return this; } /** * <p>Append to the <code>toString</code> a <code>char</code> * array.</p> * * <p>A boolean parameter controls the level of detail to show. * Setting <code>true</code> will output the array in full. Setting * <code>false</code> will output a summary, typically the size of * the array.</p> * * @param fieldName the field name * @param array the array to add to the <code>toString</code> * @param fullDetail <code>true</code> for detail, <code>false</code> * for summary info * @return this */ public ToStringBuilder append(String fieldName, char[] array, boolean fullDetail) { style.append(buffer, fieldName, array, new Boolean(fullDetail)); return this; } /** * <p>Append to the <code>toString</code> a <code>byte</code> * array.</p> * * @param array the array to add to the <code>toString</code> * @return this */ public ToStringBuilder append(byte[] array) { style.append(buffer, null, array, null); return this; } /** * <p>Append a <code>hashCode</code> for a <code>byte</code> * array.</p> * * @param fieldName the field name * @param array the array to add to the <code>hashCode</code> * @return this */ public ToStringBuilder append(String fieldName, byte[] array) { style.append(buffer, fieldName, array, null); return this; } /** * <p>Append to the <code>toString</code> a <code>byte</code> * array.</p> * * <p>A boolean parameter controls the level of detail to show. * Setting <code>true</code> will output the array in full. Setting * <code>false</code> will output a summary, typically the size of * the array. * * @param fieldName the field name * @param array the array to add to the <code>toString</code> * @param fullDetail <code>true</code> for detail, <code>false</code> * for summary info * @return this */ public ToStringBuilder append(String fieldName, byte[] array, boolean fullDetail) { style.append(buffer, fieldName, array, new Boolean(fullDetail)); return this; } /** * <p>Append to the <code>toString</code> a <code>double</code> * array.</p> * * @param array the array to add to the <code>toString</code> * @return this */ public ToStringBuilder append(double[] array) { style.append(buffer, null, array, null); return this; } /** * <p>Append a <code>hashCode</code> for a <code>double</code> * array.</p> * * @param fieldName the field name * @param array the array to add to the <code>hashCode</code> * @return this */ public ToStringBuilder append(String fieldName, double[] array) { style.append(buffer, fieldName, array, null); return this; } /** * <p>Append to the <code>toString</code> a <code>double</code> * array.</p> * * <p>A boolean parameter controls the level of detail to show. * Setting <code>true</code> will output the array in full. Setting * <code>false</code> will output a summary, typically the size of * the array.</p> * * @param fieldName the field name * @param array the array to add to the <code>toString</code> * @param fullDetail <code>true</code> for detail, <code>false</code> * for summary info * @return this */ public ToStringBuilder append(String fieldName, double[] array, boolean fullDetail) { style.append(buffer, fieldName, array, new Boolean(fullDetail)); return this; } /** * <p>Append to the <code>toString</code> a <code>float</code> * array.</p> * * @param array the array to add to the <code>toString</code> * @return this */ public ToStringBuilder append(float[] array) { style.append(buffer, null, array, null); return this; } /** * <p>Append a <code>hashCode</code> for a <code>float</code> * array.</p> * * @param fieldName the field name * @param array the array to add to the <code>hashCode</code> * @return this */ public ToStringBuilder append(String fieldName, float[] array) { style.append(buffer, fieldName, array, null); return this; } /** * <p>Append to the <code>toString</code> a <code>float</code> * array.</p> * * <p>A boolean parameter controls the level of detail to show. * Setting <code>true</code> will output the array in full. Setting * <code>false</code> will output a summary, typically the size of * the array.</p> * * @param fieldName the field name * @param array the array to add to the <code>toString</code> * @param fullDetail <code>true</code> for detail, <code>false</code> * for summary info * @return this */ public ToStringBuilder append(String fieldName, float[] array, boolean fullDetail) { style.append(buffer, fieldName, array, new Boolean(fullDetail)); return this; } /** * <p>Append to the <code>toString</code> a <code>boolean</code> * array.</p> * * @param array the array to add to the <code>toString</code> * @return this */ public ToStringBuilder append(boolean[] array) { style.append(buffer, null, array, null); return this; } /** * <p>Append a <code>hashCode</code> for a <code>boolean</code> * array.</p> * * @param fieldName the field name * @param array the array to add to the <code>hashCode</code> * @return this */ public ToStringBuilder append(String fieldName, boolean[] array) { style.append(buffer, fieldName, array, null); return this; } /** * <p>Append to the <code>toString</code> a <code>boolean</code> * array.</p> * * <p>A boolean parameter controls the level of detail to show. * Setting <code>true</code> will output the array in full. Setting * <code>false</code> will output a summary, typically the size of * the array.</p> * * @param fieldName the field name * @param array the array to add to the <code>toString</code> * @param fullDetail <code>true</code> for detail, <code>false</code> * for summary info * @return this */ public ToStringBuilder append(String fieldName, boolean[] array, boolean fullDetail) { style.append(buffer, fieldName, array, new Boolean(fullDetail)); return this; } /** * <p>Gets the <code>ToStringStyle</code> being used.</p> * * @return the <code>ToStringStyle</code> being used */ public ToStringStyle getStyle() { return style; } /** * <p>Gets the <code>StringBuffer</code> being populated.</p> * * @return the <code>StringBuffer</code> being populated */ public StringBuffer getStringBuffer() { return buffer; } /** * <p>Returns the built <code>toString</code>.</p> * * <p>This method appends the end of the buffer, and can only be called once. * Use {@link #getStringBuffer} to get the current string state.</p> * * @return the String <code>toString</code> */ public String toString() { style.appendEnd(buffer, object); return buffer.toString(); } }
package org.petapico.nanopub.indexer; import java.io.IOException; import java.util.List; import org.nanopub.Nanopub; import org.nanopub.NanopubUtils; import org.nanopub.extra.server.GetNanopub; import org.nanopub.extra.server.NanopubServerUtils; import org.nanopub.extra.server.ServerInfo; import org.nanopub.extra.server.ServerIterator; import org.openrdf.rio.RDFFormat; import org.openrdf.rio.RDFHandlerException; public class DataExtractor { public static void main(String[] args) throws IOException, RDFHandlerException { DataExtractor dataExtractor = new DataExtractor(); dataExtractor.run(); } public DataExtractor() { } public void run() throws IOException, RDFHandlerException { //Server iterator goes through every server ServerIterator serverIterator = new ServerIterator(); if (!serverIterator.hasNext()){ System.out.println("ERROR: NO SERVERS FOUND"); System.exit(0); } //for testing purposes we only use the first server ServerInfo si = serverIterator.next(); System.out.println("=========="); System.out.println("Server: " + si.getPublicUrl() + "\n"); int page = 0; int currentNanopub = 0; int totalNanopubs = 5; //(int) (si.getNextNanopubNo()-1); while (currentNanopub < totalNanopubs){ //There should be a page left //read from the next page page += 1; List<String> nanopubsOnPage = NanopubServerUtils.loadNanopubUriList(si, page); if (nanopubsOnPage.size() == 0){ break; //There are no nanopubs on this page } for (String nanopubId : nanopubsOnPage) { currentNanopub++; Nanopub np = GetNanopub.get(nanopubId); printInsertStatement(np); if (currentNanopub > 4) break; //break after 1 nanopub } } //System.out.println("all pages visited: "+ page); } public void printInsertValues(Nanopub np){ String nanopubURI = np.getUri().toString(); String artifactCode = org.nanopub.extra.server.GetNanopub.getArtifactCode(nanopubURI); String assertionURI = np.getAssertionUri().toString(); String headURI = np.getHeadUri().toString(); String provenanceURI = np.getProvenanceUri().toString(); String pubinfoURI = np.getPubinfoUri().toString(); long creationTime = np.getCreationTime().getTimeInMillis(); String query = "INSERT INTO nanopubs " + "(nanopubURI, artifactCode, assertionURI, headURI, provenanceURI, pubinfoURI, creationTime) " + "VALUES (\"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", %d)\n"; System.out.printf(query, nanopubURI, artifactCode, assertionURI, headURI, provenanceURI, pubinfoURI, creationTime); } public void printInsertStatement(Nanopub np){ String nanopubURI = np.getUri().toString(); String artifactCode = org.nanopub.extra.server.GetNanopub.getArtifactCode(nanopubURI); String assertionURI = np.getAssertionUri().toString(); String headURI = np.getHeadUri().toString(); String provenanceURI = np.getProvenanceUri().toString(); String pubinfoURI = np.getPubinfoUri().toString(); long creationTime = np.getCreationTime().getTimeInMillis(); String query = "INSERT INTO nanopubs " + "(nanopubURI, artifactCode, assertionURI, headURI, provenanceURI, pubinfoURI, creationTime) " + "VALUES (\"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", %d);\n"; System.out.printf(query, nanopubURI, artifactCode, assertionURI, headURI, provenanceURI, pubinfoURI, creationTime); } public void printNanopubInfo(Nanopub np){ System.out.println("Authors: " + np.getAuthors().toString()); System.out.println("Creators: " + np.getCreators().toString()); System.out.println("Assertion: " + np.getAssertion().toString()); System.out.println("AssertionURI: " + np.getAssertionUri().toString()); System.out.println("GraphURI: " + np.getGraphUris().toString()); System.out.println("Head: " + np.getHead().toString()); System.out.println("HeadURI: " + np.getHeadUri().toString()); System.out.println("Provenance: " + np.getProvenance().toString()); System.out.println("ProvenanceURI: " + np.getProvenanceUri().toString()); System.out.println("Pubinfo: " + np.getPubinfo().toString()); System.out.println("PubinfoURI: " + np.getPubinfoUri().toString()); System.out.println("URI: " + np.getUri().toString()); System.out.println("Creationtime: " + np.getCreationTime().getTimeInMillis()); //System.out.println("Nanopub content:" + NanopubUtils.writeToString(np, RDFFormat.TRIG) + "\n"); } public void printServerList(){ ServerIterator serverIterator = new ServerIterator(); while (serverIterator.hasNext()) { ServerInfo si = serverIterator.next(); System.out.println("=========="); System.out.println("Server: " + si.getPublicUrl() + "\n"); } } public void printServerInfo(ServerInfo si){ System.out.println("Server URL: " + si.getPublicUrl()); System.out.println("Protocol version: " + si.getProtocolVersion()); System.out.println("Description: " + si.getDescription()); String ad = si.getAdmin(); System.out.println("Admin: " + (ad == null || ad.isEmpty() ? "(unknown)" : ad)); System.out.println("Journal ID: " + si.getJournalId()); System.out.println("Page size: " + si.getPageSize()); System.out.println("Post peers: " + (si.isPostPeersEnabled() ? "enabled" : "disabled")); System.out.println("Post nanopubs: " + (si.isPostNanopubsEnabled() ? "enabled" : "disabled")); System.out.println("Nanopub count: " + (si.getNextNanopubNo()-1)); System.out.println("Max nanopubs: " + (si.getMaxNanopubs() == null ? "unrestricted" : si.getMaxNanopubs())); System.out.println("Max triples/nanopub: " + (si.getMaxNanopubTriples() == null ? "unrestricted" : si.getMaxNanopubTriples())); System.out.println("Max bytes/nanopub: " + (si.getMaxNanopubBytes() == null ? "unrestricted" : si.getMaxNanopubBytes())); System.out.println(); } }
package prm4j.indexing.staticdata; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Set; import prm4j.Util; import prm4j.Util.Tuple; import prm4j.api.BaseEvent; import prm4j.api.Parameter; import prm4j.spec.ParametricProperty; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.HashBasedTable; import com.google.common.collect.HashMultimap; import com.google.common.collect.ListMultimap; import com.google.common.collect.SetMultimap; import com.google.common.collect.Table; /** * Converts a {@link ParametricProperty} to an {@link EventContext} and a tree of {@link MetaNode}s. */ public class StaticDataConverter { private final static MaxData[] EMPTY_MAX_DATA = new MaxData[0]; private final static JoinData[] EMPTY_JOIN_DATA = new JoinData[0]; private final ParametricProperty pp; private final ListMultimap<BaseEvent, MaxData> maxData; private final ListMultimap<BaseEvent, JoinData> joinData; private final SetMultimap<Set<Parameter<?>>, ChainData> chainData; private final Table<Set<Parameter<?>>, Set<Parameter<?>>, Integer> monitorSetIds; private final MetaNode rootNode; public StaticDataConverter(ParametricProperty pp) { this.pp = pp; maxData = ArrayListMultimap.create(); joinData = ArrayListMultimap.create(); chainData = HashMultimap.create(); monitorSetIds = HashBasedTable.create(); convertToLowLevelStaticData(); rootNode = new MetaNode(new HashSet<Parameter<?>>(), pp.getParameters()); createMetaTree(); } /** * Creates arrays of maxData, joinData, chainData. */ private void convertToLowLevelStaticData() { for (Set<Parameter<?>> parameterSet : pp.getMonitorSetData().keys()) { ArrayList<Tuple<Set<Parameter<?>>, Boolean>> tupleList = new ArrayList<Tuple<Set<Parameter<?>>, Boolean>>( pp.getMonitorSetData().get(parameterSet)); Collections.sort(tupleList, new Comparator<Tuple<Set<Parameter<?>>, Boolean>>() { @Override public int compare(Tuple<Set<Parameter<?>>, Boolean> t1, Tuple<Set<Parameter<?>>, Boolean> t2) { return t1.getLeft().size() - t2.getLeft().size(); } }); int i = 0; for (Tuple<Set<Parameter<?>>, Boolean> tuple : tupleList) { monitorSetIds.put(parameterSet, tuple.getLeft(), i++); } } for (BaseEvent baseEvent : pp.getBaseEvents()) { for (Set<Parameter<?>> parameterSet : pp.getMaxData().get(baseEvent)) { final int[] nodeMask = toParameterMask(parameterSet); final int[] diffMask = toParameterMask(Util.difference(baseEvent.getParameters(), parameterSet)); maxData.put(baseEvent, new MaxData(nodeMask, diffMask)); } for (Tuple<Set<Parameter<?>>, Set<Parameter<?>>> tuple : pp.getJoinData().get(baseEvent)) { final int[] nodeMask = toParameterMask(tuple.getLeft()); final int monitorSetId = monitorSetIds.get(tuple.getLeft(), tuple.getRight()); final boolean[] extensionPattern = getExtensionPattern(tuple.getRight(), baseEvent.getParameters()); final int[] copyPattern = getCopyPattern(tuple.getRight(), baseEvent.getParameters()); joinData.put(baseEvent, new JoinData(nodeMask, monitorSetId, extensionPattern, copyPattern)); } } for (Set<Parameter<?>> parameterSet : pp.getChainData().keys()) { for (Tuple<Set<Parameter<?>>, Set<Parameter<?>>> tuple : pp.getChainData().get(parameterSet)) { final int[] nodeMask = toParameterMask(tuple.getLeft()); final int monitorSetId = monitorSetIds.get(tuple.getLeft(), tuple.getRight()); chainData.put(parameterSet, new ChainData(nodeMask, monitorSetId)); } } } protected static boolean[] getExtensionPattern(Set<Parameter<?>> ps1, Set<Parameter<?>> ps2) { List<Boolean> result = new ArrayList<Boolean>(); int i = 0; int j = 0; while (i < ps1.size() || j < ps2.size()) { if (i < ps1.size() && j < ps2.size() && toParameterMask(ps1)[i] == toParameterMask(ps2)[j]) { result.add(true); i++; j++; } else if (i < ps1.size() && (j >= ps2.size() || toParameterMask(ps1)[i] < toParameterMask(ps2)[j])) { result.add(true); i++; } else { result.add(false); j++; } } return toPrimitiveBooleanArray(result); } /** * Returns a pattern { s1, t1, ..., sN, tN } which represents a instruction to copy a binding from sourceBinding[s1] * to targetBinding[t1] to perform a join. * * @param ps1 * parameter set which masks the target binding * @param ps2 * parameter set which masks the source binding * @return the pattern */ protected static int[] getCopyPattern(Set<Parameter<?>> ps1, Set<Parameter<?>> ps2) { List<Integer> result = new ArrayList<Integer>(); int i = 0; int j = 0; int k = 0; while (i < ps1.size() || j < ps2.size()) { if (i < ps1.size() && j < ps2.size() && toParameterMask(ps1)[i] == toParameterMask(ps2)[j]) { i++; j++; } else if (i < ps1.size() && (j >= ps2.size() || toParameterMask(ps1)[i] < toParameterMask(ps2)[j])) { i++; } else { result.add(j++); result.add(i + k++); } } return toPrimitiveIntegerArray(result); } private static boolean[] toPrimitiveBooleanArray(Collection<Boolean> collection) { boolean[] result = new boolean[collection.size()]; int i = 0; for (Boolean b : collection) { result[i++] = b; } return result; } private static int[] toPrimitiveIntegerArray(Collection<Integer> collection) { int[] result = new int[collection.size()]; int i = 0; for (Integer n : collection) { result[i++] = n; } return result; } /** * Creates a tree of meta nodes */ private void createMetaTree() { Set<Set<Parameter<?>>> allParameterSets = new HashSet<Set<Parameter<?>>>(); allParameterSets.addAll(pp.getMonitorSetData().keys()); allParameterSets.addAll(pp.getPossibleParameterSets()); for (Set<Parameter<?>> parameterSet : allParameterSets) { List<Parameter<?>> parameterList = new ArrayList<Parameter<?>>(parameterSet); Collections.sort(parameterList); MetaNode node = rootNode; for (Parameter<?> parameter : parameterList) { node = node.getMetaNode(parameter); node.setChainData(chainData.get(node.getParameterSet()).toArray(new ChainData[0])); node.setMonitorSetCount(monitorSetIds.row(node.getParameterSet()).size()); } } } /** * @param parameterSet * @return an array representation of the parameter ids of the given parameter set (sorted) */ protected static int[] toParameterMask(Set<Parameter<?>> parameterSet) { int[] result = new int[parameterSet.size()]; int i = 0; for (Parameter<?> parameter : parameterSet) { result[i++] = parameter.getIndex(); } Arrays.sort(result); return result; } public EventContext getEventContext() { return new EventContext(getJoinData(), getMaxData(), getCreationEvents(), getDisablingEvents()); } /** * @return the rootnode of the tree of meta nodes */ public MetaNode getMetaTree() { return rootNode; } protected SetMultimap<Set<Parameter<?>>, ChainData> getChainData() { return chainData; } protected MaxData[][] getMaxData() { MaxData[][] maxDataArray = new MaxData[pp.getBaseEvents().size()][]; for (BaseEvent baseEvent : pp.getBaseEvents()) { maxDataArray[baseEvent.getIndex()] = maxData.get(baseEvent) != null ? maxData.get(baseEvent).toArray( EMPTY_MAX_DATA) : EMPTY_MAX_DATA; } return maxDataArray; } protected JoinData[][] getJoinData() { JoinData[][] joinDataArray = new JoinData[pp.getBaseEvents().size()][]; for (BaseEvent baseEvent : pp.getBaseEvents()) { joinDataArray[baseEvent.getIndex()] = joinData.get(baseEvent) != null ? joinData.get(baseEvent).toArray( EMPTY_JOIN_DATA) : EMPTY_JOIN_DATA; } return joinDataArray; } protected boolean[] getCreationEvents() { boolean[] creationEvents = new boolean[pp.getBaseEvents().size()]; for (BaseEvent baseEvent : pp.getBaseEvents()) { creationEvents[baseEvent.getIndex()] = pp.getCreationEvents().contains(baseEvent); } return creationEvents; } protected boolean[] getDisablingEvents() { boolean[] disablingEvents = new boolean[pp.getBaseEvents().size()]; for (BaseEvent baseEvent : pp.getBaseEvents()) { disablingEvents[baseEvent.getIndex()] = pp.getDisablingEvents().contains(baseEvent); } return disablingEvents; } }
package com.reason.ide.hints; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.LogicalPosition; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileEditor.TextEditor; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import com.intellij.psi.util.PsiTreeUtil; import com.reason.bs.Bucklescript; import com.reason.bs.BucklescriptProjectComponent; import com.reason.bs.hints.BsQueryTypesService; import com.reason.bs.hints.BsQueryTypesServiceComponent; import com.reason.lang.core.HMSignature; import com.reason.lang.core.psi.PsiLet; import com.reason.lang.core.psi.PsiModule; import com.reason.lang.core.psi.impl.PsiFileModuleImpl; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; public class InferredTypesService { public static void queryForSelectedTextEditor(Project project) { try { Editor selectedTextEditor = FileEditorManager.getInstance(project).getSelectedTextEditor(); if (selectedTextEditor != null) { Document document = selectedTextEditor.getDocument(); PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document); if (psiFile != null) { VirtualFile sourceFile = psiFile.getVirtualFile(); VirtualFile cmiPath = CmiFileManager.fromSource(project, sourceFile); if (cmiPath != null) { Bucklescript bucklescript = BucklescriptProjectComponent.getInstance(project); BsQueryTypesServiceComponent.InferredTypes types = bucklescript.queryTypes(cmiPath); ApplicationManager.getApplication().runReadAction(() -> annotatePsiExpressions(project, types, sourceFile)); } } } } catch (Error e) { // might produce an AssertionError when project is disposed but the invokeLater still process that code } } static void annotateFile(Project project, BsQueryTypesServiceComponent.InferredTypes types, VirtualFile sourceFile) { ApplicationManager.getApplication().runReadAction(() -> { annotatePsiExpressions(project, types, sourceFile); }); } private static void annotatePsiExpressions(@NotNull Project project, @Nullable BsQueryTypesService.InferredTypes types, @Nullable VirtualFile sourceFile) { if (types == null || sourceFile == null) { System.out.println("types: " + types + ", source: " + sourceFile); return; } CodeLensView.CodeLensInfo userData = project.getUserData(CodeLensView.CODE_LENS); if (userData == null) { userData = new CodeLensView.CodeLensInfo(); project.putUserData(CodeLensView.CODE_LENS, userData); } else { userData.clearInternalData(sourceFile); } PsiFile psiFile = PsiManager.getInstance(project).findFile(sourceFile); Collection<PsiLet> letExpressions = PsiTreeUtil.findChildrenOfType(psiFile, PsiLet.class); long timestamp = sourceFile.getTimeStamp(); FileEditorManager fem = FileEditorManager.getInstance(project); TextEditor selectedEditor = (TextEditor) fem.getSelectedEditor(sourceFile); if (selectedEditor != null) { for (PsiLet letStatement : letExpressions) { PsiElement letParent = letStatement.getParent(); if (letParent instanceof PsiFileModuleImpl) { HMSignature signature = applyType(types, letStatement); if (signature != null) { int letOffset = letStatement.getTextOffset(); LogicalPosition logicalPosition = selectedEditor.getEditor().offsetToLogicalPosition(letOffset); userData.put(sourceFile, logicalPosition, signature.toString(), timestamp); } } else { PsiModule letModule = PsiTreeUtil.getParentOfType(letStatement, PsiModule.class); if (letModule != null) { BsQueryTypesServiceComponent.InferredTypes inferredModuleTypes = types.getModuleType(letModule.getName()); if (inferredModuleTypes != null) { HMSignature signature = applyType(inferredModuleTypes, letStatement); if (signature != null) { int letOffset = letStatement.getTextOffset(); LogicalPosition logicalPosition = selectedEditor.getEditor().offsetToLogicalPosition(letOffset); userData.put(sourceFile, logicalPosition, signature.toString(), timestamp); } } } } } } } private static HMSignature applyType(@Nullable BsQueryTypesService.InferredTypes inferredTypes, PsiLet letStatement) { HMSignature signature = null; PsiElement letName = letStatement.getNameIdentifier(); if (letName != null && inferredTypes != null) { signature = inferredTypes.getLetType(letName.getText()); if (signature != null) { letStatement.setInferredType(signature); } } return signature; } }