answer
stringlengths
17
10.2M
package example; // tag::user_guide[] import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestReporter; class TestReporterDemo { @Test void reportSingleValue(TestReporter testReporter) { testReporter.publishEntry("a key", "a value"); } @Test void reportSeveralValues(TestReporter testReporter) { Map<String, String> values = new HashMap<>(); values.put("user name", "dk38"); values.put("award year", "1974"); testReporter.publishEntry(values); } } // end::user_guide[]
package com.jme3.cinematic.events; import com.jme3.animation.LoopMode; import com.jme3.app.Application; import com.jme3.audio.AudioNode; import com.jme3.audio.AudioRenderer; import com.jme3.cinematic.Cinematic; import com.jme3.export.InputCapsule; import com.jme3.export.JmeExporter; import com.jme3.export.JmeImporter; import com.jme3.export.OutputCapsule; import java.io.IOException; /** * A sound track to be played in a cinematic. * @author Nehon */ public class SoundTrack extends AbstractCinematicEvent { protected String path; protected AudioNode audioNode; protected boolean stream = false; /** * creates a sound track from the given resource path * @param path the path to an audi file (ie : "Sounds/mySound.wav") */ public SoundTrack(String path) { this.path = path; } /** * creates a sound track from the given resource path * @param path the path to an audi file (ie : "Sounds/mySound.wav") * @param stream true to make the audio data streamed */ public SoundTrack(String path, boolean stream) { this(path); this.stream = stream; } public SoundTrack(String path, boolean stream, float initialDuration) { super(initialDuration); this.path = path; this.stream = stream; } public SoundTrack(String path, boolean stream, LoopMode loopMode) { super(loopMode); this.path = path; this.stream = stream; } public SoundTrack(String path, boolean stream, float initialDuration, LoopMode loopMode) { super(initialDuration, loopMode); this.path = path; this.stream = stream; } public SoundTrack(String path, float initialDuration) { super(initialDuration); this.path = path; } public SoundTrack(String path, LoopMode loopMode) { super(loopMode); this.path = path; } public SoundTrack(String path, float initialDuration, LoopMode loopMode) { super(initialDuration, loopMode); this.path = path; } public SoundTrack() { } @Override public void initEvent(Application app, Cinematic cinematic) { audioNode = new AudioNode(app.getAssetManager(), path, stream); setLoopMode(loopMode); } @Override public void onPlay() { audioNode.play(); } @Override public void onStop() { audioNode.stop(); } @Override public void onPause() { audioNode.pause(); } @Override public void onUpdate(float tpf) { if (audioNode.getStatus() == AudioNode.Status.Stopped) { stop(); } } /** * Returns the underlying audion node of this sound track * @return */ public AudioNode getAudioNode() { return audioNode; } @Override public void setLoopMode(LoopMode loopMode) { super.setLoopMode(loopMode); if (loopMode != LoopMode.DontLoop) { audioNode.setLooping(true); } else { audioNode.setLooping(false); } } @Override public void write(JmeExporter ex) throws IOException { super.write(ex); OutputCapsule oc = ex.getCapsule(this); oc.write(path, "path", ""); oc.write(stream, "stream", false); } @Override public void read(JmeImporter im) throws IOException { super.read(im); InputCapsule ic = im.getCapsule(this); path = ic.readString("path", ""); stream = ic.readBoolean("stream", false); } }
package org.knowm.xchart.internal.chartpart; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.font.FontRenderContext; import java.awt.font.TextLayout; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.knowm.xchart.HeatMapChart; import org.knowm.xchart.internal.Utils; import org.knowm.xchart.internal.series.AxesChartSeries; import org.knowm.xchart.internal.series.AxesChartSeriesCategory; import org.knowm.xchart.internal.series.Series; import org.knowm.xchart.internal.series.Series.DataType; import org.knowm.xchart.style.AxesChartStyler; import org.knowm.xchart.style.BoxStyler; import org.knowm.xchart.style.CategoryStyler; import org.knowm.xchart.style.HeatMapStyler; import org.knowm.xchart.style.Styler.InfoPanelPosition; import org.knowm.xchart.style.Styler.LegendPosition; import org.knowm.xchart.style.Styler.YAxisPosition; /** Axis */ public class Axis<ST extends AxesChartStyler, S extends AxesChartSeries> implements ChartPart { private final Chart<ST, S> chart; private final Rectangle2D.Double bounds; private final ST axesChartStyler; /** the axis title */ private final AxisTitle<ST, S> axisTitle; /** the axis tick */ private final AxisTick<ST, S> axisTick; /** the axis direction */ private final Direction direction; /** the axis group index * */ private final int index; /** the dataType */ private Series.DataType dataType; /** the axis tick calculator */ private AxisTickCalculator_ axisTickCalculator; private double min; private double max; /** * Constructor * * @param chart the Chart * @param direction the axis direction (X or Y) * @param index the y-axis index (not relevant for x-axes) */ public Axis(Chart<ST, S> chart, Direction direction, int index) { this.chart = chart; this.axesChartStyler = chart.getStyler(); this.direction = direction; this.index = index; bounds = new Rectangle2D.Double(); axisTitle = new AxisTitle<ST, S>(chart, direction, direction == Direction.Y ? this : null, index); axisTick = new AxisTick<ST, S>(chart, direction, direction == Direction.Y ? this : null); } /** Reset the default min and max values in preparation for calculating the actual min and max */ void resetMinMax() { min = Double.MAX_VALUE; max = -1 * Double.MAX_VALUE; } /** * @param min * @param max */ void addMinMax(double min, double max) { // System.out.println(min); // System.out.println(max); // NaN indicates String axis data, so min and max play no role if (Double.isNaN(this.min) || min < this.min) { this.min = min; } if (Double.isNaN(this.max) || max > this.max) { this.max = max; } // System.out.println(this.min); // System.out.println(this.max); } public void preparePaint() { double legendHeightOffset = 0; if (axesChartStyler.isLegendVisible() && axesChartStyler.getLegendPosition() == LegendPosition.OutsideS) legendHeightOffset = chart.getLegend().getBounds().getHeight(); double infoPanelHeightOffset = 0; if (axesChartStyler.isInfoPanelVisible() && axesChartStyler.getInfoPanelPosition() == InfoPanelPosition.OutsideS) infoPanelHeightOffset = axesChartStyler.getInfoPanelPadding() / 2 + chart.getInfoPanel().getBounds().getHeight(); // determine Axis bounds if (direction == Direction.Y) { // Y-Axis - gets called first // calculate paint zone // double xOffset = chart.getAxisPair().getYAxisXOffset(); double xOffset = 0; // this will be updated on AxisPair.paint() method // double yOffset = chart.getChartTitle().getBounds().getHeight() < .1 ? // axesChartStyler.getChartPadding() : chart.getChartTitle().getBounds().getHeight() // + axesChartStyler.getChartPadding(); double yOffset = chart.getChartTitle().getBounds().getHeight() + axesChartStyler.getChartPadding(); int i = 1; // just twice through is all it takes double width = 60; // arbitrary, final width depends on Axis tick labels double height; do { // System.out.println("width before: " + width); double legendWidthOffset = 0; if (axesChartStyler.isLegendVisible() && axesChartStyler.getLegendPosition() == LegendPosition.OutsideE) legendWidthOffset = axesChartStyler.getChartPadding(); double approximateXAxisWidth = chart.getWidth() - width // y-axis approx. width - (axesChartStyler.getLegendPosition() == LegendPosition.OutsideE ? chart.getLegend().getBounds().getWidth() : 0) - 2 * axesChartStyler.getChartPadding() - (axesChartStyler.isYAxisTicksVisible() ? (axesChartStyler.getPlotMargin()) : 0) - legendWidthOffset; height = chart.getHeight() - yOffset - chart.getXAxis().getXAxisHeightHint(approximateXAxisWidth) - axesChartStyler.getPlotMargin() - axesChartStyler.getChartPadding() - legendHeightOffset - infoPanelHeightOffset; width = getYAxisWidthHint(height); // System.out.println("width after: " + width); // System.out.println("height: " + height); } while (i // bounds = new Rectangle2D.Double(xOffset, yOffset, width, height); bounds.setRect(xOffset, yOffset, width, height); } else { // X-Axis // calculate paint zone Rectangle2D leftYAxisBounds = chart.getAxisPair().getLeftYAxisBounds(); Rectangle2D rightYAxisBounds = chart.getAxisPair().getRightYAxisBounds(); double maxYAxisY = Math.max( leftYAxisBounds.getY() + leftYAxisBounds.getHeight(), rightYAxisBounds.getY() + rightYAxisBounds.getHeight()); double xOffset = leftYAxisBounds.getWidth() + leftYAxisBounds.getX(); double yOffset = maxYAxisY + axesChartStyler.getPlotMargin() - legendHeightOffset - infoPanelHeightOffset; double legendWidth = 0; if (axesChartStyler.getLegendPosition() == LegendPosition.OutsideE && axesChartStyler.isLegendVisible()) { legendWidth = chart.getLegend().getBounds().getWidth() + axesChartStyler.getChartPadding(); } double width = chart.getWidth() - leftYAxisBounds.getWidth() // y-axis was already painted - rightYAxisBounds.getWidth() // y-axis was already painted - leftYAxisBounds.getX() // use left y-axis x instead of padding - 1 * axesChartStyler.getChartPadding() // right y-axis padding // - tickMargin is included in left & right y axis bounds - legendWidth; // double height = this.getXAxisHeightHint(width); // System.out.println("height: " + height); // the Y-Axis was already draw at this point so we know how much vertical room is left for the // X-Axis double height = chart.getHeight() - maxYAxisY - axesChartStyler.getChartPadding() - axesChartStyler.getPlotMargin(); // System.out.println("height2: " + height2); bounds.setRect(xOffset, yOffset, width, height); } } @Override public void paint(Graphics2D g) { Object oldHint = g.getRenderingHint(RenderingHints.KEY_ANTIALIASING); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // determine Axis bounds if (direction == Direction.Y) { // Y-Axis - gets called first // fill in Axis with sub-components boolean onRight = axesChartStyler.getYAxisGroupPosistion(index) == YAxisPosition.Right; if (onRight) { axisTick.paint(g); axisTitle.paint(g); } else { axisTitle.paint(g); axisTick.paint(g); } // now we know the real bounds width after ticks and title are painted double width = (axesChartStyler.isYAxisTitleVisible() ? axisTitle.getBounds().getWidth() : 0) + axisTick.getBounds().getWidth(); bounds.width = width; // g.setColor(Color.yellow); // g.draw(bounds); } else { // X-Axis // calculate paint zone // g.setColor(Color.yellow); // g.draw(bounds); // now paint the X-Axis given the above paint zone this.axisTickCalculator = getAxisTickCalculator(bounds.getWidth()); axisTitle.paint(g); axisTick.paint(g); } g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, oldHint); } /** * The vertical Y-Axis is drawn first, but to know the lower bounds of it, we need to know how * high the X-Axis paint zone is going to be. Since the tick labels could be rotated, we need to * actually determine the tick labels first to get an idea of how tall the X-Axis tick labels will * be. * * @return the x-axis height hint */ private double getXAxisHeightHint(double workingSpace) { // Axis title double titleHeight = 0.0; if (chart.getXAxisTitle() != null && !chart.getXAxisTitle().trim().equalsIgnoreCase("") && axesChartStyler.isXAxisTitleVisible()) { TextLayout textLayout = new TextLayout( chart.getXAxisTitle(), axesChartStyler.getAxisTitleFont(), new FontRenderContext(null, true, false)); Rectangle2D rectangle = textLayout.getBounds(); titleHeight = rectangle.getHeight() + axesChartStyler.getAxisTitlePadding(); } this.axisTickCalculator = getAxisTickCalculator(workingSpace); // Axis tick labels double axisTickLabelsHeight = 0.0; if (axesChartStyler.isXAxisTicksVisible()) { // get some real tick labels // System.out.println("XAxisHeightHint"); // System.out.println("workingSpace: " + workingSpace); String sampleLabel = ""; // find the longest String in all the labels for (int i = 0; i < axisTickCalculator.getTickLabels().size(); i++) { // System.out.println("label: " + axisTickCalculator.getTickLabels().get(i)); if (axisTickCalculator.getTickLabels().get(i) != null && axisTickCalculator.getTickLabels().get(i).length() > sampleLabel.length()) { sampleLabel = axisTickCalculator.getTickLabels().get(i); } } // System.out.println("sampleLabel: " + sampleLabel); // get the height of the label including rotation TextLayout textLayout = new TextLayout( sampleLabel.length() == 0 ? " " : sampleLabel, axesChartStyler.getAxisTickLabelsFont(), new FontRenderContext(null, true, false)); AffineTransform rot = axesChartStyler.getXAxisLabelRotation() == 0 ? null : AffineTransform.getRotateInstance( -1 * Math.toRadians(axesChartStyler.getXAxisLabelRotation())); Shape shape = textLayout.getOutline(rot); Rectangle2D rectangle = shape.getBounds(); axisTickLabelsHeight = rectangle.getHeight() + axesChartStyler.getAxisTickPadding() + axesChartStyler.getAxisTickMarkLength(); } return titleHeight + axisTickLabelsHeight; } private double getYAxisWidthHint(double workingSpace) { // Axis title double titleHeight = 0.0; String yAxisTitle = chart.getYAxisGroupTitle(index); if (yAxisTitle != null && !yAxisTitle.trim().equalsIgnoreCase("") && axesChartStyler.isYAxisTitleVisible()) { TextLayout textLayout = new TextLayout( yAxisTitle, axesChartStyler.getAxisTitleFont(), new FontRenderContext(null, true, false)); Rectangle2D rectangle = textLayout.getBounds(); titleHeight = rectangle.getHeight() + axesChartStyler.getAxisTitlePadding(); } this.axisTickCalculator = getAxisTickCalculator(workingSpace); // Axis tick labels double axisTickLabelsHeight = 0.0; if (axesChartStyler.isYAxisTicksVisible()) { // get some real tick labels // System.out.println("XAxisHeightHint"); // System.out.println("workingSpace: " + workingSpace); String sampleLabel = ""; // find the longest String in all the labels for (int i = 0; i < axisTickCalculator.getTickLabels().size(); i++) { if (axisTickCalculator.getTickLabels().get(i) != null && axisTickCalculator.getTickLabels().get(i).length() > sampleLabel.length()) { sampleLabel = axisTickCalculator.getTickLabels().get(i); } } // get the height of the label including rotation TextLayout textLayout = new TextLayout( sampleLabel.length() == 0 ? " " : sampleLabel, axesChartStyler.getAxisTickLabelsFont(), new FontRenderContext(null, true, false)); Rectangle2D rectangle = textLayout.getBounds(); axisTickLabelsHeight = rectangle.getWidth() + axesChartStyler.getAxisTickPadding() + axesChartStyler.getAxisTickMarkLength(); } return titleHeight + axisTickLabelsHeight; } private AxisTickCalculator_ getAxisTickCalculator(double workingSpace) { // check if a label override map for the y axis is present Map<Object, Object> customTickLabelsMap = chart.getAxisPair().getCustomTickLabelsMap(getDirection(), index); if (customTickLabelsMap != null) { if (getDirection() == Direction.X && axesChartStyler instanceof CategoryStyler) { // get the first series AxesChartSeriesCategory axesChartSeries = (AxesChartSeriesCategory) chart.getSeriesMap().values().iterator().next(); // get the first categories, could be Number Date or String List<?> categories = (List<?>) axesChartSeries.getXData(); // add the custom tick labels for the categories Map<Double, Object> axisTickValueLabelMap = new LinkedHashMap<>(); for (Entry<Object, Object> entry : customTickLabelsMap.entrySet()) { int index = categories.indexOf(entry.getKey()); if (index == -1) { throw new IllegalArgumentException( "Could not find category index for " + entry.getKey()); } axisTickValueLabelMap.put((double) index, entry.getValue()); } return new AxisTickCalculator_Override( getDirection(), workingSpace, axesChartStyler, axisTickValueLabelMap, chart.getAxisPair().getXAxis().getDataType(), categories.size()); } else { // add the custom tick labels for the values Map<Double, Object> axisTickValueLabelMap = new LinkedHashMap<>(); for (Entry<Object, Object> entry : customTickLabelsMap.entrySet()) { Number axisTickValue = (Number) entry.getKey(); axisTickValueLabelMap.put(axisTickValue.doubleValue(), entry.getValue()); } return new AxisTickCalculator_Override( getDirection(), workingSpace, min, max, axesChartStyler, axisTickValueLabelMap); } } // X-Axis if (getDirection() == Direction.X) { if (axesChartStyler instanceof CategoryStyler || axesChartStyler instanceof BoxStyler) { // TODO Cleanup? More elegant way? AxesChartSeriesCategory axesChartSeries = (AxesChartSeriesCategory) chart.getSeriesMap().values().iterator().next(); List<?> categories = (List<?>) axesChartSeries.getXData(); DataType axisType = chart.getAxisPair().getXAxis().getDataType(); return new AxisTickCalculator_Category( getDirection(), workingSpace, categories, axisType, axesChartStyler); } else if (getDataType() == Series.DataType.Date && !(axesChartStyler instanceof HeatMapStyler)) { return new AxisTickCalculator_Date(getDirection(), workingSpace, min, max, axesChartStyler); } else if (axesChartStyler.isXAxisLogarithmic()) { return new AxisTickCalculator_Logarithmic( getDirection(), workingSpace, min, max, axesChartStyler); } else if (axesChartStyler instanceof HeatMapStyler) { List<?> categories = (List<?>) ((HeatMapChart) chart).getHeatMapSeries().getXData(); DataType axisType = chart.getAxisPair().getXAxis().getDataType(); return new AxisTickCalculator_Category( getDirection(), workingSpace, categories, axisType, axesChartStyler); } else { return new AxisTickCalculator_Number( getDirection(), workingSpace, min, max, axesChartStyler); } } // Y-Axis else { if (axesChartStyler.isYAxisLogarithmic() && getDataType() != Series.DataType.Date) { return new AxisTickCalculator_Logarithmic( getDirection(), workingSpace, min, max, axesChartStyler, getYIndex()); } else if (axesChartStyler instanceof HeatMapStyler) { List<?> categories = (List<?>) ((HeatMapChart) chart).getHeatMapSeries().getYData(); DataType axisType = chart.getAxisPair().getYAxis().getDataType(); return new AxisTickCalculator_Category( getDirection(), workingSpace, categories, axisType, axesChartStyler); } else { return new AxisTickCalculator_Number( getDirection(), workingSpace, min, max, axesChartStyler, getYIndex()); } } } Series.DataType getDataType() { return dataType; } // Getters ///////////////////////////////////////////////// public void setDataType(Series.DataType dataType) { if (dataType != null && this.dataType != null && this.dataType != dataType) { throw new IllegalArgumentException( "Different Axes (e.g. Date, Number, String) cannot be mixed on the same chart!!"); } this.dataType = dataType; } double getMin() { return min; } void setMin(double min) { this.min = min; } double getMax() { return max; } void setMax(double max) { this.max = max; } AxisTick<ST, S> getAxisTick() { return axisTick; } private Direction getDirection() { return direction; } AxisTitle<ST, S> getAxisTitle() { return axisTitle; } public AxisTickCalculator_ getAxisTickCalculator() { return this.axisTickCalculator; } @Override public Rectangle2D getBounds() { return bounds; } public int getYIndex() { return index; } /** * Converts a chart coordinate value to screen coordinate. Same as AxisTickCalculators * calculation. * * @param chartPoint value in chart coordinate system * @return Coordinate of screen. eg: MouseEvent.getX(), MouseEvent.getY() */ public double getScreenValue(double chartPoint) { double minVal = min; double maxVal = max; // min & max is not set in category charts with string labels if (min > max) { if (getDirection() == Direction.X) { if (axesChartStyler instanceof CategoryStyler) { AxesChartSeriesCategory axesChartSeries = (AxesChartSeriesCategory) chart.getSeriesMap().values().iterator().next(); int count = axesChartSeries.getXData().size(); minVal = 0; maxVal = count; } } } double workingSpace; double startOffset; boolean isLog; if (direction == Direction.X) { startOffset = bounds.getX(); workingSpace = bounds.getWidth(); isLog = axesChartStyler.isXAxisLogarithmic(); } else { startOffset = 0; // bounds.getY(); workingSpace = bounds.getHeight(); isLog = axesChartStyler.isYAxisLogarithmic(); } // a check if all axis data are the exact same values if (min == max) { return workingSpace / 2; } // tick space - a percentage of the working space available for ticks double tickSpace = axesChartStyler.getPlotContentSize() * workingSpace; // in plot space // this prevents an infinite loop when the plot gets sized really small. if (tickSpace < axesChartStyler.getXAxisTickMarkSpacingHint()) { return workingSpace / 2; } // where the tick should begin in the working space in pixels double margin = Utils.getTickStartOffset(workingSpace, tickSpace); minVal = isLog ? Math.log10(minVal) : minVal; maxVal = isLog ? Math.log10(maxVal) : maxVal; chartPoint = isLog ? Math.log10(chartPoint) : chartPoint; double tickLabelPosition = startOffset + margin + ((chartPoint - minVal) / (maxVal - minVal) * tickSpace); if (direction == Direction.Y) { tickLabelPosition = bounds.getHeight() - tickLabelPosition + bounds.getY(); } return tickLabelPosition; } /** * Converts a screen coordinate to chart coordinate value. Reverses the AxisTickCalculators * calculation. * * @param screenPoint Coordinate of screen. eg: MouseEvent.getX(), MouseEvent.getY() * @return value in chart coordinate system */ public double getChartValue(double screenPoint) { // a check if all axis data are the exact same values if (min == max) { return min; } double minVal = min; double maxVal = max; // min & max is not set in category charts with string labels if (min > max) { if (getDirection() == Direction.X) { if (axesChartStyler instanceof CategoryStyler) { AxesChartSeriesCategory axesChartSeries = (AxesChartSeriesCategory) chart.getSeriesMap().values().iterator().next(); int count = axesChartSeries.getXData().size(); minVal = 0; maxVal = count; } } } double workingSpace; double startOffset; boolean isLog; if (direction == Direction.X) { startOffset = bounds.getX(); workingSpace = bounds.getWidth(); isLog = axesChartStyler.isXAxisLogarithmic(); } else { startOffset = 0; // bounds.getY(); workingSpace = bounds.getHeight(); screenPoint = bounds.getHeight() - screenPoint + bounds.getY(); // y increments top to bottom isLog = axesChartStyler.isYAxisLogarithmic(); } // tick space - a percentage of the working space available for ticks double tickSpace = axesChartStyler.getPlotContentSize() * workingSpace; // in plot space // this prevents an infinite loop when the plot gets sized really small. if (tickSpace < axesChartStyler.getXAxisTickMarkSpacingHint()) { return minVal; } // where the tick should begin in the working space in pixels double margin = Utils.getTickStartOffset(workingSpace, tickSpace); // given tickLabelPositon (screenPoint) find value // double tickLabelPosition = // margin + ((value - min) / (max - min) * tickSpace); minVal = isLog ? Math.log10(minVal) : minVal; maxVal = isLog ? Math.log10(maxVal) : maxVal; double value = ((screenPoint - margin - startOffset) * (maxVal - minVal) / tickSpace) + minVal; value = isLog ? Math.pow(10, value) : value; return value; } /** An axis direction */ public enum Direction { /** the constant to represent X axis */ X, /** the constant to represent Y axis */ Y } }
package org.jboss.dna.common.util; import java.util.Collection; import java.util.Iterator; import java.util.Map; import org.jboss.dna.common.CommonI18n; /** * Utility class that checks arguments to methods. This class is to be used only in API methods, where failure to supply correct * arguments should result in a useful error message. In all cases, use the <code>assert</code> statement. */ public final class CheckArg { // public static void isNotLessThan( int argument, int notLessThanValue, String name ) { if (argument < notLessThanValue) { throw new IllegalArgumentException(CommonI18n.argumentMayNotBeLessThan.text(name, argument, notLessThanValue)); } } public static void isNotGreaterThan( int argument, int notGreaterThanValue, String name ) { if (argument > notGreaterThanValue) { throw new IllegalArgumentException(CommonI18n.argumentMayNotBeGreaterThan.text(name, argument, notGreaterThanValue)); } } public static void isGreaterThan( int argument, int greaterThanValue, String name ) { if (argument <= greaterThanValue) { throw new IllegalArgumentException(CommonI18n.argumentMustBeGreaterThan.text(name, argument, greaterThanValue)); } } public static void isGreaterThan( double argument, double greaterThanValue, String name ) { if (argument <= greaterThanValue) { throw new IllegalArgumentException(CommonI18n.argumentMustBeGreaterThan.text(name, argument, greaterThanValue)); } } public static void isLessThan( int argument, int lessThanValue, String name ) { if (argument >= lessThanValue) { throw new IllegalArgumentException(CommonI18n.argumentMustBeLessThan.text(name, argument, lessThanValue)); } } public static void isGreaterThanOrEqualTo( int argument, int greaterThanOrEqualToValue, String name ) { if (argument < greaterThanOrEqualToValue) { throw new IllegalArgumentException(CommonI18n.argumentMustBeGreaterThanOrEqualTo.text(name, argument, greaterThanOrEqualToValue)); } } public static void isLessThanOrEqualTo( int argument, int lessThanOrEqualToValue, String name ) { if (argument > lessThanOrEqualToValue) { throw new IllegalArgumentException(CommonI18n.argumentMustBeLessThanOrEqualTo.text(name, argument, lessThanOrEqualToValue)); } } public static void isNonNegative( int argument, String name ) { if (argument < 0) { throw new IllegalArgumentException(CommonI18n.argumentMayNotBeNegative.text(name, argument)); } } public static void isNonPositive( int argument, String name ) { if (argument > 0) { throw new IllegalArgumentException(CommonI18n.argumentMayNotBePositive.text(name, argument)); } } public static void isNegative( int argument, String name ) { if (argument >= 0) { throw new IllegalArgumentException(CommonI18n.argumentMustBeNegative.text(name, argument)); } } public static void isPositive( int argument, String name ) { if (argument <= 0) { throw new IllegalArgumentException(CommonI18n.argumentMustBePositive.text(name, argument)); } } // public static void isNonNegative( long argument, String name ) { if (argument < 0) { throw new IllegalArgumentException(CommonI18n.argumentMayNotBeNegative.text(name, argument)); } } public static void isNonPositive( long argument, String name ) { if (argument > 0) { throw new IllegalArgumentException(CommonI18n.argumentMayNotBePositive.text(name, argument)); } } public static void isNegative( long argument, String name ) { if (argument >= 0) { throw new IllegalArgumentException(CommonI18n.argumentMustBeNegative.text(name, argument)); } } public static void isPositive( long argument, String name ) { if (argument <= 0) { throw new IllegalArgumentException(CommonI18n.argumentMustBePositive.text(name, argument)); } } // public static void isNonNegative( double argument, String name ) { if (argument < 0.0) { throw new IllegalArgumentException(CommonI18n.argumentMayNotBeNegative.text(name, argument)); } } public static void isNonPositive( double argument, String name ) { if (argument > 0.0) { throw new IllegalArgumentException(CommonI18n.argumentMayNotBePositive.text(name, argument)); } } public static void isNegative( double argument, String name ) { if (argument >= 0.0) { throw new IllegalArgumentException(CommonI18n.argumentMustBeNegative.text(name, argument)); } } public static void isPositive( double argument, String name ) { if (argument <= 0.0) { throw new IllegalArgumentException(CommonI18n.argumentMustBePositive.text(name, argument)); } } public static void isNotNan( double argument, String name ) { if (Double.isNaN(argument)) { throw new IllegalArgumentException(CommonI18n.argumentMustBeNumber.text(name)); } } // public static void isNotZeroLength( String argument, String name ) { isNotNull(argument, name); if (argument.length() <= 0) { throw new IllegalArgumentException(CommonI18n.argumentMayNotBeNullOrZeroLength.text(name)); } } public static void isNotEmpty( String argument, String name ) { isNotZeroLength(argument, name); if (argument != null && argument.trim().length() == 0) { throw new IllegalArgumentException(CommonI18n.argumentMayNotBeNullOrZeroLengthOrEmpty.text(name)); } } // public static void isNotNull( Object argument, String name ) { if (argument == null) { throw new IllegalArgumentException(CommonI18n.argumentMayNotBeNull.text(name)); } } public static <T> T getNotNull( T argument, String name ) { isNotNull(argument, name); return argument; } public static void isNull( Object argument, String name ) { if (argument != null) { throw new IllegalArgumentException(CommonI18n.argumentMustBeNull.text(name)); } } public static void isInstanceOf( Object argument, Class<?> expectedClass, String name ) { isNotNull(argument, name); if (!expectedClass.isInstance(argument)) { throw new IllegalArgumentException(CommonI18n.argumentMustBeInstanceOf.text(name, argument.getClass(), expectedClass.getName())); } } // due to cast in return public static <C> C getInstanceOf( Object argument, Class<C> expectedClass, String name ) { isInstanceOf(argument, expectedClass, name); return expectedClass.cast(argument); } public static <T> void isSame( final T argument, String argumentName, final T object, String objectName ) { if (argument != object) { if (objectName == null) objectName = getObjectName(object); throw new IllegalArgumentException(CommonI18n.argumentMustBeSameAs.text(argumentName, objectName)); } } public static <T> void isNotSame( final T argument, String argumentName, final T object, String objectName ) { if (argument == object) { if (objectName == null) objectName = getObjectName(object); throw new IllegalArgumentException(CommonI18n.argumentMustNotBeSameAs.text(argumentName, objectName)); } } public static <T> void isEquals( final T argument, String argumentName, final T object, String objectName ) { if (!argument.equals(object)) { if (objectName == null) objectName = getObjectName(object); throw new IllegalArgumentException(CommonI18n.argumentMustBeEquals.text(argumentName, objectName)); } } public static <T> void isNotEquals( final T argument, String argumentName, final T object, String objectName ) { if (argument.equals(object)) { if (objectName == null) objectName = getObjectName(object); throw new IllegalArgumentException(CommonI18n.argumentMustNotBeEquals.text(argumentName, objectName)); } } // public static void isNotEmpty( Iterator<?> argument, String name ) { isNotNull(argument, name); if (!argument.hasNext()) { throw new IllegalArgumentException(CommonI18n.argumentMayNotBeEmpty.text(name)); } } // public static void isNotEmpty( Collection<?> argument, String name ) { isNotNull(argument, name); if (argument.isEmpty()) { throw new IllegalArgumentException(CommonI18n.argumentMayNotBeEmpty.text(name)); } } public static void isNotEmpty( Map<?, ?> argument, String name ) { isNotNull(argument, name); if (argument.isEmpty()) { throw new IllegalArgumentException(CommonI18n.argumentMayNotBeEmpty.text(name)); } } public static void isNotEmpty( Object[] argument, String name ) { isNotNull(argument, name); if (argument.length == 0) { throw new IllegalArgumentException(CommonI18n.argumentMayNotBeEmpty.text(name)); } } protected static String getObjectName( Object obj ) { return obj == null ? null : "'" + obj.toString() + "'"; } public static void contains( Collection<?> argument, Object value, String name ) { isNotNull(argument, name); if (!argument.contains(value)) { throw new IllegalArgumentException(CommonI18n.argumentDidNotContainObject.text(name, getObjectName(value))); } } public static void containsKey( Map<?, ?> argument, Object key, String name ) { isNotNull(argument, name); if (!argument.containsKey(key)) { throw new IllegalArgumentException(CommonI18n.argumentDidNotContainKey.text(name, getObjectName(key))); } } public static void containsNoNulls( Iterable<?> argument, String name ) { isNotNull(argument, name); int i = 0; for (Object object : argument) { if (object == null) { throw new IllegalArgumentException(CommonI18n.argumentMayNotContainNullValue.text(name, i)); } ++i; } } public static void containsNoNulls( Object[] argument, String name ) { isNotNull(argument, name); int i = 0; for (Object object : argument) { if (object == null) { throw new IllegalArgumentException(CommonI18n.argumentMayNotContainNullValue.text(name, i)); } ++i; } } public static void hasSizeOfAtLeast( Collection<?> argument, int minimumSize, String name ) { isNotNull(argument, name); if (argument.size() < minimumSize) { throw new IllegalArgumentException(CommonI18n.argumentMustBeOfMinimumSize.text(name, Collection.class.getSimpleName(), argument.size(), minimumSize)); } } public static void hasSizeOfAtMost( Collection<?> argument, int maximumSize, String name ) { isNotNull(argument, name); if (argument.size() > maximumSize) { throw new IllegalArgumentException(CommonI18n.argumentMustBeOfMinimumSize.text(name, Collection.class.getSimpleName(), argument.size(), maximumSize)); } } public static void hasSizeOfAtLeast( Map<?, ?> argument, int minimumSize, String name ) { isNotNull(argument, name); if (argument.size() < minimumSize) { throw new IllegalArgumentException(CommonI18n.argumentMustBeOfMinimumSize.text(name, Map.class.getSimpleName(), argument.size(), minimumSize)); } } public static void hasSizeOfAtMost( Map<?, ?> argument, int maximumSize, String name ) { isNotNull(argument, name); if (argument.size() > maximumSize) { throw new IllegalArgumentException(CommonI18n.argumentMustBeOfMinimumSize.text(name, Map.class.getSimpleName(), argument.size(), maximumSize)); } } public static void hasSizeOfAtLeast( Object[] argument, int minimumSize, String name ) { isNotNull(argument, name); if (argument.length < minimumSize) { throw new IllegalArgumentException(CommonI18n.argumentMustBeOfMinimumSize.text(name, Object[].class.getSimpleName(), argument.length, minimumSize)); } } public static void hasSizeOfAtMost( Object[] argument, int maximumSize, String name ) { isNotNull(argument, name); if (argument.length > maximumSize) { throw new IllegalArgumentException(CommonI18n.argumentMustBeOfMinimumSize.text(name, Object[].class.getSimpleName(), argument.length, maximumSize)); } } private CheckArg() { // prevent construction } }
package org.codehaus.xfire.test; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import junit.framework.TestCase; import org.codehaus.xfire.MessageContext; import org.codehaus.xfire.XFire; import org.codehaus.xfire.XFireFactory; import org.codehaus.xfire.exchange.InMessage; import org.codehaus.xfire.service.Service; import org.codehaus.xfire.service.ServiceFactory; import org.codehaus.xfire.service.ServiceRegistry; import org.codehaus.xfire.service.binding.MessageBindingProvider; import org.codehaus.xfire.service.binding.ObjectServiceFactory; import org.codehaus.xfire.soap.Soap11; import org.codehaus.xfire.soap.Soap12; import org.codehaus.xfire.soap.SoapConstants; import org.codehaus.xfire.transport.Channel; import org.codehaus.xfire.transport.Session; import org.codehaus.xfire.transport.Transport; import org.codehaus.xfire.transport.local.LocalTransport; import org.codehaus.xfire.util.STAXUtils; import org.codehaus.xfire.util.jdom.StaxBuilder; import org.codehaus.xfire.wsdl.WSDLWriter; import org.jdom.Document; import org.jdom.Element; import org.jdom.output.XMLOutputter; /** * Contains helpful methods to test SOAP services. * * @author <a href="mailto:dan@envoisolutions.com">Dan Diephouse</a> */ public abstract class AbstractXFireTest extends TestCase { private XFire xfire; private ServiceFactory factory; private static String basedirPath; private XMLInputFactory defaultInputFactory = XMLInputFactory.newInstance(); /** * Namespaces for the XPath expressions. */ private Map namespaces = new HashMap(); private SimpleSession session; protected void printNode(Document node) throws Exception { XMLOutputter writer = new XMLOutputter(); writer.output(node, System.out); } protected void printNode(Element node) throws Exception { XMLOutputter writer = new XMLOutputter(); writer.output(node, System.out); } /** * Invoke a service with the specified document. * * @param service The name of the service. * @param document The request as an xml document in the classpath. */ protected Document invokeService(String service, String document) throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); MessageContext context = new MessageContext(); context.setSession( session ); context.setXFire(getXFire()); context.setProperty(Channel.BACKCHANNEL_URI, out); if (service != null) context.setService(getServiceRegistry().getService(service)); InputStream stream = getResourceAsStream(document); InMessage msg = new InMessage(STAXUtils.createXMLStreamReader(stream, "UTF-8")); Transport t = getXFire().getTransportManager().getTransport(LocalTransport.BINDING_ID); Channel c = t.createChannel(); c.receive(context, msg); String response = out.toString(); if (response == null || response.length() == 0) return null; return readDocument(response); } protected Document readDocument(String text) throws XMLStreamException { return readDocument(text, defaultInputFactory); } protected Document readDocument(String text, XMLInputFactory ifactory) throws XMLStreamException { try { StaxBuilder builder = new StaxBuilder(ifactory); return builder.build(new StringReader(text)); } catch (XMLStreamException e) { System.err.println("Could not read the document!"); System.err.println(text); throw e; } } protected Document getWSDLDocument(String service) throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); getXFire().generateWSDL(service, out); return readDocument(out.toString()); } /** * @see junit.framework.TestCase#setUp() */ protected void setUp() throws Exception { super.setUp(); if( xfire == null ) xfire = XFireFactory.newInstance().getXFire(); addNamespace( "s", Soap11.getInstance().getNamespace() ); addNamespace( "soap12", Soap12.getInstance().getNamespace() ); createSession(); } protected void createSession() { session = new SimpleSession(); } /** * Assert that the following XPath query selects one or more nodes. * * @param xpath */ public List assertValid(String xpath, Object node) throws Exception { return XPathAssert.assertValid(xpath, node, namespaces); } /** * Assert that the following XPath query selects no nodes. * * @param xpath */ public List assertInvalid(String xpath, Object node) throws Exception { return XPathAssert.assertInvalid(xpath, node, namespaces); } /** * Asser that the text of the xpath node retrieved is equal to the value specified. * * @param xpath * @param value * @param node */ public void assertXPathEquals(String xpath, String value, Document node) throws Exception { XPathAssert.assertXPathEquals(xpath, value, node, namespaces); } public void assertNoFault(Document node) throws Exception { XPathAssert.assertNoFault(node); } /** * Add a namespace that will be used for XPath expressions. * * @param ns Namespace name. * @param uri The namespace uri. */ public void addNamespace(String ns, String uri) { namespaces.put(ns, uri); } /** * Get the WSDL for a service. * * @param service The name of the service. */ protected WSDLWriter getWSDL(String service) throws Exception { ServiceRegistry reg = getServiceRegistry(); Service hello = reg.getService(service); return hello.getWSDLWriter(); } protected Session getSession() { return session; } protected XFire getXFire() { return xfire; } protected ServiceRegistry getServiceRegistry() { return getXFire().getServiceRegistry(); } public ServiceFactory getServiceFactory() { if (factory == null) { ObjectServiceFactory ofactory = new ObjectServiceFactory(getXFire().getTransportManager(), new MessageBindingProvider()); ofactory.setStyle(SoapConstants.STYLE_MESSAGE); factory = ofactory; } return factory; } public void setServiceFactory(ServiceFactory factory) { this.factory = factory; } protected InputStream getResourceAsStream(String resource) { return getClass().getResourceAsStream(resource); } protected Reader getResourceAsReader(String resource) { return new InputStreamReader(getResourceAsStream(resource)); } public File getTestFile(String relativePath) { return new File(getBasedir(), relativePath); } public static String getBasedir() { if (basedirPath != null) { return basedirPath; } basedirPath = System.getProperty("basedir"); if (basedirPath == null) { basedirPath = new File("").getAbsolutePath(); } return basedirPath; } private static class SimpleSession implements Session { Map values = new HashMap(); public Object get( Object key ) { return values.get( key ); } public void put( Object key, Object value ) { values.put( key, value ); } } }
package jkind; import java.math.BigInteger; import java.util.Arrays; import java.util.List; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; public class JKindArgumentParser { private static final String EXCEL = "excel"; private static final String INDUCT_CEX = "induct_cex"; private static final String INTERVAL = "interval"; private static final String N = "n"; private static final String NO_BMC = "no_bmc"; private static final String NO_INV_GEN = "no_inv_gen"; private static final String NO_K_INDUCTION = "no_k_induction"; private static final String PDR_MAX = "pdr_max"; private static final String READ_ADVICE = "read_advice"; private static final String REDUCE_INV = "reduce_inv"; private static final String SCRATCH = "scratch"; private static final String SMOOTH = "smooth"; private static final String SOLVER = "solver"; private static final String TIMEOUT = "timeout"; private static final String WRITE_ADVICE = "write_advice"; private static final String XML = "xml"; private static final String XML_TO_STDOUT = "xml_to_stdout"; private static final String VERSION = "version"; private static final String HELP = "help"; private static Options getOptions() { Options options = new Options(); options.addOption(EXCEL, false, "generate results in Excel format"); options.addOption(INDUCT_CEX, false, "generate inductive counterexamples"); options.addOption(INTERVAL, false, "generalize counterexamples using interval analysis"); options.addOption(N, true, "maximum depth for bmc and k-induction (default: 200)"); options.addOption(NO_BMC, false, "disable bounded model checking"); options.addOption(NO_INV_GEN, false, "disable invariant generation"); options.addOption(NO_K_INDUCTION, false, "disable k-induction"); options.addOption(PDR_MAX, true, "maximum number of PDR parallel instances (0 to disable PDR)"); options.addOption(READ_ADVICE, true, "read advice from specified file"); options.addOption(REDUCE_INV, false, "reduce and display invariants used"); options.addOption(SCRATCH, false, "produce files for debugging purposes"); options.addOption(SMOOTH, false, "smooth counterexamples (minimal changes in input values)"); options.addOption(SOLVER, true, "SMT solver (default: yices, alternatives: cvc4, z3, yices2, mathsat, smtinterpol)"); options.addOption(TIMEOUT, true, "maximum runtime in seconds (default: 100)"); options.addOption(WRITE_ADVICE, true, "write advice to specified file"); options.addOption(XML, false, "generate results in XML format"); options.addOption(XML_TO_STDOUT, false, "generate results in XML format on stardard out"); options.addOption(VERSION, false, "display version information"); options.addOption(HELP, false, "print this message"); return options; } public static JKindSettings parse(String[] args) { CommandLineParser parser = new BasicParser(); try { JKindSettings settings = getSettings(parser.parse(getOptions(), args)); checkSettings(settings); return settings; } catch (Throwable t) { Output.fatal(ExitCodes.INVALID_OPTIONS, "reading command line arguments: " + t.getMessage()); return null; } } private static void printHelp() { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("jkind [options] <input>", getOptions()); } private static JKindSettings getSettings(CommandLine line) { JKindSettings settings = new JKindSettings(); ensureExclusive(line, EXCEL, XML); ensureExclusive(line, EXCEL, XML_TO_STDOUT); ensureExclusive(line, XML, XML_TO_STDOUT); if (line.hasOption(VERSION)) { Output.println("JKind " + Main.VERSION); System.exit(0); } if (line.hasOption(HELP)) { printHelp(); System.exit(0); } if (line.hasOption(EXCEL)) { settings.excel = true; } if (line.hasOption(INDUCT_CEX)) { settings.inductiveCounterexamples = true; } if (line.hasOption(NO_BMC)) { settings.boundedModelChecking = false; } if (line.hasOption(NO_INV_GEN)) { settings.invariantGeneration = false; } if (line.hasOption(NO_K_INDUCTION)) { settings.kInduction = false; } if (line.hasOption(N)) { settings.n = parseNonnegativeInt(line.getOptionValue(N)); } if (line.hasOption(PDR_MAX)) { settings.pdrMax = parseNonnegativeInt(line.getOptionValue(PDR_MAX)); } else { int available = Runtime.getRuntime().availableProcessors(); int heuristic = (available - 4) / 2; settings.pdrMax = Math.max(1, heuristic); } if (line.hasOption(READ_ADVICE)) { settings.readAdvice = line.getOptionValue(READ_ADVICE); } if (line.hasOption(REDUCE_INV)) { settings.reduceInvariants = true; } if (line.hasOption(TIMEOUT)) { settings.timeout = parseNonnegativeInt(line.getOptionValue(TIMEOUT)); } if (line.hasOption(SCRATCH)) { settings.scratch = true; } if (line.hasOption(SMOOTH)) { settings.smoothCounterexamples = true; } if (line.hasOption(INTERVAL)) { settings.intervalGeneralization = true; } if (line.hasOption(SOLVER)) { settings.solver = getSolverOption(line.getOptionValue(SOLVER)); } if (line.hasOption(WRITE_ADVICE)) { settings.writeAdvice = line.getOptionValue(WRITE_ADVICE); } if (line.hasOption(XML)) { settings.xml = true; } if (line.hasOption(XML_TO_STDOUT)) { settings.xmlToStdout = true; settings.xml = true; } String[] input = line.getArgs(); if (input.length != 1) { printHelp(); System.exit(ExitCodes.INVALID_OPTIONS); } settings.filename = input[0]; return settings; } private static int parseNonnegativeInt(String text) { BigInteger bi = new BigInteger(text); if (bi.compareTo(BigInteger.ZERO) < 0) { return 0; } else if (bi.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) > 0) { return Integer.MAX_VALUE; } else { return bi.intValue(); } } private static SolverOption getSolverOption(String solver) { List<SolverOption> options = Arrays.asList(SolverOption.values()); for (SolverOption option : options) { if (solver.equals(option.toString())) { return option; } } Output.error("unknown solver: " + solver); Output.println("Valid options: " + options); System.exit(ExitCodes.INVALID_OPTIONS); return null; } private static void ensureExclusive(CommandLine line, String opt1, String opt2) { if (line.hasOption(opt1) && line.hasOption(opt2)) { Output.fatal(ExitCodes.INVALID_OPTIONS, "cannot use option -" + opt1 + " with option -" + opt2); } } private static void checkSettings(JKindSettings settings) { if (settings.solver != SolverOption.YICES) { if (settings.smoothCounterexamples) { Output.fatal(ExitCodes.INVALID_OPTIONS, "smoothing not supported with " + settings.solver); } if (settings.reduceInvariants) { Output.fatal(ExitCodes.INVALID_OPTIONS, "invariant reduction not supported with " + settings.solver); } } if (!settings.boundedModelChecking && !settings.kInduction && !settings.invariantGeneration && settings.pdrMax == 0 && settings.readAdvice == null) { Output.fatal(ExitCodes.INVALID_OPTIONS, "all proving engines disabled"); } if (!settings.boundedModelChecking && settings.kInduction) { Output.warning("k-induction requires bmc"); } } }
package org.whattf.datatype; import org.relaxng.datatype.DatatypeException; import java.util.Arrays; import com.ibm.icu.lang.UCharacter; public class KeyLabelList extends AbstractDatatype { /** * The singleton instance. */ public static final KeyLabelList THE_INSTANCE = new KeyLabelList(); private KeyLabelList() { super(); } @Override public void checkValid(CharSequence literal) throws DatatypeException { String[] keylabels = literal.toString().split("\\s+"); Arrays.sort(keylabels); for (int i = 0; i < keylabels.length; i++) { String label = keylabels[i]; if (i > 0 && label.equals(keylabels[i-1])) { throw newDatatypeException( "Duplicate key label. Each key label must be unique."); } if (label.length() == 2) { char[] chars = label.toCharArray(); if (!(UCharacter.isHighSurrogate(chars[0]) && UCharacter.isLowSurrogate(chars[1]))) { throw newDatatypeException( "Key label has multiple characters. Each key label must be a single character."); } } if (label.length() > 2) { throw newDatatypeException( "Key label has multiple characters. Each key label must be a single character."); } } } @Override public String getName() { return "key label list"; } }
package ego.gomuku.core; import ego.gomuku.entity.Point; import java.util.ArrayList; import java.util.List; class LevelProcessor { static List<Point> getExpandPoints(Analyzer data) { List<Point> result = selectSet(data); if (result.isEmpty()) { result.add(new Point(7, 7)); return result; } return result; } private static List<Point> selectSet(Analyzer data) { if (!data.getFiveAttack().isEmpty()) { return new ArrayList<>(data.getFiveAttack()); } if (!data.getFourDefence().isEmpty()) { return new ArrayList<>(data.getFourDefence()); } if (!data.getThreeDefence().isEmpty()) { return new ArrayList<Point>(data.getFourAttack()) {{ addAll(data.getThreeDefence()); }}; } List<Point> result = new ArrayList<>(); result.addAll(data.getFourAttack()); result.addAll(data.getThreeOpenAttack()); result.addAll(data.getTwoAttack()); result.addAll(data.getNotKey()); while (result.size() > 40) { result = result.subList(0, 40); } return result; } }
package com.rocketchat.core; import com.rocketchat.common.RocketChatApiException; import com.rocketchat.common.RocketChatAuthException; import com.rocketchat.common.RocketChatException; import com.rocketchat.common.RocketChatInvalidResponseException; import com.rocketchat.common.RocketChatNetworkErrorException; import com.rocketchat.common.data.model.BaseRoom; import com.rocketchat.common.data.model.ServerInfo; import com.rocketchat.common.listener.Callback; import com.rocketchat.common.listener.PaginatedCallback; import com.rocketchat.common.listener.SimpleCallback; import com.rocketchat.common.utils.Logger; import com.rocketchat.common.utils.Sort; import com.rocketchat.core.callback.LoginCallback; import com.rocketchat.core.callback.ServerInfoCallback; import com.rocketchat.core.model.Message; import com.rocketchat.core.model.Token; import com.rocketchat.core.model.attachment.Attachment; import com.rocketchat.core.provider.TokenProvider; import com.squareup.moshi.JsonAdapter; import com.squareup.moshi.Moshi; import com.squareup.moshi.Types; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import okhttp3.Call; import okhttp3.FormBody; import okhttp3.HttpUrl; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import static com.rocketchat.common.utils.Preconditions.checkNotNull; class RestImpl { private final OkHttpClient client; private final HttpUrl baseUrl; private final TokenProvider tokenProvider; private final Moshi moshi; private final Logger logger; RestImpl(OkHttpClient client, Moshi moshi, HttpUrl baseUrl, TokenProvider tokenProvider, Logger logger) { this.client = client; this.moshi = moshi; this.baseUrl = baseUrl; this.tokenProvider = tokenProvider; this.logger = logger; } void signin(String username, String password, final LoginCallback loginCallback) { checkNotNull(username, "username == null"); checkNotNull(password, "password == null"); checkNotNull(loginCallback, "loginCallback == null"); RequestBody body = new FormBody.Builder() .add("username", username) .add("password", password) .build(); HttpUrl url = requestUrl(baseUrl, "login") .build(); Request request = new Request.Builder() .url(url) .post(body) .build(); client.newCall(request).enqueue(new okhttp3.Callback() { @Override public void onFailure(Call call, IOException e) { loginCallback.onError(new RocketChatNetworkErrorException("network error", e)); } @Override public void onResponse(Call call, Response response) throws IOException { if (!response.isSuccessful()) { processCallbackError(response, loginCallback); return; } // TODO parse message and check the response type. try { JSONObject json = new JSONObject(response.body().string()); JSONObject data = json.getJSONObject("data"); String id = data.getString("userId"); String token = data.getString("authToken"); loginCallback.onLoginSuccess(new Token(id, token, null)); } catch (JSONException e) { loginCallback.onError(new RocketChatInvalidResponseException(e.getMessage(), e)); } } }); } void serverInfo(final ServerInfoCallback callback) { checkNotNull(callback, "callback == null"); HttpUrl url = baseUrl.newBuilder() .addPathSegment("api") .addPathSegment("info") .build(); Request request = new Request.Builder() .url(url) .get() .build(); client.newCall(request).enqueue(new okhttp3.Callback() { @Override public void onFailure(Call call, IOException e) { callback.onError(new RocketChatNetworkErrorException("network error", e)); } @Override public void onResponse(Call call, Response response) throws IOException { if (!response.isSuccessful()) { processCallbackError(response, callback); return; } try { JsonAdapter<ServerInfo> adapter = moshi.adapter(ServerInfo.class); ServerInfo info = adapter.fromJson(response.body().string()); callback.onServerInfo(info); } catch (IOException e) { callback.onError(new RocketChatInvalidResponseException(e.getMessage(), e)); } } }); } void pinMessage(String messageId, final SimpleCallback callback) { checkNotNull(messageId, "messageId == null"); checkNotNull(callback, "callback == null"); RequestBody body = new FormBody.Builder() .add("messageId", messageId) .build(); HttpUrl httpUrl = requestUrl(baseUrl, "chat.pinMessage") .build(); Request request = requestBuilder(httpUrl) .post(body) .build(); client.newCall(request).enqueue(new okhttp3.Callback() { @Override public void onFailure(Call call, IOException e) { callback.onError(new RocketChatNetworkErrorException("network error", e)); } @Override public void onResponse(Call call, Response response) throws IOException { if (!response.isSuccessful()) { processCallbackError(response, callback); return; } try { JSONObject json = new JSONObject(response.body().string()); System.out.println("RESPONSE: " + json.toString()); callback.onSuccess(); } catch (JSONException e) { e.printStackTrace(); } } }); } // TODO void getRoomMembers() { } // TODO void getRoomFavoriteMessages() { } void getRoomPinnedMessages(String roomId, BaseRoom.RoomType roomType, int offset, final PaginatedCallback callback) { checkNotNull(roomId,"roomId == null"); checkNotNull(roomType,"roomType == null"); checkNotNull(callback,"callback == null"); HttpUrl httpUrl = requestUrl(baseUrl, getRestApiMethodNameByRoomType(roomType, "messages")) .addQueryParameter("roomId", roomId) .addQueryParameter("offset", String.valueOf(offset)) .addQueryParameter("query", "{\"pinned\":true}") .build(); Request request = requestBuilder(httpUrl) .get() .build(); client.newCall(request).enqueue(new okhttp3.Callback() { @Override public void onFailure(Call call, IOException e) { callback.onError(new RocketChatNetworkErrorException("network error", e)); } @Override public void onResponse(Call call, Response response) throws IOException { if (!response.isSuccessful()) { processCallbackError(response, callback); return; } try { JSONObject json = new JSONObject(response.body().string()); logger.info("Response = " + json.toString()); Type type = Types.newParameterizedType(List.class, Message.class); JsonAdapter<List<Message>> adapter = moshi.adapter(type); List<Message> messageList = adapter.fromJson(json.getJSONArray("messages").toString()); callback.onSuccess(messageList, json.optInt("total")); } catch (JSONException e) { callback.onError(new RocketChatInvalidResponseException(e.getMessage(), e)); } } }); } void getRoomFiles(String roomId, BaseRoom.RoomType roomType, int offset, Attachment.SortBy sortBy, Sort sort, final PaginatedCallback callback) { checkNotNull(roomId,"roomId == null"); checkNotNull(roomType,"roomType == null"); checkNotNull(sortBy,"sortBy == null"); checkNotNull(sort,"sort == null"); checkNotNull(callback,"callback == null"); HttpUrl httpUrl = requestUrl(baseUrl, getRestApiMethodNameByRoomType(roomType, "files")) .addQueryParameter("roomId", roomId) .addQueryParameter("offset", String.valueOf(offset)) .addQueryParameter("sort", "{\"" + sortBy.getPropertyName() + "\":" + sort.getDirection() + "}") .build(); Request request = requestBuilder(httpUrl) .get() .build(); client.newCall(request).enqueue(new okhttp3.Callback() { @Override public void onFailure(Call call, IOException e) { callback.onError(new RocketChatNetworkErrorException("network error", e)); } @Override public void onResponse(Call call, Response response) throws IOException { if (!response.isSuccessful()) { processCallbackError(response, callback); return; } try { JSONObject json = new JSONObject(response.body().string()); logger.info("Response = " + json.toString()); JSONArray filesJSONArray = json.getJSONArray("files"); int length = filesJSONArray.length(); List<Attachment> attachments = new ArrayList<>(length); for (int i = 0; i < length; ++i) { attachments.add(new Attachment(filesJSONArray.getJSONObject(i), baseUrl.url().toString())); } callback.onSuccess(attachments, json.optInt("total")); } catch (JSONException e) { callback.onError(new RocketChatInvalidResponseException(e.getMessage(), e)); } } }); } /** * Returns the correspondent Rest API method accordingly with the room type. * * @param roomType The type of the room. * @param method The method. * @return A Rest API method accordingly with the room type. * @see #requestUrl(HttpUrl, String) */ private String getRestApiMethodNameByRoomType(BaseRoom.RoomType roomType, String method) { switch (roomType) { case PUBLIC: return "channels." + method; case PRIVATE: return "groups." + method; default: return "dm." + method; } } /** * Builds and returns the HttpUrl.Builder as {baseUrl}/api/v1/{method} * * @param baseUrl The base URL. * @param method The method name. * @return A HttpUrl pointing to the REST API call. */ private HttpUrl.Builder requestUrl(HttpUrl baseUrl, String method) { return baseUrl.newBuilder() .addPathSegment("api") .addPathSegment("v1") .addPathSegment(method); } /** * Builds and returns the Request.Builder with HttpUrl and header. * Note: The user token and its ID will be added to the header only if present. * * @param httpUrl The HttpUrl. * @return A Request.Builder with HttpUrl and the user token and its ID on the header (only if the tokenProvider is present). */ private Request.Builder requestBuilder(HttpUrl httpUrl) { Request.Builder builder = new Request.Builder() .url(httpUrl); if (tokenProvider != null && tokenProvider.getToken() != null) { Token token = tokenProvider.getToken(); builder.addHeader("X-Auth-Token", token.getAuthToken()) .addHeader("X-User-Id", token.getUserId()); } return builder; } private void processCallbackError(Response response, Callback callback) { try { if (response.code() == 401) { JSONObject json = new JSONObject(response.body().string()); callback.onError(new RocketChatAuthException(json.optString("message"))); } else { JSONObject json = new JSONObject(response.body().string()); String message = json.optString("error"); String errorType = json.optString("errorType"); callback.onError(new RocketChatApiException(response.code(), message, errorType)); } } catch (IOException | JSONException e) { callback.onError(new RocketChatException(e.getMessage(), e)); } } }
package org.opennms.netmgt.provision.adapters.link; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.util.Collection; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.opennms.netmgt.dao.DataLinkInterfaceDao; import org.opennms.netmgt.dao.DatabasePopulator; import org.opennms.netmgt.dao.IpInterfaceDao; import org.opennms.netmgt.dao.LinkStateDao; import org.opennms.netmgt.dao.MonitoredServiceDao; import org.opennms.netmgt.dao.NodeDao; import org.opennms.netmgt.dao.ServiceTypeDao; import org.opennms.netmgt.dao.db.JUnitTemporaryDatabase; import org.opennms.netmgt.dao.db.OpenNMSConfigurationExecutionListener; import org.opennms.netmgt.dao.db.TemporaryDatabaseExecutionListener; import org.opennms.netmgt.model.DataLinkInterface; import org.opennms.netmgt.model.OnmsIpInterface; import org.opennms.netmgt.model.OnmsLinkState; import org.opennms.netmgt.model.OnmsMonitoredService; import org.opennms.netmgt.model.OnmsNode; import org.opennms.netmgt.model.OnmsServiceType; import org.opennms.netmgt.model.OnmsLinkState.LinkState; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.test.context.support.DirtiesContextTestExecutionListener; import org.springframework.test.context.transaction.TransactionalTestExecutionListener; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; @RunWith(SpringJUnit4ClassRunner.class) @TestExecutionListeners({ OpenNMSConfigurationExecutionListener.class, TemporaryDatabaseExecutionListener.class, DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class, TransactionalTestExecutionListener.class }) @ContextConfiguration(locations={ "classpath:/META-INF/opennms/applicationContext-dao.xml", "classpath*:/META-INF/opennms/component-dao.xml", "classpath:/META-INF/opennms/applicationContext-daemon.xml", "classpath:/META-INF/opennms/mockEventIpcManager.xml", "classpath:/META-INF/opennms/applicationContext-databasePopulator.xml", "classpath:/META-INF/opennms/provisiond-extensions.xml", "classpath:/testConfigContext.xml" }) @JUnitTemporaryDatabase() public class DefaultNodeLinkServiceTest { private static final int END_POINT1_ID = 1; private static final int END_POINT2_ID = 2; private static final int END_POINT3_ID = 3; private static final String END_POINT1_LABEL = "node1"; private static final String END_POINT2_LABEL = "node2"; private static final String END_POINT3_LABEL = "node3"; public static final String NO_SUCH_NODE_LABEL = "noSuchNode"; @Autowired DatabasePopulator m_dbPopulator; @Autowired NodeDao m_nodeDao; @Autowired IpInterfaceDao m_ipInterfaceDao; @Autowired LinkStateDao m_linkStateDao; @Autowired DataLinkInterfaceDao m_dataLinkDao; @Autowired MonitoredServiceDao m_monitoredServiceDao; @Autowired JdbcTemplate m_jdbcTemplate; @Autowired NodeLinkService m_nodeLinkService; @Autowired ServiceTypeDao m_serviceTypeDao; @Autowired TransactionTemplate m_transactionTemplate; @Before public void setup(){ m_dbPopulator.populateDatabase(); } @Test public void dwoNotNull(){ assertNotNull(m_dbPopulator); assertNotNull(m_nodeDao); assertNotNull(m_jdbcTemplate); assertNotNull(m_monitoredServiceDao); } @Test public void dwoTestGetNodeLabel(){ String nodeLabel = m_nodeLinkService.getNodeLabel(END_POINT1_ID); assertNotNull(nodeLabel); assertEquals("node1", nodeLabel); } @Test public void dwoTestNodeNotThere(){ String nodeLabel = m_nodeLinkService.getNodeLabel(200); assertNull(nodeLabel); } @Test public void dwoTestGetNodeId(){ Integer nodeId = m_nodeLinkService.getNodeId(END_POINT1_LABEL); assertNotNull(nodeId); assertEquals(Integer.valueOf(1), nodeId); } @Test public void dwoTestGetNodeIdNull(){ Integer nodeId = m_nodeLinkService.getNodeId(NO_SUCH_NODE_LABEL); assertNull(nodeId); } @Test public void dwoTestCreateLink(){ Collection<DataLinkInterface> dataLinks = m_dataLinkDao.findByNodeId(END_POINT3_ID); assertEquals(0, dataLinks.size()); m_nodeLinkService.createLink(1, 3); dataLinks = m_dataLinkDao.findByNodeId(END_POINT3_ID); assertEquals(1, dataLinks.size()); } @Test public void dwoTestLinkAlreadyExists(){ Collection<DataLinkInterface> dataLinks = m_dataLinkDao.findByNodeId(END_POINT2_ID); assertEquals(1, dataLinks.size()); m_nodeLinkService.createLink(1, 2); dataLinks = m_dataLinkDao.findByNodeId(END_POINT2_ID); assertEquals(1, dataLinks.size()); } @Test public void dwoTestUpdateLinkStatus(){ Collection<DataLinkInterface> dataLinks = m_dataLinkDao.findByNodeId(END_POINT2_ID); assertEquals("A", dataLinks.iterator().next().getStatus()); int parentNodeId = END_POINT1_ID; int nodeId = END_POINT2_ID; m_nodeLinkService.updateLinkStatus(parentNodeId, nodeId, "G"); dataLinks = m_dataLinkDao.findByNodeId(END_POINT2_ID); assertEquals("G", dataLinks.iterator().next().getStatus()); } @Test public void dwoTestUpdateLinkFailedStatus(){ int parentNodeId = END_POINT1_ID; int nodeId = END_POINT2_ID; Collection<DataLinkInterface> dataLinks = m_dataLinkDao.findByNodeId(nodeId); assertEquals("A", dataLinks.iterator().next().getStatus()); m_nodeLinkService.updateLinkStatus(parentNodeId, nodeId, "B"); dataLinks = m_dataLinkDao.findByNodeId(nodeId); assertEquals("B", dataLinks.iterator().next().getStatus()); } @Test public void dwoTestUpdateLinkGoodThenFailedStatus(){ int parentNodeId = END_POINT1_ID; int nodeId = END_POINT2_ID; Collection<DataLinkInterface> dataLinks = m_dataLinkDao.findByNodeId(nodeId); assertEquals("A", dataLinks.iterator().next().getStatus()); m_nodeLinkService.updateLinkStatus(parentNodeId, nodeId, "G"); dataLinks = m_dataLinkDao.findByNodeId(nodeId); assertEquals("G", dataLinks.iterator().next().getStatus()); m_nodeLinkService.updateLinkStatus(parentNodeId, nodeId, "B"); dataLinks = m_dataLinkDao.findByNodeId(nodeId); assertEquals("B", dataLinks.iterator().next().getStatus()); } @Test public void dwoTestGetLinkContainingNodeId() { int parentNodeId = END_POINT1_ID; Collection<DataLinkInterface> datalinks = m_nodeLinkService.getLinkContainingNodeId(parentNodeId); assertEquals(3, datalinks.size()); } @Test public void dwoTestGetLinkStateForInterface() { int nodeId = END_POINT2_ID; Collection<DataLinkInterface> dlis = m_nodeLinkService.getLinkContainingNodeId(nodeId); DataLinkInterface dli = dlis.iterator().next(); assertNotNull(dli); OnmsLinkState linkState = new OnmsLinkState(); linkState.setDataLinkInterface(dli); m_linkStateDao.save(linkState); m_linkStateDao.flush(); linkState = m_nodeLinkService.getLinkStateForInterface(dli); assertNotNull("linkState was null", linkState); assertEquals(OnmsLinkState.LinkState.LINK_UP, linkState.getLinkState()); } @Test public void dwoTestSaveLinkState() { int nodeId = END_POINT2_ID; Collection<DataLinkInterface> dlis = m_nodeLinkService.getLinkContainingNodeId(nodeId); DataLinkInterface dli = dlis.iterator().next(); OnmsLinkState linkState = new OnmsLinkState(); linkState.setDataLinkInterface(dli); m_linkStateDao.save(linkState); m_linkStateDao.flush(); OnmsLinkState linkState2 = m_nodeLinkService.getLinkStateForInterface(dli); assertNotNull("linkState was null", linkState2); assertEquals(OnmsLinkState.LinkState.LINK_UP, linkState2.getLinkState()); linkState2.setLinkState(linkState2.getLinkState().LINK_NODE_DOWN); m_nodeLinkService.saveLinkState(linkState2); OnmsLinkState linkState3 = m_nodeLinkService.getLinkStateForInterface(dli); assertEquals(OnmsLinkState.LinkState.LINK_NODE_DOWN, linkState3.getLinkState()); } @Test public void dwoTestSaveAllEnumStates() { int nodeId = END_POINT2_ID; Collection<DataLinkInterface> dlis = m_nodeLinkService.getLinkContainingNodeId(nodeId); DataLinkInterface dli = dlis.iterator().next(); OnmsLinkState linkState = new OnmsLinkState(); linkState.setDataLinkInterface(dli); for(LinkState ls : LinkState.values()){ linkState.setLinkState(ls); saveLinkState(linkState); } } @Test public void dwoTestAddPrimaryServiceToNode(){ final String END_POINT_SERVICE_NAME = "EndPoint"; addPrimaryServiceToNode(END_POINT1_ID, END_POINT_SERVICE_NAME); OnmsMonitoredService service = m_monitoredServiceDao.getPrimaryService(END_POINT1_ID, "ICMP"); assertNotNull(service); assertEquals("ICMP", service.getServiceName()); service = m_monitoredServiceDao.getPrimaryService(END_POINT1_ID, END_POINT_SERVICE_NAME); assertNotNull(service); assertEquals(END_POINT_SERVICE_NAME,service.getServiceName()); } @Test public void dwoTestNodeHasEndPointService() { assertFalse(m_nodeLinkService.nodeHasEndPointService(END_POINT1_ID)); final String END_POINT_SERVICE_NAME = "EndPoint"; addPrimaryServiceToNode(END_POINT1_ID, END_POINT_SERVICE_NAME); assertTrue(m_nodeLinkService.nodeHasEndPointService(END_POINT1_ID)); } public void addPrimaryServiceToNode(final int nodeId, final String serviceName){ m_transactionTemplate.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { OnmsServiceType svcType = m_serviceTypeDao.findByName(serviceName); if(svcType == null){ svcType = new OnmsServiceType(serviceName); m_serviceTypeDao.save(svcType); } OnmsNode node = m_nodeDao.get(nodeId); OnmsIpInterface ipInterface = node.getPrimaryInterface(); OnmsMonitoredService svc = new OnmsMonitoredService(); svc.setIpInterface(ipInterface); svc.setServiceType(svcType); m_monitoredServiceDao.save(svc); return null; } }); } public void saveLinkState(final OnmsLinkState linkState){ m_transactionTemplate.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { m_linkStateDao.saveOrUpdate(linkState); return null; } }); } }
package org.xwiki.rendering.internal.macro.message; import java.util.Collections; import java.util.List; import org.xwiki.rendering.block.Block; import org.xwiki.rendering.block.MetaDataBlock; import org.xwiki.rendering.macro.MacroExecutionException; import org.xwiki.rendering.macro.box.AbstractBoxMacro; import org.xwiki.rendering.macro.box.BoxMacroParameters; import org.xwiki.rendering.macro.descriptor.DefaultContentDescriptor; import org.xwiki.rendering.transformation.MacroTransformationContext; /** * Common implementation for message macros (e.g. info, error, warning, success, etc). * * @version $Id$ * @since 2.0M3 */ public abstract class AbstractMessageMacro extends AbstractBoxMacro<BoxMacroParameters> { /** * Create and initialize the descriptor of the macro. * * @param macroName the macro name (eg "Error", "Info", etc) * @param macroDescription the macro description */ public AbstractMessageMacro(String macroName, String macroDescription) { super(macroName, macroDescription, new DefaultContentDescriptor("Content of the message", true, Block.LIST_BLOCK_TYPE), BoxMacroParameters.class); } @Override protected List<Block> parseContent(BoxMacroParameters parameters, String content, MacroTransformationContext context) throws MacroExecutionException { List<Block> macroContent = getMacroContentParser().parse(content, context, false, context.isInline()) .getChildren(); return Collections.singletonList(new MetaDataBlock(macroContent, this.getNonGeneratedContentMetaData())); } @Override protected String getClassProperty() { return super.getClassProperty() + ' ' + this.getDescriptor().getId().getId() + "message"; } }
package $package; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.RobotDrive; import edu.wpi.first.wpilibj.RobotDrive.MotorType; import edu.wpi.first.wpilibj.SampleRobot; import edu.wpi.first.wpilibj.Timer; /** * This is a demo program showing how to use Mecanum control with the RobotDrive class. */ public class Robot extends SampleRobot { RobotDrive robotDrive; Joystick stick; // Channels for the wheels final int frontLeftChannel = 2; final int rearLeftChannel = 3; final int frontRightChannel = 1; final int rearRightChannel = 0; // The channel on the driver station that the joystick is connected to final int joystickChannel = 0; public Robot() { robotDrive = new RobotDrive(frontLeftChannel, rearLeftChannel, frontRightChannel, rearRightChannel); robotDrive.setInvertedMotor(MotorType.kFrontLeft, true); // invert the left side motors robotDrive.setInvertedMotor(MotorType.kRearLeft, true); // you may need to change or remove this to match your robot robotDrive.setExpiration(0.1); stick = new Joystick(joystickChannel); } /** * Runs the motors with Mecanum drive. */ public void operatorControl() { robotDrive.setSafetyEnabled(true); while (isOperatorControl() && isEnabled()) { // Use the joystick X axis for lateral movement, Y axis for forward movement, and Z axis for rotation. // This sample does not use field-oriented drive, so the gyro input is set to zero. robotDrive.mecanumDrive_Cartesian(stick.getX(), stick.getY(), stick.getZ(), 0); Timer.delay(0.005); // wait 5ms to avoid hogging CPU cycles } } }
package org.safehaus.subutai.core.network.impl; import java.util.Set; import java.util.StringTokenizer; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.safehaus.subutai.common.command.CommandException; import org.safehaus.subutai.common.command.CommandResult; import org.safehaus.subutai.common.command.RequestBuilder; import org.safehaus.subutai.common.network.Vni; import org.safehaus.subutai.common.network.VniVlanMapping; import org.safehaus.subutai.common.peer.ContainerHost; import org.safehaus.subutai.common.peer.Host; import org.safehaus.subutai.common.peer.PeerException; import org.safehaus.subutai.common.settings.Common; import org.safehaus.subutai.common.util.NumUtil; import org.safehaus.subutai.core.network.api.ContainerInfo; import org.safehaus.subutai.core.network.api.N2NConnection; import org.safehaus.subutai.core.network.api.NetworkManager; import org.safehaus.subutai.core.network.api.NetworkManagerException; import org.safehaus.subutai.core.network.api.Tunnel; import org.safehaus.subutai.core.peer.api.ManagementHost; import org.safehaus.subutai.core.peer.api.PeerManager; import org.safehaus.subutai.core.peer.api.ResourceHost; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.Sets; /** * Implementation of Network Manager */ public class NetworkManagerImpl implements NetworkManager { private static final String LINE_DELIMITER = "\n"; private final PeerManager peerManager; protected Commands commands = new Commands(); public NetworkManagerImpl( final PeerManager peerManager ) { Preconditions.checkNotNull( peerManager ); this.peerManager = peerManager; } @Override public void setupN2NConnection( final String superNodeIp, final int superNodePort, final String interfaceName, final String communityName, final String localIp, final String keyType, final String pathToKeyFile ) throws NetworkManagerException { execute( getManagementHost(), commands.getSetupN2NConnectionCommand( superNodeIp, superNodePort, interfaceName, communityName, localIp, keyType, pathToKeyFile ) ); } @Override public void removeN2NConnection( final String interfaceName, final String communityName ) throws NetworkManagerException { execute( getManagementHost(), commands.getRemoveN2NConnectionCommand( interfaceName, communityName ) ); } @Override public void setupTunnel( final int tunnelId, final String tunnelIp ) throws NetworkManagerException { Preconditions.checkArgument( tunnelId > 0, "Tunnel id must be greater than 0" ); execute( getManagementHost(), commands.getSetupTunnelCommand( String.format( "%s%d", TUNNEL_PREFIX, tunnelId ), tunnelIp, TUNNEL_TYPE ) ); } @Override public void removeTunnel( final int tunnelId ) throws NetworkManagerException { Preconditions.checkArgument( tunnelId > 0, "Tunnel id must be greater than 0" ); execute( getManagementHost(), commands.getRemoveTunnelCommand( String.format( "%s%d", TUNNEL_PREFIX, tunnelId ) ) ); } @Override public void setupGateway( final String gatewayIp, final int vLanId ) throws NetworkManagerException { Preconditions.checkArgument( NumUtil.isIntBetween( vLanId, MIN_VLAN_ID, MAX_VLAN_ID ) ); execute( getManagementHost(), commands.getSetupGatewayCommand( gatewayIp, vLanId ) ); } @Override public void setupGatewayOnContainer( final String containerName, final String gatewayIp, final String interfaceName ) throws NetworkManagerException { execute( getContainerHost( containerName ), commands.getSetupGatewayOnContainerCommand( gatewayIp, interfaceName ) ); } @Override public void removeGateway( final int vLanId ) throws NetworkManagerException { Preconditions.checkArgument( NumUtil.isIntBetween( vLanId, MIN_VLAN_ID, MAX_VLAN_ID ) ); execute( getManagementHost(), commands.getRemoveGatewayCommand( vLanId ) ); } @Override public void removeGatewayOnContainer( final String containerName ) throws NetworkManagerException { execute( getContainerHost( containerName ), commands.getRemoveGatewayOnContainerCommand() ); } @Override public Set<Tunnel> listTunnels() throws NetworkManagerException { Set<Tunnel> tunnels = Sets.newHashSet(); CommandResult result = execute( getManagementHost(), commands.getListTunnelsCommand() ); StringTokenizer st = new StringTokenizer( result.getStdOut(), LINE_DELIMITER ); Pattern p = Pattern.compile( "(tunnel\\d+)-(.+)" ); while ( st.hasMoreTokens() ) { Matcher m = p.matcher( st.nextToken() ); if ( m.find() && m.groupCount() == 2 ) { tunnels.add( new TunnelImpl( m.group( 1 ), m.group( 2 ) ) ); } } return tunnels; } @Override public Set<N2NConnection> listN2NConnections() throws NetworkManagerException { Set<N2NConnection> connections = Sets.newHashSet(); CommandResult result = execute( getManagementHost(), commands.getListN2NConnectionsCommand() ); StringTokenizer st = new StringTokenizer( result.getStdOut(), LINE_DELIMITER ); Pattern p = Pattern.compile( "(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})\\s+(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})\\s+(\\d+)" + "\\s+(\\w+)\\s+(\\w+)" ); while ( st.hasMoreTokens() ) { Matcher m = p.matcher( st.nextToken() ); if ( m.find() && m.groupCount() == 5 ) { connections.add( new N2NConnectionImpl( m.group( 1 ), m.group( 2 ), Integer.parseInt( m.group( 3 ) ), m.group( 4 ), m.group( 5 ) ) ); } } return connections; } @Override public void setupVniVLanMapping( final int tunnelId, final long vni, final int vLanId, final UUID environmentId ) throws NetworkManagerException { Preconditions.checkArgument( tunnelId > 0, "Tunnel id must be greater than 0" ); Preconditions.checkArgument( NumUtil.isLongBetween( vni, Common.MIN_VNI_ID, Common.MAX_VNI_ID ) ); Preconditions.checkArgument( NumUtil.isIntBetween( vLanId, MIN_VLAN_ID, MAX_VLAN_ID ) ); execute( getManagementHost(), commands.getSetupVniVlanMappingCommand( String.format( "%s%d", TUNNEL_PREFIX, tunnelId ), vni, vLanId, environmentId ) ); } @Override public void removeVniVLanMapping( final int tunnelId, final long vni, final int vLanId ) throws NetworkManagerException { Preconditions.checkArgument( tunnelId > 0, "Tunnel id must be greater than 0" ); Preconditions.checkArgument( NumUtil.isLongBetween( vni, Common.MIN_VNI_ID, Common.MAX_VNI_ID ) ); Preconditions.checkArgument( NumUtil.isIntBetween( vLanId, MIN_VLAN_ID, MAX_VLAN_ID ) ); execute( getManagementHost(), commands.getRemoveVniVlanMappingCommand( String.format( "%s%d", TUNNEL_PREFIX, tunnelId ), vni, vLanId ) ); } @Override public Set<VniVlanMapping> getVniVlanMappings() throws NetworkManagerException { Set<VniVlanMapping> mappings = Sets.newHashSet(); CommandResult result = execute( getManagementHost(), commands.getListVniVlanMappingsCommand() ); Pattern p = Pattern.compile( String.format( "\\s*(%s\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*([0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3" + "}-[89ab][0-9a-f]{3}-[0-9a-f]{12})\\s*", NetworkManager.TUNNEL_PREFIX ), Pattern.CASE_INSENSITIVE ); StringTokenizer st = new StringTokenizer( result.getStdOut(), LINE_DELIMITER ); while ( st.hasMoreTokens() ) { Matcher m = p.matcher( st.nextToken() ); if ( m.find() && m.groupCount() == 4 ) { mappings.add( new VniVlanMapping( Integer.parseInt( m.group( 1 ).replace( NetworkManager.TUNNEL_PREFIX, "" ) ), Long.parseLong( m.group( 2 ) ), Integer.parseInt( m.group( 3 ) ), UUID.fromString( m.group( 4 ) ) ) ); } } return mappings; } @Override public void reserveVni( Vni vni ) throws NetworkManagerException { Preconditions.checkNotNull( vni ); execute( getManagementHost(), commands.getReserveVniCommand( vni.getVni(), vni.getEnvironmentId() ) ); } @Override public Set<Vni> listReservedVnis() throws NetworkManagerException { Set<Vni> reservedVnis = Sets.newHashSet(); CommandResult result = execute( getManagementHost(), commands.getListReservedVnisCommand() ); Pattern p = Pattern.compile( "\\s*(\\d+)\\s*,\\s*([0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})\\s*", Pattern.CASE_INSENSITIVE ); StringTokenizer st = new StringTokenizer( result.getStdOut(), LINE_DELIMITER ); while ( st.hasMoreTokens() ) { Matcher m = p.matcher( st.nextToken() ); if ( m.find() && m.groupCount() == 2 ) { reservedVnis.add( new Vni( Long.parseLong( m.group( 1 ) ), UUID.fromString( m.group( 2 ) ) ) ); } } return reservedVnis; } @Override public void setContainerIp( final String containerName, final String ip, final int netMask, final int vLanId ) throws NetworkManagerException { Preconditions.checkArgument( !Strings.isNullOrEmpty( ip ) && ip.matches( Common.IP_REGEX ) ); Preconditions.checkArgument( NumUtil.isIntBetween( vLanId, MIN_VLAN_ID, MAX_VLAN_ID ) ); execute( getResourceHost( containerName ), commands.getSetContainerIpCommand( containerName, ip, netMask, vLanId ) ); } @Override public void removeContainerIp( final String containerName ) throws NetworkManagerException { execute( getResourceHost( containerName ), commands.getRemoveContainerIpCommand( containerName ) ); } @Override public ContainerInfo getContainerIp( final String containerName ) throws NetworkManagerException { CommandResult result = execute( getResourceHost( containerName ), commands.getShowContainerIpCommand( containerName ) ); Pattern pattern = Pattern.compile( "Environment IP:\\s+(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})/(\\d+)\\s+Vlan ID:\\s+(\\d+)\\s+" ); Matcher m = pattern.matcher( result.getStdOut() ); if ( m.find() && m.groupCount() == 3 ) { return new ContainerInfoImpl( m.group( 1 ), Integer.parseInt( m.group( 2 ) ), Integer.parseInt( m.group( 3 ) ) ); } else { throw new NetworkManagerException( String.format( "Network info of %s not found", containerName ) ); } } protected ManagementHost getManagementHost() throws NetworkManagerException { try { return peerManager.getLocalPeer().getManagementHost(); } catch ( PeerException e ) { throw new NetworkManagerException( e ); } } protected ResourceHost getResourceHost( String containerName ) throws NetworkManagerException { try { ContainerHost containerHost = getContainerHost( containerName ); return peerManager.getLocalPeer().getResourceHostByContainerName( containerHost.getHostname() ); } catch ( PeerException e ) { throw new NetworkManagerException( e ); } } protected ContainerHost getContainerHost( String containerName ) throws NetworkManagerException { try { return peerManager.getLocalPeer().getContainerHostByName( containerName ); } catch ( PeerException e ) { throw new NetworkManagerException( e ); } } protected CommandResult execute( Host host, RequestBuilder requestBuilder ) throws NetworkManagerException { try { CommandResult result = host.execute( requestBuilder ); if ( !result.hasSucceeded() ) { throw new NetworkManagerException( String.format( "Command failed: %s, %s", result.getStdErr(), result.getStatus() ) ); } return result; } catch ( CommandException e ) { throw new NetworkManagerException( e ); } } @Override public void exchangeSshKeys( final Set<ContainerHost> containers ) throws NetworkManagerException { new SshManager( containers ).execute(); } @Override public void addSshKeyToAuthorizedKeys( final Set<ContainerHost> containers, final String sshKey ) throws NetworkManagerException { new SshManager( containers ).appendSshKey( sshKey ); } @Override public void replaceSshKeyInAuthorizedKeys( final Set<ContainerHost> containers, final String oldSshKey, final String newSshKey ) throws NetworkManagerException { new SshManager( containers ).replaceSshKey( oldSshKey, newSshKey ); } @Override public void removeSshKeyFromAuthorizedKeys( final Set<ContainerHost> containers, final String sshKey ) throws NetworkManagerException { new SshManager( containers ).removeSshKey( sshKey ); } @Override public void registerHosts( final Set<ContainerHost> containerHosts, final String domainName ) throws NetworkManagerException { new HostManager( containerHosts, domainName ).execute(); } }
package org.nuxeo.ecm.platform.ec.notification.email; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import java.util.Collection; import java.util.Date; import java.util.Map; import javax.mail.Message; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.naming.InitialContext; import javax.security.auth.login.LoginContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.platform.ec.notification.NotificationConstants; import org.nuxeo.ecm.platform.ec.notification.service.NotificationService; import org.nuxeo.ecm.platform.ec.notification.service.NotificationServiceHelper; import org.nuxeo.ecm.platform.rendering.RenderingResult; import org.nuxeo.ecm.platform.rendering.RenderingService; import org.nuxeo.ecm.platform.rendering.impl.DocumentRenderingContext; import org.nuxeo.runtime.api.Framework; import freemarker.template.Configuration; import freemarker.template.Template; /** * Class EmailHelper. * <p> * An email helper: * <p> * * <pre> * Hashtable mail = new Hashtable(); * mail.put(&quot;from&quot;, &quot;dion@almaer.com&quot;); * mail.put(&quot;to&quot;, &quot;dion@almaer.com&quot;); * mail.put(&quot;subject&quot;, &quot;a subject&quot;); * mail.put(&quot;body&quot;, &quot;the body&quot;); * &lt;p&gt; * EmailHelper.sendmail(mail); * </pre> * * Currently only supports one email in to address * * @author <a href="mailto:npaslaru@nuxeo.com">Narcis Paslaru</a> * @author <a href="mailto:tmartins@nuxeo.com">Thierry Martins</a> */ public class EmailHelper { private static final Log log = LogFactory.getLog(EmailHelper.class); // used for loading templates from strings private final Configuration stringCfg = new Configuration(); protected static boolean javaMailNotAvailable = false; /* Only static methods here chaps */ public EmailHelper() { } /** * Static Method: sendmail(Map mail). * * @param mail A map of the settings */ public void sendmail(Map<String, Object> mail) throws Exception { Session session = getSession(); if (javaMailNotAvailable || session==null) { log.warn("Not sending email since JavaMail is not configured"); return; } // Construct a MimeMessage MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(session.getProperty("mail.from"))); Object to = mail.get("mail.to"); if (!(to instanceof String)) { log.error("Invalid email recipient: " + to); return; } msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse( (String) to, false)); RenderingService rs = Framework.getService(RenderingService.class); DocumentRenderingContext context = new DocumentRenderingContext(); context.remove("doc"); context.putAll(mail); context.setDocument((DocumentModel) mail.get("document")); String customSubjectTemplate = (String) mail.get(NotificationConstants.SUBJECT_TEMPLATE_KEY); if (customSubjectTemplate == null) { String subjTemplate = (String) mail.get(NotificationConstants.SUBJECT_KEY); Template templ = new Template("name", new StringReader(subjTemplate), stringCfg); Writer out = new StringWriter(); templ.process(mail, out); out.flush(); msg.setSubject(out.toString(), "UTF-8"); } else { rs.registerEngine(new NotificationsRenderingEngine( customSubjectTemplate)); LoginContext lc = Framework.login(); Collection<RenderingResult> results = rs.process(context); String subjectMail = "<HTML><P>No parsing Succeded !!!</P></HTML>"; for (RenderingResult result : results) { subjectMail = (String) result.getOutcome(); } subjectMail = NotificationServiceHelper.getNotificationService().getEMailSubjectPrefix() + subjectMail; msg.setSubject(subjectMail, "UTF-8"); lc.logout(); } msg.setSentDate(new Date()); rs.registerEngine(new NotificationsRenderingEngine( (String) mail.get(NotificationConstants.TEMPLATE_KEY))); LoginContext lc = Framework.login(); Collection<RenderingResult> results = rs.process(context); String bodyMail = "<HTML><P>No parsing Succedeed !!!</P></HTML>"; for (RenderingResult result : results) { bodyMail = (String) result.getOutcome(); } lc.logout(); rs.unregisterEngine("ftl"); msg.setContent(bodyMail, "text/html; charset=utf-8"); // Send the message. Transport.send(msg); } /** * Gets the session from the JNDI. */ private static Session getSession() { Session session = null; if (javaMailNotAvailable) { return null; } // First, try to get the session from JNDI, as would be done under J2EE. try { NotificationService service = (NotificationService) Framework.getRuntime().getComponent( NotificationService.NAME); InitialContext ic = new InitialContext(); session = (Session) ic.lookup(service.getMailSessionJndiName()); } catch (Exception ex) { log.warn("Unable to find Java mail API"); javaMailNotAvailable = true; } return session; } }
package org.ossmeter.platform.communicationchannel.nntp; import java.io.Reader; import org.apache.commons.net.nntp.Article; import org.apache.commons.net.nntp.NNTPClient; import org.apache.commons.net.nntp.NewsgroupInfo; import org.ossmeter.platform.Date; import org.ossmeter.platform.delta.communicationchannel.CommunicationChannelArticle; import org.ossmeter.platform.delta.communicationchannel.CommunicationChannelDelta; import org.ossmeter.platform.delta.communicationchannel.ICommunicationChannelManager; import org.ossmeter.repository.model.cc.nntp.NntpNewsGroup; public class NntpManager implements ICommunicationChannelManager<NntpNewsGroup> { private final static int RETRIEVAL_STEP = 50; @Override public boolean appliesTo(NntpNewsGroup newsgroup) { return newsgroup instanceof NntpNewsGroup; } @Override public CommunicationChannelDelta getDelta(NntpNewsGroup newsgroup, Date date) throws Exception { NNTPClient nntpClient = NntpUtil.connectToNntpServer(newsgroup); NewsgroupInfo newsgroupInfo = NntpUtil.selectNewsgroup(nntpClient, newsgroup); int lastArticle = newsgroupInfo.getLastArticle(); // The following statement is not really needed, but I added it to speed up running, // in the date is far latter than the first day of the newsgroup. // if (Integer.parseInt(newsgroup.getLastArticleChecked())<134500) // newsgroup.setLastArticleChecked("134500"); //137500"); int lastArticleChecked = Integer.parseInt(newsgroup.getLastArticleChecked()); if (lastArticleChecked<0) lastArticleChecked = newsgroupInfo.getFirstArticle(); CommunicationChannelDelta delta = new CommunicationChannelDelta(); delta.setNewsgroup(newsgroup); int retrievalStep = RETRIEVAL_STEP; Boolean dayCompleted = false; while (!dayCompleted) { if (lastArticleChecked + retrievalStep > lastArticle) { retrievalStep = lastArticle - lastArticleChecked; dayCompleted = true; } Article[] articles; Date articleDate=date; // The following loop discards messages for days earlier than the required one. do { articles = NntpUtil.getArticleInfo(nntpClient, lastArticleChecked + 1, lastArticleChecked + retrievalStep); if (articles.length > 0) { Article lastArticleRetrieved = articles[articles.length-1]; java.util.Date javaArticleDate = NntpUtil.parseDate(lastArticleRetrieved.getDate()); articleDate = new Date(javaArticleDate); if (date.compareTo(articleDate) > 0) lastArticleChecked = lastArticleRetrieved.getArticleNumber(); } } while (date.compareTo(articleDate) > 0); for (Article article: articles) { java.util.Date javaArticleDate = NntpUtil.parseDate(article.getDate()); if (javaArticleDate!=null) { articleDate = new Date(javaArticleDate); if (date.compareTo(articleDate) < 0) { dayCompleted = true; // System.out.println("dayCompleted"); } else if (date.compareTo(articleDate) == 0) { CommunicationChannelArticle communicationChannelArticle = new CommunicationChannelArticle(); communicationChannelArticle.setArticleId(article.getArticleId()); communicationChannelArticle.setArticleNumber(article.getArticleNumber()); communicationChannelArticle.setDate(javaArticleDate); // I haven't seen any messageThreadIds on NNTP servers, yet. // communicationChannelArticle.setMessageThreadId(article.messageThreadId()); NntpNewsGroup newNewsgroup = new NntpNewsGroup(); newNewsgroup.setUrl(newsgroup.getUrl()); newNewsgroup.setAuthenticationRequired(newsgroup.getAuthenticationRequired()); newNewsgroup.setUsername(newsgroup.getUsername()); newNewsgroup.setPassword(newsgroup.getPassword()); newNewsgroup.setPort(newsgroup.getPort()); newNewsgroup.setInterval(newsgroup.getInterval()); communicationChannelArticle.setNewsgroup(newNewsgroup); communicationChannelArticle.setReferences(article.getReferences()); communicationChannelArticle.setSubject(article.getSubject()); communicationChannelArticle.setUser(article.getFrom()); communicationChannelArticle.setText( getContents(newNewsgroup, communicationChannelArticle)); delta.getArticles().add(communicationChannelArticle); lastArticleChecked = article.getArticleNumber(); // System.out.println("dayNOTCompleted"); } else { //TODO: In this case, there are unprocessed articles whose date is earlier than the date requested. // This means that the deltas of those article dates are incomplete, // i.e. the deltas did not contain all articles of those dates. } } else { // If an article has no correct date, then ignore it System.err.println("\t\tUnparsable article date: " + article.getDate()); } } } nntpClient.disconnect(); newsgroup.setLastArticleChecked(lastArticleChecked+""); System.out.println("delta ("+date.toString()+") contains:\t"+ delta.getArticles().size() + " nntp articles"); return delta; } @Override public Date getFirstDate(NntpNewsGroup newsgroup) throws Exception { NNTPClient nntpClient = NntpUtil.connectToNntpServer(newsgroup); NewsgroupInfo newsgroupInfo = NntpUtil.selectNewsgroup(nntpClient, newsgroup); int firstArticleNumber = newsgroupInfo.getFirstArticle(); Reader reader = reader = nntpClient.retrieveArticle(firstArticleNumber);; while (reader == null) { firstArticleNumber++; reader = nntpClient.retrieveArticle(firstArticleNumber); if (firstArticleNumber >= newsgroupInfo.getLastArticle()) break; } ArticleHeader articleHeader = new ArticleHeader(reader); // Article article = NntpUtil.getArticleInfo(nntpClient, articleId); nntpClient.disconnect(); // String date = article.getDate(); return new Date(NntpUtil.parseDate(articleHeader.getDate().trim())); } @Override public String getContents(NntpNewsGroup newsgroup, CommunicationChannelArticle article) throws Exception { NNTPClient nntpClient = NntpUtil.connectToNntpServer(newsgroup); NntpUtil.selectNewsgroup(nntpClient, newsgroup); String contents = NntpUtil.getArticleBody(nntpClient, article.getArticleNumber()); nntpClient.disconnect(); return contents; } }
package br.net.mirante.singular.pet.module.wicket.view.util.dispatcher; import static br.net.mirante.singular.util.wicket.util.WicketUtils.$b; import java.lang.reflect.Constructor; import org.apache.wicket.Component; import org.apache.wicket.behavior.Behavior; import org.apache.wicket.markup.head.IHeaderResponse; import org.apache.wicket.markup.head.JavaScriptReferenceHeaderItem; import org.apache.wicket.markup.head.filter.HeaderResponseContainer; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.WebPage; import org.apache.wicket.request.Request; import org.apache.wicket.request.resource.PackageResourceReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import br.net.mirante.singular.flow.core.ITaskPageStrategy; import br.net.mirante.singular.flow.core.MTask; import br.net.mirante.singular.flow.core.MTaskUserExecutable; import br.net.mirante.singular.flow.core.TaskInstance; import br.net.mirante.singular.form.wicket.enums.ViewMode; import br.net.mirante.singular.pet.module.exception.SingularServerException; import br.net.mirante.singular.pet.module.flow.PetServerTaskPageStrategy; import br.net.mirante.singular.pet.module.flow.SingularWebRef; import br.net.mirante.singular.pet.module.wicket.view.behavior.SingularJSBehavior; import br.net.mirante.singular.pet.module.wicket.view.form.AbstractFormPage; import br.net.mirante.singular.pet.module.wicket.view.template.Template; @SuppressWarnings("serial") public abstract class AbstractDispatcherPage extends WebPage { protected static final Logger logger = LoggerFactory.getLogger(AbstractDispatcherPage.class); private final WebMarkupContainer bodyContainer = new WebMarkupContainer("body"); public AbstractDispatcherPage() { this.add(bodyContainer); bodyContainer.add(new HeaderResponseContainer("scripts", "scripts")); add(new SingularJSBehavior()); AbstractFormPage.FormPageConfig config = parseParameters(getRequest()); if (config != null) { dispatch(config); } else { closeAndReloadParent(); } } @Override public void renderHead(IHeaderResponse response) { super.renderHead(response); response.render(JavaScriptReferenceHeaderItem.forReference(new PackageResourceReference(Template.class, "singular.js"))); } protected abstract AbstractFormPage.FormPageConfig parseParameters(Request request); protected void dispatch(AbstractFormPage.FormPageConfig config) { try { WebPage destination = null; SingularWebRef ref = null; TaskInstance ti = loadCurrentTaskByFormId(config.formId); if (ti != null) { MTask task = ti.getFlowTask(); if (task instanceof MTaskUserExecutable) { ITaskPageStrategy pageStrategy = ((MTaskUserExecutable) task).getExecutionPage(); if (pageStrategy instanceof PetServerTaskPageStrategy) { ref = (SingularWebRef) pageStrategy.getPageFor(ti, null); } else { logger.warn("Atividade atual possui uma estratégia de página não suportada. A página default será utilizada."); } } else if (!ViewMode.VISUALIZATION.equals(config.viewMode)) { throw new SingularServerException("Página invocada para uma atividade que não é do tipo MTaskUserExecutable"); } } if (ref == null || ref.getPageClass() == null) { Constructor c = getDefaultFormPageClass().getConstructor(AbstractFormPage.FormPageConfig.class); destination = (WebPage) c.newInstance(config); } else if (AbstractFormPage.class.isAssignableFrom(ref.getPageClass())) { Constructor c = ref.getPageClass().getConstructor(AbstractFormPage.FormPageConfig.class); destination = (WebPage) c.newInstance(config); } else { destination = ref.getPageClass().newInstance(); } configureReload(destination); setResponsePage(destination); } catch (Exception e) { closeAndReloadParent(); logger.error(e.getMessage(), e); } } protected void configureReload(WebPage destination) { destination.add(new Behavior() { @Override public void renderHead(Component component, IHeaderResponse response) { response.render(JavaScriptReferenceHeaderItem.forReference(new PackageResourceReference(Template.class, "singular.js"))); } }); destination.add($b.onReadyScript(() -> " Singular.atualizarContentWorklist(); ")); } private void closeAndReloadParent() { add($b.onReadyScript(() -> " Singular.atualizarContentWorklist(); " + " window.close(); ")); } protected abstract TaskInstance loadCurrentTaskByFormId(String formID); protected abstract Class<? extends AbstractFormPage> getDefaultFormPageClass(); }
package org.apereo.cas.oidc.token; import org.apereo.cas.services.OidcRegisteredService; import org.apereo.cas.support.oauth.services.OAuthRegisteredService; import org.apereo.cas.ticket.BaseOidcTokenSigningAndEncryptionService; import com.github.benmanes.caffeine.cache.LoadingCache; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import lombok.val; import org.jose4j.jwk.JsonWebKey; import org.jose4j.jwk.PublicJsonWebKey; import org.jose4j.jwk.RsaJsonWebKey; import org.jose4j.jws.JsonWebSignature; import org.jose4j.jwt.JwtClaims; import java.util.Optional; /** * This is {@link BaseOidcJsonWebKeyTokenSigningAndEncryptionService}. * * @author Misagh Moayyed * @since 6.1.0 */ @Slf4j public abstract class BaseOidcJsonWebKeyTokenSigningAndEncryptionService extends BaseOidcTokenSigningAndEncryptionService { /** * The default keystore for OIDC tokens. */ protected final LoadingCache<String, Optional<RsaJsonWebKey>> defaultJsonWebKeystoreCache; /** * The service keystore for OIDC tokens. */ protected final LoadingCache<OidcRegisteredService, Optional<RsaJsonWebKey>> serviceJsonWebKeystoreCache; public BaseOidcJsonWebKeyTokenSigningAndEncryptionService(final LoadingCache<String, Optional<RsaJsonWebKey>> defaultJsonWebKeystoreCache, final LoadingCache<OidcRegisteredService, Optional<RsaJsonWebKey>> serviceJsonWebKeystoreCache, final String issuer) { super(issuer); this.defaultJsonWebKeystoreCache = defaultJsonWebKeystoreCache; this.serviceJsonWebKeystoreCache = serviceJsonWebKeystoreCache; } @Override @SneakyThrows public String encode(final OAuthRegisteredService service, final JwtClaims claims) { val svc = (OidcRegisteredService) service; LOGGER.debug("Attempting to produce token generated for service [{}]", svc); val jws = createJsonWebSignature(claims); LOGGER.debug("Generated claims to put into token are [{}]", claims.toJson()); var innerJwt = shouldSignTokenFor(svc) ? signToken(svc, jws) : jws.getCompactSerialization(); if (shouldEncryptTokenFor(svc)) { innerJwt = encryptToken(svc, jws, innerJwt); } return innerJwt; } /** * Encrypt token. * * @param svc the svc * @param jws the jws * @param innerJwt the inner jwt * @return the string */ protected abstract String encryptToken(OidcRegisteredService svc, JsonWebSignature jws, String innerJwt); /** * Should sign token for service? * * @param svc the svc * @return the boolean */ protected boolean shouldSignTokenFor(final OidcRegisteredService svc) { return false; } /** * Should encrypt token for service? * * @param svc the svc * @return the boolean */ protected boolean shouldEncryptTokenFor(final OidcRegisteredService svc) { return false; } @Override protected PublicJsonWebKey getJsonWebKeySigningKey() { val jwks = defaultJsonWebKeystoreCache.get(getIssuer()); if (jwks.isEmpty()) { throw new IllegalArgumentException("No signing key could be found for issuer " + getIssuer()); } return jwks.get(); } /** * Sign token. * * @param svc the svc * @param jws the jws * @return the string * @throws Exception the exception */ protected String signToken(final OidcRegisteredService svc, final JsonWebSignature jws) throws Exception { LOGGER.debug("Fetching JSON web key to sign the token for : [{}]", svc.getClientId()); val jsonWebKey = getJsonWebKeySigningKey(); LOGGER.debug("Found JSON web key to sign the token: [{}]", jsonWebKey); if (jsonWebKey.getPrivateKey() == null) { throw new IllegalArgumentException("JSON web key used to sign the token has no associated private key"); } configureJsonWebSignatureForTokenSigning(svc, jws, jsonWebKey); return jws.getCompactSerialization(); } /** * Gets json web key for encryption. * * @param svc the svc * @return the json web key for encryption */ protected JsonWebKey getJsonWebKeyForEncryption(final OidcRegisteredService svc) { LOGGER.debug("Service [{}] is set to encrypt tokens", svc); val jwks = this.serviceJsonWebKeystoreCache.get(svc); if (jwks.isEmpty()) { throw new IllegalArgumentException("Service " + svc.getServiceId() + " with client id " + svc.getClientId() + " is configured to encrypt tokens, yet no JSON web key is available"); } val jsonWebKey = jwks.get(); LOGGER.debug("Found JSON web key to encrypt the token: [{}]", jsonWebKey); if (jsonWebKey.getPublicKey() == null) { throw new IllegalArgumentException("JSON web key used to sign the token has no associated public key"); } return jsonWebKey; } }
import java.awt.BorderLayout; import java.awt.Button; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.EventObject; import javax.print.attribute.standard.JobHoldUntil; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JColorChooser; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.event.CellEditorListener; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; import javafx.scene.layout.Border; public class RightPanel extends JPanel { static int indexCount = 0; public class OptionEditor implements TableCellEditor { private DrawManager dm; private boolean isEditable; private JFrame frame; private JDialog dialog; private JPanel options_value; private JPanel expression_options; private JPanel particle_options; private JTextField function; private Color userColor; private JButton color_button; private JCheckBox checkVisible; private JCheckBox showParticle; private JButton removeFunction; public OptionEditor(){ isEditable = true; } public OptionEditor(DrawManager dm) { this(); this.dm = dm; } public OptionEditor(boolean isEditable) { this.isEditable = isEditable; } @Override public void addCellEditorListener(CellEditorListener l) { } @Override public void cancelCellEditing() { } @Override public Object getCellEditorValue() { return null; } @Override public boolean isCellEditable(EventObject anEvent) { // TODO Auto-generated method stub return isEditable; } @Override public void removeCellEditorListener(CellEditorListener l) { } @Override public boolean shouldSelectCell(EventObject anEvent) { return true; } @Override public boolean stopCellEditing() { return true; } @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { int index = new Integer(table.getModel() .getValueAt(row, column-2).toString())-1; frame = new JFrame(); dialog = new JDialog(frame, true); options_value = new JPanel(); expression_options = new JPanel(); grid_options = new JPanel(); particle_options = new JPanel(); userColor = null; function = new JTextField(25); color_button = new JButton("change line color"); checkVisible = new JCheckBox("Visible", true); showParticle = new JCheckBox("show particles", true); removeFunction = new JButton("remove function"); // set up size, location and title of the dialog box dialog.setLocation(100, 100); dialog.setPreferredSize(new Dimension(500, 550)); dialog.setResizable(false); dialog.setTitle("Options for " + table.getModel().getValueAt(row, column-1)); function.setText(table.getModel().getValueAt(row, column-1).toString()); checkVisible.setSelected(dm.getFunction(index).getVisible()); // incrementSize.setText(dm.); // event handlers color_button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { int index = new Integer((table.getModel() .getValueAt(row, column-2)).toString())-1; dm.getFunction(index) .setColor(JColorChooser .showDialog(dialog, "Choose a color", userColor)); } }); showParticle.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int index = new Integer((table.getModel() .getValueAt(row, column-2)).toString())-1; dm.getFunction(index).showParticles(showParticle.isSelected()); } }); checkVisible.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub int index = new Integer((table.getModel() .getValueAt(row, column-2)).toString())-1; Function f = dm.getFunction(index); boolean visible = checkVisible.isSelected(); f.setVisible(visible); } }); function.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String expression = function.getText(); table.getModel() .setValueAt(expression, row, column-1); int index = new Integer((table.getModel() .getValueAt(row, column-2)).toString())-1; Function f = dm.getFunction(index); f.setExpression(expression); } }); removeFunction.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub int index = new Integer((table.getModel() .getValueAt(row, column-2)).toString())-1; dm.removeFunction(index); ((DefaultTableModel)table.getModel()).removeRow(index); indexCount dialog.setVisible(false); } }); options_value.setLayout(new GridLayout(2, 0)); expression_options.setLayout(new GridLayout(0, 1)); particle_options.setLayout(new GridLayout(0, 1)); expression_options.add(new JLabel("Function: ")); expression_options.add(function); expression_options.add(color_button); expression_options.add(checkVisible); expression_options.add(removeFunction); particle_options.add(showParticle); options_value.add(new JLabel("Function options: " )); options_value.add(expression_options); expression_options.add(new JSeparator()); options_value.add(new JLabel("Particle options: " )); options_value.add(particle_options); dialog.add(options_value); dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); dialog.pack(); dialog.setVisible(true); return null; } } private JPanel functionInputPanel; private JPanel tableHolderPanel; private DefaultTableModel dtm; private JButton add_function; protected JTextField lineFunction; protected JTable table; // grid optins private JPanel grid_options; private JButton showGridColorOptions; private JButton showGridBGColorOptions; private JCheckBox showGrid; private JCheckBox showCursorCoords; private JCheckBox showNumbers; private JColorChooser gridColor; private JTextField tickHSize; private JTextField tickVSize; private JTextField tickHScale; private JTextField tickVScale; public RightPanel(DrawManager _drawManager) { final DrawManager drawManager = _drawManager; JScrollPane tablePane = new JScrollPane(table); JFrame tableFrame = new JFrame(); grid_options = new JPanel(); showGrid = new JCheckBox("show grid", true); showCursorCoords = new JCheckBox("show cursor coords", true); showNumbers = new JCheckBox("show numbers", true); showGridColorOptions = new JButton("change grid color"); showGridBGColorOptions = new JButton("change grid background color"); tickHSize = new JTextField(); tickVSize = new JTextField(); tickHScale = new JTextField(); tickVScale = new JTextField(); gridColor = new JColorChooser(); functionInputPanel = new JPanel(); tableHolderPanel = new JPanel(); tickHSize.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { drawManager.setTickH((new Double(tickHSize.getText()))); } catch (NumberFormatException e1) { tickHSize.setText(""); JOptionPane.showConfirmDialog(null, "Please enter a decimal value!", "Wrong input", JOptionPane.OK_CANCEL_OPTION); } } }); tickVSize.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { drawManager.setTickV((new Double(tickVSize.getText()))); } catch ( NumberFormatException e1 ) { tickVSize.setText(""); JOptionPane.showConfirmDialog(null, "Please enter a decimal value!", "Wrong input", JOptionPane.OK_CANCEL_OPTION); } } }); dtm = new DefaultTableModel(new Object[] { "Equation number", "Equation", "Options" }, 0); add_function = new JButton("Add"); lineFunction = new JTextField(15); lineFunction.setEnabled(true); table = new JTable(null, new String[] { "Equation number", "Equation", "Options" }); table.setModel(dtm); dtm.setColumnIdentifiers(new Object[] { "INDEX", "EXPRESSION", "OPTION" }); // add event handlers here add_function.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if ( lineFunction.getText().length() <= 0 ) return; try { drawManager.addFunction(new Function(lineFunction.getText(), new Color(0,0,0), drawManager)); addRow(lineFunction.getText(), dtm); table.updateUI(); } catch (Exception e1) { // TODO Auto-generated catch block JOptionPane.showConfirmDialog(null, "The input for the function is wrong! " + "Expected input is x*x or x, no white space and * for carrot symbol."); } } }); showGrid.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { drawManager.showGrid(showGrid.isSelected()); } }); showGridColorOptions.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub drawManager.setGridColor(JColorChooser .showDialog(grid_options, "Choose a color", new Color(0, 0, 0))); } }); showGridBGColorOptions.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub drawManager.setBackground(JColorChooser .showDialog(grid_options, "Choose a color", drawManager.getBackground())); } }); showNumbers.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub drawManager.showNumbers(showNumbers.isSelected()); } }); showCursorCoords.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { drawManager.showCursorCoords(showCursorCoords.isSelected()); } }); tickHScale.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub try { drawManager.setScaleH(new Double(tickHScale.getText())); } catch (NumberFormatException e1) { tickHScale.setText(""); JOptionPane.showConfirmDialog(null, "Please enter a decimal value!", "Wrong input", JOptionPane.OK_CANCEL_OPTION); } } }); tickVScale.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub try { drawManager.setScaleV(new Double(tickVScale.getText())); } catch (NumberFormatException e1) { tickVScale.setText(""); JOptionPane.showConfirmDialog(null, "Please enter a decimal value!", "Wrong input", JOptionPane.OK_CANCEL_OPTION); } } }); functionInputPanel.add(new JLabel("f(x)="), BorderLayout.PAGE_START); functionInputPanel.add(lineFunction, BorderLayout.NORTH); functionInputPanel.add(add_function, BorderLayout.NORTH); table.getColumn("INDEX").setCellEditor(new OptionEditor(false)); table.getColumn("EXPRESSION").setCellEditor(new OptionEditor(false)); table.getColumn("OPTION").setCellEditor(new OptionEditor(drawManager)); // create a table frame with the headers on top and the table on the center tableHolderPanel.setLayout(new BorderLayout()); tableHolderPanel.add(table.getTableHeader(), BorderLayout.NORTH); tableHolderPanel.add(table, BorderLayout.CENTER); grid_options.setLayout(new GridLayout(0, 1)); grid_options.add(new JLabel("H Tick Value")); grid_options.add(tickHSize); grid_options.add(new JLabel("V Tick Value")); grid_options.add(tickVSize); grid_options.add(new JLabel("V Scale Value")); grid_options.add(tickHScale); grid_options.add(new JLabel("H Scale Value")); grid_options.add(tickVScale); grid_options.add(showCursorCoords); grid_options.add(showNumbers); grid_options.add(showGrid); grid_options.add(showGridColorOptions); grid_options.add(showGridBGColorOptions); add(grid_options); add(functionInputPanel); add(tableHolderPanel); setPreferredSize(new Dimension(340,1000)); } public static void addRow(String s, DefaultTableModel dtm) { dtm.addRow(new Object[] { ++indexCount, s, "Edit" }); } }
package io.spine.server.delivery; /** * A mixin for the state of the {@linkplain CatchUpProcess catch-up processes}. */ public interface CatchUpMixin { }
package com.sinnerschrader.smaller; import java.io.File; import org.apache.commons.io.FileUtils; import org.junit.Ignore; import org.junit.Test; import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.*; /** * @author marwol */ public class ServerTest extends AbstractBaseTest { /** * @throws Exception */ @Test public void testCoffeeScript() throws Exception { runToolChain("coffeeScript", new ToolChainCallback() { public void test(File directory) throws Exception { String basicMin = FileUtils.readFileToString(new File(directory, "script.js")); assertThat(basicMin, is("(function() {\n var square;\n\n square = function(x) {\n return x * x;\n };\n\n}).call(this);\n")); } }); } /** * @throws Exception */ @Test public void testClosure() throws Exception { runToolChain("closure", new ToolChainCallback() { public void test(File directory) throws Exception { String basicMin = FileUtils.readFileToString(new File(directory, "basic-min.js")); assertThat(basicMin, is("(function(){alert(\"Test1\")})()(function(){alert(\"Test 2\")})();")); } }); } /** * @throws Exception */ @Test public void testUglifyJs() throws Exception { runToolChain("uglify", new ToolChainCallback() { public void test(File directory) throws Exception { String basicMin = FileUtils.readFileToString(new File(directory, "basic-min.js")); assertThat(basicMin, is("(function(){alert(\"Test1\")})()(function(){var aLongVariableName=\"Test 2\";alert(aLongVariableName)})()")); } }); } /** * @throws Exception */ @Test public void testClosureUglify() throws Exception { runToolChain("closure-uglify", new ToolChainCallback() { public void test(File directory) throws Exception { String basicMin = FileUtils.readFileToString(new File(directory, "basic-min.js")); assertThat(basicMin, is("(function(){alert(\"Test1\")})()(function(){alert(\"Test 2\")})()")); } }); } /** * @throws Exception */ @Test public void testLessJs() throws Exception { runToolChain("lessjs", new ToolChainCallback() { public void test(File directory) throws Exception { String css = FileUtils.readFileToString(new File(directory, "style.css")); assertThat(css, is("#header {\n color: #4d926f;\n}\nh2 {\n color: #4d926f;\n}\n.background {\n background: url('some/where.png');\n}\n")); } }); } /** * @throws Exception */ @Test public void testLessJsIncludes() throws Exception { runToolChain("lessjs-includes", new ToolChainCallback() { public void test(File directory) throws Exception { String css = FileUtils.readFileToString(new File(directory, "style.css")); assertThat(css, is("#header {\n color: #4d926f;\n}\nh2 {\n color: #4d926f;\n}\n.background {\n background: url('../some/where.png');\n}\n")); } }); } /** * @throws Exception */ @Test @Ignore("Currently sass does not work as expected") public void testSass() throws Exception { runToolChain("sass.zip", new ToolChainCallback() { public void test(File directory) throws Exception { String css = FileUtils.readFileToString(new File(directory, "style.css")); assertThat(css, is("")); } }); } /** * @throws Exception */ @Test public void testAny() throws Exception { runToolChain("any", new ToolChainCallback() { public void test(File directory) throws Exception { String basicMin = FileUtils.readFileToString(new File(directory, "basic-min.js")); assertThat(basicMin, is("(function(){alert(\"Test1\")})()(function(){alert(\"Test 2\")})()")); String css = FileUtils.readFileToString(new File(directory, "style.css")); assertThat(css, is("#header{color:#4d926f}h2{color:#4d926f;background-image:url(data:image/gif;base64,R0lGODlhZABkAP" + "AAAERERP///ywAAAAAZABkAEAI/wABCBxIsKDBgwgTKlzIsKHDhxAjSpxIsaLFixgzatzIMYBHjxxDPvwI0iHJkyhLJkx5EiLLlAZfs" + "lxJ0uTHkTULtrS402XOhT1FHkSJMKhPmUVlvhyqFKbCpkKjSp1KtarVq1izat3KtavXr2DDihVrdGzEsgzRJv3J9GZbt0DXqsQJ92l" + "TqHKXAmVrs65dvlTRqjVLuLDhw4gTK17MuLHjx5AjS55M" + "ubLlwY8x57UsUDPBu4A7g/arc7Rf0wFokt6cNrTnvathz1WN" + "WjDRia9Lx9Y9O6RS2qnPhn4bHKvt3X9751Wuu23r4bmXIwcAWjbevrc5a9/Ovbv37+DDi7wfT768+fPo06tfz769+/fw48ufT19r9MT3RU9vnJ/6c" + "Mj99feZUxIhZR1d1UmnV3IJDoRaTKYR1xuBEKrF14OsNeTZccwhWJyH2H3IYIUd" + "hljgfwPu5yBg2eGGYoYM1qbcbyAKp6KMLZJoIIwmPldiRxSm+CNxGgpYUY76Daljj8a59iKRIYr41FA18iZlkTRauRqS/jk5" + "2F0+Bilkg1peF6ORNgY4U31stunmm3DGKeecdNZp55145plVQAA7)}")); } }); } /** * @throws Exception */ @Test public void testCssEmbed() throws Exception { runToolChain("cssembed", new ToolChainCallback() { public void test(File directory) throws Exception { String css = FileUtils.readFileToString(new File(directory, "css/style-base64.css")); assertThat(css, is(".background {\n background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAA" + "ABaElEQVR42u3aQRKCMAwAQB7n/7+EVx1HbZsEStlcldAsUJrq9hDNsSGABQsWLFiwEMCCBQsWLFgIYMGCBQsWLASwYMGCBQsWAliwYMGCBQtB" + "CGt/j1UrHygTFixYsGDBgnUE1v4lKnK2Zw5h7f0RLGmMLDjCSJlVWOnuYyP8zDwdVkpVKTlnx4o8Dr1YLV8uwUqZ4IP3S1ba1wPnfRsWvZUqVj" + "MnYw1ffFiZBy6OlTvu1bBKZ7rc1f90WJGILx3ujpXSD94Iq/0ssLpPtOYEX7RR03WTro8V2TW7NVbvImOuOWtyr6u2O6fsr8O6LNY8T+JxWEd6" + "/SisGqvlFFvpZsvAenrg0+HBl2DFO97g5S1qthP24NsTVbQ+uQlTurT/WLnNxIS/rQ2UuUVyJXbX6Y16YpvZgXVK41Z3/SLhD7iwYMGCBUvAgg" + "ULFixYAhYsWLBgwRKwYMGCBQuWgAULFixYsAQsWDXxBFVy4xyOC7MdAAAAAElFTkSuQmCC);\n}\n")); } }); } /** * @throws Exception */ @Test public void testOutputOnly() throws Exception { runToolChain("out-only", new ToolChainCallback() { public void test(File directory) throws Exception { assertThat(directory.list().length, is(2)); assertThat(new File(directory, "basic-min.js").exists(), is(true)); assertThat(new File(directory, "style.css").exists(), is(true)); } }); } /** * @throws Exception */ @Test @Ignore public void testClosureError() throws Exception { runToolChain("closure-error", new ToolChainCallback() { public void test(File directory) throws Exception { String basicMin = FileUtils.readFileToString(new File(directory, "basic-min.js")); assertThat(basicMin, is("(function(){alert(\"Test1\")})()(function(){alert(\"Test 2\")})();")); } }); } /** * @throws Exception */ @Test public void testUnicodeEscape() throws Exception { runToolChain("unicode-escape", new ToolChainCallback() { public void test(File directory) throws Exception { String basicMin = FileUtils.readFileToString(new File(directory, "basic-min.js")); System.out.println(basicMin); System.out .println("var stringEscapes={\"\\\\\":\"\\\\\",\"'\":\"'\",\"\\n\":\"n\",\"\\r\":\"r\",\"\t\":\"t\",\"\\u2028\":\"u2028\",\"\\u2029\":\"u2029\"}"); assertThat(basicMin, is("var stringEscapes={\"\\\\\":\"\\\\\",\"'\":\"'\",\"\\n\":\"n\",\"\\r\":\"r\",\"\t\":\"t\",\"\\u2028\":\"u2028\",\"\\u2029\":\"u2029\"}")); } }); } }
package com.pragmaticobjects.oo.atom.codegen.bytebuddy.bt; import com.pragmaticobjects.oo.atom.tests.AssertAssertionFails; import com.pragmaticobjects.oo.atom.tests.AssertAssertionPasses; import com.pragmaticobjects.oo.atom.tests.TestCase; import com.pragmaticobjects.oo.atom.tests.TestsSuite; /** * Tests suite for {@link AssertClassToHaveCertainMethodsAfterBuilderTransition} * @author Kapralov Sergey */ public class AssertClassToHaveCertainMethodsAfterBuilderTransitionTest extends TestsSuite { public AssertClassToHaveCertainMethodsAfterBuilderTransitionTest() { super( new TestCase( "positive outcome", new AssertAssertionPasses( new AssertClassToHaveCertainMethodsAfterBuilderTransition( new BtNop(), Foo.class, "bar" ) ) ), new TestCase( "negative outcome", new AssertAssertionFails( new AssertClassToHaveCertainMethodsAfterBuilderTransition( new BtNop(), Foo.class, "baz" ) ) ), new TestCase( "assertion must match all methods in a resulting class or fail", new AssertAssertionFails( new AssertClassToHaveCertainMethodsAfterBuilderTransition( new BtNop(), Foo.class, "bar", "baz" ) ) ) ); } private static class Foo { public void bar() {} } }
/* * Component to edit requirements. */ package net.sourceforge.javydreamercsw.client.ui.components.requirement.edit; import com.validation.manager.core.DataBaseManager; import com.validation.manager.core.db.Requirement; import com.validation.manager.core.db.RequirementSpecNode; import com.validation.manager.core.db.RequirementStatus; import com.validation.manager.core.db.RequirementType; import com.validation.manager.core.db.controller.RequirementStatusJpaController; import com.validation.manager.core.db.controller.RequirementTypeJpaController; import com.validation.manager.core.server.core.RequirementServer; import java.awt.Component; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionAdapter; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.ResourceBundle; import java.util.logging.Logger; import javax.swing.DefaultComboBoxModel; import javax.swing.DefaultListModel; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.ListCellRenderer; import javax.swing.ListModel; import net.sourceforge.javydreamercsw.client.ui.nodes.actions.RequirementSelectionDialog; import org.netbeans.api.settings.ConvertAsProperties; import org.openide.explorer.ExplorerManager; import org.openide.explorer.view.OutlineView; import org.openide.util.Exceptions; import org.openide.util.Lookup; import org.openide.util.LookupEvent; import org.openide.util.LookupListener; import org.openide.util.NbBundle.Messages; import org.openide.util.Utilities; import org.openide.windows.TopComponent; /** * Top component which displays something. */ @ConvertAsProperties( dtd = "-//net.sourceforge.javydreamercsw.client.ui.nodes.actions//EditRequirementWindow//EN", autostore = false ) @TopComponent.Description( preferredID = "EditRequirementWindowTopComponent", iconBase = "com/validation/manager/resources/icons/Papermart/Document.png", persistenceType = TopComponent.PERSISTENCE_NEVER ) @TopComponent.Registration(mode = "editor", openAtStartup = false) @TopComponent.OpenActionRegistration( displayName = "#CTL_EditRequirementWindowAction", preferredID = "EditRequirementWindowTopComponent" ) @Messages({ "CTL_EditRequirementWindowAction=Edit Requirement Window", "CTL_EditRequirementWindowTopComponent=Edit Requirement Window", "HINT_EditRequirementWindowTopComponent=This is a Edit Requirement Window" }) public final class EditRequirementWindowTopComponent extends TopComponent implements LookupListener { private final Lookup.Result<Requirement> result = Utilities.actionsGlobalContext().lookupResult(Requirement.class); private final List<Requirement> linkedRequirements = new ArrayList<>(); private final List<RequirementStatus> statuses = new ArrayList<>(); private final List<RequirementType> types = new ArrayList<>(); private boolean edit = false; private Requirement requirement; private static final Logger LOG = Logger.getLogger(EditRequirementWindowTopComponent.class.getSimpleName()); private static final ResourceBundle rb = ResourceBundle.getBundle("com.validation.manager.resources.VMMessages"); private final CoveringStepFactory testCaseFactory; private final ExplorerManager em = new ExplorerManager(); public EditRequirementWindowTopComponent() { initComponents(); result.addLookupListener((EditRequirementWindowTopComponent) this); setName(Bundle.CTL_EditRequirementWindowTopComponent()); setToolTipText(Bundle.HINT_EditRequirementWindowTopComponent()); testCaseFactory = new CoveringStepFactory(); } /** * @param requirement the requirement to set */ public void setRequirement(Requirement requirement) { this.requirement = requirement; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { chooseRequirements = new javax.swing.JButton(); status = new javax.swing.JComboBox(); jScrollPane1 = new javax.swing.JScrollPane(); description = new javax.swing.JTextArea(); jLabel3 = new javax.swing.JLabel(); cancel = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); uniqueID = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jScrollPane3 = new javax.swing.JScrollPane(); requirements = new javax.swing.JList(); jLabel4 = new javax.swing.JLabel(); jScrollPane2 = new javax.swing.JScrollPane(); notes = new javax.swing.JTextArea(); type = new javax.swing.JComboBox(); save = new javax.swing.JButton(); stepsPane = new OutlineView(); jLabel7 = new javax.swing.JLabel(); org.openide.awt.Mnemonics.setLocalizedText(chooseRequirements, org.openide.util.NbBundle.getMessage(EditRequirementWindowTopComponent.class, "EditRequirementWindowTopComponent.chooseRequirements.text")); // NOI18N chooseRequirements.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { chooseRequirementsActionPerformed(evt); } }); status.setAutoscrolls(true); status.setDoubleBuffered(true); description.setColumns(20); description.setRows(5); jScrollPane1.setViewportView(description); org.openide.awt.Mnemonics.setLocalizedText(jLabel3, org.openide.util.NbBundle.getMessage(EditRequirementWindowTopComponent.class, "EditRequirementWindowTopComponent.jLabel3.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(cancel, org.openide.util.NbBundle.getMessage(EditRequirementWindowTopComponent.class, "EditRequirementWindowTopComponent.cancel.text")); // NOI18N cancel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelActionPerformed(evt); } }); org.openide.awt.Mnemonics.setLocalizedText(jLabel2, org.openide.util.NbBundle.getMessage(EditRequirementWindowTopComponent.class, "EditRequirementWindowTopComponent.jLabel2.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(jLabel6, org.openide.util.NbBundle.getMessage(EditRequirementWindowTopComponent.class, "EditRequirementWindowTopComponent.jLabel6.text")); // NOI18N uniqueID.setText(org.openide.util.NbBundle.getMessage(EditRequirementWindowTopComponent.class, "EditRequirementWindowTopComponent.uniqueID.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(EditRequirementWindowTopComponent.class, "EditRequirementWindowTopComponent.jLabel1.text")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(jLabel5, org.openide.util.NbBundle.getMessage(EditRequirementWindowTopComponent.class, "EditRequirementWindowTopComponent.jLabel5.text")); // NOI18N jScrollPane3.setViewportView(requirements); org.openide.awt.Mnemonics.setLocalizedText(jLabel4, org.openide.util.NbBundle.getMessage(EditRequirementWindowTopComponent.class, "EditRequirementWindowTopComponent.jLabel4.text")); // NOI18N notes.setColumns(20); notes.setRows(5); jScrollPane2.setViewportView(notes); org.openide.awt.Mnemonics.setLocalizedText(save, org.openide.util.NbBundle.getMessage(EditRequirementWindowTopComponent.class, "EditRequirementWindowTopComponent.save.text")); // NOI18N save.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { saveActionPerformed(evt); } }); org.openide.awt.Mnemonics.setLocalizedText(jLabel7, org.openide.util.NbBundle.getMessage(EditRequirementWindowTopComponent.class, "EditRequirementWindowTopComponent.jLabel7.text")); // NOI18N javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(save) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(cancel)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel2) .addComponent(jLabel1) .addComponent(jLabel3) .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel5) .addComponent(jLabel6) .addComponent(chooseRequirements) .addComponent(jLabel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 487, Short.MAX_VALUE) .addComponent(jScrollPane2) .addComponent(uniqueID) .addComponent(status, javax.swing.GroupLayout.Alignment.TRAILING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(type, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(stepsPane)))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap(37, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(uniqueID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(5, 5, 5) .addComponent(jLabel3)) .addGroup(layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(stepsPane, javax.swing.GroupLayout.PREFERRED_SIZE, 184, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel7)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel5) .addComponent(status, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel6) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel4)) .addComponent(type, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(9, 9, 9) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(chooseRequirements)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(cancel) .addComponent(save)) .addContainerGap()) ); }// </editor-fold>//GEN-END:initComponents private void chooseRequirementsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chooseRequirementsActionPerformed /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { final RequirementSelectionDialog dialog = new RequirementSelectionDialog(new javax.swing.JFrame(), true, linkedRequirements); dialog.setLocationRelativeTo(null); dialog.setVisible(true); //Wait for the dialog to be finished while (dialog.isVisible()) { try { Thread.sleep(100); } catch (InterruptedException ex) { Exceptions.printStackTrace(ex); } } linkedRequirements.clear(); //Clear the model to catch any removals ((DefaultListModel) requirements.getModel()).removeAllElements(); //Add the ones selected on the selection dialog. for (Requirement req : dialog.getRequirements()) { ((DefaultListModel) requirements.getModel()).addElement(req); } } }); }//GEN-LAST:event_chooseRequirementsActionPerformed private void cancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelActionPerformed close(); }//GEN-LAST:event_cancelActionPerformed private void saveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveActionPerformed if (description.getText().trim().isEmpty()) { JOptionPane.showMessageDialog(this, "Please enter a valid description", "Invalid Value", JOptionPane.WARNING_MESSAGE); } else if (uniqueID.getText().trim().isEmpty()) { JOptionPane.showMessageDialog(this, "Please enter a valid description", "Invalid Value", JOptionPane.WARNING_MESSAGE); } else if (type.getSelectedIndex() < 0) { JOptionPane.showMessageDialog(this, "Please select a valid Requirement Type", "Invalid Value", JOptionPane.WARNING_MESSAGE); } else if (status.getSelectedIndex() < 0) { JOptionPane.showMessageDialog(this, "Please select a valid Requirement Status", "Invalid Value", JOptionPane.WARNING_MESSAGE); } else { //Process RequirementServer req; if (edit) { if (requirement == null) { req = new RequirementServer(Utilities.actionsGlobalContext() .lookup(Requirement.class)); } else { req = new RequirementServer(requirement); } req.setUniqueId(uniqueID.getText().trim()); } else { RequirementSpecNode rsn = Utilities.actionsGlobalContext().lookup(RequirementSpecNode.class); req = new RequirementServer(uniqueID.getText().trim(), description.getText().trim(), rsn.getRequirementSpecNodePK(), notes.getText().trim(), ((RequirementType) type.getSelectedItem()).getId(), ((RequirementStatus) status.getSelectedItem()).getId()); } req.setRequirementStatusId((RequirementStatus) status.getSelectedItem()); req.setRequirementTypeId(((RequirementType) type.getSelectedItem())); req.setDescription(description.getText().trim()); req.setNotes(notes.getText().trim()); req.setRequirementList(linkedRequirements); try { req.write2DB(); } catch (Exception ex) { Exceptions.printStackTrace(ex); } } close(); }//GEN-LAST:event_saveActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton cancel; private javax.swing.JButton chooseRequirements; private javax.swing.JTextArea description; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JTextArea notes; private javax.swing.JList requirements; private javax.swing.JButton save; private javax.swing.JComboBox status; private javax.swing.JScrollPane stepsPane; private javax.swing.JComboBox type; private javax.swing.JTextField uniqueID; // End of variables declaration//GEN-END:variables @Override public void componentOpened() { displayRequirement(); } @Override public void componentClosed() { result.removeLookupListener((EditRequirementWindowTopComponent) this); } void writeProperties(java.util.Properties p) { p.setProperty("version", "1.0"); // Store your settings } void readProperties(java.util.Properties p) { String version = p.getProperty("version"); switch(version){ case "1.0": //Do nothing break; } } private void clear() { linkedRequirements.clear(); statuses.clear(); types.clear(); } private void displayRequirement() { clear(); //Populate lists //Get types RequirementTypeJpaController rtc = new RequirementTypeJpaController(DataBaseManager.getEntityManagerFactory()); requirements.setModel(new DefaultListModel() { @Override public void addElement(Object obj) { linkedRequirements.add((Requirement) obj); super.addElement(obj); } @Override public int getSize() { return linkedRequirements.size(); } @Override public Object getElementAt(int i) { return linkedRequirements.get(i); } }); requirements.setCellRenderer(new ListCellRenderer() { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { return new JLabel( ((Requirement) value).getUniqueId()); } }); requirements.addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseMoved(MouseEvent e) { JList l = (JList) e.getSource(); ListModel m = l.getModel(); int index = l.locationToIndex(e.getPoint()); if (index > -1) { l.setToolTipText(((Requirement) m.getElementAt(index)).getDescription()); } } }); status.setModel(new DefaultComboBoxModel<RequirementStatus>() { @Override public void addElement(RequirementStatus obj) { if (!statuses.contains(obj)) { statuses.add(obj); super.addElement(obj); } } @Override public void removeAllElements() { super.removeAllElements(); statuses.clear(); } @Override public void removeElement(Object anObject) { super.removeElement(anObject); statuses.remove((RequirementStatus) anObject); } @Override public void removeElementAt(int index) { super.removeElementAt(index); statuses.remove(index); } @Override public void insertElementAt(RequirementStatus anObject, int index) { super.insertElementAt(anObject, index); statuses.add(index, anObject); } @Override public RequirementStatus getElementAt(int index) { return statuses.get(index); } @Override public int getSize() { return statuses.size(); } }); status.setRenderer(new ListCellRenderer() { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { String label; label = ((RequirementStatus) value).getStatus(); if (rb.containsKey(label)) { label = rb.getString(label); } return new JLabel(label); } }); type.setModel(new DefaultComboBoxModel<RequirementType>() { @Override public void addElement(RequirementType obj) { if (!types.contains(obj)) { types.add(obj); super.addElement(obj); } } @Override public void removeAllElements() { super.removeAllElements(); types.clear(); } @Override public void removeElement(Object anObject) { super.removeElement(anObject); types.remove((RequirementType) anObject); } @Override public void removeElementAt(int index) { super.removeElementAt(index); types.remove(index); } @Override public void insertElementAt(RequirementType anObject, int index) { super.insertElementAt(anObject, index); types.add(index, anObject); } @Override public RequirementType getElementAt(int index) { return types.get(index); } @Override public int getSize() { return types.size(); } }); type.setRenderer(new ListCellRenderer() { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { return new JLabel(((RequirementType) value).getName()); } }); for (RequirementType rt : rtc.findRequirementTypeEntities()) { ((DefaultComboBoxModel) type.getModel()).addElement(rt); } type.setSelectedIndex(0); //Get statuses RequirementStatusJpaController rsc = new RequirementStatusJpaController(DataBaseManager.getEntityManagerFactory()); for (RequirementStatus rs : rsc.findRequirementStatusEntities()) { ((DefaultComboBoxModel) status.getModel()).addElement(rs); } status.setSelectedIndex(0); if (isEdit()) { //Get the selected Step setRequirement(Utilities.actionsGlobalContext().lookup(Requirement.class)); uniqueID.setText(requirement.getUniqueId()); //Update the linked requirements for (Requirement req : requirement.getRequirementList()) { ((DefaultListModel) requirements.getModel()).addElement(req); } //Update other fields if (requirement.getNotes() != null && !requirement.getNotes().trim().isEmpty()) { notes.setText(requirement.getNotes()); } if (requirement.getDescription() != null && requirement.getDescription().length() > 0) { description.setText(requirement.getDescription()); } if (requirement.getRequirementStatusId() != null) { status.setSelectedItem(requirement.getRequirementStatusId()); } if (requirement.getRequirementTypeId() != null) { type.setSelectedItem(requirement.getRequirementTypeId()); } } if (testCaseFactory != null) { testCaseFactory.refresh(); } } @Override public void resultChanged(LookupEvent le) { Collection<? extends Requirement> results = result.allInstances(); if (!results.isEmpty()) { displayRequirement(); } } /** * @return the edit */ public boolean isEdit() { return edit; } /** * @param edit the edit to set */ public void setEdit(boolean edit) { this.edit = edit; } private ExplorerManager getExplorerManager() { return em; } }
package io.flutter.view; import android.graphics.Rect; import android.opengl.Matrix; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; import android.view.accessibility.AccessibilityNodeProvider; import io.flutter.plugin.common.BasicMessageChannel; import io.flutter.plugin.common.StandardMessageCodec; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; class AccessibilityBridge extends AccessibilityNodeProvider implements BasicMessageChannel.MessageHandler<Object> { private static final String TAG = "FlutterView"; // Constants from higher API levels. // TODO(goderbauer): Get these from Android Support Library when private static final int ACTION_SHOW_ON_SCREEN = 16908342; // API level 23 private static final float SCROLL_EXTENT_FOR_INFINITY = 100000.0f; private static final float SCROLL_POSITION_CAP_FOR_INFINITY = 70000.0f; private static final int ROOT_NODE_ID = 0; private Map<Integer, SemanticsObject> mObjects; private final FlutterView mOwner; private boolean mAccessibilityEnabled = false; private SemanticsObject mA11yFocusedObject; private SemanticsObject mInputFocusedObject; private SemanticsObject mHoveredObject; private int previousRouteId = ROOT_NODE_ID; private List<Integer> previousRoutes; private final BasicMessageChannel<Object> mFlutterAccessibilityChannel; enum Action { TAP(1 << 0), LONG_PRESS(1 << 1), SCROLL_LEFT(1 << 2), SCROLL_RIGHT(1 << 3), SCROLL_UP(1 << 4), SCROLL_DOWN(1 << 5), INCREASE(1 << 6), DECREASE(1 << 7), SHOW_ON_SCREEN(1 << 8), MOVE_CURSOR_FORWARD_BY_CHARACTER(1 << 9), MOVE_CURSOR_BACKWARD_BY_CHARACTER(1 << 10), SET_SELECTION(1 << 11), COPY(1 << 12), CUT(1 << 13), PASTE(1 << 14), DID_GAIN_ACCESSIBILITY_FOCUS(1 << 15), DID_LOSE_ACCESSIBILITY_FOCUS(1 << 16); Action(int value) { this.value = value; } final int value; } enum Flag { HAS_CHECKED_STATE(1 << 0), IS_CHECKED(1 << 1), IS_SELECTED(1 << 2), IS_BUTTON(1 << 3), IS_TEXT_FIELD(1 << 4), IS_FOCUSED(1 << 5), HAS_ENABLED_STATE(1 << 6), IS_ENABLED(1 << 7), IS_IN_MUTUALLY_EXCLUSIVE_GROUP(1 << 8), IS_HEADER(1 << 9), IS_OBSCURED(1 << 10), SCOPES_ROUTE(1 << 11), NAMES_ROUTE(1 << 12), IS_HIDDEN(1 << 13); Flag(int value) { this.value = value; } final int value; } AccessibilityBridge(FlutterView owner) { assert owner != null; mOwner = owner; mObjects = new HashMap<Integer, SemanticsObject>(); previousRoutes = new ArrayList<>(); mFlutterAccessibilityChannel = new BasicMessageChannel<>(owner, "flutter/accessibility", StandardMessageCodec.INSTANCE); } void setAccessibilityEnabled(boolean accessibilityEnabled) { mAccessibilityEnabled = accessibilityEnabled; if (accessibilityEnabled) { mFlutterAccessibilityChannel.setMessageHandler(this); } else { mFlutterAccessibilityChannel.setMessageHandler(null); } } @Override @SuppressWarnings("deprecation") public AccessibilityNodeInfo createAccessibilityNodeInfo(int virtualViewId) { if (virtualViewId == View.NO_ID) { AccessibilityNodeInfo result = AccessibilityNodeInfo.obtain(mOwner); mOwner.onInitializeAccessibilityNodeInfo(result); if (mObjects.containsKey(ROOT_NODE_ID)) result.addChild(mOwner, ROOT_NODE_ID); return result; } SemanticsObject object = mObjects.get(virtualViewId); if (object == null) return null; AccessibilityNodeInfo result = AccessibilityNodeInfo.obtain(mOwner, virtualViewId); result.setPackageName(mOwner.getContext().getPackageName()); result.setClassName("android.view.View"); result.setSource(mOwner, virtualViewId); result.setFocusable(object.isFocusable()); if (mInputFocusedObject != null) result.setFocused(mInputFocusedObject.id == virtualViewId); if (mA11yFocusedObject != null) result.setAccessibilityFocused(mA11yFocusedObject.id == virtualViewId); if (object.hasFlag(Flag.IS_TEXT_FIELD)) { result.setPassword(object.hasFlag(Flag.IS_OBSCURED)); result.setClassName("android.widget.EditText"); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { result.setEditable(true); if (object.textSelectionBase != -1 && object.textSelectionExtent != -1) { result.setTextSelection(object.textSelectionBase, object.textSelectionExtent); } } // Cursor movements int granularities = 0; if (object.hasAction(Action.MOVE_CURSOR_FORWARD_BY_CHARACTER)) { result.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); granularities |= AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER; } if (object.hasAction(Action.MOVE_CURSOR_BACKWARD_BY_CHARACTER)) { result.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); granularities |= AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER; } result.setMovementGranularities(granularities); } if (object.hasAction(Action.SET_SELECTION)) { result.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); } if (object.hasAction(Action.COPY)) { result.addAction(AccessibilityNodeInfo.ACTION_COPY); } if (object.hasAction(Action.CUT)) { result.addAction(AccessibilityNodeInfo.ACTION_CUT); } if (object.hasAction(Action.PASTE)) { result.addAction(AccessibilityNodeInfo.ACTION_PASTE); } if (object.hasFlag(Flag.IS_BUTTON)) { result.setClassName("android.widget.Button"); } if (object.parent != null) { assert object.id > ROOT_NODE_ID; result.setParent(mOwner, object.parent.id); } else { assert object.id == ROOT_NODE_ID; result.setParent(mOwner); } Rect bounds = object.getGlobalRect(); if (object.parent != null) { Rect parentBounds = object.parent.getGlobalRect(); Rect boundsInParent = new Rect(bounds); boundsInParent.offset(-parentBounds.left, -parentBounds.top); result.setBoundsInParent(boundsInParent); } else { result.setBoundsInParent(bounds); } result.setBoundsInScreen(bounds); result.setVisibleToUser(true); result.setEnabled(!object.hasFlag(Flag.HAS_ENABLED_STATE) || object.hasFlag(Flag.IS_ENABLED)); if (object.hasAction(Action.TAP)) { result.addAction(AccessibilityNodeInfo.ACTION_CLICK); result.setClickable(true); } if (object.hasAction(Action.LONG_PRESS)) { result.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); result.setLongClickable(true); } if (object.hasAction(Action.SCROLL_LEFT) || object.hasAction(Action.SCROLL_UP) || object.hasAction(Action.SCROLL_RIGHT) || object.hasAction(Action.SCROLL_DOWN)) { result.setScrollable(true); // This tells Android's a11y to send scroll events when reaching the end of // the visible viewport of a scrollable. result.setClassName("android.widget.ScrollView"); // TODO(ianh): Once we're on SDK v23+, call addAction to // expose AccessibilityAction.ACTION_SCROLL_LEFT, _RIGHT, // _UP, and _DOWN when appropriate. if (object.hasAction(Action.SCROLL_LEFT) || object.hasAction(Action.SCROLL_UP)) { result.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD); } if (object.hasAction(Action.SCROLL_RIGHT) || object.hasAction(Action.SCROLL_DOWN)) { result.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD); } } if (object.hasAction(Action.INCREASE) || object.hasAction(Action.DECREASE)) { result.setClassName("android.widget.SeekBar"); if (object.hasAction(Action.INCREASE)) { result.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD); } if (object.hasAction(Action.DECREASE)) { result.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD); } } boolean hasCheckedState = object.hasFlag(Flag.HAS_CHECKED_STATE); result.setCheckable(hasCheckedState); if (hasCheckedState) { result.setChecked(object.hasFlag(Flag.IS_CHECKED)); if (object.hasFlag(Flag.IS_IN_MUTUALLY_EXCLUSIVE_GROUP)) result.setClassName("android.widget.RadioButton"); else result.setClassName("android.widget.CheckBox"); } result.setSelected(object.hasFlag(Flag.IS_SELECTED)); result.setText(object.getValueLabelHint()); // Accessibility Focus if (mA11yFocusedObject != null && mA11yFocusedObject.id == virtualViewId) { result.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); } else { result.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); } if (object.children != null) { for (SemanticsObject child : object.children) { if (!child.hasFlag(Flag.IS_HIDDEN)) { result.addChild(mOwner, child.id); } } } return result; } @Override public boolean performAction(int virtualViewId, int action, Bundle arguments) { SemanticsObject object = mObjects.get(virtualViewId); if (object == null) { return false; } switch (action) { case AccessibilityNodeInfo.ACTION_CLICK: { mOwner.dispatchSemanticsAction(virtualViewId, Action.TAP); return true; } case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: { if (object.hasAction(Action.SCROLL_UP)) { mOwner.dispatchSemanticsAction(virtualViewId, Action.SCROLL_UP); } else if (object.hasAction(Action.SCROLL_LEFT)) { // TODO(ianh): bidi support using textDirection mOwner.dispatchSemanticsAction(virtualViewId, Action.SCROLL_LEFT); } else if (object.hasAction(Action.INCREASE)) { object.value = object.increasedValue; // Event causes Android to read out the updated value. sendAccessibilityEvent(virtualViewId, AccessibilityEvent.TYPE_VIEW_SELECTED); mOwner.dispatchSemanticsAction(virtualViewId, Action.INCREASE); } else { return false; } return true; } case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: { if (object.hasAction(Action.SCROLL_DOWN)) { mOwner.dispatchSemanticsAction(virtualViewId, Action.SCROLL_DOWN); } else if (object.hasAction(Action.SCROLL_RIGHT)) { // TODO(ianh): bidi support using textDirection mOwner.dispatchSemanticsAction(virtualViewId, Action.SCROLL_RIGHT); } else if (object.hasAction(Action.DECREASE)) { object.value = object.decreasedValue; // Event causes Android to read out the updated value. sendAccessibilityEvent(virtualViewId, AccessibilityEvent.TYPE_VIEW_SELECTED); mOwner.dispatchSemanticsAction(virtualViewId, Action.DECREASE); } else { return false; } return true; } case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { return performCursorMoveAction(object, virtualViewId, arguments, false); } case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { return performCursorMoveAction(object, virtualViewId, arguments, true); } case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { mOwner.dispatchSemanticsAction(virtualViewId, Action.DID_LOSE_ACCESSIBILITY_FOCUS); sendAccessibilityEvent(virtualViewId, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); mA11yFocusedObject = null; return true; } case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { mOwner.dispatchSemanticsAction(virtualViewId, Action.DID_GAIN_ACCESSIBILITY_FOCUS); sendAccessibilityEvent(virtualViewId, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); if (mA11yFocusedObject == null) { // When Android focuses a node, it doesn't invalidate the view. // (It does when it sends ACTION_CLEAR_ACCESSIBILITY_FOCUS, so // we only have to worry about this when the focused node is null.) mOwner.invalidate(); } mA11yFocusedObject = object; if (object.hasAction(Action.INCREASE) || object.hasAction(Action.DECREASE)) { // SeekBars only announce themselves after this event. sendAccessibilityEvent(virtualViewId, AccessibilityEvent.TYPE_VIEW_SELECTED); } return true; } case ACTION_SHOW_ON_SCREEN: { mOwner.dispatchSemanticsAction(virtualViewId, Action.SHOW_ON_SCREEN); return true; } case AccessibilityNodeInfo.ACTION_SET_SELECTION: { final Map<String, Integer> selection = new HashMap<String, Integer>(); final boolean hasSelection = arguments != null && arguments.containsKey( AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT) && arguments.containsKey( AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT); if (hasSelection) { selection.put("base", arguments.getInt( AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT)); selection.put("extent", arguments.getInt( AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT)); } else { // Clear the selection selection.put("base", object.textSelectionExtent); selection.put("extent", object.textSelectionExtent); } mOwner.dispatchSemanticsAction(virtualViewId, Action.SET_SELECTION, selection); return true; } case AccessibilityNodeInfo.ACTION_COPY: { mOwner.dispatchSemanticsAction(virtualViewId, Action.COPY); return true; } case AccessibilityNodeInfo.ACTION_CUT: { mOwner.dispatchSemanticsAction(virtualViewId, Action.CUT); return true; } case AccessibilityNodeInfo.ACTION_PASTE: { mOwner.dispatchSemanticsAction(virtualViewId, Action.PASTE); return true; } } return false; } boolean performCursorMoveAction(SemanticsObject object, int virtualViewId, Bundle arguments, boolean forward) { final int granularity = arguments.getInt( AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); final boolean extendSelection = arguments.getBoolean( AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); switch (granularity) { case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { if (forward && object.hasAction(Action.MOVE_CURSOR_FORWARD_BY_CHARACTER)) { mOwner.dispatchSemanticsAction(virtualViewId, Action.MOVE_CURSOR_FORWARD_BY_CHARACTER, extendSelection); return true; } if (!forward && object.hasAction(Action.MOVE_CURSOR_BACKWARD_BY_CHARACTER)) { mOwner.dispatchSemanticsAction(virtualViewId, Action.MOVE_CURSOR_BACKWARD_BY_CHARACTER, extendSelection); return true; } } // TODO(goderbauer): support other granularities. } return false; } // TODO(ianh): implement findAccessibilityNodeInfosByText() @Override public AccessibilityNodeInfo findFocus(int focus) { switch (focus) { case AccessibilityNodeInfo.FOCUS_INPUT: { if (mInputFocusedObject != null) return createAccessibilityNodeInfo(mInputFocusedObject.id); } case AccessibilityNodeInfo.FOCUS_ACCESSIBILITY: { if (mA11yFocusedObject != null) return createAccessibilityNodeInfo(mA11yFocusedObject.id); } } return null; } private SemanticsObject getRootObject() { assert mObjects.containsKey(0); return mObjects.get(0); } private SemanticsObject getOrCreateObject(int id) { SemanticsObject object = mObjects.get(id); if (object == null) { object = new SemanticsObject(); object.id = id; mObjects.put(id, object); } return object; } void handleTouchExplorationExit() { if (mHoveredObject != null) { sendAccessibilityEvent(mHoveredObject.id, AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); mHoveredObject = null; } } void handleTouchExploration(float x, float y) { if (mObjects.isEmpty()) { return; } SemanticsObject newObject = getRootObject().hitTest(new float[]{ x, y, 0, 1 }); if (newObject != mHoveredObject) { // sending ENTER before EXIT is how Android wants it if (newObject != null) { sendAccessibilityEvent(newObject.id, AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); } if (mHoveredObject != null) { sendAccessibilityEvent(mHoveredObject.id, AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); } mHoveredObject = newObject; } } void updateSemantics(ByteBuffer buffer, String[] strings) { ArrayList<SemanticsObject> updated = new ArrayList<SemanticsObject>(); while (buffer.hasRemaining()) { int id = buffer.getInt(); SemanticsObject object = getOrCreateObject(id); object.updateWith(buffer, strings); if (object.hasFlag(Flag.IS_HIDDEN)) { continue; } if (object.hasFlag(Flag.IS_FOCUSED)) { mInputFocusedObject = object; } if (object.hadPreviousConfig) { updated.add(object); } } Set<SemanticsObject> visitedObjects = new HashSet<SemanticsObject>(); SemanticsObject rootObject = getRootObject(); List<SemanticsObject> newRoutes = new ArrayList<>(); if (rootObject != null) { final float[] identity = new float[16]; Matrix.setIdentityM(identity, 0); rootObject.updateRecursively(identity, visitedObjects, false); rootObject.collectRoutes(newRoutes); } // Dispatch a TYPE_WINDOW_STATE_CHANGED event if the most recent route id changed from the // previously cached route id. SemanticsObject lastAdded = null; for (SemanticsObject semanticsObject : newRoutes) { if (!previousRoutes.contains(semanticsObject.id)) { lastAdded = semanticsObject; } } if (lastAdded == null && newRoutes.size() > 0) { lastAdded = newRoutes.get(newRoutes.size() - 1); } if (lastAdded != null && lastAdded.id != previousRouteId) { previousRouteId = lastAdded.id; createWindowChangeEvent(lastAdded); } previousRoutes.clear(); for (SemanticsObject semanticsObject : newRoutes) { previousRoutes.add(semanticsObject.id); } Iterator<Map.Entry<Integer, SemanticsObject>> it = mObjects.entrySet().iterator(); while (it.hasNext()) { Map.Entry<Integer, SemanticsObject> entry = it.next(); SemanticsObject object = entry.getValue(); if (!visitedObjects.contains(object)) { willRemoveSemanticsObject(object); it.remove(); } } // TODO(goderbauer): Send this event only once (!) for changed subtrees, sendAccessibilityEvent(0, AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); for (SemanticsObject object : updated) { if (object.didScroll()) { AccessibilityEvent event = obtainAccessibilityEvent(object.id, AccessibilityEvent.TYPE_VIEW_SCROLLED); // Android doesn't support unbound scrolling. So we pretend there is a large // bound (SCROLL_EXTENT_FOR_INFINITY), which you can never reach. float position = object.scrollPosition; float max = object.scrollExtentMax; if (Float.isInfinite(object.scrollExtentMax)) { max = SCROLL_EXTENT_FOR_INFINITY; if (position > SCROLL_POSITION_CAP_FOR_INFINITY) { position = SCROLL_POSITION_CAP_FOR_INFINITY; } } if (Float.isInfinite(object.scrollExtentMin)) { max += SCROLL_EXTENT_FOR_INFINITY; if (position < -SCROLL_POSITION_CAP_FOR_INFINITY) { position = -SCROLL_POSITION_CAP_FOR_INFINITY; } position += SCROLL_EXTENT_FOR_INFINITY; } else { max -= object.scrollExtentMin; position -= object.scrollExtentMin; } if (object.hadAction(Action.SCROLL_UP) || object.hadAction(Action.SCROLL_DOWN)) { event.setScrollY((int) position); event.setMaxScrollY((int) max); } else if (object.hadAction(Action.SCROLL_LEFT) || object.hadAction(Action.SCROLL_RIGHT)) { event.setScrollX((int) position); event.setMaxScrollX((int) max); } sendAccessibilityEvent(event); } if (mA11yFocusedObject != null && mA11yFocusedObject.id == object.id && !object.hadFlag(Flag.IS_SELECTED) && object.hasFlag(Flag.IS_SELECTED)) { AccessibilityEvent event = obtainAccessibilityEvent(object.id, AccessibilityEvent.TYPE_VIEW_SELECTED); event.getText().add(object.label); sendAccessibilityEvent(event); } if (mInputFocusedObject != null && mInputFocusedObject.id == object.id && object.hadFlag(Flag.IS_TEXT_FIELD) && object.hasFlag(Flag.IS_TEXT_FIELD)) { String oldValue = object.previousValue != null ? object.previousValue : ""; String newValue = object.value != null ? object.value : ""; AccessibilityEvent event = createTextChangedEvent(object.id, oldValue, newValue); if (event != null) { sendAccessibilityEvent(event); } if (object.previousTextSelectionBase != object.textSelectionBase || object.previousTextSelectionExtent != object.textSelectionExtent) { AccessibilityEvent selectionEvent = obtainAccessibilityEvent( object.id, AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); selectionEvent.getText().add(newValue); selectionEvent.setFromIndex(object.textSelectionBase); selectionEvent.setToIndex(object.textSelectionExtent); selectionEvent.setItemCount(newValue.length()); sendAccessibilityEvent(selectionEvent); } } } } private AccessibilityEvent createTextChangedEvent(int id, String oldValue, String newValue) { AccessibilityEvent e = obtainAccessibilityEvent(id, AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED); e.setBeforeText(oldValue); e.getText().add(newValue); int i; for (i = 0; i < oldValue.length() && i < newValue.length(); ++i) { if (oldValue.charAt(i) != newValue.charAt(i)) { break; } } if (i >= oldValue.length() && i >= newValue.length()) { return null; // Text did not change } int firstDifference = i; e.setFromIndex(firstDifference); int oldIndex = oldValue.length() - 1; int newIndex = newValue.length() - 1; while (oldIndex >= firstDifference && newIndex >= firstDifference) { if (oldValue.charAt(oldIndex) != newValue.charAt(newIndex)) { break; } --oldIndex; --newIndex; } e.setRemovedCount(oldIndex - firstDifference + 1); e.setAddedCount(newIndex - firstDifference + 1); return e; } private AccessibilityEvent obtainAccessibilityEvent(int virtualViewId, int eventType) { assert virtualViewId != ROOT_NODE_ID; AccessibilityEvent event = AccessibilityEvent.obtain(eventType); event.setPackageName(mOwner.getContext().getPackageName()); event.setSource(mOwner, virtualViewId); return event; } private void sendAccessibilityEvent(int virtualViewId, int eventType) { if (!mAccessibilityEnabled) { return; } if (virtualViewId == ROOT_NODE_ID) { mOwner.sendAccessibilityEvent(eventType); } else { sendAccessibilityEvent(obtainAccessibilityEvent(virtualViewId, eventType)); } } private void sendAccessibilityEvent(AccessibilityEvent event) { if (!mAccessibilityEnabled) { return; } mOwner.getParent().requestSendAccessibilityEvent(mOwner, event); } // Message Handler for [mFlutterAccessibilityChannel]. public void onMessage(Object message, BasicMessageChannel.Reply<Object> reply) { @SuppressWarnings("unchecked") final HashMap<String, Object> annotatedEvent = (HashMap<String, Object>)message; final String type = (String)annotatedEvent.get("type"); @SuppressWarnings("unchecked") final HashMap<String, Object> data = (HashMap<String, Object>)annotatedEvent.get("data"); switch (type) { case "announce": mOwner.announceForAccessibility((String) data.get("message")); break; case "longPress": { Integer nodeId = (Integer) annotatedEvent.get("nodeId"); if (nodeId == null) { return; } sendAccessibilityEvent(nodeId, AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); break; } case "tap": { Integer nodeId = (Integer) annotatedEvent.get("nodeId"); if (nodeId == null) { return; } sendAccessibilityEvent(nodeId, AccessibilityEvent.TYPE_VIEW_CLICKED); break; } case "tooltip": { AccessibilityEvent e = obtainAccessibilityEvent(ROOT_NODE_ID, AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); e.getText().add((String) data.get("message")); sendAccessibilityEvent(e); } default: assert false; } } private void createWindowChangeEvent(SemanticsObject route) { AccessibilityEvent e = obtainAccessibilityEvent(route.id, AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); String routeName = route.getRouteName(); e.getText().add(routeName); sendAccessibilityEvent(e); } private void willRemoveSemanticsObject(SemanticsObject object) { assert mObjects.containsKey(object.id); assert mObjects.get(object.id) == object; object.parent = null; if (mA11yFocusedObject == object) { sendAccessibilityEvent(mA11yFocusedObject.id, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); mA11yFocusedObject = null; } if (mInputFocusedObject == object) { mInputFocusedObject = null; } if (mHoveredObject == object) { mHoveredObject = null; } } void reset() { mObjects.clear(); if (mA11yFocusedObject != null) sendAccessibilityEvent(mA11yFocusedObject.id, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); mA11yFocusedObject = null; mHoveredObject = null; sendAccessibilityEvent(0, AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); } private enum TextDirection { UNKNOWN, LTR, RTL; public static TextDirection fromInt(int value) { switch (value) { case 1: return RTL; case 2: return LTR; } return UNKNOWN; } } private class SemanticsObject { SemanticsObject() { } int id = -1; int flags; int actions; int textSelectionBase; int textSelectionExtent; float scrollPosition; float scrollExtentMax; float scrollExtentMin; String label; String value; String increasedValue; String decreasedValue; String hint; TextDirection textDirection; int hitTestPosition; boolean hadPreviousConfig = false; int previousFlags; int previousActions; int previousTextSelectionBase; int previousTextSelectionExtent; float previousScrollPosition; float previousScrollExtentMax; float previousScrollExtentMin; String previousValue; private float left; private float top; private float right; private float bottom; private float[] transform; SemanticsObject parent; List<SemanticsObject> children; // In inverse hit test order (i.e. paint order). private boolean inverseTransformDirty = true; private float[] inverseTransform; private boolean globalGeometryDirty = true; private float[] globalTransform; private Rect globalRect; boolean hasAction(Action action) { return (actions & action.value) != 0; } boolean hadAction(Action action) { return (previousActions & action.value) != 0; } boolean hasFlag(Flag flag) { return (flags & flag.value) != 0; } boolean hadFlag(Flag flag) { assert hadPreviousConfig; return (previousFlags & flag.value) != 0; } boolean didScroll() { return !Float.isNaN(scrollPosition) && !Float.isNaN(previousScrollPosition) && previousScrollPosition != scrollPosition; } void log(String indent, boolean recursive) { Log.i(TAG, indent + "SemanticsObject id=" + id + " label=" + label + " actions=" + actions + " flags=" + flags + "\n" + indent + " +-- textDirection=" + textDirection + "\n"+ indent + " +-- hitTestPosition=" + hitTestPosition + "\n"+ indent + " +-- rect.ltrb=(" + left + ", " + top + ", " + right + ", " + bottom + ")\n" + indent + " +-- transform=" + Arrays.toString(transform) + "\n"); if (children != null && recursive) { String childIndent = indent + " "; for (SemanticsObject child : children) { child.log(childIndent, recursive); } } } void updateWith(ByteBuffer buffer, String[] strings) { hadPreviousConfig = true; previousValue = value; previousFlags = flags; previousActions = actions; previousTextSelectionBase = textSelectionBase; previousTextSelectionExtent = textSelectionExtent; previousScrollPosition = scrollPosition; previousScrollExtentMax = scrollExtentMax; previousScrollExtentMin = scrollExtentMin; flags = buffer.getInt(); actions = buffer.getInt(); textSelectionBase = buffer.getInt(); textSelectionExtent = buffer.getInt(); scrollPosition = buffer.getFloat(); scrollExtentMax = buffer.getFloat(); scrollExtentMin = buffer.getFloat(); int stringIndex = buffer.getInt(); label = stringIndex == -1 ? null : strings[stringIndex]; stringIndex = buffer.getInt(); value = stringIndex == -1 ? null : strings[stringIndex]; stringIndex = buffer.getInt(); increasedValue = stringIndex == -1 ? null : strings[stringIndex]; stringIndex = buffer.getInt(); decreasedValue = stringIndex == -1 ? null : strings[stringIndex]; stringIndex = buffer.getInt(); hint = stringIndex == -1 ? null : strings[stringIndex]; textDirection = TextDirection.fromInt(buffer.getInt()); hitTestPosition = buffer.getInt(); left = buffer.getFloat(); top = buffer.getFloat(); right = buffer.getFloat(); bottom = buffer.getFloat(); if (transform == null) transform = new float[16]; for (int i = 0; i < 16; ++i) transform[i] = buffer.getFloat(); inverseTransformDirty = true; globalGeometryDirty = true; final int childCount = buffer.getInt(); if (childCount == 0) { children = null; } else { if (children == null) children = new ArrayList<SemanticsObject>(childCount); else children.clear(); for (int i = 0; i < childCount; ++i) { SemanticsObject child = getOrCreateObject(buffer.getInt()); child.parent = this; children.add(child); } } } private void ensureInverseTransform() { if (!inverseTransformDirty) return; inverseTransformDirty = false; if (inverseTransform == null) inverseTransform = new float[16]; if (!Matrix.invertM(inverseTransform, 0, transform, 0)) Arrays.fill(inverseTransform, 0); } Rect getGlobalRect() { assert !globalGeometryDirty; return globalRect; } SemanticsObject hitTest(float[] point) { final float w = point[3]; final float x = point[0] / w; final float y = point[1] / w; if (x < left || x >= right || y < top || y >= bottom) return null; if (children != null) { final float[] transformedPoint = new float[4]; for (int i = children.size() - 1; i >= 0; i -= 1) { final SemanticsObject child = children.get(i); if (child.hasFlag(Flag.IS_HIDDEN)) { continue; } child.ensureInverseTransform(); Matrix.multiplyMV(transformedPoint, 0, child.inverseTransform, 0, point, 0); final SemanticsObject result = child.hitTest(transformedPoint); if (result != null) { return result; } } } return this; } // TODO(goderbauer): This should be decided by the framework once we have more information // about focusability there. boolean isFocusable() { // We enforce in the framework that no other useful semantics are merged with these // nodes. if (hasFlag(Flag.SCOPES_ROUTE)) { return false; } int scrollableActions = Action.SCROLL_RIGHT.value | Action.SCROLL_LEFT.value | Action.SCROLL_UP.value | Action.SCROLL_DOWN.value; return (actions & ~scrollableActions) != 0 || flags != 0 || (label != null && !label.isEmpty()) || (value != null && !value.isEmpty()) || (hint != null && !hint.isEmpty()); } void collectRoutes(List<SemanticsObject> edges) { if (hasFlag(Flag.SCOPES_ROUTE)) { edges.add(this); } if (children != null) { for (int i = 0; i < children.size(); ++i) { children.get(i).collectRoutes(edges); } } } String getRouteName() { // Returns the first non-null and non-empty semantic label of a child // with an NamesRoute flag. Otherwise returns null. if (hasFlag(Flag.NAMES_ROUTE)) { if (label != null && !label.isEmpty()) { return label; } } if (children != null) { for (int i = 0; i < children.size(); ++i) { String newName = children.get(i).getRouteName(); if (newName != null && !newName.isEmpty()) { return newName; } } } return null; } void updateRecursively(float[] ancestorTransform, Set<SemanticsObject> visitedObjects, boolean forceUpdate) { visitedObjects.add(this); if (globalGeometryDirty) forceUpdate = true; if (forceUpdate) { if (globalTransform == null) globalTransform = new float[16]; Matrix.multiplyMM(globalTransform, 0, ancestorTransform, 0, transform, 0); final float[] sample = new float[4]; sample[2] = 0; sample[3] = 1; final float[] point1 = new float[4]; final float[] point2 = new float[4]; final float[] point3 = new float[4]; final float[] point4 = new float[4]; sample[0] = left; sample[1] = top; transformPoint(point1, globalTransform, sample); sample[0] = right; sample[1] = top; transformPoint(point2, globalTransform, sample); sample[0] = right; sample[1] = bottom; transformPoint(point3, globalTransform, sample); sample[0] = left; sample[1] = bottom; transformPoint(point4, globalTransform, sample); if (globalRect == null) globalRect = new Rect(); globalRect.set( Math.round(min(point1[0], point2[0], point3[0], point4[0])), Math.round(min(point1[1], point2[1], point3[1], point4[1])), Math.round(max(point1[0], point2[0], point3[0], point4[0])), Math.round(max(point1[1], point2[1], point3[1], point4[1])) ); globalGeometryDirty = false; } assert globalTransform != null; assert globalRect != null; if (children != null) { for (int i = 0; i < children.size(); ++i) { children.get(i).updateRecursively(globalTransform, visitedObjects, forceUpdate); } } } private void transformPoint(float[] result, float[] transform, float[] point) { Matrix.multiplyMV(result, 0, transform, 0, point, 0); final float w = result[3]; result[0] /= w; result[1] /= w; result[2] /= w; result[3] = 0; } private float min(float a, float b, float c, float d) { return Math.min(a, Math.min(b, Math.min(c, d))); } private float max(float a, float b, float c, float d) { return Math.max(a, Math.max(b, Math.max(c, d))); } private String getValueLabelHint() { StringBuilder sb = new StringBuilder(); String[] array = { value, label, hint }; for (String word: array) { if (word != null && word.length() > 0) { if (sb.length() > 0) sb.append(", "); sb.append(word); } } return sb.length() > 0 ? sb.toString() : null; } } }
package org.innovateuk.ifs.project.projectdetails.workflow.configuration; import org.innovateuk.ifs.project.projectdetails.workflow.guards.AllProjectDetailsSuppliedGuard; import org.innovateuk.ifs.project.resource.ProjectDetailsEvent; import org.innovateuk.ifs.project.resource.ProjectDetailsState; import org.innovateuk.ifs.workflow.WorkflowStateMachineListener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.statemachine.config.EnableStateMachine; import org.springframework.statemachine.config.StateMachineConfigurerAdapter; import org.springframework.statemachine.config.builders.StateMachineConfigurationConfigurer; import org.springframework.statemachine.config.builders.StateMachineStateConfigurer; import org.springframework.statemachine.config.builders.StateMachineTransitionConfigurer; import java.util.EnumSet; import static org.innovateuk.ifs.project.resource.ProjectDetailsEvent.*; import static org.innovateuk.ifs.project.resource.ProjectDetailsState.*; import static org.innovateuk.ifs.project.resource.ProjectDetailsState.PENDING; /** * Describes the workflow for the Project Details section for Project Setup. */ @Configuration @EnableStateMachine(name = "projectDetailsStateMachine") public class ProjectDetailsWorkflow extends StateMachineConfigurerAdapter<ProjectDetailsState, ProjectDetailsEvent> { @Autowired private AllProjectDetailsSuppliedGuard allProjectDetailsSuppliedGuard; @Override public void configure(StateMachineConfigurationConfigurer<ProjectDetailsState, ProjectDetailsEvent> config) throws Exception { config.withConfiguration().listener(new WorkflowStateMachineListener<>()); } @Override public void configure(StateMachineStateConfigurer<ProjectDetailsState, ProjectDetailsEvent> states) throws Exception { states.withStates() .initial(PENDING) .states(EnumSet.of(PENDING, SUBMITTED)) .choice(DECIDE_IF_READY_TO_SUBMIT) .end(SUBMITTED); } /* @Override public void configure(StateMachineStateConfigurer<ProjectDetailsState, ProjectDetailsEvent> states) throws Exception { states.withStates() .initial(PENDING) .states(EnumSet.of(PENDING, READY_TO_SUBMIT, SUBMITTED)) .choice(DECIDE_IF_READY_TO_SUBMIT) .end(SUBMITTED); }*/ @Override public void configure(StateMachineTransitionConfigurer<ProjectDetailsState, ProjectDetailsEvent> transitions) throws Exception { transitions .withExternal() .source(PENDING) .event(PROJECT_CREATED) .target(PENDING) .and() .withExternal() .source(PENDING) .event(PROJECT_START_DATE_ADDED) .target(DECIDE_IF_READY_TO_SUBMIT) .and() .withExternal() .source(PENDING) .event(PROJECT_ADDRESS_ADDED) .target(DECIDE_IF_READY_TO_SUBMIT) .and() .withExternal() .source(PENDING) .event(PROJECT_MANAGER_ADDED) .target(DECIDE_IF_READY_TO_SUBMIT) .and() .withChoice() .source(DECIDE_IF_READY_TO_SUBMIT) .first(SUBMITTED, allProjectDetailsSuppliedGuard) .last(PENDING); } /* @Override public void configure(StateMachineTransitionConfigurer<ProjectDetailsState, ProjectDetailsEvent> transitions) throws Exception { transitions .withExternal() .source(PENDING) .event(PROJECT_CREATED) .target(PENDING) .and() .withExternal() .source(PENDING) .event(PROJECT_START_DATE_ADDED) .target(DECIDE_IF_READY_TO_SUBMIT) .and() .withExternal() .source(PENDING) .event(PROJECT_ADDRESS_ADDED) .target(DECIDE_IF_READY_TO_SUBMIT) .and() .withExternal() .source(PENDING) .event(PROJECT_MANAGER_ADDED) .target(DECIDE_IF_READY_TO_SUBMIT) .and() .withExternal() .source(READY_TO_SUBMIT) .event(PROJECT_START_DATE_ADDED) .target(DECIDE_IF_READY_TO_SUBMIT) .and() .withExternal() .source(READY_TO_SUBMIT) .event(PROJECT_ADDRESS_ADDED) .target(DECIDE_IF_READY_TO_SUBMIT) .and() .withExternal() .source(READY_TO_SUBMIT) .event(PROJECT_MANAGER_ADDED) .target(DECIDE_IF_READY_TO_SUBMIT) .and() .withChoice() .source(DECIDE_IF_READY_TO_SUBMIT) .first(READY_TO_SUBMIT, allProjectDetailsSuppliedGuard) .last(PENDING) .and() .withExternal() .source(READY_TO_SUBMIT) .event(SUBMIT) .target(SUBMITTED) .guard(allProjectDetailsSuppliedGuard); }*/ }
package com.oasisfeng.android.base; import android.app.Activity; import android.app.Application.ActivityLifecycleCallbacks; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.annotation.NonNull; import com.oasisfeng.android.base.Scopes.Scope; import com.oasisfeng.android.content.CrossProcessSharedPreferences; import java.util.HashSet; import java.util.Set; import static android.app.PendingIntent.FLAG_NO_CREATE; import static android.app.PendingIntent.FLAG_UPDATE_CURRENT; /** @author Oasis */ public class Scopes { /* These preferences file should be included in backup configuration of your app */ public static final String KPrefsNameAppScope = "app.scope"; public static final String KPrefsNameVersionScope = "version.scope"; public interface Scope { boolean isMarked(@NonNull String tag); /** @return whether it is NOT YET marked before */ boolean mark(@NonNull String tag); void markOnly(@NonNull String tag); /** @return whether it is marked before */ boolean unmark(@NonNull String tag); } /** Throughout the whole lifecycle of this installed app, until uninstalled. (can also be extended to re-installation if configured with backup) */ public static Scope app(final Context context) { return new AppInstallationScope(context); } /** Throughout the current version (code) of this installed app, until the version changes. */ public static Scope version(final Context context) { return new PackageVersionScope(context); } /** Throughout the current update of this installed app, until being updated by in-place re-installation. */ public static Scope update(final Context context) { return new PackageUpdateScope(context); } public static Scope boot(final Context context) { return new DeviceBootScope(context); } /** Throughout the current running process of this installed app, until being terminated. */ public static Scope process() { return ProcessScope.mSingleton; } /** Throughout the time-limited session within current running process of this installed app, until session time-out. */ public static Scope session(final Activity activity) { if (SessionScope.mSingleton == null) SessionScope.mSingleton = new SessionScope(activity); return SessionScope.mSingleton; } private Scopes() {} } class SessionScope extends MemoryBasedScopeImpl { private static final int KSessionTimeout = 5 * 60 * 1000; // TODO: Configurable SessionScope(final Activity activity) { activity.getApplication().registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() { @Override public void onActivityResumed(final Activity a) { if (System.currentTimeMillis() >= mTimeLastSession + KSessionTimeout) mSeen.clear(); } @Override public void onActivityPaused(final Activity a) { mTimeLastSession = System.currentTimeMillis(); } @Override public void onActivityStopped(final Activity a) {} @Override public void onActivityStarted(final Activity a) {} @Override public void onActivitySaveInstanceState(final Activity a, final Bundle s) {} @Override public void onActivityCreated(final Activity a, final Bundle s) {} @Override public void onActivityDestroyed(final Activity a) {} }); } private long mTimeLastSession = 0; static SessionScope mSingleton; } class DeviceBootScope implements Scope { @Override public boolean isMarked(@NonNull final String tag) { return PendingIntent.getBroadcast(mContext, 0, makeIntent(tag), FLAG_NO_CREATE) != null; } @Override public boolean mark(@NonNull final String tag) { final Intent intent = makeIntent(tag); final PendingIntent mark = PendingIntent.getBroadcast(mContext, 0, intent, FLAG_NO_CREATE); PendingIntent.getBroadcast(mContext, 0, intent, FLAG_UPDATE_CURRENT); return mark != null; } @Override public void markOnly(@NonNull final String tag) { PendingIntent.getBroadcast(mContext, 0, makeIntent(tag), FLAG_UPDATE_CURRENT); } @Override public boolean unmark(@NonNull final String tag) { final PendingIntent mark = PendingIntent.getBroadcast(mContext, 0, makeIntent(tag), FLAG_NO_CREATE); if (mark == null) return false; mark.cancel(); return true; } private Intent makeIntent(final String tag) { return new Intent("SCOPE:" + tag).setPackage(mContext.getPackageName()); } DeviceBootScope(final Context context) { mContext = context; } private final Context mContext; } class ProcessScope extends MemoryBasedScopeImpl { static final Scope mSingleton = new ProcessScope(); } class MemoryBasedScopeImpl implements Scope { @Override public boolean isMarked(@NonNull final String tag) { return mSeen.contains(tag); } @Override public boolean mark(@NonNull final String tag) { return mSeen.add(tag); } @Override public void markOnly(@NonNull final String tag) { mSeen.add(tag); } @Override public boolean unmark(@NonNull final String tag) { return mSeen.remove(tag); } final Set<String> mSeen = new HashSet<>(); } class PackageUpdateScope extends SharedPrefsBasedScopeImpl { private static final String KPrefsKeyLastUpdateTime = "update-time"; PackageUpdateScope(final Context context) { super(resetIfLastUpdateTimeChanged(context, CrossProcessSharedPreferences.get(context, "update.scope"))); } private static SharedPreferences resetIfLastUpdateTimeChanged(final Context context, final SharedPreferences prefs) { final long last_update_time = Versions.lastUpdateTime(context); if (last_update_time != prefs.getLong(KPrefsKeyLastUpdateTime, 0)) prefs.edit().clear().putLong(KPrefsKeyLastUpdateTime, last_update_time).apply(); return prefs; } } class PackageVersionScope extends SharedPrefsBasedScopeImpl { private static final String KPrefsKeyVersionCode = "version-code"; PackageVersionScope(final Context context) { super(resetIfVersionChanges(context, CrossProcessSharedPreferences.get(context, Scopes.KPrefsNameVersionScope))); } private static SharedPreferences resetIfVersionChanges(final Context context, final SharedPreferences prefs) { final int version = Versions.code(context); if (version != prefs.getInt(KPrefsKeyVersionCode, 0)) prefs.edit().clear().putInt(KPrefsKeyVersionCode, version).apply(); return prefs; } } class AppInstallationScope extends SharedPrefsBasedScopeImpl { AppInstallationScope(final Context context) { super(CrossProcessSharedPreferences.get(context, Scopes.KPrefsNameAppScope)); } } class SharedPrefsBasedScopeImpl implements Scope { private static final String KPrefsKeyPrefix = "mark-"; private static final String KPrefsKeyPrefixLegacy = "first-time-"; // Old name, for backward-compatibility @Override public boolean isMarked(@NonNull final String tag) { return mPrefs.getBoolean(KPrefsKeyPrefix + tag, false); } @Override public boolean mark(@NonNull final String tag) { final String key = KPrefsKeyPrefix + tag; if (mPrefs.getBoolean(key, false)) return false; mPrefs.edit().putBoolean(key, true).apply(); return true; } @Override public void markOnly(@NonNull final String tag) { mPrefs.edit().putBoolean(KPrefsKeyPrefix + tag, true).apply(); } @Override public boolean unmark(@NonNull final String tag) { final String key = KPrefsKeyPrefix + tag; if (! mPrefs.getBoolean(key, false)) return false; mPrefs.edit().putBoolean(key, false).apply(); return true; } SharedPrefsBasedScopeImpl(final SharedPreferences prefs) { mPrefs = prefs; // Migrate legacy entries SharedPreferences.Editor editor = null; for (final String key : prefs.getAll().keySet()) { if (! key.startsWith(KPrefsKeyPrefixLegacy)) continue; if (editor == null) editor = prefs.edit(); try { editor.putBoolean(KPrefsKeyPrefix + key.substring(KPrefsKeyPrefixLegacy.length()), ! prefs.getBoolean(key, true)); } catch (final ClassCastException ignored) {} editor.remove(key); } if (editor != null) editor.apply(); } private final SharedPreferences mPrefs; }
package com.sksamuel.jqm4gwt.form; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.ScheduledCommand; import com.google.gwt.event.dom.client.BlurEvent; import com.google.gwt.event.dom.client.BlurHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.InlineLabel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.UIObject; import com.google.gwt.user.client.ui.Widget; import com.sksamuel.jqm4gwt.JQMCommon; import com.sksamuel.jqm4gwt.JQMContext; import com.sksamuel.jqm4gwt.Mobile; import com.sksamuel.jqm4gwt.form.elements.JQMFormWidget; import com.sksamuel.jqm4gwt.form.validators.NotNullOrEmptyValidator; import com.sksamuel.jqm4gwt.form.validators.Validator; /** * @author Stephen K Samuel samspade79@gmail.com 12 Jul 2011 21:36:02 * <br> * A {@link JQMForm} is a standard GWT panel that offers extra * functionality for quick building of input forms. The framework offers * built in validation and error reporting and simplified submission * processing. * <br> * Any {@link JQMSubmit} widgets that are added will be automatically * wired to submit this form. Alternatively, any widget can be set to * programatically submit the form by invoking submit(); */ public class JQMForm extends FlowPanel { /** For example icon can be added: "ui-icon-alert ui-btn-icon-left" **/ public static String globalValidationErrorStyles; private static final String STYLE_OK_VALIDATED = "jqm4gwt-fieldvalidated"; private static final String STYLE_ERRORCONTAIN = "jqm4gwt-errorcontain"; private static final String STYLE_ERROR_TYPE = "jqm4gwt-errortype-"; private static final String STYLE_FORM_REQUIRED = "jqm4gwt-form-required"; private static final String STYLE_FORM_VALIDATOR = "jqm4gwt-form-validator-"; private static final String JQM4GWT_ERROR_LABEL_STYLENAME = "jqm4gwt-error"; private static final String JQM4GWT_GENERAL_ERROR_LABEL_STYLENAME = "jqm4gwt-general-error"; /** The amount to adjust error scroll by so the error is not right at very top */ private static final int ERROR_SCROLL_OFFSET = 80; private final FlowPanel generalErrors = new FlowPanel(); private final List<Label> errors = new ArrayList<Label>(); /** * The SubmissionHandler is invoked when the form is successfully submitted. */ private SubmissionHandler<?> submissionHandler; /** A mapping between the validators and the labels they use to show errors */ private final Map<Validator, Label> validatorLabels = new HashMap<Validator, Label>(); /** A map containing the widgets and the validators that should be invoked on those */ private final Map<JQMFormWidget, Collection<Validator>> widgetValidators = new HashMap<JQMFormWidget, Collection<Validator>>(); /** * A map containing the validators and the elements/widgets that should * have the class changed depending on the result of the validation */ private final Map<Validator, Widget> notifiedWidgets = new HashMap<Validator, Widget>(); protected JQMForm(SubmissionHandler<?> handler) { this(); setSubmissionHandler(handler); } /** * Constructor used by UiBinder. A SubmissionHandler must be set before calling submit. */ public JQMForm() { setStyleName("jqm4gwt-form"); add(generalErrors); } public SubmissionHandler<?> getSubmissionHandler() { return submissionHandler; } public void setSubmissionHandler(SubmissionHandler<?> submissionHandler) { this.submissionHandler = submissionHandler; } /** * Add the given submit button to the form and automatically have it set * to submit the form on a click event. */ protected void add(JQMSubmit submit) { super.add(submit); submit.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { submit(); } }); } /** * Adds the given widget and sets it to be required. Then this field will * be checked to ensure it has a value set before the form will be * submitted. In effect, setting a field to required adds an implicit * "not null or empty" validator. */ public void addRequired(JQMFormWidget widget) { addRequired(widget, true); } public void addRequired(JQMFormWidget widget, boolean immediate) { addRequired(widget, "This field cannot be empty", immediate); } public void addRequired(JQMFormWidget widget, String msg) { addRequired(widget, msg, true); } public void addRequired(JQMFormWidget widget, String msg, boolean immediate) { add(widget); setRequired(widget, msg, immediate); } /** * This method will automatically add a label element which will be made * visible with an error message when validate is called on this field and * fails. * <br> * The label element will be located immediately after the supplied widget * (as first sibling). * <br> * If the widget is not null then the an onBlur handler will be registered * that will trigger validation for this validator only. * * @param widget the element to which the error message should be * associated with. If this param is null then the error will * be added as a generic error. * @param validator the validator that will perform the validation */ @Deprecated public void addValidator(JQMFormWidget widget, Validator validator) { addValidator(validator, widget); } /** * see addValidator(null, validator); */ public void addValidator(Validator validator) { addValidator(validator, (JQMFormWidget) null); } public void addValidator(Validator validator, boolean immediate, JQMFormWidget... firingWidgets) { addValidator(null, validator, immediate, firingWidgets); } public void addValidator(Validator validator, JQMFormWidget... firingWidgets) { addValidator(null, validator, true, firingWidgets); } private void addErrorLabel(Validator validator, Label label) { errors.add(label); // keep a list of the errors for easily iteration later validatorLabels.put(validator, label); // connect the label and the validator } /** * Adds a validator and binds it to the collection of widgets. The widget * list can be empty. * * @param validator the validator that will be invoked * @param notifiedWidget the widget that will be notified of the error. If null * then the firing widget will be used. * @param firingWidgets the list of widgets that will fire the validator * @param immediate - if true then validator will be called during firingWidgets onBlur() event * @param positionErrorAfter - optional, if defined then error label will be placed * right after this widget, otherwise it will be added as the current last one. */ public void addValidator(Widget notifiedWidget, Validator validator, boolean immediate, Widget positionErrorAfter, JQMFormWidget... firingWidgets) { boolean labelAdded = false; if (firingWidgets != null) { for (JQMFormWidget w : firingWidgets) { Label la = w.addErrorLabel(); if (la == null) continue; labelAdded = true; addErrorLabel(validator, la); } } if (!labelAdded) { Label label = new InlineLabel(); // create a label that will show the validation error label.setStyleName(JQM4GWT_ERROR_LABEL_STYLENAME); if (globalValidationErrorStyles != null && !globalValidationErrorStyles.isEmpty()) { JQMCommon.addStyleNames(label, globalValidationErrorStyles); } label.setVisible(false); addErrorLabel(validator, label); if (positionErrorAfter == null) { // add the error label to the document as the next child of this form container add(label); } else { boolean inserted = false; Widget w = positionErrorAfter; while (w != null) { int i = getWidgetIndex(w); if (i >= 0) { i++; // next after w while (i < getWidgetCount()) { Widget wi = getWidget(i); if (wi instanceof Label && JQMCommon.hasStyle(wi, JQM4GWT_ERROR_LABEL_STYLENAME)) { i++; // next after previous errors } else { break; } } insert(label, i); inserted = true; break; } w = w.getParent(); } if (!inserted) add(label); } } registerValidatorWithFiringWidgets(validator, firingWidgets, immediate); boolean required = validator instanceof NotNullOrEmptyValidator; String validatorClass = STYLE_FORM_VALIDATOR + getShortClassName(validator.getClass()); if (notifiedWidget != null) { notifiedWidgets.put(validator, notifiedWidget); notifiedWidget.getElement().addClassName(validatorClass); if (required) notifiedWidget.getElement().addClassName(STYLE_FORM_REQUIRED); } else if (firingWidgets != null) { for (JQMFormWidget w : firingWidgets) { w.asWidget().getElement().addClassName(validatorClass); if (required) w.asWidget().getElement().addClassName(STYLE_FORM_REQUIRED); } } } public void addValidator(Widget notifiedWidget, Validator validator, boolean immediate, JQMFormWidget... firingWidgets) { final Widget pos; if (firingWidgets != null && firingWidgets.length > 0) { pos = firingWidgets[firingWidgets.length - 1].asWidget(); } else { pos = notifiedWidget; } addValidator(notifiedWidget, validator, immediate, pos, firingWidgets); } public void clearValidationErrors() { for (Label label : validatorLabels.values()) { label.setVisible(false); } clearValidationStyles(); } /** * Remove all validation styles */ public void clearValidationStyles() { for (JQMFormWidget widget : widgetValidators.keySet()) { UIObject ui = widget.asWidget(); Collection<Validator> validators = widgetValidators.get(widget); for (Validator v : validators) { if (notifiedWidgets.containsKey(v)) ui = notifiedWidgets.get(v); removeStyles(v, ui); } } } private int getFirstErrorOffset() { for (Label label : errors) { if (label.isVisible()) { return JQMContext.getTop(label.getElement()); } } return 0; } public void hideFormProcessingDialog() { Mobile.hideLoadingDialog(); } private void registerValidatorWithFiringWidget(final JQMFormWidget widget, Validator validator, boolean immediate) { // add a blur handler to call validate on this widget but only if // this is the first time this widget has been registered with a validator if (immediate) if (widgetValidators.get(widget) == null) widget.addBlurHandler(new BlurHandler() { @Override public void onBlur(BlurEvent event) { validate(widget); } }); if (widgetValidators.get(widget) == null) { widgetValidators.put(widget, new ArrayList<Validator>()); } widgetValidators.get(widget).add(validator); } private void registerValidatorWithFiringWidgets(Validator validator, JQMFormWidget[] widgets, boolean immediate) { if (widgets != null) for (JQMFormWidget widget : widgets) { registerValidatorWithFiringWidget(widget, validator, immediate); } } private static String getShortClassName(Class<?> clazz) { if (clazz == null) return null; String s = clazz.getName(); int p = s.lastIndexOf('.'); if (p >= 0) return s.substring(p + 1); else return s; } private static void removeStyles(Validator validator, UIObject ui) { ui.removeStyleName(STYLE_ERROR_TYPE + getShortClassName(validator.getClass())); ui.removeStyleName(STYLE_ERRORCONTAIN); ui.removeStyleName(STYLE_OK_VALIDATED); } protected void scrollToFirstError() { int y = getFirstErrorOffset() - ERROR_SCROLL_OFFSET; Mobile.silentScroll(y); } /** * Set a general error on the form. */ public void setError(String string) { Label errorLabel = new Label(string); errorLabel.setStyleName(JQM4GWT_ERROR_LABEL_STYLENAME); errorLabel.addStyleName(JQM4GWT_GENERAL_ERROR_LABEL_STYLENAME); generalErrors.add(errorLabel); Window.scrollTo(0, 0); } /** * Sets the given widget to be required with a custom message. Then this * field will be checked to ensure it has a value set before the form will be submitted. * <br> * In effect, setting a field to required adds an implicit "not null or empty" validator. */ public void setRequired(JQMFormWidget widget, String msg) { setRequired(widget, msg, true); } public void setRequired(JQMFormWidget widget, String msg, boolean immediate) { addValidator(new NotNullOrEmptyValidator(widget, msg), immediate, widget); } public void showFormProcessingDialog(String msg) { Mobile.showLoadingDialog(msg); } /** * This method is invoked when the form is ready for submission. Typically * this method would be called from one of your submission buttons * automatically but it is possible to invoke it programmatically. * <br> * Before validation, the general errors are cleared. * <br> * If the validation phase is passed the the submission handler will be * invoked. Before the handler is invoked, the page loading dialog will be * shown so that async requests can complete in the background. * <br> * The {@link SubmissionHandler} must hide the loading dialog by calling * hideFormProcessingDialog() on the form or by calling Mobile.hideLoadingDialog() */ public void submit(String... submitMsgs) { if (submissionHandler == null) throw new IllegalStateException( "No SubmissionHandler has been set for this Form and it is in an invalid " + "state for submit() until one has been defined."); generalErrors.clear(); boolean validated = validate(); if (validated) { String s = null; if (submitMsgs.length > 0) s = submitMsgs[0]; if (s == null || s.isEmpty()) s = "Submitting form"; showFormProcessingDialog(s); @SuppressWarnings("unchecked") SubmissionHandler<JQMForm> h = (SubmissionHandler<JQMForm>) submissionHandler; h.onSubmit(this); } else { scrollToFirstError(); } } /** * Perform validation for all validators, setting error messages where appropriate. * * @return true if validation was successful for all validators, otherwise false. */ public boolean validate() { boolean validated = true; for (JQMFormWidget widget : widgetValidators.keySet()) { if (!validate(widget)) validated = false; } return validated; } /** * Performs validation for a single widget, first resetting all validation * messages on that widget. */ protected boolean validate(JQMFormWidget widget) { boolean validated = true; Collection<Validator> validators = widgetValidators.get(widget); for (Validator v : validators) if (!validate(v, widget.asWidget())) validated = false; return validated; } /** * Perform validation for a single validator * * @param ui the {@link UIObject} to change the stylesheet on * @return true if this validator was successfully applied or false otherwise */ protected boolean validate(Validator validator, UIObject ui) { if (notifiedWidgets.containsKey(validator)) ui = notifiedWidgets.get(validator); String msg = validator.validate(); if (msg == null || msg.length() == 0) { validationStyles(validator, null, ui, true); return true; } else { validationStyles(validator, msg, ui, false); return false; } } private void validationStyles(Validator validator, String msg, UIObject ui, boolean pass) { removeStyles(validator, ui); final Label label = validatorLabels.get(validator); if (pass) { // delay cleaning to allow normal button click processing Scheduler.get().scheduleEntry(new ScheduledCommand() { @Override public void execute() { label.setText(null); label.setVisible(false); } }); } else { label.setVisible(true); label.setText(msg); ui.addStyleName(STYLE_ERROR_TYPE + getShortClassName(validator.getClass())); } if (ui.getStyleName().contains(STYLE_ERROR_TYPE)) { ui.addStyleName(STYLE_ERRORCONTAIN); } else { ui.addStyleName(STYLE_OK_VALIDATED); } } }
package org.opennms.netmgt.provision.detector.simple.support; import org.apache.mina.core.session.IoSession; import org.opennms.core.utils.LogUtils; import org.opennms.netmgt.provision.detector.simple.request.LineOrientedRequest; import org.opennms.netmgt.provision.detector.simple.response.LineOrientedResponse; import org.opennms.netmgt.provision.support.BaseDetectorHandler; public class TcpDetectorHandler extends BaseDetectorHandler<LineOrientedRequest, LineOrientedResponse> { @Override public void sessionOpened(IoSession session) throws Exception { Object request = getConversation().getRequest(); if(!getConversation().hasBanner() && request != null) { session.write(request); }else if(!getConversation().hasBanner() && request == null) { LogUtils.infof(this, "TCP session was opened, no banner was expected, and there are no more pending requests. Setting service detection to true."); getFuture().setServiceDetected(true); session.close(true); } } }
package verification.platu.partialOrders; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import lpn.parser.ExprTree; import lpn.parser.Place; import lpn.parser.Transition; import lpn.parser.LpnDecomposition.LpnProcess; import verification.platu.main.Options; public class StaticSets { private Transition curTran; private HashSet<Transition> disableSet; private HashSet<Transition> disableByStealingToken; //private ArrayList<ExprTree> conjunctsOfEnabling; private ArrayList<HashSet<Transition>> otherTransSetCurTranEnablingTrue; private HashSet<Transition> curTranSetOtherTranEnablingFalse; // A set of transitions (with associated LPNs) whose enabling condition can become false due to executing curTran's assignments. private HashSet<Transition> otherTransSetCurNonPersistentCurTranEnablingFalse; // A set of transitions (with associated LPNs) whose enabling condition can become false due to executing another transition's assignments. private HashSet<Transition> modifyAssignment; private String PORdebugFileName; private FileWriter PORdebugFileStream; private BufferedWriter PORdebugBufferedWriter; private HashMap<Transition, LpnProcess> allTransToLpnProcs; public StaticSets(Transition curTran, HashMap<Transition, LpnProcess> allTransToLpnProcs) { this.curTran = curTran; this.allTransToLpnProcs = allTransToLpnProcs; disableSet = new HashSet<Transition>(); disableByStealingToken = new HashSet<Transition>(); curTranSetOtherTranEnablingFalse = new HashSet<Transition>(); otherTransSetCurNonPersistentCurTranEnablingFalse = new HashSet<Transition>(); otherTransSetCurTranEnablingTrue = new ArrayList<HashSet<Transition>>(); modifyAssignment = new HashSet<Transition>(); if (Options.getDebugMode()) { PORdebugFileName = Options.getPrjSgPath() + Options.getLogName() + "_" + Options.getPOR() + "_" + Options.getCycleClosingMthd() + "_" + Options.getCycleClosingAmpleMethd() + ".dbg"; try { PORdebugFileStream = new FileWriter(PORdebugFileName, true); } catch (IOException e) { e.printStackTrace(); } PORdebugBufferedWriter = new BufferedWriter(PORdebugFileStream); } } /** * Build a set of transitions that curTran can disable. * @param curLpnIndex */ public void buildCurTranDisableOtherTransSet() { // Test if curTran can disable other transitions by stealing their tokens. buildConflictSet(); // Test if curTran can disable other transitions by executing its assignments. // This excludes any transitions that are in the same process as curTran, and the process is a state machine. if (!curTran.getAssignments().isEmpty()) { ArrayList<Transition> transInOneStateMachine = new ArrayList<Transition>(); if (allTransToLpnProcs.get(curTran).getStateMachineFlag()) { transInOneStateMachine = allTransToLpnProcs.get(curTran).getProcessTransitions(); } for (Transition anotherTran : allTransToLpnProcs.keySet()) { if (curTran.equals(anotherTran) || transInOneStateMachine.contains(anotherTran)) continue; ExprTree anotherTranEnablingTree = anotherTran.getEnablingTree(); if (anotherTranEnablingTree != null && (anotherTranEnablingTree.getChange(curTran.getAssignments())=='F' || anotherTranEnablingTree.getChange(curTran.getAssignments())=='f' || anotherTranEnablingTree.getChange(curTran.getAssignments())=='X')) { if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile(curTran.getLpn().getLabel() + "(" + curTran.getLabel() + ") can disable " + anotherTran.getLpn().getLabel() + "(" + anotherTran.getLabel() + "). " + anotherTran.getLabel() + "'s enabling condition (" + anotherTranEnablingTree + "), may become false due to firing of " + curTran.getLabel() + "."); if (anotherTranEnablingTree.getChange(curTran.getAssignments())=='F') writeStringWithEndOfLineToPORDebugFile("Reason is " + anotherTran.getLabel() + "_enablingTree.getChange(" + curTran.getLabel() + ".getAssignments()) = F."); if (anotherTranEnablingTree.getChange(curTran.getAssignments())=='f') writeStringWithEndOfLineToPORDebugFile("Reason is " + anotherTran.getLabel() + "_enablingTree.getChange(" + curTran.getLabel() + ".getAssignments()) = f."); if (anotherTranEnablingTree.getChange(curTran.getAssignments())=='X') writeStringWithEndOfLineToPORDebugFile("Reason is " + anotherTran.getLabel() + "_enablingTree.getChange(" + curTran.getLabel() + ".getAssignments()) = X."); } curTranSetOtherTranEnablingFalse.add(anotherTran); } } } disableSet.addAll(disableByStealingToken); disableSet.addAll(curTranSetOtherTranEnablingFalse); } /** * Build a set of transitions that disable curTran. * @param allTransitionsToLpnProcesses */ public void buildOtherTransDisableCurTranSet() { // Test if other transition(s) can disable curTran by stealing their tokens. buildConflictSet(); // Test if other transitions can disable curTran by executing their assignments. // This excludes any transitions that are in the same process as curTran, and the process is a state machine. if (!curTran.isPersistent()) { // If curTran is persistent, when it becomes enabled, // it can not be disabled if another transition sets its enabling condition to false. // Dependent calculation on curTran happens when curTran is enabled. ArrayList<Transition> transInOneStateMachine = new ArrayList<Transition>(); if (allTransToLpnProcs.get(curTran).getStateMachineFlag()) { transInOneStateMachine = allTransToLpnProcs.get(curTran).getProcessTransitions(); } for (Transition anotherTran : allTransToLpnProcs.keySet()) { if (curTran.equals(anotherTran) || transInOneStateMachine.contains(anotherTran)) continue; if (!anotherTran.getAssignments().isEmpty()) { ExprTree curTranEnablingTree = curTran.getEnablingTree(); if (curTranEnablingTree != null && (curTranEnablingTree.getChange(anotherTran.getAssignments())=='F' || curTranEnablingTree.getChange(anotherTran.getAssignments())=='f' || curTranEnablingTree.getChange(anotherTran.getAssignments())=='X')) { if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile(curTran.getLpn().getLabel() + "(" + curTran.getLabel() + ") can be disabled by " + anotherTran.getLpn().getLabel() + "(" + anotherTran.getLabel() + "). " + curTran.getLabel() + "'s enabling condition (" + curTranEnablingTree + "), may become false due to firing of " + anotherTran.getLabel() + "."); if (curTranEnablingTree.getChange(anotherTran.getAssignments())=='F') writeStringWithEndOfLineToPORDebugFile("Reason is " + curTran.getLabel() + "_enablingTree.getChange(" + anotherTran.getLabel() + ".getAssignments()) = F."); if (curTranEnablingTree.getChange(anotherTran.getAssignments())=='f') writeStringWithEndOfLineToPORDebugFile("Reason is " + curTran.getLabel() + "_enablingTree.getChange(" + anotherTran.getLabel() + ".getAssignments()) = f."); if (curTranEnablingTree.getChange(anotherTran.getAssignments())=='X') writeStringWithEndOfLineToPORDebugFile("Reason is " + curTran.getLabel() + "_enablingTree.getChange(" + anotherTran.getLabel() + ".getAssignments()) = X."); } otherTransSetCurNonPersistentCurTranEnablingFalse.add(anotherTran); } } } } disableSet.addAll(disableByStealingToken); disableSet.addAll(otherTransSetCurNonPersistentCurTranEnablingFalse); buildModifyAssignSet(); disableSet.addAll(modifyAssignment); } public void buildConflictSet() { if (curTran.hasConflictSet()) { if (!tranFormsSelfLoop()) { if (allTransToLpnProcs.get(curTran).getStateMachineFlag()) { outerloop:for (Transition tranInConflict : curTran.getConflictSet()) { // In a state machine, if tranInConflict and curTran have disjoint enabling conditions, // they are not dependent on each other. // Temporary solution: compare each conjunct to decide if they are disjoint. // Each conjunct in comparison only allow single literal or the negation of a literal. // TODO: Need a (DPLL) SAT solver to decide if they are disjoint. if (!curTran.getConjunctsOfEnabling().isEmpty()) { // Assume buildConjunctsOfEnabling(term) was called previously for curTran and tranInConflict. for (ExprTree conjunctOfCurTran : curTran.getConjunctsOfEnabling()) { for (ExprTree conjunctOfTranInConflict : tranInConflict.getConjunctsOfEnabling()) { if (conjunctOfCurTran.getVars().size()==1 && conjunctOfTranInConflict.getVars().size()==1 && conjunctOfCurTran.getVars().equals(conjunctOfTranInConflict.getVars())) { ExprTree clause = new ExprTree(conjunctOfCurTran, conjunctOfTranInConflict, "&&", 'l'); HashMap<String, String> assign = new HashMap<String, String>(); assign.put(conjunctOfCurTran.getVars().get(0), "0"); if (clause.evaluateExpr(assign) == 0.0) { assign.put(conjunctOfCurTran.getVars().get(0), "1"); if (clause.evaluateExpr(assign) == 0.0) { continue outerloop; } } } } } } disableByStealingToken.add(tranInConflict); } } else { for (Transition tranInConflict : curTran.getConflictSet()) { disableByStealingToken.add(tranInConflict); } } if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile(curTran.getLpn().getLabel() + "(" + curTran.getLabel() + ") can cause dependency relation by stealing tokens from these transitions:"); for (Transition t : disableByStealingToken) { writeStringToPORDebugFile(t.getLpn().getLabel() + "(" + t.getLabel() + "), "); } writeStringWithEndOfLineToPORDebugFile(""); } } } } private boolean tranFormsSelfLoop() { boolean isSelfLoop = false; Place[] curPreset = curTran.getPreset(); Place[] curPostset = curTran.getPostset(); for (Place preset : curPreset) { for (Place postset : curPostset) { if (preset == postset) { isSelfLoop = true; break; } } if (isSelfLoop) break; } return isSelfLoop; } // /** // * Construct a set of transitions that can make the enabling condition of curTran true, by executing their assignments. // */ // public void buildEnableBySettingEnablingTrue() { // for (Integer lpnIndex : allTransitions.keySet()) { // Transition[] allTransInOneLpn = allTransitions.get(lpnIndex); // for (int i = 0; i < allTransInOneLpn.length; i++) { // if (curTran.equals(allTransInOneLpn[i])) // continue; // Transition anotherTran = allTransInOneLpn[i]; // ExprTree curTranEnablingTree = curTran.getEnablingTree(); // if (curTranEnablingTree != null // && (curTranEnablingTree.getChange(anotherTran.getAssignments())=='T' // || curTranEnablingTree.getChange(anotherTran.getAssignments())=='t' // || curTranEnablingTree.getChange(anotherTran.getAssignments())=='X')) { // enableBySettingEnablingTrue.add(new Transition(lpnIndex, anotherTran.getIndex())); // if (Options.getDebugMode()) { // writeStringWithEndOfLineToPORDebugFile(curTran.getName() + " can be enabled by " + anotherTran.getName() + ". " // + curTran.getName() + "'s enabling condition (" + curTranEnablingTree + "), may become true due to firing of " // + anotherTran.getName() + "."); // if (curTranEnablingTree.getChange(anotherTran.getAssignments())=='T') // writeStringWithEndOfLineToPORDebugFile("Reason is " + curTran.getName() + "_enablingTree.getChange(" + anotherTran.getName() + ".getAssignments()) = T."); // if (curTranEnablingTree.getChange(anotherTran.getAssignments())=='t') // writeStringWithEndOfLineToPORDebugFile("Reason is " + curTran.getName() + "_enablingTree.getChange(" + anotherTran.getName() + ".getAssignments()) = t."); // if (curTranEnablingTree.getChange(anotherTran.getAssignments())=='X') // writeStringWithEndOfLineToPORDebugFile("Reason is " + curTran.getName() + "_enablingTree.getChange(" + anotherTran.getName() + ".getAssignments()) = X."); // public void buildModifyAssignSet() { //// for every transition curTran in T, where T is the set of all transitions, we check t (t != curTran) in T, //// (1) intersection(VA(curTran), supportA(t)) != empty //// (2) intersection(VA(t), supportA(curTran)) != empty //// (3) intersection(VA(t), VA(curTran) != empty //// VA(t0) : set of variables being assigned to (left hand side of the assignment) in transition t0. //// supportA(t0): set of variables appearing in the expressions assigned to the variables of t0 (right hand side of the assignment). // for (Integer lpnIndex : allTransitions.keySet()) { // Transition[] allTransInOneLpn = allTransitions.get(lpnIndex); // for (int i = 0; i < allTransInOneLpn.length; i++) { // if (curTran.equals(allTransInOneLpn[i])) // continue; // Transition anotherTran = allTransInOneLpn[i]; // for (String v : curTran.getAssignTrees().keySet()) { // for (ExprTree anotherTranAssignTree : anotherTran.getAssignTrees().values()) { // if (anotherTranAssignTree != null && anotherTranAssignTree.containsVar(v)) { // modifyAssignment.add(new Transition(lpnIndex, anotherTran.getIndex())); // if (Options.getDebugMode()) { //// System.out.println("Variable " + v + " in " + curTran.getName() //// + " may change the right hand side of assignment " + anotherTranAssignTree + " in " + anotherTran.getName()); // for (ExprTree curTranAssignTree : curTran.getAssignTrees().values()) { // for (String v : anotherTran.getAssignTrees().keySet()) { // if (curTranAssignTree != null && curTranAssignTree.containsVar(v)) { // modifyAssignment.add(new Transition(lpnIndex, anotherTran.getIndex())); // if (Options.getDebugMode()) { //// System.out.println("Variable " + v + " in " + anotherTran.getName() //// + " may change the right hand side of assignment " + curTranAssignTree + " in " + anotherTran.getName()); // for (String v1 : curTran.getAssignTrees().keySet()) { // for (String v2 : anotherTran.getAssignTrees().keySet()) { // if (v1.equals(v2)) { // modifyAssignment.add(new Transition(lpnIndex, anotherTran.getIndex())); // if (Options.getDebugMode()) { //// System.out.println("Variable " + v1 + " are assigned in " + curTran.getName() + " and " + anotherTran.getName()); /** * Construct a set of transitions that can make the enabling condition of curTran true, by executing their assignments. */ public void buildOtherTransSetCurTranEnablingTrue() { ExprTree curTranEnablingTree = curTran.getEnablingTree(); if (curTranEnablingTree != null) {// || curTranEnablingTree.toString().equals("TRUE") || curTranEnablingTree.toString().equals("FALSE"))) { //buildConjunctsOfEnabling(curTranEnablingTree, conjunctsOfEnabling); if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("Transition " + curTran.getLpn().getLabel() + "(" + curTran.getLabel() + ")'s enabling tree is " + curTranEnablingTree.toString() + " and getOp() returns " + curTranEnablingTree.getOp()); writeStringWithEndOfLineToPORDebugFile(curTran.getLpn().getLabel() + "(" + curTran.getLabel() + ")'s enabling transition has the following terms: "); for (int i1=0; i1<curTran.getConjunctsOfEnabling().size(); i1++) { writeStringWithEndOfLineToPORDebugFile(curTran.getConjunctsOfEnabling().get(i1).toString()); } } if (!curTran.getConjunctsOfEnabling().isEmpty()) { for (int index=0; index<curTran.getConjunctsOfEnabling().size(); index++) { ExprTree conjunct = curTran.getConjunctsOfEnabling().get(index); HashSet<Transition> transCanEnableConjunct = new HashSet<Transition>(); for (Transition anotherTran : allTransToLpnProcs.keySet()) { if (curTran.equals(anotherTran)) continue; if (conjunct.getChange(anotherTran.getAssignments())=='T' || conjunct.getChange(anotherTran.getAssignments())=='t' || conjunct.getChange(anotherTran.getAssignments())=='X') { transCanEnableConjunct.add(anotherTran); if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile(curTran.getLpn().getLabel() + "(" + curTran.getLabel() + ")'s conjunct (" + conjunct.toString() + ") in its enabling condition (" + curTranEnablingTree + ") can be set to true by " + anotherTran.getLabel() + ". "); if (conjunct.getChange(anotherTran.getAssignments())=='T') writeStringWithEndOfLineToPORDebugFile("The reason is conjunct.getChange(" + anotherTran.getLabel() + ".getAssignments()) = T."); if (conjunct.getChange(anotherTran.getAssignments())=='t') writeStringWithEndOfLineToPORDebugFile("The reason is conjunct.getChange(" + anotherTran.getLabel() + ".getAssignments()) = t."); if (conjunct.getChange(anotherTran.getAssignments())=='X') writeStringWithEndOfLineToPORDebugFile("The reason is conjunct.getChange(" + anotherTran.getLabel() + ".getAssignments()) = X."); } } } otherTransSetCurTranEnablingTrue.add(index, transCanEnableConjunct); } } } } public HashSet<Transition> getModifyAssignSet() { return modifyAssignment; } public HashSet<Transition> getDisableSet() { return disableSet; } public HashSet<Transition> getOtherTransDisableCurTranSet() { HashSet<Transition> otherTransDisableCurTranSet = new HashSet<Transition>(); otherTransDisableCurTranSet.addAll(otherTransSetCurNonPersistentCurTranEnablingFalse); otherTransDisableCurTranSet.addAll(disableByStealingToken); otherTransDisableCurTranSet.addAll(modifyAssignment); return otherTransDisableCurTranSet; } public HashSet<Transition> getCurTranDisableOtherTransSet() { HashSet<Transition> curTranDisableOtherTransSet = new HashSet<Transition>(); curTranDisableOtherTransSet.addAll(disableByStealingToken); curTranDisableOtherTransSet.addAll(curTranSetOtherTranEnablingFalse); return curTranDisableOtherTransSet; } public ArrayList<HashSet<Transition>> getOtherTransSetCurTranEnablingTrue() { return otherTransSetCurTranEnablingTrue; } public Transition getTran() { return curTran; } /* For every transition curTran in T, where T is the set of all transitions, we check t (t != curTran) in T, (1) intersection(VA(curTran), supportA(t)) != empty (2) intersection(VA(t), supportA(curTran)) != empty (3) intersection(VA(t), VA(curTran) != empty VA(t0) : set of variables being assigned to (left hand side of the assignment) in transition t0. supportA(t0): set of variables appearing in the expressions assigned to the variables of t0 (right hand side of the assignment). */ public void buildModifyAssignSet() { ArrayList<Transition> transInOneStateMachine = new ArrayList<Transition>(); if (allTransToLpnProcs.get(curTran).getStateMachineFlag()) { transInOneStateMachine = allTransToLpnProcs.get(curTran).getProcessTransitions(); } for (Transition anotherTran : allTransToLpnProcs.keySet()) { if (curTran.equals(anotherTran) || transInOneStateMachine.contains(anotherTran)) // curTran does not have "modify assignments" problem with all transitions in the same process, if the process is a state machine. continue; for (String v : curTran.getAssignTrees().keySet()) { for (ExprTree anotherTranAssignTree : anotherTran.getAssignTrees().values()) { if (anotherTranAssignTree != null && anotherTranAssignTree.containsVar(v)) { modifyAssignment.add(anotherTran); if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("Variable " + v + " in " + curTran.getLpn().getLabel() + "(" + curTran.getLabel() + ")" + " may change the right hand side of assignment " + anotherTranAssignTree + " in " + anotherTran.getLabel()); } } } } for (ExprTree curTranAssignTree : curTran.getAssignTrees().values()) { for (String v : anotherTran.getAssignTrees().keySet()) { if (curTranAssignTree != null && curTranAssignTree.containsVar(v)) { modifyAssignment.add(anotherTran); if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("Variable " + v + " in " + anotherTran.getLpn().getLabel() + "(" + anotherTran.getLabel() + ")" + " may change the right hand side of assignment " + curTranAssignTree + " in " + anotherTran.getLabel()); } } } } for (String v1 : curTran.getAssignTrees().keySet()) { for (String v2 : anotherTran.getAssignTrees().keySet()) { if (v1.equals(v2) && !curTran.getAssignTree(v1).equals(anotherTran.getAssignTree(v2))) { modifyAssignment.add(anotherTran); if (Options.getDebugMode()) { writeStringWithEndOfLineToPORDebugFile("Variable " + v1 + " are assigned in " + curTran.getLpn().getLabel() + "(" + curTran.getLabel() + ") and " + anotherTran.getLpn().getLabel() + "(" + anotherTran.getLabel() + ")"); } } } } } } private void writeStringWithEndOfLineToPORDebugFile(String string) { try { PORdebugBufferedWriter.append(string); PORdebugBufferedWriter.newLine(); PORdebugBufferedWriter.flush(); } catch (IOException e) { e.printStackTrace(); } } private void writeStringToPORDebugFile(String string) { try { PORdebugBufferedWriter.append(string); //PORdebugBufferedWriter.newLine(); PORdebugBufferedWriter.flush(); } catch (IOException e) { e.printStackTrace(); } } // public HashSet<Transition> getEnableSet() { // HashSet<Transition> enableSet = new HashSet<Transition>(); // enableSet.addAll(enableByBringingToken); // enableSet.addAll(enableBySettingEnablingTrue); // return enableSet; // private void printIntegerSet(HashSet<Integer> integerSet, String setName) { // if (!setName.isEmpty()) // System.out.print(setName + ": "); // if (integerSet == null) { // System.out.println("null"); // else if (integerSet.isEmpty()) { // System.out.println("empty"); // else { // for (Iterator<Integer> curTranDisableIter = integerSet.iterator(); curTranDisableIter.hasNext();) { // Integer tranInDisable = curTranDisableIter.next(); // System.out.print(lpn.getAllTransitions()[tranInDisable] + " "); // System.out.print("\n"); }
package org.atlasapi.content; import java.util.Comparator; import java.util.Iterator; import java.util.Map; import org.joda.time.DateTime; import com.google.common.base.Strings; import com.google.common.collect.ImmutableMap; public enum SortKey { ADAPTER("95") { @Override protected String generateFrom(Item item) { if(item.sortKey() != null) { return prefix + item.sortKey(); } return null; } }, SERIES_EPISODE("85") { @Override protected String generateFrom(Item item) { if(item instanceof Episode) { Episode episode = (Episode) item; if(episode.getEpisodeNumber() != null && episode.getSeriesNumber() != null) { return SortKey.SERIES_EPISODE.append(String.format("%06d%06d",episode.getSeriesNumber(),episode.getEpisodeNumber())); } } return null; } }, BROADCAST("75") { @Override protected String generateFrom(Item item) { Iterator<Broadcast> broadcasts = item.getBroadcasts().iterator(); if (broadcasts.hasNext()) { DateTime firstBroadcast = broadcasts.next().getTransmissionTime(); while (broadcasts.hasNext()) { DateTime transmissionTime = broadcasts.next().getTransmissionTime(); if (transmissionTime.isBefore(firstBroadcast)) { firstBroadcast = transmissionTime; } } return BROADCAST.append(String.format("%019d",firstBroadcast.getMillis())); } return null; } }, EPISODE("55") { @Override protected String generateFrom(Item item) { if (item instanceof Episode) { Episode episode = (Episode) item; if (episode.getEpisodeNumber() != null) { return EPISODE.append(String.format("%010d", episode.getEpisodeNumber())); } } return null; } }, DEFAULT("11") { @Override protected String generateFrom(Item item) { return this.prefix; } }; protected String prefix; SortKey(String prefix) { this.prefix = prefix; } protected abstract String generateFrom(Item item); private String append(String key) { return prefix + key; } public static String keyFrom(Item item) { for (SortKey sortKey : SortKey.values()) { String key = sortKey.generateFrom(item); if(key != null) { return key; } } return "11"; } public static class SortKeyOutputComparator implements Comparator<String> { @Override public int compare(String sk1, String sk2) { if(Strings.isNullOrEmpty(sk1)) { sk1 = DEFAULT.prefix; } if(Strings.isNullOrEmpty(sk2)) { sk2 = DEFAULT.prefix; } if (sk1.equals("99")) { return 1; } if (sk2.equals("99")) { return -1; } sk1 = prefixMap.containsKey(keyPrefix(sk1)) ? transformPrefix(sk1) : sk1; sk2 = prefixMap.containsKey(keyPrefix(sk2)) ? transformPrefix(sk2) : sk2; return sk2.compareTo(sk1); } private static final Map<String, String> prefixMap = ImmutableMap.of( "99", "11", "10", "95", "20", "85", "30", "75" ); public String transformPrefix(String input) { return prefixMap.get(keyPrefix(input)) + input.substring(2); } public String keyPrefix(String input) { return input.substring(0, 2); } } }
package de.onyxbits.remotekeyboard; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Scanner; import android.content.Context; import android.content.res.AssetManager; import android.content.res.Resources; import android.os.PowerManager; import android.util.Log; import net.wimpi.telnetd.io.BasicTerminalIO; import net.wimpi.telnetd.io.TerminalIO; import net.wimpi.telnetd.io.terminal.ColorHelper; import net.wimpi.telnetd.io.toolkit.Label; import net.wimpi.telnetd.io.toolkit.Statusbar; import net.wimpi.telnetd.io.toolkit.Titlebar; import net.wimpi.telnetd.net.Connection; import net.wimpi.telnetd.net.ConnectionEvent; import net.wimpi.telnetd.shell.Shell; public class TelnetEditorShell implements Shell { public static final String TAG = "TelnetEditorShell"; protected static TelnetEditorShell self; private Titlebar titleBar; private Statusbar statusBar; private Label content; private BasicTerminalIO m_IO; public TelnetEditorShell() { } @Override public void connectionIdle(ConnectionEvent ce) { } @Override public void connectionTimedOut(ConnectionEvent ce) { } @Override public void connectionLogoutRequest(ConnectionEvent ce) { } @Override public void connectionSentBreak(ConnectionEvent ce) { } /** * Disconnect from remote by closing the socket * * @throws IOException */ protected void disconnect() throws IOException { m_IO.close(); } @Override public void run(Connection con) { m_IO = con.getTerminalIO(); // Ensure the screen does not go off while we are connected. PowerManager pm = (PowerManager) RemoteKeyboardService.self .getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wakeLock = pm.newWakeLock( PowerManager.FULL_WAKE_LOCK, TAG); wakeLock.acquire(); Resources res = RemoteKeyboardService.self.getResources(); RemoteKeyboardService.self.updateNotification(con.getConnectionData() .getInetAddress()); try { // Make the terminal window look pretty/informative. titleBar = new Titlebar(m_IO, "titlebar"); titleBar.setTitleText(res.getString(R.string.terminal_title)); titleBar.setAlignment(Titlebar.ALIGN_LEFT); titleBar.setForegroundColor(ColorHelper.WHITE); titleBar.setBackgroundColor(ColorHelper.BLUE); content = new Label(m_IO, "content"); content.setLocation(0, 2); statusBar = new Statusbar(m_IO, "statusbar"); statusBar.setStatusText(res.getString(R.string.terminal_statusbar)); statusBar.setAlignment(Titlebar.ALIGN_LEFT); statusBar.setForegroundColor(ColorHelper.WHITE); statusBar.setBackgroundColor(ColorHelper.BLUE); showText(getWelcomeScreen()); int in; InputAction inputAction = new InputAction(); inputAction.myService = RemoteKeyboardService.self; ActionRunner actionRunner = new ActionRunner(); Sequencer sequencer = new Sequencer(); // Main loop starts here while (true) { in = m_IO.read(); if (in == TerminalIO.IOERROR || in == TerminalIO.HANDLED) { // NOTE: TerminalIO.read() internally transforms LOGOUTREEQUEST // into HANDLED. break; } if (in == TerminalIO.ESCAPE) { // Did we read an escape sequence? in = sequencer.interpret(in); while (in == Sequencer.INCOMPLETE) { in = sequencer.interpret(m_IO.read()); if (in == Sequencer.UNKNOWN) { break; } } } else { // It's likely a printable character (potentially UTF8 multi byte). byte[] sequence = sequencer.getBuffer(in); sequence[0] = (byte) in; for (int i = 1; i < sequence.length; i++) { sequence[i] = (byte) m_IO.read(); } inputAction.printable = new String(sequence); } // Terminals interpret ASCII control characters and ANSI escape // sequences, so we have to set this either way. inputAction.function = in; actionRunner.setAction(inputAction); RemoteKeyboardService.self.handler.post(actionRunner); actionRunner.waitResult(); } // End of main loop. m_IO.eraseScreen(); m_IO.flush(); } catch (EOFException e) { // User disconnected disgracefully -> don't care. } catch (IOException e) { //Log.w(TAG, e); } finally { RemoteKeyboardService.self.updateNotification(null); wakeLock.release(); self = null; } } /** * Put some text in the area between title and statusbar * * @param text * what to display */ public void showText(String text) { try { m_IO.eraseScreen(); content.setText(text); titleBar.draw(); content.draw(); statusBar.draw(); m_IO.setCursor(m_IO.getRows() - 1, m_IO.getColumns() - 1); m_IO.flush(); } catch (IOException e) { Log.w(TAG, e); } } /** * Produce a welcome screen * * @return text to dump on the screen on session startup */ private String getWelcomeScreen() { try { RemoteKeyboardService myService = RemoteKeyboardService.self; AssetManager assetManager = myService.getResources().getAssets(); InputStream inputStream = assetManager.open("welcomescreen.txt"); Scanner s = new Scanner(inputStream).useDelimiter("\\A"); return s.next(); } catch (Exception exp) { Log.w(TAG, exp); } return ""; } public static Shell createShell() { self = new TelnetEditorShell(); return self; } }
package com.orhanobut.hawk; import android.text.TextUtils; import java.security.GeneralSecurityException; /** * Provides AES algorithm * * @author Orhan Obut */ final class AesEncryption implements Encryption { /** * Key used to look up stored generated salt values, not the actual salt * Never ever change this value since it will break backward compatibility in terms of keeping previous data */ private static final String KEY_STORAGE_SALT = "asdf3242klj"; private AesCbcWithIntegrity.SecretKeys secretKeys; private String salt; private Storage storage; private Logger logger; /** * Create an AesEncryption with a randomly generated salt value * @param logger Logger instance * @param storage Storage * @param password Encryption password */ AesEncryption(Logger logger, Storage storage, String password) { this(logger, storage, password, null); } /** * Create an AesEncryption with a custom salt value * @param logger Logger instance * @param storage Storage * @param password Encryption password * @param salt Custom salt value (pass {@code null} to generate a random one) */ AesEncryption(Logger logger, Storage storage, String password, String salt) { if (logger == null) { throw new NullPointerException("Logger may not be null"); } if (TextUtils.isEmpty(salt)) { this.salt = storage.get(KEY_STORAGE_SALT); } else { this.salt = salt; } this.logger = logger; this.storage = storage; generateSecretKey(password); } @Override public String encrypt(byte[] value) { if (value == null) { return null; } String result = null; try { AesCbcWithIntegrity.CipherTextIvMac civ = AesCbcWithIntegrity.encrypt(value, secretKeys); result = civ.toString(); } catch (GeneralSecurityException e) { logger.d(e.getMessage()); } return result; } @Override public byte[] decrypt(String value) { if (value == null) { return null; } byte[] result = null; try { AesCbcWithIntegrity.CipherTextIvMac civ = getCipherTextIvMac(value); result = AesCbcWithIntegrity.decrypt(civ, secretKeys); } catch (GeneralSecurityException e) { logger.d(e.getMessage()); } return result; } @Override public boolean reset() { return storage.clear(); } private AesCbcWithIntegrity.CipherTextIvMac getCipherTextIvMac(String cipherText) { return new AesCbcWithIntegrity.CipherTextIvMac(cipherText); } /** * Gets the secret keys by using salt and password. * If not provided, a salt is generated and stored in the storage */ private void generateSecretKey(String password) { try { // No salt provided, generate and store a random one if (TextUtils.isEmpty(salt)) { salt = AesCbcWithIntegrity.saltString(AesCbcWithIntegrity.generateSalt()); storage.put(KEY_STORAGE_SALT, salt); } secretKeys = AesCbcWithIntegrity.generateKeyFromPassword(password, salt.getBytes()); } catch (GeneralSecurityException e) { throw new RuntimeException(e); } } public String getSalt() { return salt; } public AesCbcWithIntegrity.SecretKeys getSecretKeys() { return secretKeys; } }
package org.jboss.webbeans.xml; import java.io.IOException; import java.io.InputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.net.URL; import java.util.ArrayList; 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 javax.annotation.Named; import javax.annotation.Stereotype; import javax.context.ScopeType; import javax.inject.DefinitionException; import javax.inject.DeploymentException; import javax.inject.DeploymentType; import javax.interceptor.InterceptorBindingType; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import org.jboss.webbeans.introspector.AnnotatedClass; import org.jboss.webbeans.introspector.AnnotatedField; import org.jboss.webbeans.log.Log; import org.jboss.webbeans.log.Logging; import org.jboss.webbeans.xml.checker.bean.BeanElementChecker; import org.jboss.webbeans.xml.checker.bean.ext.JmsResourceElementChecker; import org.jboss.webbeans.xml.checker.bean.ext.ResourceElementChecker; import org.jboss.webbeans.xml.checker.bean.ext.SessionBeanElementChecker; import org.jboss.webbeans.xml.checker.bean.ext.SimpleBeanElementChecker; import org.jboss.webbeans.xml.checker.beanchildren.ext.NotSimpleBeanChildrenChecker; import org.jboss.webbeans.xml.checker.beanchildren.ext.SimpleBeanChildrenChecker; public class XmlParser { private static Log log = Logging.getLog(XmlParser.class); private final XmlEnvironment environment; private List<BeanElementChecker> beanElementCheckers = new ArrayList<BeanElementChecker>(); private boolean haveAnyDeployElement = false; private Map<String, Set<String>> packagesMap = new HashMap<String, Set<String>>(); public XmlParser(XmlEnvironment environment) { this.environment = environment; } public void parse() { for (URL url : environment.getBeansXmlUrls()) { Document document = createDocument(url); if (document != null) { parseForArrays(document); parseForAnnotationTypes(document); parseForBeans(document); parseForDeploy(document); } } } private void parseForArrays(Document document) { Element root = document.getRootElement(); checkChildrenForArray(root); } private void checkChildrenForArray(Element element) { Iterator<?> childIterator = element.elementIterator(); while(childIterator.hasNext()) { Element child = (Element)childIterator.next(); if(child.getName().equalsIgnoreCase(XmlConstants.ARRAY)) { if(child.elements().size() != 1) throw new DefinitionException("<Array> element must have only one child"); Element arrayChild = (Element)child.elements().get(0); ParseXmlHelper.loadElementClass(arrayChild, Object.class, environment, packagesMap); } else checkChildrenForArray(child); } } private void parseForAnnotationTypes(Document document) { Element root = document.getRootElement(); List<Class<? extends Annotation>> bindingTypes = new ArrayList<Class<? extends Annotation>>(); List<Class<? extends Annotation>> interceptorBindingTypes = new ArrayList<Class<? extends Annotation>>(); List<Class<? extends Annotation>> stereotypes = new ArrayList<Class<? extends Annotation>>(); Iterator<?> elIterator = root.elementIterator(); while (elIterator.hasNext()) { Element element = (Element) elIterator.next(); boolean isBindingType = ParseXmlHelper.findElementsInEeNamespace(element, XmlConstants.BINDING_TYPE).size() > 0; boolean isInterceptorBindingType = ParseXmlHelper.findElementsInEeNamespace(element, XmlConstants.INTERCEPTOR_BINDING_TYPE).size() > 0; boolean isStereotype = ParseXmlHelper.findElementsInEeNamespace(element, XmlConstants.STEREOTYPE).size() > 0; if(isBindingType || isInterceptorBindingType || isStereotype) { Class<? extends Annotation> annotationType = ParseXmlHelper.loadAnnotationClass(element, Annotation.class, environment, packagesMap); if(isBindingType) bindingTypes.add(annotationType); if(isInterceptorBindingType) { interceptorBindingTypes.add(annotationType); checkForInterceptorBindingTypeChildren(element); } if(isStereotype) { stereotypes.add(annotationType); checkForStereotypeChildren(element); } } } ParseXmlHelper.checkForUniqueElements(bindingTypes); ParseXmlHelper.checkForUniqueElements(interceptorBindingTypes); ParseXmlHelper.checkForUniqueElements(stereotypes); } private void parseForBeans(Document document) { List<AnnotatedClass<?>> beanClasses = new ArrayList<AnnotatedClass<?>>(); List<Element> beanElements = findBeans(document); for (Element beanElement : beanElements) { AnnotatedClass<?> beanClass = ParseXmlHelper.loadElementClass(beanElement, Object.class, environment, packagesMap); checkBeanElement(beanElement, beanClass); checkProduces(beanElement, beanClass); beanClasses.add(beanClass); } environment.getClasses().addAll(beanClasses); } private void parseForDeploy(Document document) { Element root = document.getRootElement(); Iterator<?> elIterator = root.elementIterator(); while (elIterator.hasNext()) { Element element = (Element) elIterator.next(); if (ParseXmlHelper.isJavaEeNamespace(element) && element.getName().equalsIgnoreCase(XmlConstants.DEPLOY)) environment.getEnabledDeploymentTypes().addAll(obtainDeploymentTypes(element)); } } private Document createDocument(URL url) { try { InputStream xmlStream; xmlStream = url.openStream(); if (xmlStream.available() == 0) { return null; } SAXReader reader = new SAXReader(); Document document = reader.read(xmlStream); fullFillPackagesMap(document); return document; } catch (IOException e) { String message = "Can not open stream for " + url; log.debug(message, e); throw new DefinitionException(message, e); } catch (DocumentException e) { String message = "Error during the processing of a DOM4J document for " + url; log.debug(message, e); throw new DefinitionException(message, e); } } private void checkForInterceptorBindingTypeChildren(Element element) { Iterator<?> elIterator = element.elementIterator(); while (elIterator.hasNext()) { Element child = (Element)elIterator.next(); Class<? extends Annotation> clazz = ParseXmlHelper.loadAnnotationClass(child, Annotation.class, environment, packagesMap); if(!child.getName().equalsIgnoreCase(XmlConstants.INTERCEPTOR_BINDING_TYPE) && !clazz.isAnnotationPresent(InterceptorBindingType.class)) throw new DefinitionException("Direct child <" + child.getName() + "> of interceptor binding type <" + element.getName() + "> declaration must be interceptor binding type"); } } private void checkForStereotypeChildren(Element stereotypeElement) { Iterator<?> elIterator = stereotypeElement.elementIterator(); while (elIterator.hasNext()) { Element stereotypeChild = (Element)elIterator.next(); Class<? extends Annotation> stereotypeClass = ParseXmlHelper.loadAnnotationClass(stereotypeChild, Annotation.class, environment, packagesMap); if(stereotypeChild.getName().equalsIgnoreCase(XmlConstants.STEREOTYPE) || stereotypeClass.isAnnotationPresent(ScopeType.class) || stereotypeClass.isAnnotationPresent(DeploymentType.class) || stereotypeClass.isAnnotationPresent(InterceptorBindingType.class) || stereotypeClass.isAnnotationPresent(Named.class)) continue; throw new DefinitionException("Direct child <" + stereotypeChild.getName() + "> of stereotype <" + stereotypeElement.getName() + "> declaration must be scope type, or deployment type, or interceptor binding type, or javax.annotation.Named"); } } private List<Element> findBeans(Document document) { List<Element> beans = new ArrayList<Element>(); Element root = document.getRootElement(); Iterator<?> elIterator = root.elementIterator(); while (elIterator.hasNext()) { Element element = (Element) elIterator.next(); if (checkBeanElementName(element) && checkBeanElementChildrenNames(element)) beans.add(element); } return beans; } private boolean checkBeanElementName(Element element) { if (ParseXmlHelper.isJavaEeNamespace(element) && (element.getName().equalsIgnoreCase(XmlConstants.DEPLOY) || element.getName().equalsIgnoreCase(XmlConstants.INTERCEPTORS) || element.getName().equalsIgnoreCase(XmlConstants.DECORATORS))) return false; return true; } private boolean checkBeanElementChildrenNames(Element element) { Iterator<?> elIterator = element.elementIterator(); while (elIterator.hasNext()) { Element child = (Element) elIterator.next(); if (ParseXmlHelper.isJavaEeNamespace(child) && (child.getName().equalsIgnoreCase(XmlConstants.BINDING_TYPE) || child.getName().equalsIgnoreCase(XmlConstants.INTERCEPTOR_BINDING_TYPE) || child.getName().equalsIgnoreCase(XmlConstants.STEREOTYPE))) return false; } return true; } @SuppressWarnings("unchecked") // TODO Make this object orientated private List<Class<? extends Annotation>> obtainDeploymentTypes(Element element) { if (haveAnyDeployElement) throw new DefinitionException("<Deploy> element is specified more than once"); List<Element> deployElements = element.elements(); Set<Element> deployElementsSet = new HashSet<Element>(deployElements); if(deployElements.size() - deployElementsSet.size() != 0) throw new DefinitionException("The same deployment type is declared more than once"); List<Element> standardElements = ParseXmlHelper.findElementsInEeNamespace(element, XmlConstants.STANDARD); if (standardElements.size() == 0) throw new DeploymentException("The @Standard deployment type must be declared"); List<Class<? extends Annotation>> deploymentClasses = new ArrayList<Class<? extends Annotation>>(); List<Element> children = element.elements(); for (Element child : children) { Class<? extends Annotation> deploymentClass = ParseXmlHelper.loadAnnotationClass(child, Annotation.class, environment, packagesMap); if(!deploymentClass.isAnnotationPresent(DeploymentType.class)) throw new DefinitionException("<Deploy> child <" + child.getName() + "> must be a deployment type"); deploymentClasses.add(deploymentClass); } haveAnyDeployElement = true; return deploymentClasses; } private void checkBeanElement(Element beanElement, AnnotatedClass<?> beanClass) { beanElementCheckers.add(new JmsResourceElementChecker(new NotSimpleBeanChildrenChecker(environment, packagesMap))); beanElementCheckers.add(new ResourceElementChecker(new NotSimpleBeanChildrenChecker(environment, packagesMap))); beanElementCheckers.add(new SessionBeanElementChecker(new NotSimpleBeanChildrenChecker(environment, packagesMap), environment.getEjbDescriptors())); beanElementCheckers.add(new SimpleBeanElementChecker(new SimpleBeanChildrenChecker(environment, packagesMap), environment.getEjbDescriptors())); boolean isValidType = false; for(BeanElementChecker beanElementChecker : beanElementCheckers) { if(beanElementChecker.accept(beanElement, beanClass)) { beanElementChecker.checkBeanElement(beanElement, beanClass); isValidType = true; break; } } if(!isValidType) throw new DefinitionException("Can't determine type of bean element <" + beanElement.getName() + ">"); } private void checkProduces(Element beanElement, AnnotatedClass<?> beanClass) {//TODO: will refactor Iterator<?> beanIterator = beanElement.elementIterator(); while(beanIterator.hasNext()) { Element beanChild = (Element)beanIterator.next(); List<Element> producesElements = ParseXmlHelper.findElementsInEeNamespace(beanChild, XmlConstants.PRODUCES); if(producesElements.size() == 0) continue; if(producesElements.size() > 1) throw new DefinitionException("There is more than one child <Produces> element for <" + beanChild.getName() + "> element"); List<AnnotatedClass<?>> producesChildTypes = new ArrayList<AnnotatedClass<?>>(); Element producesElement = producesElements.get(0); Iterator<?> producesIt = producesElement.elementIterator(); while(producesIt.hasNext()) { Element producesChild = (Element)producesIt.next(); AnnotatedClass<?> producesChildClass = ParseXmlHelper.loadElementClass(producesChild, Object.class, environment, packagesMap); Class<?> producesChildType = producesChildClass.getRawType(); boolean isJavaClass = !producesChildType.isEnum() && !producesChildType.isPrimitive() && !producesChildType.isInterface(); boolean isInterface = producesChildType.isInterface() && !producesChildType.isAnnotation(); if(isJavaClass || isInterface) { producesChildTypes.add(producesChildClass); continue; } if(producesChildType.isAnnotation()) { if(producesChildClass.isAnnotationPresent(DeploymentType.class) || producesChildClass.isAnnotationPresent(ScopeType.class) || producesChildClass.isAnnotationPresent(Stereotype.class) || producesChildClass.isAnnotationPresent(Named.class)) continue; throw new DefinitionException("<" + producesChild.getName() + "> direct child of <Produces> element for <" + beanChild.getName() + "> in bean" + beanElement.getName() + "must be DeploymentType or ScopeType or Stereotype or Named"); } throw new DefinitionException("Only Java class, interface type and Java annotation type can be " + "direct child of <Produces> element for <" + beanChild.getName() + "> in bean" + beanElement.getName() + ". Element <" + producesChild.getName() + "> is incorrect"); } if(producesChildTypes.size() != 1) throw new DefinitionException("More than one or no one child element of <Produces> element for <" + beanChild.getName() + "> in bean" + beanElement.getName() + " represents a Java class or interface type"); AnnotatedClass<?> expectedType = producesChildTypes.get(0); Method beanMethod = null; AnnotatedField<?> beanField = beanClass.getDeclaredField(beanChild.getName(), expectedType); try { List<Class<?>> paramClassesList = new ArrayList<Class<?>>(); Iterator<?> beanChildIt = beanChild.elementIterator(); while(beanChildIt.hasNext()) { Element methodChild = (Element)beanChildIt.next(); if(methodChild.getName().equalsIgnoreCase(XmlConstants.PRODUCES)) continue; paramClassesList.add(ParseXmlHelper.loadElementClass(methodChild, Object.class, environment, packagesMap).getRawType()); } Class<?>[] paramClasses = (Class<?>[])paramClassesList.toArray(new Class[0]); beanMethod = beanClass.getRawType().getDeclaredMethod(beanChild.getName(), paramClasses); } catch (SecurityException e) {} catch (NoSuchMethodException e) {} if(beanField != null && beanMethod != null) throw new DefinitionException("Class '" + beanClass.getName() + "' has produser field and method with the same name '" + beanField.getName() + "'"); if(beanField != null) { if(beanChild.elements().size() > 1) throw new DefinitionException("There is more than one direct child element for producer field <" + beanChild.getName() + ">"); continue; } if(beanMethod != null) { Iterator<?> beanChildIt = producesElement.elementIterator(); while(beanChildIt.hasNext()) { Element element = (Element)beanChildIt.next(); if(!element.getName().equalsIgnoreCase(XmlConstants.PRODUCES) && ParseXmlHelper.findElementsInEeNamespace(beanChild, XmlConstants.INTERCEPTOR).size() == 0) throw new DefinitionException("Only Produces and interceptor binding types can be direct childs of a producer " + "method '" + beanChild.getName() + "' declaration in bean '" + beanElement.getName() + "'"); } continue; } throw new DefinitionException("A producer '" + beanChild.getName() + "' doesn't declared in '" + beanElement.getName() + "' class file as method or field"); } } private void fullFillPackagesMap(Document document) { Element root = document.getRootElement(); ParseXmlHelper.checkRootAttributes(root, packagesMap, environment); ParseXmlHelper.checkRootDeclaredNamespaces(root, packagesMap, environment); } }
package es.uvigo.esei.daa.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.util.LinkedList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import es.uvigo.esei.daa.entities.Event; public class EventDAO extends DAO { private final static Logger LOG = Logger.getLogger("EventDAO"); public Event get(int id) throws DAOException, IllegalArgumentException { try (final Connection conn = this.getConnection()) { final String query = "SELECT * FROM event WHERE id=?"; try (final PreparedStatement statement = conn.prepareStatement(query)) { statement.setInt(1, id); try (final ResultSet result = statement.executeQuery()) { if (result.next()) { return new Event( result.getInt("id"), result.getString("nameEvent"), result.getTimestamp("dateCreate"), result.getTimestamp("dateInit"), result.getTimestamp("dateFinal"), result.getString("description"), result.getString("category") ); } else { throw new IllegalArgumentException("Invalid id"); } } } } catch (SQLException e) { LOG.log(Level.SEVERE, "Error getting an event", e); throw new DAOException(e); } } public List<Event> list() throws DAOException { try (final Connection conn = this.getConnection()) { final String query = "SELECT * FROM event"; try (final PreparedStatement statement = conn.prepareStatement(query)) { try (final ResultSet result = statement.executeQuery()) { final List<Event> events = new LinkedList<>(); while (result.next()) { events.add(new Event( result.getInt("id"), result.getString("nameEvent"), result.getTimestamp("dateCreate"), result.getTimestamp("dateInit"), result.getTimestamp("dateFinal"), result.getString("description"), result.getString("category") )); } return events; } } } catch (SQLException e) { LOG.log(Level.SEVERE, "Error listing events", e); throw new DAOException(e); } } public void delete(int id) throws DAOException, IllegalArgumentException { try (final Connection conn = this.getConnection()) { final String query = "DELETE FROM event WHERE id=?"; try (final PreparedStatement statement = conn.prepareStatement(query)) { statement.setInt(1, id); if (statement.executeUpdate() != 1) { throw new IllegalArgumentException("Invalid id"); } } } catch (SQLException e) { LOG.log(Level.SEVERE, "Error deleting an event", e); throw new DAOException(e); } } public Event modify(int id,String nameEvent, Timestamp dateCreate, Timestamp dateInit, Timestamp dateFinal, String description, String category) throws DAOException, IllegalArgumentException { if ( nameEvent == null) { throw new IllegalArgumentException("name cannot be null"); } try (Connection conn = this.getConnection()) { ///Sentencia de modificacion, hacer cuando la bd este correcta final String query = "UPDATE event SET name=?, surname=? WHERE id=?"; try (PreparedStatement statement = conn.prepareStatement(query)) { statement.setString(1, nameEvent); statement.setString(2, dateCreate.toString()); statement.setString(3, dateInit.toString()); statement.setString(4, dateFinal.toString()); statement.setString(5, description); statement.setString(6, category); if (statement.executeUpdate() == 1) { return new Event(id, nameEvent, dateCreate,dateInit,dateFinal,description,category); } else { throw new IllegalArgumentException("id and name cannot be null"); } } } catch (SQLException e) { LOG.log(Level.SEVERE, "Error modifying an event", e); throw new DAOException(); } } public Event add(int id,String nameEvent, Timestamp dateCreate, Timestamp dateInit, Timestamp dateFinal, String description, String category)throws DAOException, IllegalArgumentException { if (nameEvent == null) { throw new IllegalArgumentException("name cannot be null"); } try (Connection conn = this.getConnection()) { final String query = "INSERT INTO event VALUES(null, ?, ?,?,?,?,?)"; try (PreparedStatement statement = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS)) { ///Comprobar que los tostring de los timestampo funcionen statement.setString(1, nameEvent); statement.setString(2, dateCreate.toString()); statement.setString(3, dateInit.toString()); statement.setString(4, dateFinal.toString()); statement.setString(5, description); statement.setString(6, category); if (statement.executeUpdate() == 1) { try (ResultSet resultKeys = statement.getGeneratedKeys()) { if (resultKeys.next()) { return new Event(resultKeys.getInt(1), nameEvent, dateCreate,dateInit,dateFinal,description,category); } else { LOG.log(Level.SEVERE, "Error retrieving inserted id"); throw new SQLException("Error retrieving inserted id"); } } } else { LOG.log(Level.SEVERE, "Error inserting value"); throw new SQLException("Error inserting value"); } } } catch (SQLException e) { LOG.log(Level.SEVERE, "Error adding an event", e); throw new DAOException(e); } } }
package de.lebk.madn.gui; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JComponent; public class BoardDice extends JComponent implements MouseListener { private int number = 0; private Color color = new Color(255, 255, 255);// new Color(239, 239, 239); protected Board board; public BoardDice(Board board) { super(); this.board = board; this.addMouseListener(this); } /** * Sets the number and updates the GUI * @param number */ public void setNumber(int number) { this.number = number; this.revalidate(); this.repaint(); } public void setColor(Color color) { this.color = color; this.revalidate(); this.repaint(); } public int getNumber() { return this.number; } /** * Draw the GUI * @param g */ public void paint(Graphics g) { super.paint(g); Graphics2D g2 = (Graphics2D) g; /** * here the colors will be prepared. The dice will be filled * with the original color of the current player. The border * an the points of the dice will be in the same color just * a bit darker. * Delta describes the difference of the border and point * color from the original color. */ float delta = 0.33f; Color background_color = new Color( Math.min(Math.round(this.color.getRed() * delta), 255), Math.min(Math.round(this.color.getGreen() * delta), 255), Math.min(Math.round(this.color.getBlue() * delta), 255) ); g2.setStroke(new BasicStroke(BoardElement.FIELD_BORDER_WIDTH)); /** * First we draw the dice with the original color as background. */ g2.setColor(this.color); g2.fillRoundRect(BoardElement.CIRCLE_PADDING, BoardElement.CIRCLE_PADDING, this.getWidth() - (2 * BoardElement.CIRCLE_PADDING), this.getHeight() - (2 * BoardElement.CIRCLE_PADDING), BoardElement.CIRCLE_PADDING, BoardElement.CIRCLE_PADDING); /** * After drawing the background we have to draw the border line * in the darker color. This color will be used to draw the * points on the dice as well then. */ g2.setColor(background_color); g2.drawRoundRect(BoardElement.CIRCLE_PADDING, BoardElement.CIRCLE_PADDING, this.getWidth() - (2 * BoardElement.CIRCLE_PADDING), this.getHeight() - (2 * BoardElement.CIRCLE_PADDING), BoardElement.CIRCLE_PADDING / 2, BoardElement.CIRCLE_PADDING / 2); this.drawPoints(g2, background_color); } protected void drawPoints(Graphics g2, Color point_color) { g2.setColor(point_color); int dotSize = (int)(this.getWidth() / 10); int number = this.number; // Top Left if(number >= 2) { this.drawPoint(g2, this.getWidth()/3-dotSize/2, this.getHeight()/3-dotSize/2, dotSize, dotSize); } // Top Center if(number >= 8) { this.drawPoint(g2, this.getWidth()/2-dotSize/2, this.getHeight()/3-dotSize/2, dotSize, dotSize); } // Top Right if(number >= 4) { this.drawPoint(g2, this.getWidth()/3*2-dotSize/2, this.getHeight()/3-dotSize/2, dotSize, dotSize); } // Middle Left if(number >= 6) { this.drawPoint(g2, this.getWidth()/3-dotSize/2, this.getHeight()/2-dotSize/2, dotSize, dotSize); } // Middle Center if(number % 2 == 1) { this.drawPoint(g2, this.getWidth()/2-dotSize/2, this.getHeight()/2-dotSize/2, dotSize, dotSize); } // Middle Right if(number >= 6) { this.drawPoint(g2, this.getWidth()/3*2-dotSize/2, this.getHeight()/2-dotSize/2, dotSize, dotSize); } // Bottom Left if(number >= 4) { this.drawPoint(g2, this.getWidth()/3-dotSize/2, this.getHeight()/3*2-dotSize/2, dotSize, dotSize); } // Bottom Center if(number >= 8) { this.drawPoint(g2, this.getWidth()/2-dotSize/2, this.getHeight()/3*2-dotSize/2, dotSize, dotSize); } // Bottom Right if(number >= 2) { this.drawPoint(g2, this.getWidth()/3*2-dotSize/2, this.getHeight()/3*2-dotSize/2, dotSize, dotSize); } } protected void drawPoint(Graphics g2, int x, int y, int width, int height) { g2.drawOval(x, y, width, height); g2.fillOval(x, y, width, height); } @Override public void mouseClicked(MouseEvent me) { this.board.useDice(); } @Override public void mouseEntered(MouseEvent me) { // Mouse is over the element } @Override public void mouseExited(MouseEvent me) { // Mouse left this element } @Override public void mousePressed(MouseEvent me) { // Mousekey pressed } @Override public void mouseReleased(MouseEvent me) { // Mousekey released } @Override public void paintComponent(Graphics g) { super.paintComponent(g); } @Override public String toString() { return String.format("Number: %d", this.number); } }
import uk.co.uwcs.choob.*; import uk.co.uwcs.choob.modules.*; import uk.co.uwcs.choob.support.*; import uk.co.uwcs.choob.support.events.*; import java.io.*; import java.net.*; import java.util.*; import java.util.regex.*; import java.text.*; import org.jibble.pircbot.Colors; public class Events { final Pattern events_pattern=Pattern.compile("(\\d+) \"([^\"]*)\" ([^ ]+) ([^ ]+) ([^ ]+) ([^ ]+) ([^ ]+) \"([^\"]*)\" \"((?:\\\\\"|\\\\\\\\|[^\"])*)\" \"((?:\\\\\"|\\\\\\\\|[^\"])*)\""); // Id: 1 2 3 4 5 6 7 8 9 10 // Name: id name start end <signup>code max current names</signup> desc. location private static final String announceChannel="#bots"; private static final long checkInterval=60000; // The crond job is run every minute. private Modules mods; private IRCInterface irc; private final URL eventsurl; private ArrayList<String[]> current; private final static int ID=1; private final static int NAME=2; private final static int START=3; private final static int END=4; private final static int SIGNUPNAMES=8; private final static int SIGNUPCURRENT=7; private final static int SIGNUPMAX=6; public String[] info() { return new String[] { "CompSoc events watcher/info plugin.", "The Choob Team", "choob@uwcs.co.uk", "$Rev$$Date$" }; } public Events(Modules mods, IRCInterface irc) throws ChoobError { this.mods = mods; this.irc = irc; try { eventsurl = new URL("http://faux.uwcs.co.uk/events.data"); } catch (MalformedURLException e) { throw new ChoobError("Error in constant data."); } mods.interval.callBack(null, checkInterval); } public void interval(Object param) throws ChoobException { ArrayList<String[]> ne=readEventsData(); if (current!=null && !current.equals(ne)) { ListIterator<String[]> ci=current.listIterator(); ListIterator<String[]> ni=ne.listIterator(); HashMap<Integer, String[]>curr=new HashMap<Integer, String[]>(); while (ci.hasNext()) { String c[]=ci.next(); curr.put(Integer.parseInt(c[ID]), new String[] {"","",c[2], c[3], c[4], c[5], c[6], c[7], c[8], c[9], c[10] }); // Strashmaps ftw. } while (ni.hasNext()) { String[] n=ni.next(); String[] c=curr.get(Integer.parseInt(n[ID])); if (c==null) irc.sendMessage(announceChannel, "New event! " + n[NAME] + " at " + n[10] + " in " + mods.util.timeMicroStamp((new Date(Long.parseLong(n[3])*(long)1000)).getTime() - (new Date()).getTime()) + "."); else { if (!c[SIGNUPCURRENT].equals(n[SIGNUPCURRENT])) { // OH MY GOD WHATTF HAXBQ! String[] cn=c[SIGNUPNAMES].split(","); String[] nn=n[SIGNUPNAMES].split(","); HashSet <String> q=new HashSet<String>(); HashSet <String> r=new HashSet<String>(); for (int i=0; i<cn.length; i++) q.add(cn[i].trim()); for (int i=0; i<nn.length; i++) r.add(nn[i].trim()); Iterator <String>it=q.iterator(); while (it.hasNext()) { Object o=it.next(); if (r.remove(o)) it.remove(); } it=r.iterator(); while (it.hasNext()) { Object o=it.next(); if (q.remove(o)) it.remove(); } StringBuilder sig=new StringBuilder(); it=q.iterator(); while (it.hasNext()) { String name=it.next(); if (name.length()>1) sig.append("-" + name + ", "); } it=r.iterator(); while (it.hasNext()) { String name=it.next(); if (name.length()>1) sig.append("+" + name + ", "); } String sigts=sig.toString(); if (sigts.length()>2) sigts=sigts.substring(0, sigts.length()-2); irc.sendMessage(announceChannel, "Signups for " + Colors.BOLD + n[NAME] + Colors.NORMAL + " (" + n[ID] + ") [" + mods.util.timeMicroStamp((new Date(Long.parseLong(n[3])*(long)1000)).getTime() - (new Date()).getTime()) + "] now " + n[SIGNUPCURRENT] + "/" + n[SIGNUPMAX] + " (" + sigts + ")."); } } } } current=ne; mods.interval.callBack(null, checkInterval); } private ArrayList<String[]> readEventsData() throws ChoobException { ArrayList<String[]> events=new ArrayList(); Matcher ma; try { ma=mods.scrape.getMatcher(eventsurl, checkInterval, events_pattern); } catch (IOException e) { throw new ChoobException("Error reading events data file."); } while (ma.find()) { String [] nine=ma.group(9).split("\\|"); events.add(0, new String[] {"", ma.group(1), ma.group(2), ma.group(3), ma.group(4), ma.group(5), ma.group(6), ma.group(7), ma.group(8), nine[0], ma.group(10), nine[1]}); } return events; } public String[] helpCommandInfo = { "Get info about a given event", "<Key>", "<Key> is a key to use for event searching" }; public void commandInfo(Message mes) throws ChoobException { String comp=mods.util.getParamString(mes).toLowerCase(); if (comp.equals("")) { irc.sendContextReply(mes, "Please name the event you want info on."); return; } ArrayList<String[]> events=readEventsData(); int c=events.size(); String rep=""; while (c { String[] ev= events.get(c); Date da=new Date(Long.parseLong(ev[3])*(long)1000); Date dat=new Date(Long.parseLong(ev[4])*(long)1000); boolean finished=(new Date()).compareTo(dat)>0; int eid=0; try { eid=Integer.parseInt(comp); } catch (NumberFormatException e) {} if (!finished) if (ev[2].toLowerCase().indexOf(comp)!=-1 || Integer.parseInt(ev[1])==eid) { irc.sendContextReply(mes, Colors.BOLD + ev[2] + Colors.NORMAL + " at " + ev[10] + " (" + ev[9] + ") (" + ev[1] + ") from " + (new SimpleDateFormat("EEEE d MMM H:mma").format(da)) + " to " + (new SimpleDateFormat("EEEE d MMM H:mma").format(dat)) + "." ); return; } } irc.sendContextReply(mes, "Event not found."); } public String[] helpCommandSignup = { "Get a signup link for a given event.", "<Key>", "<Key> is a key to use for event searching" }; public void commandSignup(Message mes) throws ChoobException { String comp=mods.util.getParamString(mes).toLowerCase(); if (comp.equals("")) { irc.sendContextReply(mes, "Please name the event you want info on."); return; } ArrayList<String[]> events=readEventsData(); int c=events.size(); String rep=""; System.out.println(comp); while (c { String[] ev= events.get(c); Date da=new Date(Long.parseLong(ev[3])*(long)1000); Date dat=new Date(Long.parseLong(ev[4])*(long)1000); boolean finished=(new Date()).compareTo(dat)>0; int eid=0; try { eid=Integer.parseInt(comp); } catch (NumberFormatException e) { } if (!finished) if (ev[2].toLowerCase().indexOf(comp)!=-1 || Integer.parseInt(ev[1])==eid) { if (!ev[5].equals("X") && !ev[5].equals("-")) irc.sendContextReply(mes, "Please use http: else { rep+="Event " + ev[1] + " matched, but does not accept sign-ups... "; continue; } return; } } irc.sendContextReply(mes, rep + "Event not found."); } public String[] helpCommandLink = { "Get an information link for a given event.", "<Key>", "<Key> is a key to use for event searching" }; public void commandLink(Message mes) throws ChoobException { String comp=mods.util.getParamString(mes).toLowerCase(); if (comp.equals("")) { irc.sendContextReply(mes, "Please name the event you want info on."); return; } ArrayList<String[]> events=readEventsData(); int c=events.size(); String rep=""; System.out.println(comp); int eid=0; try { eid=Integer.parseInt(comp); } catch (NumberFormatException e) { } while (c { String[] ev= events.get(c); Date da=new Date(Long.parseLong(ev[3])*(long)1000); Date dat=new Date(Long.parseLong(ev[4])*(long)1000); boolean finished=(new Date()).compareTo(dat)>0; if (!finished) if (ev[2].toLowerCase().indexOf(comp)!=-1 || Integer.parseInt(ev[1])==eid) { irc.sendContextReply(mes, "http: return; } } irc.sendContextReply(mes, rep + "Event not found."); } public String[] helpCommandSignups = { "Get the signups list for a given event.", "<Key>", "<Key> is a key to use for event searching" }; public void commandSignups(Message mes) throws ChoobException { String comp=mods.util.getParamString(mes).toLowerCase(); if (comp.equals("")) { irc.sendContextReply(mes, "Please name the event you want info on."); return; } ArrayList<String[]> events=readEventsData(); int c=events.size(); String rep=""; System.out.println(comp); int eid=0; try { eid=Integer.parseInt(comp); } catch (NumberFormatException e) { } while (c { String[] ev= events.get(c); Date da=new Date(Long.parseLong(ev[3])*(long)1000); Date dat=new Date(Long.parseLong(ev[4])*(long)1000); boolean finished=(new Date()).compareTo(dat)>0; if (!finished) if (ev[2].toLowerCase().indexOf(comp)!=-1 || Integer.parseInt(ev[1])==eid) { irc.sendContextReply(mes, "Signups for " + Colors.BOLD + ev[2] + Colors.NORMAL + (finished ? " (finished)" : "") + " at " + ev[10] + " (" + ev[1] + ")" + (!finished ? " [" + mods.util.timeMicroStamp(da.getTime() - (new Date()).getTime()) + "]" : "") + (!ev[6].equals("0") ? " [" + ev[7] + "/" + ev[6] + "]" : "") + ": " + ( mes instanceof PrivateEvent ? ev[8] : ev[8].replaceAll("([a-zA-Z])([^, ]+)","$1'$2") ) + "."); return; } } irc.sendContextReply(mes, rep + "Event not found."); } public String[] helpCommandList = { "Get a list of events.", }; public void commandList(Message mes) throws ChoobException { ArrayList<String[]> events=readEventsData(); int c=events.size(); if (c==0) { irc.sendContextReply(mes, "There are no events! :'("); return; } String rep=""; while (c { String[] ev= events.get(c); Date da=new Date(Long.parseLong(ev[START])*(long)1000); Date dat=new Date(Long.parseLong(ev[END])*(long)1000); final boolean finished=(new Date()).compareTo(dat)>0; final boolean inprogress=!finished && (new Date()).compareTo(da)>0; rep+=Colors.BOLD + ev[2] + Colors.NORMAL + (finished ? " (finished)" : "") + " at " + ev[10] + " (" + ev[1] + ")" + (!finished ? (inprogress ? " (" + Colors.BOLD + "on right now" + Colors.NORMAL + ", started " + mods.util.timeMicroStamp((new Date()).getTime() - da.getTime()) + " ago)" : " [" + mods.util.timeMicroStamp(da.getTime() - (new Date()).getTime()) + "]" ) : "" ) + (!ev[6].equals("0") ? " [" + ev[7] + "/" + ev[6] + "]" : "") + (c!=0 ? ", " : "."); } irc.sendContextReply(mes, "Events: " + rep); } }
package no.nordicsemi.actuators; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.media.AudioManager; import org.droidparts.annotation.inject.InjectSystemService; import org.json.JSONException; import org.json.JSONObject; import no.nordicsemi.R; import no.nordicsemi.models.Action; import no.nordicsemi.models.Rule; public class RingerActuator extends Actuator { public static final String MODE = "mode"; public static final String[] RINGER_MODES = new String[] { "Silent", "Vibrate", "Volume" }; @InjectSystemService AudioManager mAudioManager; @Override public String getDescription() { return "Change phone state"; } @Override public int getId() { return 2; } @Override public void actuate(JSONObject arguments) throws JSONException { if (arguments.has(MODE)) { mAudioManager.setRingerMode(arguments.getInt(MODE)); } else { throw new IllegalArgumentException("Arguments do not contain MODE"); } } @Override public AlertDialog getActuatorDialog(Context ctx, final Action action, final Rule rule, final ActuatorDialogFinishListener listener) { AlertDialog.Builder builder = new AlertDialog.Builder(ctx) .setTitle(getDescription()) .setItems(RINGER_MODES, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { int ringerMode; switch (which) { case 0: ringerMode = AudioManager.RINGER_MODE_SILENT; break; case 1: ringerMode = AudioManager.RINGER_MODE_VIBRATE; break; case 2: ringerMode = AudioManager.RINGER_MODE_NORMAL; break; default: throw new IllegalStateException(); } String arguments = Action.jsonStringBuilder(MODE, ringerMode); action.setArguments(arguments); rule.addAction(action); listener.onActuatorDialogFinish(action, rule); } }) .setNegativeButton(ctx.getString(R.string.abort), null); return builder.create(); } }
import uk.co.uwcs.choob.*; import uk.co.uwcs.choob.modules.*; import uk.co.uwcs.choob.support.*; import uk.co.uwcs.choob.support.events.*; import java.io.*; import java.net.*; import java.util.*; import java.util.regex.*; import java.text.*; import org.jibble.pircbot.Colors; public class Events { final Pattern events_pattern=Pattern.compile("(\\d+) \"([^\"]*)\" ([^ ]+) ([^ ]+) ([^ ]+) ([^ ]+) ([^ ]+) \"([^\"]*)\" \"((?:\\\\\"|\\\\\\\\|[^\"])*)\" \"((?:\\\\\"|\\\\\\\\|[^\"])*)\""); // Id: 1 2 3 4 5 6 7 8 9 10 // Name: id name start end <signup>code max current names</signup> desc. location enum SignupCodes { FINISHED , // X : finished HASSIGNUPS , // S : has signups (that aren't open yet) SIGNUPSMEM , // SN: non-guest signups open SIGNUPSOPEN, // SO: signups are open (for all) CANCELLED , // C : cancelled NOSIGNUPS , // - : no signups are required RUNNING , // R : running UNKNOWN , // : Anything else, ie. an error code. } /** A class for holding information about a single event */ private class EventItem { /** Constructor from strings, as will be fed from the events_pattern matches */ public EventItem( String sid, String sname, String sstart, String send, String ssignupCode, String ssignupMax, String ssignupCurrent, String ssignupNames, String sdesc, String slocation ) { id = parseId(sid); name = sname; start = convertTimestamp(sstart); end = (send.equals("-") ? start : convertTimestamp(send)); signupMax = Integer.parseInt(ssignupMax); signupCurrent = Integer.parseInt(ssignupCurrent); // ssignupCode comes as a short code (suprisingly enough) that is explained next to the enum above. Decode it: if (ssignupCode.equals("X")) signupCode = SignupCodes.FINISHED ; else if (ssignupCode.equals("S")) signupCode = SignupCodes.HASSIGNUPS ; else if (ssignupCode.equals("SN")) signupCode = SignupCodes.SIGNUPSMEM ; else if (ssignupCode.equals("SO")) signupCode = SignupCodes.SIGNUPSOPEN; else if (ssignupCode.equals("C")) signupCode = SignupCodes.CANCELLED ; else if (ssignupCode.equals("-")) signupCode = SignupCodes.NOSIGNUPS ; else if (ssignupCode.equals("R")) signupCode = SignupCodes.RUNNING ; else /* ssignupCode is unkown */ signupCode = SignupCodes.UNKNOWN ; // The description comes in as one string, pipe-seperated. // What happens if it contains strictly> 1 pipe? String [] descParts=sdesc.split("\\|"); if (descParts.length < 2) descParts = new String[] {"", ""}; // split acts unexpectedly with just "|", deal with it. shortdesc = descParts[0]; longdesc = descParts[1]; location = slocation; // The names come in in csv, break them up. signupNames = new ArrayList<String>(); for (String name : ssignupNames.split(", ")) signupNames.add(name); } private String name; private SignupCodes signupCode; public int id; public Date start; public Date end; public int signupMax; public int signupCurrent; public ArrayList<String> signupNames; public String shortdesc; public String longdesc; public String location; private Date convertTimestamp(String timestamp) { return new Date(Long.parseLong(timestamp)*(long)1000); } public boolean finished() { return signupCode == SignupCodes.FINISHED || (new Date()).compareTo(end) > 0; } public boolean cancelled() { return signupCode == SignupCodes.CANCELLED; } public boolean inprogress() { return signupCode == SignupCodes.RUNNING || !finished() && (new Date()).compareTo(start) > 0; } public String boldName() { return Colors.BOLD + name + Colors.NORMAL + (cancelled() ? " (" + Colors.BOLD + "cancelled!" + Colors.NORMAL + ")" : "") + (inprogress() && !cancelled() ? " (" + Colors.BOLD + "on right now!" + Colors.NORMAL + ")" : ""); } public String boldNameShortDetails() { return boldName() + " (" + id +") " + (!finished() && !cancelled() && !inprogress() ? "[" + microStampFromNow(start) + "]" : ""); } /** Note: This means that the event accepts /some/ signups, not necessary all */ public boolean acceptsSignups() { return signupCode == SignupCodes.SIGNUPSOPEN || signupCode == SignupCodes.SIGNUPSMEM; } } private enum Groups { _WHOLESTRING, ID, NAME, START, END, SIGNUPCODE, SIGNUPMAX, SIGNUPCURRENT, SIGNUPNAMES, DESC, LOCATION; public String getFromMatcher(Matcher ma) { return ma.group(ordinal()); } } public static final String announceChannel="#bots"; private static final long checkInterval=60000; // The crond job is run every minute. private Modules mods; private IRCInterface irc; private final URL eventsurl; private ArrayList<EventItem> current; public String[] info() { return new String[] { "CompSoc events watcher/info plugin.", "The Choob Team", "choob@uwcs.co.uk", "$Rev$$Date$" }; } public Events(Modules mods, IRCInterface irc) throws ChoobError { this.mods = mods; this.irc = irc; try { eventsurl = new URL("http://faux.uwcs.co.uk/events.data"); } catch (MalformedURLException e) { throw new ChoobError("Error in constant data."); } mods.interval.callBack(null, checkInterval); } private String microStampFromNow(Date d) { return mods.date.timeMicroStamp(d.getTime() - (new Date()).getTime()); } public void interval(Object param) throws ChoobException { ArrayList<EventItem> ne = readEventsData(); if (current!=null && !current.equals(ne)) { ListIterator<EventItem> ni = ne.listIterator(); // Generate a hashmap of current (ie. before the change) event ids -> eventitems. HashMap<Integer, EventItem>curr=new HashMap<Integer, EventItem>(); for (EventItem c : current) curr.put(c.id, c); // Now, go through the new items.. for (EventItem n : ne) { // Get the corresponding event from the old items EventItem corr=curr.get(n.id); if (corr==null) // It doesn't exist, notify people: irc.sendMessage(announceChannel, "New event! " + n.name + " at " + n.location + " in " + mods.date.timeMicroStamp(n.start.getTime() - (new Date()).getTime()) + "." ); else // The event existed, do the signups differ? if (!corr.signupNames.equals(n.signupNames)) { // Diff the lists. HashSet <String> beforeSet = new HashSet<String>(); HashSet <String> afterSet = new HashSet<String>(); // Create a set of names for each list, before (being the current names) and after (being the new ones). for (String name : corr.signupNames) beforeSet.add(name.trim()); for (String name : n.signupNames) afterSet.add(name.trim()); Iterator <String>it = beforeSet.iterator(); // Go through the list of names that's were there "before". If it exists in the "after" list, remove it from both. while (it.hasNext()) if (afterSet.remove(it.next())) it.remove(); StringBuilder sig=new StringBuilder(); // Now, anything left in "before" is not in "after", so it's been removed: for (String name : beforeSet) if (name.length()>1) sig.append("-").append(name).append(", "); // Same applies for "after", anything in here isn't in "before", so it's been added. for (String name : afterSet) if (name.length()>1) sig.append("+").append(name).append(", "); // Convert our stringbuilder to a String.. String sigts = sig.toString(); // If there's anything in the string. if (sigts.length()>2) { // Remove the trailing comma. sigts=sigts.substring(0, sigts.length()-2); // Announce the change. irc.sendMessage(announceChannel, "Signups for " + n.boldNameShortDetails() + " now " + n.signupCurrent + "/" + n.signupMax + " (" + sigts + ")." ); } } } } current = ne; mods.interval.callBack(null, checkInterval); } private ArrayList<EventItem> readEventsData() throws ChoobException { ArrayList<EventItem> events=new ArrayList<EventItem>(); Matcher ma; try { ma=mods.scrape.getMatcher(eventsurl, checkInterval, events_pattern); } catch (IOException e) { throw new ChoobException("Error reading events data file."); } while (ma.find()) events.add(new EventItem( Groups.ID .getFromMatcher(ma), Groups.NAME .getFromMatcher(ma), Groups.START .getFromMatcher(ma), Groups.END .getFromMatcher(ma), Groups.SIGNUPCODE .getFromMatcher(ma), Groups.SIGNUPMAX .getFromMatcher(ma), Groups.SIGNUPCURRENT.getFromMatcher(ma), Groups.SIGNUPNAMES .getFromMatcher(ma), Groups.DESC .getFromMatcher(ma), Groups.LOCATION .getFromMatcher(ma) )); return events; } public String[] helpCommandInfo = { "Get info about a given event", "<Key>", "<Key> is a key to use for event searching" }; public void commandInfo(Message mes) throws ChoobException { String comp=mods.util.getParamString(mes).toLowerCase(); if (comp.equals("")) { irc.sendContextReply(mes, "Please name the event you want info on."); return; } final int eid=parseId(comp); ArrayList<EventItem> events = readEventsData(); for (EventItem ev : events) if (!ev.finished()) if (ev.name.toLowerCase().indexOf(comp) != -1 || ev.id == eid) { final String signup; if (ev.signupMax != 0) { if (ev.signupCurrent != 0) signup = " Currently " + ev.signupCurrent + " signup" + (ev.signupCurrent == 1 ? "" : "s") + " out of " + ev.signupMax + "."; else signup = " Nobody has signed up yet" + (ev.acceptsSignups() ? " even though signups are open." : ", probably because signups aren't open yet!" ); } else signup=""; irc.sendContextReply(mes, ev.boldName() + " at " + ev.location + ( !"".equals(ev.shortdesc) ? " (" + ev.shortdesc + ")" : "") + " (" + ev.id + ") " + (ev.start == ev.end ? "at " + absoluteDateFormat(ev.start) : "from " + absoluteDateFormat(ev.start) + " to " + absoluteDateFormat(ev.end)) + "." + signup ); return; } irc.sendContextReply(mes, "Event not found."); } public String[] helpCommandSignup = { "Get a signup link for a given event.", "<Key>", "<Key> is a key to use for event searching" }; public void commandSignup(Message mes) throws ChoobException { String comp=mods.util.getParamString(mes).toLowerCase(); if (comp.equals("")) { irc.sendContextReply(mes, "Please name the event you want info on."); return; } final int eid=parseId(comp); ArrayList<EventItem> events = readEventsData(); StringBuilder rep = new StringBuilder(); for (EventItem ev : events) if (!ev.finished()) if (ev.name.toLowerCase().indexOf(comp) != -1 || ev.id == eid) { if (ev.acceptsSignups()) irc.sendContextReply(mes, "Please use http: ev.boldNameShortDetails() + "." ); else { rep.append(ev.boldNameShortDetails()).append(" matched, but is not currently accepting sign-ups... "); continue; } return; } irc.sendContextReply(mes, rep.toString() + "Event not found."); } public String[] helpCommandLink = { "Get an information link for a given event.", "<Key>", "<Key> is a key to use for event searching" }; public void commandLink(Message mes) throws ChoobException { String comp=mods.util.getParamString(mes).toLowerCase(); if (comp.equals("")) { irc.sendContextReply(mes, "Please name the event you want info on."); return; } final int eid=parseId(comp); ArrayList<EventItem> events=readEventsData(); for (EventItem ev : events) if (!ev.finished()) if (ev.name.toLowerCase().indexOf(comp) != -1 || ev.id == eid) { irc.sendContextReply(mes, "http: return; } irc.sendContextReply(mes, "Event not found."); } public String[] helpCommandSignups = { "Get the signups list for a given event.", "<Key>", "<Key> is a key to use for event searching" }; public void commandSignups(Message mes) throws ChoobException { String comp=mods.util.getParamString(mes).toLowerCase(); if (comp.equals("")) { irc.sendContextReply(mes, "Please name the event you want info on."); return; } final int eid=parseId(comp); ArrayList<EventItem> events = readEventsData(); for (EventItem ev : events) if (!ev.finished()) if (ev.name.toLowerCase().indexOf(comp) != -1 || ev.id == eid) { if (ev.signupCurrent == 0) irc.sendContextReply(mes, "No signups for " + ev.boldNameShortDetails() + " at " + ev.location + (ev.acceptsSignups() ? " even though signups are open." : ", probably because signups aren't open yet!" ) ); else irc.sendContextReply(mes, "Signups for " + ev.boldNameShortDetails() + " at " + ev.location + (ev.signupMax != 0 ? " [" + ev.signupCurrent + "/" + ev.signupMax + "]" : "") + ": " + nameList(ev.signupNames, mes, ev.signupMax, Colors.BOLD + "Reserves: " + Colors.NORMAL) + "." ); return; } irc.sendContextReply(mes, "Event not found."); } public String[] helpCommandList = { "Get a list of events.", }; public void commandList(Message mes) throws ChoobException { ArrayList<EventItem> events=readEventsData(); int c=events.size(); if (events.isEmpty()) { irc.sendContextReply(mes, "There are no events! :'("); return; } StringBuilder rep = new StringBuilder(); for (EventItem ev : events) { rep.append(ev.boldName()) .append(" at " + ev.location + " (" + ev.id + ")") .append(ev.inprogress() ? " (started " + mods.date.timeMicroStamp((new Date()).getTime() - ev.start.getTime()) + " ago)" : "") .append(ev.signupMax != 0 ? " [" + ev.signupCurrent + "/" + ev.signupMax + "]" : "") .append(--c != 0 ? ", " : "."); } irc.sendContextReply(mes, "Events: " + rep.toString()); } /** Convert an arraylist of names into a string, b'reaking them up to prevent pings if not in pm. */ private static String nameList(ArrayList<String> names, Message mes) { return nameList(names, mes, -1, ""); } private static String nameList(ArrayList<String> names, Message mes, int after, String message) { StringBuilder namelistb = new StringBuilder(); int i=0; for (String name : names) { if (i++ == after) namelistb.append(message); namelistb.append(name).append(", "); } String namelist = namelistb.toString(); // Remove the trailing commaspace. if (namelist.length() > 2) namelist = namelist.substring(0, namelist.length()-2); // If it's not in pm, break them up. if (!(mes instanceof PrivateEvent)) namelist = namelist.replaceAll("(?<![a-zA-Z])([a-zA-Z])(?!eserves)([^, ]+)","$1'$2"); return namelist; } /** Prettyprint a date */ private final static String absoluteDateFormat(Date da) { // Some definitions. final SimpleDateFormat formatter = new SimpleDateFormat("EEEE d MMM h:mma"); final SimpleDateFormat dayNameFormatter = new SimpleDateFormat("EEEE"); final Calendar cda = new GregorianCalendar(); cda.setTime(da); final Calendar cnow = new GregorianCalendar(); final Date now = cnow.getTime(); final Date midnight = new GregorianCalendar(cnow.get(Calendar.YEAR), cnow.get(Calendar.MONTH), cnow.get(Calendar.DAY_OF_MONTH), 24, 0, 0).getTime(); final Date midnightTommorow = new GregorianCalendar(cnow.get(Calendar.YEAR), cnow.get(Calendar.MONTH), cnow.get(Calendar.DAY_OF_MONTH), 48, 0, 0).getTime(); final Date endOfThisWeek = new GregorianCalendar(cnow.get(Calendar.YEAR), cnow.get(Calendar.MONTH), cnow.get(Calendar.DAY_OF_MONTH) + 7, 0, 0, 0).getTime(); // </definitions> if (da.compareTo(now) > 0) // It's in the future, we can cope with it. { if (da.compareTo(midnight) < 0) // It's before midnight tonight. return shortTime(cda) + " " + // 9pm (cda.get(Calendar.HOUR_OF_DAY) < 18 ? "today" : "tonight"); if (da.compareTo(midnightTommorow) < 0) // It's before midnight tommorow and not before midnight today, it's tommorow. return shortTime(cda) + // 9pm " tommorow " + // tommorow futurePeriodOfDayString(cda); // evening if (da.compareTo(endOfThisWeek) < 0) // It's not tommrow, but it is some time when the week-day names alone mean something. return shortTime(cda) + " " + // 9pm dayNameFormatter.format(da) + " " + // Monday futurePeriodOfDayString(cda); // evening } return formatter.format(da); } /** Convert a Calendar to "8pm", "7am", "7:30am" etc. */ private final static String shortTime(Calendar cda) { final SimpleDateFormat nomins = new SimpleDateFormat("ha"); final SimpleDateFormat wimins = new SimpleDateFormat("h:mma"); // Don't show the minutes if they're 0. if (cda.get(Calendar.MINUTE) != 0) return wimins.format(cda.getTime()).toLowerCase(); return nomins.format(cda.getTime()).toLowerCase(); } /** Work out if a calendar is in the morning, afternoon or evening. */ private final static String futurePeriodOfDayString(Calendar cda) { final int hour = cda.get(Calendar.HOUR_OF_DAY); if (hour < 12) return "morning"; if (hour < 18) return "afternoon"; return "evening"; } private static int parseId(String s) { try { return Integer.parseInt(s); } catch (NumberFormatException e) {} return 0; } }
package org.broad.igv; import java.io.*; import java.net.Socket; import java.net.UnknownHostException; /** * @author Jim Robinson * @date 11/3/11 */ public class Launcher { public static void main(String[] args) throws IOException { String file = null; String locus = null; String genome = null; String user = null; String memory = null; String index = null; for (String a : args) { String tokens[] = a.split("="); if (tokens.length == 2) { String key = tokens[0].toLowerCase(); if (key.equals("file")) { file = tokens[1]; } else if (key.equals("locus")) { locus = tokens[1]; } else if (key.equals("genome")) { genome = tokens[1]; } else if (key.equals("user")) { user = tokens[1]; } else if (key.equals("maxheapsize")) { memory = tokens[1]; } else if (key.equals("index")) { index = tokens[1]; } } } // TODO -- read port from igv preferences int port = 60151; boolean igvIsRunning = loadDirectly(port, file, locus, genome); if (!igvIsRunning) { StringBuffer buf = new StringBuffer("http: boolean firstArg = true; if (file != null) { String delim = firstArg ? "?" : "&"; buf.append(delim); buf.append("sessionURL="); buf.append(file); firstArg = false; } if (locus != null) { String delim = firstArg ? "?" : "&"; buf.append(delim); buf.append("locus="); buf.append(locus); firstArg = false; } if (genome != null) { String delim = firstArg ? "?" : "&"; buf.append(delim); buf.append("genome="); buf.append(genome); firstArg = false; } if (user != null) { String delim = firstArg ? "?" : "&"; buf.append(delim); buf.append("user="); buf.append(user); firstArg = false; } File jnlpFile = createJNLP(file, locus, genome, memory, index); System.out.println(jnlpFile.getAbsolutePath()); ProcessBuilder pb = new ProcessBuilder("javaws", jnlpFile.getAbsolutePath()); Process p = pb.start(); // TODO -- read from stderr and report any errors to user } System.exit(1); } private static boolean loadDirectly(int port, String file, String locus, String genome) throws IOException { boolean success; Socket socket = null; PrintWriter out = null; BufferedReader in = null; try { socket = new Socket("127.0.0.1", port); out = new PrintWriter(socket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); if (genome != null) { out.println("genome " + genome); String response = in.readLine(); } if (file != null) { out.println("load " + file); String response = in.readLine(); } if (locus != null) { out.println("goto " + locus); String response = in.readLine(); } success = true; } catch (UnknownHostException e) { success = false; } catch (IOException e) { success = false; } finally { if (in != null) in.close(); if (out != null) out.close(); if (socket != null) socket.close(); } return success; } private static File createJNLP(String file, String locus, String genome, String memory, String index) throws IOException { String tmp = System.getProperty("java.io.tmpdir"); if (tmp == null) tmp = "."; File tmpDir = new File(tmp); File f = new File(tmpDir, "igv" + System.currentTimeMillis() + ".jnlp"); InputStream is = null; PrintWriter pw = null; String maxMem = memory == null ? "1050m" : memory; try { is = Launcher.class.getResourceAsStream("jnlpTemplate.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(is)); pw = new PrintWriter(new BufferedWriter(new FileWriter(f))); String nextLine; while ((nextLine = br.readLine()) != null) { if (nextLine.contains("$ARGUMENTS")) { if (file != null) pw.println("<argument>" + file + "</argument>"); if (locus != null) pw.println("<argument>" + locus + "</argument>"); if (genome != null) pw.println("<argument>-g</argument><argument>" + genome + "</argument>"); if (index != null) pw.println("<argument>-i</argument><argument>" + index + "</argument>"); } else { pw.println(nextLine.replace("$MAXHEAP", maxMem)); } } } finally { if (is != null) is.close(); if (pw != null) pw.close(); } return f; } }
package com.exedio.cope.instrument; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.lang.reflect.Modifier; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.zip.CRC32; import java.util.zip.CheckedOutputStream; import com.exedio.cope.BooleanField; import com.exedio.cope.Feature; import com.exedio.cope.FinalViolationException; import com.exedio.cope.Item; import com.exedio.cope.ItemField; import com.exedio.cope.LengthViolationException; import com.exedio.cope.MandatoryViolationException; import com.exedio.cope.RangeViolationException; import com.exedio.cope.SetValue; import com.exedio.cope.Type; import com.exedio.cope.UniqueViolationException; import com.exedio.cope.Wrapper; import com.exedio.cope.pattern.Media; import com.exedio.cope.pattern.MediaPath; import com.exedio.cope.util.ReactivationConstructorDummy; final class Generator { private static final String STRING = String.class.getName(); private static final String COLLECTION = Collection.class.getName(); private static final String LIST = List.class.getName(); private static final String IO_EXCEPTION = IOException.class.getName(); private static final String SET_VALUE = SetValue.class.getName(); private static final String ITEM = Item.class.getName(); private static final String TYPE_NAME = Type.class.getName(); private static final String REACTIVATION = ReactivationConstructorDummy.class.getName(); private static final char ATTRIBUTE_MAP_KEY = 'k'; private static final String THROWS_MANDATORY = "if {0} is null."; private static final String THROWS_UNIQUE = "if {0} is not unique."; private static final String THROWS_RANGE = "if {0} violates its range constraint."; private static final String THROWS_LENGTH = "if {0} violates its length constraint."; private static final String CONSTRUCTOR_INITIAL = "Creates a new {0} with all the fields initially needed."; private static final String CONSTRUCTOR_INITIAL_PARAMETER = "the initial value for field {0}."; private static final String CONSTRUCTOR_INITIAL_CUSTOMIZE = "It can be customized with the tags " + "<tt>@" + CopeType.TAG_INITIAL_CONSTRUCTOR + " public|package|protected|private|none</tt> " + "in the class comment and " + "<tt>@" + CopeFeature.TAG_INITIAL + "</tt> in the comment of fields."; private static final String CONSTRUCTOR_GENERIC = "Creates a new {0} and sets the given fields initially."; private static final String CONSTRUCTOR_GENERIC_CALLED = "This constructor is called by {0}."; private static final String CONSTRUCTOR_GENERIC_CUSTOMIZE = "It can be customized with the tag " + "<tt>@" + CopeType.TAG_GENERIC_CONSTRUCTOR + " public|package|protected|private|none</tt> " + "in the class comment."; private static final String CONSTRUCTOR_REACTIVATION = "Reactivation constructor. Used for internal purposes only."; private static final String SETTER = "Sets a new value for the persistent field {0}."; private static final String SETTER_CUSTOMIZE = "It can be customized with the tag " + "<tt>@" + CopeFeature.TAG_SETTER + " public|package|protected|private|none|non-final</tt> " + "in the comment of the field."; private static final String SETTER_MEDIA = "Sets the content of media {0}."; private static final String SETTER_MEDIA_IOEXCEPTION = "if accessing {0} throws an IOException."; private static final String GETTER_STREAM_WARNING = "<b>You are responsible for closing the stream, when you are finished!</b>"; private static final String TOUCHER = "Sets the current date for the date field {0}."; private static final String FINDER_UNIQUE = "Finds a {0} by it''s unique fields."; private static final String FINDER_UNIQUE_PARAMETER = "shall be equal to field {0}."; private static final String FINDER_UNIQUE_RETURN = "null if there is no matching item."; private static final String QUALIFIER = "Returns the qualifier."; private static final String QUALIFIER_GETTER = "Returns the qualifier."; private static final String QUALIFIER_SETTER = "Sets the qualifier."; private static final String ATTIBUTE_LIST_GETTER = "Returns the contents of the field list {0}."; private static final String ATTIBUTE_LIST_SETTER = "Sets the contents of the field list {0}."; private static final String ATTIBUTE_SET_GETTER = "Returns the contents of the field set {0}."; private static final String ATTIBUTE_SET_SETTER = "Sets the contents of the field set {0}."; private static final String ATTIBUTE_MAP_GETTER = "Returns the value mapped to <tt>" + ATTRIBUTE_MAP_KEY + "</tt> by the field map {0}."; private static final String ATTIBUTE_MAP_SETTER = "Associates <tt>" + ATTRIBUTE_MAP_KEY + "</tt> to a new value in the field map {0}."; private static final String RELATION_GETTER = "Returns the items associated to this item by the relation."; private static final String RELATION_ADDER = "Adds an item to the items associated to this item by the relation."; private static final String RELATION_REMOVER = "Removes an item from the items associated to this item by the relation."; private static final String RELATION_SETTER = "Sets the items associated to this item by the relation."; private static final String PARENT = "Returns the parent field of the type of {0}."; private static final String TYPE = "The persistent type information for {0}."; private static final String TYPE_CUSTOMIZE = "It can be customized with the tag " + "<tt>@" + CopeType.TAG_TYPE + " public|package|protected|private|none</tt> " + "in the class comment."; private static final String GENERATED = "This feature has been generated by the cope instrumentor and will be overwritten by the build process."; /** * All generated class features get this doccomment tag. */ static final String TAG_GENERATED = CopeFeature.TAG_PREFIX + "generated"; private final JavaFile javaFile; private final Writer o; private final CRC32 outputCRC = new CRC32(); private final String lineSeparator; private final boolean longJavadoc; private static final String localFinal = "final "; // TODO make switchable from ant target Generator(final JavaFile javaFile, final ByteArrayOutputStream outputStream, final boolean longJavadoc) { this.javaFile = javaFile; this.o = new OutputStreamWriter(new CheckedOutputStream(outputStream, outputCRC)); final String systemLineSeparator = System.getProperty("line.separator"); if(systemLineSeparator==null) { System.out.println("warning: property \"line.separator\" is null, using LF (unix style)."); lineSeparator = "\n"; } else lineSeparator = systemLineSeparator; this.longJavadoc = longJavadoc; } void close() throws IOException { if(o!=null) o.close(); } long getCRC() { return outputCRC.getValue(); } private static final String toCamelCase(final String name) { final char first = name.charAt(0); if (Character.isUpperCase(first)) return name; else return Character.toUpperCase(first) + name.substring(1); } private static final String lowerCamelCase(final String s) { final char first = s.charAt(0); if(Character.isLowerCase(first)) return s; else return Character.toLowerCase(first) + s.substring(1); } private void writeThrowsClause(final Collection<Class> exceptions) throws IOException { if(!exceptions.isEmpty()) { o.write("\t\t\tthrows"); boolean first = true; for(final Class e : exceptions) { if(first) first = false; else o.write(','); o.write(lineSeparator); o.write("\t\t\t\t"); o.write(e.getName()); } o.write(lineSeparator); } } private void writeCommentHeader() throws IOException { o.write("/**"); o.write(lineSeparator); if(longJavadoc) { o.write(lineSeparator); o.write("\t **"); o.write(lineSeparator); } } private void writeCommentFooter() throws IOException { writeCommentFooter(null); } private void writeCommentFooter(final String extraComment) throws IOException { o.write("\t * @" + TAG_GENERATED + ' '); o.write(GENERATED); o.write(lineSeparator); if(extraComment!=null) { o.write("\t * "); o.write(extraComment); o.write(lineSeparator); } o.write("\t */"); o.write(lineSeparator); o.write('\t'); // TODO put this into calling methods } private static final String link(final String target) { return "{@link #" + target + '}'; } private static final String link(final String target, final String name) { return "{@link #" + target + ' ' + name + '}'; } private static final String format(final String pattern, final String parameter1) { return MessageFormat.format(pattern, new Object[]{ parameter1 }); } private static final String format(final String pattern, final String parameter1, final String parameter2) { return MessageFormat.format(pattern, new Object[]{ parameter1, parameter2 }); } private void writeInitialConstructor(final CopeType type) throws IOException { if(!type.hasInitialConstructor()) return; final List<CopeFeature> initialFeatures = type.getInitialFeatures(); final SortedSet<Class> constructorExceptions = type.getConstructorExceptions(); writeCommentHeader(); o.write("\t * "); o.write(format(CONSTRUCTOR_INITIAL, type.name)); o.write(lineSeparator); for(final CopeFeature feature : initialFeatures) { o.write("\t * @param "); o.write(feature.name); o.write(' '); o.write(format(CONSTRUCTOR_INITIAL_PARAMETER, link(feature.name))); o.write(lineSeparator); } for(final Class constructorException : constructorExceptions) { o.write("\t * @throws "); o.write(constructorException.getName()); o.write(' '); boolean first = true; final StringBuffer initialAttributesBuf = new StringBuffer(); for(final CopeFeature feature : initialFeatures) { if(!feature.getSetterExceptions().contains(constructorException)) continue; if(first) first = false; else initialAttributesBuf.append(", "); initialAttributesBuf.append(feature.name); } final String pattern; if(MandatoryViolationException.class.equals(constructorException)) pattern = THROWS_MANDATORY; else if(UniqueViolationException.class.equals(constructorException)) pattern = THROWS_UNIQUE; else if(RangeViolationException.class.equals(constructorException)) pattern = THROWS_RANGE; else if(LengthViolationException.class.equals(constructorException)) pattern = THROWS_LENGTH; else throw new RuntimeException(constructorException.getName()); o.write(format(pattern, initialAttributesBuf.toString())); o.write(lineSeparator); } writeCommentFooter(CONSTRUCTOR_INITIAL_CUSTOMIZE); writeModifier(type.getInitialConstructorModifier()); o.write(type.name); o.write('('); boolean first = true; for(final CopeFeature feature : initialFeatures) { if(first) first = false; else o.write(','); o.write(lineSeparator); o.write("\t\t\t\tfinal "); o.write(feature.getBoxedType()); o.write(' '); o.write(feature.name); } o.write(')'); o.write(lineSeparator); writeThrowsClause(constructorExceptions); o.write("\t{"); o.write(lineSeparator); o.write("\t\tthis(new " + SET_VALUE + "[]{"); o.write(lineSeparator); for(final CopeFeature feature : initialFeatures) { o.write("\t\t\t"); o.write(type.name); o.write('.'); o.write(feature.name); o.write(".map("); o.write(feature.name); o.write("),"); o.write(lineSeparator); } o.write("\t\t});"); o.write(lineSeparator); o.write("\t}"); } private void writeGenericConstructor(final CopeType type) throws IOException { final Option option = type.genericConstructorOption; if(!option.exists) return; writeCommentHeader(); o.write("\t * "); o.write(format(CONSTRUCTOR_GENERIC, type.name)); o.write(lineSeparator); o.write("\t * "); o.write(format(CONSTRUCTOR_GENERIC_CALLED, "{@link " + TYPE_NAME + "#newItem Type.newItem}")); o.write(lineSeparator); writeCommentFooter(CONSTRUCTOR_GENERIC_CUSTOMIZE); writeModifier(option.getModifier(type.allowSubTypes() ? Modifier.PROTECTED : Modifier.PRIVATE)); o.write(type.name); o.write('('); o.write(localFinal); o.write(SET_VALUE + "... setValues)"); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\tsuper(setValues);"); o.write(lineSeparator); o.write("\t}"); } private void writeReactivationConstructor(final CopeType type) throws IOException { final Option option = type.reactivationConstructorOption; if(!option.exists) return; writeCommentHeader(); o.write("\t * "); o.write(CONSTRUCTOR_REACTIVATION); o.write(lineSeparator); o.write("\t * @see " + ITEM + "#Item(" + REACTIVATION + ",int)"); o.write(lineSeparator); writeCommentFooter(); writeModifier(option.getModifier(type.allowSubTypes() ? Modifier.PROTECTED : Modifier.PRIVATE)); o.write(type.name); o.write('('); o.write(localFinal); o.write(REACTIVATION + " d,"); o.write(localFinal); o.write("int pk)"); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\tsuper(d,pk);"); o.write(lineSeparator); o.write("\t}"); } private void writeGenerically(final CopeFeature feature) throws InjectorParseException, IOException { final String type = feature.getBoxedType(); final Feature instance = feature.getInstance(); for(final Wrapper wrapper : instance.getWrappers()) { final String modifierTag = wrapper.getModifier(); final Option option = modifierTag!=null ? new Option(Injector.findDocTagLine( feature.docComment, modifierTag), true) : null; if(option!=null && !option.exists) continue; final String methodName = wrapper.getMethodName(); final Class methodReturnType = wrapper.getMethodReturnType(); final List<Class> parameterTypes = wrapper.getParameterTypes(); final boolean isGet = methodName.equals("get"); final String featureNameCamelCase = toCamelCase(feature.name); final String parameterName = wrapper.getParameterName()!=null ? wrapper.getParameterName() : feature.name; writeCommentHeader(); o.write("\t * "); o.write(format(wrapper.getComment(), link(feature.name))); o.write(lineSeparator); for(final String comment : wrapper.getComments()) { o.write("\t * "); o.write(comment); o.write(lineSeparator); } for(final Class pt : parameterTypes) { if(InputStream.class.equals(pt)) { o.write("\t * "); o.write(GETTER_STREAM_WARNING); o.write(lineSeparator); break; } } final String modifierComment = wrapper.getModifierComment(); writeCommentFooter(modifierComment); writeModifier(option!=null ? option.getModifier(feature.modifier) : (feature.modifier & (Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE)) | Modifier.FINAL); o.write(isGet ? type : toString(methodReturnType)); if(option!=null && (instance instanceof BooleanField) && option.booleanAsIs) { o.write(" is"); o.write(featureNameCamelCase); } else { o.write(' '); final String pattern = wrapper.getMethodWrapperPattern(); if(pattern!=null) { o.write(MessageFormat.format(pattern, featureNameCamelCase)); } else { o.write(methodName); o.write(featureNameCamelCase); } } if(option!=null) o.write(option.suffix); o.write('('); int writtenParameterI = 0; for(final Class parameter : parameterTypes) { o.write(localFinal); o.write(parameter.getName()); o.write(' '); o.write(parameterName); if(writtenParameterI++!=0) o.write(','); } o.write(')'); o.write(lineSeparator); { final SortedSet<Class> exceptions = new TreeSet<Class>(CopeType.CLASS_COMPARATOR); exceptions.addAll(wrapper.getThrowsClause()); writeThrowsClause(exceptions); } o.write("\t{"); o.write(lineSeparator); o.write("\t\t"); if(methodReturnType==null || !methodReturnType.equals(void.class)) o.write("return "); o.write(feature.parent.name); o.write('.'); o.write(feature.name); o.write('.'); o.write(methodName); if(feature.isBoxed()) o.write("Mandatory"); o.write("(this"); for(int i = 0; i<parameterTypes.size(); i++) { o.write(','); o.write(parameterName); } o.write(')'); o.write(';'); o.write(lineSeparator); o.write("\t}"); } } private static final String toString(final Class c) { if(c.isArray()) return c.getComponentType().getName() + "[]"; else return c.getName(); } private void writeAccessMethods(final CopeAttribute attribute) throws InjectorParseException, IOException { writeGenerically(attribute); writeSetter(attribute); writeUniqueFinder(attribute); } private void writeSetter(final CopeFeature feature) throws IOException { final String type = feature.getBoxedType(); if(feature.hasGeneratedSetter()) { writeCommentHeader(); o.write("\t * "); o.write(format(SETTER, link(feature.name))); o.write(lineSeparator); writeCommentFooter(SETTER_CUSTOMIZE); writeModifier(feature.getGeneratedSetterModifier()); o.write("void set"); o.write(toCamelCase(feature.name)); o.write(feature.setterOption.suffix); o.write('('); o.write(localFinal); o.write(type); o.write(' '); o.write(feature.name); o.write(')'); o.write(lineSeparator); writeThrowsClause(feature.getSetterExceptions()); o.write("\t{"); o.write(lineSeparator); o.write("\t\t"); o.write(feature.parent.name); o.write('.'); o.write(feature.name); o.write(".set(this,"); o.write(feature.name); o.write(");"); o.write(lineSeparator); o.write("\t}"); // touch for date attributes if(feature.isTouchable()) { writeCommentHeader(); o.write("\t * "); o.write(format(TOUCHER, link(feature.name))); o.write(lineSeparator); writeCommentFooter(); writeModifier(feature.getGeneratedSetterModifier()); o.write("void touch"); o.write(toCamelCase(feature.name)); o.write("()"); o.write(lineSeparator); writeThrowsClause(feature.getToucherExceptions()); o.write("\t{"); o.write(lineSeparator); o.write("\t\t"); o.write(feature.parent.name); o.write('.'); o.write(feature.name); o.write(".touch(this);"); o.write(lineSeparator); o.write("\t}"); } } } private void writeHash(final CopeHash hash) throws IOException, InjectorParseException { writeGenerically(hash); } private void writeMediaSetter(final CopeMedia media, final Class dataType) throws IOException { writeCommentHeader(); o.write("\t * "); o.write(format(SETTER_MEDIA, link(media.name))); o.write(lineSeparator); if(dataType!=byte.class) { o.write("\t * @throws " + IO_EXCEPTION + ' '); o.write(format(SETTER_MEDIA_IOEXCEPTION, "<tt>body</tt>")); o.write(lineSeparator); } writeCommentFooter(); writeModifier(media.getGeneratedSetterModifier()); o.write("void set"); o.write(toCamelCase(media.name)); o.write('('); o.write(localFinal); o.write(dataType.getName()); if(dataType==byte.class) o.write("[]"); o.write(" body,"); o.write(localFinal); o.write(STRING + " contentType)"); o.write(lineSeparator); if(dataType!=byte.class) { final SortedSet<Class> setterExceptions = new TreeSet<Class>(); setterExceptions.addAll(Arrays.asList(new Class[]{IOException.class})); // TODO writeThrowsClause(setterExceptions); } o.write("\t{"); o.write(lineSeparator); o.write("\t\t"); o.write(media.parent.name); o.write('.'); o.write(media.name); o.write(".set(this,body,contentType);"); o.write(lineSeparator); o.write("\t}"); } private void writeMedia(final CopeMedia media) throws IOException { final MediaPath instance = (MediaPath)media.getInstance(); writeGenerically(media); if(instance instanceof Media) { if(media.setterOption.exists) { writeMediaSetter(media, byte.class); writeMediaSetter(media, InputStream.class); writeMediaSetter(media, File.class); } } } private void writeUniqueFinder(final CopeAttribute attribute) throws IOException, InjectorParseException { if(!attribute.isImplicitlyUnique()) return; final String className = attribute.getParent().name; writeCommentHeader(); o.write("\t * "); o.write(format(FINDER_UNIQUE, lowerCamelCase(className))); o.write(lineSeparator); o.write("\t * @param "); o.write(attribute.name); o.write(' '); o.write(format(FINDER_UNIQUE_PARAMETER, link(attribute.name))); o.write(lineSeparator); o.write("\t * @return "); o.write(FINDER_UNIQUE_RETURN); o.write(lineSeparator); writeCommentFooter(); writeModifier((attribute.modifier & (Modifier.PRIVATE|Modifier.PROTECTED|Modifier.PUBLIC)) | (Modifier.STATIC|Modifier.FINAL) ); o.write(className); o.write(" findBy"); o.write(toCamelCase(attribute.name)); o.write('('); o.write(localFinal); o.write(attribute.getBoxedType()); o.write(' '); o.write(attribute.name); o.write(')'); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\treturn ("); o.write(className); o.write(')'); o.write(attribute.parent.name); o.write('.'); o.write(attribute.name); o.write(".searchUnique("); attribute.write(o); o.write(");"); o.write(lineSeparator); o.write("\t}"); } private void writeUniqueFinder(final CopeUniqueConstraint constraint) throws IOException, InjectorParseException { final CopeAttribute[] attributes = constraint.getAttributes(); final String className = attributes[0].getParent().name; writeCommentHeader(); o.write("\t * "); o.write(format(FINDER_UNIQUE, lowerCamelCase(className))); o.write(lineSeparator); for(int i=0; i<attributes.length; i++) { o.write("\t * @param "); o.write(attributes[i].name); o.write(' '); o.write(format(FINDER_UNIQUE_PARAMETER, link(attributes[i].name))); o.write(lineSeparator); } o.write("\t * @return "); o.write(FINDER_UNIQUE_RETURN); o.write(lineSeparator); writeCommentFooter(); writeModifier((constraint.modifier & (Modifier.PRIVATE|Modifier.PROTECTED|Modifier.PUBLIC)) | (Modifier.STATIC|Modifier.FINAL) ); o.write(className); o.write(" findBy"); o.write(toCamelCase(constraint.name)); o.write('('); for(int i=0; i<attributes.length; i++) { if(i>0) o.write(','); final CopeAttribute attribute = attributes[i]; o.write(localFinal); o.write(attribute.getBoxedType()); o.write(' '); o.write(attribute.name); } o.write(')'); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\treturn ("); o.write(className); o.write(')'); o.write(attributes[0].parent.name); o.write('.'); o.write(constraint.name); o.write(".searchUnique("); attributes[0].write(o); for(int i = 1; i<attributes.length; i++) { o.write(','); attributes[i].write(o); } o.write(");"); o.write(lineSeparator); o.write("\t}"); } private void writeQualifierParameters(final CopeQualifier qualifier) throws IOException, InjectorParseException { final CopeAttribute[] keys = qualifier.getKeyAttributes(); for(int i = 0; i<keys.length; i++) { if(i>0) o.write(','); o.write(localFinal); o.write(keys[i].persistentType); o.write(' '); o.write(keys[i].name); } } private void writeQualifierCall(final CopeQualifier qualifier) throws IOException, InjectorParseException { final CopeAttribute[] keys = qualifier.getKeyAttributes(); for(int i = 0; i<keys.length; i++) { o.write(','); o.write(keys[i].name); } } private void writeQualifier(final CopeQualifier qualifier) throws IOException, InjectorParseException { final String qualifierClassName = qualifier.parent.javaClass.getFullName(); writeCommentHeader(); o.write("\t * "); o.write(QUALIFIER); o.write(lineSeparator); writeCommentFooter(); o.write("public final "); // TODO: obey attribute visibility o.write(qualifierClassName); o.write(" get"); o.write(toCamelCase(qualifier.name)); o.write('('); writeQualifierParameters(qualifier); o.write(')'); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\treturn ("); o.write(qualifierClassName); o.write(')'); o.write(qualifierClassName); o.write('.'); o.write(qualifier.name); o.write(".getQualifier(this"); writeQualifierCall(qualifier); o.write(");"); o.write(lineSeparator); o.write("\t}"); final List<CopeAttribute> qualifierAttributes = Arrays.asList(qualifier.getAttributes()); for(final CopeFeature feature : qualifier.parent.getFeatures()) { if(feature instanceof CopeAttribute) { final CopeAttribute attribute = (CopeAttribute)feature; if(qualifierAttributes.contains(attribute)) continue; writeQualifierGetter(qualifier, attribute); writeQualifierSetter(qualifier, attribute); } } } private void writeQualifierGetter(final CopeQualifier qualifier, final CopeAttribute attribute) throws IOException, InjectorParseException { if(attribute.getterOption.exists) { final String qualifierClassName = qualifier.parent.javaClass.getFullName(); writeCommentHeader(); o.write("\t * "); o.write(QUALIFIER_GETTER); o.write(lineSeparator); writeCommentFooter(); writeModifier(attribute.getGeneratedGetterModifier()); o.write(attribute.persistentType); o.write(" get"); o.write(toCamelCase(attribute.name)); o.write(attribute.getterOption.suffix); o.write('('); writeQualifierParameters(qualifier); o.write(')'); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\treturn "); o.write(qualifierClassName); o.write('.'); o.write(qualifier.name); o.write(".get("); o.write(qualifierClassName); o.write('.'); o.write(attribute.name); o.write(",this"); writeQualifierCall(qualifier); o.write(");"); o.write(lineSeparator); o.write("\t}"); } } private void writeQualifierSetter(final CopeQualifier qualifier, final CopeAttribute attribute) throws IOException, InjectorParseException { if(attribute.setterOption.exists) { final String qualifierClassName = qualifier.parent.javaClass.getFullName(); writeCommentHeader(); o.write("\t * "); o.write(QUALIFIER_SETTER); o.write(lineSeparator); writeCommentFooter(); writeModifier(attribute.getGeneratedSetterModifier()); o.write("void set"); o.write(toCamelCase(attribute.name)); o.write(attribute.setterOption.suffix); o.write('('); writeQualifierParameters(qualifier); o.write(','); o.write(localFinal); o.write(attribute.getBoxedType()); o.write(' '); o.write(attribute.name); o.write(')'); o.write(lineSeparator); writeThrowsClause(attribute.getSetterExceptions()); o.write("\t{"); o.write(lineSeparator); o.write("\t\t"); o.write(qualifierClassName); o.write('.'); o.write(qualifier.name); o.write(".set("); o.write(qualifierClassName); o.write('.'); o.write(attribute.name); o.write(','); o.write(attribute.name); o.write(",this"); writeQualifierCall(qualifier); o.write(");"); o.write(lineSeparator); o.write("\t}"); } } private void write(final CopeAttributeList list) throws IOException { final String type = list.getType(); final String name = list.name; writeCommentHeader(); o.write("\t * "); o.write(MessageFormat.format(list.set?ATTIBUTE_SET_GETTER:ATTIBUTE_LIST_GETTER, link(name))); o.write(lineSeparator); writeCommentFooter(); o.write("public final "); // TODO: obey attribute visibility o.write((list.set?Set.class:List.class).getName()); o.write('<'); o.write(type); o.write("> get"); o.write(toCamelCase(list.name)); o.write("()"); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\treturn "); o.write(list.parent.name); o.write('.'); o.write(list.name); o.write(".get(this);"); o.write(lineSeparator); o.write("\t}"); writeCommentHeader(); o.write("\t * "); o.write(MessageFormat.format(list.set?ATTIBUTE_SET_SETTER:ATTIBUTE_LIST_SETTER, link(name))); o.write(lineSeparator); writeCommentFooter(); o.write("public final void set"); // TODO: obey attribute visibility o.write(toCamelCase(list.name)); o.write('('); o.write(localFinal); o.write(COLLECTION + "<? extends "); o.write(type); o.write("> "); o.write(list.name); o.write(')'); o.write(lineSeparator); writeThrowsClause(Arrays.asList(new Class[]{ UniqueViolationException.class, MandatoryViolationException.class, LengthViolationException.class, FinalViolationException.class, ClassCastException.class})); o.write("\t{"); o.write(lineSeparator); o.write("\t\t"); o.write(list.parent.name); o.write('.'); o.write(list.name); o.write(".set(this,"); o.write(list.name); o.write(");"); o.write(lineSeparator); o.write("\t}"); if(list.hasParent) writeParent(list); } private void write(final CopeAttributeMap map) throws IOException { if(true) // TODO SOON getter option { writeCommentHeader(); o.write("\t * "); o.write(MessageFormat.format(ATTIBUTE_MAP_GETTER, link(map.name))); o.write(lineSeparator); writeCommentFooter(); o.write("public final "); // TODO SOON getter option o.write(map.getValueType()); o.write(" get"); o.write(toCamelCase(map.name)); o.write('('); o.write(localFinal); o.write(map.getKeyType()); o.write(" " + ATTRIBUTE_MAP_KEY + ")"); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\treturn "); o.write(map.parent.name); o.write('.'); o.write(map.name); o.write(".get(this," + ATTRIBUTE_MAP_KEY + ");"); o.write(lineSeparator); o.write("\t}"); } if(true) // TODO SOON setter option { writeCommentHeader(); o.write("\t * "); o.write(MessageFormat.format(ATTIBUTE_MAP_SETTER, link(map.name))); o.write(lineSeparator); writeCommentFooter(); o.write("public final "); // TODO SOON setter option o.write("void set"); o.write(toCamelCase(map.name)); o.write('('); o.write(localFinal); o.write(map.getKeyType()); o.write(" " + ATTRIBUTE_MAP_KEY + ','); o.write(localFinal); o.write(map.getValueType()); o.write(' '); o.write(map.name); o.write(')'); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\t"); o.write(map.parent.name); o.write('.'); o.write(map.name); o.write(".set(this," + ATTRIBUTE_MAP_KEY + ','); o.write(map.name); o.write(");"); o.write(lineSeparator); o.write("\t}"); } if(map.hasParent) writeParent(map); } private void writeParent(final CopeFeature f) throws IOException { if(true) // TODO SOON parent option { writeCommentHeader(); o.write("\t * "); o.write(MessageFormat.format(PARENT, link(f.name))); o.write(lineSeparator); writeCommentFooter(); o.write(Modifier.toString(f.modifier | (Modifier.STATIC | Modifier.FINAL))); o.write(' '); o.write(ItemField.class.getName()); o.write('<'); o.write(f.parent.name); o.write('>'); o.write(' '); o.write(f.name); o.write("Parent()"); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\treturn "); o.write(f.parent.name); o.write('.'); o.write(f.name); o.write(".getParent("); o.write(f.parent.name); o.write(".class);"); o.write(lineSeparator); o.write("\t}"); } } private void writeRelation(final CopeRelation relation, final boolean source) throws IOException { final boolean vector = relation.vector; final String endType = relation.getEndType(source); final String endName = relation.getEndName(source); final String endNameCamel = toCamelCase(endName); final String methodName = source ? "Sources" : "Targets"; final String className = relation.parent.javaClass.getFullName(); // getter if(!vector || !source) { writeCommentHeader(); o.write("\t * "); o.write(RELATION_GETTER); o.write(lineSeparator); writeCommentFooter(); o.write("public final " + LIST + '<'); // TODO: obey attribute visibility o.write(endType); o.write("> get"); o.write(endNameCamel); o.write("()"); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\treturn "); o.write(className); o.write('.'); o.write(relation.name); o.write(".get"); o.write(methodName); o.write("(this);"); o.write(lineSeparator); o.write("\t}"); } // adder if(!vector) { writeCommentHeader(); o.write("\t * "); o.write(RELATION_ADDER); o.write(lineSeparator); writeCommentFooter(); o.write("public final boolean addTo"); // TODO: obey attribute visibility o.write(endNameCamel); o.write('('); o.write(localFinal); o.write(endType); o.write(' '); o.write(endName); o.write(')'); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\treturn "); o.write(className); o.write('.'); o.write(relation.name); o.write(".addTo"); o.write(methodName); o.write("(this,"); o.write(endName); o.write(");"); o.write(lineSeparator); o.write("\t}"); } // remover if(!vector) { writeCommentHeader(); o.write("\t * "); o.write(RELATION_REMOVER); o.write(lineSeparator); writeCommentFooter(); o.write("public final boolean removeFrom"); // TODO: obey attribute visibility o.write(endNameCamel); o.write('('); o.write(localFinal); o.write(endType); o.write(' '); o.write(endName); o.write(')'); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\treturn "); o.write(className); o.write('.'); o.write(relation.name); o.write(".removeFrom"); o.write(methodName); o.write("(this,"); o.write(endName); o.write(");"); o.write(lineSeparator); o.write("\t}"); } // setter if(!vector || !source) { writeCommentHeader(); o.write("\t * "); o.write(RELATION_SETTER); o.write(lineSeparator); writeCommentFooter(); o.write("public final void set"); // TODO: obey attribute visibility o.write(endNameCamel); o.write('('); o.write(localFinal); o.write(COLLECTION + "<? extends "); o.write(endType); o.write("> "); o.write(endName); o.write(')'); o.write(lineSeparator); o.write("\t{"); o.write(lineSeparator); o.write("\t\t"); o.write(className); o.write('.'); o.write(relation.name); o.write(".set"); o.write(methodName); o.write("(this,"); o.write(endName); o.write(");"); o.write(lineSeparator); o.write("\t}"); } } private void writeSerialVersionUID() throws IOException { // TODO make disableable { writeCommentHeader(); writeCommentFooter(null); writeModifier(Modifier.PRIVATE | Modifier.STATIC | Modifier.FINAL); o.write("long serialVersionUID = 1l;"); } } private void writeType(final CopeType type) throws IOException { final Option option = type.typeOption; if(option.exists) { writeCommentHeader(); o.write("\t * "); o.write(format(TYPE, lowerCamelCase(type.name))); o.write(lineSeparator); writeCommentFooter(TYPE_CUSTOMIZE); writeModifier(option.getModifier(Modifier.PUBLIC) | Modifier.STATIC | Modifier.FINAL); // TODO obey class visibility o.write(TYPE_NAME + '<'); o.write(type.name); o.write("> TYPE = newType("); o.write(type.name); o.write(".class)"); o.write(lineSeparator); o.write(';'); } } void write() throws IOException, InjectorParseException { final String buffer = javaFile.buffer.toString(); int previousClassEndPosition = 0; for(final JavaClass javaClass : javaFile.getClasses()) { final CopeType type = CopeType.getCopeType(javaClass); final int classEndPosition = javaClass.getClassEndPosition(); if(type!=null) { assert previousClassEndPosition<=classEndPosition; if(previousClassEndPosition<classEndPosition) o.write(buffer, previousClassEndPosition, classEndPosition-previousClassEndPosition); writeClassFeatures(type); previousClassEndPosition = classEndPosition; } } o.write(buffer, previousClassEndPosition, buffer.length()-previousClassEndPosition); } private void writeClassFeatures(final CopeType type) throws IOException, InjectorParseException { if(!type.isInterface()) { writeInitialConstructor(type); writeGenericConstructor(type); writeReactivationConstructor(type); for(final CopeFeature feature : type.getFeatures()) { if(feature instanceof CopeAttribute) writeAccessMethods((CopeAttribute)feature); else if(feature instanceof CopeUniqueConstraint) writeUniqueFinder((CopeUniqueConstraint)feature); else if(feature instanceof CopeAttributeList) write((CopeAttributeList)feature); else if(feature instanceof CopeAttributeMap) write((CopeAttributeMap)feature); else if(feature instanceof CopeMedia) writeMedia((CopeMedia)feature); else if(feature instanceof CopeHash) writeHash((CopeHash)feature); else if(feature instanceof CopeRelation || feature instanceof CopeQualifier) ; // is handled below else throw new RuntimeException(feature.getClass().getName()); } for(final CopeQualifier qualifier : sort(type.getQualifiers())) writeQualifier(qualifier); for(final CopeRelation relation : sort(type.getRelations(true))) writeRelation(relation, false); for(final CopeRelation relation : sort(type.getRelations(false))) writeRelation(relation, true); writeSerialVersionUID(); writeType(type); } } private static final <X extends CopeFeature> List<X> sort(final List<X> l) { final ArrayList<X> result = new ArrayList<X>(l); Collections.sort(result, new Comparator<X>() { public int compare(final X a, final X b) { return a.parent.javaClass.getFullName().compareTo(b.parent.javaClass.getFullName()); } }); return result; } private void writeModifier(final int modifier) throws IOException { final String modifierString = Modifier.toString(modifier); if(modifierString.length()>0) { o.write(modifierString); o.write(' '); } } }
package functionalTests.descriptor.services.p2p; import functionalTests.FunctionalTest; import static junit.framework.Assert.assertTrue; import org.objectweb.proactive.ProActive; import org.objectweb.proactive.core.Constants; import org.objectweb.proactive.core.config.ProActiveConfiguration; import org.objectweb.proactive.core.descriptor.data.ProActiveDescriptor; import org.objectweb.proactive.core.descriptor.data.VirtualNode; import org.objectweb.proactive.core.node.Node; import org.objectweb.proactive.core.process.AbstractExternalProcess.StandardOutputMessageLogger; import org.objectweb.proactive.core.process.JVMProcessImpl; /** * Test service: P2P JVM acquisition in deployment descriptor * * @author ProActiveTeam * @version 1.0 6 ao?t 2004 * @since ProActive 2.0.1 */ public class Test extends FunctionalTest { private static final long serialVersionUID = -3787507831019771599L; private static String P2P_XML_LOCATION_UNIX = Test.class.getResource( "/functionalTests/descriptor/services/p2p/TestP2P.xml").getPath(); static { if ("ibis".equals(ProActiveConfiguration.getInstance() .getProperty(Constants.PROPERTY_PA_COMMUNICATION_PROTOCOL))) { P2P_XML_LOCATION_UNIX = Test.class.getResource( "/functionalTests/descriptor/services/p2p/TestP2PIbis.xml") .getPath(); } else { P2P_XML_LOCATION_UNIX = Test.class.getResource( "/functionalTests/descriptor/services/p2p/TestP2P.xml") .getPath(); } } JVMProcessImpl process1; JVMProcessImpl process; Node[] nodeTab; ProActiveDescriptor pad; @org.junit.Test public void action() throws Exception { process1 = new JVMProcessImpl(new StandardOutputMessageLogger()); process1.setClassname( "org.objectweb.proactive.p2p.service.StartP2PService"); process1.setParameters("-port 2900"); process = new JVMProcessImpl(new StandardOutputMessageLogger()); process.setClassname( "org.objectweb.proactive.p2p.service.StartP2PService"); process.setParameters("-port 3000 -s //localhost:2900"); process1.startProcess(); Thread.sleep(5000); process.startProcess(); Thread.sleep(7000); pad = ProActive.getProactiveDescriptor(P2P_XML_LOCATION_UNIX); pad.activateMappings(); VirtualNode vn = pad.getVirtualNode("p2pvn"); nodeTab = vn.getNodes(); boolean resultTest = (nodeTab.length == 3); this.process.stopProcess(); this.process1.stopProcess(); assertTrue(resultTest); } public static void main(String[] args) { Test test = new Test(); try { test.action(); } catch (Exception e) { e.printStackTrace(); } } }
package jolie.net; import jolie.ExecutionThread; import jolie.Interpreter; import jolie.js.JsUtils; import jolie.lang.Constants; import jolie.lang.NativeType; import jolie.monitoring.events.ProtocolMessageEvent; import jolie.net.http.HttpMessage; import jolie.net.http.HttpParser; import jolie.net.http.HttpUtils; import jolie.net.http.Method; import jolie.net.http.MultiPartFormDataParser; import jolie.net.ports.Interface; import jolie.net.protocols.CommProtocol; import jolie.runtime.ByteArray; import jolie.runtime.FaultException; import jolie.runtime.Value; import jolie.runtime.ValueVector; import jolie.runtime.VariablePath; import jolie.runtime.typing.OneWayTypeDescription; import jolie.runtime.typing.OperationTypeDescription; import jolie.runtime.typing.RequestResponseTypeDescription; import jolie.runtime.typing.Type; import jolie.runtime.typing.TypeCastingException; import jolie.tracer.ProtocolTraceAction; import jolie.uri.UriUtils; import jolie.util.LocationParser; import jolie.xml.XmlUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Base64; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * HTTP protocol implementation * * @author Fabrizio Montesi 14 Nov 2012 - Saverio Giallorenzo - Fabrizio Montesi: support for status * codes */ public class HttpProtocol extends CommProtocol implements HttpUtils.HttpProtocol { private static final int DEFAULT_STATUS_CODE = 200; private static final int DEFAULT_REDIRECTION_STATUS_CODE = 303; private static final String DEFAULT_CONTENT_TYPE = "application/octet-stream"; // default content type per RFC // 2616#7.2.1 private static final String DEFAULT_FORMAT = "xml"; private static final Map< Integer, String > STATUS_CODE_DESCRIPTIONS = new HashMap<>(); private static final Set< Integer > LOCATION_REQUIRED_STATUS_CODES = new HashSet<>(); static { LOCATION_REQUIRED_STATUS_CODES.add( 301 ); LOCATION_REQUIRED_STATUS_CODES.add( 302 ); LOCATION_REQUIRED_STATUS_CODES.add( 303 ); LOCATION_REQUIRED_STATUS_CODES.add( 307 ); LOCATION_REQUIRED_STATUS_CODES.add( 308 ); } static { // Initialise the HTTP Status code map. STATUS_CODE_DESCRIPTIONS.put( 100, "Continue" ); STATUS_CODE_DESCRIPTIONS.put( 101, "Switching Protocols" ); STATUS_CODE_DESCRIPTIONS.put( 102, "Processing" ); STATUS_CODE_DESCRIPTIONS.put( 200, "OK" ); STATUS_CODE_DESCRIPTIONS.put( 201, "Created" ); STATUS_CODE_DESCRIPTIONS.put( 202, "Accepted" ); STATUS_CODE_DESCRIPTIONS.put( 203, "Non-Authoritative Information" ); STATUS_CODE_DESCRIPTIONS.put( 204, "No Content" ); STATUS_CODE_DESCRIPTIONS.put( 205, "Reset Content" ); STATUS_CODE_DESCRIPTIONS.put( 206, "Partial Content" ); STATUS_CODE_DESCRIPTIONS.put( 207, "Multi-Status" ); STATUS_CODE_DESCRIPTIONS.put( 208, "Already Reported" ); STATUS_CODE_DESCRIPTIONS.put( 226, "IM Used" ); STATUS_CODE_DESCRIPTIONS.put( 300, "Multiple Choices" ); STATUS_CODE_DESCRIPTIONS.put( 301, "Moved Permanently" ); STATUS_CODE_DESCRIPTIONS.put( 302, "Found" ); STATUS_CODE_DESCRIPTIONS.put( 303, "See Other" ); STATUS_CODE_DESCRIPTIONS.put( 304, "Not Modified" ); STATUS_CODE_DESCRIPTIONS.put( 305, "Use Proxy" ); STATUS_CODE_DESCRIPTIONS.put( 306, "Reserved" ); STATUS_CODE_DESCRIPTIONS.put( 307, "Temporary Redirect" ); STATUS_CODE_DESCRIPTIONS.put( 308, "Permanent Redirect" ); STATUS_CODE_DESCRIPTIONS.put( 400, "Bad Request" ); STATUS_CODE_DESCRIPTIONS.put( 401, "Unauthorized" ); STATUS_CODE_DESCRIPTIONS.put( 402, "Payment Required" ); STATUS_CODE_DESCRIPTIONS.put( 403, "Forbidden" ); STATUS_CODE_DESCRIPTIONS.put( 404, "Not Found" ); STATUS_CODE_DESCRIPTIONS.put( 405, "Method Not Allowed" ); STATUS_CODE_DESCRIPTIONS.put( 406, "Not Acceptable" ); STATUS_CODE_DESCRIPTIONS.put( 407, "Proxy Authentication Required" ); STATUS_CODE_DESCRIPTIONS.put( 408, "Request Timeout" ); STATUS_CODE_DESCRIPTIONS.put( 409, "Conflict" ); STATUS_CODE_DESCRIPTIONS.put( 410, "Gone" ); STATUS_CODE_DESCRIPTIONS.put( 411, "Length Required" ); STATUS_CODE_DESCRIPTIONS.put( 412, "Precondition Failed" ); STATUS_CODE_DESCRIPTIONS.put( 413, "Request Entity Too Large" ); STATUS_CODE_DESCRIPTIONS.put( 414, "Request-URI Too Long" ); STATUS_CODE_DESCRIPTIONS.put( 415, "Unsupported Media Type" ); STATUS_CODE_DESCRIPTIONS.put( 416, "Requested Range Not Satisfiable" ); STATUS_CODE_DESCRIPTIONS.put( 417, "Expectation Failed" ); STATUS_CODE_DESCRIPTIONS.put( 422, "Unprocessable Entity" ); STATUS_CODE_DESCRIPTIONS.put( 423, "Locked" ); STATUS_CODE_DESCRIPTIONS.put( 424, "Failed Dependency" ); STATUS_CODE_DESCRIPTIONS.put( 426, "Upgrade Required" ); STATUS_CODE_DESCRIPTIONS.put( 427, "Unassigned" ); STATUS_CODE_DESCRIPTIONS.put( 428, "Precondition Required" ); STATUS_CODE_DESCRIPTIONS.put( 429, "Too Many Requests" ); STATUS_CODE_DESCRIPTIONS.put( 430, "Unassigned" ); STATUS_CODE_DESCRIPTIONS.put( 431, "Request Header Fields Too Large" ); STATUS_CODE_DESCRIPTIONS.put( 500, "Internal Server Error" ); STATUS_CODE_DESCRIPTIONS.put( 501, "Not Implemented" ); STATUS_CODE_DESCRIPTIONS.put( 502, "Bad Gateway" ); STATUS_CODE_DESCRIPTIONS.put( 503, "Service Unavailable" ); STATUS_CODE_DESCRIPTIONS.put( 504, "Gateway Timeout" ); STATUS_CODE_DESCRIPTIONS.put( 505, "HTTP Version Not Supported" ); STATUS_CODE_DESCRIPTIONS.put( 507, "Insufficient Storage" ); STATUS_CODE_DESCRIPTIONS.put( 508, "Loop Detected" ); STATUS_CODE_DESCRIPTIONS.put( 509, "Unassigned" ); STATUS_CODE_DESCRIPTIONS.put( 510, "Not Extended" ); STATUS_CODE_DESCRIPTIONS.put( 511, "Network Authentication Required" ); } private static class Parameters { private static final String KEEP_ALIVE = "keepAlive"; private static final String DEBUG = "debug"; private static final String COOKIES = "cookies"; private static final String METHOD = "method"; private static final String ALIAS = "alias"; private static final String MULTIPART_HEADERS = "multipartHeaders"; private static final String CONCURRENT = "concurrent"; private static final String USER_AGENT = "userAgent"; private static final String HOST = "host"; private static final String HEADERS = "headers"; private static final String HEADERS_WILDCARD = "*"; private static final String REQUEST_HEADERS = "requestHeaders"; private static final String ADD_HEADERS = "addHeader"; private static final String STATUS_CODE = "statusCode"; private static final String REDIRECT = "redirect"; private static final String DEFAULT_OPERATION = "default"; private static final String COMPRESSION = "compression"; private static final String COMPRESSION_TYPES = "compressionTypes"; private static final String REQUEST_COMPRESSION = "requestCompression"; private static final String FORMAT = "format"; private static final String RESPONSE_HEADER = "responseHeaders"; private static final String JSON_ENCODING = "json_encoding"; private static final String REQUEST_USER = "request"; private static final String RESPONSE_USER = "response"; private static final String HEADER_USER = "headers"; private static final String CHARSET = "charset"; private static final String CONTENT_TYPE = "contentType"; private static final String CONTENT_TRANSFER_ENCODING = "contentTransferEncoding"; private static final String CONTENT_DISPOSITION = "contentDisposition"; private static final String DROP_URI_PATH = "dropURIPath"; private static final String CACHE_CONTROL = "cacheControl"; private static final String FORCE_CONTENT_DECODING = "forceContentDecoding"; private static final String TEMPLATE = "template"; private static final String OUTGOING_HEADERS = "outHeaders"; private static final String INCOMING_HEADERS = "inHeaders"; private static final String STATUS_CODES = "statusCodes"; private static class MultiPartHeaders { private static final String FILENAME = "filename"; } } private static class Headers { private static final String CONTENT_TYPE = "Content-Type"; private static final String JOLIE_MESSAGE_ID = "X-Jolie-MessageID"; private static final String JOLIE_RESOURCE_PATH = "X-Jolie-ServicePath"; } private static class ContentTypes { private static final String APPLICATION_JSON = "application/json"; private static final String APPLICATION_NDJSON = "application/x-ndjson"; } private String inputId = null; private final Transformer transformer; private final DocumentBuilderFactory docBuilderFactory; private final DocumentBuilder docBuilder; private final URI uri; private final boolean inInputPort; private MultiPartFormDataParser multiPartFormDataParser = null; @Override public String name() { return "http"; } @Override public boolean isThreadSafe() { return checkBooleanParameter( Parameters.CONCURRENT ); } public HttpProtocol( VariablePath configurationPath, URI uri, boolean inInputPort, TransformerFactory transformerFactory, DocumentBuilderFactory docBuilderFactory, DocumentBuilder docBuilder ) throws TransformerConfigurationException { super( configurationPath ); this.uri = uri; this.inInputPort = inInputPort; this.transformer = transformerFactory.newTransformer(); this.docBuilderFactory = docBuilderFactory; this.docBuilder = docBuilder; transformer.setOutputProperty( OutputKeys.OMIT_XML_DECLARATION, "yes" ); transformer.setOutputProperty( OutputKeys.INDENT, "no" ); } public String getMultipartHeaderForPart( String operationName, String partName ) { if( hasOperationSpecificParameter( operationName, Parameters.MULTIPART_HEADERS ) ) { Value v = getOperationSpecificParameterFirstValue( operationName, Parameters.MULTIPART_HEADERS ); if( v.hasChildren( partName ) ) { v = v.getFirstChild( partName ); if( v.hasChildren( Parameters.MultiPartHeaders.FILENAME ) ) { v = v.getFirstChild( Parameters.MultiPartHeaders.FILENAME ); return v.strValue(); } } } return null; } private final static String BOUNDARY = "----jol13h77p77bound4r155"; private void send_appendCookies( CommMessage message, String hostname, StringBuilder headerBuilder ) { Value cookieParam = null; if( hasOperationSpecificParameter( message.operationName(), Parameters.COOKIES ) ) { cookieParam = getOperationSpecificParameterFirstValue( message.operationName(), Parameters.COOKIES ); } else if( hasParameter( Parameters.COOKIES ) ) { cookieParam = getParameterFirstValue( Parameters.COOKIES ); } if( cookieParam != null ) { Value cookieConfig; String domain; StringBuilder cookieSB = new StringBuilder(); for( Entry< String, ValueVector > entry : cookieParam.children().entrySet() ) { cookieConfig = entry.getValue().first(); if( message.value().hasChildren( cookieConfig.strValue() ) ) { domain = cookieConfig.hasChildren( "domain" ) ? cookieConfig.getFirstChild( "domain" ).strValue() : ""; if( domain.isEmpty() || hostname.endsWith( domain ) ) { cookieSB .append( entry.getKey() ) .append( '=' ) .append( message.value().getFirstChild( cookieConfig.strValue() ).strValue() ) .append( ";" ); } } } if( cookieSB.length() > 0 ) { headerBuilder .append( "Cookie: " ) .append( cookieSB ) .append( HttpUtils.CRLF ); } } } private void send_appendSetCookieHeader( CommMessage message, StringBuilder headerBuilder ) { Value cookieParam = null; if( hasOperationSpecificParameter( message.operationName(), Parameters.COOKIES ) ) { cookieParam = getOperationSpecificParameterFirstValue( message.operationName(), Parameters.COOKIES ); } else if( hasParameter( Parameters.COOKIES ) ) { cookieParam = getParameterFirstValue( Parameters.COOKIES ); } if( cookieParam != null ) { Value cookieConfig; for( Entry< String, ValueVector > entry : cookieParam.children().entrySet() ) { cookieConfig = entry.getValue().first(); if( message.value().hasChildren( cookieConfig.strValue() ) ) { headerBuilder .append( "Set-Cookie: " ) .append( entry.getKey() ).append( '=' ) .append( message.value().getFirstChild( cookieConfig.strValue() ).strValue() ) .append( "; expires=" ) .append( cookieConfig.hasChildren( "expires" ) ? cookieConfig.getFirstChild( "expires" ).strValue() : "" ) .append( "; domain=" ) .append( cookieConfig.hasChildren( "domain" ) ? cookieConfig.getFirstChild( "domain" ).strValue() : "" ) .append( "; path=" ) .append( cookieConfig.hasChildren( "path" ) ? cookieConfig.getFirstChild( "path" ).strValue() : "" ); if( cookieConfig.hasChildren( "secure" ) && cookieConfig.getFirstChild( "secure" ).intValue() > 0 ) { headerBuilder.append( "; secure" ); } headerBuilder.append( HttpUtils.CRLF ); } } } } private String encoding = null; private String responseFormat = null; private boolean headRequest = false; private void send_appendQuerystring( Value value, StringBuilder headerBuilder, CommMessage message ) throws IOException { getOperationSpecificParameterFirstValue( message.operationName(), Parameters.OUTGOING_HEADERS ).children() .forEach( ( headerName, headerValues ) -> value.children().remove( headerValues.get( 0 ).strValue() ) ); if( value.hasChildren() ) { headerBuilder.append( '?' ); Iterator< Entry< String, ValueVector > > nodesIt = value.children().entrySet().iterator(); while( nodesIt.hasNext() ) { Entry< String, ValueVector > entry = nodesIt.next(); Iterator< Value > vecIt = entry.getValue().iterator(); while( vecIt.hasNext() ) { Value v = vecIt.next(); headerBuilder .append( URLEncoder.encode( entry.getKey(), HttpUtils.URL_DECODER_ENC ) ) .append( '=' ) .append( URLEncoder.encode( v.strValue(), HttpUtils.URL_DECODER_ENC ) ); if( vecIt.hasNext() || nodesIt.hasNext() ) { headerBuilder.append( '&' ); } } } } } private void send_appendJsonQueryString( CommMessage message, StringBuilder headerBuilder ) throws IOException { getOperationSpecificParameterFirstValue( message.operationName(), Parameters.OUTGOING_HEADERS ).children().forEach( ( headerName, headerValues ) -> message.value().children().remove( headerValues.get( 0 ).strValue() ) ); if( message.value().isDefined() || message.value().hasChildren() ) { headerBuilder.append( "?" ); StringBuilder builder = new StringBuilder(); JsUtils.valueToJsonString( message.value(), true, getSendType( message ), builder ); headerBuilder.append( URLEncoder.encode( builder.toString(), HttpUtils.URL_DECODER_ENC ) ); } } private static void send_appendParsedAlias( String alias, Value value, StringBuilder headerBuilder ) throws IOException { int offset = 0; List< String > aliasKeys = new ArrayList<>(); String currStrValue; String currKey; StringBuilder result = new StringBuilder( alias ); Matcher m = Pattern.compile( "%(!)?\\{[^\\}]*\\}" ).matcher( alias ); while( m.find() ) { int displacement = 2; if( m.group( 1 ) == null ) { // ! is missing after %: We have to use URLEncoder currKey = alias.substring( m.start() + displacement, m.end() - 1 ); if( "$".equals( currKey ) ) { currStrValue = URLEncoder.encode( value.strValue(), HttpUtils.URL_DECODER_ENC ); } else { currStrValue = URLEncoder.encode( value.getFirstChild( currKey ).strValue(), HttpUtils.URL_DECODER_ENC ); aliasKeys.add( currKey ); } } else { // ! is given after %: We have to insert the string raw displacement = 3; currKey = alias.substring( m.start() + displacement, m.end() - 1 ); if( "$".equals( currKey ) ) { currStrValue = value.strValue(); } else { currStrValue = value.getFirstChild( currKey ).strValue(); aliasKeys.add( currKey ); } } result.replace( m.start() + offset, m.end() + offset, currStrValue ); displacement++; // considering also } offset += currStrValue.length() - displacement - currKey.length(); } // removing used keys aliasKeys.forEach( value.children()::remove ); headerBuilder.append( result ); } private String send_getFormat() { String format = DEFAULT_FORMAT; if( inInputPort && responseFormat != null ) { format = responseFormat; responseFormat = null; } else if( hasParameter( Parameters.FORMAT ) ) { format = getStringParameter( Parameters.FORMAT ); } return format; } private static class EncodedContent { private ByteArray content = null; private String contentType = DEFAULT_CONTENT_TYPE; private String contentDisposition = ""; } private EncodedContent send_encodeContent( CommMessage message, Method method, String charset, String format ) throws IOException { EncodedContent ret = new EncodedContent(); if( inInputPort == false && (method == Method.GET || method == Method.DELETE) ) { // We are building a GET or DELETE request return ret; } if( "xml".equals( format ) ) { ret.contentType = "text/xml"; Document doc = docBuilder.newDocument(); Element root = doc.createElement( message.operationName() + ((inInputPort) ? "Response" : "") ); doc.appendChild( root ); if( message.isFault() ) { Element faultElement = doc.createElement( message.fault().faultName() ); root.appendChild( faultElement ); XmlUtils.valueToDocument( message.fault().value(), faultElement, doc ); } else { XmlUtils.valueToDocument( message.value(), root, doc ); } Source src = new DOMSource( doc ); ByteArrayOutputStream tmpStream = new ByteArrayOutputStream(); Result dest = new StreamResult( tmpStream ); transformer.setOutputProperty( OutputKeys.ENCODING, charset ); try { transformer.transform( src, dest ); } catch( TransformerException e ) { throw new IOException( e ); } ret.content = new ByteArray( tmpStream.toByteArray() ); } else if( "binary".equals( format ) ) { ret.contentType = "application/octet-stream"; ret.content = message.value().byteArrayValue(); } else if( "html".equals( format ) ) { ret.contentType = "text/html"; if( message.isFault() ) { StringBuilder builder = new StringBuilder(); builder.append( "<html><head><title>" ) .append( message.fault().faultName() ) .append( "</title></head><body>" ) .append( message.fault().value().strValue() ) .append( "</body></html>" ); ret.content = new ByteArray( builder.toString().getBytes( charset ) ); } else { ret.content = new ByteArray( message.value().strValue().getBytes( charset ) ); } } else if( "multipart/form-data".equals( format ) ) { ret.contentType = "multipart/form-data; boundary=" + BOUNDARY; ByteArrayOutputStream bStream = new ByteArrayOutputStream(); StringBuilder builder = new StringBuilder(); for( Entry< String, ValueVector > entry : message.value().children().entrySet() ) { if( !entry.getKey().startsWith( "@" ) ) { builder.append( "--" ).append( BOUNDARY ).append( HttpUtils.CRLF ) .append( "Content-Disposition: form-data; name=\"" ).append( entry.getKey() ).append( '\"' ); boolean isBinary = false; if( hasOperationSpecificParameter( message.operationName(), Parameters.MULTIPART_HEADERS ) ) { Value specOpParam = getOperationSpecificParameterFirstValue( message.operationName(), Parameters.MULTIPART_HEADERS ); if( specOpParam.hasChildren( "partName" ) ) { ValueVector partNames = specOpParam.getChildren( "partName" ); for( int p = 0; p < partNames.size(); p++ ) { if( partNames.get( p ).hasChildren( "part" ) ) { if( partNames.get( p ).getFirstChild( "part" ).strValue() .equals( entry.getKey() ) ) { isBinary = true; if( partNames.get( p ).hasChildren( "filename" ) ) { builder.append( "; filename=\"" ) .append( partNames.get( p ).getFirstChild( "filename" ).strValue() ) .append( "\"" ); } if( partNames.get( p ).hasChildren( "contentType" ) ) { builder.append( HttpUtils.CRLF ).append( "Content-Type:" ) .append( partNames.get( p ).getFirstChild( "contentType" ).strValue() ); } } } } } } builder.append( HttpUtils.CRLF ).append( HttpUtils.CRLF ); if( isBinary ) { bStream.write( builder.toString().getBytes( charset ) ); bStream.write( entry.getValue().first().byteArrayValue().getBytes() ); builder.delete( 0, builder.length() - 1 ); builder.append( HttpUtils.CRLF ); } else { builder.append( entry.getValue().first().strValue() ).append( HttpUtils.CRLF ); } } } builder.append( "--" + BOUNDARY + "--" ); bStream.write( builder.toString().getBytes( charset ) ); ret.content = new ByteArray( bStream.toByteArray() ); } else if( "x-www-form-urlencoded".equals( format ) ) { ret.contentType = "application/x-www-form-urlencoded"; Iterator< Entry< String, ValueVector > > it = message.value().children().entrySet().iterator(); StringBuilder builder = new StringBuilder(); if( message.isFault() ) { builder.append( "faultName=" ) .append( URLEncoder.encode( message.fault().faultName(), HttpUtils.URL_DECODER_ENC ) ) .append( "&data=" ) .append( URLEncoder.encode( message.fault().value().strValue(), HttpUtils.URL_DECODER_ENC ) ); } else { Entry< String, ValueVector > entry; while( it.hasNext() ) { entry = it.next(); builder.append( URLEncoder.encode( entry.getKey(), HttpUtils.URL_DECODER_ENC ) ) .append( "=" ) .append( URLEncoder.encode( entry.getValue().first().strValue(), HttpUtils.URL_DECODER_ENC ) ); if( it.hasNext() ) { builder.append( '&' ); } } } ret.content = new ByteArray( builder.toString().getBytes( charset ) ); } else if( "json".equals( format ) ) { ret.contentType = ContentTypes.APPLICATION_JSON; StringBuilder jsonStringBuilder = new StringBuilder(); if( message.isFault() ) { Value error = message.value().getFirstChild( "error" ); error.getFirstChild( "code" ).setValue( -32000 ); error.getFirstChild( "message" ).setValue( message.fault().faultName() ); error.getChildren( "data" ).set( 0, message.fault().value() ); JsUtils.faultValueToJsonString( message.value(), getSendType( message ), jsonStringBuilder ); } else { JsUtils.valueToJsonString( message.value(), true, getSendType( message ), jsonStringBuilder ); } ret.content = new ByteArray( jsonStringBuilder.toString().getBytes( charset ) ); } else if( "ndjson".equals( format ) ) { ret.contentType = ContentTypes.APPLICATION_NDJSON; StringBuilder ndJsonStringBuilder = new StringBuilder(); if( message.isFault() ) { Value error = message.value().getFirstChild( "error" ); error.getFirstChild( "code" ).setValue( -32000 ); error.getFirstChild( "message" ).setValue( message.fault().faultName() ); error.getChildren( "data" ).set( 0, message.fault().value() ); JsUtils.faultValueToJsonString( message.value(), getSendType( message ), ndJsonStringBuilder ); } else { if( !message.value().hasChildren( "item" ) ) { Interpreter.getInstance().logWarning( "ndJson requires at least one child node 'item'" ); } JsUtils.valueToNdJsonString( message.value(), true, getSendType( message ), ndJsonStringBuilder ); } ret.content = new ByteArray( ndJsonStringBuilder.toString().getBytes( charset ) ); } else if( "raw".equals( format ) ) { ret.contentType = "text/plain"; if( message.isFault() ) { ret.content = new ByteArray( message.fault().value().strValue().getBytes( charset ) ); } else { ret.content = new ByteArray( message.value().strValue().getBytes( charset ) ); } } return ret; } private static boolean isLocationNeeded( int statusCode ) { return LOCATION_REQUIRED_STATUS_CODES.contains( statusCode ); } private void send_appendResponseUserHeader( CommMessage message, StringBuilder headerBuilder ) { Value responseHeaderParameters = null; if( hasOperationSpecificParameter( message.operationName(), Parameters.RESPONSE_USER ) ) { responseHeaderParameters = getOperationSpecificParameterFirstValue( message.operationName(), Parameters.RESPONSE_USER ); if( (responseHeaderParameters != null) && (responseHeaderParameters.hasChildren( Parameters.HEADER_USER )) ) { for( Entry< String, ValueVector > entry : responseHeaderParameters .getFirstChild( Parameters.HEADER_USER ).children().entrySet() ) for( int counter = 0; counter < entry.getValue().size(); counter++ ) { headerBuilder.append( entry.getKey() ).append( ": " ) .append( entry.getValue().get( counter ).strValue() ) .append( HttpUtils.CRLF ); } } } responseHeaderParameters = null; if( hasParameter( Parameters.RESPONSE_USER ) ) { responseHeaderParameters = getParameterFirstValue( Parameters.RESPONSE_USER ); if( (responseHeaderParameters != null) && (responseHeaderParameters.hasChildren( Parameters.HEADER_USER )) ) { for( Entry< String, ValueVector > entry : responseHeaderParameters .getFirstChild( Parameters.HEADER_USER ).children().entrySet() ) for( int counter = 0; counter < entry.getValue().size(); counter++ ) { headerBuilder.append( entry.getKey() ).append( ": " ) .append( entry.getValue().get( counter ).strValue() ) .append( HttpUtils.CRLF ); } } } } private void send_appendResponseHeaders( CommMessage message, StringBuilder headerBuilder ) { int statusCode = DEFAULT_STATUS_CODE; String statusDescription = null; if( message.isFault() && hasOperationSpecificParameter( message.operationName(), Parameters.STATUS_CODES ) ) { Value exceptionsValue = getOperationSpecificParameterFirstValue( message.operationName(), Parameters.STATUS_CODES ); if( exceptionsValue.hasChildren( message.fault().faultName() ) ) { statusCode = exceptionsValue.getFirstChild( message.fault().faultName() ).intValue(); } } else if( hasParameter( Parameters.STATUS_CODE ) ) { statusCode = getIntParameter( Parameters.STATUS_CODE ); if( !STATUS_CODE_DESCRIPTIONS.containsKey( statusCode ) ) { Interpreter.getInstance().logWarning( "HTTP protocol for operation " + message.operationName() + " is sending a message with status code " + statusCode + ", which is not in the HTTP specifications." ); statusDescription = "Internal Server Error"; } else if( isLocationNeeded( statusCode ) && !hasParameter( Parameters.REDIRECT ) ) { // if statusCode is a redirection code, location parameter is needed Interpreter.getInstance().logWarning( "HTTP protocol for operation " + message.operationName() + " is sending a message with status code " + statusCode + ", which expects a redirect parameter but the latter is not set." ); } } else if( hasParameter( Parameters.REDIRECT ) ) { statusCode = DEFAULT_REDIRECTION_STATUS_CODE; } else if( message.isFault() ) { statusCode = 500; } if( statusDescription == null ) { statusDescription = STATUS_CODE_DESCRIPTIONS.get( statusCode ); } headerBuilder.append( "HTTP/1.1 " ).append( statusCode ).append( " " ).append( statusDescription ) .append( HttpUtils.CRLF ); // if redirect has been set, the redirect location parameter is set if( hasParameter( Parameters.REDIRECT ) ) { headerBuilder.append( "Location: " ).append( getStringParameter( Parameters.REDIRECT ) ) .append( HttpUtils.CRLF ); } send_appendSetCookieHeader( message, headerBuilder ); headerBuilder.append( "Server: Jolie" ).append( HttpUtils.CRLF ); StringBuilder cacheControlHeader = new StringBuilder(); if( hasParameter( Parameters.CACHE_CONTROL ) ) { Value cacheControl = getParameterFirstValue( Parameters.CACHE_CONTROL ); if( cacheControl.hasChildren( "maxAge" ) ) { cacheControlHeader.append( "max-age=" ).append( cacheControl.getFirstChild( "maxAge" ).intValue() ); } } if( cacheControlHeader.length() > 0 ) { headerBuilder.append( "Cache-Control: " ).append( cacheControlHeader ).append( HttpUtils.CRLF ); } } private static void send_appendRequestMethod( Method method, StringBuilder headerBuilder ) { headerBuilder.append( method.id() ); } private void send_appendRequestPath( CommMessage message, Method method, String qsFormat, StringBuilder headerBuilder ) throws IOException { String path = uri.getRawPath(); if( uri.getScheme().equals( "localsocket" ) || path == null || path.isEmpty() || checkBooleanParameter( Parameters.DROP_URI_PATH, false ) ) { headerBuilder.append( '/' ); } else { if( path.charAt( 0 ) != '/' ) { headerBuilder.append( '/' ); } headerBuilder.append( path ); final Matcher m = LocationParser.RESOURCE_SEPARATOR_PATTERN.matcher( path ); if( m.find() ) { if( !m.find() ) { headerBuilder.append( LocationParser.RESOURCE_SEPARATOR ); } } } if( hasOperationSpecificParameter( message.operationName(), Parameters.ALIAS ) ) { String alias = getOperationSpecificStringParameter( message.operationName(), Parameters.ALIAS ); send_appendParsedAlias( alias, message.value(), headerBuilder ); } else if( hasOperationSpecificParameter( message.operationName(), Parameters.TEMPLATE ) ) { String template = getOperationSpecificStringParameter( message.operationName(), Parameters.TEMPLATE ); send_appendParsedTemplate( template, message.value(), headerBuilder ); } else { headerBuilder.append( message.operationName() ); } if( method == Method.GET ) { if( qsFormat.equals( "json" ) ) { send_appendJsonQueryString( message, headerBuilder ); } else { send_appendQuerystring( message.value(), headerBuilder, message ); } } } private void send_appendParsedTemplate( String template, Value value, StringBuilder headerBuilder ) { List< String > templateKeys = new ArrayList<>(); UriUtils uriUtils = new UriUtils(); Map< String, Object > params = new HashMap<>(); for( final Map.Entry< String, ValueVector > entry : value.children() .entrySet() ) { params.put( entry.getKey(), entry.getValue().first().valueObject() ); } String uri = uriUtils.expand( template, params ); /* cleaning value from used keys */ uriUtils.match( template, uri ).children().forEach( ( s, values ) -> { templateKeys.add( s ); } ); templateKeys.forEach( value.children()::remove ); headerBuilder.append( uri ); } private static void send_appendAuthorizationHeader( CommMessage message, StringBuilder headerBuilder ) { if( message.value() .hasChildren( jolie.lang.Constants.Predefined.HTTP_BASIC_AUTHENTICATION.token().content() ) ) { Value v = message.value() .getFirstChild( jolie.lang.Constants.Predefined.HTTP_BASIC_AUTHENTICATION.token().content() ); // String realm = v.getFirstChild( "realm" ).strValue(); String userpass = v.getFirstChild( "userid" ).strValue() + ":" + v.getFirstChild( "password" ).strValue(); Base64.Encoder encoder = Base64.getEncoder(); userpass = encoder.encodeToString( userpass.getBytes() ); headerBuilder.append( "Authorization: Basic " ).append( userpass ).append( HttpUtils.CRLF ); message.value().children() .remove( jolie.lang.Constants.Predefined.HTTP_BASIC_AUTHENTICATION.token().content() ); } } private void send_appendRequestUserHeader( CommMessage message, StringBuilder headerBuilder ) { Value responseHeaderParameters = null; if( hasOperationSpecificParameter( message.operationName(), Parameters.REQUEST_USER ) ) { responseHeaderParameters = getOperationSpecificParameterFirstValue( message.operationName(), Parameters.RESPONSE_USER ); if( (responseHeaderParameters != null) && (responseHeaderParameters.hasChildren( Parameters.HEADER_USER )) ) { for( Entry< String, ValueVector > entry : responseHeaderParameters .getFirstChild( Parameters.HEADER_USER ).children().entrySet() ) headerBuilder.append( entry.getKey() ).append( ": " ).append( entry.getValue().first().strValue() ) .append( HttpUtils.CRLF ); } } responseHeaderParameters = null; if( hasParameter( Parameters.RESPONSE_USER ) ) { responseHeaderParameters = getParameterFirstValue( Parameters.REQUEST_USER ); if( (responseHeaderParameters != null) && (responseHeaderParameters.hasChildren( Parameters.HEADER_USER )) ) { for( Entry< String, ValueVector > entry : responseHeaderParameters .getFirstChild( Parameters.HEADER_USER ).children().entrySet() ) headerBuilder.append( entry.getKey() ).append( ": " ).append( entry.getValue().first().strValue() ) .append( HttpUtils.CRLF ); } } } private void send_appendHeader( StringBuilder headerBuilder ) { if( hasParameter( Parameters.ADD_HEADERS ) ) { Value v = getParameterFirstValue( Parameters.ADD_HEADERS ); if( v.hasChildren( "header" ) ) { for( Value head : v.getChildren( "header" ) ) { String header = head.strValue() + ": " + head.getFirstChild( "value" ).strValue(); headerBuilder.append( header ).append( HttpUtils.CRLF ); } } } if( !inInputPort && hasParameter( Parameters.REQUEST_HEADERS ) ) { getParameterFirstValue( Parameters.REQUEST_HEADERS ) .children().forEach( ( header, vector ) -> { headerBuilder.append( header ) .append( ": " ) .append( vector.first().strValue() ) .append( HttpUtils.CRLF ); } ); } } private Method send_getRequestMethod( CommMessage message ) throws IOException { return hasOperationSpecificParameter( message.operationName(), Parameters.METHOD ) ? Method.fromString( getOperationSpecificStringParameter( message.operationName(), Parameters.METHOD ) ) : hasParameterValue( Parameters.METHOD ) ? Method.fromString( getStringParameter( Parameters.METHOD ) ) : Method.POST; } private void send_appendRequestHeaders( CommMessage message, Method method, String qsFormat, StringBuilder headerBuilder ) throws IOException { send_appendRequestMethod( method, headerBuilder ); headerBuilder.append( ' ' ); send_appendRequestPath( message, method, qsFormat, headerBuilder ); headerBuilder.append( " HTTP/1.1" ).append( HttpUtils.CRLF ); String host = uri.getHost(); if( uri.getScheme().equals( "localsocket" ) ) { /* * in this case we need to replace the localsocket path with a host, that is the default one * localhost */ host = "localhost"; } headerBuilder.append( "Host: " ).append( host ).append( HttpUtils.CRLF ); send_appendCookies( message, uri.getHost(), headerBuilder ); send_appendAuthorizationHeader( message, headerBuilder ); if( checkBooleanParameter( Parameters.COMPRESSION, true ) ) { String requestCompression = getStringParameter( Parameters.REQUEST_COMPRESSION ); if( requestCompression.equals( "gzip" ) || requestCompression.equals( "deflate" ) ) { encoding = requestCompression; headerBuilder.append( "Accept-Encoding: " ).append( encoding ).append( HttpUtils.CRLF ); } else { headerBuilder.append( "Accept-Encoding: gzip, deflate" ).append( HttpUtils.CRLF ); } } send_appendHeader( headerBuilder ); if( hasOperationSpecificParameter( message.operationName(), Parameters.OUTGOING_HEADERS ) ) { send_operationSpecificHeader( message.value(), getOperationSpecificParameterFirstValue( message.operationName(), Parameters.OUTGOING_HEADERS ), headerBuilder ); } } private void send_operationSpecificHeader( Value value, Value outboundHeaders, StringBuilder headerBuilder ) { List< String > headersKeys = new ArrayList<>(); outboundHeaders.children().forEach( ( headerName, headerValues ) -> { headerBuilder.append( headerName ).append( ": " ) .append( value.getFirstChild( headerValues.get( 0 ).strValue() ).strValue() ) .append( HttpUtils.CRLF ); headersKeys.add( headerValues.get( 0 ).strValue() ); } ); headersKeys.forEach( value.children()::remove ); } private void send_appendGenericHeaders( CommMessage message, EncodedContent encodedContent, String charset, StringBuilder headerBuilder ) throws IOException { if( !checkBooleanParameter( Parameters.KEEP_ALIVE, true ) ) { if( inInputPort ) // we may do this only in input (server) mode channel().setToBeClosed( true ); headerBuilder.append( "Connection: close" ).append( HttpUtils.CRLF ); } if( checkBooleanParameter( Parameters.CONCURRENT, true ) ) { headerBuilder.append( Headers.JOLIE_MESSAGE_ID ).append( ": " ).append( message.requestId() ) .append( HttpUtils.CRLF ); } headerBuilder.append( Headers.JOLIE_RESOURCE_PATH ).append( ": " ).append( message.resourcePath() ) .append( HttpUtils.CRLF ); String contentType = getStringParameter( Parameters.CONTENT_TYPE ); if( contentType.length() > 0 ) { encodedContent.contentType = contentType; } encodedContent.contentType = encodedContent.contentType.toLowerCase(); headerBuilder.append( "Content-Type: " ).append( encodedContent.contentType ); if( charset != null ) { headerBuilder.append( "; charset=" ).append( charset.toLowerCase() ); } headerBuilder.append( HttpUtils.CRLF ); if( encodedContent.content != null ) { String transferEncoding = getStringParameter( Parameters.CONTENT_TRANSFER_ENCODING ); if( transferEncoding.length() > 0 ) { headerBuilder.append( "Content-Transfer-Encoding: " ).append( transferEncoding ) .append( HttpUtils.CRLF ); } String contentDisposition = getStringParameter( Parameters.CONTENT_DISPOSITION ); if( contentDisposition.length() > 0 ) { encodedContent.contentDisposition = contentDisposition; headerBuilder.append( "Content-Disposition: " ).append( encodedContent.contentDisposition ) .append( HttpUtils.CRLF ); } boolean compression = encoding != null && checkBooleanParameter( Parameters.COMPRESSION, true ); String compressionTypes = getStringParameter( Parameters.COMPRESSION_TYPES, "text/html text/css text/plain text/xml text/x-js application/json application/javascript application/x-www-form-urlencoded application/xhtml+xml application/xml x-font/otf x-font/ttf application/x-font-ttf" ) .toLowerCase(); if( compression && !compressionTypes.equals( "*" ) && !compressionTypes.contains( encodedContent.contentType ) ) { compression = false; } if( compression ) { Interpreter.getInstance().tracer().trace( () -> { try { final String traceMessage = encodedContent.content.toString( charset ); return new ProtocolTraceAction( ProtocolTraceAction.Type.HTTP, "HTTP COMPRESSING MESSAGE", message.resourcePath(), traceMessage, null ); } catch( UnsupportedEncodingException e ) { return new ProtocolTraceAction( ProtocolTraceAction.Type.HTTP, "HTTP COMPRESSING MESSAGE", message.resourcePath(), e.getMessage(), null ); } } ); encodedContent.content = HttpUtils.encode( encoding, encodedContent.content, headerBuilder ); } headerBuilder.append( "Content-Length: " ).append( encodedContent.content.size() ).append( HttpUtils.CRLF ); } else { headerBuilder.append( "Content-Length: 0" ).append( HttpUtils.CRLF ); } } private String prepareSendDebugString( CharSequence header, EncodedContent encodedContent, String charset, boolean showContent ) throws UnsupportedEncodingException { StringBuilder debugSB = new StringBuilder(); debugSB.append( "[HTTP debug] Sending:\n" ) .append( header ); if( showContent && encodedContent != null && encodedContent.content != null ) { debugSB.append( encodedContent.content.toString( charset ) ); } return debugSB.toString(); } private void send_logDebugInfo( CharSequence header, EncodedContent encodedContent, String charset ) throws IOException { if( checkBooleanParameter( Parameters.DEBUG ) ) { boolean showContent = false; if( getParameterVector( Parameters.DEBUG ).first().getFirstChild( "showContent" ).intValue() > 0 && encodedContent.content != null ) { showContent = true; } Interpreter.getInstance().logInfo( prepareSendDebugString( header, encodedContent, charset, showContent ) ); } } @Override public void send_internal( OutputStream ostream, CommMessage message, InputStream istream ) throws IOException { Method method = send_getRequestMethod( message ); String charset = HttpUtils.getCharset( getStringParameter( Parameters.CHARSET, "utf-8" ), null ); String format = send_getFormat(); String contentType = null; StringBuilder headerBuilder = new StringBuilder(); if( inInputPort ) { // We're responding to a request send_appendResponseHeaders( message, headerBuilder ); send_appendResponseUserHeader( message, headerBuilder ); send_appendHeader( headerBuilder ); } else { // We're sending a notification or a solicit String qsFormat = ""; if( method == Method.GET && getParameterFirstValue( Parameters.METHOD ).hasChildren( "queryFormat" ) ) { if( getParameterFirstValue( Parameters.METHOD ).getFirstChild( "queryFormat" ).strValue() .equals( "json" ) ) { qsFormat = format = "json"; contentType = ContentTypes.APPLICATION_JSON; } } send_appendRequestUserHeader( message, headerBuilder ); send_appendRequestHeaders( message, method, qsFormat, headerBuilder ); } EncodedContent encodedContent = send_encodeContent( message, method, charset, format ); if( contentType != null ) { encodedContent.contentType = contentType; } // message's body in string format needed for the monitoring String bodyMessageString = encodedContent != null && encodedContent.content != null ? encodedContent.content.toString( charset ) : ""; if( Interpreter.getInstance().isMonitoring() ) { Interpreter.getInstance().fireMonitorEvent( new ProtocolMessageEvent( bodyMessageString, headerBuilder.toString(), ExecutionThread.currentThread().getSessionId(), Long.toString( message.id() ), ProtocolMessageEvent.Protocol.HTTP ) ); } send_appendGenericHeaders( message, encodedContent, charset, headerBuilder ); headerBuilder.append( HttpUtils.CRLF ); send_logDebugInfo( headerBuilder, encodedContent, charset ); Interpreter.getInstance().tracer().trace( () -> { try { final String traceMessage = prepareSendDebugString( headerBuilder, encodedContent, charset, true ); return new ProtocolTraceAction( ProtocolTraceAction.Type.HTTP, "HTTP MESSAGE SENT", message.resourcePath(), traceMessage, null ); } catch( UnsupportedEncodingException e ) { return new ProtocolTraceAction( ProtocolTraceAction.Type.HTTP, "HTTP MESSAGE SENT", message.resourcePath(), e.getMessage(), null ); } } ); inputId = message.operationName(); ostream.write( headerBuilder.toString().getBytes( HttpUtils.URL_DECODER_ENC ) ); if( encodedContent.content != null && !headRequest ) { ostream.write( encodedContent.content.getBytes() ); } headRequest = false; } @Override public void send( OutputStream ostream, CommMessage message, InputStream istream ) throws IOException { HttpUtils.send( ostream, message, istream, inInputPort, channel(), this ); } private void parseXML( HttpMessage message, Value value, String charset ) throws IOException { try { if( message.size() > 0 ) { DocumentBuilder builder = docBuilderFactory.newDocumentBuilder(); InputSource src = new InputSource( new ByteArrayInputStream( message.content() ) ); src.setEncoding( charset ); Document doc = builder.parse( src ); XmlUtils.documentToValue( doc, value, false ); } } catch( ParserConfigurationException | SAXException pce ) { throw new IOException( pce ); } } private static void parseJson( HttpMessage message, Value value, boolean strictEncoding, String charset ) throws IOException { JsUtils.parseJsonIntoValue( new InputStreamReader( new ByteArrayInputStream( message.content() ), charset ), value, strictEncoding ); } private static void parseNdJson( HttpMessage message, Value value, boolean strictEncoding, String charset ) throws IOException { JsUtils.parseNdJsonIntoValue( new BufferedReader( new InputStreamReader( new ByteArrayInputStream( message.content() ), charset ) ), value, strictEncoding ); } private static void parseForm( HttpMessage message, Value value, String charset ) throws IOException { String line = new String( message.content(), charset ); String[] pair; for( String item : line.split( "&" ) ) { pair = item.split( "=", 2 ); if( pair.length > 1 ) { value.getChildren( URLDecoder.decode( pair[ 0 ], HttpUtils.URL_DECODER_ENC ) ).first() .setValue( URLDecoder.decode( pair[ 1 ], HttpUtils.URL_DECODER_ENC ) ); } } } private void parseMultiPartFormData( HttpMessage message, Value value ) // , String charset ) throws IOException { multiPartFormDataParser = new MultiPartFormDataParser( message, value ); multiPartFormDataParser.parse(); } private void recv_checkForSetCookie( HttpMessage message, Value value ) throws IOException { if( hasParameter( Parameters.COOKIES ) ) { String type; Value cookies = getParameterFirstValue( Parameters.COOKIES ); Value cookieConfig; Value v; for( HttpMessage.Cookie cookie : message.setCookies() ) { if( cookies.hasChildren( cookie.name() ) ) { cookieConfig = cookies.getFirstChild( cookie.name() ); if( cookieConfig.isString() ) { v = value.getFirstChild( cookieConfig.strValue() ); type = cookieConfig.hasChildren( "type" ) ? cookieConfig.getFirstChild( "type" ).strValue() : "string"; recv_assignCookieValue( cookie.value(), v, type ); } } /* * currValue = Value.create(); currValue.getNewChild( "expires" ).setValue( cookie.expirationDate() * ); currValue.getNewChild( "path" ).setValue( cookie.path() ); currValue.getNewChild( "name" * ).setValue( cookie.name() ); currValue.getNewChild( "value" ).setValue( cookie.value() ); * currValue.getNewChild( "domain" ).setValue( cookie.domain() ); currValue.getNewChild( "secure" * ).setValue( (cookie.secure() ? 1 : 0) ); cookieVec.add( currValue ); */ } } } private static void recv_assignCookieValue( String cookieValue, Value value, String typeKeyword ) throws IOException { NativeType type = NativeType.fromString( typeKeyword ); if( NativeType.INT == type ) { try { value.setValue( Integer.valueOf( cookieValue ) ); } catch( NumberFormatException e ) { throw new IOException( e ); } } else if( NativeType.LONG == type ) { try { value.setValue( Long.valueOf( cookieValue ) ); } catch( NumberFormatException e ) { throw new IOException( e ); } } else if( NativeType.STRING == type ) { value.setValue( cookieValue ); } else if( NativeType.DOUBLE == type ) { try { value.setValue( new Double( cookieValue ) ); } catch( NumberFormatException e ) { throw new IOException( e ); } } else if( NativeType.BOOL == type ) { value.setValue( Boolean.valueOf( cookieValue ) ); } else { value.setValue( cookieValue ); } } private void recv_checkForCookies( HttpMessage message, DecodedMessage decodedMessage ) throws IOException { Value cookies = null; if( hasOperationSpecificParameter( decodedMessage.operationName, Parameters.COOKIES ) ) { cookies = getOperationSpecificParameterFirstValue( decodedMessage.operationName, Parameters.COOKIES ); } else if( hasParameter( Parameters.COOKIES ) ) { cookies = getParameterFirstValue( Parameters.COOKIES ); } if( cookies != null ) { Value v; String type; for( Entry< String, String > entry : message.cookies().entrySet() ) { if( cookies.hasChildren( entry.getKey() ) ) { Value cookieConfig = cookies.getFirstChild( entry.getKey() ); if( cookieConfig.isString() ) { v = decodedMessage.value.getFirstChild( cookieConfig.strValue() ); if( cookieConfig.hasChildren( "type" ) ) { type = cookieConfig.getFirstChild( "type" ).strValue(); } else { type = "string"; } recv_assignCookieValue( entry.getValue(), v, type ); } } } } } private void recv_checkForGenericHeader( HttpMessage message, DecodedMessage decodedMessage ) throws IOException { Value headers = null; if( hasOperationSpecificParameter( decodedMessage.operationName, Parameters.INCOMING_HEADERS ) ) { headers = getOperationSpecificParameterFirstValue( decodedMessage.operationName, Parameters.INCOMING_HEADERS ); } else if( hasOperationSpecificParameter( decodedMessage.operationName, Parameters.HEADERS ) ) { headers = getOperationSpecificParameterFirstValue( decodedMessage.operationName, Parameters.HEADERS ); } else if( hasParameter( Parameters.HEADERS ) ) { headers = getParameterFirstValue( Parameters.HEADERS ); } if( headers != null ) { if( headers.hasChildren( Parameters.HEADERS_WILDCARD ) ) { String headerAlias = headers.getFirstChild( Parameters.HEADERS_WILDCARD ).strValue(); message.properties().forEach( propertyEntry -> { decodedMessage.value.getFirstChild( headerAlias ) .getFirstChild( propertyEntry.getKey() ) .setValue( propertyEntry.getValue() ); } ); } else { for( String headerName : headers.children().keySet() ) { String headerAlias = headers.getFirstChild( headerName ).strValue(); decodedMessage.value.getFirstChild( headerAlias ) .setValue( message.getPropertyOrEmptyString( headerName.replace( "_", "-" ) ) ); } } } } private static void recv_parseQueryString( HttpMessage message, Value value, String contentType, boolean strictEncoding ) throws IOException { if( message.isGet() && contentType.equals( ContentTypes.APPLICATION_JSON ) ) { recv_parseJsonQueryString( message, value, strictEncoding ); } else { Map< String, Integer > indexes = new HashMap<>(); String queryString = message.requestPath(); String[] kv = queryString.split( "\\?", 2 ); Integer index; if( kv.length > 1 ) { queryString = kv[ 1 ]; String[] params = queryString.split( "&" ); for( String param : params ) { String[] ikv = param.split( "=", 2 ); if( ikv.length > 1 ) { index = indexes.computeIfAbsent( ikv[ 0 ], k -> 0 ); // the query string was already URL decoded by the HttpParser value.getChildren( ikv[ 0 ] ).get( index ).setValue( ikv[ 1 ] ); indexes.put( ikv[ 0 ], index + 1 ); } } } } } private static void recv_parseJsonQueryString( HttpMessage message, Value value, boolean strictEncoding ) throws IOException { String queryString = message.requestPath(); String[] kv = queryString.split( "\\?", 2 ); if( kv.length > 1 ) { // the query string was already URL decoded by the HttpParser JsUtils.parseJsonIntoValue( new StringReader( kv[ 1 ] ), value, strictEncoding ); } } /* * Prints debug information about a received message */ private String getDebugMessage( HttpMessage message, String charset, boolean showContent ) throws IOException { StringBuilder debugSB = new StringBuilder(); debugSB.append( "\n[HTTP debug] Receiving:\n" ).append( getHttpHeader( message ) ); if( showContent ) { debugSB.append( "--> Message content\n" ) .append( getHttpBody( message, charset ) ); } return debugSB.toString(); } /* * return the received message's header */ private static String getHttpHeader( HttpMessage message ) throws IOException { StringBuilder headerStr = new StringBuilder(); headerStr.append( "HTTP Code: " ).append( message.statusCode() ) .append( "\n" ).append( "HTTP Method: " ).append( message.type().name() ).append( "\n" ) .append( "Resource: " ).append( message.requestPath() ).append( "\n" ) .append( "--> Header properties\n" ); for( Entry< String, String > entry : message.properties() ) { headerStr.append( '\t' ).append( entry.getKey() ).append( ": " ).append( entry.getValue() ).append( '\n' ); } for( HttpMessage.Cookie cookie : message.setCookies() ) { headerStr.append( "\tset-cookie: " ).append( cookie.toString() ).append( '\n' ); } for( Entry< String, String > entry : message.cookies().entrySet() ) { headerStr.append( "\tcookie: " ).append( entry.getKey() ).append( '=' ).append( entry.getValue() ) .append( '\n' ); } return headerStr.toString(); } /* * Prints debug information about a received message */ private static String getHttpBody( HttpMessage message, String charset ) throws IOException { StringBuilder bodyStr = new StringBuilder(); bodyStr.append( new String( message.content(), charset ) ); return bodyStr.toString(); } private void recv_parseRequestFormat( String type ) throws IOException { responseFormat = null; if( "text/xml".equals( type ) ) { responseFormat = "xml"; } else if( ContentTypes.APPLICATION_JSON.equals( type ) ) { responseFormat = "json"; } } private void recv_parseMessage( HttpMessage message, DecodedMessage decodedMessage, String type, String charset ) throws IOException { final String operationName = message.isResponse() ? inputId : decodedMessage.operationName; if( getOperationSpecificStringParameter( operationName, Parameters.FORCE_CONTENT_DECODING ) .equals( NativeType.STRING.id() ) ) { decodedMessage.value.setValue( new String( message.content(), charset ) ); } else if( getOperationSpecificStringParameter( operationName, Parameters.FORCE_CONTENT_DECODING ) .equals( NativeType.RAW.id() ) ) { decodedMessage.value.setValue( new ByteArray( message.content() ) ); } else if( "text/html".equals( type ) ) { decodedMessage.value.setValue( new String( message.content(), charset ) ); } else if( "application/x-www-form-urlencoded".equals( type ) ) { parseForm( message, decodedMessage.value, charset ); } else if( "text/xml".equals( type ) || type.contains( "xml" ) ) { parseXML( message, decodedMessage.value, charset ); } else if( "multipart/form-data".equals( type ) ) { parseMultiPartFormData( message, decodedMessage.value ); } else if( "application/octet-stream".equals( type ) || type.startsWith( "image/" ) || "application/zip".equals( type ) ) { decodedMessage.value.setValue( new ByteArray( message.content() ) ); } else if( ContentTypes.APPLICATION_NDJSON.equals( type ) || type.contains( "ndjson" ) ) { boolean strictEncoding = checkStringParameter( Parameters.JSON_ENCODING, "strict" ); parseNdJson( message, decodedMessage.value, strictEncoding, charset ); } else if( ContentTypes.APPLICATION_JSON.equals( type ) || type.contains( "json" ) ) { boolean strictEncoding = checkStringParameter( Parameters.JSON_ENCODING, "strict" ); parseJson( message, decodedMessage.value, strictEncoding, charset ); } else { decodedMessage.value.setValue( new String( message.content(), charset ) ); } } private String getDefaultOperation( HttpMessage.Type t ) { if( hasParameter( Parameters.DEFAULT_OPERATION ) ) { Value dParam = getParameterFirstValue( Parameters.DEFAULT_OPERATION ); String method = HttpUtils.httpMessageTypeToString( t ); if( method == null || dParam.hasChildren( method ) == false ) { return dParam.strValue(); } else { return dParam.getFirstChild( method ).strValue(); } } return null; } private String cutBeforeQuerystring( String requestPath ) { return requestPath.split( "\\?", 2 )[ 0 ]; } private void recv_checkReceivingOperation( HttpMessage message, DecodedMessage decodedMessage ) { if( decodedMessage.operationName == null ) { final String requestPath = cutBeforeQuerystring( message.requestPath() ).substring( 1 ); if( requestPath.startsWith( LocationParser.RESOURCE_SEPARATOR ) ) { final String compositePath = requestPath.substring( LocationParser.RESOURCE_SEPARATOR.length() - 1 ); final Matcher m = LocationParser.RESOURCE_SEPARATOR_PATTERN.matcher( compositePath ); if( m.find() ) { decodedMessage.resourcePath = compositePath.substring( 0, m.start() ); decodedMessage.operationName = compositePath.substring( m.end() ); } else { decodedMessage.resourcePath = compositePath; } } else { decodedMessage.operationName = requestPath; decodedMessage.resourcePath = message.getProperty( Headers.JOLIE_RESOURCE_PATH ); if( decodedMessage.resourcePath == null ) { decodedMessage.resourcePath = "/"; } } } } private void recv_templatedOperation( HttpMessage message, DecodedMessage decodedMessage ) { if( message.getMethod().isEmpty() ) return; // FIXME, TODO: strange jolie double slash String uri = cutBeforeQuerystring( message.requestPath().startsWith( " ? message.requestPath().substring( 1 ) : message.requestPath() ); Value configurationValue = getParameterFirstValue( CommProtocol.Parameters.OPERATION_SPECIFIC_CONFIGURATION ); Iterator< Entry< String, ValueVector > > configurationIterator = configurationValue.children().entrySet() .iterator(); boolean foundMatch = false; while( configurationIterator.hasNext() & !foundMatch ) { Entry< String, ValueVector > configEntry = configurationIterator.next(); Value opConfig = configEntry.getValue().get( 0 ); Value uriTemplateResult = Value.create(); if( opConfig.hasChildren( Parameters.TEMPLATE ) ) { uriTemplateResult = UriUtils.match( opConfig.getFirstChild( Parameters.TEMPLATE ).strValue(), uri ); } String opConfigMethod = opConfig.getFirstChild( Parameters.METHOD ).strValue(); if( uriTemplateResult.boolValue() && message.getMethod().equalsIgnoreCase( opConfigMethod ) ) { foundMatch = true; decodedMessage.operationName = configEntry.getKey(); decodedMessage.resourcePath = "/"; Iterator< Entry< String, ValueVector > > uriTemplateIterator = uriTemplateResult.children().entrySet() .iterator(); while( uriTemplateIterator.hasNext() ) { Entry< String, ValueVector > entry = uriTemplateIterator.next(); decodedMessage.value.getFirstChild( entry.getKey() ) .setValue( entry.getValue().get( 0 ).strValue() ); } if( opConfig.hasChildren( Parameters.INCOMING_HEADERS ) ) { Iterator< Entry< String, ValueVector > > inHeadersIterator = opConfig .getFirstChild( Parameters.INCOMING_HEADERS ).children().entrySet().iterator(); while( inHeadersIterator.hasNext() ) { Entry< String, ValueVector > entry = inHeadersIterator.next(); decodedMessage.value.getFirstChild( entry.getValue().get( 0 ).strValue() ) .setValue( message.getProperty( entry.getKey() ) ); } } } } } private void recv_checkDefaultOp( HttpMessage message, DecodedMessage decodedMessage ) { if( decodedMessage.resourcePath.equals( "/" ) && !channel().parentInputPort().canHandleInputOperation( decodedMessage.operationName ) ) { String defaultOpId = getDefaultOperation( message.type() ); if( defaultOpId != null ) { Value body = decodedMessage.value; decodedMessage.value = Value.create(); decodedMessage.value.getChildren( "data" ).add( body ); decodedMessage.value.getFirstChild( "operation" ).setValue( decodedMessage.operationName ); decodedMessage.value.setFirstChild( "requestUri", message.requestPath() ); if( message.userAgent() != null ) { decodedMessage.value.getFirstChild( Parameters.USER_AGENT ).setValue( message.userAgent() ); } Value cookies = decodedMessage.value.getFirstChild( "cookies" ); for( Entry< String, String > cookie : message.cookies().entrySet() ) { cookies.getFirstChild( cookie.getKey() ).setValue( cookie.getValue() ); } decodedMessage.operationName = defaultOpId; } } } private void recv_checkForMultiPartHeaders( DecodedMessage decodedMessage ) { if( multiPartFormDataParser != null ) { String target; for( Entry< String, MultiPartFormDataParser.PartProperties > entry : multiPartFormDataParser .getPartPropertiesSet() ) { if( entry.getValue().filename() != null ) { target = getMultipartHeaderForPart( decodedMessage.operationName, entry.getKey() ); if( target != null ) { decodedMessage.value.getFirstChild( target ).setValue( entry.getValue().filename() ); } } } multiPartFormDataParser = null; } } private void recv_checkForMessageProperties( HttpMessage message, DecodedMessage decodedMessage ) throws IOException { recv_checkForCookies( message, decodedMessage ); recv_checkForGenericHeader( message, decodedMessage ); recv_checkForMultiPartHeaders( decodedMessage ); if( message.userAgent() != null && hasParameter( Parameters.USER_AGENT ) ) { getParameterFirstValue( Parameters.USER_AGENT ).setValue( message.userAgent() ); } if( getParameterVector( Parameters.HOST ) != null ) { getParameterFirstValue( Parameters.HOST ).setValue( message.getPropertyOrEmptyString( Parameters.HOST ) ); } } private static class DecodedMessage { private String operationName = null; private Value value = Value.create(); private String resourcePath = "/"; private long id = CommMessage.GENERIC_REQUEST_ID; } private void recv_checkForStatusCode( HttpMessage message ) { if( hasParameter( Parameters.STATUS_CODE ) ) { getParameterFirstValue( Parameters.STATUS_CODE ).setValue( message.statusCode() ); } } @Override public CommMessage recv_internal( InputStream istream, OutputStream ostream ) throws IOException { HttpMessage message = new HttpParser( istream ).parse(); String charset = HttpUtils.getCharset( null, message ); CommMessage retVal = null; DecodedMessage decodedMessage = new DecodedMessage(); HttpUtils.recv_checkForChannelClosing( message, channel() ); if( checkBooleanParameter( Parameters.DEBUG ) ) { boolean showContent = false; if( getParameterFirstValue( Parameters.DEBUG ).getFirstChild( "showContent" ).intValue() > 0 && message.size() > 0 ) { showContent = true; } Interpreter.getInstance().logInfo( getDebugMessage( message, charset, showContent ) ); } // tracer Interpreter.getInstance().tracer().trace( () -> { try { final String traceMessage = getDebugMessage( message, charset, message.size() > 0 ); return new ProtocolTraceAction( ProtocolTraceAction.Type.HTTP, "HTTP MESSAGE RECEIVED", message.requestPath(), traceMessage, null ); } catch( IOException e ) { return new ProtocolTraceAction( ProtocolTraceAction.Type.HTTP, "HTTP MESSAGE RECEIVED", message.requestPath(), e.getMessage(), null ); } } ); recv_checkForStatusCode( message ); encoding = message.getProperty( "accept-encoding" ); headRequest = inInputPort && message.isHead(); String contentType = DEFAULT_CONTENT_TYPE; if( message.getProperty( "content-type" ) != null ) { contentType = message.getProperty( "content-type" ).split( ";", 2 )[ 0 ].toLowerCase(); } recv_parseRequestFormat( contentType ); if( !message.isResponse() ) { if( hasParameter( CommProtocol.Parameters.OPERATION_SPECIFIC_CONFIGURATION ) ) { recv_templatedOperation( message, decodedMessage ); } recv_checkReceivingOperation( message, decodedMessage ); } // URI parameter parsing if( message.requestPath() != null ) { boolean strictEncoding = checkStringParameter( Parameters.JSON_ENCODING, "strict" ); recv_parseQueryString( message, decodedMessage.value, contentType, strictEncoding ); } if( !message.isGet() && !message.isHead() ) { // body parsing if( message.size() > 0 ) { recv_parseMessage( message, decodedMessage, contentType, charset ); } } if( !message.isResponse() ) { recv_checkDefaultOp( message, decodedMessage ); } if( checkBooleanParameter( Parameters.CONCURRENT ) ) { String messageId = message.getProperty( Headers.JOLIE_MESSAGE_ID ); if( messageId != null ) { try { decodedMessage.id = Long.parseLong( messageId ); } catch( NumberFormatException e ) { } } } if( message.isResponse() ) { FaultException faultException = null; if( hasOperationSpecificParameter( inputId, Parameters.STATUS_CODES ) ) { faultException = recv_mapHttpStatusCodeFault( message, getOperationSpecificParameterFirstValue( inputId, Parameters.STATUS_CODES ), decodedMessage.value ); } String responseHeader = ""; if( hasParameter( Parameters.RESPONSE_HEADER ) || hasOperationSpecificParameter( inputId, Parameters.RESPONSE_HEADER ) ) { if( hasOperationSpecificParameter( inputId, Parameters.RESPONSE_HEADER ) ) { responseHeader = getOperationSpecificStringParameter( inputId, Parameters.RESPONSE_HEADER ); } else { responseHeader = getStringParameter( Parameters.RESPONSE_HEADER ); } for( Entry< String, String > param : message.properties() ) { decodedMessage.value.getFirstChild( responseHeader ).getFirstChild( param.getKey() ) .setValue( param.getValue() ); } decodedMessage.value.getFirstChild( responseHeader ).getFirstChild( Parameters.STATUS_CODE ) .setValue( message.statusCode() ); } recv_checkForSetCookie( message, decodedMessage.value ); retVal = new CommMessage( decodedMessage.id, inputId, decodedMessage.resourcePath, decodedMessage.value, faultException ); } else if( message.isError() == false ) { recv_checkForMessageProperties( message, decodedMessage ); retVal = new CommMessage( decodedMessage.id, decodedMessage.operationName, decodedMessage.resourcePath, decodedMessage.value, null ); } if( Interpreter.getInstance().isMonitoring() ) { Interpreter.getInstance().fireMonitorEvent( new ProtocolMessageEvent( getHttpBody( message, charset ), getHttpHeader( message ), "", Long.toString( retVal.id() ), ProtocolMessageEvent.Protocol.HTTP ) ); } if( retVal != null && "/".equals( retVal.resourcePath() ) && channel().parentPort() != null && (channel().parentPort().getInterface().containsOperation( retVal.operationName() ) || (channel().parentInputPort() != null && channel().parentInputPort().getAggregatedOperation( retVal.operationName() ) != null)) ) { try { // The message is for this service boolean hasInput = false; OneWayTypeDescription oneWayTypeDescription = null; if( channel().parentInputPort() != null ) { if( channel().parentInputPort().getAggregatedOperation( retVal.operationName() ) != null ) { oneWayTypeDescription = channel().parentInputPort().getAggregatedOperation( retVal.operationName() ) .getOperationTypeDescription().asOneWayTypeDescription(); hasInput = true; } } if( !hasInput ) { Interface iface = channel().parentPort().getInterface(); oneWayTypeDescription = iface.oneWayOperations().get( retVal.operationName() ); } if( oneWayTypeDescription != null ) { // We are receiving a One-Way message oneWayTypeDescription.requestType().cast( retVal.value() ); } else { hasInput = false; RequestResponseTypeDescription rrTypeDescription = null; if( channel().parentInputPort() != null ) { if( channel().parentInputPort().getAggregatedOperation( retVal.operationName() ) != null ) { rrTypeDescription = channel().parentInputPort().getAggregatedOperation( retVal.operationName() ) .getOperationTypeDescription().asRequestResponseTypeDescription(); hasInput = true; } } if( !hasInput ) { Interface iface = channel().parentPort().getInterface(); rrTypeDescription = iface.requestResponseOperations().get( retVal.operationName() ); } if( retVal.isFault() ) { Type faultType = rrTypeDescription.faults().get( retVal.fault().faultName() ); if( faultType != null ) { faultType.cast( retVal.value() ); } } else { if( message.isResponse() ) { rrTypeDescription.responseType().cast( retVal.value() ); } else { rrTypeDescription.requestType().cast( retVal.value() ); } } } } catch( TypeCastingException e ) { // TODO: do something here? } } return retVal; } private FaultException recv_mapHttpStatusCodeFault( HttpMessage message, Value httpStatusValue, Value decodedMessageValue ) { FaultException faultException = null; Iterator< Entry< String, ValueVector > > statusCodeIterator = httpStatusValue.children().entrySet().iterator(); while( statusCodeIterator.hasNext() && faultException == null ) { Entry< String, ValueVector > entry = statusCodeIterator.next(); int configuredStatusCode = entry.getValue().get( 0 ).intValue(); if( configuredStatusCode == message.statusCode() ) { if( message.getPropertyOrEmptyString( Headers.CONTENT_TYPE ) .equals( ContentTypes.APPLICATION_JSON ) ) { faultException = new FaultException( entry.getKey(), decodedMessageValue.getFirstChild( "error" ).getFirstChild( "data" ) ); } else { faultException = new FaultException( entry.getKey() ); } } } return faultException; } @Override public CommMessage recv( InputStream istream, OutputStream ostream ) throws IOException { return HttpUtils.recv( istream, ostream, inInputPort, channel(), this ); } private Type getSendType( CommMessage message ) throws IOException { Type ret = null; if( channel().parentPort() == null ) { throw new IOException( "Could not retrieve communication port for HTTP protocol" ); } OperationTypeDescription opDesc = channel().parentPort().getOperationTypeDescription( message.operationName(), Constants.ROOT_RESOURCE_PATH ); if( opDesc == null ) { return null; } if( opDesc.asOneWayTypeDescription() != null ) { if( message.isFault() ) { ret = Type.UNDEFINED; } else { OneWayTypeDescription ow = opDesc.asOneWayTypeDescription(); ret = ow.requestType(); } } else if( opDesc.asRequestResponseTypeDescription() != null ) { RequestResponseTypeDescription rr = opDesc.asRequestResponseTypeDescription(); if( message.isFault() ) { ret = rr.getFaultType( message.fault().faultName() ); if( ret == null ) { ret = Type.UNDEFINED; } } else { ret = (inInputPort) ? rr.responseType() : rr.requestType(); } } return ret; } }
package org.frc4931.zach.drive; import edu.wpi.first.wpilibj.DigitalInput; import edu.wpi.first.wpilibj.DoubleSolenoid; public class Solenoid { private final DoubleSolenoid solenoid; private final DigitalInput extendedSwitch; private final DigitalInput retractedSwitch; public Solenoid(int extendChannel, int retractChannel) { solenoid = new DoubleSolenoid(extendChannel, retractChannel); extendedSwitch = null; retractedSwitch = null; } public Solenoid(int extendChannel, int retractChannel, int extendSwitch, int retractSwitch){ solenoid = new DoubleSolenoid(extendChannel, retractChannel); extendedSwitch = new DigitalInput(extendSwitch); retractedSwitch = new DigitalInput(retractSwitch); } public void extend(){ System.out.println("Solenoid Extended"); solenoid.set(DoubleSolenoid.Value.kForward); } public void retract(){ System.out.println("Solenoid Retracted"); solenoid.set(DoubleSolenoid.Value.kReverse); } public boolean isExtended(){ if(extendedSwitch == null){ return (solenoid.get()==DoubleSolenoid.Value.kForward); }else{ return extendedSwitch.get(); } } public boolean isRetracted(){ if(retractedSwitch == null){ return (solenoid.get()==DoubleSolenoid.Value.kReverse); }else{ return retractedSwitch.get(); } } }
package org.xwiki.watchlist.internal.job; import java.util.Collection; import java.util.Date; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.quartz.Job; import org.quartz.JobDataMap; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xwiki.context.Execution; import org.xwiki.context.ExecutionContext; import org.xwiki.context.ExecutionContextManager; import org.xwiki.watchlist.internal.DefaultWatchListStore; import org.xwiki.watchlist.internal.WatchListEventMatcher; import org.xwiki.watchlist.internal.api.WatchList; import org.xwiki.watchlist.internal.api.WatchListEvent; import org.xwiki.watchlist.internal.api.WatchedElementType; import org.xwiki.watchlist.internal.documents.WatchListJobClassDocumentInitializer; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.doc.XWikiDocument; import com.xpn.xwiki.objects.BaseObject; import com.xpn.xwiki.plugin.scheduler.AbstractJob; import com.xpn.xwiki.web.Utils; /** * WatchList abstract implementation of Quartz's Job. * * @version $Id$ */ public class WatchListJob extends AbstractJob implements Job { /** * Wiki page which contains the default watchlist email template. */ public static final String DEFAULT_EMAIL_TEMPLATE = "XWiki.WatchListMessage"; /** * Logger. */ private static final Logger LOGGER = LoggerFactory.getLogger(WatchListJob.class); /** * Scheduler Job XObject. */ private BaseObject schedulerJobObject; /** * Watchlist Job XObject. */ private BaseObject watchListJobObject; /** * XWiki context. */ private XWikiContext context; /** * Caller component. */ private WatchList watchlist; /** * Sets objects required by the Job : XWiki, XWikiContext, WatchListPlugin, etc. * * @param jobContext Context of the request * @throws Exception when the init of components fails */ public void init(JobExecutionContext jobContext) throws Exception { JobDataMap data = jobContext.getJobDetail().getJobDataMap(); // clone the context to make sure we have a new one per run this.context = ((XWikiContext) data.get("context")).clone(); // clean up the database connections this.context.getWiki().getStore().cleanUp(this.context); this.watchlist = Utils.getComponent(WatchList.class); this.schedulerJobObject = (BaseObject) data.get("xjob"); this.watchListJobObject = this.context.getWiki().getDocument(this.schedulerJobObject.getDocumentReference(), this.context) .getXObject(WatchListJobClassDocumentInitializer.DOCUMENT_REFERENCE); initializeComponents(this.context); } /** * Initialize container context. * * @param xcontext the XWiki context * @throws Exception if the execution context initialization fails */ protected void initializeComponents(XWikiContext xcontext) throws Exception { try { ExecutionContextManager ecim = Utils.getComponent(ExecutionContextManager.class); ExecutionContext econtext = new ExecutionContext(); // Bridge with old XWiki Context, required for old code. xcontext.declareInExecutionContext(econtext); ecim.initialize(econtext); } catch (Exception e) { throw new Exception("Failed to initialize Execution Context", e); } } /** * Clean the container context. */ protected void cleanupComponents() { Execution execution = Utils.getComponent(Execution.class); // We must ensure we clean the ThreadLocal variables located in the Execution component as otherwise we will // have a potential memory leak. execution.removeContext(); } /** * @return ID of the job */ public String getId() { String className = this.getClass().getName(); return className.substring(className.lastIndexOf(".") + 1); } /** * @return the previous job fire time */ private Date getPreviousFireTime() { return this.watchListJobObject.getDateValue(WatchListJobClassDocumentInitializer.LAST_FIRE_TIME_FIELD); } /** * Save the date of the execution in the watchlist job object. * * @throws XWikiException if the job document can't be retrieved or if the save action fails */ private void setPreviousFireTime() throws XWikiException { XWikiDocument doc = this.context.getWiki().getDocument(this.watchListJobObject.getDocumentReference(), this.context); this.watchListJobObject.setDateValue(WatchListJobClassDocumentInitializer.LAST_FIRE_TIME_FIELD, new Date()); // Prevent version changes doc.setMetaDataDirty(false); doc.setContentDirty(false); this.context.getWiki().saveDocument(doc, "Updated last fire time", true, this.context); } /** * @param userWiki wiki from which the user comes from * @return the name of the page that should be used as email template for this job */ private String getEmailTemplate(String userWiki) { String fullName = this.watchListJobObject.getStringValue(WatchListJobClassDocumentInitializer.TEMPLATE_FIELD); String prefixedFullName; if (fullName.contains(DefaultWatchListStore.WIKI_SPACE_SEP)) { // If the configured template is already an absolute reference it's meant to force the template. prefixedFullName = fullName; } else { prefixedFullName = userWiki + DefaultWatchListStore.WIKI_SPACE_SEP + fullName; if (this.context.getWiki().exists(prefixedFullName, this.context)) { // If the configured template exists in the user wiki, use it. return prefixedFullName; } } return fullName; } /** * Retrieves all the XWiki.XWikiUsers who have requested to be notified by changes, i.e. who have an Object of class * WATCHLIST_CLASS attached AND who have chosen the current job for their notifications. * * @return a collection of document names pointing to the XWikiUsers wishing to get notified. */ private Collection<String> getSubscribers() { return this.watchlist.getStore().getSubscribers(this.schedulerJobObject.getName()); } /** * @return true if this job has subscribers, false otherwise */ private boolean hasSubscribers() { Collection<String> subscribers = getSubscribers(); return !subscribers.isEmpty(); } /** * Method called from the scheduler. * * @param jobContext Context of the request * @throws JobExecutionException if the job execution fails. */ @Override public void executeJob(JobExecutionContext jobContext) throws JobExecutionException { try { init(jobContext); if (this.watchListJobObject == null) { return; } Collection<String> subscribers = getSubscribers(); // Stop here if nobody is interested. if (!hasSubscribers()) { return; } // Determine what happened since the last execution for everybody. Date previousFireTime = getPreviousFireTime(); WatchListEventMatcher eventMatcher = new WatchListEventMatcher(previousFireTime, this.context); setPreviousFireTime(); // Stop here if nothing happened in the meantime. if (eventMatcher.getEventNumber() == 0) { return; } // Notify all interested subscribers, one at a time. for (String subscriber : subscribers) { try { Collection<String> wikis = this.watchlist.getStore().getWatchedElements(subscriber, WatchedElementType.WIKI); Collection<String> spaces = this.watchlist.getStore().getWatchedElements(subscriber, WatchedElementType.SPACE); Collection<String> documents = this.watchlist.getStore().getWatchedElements(subscriber, WatchedElementType.DOCUMENT); Collection<String> users = this.watchlist.getStore().getWatchedElements(subscriber, WatchedElementType.USER); // Determine what happened since the last execution on the watched elements of the current // subscriber only. List<WatchListEvent> matchingEvents = eventMatcher.getMatchingEvents(wikis, spaces, documents, users, subscriber, this.context); String userWiki = StringUtils.substringBefore(subscriber, DefaultWatchListStore.WIKI_SPACE_SEP); // If events have occurred on at least one element watched by the user, send the email if (matchingEvents.size() > 0) { this.watchlist.getNotifier().sendNotification(subscriber, matchingEvents, getEmailTemplate(userWiki), previousFireTime); } } catch (Exception e) { LOGGER.error("Failed to send watchlist notification to user [{}]", subscriber, e); } } } catch (Exception e) { // We're in a job, we don't throw exceptions LOGGER.error("Exception while running job", e); } finally { this.context.getWiki().getStore().cleanUp(this.context); cleanupComponents(); } } }
package com.yahoo.vespa.hosted.athenz.instanceproviderservice.identitydocument; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Objects; /** * @author bjorncs */ public class ProviderUniqueId { @JsonProperty("tenant") public final String tenant; @JsonProperty("application") public final String application; @JsonProperty("environment") public final String environment; @JsonProperty("region") public final String region; @JsonProperty("instance") public final String instance; @JsonProperty("cluster-id") public final String clusterId; @JsonProperty("cluster-index") public final int clusterIndex; public ProviderUniqueId(@JsonProperty("tenant") String tenant, @JsonProperty("application") String application, @JsonProperty("environment") String environment, @JsonProperty("region") String region, @JsonProperty("instance") String instance, @JsonProperty("cluster-id") String clusterId, @JsonProperty("cluster-index") int clusterIndex) { this.tenant = tenant; this.application = application; this.environment = environment; this.region = region; this.instance = instance; this.clusterId = clusterId; this.clusterIndex = clusterIndex; } public String asString() { return String.format("%d.%s.%s.%s.%s.%s.%s", clusterIndex, clusterId, instance, application, tenant, region, environment); } @Override public String toString() { return "ProviderUniqueId{" + "tenant='" + tenant + '\'' + ", application='" + application + '\'' + ", environment='" + environment + '\'' + ", region='" + region + '\'' + ", instance='" + instance + '\'' + ", clusterId='" + clusterId + '\'' + ", clusterIndex=" + clusterIndex + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ProviderUniqueId that = (ProviderUniqueId) o; return clusterIndex == that.clusterIndex && Objects.equals(tenant, that.tenant) && Objects.equals(application, that.application) && Objects.equals(environment, that.environment) && Objects.equals(region, that.region) && Objects.equals(instance, that.instance) && Objects.equals(clusterId, that.clusterId); } @Override public int hashCode() { return Objects.hash(tenant, application, environment, region, instance, clusterId, clusterIndex); } }
package dr.app.beagle.tools; import dr.app.beagle.evomodel.sitemodel.GammaSiteRateModel; import dr.app.beagle.evomodel.substmodel.FrequencyModel; import dr.evolution.alignment.SimpleAlignment; import dr.evolution.datatype.Codons; import dr.evolution.datatype.DataType; import dr.evolution.datatype.Nucleotides; import dr.evolution.sequence.Sequence; import dr.evolution.tree.NodeRef; import dr.evolution.tree.Tree; import dr.evolution.tree.TreeTrait; import dr.evolution.tree.TreeTraitProvider; import dr.evomodel.branchratemodel.BranchRateModel; import dr.inference.markovjumps.MarkovJumpsRegisterAcceptor; import dr.inference.markovjumps.MarkovJumpsType; import dr.inference.markovjumps.StateHistory; import dr.inference.model.Parameter; import dr.math.MathUtils; import java.text.NumberFormat; import java.util.*; import java.util.logging.Logger; /** * Simulates a complete transition history and alignment of sequences given a tree, substitution model and * branch rate model. This code duplicates portions of dr.app.seqgen.SequenceSimulator. However, SequenceSimulator * is wed to dr.evomodel.substmodel.SubstitutionModel which does not emit the infinitesimal generator. * * @author Marc A. Suchard * @author remco@cs.waikato.ac.nz */ public class CompleteHistorySimulator extends SimpleAlignment implements MarkovJumpsRegisterAcceptor, TreeTraitProvider { /** * number of replications */ protected int nReplications; /** * tree used for generating samples * */ protected Tree tree; /** * site model used for generating samples * */ protected GammaSiteRateModel siteModel; /** * branch rate model used for generating samples * */ protected BranchRateModel branchRateModel; /** * nr of categories in site model * */ int categoryCount; /** * nr of states in site model * */ int stateCount; /** * an array used to hold infinitesimal generator */ // protected double[] lambda; // protected double[][] probabilities; private boolean branchSpecificLambda = false; private Parameter branchVariableParameter = null; private Parameter branchPossibleValuesParameter = null; private DataType dataType; protected List<double[]> registers; protected List<String> jumpTags; protected List<MarkovJumpsType> jumpTypes; protected List<double[][]> realizedJumps; protected int nJumpProcesses = 0; protected boolean sumAcrossSites; private final Map<String, Integer> idMap = new HashMap<String, Integer>(); private boolean saveAlignment = false; private Map<Integer,Sequence> alignmentTraitList; /** * Constructor * * @param tree * @param siteModel * @param branchRateModel * @param nReplications: nr of samples to generate */ // public CompleteHistorySimulator(Tree tree, GammaSiteRateModel siteModel, BranchRateModel branchRateModel, // int nReplications) { // this(tree, siteModel, branchRateModel, nReplications, false); // public CompleteHistorySimulator(Tree tree, GammaSiteRateModel siteModel, BranchRateModel branchRateModel, // int nReplications, boolean sumAcrossSites) { // this(tree, siteModel, branchRateModel, nReplications, sumAcrossSites, null, null); public CompleteHistorySimulator(Tree tree, GammaSiteRateModel siteModel, BranchRateModel branchRateModel, int nReplications, boolean sumAcrossSites, Parameter branchVariableParameter, Parameter branchPossibleValuesParameter) { this.tree = tree; this.siteModel = siteModel; this.branchRateModel = branchRateModel; this.nReplications = nReplications; stateCount = this.siteModel.getSubstitutionModel().getDataType().getStateCount(); categoryCount = this.siteModel.getCategoryCount(); dataType = siteModel.getSubstitutionModel().getDataType(); if (dataType instanceof Codons) { this.setReportCountStatistics(false); } this.sumAcrossSites = sumAcrossSites; List<String> taxaIds = new ArrayList<String>(); for (int i = 0; i < tree.getTaxonCount(); i++) { taxaIds.add(tree.getTaxon(i).getId()); } int k = 1; for (String taxaId : taxaIds) { idMap.put(taxaId, k); k += 1; } format = NumberFormat.getNumberInstance(Locale.ENGLISH); format.setMaximumFractionDigits(3); if (branchVariableParameter != null && branchPossibleValuesParameter != null) { if (branchVariableParameter.getDimension() != 1) { throw new RuntimeException("branchVariableParameter has the wrong dimension; should be 1"); } if (branchPossibleValuesParameter.getDimension() != tree.getNodeCount()) { throw new RuntimeException("branchPossibleValuesParameter has the wrong dimension; should be " + tree.getNodeCount()); } branchSpecificLambda = true; this.branchPossibleValuesParameter = branchPossibleValuesParameter; this.branchVariableParameter = branchVariableParameter; StringBuilder sb = new StringBuilder(); sb.append("Doing a complete history simulation using branch-specific variables\n\tReplacing variable '"); sb.append(branchVariableParameter.getId()); sb.append("' with values from '"); sb.append(branchPossibleValuesParameter.getId()); sb.append("'"); Logger.getLogger("dr.app.beagle.tools").info(sb.toString()); } alignmentTraitList = new HashMap<Integer,Sequence>(tree.getNodeCount()); } /** * Convert integer representation of sequence into a Sequence * * @param seq integer representation of the sequence * @param node used to determine taxon for sequence * @return Sequence */ Sequence intArray2Sequence(int[] seq, NodeRef node) { String sSeq = ""; // DataType dataType = siteModel.getSubstitutionModel().getDataType(); for (int i = 0; i < nReplications; i++) { if (dataType instanceof Codons) { String s = dataType.getTriplet(seq[i]); sSeq += s; } else { String c = dataType.getCode(seq[i]); sSeq += c; } } return new Sequence(tree.getNodeTaxon(node), sSeq); } public void addAlignmentTrait() { saveAlignment = true; final String tag = "alignment"; treeTraits.addTrait(new TreeTrait.S() { public String getTraitName() { return tag; } public Intent getIntent() { return Intent.NODE; } public String getTrait(Tree tree, NodeRef node) { return alignmentTraitList.get(node.getNumber()).getSequenceString(); } }); } public void addRegister(Parameter addRegisterParameter, MarkovJumpsType type, boolean scaleByTime) { if (registers == null) { registers = new ArrayList<double[]>(); } if (jumpTags == null) { jumpTags = new ArrayList<String>(); } if (jumpTypes == null) { jumpTypes = new ArrayList<MarkovJumpsType>(); } if (realizedJumps == null) { realizedJumps = new ArrayList<double[][]>(); } final String tag = addRegisterParameter.getId(); registers.add(addRegisterParameter.getParameterValues()); jumpTags.add(tag); jumpTypes.add(type); realizedJumps.add(new double[tree.getNodeCount()][nReplications]); final int r = nJumpProcesses; treeTraits.addTrait(new TreeTrait.S() { public String getTraitName() { return tag; } public Intent getIntent() { return Intent.NODE; } public String getTrait(Tree tree, NodeRef node) { return formattedValue(tree, node, r); } }); nJumpProcesses++; // scaleByTime is currently ignored } public double[] getMarkovJumpsForNodeAndRegister(Tree tree, NodeRef node, int whichRegister) { if (this.tree != tree) { throw new RuntimeException("Wrong tree!"); } return realizedJumps.get(whichRegister)[node.getNumber()]; } public int getNumberOfJumpProcess() { return nJumpProcesses; } // public double[][] getMarkovJumpsForNode(Tree tree, NodeRef node) { // double[][] rtn = new double[nJumpProcesses][]; // for(int r = 0; r < nJumpProcesses; r++) { // rtn[r] = getMarkovJumpsForNodeAndRegister(tree, node, r); // return rtn; protected Helper treeTraits = new Helper(); public TreeTrait[] getTreeTraits() { return treeTraits.getTreeTraits(); } public TreeTrait getTreeTrait(String key) { return treeTraits.getTreeTrait(key); } private String formattedValue(Tree tree, NodeRef node, int jump) { StringBuffer sb = new StringBuffer(); double[] values = getMarkovJumpsForNodeAndRegister(tree, node, jump); if (sumAcrossSites) { double total = 0; for (double x : values) { total += x; } sb.append(total); } else { sb.append("{"); for (int i = 0; i < values.length; i++) { if (i > 0) { sb.append(","); } sb.append(values[i]); } sb.append("}"); } return sb.toString(); } private NumberFormat format; public String toString() { StringBuffer sb = new StringBuffer(); //alignment output sb.append("alignment\n"); // super.setDataType(Nucleotides.INSTANCE); sb.append(super.toString()); sb.append("\n"); //tree output sb.append("tree\n"); Tree.Utils.newick(tree, tree.getRoot(), true, Tree.BranchLengthType.LENGTHS_AS_TIME, format, null, (nJumpProcesses > 0 || saveAlignment ? new TreeTraitProvider[]{this} : null), idMap, sb); sb.append("\n"); return sb.toString(); } /** * perform the actual sequence generation * * @return alignment containing randomly generated sequences for the nodes in the * leaves of the tree */ public void simulate() { double[] lambda = new double[stateCount * stateCount]; if (!branchSpecificLambda) { siteModel.getSubstitutionModel().getInfinitesimalMatrix(lambda); // Assumes a single generator for whole tree } NodeRef root = tree.getRoot(); double[] categoryProbs = siteModel.getCategoryProportions(); int[] category = new int[nReplications]; for (int i = 0; i < nReplications; i++) { category[i] = MathUtils.randomChoicePDF(categoryProbs); } FrequencyModel frequencyModel = siteModel.getSubstitutionModel().getFrequencyModel(); int[] seq = new int[nReplications]; for (int i = 0; i < nReplications; i++) { seq[i] = MathUtils.randomChoicePDF(frequencyModel.getFrequencies()); } setDataType(siteModel.getSubstitutionModel().getDataType()); traverse(root, seq, category, this, lambda); } /** * recursively walk through the tree top down, and add sequence to alignment whenever * a leave node is reached. * * @param node reference to the current node, for which we visit all children * @param parentSequence randomly generated sequence of the parent node * @param category array of categories for each of the sites * @param alignment */ private void traverse(NodeRef node, int[] parentSequence, int[] category, SimpleAlignment alignment, double[] lambda) { if (saveAlignment) { alignmentTraitList.put(node.getNumber(),intArray2Sequence(parentSequence,node)); } for (int iChild = 0; iChild < tree.getChildCount(node); iChild++) { NodeRef child = tree.getChild(node, iChild); int[] seq = new int[nReplications]; StateHistory[] histories = new StateHistory[nReplications]; if (branchSpecificLambda) { final double branchValue = branchPossibleValuesParameter.getParameterValue(child.getNumber()); branchVariableParameter.setParameterValue(0, branchValue); // System.err.println("trying value = " + branchValue + " for " + child.getNumber()); siteModel.getSubstitutionModel().getInfinitesimalMatrix(lambda); } for (int i = 0; i < nReplications; i++) { histories[i] = simulateAlongBranch(tree, child, category[i], parentSequence[i], lambda); seq[i] = histories[i].getEndingState(); } processHistory(child, histories); if (tree.getChildCount(child) == 0) { alignment.addSequence(intArray2Sequence(seq, child)); } traverse(tree.getChild(node, iChild), seq, category, alignment, lambda); } } protected void processHistory(NodeRef node, StateHistory[] histories) { for (int jump = 0; jump < nJumpProcesses; jump++) { double[] register = registers.get(jump); MarkovJumpsType type = jumpTypes.get(jump); double[] realizedJump = realizedJumps.get(jump)[node.getNumber()]; for (int i = 0; i < nReplications; i++) { if (type == MarkovJumpsType.COUNTS) { realizedJump[i] = histories[i].getTotalRegisteredCounts(register); } else if (type == MarkovJumpsType.REWARDS) { realizedJump[i] = histories[i].getTotalReward(register); } else { throw new IllegalAccessError("Unknown MarkovJumps type"); } } } } private StateHistory simulateAlongBranch(Tree tree, NodeRef node, int rateCategory, int startingState, double[] lambda) { NodeRef parent = tree.getParent(node); final double branchRate = branchRateModel.getBranchRate(tree, node); // Get the operational time of the branch final double branchTime = branchRate * (tree.getNodeHeight(parent) - tree.getNodeHeight(node)); if (branchTime < 0.0) { throw new RuntimeException("Negative branch length: " + branchTime); } double branchLength = siteModel.getRateForCategory(rateCategory) * branchTime; return StateHistory.simulateUnconditionalOnEndingState(0.0, startingState, branchLength, lambda, stateCount); } }
package lucee.runtime; import java.net.URL; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Stack; import java.util.concurrent.ConcurrentHashMap; import javax.servlet.Servlet; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.jsp.JspEngineInfo; import lucee.commons.io.SystemUtil; import lucee.commons.io.log.Log; import lucee.commons.io.log.LogUtil; import lucee.commons.io.res.util.ResourceUtil; import lucee.commons.lang.SizeOf; import lucee.commons.lang.SystemOut; import lucee.runtime.config.ConfigImpl; import lucee.runtime.config.ConfigWeb; import lucee.runtime.config.ConfigWebImpl; import lucee.runtime.engine.CFMLEngineImpl; import lucee.runtime.engine.ThreadLocalPageContext; import lucee.runtime.exp.Abort; import lucee.runtime.exp.PageException; import lucee.runtime.exp.PageExceptionImpl; import lucee.runtime.exp.RequestTimeoutException; import lucee.runtime.functions.string.Hash; import lucee.runtime.lock.LockManager; import lucee.runtime.op.Caster; import lucee.runtime.query.QueryCache; import lucee.runtime.type.Array; import lucee.runtime.type.ArrayImpl; import lucee.runtime.type.Struct; import lucee.runtime.type.StructImpl; import lucee.runtime.type.dt.DateTimeImpl; import lucee.runtime.type.scope.LocalNotSupportedScope; import lucee.runtime.type.scope.ScopeContext; import lucee.runtime.type.util.ArrayUtil; import lucee.runtime.type.util.KeyConstants; import lucee.runtime.type.util.ListUtil; /** * implements a JSP Factory, this class produce JSP Compatible PageContext Object * this object holds also the must interfaces to coldfusion specified functionlity */ public final class CFMLFactoryImpl extends CFMLFactory { private static JspEngineInfo info=new JspEngineInfoImpl("1.0"); private ConfigWebImpl config; Stack<PageContext> pcs=new Stack<PageContext>(); private final Map<Integer,PageContextImpl> runningPcs=new ConcurrentHashMap<Integer, PageContextImpl>(); int idCounter=1; private ScopeContext scopeContext=new ScopeContext(this); private HttpServlet servlet; private URL url=null; private CFMLEngineImpl engine; /** * constructor of the JspFactory * @param config Lucee specified Configuration * @param compiler CFML compiler * @param engine */ public CFMLFactoryImpl(CFMLEngineImpl engine) { this.engine=engine; } /** * reset the PageContexes */ public void resetPageContext() { SystemOut.printDate(config.getOutWriter(),"Reset "+pcs.size()+" Unused PageContexts"); synchronized(pcs) { pcs.clear(); } Iterator<PageContextImpl> it = runningPcs.values().iterator(); while(it.hasNext()){ it.next().reset(); } } @Override public javax.servlet.jsp.PageContext getPageContext( Servlet servlet, ServletRequest req, ServletResponse rsp, String errorPageURL, boolean needsSession, int bufferSize, boolean autoflush) { return getPageContextImpl((HttpServlet)servlet,(HttpServletRequest)req,(HttpServletResponse)rsp,errorPageURL,needsSession,bufferSize,autoflush,true,false); } /** * similar to getPageContext Method but return the concrete implementation of the lucee PageCOntext * and take the HTTP Version of the Servlet Objects * @param servlet * @param req * @param rsp * @param errorPageURL * @param needsSession * @param bufferSize * @param autoflush * @return return the page<context */ public PageContext getLuceePageContext( HttpServlet servlet, HttpServletRequest req, HttpServletResponse rsp, String errorPageURL, boolean needsSession, int bufferSize, boolean autoflush) { //runningCount++; return getPageContextImpl(servlet, req, rsp, errorPageURL, needsSession, bufferSize, autoflush,true,false); } public PageContextImpl getPageContextImpl( HttpServlet servlet, HttpServletRequest req, HttpServletResponse rsp, String errorPageURL, boolean needsSession, int bufferSize, boolean autoflush,boolean registerPageContext2Thread,boolean isChild) { //runningCount++; PageContextImpl pc; synchronized (pcs) { if(pcs.isEmpty()) pc=new PageContextImpl(scopeContext,config,idCounter++,servlet); else pc=((PageContextImpl)pcs.pop()); runningPcs.put(Integer.valueOf(pc.getId()),pc); this.servlet=servlet; if(registerPageContext2Thread)ThreadLocalPageContext.register(pc); } pc.initialize(servlet,req,rsp,errorPageURL,needsSession,bufferSize,autoflush,isChild); return pc; } @Override public void releasePageContext(javax.servlet.jsp.PageContext pc) { releaseLuceePageContext((PageContext)pc); } /** * Similar to the releasePageContext Method, but take lucee PageContext as entry * @param pc */ public void releaseLuceePageContext(PageContext pc) { if(pc.getId()<0)return; pc.release(); ThreadLocalPageContext.release(); //if(!pc.hasFamily()){ runningPcs.remove(Integer.valueOf(pc.getId())); if(pcs.size()<100 && ((PageContextImpl)pc).getStopPosition()==null)// not more than 100 PCs pcs.push(pc); //SystemOut.printDate(config.getOutWriter(),"Release: (id:"+pc.getId()+";running-requests:"+config.getThreadQueue().size()+";)"); /*} else { SystemOut.printDate(config.getOutWriter(),"Unlink: ("+pc.getId()+")"); }*/ } /** * check timeout of all running threads, downgrade also priority from all thread run longer than 10 seconds */ public void checkTimeout() { if(!engine.allowRequestTimeout())return; //synchronized (runningPcs) { //int len=runningPcs.size(); Iterator<Entry<Integer, PageContextImpl>> it = runningPcs.entrySet().iterator(); PageContextImpl pc; //Collection.Key key; Entry<Integer, PageContextImpl> e; while(it.hasNext()) { e = it.next(); pc=e.getValue(); long timeout=pc.getRequestTimeout(); if(pc.getStartTime()+timeout<System.currentTimeMillis()) { terminate(pc); it.remove(); } // after 10 seconds downgrade priority of the thread else if(pc.getStartTime()+10000<System.currentTimeMillis() && pc.getThread().getPriority()!=Thread.MIN_PRIORITY) { Log log = config.getLog("requesttimeout"); if(log!=null)log.log(Log.LEVEL_WARN,"controler","downgrade priority of the a thread at "+getPath(pc)); try { pc.getThread().setPriority(Thread.MIN_PRIORITY); } catch(Throwable t) {} } } } public static void terminate(PageContextImpl pc) { Log log = ((ConfigImpl)pc.getConfig()).getLog("requesttimeout"); if(log!=null)LogUtil.log(log,Log.LEVEL_ERROR,"controler", "stop thread ("+pc.getId()+") because run into a timeout "+getPath(pc)+"."+getLocks(pc),pc.getThread().getStackTrace()); // then we release the pagecontext pc.getConfig().getThreadQueue().exit(pc); SystemUtil.stop(pc,createRequestTimeoutException(pc),log); } private static String getLocks(PageContext pc) { String strLocks=""; try{ LockManager manager = pc.getConfig().getLockManager(); String[] locks = manager.getOpenLockNames(); if(!ArrayUtil.isEmpty(locks)) strLocks=" open locks at this time ("+ListUtil.arrayToList(locks, ", ")+")."; //LockManagerImpl.unlockAll(pc.getId()); } catch(Throwable t){} return strLocks; } public static RequestTimeoutException createRequestTimeoutException(PageContext pc) { return new RequestTimeoutException(pc.getThread(),"request ("+getPath(pc)+":"+pc.getId()+") has run into a timeout ("+(pc.getRequestTimeout()/1000)+" seconds) and has been stopped."+getLocks(pc)); } private static String getPath(PageContext pc) { try { String base=ResourceUtil.getResource(pc, pc.getBasePageSource()).getAbsolutePath(); String current=ResourceUtil.getResource(pc, pc.getCurrentPageSource()).getAbsolutePath(); if(base.equals(current)) return "path: "+base; return "path: "+base+" ("+current+")"; } catch(Throwable t) { return "(fail to retrieve path:"+t.getClass().getName()+":"+t.getMessage()+")"; } } @Override public JspEngineInfo getEngineInfo() { return info; } /** * @return returns count of pagecontext in use */ public int getUsedPageContextLength() { int length=0; try{ Iterator it = runningPcs.values().iterator(); while(it.hasNext()){ PageContextImpl pc=(PageContextImpl) it.next(); if(!pc.isGatewayContext()) length++; } } catch(Throwable t){ return length; } return length; } /** * @return Returns the config. */ public ConfigWeb getConfig() { return config; } public ConfigWebImpl getConfigWebImpl() { return config; } /** * @return Returns the scopeContext. */ public ScopeContext getScopeContext() { return scopeContext; } /** * @return label of the factory */ public Object getLabel() { return ((ConfigWebImpl)getConfig()).getLabel(); } /** * @param label */ public void setLabel(String label) { // deprecated } /** * @return the hostName */ public URL getURL() { return url; } public void setURL(URL url) { this.url=url; } /** * @return the servlet */ public HttpServlet getServlet() { return servlet; } public void setConfig(ConfigWebImpl config) { this.config=config; } public Map<Integer, PageContextImpl> getActivePageContexts() { return runningPcs; } public long getPageContextsSize() { return SizeOf.size(pcs); } public Array getInfo() { Array info=new ArrayImpl(); //synchronized (runningPcs) { //int len=runningPcs.size(); Iterator<PageContextImpl> it = runningPcs.values().iterator(); PageContextImpl pc; Struct data,sctThread,scopes; Thread thread; Entry<Integer, PageContextImpl> e; while(it.hasNext()) { pc = it.next(); data=new StructImpl(); sctThread=new StructImpl(); scopes=new StructImpl(); data.setEL("thread", sctThread); data.setEL("scopes", scopes); if(pc.isGatewayContext()) continue; thread=pc.getThread(); if(thread==Thread.currentThread()) continue; thread=pc.getThread(); if(thread==Thread.currentThread()) continue; data.setEL("startTime", new DateTimeImpl(pc.getStartTime(),false)); data.setEL("endTime", new DateTimeImpl(pc.getStartTime()+pc.getRequestTimeout(),false)); data.setEL(KeyConstants._timeout,new Double(pc.getRequestTimeout())); // thread sctThread.setEL(KeyConstants._name,thread.getName()); sctThread.setEL("priority",Caster.toDouble(thread.getPriority())); data.setEL("TagContext",PageExceptionImpl.getTagContext(pc.getConfig(),thread.getStackTrace() )); data.setEL("urlToken", pc.getURLToken()); try { if(pc.getConfig().debug())data.setEL("debugger", pc.getDebugger().getDebuggingData(pc)); } catch (PageException e2) {} try { data.setEL("id", Hash.call(pc, pc.getId()+":"+pc.getStartTime())); } catch (PageException e1) {} data.setEL("requestid", pc.getId()); // Scopes scopes.setEL(KeyConstants._name, pc.getApplicationContext().getName()); try { scopes.setEL(KeyConstants._application, pc.applicationScope()); } catch (PageException pe) {} try { scopes.setEL(KeyConstants._session, pc.sessionScope()); } catch (PageException pe) {} try { scopes.setEL(KeyConstants._client, pc.clientScope()); } catch (PageException pe) {} scopes.setEL(KeyConstants._cookie, pc.cookieScope()); scopes.setEL(KeyConstants._variables, pc.variablesScope()); if(!(pc.localScope() instanceof LocalNotSupportedScope)){ scopes.setEL(KeyConstants._local, pc.localScope()); scopes.setEL(KeyConstants._arguments, pc.argumentsScope()); } scopes.setEL(KeyConstants._cgi, pc.cgiScope()); scopes.setEL(KeyConstants._form, pc.formScope()); scopes.setEL(KeyConstants._url, pc.urlScope()); scopes.setEL(KeyConstants._request, pc.requestScope()); info.appendEL(data); } return info; } public void stopThread(String threadId, String stopType) { //synchronized (runningPcs) { Iterator<PageContextImpl> it = runningPcs.values().iterator(); PageContext pc; while(it.hasNext()) { pc=it.next(); Log log = ((ConfigImpl)pc.getConfig()).getLog("application"); try { String id = Hash.call(pc, pc.getId()+":"+pc.getStartTime()); if(id.equals(threadId)){ stopType=stopType.trim(); Throwable t; if("abort".equalsIgnoreCase(stopType) || "cfabort".equalsIgnoreCase(stopType)) t=new Abort(Abort.SCOPE_REQUEST); else t=new RequestTimeoutException(pc.getThread(),"request has been forced to stop."); SystemUtil.stop(pc,t,log); SystemUtil.sleep(10); break; } } catch (PageException e1) {} } } @Override public QueryCache getDefaultQueryCache() { throw new RuntimeException("function PageContext.getDefaultQueryCache() no longer supported"); } }
package dr.evomodel.newtreelikelihood; import dr.evolution.alignment.PatternList; import dr.evolution.tree.NodeRef; import dr.evolution.tree.Tree; import dr.evolution.util.TaxonList; import dr.evomodel.branchratemodel.BranchRateModel; import dr.evomodel.branchratemodel.DefaultBranchRateModel; import dr.evomodel.sitemodel.SiteModel; import dr.evomodel.substmodel.FrequencyModel; import dr.evomodel.tree.TreeModel; import dr.inference.model.Likelihood; import dr.inference.model.Model; import dr.xml.*; import java.util.logging.Logger; /** * TreeLikelihoodModel - implements a Likelihood Function for sequences on a tree. * * @author Andrew Rambaut * @author Alexei Drummond * @version $Id: TreeLikelihood.java,v 1.31 2006/08/30 16:02:42 rambaut Exp $ */ public class TreeLikelihood extends AbstractTreeLikelihood { public static final String TREE_LIKELIHOOD = "crazyTreeLikelihood"; public static final String USE_AMBIGUITIES = "useAmbiguities"; public static final String DEVICE_NUMBER = "deviceNumber"; /** * Constructor. */ public TreeLikelihood(PatternList patternList, TreeModel treeModel, SiteModel siteModel, BranchRateModel branchRateModel, boolean useAmbiguities, int deviceNumber ) { super(TREE_LIKELIHOOD, patternList, treeModel); try { final Logger logger = Logger.getLogger("dr.evomodel"); logger.info("Crazy new TreeLikelihood"); this.siteModel = siteModel; addModel(siteModel); this.frequencyModel = siteModel.getFrequencyModel(); addModel(frequencyModel); if (branchRateModel != null) { this.branchRateModel = branchRateModel; logger.info("Branch rate model used: " + branchRateModel.getModelName()); } else { this.branchRateModel = new DefaultBranchRateModel(); } addModel(this.branchRateModel); this.categoryCount = siteModel.getCategoryCount(); int extNodeCount = treeModel.getExternalNodeCount(); int[] configuration = new int[4]; configuration[0] = stateCount; configuration[1] = patternCount; configuration[2] = siteModel.getCategoryCount(); // matrixCount configuration[3] = deviceNumber; likelihoodCore = LikelihoodCoreFactory.loadLikelihoodCore(configuration, this); // override use preference on useAmbiguities based on actual ability of the likelihood core if (!likelihoodCore.canHandleTipPartials()) { useAmbiguities = false; } if (!likelihoodCore.canHandleTipStates()){ useAmbiguities = true; } // dynamicRescaling = likelihoodCore.canHandleDynamicRescaling(); likelihoodCore.initialize(nodeCount, (useAmbiguities ? 0 : extNodeCount), patternCount, categoryCount); for (int i = 0; i < extNodeCount; i++) { // Find the id of tip i in the patternList String id = treeModel.getTaxonId(i); int index = patternList.getTaxonIndex(id); if (index == -1) { throw new TaxonList.MissingTaxonException("Taxon, " + id + ", in tree, " + treeModel.getId() + ", is not found in patternList, " + patternList.getId()); } else { if (useAmbiguities) { setPartials(likelihoodCore, patternList, index, i); } else { setStates(likelihoodCore, patternList, index, i); } } } updateSubstitutionModel = true; updateSiteModel = true; } catch (TaxonList.MissingTaxonException mte) { throw new RuntimeException(mte.toString()); } hasInitialized = true; } public final LikelihoodCore getLikelihoodCore() { return likelihoodCore; } // ModelListener IMPLEMENTATION /** * Handles model changed events from the submodels. */ protected void handleModelChangedEvent(Model model, Object object, int index) { if (model == treeModel) { if (object instanceof TreeModel.TreeChangedEvent) { if (((TreeModel.TreeChangedEvent) object).isNodeChanged()) { // If a node event occurs the node and its two child nodes // are flagged for updating (this will result in everything // above being updated as well. Node events occur when a node // is added to a branch, removed from a branch or its height or // rate changes. updateNodeAndChildren(((TreeModel.TreeChangedEvent) object).getNode()); } else if (((TreeModel.TreeChangedEvent) object).isTreeChanged()) { // Full tree events result in a complete updating of the tree likelihood // Currently this event type is not used. System.err.println("Full tree update event - these events currently aren't used\n" + "so either this is in error or a new feature is using them so remove this message."); updateAllNodes(); } else { // Other event types are ignored (probably trait changes). //System.err.println("Another tree event has occured (possibly a trait change)."); } } } else if (model == branchRateModel) { if (index == -1) { updateAllNodes(); } else { updateNode(treeModel.getNode(index)); } } else if (model == frequencyModel) { updateSubstitutionModel = true; updateAllNodes(); } else if (model instanceof SiteModel) { updateSubstitutionModel = true; updateSiteModel = true; updateAllNodes(); } else { throw new RuntimeException("Unknown componentChangedEvent"); } super.handleModelChangedEvent(model, object, index); } // Model IMPLEMENTATION /** * Stores the additional state other than model components */ protected void storeState() { likelihoodCore.storeState(); super.storeState(); } /** * Restore the additional stored state */ protected void restoreState() { likelihoodCore.restoreState(); super.restoreState(); } // Likelihood IMPLEMENTATION /** * Calculate the log likelihood of the current state. * * @return the log likelihood. */ protected double calculateLogLikelihood() { if (patternLogLikelihoods == null) { patternLogLikelihoods = new double[patternCount]; } if (branchUpdateIndices == null) { branchUpdateIndices = new int[nodeCount]; branchLengths = new double[nodeCount]; } if (operations == null) { operations = new int[nodeCount * 3]; dependencies = new int[nodeCount * 2]; } branchUpdateCount = 0; operationCount = 0; final NodeRef root = treeModel.getRoot(); traverse(treeModel, root, null); if (updateSubstitutionModel) { likelihoodCore.updateSubstitutionModel(siteModel.getSubstitutionModel()); } if (updateSiteModel) { likelihoodCore.updateSiteModel(siteModel); } likelihoodCore.updateMatrices(branchUpdateIndices, branchLengths, branchUpdateCount); likelihoodCore.updatePartials(operations, dependencies, operationCount, false); nodeEvaluationCount += operationCount; likelihoodCore.calculateLogLikelihoods(root.getNumber(), patternLogLikelihoods); double logL = 0.0; for (int i = 0; i < patternCount; i++) { logL += patternLogLikelihoods[i] * patternWeights[i]; } // Attempt dynamic rescaling if over/under-flow if (logL == Double.NaN || logL == Double.POSITIVE_INFINITY ) { System.err.println("Potential under/over-flow; going to attempt a partials rescaling."); updateAllNodes(); branchUpdateCount = 0; operationCount = 0; traverse(treeModel, root, null); likelihoodCore.updateMatrices(branchUpdateIndices, branchLengths, branchUpdateCount); likelihoodCore.updatePartials(operations,dependencies, operationCount, true); likelihoodCore.calculateLogLikelihoods(root.getNumber(), patternLogLikelihoods); logL = 0.0; for (int i = 0; i < patternCount; i++) { logL += patternLogLikelihoods[i] * patternWeights[i]; } } /** * Traverse the tree calculating partial likelihoods. */ private boolean traverse(Tree tree, NodeRef node, int[] operatorNumber) { boolean update = false; int nodeNum = node.getNumber(); NodeRef parent = tree.getParent(node); // First update the transition probability matrix(ices) for this branch if (parent != null && updateNode[nodeNum]) { final double branchRate = branchRateModel.getBranchRate(tree, node); // Get the operational time of the branch final double branchTime = branchRate * (tree.getNodeHeight(parent) - tree.getNodeHeight(node)); if (branchTime < 0.0) { throw new RuntimeException("Negative branch length: " + branchTime); } branchUpdateIndices[branchUpdateCount] = nodeNum; branchLengths[branchUpdateCount] = branchTime; branchUpdateCount++; update = true; } // If the node is internal, update the partial likelihoods. if (!tree.isExternal(node)) { // Traverse down the two child nodes NodeRef child1 = tree.getChild(node, 0); final int[] op1 = new int[] { -1 }; final boolean update1 = traverse(tree, child1, op1); NodeRef child2 = tree.getChild(node, 1); final int[] op2 = new int[] { -1 }; final boolean update2 = traverse(tree, child2, op2); // If either child node was updated then update this node too if (update1 || update2) { int x = operationCount * 3; operations[x] = child1.getNumber(); // source node 1 operations[x + 1] = child2.getNumber(); // source node 2 operations[x + 2] = nodeNum; // destination node int y = operationCount * 3; dependencies[y] = -1; // dependent ancestor dependencies[y + 1] = 0; // isDependent? // if one of the child nodes have an update then set the dependency // element to this operation. if (op1[0] != -1) { dependencies[op1[0] * 3] = operationCount; dependencies[y + 1] = 1; // isDependent? } if (op2[0] != -1) { dependencies[op2[0] * 3] = operationCount; dependencies[y + 1] = 1; // isDependent? } if (operatorNumber != null) { dependencies[y] = operationCount; } operationCount ++; update = true; } } return update; } /** * The XML parser */ public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { public String getParserName() { return TREE_LIKELIHOOD; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { boolean useAmbiguities = xo.getAttribute(USE_AMBIGUITIES, false); int deviceNumber = xo.getAttribute(DEVICE_NUMBER,1) - 1; PatternList patternList = (PatternList) xo.getChild(PatternList.class); TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class); SiteModel siteModel = (SiteModel) xo.getChild(SiteModel.class); BranchRateModel branchRateModel = (BranchRateModel) xo.getChild(BranchRateModel.class); return new TreeLikelihood( patternList, treeModel, siteModel, branchRateModel, useAmbiguities, deviceNumber ); } /** * the frequency model for these sites */ protected final FrequencyModel frequencyModel; /** * the site model for these sites */ protected final SiteModel siteModel; /** * the branch rate model */ protected final BranchRateModel branchRateModel; /** * the pattern likelihoods */ protected double[] patternLogLikelihoods = null; /** * the number of rate categories */ protected int categoryCount; /** * an array used to transfer tip partials */ protected double[] tipPartials; /** * the LikelihoodCore */ protected LikelihoodCore likelihoodCore; /** * Flag to specify that the substitution model has changed */ protected boolean updateSubstitutionModel; /** * Flag to specify that the site model has changed */ protected boolean updateSiteModel; private int nodeEvaluationCount = 0; public int getNodeEvaluationCount() { return nodeEvaluationCount; } // private boolean dynamicRescaling = false; }
class StringAVLTreeExtra2 extends StringAVLTree { public StringAVLTreeExtra2() { super(); } public void display() { paren_out(getRoot()); System.out.println(); bal_out(getRoot()); } public void paren_out(StringAVLNode t) { if (t == null) { } else { System.out.print("("); paren_out(t.getLeft()); if (t.getItem().length() <= 1) System.out.print(" "); System.out.print(t.getItem()); paren_out(t.getRight()); System.out.print(")"); } } public void bal_out(StringAVLNode t) { if (t == null) { } else { System.out.print("("); bal_out(t.getLeft()); if (t.getItem().length() == 3) System.out.print(" "); if (t.getBalance() == -1) System.out.print(t.getBalance()); else System.out.print(" " + t.getBalance()); bal_out(t.getRight()); System.out.print(")"); } } public String paren_out1(StringAVLNode t) { String s; if (t == null) { s = new String(); } else { s="(" + paren_out1(t.getLeft())+t.getItem()+paren_out1(t.getRight())+")"; } return s; } public String bal_out1(StringAVLNode t) { String s; if (t == null) { s = new String(); } else { s="("+bal_out1(t.getLeft())+t.getBalance()+bal_out1(t.getRight())+")"; } return s; } public String toString2() { String s = new String(); s = paren_out1(getRoot())+bal_out1(getRoot())+String.valueOf(this.leafCt())+" "+ String.valueOf(this.height())+" "+String.valueOf(this.balanced()); return s; } }
package dr.inference.operators; import dr.inference.model.Bounds; import dr.inference.model.Parameter; import dr.math.MathUtils; import dr.xml.*; /** * A generic operator for use with a sum-constrained (possibly weighted) vector parameter. * * @author Alexei Drummond * @author Andrew Rambaut * * @version $Id: DeltaExchangeOperator.java,v 1.18 2005/06/14 10:40:34 rambaut Exp $ */ public class DeltaExchangeOperator extends SimpleMCMCOperator implements CoercableMCMCOperator { public static final String DELTA_EXCHANGE = "deltaExchange"; public static final String DELTA = "delta"; public static final String INTEGER_OPERATOR = "integer"; public static final String PARAMETER_WEIGHTS = "parameterWeights"; public DeltaExchangeOperator(Parameter parameter, int[] parameterWeights, double delta, int weight, boolean isIntegerOperator, int mode) { this.parameter = parameter; this.delta = delta; this.weight = weight; this.mode = mode; this.isIntegerOperator = isIntegerOperator; this.parameterWeights = parameterWeights; if (isIntegerOperator && delta != Math.round(delta)) { throw new IllegalArgumentException("Can't be an integer operator if delta is not integer"); } } /** @return the parameter this operator acts on. */ public Parameter getParameter() { return parameter; } /** change the parameter and return the hastings ratio. * performs a delta exchange operation between two scalars in the vector * and return the hastings ratio. */ public final double doOperation() throws OperatorFailedException { // get two dimensions int dim1 = MathUtils.nextInt(parameter.getDimension()); int dim2 = MathUtils.nextInt(parameter.getDimension()); while (dim1 == dim2) { dim2 = MathUtils.nextInt(parameter.getDimension()); } double scalar1 = parameter.getParameterValue(dim1); double scalar2 = parameter.getParameterValue(dim2); // exchange a random delta double d = MathUtils.nextDouble() * delta; scalar1 -= d; if (parameterWeights[dim1] != parameterWeights[dim2]) { scalar2 += d * (double)parameterWeights[dim1] / (double)parameterWeights[dim2]; } else { scalar2 += d; } if (isIntegerOperator) { scalar1 = Math.round(scalar1); scalar2 = Math.round(scalar2); } Bounds bounds = parameter.getBounds(); if (scalar1 < bounds.getLowerLimit(dim1) || scalar1 > bounds.getUpperLimit(dim1) || scalar2 < bounds.getLowerLimit(dim2) || scalar2 > bounds.getUpperLimit(dim2)) { throw new OperatorFailedException("proposed values out of range!"); } parameter.setParameterValue(dim1, scalar1); parameter.setParameterValue(dim2, scalar2); // symmetrical move so return a zero hasting ratio return 0.0; } // Interface MCMCOperator public final String getOperatorName() { return parameter.getParameterName(); } public double getCoercableParameter() { return Math.log(delta); } public void setCoercableParameter(double value) { delta = Math.exp(value); } public double getRawParameter() { return delta; } public int getMode() { return mode; } public double getTargetAcceptanceProbability() { return 0.234;} public double getMinimumAcceptanceLevel() { return 0.1;} public double getMaximumAcceptanceLevel() { return 0.4;} public double getMinimumGoodAcceptanceLevel() { return 0.20; } public double getMaximumGoodAcceptanceLevel() { return 0.30; } public int getWeight() { return weight; } public void setWeight(int w) { weight = w; } public final String getPerformanceSuggestion() { double prob = MCMCOperator.Utils.getAcceptanceProbability(this); double targetProb = getTargetAcceptanceProbability(); double d = OperatorUtils.optimizeWindowSize(delta, parameter.getParameterValue(0) * 2.0, prob, targetProb); if (prob < getMinimumGoodAcceptanceLevel()) { return "Try decreasing delta to about " + d; } else if (prob > getMaximumGoodAcceptanceLevel()) { return "Try increasing delta to about " + d; } else return ""; } public String toString() { return getOperatorName() + "(windowsize=" + delta + ")"; } public static dr.xml.XMLObjectParser PARSER = new dr.xml.AbstractXMLObjectParser() { public String getParserName() { return DELTA_EXCHANGE; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { int mode = CoercableMCMCOperator.DEFAULT; if (xo.hasAttribute(AUTO_OPTIMIZE)) { if (xo.getBooleanAttribute(AUTO_OPTIMIZE)) { mode = CoercableMCMCOperator.COERCION_ON; } else { mode = CoercableMCMCOperator.COERCION_OFF; } } boolean isIntegerOperator = false; if (xo.hasAttribute(INTEGER_OPERATOR)) { isIntegerOperator = xo.getBooleanAttribute(INTEGER_OPERATOR); } int weight = xo.getIntegerAttribute(WEIGHT); double delta = xo.getDoubleAttribute(DELTA); if (delta <= 0.0) { throw new XMLParseException("delta must be greater than 0.0"); } Parameter parameter = (Parameter)xo.getChild(Parameter.class); int[] parameterWeights = null; if (xo.hasAttribute(PARAMETER_WEIGHTS)) { parameterWeights = xo.getIntegerArrayAttribute(PARAMETER_WEIGHTS); System.out.print("Parameter weights for delta exchange are: "); for (int i = 0; i < parameterWeights.length; i++) { System.out.print(parameterWeights[i] + "\t"); } System.out.println(); } else { parameterWeights = new int[parameter.getDimension()]; for (int i = 0; i < parameterWeights.length; i++) { parameterWeights[i] = 1; } } if (parameterWeights.length != parameter.getDimension()) { throw new XMLParseException("parameter weights have the same length as parameter"); } return new DeltaExchangeOperator(parameter, parameterWeights, delta, weight, isIntegerOperator, mode); }
package magic.data.database; import java.io.File; import java.io.IOException; import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collectors; import java.util.stream.Stream; import com.google.common.base.Charsets; import com.google.common.io.Files; import magic.data.Deck; import magic.data.Player; import magic.data.Tournament; import magic.data.Format; public class Database { private Database() { // utils } private static final String DELIMETER = " private static final String LINE_END = "\n"; private static final String NO_FORMAT_CODE = "N/A"; private static final AtomicLong PLAYER_ID_COUNTER = readPlayerId(); private static final AtomicLong DECK_ID_COUNTER = readDeckId(); private static final AtomicLong MATCH_ID_COUNTER = readMatchId(); private static final AtomicLong TOURNAMENT_ID_COUNTER = readTournamentId(); public static long nextPlayerId() { return PLAYER_ID_COUNTER.incrementAndGet(); } public static long nextDeckId() { return DECK_ID_COUNTER.incrementAndGet(); } public static long nextMatchId() { return MATCH_ID_COUNTER.incrementAndGet(); } public static long nextTournamentId() { return TOURNAMENT_ID_COUNTER.incrementAndGet(); } private static AtomicLong readPlayerId() { return readId(DatabaseConstants.PLAYERS, DatabaseConstants.PLAYERS_ID); } private static AtomicLong readDeckId() { return readId(DatabaseConstants.DECKS, DatabaseConstants.DECKS_ID); } private static AtomicLong readMatchId() { return readId(DatabaseConstants.MATCHES, DatabaseConstants.MATCHES_ID); } private static AtomicLong readTournamentId() { return readId(DatabaseConstants.TOURNAMENTS, DatabaseConstants.TOURNAMENTS_ID); } private static AtomicLong readId(File file, int idIndex) { try (Stream<String> lines = lines(file)) { return new AtomicLong(lines.map(line -> line.split(DELIMETER)) .map(arr -> arr[idIndex]) .map(Integer::valueOf) .max(Comparator.naturalOrder()) .get()); } catch (Exception e) { return new AtomicLong(); } } public static Player readPlayerFromId(long id) throws IOException { Optional<String> playerLine = matchLineId(DatabaseConstants.PLAYERS, DatabaseConstants.PLAYERS_ID, id); if (playerLine.isPresent()) { return parsePlayerFromLine(playerLine.get()); } else { throw new RuntimeException("Could not parse player with id: " + id); } } public static List<Player> readPlayers() throws IOException { return lines(DatabaseConstants.PLAYERS) .filter(line -> Long.parseLong(line.split(DELIMETER)[DatabaseConstants.PLAYERS_ID]) != 0) .map(line -> parsePlayerFromLine(line)) .collect(Collectors.toList()); } private static Player parsePlayerFromLine(String line) { String[] parts = line.split(DELIMETER); long id = Long.parseLong(parts[DatabaseConstants.PLAYERS_ID]); String name = parts[DatabaseConstants.PLAYERS_NAME]; return new Player(id, name); } public static Deck readDeckFromId(long id) throws IOException { Optional<String> deckLine = matchLineId(DatabaseConstants.DECKS, DatabaseConstants.DECKS_ID, id); if (deckLine.isPresent()) { return parseDeckFromLine(deckLine.get()); } else { throw new RuntimeException("Could not parse deck with id: " + id); } } public static List<Deck> readDecks() throws IOException { return lines(DatabaseConstants.DECKS) .map(line -> parseDeckFromLine(line)) .collect(Collectors.toList()); } private static Deck parseDeckFromLine(String line) { String[] parts = line.split(DELIMETER); long id = Long.parseLong(parts[DatabaseConstants.DECKS_ID]); String colors = parts[DatabaseConstants.DECKS_COLORS]; String archetype = parts[DatabaseConstants.DECKS_ARCHETYPE]; Format format = Format.valueOf(parts[DatabaseConstants.DECKS_FORMAT]); return new Deck(id, colors, archetype, format); } public static Tournament readTournamentFromId(long id) throws IOException { Optional<String> tournamentLine = matchLineId(DatabaseConstants.TOURNAMENTS, DatabaseConstants.TOURNAMENTS_ID, id); if (tournamentLine.isPresent()) { return parseTournamentFromLine(tournamentLine.get()); } else { throw new RuntimeException("Could not parse tournament with id: " + id); } } public static List<Tournament> readTournaments() throws IOException { return lines(DatabaseConstants.TOURNAMENTS) .map(line -> parseTournamentFromLine(line)) .collect(Collectors.toList()); } private static Tournament parseTournamentFromLine(String line) { String[] parts = line.split(DELIMETER); long id = Long.parseLong(parts[DatabaseConstants.TOURNAMENTS_ID]); Format format = Format.valueOf(parts[DatabaseConstants.TOURNAMENTS_FORMAT]); String code = parts[DatabaseConstants.TOURNAMENTS_CODE]; Optional<String> formatCode = code.equals(NO_FORMAT_CODE) ? Optional.empty() : Optional.of(code); return new Tournament(id, format, formatCode); } private static Optional<String> matchLineId(File file, int matchPart, long id) throws IOException { Optional<String> playerLine = lines(file).filter(line -> Long.parseLong(line.split(DELIMETER)[matchPart]) == id).findFirst(); return playerLine; } private static Stream<String> lines(File file) throws IOException { return java.nio.file.Files.lines(file.toPath()); } public static boolean addPlayer(Player player) { return append(DatabaseConstants.PLAYERS, formatPlayer(player)); } private static String formatPlayer(Player player) { return player.getId() + DELIMETER + player.getName() + LINE_END; } public static boolean addDeck(Deck deck) { return append(DatabaseConstants.DECKS, formatDeck(deck)); } private static String formatDeck(Deck deck) { return deck.getId() + DELIMETER + deck.getFormat() + DELIMETER + deck.getColors() + DELIMETER + deck.getArchetype() + LINE_END; } public static boolean addTournament(Tournament tournament) { return append(DatabaseConstants.TOURNAMENTS, formatTournament(tournament)); } private static String formatTournament(Tournament tournament) { return tournament.getId() + DELIMETER + tournament.getFormat() + DELIMETER + (tournament.getFormatCode() == Optional.<String> empty() ? NO_FORMAT_CODE : tournament.getFormatCode()) + LINE_END; } private static boolean append(File file, String contents) { try { Files.append(contents, file, Charsets.UTF_8); return true; } catch (IOException e) { e.printStackTrace(); return false; } } }
package cgeo.geocaching.ui.dialog; import cgeo.geocaching.activity.ActivityMixin; import cgeo.geocaching.utils.Log; import android.app.ProgressDialog; import android.content.Context; import android.os.Bundle; import android.view.View; import java.lang.reflect.Field; /** * Modified progress dialog class which allows hiding the absolute numbers. * */ public class CustomProgressDialog extends ProgressDialog { public CustomProgressDialog(final Context context) { super(context, ActivityMixin.getDialogTheme()); } @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); try { // Field is private, make it accessible through reflection before hiding it. final Field field = getClass().getSuperclass().getDeclaredField("mProgressNumber"); field.setAccessible(true); ((View) field.get(this)).setVisibility(View.GONE); } catch (NoSuchFieldException | IllegalAccessException e) { Log.e("Failed to find the progressDialog field 'mProgressNumber'", e); } } }
package com.jbooktrader.platform.util; import com.jbooktrader.platform.marketbook.*; import com.toedter.calendar.*; import java.util.*; public abstract class MarkSnapshotUtilities { public static MarketSnapshotFilter getMarketDepthFilter(JTextFieldDateEditor fromDateEditor, JTextFieldDateEditor toDateEditor) { Calendar calendar = Calendar.getInstance(); calendar.setTime(fromDateEditor.getDate()); calendar.set(Calendar.HOUR_OF_DAY, 0); final long fromDate = calendar.getTimeInMillis(); calendar.setTime(toDateEditor.getDate()); calendar.set(Calendar.HOUR_OF_DAY, 23); final long toDate = calendar.getTimeInMillis(); return new MarketSnapshotFilter() { public boolean accept(MarketSnapshot marketSnapshot) { long snapshotTime = marketSnapshot.getTime(); return (snapshotTime >= fromDate && snapshotTime <= toDate); } }; } }
package org.jasig.portal.channels.cusermanager; import java.util.Enumeration; import java.text.MessageFormat; import org.jasig.portal.IChannel; import org.jasig.portal.security.IPerson; import org.jasig.portal.security.IPermission; import org.jasig.portal.security.provider.PersonImpl; //import edu.cornell.uportal.channels.cusermanager.provider.PersonImpl; import org.jasig.portal.ChannelStaticData; import org.jasig.portal.ChannelRuntimeData; import org.jasig.portal.ChannelRuntimeProperties; import org.jasig.portal.PortalEvent; import org.jasig.portal.PortalException; import org.jasig.portal.IPermissible; import org.jasig.portal.AuthorizationException; import org.jasig.portal.utils.XSLT; import org.jasig.portal.utils.DocumentFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.ContentHandler; /** * @author smb1@cornell.edu * @version $Revision$ $Date$ */ public class CUserManager extends CUserManagerPermissions implements IChannel, IPermissible { private IDataHandler datasource; private String mode = Constants.MODEDISPLAY; private ChannelStaticData channelStaticData; private ChannelRuntimeData channelRuntimeData; private boolean ManagerMode = false; private boolean PwdChngMode = true; private PortalEvent lastEvent; /** for pwd chng mode, we want to cache the user's info because * there will be many more of these than admin channels */ private Document PersonalDocument = null; public CUserManager() { }// CUserManager public ChannelRuntimeProperties getRuntimeProperties() { return new ChannelRuntimeProperties(); }// getRuntimeProperties public void receiveEvent(PortalEvent ev) { this.lastEvent = ev; }// receiveEvent public void setStaticData(ChannelStaticData sd) { channelStaticData = sd; // Ignore since 2.0 (2003.04.21) // if( CSD.getParameter( Constants.CHNPARAMNOTMGR ) != null ) // ManagerMode = false; // let determine the user's rights try{ IPermission[] perms = channelStaticData.getAuthorizationPrincipal().getAllPermissions( Constants.PERMISSION_OWNERTOKEN, null, Constants.PERMISSION_OWNERTARGET ); for( int i = 0; i < perms.length; i++ ) { if( perms[ i ].getActivity().equals( Constants.PERMISSION_MNGRRIGHT ) && perms[ i ].getType().equals( IPermission.PERMISSION_TYPE_GRANT )) ManagerMode = true; if( perms[ i ].getActivity().equals( Constants.PERMISSION_PWDCHNGRIGHT ) && perms[ i ].getType().equals( IPermission.PERMISSION_TYPE_DENY )) PwdChngMode = false; }// for }catch( AuthorizationException ae ){ log.error(ae,ae); } }// setStaticData public void setRuntimeData(ChannelRuntimeData rd) { channelRuntimeData = rd; }// setRuntimeData public void renderXML(ContentHandler out) throws PortalException { // first, be sure they are allowed to be here if( !ManagerMode && !PwdChngMode ) throw new AuthorizationException( MessageFormat.format( Constants.ERRMSG_NORIGHTS, new Object[] { (String)channelStaticData.getPerson().getAttribute( IPerson.USERNAME ) } )); try{ String message_to_user_about_action = ""; // these always start blank Document doc = null; IPerson[] people = null; mode = Constants.MODEDISPLAY; // now, b4 we get going, there may have been an event to deal with if( channelRuntimeData.getParameter( Constants.FORMACTION ) == null && lastEvent != null ) { if( lastEvent.getEventNumber() == PortalEvent.ABOUT_BUTTON_EVENT ) channelRuntimeData.setParameter( Constants.FORMACTION, "10" ); if( lastEvent.getEventNumber() == PortalEvent.HELP_BUTTON_EVENT ) channelRuntimeData.setParameter( Constants.FORMACTION, "11" ); lastEvent = null; // don't need that anymore }// if, null & !null // see if we have form data to process if( channelRuntimeData.getParameter( Constants.FORMACTION ) != null ){ log.debug("form.action=" + channelRuntimeData.getParameter( Constants.FORMACTION )); switch( Integer.parseInt( channelRuntimeData.getParameter( Constants.FORMACTION ))) { case 1: { // update getDataSource().setUserInformation( crd2persion( channelRuntimeData )); message_to_user_about_action = Constants.MSG_SAVED; break; } case 2: { // choose mode = Constants.MODEDISPLAY; break; } case 3: { // choose people = getDataSource().getAllUsers(); mode = Constants.MODECHOOSE; break; } case 4: { // search if( channelRuntimeData.getParameter( Constants.FORMSRCHSTR ) == null ) { people = new PersonImpl[0]; mode = Constants.MODESEARCH; }else{ // if they did not enter a src str, display mode people = getDataSource().getAllUsersLike( channelRuntimeData.getParameter( Constants.FORMSRCHSTR )); if( people.length == 1 ) { // this will cause a second lookup but the user experience will benifit mode = Constants.MODEDISPLAY; channelRuntimeData.setParameter( Constants.UNFIELD, (String)people[0].getAttribute( Constants.UNFIELD )); }else mode = Constants.MODECHOOSE; // they will need to select to narrow } break; } case 5: { // prepare add new user channelRuntimeData.setParameter( Constants.UNFIELD,(String) channelStaticData.getPerson().getAttribute( Constants.ATTRUSERNAME )); mode = Constants.MODEADD; break; } case 6: { // add new user try{ getDataSource().addUser( crd2persion( channelRuntimeData )); }catch( Exception adde ) { if( adde.getMessage().indexOf( Constants.ALREADY_EXISTS ) > -1 ) message_to_user_about_action = adde.getMessage(); else throw adde; }// catch mode = Constants.MODEDISPLAY; break; } case 7: { // prepare password chng people = new IPerson[] { getDataSource().getUser( channelRuntimeData.getParameter( Constants.UNFIELD )) }; mode = Constants.MODEPWDCHNG; break; } case 8: { // password chng message_to_user_about_action = Constants.MSG_PWD_SAVED; try{ getDataSource().setUserPassword( crd2persion( channelRuntimeData ), ( ManagerMode?null: channelRuntimeData.getParameter( Constants.PWDFIELD ))); }catch( Exception pwdchng ) { if( pwdchng.getMessage() .equals( Constants.ERRMSG_PWDNOTMATACHED )) message_to_user_about_action = pwdchng.getMessage(); else throw pwdchng; }// catch mode = Constants.MODEDISPLAY; PersonalDocument = null; break; } case 9: { // delete user getDataSource().removeUser( crd2persion( channelRuntimeData )); mode = Constants.MODEDISPLAY; PersonalDocument = null; break; } case 10: { // about mode = Constants.MODEABOUT; break; } case 11: { // help mode = Constants.MODEHELP; break; } default: { mode = Constants.MODEDISPLAY; channelRuntimeData.remove( Constants.UNFIELD ); }// default }// switch } if( !ManagerMode && PersonalDocument == null && !mode.equals(Constants.MODEABOUT) && !mode.equals(Constants.MODEHELP) ) // always override mode = Constants.MODEDISPLAY; // force a read // look up the person we are supposed to display if( mode.equals( Constants.MODEDISPLAY ) || mode.equals( Constants.MODEADD )) people = new IPerson[] { getDataSource().getUser( ( channelRuntimeData.getParameter( Constants.FORMCHOSEN ) == null? ( channelRuntimeData.getParameter( Constants.UNFIELD ) == null? (String)channelStaticData.getPerson().getAttribute( Constants.ATTRUSERNAME ) : channelRuntimeData.getParameter( Constants.UNFIELD )) : channelRuntimeData.getParameter( Constants.FORMCHOSEN ) )) }; if( !ManagerMode && !mode.equals(Constants.MODEABOUT) && !mode.equals(Constants.MODEHELP) ) // always override mode = Constants.MODEPWDCHNG; if( (ManagerMode || ( !ManagerMode && PersonalDocument == null )) && !mode.equals(Constants.MODEABOUT) && !mode.equals(Constants.MODEHELP) ) { doc = DocumentFactory.getNewDocument(); // fill in info about the user Element outtermost = doc.createElement( "people" ); Element person; for( int i = 0; i < people.length; i++ ) { person = doc.createElement( "person" ); Element attr = null; String worker = null; Enumeration E = people[ i ].getAttributeNames(); while( E.hasMoreElements()) { worker = (String)E.nextElement(); attr = doc.createElement( worker ); attr.appendChild( doc.createTextNode( (String)people[ i ].getAttribute( worker ))); person.appendChild( attr ); }// while outtermost.appendChild( person ); }// for doc.appendChild( outtermost ); // end - fill in info about the user if( !ManagerMode ) PersonalDocument = doc; }else{ doc = PersonalDocument; } // Create a new XSLT styling engine XSLT xslt = XSLT.getTransformer( this, channelRuntimeData.getLocales()); // XSLT xslt = new XSLT( this ); // we could have a blank document, help and about if( doc == null ) { doc = DocumentFactory.getNewDocument(); doc.appendChild( doc.createElement( mode )); // null; }// doc null // pass the result XML to the styling engine. xslt.setXML( doc ); // specify the stylesheet selector xslt.setXSL( Constants.SSLFILE, mode, channelRuntimeData.getBrowserInfo()); // set parameters that the stylesheet needs. xslt.setStylesheetParameter( Constants.BASEACTION, channelRuntimeData.getBaseActionURL()); xslt.setStylesheetParameter( Constants.MODE, mode ); xslt.setStylesheetParameter( Constants.DISPLAYMESSAGE, message_to_user_about_action ); String MM = (!ManagerMode?"yes":"no"); xslt.setStylesheetParameter( Constants.MODEUSRPWDCHNG, MM ); /** If I write the above as shown below it does not work. Wasted a .5hr on that! */ // xslt.setStylesheetParameter( Constants.MODEUSRPWDCHNG, (!ManagerMode?"yes":"no")); // set the output Handler for the output. xslt.setTarget( out ); // do the deed xslt.transform(); }catch( Exception e ){ log.error(e,e); throw new PortalException( (e.getMessage()!=null?e.getMessage():e.toString())); }// catch }// renderXML private IDataHandler getDataSource() throws Exception { if( datasource == null ) datasource = (IDataHandler) Class.forName( ( channelStaticData.getParameter( Constants.CHNPARAMDATAHANDLER ) == null? Constants.DEFAULTDATAHANDLER : channelStaticData.getParameter( Constants.CHNPARAMDATAHANDLER ) ) ).newInstance(); return datasource; }// getDataSource private IPerson crd2persion( ChannelRuntimeData CRD ) throws Exception { String worker = null; IPerson newborn = new PersonImpl(); Enumeration E = CRD.getParameterNames(); while( E.hasMoreElements()){ worker = (String)E.nextElement(); if( !worker.equals( Constants.FORMACTION )) newborn.setAttribute( worker, ( CRD.getParameter( worker ) == null? "" : CRD.getParameter( worker ) )); }// while return newborn; }// crd2persion }// eoc
package beaform.dao; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.Callable; import org.apache.commons.collections.ListUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; import beaform.debug.DebugUtils; import beaform.entities.Formula; import beaform.entities.FormulaTag; import beaform.entities.Ingredient; import beaform.search.SearchFormulaTask; /** * Test for the formula DAO. * * @author Steven Post * */ @SuppressWarnings("static-method") public class FormulaDAOTest { @Before public void setUp() { GraphDbHandler.initInstance("test"); DebugUtils.clearDb(); } @Test public void testAddFormula() throws Exception { FormulaDAO.addFormula("Testform", "Description", "100g", ListUtils.EMPTY_LIST, ListUtils.EMPTY_LIST); final Callable<Formula> task = new SearchFormulaTask("Testform"); final Formula result = task.call(); assertNotNull("No result found", result); } @Test public void testAddFormulaWithContent() throws Exception { final List<FormulaTag> tags = new ArrayList<>(); tags.add(new FormulaTag("testtag")); final List<Ingredient> ingredients = new ArrayList<>(); ingredients.add(new Ingredient(new Formula("TestForm", "Some desc", "100%"), "100%")); FormulaDAO.addFormula("Testform", "Description", "100g", ingredients, tags); final Callable<Formula> task = new SearchFormulaTask("Testform"); final Formula result = task.call(); assertNotNull("Unable to find the newly created formula", result); } @Test public void testGetIngredients() throws Exception { DebugUtils.fillDb(); final Callable<Formula> task = new SearchFormulaTask("Form1"); final Formula result = task.call(); final List<Ingredient> ingredients = FormulaDAO.getIngredients(result); assertEquals("The ingredient list isn't the expected size", 1, ingredients.size()); } @Test public void testFindFormulaByName() { DebugUtils.fillDb(); final Formula formula = FormulaDAO.findFormulaByName("Form1"); assertNotNull("The formula wasn't found", formula); assertEquals("This isn't the expected formula", "Form1", formula.getName()); } @Test public void testFindFormulasByTag() { DebugUtils.fillDb(); final List<Formula> formulas = FormulaDAO.findFormulasByTag("First"); assertEquals("This isn't the number of found formulas", 2, formulas.size()); } @Test public void testUpdateExisting() throws Exception { DebugUtils.fillDb(); FormulaDAO.updateExisting("Form1", "New description", "100g", Collections.emptyList(), Collections.emptyList()); final Callable<Formula> task = new SearchFormulaTask("Form1"); final Formula result = task.call(); assertEquals("This isn't the expected description", "New description", result.getDescription()); } @After public void tearDown() { DebugUtils.clearDb(); GraphDbHandler.clearInstance(); } }
package fi.hu.cs.titokone; import fi.hu.cs.ttk91.*; import java.util.*; /** This class represents the processor. It can be told to run for one command cycle at a time. */ public class Processor implements TTK91Cpu { /** When SVC call is made PC points to this place. */ public static final int OS_CODE_AREA = -1; private static final String INVALID_OPCODE_MESSAGE = "Invalid operation code {0}"; private static final String ADDRESS_OUT_OF_BOUNDS_MESSAGE = "Memory address out of bounds"; private static final String BAD_ACCESS_MODE_MESSAGE = "Invalid memory addressing mode"; private static final String BRANCH_BAD_ACCESS_MODE_MESSAGE = "Invalid memory access mode in branching command"; private static final String STORE_BAD_ACCESS_MODE_MESSAGE = "Invalid memory access mode in STORE"; private static final String NO_KDB_DATA_MESSAGE = "No keyboard data available"; private static final String NO_STDIN_DATA_MESSAGE = "No standard input data available"; private static final String INVALID_DEVICE_MESSAGE = "Invalid device number"; private static final String INTEGER_OVERFLOW_MESSAGE = "Integer overflow"; private static final String DIVISION_BY_ZERO_MESSAGE = "Division by zero"; /** CRT-device */ public static final int CRT = 0; /** KBD-device */ public static final int KBD = 1; /** STDIN-device */ public static final int STDIN = 6; /** STDOUT-device */ public static final int STDOUT = 7; /** This field represents the memory of computer. */ private RandomAccessMemory ram; /** This field represents the registers of computer. */ private Registers regs; /** Is program running. */ private int status = TTK91Cpu.STATUS_SVC_SD; /** Rundebugger */ private RunDebugger runDebugger = new RunDebugger(); /** state register array. index: 0 - greater 1 - equal 2 - less 3 - arithmetic overflow 4 - divide by zero 5 - unknown instruction 6 - forbidden memory access 7 - device interrupt 8 - supervisor call 9 - priviledged mode 10 - interrupts disabled */ private boolean[] sr = new boolean[11]; /** The stdinData and kbdData fields stores buffer data to be read with the IN operation. When the data has been read, the field should be set to be null. */ private Integer stdinData=null, kbdData=null; /** Creates new processor, memory and registers. Processor state, program counter get initial values @param memsize creates new computer with given size of memory. Proper values are power of two (from 512 to 64k). */ public Processor(int memsize){ ram = new RandomAccessMemory (memsize); regs = new Registers(); } /** Returns the memory attached to the processor. */ public TTK91Memory getMemory() { return ram; } /** Returns the value of given registerID. The index numbers are available from the TTK91CPU interface. @param registerID Identifying number of the register. @return Value of given register. Inproper value returns -1. */ public int getValueOf(int registerID) { return regs.getRegister (registerID); } /** Returns queried memory line. @param row Number of the row in processor's memory. @return Queried memory line. */ public MemoryLine getMemoryLine (int row) { return ram.getMemoryLine (row); } /** Method returns the current value of Processor. Status values are available from the TTK91CPU interface. @return Current status of the Processor. */ public int getStatus() { return status; } /** Method erases memorylines from memory. Memory will be filled with 0-lines. */ public void eraseMemory() { ram = new RandomAccessMemory (ram.getSize()); } public void memoryInput(int rowNumber, MemoryLine inputLine) throws TTK91AddressOutOfBounds { String errorMessage; try { ram.setMemoryLine(rowNumber, inputLine); } catch (ArrayIndexOutOfBoundsException e) { errorMessage = new Message("Row number {0} is beyond memory " + "limits.", "" + rowNumber).toString(); throw new TTK91AddressOutOfBounds(errorMessage); } } /** This method adds a line of keyboard data to a buffer the Processor can read it from during its next command cycle (or previous cycle repeated). @param kbdInput An int to be "read from the keyboard". */ public void keyboardInput(int kbdInput) { kbdData = new Integer (kbdInput); } /** This method adds a line of stdin data to a buffer the Processor can read it from during its next command cycle (or previous cycle repeated). @param stdinInput An int to be "read from STDIN (file)". */ public void stdinInput(int stdinInput) { stdinData = new Integer (stdinInput); } public void runInit(int initSP, int initFP) { status = TTK91Cpu.STATUS_STILL_RUNNING; regs.setRegister (TTK91Cpu.CU_PC, 0); regs.setRegister (TTK91Cpu.CU_PC_CURRENT, 0); regs.setRegister (TTK91Cpu.REG_SP, initSP); regs.setRegister (TTK91Cpu.REG_FP, initFP); ram.setCodeAreaLength (initFP+1); ram.setDataAreaLength (initSP -initFP); } public RunInfo runLine() throws TTK91RuntimeException{ if (status == TTK91Cpu.STATUS_SVC_SD) return null; // if last command set status to ABNORMAL_EXIT repeat that command if (status == TTK91Cpu.STATUS_ABNORMAL_EXIT) regs.setRegister (TTK91Cpu.CU_PC, regs.getRegister (TTK91Cpu.CU_PC) -1); try { // get PC int PC = regs.getRegister (TTK91Cpu.CU_PC); // fetch the next command to IR from memory and increase PC MemoryLine IR = ram.getMemoryLine(PC); runDebugger.cycleStart (PC, IR.getSymbolic()); regs.setRegister (TTK91Cpu.CU_IR, IR.getBinary()); regs.setRegister (TTK91Cpu.CU_PC, PC+1); // cut up the command in IR int opcode = IR.getBinary() >>> 24; // operation code int Rj = ((IR.getBinary()&0xE00000) >>> 21) + TTK91Cpu.REG_R0; // first operand (register 0..7) int M = (IR.getBinary()&0x180000) >>> 19; // memory addressing mode int Ri = ((IR.getBinary()&0x070000) >>> 16) + TTK91Cpu.REG_R0; // index register int ADDR = IR.getBinary()&0xFFFF; // address runDebugger.runCommand (IR.getBinary()); // fetch parameter from memory if (Ri != TTK91Cpu.REG_R0) ADDR += regs.getRegister (Ri); // add indexing register Ri int param = ADDR; // constant value if (M == 1) { param = ram.getValue(ADDR); // one memory fetch runDebugger.setValueAtADDR (param); } if (M == 2) { param = ram.getValue(param); // two memory fetches runDebugger.setValueAtADDR (param); param = ram.getValue (param); runDebugger.setSecondFetchValue (param); } // run the command if (M == 3) { status = TTK91Cpu.STATUS_ABNORMAL_EXIT; throw new TTK91BadAccessMode(new Message(Processor.BAD_ACCESS_MODE_MESSAGE).toString()); } if (opcode == 0) nop(); else if (opcode >= 1 && opcode <= 4) transfer (opcode, Rj, M, ADDR, param); else if (opcode >= 17 && opcode <= 27) alu (opcode, Rj, param); else if (opcode == 31) comp (Rj, param); else if (opcode >= 32 && opcode <= 44) branch (opcode, Rj, M, ADDR, param); else if (opcode >= 49 && opcode <= 50) subr (opcode, Rj, ADDR, param); else if (opcode >= 51 && opcode <= 54) stack (opcode, Rj, Ri, param); else if (opcode == 112) svc (Rj, param); else { status = TTK91Cpu.STATUS_ABNORMAL_EXIT; throw new TTK91InvalidOpCode(new Message(Processor.INVALID_OPCODE_MESSAGE, ""+opcode).toString()); } } catch (ArrayIndexOutOfBoundsException e) { status = TTK91Cpu.STATUS_ABNORMAL_EXIT; throw new TTK91AddressOutOfBounds(new Message(Processor.ADDRESS_OUT_OF_BOUNDS_MESSAGE).toString()); } // update PC_CURRENT regs.setRegister (TTK91Cpu.CU_PC_CURRENT, regs.getRegister (TTK91Cpu.CU_PC)); // give registers to runDebugger int[] registers = new int[8]; for (int i=0; i < registers.length; i++) registers[i] = regs.getRegister (i + TTK91Cpu.REG_R0); runDebugger.setRegisters (registers); return runDebugger.cycleEnd(); } /** Transfer-operations. */ private void transfer(int opcode, int Rj, int M, int ADDR, int param) throws TTK91BadAccessMode, TTK91AddressOutOfBounds, TTK91NoKbdData, TTK91NoStdInData, TTK91InvalidDevice { runDebugger.setOperationType (RunDebugger.DATA_TRANSFER_OPERATION); switch (opcode) { case 1 : // STORE if (M == 2) { status = TTK91Cpu.STATUS_ABNORMAL_EXIT; throw new TTK91BadAccessMode(new Message (Processor.STORE_BAD_ACCESS_MODE_MESSAGE).toString()); } if (M == 0) writeToMemory (ADDR, regs.getRegister(Rj)); if (M == 1) writeToMemory (ram.getValue (ADDR), regs.getRegister(Rj)); break; case 2 : // LOAD regs.setRegister (Rj, param); break; case 3 : switch (param) { case KBD : // Keyboard if (kbdData == null) { status = TTK91Cpu.STATUS_ABNORMAL_EXIT; throw new TTK91NoKbdData(new Message (Processor.NO_KDB_DATA_MESSAGE).toString()); } regs.setRegister (Rj, kbdData.intValue()); runDebugger.setIN (param, kbdData.intValue()); kbdData = null; status = TTK91Cpu.STATUS_STILL_RUNNING; break; case STDIN : // Standard input file if (stdinData == null) { status = TTK91Cpu.STATUS_ABNORMAL_EXIT; throw new TTK91NoStdInData(new Message (Processor.NO_STDIN_DATA_MESSAGE).toString()); } regs.setRegister (Rj, stdinData.intValue()); runDebugger.setIN (param, stdinData.intValue()); stdinData = null; status = TTK91Cpu.STATUS_STILL_RUNNING; break; default : status = TTK91Cpu.STATUS_ABNORMAL_EXIT; throw new TTK91InvalidDevice(new Message (Processor.INVALID_DEVICE_MESSAGE).toString()); } break; case 4 : // OUT if (param != CRT && param != STDOUT) { status = TTK91Cpu.STATUS_ABNORMAL_EXIT; throw new TTK91InvalidDevice(new Message (Processor.INVALID_DEVICE_MESSAGE).toString()); } runDebugger.setOUT (param, regs.getRegister(Rj)); break; } } /** ALU-operations. @return Result of the ALU-operation. */ private void alu(int opcode, int Rj, int param) throws TTK91IntegerOverflow, TTK91DivisionByZero { runDebugger.setOperationType (RunDebugger.ALU_OPERATION); long n; switch (opcode) { case 17 : // ADD n = (long)regs.getRegister (Rj) + (long)param; if (isOverflow (n)) { status = TTK91Cpu.STATUS_ABNORMAL_EXIT; throw new TTK91IntegerOverflow(new Message (Processor.INTEGER_OVERFLOW_MESSAGE).toString()); } regs.setRegister (Rj, (int)n); break; case 18 : // SUB n = (long)regs.getRegister (Rj) - (long)param; if (isOverflow (n)) { status = TTK91Cpu.STATUS_ABNORMAL_EXIT; throw new TTK91IntegerOverflow(new Message (Processor.INTEGER_OVERFLOW_MESSAGE).toString()); } regs.setRegister (Rj, (int)n); break; case 19 : // MUL n = (long)regs.getRegister (Rj) * (long)param; if (isOverflow (n)) { status = TTK91Cpu.STATUS_ABNORMAL_EXIT; throw new TTK91IntegerOverflow(new Message (Processor.INTEGER_OVERFLOW_MESSAGE).toString()); } regs.setRegister (Rj, (int)n); break; case 20 : // DIV if (param == 0) { status = TTK91Cpu.STATUS_ABNORMAL_EXIT; throw new TTK91DivisionByZero(new Message (Processor.DIVISION_BY_ZERO_MESSAGE).toString()); } regs.setRegister (Rj, regs.getRegister (Rj) / param); break; case 21 : // MOD if (param == 0) { status = TTK91Cpu.STATUS_ABNORMAL_EXIT; throw new TTK91DivisionByZero(new Message (Processor.DIVISION_BY_ZERO_MESSAGE).toString()); } regs.setRegister (Rj, regs.getRegister (Rj) % param); break; case 22 : // AND regs.setRegister (Rj, regs.getRegister (Rj) & param); break; case 23 : regs.setRegister (Rj, regs.getRegister (Rj) | param); break; case 24 : // XOR regs.setRegister (Rj, regs.getRegister (Rj) ^ param); break; case 25 : // SHL regs.setRegister (Rj, regs.getRegister(Rj) << param); break; case 26 : // SHR regs.setRegister (Rj, regs.getRegister(Rj) >>> param); break; case 27 : // SHRA regs.setRegister (Rj, regs.getRegister(Rj) >> param); break; } runDebugger.setALUResult (regs.getRegister (Rj)); } /** Compare-method manipulates status register. @param Rj First value to compare (register index). @param param Second value. */ private void comp(int Rj, int param) { // COMP runDebugger.setOperationType (RunDebugger.COMP_OPERATION); if (regs.getRegister (Rj) > param) { sr[0] = true; sr[1] = false; sr[2] = false; runDebugger.setCompareResult (0); } else if (regs.getRegister (Rj) < param) { sr[0] = false; sr[1] = false; sr[2] = true; runDebugger.setCompareResult (2); } else { sr[0] = false; sr[1] = true; sr[2] = false; runDebugger.setCompareResult (1); } } /** Branching. */ private void branch(int opcode, int Rj, int M, int ADDR, int param) throws TTK91BadAccessMode { runDebugger.setOperationType (RunDebugger.BRANCH_OPERATION); if (M == 2) { status = TTK91Cpu.STATUS_ABNORMAL_EXIT; throw new TTK91BadAccessMode(new Message (Processor.BRANCH_BAD_ACCESS_MODE_MESSAGE).toString()); } switch (opcode) { case 32 : // JUMP setNewPC (param); break; case 33 : // JNEG if (regs.getRegister (Rj) < 0) setNewPC (param); break; case 34 : // JZER if (regs.getRegister (Rj) == 0) setNewPC (param); break; case 35 : // JPOS if (regs.getRegister (Rj) > 0) setNewPC (param); break; case 36 : // JNNEG if (regs.getRegister (Rj) >= 0) setNewPC (param); break; case 37 : // JNZER if (regs.getRegister (Rj) != 0) setNewPC (param); break; case 38 : // JNPOS if (regs.getRegister (Rj) <= 0) setNewPC (param); break; case 39 : // JLES if (sr[2]) setNewPC (param); break; case 40 : // JEQU if (sr[1]) setNewPC (param); break; case 41 : // JGRE if (sr[0]) setNewPC (param); break; case 42 : // JNLES if (sr[1] || sr[0]) setNewPC (param); break; case 43 : // JNEQU if (sr[2] || sr[0]) setNewPC (param); break; case 44 : // JNGRE if (sr[2] || sr[1]) setNewPC (param); break; } } /** Stack. */ private void stack(int opcode, int Rj, int Ri, int param) throws TTK91AddressOutOfBounds { runDebugger.setOperationType (RunDebugger.STACK_OPERATION); switch (opcode) { case 51 : // PUSH regs.setRegister (Rj, regs.getRegister(Rj) +1); writeToMemory (regs.getRegister(Rj), param); break; case 52 : // POP regs.setRegister (Ri, ram.getValue (regs.getRegister(Rj))); regs.setRegister (Rj, regs.getRegister(Rj) -1); break; case 53 : // PUSHR stack(51, Rj, Ri, regs.getRegister (TTK91Cpu.REG_R0)); // PUSH R0 stack(51, Rj, Ri, regs.getRegister (TTK91Cpu.REG_R1)); // PUSH R1 stack(51, Rj, Ri, regs.getRegister (TTK91Cpu.REG_R2)); // PUSH R2 stack(51, Rj, Ri, regs.getRegister (TTK91Cpu.REG_R3)); // PUSH R3 stack(51, Rj, Ri, regs.getRegister (TTK91Cpu.REG_R4)); // PUSH R4 stack(51, Rj, Ri, regs.getRegister (TTK91Cpu.REG_R5)); // PUSH R5 stack(51, Rj, Ri, regs.getRegister (TTK91Cpu.REG_R6)); // PUSH R6 break; case 54 : // POPR stack(52, Rj, regs.getRegister (TTK91Cpu.REG_R6), param); // POP R6 stack(52, Rj, regs.getRegister (TTK91Cpu.REG_R5), param); // POP R5 stack(52, Rj, regs.getRegister (TTK91Cpu.REG_R4), param); // POP R4 stack(52, Rj, regs.getRegister (TTK91Cpu.REG_R3), param); // POP R3 stack(52, Rj, regs.getRegister (TTK91Cpu.REG_R2), param); // POP R2 stack(52, Rj, regs.getRegister (TTK91Cpu.REG_R1), param); // POP R1 stack(52, Rj, regs.getRegister (TTK91Cpu.REG_R0), param); // POP R0 break; } } /** Subroutine. */ private void subr(int opcode, int Rj, int ADDR, int param) throws TTK91AddressOutOfBounds { runDebugger.setOperationType (RunDebugger.SUB_OPERATION); int sp; switch (opcode) { case 49 : // CALL // push PC and FP to stack (Rj is stack pointer) sp = regs.getRegister (Rj); writeToMemory (++sp, regs.getRegister (TTK91Cpu.CU_PC)); writeToMemory (++sp, regs.getRegister (TTK91Cpu.REG_FP)); // update stack and frame pointers regs.setRegister (Rj, sp); regs.setRegister (TTK91Cpu.REG_FP, sp); // set PC setNewPC (ADDR); break; case 50 : // EXIT // pop FP and PC from stack (Rj is stack pointer) sp = regs.getRegister (Rj); regs.setRegister (TTK91Cpu.REG_FP, ram.getValue (sp setNewPC (ram.getValue (sp // decrease number of parameters from stack regs.setRegister (Rj, sp -param); break; } } /** Supervisor call. */ private void svc(int Rj, int param) throws TTK91AddressOutOfBounds, TTK91NoKbdData { runDebugger.setSVCOperation (param); Calendar calendar; // make CALL operation to supervisor subr(49, Rj, OS_CODE_AREA, param); switch (param) { case 11 : // HALT runDebugger.setOperationType (RunDebugger.SVC_OPERATION); status = TTK91Cpu.STATUS_SVC_SD; break; case 12 : // READ if (kbdData == null) { subr (50, Rj, 0, 1); // EXIT from SVC(READ) with one parameter runDebugger.setOperationType (RunDebugger.SVC_OPERATION); status = TTK91Cpu.STATUS_ABNORMAL_EXIT; throw new TTK91NoKbdData(new Message (Processor.NO_KDB_DATA_MESSAGE).toString()); } writeToMemory (ram.getValue (regs.getRegister(TTK91Cpu.REG_FP) -2), kbdData.intValue()); kbdData = null; status = TTK91Cpu.STATUS_STILL_RUNNING; subr (50, Rj, 0, 1); // EXIT from SVC(READ) with one parameter break; case 13 : // WRITE runDebugger.setOUT (CRT, ram.getValue (regs.getRegister(TTK91Cpu.REG_FP) -2)); subr (50, Rj, 0, 1); // EXIT from SVC(WRITE) with 1 parameter break; case 14 : // TIME calendar = new GregorianCalendar(); int hour = calendar.get(Calendar.HOUR); int minute = calendar.get(Calendar.MINUTE); int second = calendar.get(Calendar.SECOND); // Write second, minute and hour to given places. Right places are found from stack. writeToMemory (ram.getValue (regs.getRegister(TTK91Cpu.REG_FP) -2), second); writeToMemory (ram.getValue (regs.getRegister(TTK91Cpu.REG_FP) -3), minute); writeToMemory (ram.getValue (regs.getRegister(TTK91Cpu.REG_FP) -4), hour); subr (50, Rj, 0, 3); // EXIT from SVC(TIME) with 3 parameters break; case 15 : // DATE calendar = new GregorianCalendar(); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH); int date = calendar.get(Calendar.DATE); // Write date, month and year to given places. Right places are found from stack. writeToMemory (ram.getValue (regs.getRegister(TTK91Cpu.REG_FP) -2), date); writeToMemory (ram.getValue (regs.getRegister(TTK91Cpu.REG_FP) -3), month); writeToMemory (ram.getValue (regs.getRegister(TTK91Cpu.REG_FP) -4), year); subr (50, Rj, 0, 3); // EXIT from SVC(DATE) with 3 parameters break; } runDebugger.setOperationType (RunDebugger.SVC_OPERATION); } private void nop() { runDebugger.setOperationType (RunDebugger.NO_OPERATION); } private void writeToMemory (int row, int value) throws TTK91AddressOutOfBounds { MemoryLine memoryLine = new MemoryLine (value, new BinaryInterpreter().binaryToString(value)); ram.setMemoryLine (row, memoryLine); runDebugger.addChangedMemoryLine (row, memoryLine); } private void setNewPC (int newPC) { regs.setRegister (TTK91Cpu.CU_PC, newPC); runDebugger.setNewPC (newPC); } /** Tests if given long value is acceptable int value. */ private boolean isOverflow (long value) { return (value > (long)Integer.MAX_VALUE || value < (long)Integer.MIN_VALUE); } }
package com.tns.bindings; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.*; import org.ow2.asmdex.*; import org.ow2.asmdex.structureCommon.*; import android.util.Log; public class Dump { private static final String callJsMethodSignatureCtor = "Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/String;Z[Ljava/lang/Object;"; private static final String callJsMethodSignatureMethod = "Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/String;[Ljava/lang/Object;"; private static final String LCOM_TNS = "Lcom/tns/gen/"; private static final String LCOM_TNS_PLATFORM = "Lcom/tns/Platform;"; static final String preferenceActivityJniSignature = "Lcom/tns/android/preference/PreferenceActivity;"; static final String preferenceActivityClass = "Landroid/preference/PreferenceActivity;"; static final String objectClass = "Ljava/lang/Object;"; static final String platformClass = LCOM_TNS_PLATFORM; static final String callJSMethodName = "callJSMethod"; static final String initInstanceMethodName = "initInstance"; static final StringBuffer methodDescriptorBuilder = new StringBuffer(); /** * Returns the dex descriptor corresponding to the given method. * * @param m * a {@link Method Method} object. * @return the descriptor of the given method. */ public String getDexMethodDescriptor(final Method method) { Class<?>[] parameters = method.getParameterTypes(); methodDescriptorBuilder.setLength(0); getDexDescriptor(methodDescriptorBuilder, method.getReturnType()); for (int i = 0; i < parameters.length; ++i) { getDexDescriptor(methodDescriptorBuilder, parameters[i]); } return methodDescriptorBuilder.toString(); } /** * Returns the dex descriptor corresponding to the given method. * * @param m * a {@link Method Method} object. * @return the descriptor of the given method. */ public String getMethodOverloadDescriptor(final Method method) { Class<?>[] parameters = method.getParameterTypes(); methodDescriptorBuilder.setLength(0); for (int i = 0; i < parameters.length; ++i) { getDexDescriptor(methodDescriptorBuilder, parameters[i]); } return methodDescriptorBuilder.toString(); } /** * Returns the dex descriptor corresponding to the given method. * * @param m * a {@link Method Method} object. * @return the descriptor of the given method. */ public String getDexConstructorDescriptor(final Constructor constructor) { Class<?>[] parameters = constructor.getParameterTypes(); methodDescriptorBuilder.setLength(0); getDexDescriptor(methodDescriptorBuilder, Void.TYPE); for (int i = 0; i < parameters.length; ++i) { getDexDescriptor(methodDescriptorBuilder, parameters[i]); } return methodDescriptorBuilder.toString(); } private void getDexDescriptor(final StringBuffer buf, final Class<?> c) { Class<?> d = c; while (true) { if (d.isPrimitive()) { char car; if (d == Integer.TYPE) { car = 'I'; } else if (d == Void.TYPE) { car = 'V'; } else if (d == Boolean.TYPE) { car = 'Z'; } else if (d == Byte.TYPE) { car = 'B'; } else if (d == Character.TYPE) { car = 'C'; } else if (d == Short.TYPE) { car = 'S'; } else if (d == Double.TYPE) { car = 'D'; } else if (d == Float.TYPE) { car = 'F'; } else /* if (d == Long.TYPE) */{ car = 'J'; } buf.append(car); return; } else if (d.isArray()) { buf.append('['); d = d.getComponentType(); } else { buf.append('L'); String name = d.getName(); int len = name.length(); for (int i = 0; i < len; ++i) { char car = name.charAt(i); buf.append(car == '.' ? '/' : car); } buf.append(';'); return; } } } /** * Returns the descriptor corresponding to the given Java type. * From ASM sources org.objectweb.asm.Type * @param c * an object class, a primitive class or an array class. * @return the descriptor corresponding to the given class. */ public static String getAsmDescriptor(final Class<?> c) { StringBuffer buf = new StringBuffer(); getAsmDescriptor(buf, c); return buf.toString(); } /** * Appends the descriptor of the given class to the given string buffer. * From ASM sources org.objectweb.asm.Type * @param buf * the string buffer to which the descriptor must be appended. * @param c * the class whose descriptor must be computed. */ private static void getAsmDescriptor(final StringBuffer buf, final Class<?> c) { Class<?> d = c; while (true) { if (d.isPrimitive()) { char car; if (d == Integer.TYPE) { car = 'I'; } else if (d == Void.TYPE) { car = 'V'; } else if (d == Boolean.TYPE) { car = 'Z'; } else if (d == Byte.TYPE) { car = 'B'; } else if (d == Character.TYPE) { car = 'C'; } else if (d == Short.TYPE) { car = 'S'; } else if (d == Double.TYPE) { car = 'D'; } else if (d == Float.TYPE) { car = 'F'; } else /* if (d == Long.TYPE) */{ car = 'J'; } buf.append(car); return; } else if (d.isArray()) { buf.append('['); d = d.getComponentType(); } else { buf.append('L'); String name = d.getName(); int len = name.length(); for (int i = 0; i < len; ++i) { char car = name.charAt(i); buf.append(car == '.' ? '/' : car); } buf.append(';'); return; } } } public void generateProxy(ApplicationWriter aw, String proxyName, Class<?> classTo, String[] methodOverrides, int ignored) { HashSet<String> methodOverridesSet = new HashSet<String>(); for (int i = 0; i < methodOverrides.length; i++) { String methodOverride = methodOverrides[i]; methodOverridesSet.add(methodOverride); } generateProxy(aw, proxyName, classTo, methodOverridesSet); } public void generateProxy(ApplicationWriter aw, Class<?> classTo, String[] methodOverrides, int ignored) { HashSet<String> methodOverridesSet = new HashSet<String>(); for (int i = 0; i < methodOverrides.length; i++) { String methodOverride = methodOverrides[i]; methodOverridesSet.add(methodOverride); } generateProxy(aw, "0", classTo, methodOverridesSet); } public void generateProxy(ApplicationWriter aw, String proxyName, Class<?> classTo) { generateProxy(aw, proxyName, classTo, null); } public void generateProxy(ApplicationWriter aw, Class<?> classTo) { generateProxy(aw, "0", classTo, null); } public void generateProxy(ApplicationWriter aw, String proxyName, Class<?> classTo, HashSet<String> methodOverrides) { String classSignature = getAsmDescriptor(classTo); //String methodSignature = org.objectweb.asm.Type.getMethodDescriptor(Object.class.getMethods()[0]); String tnsClassSignature = LCOM_TNS + classSignature.substring(1, classSignature.length() - 1).replace("$", "_") + "-" + proxyName + ";"; ClassVisitor cv = generateClass(aw, classTo, classSignature, tnsClassSignature); Method[] methods = getSupportedMethods(classTo, methodOverrides); methods = groupMethodsByName(methods); generateFields(cv); Constructor<?>[] ctors = classTo.getConstructors(); boolean hasOverridenCtor = ((methodOverrides != null) && methodOverrides.contains("init")); generateCtors(cv, classTo, ctors, classSignature, tnsClassSignature, hasOverridenCtor); generateMethods(cv, classTo, methods, classSignature, tnsClassSignature); cv.visitEnd(); } private Method[] groupMethodsByName(Method[] methods) { HashMap<String, Method> result = new HashMap<String, Method>(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; String methodName = method.getName(); String methodOverLoadDescriptor = getMethodOverloadDescriptor(method); methodName += "_" + methodOverLoadDescriptor; if (!result.containsKey(methodName)) { result.put(methodName, method); } } return result.values().toArray(new Method[result.size()]); } private Method[] getSupportedMethods(Class<?> clazz, HashSet<String> methodOverrides) { ArrayList<Method> result = new ArrayList<Method>(); HashMap<String, Method> finalMethods = new HashMap<String, Method>(); ArrayList<Class<?>> implementedInterfaces = new ArrayList<Class<?>>(); while (clazz != null) { Method[] methods = clazz.getDeclaredMethods(); ArrayList<Method> methodz = new ArrayList<Method>(); for (int i = 0; i < methods.length; i++) { Method candidateMethod = methods[i]; if (methodOverrides != null && !methodOverrides.contains(candidateMethod.getName())) { continue; } methodz.add(methods[i]); } Class<?>[] interfaces = clazz.getInterfaces(); for (int i = 0; i < interfaces.length; i++) { implementedInterfaces.add(interfaces[i]); } for (int i = 0; i < methodz.size(); i++) { Method method = methodz.get(i); if (isMethodSupported(method, finalMethods)) { result.add(method); } } clazz = clazz.getSuperclass(); } for (int i = 0; i < implementedInterfaces.size(); i++) { Class<?> implementedInterface = implementedInterfaces.get(i); Method[] interfaceMethods = implementedInterface.getMethods(); for (int j = 0; j < interfaceMethods.length; j++) { Method method = interfaceMethods[j]; if (methodOverrides != null && !methodOverrides.contains(method.getName())) { continue; } if (!isMethodMarkedAsFinalInClassHierarchy(method, finalMethods)) { result.add(method); } } } return result.toArray(new Method[result.size()]); //For debugging //return new Method[] { result.get(0) }; } private static boolean isMethodSupported(Method method, HashMap<String, Method> finalMethods) { int modifiers = method.getModifiers(); if (method.isSynthetic() || Modifier.isStatic(modifiers) || Modifier.isPrivate(modifiers)) { return false; } if (Modifier.isFinal(modifiers)) { finalMethods.put(method.getName(), method); return false; } boolean isPackagePrivate = !Modifier.isPrivate(modifiers) && !Modifier.isPublic(modifiers) && !Modifier.isProtected(modifiers); if (isPackagePrivate) { return false; } if (isMethodMarkedAsFinalInClassHierarchy(method, finalMethods)) { return false; } // if (finalMethods.size() != 0) // Method finalMethod = finalMethods.get(method.getName()); // if (finalMethod != null) // boolean isSameFinalMethod = areMethodSignaturesEqual(finalMethod, method); // if (isSameFinalMethod) // return false; return true; } private static boolean isMethodMarkedAsFinalInClassHierarchy(Method method, HashMap<String, Method> finalMethods) { if (finalMethods.size() != 0) { Method finalMethod = finalMethods.get(method.getName()); if (finalMethod != null) { boolean isSameFinalMethod = areMethodSignaturesEqual(finalMethod, method); if (isSameFinalMethod) { return true; } } } return false; } private static boolean areMethodSignaturesEqual(Method x, Method y) { if (x.equals(y)) return true; if (!x.getName().equals(y.getName())) return false; Class<?>[] xParams = x.getParameterTypes(); Class<?>[] yParams = y.getParameterTypes(); if (xParams.length != yParams.length) return false; boolean result = true; for (int i = 0; i < xParams.length; i++) { if (!xParams[i].equals(yParams[i])) { result = false; break; } } return result; } private void generateCtors(ClassVisitor cv, Class<?> classTo, Constructor<?>[] ctors, String classSignature, String tnsClassSignature, boolean hasOverridenCtor) { if (classTo.isInterface()) { try { generateCtor(cv, classTo, Object.class.getConstructor(), classSignature, tnsClassSignature, false); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { for (Constructor<?> ctor : ctors) { generateCtor(cv, classTo, ctor, classSignature, tnsClassSignature, hasOverridenCtor); } } } private void generateCtor(ClassVisitor cv, Class<?> classTo, Constructor<?> ctor, String classSignature, String tnsClassSignature, boolean hasOverridenCtor) { //TODO: handle generic and vararg ctors if needed String ctorSignature = getDexConstructorDescriptor(ctor); //org.objectweb.asm.Type.getConstructorDescriptor(ctor); MethodVisitor mv; int ctorModifiers = getDexModifiers(ctor.getModifiers()); //int locaVarsCount = 2; //int thisRegister = locaVarsCount + 1; mv = cv.visitMethod(ctorModifiers + org.ow2.asmdex.Opcodes.ACC_CONSTRUCTOR, "<init>", ctorSignature, null, null); mv.visitCode(); //mv.visitMaxs(4, 0); //TODO: max stack size should be equal to localVarCount + 1 int thisRegister = generateMaxStackSize(mv, ctor); int argCount = ctor.getParameterTypes().length; int[] args = generateArgsArray(thisRegister, argCount, ctor); if (!classTo.isInterface()) { mv.visitMethodInsn(org.ow2.asmdex.Opcodes.INSN_INVOKE_DIRECT_RANGE, classSignature, "<init>", ctorSignature, args); } else { mv.visitMethodInsn(org.ow2.asmdex.Opcodes.INSN_INVOKE_DIRECT_RANGE, objectClass, "<init>", ctorSignature, args); } generateInitializedBlock(mv, thisRegister, classSignature, tnsClassSignature); if (hasOverridenCtor) { generateCtorOverridenBlock(mv, thisRegister, ctor, classSignature, tnsClassSignature); } generateReturnVoid(mv); } private void generateReturnVoid(MethodVisitor mv) { mv.visitInsn(org.ow2.asmdex.Opcodes.INSN_RETURN_VOID); mv.visitEnd(); } private void generateCtorOverridenBlock(MethodVisitor mv, int thisRegister, Constructor<?> ctor, String classSignature, String tnsClassSignature) { int argCount = generateArrayForCallJsArguments(mv, ctor.getParameterTypes(), thisRegister, classSignature, tnsClassSignature); mv.visitStringInsn(org.ow2.asmdex.Opcodes.INSN_CONST_STRING, 1, "init"); //put "init" in register 1 mv.visitVarInsn(org.ow2.asmdex.Opcodes.INSN_CONST_4, 2, 1); //put true to register 2 == isConstructor argument mv.visitMethodInsn(org.ow2.asmdex.Opcodes.INSN_INVOKE_STATIC, LCOM_TNS_PLATFORM, "callJSMethod", callJsMethodSignatureCtor, new int[] { 3, 1, 2, 0 }); //invoke callJSMethod(this, "init", true, params) } private void generateInitializedBlock(MethodVisitor mv, int thisRegister, String classSignature, String tnsClassSignature) { mv.visitFieldInsn(org.ow2.asmdex.Opcodes.INSN_IGET_BOOLEAN, tnsClassSignature, "__initialized", "Z", thisRegister - 2, thisRegister); //put __initialized in local var 1 Label label = new Label(); mv.visitJumpInsn(org.ow2.asmdex.Opcodes.INSN_IF_NEZ, label, thisRegister - 2, 0); //compare local var 1 with false mv.visitVarInsn(org.ow2.asmdex.Opcodes.INSN_CONST_4, thisRegister - 1, 1); //put true in local var 1 mv.visitFieldInsn(org.ow2.asmdex.Opcodes.INSN_IPUT_BOOLEAN, tnsClassSignature, "__initialized", "Z", thisRegister - 1 , thisRegister); //set field to the value of 2 mv.visitMethodInsn(org.ow2.asmdex.Opcodes.INSN_INVOKE_STATIC, LCOM_TNS_PLATFORM, "initInstance", "VLjava/lang/Object;", new int[] { thisRegister }); //call init instance passing this as arugment mv.visitLabel(label); } private void generateMethods(ClassVisitor cv, Class<?> classTo, Method[] methods, String classSignature, String tnsClassSignature) { //for (Method method : methods) int fieldNameCounter = 0; int bitCounter = 1; for (int i = 0; i < methods.length; i++) { if (bitCounter == 128) { bitCounter = 1; fieldNameCounter++; } Method sourceMethod = methods[i]; generateMethod(cv, classTo, sourceMethod, i, classSignature, tnsClassSignature, bitCounter); bitCounter *= 2; } generateEqualsSuper(cv); generateHashCodeSuper(cv); } private void generateEqualsSuper(ClassVisitor cv) { MethodVisitor mv = cv.visitMethod(org.ow2.asmdex.Opcodes.ACC_PUBLIC, "equals__super", "ZLjava/lang/Object;", null, null); mv.visitCode(); mv.visitMaxs(3, 0); mv.visitMethodInsn(org.ow2.asmdex.Opcodes.INSN_INVOKE_SUPER, "Ljava/lang/Object;", "equals", "ZLjava/lang/Object;", new int[] { 1, 2 }); mv.visitIntInsn(org.ow2.asmdex.Opcodes.INSN_MOVE_RESULT, 0); mv.visitIntInsn(org.ow2.asmdex.Opcodes.INSN_RETURN, 0); mv.visitEnd(); } private void generateHashCodeSuper(ClassVisitor cv) { MethodVisitor mv = cv.visitMethod(org.ow2.asmdex.Opcodes.ACC_PUBLIC, "hashCode__super", "I", null, null); mv.visitCode(); mv.visitMaxs(2, 0); mv.visitMethodInsn(org.ow2.asmdex.Opcodes.INSN_INVOKE_SUPER, "Ljava/lang/Object;", "hashCode", "I", new int[] { 1 }); mv.visitIntInsn(org.ow2.asmdex.Opcodes.INSN_MOVE_RESULT, 0); mv.visitIntInsn(org.ow2.asmdex.Opcodes.INSN_RETURN, 0); mv.visitEnd(); } private void generateMethod(ClassVisitor cv, Class<?> classTo, Method method, int methodNumber, String classSignature, String tnsClassSignature, int fieldBit) { if (ProxyGenerator.IsLogEnabled) Log.d("TNS.Rungime.Proxy.Generator", "generatingMethod " + method.getName()); //TODO: handle checked exceptions String methodDexSignature = getDexMethodDescriptor(method); String[] exceptions = new String[0]; MethodVisitor mv; int methodModifiers = getDexModifiers(method.getModifiers()); mv = cv.visitMethod(methodModifiers, method.getName(), methodDexSignature, null, exceptions); mv.visitCode(); int thisRegister = generateMaxStackSize(mv, method); if (!classTo.isInterface()) { generateInitializedBlock(mv, thisRegister, classSignature, tnsClassSignature); } generateCallOverrideBlock(mv, method, thisRegister, classSignature, tnsClassSignature, methodDexSignature, fieldBit); mv.visitEnd(); } private int generateMaxStackSize(MethodVisitor mv, Method method) { //3 local vars are enough for NativeScript bindings methods. Local vars start from 0 register till register 2. //Then 'this' is register 3 and then all parameters according to their size int registersCount = 3/*local vars*/ + 1 /*this*/; int thisRegister = registersCount - 1; Class<?>[] paramTypes = method.getParameterTypes(); int paramCount = paramTypes.length; for (int i = 0; i < paramCount; i++) { Class<?> paramType = paramTypes[i]; if (paramType == Integer.TYPE || paramType == Character.TYPE || paramType == Byte.TYPE || paramType == Short.TYPE || paramType == Boolean.TYPE || paramType == Float.TYPE) { registersCount++; } else if (paramType == Long.TYPE || paramType == Double.TYPE) { registersCount += 2; } else { registersCount += 1; } } mv.visitMaxs(registersCount, 0); return thisRegister; } private int generateMaxStackSize(MethodVisitor mv, Constructor<?> ctor) { //3 local vars are enough for NativeScript bindings methods. Local vars start from 0 register till register 2. //Then 'this' is register 3 and then all parameters according to their size int registersCount = 3/*local vars*/ + 1 /*this*/; int thisRegister = registersCount - 1; Class<?>[] paramTypes = ctor.getParameterTypes(); int paramCount = paramTypes.length; for (int i = 0; i < paramCount; i++) { Class<?> paramType = paramTypes[i]; if (paramType == Integer.TYPE || paramType == Character.TYPE || paramType == Byte.TYPE || paramType == Short.TYPE || paramType == Boolean.TYPE || paramType == Float.TYPE) { registersCount++; } else if (paramType == Long.TYPE || paramType == Double.TYPE) { registersCount += 2; } else { registersCount += 1; } } mv.visitMaxs(registersCount, 0); return thisRegister; } private void generateCallOverrideBlock(MethodVisitor mv, Method method, int thisRegister, String classSignature, String tnsClassSignature, String methodDexSignature, int fieldBit) { //call the override int argCount = generateArrayForCallJsArguments(mv, method.getParameterTypes() , thisRegister, classSignature, tnsClassSignature); mv.visitStringInsn(org.ow2.asmdex.Opcodes.INSN_CONST_STRING, 1, method.getName()); mv.visitMethodInsn(org.ow2.asmdex.Opcodes.INSN_INVOKE_STATIC, platformClass, callJSMethodName, callJsMethodSignatureMethod, new int[] { thisRegister, 1, 0 }); //Label returnLabel = new Label(); //mv.visitLabel(returnLabel); generateReturnFromObject(mv, method.getReturnType(), thisRegister, 1); } private int[] generateArgsArray(int thisRegister, int argCount, Constructor ctor) { Class<?>[] paramTypes = ctor.getParameterTypes(); int argumentsCount = paramTypes.length; int[] argsForSuper = new int[1 + argumentsCount*2]; //thisRegister + argCount * 2 since it long and double take 2 registers int argsForSuperIndex = 0; argsForSuper[argsForSuperIndex] = thisRegister; argsForSuperIndex++; int arrayIndex = 0; while (arrayIndex < argumentsCount) { Class<?> paramType = paramTypes[arrayIndex]; if (paramType.isPrimitive()) { if (paramType == Integer.TYPE || paramType == Character.TYPE || paramType == Byte.TYPE || paramType == Short.TYPE || paramType == Boolean.TYPE || paramType == Float.TYPE) { argsForSuper[argsForSuperIndex] = thisRegister + arrayIndex + 1; argsForSuperIndex++; } else if (paramType == Long.TYPE || paramType == Double.TYPE) { argsForSuper[argsForSuperIndex] = thisRegister + arrayIndex + 1; argsForSuperIndex++; argsForSuper[argsForSuperIndex] = thisRegister + arrayIndex + 2; argsForSuperIndex++; } } else { argsForSuper[argsForSuperIndex] = thisRegister + arrayIndex + 1; argsForSuperIndex++; } arrayIndex++; } return Arrays.copyOf(argsForSuper, argsForSuperIndex); } /** * Creates new Object[] or null value (when no arguments) and puts it in register 0 */ private int generateArrayForCallJsArguments(MethodVisitor mv, Class<?>[] paramTypes, int thisRegister, String classSignature, String tnsClassSignature) { int argumentsCount = paramTypes.length; if (argumentsCount == 0) { mv.visitVarInsn(org.ow2.asmdex.Opcodes.INSN_CONST_4, 0, 0); //set null at register 0. our params array is null return 0; } mv.visitVarInsn(org.ow2.asmdex.Opcodes.INSN_CONST_16, 2, argumentsCount); //put array size in register 2 mv.visitTypeInsn(org.ow2.asmdex.Opcodes.INSN_NEW_ARRAY, 0, 0, 2, "[Ljava/lang/Object;"); //create array with size in register 2 and put it in register 0 int arrayIndex = 0; int argNumber = 4; int numberOfDoubleRegisterArguments = 0; while (argNumber < 4 + argumentsCount + numberOfDoubleRegisterArguments) { mv.visitVarInsn(org.ow2.asmdex.Opcodes.INSN_CONST_16, 1, arrayIndex); //put the array access index value in register 1 Class<?> paramType = paramTypes[arrayIndex]; if (paramType.isPrimitive()) { if (paramType == Integer.TYPE) { //box the primitive value at register i mv.visitMethodInsn(org.ow2.asmdex.Opcodes.INSN_INVOKE_STATIC_RANGE, "Ljava/lang/Integer;", "valueOf", "Ljava/lang/Integer;I", new int[] { argNumber }); //move the result object in register 2 mv.visitIntInsn(org.ow2.asmdex.Opcodes.INSN_MOVE_RESULT_OBJECT, 2); //put the object at register 2 in array at index register 1 mv.visitArrayOperationInsn(org.ow2.asmdex.Opcodes.INSN_APUT_OBJECT, 2, 0, 1); } else if (paramType == Character.TYPE) { mv.visitMethodInsn(org.ow2.asmdex.Opcodes.INSN_INVOKE_STATIC_RANGE, "Ljava/lang/Character;", "valueOf", "Ljava/lang/Character;C", new int[] { argNumber }); mv.visitIntInsn(org.ow2.asmdex.Opcodes.INSN_MOVE_RESULT_OBJECT, 2); mv.visitArrayOperationInsn(org.ow2.asmdex.Opcodes.INSN_APUT_OBJECT, 2, 0, 1); } else if (paramType == Byte.TYPE) { mv.visitMethodInsn(org.ow2.asmdex.Opcodes.INSN_INVOKE_STATIC_RANGE, "Ljava/lang/Byte;", "valueOf", "Ljava/lang/Byte;B", new int[] { argNumber }); mv.visitIntInsn(org.ow2.asmdex.Opcodes.INSN_MOVE_RESULT_OBJECT, 2); mv.visitArrayOperationInsn(org.ow2.asmdex.Opcodes.INSN_APUT_OBJECT, 2, 0, 1); } else if (paramType == Short.TYPE) { mv.visitMethodInsn(org.ow2.asmdex.Opcodes.INSN_INVOKE_STATIC_RANGE, "Ljava/lang/Short;", "valueOf", "Ljava/lang/Short;S", new int[] { argNumber }); mv.visitIntInsn(org.ow2.asmdex.Opcodes.INSN_MOVE_RESULT_OBJECT, 2); mv.visitArrayOperationInsn(org.ow2.asmdex.Opcodes.INSN_APUT_OBJECT, 2, 0, 1); } else if (paramType == Boolean.TYPE) { mv.visitMethodInsn(org.ow2.asmdex.Opcodes.INSN_INVOKE_STATIC_RANGE, "Ljava/lang/Boolean;", "valueOf", "Ljava/lang/Boolean;Z", new int[] { argNumber }); mv.visitIntInsn(org.ow2.asmdex.Opcodes.INSN_MOVE_RESULT_OBJECT, 2); mv.visitArrayOperationInsn(org.ow2.asmdex.Opcodes.INSN_APUT_OBJECT, 2, 0, 1); } else if (paramType == Long.TYPE) { mv.visitMethodInsn(org.ow2.asmdex.Opcodes.INSN_INVOKE_STATIC_RANGE, "Ljava/lang/Long;", "valueOf", "Ljava/lang/Long;J", new int[] { argNumber, argNumber + 1 }); mv.visitIntInsn(org.ow2.asmdex.Opcodes.INSN_MOVE_RESULT_OBJECT, 2); mv.visitArrayOperationInsn(org.ow2.asmdex.Opcodes.INSN_APUT_OBJECT, 2, 0, 1); argNumber++; numberOfDoubleRegisterArguments++; } else if (paramType == Float.TYPE) { mv.visitMethodInsn(org.ow2.asmdex.Opcodes.INSN_INVOKE_STATIC_RANGE, "Ljava/lang/Float;", "valueOf", "Ljava/lang/Float;F", new int[] { argNumber }); mv.visitIntInsn(org.ow2.asmdex.Opcodes.INSN_MOVE_RESULT_OBJECT, 2); mv.visitArrayOperationInsn(org.ow2.asmdex.Opcodes.INSN_APUT_OBJECT, 2, 0, 1); } else if (paramType == Double.TYPE) { mv.visitMethodInsn(org.ow2.asmdex.Opcodes.INSN_INVOKE_STATIC_RANGE, "Ljava/lang/Double;", "valueOf", "Ljava/lang/Double;D", new int[] { argNumber, argNumber + 1 }); mv.visitIntInsn(org.ow2.asmdex.Opcodes.INSN_MOVE_RESULT_OBJECT, 2); mv.visitArrayOperationInsn(org.ow2.asmdex.Opcodes.INSN_APUT_OBJECT, 2, 0, 1); argNumber++; numberOfDoubleRegisterArguments++; } } else { //register 1 contains the value of the arrayIndex //i is the register containing the value of the object reference //0 register contains the reference to the array mv.visitArrayOperationInsn(org.ow2.asmdex.Opcodes.INSN_APUT_OBJECT, argNumber, 0, 1); } // int arrayPutOpCode = getArrayPutInstructionByType(paramTypes[arrayIndex]); //mv.visitArrayOperationInsn(org.ow2.asmdex.Opcodes.INSN_APUT_OBJECT, i, 0, 1); //put params[i] in the array at index register 1 //mv.visitArrayOperationInsn(org.ow2.asmdex.Opcodes.INSN_APUT_ argNumber++; arrayIndex++; } return argumentsCount; } // private int getArrayPutInstructionByParamType(Class<?> paramType) // if (paramType.isPrimitive()) // if (paramType == Integer.TYPE) // return org.ow2.asmdex.Opcodes.INSN_APUT_WIDE; // else if (paramType == Boolean.TYPE) // return org.ow2.asmdex.Opcodes.INSN_APUT_BOOLEAN; // else if (d == Byte.TYPE) { // car = 'B'; // else if (d == Character.TYPE) { // car = 'C'; // else if (d == Short.TYPE) { // car = 'S'; // else if (d == Double.TYPE) { // car = 'D'; // else if (d == Float.TYPE) { // car = 'F'; // else /* if (d == Long.TYPE) */{ // car = 'J'; // buf.append(car); // return; // } else if (d.isArray()) { // buf.append('['); // d = d.getComponentType(); // } else { // buf.append('L'); // String name = d.getName(); // int len = name.length(); // for (int i = 0; i < len; ++i) { // char car = name.charAt(i); // buf.append(car == '.' ? '/' : car); // buf.append(';'); // return; private static final String integerTypeDescriptor = "Ljava/lang/Integer;"; private static final String booleanTypeDescriptor = "Ljava/lang/Boolean;"; private static final String byteTypeDescriptor = "Ljava/lang/Byte;"; private static final String characterTypeDescriptor = "Ljava/lang/Character;"; private static final String shortTypeDescriptor = "Ljava/lang/Short;"; private static final String doubleTypeDescriptor = "Ljava/lang/Double;"; private static final String floatTypeDescriptor = "Ljava/lang/Float;"; private static final String longTypeDescriptor = "Ljava/lang/Long;"; private void generateReturnFromObject(MethodVisitor mv, Class<?> targetReturnType, int thisRegister, int valueRegister) { if (targetReturnType == Void.TYPE) { mv.visitInsn(org.ow2.asmdex.Opcodes.INSN_RETURN_VOID); return; } mv.visitIntInsn(org.ow2.asmdex.Opcodes.INSN_MOVE_RESULT_OBJECT, valueRegister); //get the result of from the very last method call in register 1; if (targetReturnType.isPrimitive()) { if (targetReturnType == Integer.TYPE) { mv.visitTypeInsn(org.ow2.asmdex.Opcodes.INSN_CHECK_CAST, 0, valueRegister, 0, integerTypeDescriptor); //throw exception if can't cast this reference to the return type mv.visitMethodInsn(org.ow2.asmdex.Opcodes.INSN_INVOKE_VIRTUAL, integerTypeDescriptor, "intValue", "I", new int[] { valueRegister }); mv.visitIntInsn(org.ow2.asmdex.Opcodes.INSN_MOVE_RESULT, valueRegister); mv.visitIntInsn(org.ow2.asmdex.Opcodes.INSN_RETURN, valueRegister); } else if (targetReturnType == Boolean.TYPE) { mv.visitTypeInsn(org.ow2.asmdex.Opcodes.INSN_CHECK_CAST, 0, valueRegister, 0, booleanTypeDescriptor); //throw exception if can't cast this reference to the return type mv.visitMethodInsn(org.ow2.asmdex.Opcodes.INSN_INVOKE_VIRTUAL, booleanTypeDescriptor, "booleanValue", "Z", new int[] { valueRegister }); mv.visitIntInsn(org.ow2.asmdex.Opcodes.INSN_MOVE_RESULT, valueRegister); mv.visitIntInsn(org.ow2.asmdex.Opcodes.INSN_RETURN, valueRegister); } else if (targetReturnType == Byte.TYPE) { mv.visitTypeInsn(org.ow2.asmdex.Opcodes.INSN_CHECK_CAST, 0, valueRegister, 0, byteTypeDescriptor); //throw exception if can't cast this reference to the return type mv.visitMethodInsn(org.ow2.asmdex.Opcodes.INSN_INVOKE_VIRTUAL, byteTypeDescriptor, "byteValue", "B", new int[] { valueRegister }); mv.visitIntInsn(org.ow2.asmdex.Opcodes.INSN_MOVE_RESULT, valueRegister); mv.visitIntInsn(org.ow2.asmdex.Opcodes.INSN_RETURN, valueRegister); } else if (targetReturnType == Character.TYPE) { mv.visitTypeInsn(org.ow2.asmdex.Opcodes.INSN_CHECK_CAST, 0, valueRegister, 0, characterTypeDescriptor); //throw exception if can't cast this reference to the return type mv.visitMethodInsn(org.ow2.asmdex.Opcodes.INSN_INVOKE_VIRTUAL, characterTypeDescriptor, "charValue", "C", new int[] { valueRegister }); mv.visitIntInsn(org.ow2.asmdex.Opcodes.INSN_MOVE_RESULT, valueRegister); mv.visitIntInsn(org.ow2.asmdex.Opcodes.INSN_RETURN, valueRegister); } else if (targetReturnType == Short.TYPE) { mv.visitTypeInsn(org.ow2.asmdex.Opcodes.INSN_CHECK_CAST, 0, valueRegister, 0, shortTypeDescriptor); //throw exception if can't cast this reference to the return type mv.visitMethodInsn(org.ow2.asmdex.Opcodes.INSN_INVOKE_VIRTUAL, shortTypeDescriptor, "shortValue", "S", new int[] { valueRegister }); mv.visitIntInsn(org.ow2.asmdex.Opcodes.INSN_MOVE_RESULT, valueRegister); mv.visitIntInsn(org.ow2.asmdex.Opcodes.INSN_RETURN, valueRegister); } else if (targetReturnType == Float.TYPE) { mv.visitTypeInsn(org.ow2.asmdex.Opcodes.INSN_CHECK_CAST, 0, valueRegister, 0, floatTypeDescriptor); //throw exception if can't cast this reference to the return type mv.visitMethodInsn(org.ow2.asmdex.Opcodes.INSN_INVOKE_VIRTUAL, floatTypeDescriptor, "floatValue", "F", new int[] { valueRegister }); mv.visitIntInsn(org.ow2.asmdex.Opcodes.INSN_MOVE_RESULT, valueRegister); mv.visitIntInsn(org.ow2.asmdex.Opcodes.INSN_RETURN, valueRegister); } else if (targetReturnType == Double.TYPE) { mv.visitTypeInsn(org.ow2.asmdex.Opcodes.INSN_CHECK_CAST, 0, valueRegister, 0, doubleTypeDescriptor); //throw exception if can't cast this reference to the return type mv.visitMethodInsn(org.ow2.asmdex.Opcodes.INSN_INVOKE_VIRTUAL, doubleTypeDescriptor, "doubleValue", "D", new int[] { valueRegister }); mv.visitIntInsn(org.ow2.asmdex.Opcodes.INSN_MOVE_RESULT_WIDE, valueRegister); mv.visitIntInsn(org.ow2.asmdex.Opcodes.INSN_RETURN_WIDE, valueRegister); } else //if (d == Long.TYPE) { mv.visitTypeInsn(org.ow2.asmdex.Opcodes.INSN_CHECK_CAST, 0, valueRegister, 0, longTypeDescriptor); //throw exception if can't cast this reference to the return type mv.visitMethodInsn(org.ow2.asmdex.Opcodes.INSN_INVOKE_VIRTUAL, longTypeDescriptor, "longValue", "J", new int[] { valueRegister }); mv.visitIntInsn(org.ow2.asmdex.Opcodes.INSN_MOVE_RESULT_WIDE, valueRegister); mv.visitIntInsn(org.ow2.asmdex.Opcodes.INSN_RETURN_WIDE, valueRegister); } } else //return object { String returnTypeDescriptor = getAsmDescriptor(targetReturnType); mv.visitTypeInsn(org.ow2.asmdex.Opcodes.INSN_CHECK_CAST, 0, valueRegister, 0, returnTypeDescriptor); //throw exception if can't cast this reference to the return type mv.visitIntInsn(org.ow2.asmdex.Opcodes.INSN_RETURN_OBJECT, valueRegister); } } /** * Generate return instructions from targetReturnType. TargetReturnType * @param mv * @param targetReturnType * @param thisRegister * @param valueRegister */ private void generateReturn(MethodVisitor mv, Class<?> targetReturnType, int thisRegister, int valueRegister) { if (targetReturnType == Void.TYPE) { mv.visitInsn(org.ow2.asmdex.Opcodes.INSN_RETURN_VOID); } else if (targetReturnType.isPrimitive() && targetReturnType != Double.TYPE && targetReturnType != Long.TYPE) { mv.visitIntInsn(org.ow2.asmdex.Opcodes.INSN_MOVE_RESULT, valueRegister); //get the result of from the very last method call in register 1; mv.visitIntInsn(org.ow2.asmdex.Opcodes.INSN_RETURN, valueRegister); } else if (targetReturnType.isPrimitive() && (targetReturnType == Double.TYPE || targetReturnType == Long.TYPE)) { mv.visitIntInsn(org.ow2.asmdex.Opcodes.INSN_MOVE_RESULT_WIDE, valueRegister); //get the result of from the very last method call in register 1; mv.visitIntInsn(org.ow2.asmdex.Opcodes.INSN_RETURN_WIDE, valueRegister); } else //return object { mv.visitIntInsn(org.ow2.asmdex.Opcodes.INSN_MOVE_RESULT_OBJECT, valueRegister); //get the result of from the very last method call in register 1; String returnTypeDescriptor = getAsmDescriptor(targetReturnType); mv.visitTypeInsn(org.ow2.asmdex.Opcodes.INSN_CHECK_CAST, 0, valueRegister, 0, returnTypeDescriptor); //throw exception if can't cast this reference to the return type mv.visitIntInsn(org.ow2.asmdex.Opcodes.INSN_RETURN_OBJECT, valueRegister); } } private void generateFields(ClassVisitor cv) { generateInitializedField(cv); } private void generateInitializedField(ClassVisitor cv) { FieldVisitor fv = cv.visitField(org.ow2.asmdex.Opcodes.ACC_PRIVATE, "__initialized", "Z", null, null); fv.visitEnd(); } static final String[] classImplentedInterfaces = new String[] { "Lcom/tns/NativeScriptHashCodeProvider;" }; static final String[] interfaceImplementedInterfaces = new String[] { "Lcom/tns/NativeScriptHashCodeProvider;", "" }; private ClassVisitor generateClass(ApplicationWriter aw, Class<?> classTo, String classSignature, String tnsClassSignature) { ClassVisitor cv; int classModifiers = getDexModifiers(classTo.getModifiers()); String[] implentedInterfaces = classImplentedInterfaces; if (classTo.isInterface()) { interfaceImplementedInterfaces[1] = classSignature; //new String[] { "Lcom/tns/NativeScriptHashCodeProvider;", classSignature }; implentedInterfaces = interfaceImplementedInterfaces; classSignature = objectClass; } else { implentedInterfaces = classImplentedInterfaces; } cv = aw.visitClass(classModifiers, tnsClassSignature, null, classSignature, implentedInterfaces); cv.visit(0, classModifiers, tnsClassSignature, null, classSignature, implentedInterfaces); cv.visitSource(classTo.getName() + ".java", null); return cv; } private int getDexModifiers(int modifiers) { if (Modifier.isPublic(modifiers)) { return org.ow2.asmdex.Opcodes.ACC_PUBLIC; } return org.ow2.asmdex.Opcodes.ACC_PROTECTED; } }
package org.hyperic.sigar.jmx; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import javax.management.AttributeNotFoundException; import javax.management.MBeanAttributeInfo; import javax.management.MBeanConstructorInfo; import javax.management.MBeanInfo; import javax.management.MBeanParameterInfo; import javax.management.MBeanServer; import javax.management.ObjectInstance; import javax.management.ObjectName; import org.hyperic.sigar.FileSystem; import org.hyperic.sigar.Sigar; import org.hyperic.sigar.SigarException; import org.hyperic.sigar.SigarLoader; /** * <p>Registry of all Sigar MBeans. Can be used as a convenient way to invoke * Sigar MBeans at a central point. This brings a bunch of advantages with * it:</p> * * <ul> * <li>This class can be instantiated and registered to the MBean server by * simply calling {@link MBeanServer#createMBean(String, ObjectName)}, * resulting in the automatic creation of all known default Sigar MBeans such * as CPU and memory monitoring beans.</li> * <li>Any Sigar MBean spawned by an instance of this class will use the same * {@link org.hyperic.sigar.Sigar} instance, saving resources in the * process.</li> * <li>When this instance is deregistered from the MBean server, it will * automatically deregister all instances it created, cleaning up behind * itself.</li> * </ul> * * <p>So using this class to manage the Sigar MBeans requires one line of code * for creation, registration and MBean spawning, and one line of code to shut * it all down again.</p> * * @author Bjoern Martin * @since 1.5 */ public class SigarRegistry extends AbstractMBean { private static final String MBEAN_TYPE = "SigarRegistry"; private static final Map VERSION_ATTRS = new LinkedHashMap(); private static final MBeanInfo MBEAN_INFO; private static final MBeanConstructorInfo MBEAN_CONSTR_DEFAULT; // private static final MBeanOperationInfo MBEAN_OPER_LISTPROCESSES; static { MBEAN_CONSTR_DEFAULT = new MBeanConstructorInfo( SigarRegistry.class.getName(), "Creates a new instance of this class. Will create the Sigar " + "instance this class uses when constructing other MBeans", new MBeanParameterInfo[0]); // MBEAN_OPER_LISTPROCESSES = new MBeanOperationInfo("listProcesses", // "Executes a query returning the process IDs of all processes " + // "found on the system.", // null /* new MBeanParameterInfo[0] */, // String.class.getName(), MBeanOperationInfo.INFO); MBEAN_INFO = new MBeanInfo( SigarRegistry.class.getName(), "Sigar MBean registry. Provides a central point for creation " + "and destruction of Sigar MBeans. Any Sigar MBean created via " + "this instance will automatically be cleaned up when this " + "instance is deregistered from the MBean server.", getAttributeInfo(), new MBeanConstructorInfo[] { MBEAN_CONSTR_DEFAULT }, null /*new MBeanOperationInfo[0] */, null /*new MBeanNotificationInfo[0]*/); } private final String objectName; private final ArrayList managedBeans; private static MBeanAttributeInfo[] getAttributeInfo() { VERSION_ATTRS.put("JarVersion", Sigar.VERSION_STRING); VERSION_ATTRS.put("NativeVersion", Sigar.NATIVE_VERSION_STRING); VERSION_ATTRS.put("JarBuildDate", Sigar.BUILD_DATE); VERSION_ATTRS.put("NativeBuildDate", Sigar.NATIVE_BUILD_DATE); VERSION_ATTRS.put("JarSourceRevision", Sigar.SCM_REVISION); VERSION_ATTRS.put("NativeSourceRevision", Sigar.NATIVE_SCM_REVISION); VERSION_ATTRS.put("NativeLibraryName", SigarLoader.getNativeLibraryName()); MBeanAttributeInfo[] attrs = new MBeanAttributeInfo[VERSION_ATTRS.size()]; int i=0; for (Iterator it=VERSION_ATTRS.entrySet().iterator(); it.hasNext();) { Map.Entry entry = (Map.Entry)it.next(); String name = (String)entry.getKey(); attrs[i++] = new MBeanAttributeInfo(name, entry.getValue().getClass().getName(), name, true, // isReadable false, // isWritable false); // isIs } return attrs; } /** * Creates a new instance of this class. Will create the Sigar instance this * class uses when constructing other MBeans. */ public SigarRegistry() { super(new Sigar(), CACHELESS); this.objectName = SigarInvokerJMX.DOMAIN_NAME + ":" + MBEAN_ATTR_TYPE + "=" + MBEAN_TYPE; this.managedBeans = new ArrayList(); } /* (non-Javadoc) * @see AbstractMBean#getObjectName() */ public String getObjectName() { return this.objectName; } /* public String listProcesses() { try { final long start = System.currentTimeMillis(); long[] ids = sigar.getProcList(); StringBuffer procNames = new StringBuffer(); for (int i = 0; i < ids.length; i++) { try { procNames.append(ids[i] + ":" + sigar.getProcExe(ids[i]).getName()).append('\n'); } catch (SigarException e) { procNames.append(ids[i] + ":" + e.getMessage()).append('\n'); } } final long end = System.currentTimeMillis(); procNames.append("-- Took " + (end-start) + "ms"); return procNames.toString(); } catch (SigarException e) { throw unexpectedError("ProcList", e); } } */ /* (non-Javadoc) * @see javax.management.DynamicMBean#getAttribute(java.lang.String) */ public Object getAttribute(String attr) throws AttributeNotFoundException { Object obj = VERSION_ATTRS.get(attr); if (obj == null) { throw new AttributeNotFoundException(attr); } return obj; } /* (non-Javadoc) * @see javax.management.DynamicMBean#getMBeanInfo() */ public MBeanInfo getMBeanInfo() { return MBEAN_INFO; } private void registerMBean(AbstractMBean mbean) { try { ObjectName name = new ObjectName(mbean.getObjectName()); if (mbeanServer.isRegistered(name)) { return; } ObjectInstance instance = this.mbeanServer.registerMBean(mbean, name); this.managedBeans.add(instance.getObjectName()); } catch (Exception e) { e.printStackTrace(); } } // Implementation of the MBeanRegistration interface /** * Registers the default set of Sigar MBeans. Before doing so, a super call * is made to satisfy {@link AbstractMBean}. * * @see AbstractMBean#postRegister(Boolean) */ public void postRegister(Boolean success) { super.postRegister(success); if (!success.booleanValue()) return; //CPU beans try { final int cpuCount = sigar.getCpuInfoList().length; for (int i = 0; i < cpuCount; i++) { registerMBean(new SigarCpu(sigarImpl, i)); registerMBean(new SigarCpuPerc(sigarImpl, i)); registerMBean(new SigarCpuInfo(sigarImpl, i)); } } catch (SigarException e) { throw unexpectedError("CpuInfoList", e); } //FileSystem beans try { FileSystem[] fslist = sigarImpl.getFileSystemList(); for (int i=0; i<fslist.length; i++) { FileSystem fs = fslist[i]; if (fs.getType() != FileSystem.TYPE_LOCAL_DISK) { continue; } String name = fs.getDirName(); ReflectedMBean mbean = new ReflectedMBean(sigarImpl, "FileSystem", name); mbean.setType(mbean.getType() + "Usage"); mbean.putAttributes(fs); registerMBean(mbean); } } catch (SigarException e) { throw unexpectedError("FileSystemList", e); } //physical memory bean registerMBean(new ReflectedMBean(sigarImpl, "Mem")); //swap memory bean registerMBean(new ReflectedMBean(sigarImpl, "Swap")); //load average bean registerMBean(new SigarLoadAverage(sigarImpl)); } /** * Deregisters all Sigar MBeans that were created and registered using this * instance. After doing so, a super call is made to satisfy {@link AbstractMBean}. * @throws Exception * * @see AbstractMBean#preDeregister() */ public void preDeregister() throws Exception { // count backwards to remove ONs immediately for (int i = managedBeans.size() - 1; i >= 0; i ObjectName next = (ObjectName) managedBeans.remove(i); if (mbeanServer.isRegistered(next)) { try { mbeanServer.unregisterMBean(next); } catch (Exception e) { // ignore } } } // do the super call super.preDeregister(); } }
package dynamo.manager.games; import java.io.IOException; import java.net.MalformedURLException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import org.apache.commons.lang3.StringUtils; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.databind.JsonMappingException; import core.WebResource; import dynamo.backlog.BackLogProcessor; import dynamo.core.configuration.Configurable; import dynamo.core.configuration.Reconfigurable; import dynamo.core.manager.ConfigurationManager; import dynamo.core.manager.DAOManager; import dynamo.finders.core.GameFinder; import dynamo.manager.DownloadableManager; import dynamo.manager.LocalImageCache; import dynamo.model.DownloadableStatus; import dynamo.model.games.GamePlatform; import dynamo.model.games.VideoGame; import dynamo.model.games.VideoGameDAO; import dynamo.webapps.googleimages.GoogleImages; import dynamo.webapps.thegamesdb.net.GetArtResponse; import dynamo.webapps.thegamesdb.net.TheGamesDB; import dynamo.webapps.thegamesdb.net.TheGamesDBGame; import dynamo.webapps.thegamesdb.net.images.TheGamesDBBoxArt; public class GamesManager implements Reconfigurable { @Configurable(category="Games", name="Enable Games", bold=true) private boolean enabled; @Configurable(category="Games", name="Platforms", disabled="#{!GamesManager.enabled}", contentsClass=GamePlatform.class) private List<GamePlatform> platforms; @Configurable(category="Games", name="Game Providers", required="#{GamesManager.enabled}", disabled="#{!GamesManager.enabled}", contentsClass=GameFinder.class, ordered=true ) private List<GameFinder> providers; public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public List<GamePlatform> getPlatforms() { return platforms; } public void setPlatforms(List<GamePlatform> platforms) { this.platforms = platforms; } private VideoGameDAO videoGameDAO = DAOManager.getInstance().getDAO( VideoGameDAO.class ); private GamesManager() { } static class SingletonHolder { static GamesManager instance = new GamesManager(); } public static GamesManager getInstance() { return SingletonHolder.instance; } public List<GameFinder> getProviders() { return providers; } public void setProviders(List<GameFinder> providers) { this.providers = providers; } protected static String getFolderConfigKey( GamePlatform platform ) { return String.format( "%s.folder", platform.name() ); } public void setPlatformFolder( GamePlatform platform, Path folder ) throws JsonGenerationException, JsonMappingException, IOException { ConfigurationManager.getInstance().setConfigString( getFolderConfigKey(platform), folder.toAbsolutePath().toString() ); ConfigurationManager.getInstance().persistConfiguration(); } public Path getFolder(GamePlatform platform) { String pathValue = ConfigurationManager.getInstance().getConfigString( getFolderConfigKey(platform) ); return pathValue != null ? Paths.get( pathValue ) : null; } public List<VideoGame> getVideoGames() { return videoGameDAO.findAll(); } public List<VideoGame> getWantedAndSnatched() { return videoGameDAO.findWantedAndSnatched(); } public List<VideoGame> getGames( GamePlatform filterPlatform, DownloadableStatus status ) { if (filterPlatform == null) { return videoGameDAO.findAll( status ); } else { return videoGameDAO.findAll( status, filterPlatform ); } } public WebResource findImage( String gameName, GamePlatform platform ) { return GoogleImages.findImage( String.format("%s %s front cover", gameName, platform.name() ), platform.getCoverImageRatio()); } public void changeImage( VideoGame game ) throws MalformedURLException { String image = getLocalImage(game.getTheGamesDbId(), game.getName(), game.getPlatform() ); DownloadableManager.getInstance().updateCoverImage( game.getId(), image); } private String getLocalImage( long theGamesDbId, String title, GamePlatform platform ) { String imageId = String.format("%s-%s", title, platform.name()); GetArtResponse response = TheGamesDB.getInstance().getArt(theGamesDbId); List<TheGamesDBBoxArt> boxarts = response.getImages().getBoxarts(); String imageURL = null; String imageReferer = null; if (boxarts != null) { for (TheGamesDBBoxArt theGamesDBBoxArt : boxarts) { if (StringUtils.equals(theGamesDBBoxArt.getSide(), "front")) { imageURL = response.getBaseImgUrl() + theGamesDBBoxArt.getPath(); break; } } } if (imageURL == null) { WebResource resource = findImage( title, platform ); imageURL = resource.getUrl(); imageReferer = resource.getReferer(); } return LocalImageCache.getInstance().download("games", imageId, imageURL, imageReferer); } public VideoGame findByTheGamesDbId( long theGamesDbId ) { return videoGameDAO.findByTheGamesDbId(theGamesDbId); } public VideoGame createGame( String title, String platform, long theGamesDbId, Path folder, DownloadableStatus status ) { GamePlatform newGamePlatform = GamePlatform.match( platform ); String image = getLocalImage(theGamesDbId, title, newGamePlatform ); long videoGameId = DownloadableManager.getInstance().createDownloadable(VideoGame.class, folder, image, status ); VideoGame game = new VideoGame(videoGameId, status, folder, image, title, newGamePlatform, theGamesDbId ); videoGameDAO.save( videoGameId, title, game.getPlatform(), game.getTheGamesDbId() ); return game; } @Override public void reconfigure() { if (enabled) { if (platforms != null) { for (GamePlatform platform : platforms) { Path path = getFolder(platform); if (path != null) { BackLogProcessor.getInstance().schedule( new ScanGamesFolderTask(platform, path)); } } } } else { BackLogProcessor.getInstance().unschedule( ScanGamesFolderTask.class ); } } public void associate(long videoGameId, TheGamesDBGame game ) throws MalformedURLException { GamePlatform newGamePlatform = GamePlatform.match( game.getPlatform() ); String image = getLocalImage( game.getId(), game.getGameTitle(), newGamePlatform ); DownloadableManager.getInstance().updateCoverImage( videoGameId, image ); videoGameDAO.save( videoGameId, game.getGameTitle(), newGamePlatform, game.getId() ); } public void want(long theGamesDbId) { VideoGame game = GamesManager.getInstance().findByTheGamesDbId( theGamesDbId ); if (game == null) { TheGamesDBGame theGamesDbGame = TheGamesDB.getInstance().getGame( theGamesDbId ); if (theGamesDbGame != null) { game = GamesManager.getInstance().createGame( theGamesDbGame.getGameTitle(), theGamesDbGame.getPlatform(), theGamesDbId, null, DownloadableStatus.WANTED ); if (theGamesDbGame.getAlternateTitles() != null && theGamesDbGame.getAlternateTitles().size() > 0) { DownloadableManager.getInstance().setAkas(game.getId(), theGamesDbGame.getAlternateTitles()); } DownloadableManager.getInstance().scheduleFind( game ); } } else { if (game.getStatus() != DownloadableStatus.DOWNLOADED) { DownloadableManager.getInstance().want( game ); } } } }
package org.easybatch.core.impl; import org.easybatch.core.api.*; import org.easybatch.core.util.Utils; import java.util.List; import java.util.Set; import java.util.concurrent.Callable; import java.util.logging.Level; import java.util.logging.Logger; /** * Core Easy Batch engine implementation. * * @author Mahmoud Ben Hassine (mahmoud@benhassine.fr) */ public final class Engine implements Callable<Report> { private static final Logger LOGGER = Logger.getLogger(Engine.class.getName()); private static final String STRICT_MODE_MESSAGE = "Strict mode enabled: aborting execution"; private RecordReader recordReader; private List<RecordFilter> filterChain; private RecordMapper recordMapper; private RecordValidator recordValidator; private List<RecordProcessor> processingPipeline; private FilteredRecordHandler filteredRecordHandler; private IgnoredRecordHandler ignoredRecordHandler; private RejectedRecordHandler rejectedRecordHandler; private ErrorRecordHandler errorRecordHandler; private boolean strictMode; private EventManager eventManager; private Report report; Engine(final RecordReader recordReader, final List<RecordFilter> filterChain, final RecordMapper recordMapper, final RecordValidator recordValidator, final List<RecordProcessor> processingPipeline, final FilteredRecordHandler filteredRecordHandler, final IgnoredRecordHandler ignoredRecordHandler, final RejectedRecordHandler rejectedRecordHandler, final ErrorRecordHandler errorRecordHandler) { this.recordReader = recordReader; this.filterChain = filterChain; this.recordMapper = recordMapper; this.recordValidator = recordValidator; this.processingPipeline = processingPipeline; this.filteredRecordHandler = filteredRecordHandler; this.ignoredRecordHandler = ignoredRecordHandler; this.rejectedRecordHandler = rejectedRecordHandler; this.errorRecordHandler = errorRecordHandler; report = new Report(); } @Override public Report call() { eventManager.fireBeforeBatchStart(); LOGGER.info("Initializing easy batch engine"); try { openRecordReader(); } catch (Exception e) { LOGGER.log(Level.SEVERE, "An exception occurred during opening data source reader", e); eventManager.fireOnBatchException(e); report.setStatus(Status.ABORTED); report.setEndTime(System.currentTimeMillis()); return report; } String dataSourceName = recordReader.getDataSourceName(); LOGGER.log(Level.INFO, "Data source: {0}", dataSourceName); report.setDataSource(dataSourceName); LOGGER.log(Level.INFO, "Strict mode: {0}", strictMode); try { Integer totalRecords = recordReader.getTotalRecords(); LOGGER.log(Level.INFO, "Total records = {0}", (totalRecords == null ? "N/A" : totalRecords)); report.setStatus(Status.RUNNING); LOGGER.info("easy batch engine is running..."); report.setTotalRecords(totalRecords); report.setStartTime(System.currentTimeMillis()); //System.nanoTime() does not allow to have start time (see Javadoc) int currentRecordNumber; // the physical record number in the data source (can be different from logical record number as seen by the engine in a multi-threaded scenario) int processedRecordsNumber = 0; while (recordReader.hasNextRecord()) { //read next record Record currentRecord; try { currentRecord = readRecord(); if(currentRecord == null) { LOGGER.log(Level.SEVERE, "The record reader returned null for next record, next steps will be skipped."); report.setStatus(Status.ABORTED); report.setEndTime(System.currentTimeMillis()); return report; } } catch (Exception e) { eventManager.fireOnBatchException(e); eventManager.fireOnRecordReadException(e); LOGGER.log(Level.SEVERE, "An exception occurred during reading next data source record", e); report.setStatus(Status.ABORTED); report.setEndTime(System.currentTimeMillis()); return report; } processedRecordsNumber++; currentRecordNumber = currentRecord.getNumber(); report.setCurrentRecordNumber(currentRecordNumber); //apply filter chain on the record boolean filtered = filterRecord(currentRecord); if (filtered) { report.addFilteredRecord(currentRecordNumber); filteredRecordHandler.handle(currentRecord); continue; } //map record to domain object Object typedRecord; try { typedRecord = mapRecord(currentRecord); if(typedRecord == null) { report.addIgnoredRecord(currentRecordNumber); ignoredRecordHandler.handle(currentRecord); continue; } } catch (Exception e) { report.addIgnoredRecord(currentRecordNumber); ignoredRecordHandler.handle(currentRecord, e); eventManager.fireOnBatchException(e); if (strictMode) { LOGGER.info(STRICT_MODE_MESSAGE); report.setStatus(Status.ABORTED); break; } continue; } //validate record try { Set<ValidationError> validationsErrors = validateRecord(typedRecord); if (!validationsErrors.isEmpty()) { report.addRejectedRecord(currentRecordNumber); rejectedRecordHandler.handle(currentRecord, validationsErrors); continue; } } catch (Exception e) { LOGGER.log(Level.SEVERE, "An exception occurred while validating record #" + currentRecordNumber + " [" + currentRecord + "]", e); report.addRejectedRecord(currentRecordNumber); rejectedRecordHandler.handle(currentRecord, e); eventManager.fireOnBatchException(e); if (strictMode) { LOGGER.info(STRICT_MODE_MESSAGE); report.setStatus(Status.ABORTED); break; } continue; } //execute record processing pipeline boolean processingError = false; for (RecordProcessor recordProcessor : processingPipeline) { try { typedRecord = processRecord(recordProcessor, typedRecord); } catch (Exception e) { processingError = true; report.addErrorRecord(currentRecordNumber); errorRecordHandler.handle(currentRecord, e); eventManager.fireOnBatchException(e); eventManager.fireOnRecordProcessingException(typedRecord, e); break; } } if (processingError) { if (strictMode) { LOGGER.info(STRICT_MODE_MESSAGE); report.setStatus(Status.ABORTED); break; } } else { report.addSuccessRecord(currentRecordNumber); } } report.setTotalRecords(processedRecordsNumber); report.setEndTime(System.currentTimeMillis()); if (!report.getStatus().equals(Status.ABORTED)) { report.setStatus(Status.FINISHED); } // The batch result (if any) is held by the last processor in the pipeline (which should be of type ComputationalRecordProcessor) RecordProcessor lastRecordProcessor = processingPipeline.get(processingPipeline.size() - 1); if (lastRecordProcessor instanceof ComputationalRecordProcessor) { ComputationalRecordProcessor computationalRecordProcessor = (ComputationalRecordProcessor) lastRecordProcessor; Object batchResult = computationalRecordProcessor.getComputationResult(); report.setBatchResult(batchResult); } } finally { LOGGER.info("Shutting down easy batch engine"); //close the record reader try { closeRecordReader(); } catch (Exception e) { //at this point, there is no need to log a severe message and return null as batch report LOGGER.log(Level.WARNING, "An exception occurred during closing data source reader", e); eventManager.fireOnBatchException(e); } } eventManager.fireAfterBatchEnd(); return report; } private void closeRecordReader() throws Exception { eventManager.fireBeforeRecordReaderClose(); recordReader.close(); eventManager.fireAfterRecordReaderClose(); } private void openRecordReader() throws Exception { eventManager.fireBeforeReaderOpen(); recordReader.open(); eventManager.fireAfterReaderOpen(); } @SuppressWarnings({"unchecked"}) private Object processRecord(RecordProcessor recordProcessor, Object typedRecord) throws Exception { eventManager.fireBeforeProcessingRecord(typedRecord); Object processedRecord = recordProcessor.processRecord(typedRecord); Object processingResult = null; if (recordProcessor instanceof ComputationalRecordProcessor) { processingResult = ((ComputationalRecordProcessor) recordProcessor).getComputationResult(); } eventManager.fireAfterProcessingRecord(processedRecord, processingResult); return processedRecord; } @SuppressWarnings({"unchecked"}) private Set<ValidationError> validateRecord(Object typedRecord) { eventManager.fireBeforeValidateRecord(typedRecord); Set<ValidationError> validationsErrors = recordValidator.validateRecord(typedRecord); eventManager.fireAfterValidateRecord(typedRecord, validationsErrors); return validationsErrors; } private Object mapRecord(Record currentRecord) throws Exception { Object typedRecord; eventManager.fireBeforeMapRecord(currentRecord); typedRecord = recordMapper.mapRecord(currentRecord); eventManager.fireAfterMapRecord(currentRecord, typedRecord); return typedRecord; } private boolean filterRecord(Record currentRecord) { eventManager.fireBeforeFilterRecord(currentRecord); boolean filtered = false; for (RecordFilter recordFilter : filterChain) { if (recordFilter.filterRecord(currentRecord)) { filtered = true; break; } } eventManager.fireAfterFilterRecord(currentRecord, filtered); return filtered; } private Record readRecord() throws Exception { eventManager.fireBeforeRecordRead(); Record currentRecord = recordReader.readNextRecord(); eventManager.fireAfterRecordRead(currentRecord); return currentRecord; } /* * Setters for engine parameters */ void addRecordFilter(final RecordFilter recordFilter) { this.filterChain.add(recordFilter); } void setRecordReader(final RecordReader recordReader) { this.recordReader = recordReader; } void setRecordMapper(final RecordMapper recordMapper) { this.recordMapper = recordMapper; } void setRecordValidator(final RecordValidator recordValidator) { this.recordValidator = recordValidator; } void addRecordProcessor(final RecordProcessor recordProcessor) { this.processingPipeline.add(recordProcessor); } void setFilteredRecordHandler(final FilteredRecordHandler filteredRecordHandler) { this.filteredRecordHandler = filteredRecordHandler; } void setIgnoredRecordHandler(final IgnoredRecordHandler ignoredRecordHandler) { this.ignoredRecordHandler = ignoredRecordHandler; } void setRejectedRecordHandler(final RejectedRecordHandler rejectedRecordHandler) { this.rejectedRecordHandler = rejectedRecordHandler; } void setErrorRecordHandler(final ErrorRecordHandler errorRecordHandler) { this.errorRecordHandler = errorRecordHandler; } void setEventManager(EventManager eventManager) { this.eventManager = eventManager; } EventManager getEventManager() { return eventManager; } void setStrictMode(final boolean strictMode) { this.strictMode = strictMode; } void setSilentMode(boolean silentMode) { if (silentMode) { Utils.muteLoggers(); } } public void enableJMX(boolean jmx) { if (jmx) { Utils.registerJmxMBean(report); } } }
package com.aware.ui; import android.app.Activity; import android.app.DownloadManager; import android.app.DownloadManager.Query; import android.app.IntentService; import android.content.ActivityNotFoundException; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.CompoundButton; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import android.widget.ToggleButton; import com.aware.Aware; import com.aware.R; import com.aware.providers.Aware_Provider.Aware_Plugins; import com.aware.utils.Aware_Plugin; import com.aware.utils.Http; import org.apache.http.HttpResponse; import org.apache.http.ParseException; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.IOException; import java.util.ArrayList; /** * UI to manage installed plugins. * @author denzil * */ public class Plugins_Manager extends Activity { private static final String TAG = "AWARE::Plugin Manager"; /** * Received broadcast: ACTION_AWARE_ACTIVATE_PLUGIN<br/> * Extra: package_name (String) of the plugin to activate <br/> * This will request the framework to activate a plugin for use in another application/plugin */ public static final String ACTION_AWARE_ACTIVATE_PLUGIN = "ACTION_AWARE_ACTIVATE_PLUGIN"; /** * Received broadcast: ACTION_AWARE_DEACTIVATE_PLUGIN<br/> * Extra: package_name (String) of the plugin to activate <br/> * This will request the framework to deactivate a plugin for use in another application/plugin */ public static final String ACTION_AWARE_DEACTIVATE_PLUGIN = "ACTION_AWARE_DEACTIVATE_PLUGIN"; /** * Extra (String) for plugin package name */ public static final String EXTRA_PACKAGE_NAME = "package_name"; private static LayoutInflater mInflater = null; private static PackageManager mPkgManager = null; private static LinearLayout mPlugins_list = null; private static ProgressBar mLoader = null; private static ArrayList<Long> AWARE_PLUGIN_DOWNLOAD_IDS = new ArrayList<Long>(); private static JSONArray online_packages = new JSONArray(); private class PollPackages extends AsyncTask<Void, Void, Void> { @Override protected void onPreExecute() { super.onPreExecute(); mLoader.setVisibility(View.VISIBLE); } @Override protected Void doInBackground(Void... params) { Http fetch = new Http(); HttpResponse response = fetch.dataGET("http://dl.dropboxusercontent.com/u/758290/Contextopheles/getAddons.html"); if( response != null && response.getStatusLine().getStatusCode() == 200 ) { try { String data = EntityUtils.toString(response.getEntity()); online_packages = new JSONArray(data); } catch (ParseException e) { if( Aware.DEBUG ) Log.d( Aware.TAG, e.getMessage() ); } catch (IOException e) { if( Aware.DEBUG ) Log.d( Aware.TAG, e.getMessage() ); } catch (JSONException e) { if( Aware.DEBUG ) Log.d( Aware.TAG, e.getMessage() ); } } else { if( Aware.DEBUG ) Log.d(Aware.TAG, "Unable to fetch packages from online repository..."); } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); update_UI(); mLoader.setVisibility(View.GONE); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.plugins_manager); mInflater = getLayoutInflater(); mPkgManager = getPackageManager(); mPlugins_list = (LinearLayout) findViewById(R.id.plugin_list); mLoader = (ProgressBar) findViewById(R.id.loading_addons); mLoader.setIndeterminate(true); new PollPackages().execute(); } /** * Detect if the package was updated from the server * @param package_name * @param version * @return */ private boolean updated_package( String package_name, int version ) { for( int i=0; i< online_packages.length(); i++ ){ try { JSONObject pkg = online_packages.getJSONObject(i); if( pkg.getString("package").equals(package_name) ) { if ( pkg.getInt("version") > version ) { return true; } else { return false; } } } catch (JSONException e) { if( Aware.DEBUG) Log.d(Aware.TAG, e.getMessage()); } } return false; } /** * Detect if the package doesn't exist online * @param package_name * @return */ private boolean is_online( String package_name ) { for( int i=0; i< online_packages.length(); i++ ){ try { JSONObject pkg = online_packages.getJSONObject(i); if( pkg.getString("package").equals(package_name) ) { return true; } } catch (JSONException e) { if( Aware.DEBUG) Log.d(Aware.TAG, e.getMessage()); } } return false; } /** * Check if plugin has settings UI * @param package_name * @return */ private boolean hasSettings( String package_name ) { boolean settings = false; try { PackageInfo pkgInfo = getPackageManager().getPackageInfo(package_name, PackageManager.GET_ACTIVITIES); ActivityInfo[] activities = pkgInfo.activities; if( activities != null ) { for(ActivityInfo info : activities ) { if( info.name.contains("Settings") ) { settings = true; break; } } } } catch (NameNotFoundException e) { if( Aware.DEBUG ) Log.d( Aware.TAG, e.getMessage()); } return settings; } private static void get_online_package( Context context, String package_name, String name ) { //Create the folder where all the databases will be stored on external storage File folders = new File(Environment.getExternalStorageDirectory()+"/AWARE/plugins/"); folders.mkdirs(); String url = "http://dl.dropboxusercontent.com/u/758290/Contextopheles/APKs/" + package_name + ".apk"; DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)); if( name.length() > 0 ) { request.setDescription("Downloading " + name ); }else request.setDescription("Downloading " + package_name ); request.setTitle("AWARE add-on"); request.setDestinationInExternalPublicDir("/", "AWARE/plugins/" + package_name + ".apk"); DownloadManager manager = (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE); AWARE_PLUGIN_DOWNLOAD_IDS.add(manager.enqueue(request)); } /** * Updates the UI */ private void update_UI() { mPlugins_list.removeAllViews(); for(int i=0; i<online_packages.length(); i++ ) { final View row = mInflater.inflate(R.layout.plugin_row, null); final TextView name = (TextView) row.findViewById(R.id.plugin_name); final TextView version = (TextView) row.findViewById(R.id.plugin_version); final TextView author = (TextView) row.findViewById(R.id.plugin_author); final ToggleButton toggle = (ToggleButton) row.findViewById(R.id.plugin_toggle); final ImageButton settings = (ImageButton) row.findViewById(R.id.plugin_settings); final ImageButton update_download = (ImageButton) row.findViewById(R.id.plugin_update_download); try { JSONObject online_pkg = online_packages.getJSONObject(i); final String pkg_name = online_pkg.getString("name"); final String pkg_package = online_pkg.getString("package"); final String pkg_author = online_pkg.getString("author"); final int pkg_version = online_pkg.getInt("version"); //FIXED: clean-up of packages that are no longer installed if( ! isPackageInstalled(pkg_package) ) { getContentResolver().delete(Aware_Plugins.CONTENT_URI, Aware_Plugins.PLUGIN_PACKAGE_NAME + "='"+pkg_package+"'", null); } Cursor local_pkg = getContentResolver().query(Aware_Plugins.CONTENT_URI, null, Aware_Plugins.PLUGIN_PACKAGE_NAME + "='" + pkg_package + "'", null, null); if( local_pkg == null || ! local_pkg.moveToFirst() ) { //we don't have it, so add it as a possible to download option name.setText(pkg_name); author.setText("Author: " + pkg_author); version.setText("Version: "+ pkg_version); toggle.setVisibility(ToggleButton.GONE); settings.setVisibility(View.INVISIBLE); update_download.setVisibility(View.VISIBLE); update_download.setImageResource(R.drawable.ic_action_download); update_download.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d(Aware.TAG, "Try to download package..."); get_online_package(getApplicationContext(), pkg_package, pkg_name); } }); } else if( local_pkg != null && local_pkg.moveToFirst() ) { name.setText(pkg_name); int local_version = local_pkg.getInt(local_pkg.getColumnIndex(Aware_Plugins.PLUGIN_VERSION)); if( updated_package( pkg_package, local_version ) ) { //online is more recent author.setText("Author: " + pkg_author); version.setText("Updated: "+ pkg_version); update_download.setImageResource(R.drawable.ic_action_update); update_download.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d(Aware.TAG, "Try to update package..."); get_online_package(getApplicationContext(), pkg_package, pkg_name); } }); } if( local_version > pkg_version ) { //local is more recent author.setText("Author: You"); version.setText("Build: " + local_version); update_download.setVisibility(View.GONE); } else { //same version local and online. Use online information because has authorship author.setText("Author: " + pkg_author); version.setText("Version: "+ pkg_version); update_download.setVisibility(View.GONE); } int pluginStatus = local_pkg.getInt(local_pkg.getColumnIndex(Aware_Plugins.PLUGIN_STATUS)); switch(pluginStatus) { case Aware_Plugin.STATUS_PLUGIN_OFF: toggle.setChecked(false); break; case Aware_Plugin.STATUS_PLUGIN_ON: toggle.setChecked(true); Intent launch = new Intent(); launch.setClassName(pkg_package, pkg_package+".Plugin"); startService(launch); if( Aware.DEBUG ) Log.d(TAG,pkg_name + " started..."); break; } toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if( isChecked ) { Intent launch = new Intent(); launch.setClassName(pkg_package, pkg_package+".Plugin"); startService(launch); if( Aware.DEBUG ) Log.d(TAG,pkg_name + " started..."); ContentValues rowData = new ContentValues(); rowData.put(Aware_Plugins.PLUGIN_STATUS, Aware_Plugin.STATUS_PLUGIN_ON); getContentResolver().update(Aware_Plugins.CONTENT_URI, rowData, Aware_Plugins.PLUGIN_PACKAGE_NAME + "=?", new String[]{ pkg_package }); } else { Intent terminate = new Intent(); terminate.setClassName(pkg_package, pkg_package+".Plugin"); stopService(terminate); if( Aware.DEBUG ) Log.d(TAG,pkg_package + " terminated..."); ContentValues rowData = new ContentValues(); rowData.put(Aware_Plugins.PLUGIN_STATUS, Aware_Plugin.STATUS_PLUGIN_OFF); getContentResolver().update(Aware_Plugins.CONTENT_URI, rowData, Aware_Plugins.PLUGIN_PACKAGE_NAME + "=?", new String[]{ pkg_package }); } } }); if( ! hasSettings( pkg_package ) ) { settings.setVisibility(View.INVISIBLE); } else { settings.setVisibility(ImageButton.VISIBLE); settings.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent settings = new Intent("android.intent.action.MAIN"); settings.setComponent(new ComponentName(pkg_package, pkg_package+".Settings")); try { startActivity(settings); } catch (ActivityNotFoundException e) { Toast.makeText(getApplicationContext(), "Plugin without settings!", Toast.LENGTH_SHORT).show(); } } }); } } mPlugins_list.addView(row); if( local_pkg != null && ! local_pkg.isClosed() ) local_pkg.close(); } catch (JSONException e) { if( Aware.DEBUG) Log.d(Aware.TAG, e.getMessage()); } } //Check local only deployments Cursor plugins = getContentResolver().query(Aware_Plugins.CONTENT_URI, null, null, null, null); if( plugins != null && plugins.moveToFirst() ) { do { String pkg_package = plugins.getString(plugins.getColumnIndex(Aware_Plugins.PLUGIN_PACKAGE_NAME )); if( ! is_online( pkg_package) ) { //FIXED: clean-up of packages that are no longer installed if( ! isPackageInstalled( pkg_package ) ) { getContentResolver().delete(Aware_Plugins.CONTENT_URI, Aware_Plugins.PLUGIN_PACKAGE_NAME + "='"+pkg_package+"'", null); continue; } final View row = mInflater.inflate(R.layout.plugin_row, null); final TextView name = (TextView) row.findViewById(R.id.plugin_name); final TextView version = (TextView) row.findViewById(R.id.plugin_version); final TextView author = (TextView) row.findViewById(R.id.plugin_author); final ToggleButton toggle = (ToggleButton) row.findViewById(R.id.plugin_toggle); final ImageButton settings = (ImageButton) row.findViewById(R.id.plugin_settings); final ImageButton update_download = (ImageButton) row.findViewById(R.id.plugin_update_download); final String pluginPackage = plugins.getString(plugins.getColumnIndex(Aware_Plugins.PLUGIN_PACKAGE_NAME)); final String pluginName = plugins.getString(plugins.getColumnIndex(Aware_Plugins.PLUGIN_NAME)); final int pluginStatus = plugins.getInt(plugins.getColumnIndex(Aware_Plugins.PLUGIN_STATUS)); final int pluginVersion = plugins.getInt(plugins.getColumnIndex(Aware_Plugins.PLUGIN_VERSION)); name.setText(pluginName); author.setText("Author: You"); version.setText("Build: "+ pluginVersion); update_download.setVisibility(View.GONE); if( ! hasSettings(pluginPackage) ) { settings.setVisibility(View.INVISIBLE); } else { settings.setVisibility(View.VISIBLE); } switch(pluginStatus) { case Aware_Plugin.STATUS_PLUGIN_OFF: toggle.setChecked(false); break; case Aware_Plugin.STATUS_PLUGIN_ON: toggle.setChecked(true); Intent launch = new Intent(); launch.setClassName(pluginPackage, pluginPackage+".Plugin"); startService(launch); if( Aware.DEBUG ) Log.d(TAG,pluginName + " started..."); break; } toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if( isChecked ) { Intent launch = new Intent(); launch.setClassName(pluginPackage, pluginPackage+".Plugin"); startService(launch); if( Aware.DEBUG ) Log.d(TAG,pluginName + " started..."); ContentValues rowData = new ContentValues(); rowData.put(Aware_Plugins.PLUGIN_STATUS, Aware_Plugin.STATUS_PLUGIN_ON); getContentResolver().update(Aware_Plugins.CONTENT_URI, rowData, Aware_Plugins.PLUGIN_PACKAGE_NAME + "=?", new String[]{ pluginPackage }); } else { Intent terminate = new Intent(); terminate.setClassName(pluginPackage, pluginPackage+".Plugin"); stopService(terminate); if( Aware.DEBUG ) Log.d(TAG,pluginName + " terminated..."); ContentValues rowData = new ContentValues(); rowData.put(Aware_Plugins.PLUGIN_STATUS, Aware_Plugin.STATUS_PLUGIN_OFF); getContentResolver().update(Aware_Plugins.CONTENT_URI, rowData, Aware_Plugins.PLUGIN_PACKAGE_NAME + "=?", new String[]{ pluginPackage }); } } }); settings.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent settings = new Intent("android.intent.action.MAIN"); settings.setComponent(new ComponentName(pluginPackage, pluginPackage+".Settings")); try { startActivity(settings); } catch (ActivityNotFoundException e) { Toast.makeText(getApplicationContext(), "Plugin without settings!", Toast.LENGTH_SHORT).show(); } } }); mPlugins_list.addView(row); } }while(plugins.moveToNext()); } if( plugins!= null && ! plugins.isClosed() ) plugins.close(); } @Override protected void onResume() { super.onResume(); new PollPackages().execute(); } @Override protected void onStart() { super.onStart(); new PollPackages().execute(); } private static int getVersion( String package_name ) { try { PackageInfo pkgInfo = mPkgManager.getPackageInfo(package_name, PackageManager.GET_META_DATA); return pkgInfo.versionCode; } catch (NameNotFoundException e) { if( Aware.DEBUG ) Log.d( Aware.TAG, e.getMessage()); } return 0; } private static boolean isPackageInstalled( String mPackageName ) { try{ mPkgManager.getPackageInfo(mPackageName, PackageManager.GET_META_DATA); } catch (NameNotFoundException e) { return false; } return true; } /** * Downloads missing plugins on the background for the user * @author denzil * */ public static class Plugin_Downloader extends IntentService { public Plugin_Downloader() { super("Plugin Downloader"); } @Override protected void onHandleIntent(Intent intent) { if( intent.getStringExtra("MISSING_PLUGIN") != null ) { String missing_package = intent.getStringExtra("MISSING_PLUGIN"); get_online_package(getApplicationContext(), missing_package, ""); } } } /** * BroadcastReceiver that will monitor requests to activate plugins from other applications/plugins using the framework * ACTION_AWARE_ACTIVATE_PLUGIN <br/> * -- EXTRA_PACKAGE_NAME (string) of the plugin to activate if exists.<br/> * ACTION_AWARE_DEACTIVATE_PLUGIN <br/> * -- EXTRA_PACKAGE_NAME (string) of the plugin to deactivate if exists.<br/> * @author denzil * */ public static class Plugin_Controller extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if( intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE) ) { DownloadManager manager = (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE); long download_id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0); for( int i = 0; i < AWARE_PLUGIN_DOWNLOAD_IDS.size(); i++ ) { long queue = AWARE_PLUGIN_DOWNLOAD_IDS.get(i); if( download_id == queue ) { if( Aware.DEBUG ) Log.d(Aware.TAG, "AWARE plugin received..."); Cursor cur = manager.query(new Query().setFilterById(queue)); if( cur != null && cur.moveToFirst() ) { if( cur.getInt(cur.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL ) { String filePath = cur.getString(cur.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)); if( Aware.DEBUG ) Log.d(Aware.TAG, "Plugin to install:" + filePath); File mFile = new File( Uri.parse(filePath).getPath() ); Intent promptInstall = new Intent(Intent.ACTION_VIEW); promptInstall.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); promptInstall.setDataAndType(Uri.fromFile(mFile), "application/vnd.android.package-archive"); context.startActivity(promptInstall); } } if( cur != null && ! cur.isClosed() ) cur.close(); } } AWARE_PLUGIN_DOWNLOAD_IDS.remove(download_id); //dequeue } if( intent.getAction().equals(ACTION_AWARE_ACTIVATE_PLUGIN) ) { String extra_package = intent.getStringExtra(EXTRA_PACKAGE_NAME); if( extra_package != null ) { Cursor installed = context.getContentResolver().query(Aware_Plugins.CONTENT_URI, null, Aware_Plugins.PLUGIN_PACKAGE_NAME + "='"+extra_package+"'", null, null); if( installed != null && installed.moveToFirst() ) { String package_name = installed.getString(installed.getColumnIndex(Aware_Plugins.PLUGIN_PACKAGE_NAME)); String plugin_name = installed.getString(installed.getColumnIndex(Aware_Plugins.PLUGIN_NAME)); Intent launch = new Intent(); launch.setClassName(package_name, package_name + ".Plugin"); context.startService(launch); if( Aware.DEBUG ) Log.d(TAG, plugin_name + " started..."); ContentValues rowData = new ContentValues(); rowData.put(Aware_Plugins.PLUGIN_STATUS, Aware_Plugin.STATUS_PLUGIN_ON); context.getContentResolver().update(Aware_Plugins.CONTENT_URI, rowData, Aware_Plugins.PLUGIN_PACKAGE_NAME + "='"+package_name+"'", null); } else { if(Aware.DEBUG) Log.w(TAG, extra_package + " is not installed in this device!"); Intent pluginDownloader = new Intent(context, Plugin_Downloader.class); pluginDownloader.putExtra("MISSING_PLUGIN", extra_package); context.startService(pluginDownloader); } if( installed != null && ! installed.isClosed() ) installed.close(); } else { if(Aware.DEBUG) Log.w(TAG,"Forgot to set package_name EXTRA on the broadcast"); } } if( intent.getAction().equals(ACTION_AWARE_DEACTIVATE_PLUGIN) ) { String extra_package = intent.getStringExtra(EXTRA_PACKAGE_NAME); if( extra_package != null ) { Cursor installed = context.getContentResolver().query(Aware_Plugins.CONTENT_URI, null, Aware_Plugins.PLUGIN_PACKAGE_NAME + "='"+extra_package+"'", null, null); if( installed != null && installed.moveToFirst() ) { String package_name = installed.getString(installed.getColumnIndex(Aware_Plugins.PLUGIN_PACKAGE_NAME)); String plugin_name = installed.getString(installed.getColumnIndex(Aware_Plugins.PLUGIN_NAME)); Intent terminate = new Intent(); terminate.setClassName(package_name, package_name+".Plugin"); context.stopService(terminate); if( Aware.DEBUG ) Log.d(TAG, plugin_name + " terminated..."); ContentValues rowData = new ContentValues(); rowData.put(Aware_Plugins.PLUGIN_STATUS, Aware_Plugin.STATUS_PLUGIN_OFF); context.getContentResolver().update(Aware_Plugins.CONTENT_URI, rowData, Aware_Plugins.PLUGIN_PACKAGE_NAME + "='"+package_name+"'", null); } if( installed != null && ! installed.isClosed() ) installed.close(); } else { if(Aware.DEBUG) Log.w(TAG,"Forgot to set package_name EXTRA on the broadcast"); } } } } /** * System triggered<br/> * - ACTION_PACKAGE_ADDED: new package is installed on the device<br/> * - ACTION_PACKAGE_REMOVED: new package is removed from the device<br/> * @author denzil * */ public static class PluginMonitor extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if( mPkgManager == null ) mPkgManager = context.getPackageManager(); Bundle extras = intent.getExtras(); Uri packageUri = intent.getData(); if( packageUri == null ) return; String packageName = packageUri.getSchemeSpecificPart(); if( packageName == null ) return; if( ! packageName.matches("com.aware.plugin.*") ) return; if( intent.getAction().equals(Intent.ACTION_PACKAGE_ADDED) ) { if( extras.getBoolean(Intent.EXTRA_REPLACING) ) { if(Aware.DEBUG) Log.d(TAG,packageName + " is updating!"); ContentValues rowData = new ContentValues(); rowData.put(Aware_Plugins.PLUGIN_VERSION, getVersion(packageName)); context.getContentResolver().update(Aware_Plugins.CONTENT_URI, rowData, Aware_Plugins.PLUGIN_PACKAGE_NAME + "='" + packageName+"'", null); Cursor current_status = context.getContentResolver().query(Aware_Plugins.CONTENT_URI, new String[]{Aware_Plugins.PLUGIN_STATUS}, Aware_Plugins.PLUGIN_PACKAGE_NAME + "='"+packageName+"'", null, null); if( current_status != null && current_status.moveToFirst() ) { if( current_status.getInt(current_status.getColumnIndex(Aware_Plugins.PLUGIN_STATUS)) == Aware_Plugin.STATUS_PLUGIN_ON ) { Intent aware = new Intent(Aware.ACTION_AWARE_REFRESH); context.sendBroadcast(aware); //Show plugin manager UI Intent plugin_manager = new Intent(context, Plugins_Manager.class); plugin_manager.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(plugin_manager); } } if( current_status != null && ! current_status.isClosed() ) current_status.close(); return; } ApplicationInfo appInfo = null; try { appInfo = mPkgManager.getApplicationInfo(packageName, PackageManager.GET_ACTIVITIES); } catch( final NameNotFoundException e ) { appInfo = null; } String appName = ( appInfo != null ) ? (String) mPkgManager.getApplicationLabel(appInfo):""; ContentValues rowData = new ContentValues(); rowData.put(Aware_Plugins.PLUGIN_PACKAGE_NAME, appInfo.packageName); rowData.put(Aware_Plugins.PLUGIN_NAME, appName); rowData.put(Aware_Plugins.PLUGIN_VERSION, getVersion(packageName)); rowData.put(Aware_Plugins.PLUGIN_STATUS, Aware_Plugin.STATUS_PLUGIN_ON); context.getContentResolver().insert(Aware_Plugins.CONTENT_URI, rowData); if( Aware.DEBUG ) Log.d(TAG,"AWARE plugin added and activated:" + appInfo.packageName); Intent aware = new Intent(Aware.ACTION_AWARE_REFRESH); context.sendBroadcast(aware); //Show plugin manager UI Intent plugin_manager = new Intent(context, Plugins_Manager.class); plugin_manager.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(plugin_manager); } if( intent.getAction().equals(Intent.ACTION_PACKAGE_REMOVED) ) { if( extras.getBoolean(Intent.EXTRA_REPLACING) ) { if(Aware.DEBUG) Log.d(TAG,packageName + " is updating!"); return; } context.getContentResolver().delete(Aware_Plugins.CONTENT_URI, Aware_Plugins.PLUGIN_PACKAGE_NAME + "='" + packageName + "'", null); if( Aware.DEBUG ) Log.d(TAG,"AWARE plugin removed:" + packageName); } } } }
package com.datatorrent.stram.client; import com.datatorrent.stram.client.StramAppLauncher.AppFactory; import com.datatorrent.stram.plan.logical.LogicalPlan; import java.io.*; import java.util.*; import java.util.jar.*; import net.lingala.zip4j.core.ZipFile; import net.lingala.zip4j.exception.ZipException; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.apache.hadoop.conf.Configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author David Yan <david@datatorrent.com> */ public class AppBundle extends JarFile implements Closeable { public static final String ATTRIBUTE_DT_ENGINE_VERSION = "DT-Engine-Version"; public static final String ATTRIBUTE_DT_APP_BUNDLE_NAME = "DT-App-Bundle-Name"; public static final String ATTRIBUTE_DT_APP_BUNDLE_VERSION = "DT-App-Bundle-Version"; public static final String ATTRIBUTE_CLASS_PATH = "Class-Path"; private final String appBundleName; private final String appBundleVersion; private final String dtEngineVersion; private final ArrayList<String> classPath = new ArrayList<String>(); private final String directory; private final List<AppInfo> applications = new ArrayList<AppInfo>(); private final List<String> appJars = new ArrayList<String>(); private final List<String> appPropertiesFiles = new ArrayList<String>(); private final Set<String> requiredProperties = new TreeSet<String>(); private final Map<String, String> defaultProperties = new TreeMap<String, String>(); private final Set<String> configs = new TreeSet<String>(); public static class AppInfo { public final String name; public final String jarName; public final LogicalPlan dag; public AppInfo(String name, String jarName, LogicalPlan dag) { this.name = name; this.jarName = jarName; this.dag = dag; } } public AppBundle(File file) throws IOException, ZipException { this(file, false); } /** * Creates an App Bundle object. * * If app directory is to be processed, there may be resource leak in the class loader. Only pass true for short-lived applications * * @param file * @param processAppDirectory * @throws java.io.IOException * @throws net.lingala.zip4j.exception.ZipException */ public AppBundle(File file, boolean processAppDirectory) throws IOException, ZipException { super(file); Manifest manifest = getManifest(); if (manifest == null) { throw new IOException("Not a valid app bundle. MANIFEST.MF is not present."); } Attributes attr = manifest.getMainAttributes(); appBundleName = attr.getValue(ATTRIBUTE_DT_APP_BUNDLE_NAME); appBundleVersion = attr.getValue(ATTRIBUTE_DT_APP_BUNDLE_VERSION); dtEngineVersion = attr.getValue(ATTRIBUTE_DT_ENGINE_VERSION); String classPathString = attr.getValue(ATTRIBUTE_CLASS_PATH); if (classPathString == null) { throw new IOException("Not a valid app bundle. Class-Path is missing from MANIFEST.MF"); } classPath.addAll(Arrays.asList(StringUtils.split(classPathString, " "))); ZipFile zipFile = new ZipFile(file); if (zipFile.isEncrypted()) { throw new ZipException("Encrypted app bundle not supported yet"); } File newDirectory = new File("/tmp/dt-appBundle/" + System.currentTimeMillis()); newDirectory.mkdirs(); directory = newDirectory.getAbsolutePath(); zipFile.extractAll(directory); if (processAppDirectory) { processAppDirectory(new File(newDirectory, "app")); } processConfDirectory(new File(newDirectory, "conf")); File propertiesXml = new File(newDirectory, "META-INF/properties.xml"); if (propertiesXml.exists()) { processPropertiesXml(propertiesXml); } } public String tempDirectory() { return directory; } @Override public void close() throws IOException { super.close(); FileUtils.deleteDirectory(new File(directory)); } public String getAppBundleName() { return appBundleName; } public String getAppBundleVersion() { return appBundleVersion; } public String getDtEngineVersion() { return dtEngineVersion; } public List<String> getClassPath() { return Collections.unmodifiableList(classPath); } public Collection<String> getConfigs() { return Collections.unmodifiableCollection(configs); } public List<AppInfo> getApplications() { return Collections.unmodifiableList(applications); } public List<String> getAppJars() { return Collections.unmodifiableList(appJars); } public List<String> getAppPropertiesFiles() { return Collections.unmodifiableList(appPropertiesFiles); } public Set<String> getRequiredProperties() { return Collections.unmodifiableSet(requiredProperties); } public Map<String, String> getDefaultProperties() { return Collections.unmodifiableMap(defaultProperties); } private void processAppDirectory(File dir) { Iterator<File> it = FileUtils.iterateFiles(dir, null, false); Configuration config = new Configuration(); List<String> absClassPath = new ArrayList<String>(classPath); for (int i = 0; i < absClassPath.size(); i++) { String path = absClassPath.get(i); if (!path.startsWith("/")) { absClassPath.set(i, directory + "/" + path); } } config.set(StramAppLauncher.LIBJARS_CONF_KEY_NAME, StringUtils.join(absClassPath, ',')); while (it.hasNext()) { File entry = it.next(); if (entry.getName().endsWith(".jar")) { appJars.add(entry.getName()); try { StramAppLauncher stramAppLauncher = new StramAppLauncher(entry, config); stramAppLauncher.loadDependencies(); List<AppFactory> appFactories = stramAppLauncher.getBundledTopologies(); for (AppFactory appFactory : appFactories) { String appName = stramAppLauncher.getLogicalPlanConfiguration().getAppAlias(appFactory.getName()); if (appName == null) { appName = appFactory.getName(); } applications.add(new AppInfo(appName, entry.getName(), stramAppLauncher.prepareDAG(appFactory))); } } catch (Exception ex) { LOG.error("Caught exception trying to process {}", entry.getName(), ex); } } else if (entry.getName().endsWith(".properties")) { // TBD appPropertiesFiles.add(entry.getName()); } else { LOG.warn("Ignoring file {} with unknown extension in app directory", entry.getName()); } } } private void processConfDirectory(File dir) { Iterator<File> it = FileUtils.iterateFiles(dir, null, false); while (it.hasNext()) { File entry = it.next(); if (entry.getName().endsWith(".xml")) { configs.add(entry.getName()); } } } private void processPropertiesXml(File file) { DTConfiguration config = new DTConfiguration(); try { config.loadFile(file); for (Map.Entry<String, String> entry : config) { String key = entry.getKey(); String value = entry.getValue(); if (value == null) { requiredProperties.add(key); } else { defaultProperties.put(key, value); } } } catch (Exception ex) { LOG.warn("Ignoring META_INF/properties.xml because of error", ex); } } private static final Logger LOG = LoggerFactory.getLogger(AppBundle.class); }
package fredboat.commandmeta; import fredboat.command.admin.*; import fredboat.command.fun.*; import fredboat.command.maintenance.GetIdCommand; import fredboat.command.maintenance.ShardsCommand; import fredboat.command.maintenance.StatsCommand; import fredboat.command.admin.TestCommand; import fredboat.command.maintenance.VersionCommand; import fredboat.command.moderation.SoftbanCommand; import fredboat.command.music.control.*; import fredboat.command.music.info.ExportCommand; import fredboat.command.music.info.GensokyoRadioCommand; import fredboat.command.music.info.ListCommand; import fredboat.command.music.info.NowplayingCommand; import fredboat.command.music.seeking.ForwardCommand; import fredboat.command.music.seeking.RestartCommand; import fredboat.command.music.seeking.RewindCommand; import fredboat.command.music.seeking.SeekCommand; import fredboat.command.util.*; public class CommandInitializer { public static void initCommands() { CommandRegistry.registerCommand(0x110, "help", new HelpCommand()); CommandRegistry.registerAlias("help", "info"); CommandRegistry.registerCommand(0x101, "version", new VersionCommand()); CommandRegistry.registerCommand(0x101, "say", new SayCommand()); CommandRegistry.registerCommand(0x101, "uptime", new StatsCommand()); CommandRegistry.registerAlias("uptime", "stats"); CommandRegistry.registerCommand(0x101, "exit", new ExitCommand()); CommandRegistry.registerCommand(0x101, "avatar", new AvatarCommand()); CommandRegistry.registerCommand(0x101, "test", new TestCommand()); CommandRegistry.registerCommand(0x101, "lua", new LuaCommand()); CommandRegistry.registerCommand(0x101, "brainfuck", new BrainfuckCommand()); CommandRegistry.registerCommand(0x101, "joke", new JokeCommand()); CommandRegistry.registerCommand(0x101, "leet", new LeetCommand()); CommandRegistry.registerAlias("leet", "1337"); CommandRegistry.registerAlias("leet", "l33t"); CommandRegistry.registerAlias("leet", "1ee7"); CommandRegistry.registerCommand(0x101, "riot", new RiotCommand()); CommandRegistry.registerCommand(0x101, "update", new UpdateCommand()); CommandRegistry.registerCommand(0x101, "compile", new CompileCommand()); CommandRegistry.registerCommand(0x101, "botrestart", new BotRestartCommand()); CommandRegistry.registerCommand(0x101, "find", new FindCommand()); CommandRegistry.registerCommand(0x101, "dance", new DanceCommand()); CommandRegistry.registerCommand(0x101, "eval", new EvalCommand()); CommandRegistry.registerCommand(0x101, "s", new TextCommand("¯\\_()_/¯")); CommandRegistry.registerAlias("s", "shrug"); CommandRegistry.registerCommand(0x101, "lenny", new TextCommand("( ͡° ͜ʖ ͡°)")); CommandRegistry.registerCommand(0x101, "useless", new TextCommand("This command is useless.")); CommandRegistry.registerCommand(0x101, "clear", new ClearCommand()); CommandRegistry.registerCommand(0x101, "talk", new TalkCommand()); CommandRegistry.registerCommand(0x101, "dump", new DumpCommand()); CommandRegistry.registerCommand(0x101, "mal", new MALCommand()); CommandRegistry.registerCommand(0x101, "akinator", new AkinatorCommand()); CommandRegistry.registerCommand(0x101, "fuzzy", new FuzzyUserSearchCommand()); CommandRegistry.registerCommand(0x101, "softban", new SoftbanCommand()); CommandRegistry.registerCommand(0x101, "catgirl", new CatgirlCommand()); CommandRegistry.registerCommand(0x101, "shards", new ShardsCommand()); /* Music commands */ CommandRegistry.registerCommand(0x010, "mexit", new ExitCommand()); CommandRegistry.registerCommand(0x010, "mbotrestart", new BotRestartCommand()); CommandRegistry.registerCommand(0x010, "mstats", new StatsCommand()); CommandRegistry.registerCommand(0x010, "play", new PlayCommand()); CommandRegistry.registerCommand(0x010, "meval", new EvalCommand()); CommandRegistry.registerCommand(0x010, "skip", new SkipCommand()); CommandRegistry.registerCommand(0x010, "join", new JoinCommand()); CommandRegistry.registerAlias("join", "summon"); CommandRegistry.registerCommand(0x010, "nowplaying", new NowplayingCommand()); CommandRegistry.registerAlias("nowplaying", "np"); CommandRegistry.registerCommand(0x010, "leave", new LeaveCommand()); CommandRegistry.registerCommand(0x010, "list", new ListCommand()); CommandRegistry.registerAlias("list", "queue"); CommandRegistry.registerCommand(0x010, "mupdate", new UpdateCommand()); CommandRegistry.registerCommand(0x010, "mcompile", new CompileCommand()); CommandRegistry.registerCommand(0x010, "select", new SelectCommand()); CommandRegistry.registerCommand(0x010, "stop", new StopCommand()); CommandRegistry.registerCommand(0x010, "pause", new PauseCommand()); CommandRegistry.registerCommand(0x010, "unpause", new UnpauseCommand()); CommandRegistry.registerCommand(0x010, "getid", new GetIdCommand()); CommandRegistry.registerCommand(0x010, "shuffle", new ShuffleCommand()); CommandRegistry.registerCommand(0x010, "repeat", new RepeatCommand()); CommandRegistry.registerCommand(0x010, "volume", new VolumeCommand()); CommandRegistry.registerAlias("volume", "vol"); CommandRegistry.registerCommand(0x010, "restart", new RestartCommand()); CommandRegistry.registerCommand(0x010, "export", new ExportCommand()); CommandRegistry.registerCommand(0x010, "playerdebug", new PlayerDebugCommand()); CommandRegistry.registerCommand(0x010, "music", new MusicHelpCommand()); CommandRegistry.registerAlias("music", "musichelp"); CommandRegistry.registerCommand(0x010, "nodes", new NodesCommand()); CommandRegistry.registerCommand(0x010, "gr", new GensokyoRadioCommand()); CommandRegistry.registerAlias("gr", "gensokyo"); CommandRegistry.registerAlias("gr", "gensokyoradio"); CommandRegistry.registerCommand(0x010, "mshards", new ShardsCommand()); CommandRegistry.registerCommand(0x010, "seek", new SeekCommand()); CommandRegistry.registerCommand(0x010, "forward", new ForwardCommand()); CommandRegistry.registerAlias("forward", "fwd"); CommandRegistry.registerAlias("forward", "f"); CommandRegistry.registerCommand(0x010, "rewind", new RewindCommand()); CommandRegistry.registerAlias("rewind", "rew"); CommandRegistry.registerAlias("rewind", "r"); /* Other Anime Discord, Sergi memes or any other memes */ CommandRegistry.registerCommand(0x101, "nevrean", new RemoteFileCommand("http: CommandRegistry.registerCommand(0x101, "cheese", new RemoteFileCommand("https: CommandRegistry.registerCommand(0x101, "whats", new RemoteFileCommand("http://i.imgur.com/jeGVLk3.jpg")); CommandRegistry.registerCommand(0x101, "serg", new TextCommand("```The Sergal ( Sāgaru), is a fictional alien species created by Mick39. They belong to the Eltus race, alongside the Nevrean and Agudner in the Vilous universe, a science-fantasy world created by Mick.```")); CommandRegistry.registerCommand(0x101, "sergal", new RemoteFileCommand("http://orig08.deviantart.net/5ddf/f/2016/362/c/4/killthesergal_by_memyou-dat5xfh.png")); CommandRegistry.registerCommand(0x101, "ram", new RemoteFileCommand("http://i.imgur.com/jeGVLk3.jpg")); CommandRegistry.registerCommand(0x101, "welcome", new RemoteFileCommand("http://i.imgur.com/yjpmmBk.gif")); CommandRegistry.registerCommand(0x101, "rude", new RemoteFileCommand("http://i.imgur.com/pUn7ijx.png")); CommandRegistry.registerCommand(0x101, "fuck", new RemoteFileCommand("http://i.imgur.com/1bllKNh.png")); CommandRegistry.registerCommand(0x101, "idc", new RemoteFileCommand("http://i.imgur.com/0ZPjpNg.png")); CommandRegistry.registerCommand(0x101, "beingraped", new RemoteFileCommand("http://i.imgur.com/dPsYRYV.png")); CommandRegistry.registerCommand(0x101, "anime", new RemoteFileCommand("https://cdn.discordapp.com/attachments/132490115137142784/177751190333816834/animeeee.png")); CommandRegistry.registerCommand(0x101, "wow", new RemoteFileCommand("http: CommandRegistry.registerCommand(0x101, "what", new RemoteFileCommand("http://i.imgur.com/CTLraK4.png")); CommandRegistry.registerCommand(0x101, "pun", new RemoteFileCommand("http://i.imgur.com/2hFMrjt.png")); CommandRegistry.registerCommand(0x101, "die", new RemoteFileCommand("http://nekomata.moe/i/k2B0f6.png")); CommandRegistry.registerCommand(0x101, "stupid", new RemoteFileCommand("http://nekomata.moe/i/c056y7.png")); CommandRegistry.registerCommand(0x101, "cancer", new RemoteFileCommand("http://puu.sh/oQN2j/8e09872842.jpg")); CommandRegistry.registerCommand(0x101, "stupidbot", new RemoteFileCommand("https://cdn.discordapp.com/attachments/143976784545841161/183171963399700481/unknown.png")); CommandRegistry.registerCommand(0x101, "escape", new RemoteFileCommand("http://i.imgur.com/kk7Zu3C.png")); CommandRegistry.registerCommand(0x101, "explosion", new RemoteFileCommand("https://cdn.discordapp.com/attachments/143976784545841161/182893975965794306/megumin7.gif")); CommandRegistry.registerCommand(0x101, "gif", new RemoteFileCommand("https://cdn.discordapp.com/attachments/132490115137142784/182907929765085185/spacer.gif")); CommandRegistry.registerCommand(0x101, "noods", new RemoteFileCommand("http://i.imgur.com/CUE3gm2.png")); CommandRegistry.registerCommand(0x101, "internetspeed", new RemoteFileCommand("http: CommandRegistry.registerCommand(0x101, "hug", new RemoteFileCommand("http://i.imgur.com/U2l7mnr.gif")); CommandRegistry.registerCommand(0x101, "powerpoint", new RemoteFileCommand("http://puu.sh/rISIl/1cc927ece3.PNG")); CommandRegistry.registerCommand(0x101, "cooldog", new DogCommand()); CommandRegistry.registerCommand(0x101, "inv", new InvCommand()); CommandRegistry.registerAlias("cooldog", "dog"); CommandRegistry.registerAlias("inv", "invite"); CommandRegistry.registerAlias("cooldog", "dogmeme"); CommandRegistry.registerCommand(0x101, "lood", new TextCommand("T-that's l-lewd, baka!!!")); CommandRegistry.registerAlias("lood", "lewd"); CommandRegistry.registerCommand(0x101, "github", new TextCommand("https://github.com/Frederikam")); CommandRegistry.registerCommand(0x101, "repo", new TextCommand("https://github.com/Frederikam/FredBoat")); String[] pats = { "http://i.imgur.com/wF1ohrH.gif", "http://cdn.photonesta.com/images/i.imgur.com/I3yvqFL.gif", "http://i4.photobucket.com/albums/y131/quentinlau/Blog/sola-02-Large15.jpg", "http://i.imgur.com/OYiSZWX.gif", "http://i.imgur.com/tmidE9Q.gif", "http://i.imgur.com/CoW20gH.gif", "http://31.media.tumblr.com/e759f2da1f07de37832fc8269e99f1e7/tumblr_n3w02z954N1swm6rso1_500.gif", "https://media1.giphy.com/media/ye7OTQgwmVuVy/200.gif", "http://data.whicdn.com/images/224314340/large.gif", "http://i.imgur.com/BNiNMWC.gifv", "http://i.imgur.com/9q6fkSK.jpg", "http://i.imgur.com/eOJlnwP.gif", "http://i.imgur.com/i7bklkm.gif", "http://i.imgur.com/fSDbKwf.jpg", "https://66.media.tumblr.com/ec7472fef28b2cdf394dc85132c22ed8/tumblr_mx1asbwrBv1qbvovho1_500.gif",}; CommandRegistry.registerCommand(0x101, "pat", new PatCommand(pats)); String[] facedesk = { "https://45.media.tumblr.com/tumblr_lpzn2uFp4D1qew6kmo1_500.gif", "http://i862.photobucket.com/albums/ab181/Shadow_Milez/Animu/kuroko-facedesk.gif", "http://2.bp.blogspot.com/-Uw0i2Xv8r-M/UhyYzSHIiCI/AAAAAAAAAdg/hcI1-V7Y3A4/s1600/facedesk.gif", "https://67.media.tumblr.com/dfa4f3c1b65da06d76a271feef0d08f0/tumblr_inline_o6zkkh6VsK1u293td_500.gif", "http://stream1.gifsoup.com/webroot/animatedgifs/57302_o.gif", "http://img.neoseeker.com/mgv/59301/301/26/facedesk_display.gif" }; CommandRegistry.registerCommand(0x101, "facedesk", new FacedeskCommand(facedesk)); String[] roll = { "https://media.giphy.com/media/3xz2BCBXokf7rag0Ba/giphy.gif", "http://i.imgur.com/IWQZaHD.gif", "https://warosu.org/data/cgl/img/0077/57/1408042492433.gif", "https://media.giphy.com/media/tso0dniqIDWwg/giphy.gif", "http://s19.postimg.org/lg5x9zx8z/Hakase_Roll_anime_32552527_500_282.gif", "http://i.imgur.com/UJxrB.gif", "http://25.media.tumblr.com/tumblr_m4k42bwzNy1qj0i6io1_500.gif", "http://i.giphy.com/3o6LXfWUBTdBcccgSc.gif", "http://66.media.tumblr.com/23dec349d26317df439099fdcb4c75a4/tumblr_mld6epWdgR1riizqco1_500.gif", "https://images-2.discordapp.net/eyJ1cmwiOiJodHRwOi8vZmFybTguc3RhdGljZmxpY2tyLmNvbS83NDUxLzEyMjY4NDM2MjU1XzgwZGIxOWNlOGZfby5naWYifQ.1e8OKozMAx22ZGELeNzRkqT3v-Q.gif", "https://images-1.discordapp.net/eyJ1cmwiOiJodHRwOi8vaS5pbWd1ci5jb20vS2VHY1lYSi5naWYifQ.4dCItRLO5l91JuDw-8ls-fi8wWc.gif", "http://i.imgur.com/s2TL7A8.gif", "http://i.imgur.com/vqTAjp5.gif", "https://data.desustorage.org/a/image/1456/58/1456582568150.gif" }; CommandRegistry.registerCommand(0x101, "roll", new RollCommand(roll)); } }
package com.malhartech.stram; import com.malhartech.api.DAG; import com.malhartech.engine.GenericTestOperator; import com.malhartech.engine.TestGeneratorInputOperator; import com.malhartech.stram.PhysicalPlan.PTOperator; import com.malhartech.stram.TupleRecorder.PortInfo; import com.malhartech.stram.TupleRecorder.RecordInfo; import com.malhartech.stram.support.StramTestSupport; import com.malhartech.stram.support.StramTestSupport.WaitCondition; import java.io.*; import java.util.ArrayList; import junit.framework.Assert; import com.malhartech.netlet.DefaultEventLoop; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.LocalFileSystem; import org.apache.hadoop.fs.Path; import org.codehaus.jackson.map.ObjectMapper; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; /** * * @author Zhongjian Wang <zhongjian@malhar-inc.com> */ @Ignore public class TupleRecorderTest { @Before public void setup() throws IOException { StramChild.eventloop = new DefaultEventLoop("TupleRecorderTestEventLoop"); } @After public void teardown() { StramChild.eventloop.stop(); } public TupleRecorderTest() { } public class Tuple { public String key; public String value; } @Test public void testRecorder() { try { TupleRecorder recorder = new TupleRecorder(); recorder.setBytesPerPartFile(4096); recorder.setLocalMode(true); recorder.setBasePath("file://" + testWorkDir.getAbsolutePath() + "/recordings"); recorder.addInputPortInfo("ip1", "str1"); recorder.addInputPortInfo("ip2", "str2"); recorder.addInputPortInfo("ip3", "str3"); recorder.addOutputPortInfo("op1", "str4"); recorder.setup(null); recorder.beginWindow(1000); recorder.beginWindow(1000); recorder.beginWindow(1000); Tuple t1 = new Tuple(); t1.key = "speed"; t1.value = "5m/h"; recorder.writeTuple(t1, "ip1"); recorder.endWindow(); Tuple t2 = new Tuple(); t2.key = "speed"; t2.value = "4m/h"; recorder.writeTuple(t2, "ip3"); recorder.endWindow(); Tuple t3 = new Tuple(); t3.key = "speed"; t3.value = "6m/h"; recorder.writeTuple(t3, "ip2"); recorder.endWindow(); recorder.beginWindow(1000); Tuple t4 = new Tuple(); t4.key = "speed"; t4.value = "2m/h"; recorder.writeTuple(t4, "op1"); recorder.endWindow(); recorder.teardown(); FileSystem fs = new LocalFileSystem(); fs.initialize((new Path(recorder.getBasePath()).toUri()), new Configuration()); Path path; FSDataInputStream is; String line; BufferedReader br; path = new Path(recorder.getBasePath(), TupleRecorder.INDEX_FILE); is = fs.open(path); br = new BufferedReader(new InputStreamReader(is)); line = br.readLine(); // Assert.assertEquals("check index", "B:1000:T:0:part0.txt", line); Assert.assertEquals("check index", "F:1000-1000:T:4:33:{\"3\":\"1\",\"1\":\"1\",\"0\":\"1\",\"2\":\"1\"}:part0.txt", line); path = new Path(recorder.getBasePath(), TupleRecorder.META_FILE); //fs = FileSystem.get(path.toUri(), new Configuration()); is = fs.open(path); br = new BufferedReader(new InputStreamReader(is)); ObjectMapper mapper = new ObjectMapper(); line = br.readLine(); Assert.assertEquals("check version", "1.0", line); line = br.readLine(); // RecordInfo RecordInfo ri = mapper.readValue(line, RecordInfo.class); line = br.readLine(); PortInfo pi = mapper.readValue(line, PortInfo.class); Assert.assertEquals("port1", recorder.getPortInfoMap().get(pi.name).id, pi.id); Assert.assertEquals("port1", recorder.getPortInfoMap().get(pi.name).type, pi.type); line = br.readLine(); pi = mapper.readValue(line, PortInfo.class); Assert.assertEquals("port2", recorder.getPortInfoMap().get(pi.name).id, pi.id); Assert.assertEquals("port2", recorder.getPortInfoMap().get(pi.name).type, pi.type); line = br.readLine(); pi = mapper.readValue(line, PortInfo.class); Assert.assertEquals("port3", recorder.getPortInfoMap().get(pi.name).id, pi.id); Assert.assertEquals("port3", recorder.getPortInfoMap().get(pi.name).type, pi.type); line = br.readLine(); pi = mapper.readValue(line, PortInfo.class); Assert.assertEquals("port4", recorder.getPortInfoMap().get(pi.name).id, pi.id); Assert.assertEquals("port4", recorder.getPortInfoMap().get(pi.name).type, pi.type); Assert.assertEquals("port size", recorder.getPortInfoMap().size(), 4); //line = br.readLine(); path = new Path(recorder.getBasePath(), "part0.txt"); //fs = FileSystem.get(path.toUri(), new Configuration()); is = fs.open(path); br = new BufferedReader(new InputStreamReader(is)); line = br.readLine(); Assert.assertEquals("check part0", "B:1000", line); line = br.readLine(); Assert.assertEquals("check part0 1", "T:0:31:{\"key\":\"speed\",\"value\":\"5m/h\"}", line); line = br.readLine(); Assert.assertEquals("check part0 2", "T:2:31:{\"key\":\"speed\",\"value\":\"4m/h\"}", line); line = br.readLine(); Assert.assertEquals("check part0 3", "T:1:31:{\"key\":\"speed\",\"value\":\"6m/h\"}", line); line = br.readLine(); Assert.assertEquals("check part0 4", "T:3:31:{\"key\":\"speed\",\"value\":\"2m/h\"}", line); line = br.readLine(); Assert.assertEquals("check part0 5", "E:1000", line); } catch (IOException ex) { throw new RuntimeException(ex); } } private static File testWorkDir = new File("target", TupleRecorderTest.class.getName()); private static int testTupleCount = 100; @Test public void testRecordingFlow() throws Exception { DAG dag = new DAG(); dag.getAttributes().attr(DAG.STRAM_APP_PATH).set("file://" + testWorkDir.getAbsolutePath()); dag.getAttributes().attr(DAG.STRAM_TUPLE_RECORDING_PART_FILE_SIZE).set(1024); // 1KB per part TestGeneratorInputOperator op1 = dag.addOperator("op1", TestGeneratorInputOperator.class); GenericTestOperator op2 = dag.addOperator("op2", GenericTestOperator.class); GenericTestOperator op3 = dag.addOperator("op3", GenericTestOperator.class); op1.setEmitInterval(200); // emit every 200 msec dag.addStream("stream1", op1.outport, op2.inport1);//.setInline(true); dag.addStream("stream2", op2.outport1, op3.inport1);//.setInline(true); final StramLocalCluster localCluster = new StramLocalCluster(dag); localCluster.runAsync(); final PTOperator ptOp2 = localCluster.findByLogicalNode(dag.getOperatorMeta(op2)); StramTestSupport.waitForActivation(localCluster, ptOp2); localCluster.dnmgr.startRecording(ptOp2.getId(), null); WaitCondition c = new WaitCondition() { @Override public boolean isComplete() { TupleRecorder tupleRecorder = localCluster.getContainer(ptOp2).getTupleRecorder(ptOp2.getId(), null); return tupleRecorder != null; } }; Assert.assertTrue("Should get a tuple recorder within 2 seconds", StramTestSupport.awaitCompletion(c, 2000)); TupleRecorder tupleRecorder = localCluster.getContainer(ptOp2).getTupleRecorder(ptOp2.getId(), null); long startTime = tupleRecorder.getStartTime(); BufferedReader br; String line; File dir = new File(testWorkDir, "recordings/" + ptOp2.getId() + "/" + startTime); File file; file = new File(dir, "meta.txt"); Assert.assertTrue("meta file should exist", file.exists()); br = new BufferedReader(new FileReader(file)); line = br.readLine(); Assert.assertEquals("version should be 1.0", line, "1.0"); line = br.readLine(); Assert.assertTrue("should contain start time", line != null && line.contains("\"startTime\"")); line = br.readLine(); Assert.assertTrue("should contain name, streamName, type and id", line != null && line.contains("\"name\"") && line.contains("\"streamName\"") && line.contains("\"type\"") && line.contains("\"id\"")); line = br.readLine(); Assert.assertTrue("should contain name, streamName, type and id", line != null && line.contains("\"name\"") && line.contains("\"streamName\"") && line.contains("\"type\"") && line.contains("\"id\"")); c = new WaitCondition() { @Override public boolean isComplete() { TupleRecorder tupleRecorder = localCluster.getContainer(ptOp2).getTupleRecorder(ptOp2.getId(), null); return (tupleRecorder.getTotalTupleCount() >= testTupleCount); } }; Assert.assertTrue("Should record more than " + testTupleCount + " tuples within 15 seconds", StramTestSupport.awaitCompletion(c, 15000)); localCluster.dnmgr.stopRecording(ptOp2.getId(), null); c = new WaitCondition() { @Override public boolean isComplete() { TupleRecorder tupleRecorder = localCluster.getContainer(ptOp2).getTupleRecorder(ptOp2.getId(), null); return (tupleRecorder == null); } }; Assert.assertTrue("Tuple recorder shouldn't exist any more after stopping", StramTestSupport.awaitCompletion(c, 5000)); file = new File(dir, "index.txt"); Assert.assertTrue("index file should exist", file.exists()); br = new BufferedReader(new FileReader(file)); ArrayList<String> partFiles = new ArrayList<String>(); int indexCount = 0; while ((line = br.readLine()) != null) { String partFile = "part" + indexCount + ".txt"; if (line.startsWith("F:")) { Assert.assertTrue("index file line should end with :part" + indexCount + ".txt", line.endsWith(":" + partFile)); partFiles.add(partFile); indexCount++; } else if (line.startsWith("E")) { Assert.assertEquals("index file should end after E line", br.readLine(), null); break; } else { Assert.fail("index file line is not starting with F or E"); } } int tupleCount0 = 0; int tupleCount1 = 0; boolean beginWindowExists = false; boolean endWindowExists = false; for (String partFile: partFiles) { file = new File(dir, partFile); if (partFile != partFiles.get(partFiles.size() - 1)) { Assert.assertTrue(partFile + " should be greater than 1KB", file.length() >= 1024); } Assert.assertTrue(partFile + " should exist", file.exists()); br = new BufferedReader(new FileReader(file)); while ((line = br.readLine()) != null) { if (line.startsWith("B:")) { beginWindowExists = true; } else if (line.startsWith("E:")) { endWindowExists = true; } else if (line.startsWith("T:0:")) { tupleCount0++; } else if (line.startsWith("T:1")) { tupleCount1++; } } } Assert.assertTrue("begin window should exist", beginWindowExists); Assert.assertTrue("end window should exist", endWindowExists); Assert.assertTrue("tuple exists for port 0", tupleCount0 > 0); Assert.assertTrue("tuple exists for port 1", tupleCount1 > 0); Assert.assertTrue("total tuple count >= " + testTupleCount, tupleCount0 + tupleCount1 >= testTupleCount); localCluster.shutdown(); } }
package org.neo4j.backup; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.fail; import static org.neo4j.helpers.collection.MapUtil.stringMap; import static org.neo4j.kernel.Config.ENABLE_ONLINE_BACKUP; import java.io.File; import org.apache.commons.io.FileUtils; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.neo4j.com.ComException; import org.neo4j.graphdb.DynamicRelationshipType; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Transaction; import org.neo4j.graphdb.TransactionFailureException; import org.neo4j.graphdb.index.Index; import org.neo4j.index.impl.lucene.LuceneDataSource; import org.neo4j.kernel.AbstractGraphDatabase; import org.neo4j.kernel.Config; import org.neo4j.kernel.EmbeddedGraphDatabase; import org.neo4j.kernel.impl.transaction.xaframework.XaDataSource; import org.neo4j.test.DbRepresentation; import org.neo4j.test.subprocess.SubProcess; public class TestBackup { private final String serverPath = "target/var/serverdb"; private final String otherServerPath = serverPath + "2"; private final String backupPath = "target/var/backuedup-serverdb"; @Before public void before() throws Exception { FileUtils.deleteDirectory( new File( serverPath ) ); FileUtils.deleteDirectory( new File( otherServerPath ) ); FileUtils.deleteDirectory( new File( backupPath ) ); } // TODO MP: What happens if the server database keeps growing, virtually making the files endless? @Test public void makeSureFullFailsWhenDbExists() throws Exception { createInitialDataSet( serverPath ); ServerInterface server = startServer( serverPath ); OnlineBackup backup = OnlineBackup.from( "localhost" ); createInitialDataSet( backupPath ); try { backup.full( backupPath ); fail( "Shouldn't be able to do full backup into existing db" ); } catch ( Exception e ) { // good } shutdownServer( server ); } @Test public void makeSureIncrementalFailsWhenNoDb() throws Exception { createInitialDataSet( serverPath ); ServerInterface server = startServer( serverPath ); OnlineBackup backup = OnlineBackup.from( "localhost" ); try { backup.incremental( backupPath ); fail( "Shouldn't be able to do incremental backup into non-existing db" ); } catch ( Exception e ) { // Good } shutdownServer( server ); } @Test public void fullThenIncremental() throws Exception { DbRepresentation initialDataSetRepresentation = createInitialDataSet( serverPath ); ServerInterface server = startServer( serverPath ); OnlineBackup backup = OnlineBackup.from( "localhost" ); backup.full( backupPath ); assertEquals( initialDataSetRepresentation, DbRepresentation.of( backupPath ) ); shutdownServer( server ); DbRepresentation furtherRepresentation = addMoreData( serverPath ); server = startServer( serverPath ); backup.incremental( backupPath ); assertEquals( furtherRepresentation, DbRepresentation.of( backupPath ) ); shutdownServer( server ); } @Test public void makeSureStoreIdIsEnforced() throws Exception { // Create data set X on server A DbRepresentation initialDataSetRepresentation = createInitialDataSet( serverPath ); ServerInterface server = startServer( serverPath ); // Grab initial backup from server A OnlineBackup backup = OnlineBackup.from( "localhost" ); backup.full( backupPath ); assertEquals( initialDataSetRepresentation, DbRepresentation.of( backupPath ) ); shutdownServer( server ); // Create data set X+Y on server B createInitialDataSet( otherServerPath ); addMoreData( otherServerPath ); server = startServer( otherServerPath ); // Try to grab incremental backup from server B. // Data should be OK, but store id check should prevent that. try { backup.incremental( backupPath ); fail( "Shouldn't work" ); } catch ( ComException e ) { // Good } shutdownServer( server ); // Just make sure incremental backup can be received properly from // server A, even after a failed attempt from server B DbRepresentation furtherRepresentation = addMoreData( serverPath ); server = startServer( serverPath ); backup.incremental( backupPath ); assertEquals( furtherRepresentation, DbRepresentation.of( backupPath ) ); shutdownServer( server ); } private ServerInterface startServer( String path ) throws Exception { /* ServerProcess server = new ServerProcess(); try { server.startup( Pair.of( path, "true" ) ); } catch ( Throwable e ) { // TODO Auto-generated catch block throw new RuntimeException( e ); } */ ServerInterface server = new EmbeddedServer( path, "true" ); server.awaitStarted(); return server; } private void shutdownServer( ServerInterface server ) throws Exception { server.shutdown(); Thread.sleep( 1000 ); } private DbRepresentation addMoreData( String path ) { GraphDatabaseService db = startGraphDatabase( path ); Transaction tx = db.beginTx(); Node node = db.createNode(); node.setProperty( "backup", "Is great" ); db.getReferenceNode().createRelationshipTo( node, DynamicRelationshipType.withName( "LOVES" ) ); tx.success(); tx.finish(); DbRepresentation result = DbRepresentation.of( db ); db.shutdown(); return result; } private GraphDatabaseService startGraphDatabase( String path ) { return new EmbeddedGraphDatabase( path, stringMap( Config.KEEP_LOGICAL_LOGS, "true" ) ); } private DbRepresentation createInitialDataSet( String path ) { GraphDatabaseService db = startGraphDatabase( path ); Transaction tx = db.beginTx(); Node node = db.createNode(); node.setProperty( "myKey", "myValue" ); Index<Node> nodeIndex = db.index().forNodes( "db-index" ); nodeIndex.add( node, "myKey", "myValue" ); db.getReferenceNode().createRelationshipTo( node, DynamicRelationshipType.withName( "KNOWS" ) ); tx.success(); tx.finish(); DbRepresentation result = DbRepresentation.of( db ); db.shutdown(); return result; } @Test public void multipleIncrementals() throws Exception { GraphDatabaseService db = null; try { db = new EmbeddedGraphDatabase( serverPath, stringMap( ENABLE_ONLINE_BACKUP, "true" ) ); Transaction tx = db.beginTx(); Index<Node> index = db.index().forNodes( "yo" ); index.add( db.createNode(), "justTo", "commitATx" ); tx.success(); tx.finish(); OnlineBackup backup = OnlineBackup.from( "localhost" ); backup.full( backupPath ); long lastCommittedTxForLucene = getLastCommittedTx( backupPath ); for ( int i = 0; i < 5; i++ ) { tx = db.beginTx(); Node node = db.createNode(); index.add( node, "key", "value" + i ); tx.success(); tx.finish(); backup.incremental( backupPath ); assertEquals( lastCommittedTxForLucene + i + 1, getLastCommittedTx( backupPath ) ); } } finally { if ( db != null ) { db.shutdown(); } } } @Test @Ignore public void backupIndexWithNoCommits() throws Exception { GraphDatabaseService db = null; try { db = new EmbeddedGraphDatabase( serverPath, stringMap( ENABLE_ONLINE_BACKUP, "true" ) ); db.index().forNodes( "created-no-commits" ); OnlineBackup backup = OnlineBackup.from( "localhost" ); backup.full( backupPath ); } finally { if ( db != null ) { db.shutdown(); } } } private long getLastCommittedTx( String path ) { GraphDatabaseService db = new EmbeddedGraphDatabase( path ); try { XaDataSource ds = ((AbstractGraphDatabase)db).getConfig().getTxModule().getXaDataSourceManager().getXaDataSource( LuceneDataSource.DEFAULT_NAME ); return ds.getLastCommittedTxId(); } finally { db.shutdown(); } } @Test public void shouldRetainFileLocksAfterFullBackupOnLiveDatabase() throws Exception { GraphDatabaseService db = new EmbeddedGraphDatabase( serverPath, stringMap( ENABLE_ONLINE_BACKUP, "true" ) ); try { assertStoreIsLocked( serverPath ); OnlineBackup.from( "localhost" ).full( backupPath ); assertStoreIsLocked( serverPath ); } finally { db.shutdown(); } } private static void assertStoreIsLocked( String path ) { try { new EmbeddedGraphDatabase( path ).shutdown(); fail( "Could start up database in same process, store not locked" ); } catch ( TransactionFailureException ex ) { // expected } StartupChecker proc = new LockProcess().start( path ); try { assertFalse( "Could start up database in subprocess, store is not locked", proc.startupOk() ); } finally { SubProcess.stop( proc ); } } public interface StartupChecker { boolean startupOk(); } @SuppressWarnings( "serial" ) private static class LockProcess extends SubProcess<StartupChecker, String> implements StartupChecker { private volatile Object state; @Override public boolean startupOk() { Object result; do { result = state; } while ( result == null ); return !( state instanceof Exception ); } @Override protected void startup( String path ) throws Throwable { GraphDatabaseService db; try { db = new EmbeddedGraphDatabase( path ); } catch ( TransactionFailureException ex ) { state = ex; return; } state = new Object(); db.shutdown(); } } }
package edu.rutgers.css.Rutgers.api; import java.util.Hashtable; import java.util.Locale; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import edu.rutgers.css.Rutgers.SingleFragmentActivity; import edu.rutgers.css.Rutgers.fragments.BusDisplay; import edu.rutgers.css.Rutgers.fragments.BusMain; import edu.rutgers.css.Rutgers.fragments.DTable; import edu.rutgers.css.Rutgers.fragments.FoodHall; import edu.rutgers.css.Rutgers.fragments.FoodMain; import edu.rutgers.css.Rutgers.fragments.FoodMeal; import edu.rutgers.css.Rutgers.fragments.PlacesDisplay; import edu.rutgers.css.Rutgers.fragments.PlacesMain; import edu.rutgers.css.Rutgers.fragments.RSSReader; /** * Singleton fragment builder * */ public class ComponentFactory { private static ComponentFactory instance = null; public Activity mMainActivity; private static final String TAG = "ComponentFactory"; private Hashtable<String, Class> fragmentTable; protected ComponentFactory() { // Set up table of fragments that can be launched fragmentTable = new Hashtable<String, Class>(); fragmentTable.put("dtable", DTable.class); fragmentTable.put("bus", BusMain.class); fragmentTable.put("reader", RSSReader.class); fragmentTable.put("food", FoodMain.class); fragmentTable.put("foodhall", FoodHall.class); fragmentTable.put("foodmeal", FoodMeal.class); fragmentTable.put("places", PlacesMain.class); fragmentTable.put("placesdisplay", PlacesDisplay.class); fragmentTable.put("busdisplay", BusDisplay.class); } /** * Get singleton instance * @return Component factory singleton instance */ public static ComponentFactory getInstance () { if (instance == null) instance = new ComponentFactory(); return instance; } /** * Create component fragment * @param options Argument bundle with at least 'component' argument set to describe which component to build. All other arguments will be passed to the new fragment. * @return Built fragment */ public Fragment createFragment (Bundle options) { Log.d(TAG, "Attempting to create fragment"); Fragment fragment = new Fragment(); String component; if(options.get("component") == null) { Log.e(TAG, "Component argument not set"); return null; } component = options.getString("component").toLowerCase(Locale.US); Class compClass = fragmentTable.get(component); if(compClass != null) { try { fragment = (Fragment) compClass.newInstance(); Log.d(TAG, "Creating a " + compClass.getSimpleName()); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException e) { Log.e(TAG, Log.getStackTraceString(e)); return null; } } else { Log.e(TAG, "Failed to create component " + component); return null; } fragment.setArguments(options); return fragment; } /** * Launch an activity * @param context * @param options Argument bundle */ public void launch (Context context, Bundle options) { Intent i = new Intent(context, SingleFragmentActivity.class); i.putExtras(options); context.startActivity(i); } }
package com.lds.game; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; import android.opengl.GLU; import android.content.Context; public class GameRenderer implements com.lds.Graphics.Renderer { public Game game; public Context context; int prevRenderCount; public GameRenderer (float screenW, float screenH, Context _context) { game = new Game(screenW, screenH); this.context = _context; } public void onSurfaceCreated(GL10 gl, EGLConfig config) { game.player1.loadTexture(gl, context); gl.glEnable(GL10.GL_TEXTURE_2D); gl.glShadeModel(GL10.GL_SMOOTH); gl.glClearColor(1.0f, 0.41f, 0.71f, 0.5f); gl.glDisable(GL10.GL_DEPTH_TEST); gl.glDisable(GL10.GL_DITHER); gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST); } //TODO move interpolation to another method, less clutter in main loop public void onDrawFrame(GL10 gl) { gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); int renderedcount = 0; //Render all entities for (Entity ent : game.entList) { if (ent.isRendered) { renderedcount++; //ent.loadTexture(gl, this.context); gl.glTranslatef(ent.xPos, ent.yPos, 0.0f); gl.glRotatef(ent.angle, 0.0f, 0.0f, 1.0f); gl.glScalef(ent.xScl, ent.yScl, 1.0f); ent.draw(gl); gl.glLoadIdentity(); } } //Update screen position and entities onSurfaceChanged(gl, (int)game.screenW, (int)game.screenH); game.updateLocalEntities(); //Debugging info if (renderedcount != prevRenderCount) { System.out.println("Items rendered: " + renderedcount); prevRenderCount = renderedcount; } } public void onSurfaceChanged(GL10 gl, int width, int height) { gl.glViewport(0, 0, width, height); gl.glMatrixMode(GL10.GL_PROJECTION); gl.glLoadIdentity(); GLU.gluOrtho2D(gl, game.camPosX - (float)(game.screenW/2), game.camPosX + (float)(game.screenW/2), game.camPosY - (float)(game.screenH/2), game.camPosY + (float)(game.screenH/2)); gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glLoadIdentity(); } @Override public void onTouchInput(float xInput, float yInput) { game.camPosX = xInput - (game.screenW / 2); game.camPosY = -yInput + (game.screenH / 2); } }
package br.com.dbsoft.util; import java.math.BigDecimal; import java.math.RoundingMode; import java.sql.Date; import java.sql.Timestamp; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.SimpleDateFormat; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.faces.context.FacesContext; public class DBSFormat { public static String[] ZERO_DDI_DDDs = new String[]{ "800", "300" }; public class MASK{ public static final String CURRENCY = "###,##0.00"; } public final static class REGEX{ public static final String ZIP = "\\d{5}-\\d{3}"; public static final String LICENSE_PLATE = "[A-Z]{3}-\\d{4}"; // public static final String PHONE_NUMBER = "^([(+]{0,1})([0-9]{0,2})([)\\-\\s]{0,1})([(\\-\\s]{0,1})([0-9]{0,3})([)\\-\\s]{0,1})([0-9]{3,4})([-.]{0,1})([0-9]{4})$"; public static final String PHONE_NUMBER = "^([(+]{0,1})(([0-9]{2,3})|([0-9]{0}))([)\\-\\s]{0,1})([(\\-\\s]{0,1})(([0-9]{2,3})|([0-9]{0}))([)\\-\\s]{0,1})([0-9]{3,4})([-.]{0,1})([0-9]{4})$"; // public static final String PHONE_NUMBER = "^([(+]{0,1})([0-9]{2,3})([)\\-\\s]{0,1})([(\\-\\s]{0,1})([0-9]{2,3})([)\\-\\s]{0,1})([0-9]{3,4})([-.]{0,1})([0-9]{4})$"; public static final String ONLY_NUMBERS = "^[0-9]+$"; } private static Pattern wPHONE_NUMBER; public static enum NUMBER_SIGN{ NONE, CRDB_PREFIX, CRDB_SUFFIX, MINUS_SUFFIX, MINUS_PREFIX, PARENTHESES; } DBSFormat(){ wPHONE_NUMBER = Pattern.compile(REGEX.PHONE_NUMBER); } // //## public properties # // public static String getFormattedDate(Long pDate){ return getFormattedDate(DBSDate.toDate(pDate)); } public static String getFormattedDate(Object pDate){ if (DBSObject.isEmpty(pDate)){ return ""; }else{ SimpleDateFormat xFormat = new SimpleDateFormat("dd/MM/yyyy"); return xFormat.format(DBSDate.toDate(pDate)); } } public static String getFormattedDate(Date pDate){ if (pDate == null){ return ""; }else{ SimpleDateFormat xFormat = new SimpleDateFormat("dd/MM/yyyy"); return xFormat.format(pDate); } } public static String getFormattedDate(Timestamp pDate){ if (pDate == null){ return ""; }else{ Date xDate = DBSDate.toDate(pDate); return getFormattedDate(xDate); } } public static String getFormattedAno(Object pDate) { if (pDate == null){ return ""; }else{ SimpleDateFormat xFormat = new SimpleDateFormat("yyyy"); return xFormat.format(DBSDate.toDate(pDate)); } } public static String getFormattedDateTimes(Long pLong){ if (pLong == null){ return ""; }else{ SimpleDateFormat xFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); return xFormat.format(pLong); } } public static String getFormattedDateTimes(Date pDate){ SimpleDateFormat xFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); return xFormat.format(pDate); } public static String getFormattedDateTimes(Timestamp pDate){ Date xDate = DBSDate.toDate(pDate); return getFormattedDateTimes(xDate); } public static String getFormattedTimes(Date pDate){ SimpleDateFormat xFormat = new SimpleDateFormat("HH:mm:ss"); return xFormat.format(pDate.getTime()); } public static String getFormattedDateTime(Long pLong){ if (pLong == null){ return ""; }else{ SimpleDateFormat xFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm"); return xFormat.format(pLong); } } public static String getFormattedDateTime(Date pDate){ SimpleDateFormat xFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm"); return xFormat.format(pDate); } public static String getFormattedDateTime(Timestamp pDate){ Date xDate = DBSDate.toDate(pDate); return getFormattedDateTime(xDate); } public static String getFormattedTime(Date pDate){ SimpleDateFormat xFormat = new SimpleDateFormat("HH:mm"); return xFormat.format(pDate.getTime()); } public static String getFormattedDateCustom(Object pDate, String pMask){ if (DBSObject.isNull(pDate)) { return ""; } SimpleDateFormat xFormat = new SimpleDateFormat(pMask); return xFormat.format(DBSDate.toDate(pDate)); } public static String getFormattedTime(Timestamp pDate){ Date xDate = DBSDate.toDate(pDate); return getFormattedTimes(xDate); } public static String getFormattedNumberUnsigned(Double pValue, Object pDecimalPlaces){ return getFormattedNumberUnsigned(pValue, pDecimalPlaces, getLocale()); } public static String getFormattedNumberUnsigned(Object pValue, Object pDecimalPlaces){ return getFormattedNumberUnsigned(pValue, pDecimalPlaces, getLocale()); } public static String getFormattedNumberUnsigned(Object pValue, Object pDecimalPlaces, Locale pLocale){ return getFormattedNumber(DBSNumber.toDouble(pValue, 0D, pLocale), NUMBER_SIGN.NONE, getNumberMask(DBSNumber.toInteger(pDecimalPlaces)), pLocale); } public static String getFormattedNumber(BigDecimal pValue, Object pDecimalPlaces){ return getFormattedNumber(pValue, pDecimalPlaces, getLocale()); } public static String getFormattedNumber(BigDecimal pValue, Object pDecimalPlaces, Locale pLocale){ return getFormattedNumber(DBSNumber.toDouble(pValue, 0D, pLocale), pDecimalPlaces, pLocale); } public static String getFormattedNumber(Double pValue, Object pDecimalPlaces){ return getFormattedNumber(pValue, NUMBER_SIGN.MINUS_PREFIX, getNumberMask(DBSNumber.toInteger(pDecimalPlaces)), getLocale()); } public static String getFormattedNumber(Double pValue, Object pDecimalPlaces, Locale pLocale){ return getFormattedNumber(pValue, NUMBER_SIGN.MINUS_PREFIX, getNumberMask(DBSNumber.toInteger(pDecimalPlaces)), pLocale); } public static String getFormattedNumber(Object pValue, Object pDecimalPlaces){ return getFormattedNumber(pValue, pDecimalPlaces, getLocale()); } public static String getFormattedNumber(Object pValue, Object pDecimalPlaces, Locale pLocale){ return getFormattedNumber(DBSNumber.toDouble(pValue, 0D, pLocale), NUMBER_SIGN.MINUS_PREFIX, getNumberMask(DBSNumber.toInteger(pDecimalPlaces)), pLocale); } public static String getFormattedCurrency(Object pValor){ return getFormattedCurrency(DBSNumber.toDouble(pValor, 0D, getLocale())); } public static String getFormattedCurrency(Object pValor, Locale pLocale){ return getFormattedCurrency(DBSNumber.toDouble(pValor, 0D, pLocale), pLocale); } public static String getFormattedCurrency(Double pValor){ return getFormattedCurrency(pValor, NUMBER_SIGN.MINUS_PREFIX); } public static String getFormattedCurrency(Double pValor, Locale pLocale){ return getFormattedCurrency(pValor, NUMBER_SIGN.MINUS_PREFIX, pLocale); } public static String getFormattedCurrency(Object pValor, NUMBER_SIGN pSign){ return getFormattedCurrency(DBSNumber.toDouble(pValor, 0D, getLocale()), pSign, getLocale()); } public static String getFormattedCurrency(Object pValor, NUMBER_SIGN pSign, Locale pLocale){ return getFormattedCurrency(DBSNumber.toDouble(pValor, 0D, pLocale), pSign, pLocale); } public static String getFormattedCurrency(Double pValor, NUMBER_SIGN pSign){ return getFormattedNumber(pValor, pSign, MASK.CURRENCY, getLocale()); } public static String getFormattedCurrency(Double pValor, NUMBER_SIGN pSign, Locale pLocale){ return getFormattedNumber(pValor, pSign, MASK.CURRENCY, pLocale); } public static String getFormattedNumber(Object pValor, NUMBER_SIGN pSign, String pNumberMask){ return getFormattedNumber(DBSNumber.toDouble(pValor, 0D, getLocale()), pSign, pNumberMask, getLocale()); } public static String getFormattedNumber(Object pValor, NUMBER_SIGN pSign, String pNumberMask, Locale pLocale){ return getFormattedNumber(DBSNumber.toDouble(pValor, 0D, pLocale), pSign, pNumberMask, pLocale); } public static String getFormattedNumber(Double pValor, NUMBER_SIGN pSign, String pNumberMask){ return getFormattedNumber(pValor, pSign, pNumberMask, getLocale()); } public static String getFormattedNumber(Double pValor, NUMBER_SIGN pSign, String pNumberMask, Locale pLocale){ if (DBSObject.isEmpty(pValor)) { return null; } DecimalFormatSymbols xOtherSymbols = new DecimalFormatSymbols(pLocale); // xOtherSymbols.setDecimalSeparator(getDecimalSeparator().charAt(0)); // xOtherSymbols.setGroupingSeparator(getGroupSeparator().charAt(0)); DecimalFormat xDF = new DecimalFormat(pNumberMask, xOtherSymbols); // DecimalFormat xDF = new DecimalFormat(pNumberMask); xDF.get xDF.setRoundingMode(RoundingMode.HALF_UP); switch (pSign) { case NONE: xDF.setNegativePrefix(""); xDF.setNegativeSuffix(""); break; case CRDB_PREFIX: xDF.setPositivePrefix("CR "); xDF.setNegativePrefix("DB "); break; case CRDB_SUFFIX: xDF.setPositiveSuffix(" CR"); xDF.setNegativeSuffix(" DB"); xDF.setNegativePrefix(""); break; case MINUS_PREFIX: xDF.setPositivePrefix(""); xDF.setNegativePrefix("-"); break; case MINUS_SUFFIX: xDF.setPositivePrefix(""); xDF.setNegativePrefix(""); xDF.setNegativeSuffix("-"); break; case PARENTHESES: xDF.setPositivePrefix(""); xDF.setNegativePrefix("("); xDF.setNegativeSuffix(")"); break; default: xDF.setPositivePrefix(""); xDF.setNegativePrefix("-"); break; } return xDF.format(pValor); } public static String getNumberMask(int pDecimalPlaces, boolean pUseSeparator){ return getNumberMask(pDecimalPlaces, pUseSeparator, 0); } public static String getNumberMask(int pDecimalPlaces, int pLeadingZeroSize){ return getNumberMask(pDecimalPlaces, false, pLeadingZeroSize); } public static String getNumberMask(int pDecimalPlaces){ return getNumberMask(pDecimalPlaces, true,0 ); } public static String getNumberMask(int pDecimalPlaces, boolean pUseSeparator, int pLeadingZeroSize){ String xF; if (pUseSeparator){ xF = " }else{ if (pLeadingZeroSize > 0){ xF = DBSString.repeat("0",pLeadingZeroSize); }else{ xF = " } } if (pDecimalPlaces < 0){ return null; } if (pDecimalPlaces > 0){ xF = xF + "." + DBSString.repeat("0",pDecimalPlaces); } return xF; } public static String getNumeroSemPontoMilhar(Double pValor, int pCasasDecimais){ if (DBSObject.isEmpty(pValor)){ return null; } String xS = getFormattedNumber(pValor, getNumberMask(pCasasDecimais)); return DBSString.changeStr(xS, ",", ""); } public static String getCNPJ(Object pCNPJ) { return getFormattedMask(pCNPJ, "99.999.999/9999-99", " "); } public static String getCPF(Object pCPF) { return getFormattedMask(pCPF, "999.999.9999-99", " "); } public static String getCEP(Object pCEP) { return getFormattedMask(pCEP, "99999-999", " "); } public static String getCPFCNPJ(Object pPessoaFisica, Object pValue){ String xValue = DBSString.toString(pValue); xValue = DBSNumber.getOnlyNumber(xValue); if (DBSBoolean.toBoolean(pPessoaFisica)){ return getCPF(pValue); }else{ return getCNPJ(pValue); } } /** * Retorna o caracter utilizado para separar a casa decimal * @return */ public static String getDecimalSeparator(){ DecimalFormat xFormat = (DecimalFormat) DecimalFormat.getInstance(getLocale()); DecimalFormatSymbols xD = xFormat.getDecimalFormatSymbols(); return Character.toString(xD.getDecimalSeparator()); } public static String getGroupSeparator(){ DecimalFormat xFormat = (DecimalFormat) DecimalFormat.getInstance(getLocale()); DecimalFormatSymbols xD = xFormat.getDecimalFormatSymbols(); return Character.toString(xD.getGroupingSeparator()); } public static String getFormattedMask(Object pValue, String pMask){ return getFormattedMask(pValue, pMask, ""); } public static String getFormattedMask(Object pValue, String pMask, String pEmptyChr){ if (pValue ==null || pEmptyChr == null){ return ""; } if (pMask.equals("")){ return pValue.toString(); } //9=Numeric; a=Alpha; x=AlphaNumeric String xFV = ""; String xValue = pValue.toString(); int xVI = 0; boolean xAchou; for (int xMI =0 ; xMI < pMask.length(); xMI++){ String xMC = pMask.substring(xMI, xMI+1).toUpperCase(); if (xMC.equals("9")|| xMC.equals("A")){ xAchou = false; while (xVI < xValue.length()){ char xVC = xValue.charAt(xVI); xVI++; if(Character.isLetterOrDigit(xVC)){ xFV = xFV + xVC; xAchou = true; break; } } if (!xAchou){ xFV = xFV + pEmptyChr; } }else{ xFV = xFV + xMC; } } return xFV; } public static String numberSimplify(Number pValue){ Double xVal = pValue.doubleValue(); Integer xIntVal = pValue.intValue(); Integer xLength = xIntVal.toString().length(); if (xLength == 0){return "";} Double xSimple = (xVal / Math.pow(10, ((xLength -1) - ((xLength -1) % 3)))); String xSuf = ""; if (xLength > 15){ xSuf = "quatri"; }else if (xLength > 12){ xSuf = "tri"; }else if (xLength > 9){ xSuf = "bi"; }else if (xLength > 6){ xSuf = "mi"; }else if (xLength > 3){ xSuf = "mil"; } if (xSuf != ""){ return getFormattedNumber(xSimple, 2) + " " + xSuf; }else{ return getFormattedNumber(xVal, 2); } } //Validation public static Matcher isPhone(String pString){ if (pString == null){ return null; } Matcher xP = wPHONE_NUMBER.matcher(pString); return xP; } public static String getPhoneNumber(Object pDDI, Object pDDD, Object pNumber){ return getPhoneNumber(DBSString.toString(pDDI),DBSString.toString(pDDD),DBSString.toString(pNumber)); } public static String getPhoneNumber(String pDDI, String pDDD, String pNumber){ StringBuilder xSB = new StringBuilder(); if (DBSObject.isEmpty(pNumber)){ return ""; } if (!DBSObject.isEmpty(pDDI)){ xSB.append("("); xSB.append(pDDI); xSB.append(")"); } if (!DBSObject.isEmpty(pDDD)){ xSB.append("("); xSB.append(pDDD); xSB.append(")"); } xSB.append(pNumber); return getPhoneNumber(xSB.toString()); } public static String getPhoneNumber(String pPhoneNumber){ StringBuilder xFormattedNumber = new StringBuilder(); String xChar; Boolean xIsNumber = false; Boolean xWasNumber = null; Integer xGroup = 1; StringBuilder xValue = new StringBuilder(); for (int i=pPhoneNumber.length(); i>0; i xChar = pPhoneNumber.substring(i-1, i); xIsNumber = xChar.matches(REGEX.ONLY_NUMBERS); if (xWasNumber == null){ xWasNumber = xIsNumber; }else if (xIsNumber != xWasNumber){ xGroup = pvPhoneNumber(xFormattedNumber, xGroup, xValue.toString(), xWasNumber); if (xGroup == null){ return null; } xValue = new StringBuilder(); xWasNumber = xIsNumber; if (!xIsNumber){ xChar = "-"; } }else if (!xIsNumber){ xChar = null; } if (xChar != null){ xValue.insert(0, xChar); } } if (!DBSObject.isEmpty(xValue.toString())){ xGroup = pvPhoneNumber(xFormattedNumber, xGroup, xValue.toString(), xWasNumber); } String xFN = xFormattedNumber.toString(); if (xGroup == null || DBSObject.isEmpty(xFN)){ return null; }else{ if (xFN.startsWith(")")){ xFN = xFN.substring(1, xFN.length()); } return xFN; } } /** * DDI DDD NUMERO * xxx xxx xxxx-xxxx * @param pFormattedNumber * @param pGroup * @param pValue * @param pIsNumber * @return */ private static Integer pvPhoneNumber(StringBuilder pFormattedNumber, Integer pGroup, String pValue, Boolean pIsNumber){ String xValue = null; int xB = 0; int xE = 0; Integer xMin = 0; Integer xMax = null; if (DBSObject.isEmpty(pValue)){return pGroup;} xE = pValue.length(); if (pGroup > 8){ return null; }else if (pGroup==2 //Separadores || pGroup==4 || pGroup==6 || pGroup==8){ if (pGroup==8){ xValue = "("; }else if (pGroup==6){ xValue = ")("; }else if (pGroup==4){ xValue = ")"; }else if (pGroup==2){ xValue = "-"; } if (!pIsNumber){ pValue = ""; } }else{ if (!pIsNumber){ return null; } if (pGroup==1){ xMin = 4; xMax = 4; }else if (pGroup==3){ xMin = 3; xMax = 5; //DDD }else if (pGroup==5){ xMin = 2; xMax = 3; //DDI }else if (pGroup==7){ xMin = 1; xMax = 3; } xB = xE - xMax +1; if (xB<=0){ xB=1; } //Valor utilizado xValue = DBSString.getSubString(pValue, xB, xE); //DDD e DDI: Retira os zeros a esquerda if (pGroup==5 || pGroup==7){ xValue = getFormattedNumber(xValue, NUMBER_SIGN.NONE, " } if (xValue.equals("0") || xValue.length() < xMin){ return null; //Erro } //Resto pValue = DBSString.getSubString(pValue, 1, xB-1); } pGroup++; //Adiciona a string pFormattedNumber.insert(0, xValue); pIsNumber = pValue.matches(REGEX.ONLY_NUMBERS); return pvPhoneNumber(pFormattedNumber, pGroup, pValue, pIsNumber); } /** * Retorna o Locale corrente, dando prioridade ao locale da view e depois do sistema. * @return */ public static Locale getLocale(){ Locale xLocale; if (FacesContext.getCurrentInstance() != null){ xLocale = FacesContext.getCurrentInstance().getViewRoot().getLocale(); }else{ xLocale = DBSNumber.LOCALE_PTBR; //Locale.getDefault(); } return xLocale; } }
package com.bio4j.model; import com.bio4j.angulillos.*; import com.bio4j.angulillos.Arity.*; public final class UniProtGraph<V,E> extends TypedGraph<UniProtGraph<V,E>,V,E> { public UniProtGraph(UntypedGraph<V,E> graph) { super(graph); } @Override public final UniProtGraph<V,E> self() { return this; } /* ## Proteins The first thing to point out as clearly as possible is: `Protein`s **do not** correspond to UniProt entries; we create a protein for every isoform present in any UniProt entry. The protein which is usually identified with the entry has true `isCanonical`. */ public final class Protein extends Vertex<Protein> { private Protein(V vertex) { super(vertex, protein); } @Override public final Protein self() { return this; } } public final ProteinType protein = new ProteinType(); public final class ProteinType extends VertexType<Protein> { @Override public final Protein fromRaw(V vertex) { return new Protein(vertex); } public final Accession accession = new Accession(); public final class Accession extends Property<String> implements FromAtMostOne, ToOne { private Accession() { super(String.class); } public final Index index = new Index(); public final class Index extends UniqueIndex<Accession, String> { private Index() { super(accession); } } } public final IsCanonical isCanonical = new IsCanonical(); public final class IsCanonical extends Property<Boolean> implements FromAtLeastOne, ToOne { private IsCanonical() { super(Boolean.class); } } public final FullName fullName = new FullName(); public final class FullName extends Property<String> implements FromAny, ToOne { private FullName() { super(String.class); } } public final Dataset dataset = new Dataset(); public final class Dataset extends Property<Datasets> implements FromAny, ToOne { private Dataset() { super(Datasets.class); } } public final Existence existence = new Existence(); public final class Existence extends Property<ExistenceEvidence> implements FromAny { private Existence() { super(ExistenceEvidence.class); } } public final Sequence sequence = new Sequence(); public final class Sequence extends Property<String> implements FromAny, ToOne { private Sequence() { super(String.class); } } public final Mass mass = new Mass(); public final class Mass extends Property<Integer> implements FromAny, ToOne { private Mass() { super(Integer.class); } } } public final class Isoforms extends Edge<Protein, Isoforms, Protein> { private Isoforms(E edge) { super(edge, isoforms); } @Override public final Isoforms self() { return this; } } public final IsoformsType isoforms = new IsoformsType(); public final class IsoformsType extends EdgeType<Protein, Isoforms, Protein> implements FromAny, ToAny { private IsoformsType() { super(protein, protein); } @Override public final Isoforms fromRaw(E edge) { return new Isoforms(edge); } } public final class GeneProducts extends Edge<GeneName, GeneProducts, Protein> { private GeneProducts(E edge) { super(edge, geneProducts); } @Override public final GeneProducts self() { return this; } } public final GeneProductsType geneProducts = new GeneProductsType(); public final class GeneProductsType extends EdgeType<GeneName, GeneProducts, Protein> implements FromAny, ToAny { private GeneProductsType() { super(geneName, protein); } @Override public final GeneProducts fromRaw(E edge) { return new GeneProducts(edge); } } public final class GeneName extends Vertex<GeneName> { private GeneName(V vertex) { super(vertex, geneName); } @Override public final GeneName self() { return this; } } public final GeneNameType geneName = new GeneNameType(); public final class GeneNameType extends VertexType<GeneName> { @Override public final GeneName fromRaw(V vertex) { return new GeneName(vertex); } } public static enum GeneLocations { chromosome, // TODO this the default case, which is missing in UniProt. Please fix/improve this name. apicoplast, chloroplast, organellar_chromatophore, cyanelle, hydrogenosome, mitochondrion, non_photosynthetic_plastid, nucleomorph, plasmid, plastid; } public static enum Datasets { swissProt, trEMBL; } public static enum ExistenceEvidence { proteinLevel, transcriptLevel, homologyInferred, predicted, uncertain; } public final class Keyword extends Vertex<Keyword> { private Keyword(V vertex) { super(vertex, keyword); } @Override public final Keyword self() { return this; } } public final KeywordType keyword = new KeywordType(); public final class KeywordType extends VertexType<Keyword> { @Override public final Keyword fromRaw(V vertex) { return new Keyword(vertex); } public final Name name = new Name(); public final class Name extends Property<String> implements FromAny, ToOne { private Name() { super(String.class); } } public final Definition definition = new Definition(); public final class Definition extends Property<String> implements FromAny, ToOne { private Definition() { super(String.class); } } public final Category category = new Category(); public final class Category extends Property<KeywordCategories> implements FromAny, ToOne { private Category() { super(KeywordCategories.class); } } } public static enum KeywordCategories { biologicalProcess, cellularComponent, codingSequenceDiversity, developmentalStage, disease, domain, ligand, molecularFunction, PTM, technicalTerm; } public final class Keywords extends Edge<Protein, Keywords, Keyword> { private Keywords(E edge) { super(edge, keywords); } @Override public final Keywords self() { return this; } } public final KeywordsType keywords = new KeywordsType(); public final class KeywordsType extends EdgeType<Protein, Keywords, Keyword> implements FromAtLeastOne, ToAny { private KeywordsType() { super(protein, keyword); } @Override public final Keywords fromRaw(E edge) { return new Keywords(edge); } } public final class Annotation extends Vertex<Annotation> { private Annotation(V vertex) { super(vertex, annotation); } @Override public final Annotation self() { return this; } } public final AnnotationType annotation = new AnnotationType(); public final class AnnotationType extends VertexType<Annotation> { @Override public final Annotation fromRaw(V vertex) { return new Annotation(vertex); } public final FeatureType featureType = new FeatureType(); public final class FeatureType extends Property<FeatureTypes> implements FromAtLeastOne, ToOne { private FeatureType() { super(FeatureTypes.class); } } } public final class Annotations extends Edge<Protein, Annotations, Annotation> { private Annotations(E edge) { super(edge, annotations); } @Override public final Annotations self() { return this; } } public final AnnotationsType annotations = new AnnotationsType(); public final class AnnotationsType extends EdgeType<Protein, Annotations, Annotation> implements FromAtLeastOne, ToAny { private AnnotationsType() { super(protein, annotation); } @Override public final Annotations fromRaw(E edge) { return new Annotations(edge); } public final Begin begin = new Begin(); public final class Begin extends Property<Integer> implements FromAny, ToOne { private Begin() { super(Integer.class); } } public final End end = new End(); public final class End extends Property<Integer> implements FromAny, ToOne { private End() { super(Integer.class); } } } public static enum FeatureTypes { activeSite, bindingSite, calciumBindingRegion, chain, coiledCoilRegion, compositionallyBiasedRegion, crosslink, disulfideBond, DNABindingRegion, domain, glycosylationSite, helix, initiatorMethionine, lipidMoietyBindingRegion, metalIonBindingSite, modifiedResidue, mutagenesisSite, nonConsecutiveResidues, nonTerminalResidue, nucleotidePhosphateBindingRegion, peptide, propeptide, regionOfInterest, repeat, nonstandardAminoAcid, sequenceConflict, sequenceVariant, shortSequenceMotif, signalPeptide, site, spliceVariant, strand, topologicalDomain, transitPeptide, transmembraneRegion, turn, unsureResidue, zincFingerRegion, intramembraneRegion; } public final class Comment extends Vertex<Comment> { private Comment(V vertex) { super(vertex, comment); } @Override public final Comment self() { return this; } } public final CommentType comment = new CommentType(); public final class CommentType extends VertexType<Comment> { @Override public final Comment fromRaw(V vertex) { return new Comment(vertex); } public final Topic topic = new Topic(); public final class Topic extends Property<CommentTopics> implements FromAtLeastOne, ToOne { private Topic() { super(CommentTopics.class); } } public final Text text = new Text(); public final class Text extends Property<String> implements FromAny, ToOne { private Text() { super(String.class); } } } /* This enum only contains those topics which do *not* give rise to specific vertex types. */ public static enum CommentTopics { allergen, alternativeProducts, // TODO remove, isoforms biotechnology, biophysicochemicalProperties, catalyticActivity, caution, cofactor, developmentalStage, disease, domain, disruptionPhenotype, enzymeRegulation, function, induction, miscellaneous, pathway, pharmaceutical, polymorphism, PTM, RNAEditing, similarity, subcellularLocation, sequenceCaution, subunit, tissueSpecificity, toxicDose, onlineInformation, massSpectrometry, interaction; } }
package com.grosner.dbflow.sql; import android.database.DatabaseUtils; import com.grosner.dbflow.config.FlowLog; import com.grosner.dbflow.config.FlowManager; import com.grosner.dbflow.runtime.DBTransactionInfo; import com.grosner.dbflow.runtime.TransactionManager; import com.grosner.dbflow.runtime.transaction.QueryTransaction; import com.grosner.dbflow.runtime.transaction.ResultReceiver; import com.grosner.dbflow.sql.builder.Condition; import com.grosner.dbflow.sql.builder.ConditionQueryBuilder; import com.grosner.dbflow.sql.builder.QueryBuilder; import com.grosner.dbflow.structure.Model; import java.util.List; import java.util.Map; public class Where<ModelClass extends Model> implements Query { /** * The first chunk of the SQL statement before this query. */ private final From<ModelClass> mFrom; /** * Helps to build the where statement easily */ private ConditionQueryBuilder<ModelClass> mConditionQueryBuilder; /** * The SQL GROUP BY method */ private String mGroupBy; /** * The SQL HAVING */ private ConditionQueryBuilder<ModelClass> mHaving; /** * The SQL ORDER BY */ private String mOrderBy; /** * The SQL LIMIT */ private String mLimit; /** * The SQL OFFSET */ private String mOffset; /** * The database manager we run this query on */ private final FlowManager mManager; /** * Constructs this class with a SELECT * on the manager and {@link com.grosner.dbflow.sql.builder.ConditionQueryBuilder} * * @param flowManager * @param conditionQueryBuilder * @param <ModelClass> * @return */ public static <ModelClass extends Model> Where<ModelClass> with(FlowManager flowManager, ConditionQueryBuilder<ModelClass> conditionQueryBuilder) { return new Select(flowManager).from(conditionQueryBuilder.getTableClass()).where(conditionQueryBuilder); } /** * Constructs this class with the specified {@link com.grosner.dbflow.config.FlowManager} * and {@link com.grosner.dbflow.sql.From} chunk * * @param manager The database manager * @param from The FROM statement chunk */ public Where(FlowManager manager, From<ModelClass> from) { mManager = manager; mFrom = from; mConditionQueryBuilder = new ConditionQueryBuilder<ModelClass>(mManager, mFrom.getTable()); mHaving = new ConditionQueryBuilder<ModelClass>(mManager, mFrom.getTable()); } protected void checkSelect(String methodName) { if (!(mFrom.getQueryBuilderBase() instanceof Select)) { throw new IllegalArgumentException("Please use " + methodName + "(). The beginning is not a Select"); } } /** * Defines the full SQL clause for the WHERE statement * * @param whereClause The SQL after WHERE . ex: columnName = "name" AND ID = 0 * @return */ public Where<ModelClass> whereClause(String whereClause) { mConditionQueryBuilder.append(whereClause); return this; } /** * Defines the {@link com.grosner.dbflow.sql.builder.ConditionQueryBuilder} that will build this SQL statement * * @param conditionQueryBuilder Helps build the SQL after WHERE * @return */ public Where<ModelClass> whereQuery(ConditionQueryBuilder<ModelClass> conditionQueryBuilder) { mConditionQueryBuilder = conditionQueryBuilder; return this; } /** * Adds a param to the WHERE clause with the "=" operator * * @param columnName The name of column * @param value the value of column * @return */ public Where<ModelClass> and(String columnName, Object value) { mConditionQueryBuilder.param(columnName, value); return this; } /** * Adds a param to the WHERE clause with a custom operator. * * @param columnName The name of column * @param operator The operator to use. Ex: "=", "<", etc. * @param value The value of the column * @return */ public Where<ModelClass> and(String columnName, String operator, Object value) { mConditionQueryBuilder.param(columnName, operator, value); return this; } /** * Adds a param to the WHERE clause with the custom {@link com.grosner.dbflow.sql.builder.Condition} * * @param condition The {@link com.grosner.dbflow.sql.builder.Condition} to use * @return */ public Where<ModelClass> and(Condition condition) { mConditionQueryBuilder.param(condition); return this; } /** * Adds a bunch of {@link com.grosner.dbflow.sql.builder.Condition} to this builder. * * @param conditionMap The map of {@link com.grosner.dbflow.sql.builder.Condition} * @return */ public Where<ModelClass> andThese(Map<String, Condition> conditionMap) { mConditionQueryBuilder.params(conditionMap); return this; } /** * Adds a bunch of {@link com.grosner.dbflow.sql.builder.Condition} to this builder. * * @param conditions The array of {@link com.grosner.dbflow.sql.builder.Condition} * @return */ public Where<ModelClass> andThese(Condition...conditions) { mConditionQueryBuilder.params(conditions); return this; } /** * Adds primary key params to the where. They must be in order that the primary keys are defined. * * @param values the values of the primary keys from the table. Must be in order of the primary key declaration. * @return */ public Where<ModelClass> andPrimaryValues(Object... values) { mConditionQueryBuilder.primaryParams(values); return this; } /** * Defines a SQL GROUP BY statement without the GROUP BY. * * @param groupBy * @return */ public Where<ModelClass> groupBy(QueryBuilder groupBy) { mGroupBy = groupBy.getQuery(); return this; } /** * Defines a SQL HAVING statement without the HAVING. * * @param having * @return */ public Where<ModelClass> having(Condition...conditions) { mHaving.params(conditions); return this; } /** * Defines a SQL ORDER BY statement without the ORDER BY. * * @param orderBy * @return */ public Where<ModelClass> orderBy(QueryBuilder orderBy) { mOrderBy = orderBy.getQuery(); return this; } /** * Defines a SQL LIMIT statement without the LIMIT. * * @param limit * @return */ public Where<ModelClass> limit(Object limit) { mLimit = String.valueOf(limit); return this; } /** * Defines a SQL OFFSET statement without the OFFSET. * * @param offset * @return */ public Where<ModelClass> offset(Object offset) { mOffset = String.valueOf(offset); return this; } /** * Executes a SQL statement that retrieves the count of results in the DB. * * @return The number of rows this query returns */ public long count() { return DatabaseUtils.longForQuery(mManager.getWritableDatabase(), getQuery(), null); } /** * Run this query without expecting any results */ public void query() { // Query the sql here mManager.getWritableDatabase().rawQuery(getQuery(), null); } /** * Queries for all of the results this statement returns from a DB cursor in the form of the {@link ModelClass} * * @return All of the entries in the DB converted into {@link ModelClass} */ public List<ModelClass> queryList() { checkSelect("query"); return SqlUtils.queryList(mManager, mFrom.getTable(), getQuery()); } /** * Queries and returns only the first {@link ModelClass} result from the DB. * * @return The first result of this query. Note: this query may return more than one from the DB. */ public ModelClass querySingle() { checkSelect("query"); return SqlUtils.querySingle(mManager, mFrom.getTable(), getQuery()); } /** * Will run this query on the {@link com.grosner.dbflow.runtime.DBTransactionQueue} * * @param transactionInfo The information on how to prioritize the transaction * @param transactionManager The transaction manager to add the query to */ public void transact(DBTransactionInfo transactionInfo, TransactionManager transactionManager) { transactionManager.addTransaction(new QueryTransaction<ModelClass>(transactionInfo, this)); } /** * Will run this query on the {@link com.grosner.dbflow.runtime.DBTransactionQueue} with the shared * {@link com.grosner.dbflow.runtime.TransactionManager} * * @param transactionInfo The information on how to prioritize the transaction */ public void transact(DBTransactionInfo transactionInfo) { transact(transactionInfo, TransactionManager.getInstance()); } /** * Puts this query onto the {@link com.grosner.dbflow.runtime.DBTransactionQueue} and will return a list of * {@link ModelClass} on the UI thread. * * @param transactionManager The transaction manager to add the query to * @param listResultReceiver The result of this transaction */ public void transactList(TransactionManager transactionManager, ResultReceiver<List<ModelClass>> listResultReceiver) { checkSelect("transact"); transactionManager.fetchFromTable(this, listResultReceiver); } /** * Puts this query onto the {@link com.grosner.dbflow.runtime.DBTransactionQueue} and will return a list of * {@link ModelClass} on the UI thread with the shared {@link com.grosner.dbflow.runtime.TransactionManager}. * * @param listResultReceiver The result of this transaction */ public void transactList(ResultReceiver<List<ModelClass>> listResultReceiver) { transactList(TransactionManager.getInstance(), listResultReceiver); } /** * Puts this query onto the {@link com.grosner.dbflow.runtime.DBTransactionQueue} and will return * a single item on the UI thread. * * @param transactionManager The transaction manager to add the query to * @param resultReceiver The result of this transaction */ public void transactSingleModel(TransactionManager transactionManager, ResultReceiver<ModelClass> resultReceiver) { checkSelect("transact"); transactionManager.fetchModel(this, resultReceiver); } /** * Puts this query onto the {@link com.grosner.dbflow.runtime.DBTransactionQueue} and will return * a single item on the UI thread with the shared {@link com.grosner.dbflow.runtime.TransactionManager}. * * @param resultReceiver The result of this transaction */ public void transactSingleModel(ResultReceiver<ModelClass> resultReceiver) { transactSingleModel(TransactionManager.getInstance(), resultReceiver); } /** * Returns whether the DB {@link android.database.Cursor} returns with a count of at least 1 * * @return if {@link android.database.Cursor}.count > 0 */ public boolean hasData() { checkSelect("query"); return SqlUtils.hasData(mManager, mFrom.getTable(), getQuery()); } /** * Returns the table this query points to * * @return */ public Class<ModelClass> getTable() { return mFrom.getTable(); } @Override public String getQuery() { String fromQuery = mFrom.getQuery(); QueryBuilder queryBuilder = new QueryBuilder().append(fromQuery).appendSpace(); queryBuilder.appendQualifier("WHERE", mConditionQueryBuilder.getQuery()) .appendQualifier("GROUP BY", mGroupBy) .appendQualifier("HAVING", mHaving.getQuery()) .appendQualifier("ORDER BY", mOrderBy) .appendQualifier("LIMIT", mLimit) .appendQualifier("OFFSET", mOffset); // Don't wast time building the string // unless we're going to log it. if (FlowLog.isEnabled(FlowLog.Level.V)) { FlowLog.log(FlowLog.Level.V, queryBuilder.getQuery()); } return queryBuilder.getQuery(); } }
package sensor; import ch.quantasy.tinkerforge.tinker.agent.implementation.TinkerforgeStackAgent; import ch.quantasy.tinkerforge.tinker.application.implementation.AbstractTinkerforgeApplication; import ch.quantasy.tinkerforge.tinker.core.implementation.TinkerforgeDevice; import com.tinkerforge.*; import com.tinkerforge.BrickletBarometer.AirPressureListener; import com.tinkerforge.BrickletBarometer.AirPressureReachedListener; import java.text.*; import java.util.*; /** * This class is responsible for receiving, processing and delegating data about * the ambient-temperature and Object-IR-temperature * * @author reto * */ public class BarometerApplication extends AbstractTinkerforgeApplication implements AirPressureReachedListener { public static String formatNumber(Integer number, String unit, double kommastellen) { double doubleNumber = (double)number / Math.pow(10, kommastellen); return (new DecimalFormat(" } private final List<IDoorEventListener> eventListeners = new ArrayList<IDoorEventListener>(); public void addDoorEventListener( IDoorEventListener listener ) { if ( ! eventListeners.contains( listener ) ) { eventListeners.add( listener ); } } public void removeDoorEventListener( IDoorEventListener observer ) { eventListeners.remove( observer ); } private String Id; private String sUid; private BrickletBarometer barometer; private int iActiveCalibPoint = 0; private final int iDiffC = 200; //0.2 mBar private final int iCalibrationPointDelayC = 5; private final int iCalibrationDelayC = 60000; private BarometerCalibration barometerCalibration; private Timer CalibTimer; public BarometerApplication(String sUid) { this.sUid = sUid; CalibTimer = new Timer(); } @Override public void deviceDisconnected( final TinkerforgeStackAgent tinkerforgeStackAgent, final Device device) { if (TinkerforgeDevice.getDevice(device) == TinkerforgeDevice.Barometer) { final BrickletBarometer barometerBrick = (BrickletBarometer) device; barometer = null; barometerBrick.removeAirPressureReachedListener(this); CalibTimer.cancel(); } } @Override public void deviceConnected( final TinkerforgeStackAgent tinkerforgeStackAgent, final Device device) { try { if ((TinkerforgeDevice.getDevice(device) == TinkerforgeDevice.Barometer) && device.getIdentity().uid.equalsIgnoreCase(sUid) ) { barometer = (BrickletBarometer) device; barometer.addAirPressureReachedListener(this); Id = device.getIdentity().uid; barometerCalibration = new BarometerCalibration(); CalibTimer.scheduleAtFixedRate(barometerCalibration, 0, iCalibrationDelayC); } } catch (final TinkerforgeException ex) { } } public void setThreshold (int iAirPressure) { try { barometer.setAirPressureCallbackThreshold('o', iAirPressure - iDiffC, iAirPressure + iDiffC); } catch (TimeoutException e) { e.printStackTrace(); } catch (NotConnectedException e) { e.printStackTrace(); } } @Override public void airPressureReached(int iAirPressure) { try { main.The17HerzApplication.logInfo("Ereignis bei " + formatNumber(iAirPressure, "mBar", 3) + " | Von: " + Id + barometer.getAirPressureCallbackThreshold().toString()); setThreshold(iAirPressure); } catch (TimeoutException e) { e.printStackTrace(); } catch (NotConnectedException e) { e.printStackTrace(); } } @Override public int hashCode() { return 0; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } final BarometerApplication other = (BarometerApplication) obj; return this == other; } private class BarometerCalibration extends TimerTask implements AirPressureListener { Object lock = new Object(); private final long lCalibDurationC = 2000; private long StartTime; private ArrayList<Integer> aiCalibPoints = new ArrayList<Integer>() ; BarometerCalibration() { barometer.addAirPressureListener(this); } @Override public void run() { try { barometer.setAirPressureCallbackPeriod(iCalibrationPointDelayC); } catch (TimeoutException e) { e.printStackTrace(); } catch (NotConnectedException e) { e.printStackTrace(); } StartTime = System.currentTimeMillis(); main.The17HerzApplication.logInfo("Calibration started [SensorID=" + Id + ", ReferenceValue=" + ((aiCalibPoints.size() > 0) ? aiCalibPoints.get(0) : 0) + ", maxDiff=" + iDiffC + ", MeasureInterval=" + iCalibrationPointDelayC + "]" ); synchronized (lock) { aiCalibPoints.clear(); } while ((System.currentTimeMillis() - StartTime) < lCalibDurationC) { try { Thread.sleep(10); } catch (InterruptedException e) { } } // Durchschnitt der Kalibrationspunkte errechnen long sum = 0; synchronized (lock) { for (Integer point: aiCalibPoints) { sum += point; } if (aiCalibPoints.size() > 0) { int iThresholdValue = (int) (sum / aiCalibPoints.size()); main.The17HerzApplication.logInfo("Calibration succeeded [SensorID=" + Id + ", NewThresholdValue=" + iThresholdValue + ", MeasurePointCount=" + aiCalibPoints.size() + "]" ); setThreshold(iThresholdValue); } } try { barometer.setAirPressureCallbackPeriod(0); } catch (TimeoutException e) { e.printStackTrace(); } catch (NotConnectedException e) { e.printStackTrace(); } } @Override public void airPressure(int iAirPressure) { synchronized (lock) { aiCalibPoints.add(iAirPressure); //main.The17HerzApplication.logInfo("Add Calibration point [id=" + Id + ", value=" + iAirPressure + ", iActiveCalibPoint=" + iActiveCalibPoint + "]"); if(aiCalibPoints.get(0) + iDiffC < iAirPressure || aiCalibPoints.get(0) - iDiffC > iAirPressure) { main.The17HerzApplication.logInfo("Calibration failed [SensorID=" + Id + ", ReferenceValue=" + aiCalibPoints.get(0) + ", airPressure=" + iAirPressure + ", maxDiff=" + iDiffC + "]" ); aiCalibPoints.clear(); StartTime = System.currentTimeMillis(); } } } @Override protected void finalize() { if (barometer != null) { barometer.removeAirPressureListener(this); } } } }
package be.ibridge.kettle.test.rowproducer; import java.math.BigDecimal; import java.util.Date; import be.ibridge.kettle.core.LogWriter; import be.ibridge.kettle.core.Row; import be.ibridge.kettle.core.exception.KettleException; import be.ibridge.kettle.core.util.EnvUtil; import be.ibridge.kettle.core.value.Value; import be.ibridge.kettle.trans.RowProducer; import be.ibridge.kettle.trans.StepLoader; import be.ibridge.kettle.trans.Trans; import be.ibridge.kettle.trans.TransMeta; import be.ibridge.kettle.trans.TransPreviewFactory; import be.ibridge.kettle.trans.step.injector.InjectorMeta; public class RowProducerTest { private static final String STEPNAME_STARTPOINT = "Start point"; private static final int NR_ROWS = 150000; public static void main(String[] args) throws KettleException { // Init stuff... EnvUtil.environmentInit(); LogWriter log = LogWriter.getInstance(); StepLoader stepLoader = StepLoader.getInstance(); if (!stepLoader.read()) { throw new RuntimeException("Unable to load steps and plugins"); } Row row = createRow(); InjectorMeta startMeta = new InjectorMeta(); startMeta.allocate(row.size()); for (int i=0;i<row.size();i++) { Value v = row.getValue(i); startMeta.getName()[i] = v.getName(); startMeta.getType()[i] = v.getType(); startMeta.getLength()[i] = v.getLength(); startMeta.getPrecision()[i] = v.getPrecision(); } TransMeta transMeta = TransPreviewFactory.generatePreviewTransformation(startMeta, STEPNAME_STARTPOINT); Trans trans = new Trans(log, transMeta); trans.prepareExecution(null); final RowProducer rp = trans.addRowProducer(STEPNAME_STARTPOINT, 0); trans.startThreads(); // OK the transformation is now running in a different thread in the background, let's feed the first step some rows of data. // To prevent blocking, you can do it also in a different thread. Runnable runnable = new Runnable() { public void run() { for (int i=0;i<NR_ROWS;i++) { rp.putRow(createRow()); } // Finished processing rp.finished(); } }; Thread thread = new Thread(runnable); thread.start(); // Wait until the transformation is finished. // That would also mean that thread has finished. trans.waitUntilFinished(); } private static Row createRow() { Row row = new Row(); row.addValue(new Value("field1", "aaaaa")); row.addValue(new Value("field2", new Date())); row.addValue(new Value("field3", 123L)); row.addValue(new Value("field4", true)); row.addValue(new Value("field5", new BigDecimal(123.45))); return row; } }
package com.matt.forgehax.util; import com.matt.forgehax.Globals; import com.matt.forgehax.util.entity.EntityUtils; import com.matt.forgehax.util.math.Angle; import com.matt.forgehax.util.math.VectorUtils; import net.minecraft.entity.Entity; import net.minecraft.inventory.ItemStackHelper; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.Packet; import net.minecraft.util.NonNullList; import net.minecraft.util.math.Vec3d; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Utils implements Globals { /** * Use PacketHelper class now */ @Deprecated public static final List<Packet> OUTGOING_PACKET_IGNORE_LIST = Collections.emptyList(); @Deprecated public static int toRGBA(int r, int g, int b, int a) { return (r << 16) + (g << 8) + (b << 0) + (a << 24); } @Deprecated public static int toRGBA(float r, float g, float b, float a) { return toRGBA((int) (r * 255.f), (int) (g * 255.f), (int) (b * 255.f), (int) (a * 255.f)); } @Deprecated public static int toRGBA(float[] colors) { if(colors.length != 4) throw new IllegalArgumentException("colors[] must have a length of 4!"); return toRGBA(colors[0], colors[1], colors[2], colors[3]); } @Deprecated public static int toRGBA(double[] colors) { if(colors.length != 4) throw new IllegalArgumentException("colors[] must have a length of 4!"); return toRGBA((float)colors[0], (float)colors[1], (float)colors[2], (float)colors[3]); } @Deprecated public static int[] toRGBAArray(int colorBuffer) { return new int[] { (colorBuffer >> 16 & 255), (colorBuffer >> 8 & 255), (colorBuffer & 255), (colorBuffer >> 24 & 255) }; } public static <E extends Enum<?>> String[] toArray(E[] o) { String[] output = new String[o.length]; for(int i = 0; i < output.length; i++) output[i] = o[i].name(); return output; } public static UUID stringToUUID(String uuid) { if(uuid.contains("-")) { // if it contains the hyphen we don't have to manually put them in return UUID.fromString(uuid); } else { // otherwise we have to put Pattern pattern = Pattern.compile("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})"); Matcher matcher = pattern.matcher(uuid); return UUID.fromString(matcher.replaceAll("$1-$2-$3-$4-$5")); } } public static double normalizeAngle(double angle) { while (angle <= -180) angle += 360; while (angle > 180) angle -= 360; return angle; } public static double clamp(double value, double min, double max) { return Math.max(min, Math.min(max, value)); } public static Angle getLookAtAngles(Vec3d startPos, Vec3d endPos) { return VectorUtils.vectorAngle(endPos.subtract(startPos)).normalize(); } public static Angle getLookAtAngles(Vec3d endPos) { return getLookAtAngles(EntityUtils.getEyePos(MC.player), endPos); } public static Angle getLookAtAngles(Entity entity) { return getLookAtAngles(EntityUtils.getOBBCenter(entity)); } public static double scale(double x, double from_min, double from_max, double to_min, double to_max) { return to_min + (to_max - to_min) * ((x - from_min) / (from_max - from_min)); } public static <T> boolean isInRange(T[] array, int index) { return array != null && index >= 0 && index < array.length; } public static <T> boolean isInRange(Collection<T> list, int index) { return list != null && index >= 0 && index < list.size(); } public static <T> T defaultTo(T value, T defaultTo) { return value == null ? defaultTo : value; } public static List<ItemStack> getShulkerContents(ItemStack stack) { // TODO: move somewhere else NonNullList<ItemStack> contents = NonNullList.withSize(27, ItemStack.EMPTY); NBTTagCompound compound = stack.getTagCompound(); if(compound != null && compound.hasKey("BlockEntityTag", 10)) { NBTTagCompound tags = compound.getCompoundTag("BlockEntityTag"); if (tags.hasKey("Items", 9)) { // load in the items ItemStackHelper.loadAllItems(tags, contents); } } return contents; } @Deprecated public static class Colors { public final static int WHITE = Utils.toRGBA(255, 255, 255, 255); public final static int BLACK = Utils.toRGBA(0, 0, 0, 255); public final static int RED = Utils.toRGBA(255, 0, 0, 255); public final static int GREEN = Utils.toRGBA(0, 255, 0, 255); public final static int BLUE = Utils.toRGBA(0, 0, 255, 255); public final static int ORANGE = Utils.toRGBA(255, 128, 0, 255); public final static int PURPLE = Utils.toRGBA(163, 73, 163, 255); public final static int GRAY = Utils.toRGBA(127, 127, 127, 255); public final static int DARK_RED = Utils.toRGBA(64, 0, 0, 255); public final static int YELLOW = Utils.toRGBA(255, 255, 0, 255); } }
package ch.unizh.ini.jaer.projects.speakerid.libsvm320; import java.io.*; import java.util.*; // Kernel Cache // l is the number of total data items // size is the cache size limit in bytes class Cache { private final int l; private long size; private final class head_t { head_t prev, next; // a cicular list float[] data; int len; // data[0,len) is cached in this entry } private final head_t[] head; private head_t lru_head; Cache(int l_, long size_) { l = l_; size = size_; head = new head_t[l]; for(int i=0;i<l;i++) head[i] = new head_t(); size /= 4; size -= l * (16/4); // sizeof(head_t) == 16 size = Math.max(size, 2* (long) l); // cache must be large enough for two columns lru_head = new head_t(); lru_head.next = lru_head.prev = lru_head; } private void lru_delete(head_t h) { // delete from current location h.prev.next = h.next; h.next.prev = h.prev; } private void lru_insert(head_t h) { // insert to last position h.next = lru_head; h.prev = lru_head.prev; h.prev.next = h; h.next.prev = h; } // request data [0,len) // return some position p where [p,len) need to be filled // (p >= len if nothing needs to be filled) // java: simulate pointer using single-element array int get_data(int index, float[][] data, int len) { head_t h = head[index]; if(h.len > 0) lru_delete(h); int more = len - h.len; if(more > 0) { // free old space while(size < more) { head_t old = lru_head.next; lru_delete(old); size += old.len; old.data = null; old.len = 0; } // allocate new space float[] new_data = new float[len]; if(h.data != null) System.arraycopy(h.data,0,new_data,0,h.len); h.data = new_data; size -= more; do {int a=h.len; h.len=len; len=a;} while(false); } lru_insert(h); data[0] = h.data; return len; } void swap_index(int i, int j) { if(i==j) return; if(head[i].len > 0) lru_delete(head[i]); if(head[j].len > 0) lru_delete(head[j]); do {float[] a=head[i].data; head[i].data=head[j].data; head[j].data=a;} while(false); do {int a=head[i].len; head[i].len=head[j].len; head[j].len=a;} while(false); if(head[i].len > 0) lru_insert(head[i]); if(head[j].len > 0) lru_insert(head[j]); if(i>j) do {int a=i; i=j; j=a;} while(false); for(head_t h = lru_head.next; h!=lru_head; h=h.next) { if(h.len > i) { if(h.len > j) do {float a=h.data[i]; h.data[i]=h.data[j]; h.data[j]=a;} while(false); else { // give up lru_delete(h); size += h.len; h.data = null; h.len = 0; } } } } } // Kernel evaluation // the static method k_function is for doing single kernel evaluation // the constructor of Kernel prepares to calculate the l*l kernel matrix // the member function get_Q is for getting one column from the Q Matrix abstract class QMatrix { abstract float[] get_Q(int column, int len); abstract double[] get_QD(); abstract void swap_index(int i, int j); }; abstract class Kernel extends QMatrix { private svm_node[][] x; private final double[] x_square; // svm_parameter private final int kernel_type; private final int degree; private final double gamma; private final double coef0; abstract float[] get_Q(int column, int len); abstract double[] get_QD(); void swap_index(int i, int j) { do {svm_node[] a=x[i]; x[i]=x[j]; x[j]=a;} while(false); if(x_square != null) do {double a=x_square[i]; x_square[i]=x_square[j]; x_square[j]=a;} while(false); } private static double powi(double base, int times) { double tmp = base, ret = 1.0; for(int t=times; t>0; t/=2) { if(t%2==1) ret*=tmp; tmp = tmp * tmp; } return ret; } double kernel_function(int i, int j) { switch(kernel_type) { case svm_parameter.LINEAR: return dot(x[i],x[j]); case svm_parameter.POLY: return powi(gamma*dot(x[i],x[j])+coef0,degree); case svm_parameter.RBF: return Math.exp(-gamma*(x_square[i]+x_square[j]-2*dot(x[i],x[j]))); case svm_parameter.SIGMOID: return Math.tanh(gamma*dot(x[i],x[j])+coef0); case svm_parameter.PRECOMPUTED: return x[i][(int)(x[j][0].value)].value; default: return 0; // java } } Kernel(int l, svm_node[][] x_, svm_parameter param) { this.kernel_type = param.kernel_type; this.degree = param.degree; this.gamma = param.gamma; this.coef0 = param.coef0; x = (svm_node[][])x_.clone(); if(kernel_type == svm_parameter.RBF) { x_square = new double[l]; for(int i=0;i<l;i++) x_square[i] = dot(x[i],x[i]); } else x_square = null; } static double dot(svm_node[] x, svm_node[] y) { double sum = 0; int xlen = x.length; int ylen = y.length; int i = 0; int j = 0; while(i < xlen && j < ylen) { if(x[i].index == y[j].index) sum += x[i++].value * y[j++].value; else { if(x[i].index > y[j].index) ++j; else ++i; } } return sum; } static double k_function(svm_node[] x, svm_node[] y, svm_parameter param) { switch(param.kernel_type) { case svm_parameter.LINEAR: return dot(x,y); case svm_parameter.POLY: return powi(param.gamma*dot(x,y)+param.coef0,param.degree); case svm_parameter.RBF: { double sum = 0; int xlen = x.length; int ylen = y.length; int i = 0; int j = 0; while(i < xlen && j < ylen) { if(x[i].index == y[j].index) { double d = x[i++].value - y[j++].value; sum += d*d; } else if(x[i].index > y[j].index) { sum += y[j].value * y[j].value; ++j; } else { sum += x[i].value * x[i].value; ++i; } } while(i < xlen) { sum += x[i].value * x[i].value; ++i; } while(j < ylen) { sum += y[j].value * y[j].value; ++j; } return Math.exp(-param.gamma*sum); } case svm_parameter.SIGMOID: return Math.tanh(param.gamma*dot(x,y)+param.coef0); case svm_parameter.PRECOMPUTED: return x[(int)(y[0].value)].value; default: return 0; // java } } } // An SMO algorithm in Fan et al., JMLR 6(2005), p. 1889--1918 // Solves: // min 0.5(\alpha^T Q \alpha) + p^T \alpha // y^T \alpha = \delta // y_i = +1 or -1 // 0 <= alpha_i <= Cp for y_i = 1 // 0 <= alpha_i <= Cn for y_i = -1 // Given: // Q, p, y, Cp, Cn, and an initial feasible point \alpha // l is the size of vectors and matrices // eps is the stopping tolerance // solution will be put in \alpha, objective value will be put in obj class Solver { int active_size; byte[] y; double[] G; // gradient of objective function static final byte LOWER_BOUND = 0; static final byte UPPER_BOUND = 1; static final byte FREE = 2; byte[] alpha_status; // LOWER_BOUND, UPPER_BOUND, FREE double[] alpha; QMatrix Q; double[] QD; double eps; double Cp,Cn; double[] p; int[] active_set; double[] G_bar; // gradient, if we treat free variables as 0 int l; boolean unshrink; // XXX static final double INF = java.lang.Double.POSITIVE_INFINITY; double get_C(int i) { return (y[i] > 0)? Cp : Cn; } void update_alpha_status(int i) { if(alpha[i] >= get_C(i)) alpha_status[i] = UPPER_BOUND; else if(alpha[i] <= 0) alpha_status[i] = LOWER_BOUND; else alpha_status[i] = FREE; } boolean is_upper_bound(int i) { return alpha_status[i] == UPPER_BOUND; } boolean is_lower_bound(int i) { return alpha_status[i] == LOWER_BOUND; } boolean is_free(int i) { return alpha_status[i] == FREE; } // java: information about solution except alpha, // because we cannot return multiple values otherwise... static class SolutionInfo { double obj; double rho; double upper_bound_p; double upper_bound_n; double r; // for Solver_NU } void swap_index(int i, int j) { Q.swap_index(i,j); do {byte a=y[i]; y[i]=y[j]; y[j]=a;} while(false); do {double a=G[i]; G[i]=G[j]; G[j]=a;} while(false); do {byte a=alpha_status[i]; alpha_status[i]=alpha_status[j]; alpha_status[j]=a;} while(false); do {double a=alpha[i]; alpha[i]=alpha[j]; alpha[j]=a;} while(false); do {double a=p[i]; p[i]=p[j]; p[j]=a;} while(false); do {int a=active_set[i]; active_set[i]=active_set[j]; active_set[j]=a;} while(false); do {double a=G_bar[i]; G_bar[i]=G_bar[j]; G_bar[j]=a;} while(false); } void reconstruct_gradient() { // reconstruct inactive elements of G from G_bar and free variables if(active_size == l) return; int i,j; int nr_free = 0; for(j=active_size;j<l;j++) G[j] = G_bar[j] + p[j]; for(j=0;j<active_size;j++) if(is_free(j)) nr_free++; if(2*nr_free < active_size) svm.info("\nWARNING: using -h 0 may be faster\n"); if (nr_free*l > 2*active_size*(l-active_size)) { for(i=active_size;i<l;i++) { float[] Q_i = Q.get_Q(i,active_size); for(j=0;j<active_size;j++) if(is_free(j)) G[i] += alpha[j] * Q_i[j]; } } else { for(i=0;i<active_size;i++) if(is_free(i)) { float[] Q_i = Q.get_Q(i,l); double alpha_i = alpha[i]; for(j=active_size;j<l;j++) G[j] += alpha_i * Q_i[j]; } } } void Solve(int l, QMatrix Q, double[] p_, byte[] y_, double[] alpha_, double Cp, double Cn, double eps, SolutionInfo si, int shrinking) { this.l = l; this.Q = Q; QD = Q.get_QD(); p = (double[])p_.clone(); y = (byte[])y_.clone(); alpha = (double[])alpha_.clone(); this.Cp = Cp; this.Cn = Cn; this.eps = eps; this.unshrink = false; // initialize alpha_status { alpha_status = new byte[l]; for(int i=0;i<l;i++) update_alpha_status(i); } // initialize active set (for shrinking) { active_set = new int[l]; for(int i=0;i<l;i++) active_set[i] = i; active_size = l; } // initialize gradient { G = new double[l]; G_bar = new double[l]; int i; for(i=0;i<l;i++) { G[i] = p[i]; G_bar[i] = 0; } for(i=0;i<l;i++) if(!is_lower_bound(i)) { float[] Q_i = Q.get_Q(i,l); double alpha_i = alpha[i]; int j; for(j=0;j<l;j++) G[j] += alpha_i*Q_i[j]; if(is_upper_bound(i)) for(j=0;j<l;j++) G_bar[j] += get_C(i) * Q_i[j]; } } // optimization step int iter = 0; int max_iter = Math.max(10000000, l>Integer.MAX_VALUE/100 ? Integer.MAX_VALUE : 100*l); int counter = Math.min(l,1000)+1; int[] working_set = new int[2]; while(iter < max_iter) { // show progress and do shrinking if(--counter == 0) { counter = Math.min(l,1000); if(shrinking!=0) do_shrinking(); svm.info("."); } if(select_working_set(working_set)!=0) { // reconstruct the whole gradient reconstruct_gradient(); // reset active set size and check active_size = l; svm.info("*"); if(select_working_set(working_set)!=0) break; else counter = 1; // do shrinking next iteration } int i = working_set[0]; int j = working_set[1]; ++iter; // update alpha[i] and alpha[j], handle bounds carefully float[] Q_i = Q.get_Q(i,active_size); float[] Q_j = Q.get_Q(j,active_size); double C_i = get_C(i); double C_j = get_C(j); double old_alpha_i = alpha[i]; double old_alpha_j = alpha[j]; if(y[i]!=y[j]) { double quad_coef = QD[i]+QD[j]+2*Q_i[j]; if (quad_coef <= 0) quad_coef = 1e-12; double delta = (-G[i]-G[j])/quad_coef; double diff = alpha[i] - alpha[j]; alpha[i] += delta; alpha[j] += delta; if(diff > 0) { if(alpha[j] < 0) { alpha[j] = 0; alpha[i] = diff; } } else { if(alpha[i] < 0) { alpha[i] = 0; alpha[j] = -diff; } } if(diff > C_i - C_j) { if(alpha[i] > C_i) { alpha[i] = C_i; alpha[j] = C_i - diff; } } else { if(alpha[j] > C_j) { alpha[j] = C_j; alpha[i] = C_j + diff; } } } else { double quad_coef = QD[i]+QD[j]-2*Q_i[j]; if (quad_coef <= 0) quad_coef = 1e-12; double delta = (G[i]-G[j])/quad_coef; double sum = alpha[i] + alpha[j]; alpha[i] -= delta; alpha[j] += delta; if(sum > C_i) { if(alpha[i] > C_i) { alpha[i] = C_i; alpha[j] = sum - C_i; } } else { if(alpha[j] < 0) { alpha[j] = 0; alpha[i] = sum; } } if(sum > C_j) { if(alpha[j] > C_j) { alpha[j] = C_j; alpha[i] = sum - C_j; } } else { if(alpha[i] < 0) { alpha[i] = 0; alpha[j] = sum; } } } // update G double delta_alpha_i = alpha[i] - old_alpha_i; double delta_alpha_j = alpha[j] - old_alpha_j; for(int k=0;k<active_size;k++) { G[k] += Q_i[k]*delta_alpha_i + Q_j[k]*delta_alpha_j; } // update alpha_status and G_bar { boolean ui = is_upper_bound(i); boolean uj = is_upper_bound(j); update_alpha_status(i); update_alpha_status(j); int k; if(ui != is_upper_bound(i)) { Q_i = Q.get_Q(i,l); if(ui) for(k=0;k<l;k++) G_bar[k] -= C_i * Q_i[k]; else for(k=0;k<l;k++) G_bar[k] += C_i * Q_i[k]; } if(uj != is_upper_bound(j)) { Q_j = Q.get_Q(j,l); if(uj) for(k=0;k<l;k++) G_bar[k] -= C_j * Q_j[k]; else for(k=0;k<l;k++) G_bar[k] += C_j * Q_j[k]; } } } if(iter >= max_iter) { if(active_size < l) { // reconstruct the whole gradient to calculate objective value reconstruct_gradient(); active_size = l; svm.info("*"); } System.err.print("\nWARNING: reaching max number of iterations\n"); } // calculate rho si.rho = calculate_rho(); // calculate objective value { double v = 0; int i; for(i=0;i<l;i++) v += alpha[i] * (G[i] + p[i]); si.obj = v/2; } // put back the solution { for(int i=0;i<l;i++) alpha_[active_set[i]] = alpha[i]; } si.upper_bound_p = Cp; si.upper_bound_n = Cn; svm.info("\noptimization finished, #iter = "+iter+"\n"); } // return 1 if already optimal, return 0 otherwise int select_working_set(int[] working_set) { // return i,j such that // i: maximizes -y_i * grad(f)_i, i in I_up(\alpha) // j: mimimizes the decrease of obj value // (if quadratic coefficeint <= 0, replace it with tau) // -y_j*grad(f)_j < -y_i*grad(f)_i, j in I_low(\alpha) double Gmax = -INF; double Gmax2 = -INF; int Gmax_idx = -1; int Gmin_idx = -1; double obj_diff_min = INF; for(int t=0;t<active_size;t++) if(y[t]==+1) { if(!is_upper_bound(t)) if(-G[t] >= Gmax) { Gmax = -G[t]; Gmax_idx = t; } } else { if(!is_lower_bound(t)) if(G[t] >= Gmax) { Gmax = G[t]; Gmax_idx = t; } } int i = Gmax_idx; float[] Q_i = null; if(i != -1) // null Q_i not accessed: Gmax=-INF if i=-1 Q_i = Q.get_Q(i,active_size); for(int j=0;j<active_size;j++) { if(y[j]==+1) { if (!is_lower_bound(j)) { double grad_diff=Gmax+G[j]; if (G[j] >= Gmax2) Gmax2 = G[j]; if (grad_diff > 0) { double obj_diff; double quad_coef = QD[i]+QD[j]-2.0*y[i]*Q_i[j]; if (quad_coef > 0) obj_diff = -(grad_diff*grad_diff)/quad_coef; else obj_diff = -(grad_diff*grad_diff)/1e-12; if (obj_diff <= obj_diff_min) { Gmin_idx=j; obj_diff_min = obj_diff; } } } } else { if (!is_upper_bound(j)) { double grad_diff= Gmax-G[j]; if (-G[j] >= Gmax2) Gmax2 = -G[j]; if (grad_diff > 0) { double obj_diff; double quad_coef = QD[i]+QD[j]+2.0*y[i]*Q_i[j]; if (quad_coef > 0) obj_diff = -(grad_diff*grad_diff)/quad_coef; else obj_diff = -(grad_diff*grad_diff)/1e-12; if (obj_diff <= obj_diff_min) { Gmin_idx=j; obj_diff_min = obj_diff; } } } } } if(Gmax+Gmax2 < eps) return 1; working_set[0] = Gmax_idx; working_set[1] = Gmin_idx; return 0; } private boolean be_shrunk(int i, double Gmax1, double Gmax2) { if(is_upper_bound(i)) { if(y[i]==+1) return(-G[i] > Gmax1); else return(-G[i] > Gmax2); } else if(is_lower_bound(i)) { if(y[i]==+1) return(G[i] > Gmax2); else return(G[i] > Gmax1); } else return(false); } void do_shrinking() { int i; double Gmax1 = -INF; // max { -y_i * grad(f)_i | i in I_up(\alpha) } double Gmax2 = -INF; // max { y_i * grad(f)_i | i in I_low(\alpha) } // find maximal violating pair first for(i=0;i<active_size;i++) { if(y[i]==+1) { if(!is_upper_bound(i)) { if(-G[i] >= Gmax1) Gmax1 = -G[i]; } if(!is_lower_bound(i)) { if(G[i] >= Gmax2) Gmax2 = G[i]; } } else { if(!is_upper_bound(i)) { if(-G[i] >= Gmax2) Gmax2 = -G[i]; } if(!is_lower_bound(i)) { if(G[i] >= Gmax1) Gmax1 = G[i]; } } } if(unshrink == false && Gmax1 + Gmax2 <= eps*10) { unshrink = true; reconstruct_gradient(); active_size = l; } for(i=0;i<active_size;i++) if (be_shrunk(i, Gmax1, Gmax2)) { active_size while (active_size > i) { if (!be_shrunk(active_size, Gmax1, Gmax2)) { swap_index(i,active_size); break; } active_size } } } double calculate_rho() { double r; int nr_free = 0; double ub = INF, lb = -INF, sum_free = 0; for(int i=0;i<active_size;i++) { double yG = y[i]*G[i]; if(is_lower_bound(i)) { if(y[i] > 0) ub = Math.min(ub,yG); else lb = Math.max(lb,yG); } else if(is_upper_bound(i)) { if(y[i] < 0) ub = Math.min(ub,yG); else lb = Math.max(lb,yG); } else { ++nr_free; sum_free += yG; } } if(nr_free>0) r = sum_free/nr_free; else r = (ub+lb)/2; return r; } } // Solver for nu-svm classification and regression // additional constraint: e^T \alpha = constant final class Solver_NU extends Solver { private SolutionInfo si; void Solve(int l, QMatrix Q, double[] p, byte[] y, double[] alpha, double Cp, double Cn, double eps, SolutionInfo si, int shrinking) { this.si = si; super.Solve(l,Q,p,y,alpha,Cp,Cn,eps,si,shrinking); } // return 1 if already optimal, return 0 otherwise int select_working_set(int[] working_set) { // return i,j such that y_i = y_j and // i: maximizes -y_i * grad(f)_i, i in I_up(\alpha) // j: minimizes the decrease of obj value // (if quadratic coefficeint <= 0, replace it with tau) // -y_j*grad(f)_j < -y_i*grad(f)_i, j in I_low(\alpha) double Gmaxp = -INF; double Gmaxp2 = -INF; int Gmaxp_idx = -1; double Gmaxn = -INF; double Gmaxn2 = -INF; int Gmaxn_idx = -1; int Gmin_idx = -1; double obj_diff_min = INF; for(int t=0;t<active_size;t++) if(y[t]==+1) { if(!is_upper_bound(t)) if(-G[t] >= Gmaxp) { Gmaxp = -G[t]; Gmaxp_idx = t; } } else { if(!is_lower_bound(t)) if(G[t] >= Gmaxn) { Gmaxn = G[t]; Gmaxn_idx = t; } } int ip = Gmaxp_idx; int in = Gmaxn_idx; float[] Q_ip = null; float[] Q_in = null; if(ip != -1) // null Q_ip not accessed: Gmaxp=-INF if ip=-1 Q_ip = Q.get_Q(ip,active_size); if(in != -1) Q_in = Q.get_Q(in,active_size); for(int j=0;j<active_size;j++) { if(y[j]==+1) { if (!is_lower_bound(j)) { double grad_diff=Gmaxp+G[j]; if (G[j] >= Gmaxp2) Gmaxp2 = G[j]; if (grad_diff > 0) { double obj_diff; double quad_coef = QD[ip]+QD[j]-2*Q_ip[j]; if (quad_coef > 0) obj_diff = -(grad_diff*grad_diff)/quad_coef; else obj_diff = -(grad_diff*grad_diff)/1e-12; if (obj_diff <= obj_diff_min) { Gmin_idx=j; obj_diff_min = obj_diff; } } } } else { if (!is_upper_bound(j)) { double grad_diff=Gmaxn-G[j]; if (-G[j] >= Gmaxn2) Gmaxn2 = -G[j]; if (grad_diff > 0) { double obj_diff; double quad_coef = QD[in]+QD[j]-2*Q_in[j]; if (quad_coef > 0) obj_diff = -(grad_diff*grad_diff)/quad_coef; else obj_diff = -(grad_diff*grad_diff)/1e-12; if (obj_diff <= obj_diff_min) { Gmin_idx=j; obj_diff_min = obj_diff; } } } } } if(Math.max(Gmaxp+Gmaxp2,Gmaxn+Gmaxn2) < eps) return 1; if(y[Gmin_idx] == +1) working_set[0] = Gmaxp_idx; else working_set[0] = Gmaxn_idx; working_set[1] = Gmin_idx; return 0; } private boolean be_shrunk(int i, double Gmax1, double Gmax2, double Gmax3, double Gmax4) { if(is_upper_bound(i)) { if(y[i]==+1) return(-G[i] > Gmax1); else return(-G[i] > Gmax4); } else if(is_lower_bound(i)) { if(y[i]==+1) return(G[i] > Gmax2); else return(G[i] > Gmax3); } else return(false); } void do_shrinking() { double Gmax1 = -INF; // max { -y_i * grad(f)_i | y_i = +1, i in I_up(\alpha) } double Gmax2 = -INF; // max { y_i * grad(f)_i | y_i = +1, i in I_low(\alpha) } double Gmax3 = -INF; // max { -y_i * grad(f)_i | y_i = -1, i in I_up(\alpha) } double Gmax4 = -INF; // max { y_i * grad(f)_i | y_i = -1, i in I_low(\alpha) } // find maximal violating pair first int i; for(i=0;i<active_size;i++) { if(!is_upper_bound(i)) { if(y[i]==+1) { if(-G[i] > Gmax1) Gmax1 = -G[i]; } else if(-G[i] > Gmax4) Gmax4 = -G[i]; } if(!is_lower_bound(i)) { if(y[i]==+1) { if(G[i] > Gmax2) Gmax2 = G[i]; } else if(G[i] > Gmax3) Gmax3 = G[i]; } } if(unshrink == false && Math.max(Gmax1+Gmax2,Gmax3+Gmax4) <= eps*10) { unshrink = true; reconstruct_gradient(); active_size = l; } for(i=0;i<active_size;i++) if (be_shrunk(i, Gmax1, Gmax2, Gmax3, Gmax4)) { active_size while (active_size > i) { if (!be_shrunk(active_size, Gmax1, Gmax2, Gmax3, Gmax4)) { swap_index(i,active_size); break; } active_size } } } double calculate_rho() { int nr_free1 = 0,nr_free2 = 0; double ub1 = INF, ub2 = INF; double lb1 = -INF, lb2 = -INF; double sum_free1 = 0, sum_free2 = 0; for(int i=0;i<active_size;i++) { if(y[i]==+1) { if(is_lower_bound(i)) ub1 = Math.min(ub1,G[i]); else if(is_upper_bound(i)) lb1 = Math.max(lb1,G[i]); else { ++nr_free1; sum_free1 += G[i]; } } else { if(is_lower_bound(i)) ub2 = Math.min(ub2,G[i]); else if(is_upper_bound(i)) lb2 = Math.max(lb2,G[i]); else { ++nr_free2; sum_free2 += G[i]; } } } double r1,r2; if(nr_free1 > 0) r1 = sum_free1/nr_free1; else r1 = (ub1+lb1)/2; if(nr_free2 > 0) r2 = sum_free2/nr_free2; else r2 = (ub2+lb2)/2; si.r = (r1+r2)/2; return (r1-r2)/2; } } // Q matrices for various formulations class SVC_Q extends Kernel { private final byte[] y; private final Cache cache; private final double[] QD; SVC_Q(svm_problem prob, svm_parameter param, byte[] y_) { super(prob.l, prob.x, param); y = (byte[])y_.clone(); cache = new Cache(prob.l,(long)(param.cache_size*(1<<20))); QD = new double[prob.l]; for(int i=0;i<prob.l;i++) QD[i] = kernel_function(i,i); } float[] get_Q(int i, int len) { float[][] data = new float[1][]; int start, j; if((start = cache.get_data(i,data,len)) < len) { for(j=start;j<len;j++) data[0][j] = (float)(y[i]*y[j]*kernel_function(i,j)); } return data[0]; } double[] get_QD() { return QD; } void swap_index(int i, int j) { cache.swap_index(i,j); super.swap_index(i,j); do {byte a=y[i]; y[i]=y[j]; y[j]=a;} while(false); do {double a=QD[i]; QD[i]=QD[j]; QD[j]=a;} while(false); } } class ONE_CLASS_Q extends Kernel { private final Cache cache; private final double[] QD; ONE_CLASS_Q(svm_problem prob, svm_parameter param) { super(prob.l, prob.x, param); cache = new Cache(prob.l,(long)(param.cache_size*(1<<20))); QD = new double[prob.l]; for(int i=0;i<prob.l;i++) QD[i] = kernel_function(i,i); } float[] get_Q(int i, int len) { float[][] data = new float[1][]; int start, j; if((start = cache.get_data(i,data,len)) < len) { for(j=start;j<len;j++) data[0][j] = (float)kernel_function(i,j); } return data[0]; } double[] get_QD() { return QD; } void swap_index(int i, int j) { cache.swap_index(i,j); super.swap_index(i,j); do {double a=QD[i]; QD[i]=QD[j]; QD[j]=a;} while(false); } } class SVR_Q extends Kernel { private final int l; private final Cache cache; private final byte[] sign; private final int[] index; private int next_buffer; private float[][] buffer; private final double[] QD; SVR_Q(svm_problem prob, svm_parameter param) { super(prob.l, prob.x, param); l = prob.l; cache = new Cache(l,(long)(param.cache_size*(1<<20))); QD = new double[2*l]; sign = new byte[2*l]; index = new int[2*l]; for(int k=0;k<l;k++) { sign[k] = 1; sign[k+l] = -1; index[k] = k; index[k+l] = k; QD[k] = kernel_function(k,k); QD[k+l] = QD[k]; } buffer = new float[2][2*l]; next_buffer = 0; } void swap_index(int i, int j) { do {byte a=sign[i]; sign[i]=sign[j]; sign[j]=a;} while(false); do {int a=index[i]; index[i]=index[j]; index[j]=a;} while(false); do {double a=QD[i]; QD[i]=QD[j]; QD[j]=a;} while(false); } float[] get_Q(int i, int len) { float[][] data = new float[1][]; int j, real_i = index[i]; if(cache.get_data(real_i,data,l) < l) { for(j=0;j<l;j++) data[0][j] = (float)kernel_function(real_i,j); } // reorder and copy float buf[] = buffer[next_buffer]; next_buffer = 1 - next_buffer; byte si = sign[i]; for(j=0;j<len;j++) buf[j] = (float) si * sign[j] * data[0][index[j]]; return buf; } double[] get_QD() { return QD; } } public class svm { // construct and solve various formulations public static final int LIBSVM_VERSION=320; public static final Random rand = new Random(); private static svm_print_interface svm_print_stdout = new svm_print_interface() { public void print(String s) { System.out.print(s); System.out.flush(); } }; private static svm_print_interface svm_print_string = svm_print_stdout; static void info(String s) { svm_print_string.print(s); } private static void solve_c_svc(svm_problem prob, svm_parameter param, double[] alpha, Solver.SolutionInfo si, double Cp, double Cn) { int l = prob.l; double[] minus_ones = new double[l]; byte[] y = new byte[l]; int i; for(i=0;i<l;i++) { alpha[i] = 0; minus_ones[i] = -1; if(prob.y[i] > 0) y[i] = +1; else y[i] = -1; } Solver s = new Solver(); s.Solve(l, new SVC_Q(prob,param,y), minus_ones, y, alpha, Cp, Cn, param.eps, si, param.shrinking); double sum_alpha=0; for(i=0;i<l;i++) sum_alpha += alpha[i]; if (Cp==Cn) svm.info("nu = "+sum_alpha/(Cp*prob.l)+"\n"); for(i=0;i<l;i++) alpha[i] *= y[i]; } private static void solve_nu_svc(svm_problem prob, svm_parameter param, double[] alpha, Solver.SolutionInfo si) { int i; int l = prob.l; double nu = param.nu; byte[] y = new byte[l]; for(i=0;i<l;i++) if(prob.y[i]>0) y[i] = +1; else y[i] = -1; double sum_pos = nu*l/2; double sum_neg = nu*l/2; for(i=0;i<l;i++) if(y[i] == +1) { alpha[i] = Math.min(1.0,sum_pos); sum_pos -= alpha[i]; } else { alpha[i] = Math.min(1.0,sum_neg); sum_neg -= alpha[i]; } double[] zeros = new double[l]; for(i=0;i<l;i++) zeros[i] = 0; Solver_NU s = new Solver_NU(); s.Solve(l, new SVC_Q(prob,param,y), zeros, y, alpha, 1.0, 1.0, param.eps, si, param.shrinking); double r = si.r; svm.info("C = "+1/r+"\n"); for(i=0;i<l;i++) alpha[i] *= y[i]/r; si.rho /= r; si.obj /= (r*r); si.upper_bound_p = 1/r; si.upper_bound_n = 1/r; } private static void solve_one_class(svm_problem prob, svm_parameter param, double[] alpha, Solver.SolutionInfo si) { int l = prob.l; double[] zeros = new double[l]; byte[] ones = new byte[l]; int i; int n = (int)(param.nu*prob.l); // # of alpha's at upper bound for(i=0;i<n;i++) alpha[i] = 1; if(n<prob.l) alpha[n] = param.nu * prob.l - n; for(i=n+1;i<l;i++) alpha[i] = 0; for(i=0;i<l;i++) { zeros[i] = 0; ones[i] = 1; } Solver s = new Solver(); s.Solve(l, new ONE_CLASS_Q(prob,param), zeros, ones, alpha, 1.0, 1.0, param.eps, si, param.shrinking); } private static void solve_epsilon_svr(svm_problem prob, svm_parameter param, double[] alpha, Solver.SolutionInfo si) { int l = prob.l; double[] alpha2 = new double[2*l]; double[] linear_term = new double[2*l]; byte[] y = new byte[2*l]; int i; for(i=0;i<l;i++) { alpha2[i] = 0; linear_term[i] = param.p - prob.y[i]; y[i] = 1; alpha2[i+l] = 0; linear_term[i+l] = param.p + prob.y[i]; y[i+l] = -1; } Solver s = new Solver(); s.Solve(2*l, new SVR_Q(prob,param), linear_term, y, alpha2, param.C, param.C, param.eps, si, param.shrinking); double sum_alpha = 0; for(i=0;i<l;i++) { alpha[i] = alpha2[i] - alpha2[i+l]; sum_alpha += Math.abs(alpha[i]); } svm.info("nu = "+sum_alpha/(param.C*l)+"\n"); } private static void solve_nu_svr(svm_problem prob, svm_parameter param, double[] alpha, Solver.SolutionInfo si) { int l = prob.l; double C = param.C; double[] alpha2 = new double[2*l]; double[] linear_term = new double[2*l]; byte[] y = new byte[2*l]; int i; double sum = C * param.nu * l / 2; for(i=0;i<l;i++) { alpha2[i] = alpha2[i+l] = Math.min(sum,C); sum -= alpha2[i]; linear_term[i] = - prob.y[i]; y[i] = 1; linear_term[i+l] = prob.y[i]; y[i+l] = -1; } Solver_NU s = new Solver_NU(); s.Solve(2*l, new SVR_Q(prob,param), linear_term, y, alpha2, C, C, param.eps, si, param.shrinking); svm.info("epsilon = "+(-si.r)+"\n"); for(i=0;i<l;i++) alpha[i] = alpha2[i] - alpha2[i+l]; } // decision_function static class decision_function { double[] alpha; double rho; }; static decision_function svm_train_one( svm_problem prob, svm_parameter param, double Cp, double Cn) { double[] alpha = new double[prob.l]; Solver.SolutionInfo si = new Solver.SolutionInfo(); switch(param.svm_type) { case svm_parameter.C_SVC: solve_c_svc(prob,param,alpha,si,Cp,Cn); break; case svm_parameter.NU_SVC: solve_nu_svc(prob,param,alpha,si); break; case svm_parameter.ONE_CLASS: solve_one_class(prob,param,alpha,si); break; case svm_parameter.EPSILON_SVR: solve_epsilon_svr(prob,param,alpha,si); break; case svm_parameter.NU_SVR: solve_nu_svr(prob,param,alpha,si); break; } svm.info("obj = "+si.obj+", rho = "+si.rho+"\n"); // output SVs int nSV = 0; int nBSV = 0; for(int i=0;i<prob.l;i++) { if(Math.abs(alpha[i]) > 0) { ++nSV; if(prob.y[i] > 0) { if(Math.abs(alpha[i]) >= si.upper_bound_p) ++nBSV; } else { if(Math.abs(alpha[i]) >= si.upper_bound_n) ++nBSV; } } } svm.info("nSV = "+nSV+", nBSV = "+nBSV+"\n"); decision_function f = new decision_function(); f.alpha = alpha; f.rho = si.rho; return f; } // Platt's binary SVM Probablistic Output: an improvement from Lin et al. private static void sigmoid_train(int l, double[] dec_values, double[] labels, double[] probAB) { double A, B; double prior1=0, prior0 = 0; int i; for (i=0;i<l;i++) if (labels[i] > 0) prior1+=1; else prior0+=1; int max_iter=100; // Maximal number of iterations double min_step=1e-10; // Minimal step taken in line search double sigma=1e-12; // For numerically strict PD of Hessian double eps=1e-5; double hiTarget=(prior1+1.0)/(prior1+2.0); double loTarget=1/(prior0+2.0); double[] t= new double[l]; double fApB,p,q,h11,h22,h21,g1,g2,det,dA,dB,gd,stepsize; double newA,newB,newf,d1,d2; int iter; // Initial Point and Initial Fun Value A=0.0; B=Math.log((prior0+1.0)/(prior1+1.0)); double fval = 0.0; for (i=0;i<l;i++) { if (labels[i]>0) t[i]=hiTarget; else t[i]=loTarget; fApB = dec_values[i]*A+B; if (fApB>=0) fval += t[i]*fApB + Math.log(1+Math.exp(-fApB)); else fval += (t[i] - 1)*fApB +Math.log(1+Math.exp(fApB)); } for (iter=0;iter<max_iter;iter++) { // Update Gradient and Hessian (use H' = H + sigma I) h11=sigma; // numerically ensures strict PD h22=sigma; h21=0.0;g1=0.0;g2=0.0; for (i=0;i<l;i++) { fApB = dec_values[i]*A+B; if (fApB >= 0) { p=Math.exp(-fApB)/(1.0+Math.exp(-fApB)); q=1.0/(1.0+Math.exp(-fApB)); } else { p=1.0/(1.0+Math.exp(fApB)); q=Math.exp(fApB)/(1.0+Math.exp(fApB)); } d2=p*q; h11+=dec_values[i]*dec_values[i]*d2; h22+=d2; h21+=dec_values[i]*d2; d1=t[i]-p; g1+=dec_values[i]*d1; g2+=d1; } // Stopping Criteria if (Math.abs(g1)<eps && Math.abs(g2)<eps) break; // Finding Newton direction: -inv(H') * g det=h11*h22-h21*h21; dA=-(h22*g1 - h21 * g2) / det; dB=-(-h21*g1+ h11 * g2) / det; gd=g1*dA+g2*dB; stepsize = 1; // Line Search while (stepsize >= min_step) { newA = A + stepsize * dA; newB = B + stepsize * dB; // New function value newf = 0.0; for (i=0;i<l;i++) { fApB = dec_values[i]*newA+newB; if (fApB >= 0) newf += t[i]*fApB + Math.log(1+Math.exp(-fApB)); else newf += (t[i] - 1)*fApB +Math.log(1+Math.exp(fApB)); } // Check sufficient decrease if (newf<fval+0.0001*stepsize*gd) { A=newA;B=newB;fval=newf; break; } else stepsize = stepsize / 2.0; } if (stepsize < min_step) { svm.info("Line search fails in two-class probability estimates\n"); break; } } if (iter>=max_iter) svm.info("Reaching maximal iterations in two-class probability estimates\n"); probAB[0]=A;probAB[1]=B; } private static double sigmoid_predict(double decision_value, double A, double B) { double fApB = decision_value*A+B; if (fApB >= 0) return Math.exp(-fApB)/(1.0+Math.exp(-fApB)); else return 1.0/(1+Math.exp(fApB)) ; } // Method 2 from the multiclass_prob paper by Wu, Lin, and Weng private static void multiclass_probability(int k, double[][] r, double[] p) { int t,j; int iter = 0, max_iter=Math.max(100,k); double[][] Q=new double[k][k]; double[] Qp=new double[k]; double pQp, eps=0.005/k; for (t=0;t<k;t++) { p[t]=1.0/k; // Valid if k = 1 Q[t][t]=0; for (j=0;j<t;j++) { Q[t][t]+=r[j][t]*r[j][t]; Q[t][j]=Q[j][t]; } for (j=t+1;j<k;j++) { Q[t][t]+=r[j][t]*r[j][t]; Q[t][j]=-r[j][t]*r[t][j]; } } for (iter=0;iter<max_iter;iter++) { // stopping condition, recalculate QP,pQP for numerical accuracy pQp=0; for (t=0;t<k;t++) { Qp[t]=0; for (j=0;j<k;j++) Qp[t]+=Q[t][j]*p[j]; pQp+=p[t]*Qp[t]; } double max_error=0; for (t=0;t<k;t++) { double error=Math.abs(Qp[t]-pQp); if (error>max_error) max_error=error; } if (max_error<eps) break; for (t=0;t<k;t++) { double diff=(-Qp[t]+pQp)/Q[t][t]; p[t]+=diff; pQp=(pQp+diff*(diff*Q[t][t]+2*Qp[t]))/(1+diff)/(1+diff); for (j=0;j<k;j++) { Qp[j]=(Qp[j]+diff*Q[t][j])/(1+diff); p[j]/=(1+diff); } } } if (iter>=max_iter) svm.info("Exceeds max_iter in multiclass_prob\n"); } // Cross-validation decision values for probability estimates private static void svm_binary_svc_probability(svm_problem prob, svm_parameter param, double Cp, double Cn, double[] probAB) { int i; int nr_fold = 5; int[] perm = new int[prob.l]; double[] dec_values = new double[prob.l]; // random shuffle for(i=0;i<prob.l;i++) perm[i]=i; for(i=0;i<prob.l;i++) { int j = i+rand.nextInt(prob.l-i); do {int a=perm[i]; perm[i]=perm[j]; perm[j]=a;} while(false); } for(i=0;i<nr_fold;i++) { int begin = i*prob.l/nr_fold; int end = (i+1)*prob.l/nr_fold; int j,k; svm_problem subprob = new svm_problem(); subprob.l = prob.l-(end-begin); subprob.x = new svm_node[subprob.l][]; subprob.y = new double[subprob.l]; k=0; for(j=0;j<begin;j++) { subprob.x[k] = prob.x[perm[j]]; subprob.y[k] = prob.y[perm[j]]; ++k; } for(j=end;j<prob.l;j++) { subprob.x[k] = prob.x[perm[j]]; subprob.y[k] = prob.y[perm[j]]; ++k; } int p_count=0,n_count=0; for(j=0;j<k;j++) if(subprob.y[j]>0) p_count++; else n_count++; if(p_count==0 && n_count==0) for(j=begin;j<end;j++) dec_values[perm[j]] = 0; else if(p_count > 0 && n_count == 0) for(j=begin;j<end;j++) dec_values[perm[j]] = 1; else if(p_count == 0 && n_count > 0) for(j=begin;j<end;j++) dec_values[perm[j]] = -1; else { svm_parameter subparam = (svm_parameter)param.clone(); subparam.probability=0; subparam.C=1.0; subparam.nr_weight=2; subparam.weight_label = new int[2]; subparam.weight = new double[2]; subparam.weight_label[0]=+1; subparam.weight_label[1]=-1; subparam.weight[0]=Cp; subparam.weight[1]=Cn; svm_model submodel = svm_train(subprob,subparam); for(j=begin;j<end;j++) { double[] dec_value=new double[1]; svm_predict_values(submodel,prob.x[perm[j]],dec_value); dec_values[perm[j]]=dec_value[0]; // ensure +1 -1 order; reason not using CV subroutine dec_values[perm[j]] *= submodel.label[0]; } } } sigmoid_train(prob.l,dec_values,prob.y,probAB); } // Return parameter of a Laplace distribution private static double svm_svr_probability(svm_problem prob, svm_parameter param) { int i; int nr_fold = 5; double[] ymv = new double[prob.l]; double mae = 0; svm_parameter newparam = (svm_parameter)param.clone(); newparam.probability = 0; svm_cross_validation(prob,newparam,nr_fold,ymv); for(i=0;i<prob.l;i++) { ymv[i]=prob.y[i]-ymv[i]; mae += Math.abs(ymv[i]); } mae /= prob.l; double std=Math.sqrt(2*mae*mae); int count=0; mae=0; for(i=0;i<prob.l;i++) if (Math.abs(ymv[i]) > 5*std) count=count+1; else mae+=Math.abs(ymv[i]); mae /= (prob.l-count); svm.info("Prob. model for test data: target value = predicted value + z,\nz: Laplace distribution e^(-|z|/sigma)/(2sigma),sigma="+mae+"\n"); return mae; } // label: label name, start: begin of each class, count: #data of classes, perm: indices to the original data // perm, length l, must be allocated before calling this subroutine private static void svm_group_classes(svm_problem prob, int[] nr_class_ret, int[][] label_ret, int[][] start_ret, int[][] count_ret, int[] perm) { int l = prob.l; int max_nr_class = 16; int nr_class = 0; int[] label = new int[max_nr_class]; int[] count = new int[max_nr_class]; int[] data_label = new int[l]; int i; for(i=0;i<l;i++) { int this_label = (int)(prob.y[i]); int j; for(j=0;j<nr_class;j++) { if(this_label == label[j]) { ++count[j]; break; } } data_label[i] = j; if(j == nr_class) { if(nr_class == max_nr_class) { max_nr_class *= 2; int[] new_data = new int[max_nr_class]; System.arraycopy(label,0,new_data,0,label.length); label = new_data; new_data = new int[max_nr_class]; System.arraycopy(count,0,new_data,0,count.length); count = new_data; } label[nr_class] = this_label; count[nr_class] = 1; ++nr_class; } } // Labels are ordered by their first occurrence in the training set. // However, for two-class sets with -1/+1 labels and -1 appears first, // we swap labels to ensure that internally the binary SVM has positive data corresponding to the +1 instances. if (nr_class == 2 && label[0] == -1 && label[1] == +1) { do {int a=label[0]; label[0]=label[1]; label[1]=a;} while(false); do {int a=count[0]; count[0]=count[1]; count[1]=a;} while(false); for(i=0;i<l;i++) { if(data_label[i] == 0) data_label[i] = 1; else data_label[i] = 0; } } int[] start = new int[nr_class]; start[0] = 0; for(i=1;i<nr_class;i++) start[i] = start[i-1]+count[i-1]; for(i=0;i<l;i++) { perm[start[data_label[i]]] = i; ++start[data_label[i]]; } start[0] = 0; for(i=1;i<nr_class;i++) start[i] = start[i-1]+count[i-1]; nr_class_ret[0] = nr_class; label_ret[0] = label; start_ret[0] = start; count_ret[0] = count; } // Interface functions public static svm_model svm_train(svm_problem prob, svm_parameter param) { svm_model model = new svm_model(); model.param = param; if(param.svm_type == svm_parameter.ONE_CLASS || param.svm_type == svm_parameter.EPSILON_SVR || param.svm_type == svm_parameter.NU_SVR) { // regression or one-class-svm model.nr_class = 2; model.label = null; model.nSV = null; model.probA = null; model.probB = null; model.sv_coef = new double[1][]; if(param.probability == 1 && (param.svm_type == svm_parameter.EPSILON_SVR || param.svm_type == svm_parameter.NU_SVR)) { model.probA = new double[1]; model.probA[0] = svm_svr_probability(prob,param); } decision_function f = svm_train_one(prob,param,0,0); model.rho = new double[1]; model.rho[0] = f.rho; int nSV = 0; int i; for(i=0;i<prob.l;i++) if(Math.abs(f.alpha[i]) > 0) ++nSV; model.l = nSV; model.SV = new svm_node[nSV][]; model.sv_coef[0] = new double[nSV]; model.sv_indices = new int[nSV]; int j = 0; for(i=0;i<prob.l;i++) if(Math.abs(f.alpha[i]) > 0) { model.SV[j] = prob.x[i]; model.sv_coef[0][j] = f.alpha[i]; model.sv_indices[j] = i+1; ++j; } } else { // classification int l = prob.l; int[] tmp_nr_class = new int[1]; int[][] tmp_label = new int[1][]; int[][] tmp_start = new int[1][]; int[][] tmp_count = new int[1][]; int[] perm = new int[l]; // group training data of the same class svm_group_classes(prob,tmp_nr_class,tmp_label,tmp_start,tmp_count,perm); int nr_class = tmp_nr_class[0]; int[] label = tmp_label[0]; int[] start = tmp_start[0]; int[] count = tmp_count[0]; if(nr_class == 1) svm.info("WARNING: training data in only one class. See README for details.\n"); svm_node[][] x = new svm_node[l][]; int i; for(i=0;i<l;i++) x[i] = prob.x[perm[i]]; // calculate weighted C double[] weighted_C = new double[nr_class]; for(i=0;i<nr_class;i++) weighted_C[i] = param.C; for(i=0;i<param.nr_weight;i++) { int j; for(j=0;j<nr_class;j++) if(param.weight_label[i] == label[j]) break; if(j == nr_class) System.err.print("WARNING: class label "+param.weight_label[i]+" specified in weight is not found\n"); else weighted_C[j] *= param.weight[i]; } // train k*(k-1)/2 models boolean[] nonzero = new boolean[l]; for(i=0;i<l;i++) nonzero[i] = false; decision_function[] f = new decision_function[nr_class*(nr_class-1)/2]; double[] probA=null,probB=null; if (param.probability == 1) { probA=new double[nr_class*(nr_class-1)/2]; probB=new double[nr_class*(nr_class-1)/2]; } int p = 0; for(i=0;i<nr_class;i++) for(int j=i+1;j<nr_class;j++) { svm_problem sub_prob = new svm_problem(); int si = start[i], sj = start[j]; int ci = count[i], cj = count[j]; sub_prob.l = ci+cj; sub_prob.x = new svm_node[sub_prob.l][]; sub_prob.y = new double[sub_prob.l]; int k; for(k=0;k<ci;k++) { sub_prob.x[k] = x[si+k]; sub_prob.y[k] = +1; } for(k=0;k<cj;k++) { sub_prob.x[ci+k] = x[sj+k]; sub_prob.y[ci+k] = -1; } if(param.probability == 1) { double[] probAB=new double[2]; svm_binary_svc_probability(sub_prob,param,weighted_C[i],weighted_C[j],probAB); probA[p]=probAB[0]; probB[p]=probAB[1]; } f[p] = svm_train_one(sub_prob,param,weighted_C[i],weighted_C[j]); for(k=0;k<ci;k++) if(!nonzero[si+k] && Math.abs(f[p].alpha[k]) > 0) nonzero[si+k] = true; for(k=0;k<cj;k++) if(!nonzero[sj+k] && Math.abs(f[p].alpha[ci+k]) > 0) nonzero[sj+k] = true; ++p; } // build output model.nr_class = nr_class; model.label = new int[nr_class]; for(i=0;i<nr_class;i++) model.label[i] = label[i]; model.rho = new double[nr_class*(nr_class-1)/2]; for(i=0;i<nr_class*(nr_class-1)/2;i++) model.rho[i] = f[i].rho; if(param.probability == 1) { model.probA = new double[nr_class*(nr_class-1)/2]; model.probB = new double[nr_class*(nr_class-1)/2]; for(i=0;i<nr_class*(nr_class-1)/2;i++) { model.probA[i] = probA[i]; model.probB[i] = probB[i]; } } else { model.probA=null; model.probB=null; } int nnz = 0; int[] nz_count = new int[nr_class]; model.nSV = new int[nr_class]; for(i=0;i<nr_class;i++) { int nSV = 0; for(int j=0;j<count[i];j++) if(nonzero[start[i]+j]) { ++nSV; ++nnz; } model.nSV[i] = nSV; nz_count[i] = nSV; } svm.info("Total nSV = "+nnz+"\n"); model.l = nnz; model.SV = new svm_node[nnz][]; model.sv_indices = new int[nnz]; p = 0; for(i=0;i<l;i++) if(nonzero[i]) { model.SV[p] = x[i]; model.sv_indices[p++] = perm[i] + 1; } int[] nz_start = new int[nr_class]; nz_start[0] = 0; for(i=1;i<nr_class;i++) nz_start[i] = nz_start[i-1]+nz_count[i-1]; model.sv_coef = new double[nr_class-1][]; for(i=0;i<nr_class-1;i++) model.sv_coef[i] = new double[nnz]; p = 0; for(i=0;i<nr_class;i++) for(int j=i+1;j<nr_class;j++) { // classifier (i,j): coefficients with // i are in sv_coef[j-1][nz_start[i]...], // j are in sv_coef[i][nz_start[j]...] int si = start[i]; int sj = start[j]; int ci = count[i]; int cj = count[j]; int q = nz_start[i]; int k; for(k=0;k<ci;k++) if(nonzero[si+k]) model.sv_coef[j-1][q++] = f[p].alpha[k]; q = nz_start[j]; for(k=0;k<cj;k++) if(nonzero[sj+k]) model.sv_coef[i][q++] = f[p].alpha[ci+k]; ++p; } } return model; } // Stratified cross validation public static void svm_cross_validation(svm_problem prob, svm_parameter param, int nr_fold, double[] target) { int i; int[] fold_start = new int[nr_fold+1]; int l = prob.l; int[] perm = new int[l]; // stratified cv may not give leave-one-out rate // Each class to l folds -> some folds may have zero elements if((param.svm_type == svm_parameter.C_SVC || param.svm_type == svm_parameter.NU_SVC) && nr_fold < l) { int[] tmp_nr_class = new int[1]; int[][] tmp_label = new int[1][]; int[][] tmp_start = new int[1][]; int[][] tmp_count = new int[1][]; svm_group_classes(prob,tmp_nr_class,tmp_label,tmp_start,tmp_count,perm); int nr_class = tmp_nr_class[0]; int[] start = tmp_start[0]; int[] count = tmp_count[0]; // random shuffle and then data grouped by fold using the array perm int[] fold_count = new int[nr_fold]; int c; int[] index = new int[l]; for(i=0;i<l;i++) index[i]=perm[i]; for (c=0; c<nr_class; c++) for(i=0;i<count[c];i++) { int j = i+rand.nextInt(count[c]-i); do {int a=index[start[c]+j]; index[start[c]+j]=index[start[c]+i]; index[start[c]+i]=a;} while(false); } for(i=0;i<nr_fold;i++) { fold_count[i] = 0; for (c=0; c<nr_class;c++) fold_count[i]+=(i+1)*count[c]/nr_fold-i*count[c]/nr_fold; } fold_start[0]=0; for (i=1;i<=nr_fold;i++) fold_start[i] = fold_start[i-1]+fold_count[i-1]; for (c=0; c<nr_class;c++) for(i=0;i<nr_fold;i++) { int begin = start[c]+i*count[c]/nr_fold; int end = start[c]+(i+1)*count[c]/nr_fold; for(int j=begin;j<end;j++) { perm[fold_start[i]] = index[j]; fold_start[i]++; } } fold_start[0]=0; for (i=1;i<=nr_fold;i++) fold_start[i] = fold_start[i-1]+fold_count[i-1]; } else { for(i=0;i<l;i++) perm[i]=i; for(i=0;i<l;i++) { int j = i+rand.nextInt(l-i); do {int a=perm[i]; perm[i]=perm[j]; perm[j]=a;} while(false); } for(i=0;i<=nr_fold;i++) fold_start[i]=i*l/nr_fold; } for(i=0;i<nr_fold;i++) { int begin = fold_start[i]; int end = fold_start[i+1]; int j,k; svm_problem subprob = new svm_problem(); subprob.l = l-(end-begin); subprob.x = new svm_node[subprob.l][]; subprob.y = new double[subprob.l]; k=0; for(j=0;j<begin;j++) { subprob.x[k] = prob.x[perm[j]]; subprob.y[k] = prob.y[perm[j]]; ++k; } for(j=end;j<l;j++) { subprob.x[k] = prob.x[perm[j]]; subprob.y[k] = prob.y[perm[j]]; ++k; } svm_model submodel = svm_train(subprob,param); if(param.probability==1 && (param.svm_type == svm_parameter.C_SVC || param.svm_type == svm_parameter.NU_SVC)) { double[] prob_estimates= new double[svm_get_nr_class(submodel)]; for(j=begin;j<end;j++) target[perm[j]] = svm_predict_probability(submodel,prob.x[perm[j]],prob_estimates); } else for(j=begin;j<end;j++) target[perm[j]] = svm_predict(submodel,prob.x[perm[j]]); } } public static int svm_get_svm_type(svm_model model) { return model.param.svm_type; } public static int svm_get_nr_class(svm_model model) { return model.nr_class; } public static void svm_get_labels(svm_model model, int[] label) { if (model.label != null) for(int i=0;i<model.nr_class;i++) label[i] = model.label[i]; } public static void svm_get_sv_indices(svm_model model, int[] indices) { if (model.sv_indices != null) for(int i=0;i<model.l;i++) indices[i] = model.sv_indices[i]; } public static int svm_get_nr_sv(svm_model model) { return model.l; } public static double svm_get_svr_probability(svm_model model) { if ((model.param.svm_type == svm_parameter.EPSILON_SVR || model.param.svm_type == svm_parameter.NU_SVR) && model.probA!=null) return model.probA[0]; else { System.err.print("Model doesn't contain information for SVR probability inference\n"); return 0; } } public static double svm_predict_values(svm_model model, svm_node[] x, double[] dec_values) { int i; if(model.param.svm_type == svm_parameter.ONE_CLASS || model.param.svm_type == svm_parameter.EPSILON_SVR || model.param.svm_type == svm_parameter.NU_SVR) { double[] sv_coef = model.sv_coef[0]; double sum = 0; for(i=0;i<model.l;i++) sum += sv_coef[i] * Kernel.k_function(x,model.SV[i],model.param); sum -= model.rho[0]; dec_values[0] = sum; if(model.param.svm_type == svm_parameter.ONE_CLASS) return (sum>0)?1:-1; else return sum; } else { int nr_class = model.nr_class; int l = model.l; double[] kvalue = new double[l]; for(i=0;i<l;i++) kvalue[i] = Kernel.k_function(x,model.SV[i],model.param); int[] start = new int[nr_class]; start[0] = 0; for(i=1;i<nr_class;i++) start[i] = start[i-1]+model.nSV[i-1]; int[] vote = new int[nr_class]; for(i=0;i<nr_class;i++) vote[i] = 0; int p=0; for(i=0;i<nr_class;i++) for(int j=i+1;j<nr_class;j++) { double sum = 0; int si = start[i]; int sj = start[j]; int ci = model.nSV[i]; int cj = model.nSV[j]; int k; double[] coef1 = model.sv_coef[j-1]; double[] coef2 = model.sv_coef[i]; for(k=0;k<ci;k++) sum += coef1[si+k] * kvalue[si+k]; for(k=0;k<cj;k++) sum += coef2[sj+k] * kvalue[sj+k]; sum -= model.rho[p]; dec_values[p] = sum; if(dec_values[p] > 0) ++vote[i]; else ++vote[j]; p++; } int vote_max_idx = 0; for(i=1;i<nr_class;i++) if(vote[i] > vote[vote_max_idx]) vote_max_idx = i; return model.label[vote_max_idx]; } } public static double svm_predict(svm_model model, svm_node[] x) { int nr_class = model.nr_class; double[] dec_values; if(model.param.svm_type == svm_parameter.ONE_CLASS || model.param.svm_type == svm_parameter.EPSILON_SVR || model.param.svm_type == svm_parameter.NU_SVR) dec_values = new double[1]; else dec_values = new double[nr_class*(nr_class-1)/2]; double pred_result = svm_predict_values(model, x, dec_values); return pred_result; } public static double svm_predict_probability(svm_model model, svm_node[] x, double[] prob_estimates) { if ((model.param.svm_type == svm_parameter.C_SVC || model.param.svm_type == svm_parameter.NU_SVC) && model.probA!=null && model.probB!=null) { int i; int nr_class = model.nr_class; double[] dec_values = new double[nr_class*(nr_class-1)/2]; svm_predict_values(model, x, dec_values); double min_prob=1e-7; double[][] pairwise_prob=new double[nr_class][nr_class]; int k=0; for(i=0;i<nr_class;i++) for(int j=i+1;j<nr_class;j++) { pairwise_prob[i][j]=Math.min(Math.max(sigmoid_predict(dec_values[k],model.probA[k],model.probB[k]),min_prob),1-min_prob); pairwise_prob[j][i]=1-pairwise_prob[i][j]; k++; } multiclass_probability(nr_class,pairwise_prob,prob_estimates); int prob_max_idx = 0; for(i=1;i<nr_class;i++) if(prob_estimates[i] > prob_estimates[prob_max_idx]) prob_max_idx = i; return model.label[prob_max_idx]; } else return svm_predict(model, x); } static final String svm_type_table[] = { "c_svc","nu_svc","one_class","epsilon_svr","nu_svr", }; static final String kernel_type_table[]= { "linear","polynomial","rbf","sigmoid","precomputed" }; public static void svm_save_model(String model_file_name, svm_model model) throws IOException { DataOutputStream fp = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(model_file_name))); svm_parameter param = model.param; fp.writeBytes("svm_type "+svm_type_table[param.svm_type]+"\n"); fp.writeBytes("kernel_type "+kernel_type_table[param.kernel_type]+"\n"); if(param.kernel_type == svm_parameter.POLY) fp.writeBytes("degree "+param.degree+"\n"); if(param.kernel_type == svm_parameter.POLY || param.kernel_type == svm_parameter.RBF || param.kernel_type == svm_parameter.SIGMOID) fp.writeBytes("gamma "+param.gamma+"\n"); if(param.kernel_type == svm_parameter.POLY || param.kernel_type == svm_parameter.SIGMOID) fp.writeBytes("coef0 "+param.coef0+"\n"); int nr_class = model.nr_class; int l = model.l; fp.writeBytes("nr_class "+nr_class+"\n"); fp.writeBytes("total_sv "+l+"\n"); { fp.writeBytes("rho"); for(int i=0;i<nr_class*(nr_class-1)/2;i++) fp.writeBytes(" "+model.rho[i]); fp.writeBytes("\n"); } if(model.label != null) { fp.writeBytes("label"); for(int i=0;i<nr_class;i++) fp.writeBytes(" "+model.label[i]); fp.writeBytes("\n"); } if(model.probA != null) // regression has probA only { fp.writeBytes("probA"); for(int i=0;i<nr_class*(nr_class-1)/2;i++) fp.writeBytes(" "+model.probA[i]); fp.writeBytes("\n"); } if(model.probB != null) { fp.writeBytes("probB"); for(int i=0;i<nr_class*(nr_class-1)/2;i++) fp.writeBytes(" "+model.probB[i]); fp.writeBytes("\n"); } if(model.nSV != null) { fp.writeBytes("nr_sv"); for(int i=0;i<nr_class;i++) fp.writeBytes(" "+model.nSV[i]); fp.writeBytes("\n"); } fp.writeBytes("SV\n"); double[][] sv_coef = model.sv_coef; svm_node[][] SV = model.SV; for(int i=0;i<l;i++) { for(int j=0;j<nr_class-1;j++) fp.writeBytes(sv_coef[j][i]+" "); svm_node[] p = SV[i]; if(param.kernel_type == svm_parameter.PRECOMPUTED) fp.writeBytes("0:"+(int)(p[0].value)); else for(int j=0;j<p.length;j++) fp.writeBytes(p[j].index+":"+p[j].value+" "); fp.writeBytes("\n"); } fp.close(); } private static double atof(String s) { return Double.valueOf(s).doubleValue(); } private static int atoi(String s) { return Integer.parseInt(s); } private static boolean read_model_header(BufferedReader fp, svm_model model) { svm_parameter param = new svm_parameter(); model.param = param; try { while(true) { String cmd = fp.readLine(); String arg = cmd.substring(cmd.indexOf(' ')+1); if(cmd.startsWith("svm_type")) { int i; for(i=0;i<svm_type_table.length;i++) { if(arg.indexOf(svm_type_table[i])!=-1) { param.svm_type=i; break; } } if(i == svm_type_table.length) { System.err.print("unknown svm type.\n"); return false; } } else if(cmd.startsWith("kernel_type")) { int i; for(i=0;i<kernel_type_table.length;i++) { if(arg.indexOf(kernel_type_table[i])!=-1) { param.kernel_type=i; break; } } if(i == kernel_type_table.length) { System.err.print("unknown kernel function.\n"); return false; } } else if(cmd.startsWith("degree")) param.degree = atoi(arg); else if(cmd.startsWith("gamma")) param.gamma = atof(arg); else if(cmd.startsWith("coef0")) param.coef0 = atof(arg); else if(cmd.startsWith("nr_class")) model.nr_class = atoi(arg); else if(cmd.startsWith("total_sv")) model.l = atoi(arg); else if(cmd.startsWith("rho")) { int n = model.nr_class * (model.nr_class-1)/2; model.rho = new double[n]; StringTokenizer st = new StringTokenizer(arg); for(int i=0;i<n;i++) model.rho[i] = atof(st.nextToken()); } else if(cmd.startsWith("label")) { int n = model.nr_class; model.label = new int[n]; StringTokenizer st = new StringTokenizer(arg); for(int i=0;i<n;i++) model.label[i] = atoi(st.nextToken()); } else if(cmd.startsWith("probA")) { int n = model.nr_class*(model.nr_class-1)/2; model.probA = new double[n]; StringTokenizer st = new StringTokenizer(arg); for(int i=0;i<n;i++) model.probA[i] = atof(st.nextToken()); } else if(cmd.startsWith("probB")) { int n = model.nr_class*(model.nr_class-1)/2; model.probB = new double[n]; StringTokenizer st = new StringTokenizer(arg); for(int i=0;i<n;i++) model.probB[i] = atof(st.nextToken()); } else if(cmd.startsWith("nr_sv")) { int n = model.nr_class; model.nSV = new int[n]; StringTokenizer st = new StringTokenizer(arg); for(int i=0;i<n;i++) model.nSV[i] = atoi(st.nextToken()); } else if(cmd.startsWith("SV")) { break; } else { System.err.print("unknown text in model file: ["+cmd+"]\n"); return false; } } } catch(Exception e) { return false; } return true; } public static svm_model svm_load_model(String model_file_name) throws IOException { return svm_load_model(new BufferedReader(new FileReader(model_file_name))); } public static svm_model svm_load_model(BufferedReader fp) throws IOException { // read parameters svm_model model = new svm_model(); model.rho = null; model.probA = null; model.probB = null; model.label = null; model.nSV = null; if (read_model_header(fp, model) == false) { System.err.print("ERROR: failed to read model\n"); return null; } // read sv_coef and SV int m = model.nr_class - 1; int l = model.l; model.sv_coef = new double[m][l]; model.SV = new svm_node[l][]; for(int i=0;i<l;i++) { String line = fp.readLine(); StringTokenizer st = new StringTokenizer(line," \t\n\r\f:"); for(int k=0;k<m;k++) model.sv_coef[k][i] = atof(st.nextToken()); int n = st.countTokens()/2; model.SV[i] = new svm_node[n]; for(int j=0;j<n;j++) { model.SV[i][j] = new svm_node(); model.SV[i][j].index = atoi(st.nextToken()); model.SV[i][j].value = atof(st.nextToken()); } } fp.close(); return model; } public static String svm_check_parameter(svm_problem prob, svm_parameter param) { // svm_type int svm_type = param.svm_type; if(svm_type != svm_parameter.C_SVC && svm_type != svm_parameter.NU_SVC && svm_type != svm_parameter.ONE_CLASS && svm_type != svm_parameter.EPSILON_SVR && svm_type != svm_parameter.NU_SVR) return "unknown svm type"; // kernel_type, degree int kernel_type = param.kernel_type; if(kernel_type != svm_parameter.LINEAR && kernel_type != svm_parameter.POLY && kernel_type != svm_parameter.RBF && kernel_type != svm_parameter.SIGMOID && kernel_type != svm_parameter.PRECOMPUTED) return "unknown kernel type"; if(param.gamma < 0) return "gamma < 0"; if(param.degree < 0) return "degree of polynomial kernel < 0"; // cache_size,eps,C,nu,p,shrinking if(param.cache_size <= 0) return "cache_size <= 0"; if(param.eps <= 0) return "eps <= 0"; if(svm_type == svm_parameter.C_SVC || svm_type == svm_parameter.EPSILON_SVR || svm_type == svm_parameter.NU_SVR) if(param.C <= 0) return "C <= 0"; if(svm_type == svm_parameter.NU_SVC || svm_type == svm_parameter.ONE_CLASS || svm_type == svm_parameter.NU_SVR) if(param.nu <= 0 || param.nu > 1) return "nu <= 0 or nu > 1"; if(svm_type == svm_parameter.EPSILON_SVR) if(param.p < 0) return "p < 0"; if(param.shrinking != 0 && param.shrinking != 1) return "shrinking != 0 and shrinking != 1"; if(param.probability != 0 && param.probability != 1) return "probability != 0 and probability != 1"; if(param.probability == 1 && svm_type == svm_parameter.ONE_CLASS) return "one-class SVM probability output not supported yet"; // check whether nu-svc is feasible if(svm_type == svm_parameter.NU_SVC) { int l = prob.l; int max_nr_class = 16; int nr_class = 0; int[] label = new int[max_nr_class]; int[] count = new int[max_nr_class]; int i; for(i=0;i<l;i++) { int this_label = (int)prob.y[i]; int j; for(j=0;j<nr_class;j++) if(this_label == label[j]) { ++count[j]; break; } if(j == nr_class) { if(nr_class == max_nr_class) { max_nr_class *= 2; int[] new_data = new int[max_nr_class]; System.arraycopy(label,0,new_data,0,label.length); label = new_data; new_data = new int[max_nr_class]; System.arraycopy(count,0,new_data,0,count.length); count = new_data; } label[nr_class] = this_label; count[nr_class] = 1; ++nr_class; } } for(i=0;i<nr_class;i++) { int n1 = count[i]; for(int j=i+1;j<nr_class;j++) { int n2 = count[j]; if(param.nu*(n1+n2)/2 > Math.min(n1,n2)) return "specified nu is infeasible"; } } } return null; } public static int svm_check_probability_model(svm_model model) { if (((model.param.svm_type == svm_parameter.C_SVC || model.param.svm_type == svm_parameter.NU_SVC) && model.probA!=null && model.probB!=null) || ((model.param.svm_type == svm_parameter.EPSILON_SVR || model.param.svm_type == svm_parameter.NU_SVR) && model.probA!=null)) return 1; else return 0; } public static void svm_set_print_string_function(svm_print_interface print_func) { if (print_func == null) svm_print_string = svm_print_stdout; else svm_print_string = print_func; } }
package edu.umd.cs.findbugs.ba.jsr305; /** * This is the FindBugs representation of the When value * of a type qualifier. (Corresponding to the * javax.annotation.meta.When enumeration.) * * @author David Hovemeyer * @author Bill Pugh */ public enum When { ASSUME_ALWAYS, ALWAYS, UNKNOWN, MAYBE_NOT, NEVER; // Dataflow lattice: // Always Never // Assume | // always Unknown // Maybe // not private static final When[][] mergeMatrix = { // ASSUME_ MAYBE_ // ALWAYS ALWAYS UNKNOWN NOT NEVER /* ASSUME_ALWAYS */ { ASSUME_ALWAYS, }, /* ALWAYS */ { ASSUME_ALWAYS, ASSUME_ALWAYS, }, /* UNKNOWN */ { MAYBE_NOT, MAYBE_NOT, UNKNOWN, }, /* MAYBE_NOT */ { MAYBE_NOT, MAYBE_NOT, MAYBE_NOT, MAYBE_NOT, }, /* NEVER */ { MAYBE_NOT, MAYBE_NOT, UNKNOWN, MAYBE_NOT, NEVER, }, }; public static When meet(When a, When b) { int aIndex = a.ordinal(); int bIndex = b.ordinal(); if (aIndex < bIndex) { int tmp = aIndex; aIndex = bIndex; bIndex = tmp; } return mergeMatrix[aIndex][bIndex]; } }
package org.pentaho.di.ui.spoon.delegates; import java.util.ArrayList; import java.util.List; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DragSource; import org.eclipse.swt.dnd.DragSourceEvent; import org.eclipse.swt.dnd.DragSourceListener; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeItem; import org.pentaho.di.cluster.ClusterSchema; import org.pentaho.di.cluster.SlaveServer; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.core.dnd.DragAndDropContainer; import org.pentaho.di.core.dnd.XMLTransfer; import org.pentaho.di.job.JobEntryLoader; import org.pentaho.di.job.JobMeta; import org.pentaho.di.job.JobPlugin; import org.pentaho.di.job.entry.JobEntryCopy; import org.pentaho.di.partition.PartitionSchema; import org.pentaho.di.ui.core.ConstUI; import org.pentaho.di.ui.spoon.delegates.SpoonDelegate; import org.pentaho.di.trans.StepLoader; import org.pentaho.di.trans.StepPlugin; import org.pentaho.di.trans.TransHopMeta; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.ui.spoon.Spoon; import org.pentaho.di.ui.spoon.TreeSelection; public class SpoonTreeDelegate extends SpoonDelegate { public SpoonTreeDelegate(Spoon spoon) { super(spoon); } /** * @return The object that is selected in the tree or null if we couldn't * figure it out. (titles etc. == null) */ public TreeSelection[] getTreeObjects(final Tree tree, Tree selectionTree, Tree coreObjectsTree) { List<TreeSelection> objects = new ArrayList<TreeSelection>(); if (selectionTree!=null && !selectionTree.isDisposed() && tree.equals(selectionTree)) { TreeItem[] selection = selectionTree.getSelection(); for (int s = 0; s < selection.length; s++) { TreeItem treeItem = selection[s]; String[] path = ConstUI.getTreeStrings(treeItem); TreeSelection object = null; switch (path.length) { case 0: break; case 1: if (path[0].equals(Spoon.STRING_TRANSFORMATIONS)) // the top level Transformations entry { object = new TreeSelection(path[0], TransMeta.class); } if (path[0].equals(Spoon.STRING_JOBS)) // the top level Jobs entry { object = new TreeSelection(path[0], JobMeta.class); } break; case 2: if (path[0].equals(Spoon.STRING_BUILDING_BLOCKS)) // the top level Transformations entry { if (path[1].equals(Spoon.STRING_TRANS_BASE)) { object = new TreeSelection(path[1], StepPlugin.class); } } if (path[0].equals(Spoon.STRING_TRANSFORMATIONS)) // Transformations title { object = new TreeSelection(path[1], spoon.delegates.trans.getTransformation(path[1])); } if (path[0].equals(Spoon.STRING_JOBS)) // Jobs title { object = new TreeSelection(path[1], spoon.delegates.jobs.getJob(path[1])); } break; case 3: if (path[0].equals(Spoon.STRING_TRANSFORMATIONS)) // Transformations // title { TransMeta transMeta = spoon.delegates.trans.getTransformation(path[1]); if (path[2].equals(Spoon.STRING_CONNECTIONS)) object = new TreeSelection(path[2], DatabaseMeta.class, transMeta); if (path[2].equals(Spoon.STRING_STEPS)) object = new TreeSelection(path[2], StepMeta.class, transMeta); if (path[2].equals(Spoon.STRING_HOPS)) object = new TreeSelection(path[2], TransHopMeta.class, transMeta); if (path[2].equals(Spoon.STRING_PARTITIONS)) object = new TreeSelection(path[2], PartitionSchema.class, transMeta); if (path[2].equals(Spoon.STRING_SLAVES)) object = new TreeSelection(path[2], SlaveServer.class, transMeta); if (path[2].equals(Spoon.STRING_CLUSTERS)) object = new TreeSelection(path[2], ClusterSchema.class, transMeta); } if (path[0].equals(Spoon.STRING_JOBS)) // Jobs title { JobMeta jobMeta = spoon.delegates.jobs.getJob(path[1]); if (path[2].equals(Spoon.STRING_CONNECTIONS)) object = new TreeSelection(path[2], DatabaseMeta.class, jobMeta); if (path[2].equals(Spoon.STRING_JOB_ENTRIES)) object = new TreeSelection(path[2], JobEntryCopy.class, jobMeta); if (path[2].equals(Spoon.STRING_SLAVES)) object = new TreeSelection(path[2], SlaveServer.class, jobMeta); } break; case 4: if (path[0].equals(Spoon.STRING_TRANSFORMATIONS)) // The name of a transformation { TransMeta transMeta = spoon.delegates.trans.getTransformation(path[1]); if (path[2].equals(Spoon.STRING_CONNECTIONS)) object = new TreeSelection(path[3], transMeta.findDatabase(path[3]), transMeta); if (path[2].equals(Spoon.STRING_STEPS)) object = new TreeSelection(path[3], transMeta.findStep(path[3]), transMeta); if (path[2].equals(Spoon.STRING_HOPS)) object = new TreeSelection(path[3], transMeta.findTransHop(path[3]), transMeta); if (path[2].equals(Spoon.STRING_PARTITIONS)) object = new TreeSelection(path[3], transMeta.findPartitionSchema(path[3]), transMeta); if (path[2].equals(Spoon.STRING_SLAVES)) object = new TreeSelection(path[3], transMeta.findSlaveServer(path[3]), transMeta); if (path[2].equals(Spoon.STRING_CLUSTERS)) object = new TreeSelection(path[3], transMeta.findClusterSchema(path[3]), transMeta); } if (path[0].equals(Spoon.STRING_JOBS)) // The name of a job { JobMeta jobMeta = spoon.delegates.jobs.getJob(path[1]); if (jobMeta != null && path[2].equals(Spoon.STRING_CONNECTIONS)) object = new TreeSelection(path[3], jobMeta.findDatabase(path[3]), jobMeta); if (jobMeta != null && path[2].equals(Spoon.STRING_JOB_ENTRIES)) object = new TreeSelection(path[3], jobMeta.findJobEntry(path[3]), jobMeta); if (jobMeta != null && path[2].equals(Spoon.STRING_SLAVES)) object = new TreeSelection(path[3], jobMeta.findSlaveServer(path[3]), jobMeta); } break; case 5: if (path[0].equals(Spoon.STRING_TRANSFORMATIONS)) // The name of a transformation { TransMeta transMeta = spoon.delegates.trans.getTransformation(path[1]); if (transMeta != null && path[2].equals(Spoon.STRING_CLUSTERS)) { ClusterSchema clusterSchema = transMeta.findClusterSchema(path[3]); object = new TreeSelection(path[4], clusterSchema.findSlaveServer(path[4]), clusterSchema, transMeta); } } break; default: break; } if (object != null) { objects.add(object); } } } if (tree!=null && coreObjectsTree!=null && tree.equals(coreObjectsTree)) { TreeItem[] selection = coreObjectsTree.getSelection(); for (int s = 0; s < selection.length; s++) { TreeItem treeItem = selection[s]; String[] path = ConstUI.getTreeStrings(treeItem); TreeSelection object = null; switch (path.length) { case 0: break; case 1: break; // nothing case 2: // Job entries if (path[0].equals(Spoon.STRING_JOB_BASE)) { JobPlugin jobPlugin = JobEntryLoader.getInstance().findJobEntriesWithDescription( path[1]); if (jobPlugin != null) { object = new TreeSelection(path[1], jobPlugin); } else { object = new TreeSelection(path[1], JobPlugin.class); } } break; case 3: // Steps if (path[0].equals(Spoon.STRING_TRANS_BASE)) { object = new TreeSelection(path[2], StepLoader.getInstance().findStepPluginWithDescription(path[2])); } break; default: break; } if (object != null) { objects.add(object); } } } return objects.toArray(new TreeSelection[objects.size()]); } public void addDragSourceToTree(final Tree tree,final Tree selectionTree,final Tree coreObjectsTree) { // Drag & Drop for steps Transfer[] ttypes = new Transfer[] { XMLTransfer.getInstance() }; DragSource ddSource = new DragSource(tree, DND.DROP_MOVE); ddSource.setTransfer(ttypes); ddSource.addDragListener(new DragSourceListener() { public void dragStart(DragSourceEvent event) { TreeSelection[] treeObjects = getTreeObjects(tree,selectionTree,coreObjectsTree); if (treeObjects.length == 0) { event.doit = false; return; } TreeSelection treeObject = treeObjects[0]; Object object = treeObject.getSelection(); TransMeta transMeta = spoon.getActiveTransformation(); // JobMeta jobMeta = spoon.getActiveJob(); if (object instanceof StepMeta || object instanceof StepPlugin || ( object instanceof DatabaseMeta && transMeta!=null) || object instanceof TransHopMeta || object instanceof JobEntryCopy || object instanceof JobPlugin || (object instanceof Class && object.equals(JobPlugin.class)) ) { event.doit = true; } else { event.doit = false; } } public void dragSetData(DragSourceEvent event) { TreeSelection[] treeObjects = getTreeObjects(tree,selectionTree,coreObjectsTree); if (treeObjects.length == 0) { event.doit = false; return; } int type = 0; String data = null; TreeSelection treeObject = treeObjects[0]; Object object = treeObject.getSelection(); JobMeta jobMeta = spoon.getActiveJob(); if (object instanceof StepMeta) { StepMeta stepMeta = (StepMeta) object; type = DragAndDropContainer.TYPE_STEP; data = stepMeta.getName(); // name of the step. } else if (object instanceof StepPlugin) { StepPlugin stepPlugin = (StepPlugin) object; type = DragAndDropContainer.TYPE_BASE_STEP_TYPE; data = stepPlugin.getDescription(); // Step type description } else if (object instanceof DatabaseMeta) { DatabaseMeta databaseMeta = (DatabaseMeta) object; type = DragAndDropContainer.TYPE_DATABASE_CONNECTION; data = databaseMeta.getName(); } else if (object instanceof TransHopMeta) { TransHopMeta hop = (TransHopMeta) object; type = DragAndDropContainer.TYPE_TRANS_HOP; data = hop.toString(); // nothing for really ;-) } else if (object instanceof JobEntryCopy) { JobEntryCopy jobEntryCopy = (JobEntryCopy) object; type = DragAndDropContainer.TYPE_JOB_ENTRY; data = jobEntryCopy.getName(); // name of the job entry. } else if (object instanceof JobPlugin) { JobPlugin jobPlugin = (JobPlugin) object; type = DragAndDropContainer.TYPE_BASE_JOB_ENTRY; data = jobPlugin.getDescription(); // Step type } else if (object instanceof Class && object.equals(JobPlugin.class)) { JobEntryCopy dummy = null; if (jobMeta != null) dummy = jobMeta.findJobEntry(JobMeta.STRING_SPECIAL_DUMMY, 0, true); if (JobMeta.STRING_SPECIAL_DUMMY.equalsIgnoreCase(treeObject.getItemText()) && dummy != null) { // if dummy already exists, add a copy type = DragAndDropContainer.TYPE_JOB_ENTRY; data = dummy.getName(); } else { type = DragAndDropContainer.TYPE_BASE_JOB_ENTRY; data = treeObject.getItemText(); } } else { event.doit = false; return; // ignore anything else you drag. } event.data = new DragAndDropContainer(type, data); } public void dragFinished(DragSourceEvent event) { } }); } }
package com.ratemarkt.models; import java.math.BigDecimal; import java.time.LocalDate; import java.time.OffsetDateTime; import java.util.Currency; import java.util.List; import javax.annotation.Nullable; import org.immutables.gson.Gson; import org.immutables.value.Value; @Gson.TypeAdapters @Value.Immutable public interface Booking extends MetaModel { public static final String META_SUPPLIER_REF = "supplierRef"; String getBookingRef(); BookingStatus getStatus(); String getHotelCode(); LocalDate getCheckin(); LocalDate getCheckout(); BigDecimal getTotal(); Currency getCurrency(); Holder getHolder(); OffsetDateTime getCreationDate(); @Nullable List<CancellationPolicy> getCancellationPolicies(); @Nullable Boolean getNonrefundable(); @Nullable String getClientRef(); @Nullable RateType getRateType(); @Nullable List<Occupancy> getOccupancies(); @Nullable BigDecimal getBalance(); @Nullable String getBoardType(); @Nullable String getBoardName(); @Nullable String getRateKey(); @Nullable String getHotelName(); @Nullable String getDestinationCode(); @Nullable String getDestinationName(); @Nullable String getCountryCode(); @Nullable BigDecimal getCancellationCost(); @Nullable BigDecimal getCommission(); @Nullable BigDecimal getHotelRate(); @Nullable Currency getHotelCurrency(); @Nullable String getSpecialRequest(); @Nullable String getRemarks(); }
//FILE: LiveModeTimer.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 ij.gui.ImageWindow; import java.text.NumberFormat; import java.util.HashSet; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.LinkedBlockingQueue; import javax.swing.SwingUtilities; import mmcorej.CMMCore; import mmcorej.TaggedImage; import org.micromanager.imagedisplay.VirtualAcquisitionDisplay; import org.micromanager.MMStudio; import org.micromanager.SnapLiveManager; import org.micromanager.utils.CanvasPaintPending; import org.micromanager.utils.MDUtils; import org.micromanager.utils.MMScriptException; import org.micromanager.utils.ReportingUtils; /** * This class extends the java swing timer. It periodically retrieves images * from the core and displays them in the live window * * @author Henry Pinkard */ public class LiveModeTimer { private VirtualAcquisitionDisplay win_; private CMMCore core_; private MMStudio studio_; private SnapLiveManager snapLiveManager_; private int multiChannelCameraNrCh_; private long fpsTimer_; // Guarded by this private long fpsCounter_; // Guarded by this private long imageNumber_; // Guarded by this private long oldImageNumber_; // Guarded by this private long fpsInterval_ = 5000; private final NumberFormat format_; private boolean running_ = false; private Runnable task_; private final MMStudio.DisplayImageRoutine displayImageRoutine_; private LinkedBlockingQueue<TaggedImage> imageQueue_; private static int mCamImageCounter_ = 0; private boolean multiCam_ = false; // Helper class to start and stop timer task atomically. private class TimerController { private Timer timer_; private final Object timerLock_ = new Object(); private boolean timerTaskShouldStop_ = true; // Guarded by timerLock_ private boolean timerTaskIsBusy_ = false; // Guarded by timerLock_ public void start(final Runnable task, long interval) { synchronized (timerLock_) { if (timer_ != null) { return; } timer_ = new Timer("Live mode timer"); timerTaskShouldStop_ = false; TimerTask timerTask = new TimerTask() { @Override public void run() { synchronized (timerLock_) { if (timerTaskShouldStop_) { return; } timerTaskIsBusy_ = true; } try { task.run(); } finally { synchronized (timerLock_) { timerTaskIsBusy_ = false; timerLock_.notifyAll(); } } } }; timer_.schedule(timerTask, 0, interval); } } // Thread-safe, but will deadlock if called from within the task. public void stopAndWaitForCompletion() { synchronized (timerLock_) { if (timer_ == null) { return; } // Stop the timer task atomically, ensuring that any currently running // cycle is finished and no further cycles will be run. timerTaskShouldStop_ = true; timer_.cancel(); while (timerTaskIsBusy_) { try { timerLock_.wait(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } timer_ = null; } } } private final TimerController timerController_ = new TimerController(); /** * The LivemodeTimer constructor defines a DisplayImageRoutine that * synchronizes image display with the "paint" function (currently execute * by the ImageCanvas of ImageJ). * * The multiCamLiveTask needs extra synchronization at this point. * The multiCamLiveTask generates tagged images in groups of * multiChannelCameraNrCh_, however, we only want to update * the display (which is costly) when we have the whole group. */ public LiveModeTimer() { studio_ = MMStudio.getInstance(); snapLiveManager_ = studio_.getSnapLiveManager(); core_ = studio_.getCore(); format_ = NumberFormat.getInstance(); format_.setMaximumFractionDigits(0x1); mCamImageCounter_ = 0; displayImageRoutine_ = new MMStudio.DisplayImageRoutine() { @Override public void show(final TaggedImage ti) { // Ensure the image has summary metadata set properly, as // AcquisitionManager relies on it (e.g. in addToAlbum(), when the // "snap to album" button is clicked). try { MDUtils.setSummary(ti.tags, MMStudio.getInstance().getAcquisitionWithName(SnapLiveManager.SIMPLE_ACQ).getSummaryMetadata()); } catch (Exception e) { ReportingUtils.logError(e, "Error setting summary metadata"); } try { if (multiCam_) { mCamImageCounter_++; if (mCamImageCounter_ < multiChannelCameraNrCh_) { studio_.normalizeTags(ti); studio_.addImage(SnapLiveManager.SIMPLE_ACQ, ti, false, false); return; } else { // completes the set mCamImageCounter_ = 0; } } ImageWindow window = snapLiveManager_.getSnapLiveWindow(); if (!CanvasPaintPending.isMyPaintPending( window.getCanvas(), this) ) { CanvasPaintPending.setPaintPending( window.getCanvas(), this); studio_.normalizeTags(ti); studio_.addImage(SnapLiveManager.SIMPLE_ACQ, ti, true, true); studio_.updateLineProfile(); updateFPS(); } } catch (MMScriptException e) { ReportingUtils.logError(e); } } }; } /** * Determines the optimum interval for the live mode timer task to happen * Also sets variable fpsInterval_ */ private long getInterval() { double interval = 20; try { interval = Math.max(core_.getExposure(), interval); } catch (Exception e) { ReportingUtils.logError("Unable to get exposure from core"); } fpsInterval_ = (long) (20 * interval); if (fpsInterval_ < 1000) fpsInterval_ = 1000; return (int) interval; } /** * Determines whether we are dealing with multiple cameras */ private void setType() { multiChannelCameraNrCh_ = (int) core_.getNumberOfCameraChannels(); if (multiChannelCameraNrCh_ == 1) { task_ = singleCameraLiveTask(); multiCam_ = false; } else { task_ = multiCamLiveTask(); multiCam_ = true; } } public boolean isRunning() { return running_; } @SuppressWarnings("SleepWhileInLoop") public void begin() throws Exception { if(running_) { return; } core_.clearCircularBuffer(); try { core_.startContinuousSequenceAcquisition(0); } catch (Exception e) { ReportingUtils.showError("Unable to start the sequence acquisition: " + e); throw(e); } setType(); long period = getInterval(); // Wait for first image to create ImageWindow, so that we can be sure about image size long start = System.currentTimeMillis(); long now = start; // Give 10s extra for the camera to transfer the image to us. long timeout = period + 10000; while (core_.getRemainingImageCount() == 0 && (now - start < timeout) ) { now = System.currentTimeMillis(); Thread.sleep(5); } if (now - start >= timeout) { throw new Exception("Camera did not send image within " + timeout + "ms"); } TaggedImage timg = core_.getLastTaggedImage(); // With first image acquired, create the display snapLiveManager_.validateDisplayAndAcquisition(timg); win_ = snapLiveManager_.getSnapLiveDisplay(); long firstImageSequenceNumber = MDUtils.getSequenceNumber(timg.tags); synchronized (this) { fpsCounter_ = 0; fpsTimer_ = System.nanoTime(); imageNumber_ = firstImageSequenceNumber; oldImageNumber_ = firstImageSequenceNumber; } imageQueue_ = new LinkedBlockingQueue<TaggedImage>(10); // XXX The logic here is very weird. We add this first image only if we // are using a single camera, because the single camera timer code checks // and eliminates duplicates of the same frame. For multi camera, we do // not add the image, since no checks for duplicates are performed // (which is a bug that needs to be fixed). if (!multiCam_) { imageQueue_.put(timg); } timerController_.start(task_, period); win_.getImagePlus().getWindow().toFront(); running_ = true; studio_.runDisplayThread(imageQueue_, displayImageRoutine_); } public void stop() { stop(true); } private void stop(boolean firstAttempt) { ReportingUtils.logMessage("Stop called in LivemodeTimer, " + firstAttempt); timerController_.stopAndWaitForCompletion(); try { if (imageQueue_ != null) { imageQueue_.put(TaggedImageQueue.POISON); imageQueue_ = null; // Prevent further attempts to send POISON } } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } try { if (core_.isSequenceRunning()) { core_.stopSequenceAcquisition(); } running_ = false; } catch (Exception ex) { try { } catch (Exception e) { ReportingUtils.showError("Error closing shutter"); } ReportingUtils.showError(ex); //Wait 1 s and try to stop again if (firstAttempt) { final Timer delayStop = new Timer(); delayStop.schedule( new TimerTask() { @Override public void run() { stop(false); }},1000); } } } /** * Keep track of the last imagenumber, added by the circular buffer * that we have seen here * * @param imageNumber the new imagenumber * @return true if imagenumber was incremented */ private synchronized boolean setImageNumber(long imageNumber) { if (imageNumber > imageNumber_) { imageNumber_ = imageNumber; return true; } return false; } /** * Updates the fps timer (how fast does the camera pump images into the * circular buffer) and display fps (how fast do we display the images) * It is called from tasks that are doing the actual image drawing */ private synchronized void updateFPS() { if (!running_) return; if (imageNumber_ == oldImageNumber_) { return; } try { fpsCounter_++; long now = System.nanoTime(); long diffMs = (now - fpsTimer_) / 1000000; if (diffMs > fpsInterval_) { double d = diffMs / 1000.0; double fps = fpsCounter_ / d; double dfps = (imageNumber_ - oldImageNumber_) / d; win_.displayStatusLine("fps: " + format_.format(dfps) + ", display fps: " + format_.format(fps)); fpsCounter_ = 0; fpsTimer_ = now; oldImageNumber_ = imageNumber_; } } catch (Exception ex) { ReportingUtils.logError(ex); } } /** * Task executed to display live images when using a single camera * * @return */ private TimerTask singleCameraLiveTask() { return new TimerTask() { @Override public void run() { if (core_.getRemainingImageCount() == 0) { return; } if (win_.windowClosed()) //check is user closed window { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { snapLiveManager_.setLiveMode(false); } }); } else { try { TaggedImage ti = core_.getLastTaggedImage(); // if we have already shown this image, do not do it again. long imageNumber = MDUtils.getSequenceNumber(ti.tags); if (setImageNumber(imageNumber)) { imageQueue_.put(ti); } } catch (final Exception ex) { ReportingUtils.logMessage("Stopping live mode because of error..."); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { snapLiveManager_.setLiveMode(false); ReportingUtils.showError(ex); } }); } } } }; } private TimerTask multiCamLiveTask() { return new TimerTask() { @Override public void run() { if (core_.getRemainingImageCount() == 0) { return; } if (win_.windowClosed() || !studio_.acquisitionExists(SnapLiveManager.SIMPLE_ACQ)) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { snapLiveManager_.setLiveMode(false); } }); } else { try { String camera = core_.getCameraDevice(); Set<String> cameraChannelsAcquired = new HashSet<String>(); for (int i = 0; i < 2 * multiChannelCameraNrCh_; ++i) { TaggedImage ti = core_.getNBeforeLastTaggedImage(i); String channelName; if (ti.tags.has(camera + "-CameraChannelName")) { channelName = ti.tags.getString(camera + "-CameraChannelName"); if (!cameraChannelsAcquired.contains(channelName)) { MDUtils.setChannelName(ti.tags, channelName); int ccIndex = ti.tags.getInt(camera + "-CameraChannelIndex"); MDUtils.setChannelIndex(ti.tags, ccIndex); if (ccIndex == 0) { // XXX We do keep track of the image number, but // we are currently ignoring the check for new // images here (see the single camera version). // When fixing this, make sure to handle the // first frames correctly, even for very slow // acquisitions (see begin()). setImageNumber(MDUtils.getSequenceNumber(ti.tags)); } imageQueue_.put(ti); cameraChannelsAcquired.add(channelName); } if (cameraChannelsAcquired.size() == multiChannelCameraNrCh_) { break; } } } } catch (final Exception exc) { ReportingUtils.logMessage("Stopping live mode because of error..."); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { snapLiveManager_.setLiveMode(false); ReportingUtils.showError(exc); } }); } } } }; } }
package com.transloadit.sdk; import com.transloadit.sdk.exceptions.TransloaditRequestException; import com.transloadit.sdk.exceptions.TransloaditSignatureException; import com.transloadit.sdk.response.AssemblyResponse; import io.tus.java.client.*; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.HashMap; import java.util.Map; /** * This class represents a new assembly being created */ public class Assembly extends OptionsBuilder { Map<String, Object> files; private TusClient tusClient; public Assembly(Transloadit transloadit) { this(transloadit, new Steps(), new HashMap<String, File>(), new HashMap<String, Object>()); } /** * * @param steps {@link Steps} the steps to add to the assembly. * @param files is a map of file names and files that are meant to be uploaded. * @param options map of extra options to be sent along with the request. */ public Assembly(Transloadit transloadit, Steps steps, Map<String, File> files, Map<String, Object> options) { this.transloadit = transloadit; this.steps = steps; this.files = new HashMap<>(); this.files.putAll(files); this.options = options; tusClient = null; } /** * Adds a file to your assembly. * * @param file {@link File} the file to be uploaded. * @param name {@link String} the name you the file to be given in transloadit */ public void addFile(File file, String name){ files.put(name, file); } /** * Adds a file to your assembly but automatically genarates the name of the file. * * @param file {@link File} the file to be uploaded. */ public void addFile(File file){ String name = "file_"; for (int i = files.size(); files.containsKey(name); i++) { name += i; } files.put(name, file); } /** * Submits the configured assembly to Transloadit for processing. * * @param isResumable boolean value that tells the assembly whether or not to use tus. * @return {@link AssemblyResponse} * @throws TransloaditRequestException * @throws IOException when there's a failure with file retrieval. * @throws ProtocolException when there's a failure with tus upload. */ public AssemblyResponse save(boolean isResumable) throws TransloaditRequestException, TransloaditSignatureException, IOException, ProtocolException { Request request = new Request(transloadit); options.put("steps", steps.toMap()); if (isResumable) { Map<String, Object> tusOptions = new HashMap<>(); tusOptions.put("tus_num_expected_upload_files", files.size()); AssemblyResponse response = new AssemblyResponse( request.post("/assemblies", options, tusOptions), true); processTusFiles(response.sslUrl); return response; } else { return new AssemblyResponse(request.post("/assemblies", options, files)); } } public AssemblyResponse save() throws ProtocolException, TransloaditSignatureException, TransloaditRequestException, IOException { return this.save(false); } /** * * @param assemblyUrl the assembly url affiliated with the tus upload * @throws IOException when there's a failure with file retrieval. * @throws ProtocolException when there's a failure with tus upload. */ protected void processTusFiles(String assemblyUrl) throws IOException, ProtocolException { tusClient = new TusClient(); tusClient.setUploadCreationURL(new URL(transloadit.hostUrl + "/resumable/files/")); tusClient.enableResuming(new TusURLMemoryStore()); for (Map.Entry<String, Object> entry : files.entrySet()) { processTusFile((File) entry.getValue(), entry.getKey(), assemblyUrl); } } /** * * @param file to upload. * @param name name of the file to be uploaded. * @param assemblyUrl the assembly url affiliated with the tus upload. * @throws IOException when there's a failure with file retrieval. * @throws ProtocolException when there's a failure with tus upload. */ protected void processTusFile(File file, String name, String assemblyUrl) throws IOException, ProtocolException { final TusUpload upload = new TusUpload(file); Map<String, String> metadata = new HashMap<>(); metadata.put("filename", name); metadata.put("assembly_url", assemblyUrl); metadata.put("fieldname", name); upload.setMetadata(metadata); TusExecutor executor = new TusExecutor() { @Override protected void makeAttempt() throws ProtocolException, IOException { TusUploader uploader = tusClient.resumeOrCreateUpload(upload); uploader.setChunkSize(1024); int uploadedChunk = 0; while (uploadedChunk > -1) { uploadedChunk = uploader.uploadChunk(); } uploader.finish(); } }; executor.makeAttempts(); } }
package control; import data.ScriptingProject; import gui.CameraShotBlock; import gui.DetailView; import gui.ShotBlock; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; public class DetailViewController { private DetailView detailView; private ControllerManager manager; private ScriptingProject project; /** * Constructor. * @param manager - the controller manager this controller belongs to */ public DetailViewController(ControllerManager manager) { this.detailView = manager.getRootPane().getRootHeaderArea().getDetailView(); this.manager = manager; this.project = manager.getScriptingProject(); initDescription(); initName(); initBeginCount(); initEndCount(); } /** * Init the begincount handlers. */ private void initBeginCount() { detailView.setBeginCount(0); detailView.getBeginCountField().textProperty().addListener(( observable, oldValue, newValue) -> { if (manager.getActiveBlock() != null) { int newVal = !newValue.isEmpty() ? Integer.parseInt(newValue) : 0; manager.getActiveBlock().setBeginCount(newVal); if (manager.getActiveBlock() instanceof CameraShotBlock) { ((CameraShotBlock) manager.getActiveBlock()).getShot() .setBeginCount(newVal); } } }); } /** * Init the endcuont handlers. */ private void initEndCount() { detailView.setEndCount(0); detailView.getEndCountField().textProperty().addListener(( observable, oldValue, newValue) -> { if (manager.getActiveBlock() != null) { int newVal = !newValue.isEmpty() ? Integer.parseInt(newValue) : 0; ShotBlock block = manager.getActiveBlock(); block.setEndCount(newVal); if (manager.getActiveBlock() instanceof CameraShotBlock) { ((CameraShotBlock) manager.getActiveBlock()).getShot().setEndCount(newVal); } } }); } /** * Init the description handlers. */ private void initDescription() { detailView.setDescription(""); detailView.getDescriptionField().textProperty().addListener(( observable, oldValue, newValue) -> { if (manager.getActiveBlock() != null) { manager.getActiveBlock().setDescription(newValue); if (manager.getActiveBlock() instanceof CameraShotBlock) { ((CameraShotBlock) manager.getActiveBlock()).getShot() .setDescription(newValue); } } }); } /** * Init the name handler. */ private void initName() { detailView.setName(""); detailView.getNameField().textProperty().addListener(( observable, oldValue, newValue) -> { if (manager.getActiveBlock() != null) { manager.getActiveBlock().setName(newValue); if (manager.getActiveBlock() instanceof CameraShotBlock) { ((CameraShotBlock) manager.getActiveBlock()).getShot().setName(newValue); } } }); } /** * Method to signal that the active block is changed so we can update it. */ public void activeBlockChanged() { if (manager.getActiveBlock() != null) { detailView.setDescription(manager.getActiveBlock().getDescription()); detailView.setName(manager.getActiveBlock().getName()); // TODO: Make doubles possible in detailview detailView.setBeginCount((int) manager.getActiveBlock().getBeginCount()); detailView.setEndCount((int) manager.getActiveBlock().getEndCount()); } } }
package edu.cmu.sv.ws.ssnoc.data; /** * This class contains all the SQL related code that is used by the project. * Note that queries are grouped by their purpose and table associations for * easy maintenance. * */ public class SQL { public static final String SSN_USERS = "SSN_USERS"; public static final String SSN_STATUS_CRUMBS = "SSN_STATUS_CRUMBS"; public static final String SSN_LOCATION_CRUMBS = "SSN_LOCATION_CRUMBS"; public static final String SSN_WALL_MESSAGES = "SSN_WALL_MESSAGES"; public static final String SSN_CHAT_MESSAGES = "SSN_CHAT_MESSAGES"; /** * Query to check if a given table exists in the H2 database. */ public static final String CHECK_TABLE_EXISTS_IN_DB = "SELECT count(1) as rowCount " + " FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = SCHEMA() " + " AND UPPER(TABLE_NAME) = UPPER(?)"; // All queries related to USERS /** * Query to create the USERS table. */ public static final String CREATE_USERS = "create table IF NOT EXISTS " + SSN_USERS + " ( user_id IDENTITY PRIMARY KEY," + " user_name VARCHAR(100)," + " password VARCHAR(512)," + " salt VARCHAR(512)," + " last_status_id BIGINT, last_location_id BIGINT, " + " created_at TIMESTAMP,"+ " modified_at TIMESTAMP )"; /** * Query to load all users in the system. */ public static final String FIND_ALL_USERS = "select user_id, user_name, password," + " salt, last_status_code_id, ssc.status, ssc.created_at, last_location_id, slc.location created_at, modified_at " + " from " + SSN_USERS + " u " + " left outer join "+ SSN_STATUS_CRUMBS + " ssc on u.last_status_code_id = ssc.status_crumb_id " + " left outer join "+ SSN_LOCATION_CRUMBS + " slc on u.last_location_id = slc.location_crumb_id " + " order by user_name"; /** * Query to find a user details depending on his name. Note that this query * does a case insensitive search with the user name. */ public static final String FIND_USER_BY_NAME = "select user_id, user_name, password," + " salt, last_status_code_id, created_at, modified_at " + " from " + SSN_USERS + " where UPPER(user_name) = UPPER(?)"; /** * Query to find a user id depending on his name. Note that this query * does a case insensitive search with the user name. */ public static final String FIND_USER_ID_BY_NAME = "select user_id " + " from " + SSN_USERS + " where UPPER(user_name) = UPPER(?)"; /** * Query to find a user name depending on his id. */ public static final String FIND_USER_NAME_BY_ID = "select user_name " + " from " + SSN_USERS + " where user_id = ?"; /** * Query to insert a row into the users table. */ public static final String INSERT_USER = "insert into " + SSN_USERS + " (user_name, password, salt, last_status_code_id, created_at) values (?, ?, ?, ?, CURRENT_TIMESTAMP() )"; /** * Query to update a row in the users table. */ public static final String UPDATE_USER_BY_ID = "update " + SSN_USERS + " set last_status_code_id = ?, modified_at = ?" + " where user_id = ?"; /** * Query to update a row in the users table. */ public static final String UPDATE_USER_BY_NAME = "update " + SSN_USERS + " set last_status_code_id = ?, modified_at = ?" + " where UPPER(user_name) = UPPER(?)"; // All queries related to STATUS_CRUMBS /** * Query to create the STATUS_CRUMBS table. */ public static final String CREATE_STATUS_CRUMBS = "create table IF NOT EXISTS " + SSN_STATUS_CRUMBS + " ( status_crumb_id IDENTITY PRIMARY KEY," + " user_id BIGINT," + " status VARCHAR(10), location_crumb_id BIGINT, " + " created_at TIMESTAMP )"; /** * Query to load all status crumbs in the system. */ public static final String FIND_ALL_STATUS_CRUMBS = "select status_crumb_id, user_id, status, location_crumb_id, " + " created_at " + " from " + SSN_STATUS_CRUMBS + " order by created_at DESC"; /** * Query to find a status_crumb depending on the user_id. */ public static final String FIND_STATUS_CRUMB_FOR_USER_ID = "select status_crumb_id, user_id, status, location_crumb_id, " + " created_at " + " from " + SSN_STATUS_CRUMBS + " where user_id = ?"; /** * Query to insert a row into the status_crumbs table. */ public static final String INSERT_STATUS_CRUMB = "insert into " + SSN_STATUS_CRUMBS + " (user_id, status, location_crumb_id, created_at) values (?, ?, ?, ?)"; // All queries related to LOCATION_CRUMBS /** * Query to create the LOCATION_CRUMBS table. */ public static final String CREATE_LOCATION_CRUMBS = "create table IF NOT EXISTS " + SSN_LOCATION_CRUMBS + " ( location_crumb_id IDENTITY PRIMARY KEY," + " user_id BIGINT," + " location VARCHAR(50)," + " created_at TIMESTAMP )"; /** * Query to load all location crumbs in the system. */ public static final String FIND_ALL_LOCATION_CRUMBS = "select location_crumb_id, user_id, location," + " created_at " + " from " + SSN_LOCATION_CRUMBS + " order by created_at DESC"; /** * Query to find a location_crumb depending on the user_id. */ public static final String FIND_LOCATION_CRUMB_FOR_USER_ID = "select Location_crumb_id, user_id, location," + " created_at " + " from " + SSN_LOCATION_CRUMBS + " where user_id = ?"; /** * Query to insert a row into the location_crumbs table. */ public static final String INSERT_LOCATION_CRUMB = "insert into " + SSN_LOCATION_CRUMBS + " (user_id, location, created_at) values (?, ?, ?)"; // All queries related to WALL_MESSAGES /** * Query to create the WALL_MESSAGES table. */ public static final String CREATE_WALL_MESSAGES = "create table IF NOT EXISTS " + SSN_WALL_MESSAGES + " ( wall_message_id IDENTITY PRIMARY KEY," + " sender_id BIGINT," + " content VARCHAR(1024)," + " location VARCHAR(512)," + " created_at TIMESTAMP )"; /** * Query to load all wall messages in the system. */ public static final String FIND_ALL_WALL_MESSAGES = "select wall_message_id, sender_id," + " content, location, created_at " + " from " + SSN_WALL_MESSAGES + " order by created_at DESC"; /** * Query to insert a new wall message into the wall_messages table. */ public static final String INSERT_WALL_MESSAGE = "insert into " + SSN_WALL_MESSAGES + " (sender_id, content, location, created_at) values (?, ?, ?, ?)"; // All queries related to CHAT_MESSAGES /** * Query to create the CHAT_MESSAGES table. */ public static final String CREATE_CHAT_MESSAGES = "create table IF NOT EXISTS " + SSN_CHAT_MESSAGES + " ( chat_message_id IDENTITY PRIMARY KEY," + " sender_id BIGINT," + " receiver_id BIGINT," + " content VARCHAR(1024)," + " location VARCHAR(512)," + " created_at TIMESTAMP )"; /** * Query to load all chat messages in the system. */ public static final String FIND_ALL_CHAT_MESSAGES = "select chat_message_id, sender_id, receiver_id," + " content, location, created_at " + " from " + SSN_CHAT_MESSAGES + " order by created_at DESC"; /** * Query to insert a new chat message into the chat_messages table. */ public static final String INSERT_CHAT_MESSAGE = "insert into " + SSN_CHAT_MESSAGES + " (sender_id, receiver_id, content, location, created_at) values (?, ?, ?, ?, ?)"; }
package edu.jhu.srl; import java.io.Serializable; 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.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeSet; import org.apache.log4j.Logger; import edu.berkeley.nlp.PCFGLA.smoothing.SrlBerkeleySignatureBuilder; import edu.jhu.data.conll.SrlGraph.SrlEdge; import edu.jhu.data.conll.SrlGraph.SrlPred; import edu.jhu.data.simple.SimpleAnnoSentence; import edu.jhu.prim.tuple.ComparablePair; import edu.jhu.prim.tuple.Pair; import edu.jhu.util.Alphabet; import edu.jhu.util.collections.Lists; /** * Extract corpus statistics about a CoNLL-2009 dataset. * * @author mmitchell * @author mgormley */ public class CorpusStatistics implements Serializable { /** * Parameters for CorpusStatistics. */ public static class CorpusStatisticsPrm implements Serializable { private static final long serialVersionUID = 1848012037725581753L; // TODO: Remove useGoldSyntax since it's no longer used in CorpusStatistics. public boolean useGoldSyntax = false; public String language = "es"; /** Cutoff for OOV words. */ public int cutoff = 3; /** Cutoff for topN words. */ public int topN = 800; /** * Whether to normalize and clean words. */ public boolean normalizeWords = false; } private static final long serialVersionUID = 1L; private static final Logger log = Logger.getLogger(CorpusStatistics.class); public static final String UNKNOWN_ROLE = "argUNK"; public static final String UNKNOWN_SENSE = "senseUNK"; public static List<String> SENSES_FOR_UNK_PRED = Lists.getList(UNKNOWN_SENSE); public Set<String> knownWords = new HashSet<String>(); public Set<String> knownUnks = new HashSet<String>(); public Set<String> knownPostags = new HashSet<String>(); public Set<String> topNWords = new HashSet<String>(); public List<String> linkStateNames; public List<String> roleStateNames; // Mapping from predicate form to the set of predicate senses. public Map<String,List<String>> predSenseListMap = new HashMap<String,List<String>>(); public int maxSentLength = 0; public SrlBerkeleySignatureBuilder sig; public Normalizer normalize; public CorpusStatisticsPrm prm; private boolean initialized; public CorpusStatistics(CorpusStatisticsPrm prm) { this.prm = prm; this.normalize = new Normalizer(prm.normalizeWords); this.sig = new SrlBerkeleySignatureBuilder(new Alphabet<String>()); initialized = false; } public void init(Iterable<SimpleAnnoSentence> cr) { Map<String,Set<String>> predSenseSetMap = new HashMap<String,Set<String>>(); Set<String> knownRoles = new HashSet<String>(); Set<String> knownLinks = new HashSet<String>(); Map<String, MutableInt> words = new HashMap<String, MutableInt>(); Map<String, MutableInt> unks = new HashMap<String, MutableInt>(); initialized = true; // Store the variable states we have seen before so // we know what our vocabulary of possible states are for // the Link variable. Applies to knownLinks, knownRoles. knownLinks.add("True"); knownLinks.add("False"); knownUnks.add("UNK"); knownRoles.add(UNKNOWN_ROLE); // This is a hack: '_' won't actually be in any of the defined edges. // However, removing this messes up what we assume as default. knownRoles.add("_"); for (SimpleAnnoSentence sent : cr) { // Need to know max sent length because distance features // use these values explicitly; an unknown sentence length in // test data will result in an unknown feature. if (sent.size() > maxSentLength) { maxSentLength = sent.size(); } // Word stats. for (int position = 0; position < sent.size(); position++) { String wordForm = sent.getWord(position); String cleanWord = normalize.clean(wordForm); // Actually only need to do this for those words that are below // threshold for knownWords. String unkWord = sig.getSignature(wordForm, position, prm.language); unkWord = normalize.escape(unkWord); addWord(words, cleanWord); addWord(unks, unkWord); } // POS tag stats. if (sent.getPosTags() != null) { for (int position = 0; position < sent.size(); position++) { knownPostags.add(sent.getPosTag(position)); } } // SRL stats. if (sent.getSrlGraph() != null) { for (SrlEdge edge : sent.getSrlGraph().getEdges()) { String role = edge.getLabel(); knownRoles.add(role); } for (SrlPred pred : sent.getSrlGraph().getPreds()) { int position = pred.getPosition(); String lemma = sent.getLemma(position); Set<String> senses = predSenseSetMap.get(lemma); if (senses == null) { senses = new TreeSet<String>(); predSenseSetMap.put(lemma, senses); } senses.add(pred.getLabel()); } } } // For words and unknown word classes, we only keep those above some threshold. knownWords = getUnigramsAboveThreshold(words, prm.cutoff); knownUnks = getUnigramsAboveThreshold(unks, prm.cutoff); topNWords = getTopNUnigrams(words, prm.topN, prm.cutoff); this.linkStateNames = new ArrayList<String>(knownLinks); this.roleStateNames = new ArrayList<String>(knownRoles); for (Entry<String,Set<String>> entry : predSenseSetMap.entrySet()) { predSenseListMap.put(entry.getKey(), new ArrayList<String>(entry.getValue())); } log.info("Num known roles: " + roleStateNames.size()); log.info("Known roles: " + roleStateNames); log.info("Num known predicates: " + predSenseListMap.size()); } private static void addWord(Map<String, MutableInt> inputHash, String w) { MutableInt count = inputHash.get(w); if (count == null) { inputHash.put(w, new MutableInt()); } else { count.increment(); } } private static Set<String> getUnigramsAboveThreshold(Map<String, MutableInt> inputHash, int cutoff) { Set<String> knownHash = new HashSet<String>(); Iterator<Entry<String, MutableInt>> it = inputHash.entrySet().iterator(); while (it.hasNext()) { Map.Entry pairs = it.next(); int count = ((MutableInt) pairs.getValue()).get(); if (count > cutoff) { knownHash.add((String) pairs.getKey()); } } return knownHash; } private static Set<String> getTopNUnigrams(Map<String, MutableInt> map, int topN, int cutoff) { List<ComparablePair<Integer, String>> pairs = new ArrayList<ComparablePair<Integer, String>>(map.size()); for (Entry<String, MutableInt> entry : map.entrySet()) { int count = entry.getValue().value; if (count > cutoff) { pairs.add(new ComparablePair<Integer, String>(count, entry.getKey())); } } Collections.sort(pairs, Collections.reverseOrder()); HashSet<String> set = new HashSet<String>(); for (Pair<Integer,String> p : pairs.subList(0, Math.min(pairs.size(), topN))) { set.add(p.get2()); } return set; } @Override public String toString() { return "CorpusStatistics [" + "\n knownWords=" + knownWords + ",\n topNWords=" + topNWords + ",\n knownUnks=" + knownUnks + ",\n knownPostags=" + knownPostags + ",\n linkStateNames=" + linkStateNames + ",\n roleStateNames=" + roleStateNames + ",\n maxSentLength=" + maxSentLength + "]"; } public boolean isInitialized() { return initialized; } public String getLanguage() { return prm.language; } }
package gov.nih.nci.ncicb.cadsr.loader.ui; import gov.nih.nci.ncicb.cadsr.loader.UserSelections; import gov.nih.nci.ncicb.cadsr.loader.ui.util.TreeUtil; import gov.nih.nci.ncicb.cadsr.loader.util.RunMode; import gov.nih.nci.ncicb.cadsr.loader.util.UserPreferences; import java.io.File; import java.io.FileWriter; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeEvent; import javax.swing.tree.TreePath; import javax.swing.tree.TreeNode; import javax.swing.tree.DefaultMutableTreeNode; import gov.nih.nci.ncicb.cadsr.loader.validator.*; import gov.nih.nci.ncicb.cadsr.loader.ui.tree.*; import java.util.*; import javax.swing.tree.DefaultTreeCellRenderer; import org.apache.log4j.spi.LoggingEvent; import org.jdom.*; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; /** * The error viewer. * * @author Anwar Ahmad */ public class ErrorPanel extends JPanel implements MouseListener { private JTree tree; private Set<UMLNode> displaySet = new HashSet<UMLNode>(); private JPopupMenu popup; private JCheckBoxMenuItem conceptCb = new JCheckBoxMenuItem("Hide Concept Errors", false); private UMLNode node; private JPanel cbPanel; private UserSelections userSelections = UserSelections.getInstance(); private boolean hideConceptError = false; private java.util.List<PropertyChangeListener> propChangeListeners = new ArrayList<PropertyChangeListener>(); public ErrorPanel(UMLNode rootNode) { node = rootNode; if(userSelections.getProperty("MODE").equals(RunMode.UnannotatedXmi)) { hideConceptError = true; conceptCb.setSelected(true); } initUI(rootNode); } public void addPropertyChangeListener(PropertyChangeListener l) { propChangeListeners.add(l); } public void update(UMLNode rootNode) { node = rootNode; this.removeAll(); initUI(rootNode); this.updateUI(); } private void update() { update(node); } private void initUI(UMLNode rootNode) { displaySet.clear(); firstRun(rootNode); DefaultMutableTreeNode node = buildTree(rootNode); //create tree and make root not visible tree = new JTree(node); tree.setRootVisible(false); tree.setShowsRootHandles(true); //Traverse Tree expanding all nodes TreeUtil.expandAll(tree, node); tree.setCellRenderer(new UMLTreeCellRenderer()); tree.addMouseListener(this); this.setLayout(new BorderLayout()); JScrollPane scrollPane = new JScrollPane(tree); this.setPreferredSize(new Dimension(450, 110)); this.add(scrollPane, BorderLayout.CENTER); buildPopupMenu(); } public void mousePressed(MouseEvent e) { showPopup(e); } public void mouseExited(MouseEvent e) { } public void mouseClicked(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseReleased(MouseEvent e) { showPopup(e); } private void showPopup(MouseEvent e) { if (e.isPopupTrigger()) { popup.show(e.getComponent(), e.getX(), e.getY()); } } private void buildPopupMenu() { popup = new JPopupMenu(); JMenuItem menuItem = new JMenuItem("Export Errors"); popup.add(menuItem); popup.addSeparator(); popup.add(conceptCb); ActionListener cbAl = new ActionListener() { public void actionPerformed(ActionEvent evt) { AbstractButton cb = (AbstractButton)evt.getSource(); boolean isSel = cb.isSelected(); if (isSel) { hideConceptError = true; } else { hideConceptError = false; } update(); } }; conceptCb.addActionListener(cbAl); menuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { String saveDir = UserPreferences.getInstance().getRecentDir(); JFileChooser chooser = new JFileChooser(); javax.swing.filechooser.FileFilter filter = new javax.swing.filechooser.FileFilter() { String fileExtension = "xml"; public boolean accept(File f) { if (f.isDirectory()) { return true; } return f.getName().endsWith("." + fileExtension); } public String getDescription() { return fileExtension.toUpperCase() + " Files"; } }; chooser.setFileFilter(filter); int returnVal = chooser.showSaveDialog(null); if(returnVal == JFileChooser.APPROVE_OPTION) { String filePath = chooser.getSelectedFile().getAbsolutePath(); //export here //writeXML(); String fileExtension = "xml"; if(!filePath.endsWith(fileExtension)) filePath = filePath + "." + fileExtension; try { FileWriter fw = new FileWriter(filePath); new XMLOutputter(Format.getPrettyFormat()).output(writeXML(filePath), fw); firePropertyChange(new PropertyChangeEvent(this, "EXPORT_ERRORS", null, null)); } catch (Exception e) { firePropertyChange(new PropertyChangeEvent(this, "EXPORT_ERRORS_FAILED", null, null)); throw new RuntimeException("Error writing to " + filePath, e); } } } }); } private void firstRun(UMLNode node) { Set<UMLNode> children = node.getChildren(); Set<ValidationNode> valNodes = node.getValidationNodes(); // displaySet = new HashSet<UMLNode>(); for (ValidationNode valNode: valNodes) { if (!(hideConceptError && valNode.getUserObject() instanceof ValidationConceptError)) { navTree(valNode); } } for (UMLNode child: children) { firstRun(child); } } private void navTree(UMLNode node) { UMLNode pNode = node.getParent(); if (pNode != null) { navTree(pNode); } displaySet.add(node); } private DefaultMutableTreeNode buildTree(UMLNode rootNode) { DefaultMutableTreeNode node = new DefaultMutableTreeNode(rootNode); return doNode(node); } private Element writeXML(String filePath) { Element rootElement = new Element("File"); File file = new File((String)userSelections.getProperty("FILENAME")); rootElement.setAttribute("name", file.getName()); doNode(rootElement, node); return rootElement; } private void doNode(Element element, UMLNode node) { Set<UMLNode> children = node.getChildren(); Set<ValidationNode> valNodes = node.getValidationNodes(); for (ValidationNode valNode: valNodes) { String elementName = "ValidationError"; if(valNode instanceof WarningNode) elementName = "ValidationWarning"; Element validationElement = new Element(elementName); validationElement.addContent(valNode.getDisplay()); element.addContent(validationElement); } for (UMLNode child: children) { //DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(child); Element childElement = new Element("child"); if(child instanceof PackageNode) { childElement = new Element("Package"); childElement.setAttribute("name", child.getDisplay()); } if(child instanceof ClassNode) { childElement = new Element("Class"); childElement.setAttribute("name", child.getDisplay()); } if(child instanceof AttributeNode) { childElement = new Element("Attribute"); childElement.setAttribute("name", child.getDisplay()); } if(child instanceof ValueDomainNode) { childElement = new Element("ValueDomain"); childElement.setAttribute("name", child.getDisplay()); } if(child instanceof ValueMeaningNode) { childElement = new Element("ValueMeaning"); childElement.setAttribute("name", child.getDisplay()); } if(child instanceof AssociationNode) { childElement = new Element("Association"); childElement.setAttribute("name", child.getDisplay()); } if (displaySet.contains(child)) { element.addContent(childElement); //node.add(newNode); } doNode(childElement, child); } } private DefaultMutableTreeNode doNode(DefaultMutableTreeNode node) { UMLNode umlNode = (UMLNode)node.getUserObject(); Set<UMLNode> children = umlNode.getChildren(); Set<ValidationNode> valNodes = umlNode.getValidationNodes(); for (ValidationNode valNode: valNodes) { if (!(hideConceptError && valNode.getUserObject() instanceof ValidationConceptError)) { DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(valNode); node.add(newNode); } } for (UMLNode child: children) { DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(child); if (displaySet.contains(child) && child.getDisplay() != "Inherited Attributes") node.add(newNode); doNode(newNode); } return node; } private void firePropertyChange(PropertyChangeEvent evt) { for(PropertyChangeListener l : propChangeListeners) { l.propertyChange(evt); } } }
package edu.ouc.async.event; /** * Listener * * @author wqx * * @param <T> */ public interface Listener<T> { /** * success * * @param event */ public void onSuccess(Event<T> event); /** * failure * * @param event * @param t */ void onException(Event<T> event, Throwable t); }
package eu.amidst.scai2015; import eu.amidst.core.datastream.*; import eu.amidst.core.distribution.Multinomial; import eu.amidst.core.inference.InferenceAlgorithmForBN; import eu.amidst.core.inference.messagepassing.VMP; import eu.amidst.core.io.DataStreamLoader; import eu.amidst.core.learning.StreamingVariationalBayesVMP; import eu.amidst.core.models.BayesianNetwork; import eu.amidst.core.models.DAG; import eu.amidst.core.utils.Utils; import eu.amidst.core.variables.StaticVariables; import eu.amidst.core.variables.Variable; import weka.classifiers.evaluation.NominalPrediction; import weka.classifiers.evaluation.Prediction; import weka.classifiers.evaluation.ThresholdCurve; import weka.core.Instances; import java.io.IOException; import java.util.*; public class wrapperBN { int seed = 0; Variable classVariable; Variable classVariable_PM; Attribute SEQUENCE_ID; Attribute TIME_ID; static int DEFAULTER_VALUE_INDEX = 1; static int NON_DEFAULTER_VALUE_INDEX = 0; boolean parallelMode = true; int NbrClients= 50000; HashMap<Integer, Multinomial> posteriorsGlobal = new HashMap<>(); static boolean usePRCArea = false; //By default ROCArea is used static boolean nonDeterministic = false; //By default, if a client is DEFAULTER one month, then it is predicted as //defaulter until evidence shows otherwise. static boolean NB = false; public static boolean isNB() { return NB; } public static void setNB(boolean NB) { wrapperBN.NB = NB; } public static boolean isNonDeterministic() { return nonDeterministic; } public static void setNonDeterministic(boolean nonDeterministic) { wrapperBN.nonDeterministic = nonDeterministic; } HashMap<Integer, Integer> defaultingClients = new HashMap<>(); public static boolean isUsePRCArea() { return usePRCArea; } public static void setUsePRCArea(boolean usePRCArea) { wrapperBN.usePRCArea = usePRCArea; } public Attribute getSEQUENCE_ID() { return SEQUENCE_ID; } public void setSEQUENCE_ID(Attribute SEQUENCE_ID) { this.SEQUENCE_ID = SEQUENCE_ID; } public Attribute getTIME_ID() { return TIME_ID; } public void setTIME_ID(Attribute TIME_ID) { this.TIME_ID = TIME_ID; } public Variable getClassVariable_PM() { return classVariable_PM; } public void setClassVariable_PM(Variable classVariable_PM) { this.classVariable_PM = classVariable_PM; } public int getSeed() { return seed; } public void setSeed(int seed) { this.seed = seed; } public Variable getClassVariable() { return classVariable; } public void setClassVariable(Variable classVariable) { this.classVariable = classVariable; } public BayesianNetwork wrapperBNOneMonthNB(DataOnMemory<DataInstance> data){ StaticVariables Vars = new StaticVariables(data.getAttributes()); //Split the whole data into training and testing List<DataOnMemory<DataInstance>> splitData = this.splitTrainAndTest(data,66.0); DataOnMemory<DataInstance> trainingData = splitData.get(0); DataOnMemory<DataInstance> testData = splitData.get(1); List<Variable> NSF = new ArrayList<>(Vars.getListOfVariables()); // NSF: non selected features NSF.remove(classVariable); //remove C NSF.remove(classVariable_PM); // remove C' int nbrNSF = NSF.size(); List<Variable> SF = new ArrayList(); // SF:selected features Boolean stop = false; //Learn the initial BN with training data including only the class variable BayesianNetwork bNet = train(trainingData, Vars, SF,false); System.out.println(bNet.toString()); //Evaluate the initial BN with testing data including only the class variable, i.e., initial score or initial auc double score = testFS(testData, bNet); int cont=0; //iterate until there is no improvement in score while (nbrNSF > 0 && stop == false ){ System.out.print(cont + ", "+score +", "+SF.size() + ", "); SF.stream().forEach(v -> System.out.print(v.getName() + ", ")); System.out.println(); Map<Variable, Double> scores = new HashMap<>(); //scores for each considered feature for(Variable V:NSF) { //if (V.getVarID()>5) // break; System.out.println("Testing "+V.getName()); SF.add(V); //train bNet = train(trainingData, Vars, SF, false); //evaluate scores.put(V, testFS(testData, bNet)); SF.remove(V); } //determine the Variable V with max score double maxScore = (Collections.max(scores.values())); //returns max value in the Hashmap if (maxScore - score > 0.001){ score = maxScore; //Variable with best score for (Map.Entry<Variable, Double> entry : scores.entrySet()) { if (entry.getValue()== maxScore){ Variable SelectedV = entry.getKey(); SF.add(SelectedV); NSF.remove(SelectedV); break; } } nbrNSF = nbrNSF - 1; } else{ stop = true; } cont++; } //Final training with the winning SF and the full initial data bNet = train(data, Vars, SF, true); System.out.println(bNet.getDAG().toString()); return bNet; } public BayesianNetwork wrapperBNOneMonth(DataOnMemory<DataInstance> data){ StaticVariables Vars = new StaticVariables(data.getAttributes()); //Split the whole data into training and testing List<DataOnMemory<DataInstance>> splitData = this.splitTrainAndTest(data,66.0); DataOnMemory<DataInstance> trainingData = splitData.get(0); DataOnMemory<DataInstance> testData = splitData.get(1); List<Variable> NSF = new ArrayList<>(Vars.getListOfVariables()); // NSF: non selected features NSF.remove(classVariable); //remove C NSF.remove(classVariable_PM); // remove C' int nbrNSF = NSF.size(); List<Variable> SF = new ArrayList(); // SF:selected features Boolean stop = false; //Learn the initial BN with training data including only the class variable BayesianNetwork bNet = train(trainingData, Vars, SF); System.out.println(bNet.toString()); //Evaluate the initial BN with testing data including only the class variable, i.e., initial score or initial auc double score = test(testData, bNet, posteriorsGlobal, false); int cont=0; //iterate until there is no improvement in score while (nbrNSF > 0 && stop == false ){ System.out.print(cont + ", "+score +", "+SF.size() + ", "); SF.stream().forEach(v -> System.out.print(v.getName() + ", ")); System.out.println(); Map<Variable, Double> scores = new HashMap<>(); //scores for each considered feature for(Variable V:NSF) { //if (V.getVarID()>5) // break; System.out.println("Testing "+V.getName()); SF.add(V); //train bNet = train(trainingData, Vars, SF); //evaluate scores.put(V, test(testData, bNet, posteriorsGlobal, false)); SF.remove(V); } //determine the Variable V with max score double maxScore = (Collections.max(scores.values())); //returns max value in the Hashmap if (maxScore - score > 0.001){ score = maxScore; //Variable with best score for (Map.Entry<Variable, Double> entry : scores.entrySet()) { if (entry.getValue()== maxScore){ Variable SelectedV = entry.getKey(); SF.add(SelectedV); NSF.remove(SelectedV); break; } } nbrNSF = nbrNSF - 1; } else{ stop = true; } cont++; } //Final training with the winning SF and the full initial data bNet = train(data, Vars, SF); test(data, bNet, posteriorsGlobal, true); return bNet; } List<DataOnMemory<DataInstance>> splitTrainAndTest(DataOnMemory<DataInstance> data, double trainPercentage) { Random random = new Random(this.seed); DataOnMemoryListContainer<DataInstance> train = new DataOnMemoryListContainer(data.getAttributes()); DataOnMemoryListContainer<DataInstance> test = new DataOnMemoryListContainer(data.getAttributes()); for (DataInstance dataInstance : data) { if (dataInstance.getValue(classVariable) == DEFAULTER_VALUE_INDEX) continue; if (random.nextDouble()<trainPercentage/100.0) train.add(dataInstance); else test.add(dataInstance); } for (DataInstance dataInstance : data) { if (dataInstance.getValue(classVariable) != DEFAULTER_VALUE_INDEX) continue; if (random.nextDouble()<trainPercentage/100.0) train.add(dataInstance); else test.add(dataInstance); } Collections.shuffle(train.getList(), random); Collections.shuffle(test.getList(), random); return Arrays.asList(train, test); } public BayesianNetwork train(DataOnMemory<DataInstance> data, StaticVariables allVars, List<Variable> SF, boolean includeClassVariablePM){ DAG dag = new DAG(allVars); if(data.getDataInstance(0).getValue(TIME_ID)!=0 && includeClassVariablePM) dag.getParentSet(classVariable).addParent(classVariable_PM); /* Add classVariable to all SF*/ dag.getParentSets().stream() .filter(parent -> SF.contains(parent.getMainVar())) .filter(w -> w.getMainVar().getVarID() != classVariable.getVarID()) .forEach(w -> w.addParent(classVariable)); StreamingVariationalBayesVMP vmp = new StreamingVariationalBayesVMP(); vmp.setDAG(dag); vmp.setDataStream(data); vmp.setWindowsSize(100); vmp.runLearning(); return vmp.getLearntBayesianNetwork(); } public BayesianNetwork train(DataOnMemory<DataInstance> data, StaticVariables allVars, List<Variable> SF){ DAG dag = new DAG(allVars); if(data.getDataInstance(0).getValue(TIME_ID)!=0) dag.getParentSet(classVariable).addParent(classVariable_PM); /* Add classVariable to all SF*/ dag.getParentSets().stream() .filter(parent -> SF.contains(parent.getMainVar())) .filter(w -> w.getMainVar().getVarID() != classVariable.getVarID()) .forEach(w -> w.addParent(classVariable)); StreamingVariationalBayesVMP vmp = new StreamingVariationalBayesVMP(); vmp.setDAG(dag); vmp.setDataStream(data); vmp.setWindowsSize(100); vmp.runLearning(); return vmp.getLearntBayesianNetwork(); } public double testFS(DataOnMemory<DataInstance> data, BayesianNetwork bn){ InferenceAlgorithmForBN vmp = new VMP(); ArrayList<Prediction> predictions = new ArrayList<>(); int currentMonthIndex = (int)data.getDataInstance(0).getValue(TIME_ID); for (DataInstance instance : data) { int clientID = (int) instance.getValue(SEQUENCE_ID); double classValue = instance.getValue(classVariable); Prediction prediction; Multinomial posterior; vmp.setModel(bn); instance.setValue(classVariable, Utils.missingValue()); vmp.setEvidence(instance); vmp.runInference(); posterior = vmp.getPosterior(classVariable); instance.setValue(classVariable, classValue); prediction = new NominalPrediction(classValue, posterior.getProbabilities()); predictions.add(prediction); } ThresholdCurve thresholdCurve = new ThresholdCurve(); Instances tcurve = thresholdCurve.getCurve(predictions); if(usePRCArea) return ThresholdCurve.getPRCArea(tcurve); else return ThresholdCurve.getROCArea(tcurve); } public double test(DataOnMemory<DataInstance> data, BayesianNetwork bn, HashMap<Integer, Multinomial> posteriors, boolean updatePosteriors){ InferenceAlgorithmForBN vmp = new VMP(); ArrayList<Prediction> predictions = new ArrayList<>(); int currentMonthIndex = (int)data.getDataInstance(0).getValue(TIME_ID); for (DataInstance instance : data) { int clientID = (int) instance.getValue(SEQUENCE_ID); double classValue = instance.getValue(classVariable); Prediction prediction; Multinomial posterior; if(!nonDeterministic && (defaultingClients.get(clientID) != null) && (defaultingClients.get(clientID) - currentMonthIndex >= 12)) { prediction = new NominalPrediction(classValue, new double[]{0.0, 1.0}); posterior = new Multinomial(classVariable); /* This is for the sake of "correctness", this will never be used*/ posterior.setProbabilityOfState(DEFAULTER_VALUE_INDEX, 1.0); posterior.setProbabilityOfState(NON_DEFAULTER_VALUE_INDEX, 0.0); }else{ /*Propagates*/ bn.setConditionalDistribution(classVariable_PM, posteriors.get(clientID)); /* Multinomial_MultinomialParents distClass = bn.getConditionalDistribution(classVariable); Multinomial deterministic = new Multinomial(classVariable); deterministic.setProbabilityOfState(DEFAULTER_VALUE_INDEX, 1.0); deterministic.setProbabilityOfState(NON_DEFAULTER_VALUE_INDEX, 0.0); distClass.setMultinomial(DEFAULTER_VALUE_INDEX, deterministic); */ vmp.setModel(bn); double classValue_PM = instance.getValue(classVariable_PM); instance.setValue(classVariable, Utils.missingValue()); instance.setValue(classVariable_PM, Utils.missingValue()); vmp.setEvidence(instance); vmp.runInference(); posterior = vmp.getPosterior(classVariable); instance.setValue(classVariable, classValue); instance.setValue(classVariable_PM, classValue_PM); prediction = new NominalPrediction(classValue, posterior.getProbabilities()); } predictions.add(prediction); if (classValue == DEFAULTER_VALUE_INDEX) { defaultingClients.putIfAbsent(clientID, currentMonthIndex); } if(updatePosteriors) { Multinomial multi_PM = posterior.toEFUnivariateDistribution().deepCopy(classVariable_PM).toUnivariateDistribution(); if (classValue == DEFAULTER_VALUE_INDEX) { multi_PM.setProbabilityOfState(DEFAULTER_VALUE_INDEX, 1.0); multi_PM.setProbabilityOfState(NON_DEFAULTER_VALUE_INDEX, 0); } posteriors.put(clientID, multi_PM); } } ThresholdCurve thresholdCurve = new ThresholdCurve(); Instances tcurve = thresholdCurve.getCurve(predictions); if(usePRCArea) return ThresholdCurve.getPRCArea(tcurve); else return ThresholdCurve.getROCArea(tcurve); } public double propagateAndTest(Queue<DataOnMemory<DataInstance>> data, BayesianNetwork bn){ HashMap<Integer, Multinomial> posteriors = new HashMap<>(); InferenceAlgorithmForBN vmp = new VMP(); ArrayList<Prediction> predictions = new ArrayList<>(); /* for (int i = 0; i < NbrClients ; i++){ Multinomial uniform = new Multinomial(classVariable_PM); uniform.setProbabilityOfState(DEFAULTER_VALUE_INDEX, 0.5); uniform.setProbabilityOfState(NON_DEFAULTER_VALUE_INDEX, 0.5); posteriors.put(i, uniform); } */ boolean firstMonth = true; Iterator<DataOnMemory<DataInstance>> iterator = data.iterator(); while(iterator.hasNext()){ Prediction prediction = null; Multinomial posterior = null; DataOnMemory<DataInstance> batch = iterator.next(); int currentMonthIndex = (int)batch.getDataInstance(0).getValue(TIME_ID); for (DataInstance instance : batch) { int clientID = (int) instance.getValue(SEQUENCE_ID); double classValue = instance.getValue(classVariable); if(!nonDeterministic && (defaultingClients.get(clientID) != null) && (defaultingClients.get(clientID) - currentMonthIndex >= 12)) { prediction = new NominalPrediction(classValue, new double[]{0.0, 1.0}); posterior = new Multinomial(classVariable); /* This is for the sake of "correctness", this will never be used*/ posterior.setProbabilityOfState(DEFAULTER_VALUE_INDEX, 1.0); posterior.setProbabilityOfState(NON_DEFAULTER_VALUE_INDEX, 0.0); }else{ /*Propagates*/ double classValue_PM = -1; if(!firstMonth){ bn.setConditionalDistribution(classVariable_PM, posteriors.get(clientID)); classValue_PM = instance.getValue(classVariable_PM); instance.setValue(classVariable_PM, Utils.missingValue()); } vmp.setModel(bn); instance.setValue(classVariable, Utils.missingValue()); vmp.setEvidence(instance); vmp.runInference(); posterior = vmp.getPosterior(classVariable); instance.setValue(classVariable, classValue); if(!firstMonth) { instance.setValue(classVariable_PM, classValue_PM); } if(!iterator.hasNext()) { //Last month or present prediction = new NominalPrediction(classValue, posterior.getProbabilities()); predictions.add(prediction); } } if (classValue == DEFAULTER_VALUE_INDEX) { defaultingClients.putIfAbsent(clientID, currentMonthIndex); } Multinomial multi_PM = posterior.toEFUnivariateDistribution().deepCopy(classVariable_PM).toUnivariateDistribution(); if (classValue == DEFAULTER_VALUE_INDEX) { multi_PM.setProbabilityOfState(DEFAULTER_VALUE_INDEX, 1.0); multi_PM.setProbabilityOfState(NON_DEFAULTER_VALUE_INDEX, 0); } posteriors.put(clientID, multi_PM); } firstMonth = false; if(!iterator.hasNext()) {//Last month or present ThresholdCurve thresholdCurve = new ThresholdCurve(); Instances tcurve = thresholdCurve.getCurve(predictions); if(usePRCArea) return ThresholdCurve.getPRCArea(tcurve); else return ThresholdCurve.getROCArea(tcurve); } //First time for TIME_ID=0, inference must be done over a NB, subsequently, the classVariable_PM must be included if(currentMonthIndex == 0) bn.getDAG().getParentSet(classVariable).addParent(classVariable_PM); } throw new UnsupportedOperationException("Something went wrong: The method should have stopped at some point in the loop."); } void learnCajamarModel(DataStream<DataInstance> data) { StaticVariables Vars = new StaticVariables(data.getAttributes()); classVariable = Vars.getVariableById(Vars.getNumberOfVars()-1); classVariable_PM = Vars.getVariableById(Vars.getNumberOfVars()-2); TIME_ID = data.getAttributes().getAttributeByName("TIME_ID"); SEQUENCE_ID = data.getAttributes().getAttributeByName("SEQUENCE_ID"); int count = 0; double averageAUC = 0; /* for (int i = 0; i < NbrClients ; i++){ Multinomial uniform = new Multinomial(classVariable_PM); uniform.setProbabilityOfState(DEFAULTER_VALUE_INDEX, 0.5); uniform.setProbabilityOfState(NON_DEFAULTER_VALUE_INDEX, 0.5); posteriorsGlobal.put(i, uniform); } */ Iterable<DataOnMemory<DataInstance>> iteratable = data.iterableOverBatches(NbrClients); Iterator<DataOnMemory<DataInstance>> iterator = iteratable.iterator(); Queue<DataOnMemory<DataInstance>> monthsMinus12to0 = new LinkedList<>(); //Take 13 batches at a time - 1 for training and 12 for testing //for (int i = 0; i < 12; i++) { for (int i = 0; i < 2; i++) { monthsMinus12to0.add(iterator.next()); } while(iterator.hasNext()){ int idMonthMinus12 = (int)monthsMinus12to0.peek().getDataInstance(0).getValue(TIME_ID); BayesianNetwork bn = wrapperBNOneMonthNB(monthsMinus12to0.poll()); double auc = propagateAndTest(monthsMinus12to0, bn); System.out.println( idMonthMinus12 + "\t" + auc); averageAUC += auc; count += NbrClients; DataOnMemory<DataInstance> currentMonth = iterator.next(); monthsMinus12to0.add(currentMonth); } System.out.println("Average Accuracy: " + averageAUC / (count / NbrClients)); } public static void main(String[] args) throws IOException { DataStream<DataInstance> data = DataStreamLoader.loadFromFile("/Users/ana/Dropbox/amidst/datasets/BankArtificialDataSCAI2015_DEFAULTING_PM.arff"); //DataStream<DataInstance> data = DataStreamLoader.loadFromFile(args[0]); for (int i = 1; i < args.length ; i++) { if(args[i].equalsIgnoreCase("PRCArea")) setUsePRCArea(true); if(args[i].equalsIgnoreCase("nonDeterministic")) setNonDeterministic(true); if(args[i].equalsIgnoreCase("NB")) setNB(true); } wrapperBN wbnet = new wrapperBN(); wbnet.learnCajamarModel(data); } }
package fr.insee.stamina.utils; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * Implementation of the URI and naming policy for the project. * * @author Franck Cotton * @version 0.1, 28 Apr 2016 */ public class Names { /** Base URI for all resources in the classification models */ public static String CLASSIFICATION_BASE_URI = "http://stamina-project.org/codes/"; /** Classifications for which major versions are named 'revisions' instead of 'versions' */ public static Set<String> REVISION_CLASSIFICATIONS = new HashSet<String>(Arrays.asList("ISIC", "NACE", "NAF", "CPF")); public static Map<String, List<String>> LEVEL_NAMES = new HashMap<String, List<String>>(); static { LEVEL_NAMES.put("ISIC", Arrays.asList("section", "division", "group", "class")); LEVEL_NAMES.put("CPC", Arrays.asList("section", "division", "group", "class", "subclass")); LEVEL_NAMES.put("NACE", Arrays.asList("section", "division", "group", "class")); LEVEL_NAMES.put("CPA", Arrays.asList("section", "division", "group", "class", "category", "subcategory")); // TODO Distinguish according to NACE and CPA versions (CPA 2002 and NACE 1.1 have subsections) // TODO Add other cases } /** * Returns the base URI corresponding to a classification version (or classification scheme, CS). * <i>Note<i>: the base URI is not the URI of the classification itself (see getClassificationURI). * * @param classification Short name of the classification, e.g. "NACE", "ISIC", etc. * @param version Version of the classification ("4", "2.1", "2008", etc.). * @return The base URI for all resources of the classification version. */ public static String getCSBaseURI(String classification, String version) { return CLASSIFICATION_BASE_URI + getCSContext(classification, version) + "/"; } /** * Returns the URI corresponding to a classification version. * * @param classification Short name of the classification, e.g. "NACE", "ISIC", etc. * @param version Version of the classification ("4", "2.1", "2008", etc.). * @return The URI for the resource corresponding to the classification version. */ public static String getCSURI(String classification, String version) { return getCSBaseURI(classification, version) + classification.toLowerCase(); } /** * Returns the naming context corresponding to a classification version. * The naming context is the path element dedicated to a given classification scheme below the * classification base URI, for example "nacer2" for NACE Rev. 2, "cpcv21" for CPC Ver.2.1, etc. * * @param classification Short name of the classification, e.g. "NACE", "ISIC", etc. * @param version Version of the classification ("4", "2.1", "2008", etc.). * @return The naming context for the classification version. */ public static String getCSContext(String classification, String version) { String versionQualifier = null; if (REVISION_CLASSIFICATIONS.contains(classification.toUpperCase())) versionQualifier = "r"; else versionQualifier = "v"; return classification.toLowerCase() + versionQualifier + version.replaceAll("\\.", ""); } /** * Returns the long name of a classification version. * * @param classification Short name of the classification, e.g. "NACE", "ISIC", etc. * @param version Version of the classification ("4", "2.1", "2008", etc.). * @return The long name of the classification version. */ public static String getCSLabel(String classification, String version) { String shortName = classification.toUpperCase(); if ("ISIC".equals(shortName)) return String.format("International Standard Industrial Classification of All Economic Activities, Rev.%s", version); if ("CPC".equals(shortName)) return String.format("Central Product Classification, Ver.%s", version); if ("NACE".equals(shortName)) return String.format("Statistical Classification of Economic Activities in the European Community, Rev. %s", version); if ("CPA".equals(shortName)) return String.format("Statistical Classification of Products by Activity, Version %s", version); if ("NAF".equals(shortName)) return String.format("Nomenclature d'activits franaise - NAF rv. %s", version); if ("CPF".equals(shortName)) return String.format("Classification des produits franaise - CPF rv. %s", version); return null; } /** * Returns the short name of a classification version. * Examples of short names are: ISIC Rev.3.1, CPC Ver.2.1, etc. * * @param classification Short name of the classification, e.g. "NACE", "ISIC", etc. * @param version Version of the classification ("4", "2.1", "2008", etc.). * @return The short name of the classification version. */ public static String getCSShortName(String classification, String version) { // A rather dumb implementation, not sure a smarter one is possible String shortName = classification.toUpperCase(); if ("ISIC".equals(shortName)) return String.format("ISIC Rev.%s", version); if ("CPC".equals(shortName)) return String.format("CPC Ver.%s", version); if ("NACE".equals(shortName)) return String.format("NACE Rev. %s", version); if ("CPA".equals(shortName)) return String.format("CPA %s", version); if ("NAF".equals(shortName)) return String.format("NAF rv. %s", version); if ("CPF".equals(shortName)) return String.format("CPF rv. %s", version); return null; } /** * Return the URI of a level in a classification version. * * @param classification Short name of the classification, e.g. "NACE", "ISIC", etc. * @param version Version of the classification ("4", "2.1", "2008", etc.). * @param depth The depth of the level which URI is requested (the most aggregated level has depth 1). * @return The URI for the resource corresponding to the classification version. */ public static String getClassificationLevelURI(String classification, String version, int depth) { String levelName = LEVEL_NAMES.get(classification).get(depth - 1); if (levelName.endsWith("ss")) levelName += "es"; // Case of class and subclass else if (levelName.endsWith("y")) levelName = levelName.substring(0, levelName.length() - 1) + "ies"; // Case of category and subcategory else levelName += "s"; return getCSBaseURI(classification, version) + levelName; } /** * Return the label of a level in a classification version. * * @param classification Short name of the classification, e.g. "NACE", "ISIC", etc. * @param version Version of the classification ("4", "2.1", "2008", etc.). * @param depth The depth of the level which URI is requested (the most aggregated level has depth 1). * @return The label of a level in a classification version. */ public static String getClassificationLevelLabel(String classification, String version, int depth) { String levelName = LEVEL_NAMES.get(classification).get(depth - 1); return getCSLabel(classification, version) + " - " + levelName.substring(0, 1).toUpperCase() + levelName.substring(1); } /** * Returns the base URI corresponding to a correspondence table between two classification versions. * <i>Note<i>: the base URI is not the URI of the correspondence itself (see getCorrespondenceURI). * * @param sourceClassification Short name of the source classification, e.g. "NACE", "ISIC", etc. * @param sourceVersion Version of the source classification ("4", "2.1", "2008", etc.). * @param targetClassification Short name of the target classification. * @param targetVersion Version of the target classification. * @return The URI for the resource corresponding to the correspondence table. */ public static String getCorrespondenceBaseURI(String sourceClassification, String sourceVersion, String targetClassification, String targetVersion) { return CLASSIFICATION_BASE_URI + getCorrespondenceContext(sourceClassification, sourceVersion, targetClassification, targetVersion) + "/"; } /** * Returns the URI corresponding to a correspondence table between two classification versions. * * @param sourceClassification Short name of the source classification, e.g. "NACE", "ISIC", etc. * @param sourceVersion Version of the source classification ("4", "2.1", "2008", etc.). * @param targetClassification Short name of the target classification. * @param targetVersion Version of the target classification. * @return The base URI for all resources of the correspondence table. */ public static String getCorrespondenceURI(String sourceClassification, String sourceVersion, String targetClassification, String targetVersion) { return getCorrespondenceBaseURI(sourceClassification, sourceVersion, targetClassification, targetVersion) + "correspondence"; } /** * Returns the naming context corresponding to a correspondence table between two classification versions. * * @param sourceClassification Short name of the source classification, e.g. "NACE", "ISIC", etc. * @param sourceVersion Version of the source classification ("4", "2.1", "2008", etc.). * @param targetClassification Short name of the target classification. * @param targetVersion Version of the target classification. * @return The naming context for the correspondence table. */ public static String getCorrespondenceContext(String sourceClassification, String sourceVersion, String targetClassification, String targetVersion) { return getCSContext(sourceClassification, sourceVersion) + "-" + getCSContext(targetClassification, targetVersion); } /** * Returns the short name of a correspondence table between two classification versions. * * @param sourceClassification Short name of the source classification, e.g. "NACE", "ISIC", etc. * @param sourceVersion Version of the source classification ("4", "2.1", "2008", etc.). * @param targetClassification Short name of the target classification. * @param targetVersion Version of the target classification. * @return The short name of the correspondence table. */ public static String getCorrespondenceShortName(String sourceClassification, String sourceVersion, String targetClassification, String targetVersion) { return getCSShortName(sourceClassification, sourceVersion) + " - " + getCSShortName(targetClassification, targetVersion); } /** * Computes the URI of a classification item. * * @param code The item code. * @param classification The classification to which the item belongs, e.g. "NACE", "ISIC", etc. * @param version The version of the classification to which the item belongs ("4", "2.1", "2008", etc.). * @return The item URI. */ public static String getItemURI(String code, String classification, String version) { return getCSContext(classification, version) + getItemPathInContext(code, classification, version); } /** * Computes the path part of a classification item URI within the context of its classification version. * Examples of item paths relative to a naming context are: section/B, group/12.1, etc. * * @param code The item code. * @param classification The classification to which the item belongs, e.g. "NACE", "ISIC", etc. * @param version The version of the classification to which the item belongs ("4", "2.1", "2008", etc.). * @return The item path relative to the classification version naming context. */ public static String getItemPathInContext(String code, String classification, String version) { String selector = classification.toUpperCase(); // TODO If CPA do additional things return LEVEL_NAMES.get(selector).get(getItemLevelDepth(code, classification, version) - 1) + "/" + code; } /** * Returns the depth of the level to which an item belongs. * <i>Note<i>: levels are numbered from the top (base 1): the most aggregated level has depth 1. * * @param code The item code. * @param classification The classification to which the item belongs, e.g. "NACE", "ISIC", etc. * @param version The version of the classification to which the item belongs ("4", "2.1", "2008", etc.). * @return The item URI. */ public static int getItemLevelDepth(String code, String classification, String version) { // Except for old versions of the NACE and CPA, the level is the number of characters (except dots) of the code int depth = code.replace(".", "").length(); // For oldest CPA and NACE versions, the subsections (two letters) are level 2, then the codes are digits if (("CPA".equals(classification.toUpperCase())) && (version.length() >= 4) && (Integer.parseInt(version) <= 2002)) { if (Character.isDigit(code.charAt(0))) depth++; } if (("NACE".equals(classification.toUpperCase())) && (version.startsWith("1"))) { if (Character.isDigit(code.charAt(0))) depth++; } // TODO Check that return depth; } /** * Computes the URI of a concept association. * * @param sourceCode The source item code. * @param sourceClassification Short name of the source classification, e.g. "NACE", "ISIC", etc. * @param sourceVersion Version of the source classification ("4", "2.1", "2008", etc.). * @param targetCode The target item code. * @param targetClassification Short name of the target classification. * @param targetVersion Version of the target classification. * @return The association URI. */ public static String getAssociationURI(String sourceCode, String sourceClassification, String sourceVersion, String targetCode, String targetClassification, String targetVersion) { return getCorrespondenceBaseURI(sourceClassification, sourceVersion, targetClassification, targetVersion) + getAssociationPathInContext(sourceCode, targetCode); } /** * Computes the path part of a concept association URI within the context of its correspondence table. * * @param sourceCode The source item code. * @param targetCode The target item code. * @return The association path relative to the correspondence table naming context. */ public static String getAssociationPathInContext(String sourceCode, String targetCode) { return "association/" + sourceCode + "-" + targetCode; } }
package org.caboto; import com.hp.hpl.jena.vocabulary.DCTerms; import com.hp.hpl.jena.vocabulary.DC; import com.hp.hpl.jena.vocabulary.RDF; import org.caboto.vocabulary.Annotea; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.Resource; import org.codehaus.jettison.json.JSONObject; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; /** * * @author pldms */ public class CabotoJsonSupportTest { private Resource resource; private Resource body; public CabotoJsonSupportTest() { } @Before public void setUp() throws Exception { Model model = ModelFactory.createDefaultModel(); resource = model.createResource(); body = model.createResource(); resource.addProperty(RDF.type, model.createResource("http://example.com/TheType")); resource.addProperty(Annotea.annotates, model.createResource("http://example.com/annotated")); resource.addProperty(Annotea.body, body); } /** * Test of generateJsonObject method, of class CabotoJsonSupport. */ @Test public void testGenerateJsonObject_Literal() throws Exception { body.addProperty(DC.subject, "subj1"); CabotoJsonSupport instance = new CabotoJsonSupport(); String expResult = "{\"body\":{\"subject\":[\"subj1\"]},\"annotates\":\"http:\\/\\/example.com\\/annotated\",\"type\":\"TheType\"}"; JSONObject result = instance.generateJsonObject(resource); assertEquals(expResult, result.toString()); body.addProperty(DC.subject, "subj2"); expResult = "{\"body\":{\"subject\":[\"subj2\",\"subj1\"]},\"annotates\":\"http:\\/\\/example.com\\/annotated\",\"type\":\"TheType\"}"; result = instance.generateJsonObject(resource); assertEquals(expResult, result.toString()); } /** * Test of generateJsonObject method, of class CabotoJsonSupport. */ @Test public void testGenerateJsonObject_Resource() throws Exception { body.addProperty(DCTerms.provenance, body.getModel().createResource("http://example.com/doc/1")); CabotoJsonSupport instance = new CabotoJsonSupport(); String expResult = "{\"body\":{\"provenance\":[\"http:\\/\\/example.com\\/doc\\/1\"]},\"annotates\":\"http:\\/\\/example.com\\/annotated\",\"type\":\"TheType\"}"; JSONObject result = instance.generateJsonObject(resource); assertEquals(expResult, result.toString()); body.addProperty(DCTerms.provenance, body.getModel().createResource("http://example.com/doc/2")); expResult = "{\"body\":{\"provenance\":[\"http:\\/\\/example.com\\/doc\\/2\",\"http:\\/\\/example.com\\/doc\\/1\"]},\"annotates\":\"http:\\/\\/example.com\\/annotated\",\"type\":\"TheType\"}"; result = instance.generateJsonObject(resource); assertEquals(expResult, result.toString()); } }
package io.pivotal; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; public class LandmarkQualifier { private static final double MIN_WORD_FRACTION = 0.30; private static final String[] WORD_LIST = { "according", "achieved", "achievement", "across", "action", "added", "addition", "adjacent", "africa", "african", "agreement", "agricultural", "airport", "alabama", "alberta", "album", "albums", "allows", "almost", "along", "also", "although", "america", "american", "among", "anatomical", "ancient", "andalusia", "angeles", "anniversary", "another", "appeal", "appears", "april", "arch", "architect", "architectural", "architecture", "area", "areas", "arizona", "around", "article", "articles", "artist", "artists", "arts", "associated", "association", "atlanta", "attraction", "attractions", "august", "australia", "australian", "author", "authored", "avenue", "award", "away", "back", "background", "baltimore", "band", "bank", "banksia", "base", "based", "basin", "battle", "beach", "became", "become", "began", "behind", "bell", "berlin", "best", "bien", "bill", "black", "block", "blue", "board", "book", "books", "border", "born", "boston", "boulevard", "branch", "brick", "bridge", "bridges", "brings", "brisbane", "british", "brought", "brown", "build", "building", "buildings", "built", "business", "butary", "calgary", "california", "called", "came", "campaign", "campus", "canada", "canadian", "cape", "capital", "caption", "career", "carolina", "case", "cases", "castle", "castles", "catchment", "category", "cathedral", "catholic", "cemetery", "center", "central", "centre", "centuries", "century", "change", "changed", "chapel", "charles", "chicago", "chief", "child", "children", "chimney", "china", "chinese", "christian", "church", "churches", "cinema", "citation", "cite", "cited", "cities", "city", "civil", "class", "classic", "clock", "close", "closed", "club", "coast", "code", "collection", "college", "colonial", "colorado", "columbia", "come", "commercial", "commission", "committee", "commons", "communities", "community", "company", "completed", "complex", "concert", "conference", "considered", "constitution", "constitutional", "constructed", "construction", "contains", "content", "control", "convert", "coord", "coordinates", "corner", "could", "council", "country", "county", "course", "court", "covered", "create", "created", "creek", "cross", "cultural", "culture", "current", "currently", "daily", "date", "david", "days", "deal", "death", "december", "decision", "decisions", "declared", "deco", "dedicated", "defaultsort", "deletion", "delhi", "demolished", "demolition", "department", "described", "description", "design", "designated", "designation", "designed", "despite", "destroyed", "detroit", "developed", "development", "different", "directed", "director", "display", "distance", "distinctive", "district", "districts", "divid", "documentary", "dome", "downtown", "dubai", "earlier", "early", "earth", "east", "eastern", "economy", "edition", "education", "eiffel", "eight", "election", "elevati", "elevation", "empire", "engineering", "england", "english", "entrance", "episode", "erected", "established", "establishing", "estate", "europe", "european", "even", "event", "events", "eventually", "ever", "every", "example", "exhibition", "exist", "external", "facilities", "factory", "fair", "falls", "familiar", "family", "famous", "farm", "father", "feature", "featured", "features", "february", "federal", "field", "file", "film", "films", "final", "find", "fire", "firm", "first", "five", "flag", "florida", "following", "force", "forest", "form", "former", "forms", "fort", "found", "foundation", "founded", "fountain", "four", "france", "francisco", "free", "freedom", "french", "front", "future", "gallery", "game", "games", "garden", "gardens", "gate", "gave", "general", "genre", "geographic", "geographical", "geography", "george", "georgia", "german", "germany", "given", "going", "golden", "good", "google", "gothic", "government", "grand", "great", "green", "ground", "group", "guadalajara", "guide", "half", "hall", "harbour", "head", "headquarters", "health", "heart", "height", "held", "help", "helped", "henry", "heritage", "high", "highest", "highly", "highway", "hill", "hills", "historic", "historical", "history", "hollywood", "home", "hong", "hospital", "hotel", "hotels", "house", "houses", "housing", "however", "html", "http", "https", "human", "icon", "iconic", "ight", "illinois", "image", "images", "importance", "important", "include", "included", "includes", "including", "independent", "india", "indian", "indiana", "industrial", "industry", "information", "inline", "inside", "institute", "inter", "interest", "international", "involved", "ireland", "isbn", "island", "issue", "issued", "issues", "italy", "jackson", "james", "january", "japan", "japanese", "jazz", "jersey", "john", "joseph", "journal", "judge", "judgement", "judgment", "july", "junction", "june", "justice", "kansas", "keep", "kentucky", "king", "kingdom", "known", "kong", "lake", "lakes", "land", "lang", "language", "large", "largest", "last", "late", "later", "laws", "lawsuit", "lead", "leading", "league", "left", "legal", "legislation", "length", "level", "library", "life", "light", "lighthouse", "like", "line", "link", "links", "list", "listed", "lists", "literary", "literature", "little", "live", "local", "locality", "locally", "located", "location", "locations", "london", "long", "longew", "longm", "longs", "lost", "louis", "louisville", "lower", "made", "madison", "madrid", "magazine", "main", "major", "make", "makes", "making", "mall", "manhattan", "mansion", "many", "maps", "march", "maria", "mark", "marked", "market", "martin", "mary", "maryland", "massachusetts", "mayor", "media", "medical", "medieval", "melbourne", "memorial", "mention", "mentioned", "metal", "metropolitan", "mexico", "michael", "michigan", "middle", "mile", "miles", "mill", "million", "missing", "mission", "mississippi", "model", "modern", "monastery", "monument", "monuments", "mosque", "mount", "mountain", "mountains", "move", "moved", "movement", "movie", "movies", "much", "mumbai", "municipal", "municipality", "museum", "museums", "music", "musical", "name", "named", "names", "nation", "national", "native", "natural", "nature", "navbox", "navigation", "nbsp", "ndash", "near", "nearby", "nearest", "needed", "neighborhood", "nevada", "never", "news", "newspaper", "next", "night", "nomination", "north", "northern", "northwest", "notability", "notable", "note", "noted", "novel", "november", "nowiki", "nrhp", "nris", "number", "numerous", "ocean", "october", "office", "official", "often", "ohio", "older", "oldest", "omaha", "ontario", "open", "opened", "opening", "opera", "order", "oregon", "original", "originally", "others", "outside", "owned", "page", "pages", "pakistan", "palace", "paper", "parent", "paris", "parish", "park", "parks", "part", "parts", "party", "pass", "passed", "passes", "passing", "past", "paul", "peak", "pennsylvania", "people", "performance", "period", "peter", "philadelphia", "photo", "picture", "pictures", "piece", "pittsburgh", "place", "places", "plans", "plant", "play", "played", "plaza", "plot", "point", "points", "police", "political", "popular", "population", "port", "portland", "position", "post", "power", "precedent", "present", "preservation", "preserve", "preserved", "president", "press", "primary", "private", "probably", "process", "produced", "production", "program", "project", "projects", "prominent", "properties", "property", "protected", "protection", "provided", "provides", "province", "public", "publication", "publications", "publishe", "published", "publisher", "pushpin", "quality", "queen", "quot", "race", "radio", "railway", "range", "reached", "real", "reason", "received", "recent", "recently", "recognizable", "recognized", "record", "recorded", "recording", "records", "redirect", "reference", "references", "reflist", "reform", "regarded", "regarding", "region", "regional", "register", "registered", "related", "release", "released", "religious", "remain", "remained", "remains", "renaissance", "report", "represented", "research", "residential", "residents", "responsible", "restaurant", "restoration", "restored", "result", "resulted", "retrieved", "review", "revival", "ridge", "right", "rights", "river", "road", "roads", "robert", "rock", "role", "roman", "route", "royal", "ruled", "ruling", "runs", "russia", "said", "saint", "santa", "scale", "scene", "school", "schools", "science", "sculpture", "season", "seat", "seattle", "second", "section", "seems", "seen", "september", "series", "serve", "served", "serves", "service", "settlement", "several", "shopping", "shot", "show", "shows", "side", "sign", "signed", "significance", "significant", "signs", "silver", "similar", "since", "singapore", "single", "site", "sites", "situated", "size", "skyline", "small", "smith", "social", "society", "sold", "song", "songs", "sound", "source", "sources", "south", "southern", "space", "spain", "spanish", "special", "speech", "spire", "sports", "spring", "springs", "square", "stadium", "stage", "stand", "standing", "stands", "star", "started", "state", "states", "station", "stations", "statue", "status", "steel", "still", "stirling", "stone", "stood", "store", "stories", "story", "street", "streets", "struct", "structure", "structures", "stub", "students", "studies", "studio", "study", "style", "subject", "suburb", "success", "successful", "summit", "support", "supreme", "surrounding", "sydney", "symbol", "system", "take", "taken", "takes", "talk", "tall", "tallest", "tamil", "tary", "team", "television", "template", "temple", "terms", "texas", "text", "theater", "theatre", "theory", "think", "thomas", "though", "three", "throughout", "thumb", "time", "Time: 209.358 ms", "times", "Timing is on.", "title", "today", "together", "took", "toronto", "tour", "tourism", "tourist", "tourists", "tower", "towers", "town", "towns", "township", "trade", "traffic", "trail", "tree", "trees", "trial", "tribut", "tributaries", "tributary", "twin", "type", "ukraine", "union", "unique", "united", "university", "unnamed", "upon", "upper", "urban", "used", "user", "using", "utah", "valley", "various", "venue", "version", "viccity", "victoria", "victorian", "victory", "video", "view", "views", "village", "virginia", "visible", "visit", "visited", "visitors", "visual", "volume", "vote", "wales", "walk", "washington", "water", "website", "well", "went", "west", "western", "white", "whose", "widely", "wikipedia", "william", "within", "women", "work", "worked", "working", "works", "world", "would", "written", "wrote", "year", "years", "york", "young", "zealand" }; private static Set<String> WORD_SET; static { WORD_SET = new HashSet<String>(Arrays.asList(WORD_LIST)); } public static double getWordFraction (List<String> testWordList) { double rv = 0.0; int nMatches = 0; for (String word : testWordList) { if (WORD_SET.contains(word.toLowerCase())) { nMatches++; } } rv = (double) nMatches / (double) testWordList.size(); return rv; } public static boolean isPossibleLandmark (List<String> testWordList) { return getWordFraction(testWordList) >= MIN_WORD_FRACTION; } }
// 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.media.sound; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Properties; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine; import javax.sound.sampled.FloatControl; import javax.sound.sampled.Line; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.SourceDataLine; import javax.sound.sampled.UnsupportedAudioFileException; import org.apache.commons.io.IOUtils; import com.samskivert.util.Config; import com.samskivert.util.ConfigUtil; import com.samskivert.util.Interval; import com.samskivert.util.LRUHashMap; import com.samskivert.util.Queue; import com.samskivert.util.RuntimeAdjust; import com.samskivert.util.StringUtil; import com.threerings.resource.ResourceManager; import com.threerings.util.RandomUtil; import com.threerings.media.Log; import com.threerings.media.MediaPrefs; /** * Manages the playing of audio files. */ public class SoundManager { /** * Create instances of this for your application to differentiate * between different types of sounds. */ public static class SoundType { /** * Construct a new SoundType. * Which should be a static variable stashed somewhere for the * entire application to share. * * @param strname a short string identifier, preferably without spaces. */ public SoundType (String strname) { _strname = strname; } public String toString () { return _strname; } protected String _strname; } /** * A control for sounds. */ public static interface Frob { /** * Stop playing or looping the sound. * At present, the granularity of this command is limited to the * buffer size of the line spooler, or about 8k of data. Thus, * if playing an 11khz sample, it could take 8/11ths of a second * for the sound to actually stop playing. */ public void stop (); /** * Set the volume of the sound. */ public void setVolume (float vol); /** * Get the volume of this sound. */ public float getVolume (); } /** The default sound type. */ public static final SoundType DEFAULT = new SoundType("default"); /** * Constructs a sound manager. */ public SoundManager (ResourceManager rmgr) { this(rmgr, null, null); } /** * Constructs a sound manager. * * @param defaultClipBundle * @param defaultClipPath The pathname of a sound clip to use as a * fallback if another sound clip cannot be located. */ public SoundManager ( ResourceManager rmgr, String defaultClipBundle, String defaultClipPath) { // save things off _rmgr = rmgr; _defaultClipBundle = defaultClipBundle; _defaultClipPath = defaultClipPath; } /** * Shut the damn thing off. */ public void shutdown () { // TODO: we need to stop any looping sounds synchronized (_queue) { _queue.clear(); if (_spoolerCount > 0) { _queue.append(new SoundKey(DIE)); // signal death } } synchronized (_clipCache) { _lockedClips.clear(); _configs.clear(); } } /** * Returns a string summarizing our volume settings and disabled sound * types. */ public String summarizeState () { StringBuffer buf = new StringBuffer(); buf.append("clipVol=").append(_clipVol); buf.append(", disabled=["); int ii = 0; for (Iterator iter = _disabledTypes.iterator(); iter.hasNext(); ) { if (ii++ > 0) { buf.append(", "); } buf.append(iter.next()); } return buf.append("]").toString(); } /** * Is the specified soundtype enabled? */ public boolean isEnabled (SoundType type) { // by default, types are enabled.. return (!_disabledTypes.contains(type)); } /** * Turns on or off the specified sound type. */ public void setEnabled (SoundType type, boolean enabled) { if (enabled) { _disabledTypes.remove(type); } else { _disabledTypes.add(type); } } /** * Sets the volume for all sound clips. * * @param vol a volume parameter between 0f and 1f, inclusive. */ public void setClipVolume (float vol) { _clipVol = Math.max(0f, Math.min(1f, vol)); } /** * Get the volume for all sound clips. */ public float getClipVolume () { return _clipVol; } /** * Optionally lock the sound data prior to playing, to guarantee * that it will be quickly available for playing. */ public void lock (String pkgPath, String key) { enqueue(new SoundKey(LOCK, pkgPath, key), true); } /** * Unlock the specified sound so that its resources can be freed. */ public void unlock (String pkgPath, String key) { enqueue(new SoundKey(UNLOCK, pkgPath, key), true); } /** * Batch lock a list of sounds. */ public void lock (String pkgPath, String[] keys) { for (int ii=0; ii < keys.length; ii++) { enqueue(new SoundKey(LOCK, pkgPath, keys[ii]), (ii == 0)); } } /** * Batch unlock a list of sounds. */ public void unlock (String pkgPath, String[] keys) { for (int ii=0; ii < keys.length; ii++) { enqueue(new SoundKey(UNLOCK, pkgPath, keys[ii]), (ii == 0)); } } /** * Play the specified sound of as the specified type of sound, immediately. * Note that a sound need not be locked prior to playing. */ public void play (SoundType type, String pkgPath, String key) { play(type, pkgPath, key, 0); } /** * Play the specified sound after the specified delay. * @param delay the delay in milliseconds. */ public void play (SoundType type, String pkgPath, String key, int delay) { if (type == null) { type = DEFAULT; // let the lazy kids play too } if ((_clipVol != 0f) && isEnabled(type)) { final SoundKey skey = new SoundKey(PLAY, pkgPath, key, delay, _clipVol); if (delay > 0) { new Interval() { public void expired () { addToPlayQueue(skey); } }.schedule(delay); } else { addToPlayQueue(skey); } } } /** * Loop the specified sound. */ public Frob loop (SoundType type, String pkgPath, String key) { SoundKey skey = new SoundKey(LOOP, pkgPath, key, 0, _clipVol); addToPlayQueue(skey); return skey; // it is a frob } /** * Add the sound clip key to the queue to be played. */ protected void addToPlayQueue (SoundKey skey) { boolean queued = enqueue(skey, true); if (queued) { if (_verbose.getValue()) { Log.info("Sound request [key=" + skey.key + "]."); } } else /* if (_verbose.getValue()) */ { Log.warning("SoundManager not playing sound because " + "too many sounds in queue [key=" + skey + "]."); } } /** * Enqueue a new SoundKey. */ protected boolean enqueue (SoundKey key, boolean okToStartNew) { boolean add; boolean queued; synchronized (_queue) { if (key.cmd == PLAY && _queue.size() > MAX_QUEUE_SIZE) { queued = add = false; } else { _queue.appendLoud(key); queued = true; add = okToStartNew && (_freeSpoolers == 0) && (_spoolerCount < MAX_SPOOLERS); if (add) { _spoolerCount++; } } } // and if we need a new thread, add it if (add) { Thread spooler = new Thread("narya SoundManager line spooler") { public void run () { spoolerRun(); } }; spooler.setDaemon(true); spooler.start(); } return queued; } /** * This is the primary run method of the sound-playing threads. */ protected void spoolerRun () { while (true) { try { SoundKey key; synchronized (_queue) { _freeSpoolers++; key = (SoundKey) _queue.get(MAX_WAIT_TIME); _freeSpoolers if (key == null || key.cmd == DIE) { _spoolerCount // if dieing and there are others to kill, do so if (key != null && _spoolerCount > 0) { _queue.appendLoud(key); } return; } } // process the command processKey(key); } catch (Exception e) { Log.logStackTrace(e); } } } /** * Process the requested command in the specified SoundKey. */ protected void processKey (SoundKey key) throws Exception { switch (key.cmd) { case PLAY: case LOOP: playSound(key); break; case LOCK: if (!isTesting()) { synchronized (_clipCache) { try { getClipData(key); // preload // copy cached to lock map _lockedClips.put(key, _clipCache.get(key)); } catch (Exception e) { // don't whine about LOCK failures unless // we are verbosely logging if (_verbose.getValue()) { throw e; } } } } break; case UNLOCK: synchronized (_clipCache) { _lockedClips.remove(key); } break; } } /** * On a spooling thread, */ protected void playSound (SoundKey key) { if (!key.running) { return; } key.thread = Thread.currentThread(); SourceDataLine line = null; try { // get the sound data from our LRU cache byte[] data = getClipData(key); if (data == null) { return; // borked! } else if (key.isExpired()) { if (_verbose.getValue()) { Log.info("Sound expired [key=" + key.key + "]."); } return; } AudioInputStream stream = AudioSystem.getAudioInputStream( new ByteArrayInputStream(data)); if (key.cmd == LOOP) { stream.mark(data.length); } // open the sound line AudioFormat format = stream.getFormat(); line = (SourceDataLine) AudioSystem.getLine( new DataLine.Info(SourceDataLine.class, format)); line.open(format, LINEBUF_SIZE); float setVolume = 1; line.start(); _soundSeemsToWork = true; do { // play the sound byte[] buffer = new byte[LINEBUF_SIZE]; int count = 0; while (key.running && count != -1) { float vol = key.volume; if (vol != setVolume) { adjustVolume(line, vol); setVolume = vol; } try { count = stream.read(buffer, 0, buffer.length); } catch (IOException e) { // this shouldn't ever ever happen because the stream // we're given is from a reliable source Log.warning("Error reading clip data! [e=" + e + "]."); return; } if (count >= 0) { line.write(buffer, 0, count); } } // if we're going to loop, reset the stream to the beginning if (key.cmd == LOOP) { stream.reset(); } } while (key.cmd == LOOP && key.running); // sleep the drain time. We never trust line.drain() because // it is buggy and locks up on natively multithreaded systems // (linux, winXP with HT). float sampleRate = format.getSampleRate(); if (sampleRate == AudioSystem.NOT_SPECIFIED) { sampleRate = 11025; // most of our sounds are } int sampleSize = format.getSampleSizeInBits(); if (sampleSize == AudioSystem.NOT_SPECIFIED) { sampleSize = 16; } int drainTime = (int) Math.ceil( (LINEBUF_SIZE * 8 * 1000) / (sampleRate * sampleSize)); // add in a fudge factor of half a second drainTime += 500; try { Thread.sleep(drainTime); } catch (InterruptedException ie) { } } catch (IOException ioe) { Log.warning("Error loading sound file [key=" + key + ", e=" + ioe + "]."); } catch (UnsupportedAudioFileException uafe) { Log.warning("Unsupported sound format [key=" + key + ", e=" + uafe + "]."); } catch (LineUnavailableException lue) { String err = "Line not available to play sound [key=" + key.key + ", e=" + lue + "]."; if (_soundSeemsToWork) { Log.warning(err); } else { // this error comes every goddamned time we play a sound on // someone with a misconfigured sound card, so let's just keep // it to ourselves Log.debug(err); } } finally { if (line != null) { line.close(); } key.thread = null; } } /** * @return true if we're using a test sound directory. */ protected boolean isTesting () { return !StringUtil.blank(_testDir.getValue()); } /** * Called by spooling threads, loads clip data from the resource * manager or the cache. */ protected byte[] getClipData (SoundKey key) throws IOException, UnsupportedAudioFileException { byte[][] data; boolean verbose = _verbose.getValue(); synchronized (_clipCache) { // if we're testing, clear all non-locked sounds every time if (isTesting()) { _clipCache.clear(); } data = (byte[][]) _clipCache.get(key); // see if it's in the locked cache (we first look in the regular // clip cache so that locked clips that are still cached continue // to be moved to the head of the LRU queue) if (data == null) { data = (byte[][]) _lockedClips.get(key); } if (data == null) { // if there is a test sound, JUST use the test sound. InputStream stream = getTestClip(key); if (stream != null) { data = new byte[1][]; data[0] = IOUtils.toByteArray(stream); } else { // otherwise, randomize between all available sounds Config c = getConfig(key); String[] names = c.getValue(key.key, (String[])null); if (names == null) { Log.warning("No such sound [key=" + key + "]."); return null; } data = new byte[names.length][]; String bundle = c.getValue("bundle", (String)null); for (int ii=0; ii < names.length; ii++) { data[ii] = loadClipData(bundle, names[ii]); } } _clipCache.put(key, data); } } return (data.length > 0) ? data[RandomUtil.getInt(data.length)] : null; } protected InputStream getTestClip (SoundKey key) { String testDirectory = _testDir.getValue(); if (StringUtil.blank(testDirectory)) { return null; } final String namePrefix = key.key; File f = new File(testDirectory); File[] list = f.listFiles(new FilenameFilter() { public boolean accept (File f, String name) { if (name.startsWith(namePrefix)) { String backhalf = name.substring(namePrefix.length()); int dot = backhalf.indexOf('.'); if (dot == -1) { dot = backhalf.length(); } // allow the file if the portion of the name // after the prefix but before the extension is blank // or a parsable integer String extra = backhalf.substring(0, dot); if ("".equals(extra)) { return true; } else { try { Integer.parseInt(extra); // success! return true; } catch (NumberFormatException nfe) { // not a number, we fall through... } } // else fall through } return false; } }); int size = (list == null) ? 0 : list.length; if (size > 0) { File pick = list[RandomUtil.getInt(size)]; try { return new FileInputStream(pick); } catch (Exception e) { Log.warning("Error reading test sound [e=" + e + ", file=" + pick + "]."); } } return null; } /** * Read the data from the resource manager. */ protected byte[] loadClipData (String bundle, String path) throws IOException { InputStream clipin = null; try { clipin = _rmgr.getResource(bundle, path); } catch (FileNotFoundException fnfe) { // try from the classpath try { clipin = _rmgr.getResource(path); } catch (FileNotFoundException fnfe2) { // only play the default sound if we have verbose sound // debuggin turned on. if (_verbose.getValue()) { Log.warning("Could not locate sound data [bundle=" + bundle + ", path=" + path + "]."); if (_defaultClipPath != null) { try { clipin = _rmgr.getResource( _defaultClipBundle, _defaultClipPath); } catch (FileNotFoundException fnfe3) { try { clipin = _rmgr.getResource(_defaultClipPath); } catch (FileNotFoundException fnfe4) { Log.warning("Additionally, the default " + "fallback sound could not be located " + "[bundle=" + _defaultClipBundle + ", path=" + _defaultClipPath + "]."); } } } else { Log.warning("No fallback default sound specified!"); } } // if we couldn't load the default, rethrow if (clipin == null) { throw fnfe2; } } } return IOUtils.toByteArray(clipin); } /** * Get the cached Config. */ protected Config getConfig (SoundKey key) { Config c = (Config) _configs.get(key.pkgPath); if (c == null) { String propPath = key.pkgPath + Sounds.PROP_NAME; Properties props = new Properties(); try { props = ConfigUtil.loadInheritedProperties( propPath + ".properties", _rmgr.getClassLoader()); } catch (IOException ioe) { Log.warning("Failed to load sound properties " + "[path=" + propPath + ", error=" + ioe + "]."); } c = new Config(propPath, props); _configs.put(key.pkgPath, c); } return c; } // /** // * Adjust the volume of this clip. // */ // protected static void adjustVolumeIdeally (Line line, float volume) // if (line.isControlSupported(FloatControl.Type.VOLUME)) { // FloatControl vol = (FloatControl) // line.getControl(FloatControl.Type.VOLUME); // float min = vol.getMinimum(); // float max = vol.getMaximum(); // float ourval = (volume * (max - min)) + min; // Log.debug("adjust vol: [min=" + min + ", ourval=" + ourval + // ", max=" + max + "]."); // vol.setValue(ourval); // } else { // // fall back // adjustVolume(line, volume); /** * Use the gain control to implement volume. */ protected static void adjustVolume (Line line, float vol) { FloatControl control = (FloatControl) line.getControl(FloatControl.Type.MASTER_GAIN); // the only problem is that gain is specified in decibals, // which is a logarithmic scale. // Since we want max volume to leave the sample unchanged, our // maximum volume translates into a 0db gain. float gain; if (vol == 0f) { gain = control.getMinimum(); } else { gain = (float) ((Math.log(vol) / Math.log(10.0)) * 20.0); } control.setValue(gain); //Log.info("Set gain: " + gain); } /** * A key for tracking sounds. */ protected static class SoundKey implements Frob { public byte cmd; public String pkgPath; public String key; public long stamp; /** Should we still be running? */ public volatile boolean running = true; public volatile float volume; /** The player thread, if it's playing us. */ public Thread thread; /** * Create a SoundKey that just contains the specified command. * DIE. */ public SoundKey (byte cmd) { this.cmd = cmd; } /** * Quicky constructor for music keys and lock operations. */ public SoundKey (byte cmd, String pkgPath, String key) { this(cmd); this.pkgPath = pkgPath; this.key = key; } /** * Constructor for a sound effect soundkey. */ public SoundKey (byte cmd, String pkgPath, String key, int delay, float volume) { this(cmd, pkgPath, key); stamp = System.currentTimeMillis() + delay; this.volume = volume; } // documentation inherited from interface Frob public void stop () { running = false; Thread t = thread; if (t != null) { // doesn't actually ever seem to do much t.interrupt(); } } // documentation inherited from interface Frob public void setVolume (float vol) { volume = Math.max(0f, Math.min(1f, vol)); } // documentation inherited from interface Frob public float getVolume () { return volume; } /** * Has this sound key expired. */ public boolean isExpired () { return (stamp + MAX_SOUND_DELAY < System.currentTimeMillis()); } // documentation inherited public String toString () { return "SoundKey{cmd=" + cmd + ", pkgPath=" + pkgPath + ", key=" + key + "}"; } // documentation inherited public int hashCode () { return pkgPath.hashCode() ^ key.hashCode(); } // documentation inherited public boolean equals (Object o) { if (o instanceof SoundKey) { SoundKey that = (SoundKey) o; return this.pkgPath.equals(that.pkgPath) && this.key.equals(that.key); } return false; } } /** The path of the default sound to use for missing sounds. */ protected String _defaultClipBundle, _defaultClipPath; /** The resource manager from which we obtain audio files. */ protected ResourceManager _rmgr; /** The queue of sound clips to be played. */ protected Queue _queue = new Queue(); /** The number of currently active LineSpoolers. */ protected int _spoolerCount, _freeSpoolers; /** If we every play a sound successfully, this is set to true. */ protected boolean _soundSeemsToWork = false; /** Volume level for sound clips. */ protected float _clipVol = 1f; /** The cache of recent audio clips . */ protected LRUHashMap _clipCache = new LRUHashMap(10); /** The set of locked audio clips; this is separate from the LRU so * that locking clips doesn't booch up an otherwise normal caching * agenda. */ protected HashMap _lockedClips = new HashMap(); /** A set of soundTypes for which sound is enabled. */ protected HashSet _disabledTypes = new HashSet(); /** A cache of config objects we've created. */ protected LRUHashMap _configs = new LRUHashMap(5); /** Soundkey command constants. */ protected static final byte PLAY = 0; protected static final byte LOCK = 1; protected static final byte UNLOCK = 2; protected static final byte DIE = 3; protected static final byte LOOP = 4; /** A pref that specifies a directory for us to get test sounds from. */ protected static RuntimeAdjust.FileAdjust _testDir = new RuntimeAdjust.FileAdjust( "Test sound directory", "narya.media.sound.test_dir", MediaPrefs.config, true, ""); protected static RuntimeAdjust.BooleanAdjust _verbose = new RuntimeAdjust.BooleanAdjust( "Verbose sound event logging", "narya.media.sound.verbose", MediaPrefs.config, false); /** The queue size at which we start to ignore requests to play sounds. */ protected static final int MAX_QUEUE_SIZE = 25; /** The maximum time after which we throw away a sound rather * than play it. */ protected static final long MAX_SOUND_DELAY = 400L; /** The size of the line's buffer. */ protected static final int LINEBUF_SIZE = 8 * 1024; /** The maximum time a spooler will wait for a stream before * deciding to shut down. */ protected static final long MAX_WAIT_TIME = 30000L; /** The maximum number of spoolers we'll allow. This is a lot. */ protected static final int MAX_SPOOLERS = 12; }
package io.teknek.model; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; /** * This operator opens a Pipe to a subprocess connecting the input and output streams. * Child classes should interact with the pipe by writing to the outstream, flushing, * and then reading from the input stream. See TestPipeOperator for an example. * @author edward * */ public abstract class PipeOperator extends Operator { public static final String PIPE_OPERATOR_COMMAND = "pipe.operator.command.and.arguments"; protected CountDownLatch waitForShutdown; protected Thread waitForTheEnd; protected AtomicInteger exitValue = new AtomicInteger(-9999); protected InputStream output; protected InputStream error; protected OutputStream toProcess; protected Process process; @Override public void setProperties(Map<String, Object> properties) { super.setProperties(properties); String [] commandAndArgs = (String []) properties.get(PIPE_OPERATOR_COMMAND); Runtime rt = Runtime.getRuntime(); final Process process; try { process = rt.exec(commandAndArgs); } catch (IOException e) { throw new RuntimeException (e); } waitForShutdown = new CountDownLatch(1); output = process.getInputStream(); error = process.getErrorStream(); toProcess = process.getOutputStream(); waitForTheEnd = new Thread() { public void run() { try { exitValue.set(process.waitFor()); waitForShutdown.countDown(); } catch (InterruptedException e) { waitForShutdown.countDown(); } } }; waitForTheEnd.start(); } @Override public abstract void handleTuple(ITuple tuple) ; @Override public void close() { if (waitForShutdown == null){ throw new RuntimeException("Instance is not started. Can not shutdown."); } process.destroy(); try { waitForShutdown.await(10, TimeUnit.SECONDS); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
// 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.media.sprite; import java.awt.Dimension; import java.awt.Graphics2D; import java.awt.RenderingHints; import com.samskivert.swing.Label; /** * A sprite that uses a label to render itself. If the label has not been * previously laid out (see {@link Label#layout}) it will be done when the * sprite is added to a media panel. If the label is altered after the * sprite is created, {@link #updateBounds} should be called. */ public class LabelSprite extends Sprite { /** * Constructs a label sprite that renders itself with the specified * label. */ public LabelSprite (Label label) { _label = label; } /** * Returns the label displayed by this sprite. */ public Label getLabel () { return _label; } /** * Indicates that our label should be rendered with antialiased text. */ public void setAntiAliased (boolean antiAliased) { _antiAliased = antiAliased; } /** * Updates the bounds of the sprite after a change to the label. */ public void updateBounds () { Dimension size = _label.getSize(); _bounds.width = size.width; _bounds.height = size.height; } // documentation inherited protected void init () { super.init(); // if our label is not yet laid out, do the deed if (!_label.isLaidOut()) { layoutLabel(); } // size the bounds to fit our label updateBounds(); } // documentation inherited public void paint (Graphics2D gfx) { _label.render(gfx, _bounds.x, _bounds.y); } /** * Lays out our underlying label which must be done if the text is * changed. */ protected void layoutLabel () { Graphics2D gfx = (Graphics2D)_mgr.getMediaPanel().getGraphics(); if (gfx != null) { gfx.setRenderingHint(RenderingHints.KEY_ANTIALIASING, (_antiAliased) ? RenderingHints.VALUE_ANTIALIAS_ON : RenderingHints.VALUE_ANTIALIAS_OFF); _label.layout(gfx); gfx.dispose(); } } /** The label associated with this sprite. */ protected Label _label; /** Whether or not to use anti-aliased rendering. */ protected boolean _antiAliased; }
package lexek.fetcher; import com.github.benmanes.caffeine.cache.Caffeine; import com.github.benmanes.caffeine.cache.LoadingCache; import com.google.common.collect.ImmutableMap; import io.netty.buffer.ByteBuf; import io.netty.buffer.PooledByteBufAllocator; import io.netty.handler.codec.http.HttpContentDecompressor; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http.HttpUtil; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import reactor.core.publisher.Mono; import reactor.ipc.netty.http.client.HttpClient; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.time.temporal.ChronoUnit; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.concurrent.TimeUnit; @Service public class FetcherService { private final Logger logger = LoggerFactory.getLogger(FetcherService.class); private final HttpClient httpClient; private final LoadingCache<String, Mono<Map<String, String>>> cache; private long maxBodySize = 8388608; private long maxSupportedRedirects = 1; private boolean handleNonStandardPorts = false; public FetcherService() { this.httpClient = HttpClient.create( options -> { options.sslSupport(); options.afterChannelInit(channel -> //need this to handle compressed responses channel.pipeline().addBefore("reactor.right.reactiveBridge", "decompressor", new HttpContentDecompressor()) ); } ); this.cache = Caffeine .<String, Mono<Map<String, String>>>newBuilder() .expireAfterAccess(10, TimeUnit.MINUTES) .maximumSize(500) .build(this::doFetch); } public Mono<Map<String, String>> fetch(String url) { if (StringUtils.isEmpty(url)) { return Mono.just(ImmutableMap.of("error", "Url is not present")); } return cache.get(url); } private Mono<Map<String, String>> doFetch(String url) { return validateUrlAndFetch(url, 0); } private Mono<Map<String, String>> validateUrlAndFetch(String url, int redirect) { try { return doFetch(new URL(url), redirect); } catch (MalformedURLException e) { return Mono.just(ImmutableMap.of("error", "Incorrect url")); } } private Mono<Map<String, String>> doFetch(URL url, int redirectNumber) { if (redirectNumber > maxSupportedRedirects) { return Mono.just(ImmutableMap.of( "error", "Too many consequent redirects" )); } if (!handleNonStandardPorts) { int port = url.getPort(); if (port != -1) { if (url.getProtocol().equals("http") && port != 80 || url.getProtocol().equals("https") && port != 443) { return Mono.just(ImmutableMap.of( "error", "Handling of non-standard ports is disabled" )); } } } return httpClient .get(url.toExternalForm()) .map(ReactorRequestWrapper::new) .then(response -> handleResponse(url, response, redirectNumber)) .doOnError(throwable -> logger.warn("caught exception", throwable)) .otherwise((e) -> Mono.just(ImmutableMap.of( "error", e.getMessage() != null ? e.getMessage() : e.getClass().toString() ))) .cache() .timeout(Duration.of(30, ChronoUnit.SECONDS)); } private Mono<Map<String, String>> handleResponse(URL url, ReactorRequestWrapper response, int redirectNumber) { int status = response.status(); if (status == 301 || status == 302) { String location = response.headers().get(HttpHeaderNames.LOCATION); if (location == null) { return Mono.just(ImmutableMap.of("error", "Http redirect without location header")); } return validateUrlAndFetch(location, redirectNumber + 1); } if (status != 200) { return Mono.just(ImmutableMap.of("error", "Invalid response status " + status)); } CharSequence mimeType = HttpUtil.getMimeType(response); if (mimeType == null) { return Mono.just(ImmutableMap.of("error", "No content-type")); } if (!Objects.equals(mimeType, "text/html")) { return Mono.just(ImmutableMap.of( "error", "Unsupported content-type", "mime", mimeType.toString() )); } long contentLength = HttpUtil.getContentLength(response, -1); if (contentLength > maxBodySize) { return Mono.just(ImmutableMap.of( "error", "Content is too big", "mime", mimeType.toString() )); } return readyBody(response) .cast(String.class) .map(Jsoup::parse) .map(FetcherService::parseBody) .doOnNext(result -> { if (!result.containsKey("error")) { result.put("hostname", url.getHost()); result.put("mime", mimeType.toString()); } }); } private Mono<String> readyBody(ReactorRequestWrapper response) { Charset charset = HttpUtil.getCharset(response, StandardCharsets.UTF_8); return Mono.using( PooledByteBufAllocator.DEFAULT::buffer, buffer -> response .originalResponse() .receiveContent() .map((content) -> buffer.writeBytes(content.content())) .all((ignore) -> buffer.readableBytes() < maxBodySize) .then() .then(() -> Mono.just(buffer.toString(charset))), ByteBuf::release ); } private static Map<String, String> parseBody(Document document) { Map<String, String> result = new HashMap<>(); for (Element element : document.head().children()) { String tag = element.tag().getName(); switch (tag) { case "meta": { String property = element.attr("PROPERTY"); String content = element.attr("CONTENT"); if (property != null && content != null) { if (property.startsWith("og:")) { result.put(property, content); } } break; } case "title": { result.put("title", element.ownText()); break; } } } return result; } @Value("${og.maxBodySize ?: 8388608}") public void setMaxBodySize(long maxBodySize) { this.maxBodySize = maxBodySize; } @Value("${og.maxSupportedRedirects ?: 1}") public void setMaxSupportedRedirects(long maxSupportedRedirects) { this.maxSupportedRedirects = maxSupportedRedirects; } @Value("${og.handleNonStandardPorts ?: false}") public void setHandleNonStandardPorts(boolean handleNonStandardPorts) { this.handleNonStandardPorts = handleNonStandardPorts; } }
// $Id: IsoSceneView.java,v 1.81 2001/12/18 08:38:33 mdb Exp $ package com.threerings.miso.scene; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Polygon; import java.awt.Shape; import java.awt.Stroke; import java.awt.Rectangle; import java.awt.FontMetrics; import java.awt.Point; import java.awt.Font; import java.awt.BasicStroke; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import com.samskivert.util.HashIntMap; import com.threerings.media.sprite.DirtyRectList; import com.threerings.media.sprite.Path; import com.threerings.media.sprite.SpriteManager; import com.threerings.media.tile.ObjectTile; import com.threerings.media.tile.ObjectTileLayer; import com.threerings.media.tile.Tile; import com.threerings.media.tile.TileLayer; import com.threerings.miso.Log; import com.threerings.miso.scene.DirtyItemList.DirtyItem; import com.threerings.miso.scene.util.AStarPathUtil; import com.threerings.miso.scene.util.IsoUtil; import com.threerings.miso.tile.BaseTileLayer; /** * The iso scene view provides an isometric view of a particular * scene. */ public class IsoSceneView implements SceneView { /** * Constructs an iso scene view. * * @param spritemgr the sprite manager. * @param model the data model. */ public IsoSceneView (SpriteManager spritemgr, IsoSceneViewModel model) { _spritemgr = spritemgr; _model = model; _model.precalculate(); // create our polygon arrays and create polygons for each of the // tiles. we use these repeatedly, so we go ahead and make 'em all // up front _polys = new Polygon[model.scenewid][model.scenehei]; for (int xx = 0; xx < model.scenewid; xx++) { for (int yy = 0; yy < model.scenehei; yy++) { _polys[xx][yy] = IsoUtil.getTilePolygon(_model, xx, yy); } } // create the array used to mark dirty tiles _dirty = new boolean[model.scenewid][model.tilehei]; } // documentation inherited public void setScene (DisplayMisoScene scene) { _scene = scene; // clear all dirty lists and tile array clearDirtyRegions(); // generate all object shadow tiles and polygons initAllObjectBounds(); // invalidate the entire screen as there's a new scene in town invalidate(); } // documentation inherited public void paint (Graphics g) { if (_scene == null) { Log.warning("Scene view painted with null scene."); return; } Graphics2D gfx = (Graphics2D)g; // clip everything to the overall scene view bounds Shape oldclip = gfx.getClip(); gfx.setClip(_model.bounds); if (_numDirty == 0) { // invalidate the entire screen invalidate(); } // render the scene to the graphics context renderScene(gfx); // draw frames of dirty tiles and rectangles // drawDirtyRegions(gfx); // draw tile coordinates if (_model.showCoords) { paintCoordinates(gfx); } // clear out the dirty tiles and rectangles clearDirtyRegions(); // draw sprite paths if (_model.showPaths) { _spritemgr.renderSpritePaths(gfx); } // paint any extra goodies paintExtras(gfx); // restore the original clipping region gfx.setClip(oldclip); } /** * A function where derived classes can paint extra stuff while we've * got the clipping region set up. */ protected void paintExtras (Graphics2D gfx) { // nothing for now } /** * Invalidate the entire visible scene view. */ protected void invalidate () { DirtyRectList rects = new DirtyRectList(); rects.add(_model.bounds); invalidateRects(rects); } /** * Clears the dirty rectangles and items lists, and the array of * dirty tiles. */ protected void clearDirtyRegions () { _dirtyRects.clear(); _dirtyItems.clear(); _numDirty = 0; for (int xx = 0; xx < _model.scenewid; xx++) { for (int yy = 0; yy < _model.scenehei; yy++) { _dirty[xx][yy] = false; } } } /** * Draws highlights around the dirty tiles and rectangles. */ protected void drawDirtyRegions (Graphics2D gfx) { // draw the dirty tiles gfx.setColor(Color.cyan); for (int xx = 0; xx < _model.scenewid; xx++) { for (int yy = 0; yy < _model.scenehei; yy++) { if (_dirty[xx][yy]) { gfx.draw(_polys[xx][yy]); } } } // draw the dirty rectangles Stroke ostroke = gfx.getStroke(); gfx.setStroke(DIRTY_RECT_STROKE); gfx.setColor(Color.red); int size = _dirtyRects.size(); for (int ii = 0; ii < size; ii++) { Rectangle rect = (Rectangle)_dirtyRects.get(ii); gfx.draw(rect); } gfx.setStroke(ostroke); // draw the dirty item rectangles gfx.setColor(Color.yellow); size = _dirtyItems.size(); for (int ii = 0; ii < size; ii++) { Rectangle rect = _dirtyItems.get(ii).dirtyRect; gfx.draw(rect); } } /** * Renders the scene to the given graphics context. * * @param gfx the graphics context. */ protected void renderScene (Graphics2D gfx) { // Log.info("renderScene"); renderTiles(gfx); renderBaseDecorations(gfx); renderDirtyItems(gfx); } /** * Renders the base and fringe layer tiles to the given graphics * context. */ protected void renderTiles (Graphics2D gfx) { BaseTileLayer base = _scene.getBaseLayer(); TileLayer fringe = _scene.getFringeLayer(); // render the base and fringe layers for (int yy = 0; yy < base.getHeight(); yy++) { for (int xx = 0; xx < base.getWidth(); xx++) { if (!_dirty[xx][yy]) { continue; } // draw the base and fringe tile images Tile tile; if ((tile = base.getTile(xx, yy)) != null) { tile.paint(gfx, _polys[xx][yy]); } if ((tile = fringe.getTile(xx, yy)) != null) { tile.paint(gfx, _polys[xx][yy]); } // if we're showing coordinates, outline the tiles as well if (_model.showCoords) { gfx.draw(_polys[xx][yy]); } } } } /** * A function where derived classes can paint things after the base * tiles have been rendered but before anything else has been rendered * (so that whatever is painted appears to be on the ground). */ protected void renderBaseDecorations (Graphics2D gfx) { // nothing for now } /** * Renders the dirty sprites and objects in the scene to the given * graphics context. */ protected void renderDirtyItems (Graphics2D gfx) { // Log.info("renderDirtyItems [rects=" + _dirtyRects.size() + // ", items=" + _dirtyItems.size() + "]."); // sort the dirty sprites and objects visually back-to-front DirtyItem items[] = _dirtyItems.sort(); // render each item clipping to its dirty rectangle for (int ii = 0; ii < items.length; ii++) { items[ii].paint(gfx, items[ii].dirtyRect); // Log.info("Painting item [item=" + items[ii] + "]."); } } /** * Generates and stores bounding polygons for all object tiles in the * scene for later use while rendering. */ protected void initAllObjectBounds () { // clear out any previously existing object polygons _objpolys.clear(); // generate bounding polygons for all objects ObjectTileLayer tiles = _scene.getObjectLayer(); for (int yy = 0; yy < tiles.getHeight(); yy++) { for (int xx = 0; xx < tiles.getWidth(); xx++) { ObjectTile tile = tiles.getTile(xx, yy); if (tile != null) { generateObjectBounds(tile, xx, yy); } } } } /** * Generates and stores the bounding polygon for the object which * is used when invalidating dirty rectangles or tiles, and when * rendering the object to a graphics context. This method should * be called when an object tile is added to a scene. */ protected void generateObjectBounds (ObjectTile tile, int x, int y) { // create the bounding polygon for this object int key = getCoordinateKey(x, y); // save it off in the object bounds hashtable _objpolys.put(key, newObjectBounds(tile, x, y)); } /** * Creates and returns a new polygon bounding the given object * tile positioned at the given scene coordinates. */ protected Polygon newObjectBounds (ObjectTile tile, int x, int y) { return IsoUtil.getObjectBounds(_model, _polys[x][y], tile); } /** * Returns a unique integer key corresponding to the given * coordinates, suitable for storing and retrieving objects from a * hashtable. */ protected int getCoordinateKey (int x, int y) { return (x << 16 | y); } /** * Paints tile coordinate numbers on all dirty tiles. * * @param gfx the graphics context. */ protected void paintCoordinates (Graphics2D gfx) { FontMetrics fm = gfx.getFontMetrics(_font); gfx.setFont(_font); gfx.setColor(Color.white); int cx = _model.tilehwid, cy = _model.tilehhei; int fhei = fm.getAscent(); for (int yy = 0; yy < _model.scenehei; yy++) { for (int xx = 0; xx < _model.scenewid; xx++) { // get the top-left screen coordinates of the tile Rectangle bounds = _polys[xx][yy].getBounds(); // only draw coordinates if the tile is on-screen if (bounds.intersects(_model.bounds)) { int sx = bounds.x, sy = bounds.y; // draw x-coordinate String str = String.valueOf(xx); int xpos = sx + cx - (fm.stringWidth(str) / 2); gfx.drawString(str, xpos, sy + cy); // draw y-coordinate str = String.valueOf(yy); xpos = sx + cx - (fm.stringWidth(str) / 2); gfx.drawString(str, xpos, sy + cy + fhei); } } } } // documentation inherited public void invalidateRects (DirtyRectList rects) { int size = rects.size(); for (int ii = 0; ii < size; ii++) { Rectangle r = (Rectangle)rects.get(ii); invalidateRect(r); } } // documentation inherited public void invalidateRect (Rectangle rect) { // dirty the tiles impacted by this rectangle Rectangle tileBounds = invalidateScreenRect(rect); // dirty any sprites or objects impacted by this rectangle invalidateItems(tileBounds); // save the rectangle for potential display later _dirtyRects.add(rect); } /** * Invalidates the given rectangle in screen pixel coordinates in the * view. Returns a rectangle that bounds all tiles that were dirtied. * * @param rect the dirty rectangle. */ public Rectangle invalidateScreenRect (Rectangle r) { // initialize the rectangle bounding all tiles dirtied by the // invalidated rectangle Rectangle tileBounds = new Rectangle(-1, -1, 0, 0); // note that corner tiles may be included unnecessarily, but // checking to determine whether they're actually needed // complicates the code with likely-insufficient benefit // determine the top-left tile impacted by this rect Point tpos = new Point(); IsoUtil.screenToTile(_model, r.x, r.y, tpos); // determine screen coordinates for top-left tile Point topleft = new Point(); IsoUtil.tileToScreen(_model, tpos.x, tpos.y, topleft); // determine number of horizontal and vertical tiles for rect int numh = (int)Math.ceil((float)r.width / (float)_model.tilewid); int numv = (int)Math.ceil((float)r.height / (float)_model.tilehhei); // set up iterating variables int tx = tpos.x, ty = tpos.y, mx = tpos.x, my = tpos.y; // set the starting screen y-position int screenY = topleft.y; // add top row if rect may overlap if (r.y < (screenY + _model.tilehhei)) { ty for (int ii = 0; ii < numh; ii++) { addDirtyTile(tileBounds, tx++, ty } } // add rows to the bottom if rect may overlap int ypos = screenY + (numv * _model.tilehhei); if ((r.y + r.height) > ypos) { numv += ((r.y + r.height) > (ypos + _model.tilehhei)) ? 2 : 1; } // add dirty tiles from each affected row boolean isodd = false; for (int ii = 0; ii < numv; ii++) { // set up iterating variables for this row tx = mx; ty = my; int length = numh; // set the starting screen x-position int screenX = topleft.x; if (isodd) { screenX -= _model.tilehwid; } // skip leftmost tile if rect doesn't overlap if (r.x > screenX + _model.tilewid) { tx++; ty screenX += _model.tilewid; } // add to the right edge if rect may overlap if (r.x + r.width > (screenX + (length * _model.tilewid))) { length++; } // add all tiles in the row to the dirty set for (int jj = 0; jj < length; jj++) { addDirtyTile(tileBounds, tx++, ty } // step along the x- or y-axis appropriately if (isodd) { mx++; } else { my++; } // increment the screen y-position screenY += _model.tilehhei; // toggle whether we're drawing an odd-numbered row isodd = !isodd; } return tileBounds; } /** * Marks the tile at the given coordinates dirty and expands the * tile bounds rectangle to include the rectangle for the dirtied * tile. */ protected void addDirtyTile (Rectangle tileBounds, int x, int y) { if (!_model.isCoordinateValid(x, y)) { return; } // expand the tile bounds rectangle to include this tile Rectangle bounds = _polys[x][y].getBounds(); if (tileBounds.x == -1) { tileBounds.setBounds(bounds); } else { tileBounds.add(bounds); } // do nothing if the tile's already dirty if (_dirty[x][y]) { return; } // mark the tile dirty _numDirty++; _dirty[x][y] = true; } /** * Adds any sprites or objects in the scene whose bounds overlap * with the given dirty rectangle to the dirty item list for later * re-rendering. */ protected void invalidateItems (Rectangle r) { // add any sprites impacted by the dirty rectangle _dirtySprites.clear(); _spritemgr.getIntersectingSprites(_dirtySprites, r); int size = _dirtySprites.size(); for (int ii = 0; ii < size; ii++) { MisoCharacterSprite sprite = (MisoCharacterSprite)_dirtySprites.get(ii); // get the dirty portion of the sprite Rectangle drect = sprite.getBounds().intersection(r); _dirtyItems.appendDirtySprite( sprite, sprite.getTileX(), sprite.getTileY(), drect); // Log.info("Dirtied item: " + sprite); } // add any objects impacted by the dirty rectangle if (_scene != null) { ObjectTileLayer tiles = _scene.getObjectLayer(); Iterator iter = _objpolys.keys(); while (iter.hasNext()) { // get the object's coordinates and bounding polygon int coord = ((Integer)iter.next()).intValue(); Polygon poly = (Polygon)_objpolys.get(coord); if (poly.intersects(r)) { // get the dirty portion of the object Rectangle drect = poly.getBounds().intersection(r); int tx = coord >> 16, ty = coord & 0x0000FFFF; _dirtyItems.appendDirtyObject( tiles.getTile(tx, ty), poly, tx, ty, drect); // Log.info("Dirtied item: Object(" + tx + ", " + } } } } // documentation inherited public Path getPath (MisoCharacterSprite sprite, int x, int y) { // make sure the destination point is within our bounds if (!_model.bounds.contains(x, y)) { return null; } // get the destination tile coordinates Point dest = new Point(); IsoUtil.screenToTile(_model, x, y, dest); // get a reasonable tile path through the scene List points = AStarPathUtil.getPath( _scene.getBaseLayer(), _model.scenewid, _model.scenehei, sprite, sprite.getTileX(), sprite.getTileY(), dest.x, dest.y); // construct a path object to guide the sprite on its merry way return (points == null) ? null : new TilePath(_model, sprite, points, x, y); } // documentation inherited public Point getScreenCoords (int x, int y) { Point coords = new Point(); IsoUtil.fullToScreen(_model, x, y, coords); return coords; } /** The stroke used to draw dirty rectangles. */ protected static final Stroke DIRTY_RECT_STROKE = new BasicStroke(2); /** The font to draw tile coordinates. */ protected Font _font = new Font("Arial", Font.PLAIN, 7); /** Polygon instances for all of our tiles. */ protected Polygon _polys[][]; /** Bounding polygons for all of the object tiles. */ protected HashIntMap _objpolys = new HashIntMap(); /** The dirty tiles that need to be re-painted. */ protected boolean _dirty[][]; /** The number of dirty tiles. */ protected int _numDirty; /** The dirty rectangles that need to be re-painted. */ protected ArrayList _dirtyRects = new ArrayList(); /** The dirty sprites and objects that need to be re-painted. */ protected DirtyItemList _dirtyItems = new DirtyItemList(); /** The working sprites list used when calculating dirty regions. */ protected ArrayList _dirtySprites = new ArrayList(); /** The scene view model data. */ protected IsoSceneViewModel _model; /** The scene to be displayed. */ protected DisplayMisoScene _scene; /** The sprite manager. */ protected SpriteManager _spritemgr; }
package lib.jebt.xlsx; import lib.jebt.BaseJebtWriter; import lib.jebt.JebtWriter; import lib.jebt.parser.*; import org.apache.commons.lang3.StringUtils; import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.util.WorkbookUtil; import org.apache.poi.util.IOUtils; import org.apache.poi.xssf.streaming.SXSSFCell; import org.apache.poi.xssf.streaming.SXSSFRow; import org.apache.poi.xssf.streaming.SXSSFSheet; import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.apache.poi.xssf.usermodel.*; import java.io.IOException; import java.io.OutputStream; import java.io.StringReader; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * Implementation of {@link JebtWriter} for XLSX format. * It works by cloning the template workbook metadata only, and then reads from template cells one by one and insert them in output document with on-the-fly filling from data. */ public class JebtXlsxWriter extends BaseJebtWriter { boolean isWritten = false; private OutputStream docOS; private XSSFWorkbook templateWorkbook; private XSSFWorkbook documentBaseWorkbook; public JebtXlsxWriter(XSSFWorkbook templateWorkbook, XSSFWorkbook documentBaseWorkbook, OutputStream docOS) { this.docOS = docOS; this.templateWorkbook = templateWorkbook; this.documentBaseWorkbook = documentBaseWorkbook; } public void writeData(Map data) { if (isWritten) { throw new RuntimeException("Output XLSX file has already been generated"); } isWritten = true; // We delete all cells from sheets, but keep the sheets as they may contain valuable metadata. for (Sheet sheet: documentBaseWorkbook) { for (int index = sheet.getLastRowNum(); index >= sheet.getFirstRowNum(); index Row row = sheet.getRow(index); if (row != null) { sheet.removeRow(sheet.getRow(index)); } } } final SXSSFWorkbook sDocWorkbook = new SXSSFWorkbook(documentBaseWorkbook); // Fill Document sheet by sheet for (int i = 0; i < templateWorkbook.getNumberOfSheets(); i++) { XSSFSheet templateSheet = templateWorkbook.getSheetAt(i); documentBaseWorkbook.setSheetName(i, WorkbookUtil.createSafeSheetName(convertString(templateSheet.getSheetName(), data))); SXSSFSheet docSheet = sDocWorkbook.getSheetAt(i); fillDocSheetFromTemplate(templateSheet, docSheet, data); } try { sDocWorkbook.write(docOS); } catch (IOException e) { throw new RuntimeException("Error writing document Workbook", e); } finally { IOUtils.closeQuietly(docOS); } } /** * Core method that makes the job of filling Excel template. * It goes over cell events of the sourceSheet, and applies them to the target sheet in a streaming way. */ private void fillDocSheetFromTemplate(XSSFSheet sourceSheet, SXSSFSheet targetSheet, Map data) { JebtXlsxTokenizer sheetTokenizer = new JebtXlsxTokenizer(sourceSheet); SheetContext targetSheetContext = new SheetContext(targetSheet); Token t; while ((t = sheetTokenizer.readNext()) != Token.EOD) { processToken(t, data, targetSheetContext); } } private void processToken(Token t, Map data, SheetContext targetSheetContext) { SXSSFSheet sheet = targetSheetContext.getSheet(); // While filling Excel sheet, tokens are either NEW_TEXT_CELL, NEW_NON_TEXT_CELL, NEW_BLANK_CELL, NEW_BLANK_ROW or NEW_ROW (or LOOP). if (t.getType() == Token.TokenType.NEW_ROW || t.getType() == Token.TokenType.NEW_BLANK_ROW) { // We go to the next row, and create it if it doesn't already exist. targetSheetContext.rowId++; // We reinitialize Column Index too targetSheetContext.columnId = -1; SXSSFRow row = sheet.getRow(targetSheetContext.rowId); if (row == null) { row = sheet.createRow(targetSheetContext.rowId); } } else if (t.getType() == Token.TokenType.NEW_NON_TEXT_CELL || t.getType() == Token.TokenType.NEW_BLANK_CELL) { // We just copy the cell and its contents to the destination sheet. SXSSFCell cell = initCellCopy(t, targetSheetContext, data); if (t.getCell() == null) { // null cell means this was a Blank cell, it was already created in initCell and there's nothing to copy. return; } // Copying value switch (t.getCell().getCellTypeEnum()) { case _NONE: break; case BLANK: break; case STRING: // A String cell here can only be blank, i.e. contain empty string. cell.setCellValue(""); break; case BOOLEAN: cell.setCellValue(t.getCell().getBooleanCellValue()); break; case NUMERIC: cell.setCellValue(t.getCell().getNumericCellValue()); break; case FORMULA: cell.setCellValue(t.getCell().getStringCellValue()); cell.setCellFormula(t.getCell().getCellFormula()); break; case ERROR: break; } } else if (t.getType() == Token.TokenType.NEW_TEXT_CELL) { SXSSFCell cell = initCellCopy(t, targetSheetContext, data); processTextCell(t.getCell(), cell, data); } else if (t.getType() == Token.TokenType.LOOP) { JebtTextTokenizer.LoopToken loop = (JebtTextTokenizer.LoopToken)t; List collection = null; try { collection = (List)new JsonPathResolver(data).evaluatePathToObject(loop.getCollectionJsonPath()); } catch (ClassCastException e) { throw new JebtEvaluationException("Object found at " + loop.getCollectionJsonPath() + " is not a List", e); } if (collection == null) { // The list is empty or non-existent, so we have nothing to iterate. return; } Iterator it = collection.iterator(); boolean first = true; targetSheetContext.loopDepth++; while (it.hasNext()) { if (targetSheetContext.loopDepth <= 1) { // We must go to the next row before every new record for the main Loop if (first) { first = false; } else { processToken(new Token(Token.TokenType.NEW_ROW, null), data, targetSheetContext); } } Object obj = it.next(); Map dataCopy = new LinkedHashMap(data); dataCopy.put(loop.getLoopItemName(), obj); for (Token tok : loop.getLoopTokens()) { processToken(tok, dataCopy, targetSheetContext); } } targetSheetContext.loopDepth } else { throw new RuntimeException("Unknown Token: " + t.getType()); } } private SXSSFCell initCellCopy(Token t, SheetContext targetSheetContext, Map data) { targetSheetContext.columnId++; SXSSFRow row = targetSheetContext.getSheet().getRow(targetSheetContext.rowId); SXSSFCell cell = row.getCell(targetSheetContext.columnId); if (cell == null) { cell = row.createCell(targetSheetContext.columnId); } if (t.getCell() == null) { cell.setCellType(CellType.BLANK); } else { cell.setCellType(t.getCell().getCellTypeEnum()); // Not sure if this call will work since styles are coming from different workbooks... cell.setCellStyle(t.getCell().getCellStyle()); } // Remove any loop tag from comments & Resolve any expression in it. if (cell.getCellComment() != null && cell.getCellComment().getString() != null && !StringUtils .isBlank(cell.getCellComment().getString().toString())) { String commentStr = cell.getCellComment().getString().toString(); // Removing loop tags while (commentStr.indexOf("{[") >= 0 && commentStr.indexOf("]}", commentStr.indexOf("{[")) >= 0) { commentStr = commentStr.substring(0, commentStr.indexOf("{[")) + commentStr .substring(commentStr.indexOf("]}", commentStr.indexOf("{[")) + 2); } cell.getCellComment().setString(new XSSFRichTextString(convertString(commentStr, data))); } return cell; } /** * Copies cell contents from source to target, and resolves any token in cell's text in the process. * SXSSF doesn't support RichTextString, so we'll discard any text-part specific font, and will rely on Cell style only for formatting. */ private void processTextCell(Cell sourceCell, SXSSFCell targetCell, Map data) { String sourceStr = sourceCell.getRichStringCellValue().getString(); String targetStr = escapeExcelInjection(sourceStr, convertString(sourceStr, data)); targetCell.setCellValue(targetStr); } /** * An excel injection can occur if a user passes a string with a malicious content, such as * =SUM(1+1)*cmd|' /C calc'!A0 * When we detect this, we escape the string with a single quote. * We don't exepect anyone to pass to such a formula in a normal text label, so that protection will suffice for now. * Later we might want to consider using Apache POI setQuotePrefixed(boolean) on CellStyle. */ private String escapeExcelInjection(String sourceStr, String evaluatedStr) { if (sourceStr == null || evaluatedStr == null) { // Should never happen. return evaluatedStr; } if (sourceStr.equals(evaluatedStr)) { // Nothing was changed return evaluatedStr; } if (sourceStr.startsWith("{{") && !"".equals(evaluatedStr) && "=-+@".indexOf(evaluatedStr.charAt(0)) >= 0) { // Escaping any generated value starting with =-+@ with a starting quote. return "'" + evaluatedStr; } return evaluatedStr; } private class SheetContext { public int rowId = -1; public int columnId = -1; public XSSFRow currentRow; public int loopDepth = 0; private SXSSFSheet sheet; public SheetContext(SXSSFSheet sheet) { this.sheet = sheet; } public SXSSFSheet getSheet() { return sheet; } } }
package org.unitime.commons.jgroups; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.hibernate.Transaction; import org.jgroups.Address; import org.jgroups.Event; import org.jgroups.Global; import org.jgroups.PhysicalAddress; import org.jgroups.View; import org.jgroups.annotations.Property; import org.jgroups.conf.ClassConfigurator; import org.jgroups.conf.PropertyConverters; import org.jgroups.protocols.Discovery; import org.jgroups.protocols.PingData; import org.jgroups.stack.IpAddress; import org.jgroups.util.UUID; import org.unitime.timetable.model.ClusterDiscovery; import org.unitime.timetable.model.dao.ClusterDiscoveryDAO; /** * @author Tomas Muller */ public class UniTimeClusterDiscovery extends Discovery { static { ClassConfigurator.addProtocol((short) 666, UniTimeClusterDiscovery.class); } @Property(description="Number of additional ports to be probed for membership. A port_range of 0 does not " + "probe additional ports. Example: initial_hosts=A[7800] port_range=0 probes A:7800, port_range=1 probes " + "A:7800 and A:7801") protected int port_range=1; @Property(name="initial_hosts", description="Comma delimited list of hosts to be contacted for initial membership", converter=PropertyConverters.InitialHosts.class, dependsUpon="port_range", systemProperty=Global.TCPPING_INITIAL_HOSTS) protected List<IpAddress> initial_hosts=Collections.EMPTY_LIST; @Property(description="Interval (in milliseconds) at which the own Address is written. 0 disables it.") protected long interval = 60000; @Property(description="Interval (in milliseconds) after which an old record is deleted from the cluster discovery table.") protected long time_to_live = 600000; private Future<?> writer_future; @Override public void stop() { final Future<?> wf = writer_future; if (wf != null) { wf.cancel(false); writer_future = null; } try { deleteSelf(); } catch (Exception e) { log.error("Failed to remove my address from the " + group_addr + " cluster database."); } super.stop(); } @Override public void start() throws Exception { super.start(); if (interval > 0) { writer_future = timer.scheduleWithFixedDelay(new WriterTask(), interval, interval, TimeUnit.MILLISECONDS); } } @Override public Collection<PhysicalAddress> fetchClusterMembers(String cluster_name) { Set<PhysicalAddress> retval = new HashSet<PhysicalAddress>(initial_hosts); if (!ClusterDiscoveryDAO.isConfigured()) { log.info("Hibernate not configured yet, returning initial hosts for " + group_addr + " cluster members."); return retval; } List<PingData> members = readAllMembers(); if (members.isEmpty()) return retval; for(PingData tmp: members) { Collection<PhysicalAddress> dests = (tmp != null ? tmp.getPhysicalAddrs() : null); if (dests == null) continue; for (PhysicalAddress dest: dests) { if (dest == null) continue; retval.add(dest); } } PhysicalAddress my_addr = getAndSavePhysicalAddress(); log.debug("Cluster " + cluster_name + " has members " + retval + " (I am " + my_addr + ")"); return retval; } protected synchronized List<PingData> readAllMembers() { List<PingData> members = new ArrayList<PingData>(); org.hibernate.Session hibSession = ClusterDiscoveryDAO.getInstance().createNewSession(); Transaction tx = null; try { tx = hibSession.beginTransaction(); long deadline = new Date().getTime() - time_to_live; for (ClusterDiscovery cluster: (List<ClusterDiscovery>)hibSession.createQuery("from ClusterDiscovery where clusterName = :clusterName").setString("clusterName", group_addr).list()) { if (cluster.getTimeStamp().getTime() >= deadline) members.add(deserialize(cluster.getPingData())); } if (tx != null) tx.commit(); } catch (IllegalStateException e) { log.info("Failed to read all members of cluster " + group_addr + ": " + e.getMessage()); if (tx!=null) tx.rollback(); } catch (Exception e) { if (tx!=null) tx.rollback(); } finally { hibSession.close(); } return members; } protected static String addressAsString(Address address) { if(address == null) return ""; if(address instanceof UUID) return ((UUID) address).toStringLong(); return address.toString(); } protected PhysicalAddress getAndSavePhysicalAddress() { PhysicalAddress physical_addr = (PhysicalAddress)down(new Event(Event.GET_PHYSICAL_ADDRESS, local_addr)); if (!ClusterDiscoveryDAO.isConfigured()) { log.info("Hibernate not configured yet, skiping save of physical address for cluster " + group_addr + "."); return physical_addr; } List<PhysicalAddress> physical_addrs = Arrays.asList(physical_addr); PingData data = new PingData(local_addr, null, false, UUID.get(local_addr), physical_addrs); updateMyData(data); return physical_addr; } protected synchronized void updateMyData(PingData data) { org.hibernate.Session hibSession = ClusterDiscoveryDAO.getInstance().createNewSession(); String own_address = addressAsString(data.getAddress()); Transaction tx = null; try { tx = hibSession.beginTransaction(); ClusterDiscovery cluster = ClusterDiscoveryDAO.getInstance().get(new ClusterDiscovery(own_address, group_addr), hibSession); if (cluster == null) cluster = new ClusterDiscovery(own_address, group_addr); cluster.setPingData(serializeWithoutView(data)); cluster.setTimeStamp(new Date()); hibSession.saveOrUpdate(cluster); hibSession.flush(); if (tx != null) tx.commit(); } catch (IllegalStateException e) { if (tx!=null) tx.rollback(); log.info("Failed to update my data for cluster " + group_addr + ": " + e.getMessage()); } catch (Exception e) { if (tx!=null) tx.rollback(); } finally { hibSession.close(); } } @Override public Object down(Event evt) { final Object retval = super.down(evt); if (evt.getType() == Event.VIEW_CHANGE) handleView((View) evt.getArg()); return retval; } protected void handleView(View view) { if (!ClusterDiscoveryDAO.isConfigured()) { log.info("Hibernate not configured yet, ignoring view change for cluster " + group_addr + "."); return; } final Collection<Address> mbrs = view.getMembers(); final boolean is_coordinator = !mbrs.isEmpty() && mbrs.iterator().next().equals(local_addr); if (is_coordinator) { purgeOtherAddresses(mbrs); } } protected synchronized void purgeOtherAddresses(Collection<Address> members) { org.hibernate.Session hibSession = ClusterDiscoveryDAO.getInstance().createNewSession(); Transaction tx = null; try { tx = hibSession.beginTransaction(); long deadline = new Date().getTime() - time_to_live; cluster: for (ClusterDiscovery cluster: (List<ClusterDiscovery>)hibSession.createQuery("from ClusterDiscovery where clusterName = :clusterName").setString("clusterName", group_addr).list()) { for (Address address: members) if (cluster.getOwnAddress().equals(addressAsString(address))) continue cluster; PingData pd = deserialize(cluster.getPingData()); if (pd != null && cluster.getTimeStamp().getTime() < deadline) { log.debug("Purging " + pd.getPhysicalAddrs() + " from cluster " + group_addr + "."); hibSession.delete(cluster); } } hibSession.flush(); if (tx != null) tx.commit(); } catch (Exception e) { if (tx!=null) tx.rollback(); } finally { hibSession.close(); } } protected synchronized void deleteSelf() { final String ownAddress = addressAsString(local_addr); org.hibernate.Session hibSession = ClusterDiscoveryDAO.getInstance().createNewSession(); Transaction tx = null; try { tx = hibSession.beginTransaction(); ClusterDiscovery cluster = ClusterDiscoveryDAO.getInstance().get(new ClusterDiscovery(ownAddress, group_addr), hibSession); if (cluster != null) hibSession.delete(cluster); hibSession.flush(); if (tx != null) tx.commit(); } catch (Exception e) { if (tx!=null) tx.rollback(); } finally { hibSession.close(); } } @Override public boolean sendDiscoveryRequestsInParallel() { return true; } @Override public boolean isDynamic() { return true; } protected final class WriterTask implements Runnable { public void run() { getAndSavePhysicalAddress(); } } }
// 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.stage.server; import com.threerings.resource.ResourceManager; import com.threerings.media.tile.TileManager; import com.threerings.media.tile.bundle.BundledTileSetRepository; import com.threerings.whirled.server.WhirledServer; import com.threerings.stage.Log; import com.threerings.stage.data.StageCodes; /** * Extends the Whirled server to provide services needed by the Stage * system. */ public abstract class StageServer extends WhirledServer { /** A resource manager with which we can load resources in the same * manner that the client does (for resources that are used on both * the server and client). */ public ResourceManager rsrcmgr; /** Provides access to our tile repository. */ public static TileManager tilemgr; // documentation inherited public void init () throws Exception { // do the base server initialization super.init(); // create the resource manager rsrcmgr = new ResourceManager("rsrc"); rsrcmgr.initBundles(null, getResourceConfig(), null); // create our tile manager and repository tilemgr = new TileManager(null); tilemgr.setTileSetRepository( new BundledTileSetRepository(rsrcmgr, null, StageCodes.TILESET_RSRC_SET)); Log.info("Stage server initialized."); } /** * Returns the path to the configuration file for the resource manager that * will be created for use by the server. This is a resource path (meaning * it should be relative to the resource prefix (which is * <code>rsrc</code>). */ protected String getResourceConfig () { return "config/resource/manager.properties"; } }
// $Id: Portal.java,v 1.2 2001/11/29 00:16:31 mdb Exp $ package com.threerings.whirled.spot.data; /** * A portal is a location, but one that represents an exit to another * scene rather than a place to stand in the current scene. A body sprite * would walk over to a portal's coordinates and then either proceed off * of the edge of the display, or open a door and walk through it, or * fizzle away in a Star Trekkian transporter style or whatever is * appropriate for the game in question. It contains information on the * scene to which the body exits when using this portal and the location * at which the body sprite should appear in that target scene. * * <p> Though portals extend locations, they generally would not occupy a * cluster (because that wouldn't make much sense) and as such should * always have a {@link #clusterIndex} of -1. */ public class Portal extends Location { /** The scene identifier of the scene to which a body will exit when * they "use" this portal. */ public int targetSceneId; /** The location identifier of the location at which a body will enter * the target scene when they "use" this portal. */ public int targetLocationId; /** During the offline scene creation process, a portal will have a * huamn readable name. This is not serialized or transmitted over the * wire. */ public String name; /** * Constructs a portal with the supplied values. */ public Portal (int id, int x, int y, int orientation, int targetSceneId, int targetLocationId) { super(id, x, y, orientation, -1); this.targetSceneId = targetSceneId; this.targetLocationId = targetLocationId; } // documentation inherited protected void toString (StringBuffer buf) { super.toString(buf); buf.append(", targetScene=").append(targetSceneId); buf.append(", targetLoc=").append(targetLocationId); } }
package com.elmakers.mine.bukkit.spell; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import javax.annotation.Nullable; import org.bukkit.configuration.ConfigurationSection; import com.elmakers.mine.bukkit.action.ActionHandler; import com.elmakers.mine.bukkit.api.batch.Batch; import com.elmakers.mine.bukkit.api.batch.SpellBatch; import com.elmakers.mine.bukkit.api.spell.SpellResult; import com.elmakers.mine.bukkit.utility.ConfigurationUtils; public class ActionSpell extends BrushSpell { private Map<String, ActionHandler> actions = new HashMap<>(); private boolean undoable = false; private boolean requiresBuildPermission = false; private boolean requiresBreakPermission = false; private ActionHandler currentHandler = null; private Map<String, ConfigurationSection> handlerParameters = new HashMap<>(); private int workThreshold = 500; @Override protected void processResult(SpellResult result, ConfigurationSection castParameters) { if (!result.isSuccess()) { ActionHandler handler = actions.get(result.name().toLowerCase()); if (handler != null) { handler.start(currentCast, castParameters); } } super.processResult(result, castParameters); } @Override protected boolean isLegacy() { return false; } @Override protected boolean isBatched() { return true; } @Override public boolean hasHandlerParameters(String handlerKey) { return handlerParameters.containsKey(handlerKey); } @Override public ConfigurationSection getHandlerParameters(String handlerKey) { return handlerParameters.get(handlerKey); } @Override public void processParameters(ConfigurationSection parameters) { ConfigurationSection alternateParameters = null; if (isLookingDown()) { alternateParameters = getHandlerParameters("alternate_down"); } else if (isLookingUp()) { alternateParameters = getHandlerParameters("alternate_up"); } else if (mage.isSneaking()) { alternateParameters = getHandlerParameters("alternate_sneak"); } else if (mage.isJumping()) { alternateParameters = getHandlerParameters("alternate_jumping"); } if (alternateParameters != null) { if (parameters == null) { parameters = alternateParameters; } else { parameters = ConfigurationUtils.addConfigurations(parameters, alternateParameters, true); } } super.processParameters(parameters); } @Override public SpellResult onCast(ConfigurationSection parameters) { currentCast.setWorkAllowed(workThreshold); SpellResult result = SpellResult.CAST; currentHandler = actions.get("cast"); ActionHandler downHandler = actions.get("alternate_down"); ActionHandler upHandler = actions.get("alternate_up"); ActionHandler sneakHandler = actions.get("alternate_sneak"); ActionHandler jumpHandler = actions.get("alternate_jumping"); workThreshold = parameters.getInt("work_threshold", 500); if (downHandler != null && isLookingDown()) { result = SpellResult.ALTERNATE_DOWN; currentHandler = downHandler; } else if (upHandler != null && isLookingUp()) { result = SpellResult.ALTERNATE_UP; currentHandler = upHandler; } else if (sneakHandler != null && mage.isSneaking()) { result = SpellResult.ALTERNATE_SNEAK; currentHandler = sneakHandler; } else if (jumpHandler != null && mage.isJumping()) { result = SpellResult.ALTERNATE_JUMPING; currentHandler = jumpHandler; } if (isUndoable()) { getMage().prepareForUndo(getUndoList()); } target(); playEffects("precast"); if (currentHandler != null) { currentHandler = (ActionHandler)currentHandler.clone(); try { result = result.max(currentHandler.start(currentCast, parameters)); currentCast.setInitialResult(result); } catch (Exception ex) { controller.getLogger().log(Level.WARNING, "Spell cast failed for " + getKey(), ex); result = SpellResult.FAIL; try { currentCast.setResult(result); currentCast.setInitialResult(result); currentHandler.finish(currentCast); currentCast.finish(); } catch (Exception finishException) { controller.getLogger().log(Level.WARNING, "Failed to clean up failed spell " + getKey(), finishException); } } } else { currentCast.setResult(result); currentCast.setInitialResult(result); currentCast.finish(); } return result; } @Override public void onLoad(ConfigurationSection data) { super.onLoad(data); for (ActionHandler handler : actions.values()) { handler.loadData(getMage(), data); } } @Override public void onSave(ConfigurationSection data) { super.onSave(data); for (ActionHandler handler : actions.values()) { handler.saveData(getMage(), data); } } @Override protected void loadTemplate(ConfigurationSection template) { castOnNoTarget = true; super.loadTemplate(template); undoable = false; requiresBuildPermission = false; requiresBreakPermission = false; usesBrush = template.getBoolean("uses_brush", false); ConfigurationSection actionsNode = template.getConfigurationSection("actions"); if (actionsNode != null) { ConfigurationSection parameters = template.getConfigurationSection("parameters"); Object baseActions = actionsNode.get("cast"); Collection<String> templateKeys = template.getKeys(false); for (String templateKey : templateKeys) { if (templateKey.endsWith("_parameters")) { ConfigurationSection overrides = ConfigurationUtils.cloneConfiguration(template.getConfigurationSection(templateKey)); String handlerKey = templateKey.substring(0, templateKey.length() - 11); handlerParameters.put(handlerKey, overrides); // Auto-register base actions, kind of hacky to check for alternates though. if (baseActions != null && !actionsNode.contains(handlerKey) && handlerKey.startsWith("alternate_")) { actionsNode.set(handlerKey, baseActions); } } } // This is here for sub-action initialization, and will get replaced with real working parameters for prepare workingParameters = parameters; actionsNode = ConfigurationUtils.replaceParameters(actionsNode, parameters); if (actionsNode != null) { Collection<String> actionKeys = actionsNode.getKeys(false); for (String actionKey : actionKeys) { ActionHandler handler = new ActionHandler(); handler.load(this, actionsNode, actionKey); handler.initialize(this, parameters); usesBrush = usesBrush || handler.usesBrush(); undoable = undoable || handler.isUndoable(); requiresBuildPermission = requiresBuildPermission || handler.requiresBuildPermission(); requiresBreakPermission = requiresBreakPermission || handler.requiresBreakPermission(); actions.put(actionKey, handler); } } } else if (template.contains("actions")) { controller.getLogger().warning("Invalid actions configuration in spell " + getKey() + ", did you forget to add cast: ?"); } undoable = template.getBoolean("undoable", undoable); requiresBreakPermission = template.getBoolean("require_break", requiresBreakPermission); requiresBuildPermission = template.getBoolean("require_build", requiresBuildPermission); } @Override public boolean isUndoable() { return undoable; } @Override public void getParameters(Collection<String> parameters) { super.getParameters(parameters); for (ActionHandler handler : actions.values()) { handler.getParameterNames(this, parameters); } } @Override public void getParameterOptions(Collection<String> examples, String parameterKey) { super.getParameterOptions(examples, parameterKey); for (ActionHandler handler : actions.values()) { handler.getParameterOptions(this, parameterKey, examples); } } @Override public String getMessage(String messageKey, String def) { String message = super.getMessage(messageKey, def); if (currentHandler != null) { message = currentHandler.transformMessage(message); } return message; } @Override public boolean requiresBuildPermission() { return requiresBuildPermission && !brushIsErase(); } @Override public boolean requiresBreakPermission() { return requiresBreakPermission || (requiresBuildPermission && brushIsErase()); } @Nullable @Override public com.elmakers.mine.bukkit.api.block.MaterialAndData getEffectMaterial() { if (!usesBrush) { return null; } return super.getEffectMaterial(); } @Override public boolean isActive() { if (mage == null) return false; if (toggle == ToggleType.UNDO && toggleUndo != null && !toggleUndo.isUndone()) { return true; } Collection<Batch> pendingBatches = mage.getPendingBatches(); for (Batch batch : pendingBatches) { if (batch instanceof SpellBatch && ((SpellBatch)batch).getSpell() == this) { return true; } } return false; } }
package net.imagej.ops.fopd; import net.imagej.ops.OpMatchingService; import net.imagej.ops.OpService; import net.imglib2.img.ImagePlusAdapter; import net.imglib2.img.Img; import net.imglib2.img.display.imagej.ImageJFunctions; import net.imglib2.type.numeric.real.FloatType; import org.scijava.Context; import org.scijava.cache.CacheService; import org.scijava.plugin.Parameter; import ij.IJ; /** * * @author Tim-Oliver Buchholz, University of Konstanz * */ public class Examples { @Parameter private OpService ops; public static void main(String[] args) { Examples ex = new Examples(); final int numIts = 100; ImageJFunctions.show(ex.getNoisyImg()); ImageJFunctions.show(ex.denoisingL1TV2D(ex.getNoisyImg(), numIts)); ImageJFunctions.show(ex.denoisingL1TVHuber2D(ex.getNoisyImg(), numIts)); ImageJFunctions.show(ex.denoisingL1TGV2D(ex.getNoisyImg(), numIts)); ImageJFunctions.show(ex.denoisingKLDivTV2D(ex.getNoisyImg(), numIts)); ImageJFunctions.show(ex.denoisingKLDivTVHuber2D(ex.getNoisyImg(), numIts)); ImageJFunctions.show(ex.denoisingKLDivTGV2D(ex.getNoisyImg(), numIts)); ImageJFunctions.show(ex.getConvolvedImg()); ImageJFunctions.show(ex.deconvolutionL1TV2D(ex.getConvolvedImg(), ex.getKernel(), numIts)); ImageJFunctions.show(ex.deconvolutionL1TVHuber2D(ex.getConvolvedImg(), ex.getKernel(), numIts)); ImageJFunctions.show(ex.deconvolutionL1TGV2D(ex.getConvolvedImg(), ex.getKernel(), numIts)); ImageJFunctions.show(ex.deconvolutionKLDivTV2D(ex.getConvolvedImg(), ex.getKernel(), numIts)); ImageJFunctions.show(ex.deconvolutionKLDivTVHuber2D(ex.getConvolvedImg(), ex.getKernel(), numIts)); ImageJFunctions.show(ex.deconvolutionKLDivTGV2D(ex.getConvolvedImg(), ex.getKernel(), numIts)); } public Examples() { Context context = new Context(OpService.class, OpMatchingService.class, CacheService.class); context.inject(this); } private Img<FloatType> getNoisyImg() { return ImagePlusAdapter.wrap(IJ.openImage(this.getClass().getResource("2D_noise.tif").getPath())); } private Img<FloatType> getConvolvedImg() { return ImagePlusAdapter.wrap(IJ.openImage(this.getClass().getResource("2D_convolved.tif").getPath())); } private Img<FloatType> getKernel() { return ImagePlusAdapter.wrap(IJ.openImage(this.getClass().getResource("2D_kernel.tif").getPath())); } @SuppressWarnings("unchecked") private Img<FloatType> denoisingL1TV2D(final Img<FloatType> img, final int numIts) { long t = System.currentTimeMillis(); final Img<FloatType> result = (Img<FloatType>) ops.run(TVL1Denoising.class, img, 2, numIts); t = System.currentTimeMillis() - t; System.out .println("TVL1-Denoising [" + img.dimension(0) + ", " + img.dimension(1) + "]: " + t / 1000.0 + "sec"); System.out.println("Time/Iteration: " + (double) t / numIts + "millisec"); return result; } @SuppressWarnings("unchecked") private Img<FloatType> denoisingL1TVHuber2D(final Img<FloatType> img, final int numIts) { long t = System.currentTimeMillis(); final Img<FloatType> result = (Img<FloatType>) ops.run(TVHuberL1Denoising.class, img, 2, 0.02, numIts); t = System.currentTimeMillis() - t; System.out.println( "TVHuberL1-Denoising [" + img.dimension(0) + ", " + img.dimension(1) + "]: " + t / 1000.0 + "sec"); System.out.println("Time/Iteration: " + (double) t / numIts + "millisec"); return result; } @SuppressWarnings("unchecked") private Img<FloatType> denoisingL1TGV2D(final Img<FloatType> img, final int numIts) { long t = System.currentTimeMillis(); final Img<FloatType> result = (Img<FloatType>) ops.run(TGVL1Denoising.class, img, 1.0, 2.0, numIts); t = System.currentTimeMillis() - t; System.out .println("TGVL1-Denoising [" + img.dimension(0) + ", " + img.dimension(1) + "]: " + t / 1000.0 + "sec"); System.out.println("Time/Iteration: " + (double) t / numIts + "millisec"); return result; } @SuppressWarnings("unchecked") private Img<FloatType> deconvolutionL1TV2D(final Img<FloatType> img, final Img<FloatType> kernel, final int numIts) { long t = System.currentTimeMillis(); final Img<FloatType> result = (Img<FloatType>) ops.run(TVL1Deconvolution.class, img, kernel, 0.08, numIts); t = System.currentTimeMillis() - t; System.out.println( "TVL1-Deconvolution [" + img.dimension(0) + ", " + img.dimension(1) + "]: " + t / 1000.0 + "sec"); System.out.println("Time/Iteration: " + (double) t / numIts + "millisec"); return result; } @SuppressWarnings("unchecked") private Img<FloatType> deconvolutionL1TVHuber2D(final Img<FloatType> img, final Img<FloatType> kernel, final int numIts) { long t = System.currentTimeMillis(); final Img<FloatType> result = (Img<FloatType>) ops.run(TVHuberL1Deconvolution.class, img, kernel, 0.1, 0.05, numIts); t = System.currentTimeMillis() - t; System.out.println( "TVHuberL1-Deconvolution [" + img.dimension(0) + ", " + img.dimension(1) + "]: " + t / 1000.0 + "sec"); System.out.println("Time/Iteration: " + (double) t / numIts + "millisec"); return result; } @SuppressWarnings("unchecked") private Img<FloatType> deconvolutionL1TGV2D(final Img<FloatType> img, final Img<FloatType> kernel, final int numIts) { long t = System.currentTimeMillis(); final Img<FloatType> result = (Img<FloatType>) ops.run(TGVL1Deconvolution.class, img, kernel, 0.1, 0.2, numIts); t = System.currentTimeMillis() - t; System.out.println( "TGVL1-Deconvolution [" + img.dimension(0) + ", " + img.dimension(1) + "]: " + t / 1000.0 + "sec"); System.out.println("Time/Iteration: " + (double) t / numIts + "millisec"); return result; } @SuppressWarnings("unchecked") private Img<FloatType> denoisingKLDivTV2D(final Img<FloatType> img, final int numIts) { long t = System.currentTimeMillis(); final Img<FloatType> result = (Img<FloatType>) ops.run(TVKLDivDenoising.class, img, 0.5, numIts); t = System.currentTimeMillis() - t; System.out.println( "TVKLDiv-Denoising [" + img.dimension(0) + ", " + img.dimension(1) + "]: " + t / 1000.0 + "sec"); System.out.println("Time/Iteration: " + (double) t / numIts + "millisec"); return result; } @SuppressWarnings("unchecked") private Img<FloatType> denoisingKLDivTVHuber2D(final Img<FloatType> img, final int numIts) { long t = System.currentTimeMillis(); final Img<FloatType> result = (Img<FloatType>) ops.run(TVHuberKLDivDenoising.class, img, 0.5, 0.02, numIts); t = System.currentTimeMillis() - t; System.out.println( "TVHuberKLDiv-Denoising [" + img.dimension(0) + ", " + img.dimension(1) + "]: " + t / 1000.0 + "sec"); System.out.println("Time/Iteration: " + (double) t / numIts + "millisec"); return result; } @SuppressWarnings("unchecked") private Img<FloatType> denoisingKLDivTGV2D(final Img<FloatType> img, final int numIts) { long t = System.currentTimeMillis(); final Img<FloatType> result = (Img<FloatType>) ops.run(TGVKLDivDenoising.class, img, 0.5, 2.0, numIts); t = System.currentTimeMillis() - t; System.out.println( "TGVKLDiv-Denoising [" + img.dimension(0) + ", " + img.dimension(1) + "]: " + t / 1000.0 + "sec"); System.out.println("Time/Iteration: " + (double) t / numIts + "millisec"); return result; } @SuppressWarnings("unchecked") private Img<FloatType> deconvolutionKLDivTV2D(final Img<FloatType> img, final Img<FloatType> kernel, final int numIts) { long t = System.currentTimeMillis(); final Img<FloatType> result = (Img<FloatType>) ops.run(TVKLDivDeconvolution.class, img, kernel, 0.008, numIts); t = System.currentTimeMillis() - t; System.out.println( "TVKLDiv-Deconvolution [" + img.dimension(0) + ", " + img.dimension(1) + "]: " + t / 1000.0 + "sec"); System.out.println("Time/Iteration: " + (double) t / numIts + "millisec"); return result; } @SuppressWarnings("unchecked") private Img<FloatType> deconvolutionKLDivTVHuber2D(final Img<FloatType> img, final Img<FloatType> kernel, final int numIts) { long t = System.currentTimeMillis(); final Img<FloatType> result = (Img<FloatType>) ops.run(TVHuberKLDivDeconvolution.class, img, kernel, 0.01, 0.05, numIts); t = System.currentTimeMillis() - t; System.out.println("TVHuberKLDiv-Deconvolution [" + img.dimension(0) + ", " + img.dimension(1) + "]: " + t / 1000.0 + "sec"); System.out.println("Time/Iteration: " + (double) t / numIts + "millisec"); return result; } @SuppressWarnings("unchecked") private Img<FloatType> deconvolutionKLDivTGV2D(final Img<FloatType> img, final Img<FloatType> kernel, final int numIts) { long t = System.currentTimeMillis(); final Img<FloatType> result = (Img<FloatType>) ops.run(TGVKLDivDeconvolution.class, img, kernel, 0.01, 0.02, numIts); t = System.currentTimeMillis() - t; System.out.println( "TGVKLDiv-Deconvolution [" + img.dimension(0) + ", " + img.dimension(1) + "]: " + t / 1000.0 + "sec"); System.out.println("Time/Iteration: " + (double) t / numIts + "millisec"); return result; } }
package org.apache.commons.dbcp; import java.io.PrintWriter; import java.util.Properties; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverManager; import java.sql.SQLException; import javax.sql.DataSource; import org.apache.commons.dbcp.DriverConnectionFactory; import org.apache.commons.dbcp.PoolableConnectionFactory; import org.apache.commons.dbcp.PoolingDataSource; import org.apache.commons.pool.impl.GenericObjectPool; public class BasicDataSource implements DataSource { protected boolean defaultAutoCommit = true; public boolean getDefaultAutoCommit() { return (this.defaultAutoCommit); } public void setDefaultAutoCommit(boolean defaultAutoCommit) { this.defaultAutoCommit = defaultAutoCommit; } protected boolean defaultReadOnly = false; public boolean getDefaultReadOnly() { return (this.defaultReadOnly); } public void setDefaultReadOnly(boolean defaultReadOnly) { this.defaultReadOnly = defaultReadOnly; } /** * The fully qualified Java class name of the JDBC driver to be used. */ protected String driverClassName = null; public String getDriverClassName() { return (this.driverClassName); } public void setDriverClassName(String driverClassName) { this.driverClassName = driverClassName; } /** * The maximum number of active connections that can be allocated from * this pool at the same time, or zero for no limit. */ protected int maxActive = 0; public int getMaxActive() { return (this.maxActive); } public void setMaxActive(int maxActive) { this.maxActive = maxActive; } /** * The maximum number of active connections that can remain idle in the * pool, without extra ones being released, or zero for no limit. */ protected int maxIdle = 0; public int getMaxIdle() { return (this.maxIdle); } public void setMaxIdle(int maxIdle) { this.maxIdle = maxIdle; } /** * The maximum number of milliseconds that the pool will wait (when there * are no available connections) for a connection to be returned before * throwing an exception, or -1 to wait indefinitely. */ protected long maxWait = -1; public long getMaxWait() { return (this.maxWait); } public void setMaxWait(long maxWait) { this.maxWait = maxWait; } /** * [Read Only] The current number of active connections that have been * allocated from this data source. */ public int getNumActive() { if (connectionPool != null) { return (connectionPool.getNumActive()); } else { return (0); } } /** * [Read Only] The current number of idle connections that are waiting * to be allocated from this data source. */ public int getNumIdle() { if (connectionPool != null) { return (connectionPool.getNumIdle()); } else { return (0); } } /** * The connection password to be passed to our JDBC driver to establish * a connection. */ protected String password = null; public String getPassword() { return (this.password); } public void setPassword(String password) { this.password = password; } /** * The connection URL to be passed to our JDBC driver to establish * a connection. */ protected String url = null; public String getUrl() { return (this.url); } public void setUrl(String url) { this.url = url; } /** * The connection username to be passed to our JDBC driver to * establish a connection. */ protected String username = null; public String getUsername() { return (this.username); } public void setUsername(String username) { this.username = username; } /** * The SQL query that will be used to validate connections from this pool * before returning them to the caller. If specified, this query * <strong>MUST</strong> be an SQL SELECT statement that returns at least * one row. */ protected String validationQuery = null; public String getValidationQuery() { return (this.validationQuery); } public void setValidationQuery(String validationQuery) { this.validationQuery = validationQuery; } /** * The object pool that internally manages our connections. */ protected GenericObjectPool connectionPool = null; /** * The connection properties that will be sent to our JDBC driver when * establishing new connections. <strong>NOTE</strong> - The "user" and * "password" properties will be passed explicitly, so they do not need * to be included here. */ protected Properties connectionProperties = new Properties(); /** * The data source we will use to manage connections. This object should * be acquired <strong>ONLY</strong> by calls to the * <code>createDataSource()</code> method. */ protected DataSource dataSource = null; /** * The PrintWriter to which log messages should be directed. */ protected PrintWriter logWriter = new PrintWriter(System.out); /** * Create (if necessary) and return a connection to the database. * * @exception SQLException if a database access error occurs */ public Connection getConnection() throws SQLException { return (createDataSource().getConnection()); } /** * Create (if necessary) and return a connection to the database. * * @param username Database user on whose behalf the Connection * is being made * @param password The database user's password * * @exception SQLException if a database access error occurs */ public Connection getConnection(String username, String password) throws SQLException { return (createDataSource().getConnection(username, password)); } /** * Return the login timeout (in seconds) for connecting to the database. * * @exception SQLException if a database access error occurs */ public int getLoginTimeout() throws SQLException { return (createDataSource().getLoginTimeout()); } /** * Return the log writer being used by this data source. * * @exception SQLException if a database access error occurs */ public PrintWriter getLogWriter() throws SQLException { return (createDataSource().getLogWriter()); } /** * Set the login timeout (in seconds) for connecting to the database. * * @param loginTimeout The new login timeout, or zero for no timeout * * @exception SQLException if a database access error occurs */ public void setLoginTimeout(int loginTimeout) throws SQLException { createDataSource().setLoginTimeout(loginTimeout); } /** * Set the log writer being used by this data source. * * @param logWriter The new log writer * * @exception SQLException if a database access error occurs */ public void setLogWriter(PrintWriter logWriter) throws SQLException { createDataSource().setLogWriter(logWriter); this.logWriter = logWriter; } /** * Add a custom connection property to the set that will be passed to our * JDBC driver. This <strong>MUST</strong> be called before the first * connection is retrieved (along with all the other configuration * property setters). * * @param name Name of the custom connection property * @param value Value of the custom connection property */ public void addConnectionProperty(String name, String value) { connectionProperties.put(name, value); } /** * Close and release all connections that are currently stored in the * connection pool associated with our data source. * * @exception SQLException if a database error occurs */ public void close() throws SQLException { GenericObjectPool oldpool = connectionPool; connectionPool = null; dataSource = null; try { oldpool.close(); } catch(SQLException e) { throw e; } catch(RuntimeException e) { throw e; } catch(Exception e) { throw new SQLException(e.toString()); } } protected synchronized DataSource createDataSource() throws SQLException { // Return the pool if we have already created it if (dataSource != null) { return (dataSource); } // Load the JDBC driver class Class driverClass = null; try { driverClass = Class.forName(driverClassName); } catch (Throwable t) { String message = "Cannot load JDBC driver class '" + driverClassName + "'"; logWriter.println(message); t.printStackTrace(logWriter); throw new SQLException(message); } // Create a JDBC driver instance Driver driver = null; try { driver = DriverManager.getDriver(url); } catch (Throwable t) { String message = "Cannot create JDBC driver of class '" + driverClassName + "'"; logWriter.println(message); t.printStackTrace(logWriter); throw new SQLException(message); } // Create an object pool to contain our active connections connectionPool = new GenericObjectPool(null); connectionPool.setMaxActive(maxActive); connectionPool.setMaxIdle(maxIdle); connectionPool.setMaxWait(maxWait); // Set up the driver connection factory we will use connectionProperties.put("user", username); connectionProperties.put("password", password); DriverConnectionFactory driverConnectionFactory = new DriverConnectionFactory(driver, url, connectionProperties); // Set up the poolable connection factory we will use PoolableConnectionFactory connectionFactory = null; try { connectionFactory = new PoolableConnectionFactory(driverConnectionFactory, connectionPool, null, // FIXME - stmtPoolFactory? validationQuery, defaultReadOnly, defaultAutoCommit); } catch(SQLException e) { throw e; } catch(RuntimeException e) { throw e; } catch(Exception e) { throw new SQLException(e.toString()); } // Create and return the pooling data source to manage the connections dataSource = new PoolingDataSource(connectionPool); dataSource.setLogWriter(logWriter); return (dataSource); } }
package com.elmakers.mine.bukkit.utility; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Arrays; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.util.Vector; public class TextUtils { private static final NumberFormat[] formatters = { new DecimalFormat(" new DecimalFormat(" new DecimalFormat("#0.00"), new DecimalFormat("#0.000") }; private static final Pattern replacePattern = Pattern.compile("([$@][\\w]+)([$@]?)"); enum Numeral { I(1), IV(4), V(5), IX(9), X(10), XL(40), L(50), XC(90), C(100), CD(400), D(500), CM(900), M(1000); final int weight; Numeral(int weight) { this.weight = weight; } } public static String roman(long n) { if (n <= 0) { return ""; } StringBuilder buf = new StringBuilder(); final Numeral[] values = Numeral.values(); for (int i = values.length - 1; i >= 0; i { while (n >= values[i].weight) { buf.append(values[i]); n -= values[i].weight; } } return buf.toString(); } public static String printNumber(double number, int digits) { NumberFormat formatter = formatters[Math.min(Math.max(0, digits), formatters.length - 1)]; return formatter.format(number); } public static String printLocationAndWorld(Location location, int digits) { String locationString = printLocation(location, digits); World world = location.getWorld(); if (world != null) { locationString = locationString + ChatColor.GRAY + "(" + ChatColor.AQUA + world.getName() + ChatColor.GRAY + ")"; } return locationString; } public static String printLocation(Location location) { return printLocation(location, 2); } public static String printLocation(Location location, int digits) { NumberFormat formatter = formatters[Math.min(Math.max(0, digits), formatters.length - 1)]; return "" + ChatColor.BLUE + formatter.format(location.getX()) + ChatColor.GRAY + "," + ChatColor.BLUE + formatter.format(location.getY()) + ChatColor.GRAY + "," + ChatColor.BLUE + formatter.format(location.getZ()); } public static String printBlockLocation(Location location) { return "" + ChatColor.BLUE + location.getBlockX() + ChatColor.GRAY + "," + ChatColor.BLUE + location.getBlockY() + ChatColor.GRAY + "," + ChatColor.BLUE + location.getBlockZ(); } public static String printVector(Vector vector) { return printVector(vector, 3); } public static String printVector(Vector vector, int digits) { NumberFormat formatter = formatters[Math.min(Math.max(0, digits), formatters.length - 1)]; return "" + ChatColor.BLUE + formatter.format(vector.getX()) + ChatColor.GRAY + "," + ChatColor.BLUE + formatter.format(vector.getY()) + ChatColor.GRAY + "," + ChatColor.BLUE + formatter.format(vector.getZ()); } public static String printBlock(Block block) { return printLocation(block.getLocation(), 0) + ChatColor.GRAY + "(" + ChatColor.GOLD + block.getType() + ChatColor.GRAY + ")"; } public static String parameterize(String command, Location location, Player player) { return parameterize(command, new BasicReplacer(location, player)); } public static String parameterize(String text, Replacer replacer) { StringBuffer parameterized = new StringBuffer(); Matcher m = replacePattern.matcher(text); while (m.find()) { String symbol = m.group(1); if (symbol.length() < 2) continue; char prefix = symbol.charAt(0); boolean integerValue = prefix == '@'; symbol = symbol.substring(1); String repString = replacer.getReplacement(symbol, integerValue); if (repString != null) m.appendReplacement(parameterized, repString); } m.appendTail(parameterized); return parameterized.toString(); } public static void sendMessage(CommandSender target, String message) { sendMessage(target, "", message); } public static void sendMessage(CommandSender target, String prefix, String message) { sendMessage(target, target instanceof Player ? (Player)target : null, prefix, message); } public static void sendMessage(CommandSender sender, Player player, String prefix, String message) { if (message == null || message.length() == 0 || sender == null) return; boolean isTitle = false; boolean isActionBar = false; if (message.startsWith("a:")) { prefix = ""; isActionBar = true; message = message.substring(2); } else if (message.startsWith("t:")) { isTitle = true; prefix = ""; message = message.substring(2); } else if (prefix.startsWith("a:")) { isActionBar = true; prefix = prefix.substring(2); } else if (prefix.startsWith("t:")) { isTitle = true; prefix = prefix.substring(2); } String[] messages = StringUtils.split(message, "\n"); if (messages.length == 0) { return; } if (isTitle && player != null) { String fullMessage = prefix + messages[0]; String subtitle = messages.length > 1 ? prefix + messages[1] : ""; CompatibilityLib.getCompatibilityUtils().sendTitle(player, fullMessage, subtitle, -1, -1, -1); if (messages.length > 2) { messages = Arrays.copyOfRange(messages, 2, messages.length); } else { return; } } for (String line : messages) { if (line.trim().isEmpty()) continue; boolean lineIsActionBar = isActionBar; if (line.startsWith("a:")) { lineIsActionBar = true; line = line.substring(2); } isActionBar = false; String fullMessage = prefix + line; if (lineIsActionBar && player != null) { CompatibilityLib.getCompatibilityUtils().sendActionBar(player, fullMessage); } else { sender.sendMessage(fullMessage); } } } public static String nameItem(ItemStack itemStack) { if (itemStack == null) { return "Nothing"; } ItemMeta meta = itemStack.getItemMeta(); if (meta != null && meta.hasDisplayName()) { return meta.getDisplayName(); } return itemStack.getType().name(); } }