answer
stringlengths
17
10.2M
package org.jfree.chart.plot; import java.awt.AlphaComposite; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Composite; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Polygon; import java.awt.Rectangle; import java.awt.Shape; import java.awt.Stroke; import java.awt.font.FontRenderContext; import java.awt.font.LineMetrics; import java.awt.geom.Arc2D; import java.awt.geom.Ellipse2D; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.jfree.chart.LegendItem; import org.jfree.chart.LegendItemCollection; import org.jfree.chart.entity.CategoryItemEntity; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.PlotChangeEvent; import org.jfree.chart.labels.CategoryItemLabelGenerator; import org.jfree.chart.labels.CategoryToolTipGenerator; import org.jfree.chart.labels.StandardCategoryItemLabelGenerator; import org.jfree.chart.urls.CategoryURLGenerator; import org.jfree.data.category.CategoryDataset; import org.jfree.data.general.DatasetChangeEvent; import org.jfree.data.general.DatasetUtilities; import org.jfree.io.SerialUtilities; import org.jfree.ui.RectangleInsets; import org.jfree.util.ObjectUtilities; import org.jfree.util.PaintList; import org.jfree.util.PaintUtilities; import org.jfree.util.Rotation; import org.jfree.util.ShapeUtilities; import org.jfree.util.StrokeList; import org.jfree.util.TableOrder; /** * A plot that displays data from a {@link CategoryDataset} in the form of a * "spider web". Multiple series can be plotted on the same axis to allow * easy comparison. This plot doesn't support negative values at present. */ public class SpiderWebPlot extends Plot implements Cloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = -5376340422031599463L; /** The default head radius percent (currently 1%). */ public static final double DEFAULT_HEAD = 0.01; /** The default axis label gap (currently 10%). */ public static final double DEFAULT_AXIS_LABEL_GAP = 0.10; /** The default interior gap. */ public static final double DEFAULT_INTERIOR_GAP = 0.25; /** The maximum interior gap (currently 40%). */ public static final double MAX_INTERIOR_GAP = 0.40; /** The default starting angle for the radar chart axes. */ public static final double DEFAULT_START_ANGLE = 90.0; /** The default series label font. */ public static final Font DEFAULT_LABEL_FONT = new Font("SansSerif", Font.PLAIN, 10); /** The default series label paint. */ public static final Paint DEFAULT_LABEL_PAINT = Color.black; /** The default series label background paint. */ public static final Paint DEFAULT_LABEL_BACKGROUND_PAINT = new Color(255, 255, 192); /** The default series label outline paint. */ public static final Paint DEFAULT_LABEL_OUTLINE_PAINT = Color.black; /** The default series label outline stroke. */ public static final Stroke DEFAULT_LABEL_OUTLINE_STROKE = new BasicStroke(0.5f); /** The default series label shadow paint. */ public static final Paint DEFAULT_LABEL_SHADOW_PAINT = Color.lightGray; /** * Length of the tick mark. * (hardcoded for now, to be customizable in the future). */ private static final double TICK_MARK_LENGTH = 6d; /** The head radius as a percentage of the available drawing area. */ protected double headPercent; /** Stroke to be used for head drawing. */ protected Stroke headOutlineStroke; /** The space left around the outside of the plot as a percentage. */ private double interiorGap; /** The gap between the labels and the axes as a %age of the radius. */ private double axisLabelGap; /** * The paint used to draw the axis lines. * * @since 1.0.4 */ private transient Paint axisLinePaint; /** * The stroke used to draw the axis lines. * * @since 1.0.4 */ private transient Stroke axisLineStroke; /** The dataset. */ private CategoryDataset dataset; /** The maximum value we are plotting against on each category axis */ private Double maxValue; private Map/*<Integer, Double>*/ maxValues; /** The origin common for all categories axes. */ private Double origin; private Map/*<Integer, Double>*/ origins; /** * The data extract order (BY_ROW or BY_COLUMN). This denotes whether * the data series are stored in rows (in which case the category names are * derived from the column keys) or in columns (in which case the category * names are derived from the row keys). */ private TableOrder dataExtractOrder; /** The starting angle. */ private double startAngle; /** The direction for drawing the radar axis & plots. */ private Rotation direction; /** The legend item shape. */ private transient Shape legendItemShape; /** The paint for ALL series (overrides list). */ private transient Paint seriesPaint; /** The series paint list. */ private PaintList seriesPaintList; /** The base series paint (fallback). */ private transient Paint baseSeriesPaint; /** The outline paint for ALL series (overrides list). */ private transient Paint seriesOutlinePaint; /** The series outline paint list. */ private PaintList seriesOutlinePaintList; /** The base series outline paint (fallback). */ private transient Paint baseSeriesOutlinePaint; /** The outline stroke for ALL series (overrides list). */ private transient Stroke seriesOutlineStroke; /** The series outline stroke list. */ private StrokeList seriesOutlineStrokeList; /** The base series outline stroke (fallback). */ private transient Stroke baseSeriesOutlineStroke; /** The font used to display the category labels. */ private Font labelFont; /** The color used to draw the category labels. */ private transient Paint labelPaint; /** The label generator. */ private CategoryItemLabelGenerator labelGenerator; /** controls if the web polygons are filled or not */ private boolean webFilled = true; /** A tooltip generator for the plot (<code>null</code> permitted). */ private CategoryToolTipGenerator toolTipGenerator; /** A URL generator for the plot (<code>null</code> permitted). */ private CategoryURLGenerator urlGenerator; /** Whether to draw tick marks and labels. */ private boolean axisTickVisible; /** * Creates a default plot with no dataset. */ public SpiderWebPlot() { this(null); } /** * Creates a new spider web plot with the given dataset, with each row * representing a series. * * @param dataset the dataset (<code>null</code> permitted). */ public SpiderWebPlot(CategoryDataset dataset) { this(dataset, TableOrder.BY_ROW); } /** * Creates a new spider web plot with the given dataset. * * @param dataset the dataset. * @param extract controls how data is extracted ({@link TableOrder#BY_ROW} * or {@link TableOrder#BY_COLUMN}). */ public SpiderWebPlot(CategoryDataset dataset, TableOrder extract) { super(); if (extract == null) { throw new IllegalArgumentException("Null 'extract' argument."); } this.dataset = dataset; if (dataset != null) { dataset.addChangeListener(this); } this.dataExtractOrder = extract; this.headPercent = DEFAULT_HEAD; this.axisLabelGap = DEFAULT_AXIS_LABEL_GAP; this.axisLinePaint = Color.black; this.axisLineStroke = new BasicStroke(1.0f); this.interiorGap = DEFAULT_INTERIOR_GAP; this.startAngle = DEFAULT_START_ANGLE; this.direction = Rotation.CLOCKWISE; this.seriesPaint = null; this.seriesPaintList = new PaintList(); this.baseSeriesPaint = null; this.seriesOutlinePaint = null; this.seriesOutlinePaintList = new PaintList(); this.baseSeriesOutlinePaint = DEFAULT_OUTLINE_PAINT; this.seriesOutlineStroke = null; this.seriesOutlineStrokeList = new StrokeList(); this.baseSeriesOutlineStroke = DEFAULT_OUTLINE_STROKE; this.labelFont = DEFAULT_LABEL_FONT; this.labelPaint = DEFAULT_LABEL_PAINT; this.labelGenerator = new StandardCategoryItemLabelGenerator(); this.legendItemShape = DEFAULT_LEGEND_ITEM_CIRCLE; this.origins = new HashMap(); this.maxValues = new HashMap(); } /** * Returns a short string describing the type of plot. * * @return The plot type. */ public String getPlotType() { // return localizationResources.getString("Radar_Plot"); return ("Spider Web Plot"); } /** * Returns the dataset. * * @return The dataset (possibly <code>null</code>). * * @see #setDataset(CategoryDataset) */ public CategoryDataset getDataset() { return this.dataset; } /** * Sets the dataset used by the plot and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param dataset the dataset (<code>null</code> permitted). * * @see #getDataset() */ public void setDataset(CategoryDataset dataset) { // if there is an existing dataset, remove the plot from the list of // change listeners... if (this.dataset != null) { this.dataset.removeChangeListener(this); } // set the new dataset, and register the chart as a change listener... this.dataset = dataset; if (dataset != null) { setDatasetGroup(dataset.getGroup()); dataset.addChangeListener(this); } resetBoundaryValues(); // send a dataset change event to self to trigger plot change event datasetChanged(new DatasetChangeEvent(this, dataset)); } private void resetBoundaryValues() { this.maxValues.clear(); this.origins.clear(); } /** * Method to determine if the web chart is to be filled. * * @return A boolean. * * @see #setWebFilled(boolean) */ public boolean isWebFilled() { return this.webFilled; } /** * Sets the webFilled flag and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param flag the flag. * * @see #isWebFilled() */ public void setWebFilled(boolean flag) { this.webFilled = flag; fireChangeEvent(); } /** * Returns the data extract order (by row or by column). * * @return The data extract order (never <code>null</code>). * * @see #setDataExtractOrder(TableOrder) */ public TableOrder getDataExtractOrder() { return this.dataExtractOrder; } public void setDataExtractOrder(TableOrder order) { if (order == null) { throw new IllegalArgumentException("Null 'order' argument"); } this.dataExtractOrder = order; fireChangeEvent(); } /** * Returns the head percent. * * @return The head percent. * * @see #setHeadPercent(double) */ public double getHeadPercent() { return this.headPercent; } /** * Sets the head percent and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param percent the percent. * * @see #getHeadPercent() */ public void setHeadPercent(double percent) { this.headPercent = percent; fireChangeEvent(); } /** * Sets the head outline stroke for all series. When <code>null</code> * {@link #getSeriesOutlineStroke(int)} is used. Sends a {@link * PlotChangeEvent} to all registered listeners. * * @param headOutlineStroke head outline stroke */ public void setHeadOutlineStroke(Stroke headOutlineStroke) { this.headOutlineStroke = headOutlineStroke; fireChangeEvent(); } /** * Returns the head outline stroke. * * @return head outline stroke. */ public Stroke getHeadOutlineStroke() { return headOutlineStroke; } private Stroke getHeadOutlineStroke(int series) { return headOutlineStroke == null ? getSeriesOutlineStroke(series) : headOutlineStroke; } /** * Returns the start angle for the first radar axis. * <BR> * This is measured in degrees starting from 3 o'clock (Java Arc2D default) * and measuring anti-clockwise. * * @return The start angle. * * @see #setStartAngle(double) */ public double getStartAngle() { return this.startAngle; } /** * Sets the starting angle and sends a {@link PlotChangeEvent} to all * registered listeners. * <P> * The initial default value is 90 degrees, which corresponds to 12 o'clock. * A value of zero corresponds to 3 o'clock... this is the encoding used by * Java's Arc2D class. * * @param angle the angle (in degrees). * * @see #getStartAngle() */ public void setStartAngle(double angle) { this.startAngle = angle; fireChangeEvent(); } /** * Returns the maximum value which is used for all categories. * * @return The maximum value. * * @see #setMaxValue(Double) */ public Double getMaxValue() { return this.maxValue; } /** * Returns maximum value for a particular category. * * @return The maximum value. * * @see #setMaxValue(Double) */ public Double getMaxValue(int cat) { return maxValue == null ? (Double) maxValues.get(new Integer(cat)) : maxValue; } /** * Sets the maxValue for <em>all</em> series in the plot. If this is set to * <code>null</code>, then a list of maxValues is used instead (to allow * different maxValues to be used for each series). * * @param maxValue the maxValue (<code>null</code> permitted). */ public void setMaxValue(Double maxValue) { this.maxValue = maxValue; fireChangeEvent(); } /** * Sets maximum value for category. */ public void setMaxValue(int cat, Double value) { maxValues.put(new Integer(cat), value); fireChangeEvent(); } public Double getOrigin(int cat) { return origin == null ? (Double) origins.get(new Integer(cat)) : origin; } /** * Sets origin for category. */ public void setOrigin(int cat, Double value) { origins.put(new Integer(cat), value); fireChangeEvent(); } /** * Sets the origin for <em>all</em> series in the plot. If this is set to * <code>null</code>, then a list of origins is used instead (to allow * different origins to be used for each series). * * @param origin the origin (<code>null</code> permitted). */ public void setOrigin(Double origin) { this.origin = origin; fireChangeEvent(); } /** * Returns the direction in which the radar axes are drawn * (clockwise or anti-clockwise). * * @return The direction (never <code>null</code>). * * @see #setDirection(Rotation) */ public Rotation getDirection() { return this.direction; } /** * Sets the direction in which the radar axes are drawn and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param direction the direction (<code>null</code> not permitted). * * @see #getDirection() */ public void setDirection(Rotation direction) { if (direction == null) { throw new IllegalArgumentException("Null 'direction' argument."); } this.direction = direction; fireChangeEvent(); } /** * Returns the interior gap, measured as a percentage of the available * drawing space. * * @return The gap (as a percentage of the available drawing space). * * @see #setInteriorGap(double) */ public double getInteriorGap() { return this.interiorGap; } /** * Sets the interior gap and sends a {@link PlotChangeEvent} to all * registered listeners. This controls the space between the edges of the * plot and the plot area itself (the region where the axis labels appear). * * @param percent the gap (as a percentage of the available drawing space). * * @see #getInteriorGap() */ public void setInteriorGap(double percent) { if ((percent < 0.0) || (percent > MAX_INTERIOR_GAP)) { throw new IllegalArgumentException( "Percentage outside valid range."); } if (this.interiorGap != percent) { this.interiorGap = percent; fireChangeEvent(); } } /** * Returns the axis label gap. * * @return The axis label gap. * * @see #setAxisLabelGap(double) */ public double getAxisLabelGap() { return this.axisLabelGap; } /** * Sets the axis label gap and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param gap the gap. * * @see #getAxisLabelGap() */ public void setAxisLabelGap(double gap) { this.axisLabelGap = gap; fireChangeEvent(); } /** * Returns the paint used to draw the axis lines. * * @return The paint used to draw the axis lines (never <code>null</code>). * * @see #setAxisLinePaint(Paint) * @see #getAxisLineStroke() * @since 1.0.4 */ public Paint getAxisLinePaint() { return this.axisLinePaint; } /** * Sets the paint used to draw the axis lines and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getAxisLinePaint() * @since 1.0.4 */ public void setAxisLinePaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.axisLinePaint = paint; fireChangeEvent(); } /** * Returns the stroke used to draw the axis lines. * * @return The stroke used to draw the axis lines (never <code>null</code>). * * @see #setAxisLineStroke(Stroke) * @see #getAxisLinePaint() * @since 1.0.4 */ public Stroke getAxisLineStroke() { return this.axisLineStroke; } /** * Sets the stroke used to draw the axis lines and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param stroke the stroke (<code>null</code> not permitted). * * @see #getAxisLineStroke() * @since 1.0.4 */ public void setAxisLineStroke(Stroke stroke) { if (stroke == null) { throw new IllegalArgumentException("Null 'stroke' argument."); } this.axisLineStroke = stroke; fireChangeEvent(); } //// SERIES PAINT ///////////////////////// /** * Returns the paint for ALL series in the plot. * * @return The paint (possibly <code>null</code>). * * @see #setSeriesPaint(Paint) */ public Paint getSeriesPaint() { return this.seriesPaint; } /** * Sets the paint for ALL series in the plot. If this is set to</code> null * </code>, then a list of paints is used instead (to allow different colors * to be used for each series of the radar group). * * @param paint the paint (<code>null</code> permitted). * * @see #getSeriesPaint() */ public void setSeriesPaint(Paint paint) { this.seriesPaint = paint; fireChangeEvent(); } /** * Returns the paint for the specified series. * * @param series the series index (zero-based). * * @return The paint (never <code>null</code>). * * @see #setSeriesPaint(int, Paint) */ public Paint getSeriesPaint(int series) { // return the override, if there is one... if (this.seriesPaint != null) { return this.seriesPaint; } // otherwise look up the paint list Paint result = this.seriesPaintList.getPaint(series); if (result == null) { DrawingSupplier supplier = getDrawingSupplier(); if (supplier != null) { Paint p = supplier.getNextPaint(); this.seriesPaintList.setPaint(series, p); result = p; } else { result = this.baseSeriesPaint; } } return result; } /** * Sets the paint used to fill a series of the radar and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param series the series index (zero-based). * @param paint the paint (<code>null</code> permitted). * * @see #getSeriesPaint(int) */ public void setSeriesPaint(int series, Paint paint) { this.seriesPaintList.setPaint(series, paint); fireChangeEvent(); } /** * Returns the base series paint. This is used when no other paint is * available. * * @return The paint (never <code>null</code>). * * @see #setBaseSeriesPaint(Paint) */ public Paint getBaseSeriesPaint() { return this.baseSeriesPaint; } /** * Sets the base series paint. * * @param paint the paint (<code>null</code> not permitted). * * @see #getBaseSeriesPaint() */ public void setBaseSeriesPaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.baseSeriesPaint = paint; fireChangeEvent(); } //// SERIES OUTLINE PAINT //////////////////////////// /** * Returns the outline paint for ALL series in the plot. * * @return The paint (possibly <code>null</code>). */ public Paint getSeriesOutlinePaint() { return this.seriesOutlinePaint; } /** * Sets the outline paint for ALL series in the plot. If this is set to * </code> null</code>, then a list of paints is used instead (to allow * different colors to be used for each series). * * @param paint the paint (<code>null</code> permitted). */ public void setSeriesOutlinePaint(Paint paint) { this.seriesOutlinePaint = paint; fireChangeEvent(); } /** * Returns the paint for the specified series. * * @param series the series index (zero-based). * * @return The paint (never <code>null</code>). */ public Paint getSeriesOutlinePaint(int series) { // return the override, if there is one... if (this.seriesOutlinePaint != null) { return this.seriesOutlinePaint; } // otherwise look up the paint list Paint result = this.seriesOutlinePaintList.getPaint(series); if (result == null) { result = this.baseSeriesOutlinePaint; } return result; } /** * Sets the paint used to fill a series of the radar and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param series the series index (zero-based). * @param paint the paint (<code>null</code> permitted). */ public void setSeriesOutlinePaint(int series, Paint paint) { this.seriesOutlinePaintList.setPaint(series, paint); fireChangeEvent(); } /** * Returns the base series paint. This is used when no other paint is * available. * * @return The paint (never <code>null</code>). */ public Paint getBaseSeriesOutlinePaint() { return this.baseSeriesOutlinePaint; } /** * Sets the base series paint. * * @param paint the paint (<code>null</code> not permitted). */ public void setBaseSeriesOutlinePaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.baseSeriesOutlinePaint = paint; fireChangeEvent(); } //// SERIES OUTLINE STROKE ///////////////////// /** * Returns the outline stroke for ALL series in the plot. * * @return The stroke (possibly <code>null</code>). */ public Stroke getSeriesOutlineStroke() { return this.seriesOutlineStroke; } /** * Sets the outline stroke for ALL series in the plot. If this is set to * </code> null</code>, then a list of paints is used instead (to allow * different colors to be used for each series). * * @param stroke the stroke (<code>null</code> permitted). */ public void setSeriesOutlineStroke(Stroke stroke) { this.seriesOutlineStroke = stroke; fireChangeEvent(); } /** * Returns the stroke for the specified series. * * @param series the series index (zero-based). * * @return The stroke (never <code>null</code>). */ public Stroke getSeriesOutlineStroke(int series) { // return the override, if there is one... if (this.seriesOutlineStroke != null) { return this.seriesOutlineStroke; } // otherwise look up the paint list Stroke result = this.seriesOutlineStrokeList.getStroke(series); if (result == null) { result = this.baseSeriesOutlineStroke; } return result; } /** * Sets the stroke used to fill a series of the radar and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param series the series index (zero-based). * @param stroke the stroke (<code>null</code> permitted). */ public void setSeriesOutlineStroke(int series, Stroke stroke) { this.seriesOutlineStrokeList.setStroke(series, stroke); fireChangeEvent(); } /** * Returns the base series stroke. This is used when no other stroke is * available. * * @return The stroke (never <code>null</code>). */ public Stroke getBaseSeriesOutlineStroke() { return this.baseSeriesOutlineStroke; } /** * Sets the base series stroke. * * @param stroke the stroke (<code>null</code> not permitted). */ public void setBaseSeriesOutlineStroke(Stroke stroke) { if (stroke == null) { throw new IllegalArgumentException("Null 'stroke' argument."); } this.baseSeriesOutlineStroke = stroke; fireChangeEvent(); } /** * Returns the shape used for legend items. * * @return The shape (never <code>null</code>). * * @see #setLegendItemShape(Shape) */ public Shape getLegendItemShape() { return this.legendItemShape; } /** * Sets the shape used for legend items and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param shape the shape (<code>null</code> not permitted). * * @see #getLegendItemShape() */ public void setLegendItemShape(Shape shape) { if (shape == null) { throw new IllegalArgumentException("Null 'shape' argument."); } this.legendItemShape = shape; fireChangeEvent(); } /** * Returns the series label font. * * @return The font (never <code>null</code>). * * @see #setLabelFont(Font) */ public Font getLabelFont() { return this.labelFont; } /** * Sets the series label font and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param font the font (<code>null</code> not permitted). * * @see #getLabelFont() */ public void setLabelFont(Font font) { if (font == null) { throw new IllegalArgumentException("Null 'font' argument."); } this.labelFont = font; fireChangeEvent(); } /** * Returns the series label paint. * * @return The paint (never <code>null</code>). * * @see #setLabelPaint(Paint) */ public Paint getLabelPaint() { return this.labelPaint; } /** * Sets the series label paint and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getLabelPaint() */ public void setLabelPaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.labelPaint = paint; fireChangeEvent(); } /** * Returns the label generator. * * @return The label generator (never <code>null</code>). * * @see #setLabelGenerator(CategoryItemLabelGenerator) */ public CategoryItemLabelGenerator getLabelGenerator() { return this.labelGenerator; } /** * Sets the label generator and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param generator the generator (<code>null</code> not permitted). * * @see #getLabelGenerator() */ public void setLabelGenerator(CategoryItemLabelGenerator generator) { if (generator == null) { throw new IllegalArgumentException("Null 'generator' argument."); } this.labelGenerator = generator; } /** * Returns the tool tip generator for the plot. * * @return The tool tip generator (possibly <code>null</code>). * * @see #setToolTipGenerator(CategoryToolTipGenerator) * * @since 1.0.2 */ public CategoryToolTipGenerator getToolTipGenerator() { return this.toolTipGenerator; } /** * Sets the tool tip generator for the plot and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param generator the generator (<code>null</code> permitted). * * @see #getToolTipGenerator() * * @since 1.0.2 */ public void setToolTipGenerator(CategoryToolTipGenerator generator) { this.toolTipGenerator = generator; fireChangeEvent(); } /** * Returns the URL generator for the plot. * * @return The URL generator (possibly <code>null</code>). * * @see #setURLGenerator(CategoryURLGenerator) * * @since 1.0.2 */ public CategoryURLGenerator getURLGenerator() { return this.urlGenerator; } /** * Sets the URL generator for the plot and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param generator the generator (<code>null</code> permitted). * * @see #getURLGenerator() * * @since 1.0.2 */ public void setURLGenerator(CategoryURLGenerator generator) { this.urlGenerator = generator; fireChangeEvent(); } public boolean isAxisTickVisible() { return axisTickVisible; } public void setAxisTickVisible(boolean visible) { this.axisTickVisible = visible; fireChangeEvent(); } /** * Returns a collection of legend items for the spider web chart. * * @return The legend items (never <code>null</code>). */ public LegendItemCollection getLegendItems() { LegendItemCollection result = new LegendItemCollection(); if (getDataset() == null) { return result; } List keys = null; if (this.dataExtractOrder == TableOrder.BY_ROW) { keys = this.dataset.getRowKeys(); } else if (this.dataExtractOrder == TableOrder.BY_COLUMN) { keys = this.dataset.getColumnKeys(); } if (keys == null) { return result; } int series = 0; Iterator iterator = keys.iterator(); Shape shape = getLegendItemShape(); while (iterator.hasNext()) { Comparable key = (Comparable) iterator.next(); String label = key.toString(); String description = label; Paint paint = getSeriesPaint(series); Paint outlinePaint = getSeriesOutlinePaint(series); Stroke stroke = getHeadOutlineStroke(series); LegendItem item = new LegendItem(label, description, null, null, shape, paint, stroke, outlinePaint); item.setDataset(getDataset()); item.setSeriesKey(key); item.setSeriesIndex(series); result.add(item); series++; } return result; } /** * Returns a cartesian point from a polar angle, length and bounding box * * @param bounds the area inside which the point needs to be. * @param angle the polar angle, in degrees. * @param length the relative length. Given in percent of maximum extend. * * @return The cartesian point. */ protected Point2D getWebPoint(Rectangle2D bounds, double angle, double length) { double angrad = Math.toRadians(angle); double x = Math.cos(angrad) * length * bounds.getWidth() / 2; double y = -Math.sin(angrad) * length * bounds.getHeight() / 2; return new Point2D.Double(bounds.getX() + x + bounds.getWidth() / 2, bounds.getY() + y + bounds.getHeight() / 2); } /** * Draws the plot on a Java 2D graphics device (such as the screen or a * printer). * * @param g2 the graphics device. * @param area the area within which the plot should be drawn. * @param anchor the anchor point (<code>null</code> permitted). * @param parentState the state from the parent plot, if there is one. * @param info collects info about the drawing. */ public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor, PlotState parentState, PlotRenderingInfo info) { // adjust for insets... RectangleInsets insets = getInsets(); insets.trim(area); if (info != null) { info.setPlotArea(area); info.setDataArea(area); } drawBackground(g2, area); drawOutline(g2, area); Shape savedClip = g2.getClip(); g2.clip(area); Composite originalComposite = g2.getComposite(); g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getForegroundAlpha())); if (!DatasetUtilities.isEmptyOrNull(this.dataset)) { int seriesCount = 0, catCount = 0; if (this.dataExtractOrder == TableOrder.BY_ROW) { seriesCount = this.dataset.getRowCount(); catCount = this.dataset.getColumnCount(); } else { seriesCount = this.dataset.getColumnCount(); catCount = this.dataset.getRowCount(); } // ensure we have origin and maximum value for each axis ensureBoundaryValues(seriesCount, catCount); // Next, setup the plot area // adjust the plot area by the interior spacing value double gapHorizontal = area.getWidth() * getInteriorGap(); double gapVertical = area.getHeight() * getInteriorGap(); double X = area.getX() + gapHorizontal / 2; double Y = area.getY() + gapVertical / 2; double W = area.getWidth() - gapHorizontal; double H = area.getHeight() - gapVertical; double headW = area.getWidth() * this.headPercent; double headH = area.getHeight() * this.headPercent; // make the chart area a square double min = Math.min(W, H) / 2; X = (X + X + W) / 2 - min; Y = (Y + Y + H) / 2 - min; W = 2 * min; H = 2 * min; Point2D centre = new Point2D.Double(X + W / 2, Y + H / 2); Rectangle2D radarArea = new Rectangle2D.Double(X, Y, W, H); // draw the axis and category label for (int cat = 0; cat < catCount; cat++) { double angle = getStartAngle() + (getDirection().getFactor() * cat * 360 / catCount); Point2D endPoint = getWebPoint(radarArea, angle, 1); // 1 = end of axis Line2D line = new Line2D.Double(centre, endPoint); g2.setPaint(this.axisLinePaint); g2.setStroke(this.axisLineStroke); g2.draw(line); if (isAxisTickVisible()) { drawTicks(g2, radarArea, angle, cat); } drawLabel(g2, area, radarArea, 0.0, cat, angle, 360.0 / catCount); } // Now actually plot each of the series polygons.. for (int series = 0; series < seriesCount; series++) { drawRadarPoly(g2, radarArea, centre, info, series, catCount, headH, headW); } } else { drawNoDataMessage(g2, area); } g2.setClip(savedClip); g2.setComposite(originalComposite); drawOutline(g2, area); } private void drawTicks(Graphics2D g2, Rectangle2D radarArea, double axisAngle, int cat) { double[] ticks = {0.5d, 1d}; for (int i = 0; i < ticks.length; i++) { double tick = ticks[i]; Point2D middlePoint = getWebPoint(radarArea, axisAngle, tick); double xt = middlePoint.getX(); double yt = middlePoint.getY(); double angrad = Math.toRadians(-axisAngle); g2.translate(xt, yt); g2.rotate(angrad); g2.drawLine(0, (int) -TICK_MARK_LENGTH / 2, 0, (int) TICK_MARK_LENGTH / 2); g2.rotate(-angrad); g2.translate(-xt, -yt); drawTickLabel(g2, radarArea, middlePoint, axisAngle, cat, tick); } } private void drawTickLabel( Graphics2D g2, Rectangle2D radarArea, Point2D middlePoint, double _axisAngle, int cat, double tick) { double axisAngle = normalize(_axisAngle); double _origin = getOrigin(cat).doubleValue(); double max = getMaxValue(cat).doubleValue(); double tickValue = ((max - _origin) * tick) + _origin; String label = "" + Math.round(tickValue * 1000) / 1000d; FontRenderContext frc = g2.getFontRenderContext(); Rectangle2D labelBounds = getLabelFont().getStringBounds(label, frc); int labelW = (int) labelBounds.getWidth(); int labelH = (int) labelBounds.getHeight(); double centerX = radarArea.getCenterX(); double centerY = radarArea.getCenterY(); double adj = middlePoint.distance(centerX, centerY); double opp = TICK_MARK_LENGTH / 2 + 4; double hyp = Math.sqrt(Math.pow(opp, 2) + Math.pow(adj, 2)); double angle = Math.toDegrees(Math.atan(opp / adj)); int charHeight = g2.getFontMetrics().getHeight(); int charWidth = g2.getFontMetrics().charWidth('M'); double alphaRad = Math.toRadians(axisAngle - angle); double labelX = centerX + (hyp * Math.cos(alphaRad)); double labelY = centerY - (hyp * Math.sin(alphaRad)) + labelH; // g2.draw(new Line2D.Double(centerX, centerY, labelX, labelY - labelH)); // test line double sinGap = Math.pow(Math.sin(Math.toRadians(axisAngle)), 2); if (axisAngle > 90 && axisAngle < 270) { labelY -= labelH; labelY += (charHeight * sinGap / 2); } else { labelY -= (charHeight * sinGap / 2); } double cosGap = Math.pow(Math.cos(Math.toRadians(axisAngle)), 2); if (axisAngle > 180) { labelX -= labelW; labelX += (charWidth * cosGap / 2); } else { labelX -= (charWidth * cosGap / 2); } // g2.drawRect((int) labelX, (int) labelY - labelH, labelW, labelH); // test rectangle g2.setPaint(getLabelPaint()); g2.setFont(getLabelFont()); g2.drawString(label, (float) labelX, (float) labelY); } /** * Loop through each of the series to get the maximum value * on each category axis. * * @param seriesCount the number of series * @param catCount the number of categories */ private void ensureBoundaryValues(int seriesCount, int catCount) { // base origin and maxVaue are used if (origin != null && maxValue != null) { return; } for (int catIndex = 0; catIndex < catCount; catIndex++) { Double preferredCatMax = getMaxValue(catIndex); Double preferredCatOrigin = getOrigin(catIndex); if (preferredCatOrigin != null && preferredCatMax != null) { continue; // already set per category } double catDataMaxVal = -Double.MAX_VALUE; double catDataMinVal = Double.MAX_VALUE; boolean hasValues = false; for (int seriesIndex = 0; seriesIndex < seriesCount; seriesIndex++) { Number nV = getPlotValue(seriesIndex, catIndex); if (nV != null) { hasValues = true; double v = nV.doubleValue(); if (v > catDataMaxVal) { catDataMaxVal = v; } if (v < catDataMinVal) { catDataMinVal = v; } } } if (!hasValues) { setMaxValue(catIndex, new Double(0)); setOrigin(catIndex, new Double(0)); continue; } if (preferredCatMax == null) { preferredCatMax = new Double(catDataMaxVal); setMaxValue(catIndex, preferredCatMax); } // Ensure that origin of a spoke does not coincide with a data point with minimum value. // Such data point would lost information to which spoke (axis) it belongs since it // would be in the center of the spider plot, i.e. it would "belong" to all spokes. if (preferredCatOrigin == null) { double catOriginShift; if (catDataMaxVal == catDataMinVal) { if (catDataMinVal == 0) { // all data points at zero catOriginShift = 0.1; } else { // all data points at the same value catOriginShift = Math.abs(catDataMinVal / 10); } } else { // Shift origin about 10% of the data range from minimum. catOriginShift = Math.abs((catDataMaxVal - catDataMinVal) / 10); } preferredCatOrigin = new Double(catDataMinVal - catOriginShift); setOrigin(catIndex, preferredCatOrigin); } double prefOrigin = preferredCatOrigin.doubleValue(); double prefMax = preferredCatMax.doubleValue(); // special case. Min, max and all values are zero. if (prefOrigin == 0 && prefMax == 0) { prefMax = 0.1; setMaxValue(catIndex, new Double(prefMax)); } if (prefOrigin >= prefMax) { setMaxValue(catIndex, new Double(prefOrigin + Math.abs(prefOrigin / 2))); } } } /** * Draws a radar plot polygon. * * @param g2 the graphics device. * @param plotArea the area we are plotting in (already adjusted). * @param centre the centre point of the radar axes * @param info chart rendering info. * @param series the series within the dataset we are plotting * @param catCount the number of categories per radar plot * @param headH the data point height * @param headW the data point width */ protected void drawRadarPoly(Graphics2D g2, Rectangle2D plotArea, Point2D centre, PlotRenderingInfo info, int series, int catCount, double headH, double headW) { Polygon polygon = new Polygon(); EntityCollection entities = null; if (info != null) { entities = info.getOwner().getEntityCollection(); } // plot the data... for (int cat = 0; cat < catCount; cat++) { Number dataValue = getPlotValue(series, cat); if (dataValue != null) { double value = dataValue.doubleValue(); // Finds our starting angle from the centre for this axis double angle = getStartAngle() + (getDirection().getFactor() * cat * 360 / catCount); // The following angle calc will ensure there isn't a top // vertical axis - this may be useful if you don't want any // given criteria to 'appear' move important than the // others.. // + (getDirection().getFactor() // * (cat + 0.5) * 360 / catCount); // find the point at the appropriate distance end point // along the axis/angle identified above and add it to the // polygon double _maxValue = getMaxValue(cat).doubleValue(); double _origin = getOrigin(cat).doubleValue(); if (value < _origin || value > _maxValue) { continue; } Point2D point = getWebPoint(plotArea, angle, (value - _origin) / (_maxValue - _origin)); polygon.addPoint((int) point.getX(), (int) point.getY()); // put an elipse at the point being plotted.. Paint paint = getSeriesPaint(series); Paint outlinePaint = getSeriesOutlinePaint(series); Ellipse2D head = new Ellipse2D.Double(point.getX() - headW / 2, point.getY() - headH / 2, headW, headH); g2.setPaint(paint); g2.fill(head); g2.setStroke(getHeadOutlineStroke(series)); g2.setPaint(outlinePaint); g2.draw(head); if (entities != null) { int row = 0; int col = 0; if (this.dataExtractOrder == TableOrder.BY_ROW) { row = series; col = cat; } else { row = cat; col = series; } String tip = null; if (this.toolTipGenerator != null) { tip = this.toolTipGenerator.generateToolTip( this.dataset, row, col); } String url = null; if (this.urlGenerator != null) { url = this.urlGenerator.generateURL(this.dataset, row, col); } Shape area = new Rectangle( (int) (point.getX() - headW), (int) (point.getY() - headH), (int) (headW * 2), (int) (headH * 2)); CategoryItemEntity entity = new CategoryItemEntity( area, tip, url, this.dataset, this.dataset.getRowKey(row), this.dataset.getColumnKey(col)); entities.add(entity); } } } // Plot the polygon Paint paint = getSeriesPaint(series); g2.setPaint(paint); g2.setStroke(getSeriesOutlineStroke(series)); g2.draw(polygon); // Lastly, fill the web polygon if this is required if (this.webFilled) { g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.1f)); g2.fill(polygon); g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getForegroundAlpha())); } } /** * Returns the value to be plotted at the interseries of the * series and the category. This allows us to plot * <code>BY_ROW</code> or <code>BY_COLUMN</code> which basically is just * reversing the definition of the categories and data series being * plotted. * * @param series the series to be plotted. * @param cat the category within the series to be plotted. * * @return The value to be plotted (possibly <code>null</code>). * * @see #getDataExtractOrder() */ protected Number getPlotValue(int series, int cat) { Number value = null; if (this.dataExtractOrder == TableOrder.BY_ROW) { value = this.dataset.getValue(series, cat); } else if (this.dataExtractOrder == TableOrder.BY_COLUMN) { value = this.dataset.getValue(cat, series); } return value; } /** * Draws the label for one axis. * * @param g2 the graphics device. * @param plotArea whole plot drawing area (e.g. including space for labels) * @param plotDrawingArea the plot drawing area (just spanning of axis) * @param value the value of the label (ignored). * @param cat the category (zero-based index). * @param startAngle the starting angle. * @param extent the extent of the arc. */ protected void drawLabel(Graphics2D g2, Rectangle2D plotArea, Rectangle2D plotDrawingArea, double value, int cat, double startAngle, double extent) { FontRenderContext frc = g2.getFontRenderContext(); String label = null; if (this.dataExtractOrder == TableOrder.BY_ROW) { // if series are in rows, then the categories are the column keys label = this.labelGenerator.generateColumnLabel(this.dataset, cat); } else { // if series are in columns, then the categories are the row keys label = this.labelGenerator.generateRowLabel(this.dataset, cat); } double angle = normalize(startAngle); Font font = getLabelFont(); Point2D labelLocation; do { Rectangle2D labelBounds = font.getStringBounds(label, frc); LineMetrics lm = font.getLineMetrics(label, frc); double ascent = lm.getAscent(); labelLocation = calculateLabelLocation(labelBounds, ascent, plotDrawingArea, startAngle); boolean leftOut = angle > 90 && angle < 270 && labelLocation.getX() < plotArea.getX(); boolean rightOut = (angle < 90 || angle > 270) && labelLocation.getX() + labelBounds.getWidth() > plotArea.getX() + plotArea.getWidth(); if (leftOut || rightOut) { font = font.deriveFont(font.getSize2D() - 1); } else { break; } } while (font.getSize() > 8); Composite saveComposite = g2.getComposite(); g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f)); g2.setPaint(getLabelPaint()); g2.setFont(font); g2.drawString(label, (float) labelLocation.getX(), (float) labelLocation.getY()); g2.setComposite(saveComposite); } /** * Returns the location for a label * * @param labelBounds the label bounds. * @param ascent the ascent (height of font). * @param plotArea the plot area * @param startAngle the start angle for the pie series. * * @return The location for a label. */ protected Point2D calculateLabelLocation(Rectangle2D labelBounds, double ascent, Rectangle2D plotArea, double startAngle) { Arc2D arc1 = new Arc2D.Double(plotArea, startAngle, 0, Arc2D.OPEN); Point2D point1 = arc1.getEndPoint(); double deltaX = -(point1.getX() - plotArea.getCenterX()) * this.axisLabelGap; double deltaY = -(point1.getY() - plotArea.getCenterY()) * this.axisLabelGap; double labelX = point1.getX() - deltaX; double labelY = point1.getY() - deltaY; if (labelX < plotArea.getCenterX()) { labelX -= labelBounds.getWidth(); } if (labelX == plotArea.getCenterX()) { labelX -= labelBounds.getWidth() / 2; } if (labelY > plotArea.getCenterY()) { labelY += ascent; } return new Point2D.Double(labelX, labelY); } private double normalize(double _axisAngle) { double axisAngle = _axisAngle % 360; if (axisAngle < 0) { axisAngle += 360; } return axisAngle; } /** * Tests this plot for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof SpiderWebPlot)) { return false; } if (!super.equals(obj)) { return false; } SpiderWebPlot that = (SpiderWebPlot) obj; if (!this.dataExtractOrder.equals(that.dataExtractOrder)) { return false; } if (this.headPercent != that.headPercent) { return false; } if (this.interiorGap != that.interiorGap) { return false; } if (this.startAngle != that.startAngle) { return false; } if (!this.direction.equals(that.direction)) { return false; } if (!ObjectUtilities.equal(this.maxValue, that.maxValue)) { return false; } if (!ObjectUtilities.equal(this.maxValues, that.maxValues)) { return false; } if (!ObjectUtilities.equal(this.origins, that.origins)) { return false; } if (this.webFilled != that.webFilled) { return false; } if (this.axisLabelGap != that.axisLabelGap) { return false; } if (!PaintUtilities.equal(this.axisLinePaint, that.axisLinePaint)) { return false; } if (!this.axisLineStroke.equals(that.axisLineStroke)) { return false; } if (!ShapeUtilities.equal(this.legendItemShape, that.legendItemShape)) { return false; } if (!PaintUtilities.equal(this.seriesPaint, that.seriesPaint)) { return false; } if (!this.seriesPaintList.equals(that.seriesPaintList)) { return false; } if (!PaintUtilities.equal(this.baseSeriesPaint, that.baseSeriesPaint)) { return false; } if (!PaintUtilities.equal(this.seriesOutlinePaint, that.seriesOutlinePaint)) { return false; } if (!this.seriesOutlinePaintList.equals(that.seriesOutlinePaintList)) { return false; } if (!PaintUtilities.equal(this.baseSeriesOutlinePaint, that.baseSeriesOutlinePaint)) { return false; } if (!ObjectUtilities.equal(this.seriesOutlineStroke, that.seriesOutlineStroke)) { return false; } if (!this.seriesOutlineStrokeList.equals( that.seriesOutlineStrokeList)) { return false; } if (!this.baseSeriesOutlineStroke.equals( that.baseSeriesOutlineStroke)) { return false; } if (!this.labelFont.equals(that.labelFont)) { return false; } if (!PaintUtilities.equal(this.labelPaint, that.labelPaint)) { return false; } if (!this.labelGenerator.equals(that.labelGenerator)) { return false; } if (!ObjectUtilities.equal(this.toolTipGenerator, that.toolTipGenerator)) { return false; } if (!ObjectUtilities.equal(this.urlGenerator, that.urlGenerator)) { return false; } return true; } /** * Returns a clone of this plot. * * @return A clone of this plot. * * @throws CloneNotSupportedException if the plot cannot be cloned for * any reason. */ public Object clone() throws CloneNotSupportedException { SpiderWebPlot clone = (SpiderWebPlot) super.clone(); clone.legendItemShape = ShapeUtilities.clone(this.legendItemShape); clone.seriesPaintList = (PaintList) this.seriesPaintList.clone(); clone.seriesOutlinePaintList = (PaintList) this.seriesOutlinePaintList.clone(); clone.seriesOutlineStrokeList = (StrokeList) this.seriesOutlineStrokeList.clone(); return clone; } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writeShape(this.legendItemShape, stream); SerialUtilities.writePaint(this.seriesPaint, stream); SerialUtilities.writePaint(this.baseSeriesPaint, stream); SerialUtilities.writePaint(this.seriesOutlinePaint, stream); SerialUtilities.writePaint(this.baseSeriesOutlinePaint, stream); SerialUtilities.writeStroke(this.seriesOutlineStroke, stream); SerialUtilities.writeStroke(this.baseSeriesOutlineStroke, stream); SerialUtilities.writePaint(this.labelPaint, stream); SerialUtilities.writePaint(this.axisLinePaint, stream); SerialUtilities.writeStroke(this.axisLineStroke, stream); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.legendItemShape = SerialUtilities.readShape(stream); this.seriesPaint = SerialUtilities.readPaint(stream); this.baseSeriesPaint = SerialUtilities.readPaint(stream); this.seriesOutlinePaint = SerialUtilities.readPaint(stream); this.baseSeriesOutlinePaint = SerialUtilities.readPaint(stream); this.seriesOutlineStroke = SerialUtilities.readStroke(stream); this.baseSeriesOutlineStroke = SerialUtilities.readStroke(stream); this.labelPaint = SerialUtilities.readPaint(stream); this.axisLinePaint = SerialUtilities.readPaint(stream); this.axisLineStroke = SerialUtilities.readStroke(stream); if (this.dataset != null) { this.dataset.addChangeListener(this); } } }
package org.sagebionetworks.bridge.dynamodb; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static org.sagebionetworks.bridge.BridgeConstants.API_MAXIMUM_PAGE_SIZE; import static org.sagebionetworks.bridge.dynamodb.DynamoExternalIdDao.PAGE_SIZE_ERROR; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.Resource; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper.FailedBatch; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBQueryExpression; import com.amazonaws.services.dynamodbv2.datamodeling.QueryResultPage; import com.amazonaws.services.dynamodbv2.document.Index; import com.amazonaws.services.dynamodbv2.document.ItemCollection; import com.amazonaws.services.dynamodbv2.document.KeyAttribute; import com.amazonaws.services.dynamodbv2.document.QueryOutcome; import com.amazonaws.services.dynamodbv2.document.RangeKeyCondition; import com.amazonaws.services.dynamodbv2.document.spec.QuerySpec; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.ComparisonOperator; import com.amazonaws.services.dynamodbv2.model.Condition; import com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException; import com.amazonaws.services.dynamodbv2.model.ReturnConsumedCapacity; import org.apache.commons.lang3.StringUtils; import org.joda.time.DateTime; import org.joda.time.LocalDate; import org.springframework.stereotype.Component; import org.sagebionetworks.bridge.BridgeConstants; import org.sagebionetworks.bridge.BridgeUtils; import org.sagebionetworks.bridge.dao.UploadDao; import org.sagebionetworks.bridge.exceptions.BadRequestException; import org.sagebionetworks.bridge.exceptions.BridgeServiceException; import org.sagebionetworks.bridge.exceptions.ConcurrentModificationException; import org.sagebionetworks.bridge.exceptions.NotFoundException; import org.sagebionetworks.bridge.json.BridgeObjectMapper; import org.sagebionetworks.bridge.json.DateUtils; import org.sagebionetworks.bridge.models.ForwardCursorPagedResourceList; import org.sagebionetworks.bridge.models.studies.StudyIdentifier; import org.sagebionetworks.bridge.models.upload.Upload; import org.sagebionetworks.bridge.models.upload.UploadCompletionClient; import org.sagebionetworks.bridge.models.upload.UploadRequest; import org.sagebionetworks.bridge.models.upload.UploadStatus; @Component public class DynamoUploadDao implements UploadDao { private DynamoDBMapper mapper; private DynamoIndexHelper healthCodeRequestedOnIndex; private static final String UPLOAD_ID = "uploadId"; private static final String STUDY_ID = "studyId"; private static final String REQUESTED_ON = "requestedOn"; private static final String HEALTH_CODE = "healthCode"; private static final String STUDY_ID_REQUESTED_ON_INDEX = "studyId-requestedOn-index"; /** * This is the DynamoDB mapper that reads from and writes to our DynamoDB table. This is normally configured by * Spring. */ @Resource(name = "uploadDdbMapper") final void setDdbMapper(DynamoDBMapper mapper) { this.mapper = mapper; } /** * DynamoDB Index reference for the healthCode-requestedOn index. */ @Resource(name = "uploadHealthCodeRequestedOnIndex") final void setHealthCodeRequestedOnIndex(DynamoIndexHelper healthCodeRequestedOnIndex) { this.healthCodeRequestedOnIndex = healthCodeRequestedOnIndex; } /** {@inheritDoc} */ @Override public Upload createUpload(@Nonnull UploadRequest uploadRequest, @Nonnull StudyIdentifier studyId, @Nonnull String healthCode, @Nullable String originalUploadId) { checkNotNull(uploadRequest, "Upload request is null"); checkNotNull(studyId, "Study identifier is null"); checkArgument(StringUtils.isNotBlank(healthCode), "Health code is null or blank"); // Always write new uploads to the new upload table. DynamoUpload2 upload = new DynamoUpload2(uploadRequest, healthCode); upload.setStudyId(studyId.getIdentifier()); upload.setRequestedOn(DateUtils.getCurrentMillisFromEpoch()); if (originalUploadId != null) { // This is a dupe. Tag it as such. upload.setDuplicateUploadId(originalUploadId); upload.setStatus(UploadStatus.DUPLICATE); } mapper.save(upload); return upload; } // TODO: Cache this, or make it so that calling getUpload() and uploadComplete() in sequence don't cause duplicate // calls to DynamoDB. /** {@inheritDoc} */ @Override public Upload getUpload(@Nonnull String uploadId) { // Fetch upload from DynamoUpload2 DynamoUpload2 key = new DynamoUpload2(); key.setUploadId(uploadId); DynamoUpload2 upload = mapper.load(key); if (upload != null) { return upload; } throw new NotFoundException(String.format("Upload ID %s not found", uploadId)); } /** {@inheritDoc} */ @Override public ForwardCursorPagedResourceList<Upload> getUploads(String healthCode, DateTime startTime, DateTime endTime, int pageSize, String offsetKey) { // Set a sane upper limit on this. if (pageSize < 1 || pageSize > API_MAXIMUM_PAGE_SIZE) { throw new BadRequestException(PAGE_SIZE_ERROR); } RangeKeyCondition condition = new RangeKeyCondition(REQUESTED_ON).between( startTime.getMillis(), endTime.getMillis()); Index index = healthCodeRequestedOnIndex.getIndex(); List<Upload> results = new ArrayList<>(pageSize); QuerySpec spec = new QuerySpec() .withHashKey(HEALTH_CODE, healthCode) .withMaxPageSize(pageSize) .withReturnConsumedCapacity(ReturnConsumedCapacity.TOTAL) .withRangeKeyCondition(condition); // this is not a filter, it should not require paging on our side. if (offsetKey != null) { spec.withExclusiveStartKey(new KeyAttribute(UPLOAD_ID, offsetKey)); } ItemCollection<QueryOutcome> query = index.query(spec); query.forEach((item) -> { DynamoUpload2 oneRecord = BridgeObjectMapper.get().convertValue(item.asMap(), DynamoUpload2.class); results.add(oneRecord); }); Map<String,AttributeValue> key = query.getLastLowLevelResult().getQueryResult().getLastEvaluatedKey(); String nextOffsetKey = (key != null) ? key.get(UPLOAD_ID).getS() : null; return new ForwardCursorPagedResourceList<>(results, nextOffsetKey, pageSize) .withFilter("startTime", startTime.toString()) .withFilter("endTime", endTime.toString()); } /** {@inheritDoc} */ @Override public ForwardCursorPagedResourceList<Upload> getStudyUploads(StudyIdentifier studyId, DateTime startTime, DateTime endTime, int pageSize, String offsetKey) { checkNotNull(studyId); // Just set a sane upper limit on this. if (pageSize < 1 || pageSize > API_MAXIMUM_PAGE_SIZE) { throw new BadRequestException(PAGE_SIZE_ERROR); } // only query one page each time client calling this method QueryResultPage<DynamoUpload2> page = mapper.queryPage(DynamoUpload2.class, createGetQuery(studyId, startTime, endTime, offsetKey, pageSize)); Map<String, List<Object>> resultMap = mapper.batchLoad(page.getResults()); List<Upload> uploadList = new ArrayList<>(); for (List<Object> resultList : resultMap.values()) { for (Object oneResult : resultList) { if (!DynamoUpload2.class.isInstance(oneResult)) { // This should never happen, but just in case. throw new BridgeServiceException(String.format( "DynamoDB returned objects of type %s instead of %s", oneResult.getClass().getName(), DynamoUpload2.class.getName())); } uploadList.add((DynamoUpload2) oneResult); } } String nextPageOffsetKey = (page.getLastEvaluatedKey() != null) ? page.getLastEvaluatedKey().get(UPLOAD_ID).getS() : null; return new ForwardCursorPagedResourceList<>(uploadList, nextPageOffsetKey, pageSize) .withFilter("startDate", startTime.toString()) .withFilter("endDate", endTime.toString()); } private DynamoDBQueryExpression<DynamoUpload2> createGetQuery(StudyIdentifier studyId, DateTime startTime, DateTime endTime, String offsetKey, int pageSize) { DynamoDBQueryExpression<DynamoUpload2> query = createCountQuery(studyId.getIdentifier(), startTime, endTime); if (offsetKey != null) { // load table again to get the one last evaluated upload DynamoUpload2 retLastEvaluatedUpload = mapper.load(DynamoUpload2.class, offsetKey); Map<String,AttributeValue> map = new HashMap<>(); map.put(UPLOAD_ID, new AttributeValue().withS(offsetKey)); map.put(REQUESTED_ON, new AttributeValue().withN(String.valueOf(retLastEvaluatedUpload.getRequestedOn()))); map.put(STUDY_ID, new AttributeValue().withS(studyId.getIdentifier())); query.withExclusiveStartKey(map); } query.withLimit(pageSize); return query; } /** * Create a query for records applying the filter values if they exist. */ private DynamoDBQueryExpression<DynamoUpload2> createCountQuery(String studyId, DateTime startTime, DateTime endTime) { Condition rangeKeyCondition = new Condition() .withComparisonOperator(ComparisonOperator.BETWEEN.toString()) .withAttributeValueList(new AttributeValue().withN(String.valueOf(startTime.getMillis())), new AttributeValue().withN(String.valueOf(endTime.getMillis()))); DynamoUpload2 upload = new DynamoUpload2(); upload.setStudyId(studyId); DynamoDBQueryExpression<DynamoUpload2> query = new DynamoDBQueryExpression<>(); query.withIndexName(STUDY_ID_REQUESTED_ON_INDEX); query.withHashKeyValues(upload); query.withConsistentRead(false); query.setScanIndexForward(false); query.withRangeKeyCondition(REQUESTED_ON, rangeKeyCondition); return query; } /** {@inheritDoc} */ @Override public void uploadComplete(@Nonnull UploadCompletionClient completedBy, @Nonnull Upload upload) { DynamoUpload2 upload2 = (DynamoUpload2) upload; upload2.setStatus(UploadStatus.VALIDATION_IN_PROGRESS); // TODO: If we globalize Bridge, we'll need to make this timezone configurable. upload2.setUploadDate(LocalDate.now(BridgeConstants.LOCAL_TIME_ZONE)); upload2.setCompletedOn(DateUtils.getCurrentMillisFromEpoch()); upload2.setCompletedBy(completedBy); try { mapper.save(upload2); } catch (ConditionalCheckFailedException ex) { throw new ConcurrentModificationException("Upload " + upload.getUploadId() + " is already complete"); } } /** * Writes validation status and appends messages to Dynamo DB. Only DynamoUpload2 objects can have status and * validation. DynamoUpload objects will be ignored. * * @see org.sagebionetworks.bridge.dao.UploadDao#writeValidationStatus */ @Override public void writeValidationStatus(@Nonnull Upload upload, @Nonnull UploadStatus status, @Nonnull List<String> validationMessageList, String recordId) { // set status and append messages DynamoUpload2 upload2 = (DynamoUpload2) upload; upload2.setStatus(status); upload2.appendValidationMessages(validationMessageList); upload2.setRecordId(recordId); // persist mapper.save(upload2); } @Override public void deleteUploadsForHealthCode(@Nonnull String healthCode) { List<? extends Upload> uploadsToDelete = healthCodeRequestedOnIndex.queryKeys( DynamoUpload2.class, HEALTH_CODE, healthCode, null); if (!uploadsToDelete.isEmpty()) { List<FailedBatch> failures = mapper.batchDelete(uploadsToDelete); BridgeUtils.ifFailuresThrowException(failures); } } }
package net.java.sip.communicator.impl.gui.main.chat; import java.awt.*; import java.awt.Container; import java.awt.event.*; import java.beans.*; import java.io.*; import java.util.*; import java.util.List; import javax.swing.*; import javax.swing.event.*; import javax.swing.text.*; import net.java.sip.communicator.impl.gui.*; import net.java.sip.communicator.impl.gui.main.chat.conference.*; import net.java.sip.communicator.impl.gui.main.chat.filetransfer.*; import net.java.sip.communicator.impl.gui.utils.*; import net.java.sip.communicator.plugin.desktoputil.*; import net.java.sip.communicator.service.contactlist.*; import net.java.sip.communicator.service.filehistory.*; import net.java.sip.communicator.service.gui.*; import net.java.sip.communicator.service.gui.event.*; import net.java.sip.communicator.service.metahistory.*; import net.java.sip.communicator.service.protocol.*; import net.java.sip.communicator.service.protocol.event.*; import net.java.sip.communicator.util.*; import net.java.sip.communicator.util.Logger; import net.java.sip.communicator.util.skin.*; import net.java.sip.communicator.plugin.desktoputil.SwingWorker; import org.jitsi.util.*; /** * The <tt>ChatPanel</tt> is the panel, where users can write and send messages, * view received messages. A ChatPanel is created for a contact or for a group * of contacts in case of a chat conference. There is always one default contact * for the chat, which is the first contact which was added to the chat. * When chat is in mode "open all messages in new window", each ChatPanel * corresponds to a ChatWindow. When chat is in mode "group all messages in * one chat window", each ChatPanel corresponds to a tab in the ChatWindow. * * @author Yana Stamcheva * @author Lyubomir Marinov * @author Adam Netocny */ @SuppressWarnings("serial") public class ChatPanel extends TransparentPanel implements ChatSessionRenderer, Chat, ChatConversationContainer, ChatRoomMemberRoleListener, ChatRoomLocalUserRoleListener, ChatRoomMemberPropertyChangeListener, FileTransferStatusListener, Skinnable { /** * The <tt>Logger</tt> used by the <tt>CallPanel</tt> class and its * instances for logging output. */ private static final Logger logger = Logger.getLogger(ChatPanel.class); private final JSplitPane messagePane = new JSplitPane(JSplitPane.VERTICAL_SPLIT); private JSplitPane topSplitPane; private final JPanel topPanel = new JPanel(new BorderLayout()); private final ChatConversationPanel conversationPanel; /** * Will contain the typing panel on south and centered the * conversation panel. */ private final JPanel conversationPanelContainer = new JPanel(new BorderLayout()); private final ChatWritePanel writeMessagePanel; private ChatRoomMemberListPanel chatContactListPanel; private final ChatContainer chatContainer; private ChatRoomSubjectPanel subjectPanel; public int unreadMessageNumber = 0; /** * The label showing current typing notification. */ private JLabel typingNotificationLabel; /** * The typing notification icon. */ private final Icon typingIcon = GuiActivator.getResources() .getImage("service.gui.icons.TYPING"); /** * Indicates that a typing notification event is successfully sent. */ public static final int TYPING_NOTIFICATION_SUCCESSFULLY_SENT = 1; /** * Indicates that sending a typing notification event has failed. */ public static final int TYPING_NOTIFICATION_SEND_FAILED = 0; /** * The number of messages shown per page. */ protected static final int MESSAGES_PER_PAGE = 20; private boolean isShown = false; public ChatSession chatSession; private Date firstHistoryMsgTimestamp = new Date(0); private Date lastHistoryMsgTimestamp = new Date(0); private final List<ChatFocusListener> focusListeners = new Vector<ChatFocusListener>(); private final List<ChatHistoryListener> historyListeners = new Vector<ChatHistoryListener>(); private final Vector<Object> incomingEventBuffer = new Vector<Object>(); private boolean isHistoryLoaded; /** * Stores all active file transfer requests and effective transfers with * the identifier of the transfer. */ private final Hashtable<String, Object> activeFileTransfers = new Hashtable<String, Object>(); /** * The ID of the message being corrected, or <tt>null</tt> if * not correcting any message. */ private String correctedMessageUID = null; /** * The ID of the last sent message in this chat. */ private String lastSentMessageUID = null; /** * Creates a <tt>ChatPanel</tt> which is added to the given chat window. * * @param chatContainer The parent window of this chat panel. */ public ChatPanel(ChatContainer chatContainer) { super(new BorderLayout()); this.chatContainer = chatContainer; this.conversationPanel = new ChatConversationPanel(this); this.conversationPanel.setPreferredSize(new Dimension(400, 200)); this.conversationPanel.getChatTextPane() .setTransferHandler(new ChatTransferHandler(this)); this.conversationPanelContainer.add( conversationPanel, BorderLayout.CENTER); this.conversationPanelContainer.setBackground(Color.WHITE); initTypingNotificationLabel(conversationPanelContainer); topPanel.setBackground(Color.WHITE); topPanel.setBorder( BorderFactory.createMatteBorder(1, 0, 1, 0, Color.GRAY)); this.writeMessagePanel = new ChatWritePanel(this); this.messagePane.setBorder(null); this.messagePane.setOpaque(false); this.messagePane.addPropertyChangeListener( new DividerLocationListener()); this.messagePane.setDividerSize(3); this.messagePane.setResizeWeight(1.0D); this.messagePane.setBottomComponent(writeMessagePanel); this.messagePane.setTopComponent(topPanel); this.add(messagePane, BorderLayout.CENTER); if (OSUtils.IS_MAC) { setOpaque(true); setBackground( new Color(GuiActivator.getResources() .getColor("service.gui.MAC_PANEL_BACKGROUND"))); } this.addComponentListener(new TabSelectionComponentListener()); } /** * Sets the chat session to associate to this chat panel. * @param chatSession the chat session to associate to this chat panel */ public void setChatSession(ChatSession chatSession) { this.chatSession = chatSession; if ((this.chatSession != null) && this.chatSession.isContactListSupported()) { topPanel.remove(conversationPanelContainer); TransparentPanel rightPanel = new TransparentPanel(new BorderLayout(5, 5)); Dimension chatContactPanelSize = new Dimension(150, 100); rightPanel.setMinimumSize(chatContactPanelSize); rightPanel.setPreferredSize(chatContactPanelSize); this.chatContactListPanel = new ChatRoomMemberListPanel(this); this.chatContactListPanel.setOpaque(false); topSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); topSplitPane.setBorder(null); // remove default borders topSplitPane.setOneTouchExpandable(true); topSplitPane.setOpaque(false); topSplitPane.setResizeWeight(1.0D); ChatTransport chatTransport = chatSession.getCurrentChatTransport(); JLabel localUserLabel = new JLabel( chatTransport.getProtocolProvider() .getAccountID().getDisplayName()); localUserLabel.setFont( localUserLabel.getFont().deriveFont(Font.BOLD)); rightPanel.add(localUserLabel, BorderLayout.NORTH); rightPanel.add(chatContactListPanel, BorderLayout.CENTER); topSplitPane.setLeftComponent(conversationPanelContainer); topSplitPane.setRightComponent(rightPanel); topPanel.add(topSplitPane); } else { if (topSplitPane != null) { if (chatContactListPanel != null) { topSplitPane.remove(chatContactListPanel); chatContactListPanel = null; } this.messagePane.remove(topSplitPane); topSplitPane = null; } topPanel.add(conversationPanelContainer); } if (chatSession instanceof MetaContactChatSession) { // The subject panel is added here, because it's specific for the // multi user chat and is not contained in the single chat chat panel. if (subjectPanel != null) { this.remove(subjectPanel); subjectPanel = null; this.revalidate(); this.repaint(); } writeMessagePanel.setTransportSelectorBoxVisible(true); //Enables to change the protocol provider by simply pressing the // CTRL-P key combination ActionMap amap = this.getActionMap(); amap.put("ChangeProtocol", new ChangeTransportAction()); InputMap imap = this.getInputMap( JComponent.WHEN_IN_FOCUSED_WINDOW); imap.put(KeyStroke.getKeyStroke(KeyEvent.VK_P, KeyEvent.CTRL_DOWN_MASK), "ChangeProtocol"); } else if (chatSession instanceof ConferenceChatSession) { ConferenceChatSession confSession = (ConferenceChatSession) chatSession; writeMessagePanel.setTransportSelectorBoxVisible(false); confSession.addLocalUserRoleListener(this); confSession.addMemberRoleListener(this); ((ChatRoomWrapper) chatSession.getDescriptor()) .getChatRoom().addMemberPropertyChangeListener(this); subjectPanel = new ChatRoomSubjectPanel((ConferenceChatSession) chatSession); // The subject panel is added here, because it's specific for the // multi user chat and is not contained in the single chat chat panel. this.add(subjectPanel, BorderLayout.NORTH); } if (chatContactListPanel != null) { // Initialize chat participants' panel. Iterator<ChatContact<?>> chatParticipants = chatSession.getParticipants(); while (chatParticipants.hasNext()) chatContactListPanel.addContact(chatParticipants.next()); } } /** * Returns the chat session associated with this chat panel. * @return the chat session associated with this chat panel */ public ChatSession getChatSession() { return chatSession; } /** * Runs clean-up for associated resources which need explicit disposal (e.g. * listeners keeping this instance alive because they were added to the * model which operationally outlives this instance). */ public void dispose() { writeMessagePanel.dispose(); chatSession.dispose(); conversationPanel.dispose(); } /** * Returns the chat window, where this chat panel is added. * * @return the chat window, where this chat panel is added */ public ChatContainer getChatContainer() { return chatContainer; } /** * Returns the chat window, where this chat panel * is located. Implements the * <tt>ChatConversationContainer.getConversationContainerWindow()</tt> * method. * * @return ChatWindow The chat window, where this * chat panel is located. */ public Window getConversationContainerWindow() { return chatContainer.getFrame(); } /** * Adds a typing notification message to the conversation panel. * * @param typingNotification the typing notification to show */ public void addTypingNotification(final String typingNotification) { if(!SwingUtilities.isEventDispatchThread()) { SwingUtilities.invokeLater(new Runnable() { public void run() { addTypingNotification(typingNotification); } }); return; } typingNotificationLabel.setText(typingNotification); if (typingNotification != null && !typingNotification.equals(" ")) typingNotificationLabel.setIcon(typingIcon); else typingNotificationLabel.setIcon(null); revalidate(); repaint(); } /** * Adds a typing notification message to the conversation panel, * saying that typin notifications has not been delivered. * * @param typingNotification the typing notification to show */ public void addErrorSendingTypingNotification( final String typingNotification) { if(!SwingUtilities.isEventDispatchThread()) { SwingUtilities.invokeLater(new Runnable() { public void run() { addErrorSendingTypingNotification(typingNotification); } }); return; } typingNotificationLabel.setText(typingNotification); if (typingNotification != null && !typingNotification.equals(" ")) typingNotificationLabel.setIcon(typingIcon); else typingNotificationLabel.setIcon(null); revalidate(); repaint(); } /** * Removes the typing notification message from the conversation panel. */ public void removeTypingNotification() { addTypingNotification(" "); } /** * Initializes the typing notification label. * @param typingLabelParent the parent container * of typing notification label. */ private void initTypingNotificationLabel(JPanel typingLabelParent) { typingNotificationLabel = new JLabel(" ", SwingConstants.CENTER); typingNotificationLabel.setPreferredSize(new Dimension(500, 20)); typingNotificationLabel.setForeground(Color.GRAY); typingNotificationLabel.setFont( typingNotificationLabel.getFont().deriveFont(11f)); typingNotificationLabel.setVerticalTextPosition(JLabel.BOTTOM); typingNotificationLabel.setHorizontalTextPosition(JLabel.LEFT); typingNotificationLabel.setIconTextGap(0); typingLabelParent.add(typingNotificationLabel, BorderLayout.SOUTH); } /** * Returns the conversation panel, contained in this chat panel. * * @return the conversation panel, contained in this chat panel */ public ChatConversationPanel getChatConversationPanel() { return this.conversationPanel; } /** * Returns the write area panel, contained in this chat panel. * * @return the write area panel, contained in this chat panel */ public ChatWritePanel getChatWritePanel() { return this.writeMessagePanel; } /** * Returns the corresponding role description to the given role index. * * @param role to role index to analyse * @return String the corresponding role description */ public String getRoleDescription(ChatRoomMemberRole role) { String roleDescription = null; switch(role) { case OWNER: roleDescription = GuiActivator.getResources().getI18NString( "service.gui.OWNER"); break; case ADMINISTRATOR: roleDescription = GuiActivator.getResources().getI18NString( "service.gui.ADMINISTRATOR"); break; case MODERATOR: roleDescription = GuiActivator.getResources().getI18NString( "service.gui.MODERATOR"); break; case MEMBER: roleDescription = GuiActivator.getResources().getI18NString( "service.gui.MEMBER"); break; case GUEST: roleDescription = GuiActivator.getResources().getI18NString( "service.gui.GUEST"); break; case SILENT_MEMBER: roleDescription = GuiActivator.getResources().getI18NString( "service.gui.SILENT_MEMBER"); break; default:; } return roleDescription; } /** * Implements the <tt>memberRoleChanged()</tt> method. * * @param evt */ public void memberRoleChanged(ChatRoomMemberRoleChangeEvent evt) { this.conversationPanel.appendMessageToEnd( "<DIV identifier=\"message\" style=\"color:#707070;\">" + GuiActivator.getResources().getI18NString("service.gui.IS_NOW", new String[]{evt.getSourceMember().getName(), getRoleDescription(evt.getNewRole())}) +"</DIV>", ChatHtmlUtils.HTML_CONTENT_TYPE); } /** * Implements the <tt>localUserRoleChanged()</tt> method. * * @param evt */ public void localUserRoleChanged(ChatRoomLocalUserRoleChangeEvent evt) { this.conversationPanel.appendMessageToEnd( "<DIV identifier=\"message\" style=\"color:#707070;\">" +GuiActivator.getResources().getI18NString("service.gui.ARE_NOW", new String[]{ getRoleDescription(evt.getNewRole())}) +"</DIV>", ChatHtmlUtils.HTML_CONTENT_TYPE); } /** * Returns the ID of the last message sent in this chat, or <tt>null</tt> * if no messages have been sent yet. * * @return the ID of the last message sent in this chat, or <tt>null</tt> * if no messages have been sent yet. */ public String getLastSentMessageUID() { return lastSentMessageUID; } /** * Every time the chat panel is shown we set it as a current chat panel. * This is done here and not in the Tab selection listener, because the tab * change event is not fired when the user clicks on the close tab button * for example. */ private class TabSelectionComponentListener extends ComponentAdapter { @Override public void componentShown(ComponentEvent evt) { Component component = evt.getComponent(); Container parent = component.getParent(); if (!(parent instanceof JTabbedPane)) return; JTabbedPane tabbedPane = (JTabbedPane) parent; if (tabbedPane.getSelectedComponent() != component) return; chatContainer.setCurrentChat(ChatPanel.this); } } /** * Requests the focus in the write message area. */ public void requestFocusInWriteArea() { getChatWritePanel().getEditorPane().requestFocus(); } /** * Checks if the editor contains text. * * @return TRUE if editor contains text, FALSE otherwise. */ public boolean isWriteAreaEmpty() { JEditorPane editorPane = getChatWritePanel().getEditorPane(); Document doc = editorPane.getDocument(); try { String text = doc.getText(0, doc.getLength()); if (text == null || text.equals("")) return true; } catch (BadLocationException e) { logger.error("Failed to obtain document text.", e); } return false; } /** * Process history messages. * * @param historyList The collection of messages coming from history. * @param escapedMessageID The incoming message needed to be ignored if * contained in history. */ private void processHistory( Collection<Object> historyList, String escapedMessageID) { Iterator<Object> iterator = historyList.iterator(); String messageType; while (iterator.hasNext()) { Object o = iterator.next(); String historyString = ""; if(o instanceof MessageDeliveredEvent) { MessageDeliveredEvent evt = (MessageDeliveredEvent)o; ProtocolProviderService protocolProvider = evt .getDestinationContact().getProtocolProvider(); if (isGreyHistoryStyleDisabled(protocolProvider)) messageType = Chat.OUTGOING_MESSAGE; else messageType = Chat.HISTORY_OUTGOING_MESSAGE; historyString = processHistoryMessage( GuiActivator.getUIService().getMainFrame() .getAccountAddress(protocolProvider), GuiActivator.getUIService().getMainFrame() .getAccountDisplayName(protocolProvider), evt.getTimestamp(), messageType, evt.getSourceMessage().getContent(), evt.getSourceMessage().getContentType(), evt.getSourceMessage().getMessageUID()); } else if(o instanceof MessageReceivedEvent) { MessageReceivedEvent evt = (MessageReceivedEvent)o; ProtocolProviderService protocolProvider = evt.getSourceContact().getProtocolProvider(); if(!evt.getSourceMessage().getMessageUID() .equals(escapedMessageID)) { if (isGreyHistoryStyleDisabled(protocolProvider)) messageType = Chat.INCOMING_MESSAGE; else messageType = Chat.HISTORY_INCOMING_MESSAGE; historyString = processHistoryMessage( evt.getSourceContact().getAddress(), evt.getSourceContact().getDisplayName(), evt.getTimestamp(), messageType, evt.getSourceMessage().getContent(), evt.getSourceMessage().getContentType(), evt.getSourceMessage().getMessageUID()); } } else if(o instanceof ChatRoomMessageDeliveredEvent) { ChatRoomMessageDeliveredEvent evt = (ChatRoomMessageDeliveredEvent)o; ProtocolProviderService protocolProvider = evt .getSourceChatRoom().getParentProvider(); historyString = processHistoryMessage( GuiActivator.getUIService().getMainFrame() .getAccountAddress(protocolProvider), GuiActivator.getUIService().getMainFrame() .getAccountDisplayName(protocolProvider), evt.getTimestamp(), Chat.HISTORY_OUTGOING_MESSAGE, evt.getMessage().getContent(), evt.getMessage().getContentType()); } else if(o instanceof ChatRoomMessageReceivedEvent) { ChatRoomMessageReceivedEvent evt = (ChatRoomMessageReceivedEvent) o; if(!evt.getMessage().getMessageUID() .equals(escapedMessageID)) { historyString = processHistoryMessage( evt.getSourceChatRoomMember().getContactAddress(), evt.getSourceChatRoomMember().getName(), evt.getTimestamp(), Chat.HISTORY_INCOMING_MESSAGE, evt.getMessage().getContent(), evt.getMessage().getContentType()); } } else if (o instanceof FileRecord) { FileRecord fileRecord = (FileRecord) o; if (!fileRecord.getID().equals(escapedMessageID)) { FileHistoryConversationComponent component = new FileHistoryConversationComponent(fileRecord); conversationPanel.addComponent(component); } } if (historyString != null) conversationPanel.appendMessageToEnd( historyString, ChatHtmlUtils.TEXT_CONTENT_TYPE); } fireChatHistoryChange(); } /** * Passes the message to the contained <code>ChatConversationPanel</code> * for processing and appends it at the end of the conversationPanel * document. * * @param contactName the name of the contact sending the message * @param date the time at which the message is sent or received * @param messageType the type of the message. One of OUTGOING_MESSAGE * or INCOMING_MESSAGE * @param message the message text * @param contentType the content type */ public void addMessage(String contactName, Date date, String messageType, String message, String contentType) { addMessage(contactName, null, date, messageType, message, contentType, null, null); } /** * Passes the message to the contained <code>ChatConversationPanel</code> * for processing and appends it at the end of the conversationPanel * document. * * @param contactName the name of the contact sending the message * @param displayName the display name of the contact * @param date the time at which the message is sent or received * @param messageType the type of the message. One of OUTGOING_MESSAGE * or INCOMING_MESSAGE * @param message the message text * @param contentType the content type */ public void addMessage(String contactName, String displayName, Date date, String messageType, String message, String contentType, String messageUID, String correctedMessageUID) { ChatMessage chatMessage = new ChatMessage(contactName, displayName, date, messageType, null, message, contentType, messageUID, correctedMessageUID); this.addChatMessage(chatMessage); // A bug Fix for Previous/Next buttons . // Must update buttons state after message is processed // otherwise states are not proper fireChatHistoryChange(); } /** * Passes the message to the contained <code>ChatConversationPanel</code> * for processing and appends it at the end of the conversationPanel * document. * * @param contactName the name of the contact sending the message * @param date the time at which the message is sent or received * @param messageType the type of the message. One of OUTGOING_MESSAGE * or INCOMING_MESSAGE * @param title the title of the message * @param message the message text * @param contentType the content type */ public void addMessage(String contactName, Date date, String messageType, String title, String message, String contentType) { ChatMessage chatMessage = new ChatMessage(contactName, date, messageType, title, message, contentType); this.addChatMessage(chatMessage); } /** * Passes the message to the contained <code>ChatConversationPanel</code> * for processing and appends it at the end of the conversationPanel * document. * * @param chatMessage the chat message to add */ private void addChatMessage(final ChatMessage chatMessage) { // We need to be sure that chat messages are added in the event dispatch // thread. if (!SwingUtilities.isEventDispatchThread()) { SwingUtilities.invokeLater(new Runnable() { public void run() { addChatMessage(chatMessage); } }); return; } if (ConfigurationUtils.isHistoryShown() && !isHistoryLoaded) { synchronized (incomingEventBuffer) { incomingEventBuffer.add(chatMessage); } } else { displayChatMessage(chatMessage); } // change the last history message timestamp after we add one. this.lastHistoryMsgTimestamp = chatMessage.getDate(); if (chatMessage.getMessageType().equals(Chat.OUTGOING_MESSAGE)) { this.lastSentMessageUID = chatMessage.getMessageUID(); } } /** * Adds the given error message to the chat window conversation area. * * @param contactName the name of the contact, for which the error occured * @param message the error message */ public void addErrorMessage(String contactName, String message) { this.addMessage(contactName, new Date(), Chat.ERROR_MESSAGE, GuiActivator.getResources() .getI18NString("service.gui.MSG_DELIVERY_FAILURE"), message, "text"); } /** * Adds the given error message to the chat window conversation area. * * @param contactName the name of the contact, for which the error occurred * @param title the title of the error * @param message the error message */ public void addErrorMessage(String contactName, String title, String message) { this.addMessage(contactName, new Date(), Chat.ERROR_MESSAGE, title, message, "text"); } /** * Displays the given chat message. * * @param chatMessage the chat message to display */ private void displayChatMessage(ChatMessage chatMessage) { if (chatMessage.getCorrectedMessageUID() != null && conversationPanel.getMessageContents( chatMessage.getCorrectedMessageUID()) != null) { applyMessageCorrection(chatMessage); } else { appendChatMessage(chatMessage); } } /** * Passes the message to the contained <code>ChatConversationPanel</code> * for processing and appends it at the end of the conversationPanel * document. * * @param chatMessage the message to append */ private void appendChatMessage(ChatMessage chatMessage) { String processedMessage = this.conversationPanel.processMessage(chatMessage, chatSession.getCurrentChatTransport().getProtocolProvider(), chatSession.getCurrentChatTransport().getName()); if (chatSession instanceof ConferenceChatSession) { if (chatMessage.getMessageType().equals(Chat.INCOMING_MESSAGE)) { String keyWord = ((ChatRoomWrapper) chatSession.getDescriptor()) .getChatRoom().getUserNickname(); try { processedMessage = this.conversationPanel .processChatRoomHighlight(processedMessage, chatMessage.getContentType(), keyWord); } catch(Throwable t) { logger.error("Error processing highlight", t); } } String meCommandMsg = this.conversationPanel.processMeCommand(chatMessage); if (meCommandMsg.length() > 0) processedMessage = meCommandMsg; } this.conversationPanel.appendMessageToEnd( processedMessage, chatMessage.getContentType()); } /** * Passes the message to the contained <code>ChatConversationPanel</code> * for processing and replaces the specified message with this one. * * @param message The message used as a correction. */ private void applyMessageCorrection(ChatMessage message) { conversationPanel.correctMessage(message); } /** * Passes the message to the contained <code>ChatConversationPanel</code> * for processing. * * @param contactName The name of the contact sending the message. * @param contactDisplayName the display name of the contact sending the * message * @param date The time at which the message is sent or received. * @param messageType The type of the message. One of OUTGOING_MESSAGE * or INCOMING_MESSAGE. * @param message The message text. * @param contentType the content type of the message (html or plain text) * * @return a string containing the processed message. */ private String processHistoryMessage(String contactName, String contactDisplayName, Date date, String messageType, String message, String contentType) { return processHistoryMessage(contactName, contactDisplayName, date, messageType, message, contentType, null); } /** * Passes the message to the contained <code>ChatConversationPanel</code> * for processing. * * @param contactName The name of the contact sending the message. * @param contactDisplayName the display name of the contact sending the * message * @param date The time at which the message is sent or received. * @param messageType The type of the message. One of OUTGOING_MESSAGE * or INCOMING_MESSAGE. * @param message The message text. * @param contentType the content type of the message (html or plain text) * @param messageId The ID of the message. * * @return a string containing the processed message. */ private String processHistoryMessage(String contactName, String contactDisplayName, Date date, String messageType, String message, String contentType, String messageId) { ChatMessage chatMessage = new ChatMessage( contactName, contactDisplayName, date, messageType, null, message, contentType, messageId, null); String processedMessage = this.conversationPanel.processMessage(chatMessage, chatSession.getCurrentChatTransport().getProtocolProvider(), chatSession.getCurrentChatTransport().getName()); if (chatSession instanceof ConferenceChatSession) { String tempMessage = conversationPanel.processMeCommand(chatMessage); if (tempMessage.length() > 0) processedMessage = tempMessage; } return processedMessage; } /** * Refreshes write area editor pane. Deletes all existing text * content. */ public void refreshWriteArea() { if(!SwingUtilities.isEventDispatchThread()) { SwingUtilities.invokeLater(new Runnable() { public void run() { refreshWriteArea(); } }); return; } this.writeMessagePanel.clearWriteArea(); } /** * Adds text to the write area editor. * * @param text The text to add. */ public void addTextInWriteArea(String text){ JEditorPane editorPane = this.writeMessagePanel.getEditorPane(); editorPane.setText(editorPane.getText() + text); } /** * Returns the text contained in the write area editor. * @param mimeType the mime type * @return The text contained in the write area editor. */ public String getTextFromWriteArea(String mimeType) { if (mimeType.equals( OperationSetBasicInstantMessaging.DEFAULT_MIME_TYPE)) { return writeMessagePanel.getText(); } else { return writeMessagePanel.getTextAsHtml(); } } /** * Cuts the write area selected content to the clipboard. */ public void cut() { this.writeMessagePanel.getEditorPane().cut(); } /** * Copies either the selected write area content or the selected * conversation panel content to the clipboard. */ public void copy() { JTextComponent textPane = this.conversationPanel.getChatTextPane(); if (textPane.getSelectedText() == null) textPane = this.writeMessagePanel.getEditorPane(); textPane.copy(); } /** * Copies the selected write panel content to the clipboard. */ public void copyWriteArea(){ JEditorPane editorPane = this.writeMessagePanel.getEditorPane(); editorPane.copy(); } /** * Pastes the content of the clipboard to the write area. */ public void paste() { JEditorPane editorPane = this.writeMessagePanel.getEditorPane(); editorPane.paste(); editorPane.requestFocus(); } /** * Sends current write area content. */ public void sendButtonDoClick() { if (!isWriteAreaEmpty()) { new Thread() { @Override public void run() { sendMessage(); } }.start(); } //make sure the focus goes back to the write area requestFocusInWriteArea(); } /** * Returns TRUE if this chat panel is added to a container (window or * tabbed pane), which is shown on the screen, FALSE - otherwise. * * @return TRUE if this chat panel is added to a container (window or * tabbed pane), which is shown on the screen, FALSE - otherwise */ public boolean isShown() { return isShown; } /** * Marks this chat panel as shown or hidden. * * @param isShown TRUE to mark this chat panel as shown, FALSE - otherwise */ public void setShown(boolean isShown) { this.isShown = isShown; } /** * Brings the <tt>ChatWindow</tt> containing this <tt>ChatPanel</tt> to the * front if <tt>isVisble</tt> is <tt>true</tt>; hides it, otherwise. * * @param isVisible <tt>true</tt> to bring the <tt>ChatWindow</tt> of this * <tt>ChatPanel</tt> to the front; <tt>false</tt> to close this * <tt>ChatPanel</tt> */ public void setChatVisible(boolean isVisible) { ChatWindowManager chatWindowManager = GuiActivator.getUIService().getChatWindowManager(); if (isVisible) chatWindowManager.openChat(this, isVisible); else chatWindowManager.closeChat(this); } /** * Implements the <tt>Chat.isChatFocused</tt> method. Returns TRUE if this * chat panel is the currently selected panel and if the chat window, where * it's contained is active. * * @return true if this chat panel has the focus and false otherwise. */ public boolean isChatFocused() { ChatPanel currentChatPanel = chatContainer.getCurrentChat(); return (currentChatPanel != null && currentChatPanel.equals(this) && chatContainer.getFrame().isActive()); } /** * Adds the given {@link KeyListener} to this <tt>Chat</tt>. * The <tt>KeyListener</tt> is used to inform other bundles when a user has * typed in the chat editor area. * * @param l the <tt>KeyListener</tt> to add */ public void addChatEditorKeyListener(KeyListener l) { this.getChatWritePanel().getEditorPane().addKeyListener(l); } /** * Removes the given {@link KeyListener} from this <tt>Chat</tt>. * The <tt>KeyListener</tt> is used to inform other bundles when a user has * typed in the chat editor area. * * @param l the <tt>ChatFocusListener</tt> to remove */ public void removeChatEditorKeyListener(KeyListener l) { this.getChatWritePanel().getEditorPane().removeKeyListener(l); } /** * Returns the message written by user in the chat write area. * * @return the message written by user in the chat write area */ public String getMessage() { Document writeEditorDoc = writeMessagePanel.getEditorPane().getDocument(); try { return writeEditorDoc.getText(0, writeEditorDoc.getLength()); } catch (BadLocationException e) { return writeMessagePanel.getEditorPane().getText(); } } /** * Sets the given message as a message in the chat write area. * * @param message the text that would be set to the chat write area */ public void setMessage(String message) { writeMessagePanel.getEditorPane().setText(message); } /** * Indicates if the history of a hidden protocol should be shown to the * user in the default <b>grey</b> history style or it should be shown as * a normal message. * * @param protocolProvider the protocol provider to check * @return <code>true</code> if the given protocol is a hidden one and the * "hiddenProtocolGreyHistoryDisabled" property is set to true. */ private boolean isGreyHistoryStyleDisabled( ProtocolProviderService protocolProvider) { boolean isProtocolHidden = protocolProvider.getAccountID().isHidden(); boolean isGreyHistoryDisabled = false; String greyHistoryProperty = GuiActivator.getResources() .getSettingsString("impl.gui.GREY_HISTORY_ENABLED"); if (greyHistoryProperty != null) isGreyHistoryDisabled = Boolean.parseBoolean(greyHistoryProperty); return isProtocolHidden && isGreyHistoryDisabled; } /** * Sends the given file through the currently selected chat transport by * using the given fileComponent to visualize the transfer process in the * chat conversation panel. * * @param file the file to send * @param fileComponent the file component to use for visualization */ public void sendFile( final File file, final SendFileConversationComponent fileComponent) { final ChatTransport sendFileTransport = this.findFileTransferChatTransport(); this.setSelectedChatTransport(sendFileTransport, true); if(file.length() > sendFileTransport.getMaximumFileLength()) { addMessage( chatSession.getCurrentChatTransport().getName(), new Date(), Chat.ERROR_MESSAGE, GuiActivator.getResources() .getI18NString("service.gui.FILE_TOO_BIG", new String[]{ sendFileTransport.getMaximumFileLength()/1024/1024 + " MB"}), "", "text"); fileComponent.setFailed(); return; } SwingWorker worker = new SwingWorker() { @Override public Object construct() throws Exception { final FileTransfer fileTransfer = sendFileTransport.sendFile(file); addActiveFileTransfer(fileTransfer.getID(), fileTransfer); // Add the status listener that would notify us when the file // transfer has been completed and should be removed from // active components. fileTransfer.addStatusListener(ChatPanel.this); fileComponent.setProtocolFileTransfer(fileTransfer); return ""; } @Override public void catchException(Throwable ex) { logger.error("Failed to send file.", ex); if (ex instanceof IllegalStateException) { addErrorMessage( chatSession.getCurrentChatTransport().getName(), GuiActivator.getResources().getI18NString( "service.gui.MSG_SEND_CONNECTION_PROBLEM")); } else { addErrorMessage( chatSession.getCurrentChatTransport().getName(), GuiActivator.getResources().getI18NString( "service.gui.MSG_DELIVERY_ERROR", new String[]{ex.getMessage()})); } } }; worker.start(); } /** * Sends the given file through the currently selected chat transport. * * @param file the file to send */ public void sendFile(final File file) { // We need to be sure that the following code is executed in the event // dispatch thread. if (!SwingUtilities.isEventDispatchThread()) { SwingUtilities.invokeLater(new Runnable() { public void run() { sendFile(file); } }); return; } final ChatTransport fileTransferTransport = findFileTransferChatTransport(); // If there's no operation set we show some "not supported" messages // and we return. if (fileTransferTransport == null) { logger.error("Failed to send file."); this.addErrorMessage( chatSession.getChatName(), GuiActivator.getResources().getI18NString( "service.gui.FILE_SEND_FAILED", new String[]{file.getName()}), GuiActivator.getResources().getI18NString( "service.gui.FILE_TRANSFER_NOT_SUPPORTED")); return; } final SendFileConversationComponent fileComponent = new SendFileConversationComponent( this, fileTransferTransport.getDisplayName(), file); if (ConfigurationUtils.isHistoryShown() && !isHistoryLoaded) { synchronized (incomingEventBuffer) { incomingEventBuffer.add(fileComponent); } } else getChatConversationPanel().addComponent(fileComponent); this.sendFile(file, fileComponent); } /** * Sends the text contained in the write area as an SMS message or an * instance message depending on the "send SMS" check box. */ protected void sendMessage() { if (writeMessagePanel.isSmsSelected()) { this.sendSmsMessage(); } else { this.sendInstantMessage(); } } /** * Sends the text contained in the write area as an SMS message. */ public void sendSmsMessage() { String messageText = getTextFromWriteArea( OperationSetBasicInstantMessaging.DEFAULT_MIME_TYPE); ChatTransport smsChatTransport = chatSession.getCurrentChatTransport(); if (!smsChatTransport.allowsSmsMessage()) { Iterator<ChatTransport> chatTransports = chatSession.getChatTransports(); while(chatTransports.hasNext()) { ChatTransport transport = chatTransports.next(); if (transport.allowsSmsMessage()) { smsChatTransport = transport; break; } } } // If there's no operation set we show some "not supported" messages // and we return. if (!smsChatTransport.allowsSmsMessage()) { logger.error("Failed to send SMS."); this.refreshWriteArea(); this.addMessage( smsChatTransport.getName(), new Date(), Chat.OUTGOING_MESSAGE, messageText, "plain/text"); this.addErrorMessage( smsChatTransport.getName(), GuiActivator.getResources().getI18NString( "service.gui.SEND_SMS_NOT_SUPPORTED")); return; } smsChatTransport.addSmsMessageListener( new SmsMessageListener(smsChatTransport)); // We open the send SMS dialog. SendSmsDialog smsDialog = new SendSmsDialog(this, smsChatTransport, messageText); smsDialog.setPreferredSize(new Dimension(400, 200)); smsDialog.setVisible(true); } /** * Implements the <tt>ChatPanel.sendMessage</tt> method. Obtains the * appropriate operation set and sends the message, contained in the write * area, through it. */ protected void sendInstantMessage() { String htmlText; String plainText; // read the text and clear it as quick as possible // to avoid double sending if the user hits enter too quickly synchronized(writeMessagePanel) { if(isWriteAreaEmpty()) return; // Trims the html message, as it sometimes contains a lot of empty // lines, which causes some problems to some protocols. htmlText = getTextFromWriteArea( OperationSetBasicInstantMessaging.HTML_MIME_TYPE).trim(); plainText = getTextFromWriteArea( OperationSetBasicInstantMessaging.DEFAULT_MIME_TYPE).trim(); // clear the message earlier // to avoid as much as possible to not sending it twice (double enter) this.refreshWriteArea(); } String messageText; String mimeType; if (chatSession.getCurrentChatTransport().isContentTypeSupported( OperationSetBasicInstantMessaging.HTML_MIME_TYPE) && (htmlText.indexOf("<b") > -1 || htmlText.indexOf("<i") > -1 || htmlText.indexOf("<u") > -1 || htmlText.indexOf("<font") > -1)) { messageText = htmlText; mimeType = OperationSetBasicInstantMessaging.HTML_MIME_TYPE; } else { messageText = plainText; mimeType = OperationSetBasicInstantMessaging.DEFAULT_MIME_TYPE; } try { if (isMessageCorrectionActive() && chatSession.getCurrentChatTransport() .allowsMessageCorrections()) { chatSession.getCurrentChatTransport().correctInstantMessage( messageText, mimeType, correctedMessageUID); } else { chatSession.getCurrentChatTransport().sendInstantMessage( messageText, mimeType); } stopMessageCorrection(); } catch (IllegalStateException ex) { logger.error("Failed to send message.", ex); this.addMessage( chatSession.getCurrentChatTransport().getName(), new Date(), Chat.OUTGOING_MESSAGE, messageText, mimeType); String protocolError = ""; if (ex.getMessage() != null) protocolError = " " + GuiActivator.getResources().getI18NString( "service.gui.ERROR_WAS", new String[]{ex.getMessage()}); this.addErrorMessage( chatSession.getCurrentChatTransport().getName(), GuiActivator.getResources().getI18NString( "service.gui.MSG_SEND_CONNECTION_PROBLEM") + protocolError); } catch (Exception ex) { logger.error("Failed to send message.", ex); this.refreshWriteArea(); this.addMessage( chatSession.getCurrentChatTransport().getName(), new Date(), Chat.OUTGOING_MESSAGE, messageText, mimeType); String protocolError = ""; if (ex.getMessage() != null) protocolError = " " + GuiActivator.getResources().getI18NString( "service.gui.ERROR_WAS", new String[]{ex.getMessage()}); this.addErrorMessage( chatSession.getCurrentChatTransport().getName(), GuiActivator.getResources().getI18NString( "service.gui.MSG_DELIVERY_ERROR", new String[]{protocolError})); } if (chatSession.getCurrentChatTransport().allowsTypingNotifications()) { // Send TYPING STOPPED event before sending the message getChatWritePanel().stopTypingTimer(); } } /** * Enters editing mode for the last sent message in this chat. */ public void startLastMessageCorrection() { startMessageCorrection(lastSentMessageUID); } /** * Enters editing mode for the message with the specified id - puts the * message contents in the write panel and changes the background. * * @param correctedMessageUID The ID of the message being corrected. */ public void startMessageCorrection(String correctedMessageUID) { if (!showMessageInWriteArea(correctedMessageUID)) { return; } if (chatSession.getCurrentChatTransport().allowsMessageCorrections()) { this.correctedMessageUID = correctedMessageUID; Color bgColor = new Color(GuiActivator.getResources() .getColor("service.gui.CHAT_EDIT_MESSAGE_BACKGROUND")); this.writeMessagePanel.setEditorPaneBackground(bgColor); } } /** * Shows the last sent message in the write area, either in order to * correct it or to send it again. * * @return <tt>true</tt> on success, <tt>false</tt> on failure. */ public boolean showLastMessageInWriteArea() { return showMessageInWriteArea(lastSentMessageUID); } /** * Shows the message with the specified ID in the write area, either * in order to correct it or to send it again. * * @param messageUID The ID of the message to show. * @return <tt>true</tt> on success, <tt>false</tt> on failure. */ public boolean showMessageInWriteArea(String messageUID) { String messageContents = conversationPanel.getMessageContents( messageUID); if (messageContents == null) { return false; } this.refreshWriteArea(); this.setMessage(messageContents); return true; } /** * Exits editing mode, clears the write panel and the background. */ public void stopMessageCorrection() { this.correctedMessageUID = null; this.writeMessagePanel.setEditorPaneBackground(Color.WHITE); this.refreshWriteArea(); } /** * Returns whether a message is currently being edited. * * @return <tt>true</tt> if a message is currently being edited, * <tt>false</tt> otherwise. */ public boolean isMessageCorrectionActive() { return correctedMessageUID != null; } /** * Listens for SMS messages and shows them in the chat. */ private class SmsMessageListener implements MessageListener { /** * Initializes a new <tt>SmsMessageListener</tt> instance. * * @param chatTransport Currently unused */ public SmsMessageListener(ChatTransport chatTransport) { } public void messageDelivered(MessageDeliveredEvent evt) { Message msg = evt.getSourceMessage(); Contact contact = evt.getDestinationContact(); addMessage( contact.getDisplayName(), new Date(), Chat.OUTGOING_MESSAGE, msg.getContent(), msg.getContentType()); addMessage( contact.getDisplayName(), new Date(), Chat.ACTION_MESSAGE, GuiActivator.getResources().getI18NString( "service.gui.SMS_SUCCESSFULLY_SENT"), "text"); } public void messageDeliveryFailed(MessageDeliveryFailedEvent evt) { logger.error(evt.getReason()); String errorMsg = null; Message sourceMessage = (Message) evt.getSource(); Contact sourceContact = evt.getDestinationContact(); MetaContact metaContact = GuiActivator .getContactListService().findMetaContactByContact(sourceContact); if (evt.getErrorCode() == MessageDeliveryFailedEvent.OFFLINE_MESSAGES_NOT_SUPPORTED) { errorMsg = GuiActivator.getResources().getI18NString( "service.gui.MSG_DELIVERY_NOT_SUPPORTED", new String[]{sourceContact.getDisplayName()}); } else if (evt.getErrorCode() == MessageDeliveryFailedEvent.NETWORK_FAILURE) { errorMsg = GuiActivator.getResources().getI18NString( "service.gui.MSG_NOT_DELIVERED"); } else if (evt.getErrorCode() == MessageDeliveryFailedEvent.PROVIDER_NOT_REGISTERED) { errorMsg = GuiActivator.getResources().getI18NString( "service.gui.MSG_SEND_CONNECTION_PROBLEM"); } else if (evt.getErrorCode() == MessageDeliveryFailedEvent.INTERNAL_ERROR) { errorMsg = GuiActivator.getResources().getI18NString( "service.gui.MSG_DELIVERY_INTERNAL_ERROR"); } else { errorMsg = GuiActivator.getResources().getI18NString( "service.gui.MSG_DELIVERY_UNKNOWN_ERROR"); } String reason = evt.getReason(); if (reason != null) errorMsg += " " + GuiActivator.getResources().getI18NString( "service.gui.ERROR_WAS", new String[]{reason}); addMessage( metaContact.getDisplayName(), new Date(), Chat.OUTGOING_MESSAGE, sourceMessage.getContent(), sourceMessage.getContentType()); addErrorMessage( metaContact.getDisplayName(), errorMsg); } public void messageReceived(MessageReceivedEvent evt) {} } /** * Returns the date of the first message in history for this chat. * * @return the date of the first message in history for this chat. */ public Date getFirstHistoryMsgTimestamp() { return firstHistoryMsgTimestamp; } /** * Returns the date of the last message in history for this chat. * * @return the date of the last message in history for this chat. */ public Date getLastHistoryMsgTimestamp() { return lastHistoryMsgTimestamp; } /** * Loads history messages ignoring the message with the specified id. * * @param escapedMessageID the id of the message to be ignored; * <tt>null</tt> if no message is to be ignored */ public void loadHistory(final String escapedMessageID) { SwingWorker historyWorker = new SwingWorker() { private Collection<Object> historyList; @Override public Object construct() throws Exception { // Load the history period, which initializes the // firstMessageTimestamp and the lastMessageTimeStamp variables. // Used to disable/enable history flash buttons in the chat // window tool bar. loadHistoryPeriod(); // Load the last N=CHAT_HISTORY_SIZE messages from history. historyList = chatSession.getHistory( ConfigurationUtils.getChatHistorySize()); return historyList; } /** * Called on the event dispatching thread (not on the worker thread) * after the <code>construct</code> method has returned. */ @Override public void finished() { if(historyList != null && historyList.size() > 0) { processHistory(historyList, escapedMessageID); } isHistoryLoaded = true; // Add incoming events accumulated while the history was loading // at the end of the chat. addIncomingEvents(); } }; historyWorker.start(); } /** * Loads history for the chat meta contact in a separate thread. Equivalent * to calling {@link #loadHistory(String)} with <tt>null</tt> for * <tt>escapedMessageID</tt>. */ public void loadHistory() { this.loadHistory(null); } /** * Loads history period dates for the current chat. */ private void loadHistoryPeriod() { this.firstHistoryMsgTimestamp = chatSession.getHistoryStartDate(); this.lastHistoryMsgTimestamp = chatSession.getHistoryEndDate(); } /** * Changes the "Send as SMS" check box state. * * @param isSmsSelected <code>true</code> to set the "Send as SMS" check box * selected, <code>false</code> - otherwise. */ public void setSmsSelected(boolean isSmsSelected) { writeMessagePanel.setSmsSelected(isSmsSelected); } /** * The <tt>ChangeProtocolAction</tt> is an <tt>AbstractAction</tt> that * opens the menu, containing all available protocol contacts. */ private class ChangeTransportAction extends AbstractAction { public void actionPerformed(ActionEvent e) { writeMessagePanel.openChatTransportSelectorBox(); } } /** * Renames all occurrences of the given <tt>chatContact</tt> in this chat * panel. * * @param chatContact the contact to rename * @param name the new name */ public void setContactName(ChatContact<?> chatContact, String name) { if (chatContactListPanel != null) { chatContactListPanel.renameContact(chatContact); } ChatContainer chatContainer = getChatContainer(); chatContainer.setChatTitle(this, name); if (chatContainer.getCurrentChat() == this) { chatContainer.setTitle(name); } } /** * Adds the given chatTransport to the given send via selector box. * * @param chatTransport the transport to add */ public void addChatTransport(ChatTransport chatTransport) { writeMessagePanel.addChatTransport(chatTransport); } /** * Removes the given chat status state from the send via selector box. * * @param chatTransport the transport to remove */ public void removeChatTransport(ChatTransport chatTransport) { writeMessagePanel.removeChatTransport(chatTransport); } /** * Selects the given chat transport in the send via box. * * @param chatTransport the chat transport to be selected * @param isMessageOrFileTransferReceived Boolean telling us if this change * of the chat transport correspond to an effective switch to this new * transform (a mesaage received from this transport, or a file transfer * request received, or if the resource timeouted), or just a status update * telling us a new chatTransport is now available (i.e. another device has * startup). */ public void setSelectedChatTransport( ChatTransport chatTransport, boolean isMessageOrFileTransferReceived) { writeMessagePanel.setSelectedChatTransport( chatTransport, isMessageOrFileTransferReceived); } /** * Updates the status of the given chat transport in the send via selector * box and notifies the user for the status change. * @param chatTransport the <tt>chatTransport</tt> to update */ public void updateChatTransportStatus(final ChatTransport chatTransport) { if(!SwingUtilities.isEventDispatchThread()) { SwingUtilities.invokeLater(new Runnable() { public void run() { updateChatTransportStatus(chatTransport); } }); return; } writeMessagePanel.updateChatTransportStatus(chatTransport); if (!chatTransport.equals(chatSession.getCurrentChatTransport())) return; if(ConfigurationUtils.isShowStatusChangedInChat()) { // Show a status message to the user. this.addMessage( chatTransport.getName(), new Date(), Chat.STATUS_MESSAGE, GuiActivator.getResources().getI18NString( "service.gui.STATUS_CHANGED_CHAT_MESSAGE", new String[]{chatTransport.getStatus().getStatusName()}), "text/plain"); } setChatIcon(new ImageIcon( Constants.getStatusIcon(chatTransport.getStatus()))); } /** * Sets the chat icon. * * @param icon the chat icon to set */ public void setChatIcon(Icon icon) { if(ConfigurationUtils.isMultiChatWindowEnabled()) { if (getChatContainer().getChatCount() > 0) { getChatContainer().setChatIcon(this, icon); } } } /** * Implements <tt>ChatPanel.loadPreviousFromHistory</tt>. * Loads previous page from history. */ public void loadPreviousPageFromHistory() { final MetaHistoryService chatHistory = GuiActivator.getMetaHistoryService(); // If the MetaHistoryService is not registered we have nothing to do // here. The history service could be "disabled" from the user // through one of the configuration forms. if (chatHistory == null) return; SwingWorker worker = new SwingWorker() { @Override public Object construct() throws Exception { ChatConversationPanel conversationPanel = getChatConversationPanel(); Date firstMsgDate = conversationPanel.getPageFirstMsgTimestamp(); Collection<Object> c = null; if(firstMsgDate != null) { c = chatSession.getHistoryBeforeDate( firstMsgDate, MESSAGES_PER_PAGE); } if(c !=null && c.size() > 0) { SwingUtilities.invokeLater( new HistoryMessagesLoader(c)); } return ""; } @Override public void finished() { getChatContainer().updateHistoryButtonState(ChatPanel.this); } }; worker.start(); } /** * Implements <tt>ChatPanel.loadNextFromHistory</tt>. * Loads next page from history. */ public void loadNextPageFromHistory() { final MetaHistoryService chatHistory = GuiActivator.getMetaHistoryService(); // If the MetaHistoryService is not registered we have nothing to do // here. The history could be "disabled" from the user // through one of the configuration forms. if (chatHistory == null) return; SwingWorker worker = new SwingWorker() { @Override public Object construct() throws Exception { Date lastMsgDate = getChatConversationPanel().getPageLastMsgTimestamp(); Collection<Object> c = null; if(lastMsgDate != null) { c = chatSession.getHistoryAfterDate( lastMsgDate, MESSAGES_PER_PAGE); } if(c != null && c.size() > 0) SwingUtilities.invokeLater( new HistoryMessagesLoader(c)); return ""; } @Override public void finished() { getChatContainer().updateHistoryButtonState(ChatPanel.this); } }; worker.start(); } /** * From a given collection of messages shows the history in the chat window. */ private class HistoryMessagesLoader implements Runnable { private final Collection<Object> chatHistory; public HistoryMessagesLoader(Collection<Object> history) { this.chatHistory = history; } public void run() { ChatConversationPanel chatConversationPanel = getChatConversationPanel(); chatConversationPanel.clear(); processHistory(chatHistory, ""); chatConversationPanel.setDefaultContent(); } } /** * Adds the given <tt>chatContact</tt> to the list of chat contacts * participating in the corresponding to this chat panel chat. * @param chatContact the contact to add */ public void addChatContact(ChatContact<?> chatContact) { if (chatContactListPanel != null) chatContactListPanel.addContact(chatContact); } /** * Removes the given <tt>chatContact</tt> from the list of chat contacts * participating in the corresponding to this chat panel chat. * @param chatContact the contact to remove */ public void removeChatContact(ChatContact<?> chatContact) { if (chatContactListPanel != null) chatContactListPanel.removeContact(chatContact); } /** * Removes all chat contacts from the contact list of the chat. */ public void removeAllChatContacts() { if (chatContactListPanel != null) chatContactListPanel.removeAllChatContacts(); } /** * Updates the contact status. * @param chatContact the chat contact to update * @param statusMessage the status message to show */ public void updateChatContactStatus(final ChatContact<?> chatContact, final String statusMessage) { if(!SwingUtilities.isEventDispatchThread()) { SwingUtilities.invokeLater(new Runnable() { public void run() { updateChatContactStatus(chatContact, statusMessage); } }); return; } this.addMessage( chatContact.getName(), new Date(), Chat.STATUS_MESSAGE, statusMessage, ChatHtmlUtils.TEXT_CONTENT_TYPE); } /** * Sets the given <tt>subject</tt> to this chat. * @param subject the subject to set */ public void setChatSubject(String subject) { if (subjectPanel != null) { // Don't do anything if the subject doesn't really change. String oldSubject = subjectPanel.getSubject(); if ((subject == null ) || (subject.length() == 0)) { if ((oldSubject == null) || (oldSubject.length() == 0)) return; } else if (subject.equals(oldSubject)) return; subjectPanel.setSubject(subject); this.addMessage( chatSession.getChatName(), new Date(), Chat.STATUS_MESSAGE, GuiActivator.getResources().getI18NString( "service.gui.CHAT_ROOM_SUBJECT_CHANGED", new String []{ chatSession.getChatName(), subject}), ChatHtmlUtils.TEXT_CONTENT_TYPE); } } /** * Adds the given <tt>IncomingFileTransferRequest</tt> to the conversation * panel in order to notify the user of the incoming file. * * @param fileTransferOpSet the file transfer operation set * @param request the request to display in the conversation panel * @param date the date on which the request has been received */ public void addIncomingFileTransferRequest( final OperationSetFileTransfer fileTransferOpSet, final IncomingFileTransferRequest request, final Date date) { if(!SwingUtilities.isEventDispatchThread()) { SwingUtilities.invokeLater(new Runnable() { public void run() { addIncomingFileTransferRequest( fileTransferOpSet, request, date); } }); return; } this.addActiveFileTransfer(request.getID(), request); ReceiveFileConversationComponent component = new ReceiveFileConversationComponent( this, fileTransferOpSet, request, date); if (ConfigurationUtils.isHistoryShown() && !isHistoryLoaded) { synchronized (incomingEventBuffer) { incomingEventBuffer.add(component); } } else this.getChatConversationPanel().addComponent(component); } /** * Implements <tt>Chat.addChatFocusListener</tt> method. Adds the given * <tt>ChatFocusListener</tt> to the list of listeners. * * @param listener the listener that we'll be adding. */ public void addChatFocusListener(ChatFocusListener listener) { synchronized (focusListeners) { if (!focusListeners.contains(listener)) focusListeners.add(listener); } } /** * Implements <tt>Chat.removeChatFocusListener</tt> method. Removes the given * <tt>ChatFocusListener</tt> from the list of listeners. * * @param listener the listener to remove. */ public void removeChatFocusListener(ChatFocusListener listener) { synchronized (focusListeners) { focusListeners.remove(listener); } } /** * Returns the first chat transport for the current chat session that * supports file transfer. * * @return the first chat transport for the current chat session that * supports file transfer. */ public ChatTransport findFileTransferChatTransport() { // We currently don't support file transfer in group chats. if (chatSession instanceof ConferenceChatSession) return null; ChatTransport currentChatTransport = chatSession.getCurrentChatTransport(); if (currentChatTransport.getProtocolProvider() .getOperationSet(OperationSetFileTransfer.class) != null) { return currentChatTransport; } else { Iterator<ChatTransport> chatTransportsIter = chatSession.getChatTransports(); while (chatTransportsIter.hasNext()) { ChatTransport chatTransport = chatTransportsIter.next(); Object fileTransferOpSet = chatTransport.getProtocolProvider() .getOperationSet(OperationSetFileTransfer.class); if (fileTransferOpSet != null) return chatTransport; } } return null; } /** * Returns the first chat transport for the current chat session that * supports group chat. * * @return the first chat transport for the current chat session that * supports group chat. */ public ChatTransport findInviteChatTransport() { ChatTransport currentChatTransport = chatSession.getCurrentChatTransport(); ProtocolProviderService protocolProvider = currentChatTransport.getProtocolProvider(); // We choose between OpSets for multi user chat... if (protocolProvider.getOperationSet( OperationSetMultiUserChat.class) != null || protocolProvider.getOperationSet( OperationSetAdHocMultiUserChat.class) != null) { return chatSession.getCurrentChatTransport(); } else { Iterator<ChatTransport> chatTransportsIter = chatSession.getChatTransports(); while (chatTransportsIter.hasNext()) { ChatTransport chatTransport = chatTransportsIter.next(); Object groupChatOpSet = chatTransport.getProtocolProvider() .getOperationSet(OperationSetMultiUserChat.class); if (groupChatOpSet != null) return chatTransport; } } return null; } /** * Invites the given <tt>chatContacts</tt> to this chat. * @param inviteChatTransport the chat transport to use to send the invite * @param chatContacts the contacts to invite * @param reason the reason of the invitation */ public void inviteContacts( ChatTransport inviteChatTransport, Collection<String> chatContacts, String reason) { ChatSession conferenceChatSession = null; if (chatSession instanceof MetaContactChatSession) { chatContacts.add(inviteChatTransport.getName()); ConferenceChatManager conferenceChatManager = GuiActivator.getUIService().getConferenceChatManager(); // the chat session is set regarding to which OpSet is used for MUC if(inviteChatTransport.getProtocolProvider(). getOperationSet(OperationSetMultiUserChat.class) != null) { ChatRoomWrapper chatRoomWrapper = conferenceChatManager.createChatRoom( inviteChatTransport.getProtocolProvider(), chatContacts, reason); conferenceChatSession = new ConferenceChatSession(this, chatRoomWrapper); } else if (inviteChatTransport.getProtocolProvider(). getOperationSet(OperationSetAdHocMultiUserChat.class) != null) { AdHocChatRoomWrapper chatRoomWrapper = conferenceChatManager.createAdHocChatRoom( inviteChatTransport.getProtocolProvider(), chatContacts, reason); conferenceChatSession = new AdHocConferenceChatSession(this, chatRoomWrapper); } if (conferenceChatSession != null) this.setChatSession(conferenceChatSession); } // We're already in a conference chat. else { conferenceChatSession = chatSession; for (String contactAddress : chatContacts) { conferenceChatSession.getCurrentChatTransport() .inviteChatContact(contactAddress, reason); } } } /** * Informs all <tt>ChatFocusListener</tt>s that a <tt>ChatFocusEvent</tt> * has been triggered. * * @param eventID the type of the <tt>ChatFocusEvent</tt> */ public void fireChatFocusEvent(int eventID) { ChatFocusEvent evt = new ChatFocusEvent(this, eventID); if (logger.isTraceEnabled()) logger.trace("Will dispatch the following chat event: " + evt); Iterable<ChatFocusListener> listeners; synchronized (focusListeners) { listeners = new ArrayList<ChatFocusListener>(focusListeners); } for (ChatFocusListener listener : listeners) { switch (evt.getEventID()) { case ChatFocusEvent.FOCUS_GAINED: listener.chatFocusGained(evt); break; case ChatFocusEvent.FOCUS_LOST: listener.chatFocusLost(evt); break; default: logger.error("Unknown event type " + evt.getEventID()); } } } /** * Handles file transfer status changed in order to remove completed file * transfers from the list of active transfers. * @param event the file transfer status change event the notified us for * the change */ public void statusChanged(FileTransferStatusChangeEvent event) { FileTransfer fileTransfer = event.getFileTransfer(); int newStatus = event.getNewStatus(); if (newStatus == FileTransferStatusChangeEvent.COMPLETED || newStatus == FileTransferStatusChangeEvent.CANCELED || newStatus == FileTransferStatusChangeEvent.FAILED || newStatus == FileTransferStatusChangeEvent.REFUSED) { removeActiveFileTransfer(fileTransfer.getID()); fileTransfer.removeStatusListener(this); } } /** * Returns <code>true</code> if there are active file transfers, otherwise * returns <code>false</code>. * @return <code>true</code> if there are active file transfers, otherwise * returns <code>false</code> */ public boolean containsActiveFileTransfers() { return !activeFileTransfers.isEmpty(); } /** * Cancels all active file transfers. */ public void cancelActiveFileTransfers() { Enumeration<String> activeKeys = activeFileTransfers.keys(); while (activeKeys.hasMoreElements()) { // catchall so if anything happens we still // will close the chat/window try { String key = activeKeys.nextElement(); Object descriptor = activeFileTransfers.get(key); if (descriptor instanceof IncomingFileTransferRequest) { ((IncomingFileTransferRequest) descriptor).rejectFile(); } else if (descriptor instanceof FileTransfer) { ((FileTransfer) descriptor).cancel(); } } catch(Throwable t) { logger.error("Cannot cancel file transfer.", t); } } } /** * Stores the current divider position. */ private class DividerLocationListener implements PropertyChangeListener { public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName() .equals(JSplitPane.DIVIDER_LOCATION_PROPERTY)) { int dividerLocation = (Integer) evt.getNewValue(); // We store the divider location only when the user drags the // divider and not when we've set it programatically. // if (dividerLocation != autoDividerLocation) int writeAreaSize = messagePane.getHeight() - dividerLocation - messagePane.getDividerSize(); ConfigurationUtils .setChatWriteAreaSize(writeAreaSize); // writeMessagePanel.setPreferredSize( // new Dimension( // (int) writeMessagePanel.getPreferredSize() // .getWidth(), // writeAreaSize)); } } } /** * Sets the location of the split pane divider. * * @param location the location of the divider given by the pixel count * between the left bottom corner and the left bottom divider location */ public void setDividerLocation(int location) { int dividerLocation = messagePane.getHeight() - location; messagePane.setDividerLocation(dividerLocation); messagePane.revalidate(); messagePane.repaint(); } /** * Returns the contained divider location. * * @return the contained divider location */ public int getDividerLocation() { return messagePane.getHeight() - messagePane.getDividerLocation(); } /** * Returns the contained divider size. * * @return the contained divider size */ public int getDividerSize() { return messagePane.getDividerSize(); } /** * Adds all events accumulated in the incoming event buffer to the * chat conversation panel. */ private void addIncomingEvents() { synchronized (incomingEventBuffer) { Iterator<Object> eventBufferIter = incomingEventBuffer.iterator(); while(eventBufferIter.hasNext()) { Object incomingEvent = eventBufferIter.next(); if (incomingEvent instanceof ChatMessage) { this.displayChatMessage((ChatMessage) incomingEvent); } else if (incomingEvent instanceof ChatConversationComponent) { this.getChatConversationPanel() .addComponent((ChatConversationComponent)incomingEvent); } } } } /** * Adds the given file transfer <tt>id</tt> to the list of active file * transfers. * * @param id the identifier of the file transfer to add * @param descriptor the descriptor of the file transfer */ public void addActiveFileTransfer(String id, Object descriptor) { synchronized (activeFileTransfers) { activeFileTransfers.put(id, descriptor); } } /** * Removes the given file transfer <tt>id</tt> from the list of active * file transfers. * @param id the identifier of the file transfer to remove */ public void removeActiveFileTransfer(String id) { synchronized (activeFileTransfers) { activeFileTransfers.remove(id); } } /** * Adds the given {@link ChatMenuListener} to this <tt>Chat</tt>. * The <tt>ChatMenuListener</tt> is used to determine menu elements * that should be added on right clicks. * * @param l the <tt>ChatMenuListener</tt> to add */ public void addChatEditorMenuListener(ChatMenuListener l) { this.getChatWritePanel().addChatEditorMenuListener(l); } /** * Adds the given {@link CaretListener} to this <tt>Chat</tt>. * The <tt>CaretListener</tt> is used to inform other bundles when a user has * moved the caret in the chat editor area. * * @param l the <tt>CaretListener</tt> to add */ public void addChatEditorCaretListener(CaretListener l) { this.getChatWritePanel().getEditorPane().addCaretListener(l); } /** * Adds the given {@link DocumentListener} to this <tt>Chat</tt>. * The <tt>DocumentListener</tt> is used to inform other bundles when a user has * modified the document in the chat editor area. * * @param l the <tt>DocumentListener</tt> to add */ public void addChatEditorDocumentListener(DocumentListener l) { this.getChatWritePanel().getEditorPane() .getDocument().addDocumentListener(l); } /** * Removes the given {@link CaretListener} from this <tt>Chat</tt>. * The <tt>CaretListener</tt> is used to inform other bundles when a user has * moved the caret in the chat editor area. * * @param l the <tt>CaretListener</tt> to remove */ public void removeChatEditorCaretListener(CaretListener l) { this.getChatWritePanel().getEditorPane().removeCaretListener(l); } /** * Removes the given {@link ChatMenuListener} to this <tt>Chat</tt>. * The <tt>ChatMenuListener</tt> is used to determine menu elements * that should be added on right clicks. * * @param l the <tt>ChatMenuListener</tt> to add */ public void removeChatEditorMenuListener(ChatMenuListener l) { this.getChatWritePanel().removeChatEditorMenuListener(l); } /** * Removes the given {@link DocumentListener} from this <tt>Chat</tt>. * The <tt>DocumentListener</tt> is used to inform other bundles when a user has * modified the document in the chat editor area. * * @param l the <tt>DocumentListener</tt> to remove */ public void removeChatEditorDocumentListener(DocumentListener l) { this.getChatWritePanel().getEditorPane() .getDocument().removeDocumentListener(l); } /** * Adds the given <tt>ChatHistoryListener</tt> to the list of listeners * notified when a change occurs in the history shown in this chat panel. * * @param l the <tt>ChatHistoryListener</tt> to add */ public void addChatHistoryListener(ChatHistoryListener l) { synchronized (historyListeners) { historyListeners.add(l); } } /** * Removes the given <tt>ChatHistoryListener</tt> from the list of listeners * notified when a change occurs in the history shown in this chat panel. * * @param l the <tt>ChatHistoryListener</tt> to remove */ public void removeChatHistoryListener(ChatHistoryListener l) { synchronized (historyListeners) { historyListeners.remove(l); } } /** * Notifies all registered <tt>ChatHistoryListener</tt>s that a change has * occurred in the history of this chat. */ private void fireChatHistoryChange() { Iterator<ChatHistoryListener> listeners = historyListeners.iterator(); while (listeners.hasNext()) { listeners.next().chatHistoryChanged(this); } } /** * Provides the {@link Highlighter} used in rendering the chat editor. * * @return highlighter used to render message being composed */ public Highlighter getHighlighter() { return this.getChatWritePanel().getEditorPane().getHighlighter(); } /** * Gets the caret position in the chat editor. * @return index of caret in message being composed */ public int getCaretPosition() { return this.getChatWritePanel().getEditorPane().getCaretPosition(); } /** * Causes the chat to validate its appearance (suggests a repaint operation * may be necessary). */ public void promptRepaint() { this.getChatWritePanel().getEditorPane().repaint(); } /** * Shows the font chooser dialog */ public void showFontChooserDialog() { JEditorPane editorPane = writeMessagePanel.getEditorPane(); FontChooser fontChooser = new FontChooser(); int result = fontChooser.showDialog(this); if (result != FontChooser.CANCEL_OPTION) { String fontFamily = fontChooser.getFontFamily(); int fontSize = fontChooser.getFontSize(); boolean isBold = fontChooser.isBoldStyleSelected(); boolean isItalic = fontChooser.isItalicStyleSelected(); boolean isUnderline = fontChooser.isUnderlineStyleSelected(); Color fontColor = fontChooser.getFontColor(); // Font family and size writeMessagePanel.setFontFamilyAndSize(fontFamily, fontSize); // Font style writeMessagePanel.setBoldStyleEnable(isBold); writeMessagePanel.setItalicStyleEnable(isItalic); writeMessagePanel.setUnderlineStyleEnable(isUnderline); // Font color writeMessagePanel.setFontColor(fontColor); writeMessagePanel.saveDefaultFontConfiguration( fontFamily, fontSize, isBold, isItalic, isUnderline, fontColor); } editorPane.requestFocus(); } /** * Reloads chat messages. */ public void loadSkin() { getChatConversationPanel().clear(); loadHistory(); getChatConversationPanel().setDefaultContent(); } /** * Notifies the user if any member of the chatroom changes nickname. * * @param event a <tt>ChatRoomMemberPropertyChangeEvent</tt> which carries * the specific of the change */ public void chatRoomPropertyChanged(ChatRoomMemberPropertyChangeEvent event) { this.conversationPanel .appendMessageToEnd( "<DIV identifier=\"message\" style=\"color:#707070;\">" + event.getOldValue() + " is now known as " + event.getNewValue() + "</DIV>", ChatHtmlUtils.HTML_CONTENT_TYPE); } /** * Add a new ChatLinkClickedListener * * @param listener ChatLinkClickedListener */ public void addChatLinkClickedListener(ChatLinkClickedListener listener) { conversationPanel.addChatLinkClickedListener(listener); } /** * Remove existing ChatLinkClickedListener * * @param listener ChatLinkClickedListener */ public void removeChatLinkClickedListener(ChatLinkClickedListener listener) { conversationPanel.removeChatLinkClickedListener(listener); } }
package org.jivesoftware.smack; import org.jivesoftware.smack.packet.RosterPacket; import org.jivesoftware.smack.packet.IQ; import org.jivesoftware.smack.util.StringUtils; import java.util.*; /** * A group of roster entries. * * @see Roster#getGroup(String) * @author Matt Tucker */ public class RosterGroup { private String name; private XMPPConnection connection; private List entries; /** * Creates a new roster group instance. * * @param name the name of the group. * @param connection the connection the group belongs to. */ RosterGroup(String name, XMPPConnection connection) { this.name = name; this.connection = connection; entries = new ArrayList(); } /** * Returns the name of the group. * * @return the name of the group. */ public String getName() { return name; } /** * Sets the name of the group. Changing the group's name is like moving all the group entries * of the group to a new group specified by the new name. Since this group won't have entries * it will be removed from the roster. This means that all the references to this object will * be invalid and will need to be updated to the new group specified by the new name. * * @param name the name of the group. */ public void setName(String name) { synchronized (entries) { for (int i=0; i<entries.size(); i++) { RosterPacket packet = new RosterPacket(); packet.setType(IQ.Type.SET); RosterEntry entry = (RosterEntry)entries.get(i); RosterPacket.Item item = RosterEntry.toRosterItem(entry); item.removeGroupName(this.name); item.addGroupName(name); packet.addRosterItem(item); connection.sendPacket(packet); } } } /** * Returns the number of entries in the group. * * @return the number of entries in the group. */ public int getEntryCount() { synchronized (entries) { return entries.size(); } } /** * Returns an iterator for the entries in the group. * * @return an iterator for the entries in the group. */ public Iterator getEntries() { synchronized (entries) { return Collections.unmodifiableList(new ArrayList(entries)).iterator(); } } /** * Returns the roster entry associated with the given XMPP address or * <tt>null</tt> if the user is not an entry in the group. * * @param user the XMPP address of the user (eg "jsmith@example.com"). * @return the roster entry or <tt>null</tt> if it does not exist in the group. */ public RosterEntry getEntry(String user) { if (user == null) { return null; } // Roster entries never include a resource so remove the resource // if it's a part of the XMPP address. user = StringUtils.parseBareAddress(user); synchronized (entries) { for (Iterator i=entries.iterator(); i.hasNext(); ) { RosterEntry entry = (RosterEntry)i.next(); if (entry.getUser().equals(user)) { return entry; } } } return null; } /** * Returns true if the specified entry is part of this group. * * @param entry a roster entry. * @return true if the entry is part of this group. */ public boolean contains(RosterEntry entry) { synchronized (entries) { return entries.contains(entry); } } /** * Returns true if the specified XMPP address is an entry in this group. * * @param user the XMPP address of the user. * @return true if the XMPP address is an entry in this group. */ public boolean contains(String user) { if (user == null) { return false; } // Roster entries never include a resource so remove the resource // if it's a part of the XMPP address. user = StringUtils.parseBareAddress(user); synchronized (entries) { for (Iterator i=entries.iterator(); i.hasNext(); ) { RosterEntry entry = (RosterEntry)i.next(); if (entry.getUser().equals(user)) { return true; } } } return false; } /** * Adds a roster entry to this group. If the entry was unfiled then it will be removed from * the unfiled list and will be added to this group. * * @param entry a roster entry. */ public void addEntry(RosterEntry entry) { // Only add the entry if it isn't already in the list. synchronized (entries) { if (!entries.contains(entry)) { entries.add(entry); RosterPacket packet = new RosterPacket(); packet.setType(IQ.Type.SET); packet.addRosterItem(RosterEntry.toRosterItem(entry)); connection.sendPacket(packet); } } } /** * Removes a roster entry from this group. If the entry does not belong to any other group * then it will be considered as unfiled, therefore it will be added to the list of unfiled * entries. * * @param entry a roster entry. */ public void removeEntry(RosterEntry entry) { // Only remove the entry if it's in the entry list. // Remove the entry locally, if we wait for RosterPacketListenerprocess>>Packet(Packet) // to take place the entry will exist in the group until a packet is received from the // server. synchronized (entries) { if (entries.contains(entry)) { RosterPacket packet = new RosterPacket(); packet.setType(IQ.Type.SET); RosterPacket.Item item = RosterEntry.toRosterItem(entry); item.removeGroupName(this.getName()); packet.addRosterItem(item); connection.sendPacket(packet); // Remove the entry locally entries.remove(entry); } } } void addEntryLocal(RosterEntry entry) { // Only add the entry if it isn't already in the list. synchronized (entries) { entries.remove(entry); entries.add(entry); } } void removeEntryLocal(RosterEntry entry) { // Only remove the entry if it's in the entry list. synchronized (entries) { if (entries.contains(entry)) { entries.remove(entry); } } } }
package com.freak.dashboard; import com.freak.dashboard.DashboardService.LocalBinder; import android.content.ComponentName; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.IBinder; import android.preference.ListPreference; import android.preference.PreferenceActivity; import android.util.Log; public class DashboardSettings extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener /*implements OnSharedPreferenceChangeListener */{ private static final boolean DEBUG = false; private static final String TAG = DashboardSettings.class.getSimpleName(); private static final int PICK_IMAGE = 1; private DashboardService dashboardService; @Override @SuppressWarnings("deprecation") protected void onCreate(Bundle icicle) { super.onCreate(icicle); addPreferencesFromResource(R.xml.dashboard_settings); } @Override @SuppressWarnings("deprecation") protected void onPause() { getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); // Bind to the dashboard service Intent intent = new Intent(this, DashboardService.class); bindService(intent, connection, 0); super.onPause(); } @Override @SuppressWarnings("deprecation") protected void onResume() { super.onResume(); getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); } /** * Bits of service code. You usually won't need to change this. */ private ServiceConnection connection = new ServiceConnection() { public void onServiceConnected(ComponentName arg0, IBinder service) { if (DEBUG) Log.d(TAG, "onServiceConnected"); // We've bound to LocalService, cast the IBinder and get LocalService instance LocalBinder binder = (LocalBinder) service; dashboardService = binder.getService(); if (DEBUG) Log.d(TAG, "unbindService"); dashboardService.reload(); unbindService(connection); } public void onServiceDisconnected(ComponentName name) { if (DEBUG) Log.d(TAG, "onServiceDisconnected"); dashboardService = null; } }; @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals(getString(R.string.key_background_picture))) { if (DEBUG) Log.d(TAG, "Change background"); if (Integer.decode(sharedPreferences.getString(key, "-1")) == -2) { Intent intent = new Intent();
package org.helioviewer.jhv.renderable.gui; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import javax.swing.table.AbstractTableModel; import org.helioviewer.jhv.JHVDirectory; import org.helioviewer.jhv.JHVGlobals; import org.helioviewer.jhv.base.FileUtils; import org.helioviewer.jhv.base.JSONUtils; import org.helioviewer.jhv.camera.Camera; import org.helioviewer.jhv.display.Displayer; import org.helioviewer.jhv.display.Displayer.DisplayMode; import org.helioviewer.jhv.display.Viewport; import org.helioviewer.jhv.layers.ImageLayer; import org.helioviewer.jhv.layers.Layers; import org.helioviewer.jhv.renderable.components.RenderableMiniview; import org.helioviewer.jhv.threads.JHVWorker; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.jogamp.opengl.GL2; @SuppressWarnings("serial") public class RenderableContainer extends AbstractTableModel implements Reorderable { private ArrayList<Renderable> renderables = new ArrayList<>(); private ArrayList<Renderable> newRenderables = new ArrayList<>(); private final ArrayList<Renderable> removedRenderables = new ArrayList<>(); public void addBeforeRenderable(Renderable renderable) { int lastImagelayerIndex = -1; int size = renderables.size(); for (int i = 0; i < size; i++) { if (renderables.get(i) instanceof ImageLayer) { lastImagelayerIndex = i; } } renderables.add(lastImagelayerIndex + 1, renderable); newRenderables.add(renderable); int row = lastImagelayerIndex + 1; fireTableRowsInserted(row, row); } public void addRenderable(Renderable renderable) { renderables.add(renderable); newRenderables.add(renderable); int row = renderables.size() - 1; fireTableRowsInserted(row, row); Displayer.display(); // e.g., PFSS renderable } public void removeRenderable(Renderable renderable) { renderables.remove(renderable); removedRenderables.add(renderable); // refreshTable(); display() will take care Displayer.display(); } public void prerender(GL2 gl) { int count = removeRenderables(gl); initRenderables(gl); if (count > 0) refreshTable(); for (Renderable renderable : renderables) { renderable.prerender(gl); } } public void render(Camera camera, Viewport vp, GL2 gl) { for (Renderable renderable : renderables) { renderable.render(camera, vp, gl); } } public void renderScale(Camera camera, Viewport vp, GL2 gl) { for (Renderable renderable : renderables) { renderable.renderScale(camera, vp, gl); } } public void renderFloat(Camera camera, Viewport vp, GL2 gl) { for (Renderable renderable : renderables) { renderable.renderFloat(camera, vp, gl); } } public void renderFullFloat(Camera camera, Viewport vp, GL2 gl) { for (Renderable renderable : renderables) { renderable.renderFullFloat(camera, vp, gl); } } public void renderMiniview(Camera camera, Viewport miniview, GL2 gl) { RenderableMiniview.renderBackground(camera, miniview, gl); for (Renderable renderable : renderables) { renderable.renderMiniview(camera, miniview, gl); } } private void initRenderables(GL2 gl) { for (Renderable renderable : newRenderables) { renderable.init(gl); } newRenderables.clear(); } private int removeRenderables(GL2 gl) { int count = removedRenderables.size(); for (Renderable renderable : removedRenderables) { renderable.remove(gl); } removedRenderables.clear(); return count; } private void insertRow(int row, Renderable rowData) { if (row > renderables.size()) { renderables.add(rowData); } else { renderables.add(row, rowData); } } @Override public void reorder(int fromIndex, int toIndex) { if (toIndex > renderables.size()) { return; } Renderable toMove = renderables.get(fromIndex); Renderable moveTo = renderables.get(Math.max(0, toIndex - 1)); if (!(toMove instanceof ImageLayer) || !(moveTo instanceof ImageLayer)) { return; } renderables.remove(fromIndex); if (fromIndex < toIndex) { insertRow(toIndex - 1, toMove); } else { insertRow(toIndex, toMove); } refreshTable(); if (Displayer.multiview) { Layers.arrangeMultiView(true); } } @Override public int getRowCount() { return renderables.size(); } @Override public int getColumnCount() { return RenderableContainerPanel.NUMBER_COLUMNS; } @Override public Object getValueAt(int row, int col) { try { return renderables.get(row); } catch (Exception e) { return null; } } public void refreshTable() { fireTableDataChanged(); } public void updateCell(int row, int col) { if (row >= 0) // negative row breaks model fireTableCellUpdated(row, col); } public void fireTimeUpdated(Renderable renderable) { updateCell(renderables.indexOf(renderable), RenderableContainerPanel.TIME_COL); } public void dispose(GL2 gl) { for (Renderable renderable : renderables) { renderable.dispose(gl); } newRenderables = renderables; renderables = new ArrayList<>(); } public void saveCurrentScene() { JSONObject main = new JSONObject(); main.put("displayMode", Displayer.mode.toString()); JSONArray ja = new JSONArray(); for (Renderable renderable : renderables) { JSONObject jo = new JSONObject(); JSONObject dataObject = new JSONObject(); jo.put("data", dataObject); jo.put("className", renderable.getClass().getName()); renderable.serialize(dataObject); ja.put(jo); JSONArray va = new JSONArray(); renderable.serializeVisibility(va); jo.put("visibility", va); if (renderable instanceof ImageLayer) { ImageLayer irenderable = (ImageLayer) renderable; if (irenderable.isActiveImageLayer()) { jo.put("master", true); jo.put("masterFrame", Layers.getActiveView().getCurrentFrameNumber()); } } } main.put("renderables", ja); try (OutputStream os = FileUtils.newBufferedOutputStream(new File(JHVDirectory.HOME.getPath() + "test.json"))) { final PrintStream printStream = new PrintStream(os); printStream.print(main.toString()); printStream.close(); } catch (IOException e) { e.printStackTrace(); } } public void loadScene() { ArrayList<Renderable> newlist = new ArrayList<Renderable>(); Renderable masterRenderable = null; int masterFrame = 0; try (InputStream in = FileUtils.newBufferedInputStream(new File(JHVDirectory.HOME.getPath() + "test.json"))) { JSONObject data = JSONUtils.getJSONStream(in); JSONArray rja = data.getJSONArray("renderables"); for (Object o : rja) { if (o instanceof JSONObject) { JSONObject jo = (JSONObject) o; try { JSONObject jdata = jo.optJSONObject("data"); if (jdata == null) continue; Class<?> c = Class.forName(jo.optString("className")); Constructor<?> cons = c.getConstructor(JSONObject.class); Object _renderable = cons.newInstance(jdata); if (_renderable instanceof Renderable) { Renderable renderable = (Renderable) _renderable; newlist.add(renderable); JSONArray va = jo.optJSONArray("visibility"); if (va == null) va = new JSONArray(new double[] { 1, 0, 0, 0 }); renderable.deserializeVisibility(va); boolean master = jo.optBoolean("master", false); if (master) { masterRenderable = renderable; masterFrame = jo.optInt("masterFrame", 0); } } } catch (InstantiationException | IllegalAccessException | InvocationTargetException | JSONException | ClassNotFoundException | NoSuchMethodException | SecurityException e) { e.printStackTrace(); } } } removedRenderables.addAll(renderables); renderables = new ArrayList<>(); LoadState loadStateTask = new LoadState(newlist, masterRenderable, masterFrame); JHVGlobals.getExecutorService().execute(loadStateTask); String displayModeString = data.optString("displayMode", "Orthographic"); DisplayMode displayMode; try { displayMode = Displayer.DisplayMode.valueOf(displayModeString); } catch (Exception e) { displayMode = Displayer.DisplayMode.Orthographic; } Displayer.setMode(displayMode); } catch (IOException e1) { e1.printStackTrace(); } } class LoadState extends JHVWorker<Integer, Void> { private ArrayList<Renderable> newlist; private Renderable master; private int masterFrame; public LoadState(ArrayList<Renderable> _newlist, Renderable _master, int _masterFrame) { newlist = _newlist; master = _master; masterFrame = _masterFrame; } @Override protected Integer backgroundWork() { for (Renderable renderable : newlist) { while (!renderable.isLoadedForState()) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } return 1; } @Override protected void done() { if (!isCancelled()) { for (Renderable renderable : newlist) { addRenderable(renderable); if (renderable instanceof ImageLayer && renderable == master) { ((ImageLayer) renderable).setActiveImageLayer(); Layers.setFrame(masterFrame); } } } } } }
package com.osho.ernesto.animate; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //Snackbar.make(view, "Contact Me", Snackbar.LENGTH_LONG) // .setAction("Email", null).show(); } }); } // Animation code public void clockwise(View view){ ImageView image = (ImageView)findViewById(R.id.imageView); Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.clockwise); image.startAnimation(animation); Toast.makeText(this, "CLOCKWISE animation", Toast.LENGTH_SHORT).show(); } public void zoom(View view){ ImageView image = (ImageView)findViewById(R.id.imageView); Animation animation1 = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.zoom); image.startAnimation(animation1); Toast.makeText(this, "ZOOM animation", Toast.LENGTH_SHORT).show(); } public void blink(View view){ ImageView image = (ImageView)findViewById(R.id.imageView); Animation animation1 = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.blink); image.startAnimation(animation1); Toast.makeText(this, "BLINK animation", Toast.LENGTH_SHORT).show(); } public void move(View view){ ImageView image = (ImageView)findViewById(R.id.imageView); Animation animation1 = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.move); image.startAnimation(animation1); Toast.makeText(this, "MOVE animation", Toast.LENGTH_SHORT).show(); } public void slide(View view){ ImageView image = (ImageView)findViewById(R.id.imageView); Animation animation1 = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide); image.startAnimation(animation1); Toast.makeText(this, "SLIDE animation", Toast.LENGTH_SHORT).show(); } public void bounce(View view){ ImageView image = (ImageView)findViewById(R.id.imageView); Animation animation1 = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.bounce); image.startAnimation(animation1); Toast.makeText(this, "BOUNCE animation", Toast.LENGTH_SHORT).show(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
package org.leyfer.thesis.TouchLogger.helper; import org.leyfer.thesis.TouchLogger.config.Code; import org.leyfer.thesis.TouchLogger.config.Range; import org.leyfer.thesis.TouchLogger.config.TouchConfig; import org.leyfer.thesis.TouchLogger.config.Type; import java.util.HashMap; import java.util.Map; public class DeviceTouchConfig { // LG Nexus 5 (stock) public static final TouchConfig hammerhead_Nexus_5_Config = new TouchConfig( "/dev/input/event1", new Code("0003", "0000"), new Range(0, 9, 255), new Type("002f", "0035", "0036", "003a", "0039") ); // Samsung galaxy note 3 public static final TouchConfig MSM8974_SM_N900_Config = new TouchConfig( "/dev/input/event1", new Code("0003", "0000"), new Range(0, 9, 255), new Type("002f", "0035", "0036", "0032", "0039") ); // LG G2 public static final TouchConfig MSM8974_LG_D802_Config = new TouchConfig( "/dev/input/event1", new Code("0003", "0000"), new Range(0, 9, 255), new Type("002f", "0035", "0036", "003a", "0039") ); // Lenovo K900 public static final TouchConfig clovertrail_Lenovo_K900_ROW_Config = new TouchConfig( "/dev/input/event0", new Code("0003", "0000"), new Range(0, 9, 255), new Type("002f", "0035", "0036", "003b", "0039") ); public static final Map<String, TouchConfig> configMap = new HashMap<String, TouchConfig>() {{ put("HAMMERHEAD,NEXUS 5", hammerhead_Nexus_5_Config); put("HAMMERHEAD,AOSP ON HAMMERHEAD", hammerhead_Nexus_5_Config); put("UNIVERSAL5420,SM-N900", MSM8974_SM_N900_Config); put("MSM8974,SM-N9005", MSM8974_SM_N900_Config); put("GALBI,LG-D802", MSM8974_LG_D802_Config); put("CLOVERTRAIL,LENOVO K900_ROW", clovertrail_Lenovo_K900_ROW_Config); }}; }
package com.pr0gramm.app.services; import android.content.SharedPreferences; import android.graphics.PointF; import com.google.common.base.Optional; import com.google.common.base.Stopwatch; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.gson.Gson; import com.pr0gramm.app.Settings; import com.pr0gramm.app.api.pr0gramm.Api; import com.pr0gramm.app.api.pr0gramm.ApiGsonBuilder; import com.pr0gramm.app.api.pr0gramm.LoginCookieHandler; import com.pr0gramm.app.api.pr0gramm.response.Info; import com.pr0gramm.app.api.pr0gramm.response.Login; import com.pr0gramm.app.api.pr0gramm.response.Sync; import com.pr0gramm.app.feed.ContentType; import com.pr0gramm.app.orm.BenisRecord; import com.pr0gramm.app.util.BackgroundScheduler; import org.joda.time.Duration; import org.joda.time.Instant; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Set; import java.util.concurrent.TimeUnit; import javax.inject.Inject; import javax.inject.Singleton; import rx.Observable; import rx.subjects.BehaviorSubject; import rx.util.async.Async; import static com.pr0gramm.app.Settings.resetContentTypeSettings; import static com.pr0gramm.app.orm.BenisRecord.getBenisValuesAfter; import static com.pr0gramm.app.services.UserService.LoginState.NOT_AUTHORIZED; import static com.pr0gramm.app.util.AndroidUtility.checkNotMainThread; import static org.joda.time.Duration.standardDays; @Singleton public class UserService { private static final Logger logger = LoggerFactory.getLogger(UserService.class); private static final String KEY_LAST_SYNC_ID = "UserService.lastSyncId"; private static final String KEY_LAST_USER_INFO = "UserService.lastUserInfo"; private final Api api; private final VoteService voteService; private final SeenService seenService; private final InboxService inboxService; private final LoginCookieHandler cookieHandler; private final SharedPreferences preferences; private final Gson gson = ApiGsonBuilder.builder().create(); private final BehaviorSubject<LoginState> loginStateObservable = BehaviorSubject.create(NOT_AUTHORIZED); private final Settings settings; @Inject public UserService(Api api, VoteService voteService, SeenService seenService, InboxService inboxService, LoginCookieHandler cookieHandler, SharedPreferences preferences, Settings settings) { this.api = api; this.seenService = seenService; this.voteService = voteService; this.inboxService = inboxService; this.cookieHandler = cookieHandler; this.preferences = preferences; this.settings = settings; restoreLatestUserInfo(preferences); this.cookieHandler.setOnCookieChangedListener(this::onCookieChanged); } private void restoreLatestUserInfo(SharedPreferences preferences) { // try to restore the previous user info object Observable.just(preferences.getString(KEY_LAST_USER_INFO, null)) .filter(value -> value != null) .map(encoded -> createLoginState(Optional.of(gson.fromJson(encoded, Info.class)))) .subscribeOn(BackgroundScheduler.instance()) .doOnNext(info -> logger.info("Restoring user info: {}", info)) .subscribe( loginStateObservable::onNext, error -> logger.warn("Could not restore user info: " + error)); } private void onCookieChanged() { Optional<String> cookie = cookieHandler.getLoginCookie(); if (!cookie.isPresent()) logout(); } public Observable<LoginProgress> login(String username, String password) { return api.login(username, password).flatMap(login -> { Observable<LoginProgress> syncState; if (login.isSuccess()) { // perform initial sync. syncState = syncWithProgress() .filter(val -> val instanceof Float) .cast(Float.class) .map(LoginProgress::new) .mergeWith(info().ignoreElements().cast(LoginProgress.class)) .onErrorResumeNext(Observable.<LoginProgress>empty()); } else { syncState = Observable.empty(); } // wait for sync to complete before emitting login result. return syncState.concatWith(Observable.just(new LoginProgress(login))); }); } /** * Check if we can do authorized requests. */ public boolean isAuthorized() { return cookieHandler.hasCookie(); } /** * Checks if the user has paid for a pr0mium account */ public boolean isPremiumUser() { return cookieHandler.isPaid(); } /** * Performs a logout of the user. */ public Observable<Void> logout() { return Async.<Void>start(() -> { loginStateObservable.onNext(NOT_AUTHORIZED); // removing cookie from requests cookieHandler.clearLoginCookie(false); // remove sync id preferences.edit() .remove(KEY_LAST_SYNC_ID) .remove(KEY_LAST_USER_INFO) .apply(); // clear all the vote cache voteService.clear(); // clear the seen items seenService.clear(); // and reset the content user, because only signed in users can // see the nsfw and nsfl stuff. resetContentTypeSettings(settings); return null; }, BackgroundScheduler.instance()).ignoreElements(); } public Observable<LoginState> loginState() { return loginStateObservable.asObservable(); } /** * Performs a sync. This updates the vote cache with all the votes that * where performed since the last call to sync. */ public Observable<Sync> sync() { return syncWithProgress().filter(val -> val instanceof Sync).cast(Sync.class); } /** * Performs a sync. If values need to be stored in the database, a sequence * of float values between 0 and 1 will be emitted. At the end, the sync * object is appended to the stream of values. */ public Observable<Object> syncWithProgress() { if (!isAuthorized()) return Observable.empty(); BehaviorSubject<Float> progressSubject = BehaviorSubject.create(); // tell the sync request where to start long lastSyncId = preferences.getLong(KEY_LAST_SYNC_ID, 0L); Observable<Sync> sync = api.sync(lastSyncId).map(response -> { inboxService.publishUnreadMessagesCount(response.getInboxCount()); // store syncId for next time. if (response.getLastId() > lastSyncId) { preferences.edit() .putLong(KEY_LAST_SYNC_ID, response.getLastId()) .apply(); } // and apply votes now voteService.applyVoteActions(response.getLog(), progressSubject::onNext); progressSubject.onCompleted(); return response; }).finallyDo(progressSubject::onCompleted); return sync.cast(Object.class).mergeWith(progressSubject.throttleFirst(50, TimeUnit.MILLISECONDS)); } /** * Retrieves the user data and stores part of the data in the database. */ public Observable<Info> info(String username) { return api.info(username, null); } /** * Retrieves the user data and stores part of the data in the database. */ public Observable<Info> info(String username, Set<ContentType> contentTypes) { return api.info(username, ContentType.combine(contentTypes)); } /** * Returns information for the current user, if a user is signed in. * As a side-effect, this will store the current benis of the user in the database. * * @return The info, if the user is currently signed in. */ public Observable<Info> info() { return Observable.from(getName().asSet()).flatMap(this::info).map(info -> { Info.User user = info.getUser(); // stores the current benis value BenisRecord record = new BenisRecord(user.getId(), Instant.now(), user.getScore()); record.save(); // updates the login state and ui loginStateObservable.onNext(createLoginState(Optional.of(info))); // and store the login state for later persistLatestUserInfo(info); return info; }); } private void persistLatestUserInfo(Info info) { try { String encoded = gson.toJson(info); preferences.edit() .putString(KEY_LAST_USER_INFO, encoded) .apply(); } catch (RuntimeException error) { logger.warn("Could not persist latest user info", error); } } private LoginState createLoginState(Optional<Info> info) { checkNotMainThread(); int userId = info.get().getUser().getId(); Graph benisHistory = loadBenisHistory(userId); return new LoginState(info.get(), benisHistory); } private Graph loadBenisHistory(int userId) { Stopwatch watch = Stopwatch.createStarted(); Duration historyLength = standardDays(7); Instant start = Instant.now().minus(historyLength); // get the values and transform them ImmutableList<PointF> points = FluentIterable .from(getBenisValuesAfter(userId, start)) .transform(record -> { float x = record.getTimeMillis() - start.getMillis(); return new PointF(x, record.getBenis()); }).toList(); logger.info("Loading benis graph took " + watch); return new Graph(0, historyLength.getMillis(), points); } /** * Gets the name of the current user from the cookie. This will only * work, if the user is authorized. * * @return The name of the currently signed in user. */ public Optional<String> getName() { return cookieHandler.getCookie().transform(cookie -> cookie.n); } public static Optional<Info.User> getUser(LoginState loginState) { if (loginState.getInfo() == null) return Optional.absent(); return Optional.fromNullable(loginState.getInfo().getUser()); } public static final class LoginState { private final Info info; private final Graph benisHistory; private LoginState() { this(null, null); } private LoginState(Info info, Graph benisHistory) { this.info = info; this.benisHistory = benisHistory; } public boolean isAuthorized() { return info != null; } public Info getInfo() { return info; } public Graph getBenisHistory() { return benisHistory; } public static final LoginState NOT_AUTHORIZED = new LoginState(); } public static final class LoginProgress { private final Optional<Login> login; private final float progress; public LoginProgress(float progress) { this.progress = progress; this.login = Optional.absent(); } public LoginProgress(Login login) { this.progress = 1.f; this.login = Optional.of(login); } public float getProgress() { return progress; } public Optional<Login> getLogin() { return login; } } }
package org.objectweb.proactive.core.process.lsf; import org.objectweb.proactive.core.process.SimpleExternalProcess; import org.objectweb.proactive.core.process.AbstractExternalProcessDecorator; import org.objectweb.proactive.core.process.ExternalProcess; /** * <p> * The RloginProcess class is able to start any class, of the ProActive library, * using rlogin command. * </p><p> * For instance: * </p><pre> * ............... * LSFBSubProcess lsf = new LSFBSubProcess(new SimpleExternalProcess("ls -lsa")); * RLoginProcess p = new RLoginProcess(lsf, false); * p.setHostname("cluster_front_end_name"); * p.startProcess(); * ............... * </pre> * @author ProActive Team * @version 1.0, 2002/09/20 * @since ProActive 0.9.4 */ public class RLoginProcess extends AbstractExternalProcessDecorator { private boolean exitAfterCommand; /** * Creates a new RloginProcess * Used with XML Descriptors */ public RLoginProcess() { super(); setCompositionType(SEND_TO_OUTPUT_STREAM_COMPOSITION); } /** * Creates a new RloginProcess * @param targetProcess The target process associated to this process. The target process * represents the process that will be launched after logging remote host with rlogin */ public RLoginProcess(ExternalProcess targetProcess) { this(targetProcess, false); } /** * Creates a new RloginProcess * @param targetProcess The target process associated to this process. The target process * represents the process that will be launched after logging remote host with rlogin * @param exitAfterCommand If true the process will finished once rlogin command is performed. The default value is false */ public RLoginProcess(ExternalProcess targetProcess, boolean exitAfterCommand) { super(targetProcess, SEND_TO_OUTPUT_STREAM_COMPOSITION); this.exitAfterCommand = exitAfterCommand; } /** * Method setExitAfterCommand * @param b If true the process will finished once rlogin command is performed. The default vaule is false */ public void setExitAfterCommand(boolean b) { exitAfterCommand = b; } /** * Returns the value of the boolean telling that the process will finished after rlogin command or will wait * for another command to be pushed once logging on the remote host * @return boolean */ public boolean getExitAfterCommand() { return exitAfterCommand; } public static void main(String[] args) { try { LSFBSubProcess lsf = new LSFBSubProcess(new SimpleExternalProcess("ls -lsa")); RLoginProcess p = new RLoginProcess(lsf, false); p.setHostname("galere1"); p.startProcess(); } catch (Exception e) { e.printStackTrace(); } } protected String internalBuildCommand() { return buildEnvironmentCommand()+buildRLoginCommand(); } protected String buildRLoginCommand() { return "rlogin "+hostname+" "; } protected void internalStartProcess(String command) throws java.io.IOException { super.internalStartProcess(command); if (exitAfterCommand) { outputMessageSink.setMessage(null); } } }
package diaspora.forager; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.crash.FirebaseCrash; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.ValueEventListener; import java.util.logging.Level; import java.util.logging.Logger; public class CloudDatabaseHandler { // TODO test all these methods private static final Logger logger = Logger.getLogger(CloudDatabaseHandler.class.getName()); public CloudDatabaseHandler() { } private void writeNewUserToDatabase(DatabaseReference databaseReference, FirebaseUser firebaseUser) { try { User user = new User(firebaseUser.getEmail(), 0, 0); databaseReference.child("users") .child(firebaseUser.getUid()).setValue(user); } catch (Throwable e) { logger.log(Level.SEVERE, "Unidentified Error Occurred", e); FirebaseCrash.report(e); } } private void updateNickName(DatabaseReference databaseReference, FirebaseUser firebaseUser, String nickName) { try { databaseReference.child("users") .child(firebaseUser.getUid()) .child("nickName").setValue(nickName); } catch (Throwable e) { logger.log(Level.SEVERE, "Unidentified Error Occurred", e); FirebaseCrash.report(e); } } private void addMushrooms(DatabaseReference databaseReference, FirebaseUser firebaseUser, final int numberOfMushrooms) { try { databaseReference.child("users") .child(firebaseUser.getUid()) .addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { // Update the cloud database updateDatabase(dataSnapshot.getValue(User.class).getNumberOfMushrooms() + numberOfMushrooms); } @Override public void onCancelled(DatabaseError databaseError) { logger.log(Level.SEVERE, "Database Error Occurred", databaseError.toException()); FirebaseCrash.report(databaseError.toException()); } }); } catch (Throwable e) { logger.log(Level.SEVERE, "Unidentified Error Occurred", e); FirebaseCrash.report(e); } } private void addPoints(DatabaseReference databaseReference, FirebaseUser firebaseUser, final int numberOfPoints) { try { databaseReference.child("users") .child(firebaseUser.getUid()) .addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { // Update the cloud database updateDatabase(dataSnapshot.getValue(User.class).getNumberOfPoints() + numberOfPoints); } @Override public void onCancelled(DatabaseError databaseError) { logger.log(Level.SEVERE, "Database Error Occurred", databaseError.toException()); FirebaseCrash.report(databaseError.toException()); } }); } catch (Throwable e) { logger.log(Level.SEVERE, "Unidentified Error Occurred", e); FirebaseCrash.report(e); } } private void subtractMushrooms(DatabaseReference databaseReference, FirebaseUser firebaseUser, final int numberOfMushrooms) { try { databaseReference.child("users") .child(firebaseUser.getUid()) .addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { // Update the cloud database updateDatabase(dataSnapshot.getValue(User.class).getNumberOfMushrooms() - numberOfMushrooms); } @Override public void onCancelled(DatabaseError databaseError) { logger.log(Level.SEVERE, "Database Error Occurred", databaseError.toException()); FirebaseCrash.report(databaseError.toException()); } }); } catch (Throwable e) { logger.log(Level.SEVERE, "Unidentified Error Occurred", e); FirebaseCrash.report(e); } } private void subtractPoints(DatabaseReference databaseReference, FirebaseUser firebaseUser, final int numberOfPoints) { try { databaseReference.child("users") .child(firebaseUser.getUid()) .addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { // Update the cloud database updateDatabase(dataSnapshot.getValue(User.class).getNumberOfPoints() - numberOfPoints); } @Override public void onCancelled(DatabaseError databaseError) { logger.log(Level.SEVERE, "Database Error Occurred", databaseError.toException()); FirebaseCrash.report(databaseError.toException()); } }); } catch (Throwable e) { logger.log(Level.SEVERE, "Unidentified Error Occurred", e); FirebaseCrash.report(e); } } private void getNickName(DatabaseReference databaseReference, FirebaseUser firebaseUser) { try { databaseReference.child("users") .child(firebaseUser.getUid()) .addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { // Update the android UI updateUI(dataSnapshot.getValue(User.class).getNickName()); } @Override public void onCancelled(DatabaseError databaseError) { logger.log(Level.SEVERE, "Database Error Occurred", databaseError.toException()); FirebaseCrash.report(databaseError.toException()); } }); } catch (Throwable e) { logger.log(Level.SEVERE, "Unidentified Error Occurred", e); FirebaseCrash.report(e); } } private void getNumberOfMushrooms(DatabaseReference databaseReference, FirebaseUser firebaseUser) { try { databaseReference.child("users") .child(firebaseUser.getUid()) .addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { // Update the android UI updateUI(dataSnapshot.getValue(User.class).getNumberOfMushrooms()); } @Override public void onCancelled(DatabaseError databaseError) { logger.log(Level.SEVERE, "Database Error Occurred", databaseError.toException()); FirebaseCrash.report(databaseError.toException()); } }); } catch (Throwable e) { logger.log(Level.SEVERE, "Unidentified Error Occurred", e); FirebaseCrash.report(e); } } private void getNumberOfPoints(DatabaseReference databaseReference, FirebaseUser firebaseUser) { try { databaseReference.child("users") .child(firebaseUser.getUid()) .addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { // Update the android UI updateUI(dataSnapshot.getValue(User.class).getNumberOfPoints()); } @Override public void onCancelled(DatabaseError databaseError) { logger.log(Level.SEVERE, "Database Error Occurred", databaseError.toException()); FirebaseCrash.report(databaseError.toException()); } }); } catch (Throwable e) { logger.log(Level.SEVERE, "Unidentified Error Occurred", e); FirebaseCrash.report(e); } } private void updateUI(Object object) { // DO NOTHING, VIRTUAL METHOD } private void updateDatabase(Object object) { // DO NOTHING, VIRTUAL METHOD } }
package org.owasp.esapi.reference; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.TreeSet; import java.util.regex.Pattern; import org.owasp.esapi.Logger; import org.owasp.esapi.SecurityConfiguration; public class DefaultSecurityConfiguration implements SecurityConfiguration { /** The properties. */ private Properties properties = new Properties(); /** Regular expression cache */ private Map regexMap = null; /** The location of the Resources directory used by ESAPI. */ public static final String RESOURCE_DIRECTORY = "org.owasp.esapi.resources"; private static final String ALLOWED_LOGIN_ATTEMPTS = "AllowedLoginAttempts"; private static final String APPLICATION_NAME = "ApplicationName"; private static final String MASTER_PASSWORD = "MasterPassword"; private static final String MASTER_SALT = "MasterSalt"; private static final String VALID_EXTENSIONS = "ValidExtensions"; private static final String MAX_UPLOAD_FILE_BYTES = "MaxUploadFileBytes"; private static final String USERNAME_PARAMETER_NAME = "UsernameParameterName"; private static final String PASSWORD_PARAMETER_NAME = "PasswordParameterName"; private static final String MAX_OLD_PASSWORD_HASHES = "MaxOldPasswordHashes"; private static final String ENCRYPTION_ALGORITHM = "EncryptionAlgorithm"; private static final String HASH_ALGORITHM = "HashAlgorithm"; private static final String CHARACTER_ENCODING = "CharacterEncoding"; private static final String RANDOM_ALGORITHM = "RandomAlgorithm"; private static final String DIGITAL_SIGNATURE_ALGORITHM = "DigitalSignatureAlgorithm"; private static final String RESPONSE_CONTENT_TYPE = "ResponseContentType"; private static final String REMEMBER_TOKEN_DURATION = "RememberTokenDuration"; private static final String IDLE_TIMEOUT_DURATION = "IdleTimeoutDuration"; private static final String ABSOLUTE_TIMEOUT_DURATION = "AbsoluteTimeoutDuration"; private static final String LOG_LEVEL = "LogLevel"; private static final String LOG_FILE_NAME = "LogFileName"; private static final String MAX_LOG_FILE_SIZE = "MaxLogFileSize"; private static final String LOG_ENCODING_REQUIRED = "LogEncodingRequired"; protected final int MAX_REDIRECT_LOCATION = 1000; protected final int MAX_FILE_NAME_LENGTH = 1000; /** * Load properties from properties file. Set this with setResourceDirectory * from your web application or ESAPI filter. For test and non-web applications, * this implementation defaults to a System property defined when Java is launched. * Use: * <P> * java -Dorg.owasp.esapi.resources="/path/resources" * <P> * where 'path' references the appropriate directory in your system. */ private static String resourceDirectory = System.getProperty(RESOURCE_DIRECTORY); private static long lastModified = 0; /** * Instantiates a new configuration. */ public DefaultSecurityConfiguration() { loadConfiguration(); } /** * {@inheritDoc} */ public String getApplicationName() { return properties.getProperty(APPLICATION_NAME, "AppNameNotSpecified"); } /** * {@inheritDoc} */ public char[] getMasterPassword() { return properties.getProperty(MASTER_PASSWORD).toCharArray(); } /** * {@inheritDoc} */ public File getKeystore() { return new File(getResourceDirectory(), "keystore"); } /** * {@inheritDoc} */ public String getResourceDirectory() { if (resourceDirectory != null && !resourceDirectory.endsWith( System.getProperty("file.separator"))) { resourceDirectory += System.getProperty("file.separator" ); } return resourceDirectory; } /** * {@inheritDoc} */ public void setResourceDirectory( String dir ) { resourceDirectory = dir; if ( resourceDirectory != null && !resourceDirectory.endsWith( System.getProperty("file.separator"))) { resourceDirectory += System.getProperty("file.separator" ); } this.loadConfiguration(); } /** * {@inheritDoc} */ public byte[] getMasterSalt() { return properties.getProperty(MASTER_SALT).getBytes(); } /** * {@inheritDoc} */ public List getAllowedFileExtensions() { String def = ".zip,.pdf,.tar,.gz,.xls,.properties,.txt,.xml"; String[] extList = properties.getProperty(VALID_EXTENSIONS,def).split(","); return Arrays.asList(extList); } /** * {@inheritDoc} */ public int getAllowedFileUploadSize() { String bytes = properties.getProperty(MAX_UPLOAD_FILE_BYTES, "5000000"); return Integer.parseInt(bytes); } /** * Load ESAPI.properties from the classpath. For easy deployment, * place your ESAPI.properties file in WEB-INF/classes */ private Properties loadConfigurationFromClasspath() { ClassLoader loader = getClass().getClassLoader(); if ( loader == null ) throw new IllegalArgumentException( "Failure to load ESAPI configuration from classpath"); Properties result = null; InputStream in = null; try { in = loader.getResourceAsStream("ESAPI.properties"); if (in != null) { result = new Properties (); result.load(in); // Can throw IOException } } catch (Exception e) { result = null; } finally { try { in.close(); } catch (Exception e) {} } if (result == null) { throw new IllegalArgumentException ("Can't load ESAPI.properties as a classloader resource"); } return result; } /** * Load configuration. */ private void loadConfiguration() { File file = null; try { properties = loadConfigurationFromClasspath(); logSpecial("Loaded ESAPI properties from classpath", null); } catch (Exception ce) { logSpecial("Can't load ESAPI properties from classpath, trying FileIO", ce); file = new File(getResourceDirectory(), "ESAPI.properties"); if (file.lastModified() == lastModified) return; FileInputStream fis = null; try { fis = new FileInputStream( file ); properties.load(fis); logSpecial("Loaded ESAPI properties from " + file.getAbsolutePath(), null); } catch (Exception e) { logSpecial("Can't load ESAPI properties from " + file.getAbsolutePath(), e); } finally { try { fis.close(); } catch (IOException e) { // give up } } } logSpecial(" ========Master Configuration========", null); Iterator i = new TreeSet( properties.keySet() ).iterator(); while (i.hasNext()) { String key = (String) i.next(); logSpecial(" | " + key + "=" + properties.get(key), null); } if (file != null) { logSpecial(" ========Master Configuration========", null); lastModified = file.lastModified(); } // cache regular expressions regexMap = new HashMap(); Iterator regexIterator = getValidationPatternNames(); while ( regexIterator.hasNext() ) { String name = (String)regexIterator.next(); Pattern regex = getValidationPattern(name); if ( name != null && regex != null ) { regexMap.put( name, regex ); } } } /** * Used to log errors to the console during the loading of the properties file itself. Can't use * standard logging in this case, since the Logger is not initialized yet. * * @param message The message to send to the console. * @param e The error that occured (this value is currently ignored). */ private void logSpecial(String message, Throwable e) { System.out.println(message); } /** * {@inheritDoc} */ public String getPasswordParameterName() { return properties.getProperty(PASSWORD_PARAMETER_NAME, "password"); } /** * {@inheritDoc} */ public String getUsernameParameterName() { return properties.getProperty(USERNAME_PARAMETER_NAME, "username"); } /** * {@inheritDoc} */ public String getEncryptionAlgorithm() { return properties.getProperty(ENCRYPTION_ALGORITHM, "PBEWithMD5AndDES/CBC/PKCS5Padding"); } /** * {@inheritDoc} */ public String getHashAlgorithm() { return properties.getProperty(HASH_ALGORITHM, "SHA-512"); } /** * {@inheritDoc} */ public String getCharacterEncoding() { return properties.getProperty(CHARACTER_ENCODING, "UTF-8"); } /** * {@inheritDoc} */ public String getDigitalSignatureAlgorithm() { return properties.getProperty(DIGITAL_SIGNATURE_ALGORITHM, "SHAwithDSA"); } /** * {@inheritDoc} */ public String getRandomAlgorithm() { return properties.getProperty(RANDOM_ALGORITHM, "SHA1PRNG"); } /** * {@inheritDoc} */ public int getAllowedLoginAttempts() { String attempts = properties.getProperty(ALLOWED_LOGIN_ATTEMPTS, "5"); return Integer.parseInt(attempts); } /** * {@inheritDoc} */ public int getMaxOldPasswordHashes() { String max = properties.getProperty(MAX_OLD_PASSWORD_HASHES, "12"); return Integer.parseInt(max); } /** * {@inheritDoc} */ public Threshold getQuota(String eventName) { int count = 0; String countString = properties.getProperty(eventName + ".count"); if (countString != null) { count = Integer.parseInt(countString); } int interval = 0; String intervalString = properties.getProperty(eventName + ".interval"); if (intervalString != null) { interval = Integer.parseInt(intervalString); } List actions = new ArrayList(); String actionString = properties.getProperty(eventName + ".actions"); if (actionString != null) { String[] actionList = actionString.split(","); actions = Arrays.asList(actionList); } Threshold q = new Threshold(eventName, count, interval, actions); return q; } /** * {@inheritDoc} */ public int getLogLevel() { String level = properties.getProperty(LOG_LEVEL); if (level == null) { // This error is NOT logged the normal way because the logger constructor calls getLogLevel() and if this error occurred it would cause // an infinite loop. logSpecial("The LOG-LEVEL property in the ESAPI properties file is not defined.", null); return Logger.WARNING; } if (level.equalsIgnoreCase("OFF")) return Logger.OFF; if (level.equalsIgnoreCase("FATAL")) return Logger.FATAL; if (level.equalsIgnoreCase("ERROR")) return Logger.ERROR ; if (level.equalsIgnoreCase("WARNING")) return Logger.WARNING; if (level.equalsIgnoreCase("INFO")) return Logger.INFO; if (level.equalsIgnoreCase("DEBUG")) return Logger.DEBUG; if (level.equalsIgnoreCase("TRACE")) return Logger.TRACE; if (level.equalsIgnoreCase("ALL")) return Logger.ALL; // This error is NOT logged the normal way because the logger constructor calls getLogLevel() and if this error occurred it would cause // an infinite loop. logSpecial("The LOG-LEVEL property in the ESAPI properties file has the unrecognized value: " + level, null); return Logger.WARNING; // Note: The default logging level is WARNING. } /** * {@inheritDoc} */ public String getLogFileName() { return properties.getProperty( LOG_FILE_NAME, "ESAPI_logging_file" ); } /** * The default max log file size is set to 10,000,000 bytes (10 Meg). If the current log file exceeds the current * max log file size, the logger will move the old log data into another log file. There currently is a max of * 1000 log files of the same name. If that is exceeded it will presumably start discarding the oldest logs. */ public static final int DEFAULT_MAX_LOG_FILE_SIZE = 10000000; /** * {@inheritDoc} */ public int getMaxLogFileSize() { // The default is 10 Meg if the property is not specified String value = properties.getProperty( MAX_LOG_FILE_SIZE ); if (value == null) return DEFAULT_MAX_LOG_FILE_SIZE; try { return Integer.parseInt(value); } catch (NumberFormatException e) { return DEFAULT_MAX_LOG_FILE_SIZE; } } /** * {@inheritDoc} */ public boolean getLogEncodingRequired() { String value = properties.getProperty( LOG_ENCODING_REQUIRED ); if ( value != null && value.equalsIgnoreCase("true")) return true; return false; // Default result } /** * {@inheritDoc} */ public String getResponseContentType() { return properties.getProperty( RESPONSE_CONTENT_TYPE, "text/html; charset=UTF-8" ); } /** * {@inheritDoc} */ public long getRememberTokenDuration() { String value = properties.getProperty( REMEMBER_TOKEN_DURATION, "14" ); long days = Long.parseLong( value ); long duration = 1000 * 60 * 60 * 24 * days; return duration; } /** * {@inheritDoc} */ public int getSessionIdleTimeoutLength() { String value = properties.getProperty( IDLE_TIMEOUT_DURATION, "20" ); int minutes = Integer.parseInt( value ); int duration = 1000 * 60 * minutes; return duration; } /** * {@inheritDoc} */ public int getSessionAbsoluteTimeoutLength() { String value = properties.getProperty( ABSOLUTE_TIMEOUT_DURATION, "120" ); int minutes = Integer.parseInt( value ); int duration = 1000 * 60 * minutes; return duration; } /** * getValidationPattern names returns validator pattern names * from ESAPI's global properties * * @return * a list iterator of pattern names */ public Iterator getValidationPatternNames() { TreeSet list = new TreeSet(); Iterator i = properties.keySet().iterator(); while( i.hasNext() ) { String name = (String)i.next(); if ( name.startsWith( "Validator.")) { list.add( name.substring(name.indexOf('.') + 1 ) ); } } return list.iterator(); } /** * getValidationPattern returns a single pattern based upon key * * @param key * validation pattern name you'd like * @return * if key exists, the associated validation pattern, null otherwise */ public Pattern getValidationPattern( String key ) { String value = properties.getProperty( "Validator." + key ); if ( value == null ) return null; Pattern pattern = Pattern.compile(value); return pattern; } }
package lic.swifter.box.activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.FrameLayout; import android.widget.ImageView; import com.yalantis.guillotine.animation.GuillotineAnimation; import java.lang.ref.WeakReference; import java.util.HashMap; import java.util.Map; import java.util.Vector; import lic.swifter.box.R; import lic.swifter.box.fragment.BaseFragment; import lic.swifter.box.fragment.IPQueryFragment; import lic.swifter.box.recycler.Divider; import lic.swifter.box.recycler.adapter.ToolsAdapter; import lic.swifter.box.util.FindUtil; import lic.swifter.box.util.ToastUtil; public class MainActivity extends AppCompatActivity implements ToolsAdapter.OnItemClickListener { private final int RIPPLE_DURATION = 250; private final int TIME_EXIT = 2000; private static final int WHAT_MESSAGE_EXIT = 1001; private FrameLayout rootFrame; private Toolbar toolBar; private ImageView openImage; private FrameLayout placeHolder; private View guillioView; private ImageView closeImage; private RecyclerView recycler; private GuillotineAnimation guillo; private ToolsAdapter toolsAdapter; private boolean readyExit; private int currentIndex = -1; private MainHandler handler; private Map<Integer, BaseFragment> fragmentMap; private static class MainHandler extends Handler { private WeakReference<MainActivity> activityWrapper; MainHandler(MainActivity activity) { activityWrapper = new WeakReference<>(activity); } @Override public void handleMessage(Message msg) { MainActivity activity = activityWrapper.get(); if (activity != null) { switch (msg.what) { case WHAT_MESSAGE_EXIT: activity.readyExit = false; break; } } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); handler = new MainHandler(this); } private void initView() { rootFrame = FindUtil.$(this, R.id.root_frame_layout); toolBar = FindUtil.$(rootFrame, R.id.toolbar); openImage = FindUtil.$(rootFrame, R.id.guillo_image_open); placeHolder = FindUtil.$(rootFrame, R.id.fragment_place_holder); setSupportActionBar(toolBar); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) actionBar.setTitle(null); guillioView = LayoutInflater.from(this).inflate(R.layout.guillio, rootFrame, false); rootFrame.addView(guillioView); recycler = FindUtil.$(guillioView, R.id.guillo_recycler); closeImage = FindUtil.$(guillioView, R.id.guillo_image_close); guillo = new GuillotineAnimation.GuillotineBuilder(guillioView, closeImage, openImage) .setStartDelay(RIPPLE_DURATION) .setActionBarViewForAnimation(toolBar) .setClosedOnStart(false) .build(); fragmentMap = new HashMap<>(); initRecyclerView(); test(); } private void initRecyclerView() { toolsAdapter = new ToolsAdapter(); toolsAdapter.setOnItemClickListener(this); recycler.setLayoutManager(new GridLayoutManager(this, 3)); recycler.addItemDecoration(new Divider(this)); recycler.setAdapter(toolsAdapter); } @Override public void onBackPressed() { if (!readyExit) { ToastUtil.showShort(this, R.string.ready_exit); readyExit = true; handler.sendEmptyMessageDelayed(WHAT_MESSAGE_EXIT, TIME_EXIT); return; } super.onBackPressed(); } @Override public void onItemClickListener(int position) { Log.i("swifter", "current = "+currentIndex+"; position = "+position); guillo.close(); if(currentIndex == position) return ; currentIndex = position; changeFragment(currentIndex); } private void test() { Vector<Object> vector = new Vector<>(); vector.add("aa"); vector.add("bb"); String[] strs = vector.toArray(new String[1]); Object a = "aa"; String b = (String) a; // Object[] ar = new Object[]{"aa", "bb"}; // String[] br = (String[]) ar; Log.i("swifter", "type of strs = "+strs); Log.i("swifter", "type of toArray() = "+vector.toArray()); } private void changeFragment(int index) { FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction transaction = fragmentManager.beginTransaction(); switch (index) { case 0: if(fragmentMap.get(index) == null) { fragmentMap.put(index, new IPQueryFragment()); } transaction.replace(R.id.fragment_place_holder, fragmentMap.get(index)); break; default: break; } transaction.commit(); } }
package org.pentaho.di.trans.steps.detectlastrow; import org.pentaho.di.core.Const; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.row.RowDataUtil; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStep; import org.pentaho.di.trans.step.StepDataInterface; import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; /** * Detect last row in a stream * * @author Samatar * @since 03June2008 */ public class DetectLastRow extends BaseStep implements StepInterface { private static Class<?> PKG = DetectLastRowMeta.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$ private DetectLastRowMeta meta; private DetectLastRowData data; private Object[] previousRow; public DetectLastRow(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans) { super(stepMeta, stepDataInterface, copyNr, transMeta, trans); } public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { meta=(DetectLastRowMeta)smi; data=(DetectLastRowData)sdi; Object[] r = getRow(); // Get row from input rowset & set row busy! if(first) { if (getInputRowMeta() == null) { setOutputDone(); return false; } // get the RowMeta data.previousRowMeta = getInputRowMeta().clone(); data.NrPrevFields = data.previousRowMeta.size(); data.outputRowMeta = data.previousRowMeta; meta.getFields(data.outputRowMeta, getStepname(), null, null, this); } Object[] outputRow=null; if (r==null) // no more input to be expected... { if(previousRow != null) { // Output the last row with last row indicator set to true. outputRow = RowDataUtil.addRowData(previousRow, getInputRowMeta().size(), data.getTrueArray()); putRow(data.outputRowMeta, outputRow); // copy row to output rowset(s); if (log.isRowLevel()) { logRowlevel(BaseMessages.getString(PKG, "DetectLastRow.Log.WroteRowToNextStep")+data.outputRowMeta.getString(outputRow)); //$NON-NLS-1$ } if (checkFeedback(getLinesRead())) { logBasic(BaseMessages.getString(PKG, "DetectLastRow.Log.LineNumber")+getLinesRead()); //$NON-NLS-1$ } } setOutputDone(); return false; } if(!first) { outputRow = RowDataUtil.addRowData(previousRow, getInputRowMeta().size(), data.getFalseArray()); putRow(data.outputRowMeta, outputRow); // copy row to output rowset(s); if (log.isRowLevel()) { logRowlevel(BaseMessages.getString(PKG, "DetectLastRow.Log.WroteRowToNextStep")+data.outputRowMeta.getString(outputRow)); //$NON-NLS-1$ } if (checkFeedback(getLinesRead())) { logBasic(BaseMessages.getString(PKG, "DetectLastRow.Log.LineNumber")+getLinesRead()); //$NON-NLS-1$ } } // keep track of the current row previousRow = r; if (first) first = false; return true; } public boolean init(StepMetaInterface smi, StepDataInterface sdi) { meta=(DetectLastRowMeta)smi; data=(DetectLastRowData)sdi; if (super.init(smi, sdi)) { if(Const.isEmpty(meta.getResultFieldName())) { log.logError(toString(), BaseMessages.getString(PKG, "DetectLastRow.Error.ResultFieldMissing")); return false; } return true; } return false; } public void dispose(StepMetaInterface smi, StepDataInterface sdi) { meta = (DetectLastRowMeta)smi; data = (DetectLastRowData)sdi; super.dispose(smi, sdi); } // Run is were the action happens! public void run() { BaseStep.runStepThread(this, meta, data); } }
package com.afollestad.silk.http; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; /** * @author Aidan Follestad (afollestad) */ public class SilkHttpException extends Exception { SilkHttpException(String msg) { super(msg); } SilkHttpException(Exception e) { super(e); mIsResponse = true; } SilkHttpException(HttpResponse response) { StatusLine stat = response.getStatusLine(); mStatus = stat.getStatusCode(); mReason = stat.getReasonPhrase(); } private int mStatus; private String mReason; private boolean mIsResponse; /** * Gets the status code returned from the HTTP request, this will only be set if {@link #isServerResponse()} returns true;. */ public int getStatusCode() { return mStatus; } /** * Gets the reason phrase for the value of {@link #getStatusCode()}. this will only be set if {@link #isServerResponse()} returns true. */ public String getReasonPhrase() { return mReason; } /** * Gets whether or not this exception was thrown for a non-200 HTTP response code, or if it was thrown for a code level Exception. */ public boolean isServerResponse() { return mIsResponse; } @Override public String getMessage() { if (isServerResponse()) return getStatusCode() + " " + getReasonPhrase(); return super.getMessage(); } }
package org.schemeway.plugins.schemescript.action; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITypedRegion; import org.eclipse.jface.text.Region; import org.schemeway.plugins.schemescript.editor.SchemeEditor; import org.schemeway.plugins.schemescript.indentation.SchemeIndentationContext; import org.schemeway.plugins.schemescript.indentation.SchemeIndentationStrategy; import org.schemeway.plugins.schemescript.parser.SexpNavigator; public class FormatAction extends SchemeAction { public FormatAction(SchemeEditor editor) { super(editor); setText("Format"); setToolTipText("Formats the current selection"); } public void run() { final SchemeEditor editor = getSchemeEditor(); if (editor == null) return; final Region selection = editor.getSelection(); final SexpNavigator explorer = editor.getExplorer(); final IDocument document = explorer.getDocument(); final SchemeIndentationContext context = new SchemeIndentationContext(explorer, editor.getIndentationManager(), 0); final int selectionOffset = selection.getOffset(); try { final int firstLine = document.getLineOfOffset(selectionOffset); final int lastLine = document.getLineOfOffset(selectionOffset + selection.getLength()); editor.runCompoundChange(new Runnable() { public void run() { indentLines(document, firstLine, lastLine, context); if (selection.getLength() == 0) { editor.setPoint(repositionPoint(document, selectionOffset, firstLine)); } } }); } catch (BadLocationException exception) { } } public static void indentLines(IDocument document, int firstLine, int lastLine, SchemeIndentationContext context) { try { for (int lineIndex = firstLine; lineIndex <= lastLine; lineIndex++) { indentLine(document, lineIndex, context); } } catch (BadLocationException exception) { } } public static void indentLine(IDocument document, int lineNo, SchemeIndentationContext context) throws BadLocationException { IRegion lineInfo = document.getLineInformation(lineNo); int lineOffset = lineInfo.getOffset(); int lineEnd = lineInfo.getLength() + lineOffset; ITypedRegion partition = document.getPartition(lineOffset); context.setOffset(lineOffset); // re-indent line if (partition.getType() == IDocument.DEFAULT_CONTENT_TYPE) { int newIndentation = SchemeIndentationStrategy.findIndentation(context); int oldIndentation = SchemeIndentationStrategy.indentationLength(document, lineOffset); String indentString = SchemeIndentationStrategy.makeIndentationString(newIndentation); if (indentString.length() != oldIndentation) { document.replace(lineOffset, oldIndentation, indentString); lineEnd += (indentString.length() - oldIndentation); } } // remove extra whitespace at end of line if (lineEnd > lineOffset) { removeExtraWhitespace(document, lineEnd - 1); } } private static void removeExtraWhitespace(IDocument document, int lineLastChar) throws BadLocationException { ITypedRegion partition; int index = lineLastChar; partition = document.getPartition(index); if (partition.getType() == IDocument.DEFAULT_CONTENT_TYPE) { char c = document.getChar(index); while (Character.isWhitespace(c) && !(c == '\n' || c == '\r')) { index c = document.getChar(index); } } if (index != lineLastChar) { document.replace(index + 1, (lineLastChar - index), ""); } } public static int repositionPoint(IDocument document, int initialPosition, int lineNo) { try { int lineOffset = document.getLineOffset(lineNo); int indentation = SchemeIndentationStrategy.indentationLength(document, lineOffset); if (initialPosition < lineOffset + indentation) { return lineOffset + indentation; } } catch (BadLocationException exception) { } return initialPosition; } }
package me.devsaki.hentoid.util; import static me.devsaki.hentoid.util.network.HttpHelper.HEADER_CONTENT_TYPE; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.util.Pair; import androidx.annotation.DrawableRes; import androidx.annotation.IntDef; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.documentfile.provider.DocumentFile; import com.annimon.stream.Optional; import com.annimon.stream.Stream; import com.google.firebase.crashlytics.FirebaseCrashlytics; import net.greypanther.natsort.CaseInsensitiveSimpleNaturalComparator; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.greenrobot.eventbus.EventBus; import org.threeten.bp.Instant; import java.io.File; import java.io.IOException; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Nonnull; import io.reactivex.disposables.Disposable; import io.reactivex.schedulers.Schedulers; import me.devsaki.hentoid.R; import me.devsaki.hentoid.activities.ImageViewerActivity; import me.devsaki.hentoid.activities.UnlockActivity; import me.devsaki.hentoid.activities.bundles.BaseWebActivityBundle; import me.devsaki.hentoid.activities.bundles.ImageViewerActivityBundle; import me.devsaki.hentoid.core.Consts; import me.devsaki.hentoid.database.CollectionDAO; import me.devsaki.hentoid.database.domains.Attribute; import me.devsaki.hentoid.database.domains.AttributeMap; import me.devsaki.hentoid.database.domains.Content; import me.devsaki.hentoid.database.domains.DuplicateEntry; import me.devsaki.hentoid.database.domains.Group; import me.devsaki.hentoid.database.domains.GroupItem; import me.devsaki.hentoid.database.domains.ImageFile; import me.devsaki.hentoid.database.domains.QueueRecord; import me.devsaki.hentoid.enums.AttributeType; import me.devsaki.hentoid.enums.Grouping; import me.devsaki.hentoid.enums.Site; import me.devsaki.hentoid.enums.StatusContent; import me.devsaki.hentoid.events.DownloadEvent; import me.devsaki.hentoid.json.JsonContent; import me.devsaki.hentoid.json.JsonContentCollection; import me.devsaki.hentoid.parsers.ContentParserFactory; import me.devsaki.hentoid.parsers.content.ContentParser; import me.devsaki.hentoid.util.exception.ContentNotRemovedException; import me.devsaki.hentoid.util.exception.FileNotRemovedException; import me.devsaki.hentoid.util.network.HttpHelper; import me.devsaki.hentoid.util.string_similarity.Cosine; import me.devsaki.hentoid.util.string_similarity.StringSimilarity; import okhttp3.Response; import okhttp3.ResponseBody; import pl.droidsonroids.jspoon.HtmlAdapter; import pl.droidsonroids.jspoon.Jspoon; import timber.log.Timber; /** * Utility class for Content-related operations */ public final class ContentHelper { @IntDef({QueuePosition.TOP, QueuePosition.BOTTOM}) @Retention(RetentionPolicy.SOURCE) public @interface QueuePosition { int TOP = Preferences.Constant.QUEUE_NEW_DOWNLOADS_POSITION_TOP; int BOTTOM = Preferences.Constant.QUEUE_NEW_DOWNLOADS_POSITION_BOTTOM; } private static final String UNAUTHORIZED_CHARS = "[^a-zA-Z0-9.-]"; private static final int[] libraryStatus = new int[]{StatusContent.DOWNLOADED.getCode(), StatusContent.MIGRATED.getCode(), StatusContent.EXTERNAL.getCode(), StatusContent.ONLINE.getCode()}; private static final int[] queueStatus = new int[]{StatusContent.DOWNLOADING.getCode(), StatusContent.PAUSED.getCode(), StatusContent.ERROR.getCode()}; private static final int[] queueTabStatus = new int[]{StatusContent.DOWNLOADING.getCode(), StatusContent.PAUSED.getCode()}; // TODO empty this cache at some point private static final Map<String, String> fileNameMatchCache = new HashMap<>(); private ContentHelper() { throw new IllegalStateException("Utility class"); } public static int[] getLibraryStatuses() { return libraryStatus; } public static boolean isInLibrary(@NonNull final StatusContent status) { return Helper.getListFromPrimitiveArray(libraryStatus).contains(status.getCode()); } public static int[] getQueueStatuses() { return queueStatus; } public static int[] getQueueTabStatuses() { return queueTabStatus; } public static boolean isInQueue(@NonNull final StatusContent status) { return Helper.getListFromPrimitiveArray(queueStatus).contains(status.getCode()); } private static boolean isInQueueTab(@NonNull final StatusContent status) { return Helper.getListFromPrimitiveArray(queueTabStatus).contains(status.getCode()); } /** * Open the app's web browser to view the given Content's gallery page * * @param context Context to use for the action * @param content Content to view */ public static void viewContentGalleryPage(@NonNull final Context context, @NonNull Content content) { viewContentGalleryPage(context, content, false); } /** * Open the app's web browser to view the given Content's gallery page * * @param context Context to use for the action * @param content Content to view * @param wrapPin True if the intent should be wrapped with PIN protection */ public static void viewContentGalleryPage(@NonNull final Context context, @NonNull Content content, boolean wrapPin) { if (content.getSite().equals(Site.NONE)) return; Intent intent = new Intent(context, Content.getWebActivityClass(content.getSite())); BaseWebActivityBundle.Builder builder = new BaseWebActivityBundle.Builder(); builder.setUrl(content.getGalleryUrl()); intent.putExtras(builder.getBundle()); if (wrapPin) intent = UnlockActivity.wrapIntent(context, intent); context.startActivity(intent); } /** * Update the given Content's JSON file with its current values * * @param context Context to use for the action * @param content Content whose JSON file to update */ public static void updateContentJson(@NonNull Context context, @NonNull Content content) { Helper.assertNonUiThread(); DocumentFile file = FileHelper.getFileFromSingleUriString(context, content.getJsonUri()); if (null == file) throw new IllegalArgumentException("'" + content.getJsonUri() + "' does not refer to a valid file"); try { JsonHelper.updateJson(context, JsonContent.fromEntity(content), JsonContent.class, file); } catch (IOException e) { Timber.e(e, "Error while writing to %s", content.getJsonUri()); } } /** * Create the given Content's JSON file and populate it with its current values * * @param content Content whose JSON file to create */ public static void createContentJson(@NonNull Context context, @NonNull Content content) { Helper.assertNonUiThread(); if (content.isArchive()) return; // Keep that as is, we can't find the parent folder anyway DocumentFile folder = FileHelper.getFolderFromTreeUriString(context, content.getStorageUri()); if (null == folder) return; try { JsonHelper.jsonToFile(context, JsonContent.fromEntity(content), JsonContent.class, folder); } catch (IOException e) { Timber.e(e, "Error while writing to %s", content.getStorageUri()); } } /** * Update the JSON file that stores the queue with the current contents of the queue * * @param context Context to be used * @param dao DAO to be used * @return True if the queue JSON file has been updated properly; false instead */ public static boolean updateQueueJson(@NonNull Context context, @NonNull CollectionDAO dao) { Helper.assertNonUiThread(); List<QueueRecord> queue = dao.selectQueue(); List<Content> errors = dao.selectErrorContentList(); // Save current queue (to be able to restore it in case the app gets uninstalled) List<Content> queuedContent = Stream.of(queue).map(qr -> qr.getContent().getTarget()).withoutNulls().toList(); if (errors != null) queuedContent.addAll(errors); JsonContentCollection contentCollection = new JsonContentCollection(); contentCollection.setQueue(queuedContent); DocumentFile rootFolder = FileHelper.getFolderFromTreeUriString(context, Preferences.getStorageUri()); if (null == rootFolder) return false; try { JsonHelper.jsonToFile(context, contentCollection, JsonContentCollection.class, rootFolder, Consts.QUEUE_JSON_FILE_NAME); } catch (IOException | IllegalArgumentException e) { // even though all the file existence checks are in place // ("Failed to determine if primary:.Hentoid/queue.json is child of primary:.Hentoid: java.io.FileNotFoundException: Missing file for primary:.Hentoid/queue.json at /storage/emulated/0/.Hentoid/queue.json") Timber.e(e); FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance(); crashlytics.recordException(e); return false; } return true; } /** * Open the given Content in the built-in image viewer * * @param context Context to use for the action * @param content Content to view * @param pageNumber Page number to view * @param searchParams Current search parameters (so that the next/previous book feature * is faithful to the library screen's order) */ public static boolean openHentoidViewer(@NonNull Context context, @NonNull Content content, int pageNumber, Bundle searchParams) { // Check if the book has at least its own folder if (content.getStorageUri().isEmpty()) return false; Timber.d("Opening: %s from: %s", content.getTitle(), content.getStorageUri()); ImageViewerActivityBundle.Builder builder = new ImageViewerActivityBundle.Builder(); builder.setContentId(content.getId()); if (searchParams != null) builder.setSearchParams(searchParams); if (pageNumber > -1) builder.setPageNumber(pageNumber); Intent viewer = new Intent(context, ImageViewerActivity.class); viewer.putExtras(builder.getBundle()); context.startActivity(viewer); return true; } /** * Update the given Content's number of reads in both DB and JSON file * * @param context Context to use for the action * @param dao DAO to use for the action * @param content Content to update */ public static void updateContentReadStats( @NonNull Context context, @Nonnull CollectionDAO dao, @NonNull Content content, @NonNull List<ImageFile> images, int targetLastReadPageIndex, boolean updateReads) { content.setLastReadPageIndex(targetLastReadPageIndex); if (updateReads) content.increaseReads().setLastReadDate(Instant.now().toEpochMilli()); dao.replaceImageList(content.getId(), images); dao.insertContent(content); if (!content.getJsonUri().isEmpty()) updateContentJson(context, content); else createContentJson(context, content); } /** * Find the picture files for the given Content * NB1 : Pictures with non-supported formats are not included in the results * NB2 : Cover picture is not included in the results * * @param content Content to retrieve picture files for * @return List of picture files */ public static List<DocumentFile> getPictureFilesFromContent(@NonNull final Context context, @NonNull final Content content) { Helper.assertNonUiThread(); String storageUri = content.getStorageUri(); Timber.d("Opening: %s from: %s", content.getTitle(), storageUri); DocumentFile folder = FileHelper.getFolderFromTreeUriString(context, storageUri); if (null == folder) { Timber.d("File not found!! Exiting method."); return new ArrayList<>(); } return FileHelper.listFoldersFilter(context, folder, displayName -> (displayName.toLowerCase().startsWith(Consts.THUMB_FILE_NAME) && ImageHelper.isImageExtensionSupported(FileHelper.getExtension(displayName)) ) ); } /** * Remove the given Content from the disk and the DB * * @param context Context to be used * @param dao DAO to be used * @param content Content to be removed * @throws ContentNotRemovedException in case an issue prevents the content from being actually removed */ public static void removeContent(@NonNull Context context, @NonNull CollectionDAO dao, @NonNull Content content) throws ContentNotRemovedException { Helper.assertNonUiThread(); // Remove from DB // NB : start with DB to have a LiveData feedback, because file removal can take much time dao.deleteContent(content); if (content.isArchive()) { // Remove an archive DocumentFile archive = FileHelper.getFileFromSingleUriString(context, content.getStorageUri()); if (null == archive) throw new FileNotRemovedException(content, "Failed to find archive " + content.getStorageUri()); if (archive.delete()) { Timber.i("Archive removed : %s", content.getStorageUri()); } else { throw new FileNotRemovedException(content, "Failed to delete archive " + content.getStorageUri()); } // Remove the cover stored in the app's persistent folder File appFolder = context.getFilesDir(); File[] images = appFolder.listFiles((dir, name) -> FileHelper.getFileNameWithoutExtension(name).equals(content.getId() + "")); if (images != null) for (File f : images) FileHelper.removeFile(f); } else if (/*isInLibrary(content.getStatus()) &&*/ !content.getStorageUri().isEmpty()) { // Remove a folder and its content // If the book has just starting being downloaded and there are no complete pictures on memory yet, it has no storage folder => nothing to delete DocumentFile folder = FileHelper.getFolderFromTreeUriString(context, content.getStorageUri()); if (null == folder) throw new FileNotRemovedException(content, "Failed to find directory " + content.getStorageUri()); if (folder.delete()) { Timber.i("Directory removed : %s", content.getStorageUri()); } else { throw new FileNotRemovedException(content, "Failed to delete directory " + content.getStorageUri()); } } } /** * Remove the given Content from the queue, disk and the DB * * @param context Context to be used * @param dao DAO to be used * @param content Content to be removed * @throws ContentNotRemovedException in case an issue prevents the content from being actually removed */ public static void removeQueuedContent(@NonNull Context context, @NonNull CollectionDAO dao, @NonNull Content content) throws ContentNotRemovedException { Helper.assertNonUiThread(); // Check if the content is on top of the queue; if so, send a CANCEL event if (isInQueueTab(content.getStatus())) { List<QueueRecord> queue = dao.selectQueue(); if (!queue.isEmpty() && queue.get(0).getContent().getTargetId() == content.getId()) EventBus.getDefault().post(new DownloadEvent(content, DownloadEvent.EV_CANCEL)); // Remove from queue dao.deleteQueue(content); } // Remove content itself removeContent(context, dao, content); } /** * Add new content to the library * * @param dao DAO to be used * @param content Content to add to the library * @return ID of the newly added Content */ public static long addContent( @NonNull final Context context, @NonNull final CollectionDAO dao, @NonNull final Content content) { long newContentId = dao.insertContent(content); content.setId(newContentId); // Perform group operations only if // - the book is in the library (i.e. not queued) // - the book is linked to no group from the given grouping if (Helper.getListFromPrimitiveArray(libraryStatus).contains(content.getStatus().getCode())) { List<Grouping> staticGroupings = Stream.of(Grouping.values()).filter(Grouping::canReorderBooks).toList(); for (Grouping g : staticGroupings) if (content.getGroupItems(g).isEmpty()) { if (g.equals(Grouping.ARTIST)) { int nbGroups = (int) dao.countGroupsFor(g); AttributeMap attrs = content.getAttributeMap(); List<Attribute> artists = new ArrayList<>(); List<Attribute> sublist = attrs.get(AttributeType.ARTIST); if (sublist != null) artists.addAll(sublist); sublist = attrs.get(AttributeType.CIRCLE); if (sublist != null) artists.addAll(sublist); if (artists.isEmpty()) { // Add to the "no artist" group if no artist has been found Group group = GroupHelper.getOrCreateNoArtistGroup(context, dao); GroupItem item = new GroupItem(content, group, -1); dao.insertGroupItem(item); } else { for (Attribute a : artists) { // Add to the artist groups attached to the artists attributes Group group = a.getGroup().getTarget(); if (null == group) { group = new Group(Grouping.ARTIST, a.getName(), ++nbGroups); group.setSubtype(a.getType().equals(AttributeType.ARTIST) ? Preferences.Constant.ARTIST_GROUP_VISIBILITY_ARTISTS : Preferences.Constant.ARTIST_GROUP_VISIBILITY_GROUPS); if (!a.contents.isEmpty()) group.picture.setTarget(a.contents.get(0).getCover()); } GroupHelper.addContentToAttributeGroup(dao, group, a, content); } } } } } // Extract the cover to the app's persistent folder if the book is an archive if (content.isArchive() && content.getImageFiles() != null) { DocumentFile archive = FileHelper.getFileFromSingleUriString(context, content.getStorageUri()); if (archive != null) { try { Disposable unarchiveDisposable = ArchiveHelper.extractArchiveEntriesRx( context, archive, Stream.of(content.getCover().getFileUri().replace(content.getStorageUri() + File.separator, "")).toList(), context.getFilesDir(), Stream.of(newContentId + "").toList(), null) .subscribeOn(Schedulers.io()) .observeOn(Schedulers.computation()) .subscribe( uri -> { Timber.i(">> Set cover for %s", content.getTitle()); content.getCover().setFileUri(uri.toString()); dao.replaceImageList(newContentId, content.getImageFiles()); }, Timber::e ); // Not ideal, but better than attaching it to the calling service that may not have enough longevity new Helper.LifecycleRxCleaner(unarchiveDisposable).publish(); } catch (IOException e) { Timber.w(e); } } } return newContentId; } /** * Remove the given pages from the disk and the DB * * @param images Pages to be removed * @param dao DAO to be used * @param context Context to be used */ public static void removePages(@NonNull List<ImageFile> images, @NonNull CollectionDAO dao, @NonNull final Context context) { Helper.assertNonUiThread(); // Remove from DB // NB : start with DB to have a LiveData feedback, because file removal can take much time dao.deleteImageFiles(images); // Remove the pages from disk for (ImageFile image : images) FileHelper.removeFile(context, Uri.parse(image.getFileUri())); // Lists all relevant content List<Long> contents = Stream.of(images).filter(i -> i.getContent() != null).map(i -> i.getContent().getTargetId()).distinct().toList(); // Update content JSON if it exists (i.e. if book is not queued) for (Long contentId : contents) { Content content = dao.selectContent(contentId); if (content != null && !content.getJsonUri().isEmpty()) updateContentJson(context, content); } } /** * Define a new cover among a Content's ImageFiles * * @param newCover ImageFile to be used as a cover for the Content it is related to * @param dao DAO to be used * @param context Context to be used */ public static void setContentCover(@NonNull ImageFile newCover, @NonNull CollectionDAO dao, @NonNull final Context context) { Helper.assertNonUiThread(); // Get all images from the DB Content content = dao.selectContent(newCover.getContent().getTargetId()); if (null == content) return; List<ImageFile> images = content.getImageFiles(); if (null == images) return; // Remove current cover from the set for (int i = 0; i < images.size(); i++) if (images.get(i).isCover()) { images.remove(i); break; } // Duplicate given picture and set it as a cover ImageFile cover = ImageFile.newCover(newCover.getUrl(), newCover.getStatus()).setFileUri(newCover.getFileUri()).setMimeType(newCover.getMimeType()); images.add(0, cover); // Update cover URL to "ping" the content to be updated too (useful for library screen that only detects "direct" content updates) content.setCoverImageUrl(newCover.getUrl()); // Update the whole list dao.insertContent(content); // Update content JSON if it exists (i.e. if book is not queued) if (!content.getJsonUri().isEmpty()) updateContentJson(context, content); } /** * Create the download directory of the given content * * @param context Context * @param content Content for which the directory to create * @return Created directory */ @Nullable public static DocumentFile getOrCreateContentDownloadDir(@NonNull Context context, @NonNull Content content) { DocumentFile siteDownloadDir = getOrCreateSiteDownloadDir(context, null, content.getSite()); if (null == siteDownloadDir) return null; ImmutablePair<String, String> bookFolderName = formatBookFolderName(content); // First try finding the folder with new naming... DocumentFile bookFolder = FileHelper.findFolder(context, siteDownloadDir, bookFolderName.left); if (null == bookFolder) { // ...then with old (sanitized) naming... bookFolder = FileHelper.findFolder(context, siteDownloadDir, bookFolderName.right); if (null == bookFolder) { // ...if not, create a new folder with the new naming... DocumentFile result = siteDownloadDir.createDirectory(bookFolderName.left); if (null == result) { // ...if it fails, create a new folder with the old naming return siteDownloadDir.createDirectory(bookFolderName.right); } else return result; } } return bookFolder; } /** * Format the download directory path of the given content according to current user preferences * * @param content Content to get the path from * @return Pair containing the canonical naming of the given content : * - Left side : Naming convention allowing non-ANSI characters * - Right side : Old naming convention with ANSI characters alone */ public static ImmutablePair<String, String> formatBookFolderName(@NonNull final Content content) { String title = content.getTitle(); title = (null == title) ? "" : title; String author = formatBookAuthor(content).toLowerCase(); return new ImmutablePair<>( formatBookFolderName(content, FileHelper.cleanFileName(title), FileHelper.cleanFileName(author)), formatBookFolderName(content, title.replaceAll(UNAUTHORIZED_CHARS, "_"), author.replaceAll(UNAUTHORIZED_CHARS, "_")) ); } private static String formatBookFolderName(@NonNull final Content content, @NonNull final String title, @NonNull final String author) { String result = ""; switch (Preferences.getFolderNameFormat()) { case Preferences.Constant.FOLDER_NAMING_CONTENT_TITLE_ID: result += title; break; case Preferences.Constant.FOLDER_NAMING_CONTENT_AUTH_TITLE_ID: result += author + " - " + title; break; case Preferences.Constant.FOLDER_NAMING_CONTENT_TITLE_AUTH_ID: result += title + " - " + author; break; } result += " - "; // Unique content ID String suffix = formatBookId(content); // Truncate folder dir to something manageable for Windows // If we are to assume NTFS and Windows, then the fully qualified file, with it's drivename, path, filename, and extension, altogether is limited to 260 characters. int truncLength = Preferences.getFolderTruncationNbChars(); int titleLength = result.length(); if (truncLength > 0 && titleLength + suffix.length() > truncLength) result = result.substring(0, truncLength - suffix.length() - 1); // We always add the unique ID at the end of the folder name to avoid collisions between two books with the same title from the same source // (e.g. different scans, different languages) result += suffix; return result; } /** * Format the Content ID for folder naming purposes * * @param content Content whose ID to format * @return Formatted Content ID */ @SuppressWarnings("squid:S2676") // Math.abs is used for formatting purposes only public static String formatBookId(@NonNull final Content content) { String id = content.getUniqueSiteId(); // For certain sources (8muses, fakku), unique IDs are strings that may be very long // => shorten them by using their hashCode if (id.length() > 10) id = StringHelper.formatIntAsStr(Math.abs(id.hashCode()), 10); return "[" + id + "]"; } public static String formatBookAuthor(@NonNull final Content content) { String result = ""; AttributeMap attrMap = content.getAttributeMap(); // Try and get first Artist List<Attribute> artistAttributes = attrMap.get(AttributeType.ARTIST); if (artistAttributes != null && !artistAttributes.isEmpty()) result = artistAttributes.get(0).getName(); // If no Artist found, try and get first Circle if (null == result || result.isEmpty()) { List<Attribute> circleAttributes = attrMap.get(AttributeType.CIRCLE); if (circleAttributes != null && !circleAttributes.isEmpty()) result = circleAttributes.get(0).getName(); } return StringHelper.protect(result); } /** * Return the given site's download directory. Create it if it doesn't exist. * * @param context Context to use for the action * @param site Site to get the download directory for * @return Download directory of the given Site */ @Nullable static DocumentFile getOrCreateSiteDownloadDir(@NonNull Context context, @Nullable FileExplorer explorer, @NonNull Site site) { String appUriStr = Preferences.getStorageUri(); if (appUriStr.isEmpty()) { Timber.e("No storage URI defined for the app"); return null; } DocumentFile appFolder = DocumentFile.fromTreeUri(context, Uri.parse(appUriStr)); if (null == appFolder || !appFolder.exists()) { Timber.e("App folder %s does not exist", appUriStr); return null; } String siteFolderName = site.getFolder(); DocumentFile siteFolder; if (null == explorer) siteFolder = FileHelper.findFolder(context, appFolder, siteFolderName); else siteFolder = explorer.findFolder(context, appFolder, siteFolderName); if (null == siteFolder) // Create return appFolder.createDirectory(siteFolderName); else return siteFolder; } /** * Open the "share with..." Android dialog for the given Content * * @param context Context to use for the action * @param item Content to share */ public static void shareContent(@NonNull final Context context, @NonNull final Content item) { String url = item.getGalleryUrl(); Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_SUBJECT, item.getTitle()); intent.putExtra(Intent.EXTRA_TEXT, url); context.startActivity(Intent.createChooser(intent, context.getString(R.string.send_to))); } /** * Parse the given download parameters string into a map of strings * * @param downloadParamsStr String representation of the download parameters to parse * @return Map of strings describing the given download parameters */ public static Map<String, String> parseDownloadParams(final String downloadParamsStr) { // Handle empty and {} if (null == downloadParamsStr || downloadParamsStr.trim().length() <= 2) return new HashMap<>(); try { return JsonHelper.jsonToObject(downloadParamsStr, JsonHelper.MAP_STRINGS); } catch (IOException e) { Timber.w(e); } return new HashMap<>(); } /** * Remove the leading zeroes and the file extension of the given string * * @param s String to be cleaned * @return Input string, without leading zeroes and extension */ private static String removeLeadingZeroesAndExtension(@Nullable String s) { if (null == s) return ""; int beginIndex = 0; if (s.startsWith("0")) beginIndex = -1; for (int i = 0; i < s.length(); i++) { if (-1 == beginIndex && s.charAt(i) != '0') beginIndex = i; if ('.' == s.charAt(i)) return s.substring(beginIndex, i); } return (-1 == beginIndex) ? "0" : s.substring(beginIndex); } /** * Remove the leading zeroes and the file extension of the given string using cached results * * @param s String to be cleaned * @return Input string, without leading zeroes and extension */ private static String removeLeadingZeroesAndExtensionCached(String s) { if (fileNameMatchCache.containsKey(s)) return fileNameMatchCache.get(s); else { String result = removeLeadingZeroesAndExtension(s); fileNameMatchCache.put(s, result); return result; } } /** * Matches the given files to the given ImageFiles according to their name (without leading zeroes nor file extension) * * @param files Files to be matched to the given ImageFiles * @param images ImageFiles to be matched to the given files * @return List of matched ImageFiles, with the Uri of the matching file */ public static List<ImageFile> matchFilesToImageList(@NonNull final List<DocumentFile> files, @NonNull final List<ImageFile> images) { Map<String, ImmutablePair<String, Long>> fileNameProperties = new HashMap<>(files.size()); List<ImageFile> result = new ArrayList<>(); boolean coverFound = false; // Put file names into a Map to speed up the lookup for (DocumentFile file : files) fileNameProperties.put(removeLeadingZeroesAndExtensionCached(file.getName()), new ImmutablePair<>(file.getUri().toString(), file.length())); // Look up similar names between images and file names for (ImageFile img : images) { String imgName = removeLeadingZeroesAndExtensionCached(img.getName()); ImmutablePair<String, Long> property = fileNameProperties.get(imgName); if (property != null) { if (imgName.equals(Consts.THUMB_FILE_NAME)) { coverFound = true; img.setIsCover(true); } result.add(img.setFileUri(property.left).setSize(property.right).setStatus(StatusContent.DOWNLOADED)); } else Timber.i(">> img dropped %s", imgName); } // If no thumb found, set the 1st image as cover if (!coverFound && !result.isEmpty()) result.get(0).setIsCover(true); return result; } /** * Create the list of ImageFiles from the given folder * * @param context Context to be used * @param folder Folder to read the images from * @return List of ImageFiles corresponding to all supported pictures inside the given folder, sorted numerically then alphabetically */ public static List<ImageFile> createImageListFromFolder(@NonNull final Context context, @NonNull final DocumentFile folder) { List<DocumentFile> imageFiles = FileHelper.listFiles(context, folder, ImageHelper.getImageNamesFilter()); if (!imageFiles.isEmpty()) return createImageListFromFiles(imageFiles); else return Collections.emptyList(); } /** * Create the list of ImageFiles from the given files * * @param files Files to find images into * @return List of ImageFiles corresponding to all supported pictures among the given files, sorted numerically then alphabetically */ public static List<ImageFile> createImageListFromFiles(@NonNull final List<DocumentFile> files) { return createImageListFromFiles(files, StatusContent.DOWNLOADED, 0, ""); } /** * Create the list of ImageFiles from the given files * * @param files Files to find images into * @param targetStatus Target status of the ImageFiles to create * @param startingOrder Starting order of the ImageFiles to create * @param namePrefix Prefix to add in front of the name of the ImageFiles to create * @return List of ImageFiles corresponding to all supported pictures among the given files, sorted numerically then alphabetically */ public static List<ImageFile> createImageListFromFiles( @NonNull final List<DocumentFile> files, @NonNull final StatusContent targetStatus, int startingOrder, @NonNull final String namePrefix) { Helper.assertNonUiThread(); List<ImageFile> result = new ArrayList<>(); int order = startingOrder; boolean coverFound = false; // Sort files by anything that resembles a number inside their names List<DocumentFile> fileList = Stream.of(files).withoutNulls().sorted(new InnerNameNumberFileComparator()).toList(); for (DocumentFile f : fileList) { String name = namePrefix + ((f.getName() != null) ? f.getName() : ""); ImageFile img = new ImageFile(); if (name.startsWith(Consts.THUMB_FILE_NAME)) { coverFound = true; img.setIsCover(true); } else order++; img.setName(FileHelper.getFileNameWithoutExtension(name)).setOrder(order).setUrl(f.getUri().toString()).setStatus(targetStatus).setFileUri(f.getUri().toString()).setSize(f.length()); img.setMimeType(FileHelper.getMimeTypeFromFileName(name)); result.add(img); } // If no thumb found, set the 1st image as cover if (!coverFound && !result.isEmpty()) result.get(0).setIsCover(true); return result; } /** * Create a list of ImageFiles from the given archive entries * * @param archiveFileUri Uri of the archive file the entries have been read from * @param files Entries to create the ImageFile list with * @param targetStatus Target status of the ImageFiles * @param startingOrder Starting order of the first ImageFile to add; will be numbered incrementally from that number on * @param namePrefix Prefix to add to image names * @return List of ImageFiles contructed from the given parameters */ public static List<ImageFile> createImageListFromArchiveEntries( @NonNull final Uri archiveFileUri, @NonNull final List<ArchiveHelper.ArchiveEntry> files, @NonNull final StatusContent targetStatus, int startingOrder, @NonNull final String namePrefix) { Helper.assertNonUiThread(); List<ImageFile> result = new ArrayList<>(); int order = startingOrder; // Sort files by anything that resembles a number inside their names (default entry order from ZipInputStream is chaotic) List<ArchiveHelper.ArchiveEntry> fileList = Stream.of(files).withoutNulls().sorted(new InnerNameNumberArchiveComparator()).toList(); for (ArchiveHelper.ArchiveEntry f : fileList) { String name = namePrefix + f.path; String path = archiveFileUri.toString() + File.separator + f.path; ImageFile img = new ImageFile(); if (name.startsWith(Consts.THUMB_FILE_NAME)) img.setIsCover(true); else order++; img.setName(FileHelper.getFileNameWithoutExtension(name)).setOrder(order).setUrl(path).setStatus(targetStatus).setFileUri(path).setSize(f.size); img.setMimeType(FileHelper.getMimeTypeFromFileName(name)); result.add(img); } return result; } /** * Launch the web browser for the given site and URL * TODO make sure the URL and the site are compatible * * @param context COntext to be used * @param s Site to navigate to * @param targetUrl Url to navigate to */ public static void launchBrowserFor(@NonNull final Context context, @NonNull final Site s, @NonNull final String targetUrl) { Intent intent = new Intent(context, Content.getWebActivityClass(s)); BaseWebActivityBundle.Builder builder = new BaseWebActivityBundle.Builder(); builder.setUrl(targetUrl); intent.putExtras(builder.getBundle()); context.startActivity(intent); } /** * Get the blocked tags of the given Content * NB : Blocked tags are detected according to the current app Preferences * * @param content Content to extract blocked tags from * @return List of blocked tags from the given Content */ public static List<String> getBlockedTags(@NonNull final Content content) { List<String> result = Collections.emptyList(); if (!Preferences.getBlockedTags().isEmpty()) { List<String> tags = Stream.of(content.getAttributes()) .filter(a -> a.getType().equals(AttributeType.TAG) || a.getType().equals(AttributeType.LANGUAGE)) .map(Attribute::getName) .toList(); for (String blocked : Preferences.getBlockedTags()) for (String tag : tags) if (blocked.equalsIgnoreCase(tag) || StringHelper.isPresentAsWord(blocked, tag)) { if (result.isEmpty()) result = new ArrayList<>(); result.add(tag); break; } } return result; } /** * Update the given content's properties by parsing its webpage * * @param content Content to parse again from its online source * @return Content updated from its online source, or Optional.empty when something went wrong * @throws IOException If something horrible happens during parsing */ public static Optional<Content> reparseFromScratch(@NonNull final Content content) throws IOException { return reparseFromScratch(content, content.getGalleryUrl()); } /** * Parse the given webpage to update the given Content's properties * * @param content Content which properties to update * @param url Webpage to parse to update the given Content's properties * @return Content with updated properties, or Optional.empty when something went wrong * @throws IOException If something horrible happens during parsing */ private static Optional<Content> reparseFromScratch(@NonNull final Content content, @NonNull final String url) throws IOException { Helper.assertNonUiThread(); String readerUrl = content.getReaderUrl(); List<Pair<String, String>> requestHeadersList = new ArrayList<>(); requestHeadersList.add(new Pair<>(HttpHelper.HEADER_REFERER_KEY, readerUrl)); String cookieStr = HttpHelper.getCookies(url, requestHeadersList, content.getSite().useMobileAgent(), content.getSite().useHentoidAgent(), content.getSite().useWebviewAgent()); if (!cookieStr.isEmpty()) requestHeadersList.add(new Pair<>(HttpHelper.HEADER_COOKIE_KEY, cookieStr)); Response response = HttpHelper.getOnlineResource(url, requestHeadersList, content.getSite().useMobileAgent(), content.getSite().useHentoidAgent(), content.getSite().useWebviewAgent()); // Scram if the response is a redirection or an error if (response.code() >= 300) return Optional.empty(); // Scram if the response is something else than html Pair<String, String> contentType = HttpHelper.cleanContentType(StringHelper.protect(response.header(HEADER_CONTENT_TYPE, ""))); if (!contentType.first.isEmpty() && !contentType.first.equals("text/html")) return Optional.empty(); // Scram if the response is empty ResponseBody body = response.body(); if (null == body) return Optional.empty(); Class<? extends ContentParser> c = ContentParserFactory.getInstance().getContentParserClass(content.getSite()); final Jspoon jspoon = Jspoon.create(); HtmlAdapter<? extends ContentParser> htmlAdapter = jspoon.adapter(c); // Unchecked but alright ContentParser contentParser = htmlAdapter.fromInputStream(body.byteStream(), new URL(url)); Content newContent = contentParser.update(content, url); if (newContent.getStatus() != null && newContent.getStatus().equals(StatusContent.IGNORED)) { String canonicalUrl = contentParser.getCanonicalUrl(); if (!canonicalUrl.isEmpty() && !canonicalUrl.equalsIgnoreCase(url)) return reparseFromScratch(content, canonicalUrl); else return Optional.empty(); } // Save cookies for future calls during download Map<String, String> params = new HashMap<>(); if (!cookieStr.isEmpty()) params.put(HttpHelper.HEADER_COOKIE_KEY, cookieStr); newContent.setDownloadParams(JsonHelper.serializeToJson(params, JsonHelper.MAP_STRINGS)); return Optional.of(newContent); } /** * Remove all files (including JSON and cover thumb) from the given Content's folder * The folder itself is left empty * <p> * Caution : exec time is long * * @param context Context to use * @param content Content to remove files from */ public static void purgeFiles(@NonNull final Context context, @NonNull final Content content, boolean removeJson) { DocumentFile bookFolder = FileHelper.getFolderFromTreeUriString(context, content.getStorageUri()); if (bookFolder != null) { List<DocumentFile> files = FileHelper.listFiles(context, bookFolder, null); if (!files.isEmpty()) for (DocumentFile file : files) if (removeJson || !HttpHelper.getExtensionFromUri(file.getUri().toString()).toLowerCase().endsWith("json")) file.delete(); } } /** * Format the given Content's tags for display * * @param content Content to get the formatted tags for * @return Given Content's tags formatted for display */ public static String formatTagsForDisplay(@NonNull final Content content) { List<Attribute> tagsAttributes = content.getAttributeMap().get(AttributeType.TAG); if (tagsAttributes == null) return ""; List<String> allTags = new ArrayList<>(); for (Attribute attribute : tagsAttributes) { allTags.add(attribute.getName()); } if (Build.VERSION.SDK_INT >= 24) { allTags.sort(null); } return android.text.TextUtils.join(", ", allTags); } /** * Get the resource ID for the given Content's language flag * * @param context Context to use * @param content Content to get the flag resource ID for * @return Resource ID (DrawableRes) of the given Content's language flag; 0 if no matching flag found */ public static @DrawableRes int getFlagResourceId(@NonNull final Context context, @NonNull final Content content) { List<Attribute> langAttributes = content.getAttributeMap().get(AttributeType.LANGUAGE); if (langAttributes != null && !langAttributes.isEmpty()) for (Attribute lang : langAttributes) { @DrawableRes int resId = LanguageHelper.getFlagFromLanguage(context, lang.getName()); if (resId != 0) return resId; } return 0; } /** * Format the given Content's artists for display * * @param context Context to use * @param content Content to get the formatted artists for * @return Given Content's artists formatted for display */ public static String formatArtistForDisplay(@NonNull final Context context, @NonNull final Content content) { List<Attribute> attributes = new ArrayList<>(); List<Attribute> artistAttributes = content.getAttributeMap().get(AttributeType.ARTIST); if (artistAttributes != null) attributes.addAll(artistAttributes); List<Attribute> circleAttributes = content.getAttributeMap().get(AttributeType.CIRCLE); if (circleAttributes != null) attributes.addAll(circleAttributes); if (attributes.isEmpty()) { return context.getString(R.string.work_artist, context.getResources().getString(R.string.work_untitled)); } else { List<String> allArtists = new ArrayList<>(); for (Attribute attribute : attributes) { allArtists.add(attribute.getName()); } String artists = android.text.TextUtils.join(", ", allArtists); return context.getString(R.string.work_artist, artists); } } /** * Find the best match for the given Content inside the library and queue * * @param content Content to find the duplicate for * // TOD update * @param dao CollectionDao to use * @return Pair containing * left side : Best match for the given Content inside the library and queue * Right side : Similarity score (between 0 and 1; 1=100%) */ @Nullable public static ImmutablePair<Content, Float> findDuplicate( @NonNull final Context context, @NonNull final Content content, long pHash, @NonNull final CollectionDAO dao) { // First find good rough candidates by searching for the longest word in the title String[] words = StringHelper.cleanMultipleSpaces(StringHelper.cleanup(content.getTitle())).split(" "); Optional<String> longestWord = Stream.of(words).sorted((o1, o2) -> Integer.compare(o1.length(), o2.length())).findLast(); if (longestWord.isEmpty()) return null; int[] contentStatuses = ArrayUtils.addAll(libraryStatus, queueTabStatus); List<Content> roughCandidates = dao.searchTitlesWith(longestWord.get(), contentStatuses); if (roughCandidates.isEmpty()) return null; // Compute cover hashes for selected candidates for (Content c : roughCandidates) if (0 == c.getCover().getImageHash()) computeAndSaveCoverHash(context, c, dao); // Refine by running the actual duplicate detection algorithm against the rough candidates List<DuplicateEntry> entries = new ArrayList<>(); StringSimilarity cosine = new Cosine(); // TODO make useLanguage a setting ? DuplicateHelper.DuplicateCandidate reference = new DuplicateHelper.DuplicateCandidate(content, true, true, false, pHash); List<DuplicateHelper.DuplicateCandidate> candidates = Stream.of(roughCandidates).map(c -> new DuplicateHelper.DuplicateCandidate(c, true, true, false, Long.MIN_VALUE)).toList(); for (DuplicateHelper.DuplicateCandidate candidate : candidates) { DuplicateEntry entry = DuplicateHelper.Companion.processContent(reference, candidate, true, true, true, false, true, 2, cosine); if (entry != null) entries.add(entry); } // Sort by similarity and size (unfortunately, Comparator.comparing is API24...) Optional<DuplicateEntry> bestMatch = Stream.of(entries).sorted(DuplicateEntry::compareTo).findFirst(); if (bestMatch.isPresent()) { Content resultContent = dao.selectContent(bestMatch.get().getDuplicateId()); float resultScore = bestMatch.get().calcTotalScore(); return new ImmutablePair<>(resultContent, resultScore); } return null; } // Compute perceptual hash for the cover picture public static void computeAndSaveCoverHash( @NonNull final Context context, @NonNull final Content content, @NonNull final CollectionDAO dao) { Bitmap coverBitmap = DuplicateHelper.Companion.getCoverBitmapFromContent(context, content); long pHash = DuplicateHelper.Companion.calcPhash(DuplicateHelper.Companion.getHashEngine(), coverBitmap); if (coverBitmap != null) coverBitmap.recycle(); content.getCover().setImageHash(pHash); dao.insertImageFile(content.getCover()); } /** * Comparator to be used to sort files according to their names */ private static class InnerNameNumberFileComparator implements Comparator<DocumentFile> { @Override public int compare(@NonNull DocumentFile o1, @NonNull DocumentFile o2) { return CaseInsensitiveSimpleNaturalComparator.getInstance().compare(StringHelper.protect(o1.getName()), StringHelper.protect(o2.getName())); } } /** * Comparator to be used to sort archive entries according to their names */ private static class InnerNameNumberArchiveComparator implements Comparator<ArchiveHelper.ArchiveEntry> { @Override public int compare(@NonNull ArchiveHelper.ArchiveEntry o1, @NonNull ArchiveHelper.ArchiveEntry o2) { return CaseInsensitiveSimpleNaturalComparator.getInstance().compare(o1.path, o2.path); } } }
/* * While not entirely a direct port, this file is heavily based on */ package net.justdave.mcstatus; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.URI; import java.net.URISyntaxException; import java.net.UnknownHostException; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Base64; import android.util.Log; public class MinecraftServer { private static final String TAG = MinecraftServer.class.getSimpleName(); private static final int THUMBNAIL_SIZE = 64; private String serverName = "My Minecraft Server"; private String serverAddress = "localhost"; private int queryPort = 25565; // the default minecraft query port private JSONObject serverJSON = new JSONObject(); public MinecraftServer() { // default to localhost:25565 setDescription("Loading..."); } public MinecraftServer(String name, String address) throws URISyntaxException { serverName = name; Log.i(TAG, "new MinecraftServer(".concat(address).concat(")")); URI uri = new URI("my://" + address); serverAddress = uri.getHost(); if (uri.getPort() > 0) { queryPort = uri.getPort(); } setDescription("Loading..."); } public void setDescription(String msg) { try { serverJSON.put("description", msg); } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } public String serverAddress() { StringBuilder result = new StringBuilder(); result.append(serverAddress); if (queryPort != 25565) { // if it's not the default minecraft port result.append(":"); result.append(queryPort); } return result.toString(); } public String serverName() { return serverName; } public int maxPlayers() { JSONObject players = serverJSON.optJSONObject("players"); if (players == null) { return 0; } return players.optInt("max"); } public int onlinePlayers() { JSONObject players = serverJSON.optJSONObject("players"); if (players == null) { return 0; } return players.optInt("online"); } public ArrayList<String> playerList() { ArrayList<String> result = new ArrayList<>(); result.clear(); JSONObject players = serverJSON.optJSONObject("players"); if (players == null) { return result; } JSONArray sample = players.optJSONArray("sample"); if (sample == null) { return result; } int pos = 0; while (pos < sample.length()) { JSONObject entry = sample.optJSONObject(pos++); String username = entry.optString("name"); result.add(username); } Log.i(TAG, "playerList() returning ".concat(result.toString())); return result; } public String serverVersion() { JSONObject version = serverJSON.optJSONObject("version"); if (version == null) { return ""; } return version.optString("name"); } public String description() { StringBuilder result = new StringBuilder(); String desc = serverJSON.optString("description"); JSONObject descriptionObj = serverJSON.optJSONObject("description"); if (descriptionObj != null) { desc = descriptionObj.optString("text"); } result.append("<body style='background-color: transparent; color: white; margin: 0; padding: 0;'><span>"); int curChar = 0; String color = ""; String decoration = ""; while (curChar < desc.length()) { char theChar = desc.charAt(curChar++); if (theChar == '§') { char code = desc.charAt(curChar++); switch (code) { case '0': color = "#000000"; decoration = ""; break; case '1': color = "#0000aa"; decoration = ""; break; case '2': color = "#00aa00"; decoration = ""; break; case '3': color = "#00aaaa"; decoration = ""; break; case '4': color = "#aa0000"; decoration = ""; break; case '5': color = "#aa00aa"; decoration = ""; break; case '6': color = "#ffaa00"; decoration = ""; break; case '7': color = "#aaaaaa"; decoration = ""; break; case '8': color = "#555555"; decoration = ""; break; case '9': color = "#5555ff"; decoration = ""; break; case 'a': color = "#55ff55"; decoration = ""; break; case 'b': color = "#55ffff"; decoration = ""; break; case 'c': color = "#ff5555"; decoration = ""; break; case 'd': color = "#ff55ff"; decoration = ""; break; case 'e': color = "#ffff55"; decoration = ""; break; case 'f': color = "#ffffff"; decoration = ""; break; case 'k': color = ""; break; case 'l': decoration = "bold"; break; case 'm': decoration = "strikethrough"; break; case 'n': decoration = "underscore"; break; case 'o': decoration = "italic"; break; case 'r': decoration = ""; color = ""; } result.append("</span><span style='"); if (color.length() > 0) { result.append("color: ".concat(color).concat("; ")); } if (decoration.length() > 0) { result.append("text-decoration: ".concat(decoration).concat("; ")); } result.append("'>"); } else { result.append(theChar); } } result.append("</span></body>"); return result.toString(); } public Bitmap image() { String imageData = serverJSON.optString("favicon"); if (imageData.isEmpty()) return null; try { return getThumbnail(imageData); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public void query() { Log.i(TAG, "query() called on ".concat(serverAddress())); Socket socket; try { socket = new Socket(serverAddress, queryPort); socket.setSoTimeout(10000); // 10 second read timeout } catch (IllegalArgumentException e) { setDescription("Error: " + e.getLocalizedMessage()); return; } catch (UnknownHostException e) { setDescription("Error: Lookup failed: Unknown host"); return; } catch (IOException e) { setDescription("Error: " + e.getLocalizedMessage()); return; } OutputStream out; InputStream in; try { out = socket.getOutputStream(); in = socket.getInputStream(); out.write(6 + serverAddress.length()); // length of packet ID + data // to follow out.write(0); // packet ID = 0 out.write(4); // Protocol version out.write(serverAddress.length()); // varint length of server // address out.write(serverAddress.getBytes()); // server address in UTF8 out.write((queryPort & 0xFF00) >> 8); // port number high byte out.write(queryPort & 0x00FF); // port number low byte out.write(1); // Next state: status out.write(0x01); // status ping (1st byte) out.write(0x00); // status ping (2nd byte) int packetLength = readVarInt(in); // size of entire packet String serverData; if (packetLength < 11) { Log.i(TAG, String.format("%s, %s: packet length too small: %d", serverName, serverAddress, packetLength)); serverData = null; setDescription("Invalid response from server (server may be in the process of restarting, try again in a few seconds)"); in.close(); out.close(); socket.close(); return; } final int packetType = in.read(); // packet type - going to ignore it because we should // only ever get the one type back anyway Log.d(TAG, String.format("%s, %s: packet type: %d", serverName, serverAddress, packetType)); int jsonLength = readVarInt(in); // size of JSON blob if (jsonLength < 0){ in.close(); out.close(); socket.close(); return; } byte[] buffer = new byte[jsonLength + 10]; // a little more than // we're expecting just // to be safe int bytesRead = 0; do { bytesRead += in.read(buffer, bytesRead, jsonLength - bytesRead); } while (bytesRead < jsonLength); serverData = new String(buffer, 0, bytesRead); serverJSON = new JSONObject(serverData); in.close(); out.close(); socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private int readVarInt(InputStream in) { int theInt = 0; // int byteCounter = 0; for (int i = 0; i < 6; i++){ int theByte; try { theByte = in.read(); } catch (IOException e){ e.printStackTrace(); Log.w(TAG, "readVarInt: Failed to retrieve data from server"); return 0; } theInt |= (theByte & 0x7F) << (7 * i); // if (byteCounter > 5) { // Log.w(TAG, String.format("readVarInt: invalid data received, %d bytes", byteCounter)); // return -1; if (theByte == 0xffffffff){ Log.w(TAG, String.format("readVarInt: received unexpected byte value: %#x", theByte)); return -1; } if ((theByte & 0x80) != 128) { break; } } return theInt; } public Bitmap getThumbnail(String uri) throws IOException { // data:image/png;base64,iVBORw0KGgoAAAANSUhEUgA final String prefixString = "data:image/png;base64,"; byte[] imageDataBase64; byte[] imageData; if (uri.startsWith(prefixString)) { imageDataBase64 = uri.substring(prefixString.length()).getBytes(); } else { throw new FileNotFoundException("Not the correct URI Prefix"); } imageData = Base64.decode(imageDataBase64, Base64.DEFAULT); BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options(); onlyBoundsOptions.inJustDecodeBounds = true; onlyBoundsOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;// optional BitmapFactory.decodeByteArray(imageData, 0, imageData.length, onlyBoundsOptions); if ((onlyBoundsOptions.outWidth == -1) || (onlyBoundsOptions.outHeight == -1)) return null; int originalSize = Math.max(onlyBoundsOptions.outHeight, onlyBoundsOptions.outWidth); double ratio = (originalSize > THUMBNAIL_SIZE) ? (originalSize / THUMBNAIL_SIZE) : 1.0; BitmapFactory.Options bitmapOptions = new BitmapFactory.Options(); bitmapOptions.inSampleSize = getPowerOfTwoForSampleRatio(ratio); bitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;// optional return BitmapFactory.decodeByteArray(imageData, 0, imageData.length, bitmapOptions); } private static int getPowerOfTwoForSampleRatio(double ratio) { int k = Integer.highestOneBit((int) Math.floor(ratio)); if (k == 0) return 1; else return k; } }
package org.usfirst.frc.team910.robot.Auton; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; public class AutonDriveStraight extends AutonStep { private static final double V_MAX = 10.0; private static final double ACCEL = 3.0; private static final double PCONST = 0.15; double distance; double stopDistance; double startDistance; double startTime; double halfDistance; double startDeccelTime; double power; double angle; double currVel; double x; private static final double RAMP_RATE = 0.5; //power per second private static final double RAMP_DOWN_OFFSET = 0.1; public AutonDriveStraight(double distance, double speed, double angle) { this.distance = distance; this.power = speed; this.angle = angle; } @Override public void setup() { startDistance = (drive.leftDriveEncoder + drive.rightDriveEncoder) / 2; stopDistance = startDistance + distance; halfDistance = distance / 2 + startDistance; x = 0; currVel = 0; startTime = Timer.getFPGATimestamp(); startDeccelTime = Math.sqrt(distance/2*ACCEL); if (ACCEL*startDeccelTime > V_MAX){ double accelTime = V_MAX / ACCEL; double accelDist = (V_MAX/2)*accelTime; double vMaxDist = (halfDistance - accelDist); double vMaxTime = vMaxDist / V_MAX; startDeccelTime = accelTime + vMaxTime*2; } } @Override public void run() { double currentDistance = (drive.leftDriveEncoder + drive.rightDriveEncoder) / 2; double accel = ACCEL; if (Timer.getFPGATimestamp() > startTime+startDeccelTime){ accel = -ACCEL; } else if(currVel == V_MAX) { accel = 0; } x = x + currVel*sense.deltaTime+0.5*accel*sense.deltaTime*sense.deltaTime; currVel = currVel + accel*sense.deltaTime; if(currVel > V_MAX) currVel = V_MAX; double distError = currentDistance - startDistance - x; power = PCONST * distError; SmartDashboard.putNumber("autonPower", power); drive.driveStraightNavX(false, power, 0); //TODO Maybe add jerk later } @Override public boolean isDone() { double avgEncDist = (drive.leftDriveEncoder + drive.rightDriveEncoder) / 2; return avgEncDist >= stopDistance; } }
package org.openalpr.app; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; import com.google.android.gms.gcm.GoogleCloudMessaging; import java.io.IOException; public class ConfirmPlateActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener { private String TAG = "ConfirmPlateActivity"; private Context context; private String plate_state = ""; protected String plate_number = ""; protected GoogleCloudMessaging gcm = null; private String[] abrv_state; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_confirm_plate); Spinner spinner = (Spinner) findViewById(R.id.plate_state_spinner); // Create an ArrayAdapter using the string array and a default spinner layout ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.states, android.R.layout.simple_spinner_item); // Specify the layout to use when the list of choices appears adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Apply the adapter to the spinner spinner.setAdapter(adapter); spinner.setOnItemSelectedListener(this); context = this; Log.v(TAG, "TEST TEST TEST: "); Log.v(TAG, "TEST TEST TEST: Variables.username = " + Variables.username); Log.v(TAG, "TEST TEST TEST: Variables.password = " + Variables.password); Log.v(TAG, "TEST TEST TEST: "); // get the abrv. version of the states for sending to db Resources res = getResources(); abrv_state = res.getStringArray(R.array.states_abbreviated); } public void confirmPlate(View view) { EditText p = (EditText)findViewById(R.id.plate_number); plate_number = p.getText().toString(); context = getApplicationContext(); gcm = GoogleCloudMessaging.getInstance(context); Log.d(TAG, "Plate Number: " + plate_number); Log.d(TAG, "Plate State: " + plate_state); // for sending gcm Variables.user_plate = this.plate_number; Variables.user_state = this.plate_state; // Logic needs to be added to this variable based on the database interaction(s) Boolean plateConfirmationComplete = true; if(plateConfirmationComplete){ //gcm sends hi message to server Log.v("GCM_PRINT gcm: ", gcm.toString()); new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... params) { String msg = "Sent message"; try { Bundle data = new Bundle(); data.putString("messageType", "register_user"); data.putString("username", Variables.username); data.putString("password", Variables.password); data.putString("plateString", Variables.user_plate); data.putString("plateState", Variables.user_state); String id = Integer.toString(Constants.MSG_ID) + "alpr"; Constants.MSG_ID++; Log.v(TAG, "GCM_SEND BEFORE_TOKEN: " + Constants.REG_TOKEN); Log.v(TAG, "GCM_SEND BEFORE_PROJECT_ID: " + Constants.PROJECT_ID); gcm.send(Constants.PROJECT_ID + "@gcm.googleapis.com", id, data); Log.v(TAG, "GCM_SEND AFTER_data: " + data.toString()); } catch (IOException ex) { msg = "Error :" + ex.getMessage(); Log.v(TAG, "GCM_SEND " + msg); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); msg = "Error : " + e.getMessage(); Log.v(TAG, "GCM_SEND " + msg); } return msg; } @Override protected void onPostExecute(String msg) { // mDisplay.append(msg + "\n"); } }.execute(null, null, null); Intent intent = new Intent(this, HomeActivity.class); startActivity(intent); } } public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { // An item was selected. You can retrieve the selected item using // get the abrv version of the plate from the displayed full state name drop down int s = parent.getSelectedItemPosition(); plate_state = abrv_state[s]; Log.d(TAG, "abrv_state: " + plate_state); } public void onNothingSelected(AdapterView<?> parent) { // Another interface callback String message = "Error: No state selected."; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, message, duration); toast.show(); } }
package org.unhack.chemistryeasy; import android.graphics.Point; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.Display; import android.view.View; import android.widget.GridLayout; import android.widget.SeekBar; import android.widget.Space; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import org.unhack.chemistryeasy.db.DataBaseHelper; import org.unhack.chemistryeasy.elements.ChemElement; import org.unhack.chemistryeasy.elements.ChemElementContainer; import org.unhack.chemistryeasy.events.TemperatureSlideEvent; import org.unhack.chemistryeasy.ui.listeners.TempSeekBarListener; import org.unhack.chemistryeasy.ui.popups.ElementPopUp; import java.util.HashMap; public class MainActivity extends AppCompatActivity implements View.OnClickListener, View.OnLongClickListener{ BigViewController big_view; ChemElementContainer allElementsContainer; SeekBar temp; int width; int height; private static final int X_CROP = 18; private static final int Y_CROP = 12; private static final int BV_X_SIZE = 10; private static final int BV_Y_SIZE = 3; @Override public void onStart() { super.onStart(); EventBus.getDefault().register(this); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); /* Get screen size */ Display display = getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); width = size.x; height = size.y; DataBaseHelper db = new DataBaseHelper(getApplicationContext()); if (db.isValid) { db.openDataBase(); } else { Log.d("DB", "problem, db was not inited well"); } Ui_init(); } public void Ui_init(){ allElementsContainer = new ChemElementContainer(getApplicationContext()); allElementsContainer.initFromDb(getApplicationContext()); big_view = new BigViewController(getApplicationContext()); Space space = new Space(getApplicationContext()); Space space2 = new Space(getApplicationContext()); space2.setLayoutParams(new GridLayout.LayoutParams(GridLayout.spec(0,0), GridLayout.spec(12,5))); GridLayout table = (GridLayout) findViewById(R.id.table_layout); GridLayout lantan = (GridLayout) findViewById(R.id.lantan); int x_size = (int) Math.floor((double)width / X_CROP); int y_size = (int) Math.floor((double)height / Y_CROP); GridLayout.LayoutParams bigViewParams = new GridLayout.LayoutParams(GridLayout.spec(0,3), GridLayout.spec(2,10)); bigViewParams.width = x_size*BV_X_SIZE; bigViewParams.height = y_size*BV_Y_SIZE; big_view.setLayoutParams(bigViewParams); for(int i = 0; i < allElementsContainer.getSize(); i++) { ChemElement buf = allElementsContainer.getElementByNumber(i + 1); buf.setSize(x_size, y_size); switch (buf.getElementNumber()){ case 2: table.addView(space); table.addView(big_view); table.addView(space2); break; } if(buf.getElementNumber() >= 58 && buf.getElementNumber() <= 71) { lantan.addView(buf); } else if(buf.getElementNumber() >= 90 && buf.getElementNumber() <= 103){ lantan.addView(buf); } else { table.addView(buf); } buf.setOnClickListener(this); buf.setOnLongClickListener(this); } /** Test Filter */ int r[] = {2,3,5,6,7,8,9,11,12}; HashMap el = allElementsContainer.getFilteredElements(r); for(int i = 0; i < el.size(); i++) { ChemElement s = (ChemElement) el.get(r[i]); //s.setBackgroundColor(Color.RED); } temp = (SeekBar) findViewById(R.id.temp); temp.setOnSeekBarChangeListener(new TempSeekBarListener(temp)); } @Subscribe(threadMode = ThreadMode.MAIN) public void onMessageEvent(TemperatureSlideEvent event) { allElementsContainer.getStateInTemp(event.temperature); } @Override public void onClick(View v) { allElementsContainer.getStateInTemp(temp.getProgress()); ChemElement el = (ChemElement) v; ElementPopUp popUp = new ElementPopUp((ChemElement) v,getApplicationContext(),v); popUp.show(); Log.d("ELEMENT", ((ChemElement) v).getElementNativeName()); } @Override public boolean onLongClick(View v) { ChemElement el = (ChemElement) v; int num = el.getElementNumber(); big_view.setElementToView(num); return true; } @Override public void onStop() { EventBus.getDefault().unregister(this); super.onStop(); } }
package org.wikipedia.views; import android.content.Context; import android.graphics.Canvas; import android.os.SystemClock; import android.util.AttributeSet; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.ViewConfiguration; import android.webkit.WebView; import org.wikipedia.WikipediaApp; import org.wikipedia.events.WebViewInvalidateEvent; import org.wikipedia.util.DimenUtil; import java.util.ArrayList; import java.util.List; public class ObservableWebView extends WebView { private static final WebViewInvalidateEvent INVALIDATE_EVENT = new WebViewInvalidateEvent(); private List<OnClickListener> onClickListeners; private List<OnScrollChangeListener> onScrollChangeListeners; private List<OnDownMotionEventListener> onDownMotionEventListeners; private List<OnUpOrCancelMotionEventListener> onUpOrCancelMotionEventListeners; private List<OnContentHeightChangedListener> onContentHeightChangedListeners; private OnFastScrollListener onFastScrollListener; private OnEdgeSwipeListener onEdgeSwipeListener; private int contentHeight = 0; private float touchStartX; private float touchStartY; private int touchSlop; private long lastScrollTime; private int totalAmountScrolled; private boolean edgeSwipePending; private boolean edgeSwipeReset; /** * Threshold (in pixels) of continuous scrolling, to be considered "fast" scrolling. */ private static final int FAST_SCROLL_THRESHOLD = (int) (1000 * DimenUtil.getDensityScalar()); /** * Maximum single scroll amount (in pixels) to be considered a "human" scroll. * Otherwise it's probably a programmatic scroll, which we won't count. */ private static final int MAX_HUMAN_SCROLL = (int) (500 * DimenUtil.getDensityScalar()); private static final int EDGE_SWIPE_THRESHOLD = DimenUtil.roundedDpToPx(64); /** * Maximum amount of time that needs to elapse before the previous scroll amount * is "forgotten." That is, if the user scrolls once, then scrolls again within this * time, then the two scroll actions will be added together as one, and counted towards * a possible "fast" scroll. */ private static final int MAX_MILLIS_BETWEEN_SCROLLS = 500; public void addOnClickListener(OnClickListener onClickListener) { onClickListeners.add(onClickListener); } public void addOnScrollChangeListener(OnScrollChangeListener onScrollChangeListener) { onScrollChangeListeners.add(onScrollChangeListener); } public void addOnDownMotionEventListener(OnDownMotionEventListener onDownMotionEventListener) { onDownMotionEventListeners.add(onDownMotionEventListener); } public void addOnUpOrCancelMotionEventListener(OnUpOrCancelMotionEventListener onUpOrCancelMotionEventListener) { onUpOrCancelMotionEventListeners.add(onUpOrCancelMotionEventListener); } public void addOnContentHeightChangedListener(OnContentHeightChangedListener onContentHeightChangedListener) { onContentHeightChangedListeners.add(onContentHeightChangedListener); } public void setOnFastScrollListener(OnFastScrollListener onFastScrollListener) { this.onFastScrollListener = onFastScrollListener; } public void setOnEdgeSwipeListener(OnEdgeSwipeListener onEdgeSwipeListener) { this.onEdgeSwipeListener = onEdgeSwipeListener; } public void clearAllListeners() { onClickListeners.clear(); onScrollChangeListeners.clear(); onDownMotionEventListeners.clear(); onUpOrCancelMotionEventListeners.clear(); onContentHeightChangedListeners.clear(); onFastScrollListener = null; // To stop the music when left the article loadUrl("about:blank"); } public interface OnClickListener { boolean onClick(float x, float y); } public interface OnScrollChangeListener { void onScrollChanged(int oldScrollY, int scrollY, boolean isHumanScroll); } public interface OnDownMotionEventListener { void onDownMotionEvent(); } public interface OnUpOrCancelMotionEventListener { void onUpOrCancelMotionEvent(); } public interface OnContentHeightChangedListener { void onContentHeightChanged(int contentHeight); } public interface OnFastScrollListener { void onFastScroll(); } public interface OnEdgeSwipeListener { void onEdgeSwipe(boolean direction); } public void copyToClipboard() { // Simulate a Ctrl-C key press, which copies the current selection to the clipboard. // Seems to work across all APIs. dispatchKeyEvent(new KeyEvent(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_C, 0, KeyEvent.META_CTRL_ON)); dispatchKeyEvent(new KeyEvent(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), KeyEvent.ACTION_UP, KeyEvent.KEYCODE_C, 0, KeyEvent.META_CTRL_ON)); } public ObservableWebView(Context context) { super(context); init(); } public ObservableWebView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public ObservableWebView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } private void init() { onClickListeners = new ArrayList<>(); onScrollChangeListeners = new ArrayList<>(); onDownMotionEventListeners = new ArrayList<>(); onUpOrCancelMotionEventListeners = new ArrayList<>(); onContentHeightChangedListeners = new ArrayList<>(); touchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop(); } @Override protected void onScrollChanged(int left, int top, int oldLeft, int oldTop) { super.onScrollChanged(left, top, oldLeft, oldTop); boolean isHumanScroll = Math.abs(top - oldTop) < MAX_HUMAN_SCROLL; for (OnScrollChangeListener listener : onScrollChangeListeners) { listener.onScrollChanged(oldTop, top, isHumanScroll); } if (!isHumanScroll) { return; } totalAmountScrolled += (top - oldTop); if (Math.abs(totalAmountScrolled) > FAST_SCROLL_THRESHOLD && onFastScrollListener != null) { onFastScrollListener.onFastScroll(); totalAmountScrolled = 0; } lastScrollTime = System.currentTimeMillis(); } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getActionMasked()) { case MotionEvent.ACTION_DOWN: for (OnDownMotionEventListener listener : onDownMotionEventListeners) { listener.onDownMotionEvent(); } if (System.currentTimeMillis() - lastScrollTime > MAX_MILLIS_BETWEEN_SCROLLS) { totalAmountScrolled = 0; } touchStartX = event.getX(); touchStartY = event.getY(); edgeSwipePending = true; break; case MotionEvent.ACTION_MOVE: if (edgeSwipePending) { if (edgeSwipeReset) { touchStartX = event.getX(); touchStartY = event.getY(); edgeSwipeReset = false; } if (event.getX() - touchStartX > EDGE_SWIPE_THRESHOLD) { edgeSwipePending = false; if (onEdgeSwipeListener != null) { onEdgeSwipeListener.onEdgeSwipe(true); } } else if (touchStartX - event.getX() > EDGE_SWIPE_THRESHOLD) { edgeSwipePending = false; if (onEdgeSwipeListener != null) { onEdgeSwipeListener.onEdgeSwipe(false); } } } break; case MotionEvent.ACTION_UP: edgeSwipePending = false; if (Math.abs(event.getX() - touchStartX) <= touchSlop && Math.abs(event.getY() - touchStartY) <= touchSlop) { for (OnClickListener listener : onClickListeners) { if (listener.onClick(event.getX(), event.getY())) { return true; } } } case MotionEvent.ACTION_CANCEL: edgeSwipePending = false; for (OnUpOrCancelMotionEventListener listener : onUpOrCancelMotionEventListeners) { listener.onUpOrCancelMotionEvent(); } break; default: break; } return super.onTouchEvent(event); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (isInEditMode()) { return; } edgeSwipeReset = true; if (contentHeight != getContentHeight()) { contentHeight = getContentHeight(); for (OnContentHeightChangedListener listener : onContentHeightChangedListeners) { listener.onContentHeightChanged(contentHeight); } } WikipediaApp.getInstance().getBus().post(INVALIDATE_EVENT); } public float getTouchStartX() { return touchStartX; } public float getTouchStartY() { return touchStartY; } }
package ru.furry.furview2; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import android.widget.ToggleButton; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import ru.furry.furview2.database.FurryDatabase; import ru.furry.furview2.drivers.Driver; import ru.furry.furview2.drivers.Drivers; import ru.furry.furview2.images.FurImage; import ru.furry.furview2.images.RemoteFurImage; import ru.furry.furview2.system.AsyncHandlerUI; import ru.furry.furview2.system.BlockUnblockUI; import ru.furry.furview2.system.Utils; public class DownloadingActivity extends AppCompatActivity { private final static int MAX_NUM_OF_PICS = 20; DriverWrapperAdapter dataAdapter; String drivername; ToggleButton sfwButton; Button downloadButton; AlertDialog.Builder aBuilder; EditText numOfPicsEditText; ProgressBar massDownloadingProgressBar; EditText counterTextEdit; List<Drivers> drivers; SyncCounter syncCounter; EditText searchField; private int numOfPics; FurryDatabase database; RelativeLayout mMassDownloadLayout; ListView mMassDownloadDriverList; BlockUnblockUI blocking; ProgressBar mMassDownloadWheel; boolean blocked = false; AtomicInteger currentSavedPic = new AtomicInteger(0); //for save and restore settings public static final String APP_PREFERENCES = "settings"; public static final String APP_PREFERENCES_SWF = "swf"; private SharedPreferences mSettings; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_downloading); getSupportActionBar().setDisplayHomeAsUpEnabled(false); //Initial settings mSettings = getSharedPreferences(APP_PREFERENCES, Context.MODE_PRIVATE); database = new FurryDatabase(this); searchField = (EditText) findViewById(R.id.searchField); searchField.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { numOfPicsEditText.requestFocus(); return true; } }); counterTextEdit = (EditText) findViewById(R.id.counterTextEdit); massDownloadingProgressBar = (ProgressBar) findViewById(R.id.massDownloadingProgressBar); mMassDownloadWheel = (ProgressBar) findViewById(R.id.massDownloadWheel); mMassDownloadLayout = (RelativeLayout) findViewById(R.id.massDownloadLayout); mMassDownloadDriverList = (ListView) findViewById(R.id.listView); blocking = new BlockUnblockUI(mMassDownloadLayout); drivername = getIntent().getStringExtra("drivername"); displayListView(); sfwButton = (ToggleButton) findViewById(R.id.sfwButton); if (MainActivity.swf) { sfwButton.setBackgroundColor(0xff63ec4f); sfwButton.setChecked(true); } else { sfwButton.setBackgroundColor(0xccb3b3b3); sfwButton.setChecked(false); } sfwButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { MainActivity.swf = !MainActivity.swf; if (sfwButton.isChecked()) sfwButton.setBackgroundColor(0xff63ec4f); else sfwButton.setBackgroundColor(0xccb3b3b3); } }); aBuilder = new AlertDialog.Builder(this); aBuilder.setTitle(R.string.too_many_pics); aBuilder.setMessage(R.string.too_many_pics_body); aBuilder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); startDownload(); } }); aBuilder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // Do nothing but close the dialog dialog.dismiss(); } }); numOfPicsEditText = (EditText) findViewById(R.id.numOfPicsEditText); numOfPicsEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { preStartDownload(); return true; } }); downloadButton = (Button) findViewById(R.id.downloadButton); downloadButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(), 0); preStartDownload(); } }); } private void preStartDownload() { MainActivity.searchQuery = searchField.getText().toString(); drivers = getDrivers(); numOfPics = Integer.parseInt("0" + numOfPicsEditText.getText().toString()); Log.d("fgsfds", "downloading #" + numOfPics + " pics"); syncCounter = new SyncCounter(numOfPics); massDownloadingProgressBar.setMax(numOfPics); massDownloadingProgressBar.setProgress(0); currentSavedPic.set(0); progressLayout(false); if (numOfPics > 0) { if (drivers.size() * numOfPics <= MAX_NUM_OF_PICS) startDownload(); else aBuilder.create().show(); } else { Toast.makeText(getApplicationContext(), R.string.no_zero, Toast.LENGTH_SHORT).show(); } } class SyncCounter { int maxSize; public int size; public AtomicInteger blocking; public SyncCounter(int maxSize) { this.maxSize = maxSize; this.size = 0; counterTextEdit.setText(""); //massDownloadingProgressBar.setMax(maxSize); Log.d("fgsfds", "max size: " + maxSize); blocking = new AtomicInteger(0); } public synchronized void increment() { size += 1; Log.d("fgsfds", "size: " + size); //counterTextEdit.setText(Integer.toString(size)); //massDownloadingProgressBar.setProgress(size); if (size == maxSize) { unblockUI_(); blocking.set(9999); } } } private void unblockUI_() { Log.d("fgsfds", "UI unblocked"); //blocking.unblockUI(); } private void blockUI_() { Log.d("fgsfds", "UI blocked..."); //blocking.blockUI(); blocking.blockUIall(); blocked = true; } private void progressLayout(boolean progressCheck) { if (progressCheck) { mMassDownloadWheel.setVisibility(View.GONE); counterTextEdit.setVisibility(View.VISIBLE); } else { mMassDownloadWheel.setVisibility(View.VISIBLE); counterTextEdit.setVisibility(View.GONE); } } private void startDownload() { blockUI_(); for (final Drivers driver : drivers) { try { Log.d("fgsfds", "init " + driver.drivername); final Driver driverInstance = driver.driverclass.newInstance(); final AtomicInteger counter = new AtomicInteger(0); final List<RemoteFurImage> remoteImages = new ArrayList<>(numOfPics); driverInstance.init(MainActivity.permanentStorage, this); driverInstance.setSfw(sfwButton.isChecked()); syncCounter.blocking.incrementAndGet(); final AsyncHandlerUI<FurImage> imagesHandler = new AsyncHandlerUI<FurImage>() { @Override public void blockUI() { // don't fill } @Override public void unblockUI() { // don't fill } @Override public void retrieve(List<? extends FurImage> images) { for (FurImage image : images) { driverInstance.saveToDBandStorage(image, database, new AsyncHandlerUI<FurImage>() { @Override public void blockUI() { //blocking.blockUI(); } @Override public void unblockUI() { progressLayout(true); massDownloadingProgressBar.setProgress(currentSavedPic.incrementAndGet()); counterTextEdit.setText(getResources().getString(R.string.images_downloaded) + " " + Integer.toString(currentSavedPic.get())); if (currentSavedPic.get() == numOfPics) { blocking.unblockUIall(); blocked = false; } } @Override public void retrieve(List<? extends FurImage> images) { Log.d("fgsfds", "This message don't shown( "); } }); syncCounter.increment(); } } }; driverInstance.search(searchField.getText().toString(), new AsyncHandlerUI<RemoteFurImage>() { @Override public void blockUI() { // don't fill } @Override public void unblockUI() { // don't fill } @Override public void retrieve(List<? extends RemoteFurImage> images) { int c = counter.addAndGet(images.size()); remoteImages.addAll(images); if (c < numOfPics) { if (driverInstance.hasNext()) { driverInstance.getNext(this); } else { if (c == 0) { Log.d("fgsfds", "Running " + syncCounter.blocking.get() + " threads"); if (syncCounter.blocking.decrementAndGet() == 0) { unblockUI_(); } } else { driverInstance.downloadFurImage(remoteImages.subList(0, Math.min(remoteImages.size(), numOfPics)), Collections.nCopies(remoteImages.size(), imagesHandler)); } } } else { driverInstance.downloadFurImage(remoteImages.subList(0, numOfPics), Collections.nCopies(remoteImages.size(), imagesHandler)); } } }); } catch (Exception e) { Utils.printError(e); } } } private void displayListView() { ArrayList<DriverContainer> driverContainerList = new ArrayList<DriverContainer>(); for (Drivers driver : Drivers.values()) { DriverContainer driverContainer = new DriverContainer(getResources().getString(driver.type.nameId), driver.drivername, drivername.equals(driver.drivername)); driverContainerList.add(driverContainer); } dataAdapter = new DriverWrapperAdapter(this, R.layout.driver_wrapper, driverContainerList); ListView listView = (ListView) findViewById(R.id.listView); listView.setAdapter(dataAdapter); } private class DriverWrapperAdapter extends ArrayAdapter<DriverContainer> { private ArrayList<DriverContainer> driverContainerList; public DriverWrapperAdapter(Context context, int textViewResourceId, ArrayList<DriverContainer> driverContainerList) { super(context, textViewResourceId, driverContainerList); this.driverContainerList = new ArrayList<DriverContainer>(); this.driverContainerList.addAll(driverContainerList); } private class ViewHolder { TextView code; CheckBox name; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { LayoutInflater vi = (LayoutInflater) getSystemService( Context.LAYOUT_INFLATER_SERVICE); convertView = vi.inflate(R.layout.driver_wrapper, null); holder = new ViewHolder(); holder.code = (TextView) convertView.findViewById(R.id.type); holder.name = (CheckBox) convertView.findViewById(R.id.code); convertView.setTag(holder); //blocking.addViewToBlock((RelativeLayout) convertView.findViewById(R.id.driverWrapperAdapterLayout)); blocking.addViewToBlock((CheckBox) convertView.findViewById(R.id.code)); blocking.addViewToBlock((TextView) convertView.findViewById(R.id.type)); holder.name.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { CheckBox cb = (CheckBox) v; DriverContainer driverContainer = (DriverContainer) cb.getTag(); driverContainer.setSelected(cb.isChecked()); } }); } else { holder = (ViewHolder) convertView.getTag(); } DriverContainer driverContainer = driverContainerList.get(position); holder.code.setText(" (" + driverContainer.getType() + ")"); holder.name.setText(driverContainer.getName()); holder.name.setChecked(driverContainer.isSelected()); holder.name.setTag(driverContainer); return convertView; } } private List<Drivers> getDrivers() { ArrayList<Drivers> drivers = new ArrayList<>(); for (DriverContainer container : dataAdapter.driverContainerList) { if (container.isSelected()) { drivers.add(Drivers.getDriver(container.getName())); } } return drivers; } class DriverContainer { String type = null; String name = null; boolean selected = false; public DriverContainer(String type, String name, boolean selected) { super(); this.type = type; this.name = name; this.selected = selected; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isSelected() { return selected; } public void setSelected(boolean selected) { this.selected = selected; } } @Override public void onBackPressed() { if (blocked){ openQuitDialog(); } else { super.onBackPressed(); } } private void openQuitDialog() { AlertDialog.Builder quitDialog = new AlertDialog.Builder(this); quitDialog.setTitle(getString(R.string.warning)); quitDialog.setMessage(getString(R.string.massDownloadExit)); quitDialog.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }); quitDialog.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // Do nothing but close the dialog dialog.dismiss(); } }); quitDialog.show(); } @Override protected void onResume() { super.onResume(); //Restore settings //swf button if (mSettings.contains(APP_PREFERENCES_SWF)) { MainActivity.swf = mSettings.getBoolean(APP_PREFERENCES_SWF, true); } sfwButton.setChecked(MainActivity.swf); if (MainActivity.swf) sfwButton.setBackgroundColor(0xff63ec4f); else sfwButton.setBackgroundColor(0xccb3b3b3); } @Override protected void onPause() { super.onPause(); // Store settings SharedPreferences.Editor editor = mSettings.edit(); editor.putBoolean(APP_PREFERENCES_SWF, MainActivity.swf); editor.apply(); } }
package com.macro.mall.dao; import com.macro.mall.model.UmsMenu; import com.macro.mall.model.UmsResource; import org.apache.ibatis.annotations.Param; import java.util.List; public interface UmsRoleDao { List<UmsMenu> getMenuList(@Param("adminId") Long adminId); List<UmsMenu> getMenuListByRoleId(@Param("roleId") Long roleId); List<UmsResource> getResourceListByRoleId(@Param("roleId") Long roleId); }
package com.flytxt.tp.marker; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; public class MarkerSerDer { public Marker[] fromBytes(byte[] data) throws IOException { ByteArrayInputStream bIs = new ByteArrayInputStream(data); DataInputStream dIs = new DataInputStream(bIs); int size = dIs.readInt(); Marker markers[] = new Marker[size]; int index = 0; for (Marker aMarker : markers) { int dataSize = dIs.readInt(); byte[] mData = new byte[dataSize]; dIs.read(mData); Marker m = new Marker(mData, 0, dataSize); markers[index++] = m; } return markers; } public byte[] toBytes(Marker... markers) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dOs = new DataOutputStream(bos); toBytes(dOs, markers); byte[] data = bos.toByteArray(); dOs.flush(); bos.reset(); return data; } private void toBytes(DataOutputStream dOs, Marker... markers) throws IOException { dOs.writeInt(markers.length); for (Marker aMarker : markers) { dOs.writeInt(aMarker.length); dOs.write(aMarker.getData(), aMarker.index, aMarker.length); } dOs.flush(); } }
package net.time4j.tz.other; import net.time4j.Iso8601Format; import net.time4j.Moment; import net.time4j.PatternType; import net.time4j.SystemClock; import net.time4j.format.ChronoFormatter; import net.time4j.tz.NameStyle; import net.time4j.tz.TZID; import net.time4j.tz.Timezone; import net.time4j.tz.ZonalOffset; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.text.ParseException; import java.util.Locale; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; @RunWith(JUnit4.class) public class WindowsZoneTest { @Test public void loadAll() { for (TZID tzid : Timezone.getAvailableIDs("WINDOWS")) { try { Timezone.of(tzid); } catch (RuntimeException ex) { fail(ex.getMessage()); } } } @Test(expected=IllegalArgumentException.class) public void ofInvalidNameXYZ() { WindowsZone.of("xyz"); } @Test(expected=IllegalArgumentException.class) public void ofInvalidNameAsWinID() { WindowsZone.of("WINDOWS~America/New_York"); } @Test(expected=IllegalArgumentException.class) public void ofInvalidNameAsOlsonID() { WindowsZone.of("America/New_York"); } @Test public void testToString() { String name = "Eastern Standard Time"; WindowsZone wzn = WindowsZone.of(name); assertThat( wzn.toString(), is(name)); } @Test public void resolveSmartUS() { WindowsZone wzn = WindowsZone.of("Eastern Standard Time"); assertThat( wzn.resolveSmart(Locale.US).canonical(), is("WINDOWS~America/New_York")); } @Test public void resolveSmartFrance() { WindowsZone wzn = WindowsZone.of("Eastern Standard Time"); TZID tzid = wzn.resolveSmart(Locale.FRANCE); assertThat(tzid, nullValue()); } @Test public void resolveSmartEnglish() { WindowsZone wzn = WindowsZone.of("Eastern Standard Time"); TZID tzid = wzn.resolveSmart(Locale.ENGLISH); assertThat(tzid, nullValue()); } @Test public void resolve() { WindowsZone wzn = WindowsZone.of("Eastern Standard Time"); assertThat( wzn.resolve(Locale.US).size(), is(7)); } @Test public void getDisplayNameUS() { String name = "Eastern Standard Time"; WindowsZone wzn = WindowsZone.of(name); TZID tzid = wzn.resolveSmart(Locale.US); for (NameStyle style : NameStyle.values()) { assertThat( Timezone.of(tzid).getDisplayName(style, Locale.US), is(name)); } } @Test public void getDisplayNameFrance() { String name = "Romance Standard Time"; WindowsZone wzn = WindowsZone.of(name); TZID tzid = wzn.resolveSmart(Locale.FRANCE); for (NameStyle style : NameStyle.values()) { assertThat( Timezone.of(tzid).getDisplayName(style, Locale.FRANCE), is(name)); } } @Test public void getOffset() { WindowsZone wzn = WindowsZone.of("Eastern Standard Time"); TZID winzone = wzn.resolveSmart(Locale.US); Moment now = SystemClock.INSTANCE.currentTime(); ZonalOffset offset = Timezone.of(winzone).getOffset(now); ZonalOffset expected = Timezone.of("America/New_York").getOffset(now); assertThat(offset, is(expected)); } @Test public void parseName() throws ParseException { ChronoFormatter<Moment> formatter = Moment.formatter( "uuuu-MM-dd'T'HH:mm:ss.SSSzzzz", PatternType.CLDR, Locale.FRANCE, Timezone.of("America/New_York").getID()); String input = "2012-07-01T01:59:60.123Romance Standard Time"; String v = "2012-06-30T23:59:60,123000000Z"; Moment leapsecond = Iso8601Format.EXTENDED_DATE_TIME_OFFSET.parse(v); assertThat( formatter.parse(input), is(leapsecond)); } @Test public void serializeName() throws IOException, ClassNotFoundException { WindowsZone wzn = WindowsZone.of("Eastern Standard Time"); assertThat(wzn, is(roundtrip(wzn))); } @Test public void serializeTimezone() throws IOException, ClassNotFoundException { WindowsZone wzn = WindowsZone.of("Eastern Standard Time"); TZID winzone = wzn.resolveSmart(Locale.US); Timezone tz = Timezone.of(winzone); assertThat(tz, is(roundtrip(tz))); } private static Object roundtrip(Object obj) throws IOException, ClassNotFoundException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(obj); byte[] data = baos.toByteArray(); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(data); ObjectInputStream ois = new ObjectInputStream(bais); Object ser = ois.readObject(); ois.close(); return ser; } }
//FILE: AcquisitionData.java //PROJECT: Micro-Manager //SUBSYSTEM: mmstudio and 3rd party applications // 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. // HISTORY: Revised, March 2007, N. Amodaj: Allows writing as well as reading // of micro-manager data files. More comprehensive commands for setting // color and contrast. //CVS: $Id$ package org.micromanager.metadata; import ij.ImagePlus; import ij.io.FileSaver; import ij.io.Opener; import ij.measure.Calibration; import ij.process.ByteProcessor; import ij.process.ImageProcessor; import ij.process.ImageStatistics; import ij.process.ShortProcessor; import java.awt.Color; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Enumeration; import java.util.GregorianCalendar; import java.util.Hashtable; import java.util.Iterator; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.quirkware.guid.PlatformIndependentGuidGen; /** * Encapsulation of the acquisition data files. * Enables the user access pixels and and other data through a simple interface. */ public class AcquisitionData { public static final String METADATA_FILE_NAME = "metadata.txt"; public static final String METADATA_SITE_PREFIX = "site"; private JSONObject metadata_; private JSONObject summary_; private JSONObject positionProperties_; private int frames_=0; private int slices_=0; private int channels_=0; private int imgWidth_=0; private int imgHeight_=0; private int imgDepth_=0; private double pixelSize_um_ = 0.0; private double pixelAspect_ = 1.0; private int ijType_ = 0; private String basePath_; private String name_; private int version_ = 0; private double imageInterval_ms_; private double imageZStep_um_; private String channelNames_[]; private boolean inmemory_; private Hashtable<String, ImageProcessor> images_; private PlatformIndependentGuidGen guidgen_; private GregorianCalendar creationTime_; private static final String ERR_METADATA_CREATE = "Internal error creating metadata"; private static final String ERR_CHANNEL_INDEX = "Channel index out of bounds"; /** * Constructs an empty object. * load() or createNew() must be called before use. */ public AcquisitionData() { positionProperties_ = new JSONObject(); guidgen_ = PlatformIndependentGuidGen.getInstance(); creationTime_ = new GregorianCalendar(); inmemory_ = true; images_ = null; name_ = new String(); basePath_ = null; metadata_ = new JSONObject(); } /** * Checks if the specified directory contains micro-manager metadata file * @param dir - directory path * @return */ public static boolean hasMetadata(String dir) { File metaFile = new File(dir + "/" + METADATA_FILE_NAME); if (metaFile.exists()) return true; else return false; } /** * Returns the path containing a full data set: metadata and images. * @return - path */ public String getBasePath() throws MMAcqDataException { if (inmemory_) throw new MMAcqDataException("Base path not defined - acquisition data is created in-memory."); return new String(basePath_); } public boolean isInMemory() { return inmemory_; } public String getName() { return name_; } /** * Loads the metadata from the acquisition files stored on disk and initializes the object. * This method must be called prior to any other calls. * @param basePath - acquisition directory path * @throws MMAcqDataException */ public void load(String basePath) throws MMAcqDataException { reset(); // attempt to open metadata file basePath_ = basePath; images_ = null; inmemory_ = false; File metaFile = new File(basePath_ + "/" + METADATA_FILE_NAME); if (!metaFile.exists()) { throw new MMAcqDataException("Metadata file missing.\n" + "Specified directory does not exist or does not contain acquisition data."); } // load metadata StringBuffer contents = new StringBuffer(); try { // read metadata from file BufferedReader input = null; input = new BufferedReader(new FileReader(metaFile)); String line = null; while (( line = input.readLine()) != null){ contents.append(line); contents.append(System.getProperty("line.separator")); } metadata_ = new JSONObject(contents.toString()); } catch (JSONException e) { throw new MMAcqDataException(e); } catch (IOException e) { throw new MMAcqDataException(e); } File bp = new File(basePath_); name_ = bp.getName(); parse(); } /** * Loads contents from the JSON object. * This method should be used only within Micro-manager for efficiency purposes, * i.e. to avoid conversions between string and object representations of metadata. * @param metadata JSON object * @throws MMAcqDataException */ public void load (JSONObject metadata) throws MMAcqDataException { reset(); metadata_ = metadata; parse(); } public AcquisitionData createCopy() throws MMAcqDataException { AcquisitionData ad = new AcquisitionData(); try { ad.createNew(); ad.load(metadata_); // remove image references and turn for (int i=0; i<frames_; i++) { for (int j=0; j<channels_; j++) { for (int k=0; k<slices_; k++) { String key = ImageKey.generateFrameKey(i, j, k); if (metadata_.has(key)) { JSONObject imageData = metadata_.getJSONObject(key); if (imageData.has(ImagePropertyKeys.FILE)) { imageData.remove(ImagePropertyKeys.FILE); metadata_.put(key, imageData); } } } } } } catch (MMAcqDataException e) { throw new MMAcqDataException("Internal error: unable to create a copy of the metadata."); } catch (JSONException e) { throw new MMAcqDataException("Internal error: unable to remove image file references."); } return ad; } /** * Returns number of frames - time dimension. * @return - number of frames */ public int getNumberOfFrames() { return frames_; } /** * Returns number of slices - focus (Z) dimension. * @return - number of slices */ public int getNumberOfSlices() { return slices_; } /** * Returns number of channels - usually a wavelength dimension. * @return - number of channels */ public int getNumberOfChannels() { return channels_; } /** * Width of the image in pixels. */ public int getImageWidth() { return imgWidth_; } /** * Height of the image in pixels. */ public int getImageHeight() { return imgHeight_; } /** * Depth of the pixel expressed in bytes. */ public int getPixelDepth() { return imgDepth_; } /** * Size of the he pixel in microns. * We are assuming square pixels here. In order to deal with non-square pixels * use getPixelAspect() */ public double getPixelSize_um() { return pixelSize_um_; } /** * Returns aspect ratio of the pixel X:Y * @return - aspect ratio */ public double getPixelAspect() { return pixelAspect_; } /** * ImageJ pixel type constant. */ public int getImageJType() { return ijType_; } /** * Returns serialized metadata. */ public String getMetadata() { try { return metadata_.toString(3); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } /** * Returns channel names. * @return - array of channel names * @throws MMAcqDataException */ public String[] getChannelNames() throws MMAcqDataException { return channelNames_; } /** * Set channel names. * This function will resize the number channels according to the length of * the names buffer * @param names - array of channel names * @throws MMAcqDataException */ public void setChannelNames(String names[]) throws MMAcqDataException { channels_ = names.length; channelNames_ = names; JSONArray channelNames = new JSONArray(); for (int i=0; i<channels_; i++) channelNames.put(names[i]); try { summary_.put(SummaryKeys.CHANNEL_NAMES, channelNames); metadata_.put(SummaryKeys.SUMMARY, summary_); } catch (JSONException e) { throw new MMAcqDataException(e); } if (!inmemory_) writeMetadata(); } /** * Sets a channel name for a specified channel index * @param channelIdx - channel index * @param name - label * @throws MMAcqDataException */ public void setChannelName(int channelIdx, String name) throws MMAcqDataException { if (channels_ <= channelIdx) throw new MMAcqDataException(ERR_CHANNEL_INDEX); JSONArray channelNames; try { if (summary_.has(SummaryKeys.CHANNEL_NAMES)) channelNames = summary_.getJSONArray(SummaryKeys.CHANNEL_NAMES); else channelNames = new JSONArray(); channelNames.put(channelIdx, name); summary_.put(SummaryKeys.CHANNEL_NAMES, channelNames); } catch (JSONException e) { throw new MMAcqDataException(e); } channelNames_[channelIdx] = name; } /** * Returns all available summary attributes as an array of strings. * @return - an array of all attributes in the summary data * @throws MMAcqDataException */ @SuppressWarnings("unchecked") public String[] getSummaryKeys() throws MMAcqDataException { if (summary_ == null) throw new MMAcqDataException("No summary data available."); String keys[] = new String[summary_.length()]; int count = 0; for (Iterator i = summary_.keys(); i.hasNext();) keys[count++] = (String)i.next(); return keys; } public JSONObject getSummaryMetadata() throws MMAcqDataException { if (summary_ == null) throw new MMAcqDataException("The acquisition data is empty."); try { return new JSONObject(summary_.toString()); } catch (JSONException e) { throw new MMAcqDataException("Internal error. Unable to create a copy of the summary data."); } } /** * Returns all available keys associated with the position. * "Position" in this context usually means XY location * @return */ @SuppressWarnings("unchecked") public String[] getPositionPropertyKeys() { String keys[] = new String[positionProperties_.length()]; int count = 0; for (Iterator i = positionProperties_.keys(); i.hasNext();) keys[count++] = (String)i.next(); return keys; } /** * Returns a property value associated with the position * @param key * @return - value * @throws JSONException */ public String getPositionProperty(String key) throws JSONException { return positionProperties_.getString(key); } /** * Sets a property value associated with the position * @param key * @return - value * @throws JSONException */ public void setPositionProperty(String key, String prop) { try { positionProperties_.put(key, prop); } catch (JSONException e) { new MMAcqDataException(e); } } /** * Returns a summary value associated with the key. * @param key * @return - value * @throws MMAcqDataException */ public String getSummaryValue(String key) throws MMAcqDataException { try { return summary_.getString(key); } catch (JSONException e) { throw new MMAcqDataException(e); } } /** * Sets the value for the specified summary key. * This method should be used with caution because setting wrong values * may violate the integrity of the multidimensional data. * @param key * @param value * @throws MMAcqDataException */ public void setSummaryValue(String key, String value) throws MMAcqDataException { try { summary_.put(key, value); } catch (JSONException e) { throw new MMAcqDataException(e); } } /** * Test whether the particular key exists in the summary metadata * @param key * @return */ public boolean hasSummaryValue(String key) { return summary_.has(key); } /** * Test whether the particular image coordinate exists * @return * @throws MMAcqDataException */ public boolean hasImageMetadata(int frame, int channel, int slice) { String frameKey = ImageKey.generateFrameKey(frame, channel, slice); return metadata_.has(frameKey); } public JSONObject getImageMetadata(int frame, int channel, int slice) throws MMAcqDataException { String frameKey = ImageKey.generateFrameKey(frame, channel, slice); try { return metadata_.getJSONObject(frameKey); } catch (JSONException e) { throw new MMAcqDataException("Invalid image coordinates (frame,channel,slice): " + frame + "," + channel + "," + slice); } } /** * Returns a value associated with the specified key and image coordinates. * @param frame * @param channel * @param slice * @param key * @return - value * @throws MMAcqDataException */ public String getImageValue(int frame, int channel, int slice, String key) throws MMAcqDataException { if (metadata_ == null) throw new MMAcqDataException("No image data available."); if (frame <0 || frame >= frames_ || channel < 0 || channel >= channels_ || slice < 0 || slice >= slices_) throw new MMAcqDataException("Invalid image coordinates (frame,channel,slice): " + frame + "," + channel + "," + slice); String frameKey = ImageKey.generateFrameKey(frame, channel, slice); try { JSONObject frameData = metadata_.getJSONObject(frameKey); return frameData.getString(key); } catch (JSONException e) { throw new MMAcqDataException(e); } } public void setImageValue(int frame, int channel, int slice, String key, String value) throws MMAcqDataException { if (metadata_ == null) throw new MMAcqDataException("No image data available."); if (frame <0 || frame >= frames_ || channel < 0 || channel >= channels_ || slice < 0 || slice >= slices_) throw new MMAcqDataException("Invalid image coordinates (frame,channel,slice): " + frame + "," + channel + "," + slice); String frameKey = ImageKey.generateFrameKey(frame, channel, slice); try { JSONObject frameData = metadata_.getJSONObject(frameKey); frameData.put(key, value); } catch (JSONException e) { throw new MMAcqDataException(e); } } public void setImageValue(int frame, int channel, int slice, String key, int value) throws MMAcqDataException { setImageValue(frame, channel, slice, key, Integer.toString(value)); } public void setImageValue(int frame, int channel, int slice, String key, double value) throws MMAcqDataException { setImageValue(frame, channel, slice, key, Double.toString(value)); } public void setSystemState(int frame, int channel, int slice, JSONObject state) throws MMAcqDataException { if (metadata_ == null) throw new MMAcqDataException("No image data available."); if (frame <0 || frame >= frames_ || channel < 0 || channel >= channels_ || slice < 0 || slice >= slices_) throw new MMAcqDataException("Invalid image coordinates (frame,channel,slice): " + frame + "," + channel + "," + slice); String frameKey = ImageKey.generateFrameKey(frame, channel, slice); JSONObject stateData; try { if (metadata_.has(SummaryKeys.SYSTEM_STATE)) stateData = metadata_.getJSONObject(SummaryKeys.SYSTEM_STATE); else stateData = new JSONObject(); stateData.put(frameKey, state); metadata_.put(SummaryKeys.SYSTEM_STATE, stateData); } catch (JSONException e) { throw new MMAcqDataException(e); } } public JSONObject getSystemState(int frame, int channel, int slice) throws MMAcqDataException { if (metadata_ == null) throw new MMAcqDataException("No image data available."); if (frame <0 || frame >= frames_ || channel < 0 || channel >= channels_ || slice < 0 || slice >= slices_) throw new MMAcqDataException("Invalid image coordinates (frame,channel,slice): " + frame + "," + channel + "," + slice); if (!metadata_.has(SummaryKeys.SYSTEM_STATE)) return new JSONObject(); String frameKey = ImageKey.generateFrameKey(frame, channel, slice); try { JSONObject stateData = metadata_.getJSONObject(SummaryKeys.SYSTEM_STATE); return stateData.getJSONObject(frameKey); } catch (JSONException e) { throw new MMAcqDataException(e); } } public String getSystemStateValue(int frame, int channel, int slice, String key) throws MMAcqDataException { if (metadata_ == null) throw new MMAcqDataException("No image data available."); if (frame <0 || frame >= frames_ || channel < 0 || channel >= channels_ || slice < 0 || slice >= slices_) throw new MMAcqDataException("Invalid image coordinates (frame,channel,slice): " + frame + "," + channel + "," + slice); if (!metadata_.has(SummaryKeys.SYSTEM_STATE)) return ""; String frameKey = ImageKey.generateFrameKey(frame, channel, slice); try { JSONObject stateData = metadata_.getJSONObject(SummaryKeys.SYSTEM_STATE); JSONObject state = stateData.getJSONObject(frameKey); return state.getString(key); } catch (JSONException e) { throw new MMAcqDataException(e); } } /** * Returns an entire set of available keys (properties) associated with the specified image coordinates. * @param frame * @param channel * @param slice * @return - array of available keys * @throws MMAcqDataException */ @SuppressWarnings("unchecked") public String[] getImageKeys(int frame, int channel, int slice) throws MMAcqDataException { if (metadata_ == null) throw new MMAcqDataException("No image data available."); if (frame <0 || frame >= frames_ || channel < 0 || channel >= channels_ || slice < 0 || slice >= slices_) throw new MMAcqDataException("Invalid image coordinates (frame,channel,slice): " + frame + "," + channel + "," + slice); String frameKey = ImageKey.generateFrameKey(frame, channel, slice); JSONObject frameData; try { frameData = metadata_.getJSONObject(frameKey); } catch (JSONException e) { throw new MMAcqDataException(e); } String keys[] = new String[frameData.length()]; int count = 0; for (Iterator i = frameData.keys(); i.hasNext();) keys[count++] = (String)i.next(); return keys; } /** * Returns channel colors. * @return - array of colors * @throws MMAcqDataException */ public Color[] getChannelColors() throws MMAcqDataException { if (!summary_.has(SummaryKeys.CHANNEL_COLORS)) return null; JSONArray metaColors; Color colors[] = new Color[channels_]; if (channels_ > 0) { try { metaColors = summary_.getJSONArray(SummaryKeys.CHANNEL_COLORS); for (int i=0; i<channels_; i++) { colors[i] = new Color(metaColors.getInt(i)); } } catch (JSONException e) { throw new MMAcqDataException(e); } } return colors; } /** * Sets channel colors. * The number of colors should match the number of channels. * @param colors * @throws MMAcqDataException */ public void setChannelColors(Color[] colors) throws MMAcqDataException { JSONArray jsonColors = new JSONArray(); for (int i=0; i<colors.length; i++) { jsonColors.put(colors[i].getRGB()); } try { summary_.put(SummaryKeys.CHANNEL_COLORS, jsonColors); metadata_.put(SummaryKeys.SUMMARY, summary_); } catch (JSONException e) { throw new MMAcqDataException(e); } if (!inmemory_) writeMetadata(); } /** * Sets a color associated with a single channel. * @param channel - channel index * @param rgb - integer representation of the RGB value * @throws MMAcqDataException */ public void setChannelColor(int channel, int rgb) throws MMAcqDataException { if (channels_ <= channel) throw new MMAcqDataException(ERR_CHANNEL_INDEX); JSONArray chanColors; try { if (summary_.has(SummaryKeys.CHANNEL_COLORS)) chanColors = summary_.getJSONArray(SummaryKeys.CHANNEL_COLORS); else { chanColors = new JSONArray(); } chanColors.put(channel, rgb); summary_.put(SummaryKeys.CHANNEL_COLORS, chanColors); } catch (JSONException e) { throw new MMAcqDataException(e); } } /** * Returns display settings for channels. * @return - an array of settings or null if not available. * @throws MMAcqDataException */ public DisplaySettings[] getChannelDisplaySettings() throws MMAcqDataException { JSONArray minContrast = null; JSONArray maxContrast = null; DisplaySettings settings[] = new DisplaySettings[channels_]; if (summary_.has(SummaryKeys.CHANNEL_CONTRAST_MIN) && summary_.has(SummaryKeys.CHANNEL_CONTRAST_MAX)) { try { minContrast = summary_.getJSONArray(SummaryKeys.CHANNEL_CONTRAST_MIN); maxContrast = summary_.getJSONArray(SummaryKeys.CHANNEL_CONTRAST_MAX); for (int i=0; i<channels_; i++) { settings[i] = new DisplaySettings(minContrast.getDouble(i), maxContrast.getDouble(i)); } } catch (JSONException e) { throw new MMAcqDataException(e); } } else { return null; } return settings; } /** * Sets contrast limits for all channels. * @param ds - display settings array * @throws MMAcqDataException */ public void setChannelDisplaySettings(DisplaySettings[] ds) throws MMAcqDataException { JSONArray minContrast = new JSONArray(); JSONArray maxContrast = new JSONArray(); try { for (int i=0; i<ds.length; i++) { minContrast.put(ds[i].min); maxContrast.put(ds[i].max); } summary_.put(SummaryKeys.CHANNEL_CONTRAST_MIN, minContrast); summary_.put(SummaryKeys.CHANNEL_CONTRAST_MAX, maxContrast); metadata_.put(SummaryKeys.SUMMARY, summary_); } catch (JSONException e) { throw new MMAcqDataException(e); } if (!inmemory_) writeMetadata(); } /** * Sets display parameters for a single channel * @param channelIdx * @param ds * @throws MMAcqDataException */ public void setChannelDisplaySetting(int channelIdx, DisplaySettings ds) throws MMAcqDataException { JSONArray minContrast; JSONArray maxContrast; try { if (summary_.has(SummaryKeys.CHANNEL_CONTRAST_MIN)) minContrast = summary_.getJSONArray(SummaryKeys.CHANNEL_CONTRAST_MIN); else minContrast = new JSONArray(); if (summary_.has(SummaryKeys.CHANNEL_CONTRAST_MAX)) maxContrast = summary_.getJSONArray(SummaryKeys.CHANNEL_CONTRAST_MAX); else maxContrast = new JSONArray(); minContrast.put(channelIdx, ds.min); maxContrast.put(channelIdx, ds.max); summary_.put(SummaryKeys.CHANNEL_CONTRAST_MIN, minContrast); summary_.put(SummaryKeys.CHANNEL_CONTRAST_MAX, maxContrast); } catch (JSONException e) { throw new MMAcqDataException(e); } } /** * Returns pixel array for the entire image specified by coordinates: frame, channel, slice. * Pixels are packed by lines. The type of the array depends on the pixel depth (getPixelDepth()), e.g. * byte[] (depth 1), or short[] (depth 2). * Size of the array is width * height (getImageWidth() and getImageHeight()) * If the frame is missing, this method returns null. * @param frame * @param channel * @param slice * @return - pixel array * @throws MMAcqDataException */ public Object getPixels(int frame, int channel, int slice) throws MMAcqDataException { if (metadata_ == null) throw new MMAcqDataException("No image data available."); if (frame <0 || frame >= frames_ || channel < 0 || channel >= channels_ || slice < 0 || slice >= slices_) throw new MMAcqDataException("Invalid image coordinates (frame,channel,slice): " + frame + "," + channel + "," + slice); String frameKey = ImageKey.generateFrameKey(frame, channel, slice); JSONObject frameData; String fileName; if (metadata_.has(frameKey)) { if (inmemory_) { // access pixel data from the memory ImageProcessor ip = images_.get(frameKey); if (ip == null) return null; else return ip.getPixels(); } else { // access pixel data from a file try { frameData = metadata_.getJSONObject(frameKey); fileName = frameData.getString(ImagePropertyKeys.FILE); } catch (JSONException e) { throw new MMAcqDataException(e); } ImagePlus imp; try { Opener opener = new Opener(); imp = opener.openTiff(basePath_ + "/", fileName); } catch (OutOfMemoryError e) { throw new MMAcqDataException("Out of Memory..."); } if (imp == null) { throw new MMAcqDataException("Unable to open file " + fileName); } return imp.getProcessor().getPixels(); } } else // frame does not exist return null; } /** * Returns full path of the image file. * * @param frame * @param channel * @param slice * @return String - full file path * @throws MMAcqDataException */ public String getImagePath(int frame, int channel, int slice) throws MMAcqDataException { if (inmemory_) throw new MMAcqDataException("Image path not defined - acquisition data is created in-memory."); return basePath_ + "/" + getImageFileName(frame, channel, slice); } public String getImageFileName(int frame, int channel, int slice) throws MMAcqDataException { if (metadata_ == null) throw new MMAcqDataException("No image data available."); if (frame <0 || frame >= frames_ || channel < 0 || channel >= channels_ || slice < 0 || slice >= slices_) throw new MMAcqDataException("Invalid image coordinates (frame,channel,slice): " + frame + "," + channel + "," + slice); // TODO: change to parsing String frameKey = ImageKey.generateFrameKey(frame, channel, slice); JSONObject frameData; String fileName; try { frameData = metadata_.getJSONObject(frameKey); fileName = frameData.getString(ImagePropertyKeys.FILE); } catch (JSONException e) { throw new MMAcqDataException(e); } return fileName; } /** * ImageJ specific command, to provide calibration information. * @return */ public Calibration ijCal() { Calibration cal = new Calibration(); if (getPixelSize_um() != 0) { cal.setUnit("um"); cal.pixelWidth = getPixelSize_um(); cal.pixelHeight = getPixelSize_um(); } if (getNumberOfSlices() > 1) { double zDist; try { if (summary_.has(SummaryKeys.IMAGE_Z_STEP_UM)) zDist = summary_.getDouble(SummaryKeys.IMAGE_Z_STEP_UM); else { String z1, z2; z1 = getImageValue(1, 1, 0, "Z-um"); z2 = getImageValue(1, 1, 1, "Z-um"); zDist = Double.valueOf(z2).doubleValue() - Double.valueOf(z1).doubleValue(); } } catch (JSONException j) { return null; } catch (MMAcqDataException e) { return null; } cal.pixelDepth = zDist; cal.setUnit("um"); } if (getNumberOfFrames() > 1) { double interval; try { if (summary_.has(SummaryKeys.IMAGE_INTERVAL_MS)) interval = summary_.getDouble(SummaryKeys.IMAGE_INTERVAL_MS); else { String t1, t2; t1 = getImageValue(0, 1, 1, "ElapsedTime-ms"); t2 = getImageValue(getNumberOfFrames() - 1, 1, 1, "ElapsedTime-ms"); interval = Double.valueOf(t2).doubleValue() - Double.valueOf(t1).doubleValue(); interval = interval / (getNumberOfFrames() - 1); } } catch (JSONException j) { System.out.println("JSON exception in t"); return null; } catch (MMAcqDataException e) { System.out.println("Caught exception in t"); return null; } cal.frameInterval = interval; cal.setTimeUnit("ms"); } return cal; } /** * Determine contrast display settings based on the specified image * @param frame * @param channel * @param slice * @throws MMAcqDataException */ public DisplaySettings[] setChannelContrastBasedOnFrameAndSlice(int frame, int slice) throws MMAcqDataException { JSONArray minArray = new JSONArray(); JSONArray maxArray = new JSONArray(); DisplaySettings[] settings = new DisplaySettings[channels_]; try { for (int i=0; i<channels_; i++) { Object img = getPixels(frame, i, slice); if (img == null) throw new MMAcqDataException("Image does not exist for specified coordinates."); ImageProcessor ip; if (img instanceof byte[]) ip = new ByteProcessor(imgWidth_, imgHeight_); else if (img instanceof short[]) ip = new ShortProcessor(imgWidth_, imgHeight_); else throw new MMAcqDataException("Internal error: unrecognized pixel type"); ip.setPixels(img); ImagePlus imp = new ImagePlus("test", ip); ImageStatistics istat = imp.getStatistics(); minArray.put(istat.min); maxArray.put(istat.max); settings[i] = new DisplaySettings(); settings[i].min = istat.min; settings[i].max = istat.max; } summary_.put(SummaryKeys.CHANNEL_CONTRAST_MIN, minArray); summary_.put(SummaryKeys.CHANNEL_CONTRAST_MAX, maxArray); metadata_.put(SummaryKeys.SUMMARY, summary_); } catch (JSONException e) { throw new MMAcqDataException(e); } if (!inmemory_) writeMetadata(); return settings; } /** * Creates the new acquisition data set. * If the object was already pointing to another data set, it * will be simply disconnected from it - no data will be lost. * The actual name of the directory for the data set will be * created using "name" variable as the prefix and the acquisition * number as the suffix. Acquisition numbers are automatically generated: * e.g. "name_0", "name_1", etc. * @param name - acquisition name (title) * @param path - root directory for the acquisition * @throws MMAcqDataException */ public void createNew(String name, String path, boolean autoName) throws MMAcqDataException { metadata_ = new JSONObject(); summary_ = new JSONObject(); positionProperties_ = new JSONObject(); inmemory_ = false; images_ = null; frames_=0; slices_=0; channels_=0; imgWidth_= 0; imgHeight_= 0; imgDepth_= 0; pixelSize_um_ = 0.0; pixelAspect_ = 1.0; ijType_ = 0; channelNames_ = new String[channels_]; // set initial summary data try { summary_.put(SummaryKeys.GUID, guidgen_.genNewGuid()); version_ = SummaryKeys.VERSION; summary_.put(SummaryKeys.METADATA_VERSION, version_); summary_.put(SummaryKeys.METADATA_SOURCE, SummaryKeys.SOURCE); summary_.put(SummaryKeys.NUM_FRAMES, frames_); summary_.put(SummaryKeys.NUM_CHANNELS, channels_); summary_.put(SummaryKeys.NUM_SLICES, slices_); summary_.put(SummaryKeys.IMAGE_WIDTH, imgWidth_); summary_.put(SummaryKeys.IMAGE_HEIGHT, imgHeight_); summary_.put(SummaryKeys.IMAGE_DEPTH, imgDepth_); summary_.put(SummaryKeys.IJ_IMAGE_TYPE, ijType_); summary_.put(SummaryKeys.IMAGE_PIXEL_SIZE_UM, pixelSize_um_); summary_.put(SummaryKeys.IMAGE_PIXEL_ASPECT, pixelAspect_); summary_.put(SummaryKeys.IMAGE_INTERVAL_MS, 0.0); summary_.put(SummaryKeys.IMAGE_Z_STEP_UM, 0.0); creationTime_ = new GregorianCalendar(); summary_.put(SummaryKeys.TIME, creationTime_.getTime()); summary_.put(SummaryKeys.COMMENT, "empty"); metadata_.put(SummaryKeys.SUMMARY, summary_); } catch (JSONException e) { throw new MMAcqDataException(e); } // create directory String actualName = name; if (autoName) actualName = generateRootName(name, path); basePath_ = path + "/" + actualName; File outDir = new File(basePath_); if (!outDir.mkdirs()) throw new MMAcqDataException("Unable to create directory: " + basePath_ + ". It already exists."); name_ = actualName; // write initial metadata writeMetadata(); } /** * Creates a new in-memory acquisition data set. * If the object was already pointing to another data set, it * will be simply disconnected from it - no data will be lost. * @throws MMAcqDataException */ public void createNew() throws MMAcqDataException { metadata_ = new JSONObject(); summary_ = new JSONObject(); positionProperties_ = new JSONObject(); inmemory_ = true; frames_=0; slices_=0; channels_=0; imgWidth_= 0; imgHeight_= 0; imgDepth_= 0; pixelSize_um_ = 0.0; pixelAspect_ = 1.0; ijType_ = 0; channelNames_ = new String[channels_]; // set initial summary data try { summary_.put(SummaryKeys.GUID, guidgen_.genNewGuid()); version_ = SummaryKeys.VERSION; summary_.put(SummaryKeys.METADATA_VERSION, version_); summary_.put(SummaryKeys.METADATA_SOURCE, SummaryKeys.SOURCE); summary_.put(SummaryKeys.NUM_FRAMES, frames_); summary_.put(SummaryKeys.NUM_CHANNELS, channels_); summary_.put(SummaryKeys.NUM_SLICES, slices_); summary_.put(SummaryKeys.IMAGE_WIDTH, imgWidth_); summary_.put(SummaryKeys.IMAGE_HEIGHT, imgHeight_); summary_.put(SummaryKeys.IMAGE_DEPTH, imgDepth_); summary_.put(SummaryKeys.IJ_IMAGE_TYPE, ijType_); summary_.put(SummaryKeys.IMAGE_PIXEL_SIZE_UM, pixelSize_um_); summary_.put(SummaryKeys.IMAGE_PIXEL_ASPECT, pixelAspect_); summary_.put(SummaryKeys.IMAGE_INTERVAL_MS, 0.0); summary_.put(SummaryKeys.IMAGE_Z_STEP_UM, 0.0); creationTime_ = new GregorianCalendar(); summary_.put(SummaryKeys.TIME, creationTime_.getTime()); summary_.put(SummaryKeys.COMMENT, "empty"); metadata_.put(SummaryKeys.SUMMARY, summary_); } catch (JSONException e) { throw new MMAcqDataException(e); } basePath_ = null; name_ = "in-memory"; images_ = new Hashtable<String, ImageProcessor>(); } /** * Defines physical dimensions of the image: height and width in pixels, * depth in bytes. * @param width - X dimension (columns) * @param height - Y dimension (rows) * @param depth - bytes per pixel * @throws MMAcqDataException */ public void setImagePhysicalDimensions(int width, int height, int depth) throws MMAcqDataException { imgWidth_= width; imgHeight_= height; imgDepth_= depth; if (imgDepth_ == 1) ijType_ = ImagePlus.GRAY8; else if (imgDepth_ == 2) ijType_ = ImagePlus.GRAY16; else throw new MMAcqDataException("Unsupported pixel depth: " + imgDepth_); try { summary_.put(SummaryKeys.IMAGE_WIDTH, imgWidth_); summary_.put(SummaryKeys.IMAGE_HEIGHT, imgHeight_); summary_.put(SummaryKeys.IMAGE_DEPTH, imgDepth_); summary_.put(SummaryKeys.IJ_IMAGE_TYPE, ijType_); metadata_.put(SummaryKeys.SUMMARY, summary_); } catch (JSONException e) { throw new MMAcqDataException(e); } if (!inmemory_) writeMetadata(); } /** * Sets time, wavelength and focus dimensions of the data set. * @param frames - number or frames (time) * @param channels - number of channels (wavelength) * @param slices - number of slices (Z, or focus) * @throws MMAcqDataException */ public void setDimensions(int frames, int channels, int slices) throws MMAcqDataException { boolean resetNames = false; if (channels != channels_) resetNames = true; frames_ = frames; channels_ = channels; slices_ = slices; // update summary try { summary_.put(SummaryKeys.NUM_FRAMES, frames_); summary_.put(SummaryKeys.NUM_CHANNELS, channels_); summary_.put(SummaryKeys.NUM_SLICES, slices_); // TODO: non-destructive fill-in of default names if (resetNames) defaultChannelNames(); metadata_.put(SummaryKeys.SUMMARY, summary_); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } //if (!inmemory_) //writeMetadata(); } /** * Inserts a single image into the acquisition data set. * @param img - image object pixels * @param frame - frame (time sample)index * @param channel - channel index * @param slice - slice (focus) index * @return - actual file name without the path * @throws MMAcqDataException */ public String insertImage(Object img, int frame, int channel, int slice) throws MMAcqDataException { if (metadata_ == null) throw new MMAcqDataException("Summary metadata not initialized"); if (frame <0 || channel < 0 || channel >= channels_ || slice < 0 || slice >= slices_) throw new MMAcqDataException("Invalid image coordinates (frame,channel,slice): " + frame + "," + channel + "," + slice); String fname = ImageKey.generateFileName(frame, channelNames_[channel], slice); String frameKey = ImageKey.generateFrameKey(frame, channel, slice); try { // increase frame count if necessary if (frame >= frames_) { frames_ = frame + 1; summary_.put(SummaryKeys.NUM_FRAMES, frames_); } JSONObject frameData = new JSONObject(); frameData.put(ImagePropertyKeys.FILE, fname); frameData.put(ImagePropertyKeys.FRAME, frame); frameData.put(ImagePropertyKeys.CHANNEL, channelNames_[channel]); frameData.put(ImagePropertyKeys.SLICE, slice); GregorianCalendar gc = new GregorianCalendar(); frameData.put(ImagePropertyKeys.TIME, gc.getTime()); frameData.put(ImagePropertyKeys.ELAPSED_TIME_MS, gc.getTimeInMillis() - creationTime_.getTimeInMillis() ); frameData.put(ImagePropertyKeys.EXPOSURE_MS, 0.0); // TODO metadata_.put(frameKey, frameData); } catch (JSONException e) { throw new MMAcqDataException(e); } if (inmemory_) { // save pixels to memory ImageProcessor ip = createCompatibleIJImageProcessor(img); images_.put(frameKey, ip); } else { // save pixels to disk saveImageFile(basePath_ + "/" + fname, img, (int)imgWidth_, (int)imgHeight_); //writeMetadata(); } return fname; } /** * Attaches a single image into the acquisition data set. * The metadata for a given coordinates must already exist. * @param img - image object pixels * @param frame - frame (time sample)index * @param channel - channel index * @param slice - slice (focus) index * @return - actual file name without the path * @throws MMAcqDataException */ public String attachImage(Object img, int frame, int channel, int slice) throws MMAcqDataException { if (metadata_ == null) throw new MMAcqDataException("Summary metadata not initialized"); if (frame <0 || frame >= frames_ || channel < 0 || channel >= channels_ || slice < 0 || slice >= slices_) throw new MMAcqDataException("Invalid image coordinates (frame,channel,slice): " + frame + "," + channel + "," + slice); String fname = ImageKey.generateFileName(frame, channelNames_[channel], slice); String frameKey = ImageKey.generateFrameKey(frame, channel, slice); if (!metadata_.has(frameKey)) throw new MMAcqDataException("Could not attach image file: metadata does not exist for these coordinates."); try { JSONObject frameData = metadata_.getJSONObject(frameKey); frameData.put(ImagePropertyKeys.FILE, fname); metadata_.put(frameKey, frameData); } catch (JSONException e) { throw new MMAcqDataException(e); } if (inmemory_) { // save pixels to memory ImageProcessor ip = createCompatibleIJImageProcessor(img); images_.put(frameKey, ip); } else { // save pixels to disk saveImageFile(basePath_ + "/" + fname, img, (int)imgWidth_, (int)imgHeight_); // writeMetadata(); } return fname; } /** * Inserts a single image metadata into the acquisition data set. * This method is used to generate metadata without recording pixel data in any way. * @param img - image object pixels * @param frame - frame (time sample)index * @param channel - channel index * @param slice - slice (focus) index * @return - actual file name without the path * @throws MMAcqDataException */ public void insertImageMetadata(int frame, int channel, int slice) throws MMAcqDataException { if (metadata_ == null) throw new MMAcqDataException("Summary metadata not initialized"); if (frame <0 || channel < 0 || channel >= channels_ || slice < 0 || slice >= slices_) throw new MMAcqDataException("Invalid image coordinates (frame,channel,slice): " + frame + "," + channel + "," + slice); // increase frame count if necessary if (frame >= frames_) { frames_ = frame + 1; } String frameKey = ImageKey.generateFrameKey(frame, channel, slice); try { JSONObject frameData = new JSONObject(); frameData.put(ImagePropertyKeys.FRAME, frame); frameData.put(ImagePropertyKeys.CHANNEL, channelNames_[channel]); frameData.put(ImagePropertyKeys.SLICE, slice); GregorianCalendar gc = new GregorianCalendar(); frameData.put(ImagePropertyKeys.TIME, gc.getTime()); frameData.put(ImagePropertyKeys.ELAPSED_TIME_MS, gc.getTimeInMillis() - creationTime_.getTimeInMillis() ); frameData.put(ImagePropertyKeys.EXPOSURE_MS, 0.0); // TODO metadata_.put(frameKey, frameData); } catch (JSONException e) { throw new MMAcqDataException(e); } if (!inmemory_) { //writeMetadata(); } } /** * Converts an in-memory data to persistent disk based directory. * @param path * @throws MMAcqDataException */ public void save(String name, String path, boolean autoName, SaveProgressCallback scb) throws MMAcqDataException { if (!inmemory_) throw new MMAcqDataException("This data is already created as persistent - location can't be changed."); // create directory String actualName = name; if (autoName) actualName = generateRootName(name, path); String bp = path + "/" + actualName; File outDir = new File(bp); if (!outDir.mkdirs()) { throw new MMAcqDataException("Unable to create directory: " + bp); } basePath_ = bp; name_ = actualName; // write initial metadata writeMetadata(); // write images for (Enumeration<String> e = images_.keys() ; e.hasMoreElements(); ) { String frameKey = e.nextElement(); JSONObject frameData; String fname; try { frameData = metadata_.getJSONObject(frameKey); if (frameData.has(ImagePropertyKeys.FILE)) { fname = frameData.getString(ImagePropertyKeys.FILE); String filePath = basePath_ + "/" + fname; ImagePlus imp = new ImagePlus(fname, images_.get(frameKey)); FileSaver fs = new FileSaver(imp); fs.saveAsTiff(filePath); } } catch (JSONException exc) { throw new MMAcqDataException(exc); } if (scb != null) scb.imageSaved(); } // finally tag the object as persistent (not in-memory) inmemory_ = false; images_ = null; } public void saveMetadata() throws MMAcqDataException { if (inmemory_) throw new MMAcqDataException("Unable to save metadata - this acquisition is defined as 'in-memory'."); writeMetadata(); } /** * Utility to save TIF files. * No connection to the metadata. * @param fname - file path * @param img - pixels * @param width * @param height * @return */ static public boolean saveImageFile(String fname, Object img, int width, int height) { ImageProcessor ip; if (img instanceof byte[]) { ip = new ByteProcessor(width, height); ip.setPixels((byte[])img); } else if (img instanceof short[]) { ip = new ShortProcessor(width, height); ip.setPixels((short[])img); } else return false; ImagePlus imp = new ImagePlus(fname, ip); FileSaver fs = new FileSaver(imp); return fs.saveAsTiff(fname); } /** * @return the imageInterval */ public double getImageIntervalMs() { return imageInterval_ms_; } /** * Sets image interval annotation. * @param imageInterval_ms */ public void setImageIntervalMs(double imageInterval_ms) { imageInterval_ms_ = imageInterval_ms; try { summary_.put(SummaryKeys.IMAGE_INTERVAL_MS, imageInterval_ms); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Returns focus step for slices. * @return the imageZStep_um_ */ public double getImageZStepUm() { return imageZStep_um_; } /** * Sets focus step for slices. * @param imageZStep_um */ public void setImageZStepUm(double imageZStep_um) { imageZStep_um_ = imageZStep_um; try { summary_.put(SummaryKeys.IMAGE_Z_STEP_UM, imageZStep_um); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void setComment(String comment) throws MMAcqDataException { setSummaryValue(SummaryKeys.COMMENT, comment); } public String getComment() throws MMAcqDataException { return getSummaryValue(SummaryKeys.COMMENT); } public void setPixelSizeUm(double pixelSize_um) throws MMAcqDataException { setSummaryValue(SummaryKeys.IMAGE_PIXEL_SIZE_UM, Double.toString(pixelSize_um)); } // Private methods static private String generateRootPath(String name, String baseDir) { return baseDir + "/" + generateRootName(name, baseDir); } static private String generateRootName(String name, String baseDir) { // create new acquisition directory int suffixCounter = 0; String testPath; File testDir; String testName; do { testName = name + "_" + suffixCounter; testPath = new String(baseDir + "/" + testName); suffixCounter++; testDir = new File(testPath); } while (testDir.exists()); return testName; } private void reset() { metadata_ = new JSONObject(); summary_ = new JSONObject(); inmemory_ = true; positionProperties_ = new JSONObject(); frames_=0; slices_=0; channels_=0; imgWidth_= 0; imgHeight_= 0; imgDepth_= 0; pixelSize_um_ = 0.0; pixelAspect_ = 1.0; ijType_ = 0; channelNames_ = new String[0]; basePath_ = new String(); name_ = new String(); creationTime_ = new GregorianCalendar(); } private void writeMetadata() throws MMAcqDataException { File outDir = new File(basePath_); try { String metaStream = metadata_.toString(3); FileWriter fw = new FileWriter(new File(outDir.getAbsolutePath() + "/" + ImageKey.METADATA_FILE_NAME)); fw.write(metaStream); fw.close(); } catch (IOException e) { reset(); throw new MMAcqDataException("Unable to create metadata file"); } catch (JSONException e) { reset(); throw new MMAcqDataException(ERR_METADATA_CREATE); } } private void parse() throws MMAcqDataException { try { summary_ = metadata_.getJSONObject(SummaryKeys.SUMMARY); // extract position properties (if any) if (summary_.has(SummaryKeys.POSITION_PROPERTIES)) { positionProperties_ = summary_.getJSONObject(SummaryKeys.POSITION_PROPERTIES); } else { // initialize to empty positionProperties_ = new JSONObject(); } // extract summary data frames_ = summary_.getInt(SummaryKeys.NUM_FRAMES); channels_ = summary_.getInt(SummaryKeys.NUM_CHANNELS); slices_ = summary_.getInt(SummaryKeys.NUM_SLICES); imgWidth_ = summary_.getInt(SummaryKeys.IMAGE_WIDTH); imgHeight_ = summary_.getInt(SummaryKeys.IMAGE_HEIGHT); imgDepth_ = summary_.getInt(SummaryKeys.IMAGE_DEPTH); ijType_ = summary_.getInt(SummaryKeys.IJ_IMAGE_TYPE); if (summary_.has(SummaryKeys.METADATA_VERSION)) version_ = summary_.getInt(SummaryKeys.METADATA_VERSION); else version_ = 0; // unknown if (summary_.has(SummaryKeys.IMAGE_PIXEL_SIZE_UM)) pixelSize_um_ = summary_.getDouble(SummaryKeys.IMAGE_PIXEL_SIZE_UM); else pixelSize_um_ = 0.0; // uncalibrated if (summary_.has(SummaryKeys.IMAGE_PIXEL_ASPECT)) pixelAspect_ = summary_.getDouble(SummaryKeys.IMAGE_PIXEL_ASPECT); else pixelAspect_ = 1.0; // square pixels are default if (summary_.has(SummaryKeys.IMAGE_INTERVAL_MS)) imageInterval_ms_ = summary_.getDouble(SummaryKeys.IMAGE_INTERVAL_MS); else { imageInterval_ms_ = 0.0; } if (summary_.has(SummaryKeys.IMAGE_Z_STEP_UM)) imageZStep_um_ = summary_.getDouble(SummaryKeys.IMAGE_Z_STEP_UM); else { imageZStep_um_ = 0.0; } if (!summary_.has(SummaryKeys.CHANNEL_NAMES)) { defaultChannelNames(); } JSONArray metaNames; channelNames_ = new String[channels_]; if (channels_ > 0) { try { metaNames = summary_.getJSONArray(SummaryKeys.CHANNEL_NAMES); for (int i=0; i<channels_; i++) { channelNames_[i] = metaNames.getString(i); } } catch (JSONException e) { throw new MMAcqDataException(e); } } } catch (JSONException e) { throw new MMAcqDataException(e); } } private void defaultChannelNames() throws JSONException { JSONArray channelNames = new JSONArray(); channelNames_ = new String[channels_]; for (int i=0; i<channels_; i++) { channelNames_[i] = new String("Channel-" + i); channelNames.put(channelNames_[i]); } summary_.put(SummaryKeys.CHANNEL_NAMES, channelNames); } private ImageProcessor createCompatibleIJImageProcessor(Object img) throws MMAcqDataException { ImageProcessor ip = null; if (img instanceof byte[]) { ip = new ByteProcessor(imgWidth_, imgHeight_); ip.setPixels((byte[])img); } else if (img instanceof short[]) { ip = new ShortProcessor(imgWidth_, imgHeight_); ip.setPixels((short[])img); } if (ip == null) throw new MMAcqDataException("Unrecognized pixel type."); else return ip; } }
package tester; import java.io.*; import java.util.*; import java.lang.*; import java.lang.reflect.*; import java.lang.annotation.*; import org.junit.*; import org.junit.rules.*; import org.junit.runner.*; import org.junit.runners.model.*; import tools.sep.*; public class ReadReplace{ public static String getSig(Method m){ String sig = m.getDeclaringClass().getName() + "." + m.getName() + "("; for(Class p : m.getParameterTypes()){ sig += p.getSimpleName() + ", "; } if(m.getParameterTypes().length > 0){ sig = sig.substring(0, sig.length()-2); } return sig + ")"; } public static String getCanonicalReplacement(Replace r) { Map<String, SortedSet<String>> mMethsMap = getMap(r); String ncln = ""; for(Map.Entry<String, SortedSet<String>> e : mMethsMap.entrySet()){ ncln += "@" + e.getKey(); for(String me : e.getValue()) ncln += " } return ncln; } public static Map<String, SortedSet<String>> getMap(Replace r) { Map<String, SortedSet<String>> mMethsMap = new TreeMap<>(); for(int i=0; i<r.value().length; ++i){ int s = r.value()[i].indexOf('.'); String cln; String regex; if(s == -1){ cln = r.value()[i]; regex = ".*"; }else{ cln = r.value()[i].substring(0, s); regex = r.value()[i].substring(s+1); } if(!mMethsMap.containsKey(cln)) mMethsMap.put(cln, new TreeSet<String>()); SortedSet<String> meths = mMethsMap.get(cln); try { for(Method me : Class.forName(cln).getDeclaredMethods()){ if(me.getName().matches(regex)){ meths.add(me.getName()); } } if ("<init>".matches(regex)) { meths.add("<init>"); } } catch (ClassNotFoundException e) { throw new AnnotationFormatError("Cannot replace unknown class: " + cln); } } return mMethsMap; } public static String getCanonicalReplacement(Description description) { if(description.getAnnotation(Replace.class) != null) { Replace r = description.getAnnotation(Replace.class); return getCanonicalReplacement(r); } return ""; } public static void loopSingle(String tcln, String pubClass) throws Exception { HashSet<String> set = new HashSet<>(); ClassLoader cl = ClassLoader.getSystemClassLoader(); Class c = cl.loadClass(tcln); for(Method meth : c.getMethods()) { if(meth.isAnnotationPresent(Replace.class)){ Replace r = meth.getAnnotation(Replace.class); set.add(getCanonicalReplacement(r)); } } // execute sep for single execution String args[] = new String[3]; args[0] = "lib/json-simple-1.1.1.jar:lib/junit.jar:lib/junitpoints.jar:--THIS-WILL-NEVER-HAPPEN:."; args[1] = "-Dreplace=THIS-WILL-NEVER-HAPPEN -Djson=yes"; args[2] = tcln; System.out.println("echo \"[\" 1>&2"); SingleExecutionPreparer.main(args); System.out.println("echo \"]\" 1>&2"); for (String s : set) { String classpath = s.substring(1).replaceAll("@", ":").replaceAll("<", "\\\\<").replaceAll(">", "\\\\>"); System.out.println("echo \",\" 1>&2"); // System.out.println("echo \"[\" 1>&2"); // args[0] = "lib/json-simple-1.1.1.jar:lib/junit.jar:lib/junitpoints.jar:"+classpath+":."; // args[1] = "-Dreplace=" + s.replaceAll("<", "\\\\<").replaceAll(">", "\\\\>") + " -Djson=yes"; // SingleExecutionPreparer.main(args); // System.out.println("echo \"]\" 1>&2"); System.out.println("java -XX:+UseConcMarkSweepGC -Xmx1024m -cp lib/json-simple-1.1.1.jar:lib/junit.jar:lib/junitpoints.jar:" + classpath + ":. -Dreplace=" + s.replaceAll("<", "\\\\<").replaceAll(">", "\\\\>") + " -Djson=yes org.junit.runner.JUnitCore " + tcln + " || echo"); } } public static void loop(String tcln, String pubClass) throws Exception { HashSet<String> set = new HashSet<>(); ClassLoader cl = ClassLoader.getSystemClassLoader(); Class c = cl.loadClass(tcln); for(Method meth : c.getMethods()) { if(meth.isAnnotationPresent(Replace.class)){ Replace r = meth.getAnnotation(Replace.class); set.add(getCanonicalReplacement(r)); } } if(!pubClass.equals("")){ System.out.println("java -XX:+UseConcMarkSweepGC -Xmx1024m -cp lib/json-simple-1.1.1.jar:lib/junit.jar:lib/junitpoints.jar:" + "--THIS-WILL-NEVER-HAPPEN" + ":. -Dreplace=" + "--THIS-WILL-NEVER-HAPPEN" + " -Djson=yes" + " -Dpub=" +pubClass + " org.junit.runner.JUnitCore " + tcln + " || echo"); }else{ System.out.println("java -XX:+UseConcMarkSweepGC -Xmx1024m -cp lib/json-simple-1.1.1.jar:lib/junit.jar:lib/junitpoints.jar:" + "--THIS-WILL-NEVER-HAPPEN" + ":. -Dreplace=" + "--THIS-WILL-NEVER-HAPPEN" + " -Djson=yes org.junit.runner.JUnitCore " + tcln + " || echo"); } for (String s : set) { System.out.println("echo \",\" 1>&2"); String classpath = s.substring(1).replaceAll("@", ":").replaceAll("<", "\\\\<").replaceAll(">", "\\\\>"); if(!pubClass.equals("")){ System.out.println("java -XX:+UseConcMarkSweepGC -Xmx1024m -cp lib/json-simple-1.1.1.jar:lib/junit.jar:lib/junitpoints.jar:" + classpath + ":. -Dreplace=" + s.replaceAll("<", "\\\\<").replaceAll(">", "\\\\>") + " -Djson=yes" + " -Dpub="+pubClass + " org.junit.runner.JUnitCore " + tcln + " || echo"); }else{ System.out.println("java -XX:+UseConcMarkSweepGC -Xmx1024m -cp lib/json-simple-1.1.1.jar:lib/junit.jar:lib/junitpoints.jar:" + classpath + ":. -Dreplace=" + s.replaceAll("<", "\\\\<").replaceAll(">", "\\\\>") + " -Djson=yes org.junit.runner.JUnitCore " + tcln + " || echo"); } } } public static void main(String args[]) throws Exception{ if(args.length < 1){ System.err.println("missing class argument"); System.exit(-1); } if (args[0].equals("--loop")) { String pubClass = ""; if(args[1].equals("--single")) { if(args[2].equals("--secret")){ pubClass = args[3]; loopSingle(args[4],pubClass); }else { loopSingle(args[2],pubClass); } }else { if(args[1].equals("--secret")){ pubClass = args[2]; loop(args[3],pubClass); }else { loop(args[1],pubClass); } } return; } String tcln = args[0]; ClassLoader cl = ClassLoader.getSystemClassLoader(); Class c = cl.loadClass(tcln); HashSet<String> pres = new HashSet<>(); HashSet<String> mids = new HashSet<>(); HashSet<String> posts = new HashSet<>(); for(Method meth : c.getMethods()) { if(meth.isAnnotationPresent(Replace.class)){ Replace r = meth.getAnnotation(Replace.class); Map<String, SortedSet<String>> methsMap = getMap(r); for(Map.Entry<String, SortedSet<String>> e : methsMap.entrySet()){ String ncln = e.getKey(); if(e.getValue().size() == 0) continue; for(String me : e.getValue()) ncln += "#" + me.replaceAll("<", "\\\\<").replaceAll(">", "\\\\>"); pres.add("cp cleanroom/" + e.getKey() + ".java cleanroom/orig_" + e.getKey() + ".java; " + "/bin/echo -e \"package cleanroom;\" > cleanroom/" + e.getKey() + ".java; " + "cat cleanroom/orig_" + e.getKey() + ".java >> cleanroom/" + e.getKey() + ".java;"); mids.add("mkdir -p " + ncln + "; " + "javac -cp .:lib/tools.jar:lib/junit.jar:lib/junitpoints.jar -Areplaces=" + ncln + " -proc:only -processor ReplaceMixer cleanroom/" + e.getKey() + ".java " + e.getKey() + ".java > " + ncln + "/" + e.getKey() + ".java; " + "javac -cp . -d " + ncln + " -sourcepath " + ncln + " " + ncln + "/" + e.getKey() + ".java;"); posts.add("mv cleanroom/orig_" + e.getKey() + ".java cleanroom/" + e.getKey() + ".java;"); } } } for (String pre : pres) System.out.println(pre); for (String mid : mids) System.out.println(mid); for (String post : posts) System.out.println(post); } }
package com.illposed.osc; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.LinkedList; import java.util.List; import com.illposed.osc.utility.OSCJavaToByteArrayConverter; /** * An simple (non-bundle) OSC message. * * An OSC message is made up of an address (the receiver of the message) * and arguments (the content of the message). * * @author Chandrasekhar Ramakrishnan */ public class OSCMessage extends OSCPacket { private String address; private List<Object> arguments; /** * Creates an empty OSC Message. * In order to send this OSC message, * you need to set the address and optionally some arguments. */ public OSCMessage() { arguments = new LinkedList<Object>(); } /** * Creates an OSCMessage with an address already initialized. * @param address the recipient of this OSC message */ public OSCMessage(String address) { this(address, (Collection<Object>) null); } // deprecated since version 1.0, March 2012 /** * Creates an OSCMessage with an address and arguments already initialized. * @param address the recipient of this OSC message * @param arguments the data sent to the receiver * @deprecated */ public OSCMessage(String address, Object[] arguments) { this.address = address; if (arguments == null) { this.arguments = new LinkedList(); } else { this.arguments = new ArrayList(arguments.length); this.arguments.addAll(Arrays.asList(arguments)); } init(); } /** * Creates an OSCMessage with an address * and arguments already initialized. * @param address the recipient of this OSC message * @param arguments the data sent to the receiver */ public OSCMessage(String address, Collection<Object> arguments) { this.address = address; if (arguments == null) { this.arguments = new LinkedList(); } else { this.arguments = new ArrayList(arguments); } init(); } /** * The receiver of this message. * @return the receiver of this OSC Message */ public String getAddress() { return address; } /** * Set the address of this message. * @param address the receiver of the message */ public void setAddress(String address) { this.address = address; } /** * Add an argument to the list of arguments. * @param argument a Float, String, Integer, BigInteger, Boolean * or an array of these */ public void addArgument(Object argument) { arguments.add(argument); } /** * The arguments of this message. * @return the arguments to this message */ public Object[] getArguments() { return arguments.toArray(); } /** * Convert the address into a byte array. * Used internally only. */ protected void computeAddressByteArray(OSCJavaToByteArrayConverter stream) { stream.write(address); } /** * Convert the arguments into a byte array. * Used internally only. */ protected void computeArgumentsByteArray(OSCJavaToByteArrayConverter stream) { stream.write(','); if (null == arguments) { return; } stream.writeTypes(arguments); for (Object argument : arguments) { stream.write(argument); } } /** * Convert the message into a byte array. * Used internally only. */ protected byte[] computeByteArray(OSCJavaToByteArrayConverter stream) { computeAddressByteArray(stream); computeArgumentsByteArray(stream); return stream.toByteArray(); } }
package com.alexrnl.commons.utils.object; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; /** * Test suite for the object package. * @author Alex */ @RunWith(Suite.class) @SuiteClasses({ AttributeComparatorTest.class, AutoCompareTest.class, ComparisonErrorTest.class, HashCodeUtilsTest.class, ReflectUtilsTest.class }) public class ObjectTests { }
package com.auth0.utils.tokens; import com.auth0.exception.IdTokenValidationException; import com.auth0.exception.PublicKeyProviderException; import com.auth0.jwt.exceptions.AlgorithmMismatchException; import com.auth0.jwt.interfaces.DecodedJWT; import org.bouncycastle.util.io.pem.PemReader; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.nio.file.Paths; import java.security.KeyFactory; import java.security.PublicKey; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.security.interfaces.RSAPublicKey; import java.security.spec.EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.Scanner; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.Matchers.hasProperty; import static org.junit.Assert.assertThat; public class SignatureVerifierTest { private static final String EXPIRED_HS_JWT = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJub25jZSI6IjEyMzQiLCJpc3MiOiJodHRwczovL21lLmF1dGgwLmNvbS8iLCJhdWQiOiJkYU9nbkdzUlloa3d1NjIxdmYiLCJzdWIiOiJhdXRoMHx1c2VyMTIzIiwiZXhwIjo5NzE3ODkzMTd9.5_VOXBmOVMSi8OGgonyfyiJSq3A03PwOEuZlPD-Gxik"; private static final String NONE_JWT = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJub25jZSI6IjEyMzQiLCJpc3MiOiJodHRwczovL21lLmF1dGgwLmNvbS8iLCJhdWQiOiJkYU9nbkdzUlloa3d1NjIxdmYiLCJzdWIiOiJhdXRoMHx1c2VyMTIzIn0."; private static final String HS_JWT = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJub25jZSI6IjEyMzQiLCJpc3MiOiJodHRwczovL21lLmF1dGgwLmNvbS8iLCJhdWQiOiJkYU9nbkdzUlloa3d1NjIxdmYiLCJzdWIiOiJhdXRoMHx1c2VyMTIzIn0.a7ayNmFTxS2D-EIoUikoJ6dck7I8veWyxnje_mYD3qY"; private static final String RS_JWT = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImFiYzEyMyJ9.eyJub25jZSI6IjEyMzQiLCJpc3MiOiJodHRwczovL21lLmF1dGgwLmNvbS8iLCJhdWQiOiJkYU9nbkdzUlloa3d1NjIxdmYiLCJzdWIiOiJhdXRoMHx1c2VyMTIzIn0.PkPWdoZNfXz8EB0SBPH83lNSOhyhdhdqYIgIwgY2nHozUnFOaUjVewlAXxP_3LBGibQ_ng4s5fEEOCJjaKBy04McryvOuL6nqb1dPQseeyxuv2zQitfrs-7kEtfeS3umywM-tV6guw9_W3nmIgaXOiYiF4WJM23ItbdCmvwdXLaf9-xHkQbRY_zEwEFbprFttKUXFbkPt6XjZ3zZwZbNZn64bx2PBiSJ2KMZAE3Lghmci-RXdhi7hXpmN30Tzze1ZsjvVeRRKNzShByKK9ZGZPmQ5yggJOXFy32ehjGkYwFMCqgMQomcGbcYhsd97huKHMHl3HOE5GDYjIq9o9oKRA"; private static final String RS_PUBLIC_KEY = "src/test/resources/keys/public-rsa.pem"; private static final String RS_PUBLIC_KEY_BAD = "src/test/resources/keys/bad-public-rsa.pem"; @Rule public ExpectedException exception = ExpectedException.none(); @Test public void failsWhenAlgorithmIsNotExpected() { exception.expect(IdTokenValidationException.class); exception.expectMessage("Token signed with an unexpected algorithm"); exception.expectCause(isA(AlgorithmMismatchException.class)); SignatureVerifier verifier = SignatureVerifier.forHS256("secret"); verifier.verifySignature(NONE_JWT); } @Test public void failsWhenTokenCannotBeDecoded() { exception.expect(IdTokenValidationException.class); exception.expectMessage("ID token could not be decoded"); SignatureVerifier verifier = SignatureVerifier.forHS256("secret"); verifier.verifySignature("boom"); } @Test public void failsWhenAlgorithmRS256IsNotExpected() { exception.expect(IdTokenValidationException.class); exception.expectMessage("Token signed with an unexpected algorithm"); exception.expectCause(isA(AlgorithmMismatchException.class)); SignatureVerifier verifier = SignatureVerifier.forHS256("secret"); verifier.verifySignature(RS_JWT); } @Test public void failsWhenAlgorithmHS256IsNotExpected() throws Exception { exception.expect(IdTokenValidationException.class); exception.expectMessage("Token signed with an unexpected algorithm"); exception.expectCause(isA(AlgorithmMismatchException.class)); SignatureVerifier verifier = SignatureVerifier.forRS256(getRSProvider(RS_PUBLIC_KEY)); verifier.verifySignature(HS_JWT); } @Test public void succeedsWithValidSignatureHS256Token() { SignatureVerifier verifier = SignatureVerifier.forHS256("secret"); DecodedJWT decodedJWT = verifier.verifySignature(HS_JWT); assertThat(decodedJWT, notNullValue()); } @Test public void succeedsAndIgnoresExpiredTokenException() { SignatureVerifier verifier = SignatureVerifier.forHS256("secret"); DecodedJWT decodedJWT = verifier.verifySignature(EXPIRED_HS_JWT); assertThat(decodedJWT, notNullValue()); } @Test public void failsWithInvalidSignatureHS256Token() { exception.expect(IdTokenValidationException.class); exception.expectMessage("Invalid token signature"); SignatureVerifier verifier = SignatureVerifier.forHS256("badsecret"); verifier.verifySignature(HS_JWT); } @Test public void succeedsWithValidSignatureRS256Token() throws Exception { SignatureVerifier verifier = SignatureVerifier.forRS256(getRSProvider(RS_PUBLIC_KEY)); DecodedJWT decodedJWT = verifier.verifySignature(RS_JWT); assertThat(decodedJWT, notNullValue()); } @Test public void failsWithInvalidSignatureRS256Token() throws Exception { exception.expect(IdTokenValidationException.class); exception.expectMessage("Invalid token signature"); SignatureVerifier verifier = SignatureVerifier.forRS256(getRSProvider(RS_PUBLIC_KEY_BAD)); DecodedJWT decodedJWT = verifier.verifySignature(RS_JWT); assertThat(decodedJWT, notNullValue()); } @Test public void failsWhenErrorGettingPublicKey() { exception.expect(IdTokenValidationException.class); exception.expectCause(isA(PublicKeyProviderException.class)); exception.expectMessage("Error retrieving public key"); SignatureVerifier verifier = SignatureVerifier.forRS256(new PublicKeyProvider() { @Override public RSAPublicKey getPublicKeyById(String keyId) throws PublicKeyProviderException { throw new PublicKeyProviderException("error"); } }); verifier.verifySignature(RS_JWT); } @Test public void failsWhenErrorGettingPublicKeyAndHasNestedExceptionCause() { exception.expect(IdTokenValidationException.class); exception.expectMessage("Error retrieving public key"); exception.expectCause(allOf( instanceOf(PublicKeyProviderException.class), hasProperty("cause", instanceOf(IOException.class)) )); SignatureVerifier verifier = SignatureVerifier.forRS256(new PublicKeyProvider() { @Override public RSAPublicKey getPublicKeyById(String keyId) throws PublicKeyProviderException { throw new PublicKeyProviderException("error", new IOException("error reading file")); } }); verifier.verifySignature(RS_JWT); } @Test public void failsWithNullVerifier() { exception.expect(IllegalArgumentException.class); exception.expectMessage("'verifier' cannot be null"); new NullVerifier(); } private PublicKeyProvider getRSProvider(String rsaPath) throws Exception { return new PublicKeyProvider() { @Override public RSAPublicKey getPublicKeyById(String keyId) throws PublicKeyProviderException { try { return readPublicKeyFromFile(rsaPath); } catch (IOException ioe) { throw new PublicKeyProviderException("Error reading public key", ioe); } }; }; } private static RSAPublicKey readPublicKeyFromFile(final String path) throws IOException { Scanner scanner = null; PemReader pemReader = null; try { scanner = new Scanner(Paths.get(path)); if (scanner.hasNextLine() && scanner.nextLine().startsWith(" FileInputStream fs = new FileInputStream(path); CertificateFactory fact = CertificateFactory.getInstance("X.509"); X509Certificate cer = (X509Certificate) fact.generateCertificate(fs); PublicKey key = cer.getPublicKey(); fs.close(); return (RSAPublicKey) key; } else { pemReader = new PemReader(new FileReader(path)); byte[] keyBytes = pemReader.readPemObject().getContent(); KeyFactory kf = KeyFactory.getInstance("RSA"); EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes); return (RSAPublicKey) kf.generatePublic(keySpec); } } catch (Exception e) { throw new IOException("Couldn't parse the RSA Public Key / Certificate file.", e); } finally { if (scanner != null) { scanner.close(); } if (pemReader != null) { pemReader.close(); } } } private static class NullVerifier extends SignatureVerifier { NullVerifier() { super(null); } } }
package com.nobullet.interview; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * Longest palindrome test. */ public class LongestPalindromeTest { @Test public void test() { assertEquals("123321", LongestPalindrome.getLongestPalindromeON3("0912332189")); assertEquals("91233219", LongestPalindrome.getLongestPalindromeON3("0912332199")); assertEquals("", LongestPalindrome.getLongestPalindromeON3("")); assertEquals("1", LongestPalindrome.getLongestPalindromeON3("12")); assertEquals("12345678900987654321", LongestPalindrome.getLongestPalindromeON3("1 5555555555 00~~12345678900987654321 abbaabbaabbaabbba")); } }
package org.ambraproject.rhino.service; import com.google.common.base.Function; import com.google.common.base.Objects; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableListMultimap; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import com.google.common.collect.Ordering; import com.google.common.collect.Sets; import com.google.common.io.Closeables; import com.google.gson.Gson; import org.ambraproject.models.AmbraEntity; import org.ambraproject.models.Article; import org.ambraproject.models.ArticleAsset; import org.ambraproject.models.ArticlePerson; import org.ambraproject.models.ArticleRelationship; import org.ambraproject.models.Category; import org.ambraproject.models.CitedArticle; import org.ambraproject.models.CitedArticlePerson; import org.ambraproject.models.Journal; import org.ambraproject.rhino.BaseRhinoTest; import org.ambraproject.rhino.content.PersonName; import org.ambraproject.rhino.identity.ArticleIdentity; import org.ambraproject.rhino.identity.AssetFileIdentity; import org.ambraproject.rhino.identity.AssetIdentity; import org.ambraproject.rhino.test.AssertionCollector; import org.hibernate.Criteria; import org.hibernate.FetchMode; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Restrictions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.support.DataAccessUtils; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FilenameFilter; import java.io.IOException; import java.io.Reader; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; public class IngestionTest extends BaseRhinoTest { private static final Logger log = LoggerFactory.getLogger(IngestionTest.class); private static final File DATA_PATH = new File("src/test/resources/articles/"); private static final String JSON_SUFFIX = ".json"; private static final String XML_SUFFIX = ".xml"; @Autowired private ArticleCrudService articleCrudService; @Autowired private Gson entityGson; private static FilenameFilter forSuffix(final String suffix) { return new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(suffix); } }; } @DataProvider public Object[][] generatedIngestionData() { File[] jsonFiles = DATA_PATH.listFiles(forSuffix(JSON_SUFFIX)); Arrays.sort(jsonFiles); List<Object[]> cases = Lists.newArrayListWithCapacity(jsonFiles.length); // For each JSON file, expect a matching XML file. Ignore XML files without JSON files. for (File jsonFile : jsonFiles) { String jsonFilePath = jsonFile.getPath(); String xmlPath = jsonFilePath.substring(0, jsonFilePath.length() - JSON_SUFFIX.length()) + XML_SUFFIX; File xmlFile = new File(xmlPath); if (!xmlFile.exists()) { fail("No XML file to match JSON test case data: " + xmlPath); } cases.add(new Object[]{jsonFile, xmlFile}); } return cases.toArray(new Object[0][]); } private Article readReferenceCase(File jsonFile) throws IOException { Preconditions.checkNotNull(jsonFile); Article article; Reader input = null; boolean threw = true; try { input = new FileReader(jsonFile); input = new BufferedReader(input); article = entityGson.fromJson(input, Article.class); threw = false; } finally { Closeables.close(input, threw); } createTestJournal(article.geteIssn()); return article; } /** * Persist a dummy Journal object with a particular eIssn into the test environment, if it doesn't already exist. * * @param eissn the journal eIssn */ private void createTestJournal(String eissn) { Journal journal = (Journal) DataAccessUtils.uniqueResult((List<?>) hibernateTemplate.findByCriteria(DetachedCriteria .forClass(Journal.class) .add(Restrictions.eq("eIssn", eissn)) .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY))); if (journal == null) { journal = new Journal(); journal.setTitle("Test Journal " + eissn); journal.seteIssn(eissn); hibernateTemplate.save(journal); } } @Test(dataProvider = "generatedIngestionData") public void testIngestion(File jsonFile, File xmlFile) throws Exception { final Article expected = readReferenceCase(jsonFile); final String caseDoi = expected.getDoi(); WriteResult writeResult = articleCrudService.write(new TestFile(xmlFile).read(), Optional.<ArticleIdentity>absent(), DoiBasedCrudService.WriteMode.CREATE_ONLY); assertEquals(writeResult.getAction(), WriteResult.Action.CREATED, "Service didn't report creating article"); Article actual = (Article) DataAccessUtils.uniqueResult((List<?>) hibernateTemplate.findByCriteria(DetachedCriteria .forClass(Article.class) .setFetchMode("journals", FetchMode.JOIN) .add(Restrictions.eq("doi", caseDoi)))); assertNotNull(actual, "Failed to create article with expected DOI"); AssertionCollector results = compareArticle(actual, expected); log.info("{} successes", results.getSuccessCount()); Collection<AssertionCollector.Failure> failures = results.getFailures(); for (AssertionCollector.Failure failure : failures) { log.error(failure.toString()); } assertEquals(failures.size(), 0, "Mismatched Article fields"); } private AssertionCollector compareArticle(Article actual, Article expected) { AssertionCollector results = new AssertionCollector(); compareArticleFields(results, actual, expected); comparePersonLists(results, Article.class, "authors", actual.getAuthors(), expected.getAuthors()); comparePersonLists(results, Article.class, "editors", actual.getEditors(), expected.getEditors()); compareCategorySets(results, actual.getCategories(), expected.getCategories()); compareJournalSets(results, actual.getJournals(), expected.getJournals()); compareRelationshipLists(results, actual.getRelatedArticles(), expected.getRelatedArticles()); compareAssetLists(results, actual.getAssets(), expected.getAssets()); compareCitationLists(results, actual.getCitedArticles(), expected.getCitedArticles()); return results; } /** * Compare simple (non-associative) fields. * * @param results * @param actual * @param expected */ private void compareArticleFields(AssertionCollector results, Article actual, Article expected) { results.compare(Article.class, "doi", actual.getDoi(), expected.getDoi()); results.compare(Article.class, "title", actual.getTitle(), expected.getTitle()); results.compare(Article.class, "eIssn", actual.geteIssn(), expected.geteIssn()); results.compare(Article.class, "state", actual.getState(), expected.getState()); results.compare(Article.class, "description", actual.getDescription(), expected.getDescription()); results.compare(Article.class, "rights", actual.getRights(), expected.getRights()); results.compare(Article.class, "language", actual.getLanguage(), expected.getLanguage()); results.compare(Article.class, "format", actual.getFormat(), expected.getFormat()); results.compare(Article.class, "pages", actual.getPages(), expected.getPages()); results.compare(Article.class, "eLocationId", actual.geteLocationId(), expected.geteLocationId()); // TODO: Test archiveName field when Rhino has a design for if and how to store the article as a .zip archive // results.compare(Article.class, "archiveName", actual.getArchiveName(), expected.getArchiveName()); // Skip striking image field as long as it's not set as part of ingesting NLM DTD // results.compare(Article.class, "strkImgURI", // Strings.nullToEmpty(actual.getStrkImgURI()), // Strings.nullToEmpty(expected.getStrkImgURI())); // actual.getDate() returns a java.sql.Date since it's coming from hibernate. We have // to convert that to a java.util.Date (which GSON returns) for the comparison. results.compare(Article.class, "date", new Date(actual.getDate().getTime()), expected.getDate()); results.compare(Article.class, "volume", actual.getVolume(), expected.getVolume()); results.compare(Article.class, "issue", actual.getIssue(), expected.getIssue()); results.compare(Article.class, "journal", actual.getJournal(), expected.getJournal()); results.compare(Article.class, "publisherLocation", actual.getPublisherLocation(), expected.getPublisherLocation()); results.compare(Article.class, "publisherName", actual.getPublisherName(), expected.getPublisherName()); results.compare(Article.class, "url", actual.getUrl(), expected.getUrl()); results.compare(Article.class, "collaborativeAuthors", actual.getCollaborativeAuthors(), expected.getCollaborativeAuthors()); results.compare(Article.class, "types", actual.getTypes(), expected.getTypes()); } private void compareCategorySets(AssertionCollector results, Set<Category> actual, Set<Category> expected) { /* * Ignore this field. We rely on an external taxonomy server to set it, which in testing will set only dummy values. */ } private void compareJournalSets(AssertionCollector results, Set<Journal> actualSet, Set<Journal> expectedSet) { // We care only about eIssn, because that's the only part given in article XML. // All other Journal fields come from the environment, which doesn't exist here (see createTestJournal). Map<String, Journal> actualMap = mapJournalsByEissn(actualSet); Set<String> actualKeys = actualMap.keySet(); Map<String, Journal> expectedMap = mapJournalsByEissn(expectedSet); Set<String> expectedKeys = expectedMap.keySet(); for (String missing : Sets.difference(expectedKeys, actualKeys)) { results.compare(Journal.class, "eIssn", null, missing); } for (String extra : Sets.difference(actualKeys, expectedKeys)) { results.compare(Journal.class, "eIssn", extra, null); } for (String key : Sets.intersection(actualKeys, expectedKeys)) { results.compare(Journal.class, "eIssn", key, key); } } private void compareRelationshipLists(AssertionCollector results, List<ArticleRelationship> actual, List<ArticleRelationship> expected) { /* * Ignore this field. No known cases where it would be defined by article XML. */ } private void compareAssetLists(AssertionCollector results, Collection<ArticleAsset> actualList, Collection<ArticleAsset> expectedList) { // Compare assets by their DOI, ignoring order Map<AssetIdentity, ArticleAsset> actualAssetMap = mapUninitAssetsById(actualList); Set<AssetIdentity> actualAssetIds = actualAssetMap.keySet(); Multimap<AssetIdentity, ArticleAsset> expectedAssetMap = mapAssetFilesByAssetId(expectedList); Set<AssetIdentity> expectedAssetIds = expectedAssetMap.keySet(); for (AssetIdentity missingDoi : Sets.difference(expectedAssetIds, actualAssetIds)) { results.compare(ArticleAsset.class, "doi", null, missingDoi); } for (AssetIdentity extraDoi : Sets.difference(actualAssetIds, expectedAssetIds)) { results.compare(ArticleAsset.class, "doi", extraDoi, null); } for (AssetIdentity assetDoi : Sets.intersection(actualAssetIds, expectedAssetIds)) { // One created asset with a null extension and material from article XML ArticleAsset actualAsset = actualAssetMap.get(assetDoi); // Multiple assets corresponding to various uploaded files Collection<ArticleAsset> expectedFileAssets = expectedAssetMap.get(assetDoi); /* * The relevant fields of the expected assets should all match each other. (If a counterexample is found, * will have to change this test.) We want to test that the actual asset matches all of them. */ verifyExpectedAssets(expectedFileAssets); for (ArticleAsset expectedAsset : expectedFileAssets) { compareAssetFields(results, actualAsset, expectedAsset); } } } /** * Compare only those fields that can be gotten from article XML. * * @param results the object into which to insert results * @param actual an actual asset with no information specific to an uploaded file * @param expected an expected asset with an associated file */ private void compareAssetFields(AssertionCollector results, ArticleAsset actual, ArticleAsset expected) { assertEquals(actual.getDoi(), expected.getDoi()); // should be true as a method precondition results.compare(ArticleAsset.class, "contextElement", actual.getContextElement(), expected.getContextElement()); results.compare(ArticleAsset.class, "title", actual.getTitle(), expected.getTitle()); results.compare(ArticleAsset.class, "description", actual.getDescription(), expected.getDescription()); // These are skipped because they would require a file upload before we could know them. // results.compare(ArticleAsset.class, "extension", actual.getExtension(), expected.getExtension()); // results.compare(ArticleAsset.class, "contentType", actual.getContentType(), expected.getContentType()); // results.compare(ArticleAsset.class, "size", actual.getSize(), expected.getSize()); } /** * Assert that the fields checked in {@link #compareAssetFields} are the same among all expected assets with the same * DOI. The test expects this condition to hold about its own case data, so if it fails, halt instead of logging a * soft case failure. * * @param assets non-empty collection of expected assets */ private void verifyExpectedAssets(Iterable<ArticleAsset> assets) { Iterator<ArticleAsset> iterator = assets.iterator(); ArticleAsset first = iterator.next(); while (iterator.hasNext()) { ArticleAsset next = iterator.next(); assertTrue(Objects.equal(first.getDoi(), next.getDoi())); assertTrue(Objects.equal(first.getContextElement(), next.getContextElement())); assertTrue(Objects.equal(first.getTitle(), next.getTitle())); assertTrue(Objects.equal(first.getDescription(), next.getDescription())); } } private void compareCitationLists(AssertionCollector results, List<CitedArticle> actualList, List<CitedArticle> expectedList) { // Ensure no problems with random access or delayed evaluation actualList = ImmutableList.copyOf(actualList); expectedList = ImmutableList.copyOf(expectedList); /* * Compare citations with matching "key" fields (nothing else identifies them uniquely). It may be valid for them * to be represented out of order in these lists (dependent on Hibernate?), but all cases so far give them in order. * If a counterexample is found, we can forcibly sort by key, but until then, assert that they are already ordered. * (If any keys are skipped, it will show up as a soft failure in compareCitations.) */ assertTrue(CITATION_BY_KEY.isStrictlyOrdered(actualList)); assertTrue(CITATION_BY_KEY.isStrictlyOrdered(expectedList)); int commonSize = Math.min(actualList.size(), expectedList.size()); for (int i = 0; i < commonSize; i++) { compareCitations(results, actualList.get(i), expectedList.get(i)); } // If the sizes didn't match, report missing/extra citations as errors for (int i = commonSize; i < actualList.size(); i++) { results.compare(Article.class, "citedArticles", actualList.get(i), null); } for (int i = commonSize; i < expectedList.size(); i++) { results.compare(Article.class, "citedArticles", null, expectedList.get(i)); } } private void compareCitations(AssertionCollector results, CitedArticle actual, CitedArticle expected) { results.compare(CitedArticle.class, "key", actual.getKey(), expected.getKey()); results.compare(CitedArticle.class, "year", actual.getYear(), expected.getYear()); results.compare(CitedArticle.class, "displayYear", actual.getDisplayYear(), expected.getDisplayYear()); results.compare(CitedArticle.class, "month", actual.getMonth(), expected.getMonth()); results.compare(CitedArticle.class, "day", actual.getDay(), expected.getDay()); results.compare(CitedArticle.class, "volumeNumber", actual.getVolumeNumber(), expected.getVolumeNumber()); results.compare(CitedArticle.class, "volume", actual.getVolume(), expected.getVolume()); results.compare(CitedArticle.class, "issue", actual.getIssue(), expected.getIssue()); results.compare(CitedArticle.class, "title", actual.getTitle(), expected.getTitle()); results.compare(CitedArticle.class, "publisherLocation", actual.getPublisherLocation(), expected.getPublisherLocation()); results.compare(CitedArticle.class, "publisherName", actual.getPublisherName(), expected.getPublisherName()); results.compare(CitedArticle.class, "pages", actual.getPages(), expected.getPages()); results.compare(CitedArticle.class, "eLocationID", actual.geteLocationID(), expected.geteLocationID()); results.compare(CitedArticle.class, "journal", actual.getJournal(), expected.getJournal()); results.compare(CitedArticle.class, "note", actual.getNote(), expected.getNote()); results.compare(CitedArticle.class, "collaborativeAuthors", actual.getCollaborativeAuthors(), expected.getCollaborativeAuthors()); results.compare(CitedArticle.class, "url", actual.getUrl(), expected.getUrl()); results.compare(CitedArticle.class, "doi", actual.getDoi(), expected.getDoi()); results.compare(CitedArticle.class, "summary", actual.getSummary(), expected.getSummary()); results.compare(CitedArticle.class, "citationType", actual.getCitationType(), expected.getCitationType()); comparePersonLists(results, CitedArticle.class, "authors", actual.getAuthors(), expected.getAuthors()); comparePersonLists(results, CitedArticle.class, "editors", actual.getEditors(), expected.getEditors()); } private void comparePersonLists(AssertionCollector results, Class<?> parentType, String fieldName, List<? extends AmbraEntity> actualList, List<? extends AmbraEntity> expectedList) { final String field = parentType.getSimpleName() + "." + fieldName; List<PersonName> actualNames = asPersonNames(actualList); List<PersonName> expectedNames = asPersonNames(expectedList); int commonSize = Math.min(actualNames.size(), expectedNames.size()); for (int i = 0; i < commonSize; i++) { PersonName actualName = actualNames.get(i); PersonName expectedName = expectedNames.get(i); results.compare(field, "fullName", actualName.getFullName(), expectedName.getFullName()); results.compare(field, "givenNames", actualName.getGivenNames(), expectedName.getGivenNames()); results.compare(field, "surname", actualName.getSurname(), expectedName.getSurname()); results.compare(field, "suffix", actualName.getSuffix(), expectedName.getSuffix()); } // If the sizes didn't match, report missing/extra elements as errors for (int i = commonSize; i < actualList.size(); i++) { results.compare(parentType, fieldName, actualNames.get(i), null); } for (int i = commonSize; i < expectedList.size(); i++) { results.compare(parentType, fieldName, null, expectedNames.get(i)); } } // Transformation helper methods private static ImmutableMap<String, Journal> mapJournalsByEissn(Collection<Journal> journals) { ImmutableMap.Builder<String, Journal> map = ImmutableMap.builder(); for (Journal journal : journals) { map.put(journal.geteIssn(), journal); } return map.build(); } private static ImmutableMap<AssetIdentity, ArticleAsset> mapUninitAssetsById(Collection<ArticleAsset> assets) { ImmutableMap.Builder<AssetIdentity, ArticleAsset> map = ImmutableMap.builder(); for (ArticleAsset asset : assets) { map.put(AssetIdentity.from(asset), asset); } return map.build(); } private static ImmutableMultimap<AssetIdentity, ArticleAsset> mapAssetFilesByAssetId(Collection<ArticleAsset> assets) { ImmutableListMultimap.Builder<AssetIdentity, ArticleAsset> map = ImmutableListMultimap.builder(); for (ArticleAsset asset : assets) { AssetFileIdentity fileIdentity = AssetFileIdentity.from(asset); map.put(fileIdentity.forAsset(), asset); } return map.build(); } /** * Orders {@link CitedArticle} objects by the numeric value of their {@code key} string. Throws an exception if * applied to a CitedArticle whose key is null or otherwise can't be parsed as an integer. */ private static final Ordering<CitedArticle> CITATION_BY_KEY = Ordering.natural().onResultOf( new Function<CitedArticle, Comparable>() { @Override public Integer apply(CitedArticle input) { return Integer.valueOf(input.getKey()); } }); private static ImmutableList<PersonName> asPersonNames(Collection<? extends AmbraEntity> persons) { List<PersonName> names = Lists.newArrayListWithCapacity(persons.size()); for (Object personObj : persons) { // Have to do it this way for the same reason that PersonName exists in the first place -- see PersonName docs PersonName name; if (personObj instanceof ArticlePerson) { name = PersonName.from((ArticlePerson) personObj); } else if (personObj instanceof CitedArticlePerson) { name = PersonName.from((CitedArticlePerson) personObj); } else { throw new ClassCastException(); } names.add(name); } return ImmutableList.copyOf(names); } }
package org.jmeterplugins.repository; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import java.awt.KeyboardFocusManager; import java.awt.event.KeyEvent; import java.io.File; import java.util.HashSet; import java.util.Set; import javax.swing.JComboBox; import javax.swing.JList; import javax.swing.JTextField; import javax.swing.ListModel; import javax.swing.event.ChangeListener; import javax.swing.event.ListSelectionEvent; import org.junit.Test; import net.sf.json.JSONObject; import net.sf.json.JsonConfig; public class PluginsListTest { private static final String EXPECTED_DESC_MAVEN = "Maven groupId: <i>kg.apc</i>, artifactId: <i>jmeter-plugins-webdriver</i>, version: <i>0.3</i>"; private static final String EXPECTED_DESC_CHANGES = "What's new in version 0.3: fix verified exception1"; @Test public void testFlow() throws Exception { String imgPath = "file:///" + new File(".").getAbsolutePath() + "/target/classes/org/jmeterplugins/logo.png"; String str = "{\"id\": 0, \"markerClass\": \"" + PluginsListTest.class.getName() + "\"," + " \"screenshotUrl\": \"" + imgPath + "\", \"name\": 3, \"description\": 4, \"helpUrl\": 5, \"vendor\": 5, \"installerClass\": \"test\", " + "\"versions\" : { \"0.1\" : { \"changes\": \"fix verified exception1\", \"downloadUrl\": \"https://search.maven.org/remotecontent?filepath=kg/apc/jmeter-plugins-webdriver/0.3/jmeter-plugins-webdriver-0.1.jar\" }," + "\"0.2\" : { \"changes\": \"fix verified exception1\", \"downloadUrl\": \"https://search.maven.org/remotecontent?filepath=kg/apc/jmeter-plugins-webdriver/0.3/jmeter-plugins-webdriver-0.2.jar\"}," + "\"0.3\" : { \"changes\": \"fix verified exception1\", " + "\"downloadUrl\": \"https://search.maven.org/remotecontent?filepath=kg/apc/jmeter-plugins-webdriver/0.3/jmeter-plugins-webdriver-0.3.jar\"} }}"; Plugin p = Plugin.fromJSON(JSONObject.fromObject(str, new JsonConfig())); Set<Plugin> set = new HashSet<>(); set.add(p); PluginsListExt pluginsList = new PluginsListExt(set, null, null); pluginsList.getList().setSelectedIndex(0); ListSelectionEvent event = new ListSelectionEvent("0.2", 0, 2, false); pluginsList.valueChanged(event); p.setCandidateVersion("0.3"); assertEquals("0.3", pluginsList.getCbVersion(pluginsList.getCheckboxItem(p, null))); String desc = pluginsList.getDescriptionHTML(p); assertFalse(desc.indexOf(EXPECTED_DESC_MAVEN)<0); assertFalse(desc.indexOf(EXPECTED_DESC_CHANGES)<0); p.detectInstalled(null); assertEquals(Plugin.VER_STOCK, pluginsList.getCbVersion(pluginsList.getCheckboxItem(p, null))); pluginsList.setEnabled(false); assertFalse(pluginsList.getList().isEnabled()); assertFalse(pluginsList.getVersion().isEnabled()); assertFalse(pluginsList.getList().getModel().getElementAt(0).isEnabled()); JTextField searchField = pluginsList.searchField; ListModel model = pluginsList.getList().getModel(); searchField.setText("not found plugin"); KeyEvent keyEvent = new KeyEvent(pluginsList.searchField, KeyEvent.KEY_RELEASED, 20, 1, KeyEvent.VK_Z, 'z'); KeyboardFocusManager.getCurrentKeyboardFocusManager().redispatchEvent(searchField, keyEvent); searchField.dispatchEvent(keyEvent); assertEquals(0, pluginsList.getList().getModel().getSize()); assertFalse(model == pluginsList.getList().getModel()); searchField.setText(""); KeyboardFocusManager.getCurrentKeyboardFocusManager().redispatchEvent(searchField, keyEvent); searchField.dispatchEvent(keyEvent); assertEquals(1, pluginsList.getList().getModel().getSize()); assertEquals(model, pluginsList.getList().getModel()); } public static class PluginsListExt extends PluginsList { public PluginsListExt(Set<Plugin> plugins, ChangeListener checkboxNotifier, GenericCallback<Object> dialogRefresh) { super(dialogRefresh); setPlugins(plugins, checkboxNotifier); } public JList<PluginCheckbox> getList() { return list; } public JComboBox<String> getVersion() { return version; } } }
package org.recap.model.etl; import org.apache.camel.ProducerTemplate; import org.apache.commons.io.FileUtils; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.recap.BaseTestCase; import org.recap.model.jaxb.BibRecord; import org.recap.model.jaxb.JAXBHandler; import org.recap.model.jpa.BibliographicEntity; import org.recap.repository.BibliographicDetailsRepository; import org.recap.route.ETLExchange; import org.recap.util.CsvUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.CollectionUtils; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.io.File; import java.net.URL; import java.util.*; import static org.junit.Assert.*; public class BibPersisterCallableTest extends BaseTestCase { @Autowired BibliographicDetailsRepository bibliographicDetailsRepository; @Autowired private ProducerTemplate producer; @PersistenceContext private EntityManager entityManager; @Autowired CsvUtil csvUtil; @Mock private Map<String, Integer> institutionMap; @Mock private Map itemStatusMap; @Mock private Map<String, Integer> collectionGroupMap; @Before public void setUp() { MockitoAnnotations.initMocks(this); } @Test public void newInstance() { BibRecord bibRecord = new BibRecord(); BibPersisterCallable bibPersisterCallable = new BibPersisterCallable(bibRecord, institutionMap, itemStatusMap, collectionGroupMap); assertNotNull(bibPersisterCallable); } @Test public void checkNullConstraints() throws Exception { Mockito.when(institutionMap.get("NYPL")).thenReturn(3); Mockito.when(itemStatusMap.get("Available")).thenReturn(1); Mockito.when(collectionGroupMap.get("Open")).thenReturn(2); List<LoadReportEntity> loadReportEntities = new ArrayList<>(); Map<String, Integer> institution = new HashMap<>(); institution.put("NYPL", 3); Mockito.when(institutionMap.entrySet()).thenReturn(institution.entrySet()); Map<String, Integer> collection = new HashMap<>(); collection.put("Open", 2); Mockito.when(collectionGroupMap.entrySet()).thenReturn(collection.entrySet()); URL resource = getClass().getResource("BibWithoutItemBarcode.xml"); assertNotNull(resource); File file = new File(resource.toURI()); assertNotNull(file); assertTrue(file.exists()); BibRecord bibRecord = null; bibRecord = (BibRecord) JAXBHandler.getInstance().unmarshal(FileUtils.readFileToString(file, "UTF-8"), BibRecord.class); assertNotNull(bibRecord); BibPersisterCallable bibPersisterCallable = new BibPersisterCallable(bibRecord, institutionMap, itemStatusMap, collectionGroupMap); Map<String, Object> map = (Map<String, Object>) bibPersisterCallable.call(); if (map != null) { Object object = map.get("loadReportEntity"); if (object != null) { loadReportEntities.add((LoadReportEntity) object); } } assertEquals(loadReportEntities.size(), 1); if (!CollectionUtils.isEmpty(loadReportEntities)) { csvUtil.writeLoadReportToCsv(loadReportEntities); } } @Test public void loadBibHoldingsMultipleItems() throws Exception { Mockito.when(institutionMap.get("NYPL")).thenReturn(3); Mockito.when(itemStatusMap.get("Available")).thenReturn(1); Mockito.when(collectionGroupMap.get("Open")).thenReturn(2); Map<String, Integer> institution = new HashMap<>(); institution.put("NYPL", 3); Mockito.when(institutionMap.entrySet()).thenReturn(institution.entrySet()); Map<String, Integer> collection = new HashMap<>(); collection.put("Open", 2); Mockito.when(collectionGroupMap.entrySet()).thenReturn(collection.entrySet()); URL resource = getClass().getResource("BibHoldingsMultipleItems.xml"); assertNotNull(resource); File file = new File(resource.toURI()); assertNotNull(file); assertTrue(file.exists()); BibRecord bibRecord1 = null; bibRecord1 = (BibRecord) JAXBHandler.getInstance().unmarshal(FileUtils.readFileToString(file, "UTF-8"), BibRecord.class); assertNotNull(bibRecord1); BibliographicEntity bibliographicEntity = null; BibPersisterCallable bibPersisterCallable = new BibPersisterCallable(bibRecord1, institutionMap, itemStatusMap, collectionGroupMap); Map<String, Object> map = (Map<String, Object>) bibPersisterCallable.call(); if (map != null) { Object object = map.get("bibliographicEntity"); if (object != null) { bibliographicEntity = (BibliographicEntity) object; } } assertNotNull(bibliographicEntity); assertEquals(bibliographicEntity.getHoldingsEntities().size(), 1); assertEquals(bibliographicEntity.getItemEntities().size(), 5); assertNotNull(bibliographicDetailsRepository); assertNotNull(producer); ETLExchange etlExchange = new ETLExchange(); etlExchange.setBibliographicEntities(Arrays.asList(bibliographicEntity)); etlExchange.setInstitutionEntityMap(new HashMap()); etlExchange.setCollectionGroupMap(new HashMap()); producer.sendBody("activemq:queue:etlLoadQ", etlExchange); Thread.sleep(1000); BibliographicEntity savedBibliographicEntity = bibliographicDetailsRepository.findByOwningInstitutionIdAndOwningInstitutionBibId(bibliographicEntity.getOwningInstitutionId(), bibliographicEntity.getOwningInstitutionBibId()); assertNotNull(savedBibliographicEntity); assertNotNull(savedBibliographicEntity.getHoldingsEntities()); assertEquals(savedBibliographicEntity.getHoldingsEntities().size(), 1); assertNotNull(savedBibliographicEntity.getItemEntities()); assertEquals(savedBibliographicEntity.getItemEntities().size(), 5); } @Test public void checkDataTruncateIssue() throws Exception { Mockito.when(institutionMap.get("NYPL")).thenReturn(3); Mockito.when(itemStatusMap.get("Available")).thenReturn(1); Mockito.when(collectionGroupMap.get("Open")).thenReturn(2); Map<String, Integer> institution = new HashMap<>(); institution.put("NYPL", 3); Mockito.when(institutionMap.entrySet()).thenReturn(institution.entrySet()); Map<String, Integer> collection = new HashMap<>(); collection.put("Open", 2); Mockito.when(collectionGroupMap.entrySet()).thenReturn(collection.entrySet()); URL resource = getClass().getResource("BibMultipleHoldingsItems.xml"); assertNotNull(resource); File file = new File(resource.toURI()); assertNotNull(file); assertTrue(file.exists()); BibRecord bibRecord = null; bibRecord = (BibRecord) JAXBHandler.getInstance().unmarshal(FileUtils.readFileToString(file, "UTF-8"), BibRecord.class); assertNotNull(bibRecord); BibliographicEntity bibliographicEntity = null; BibPersisterCallable bibPersisterCallable = new BibPersisterCallable(bibRecord, institutionMap, itemStatusMap, collectionGroupMap); Map<String, Object> map = (Map<String, Object>) bibPersisterCallable.call(); if (map != null) { Object object = map.get("bibliographicEntity"); if (object != null) { bibliographicEntity = (BibliographicEntity) object; } } assertNotNull(bibliographicEntity); assertEquals(bibliographicEntity.getHoldingsEntities().size(), 2); assertEquals(bibliographicEntity.getItemEntities().size(), 4); assertNotNull(bibliographicDetailsRepository); assertNotNull(producer); ETLExchange etlExchange = new ETLExchange(); etlExchange.setBibliographicEntities(Arrays.asList(bibliographicEntity)); etlExchange.setInstitutionEntityMap(new HashMap()); etlExchange.setCollectionGroupMap(new HashMap()); producer.sendBody("activemq:queue:etlLoadQ", etlExchange); Thread.sleep(1000); BibliographicEntity savedBibliographicEntity = bibliographicDetailsRepository.findByOwningInstitutionIdAndOwningInstitutionBibId(bibliographicEntity.getOwningInstitutionId(), bibliographicEntity.getOwningInstitutionBibId()); assertNotNull(savedBibliographicEntity); assertNotNull(savedBibliographicEntity.getHoldingsEntities()); assertEquals(savedBibliographicEntity.getHoldingsEntities().size(), 2); assertNotNull(savedBibliographicEntity.getItemEntities()); assertEquals(savedBibliographicEntity.getItemEntities().size(), 3); } //TODO : need to fix constraint in bibliographic_item_t @Test @Ignore public void duplicateItemsForSingleBib() throws Exception { Mockito.when(institutionMap.get("NYPL")).thenReturn(3); Mockito.when(itemStatusMap.get("Available")).thenReturn(1); Mockito.when(collectionGroupMap.get("Open")).thenReturn(2); Map<String, Integer> institution = new HashMap<>(); institution.put("NYPL", 3); Mockito.when(institutionMap.entrySet()).thenReturn(institution.entrySet()); Map<String, Integer> collection = new HashMap<>(); collection.put("Open", 2); Mockito.when(collectionGroupMap.entrySet()).thenReturn(collection.entrySet()); URL resource = getClass().getResource("BibWithDuplicateItems.xml"); assertNotNull(resource); File file = new File(resource.toURI()); assertNotNull(file); assertTrue(file.exists()); BibRecord bibRecord = null; bibRecord = (BibRecord) JAXBHandler.getInstance().unmarshal(FileUtils.readFileToString(file, "UTF-8"), BibRecord.class); assertNotNull(bibRecord); BibliographicEntity bibliographicEntity = null; BibPersisterCallable bibPersisterCallable = new BibPersisterCallable(bibRecord, institutionMap, itemStatusMap, collectionGroupMap); Map<String, Object> map = (Map<String, Object>) bibPersisterCallable.call(); if (map != null) { Object object = map.get("bibliographicEntity"); if (object != null) { bibliographicEntity = (BibliographicEntity) object; } } assertNotNull(bibliographicEntity); assertEquals(bibliographicEntity.getHoldingsEntities().size(), 2); assertEquals(bibliographicEntity.getItemEntities().size(), 4); BibliographicEntity savedBibliographicEntity = bibliographicDetailsRepository.saveAndFlush(bibliographicEntity); entityManager.refresh(savedBibliographicEntity); assertNotNull(savedBibliographicEntity); assertNotNull(savedBibliographicEntity.getBibliographicId()); assertEquals(savedBibliographicEntity.getHoldingsEntities().size(), 2); assertEquals(savedBibliographicEntity.getItemEntities().size(), 2); } @Test @Ignore public void duplicateBibsWithDifferentItems() throws Exception { Mockito.when(institutionMap.get("NYPL")).thenReturn(3); Mockito.when(itemStatusMap.get("Available")).thenReturn(1); Mockito.when(collectionGroupMap.get("Open")).thenReturn(2); Map<String, Integer> institution = new HashMap<>(); institution.put("NYPL", 3); Mockito.when(institutionMap.entrySet()).thenReturn(institution.entrySet()); Map<String, Integer> collection = new HashMap<>(); collection.put("Open", 2); Mockito.when(collectionGroupMap.entrySet()).thenReturn(collection.entrySet()); URL resource = getClass().getResource("sampleRecord1.xml"); assertNotNull(resource); File file = new File(resource.toURI()); assertNotNull(file); assertTrue(file.exists()); BibRecord bibRecord1 = null; bibRecord1 = (BibRecord) JAXBHandler.getInstance().unmarshal(FileUtils.readFileToString(file, "UTF-8"), BibRecord.class); assertNotNull(bibRecord1); BibliographicEntity bibliographicEntity1 = null; BibPersisterCallable bibPersisterCallable = new BibPersisterCallable(bibRecord1, institutionMap, itemStatusMap, collectionGroupMap); Map<String, Object> map = (Map<String, Object>) bibPersisterCallable.call(); if (map != null) { Object object = map.get("bibliographicEntity"); if (object != null) { bibliographicEntity1 = (BibliographicEntity) object; } } resource = getClass().getResource("sampleRecord2.xml"); assertNotNull(resource); file = new File(resource.toURI()); assertNotNull(file); assertTrue(file.exists()); BibRecord bibRecord2 = null; bibRecord2 = (BibRecord) JAXBHandler.getInstance().unmarshal(FileUtils.readFileToString(file, "UTF-8"), BibRecord.class); assertNotNull(bibRecord2); BibliographicEntity bibliographicEntity2 = null; bibPersisterCallable = new BibPersisterCallable(bibRecord2, institutionMap, itemStatusMap, collectionGroupMap); map = (Map<String, Object>) bibPersisterCallable.call(); if (map != null) { Object object = map.get("bibliographicEntity"); if (object != null) { bibliographicEntity2 = (BibliographicEntity) object; } } assertNotNull(bibliographicEntity1); assertNotNull(bibliographicEntity2); BibliographicEntity savedBibliographicEntity1 = bibliographicDetailsRepository.saveAndFlush(bibliographicEntity1); entityManager.refresh(savedBibliographicEntity1); assertNotNull(savedBibliographicEntity1); assertNotNull(savedBibliographicEntity1.getBibliographicId()); BibliographicEntity savedBibliographicEntity2 = bibliographicDetailsRepository.saveAndFlush(bibliographicEntity2); entityManager.refresh(savedBibliographicEntity2); assertNotNull(savedBibliographicEntity2); assertNotNull(savedBibliographicEntity2.getBibliographicId()); BibliographicEntity byOwningInstitutionBibId = bibliographicDetailsRepository.findByOwningInstitutionIdAndOwningInstitutionBibId(3, ".b153286131"); assertNotNull(byOwningInstitutionBibId); assertEquals(byOwningInstitutionBibId.getHoldingsEntities().size(), 2); assertEquals(byOwningInstitutionBibId.getItemEntities().size(), 2); } }
package us.kbase.narrativejobservice; import java.io.File; import java.util.List; import java.util.Map; import us.kbase.auth.AuthToken; import us.kbase.common.service.JsonServerMethod; import us.kbase.common.service.JsonServerServlet; import us.kbase.common.service.JsonServerSyslog; import us.kbase.common.service.RpcContext; import us.kbase.common.service.Tuple2; //BEGIN_HEADER import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Properties; import java.util.Set; import java.util.regex.Pattern; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.exception.ExceptionUtils; import org.ini4j.Ini; import com.fasterxml.jackson.databind.ObjectMapper; import us.kbase.common.executionengine.JobRunnerConstants; import us.kbase.common.executionengine.ModuleMethod; import us.kbase.common.service.JacksonTupleModule; import us.kbase.common.service.UObject; import us.kbase.narrativejobservice.db.ExecEngineMongoDb; import us.kbase.narrativejobservice.sdkjobs.ErrorLogger; import us.kbase.narrativejobservice.sdkjobs.SDKMethodRunner; import org.slf4j.LoggerFactory; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; //END_HEADER /** * <p>Original spec-file module name: NarrativeJobService</p> * <pre> * </pre> */ public class NarrativeJobServiceServer extends JsonServerServlet { private static final long serialVersionUID = 1L; private static final String version = "0.0.1"; private static final String gitUrl = "https://github.com/rsutormin/njs_wrapper"; private static final String gitCommitHash = "18145b1030a53a711fb0615ed0edcadb7cf17dcf"; //BEGIN_CLASS_HEADER public static final String SYS_PROP_KB_DEPLOYMENT_CONFIG = "KB_DEPLOYMENT_CONFIG"; public static final String SERVICE_DEPLOYMENT_NAME = "NarrativeJobService"; public static final String CFG_PROP_SCRATCH = "scratch"; public static final String CFG_PROP_WORKSPACE_SRV_URL = JobRunnerConstants.CFG_PROP_WORKSPACE_SRV_URL; public static final String CFG_PROP_JOBSTATUS_SRV_URL = JobRunnerConstants.CFG_PROP_JOBSTATUS_SRV_URL; public static final String CFG_PROP_RUNNING_TASKS_PER_USER = "running.tasks.per.user"; public static final String CFG_PROP_ADMIN_USER_NAME = "admin.user"; public static final String CFG_PROP_SHOCK_URL = JobRunnerConstants.CFG_PROP_SHOCK_URL; public static final String CFG_PROP_HANDLE_SRV_URL = JobRunnerConstants.CFG_PROP_HANDLE_SRV_URL; public static final String CFG_PROP_SRV_WIZ_URL = JobRunnerConstants.CFG_PROP_SRV_WIZ_URL; public static final String CFG_PROP_CONDOR_MODE = "condor.mode"; public static final String CFG_PROP_CONDOR_SUBMIT_DESC = "condor.submit.desc.file.path"; public static final String CFG_PROP_AWE_SRV_URL = "awe.srv.url"; public static final String CFG_PROP_AWE_CLIENT_SCRATCH = "awe.client.scratch"; public static final String CFG_PROP_AWE_CLIENT_DOCKER_URI = JobRunnerConstants.CFG_PROP_AWE_CLIENT_DOCKER_URI; public static final String CFG_PROP_DOCKER_REGISTRY_URL = "docker.registry.url"; public static final String AWE_CLIENT_SCRIPT_NAME = "run_async_srv_method.sh"; public static final String CFG_PROP_CATALOG_SRV_URL = JobRunnerConstants.CFG_PROP_CATALOG_SRV_URL; public static final String CFG_PROP_CATALOG_ADMIN_USER = "catalog.admin.user"; public static final String CFG_PROP_CATALOG_ADMIN_PWD = "catalog.admin.pwd"; public static final String CFG_PROP_CATALOG_ADMIN_TOKEN = "catalog.admin.token"; public static final String CFG_PROP_KBASE_ENDPOINT = JobRunnerConstants.CFG_PROP_KBASE_ENDPOINT; public static final String CFG_PROP_SELF_EXTERNAL_URL = JobRunnerConstants.CFG_PROP_NJSW_URL; public static final String CFG_PROP_REF_DATA_BASE = "ref.data.base"; public static final String CFG_PROP_DEFAULT_AWE_CLIENT_GROUPS = "default.awe.client.groups"; public static final String CFG_PROP_AWE_READONLY_ADMIN_USER = "awe.readonly.admin.user"; public static final String CFG_PROP_AWE_READONLY_ADMIN_PWD = "awe.readonly.admin.pwd"; public static final String CFG_PROP_AWE_READONLY_ADMIN_TOKEN = "awe.readonly.admin.token"; public static final String CFG_PROP_MONGO_HOSTS = "mongodb-host"; public static final String CFG_PROP_MONGO_DBNAME = "mongodb-database"; public static final String CFG_PROP_MONGO_USER = "mongodb-user"; public static final String CFG_PROP_MONGO_PWD = "mongodb-pwd"; public static final String CFG_PROP_MONGO_HOSTS_UJS = "ujs-mongodb-host"; public static final String CFG_PROP_MONGO_DBNAME_UJS = "ujs-mongodb-database"; public static final String CFG_PROP_MONGO_USER_UJS = "ujs-mongodb-user"; public static final String CFG_PROP_MONGO_PWD_UJS = "ujs-mongodb-pwd"; public static final String CFG_PROP_JOB_TIMEOUT_MINUTES = "condor.job.shutdown.minutes"; public static final String CFG_PROP_DOCKER_JOB_TIMEOUT_SECONDS = "condor.docker.job.timeout.seconds"; public static final String CFG_PROP_CONDOR_QUEUE_DESCRIPTION_INI= "condor.queue.description.file.path"; public static final String CFG_PROP_CONDOR_JOB_DATA_DIR= "condor-submit-workdir"; public static final String CFG_PROP_AWE_CLIENT_CALLBACK_NETWORKS = JobRunnerConstants.CFG_PROP_AWE_CLIENT_CALLBACK_NETWORKS; public static final String CFG_PROP_AUTH_SERVICE_URL = JobRunnerConstants.CFG_PROP_AUTH_SERVICE_URL; public static final String CFG_PROP_AUTH_SERVICE_URL_V2 = JobRunnerConstants.CFG_PROP_AUTH_SERVICE_URL_V2; public static final String CFG_PROP_TIME_BEFORE_EXPIRATION = JobRunnerConstants.CFG_PROP_TIME_BEFORE_EXPIRATION; public static final String CFG_PROP_AUTH_SERVICE_ALLOW_INSECURE_URL_PARAM = JobRunnerConstants.CFG_PROP_AUTH_SERVICE_ALLOW_INSECURE_URL_PARAM; public static final String VERSION = "0.2.11"; private static Throwable configError = null; private static String configPath = null; private static Map<String, String> config = null; private static ExecEngineMongoDb db = null; private final ErrorLogger logger; private final static long maxRPCPackageSize = JobRunnerConstants.MAX_IO_BYTE_SIZE; public static Map<String, String> config() { if (config != null) return config; if (configError != null) throw new IllegalStateException("There was an error while loading configuration", configError); String configPath = System.getProperty(SYS_PROP_KB_DEPLOYMENT_CONFIG); if (configPath == null) configPath = System.getenv(SYS_PROP_KB_DEPLOYMENT_CONFIG); if (configPath == null) { configError = new IllegalStateException("Configuration file was not defined"); } else { System.out.println(NarrativeJobServiceServer.class.getName() + ": Deployment config path was defined: " + configPath); try { NarrativeJobServiceServer.configPath = configPath; config = loadConfigFromDisk(); } catch (Throwable ex) { System.out.println(NarrativeJobServiceServer.class.getName() + ": Error loading deployment config-file: " + ex.getMessage()); configError = ex; } } if (config == null) throw new IllegalStateException("There was unknown error in service initialization when checking" + "the configuration: is the [" + SERVICE_DEPLOYMENT_NAME + "] config group defined?"); return config; } private static Map<String, String> loadConfigFromDisk() throws Exception { return new Ini(new File(configPath)).get(SERVICE_DEPLOYMENT_NAME); } public static File getTempDir() { String ret = config().get(CFG_PROP_SCRATCH); if (ret == null) throw new IllegalStateException("Parameter " + CFG_PROP_SCRATCH + " is not defined in configuration"); File dir = new File(ret); if (!dir.exists()) dir.mkdirs(); return dir; } public static String getWorkspaceServiceURL() { String ret = config().get(CFG_PROP_WORKSPACE_SRV_URL); if (ret == null) throw new IllegalStateException("Parameter " + CFG_PROP_WORKSPACE_SRV_URL + " is not defined in configuration"); return ret; } public static String getUJSServiceURL() { String ret = config().get(CFG_PROP_JOBSTATUS_SRV_URL); if (ret == null) throw new IllegalStateException("Parameter " + CFG_PROP_JOBSTATUS_SRV_URL + " is not defined in configuration"); return ret; } public static Set<String> getAdminUsers() { String ret = config().get(CFG_PROP_ADMIN_USER_NAME); if (ret == null) throw new IllegalStateException("Parameter " + CFG_PROP_ADMIN_USER_NAME + " is not defined in configuration"); return new LinkedHashSet<String>(Arrays.asList(ret.split(Pattern.quote(",")))); } public static ExecEngineMongoDb getMongoDb(Map<String, String> config) throws Exception { if (db == null) { String hosts = config.get(CFG_PROP_MONGO_HOSTS); if (hosts == null) throw new IllegalStateException("Parameter " + CFG_PROP_MONGO_HOSTS + " is not defined in configuration"); String dbname = config.get(CFG_PROP_MONGO_DBNAME); if (dbname == null) throw new IllegalStateException("Parameter " + CFG_PROP_MONGO_DBNAME + " is not defined in configuration"); db = new ExecEngineMongoDb(hosts, dbname, config.get(CFG_PROP_MONGO_USER), config.get(CFG_PROP_MONGO_PWD)); } return db; } protected void processRpcCall(RpcCallData rpcCallData, String token, JsonServerSyslog.RpcInfo info, String requestHeaderXForwardedFor, ResponseStatusSetter response, OutputStream output, boolean commandLine) { if (rpcCallData.getMethod().startsWith("NarrativeJobService.")) { super.processRpcCall(rpcCallData, token, info, requestHeaderXForwardedFor, response, output, commandLine); } else { final ModuleMethod modmeth = new ModuleMethod( rpcCallData.getMethod()); List<UObject> paramsList = rpcCallData.getParams(); List<Object> result = null; ObjectMapper mapper = new ObjectMapper().registerModule(new JacksonTupleModule()); us.kbase.narrativejobservice.RpcContext context = UObject.transformObjectToObject(rpcCallData.getContext(), us.kbase.narrativejobservice.RpcContext.class); Exception exc = null; try { if (modmeth.isSubmit()) { RunJobParams runJobParams = new RunJobParams(); String serviceVer = rpcCallData.getContext() == null ? null : (String) rpcCallData.getContext().getAdditionalProperties().get("service_ver"); runJobParams.setServiceVer(serviceVer); runJobParams.setMethod(modmeth.getModuleDotMethod()); runJobParams.setParams(paramsList); runJobParams.setRpcContext(context); result = new ArrayList<Object>(); result.add(runJob(runJobParams, validateToken(token), rpcCallData.getContext())); } else if (modmeth.isCheck()) { if (paramsList.size() == 1) { String jobId = paramsList.get(0).asClassInstance( String.class); JobState jobState = checkJob(jobId, validateToken(token), rpcCallData.getContext()); Long finished = jobState.getFinished(); if (finished != 0L) { Object error = jobState.getError(); if (error != null) { Map<String, Object> ret = new LinkedHashMap<String, Object>(); ret.put("version", "1.1"); ret.put("error", error); response.setStatus(HttpServletResponse .SC_INTERNAL_SERVER_ERROR); mapper.writeValue(new UnclosableOutputStream( output), ret); return; } } result = new ArrayList<Object>(); result.add(jobState); } else { throw new IllegalArgumentException( "Check method expects exactly one argument"); } } else { throw new IllegalArgumentException( "Method [" + rpcCallData.getMethod() + "] is not a valid method name for asynchronous job execution"); } Map<String, Object> ret = new LinkedHashMap<String, Object>(); ret.put("version", "1.1"); ret.put("result", result); mapper.writeValue(new UnclosableOutputStream(output), ret); return; } catch (Exception ex) { exc = ex; } try { Map<String, Object> error = new LinkedHashMap<String, Object>(); error.put("name", "JSONRPCError"); error.put("code", -32601); error.put("message", exc.getLocalizedMessage()); error.put("error", ExceptionUtils.getStackTrace(exc)); Map<String, Object> ret = new LinkedHashMap<String, Object>(); ret.put("version", "1.1"); ret.put("error", error); mapper.writeValue(new UnclosableOutputStream(output), ret); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } catch (Exception ex) { new Exception("Error sending error: " + exc.getLocalizedMessage(), ex).printStackTrace(); } } } private static class UnclosableOutputStream extends OutputStream { OutputStream inner; boolean isClosed = false; public UnclosableOutputStream(OutputStream inner) { this.inner = inner; } @Override public void write(int b) throws IOException { if (isClosed) return; inner.write(b); } @Override public void close() throws IOException { isClosed = true; } @Override public void flush() throws IOException { inner.flush(); } @Override public void write(byte[] b) throws IOException { if (isClosed) return; inner.write(b); } @Override public void write(byte[] b, int off, int len) throws IOException { if (isClosed) return; inner.write(b, off, len); } } protected Long getMaxRPCPackageSize() { return maxRPCPackageSize; } //END_CLASS_HEADER public void setUpLogger() { final Logger rootLogger = ((Logger) LoggerFactory.getLogger( org.slf4j.Logger.ROOT_LOGGER_NAME)); rootLogger.setLevel(Level.INFO); rootLogger.detachAndStopAllAppenders(); } public NarrativeJobServiceServer() throws Exception { super("NarrativeJobService"); //BEGIN_CONSTRUCTOR setUpLogger(); logger = new ErrorLogger() { @Override public void logErr(Throwable err) { NarrativeJobServiceServer.this.logErr(err); } @Override public void logErr(String message) { NarrativeJobServiceServer.this.logErr(message); } }; String authUrl = config().get(CFG_PROP_AUTH_SERVICE_URL); if (authUrl == null) { throw new IllegalStateException("Deployment configuration parameter is not defined: " + CFG_PROP_AUTH_SERVICE_URL); } String aweAdminUser = config().get(CFG_PROP_AWE_READONLY_ADMIN_USER); if (aweAdminUser != null && aweAdminUser.trim().isEmpty()) { aweAdminUser = null; } String aweAdminToken = config().get(CFG_PROP_AWE_READONLY_ADMIN_TOKEN); if (aweAdminToken != null && aweAdminToken.trim().isEmpty()) { aweAdminToken = null; } if (aweAdminUser == null && aweAdminToken == null) { throw new IllegalStateException("Deployment configuration for AWE admin credentials " + "is not defined: " + CFG_PROP_AWE_READONLY_ADMIN_USER + " or " + CFG_PROP_AWE_READONLY_ADMIN_TOKEN); } String catAdminUser = config().get(CFG_PROP_CATALOG_ADMIN_USER); if (catAdminUser != null && catAdminUser.trim().isEmpty()) { catAdminUser = null; } String catAdminToken = config().get(CFG_PROP_CATALOG_ADMIN_TOKEN); if (catAdminToken != null && catAdminToken.trim().isEmpty()) { catAdminToken = null; } if (catAdminUser == null && catAdminToken == null) { throw new IllegalStateException("Deployment configuration for AWE admin credentials " + "is not defined: " + CFG_PROP_CATALOG_ADMIN_USER + " or " + CFG_PROP_CATALOG_ADMIN_TOKEN); } //END_CONSTRUCTOR } /** * <p>Original spec-file function name: list_config</p> * <pre> * </pre> * * @return instance of mapping from String to String */ @JsonServerMethod(rpc = "NarrativeJobService.list_config", authOptional = true, async = true) public Map<String, String> listConfig(AuthToken authPart, RpcContext jsonRpcContext) throws Exception { Map<String, String> returnVal = null; //BEGIN list_config Map<String, String> safeConfig = new LinkedHashMap<String, String>(); String[] keys = { CFG_PROP_AWE_SRV_URL, CFG_PROP_DOCKER_REGISTRY_URL, CFG_PROP_JOBSTATUS_SRV_URL, CFG_PROP_SCRATCH, CFG_PROP_SHOCK_URL, CFG_PROP_WORKSPACE_SRV_URL, CFG_PROP_KBASE_ENDPOINT, CFG_PROP_SELF_EXTERNAL_URL, CFG_PROP_CONDOR_MODE, CFG_PROP_CONDOR_SUBMIT_DESC, CFG_PROP_REF_DATA_BASE, CFG_PROP_CATALOG_SRV_URL, CFG_PROP_AWE_CLIENT_DOCKER_URI, CFG_PROP_AWE_CLIENT_CALLBACK_NETWORKS }; Map<String, String> config = config(); for (String key : keys) { String value = config.get(key); if (value == null) value = "<not-defined>"; safeConfig.put(key, value); } returnVal = safeConfig; //END list_config return returnVal; } /** * <p>Original spec-file function name: ver</p> * <pre> * Returns the current running version of the NarrativeJobService. * </pre> * * @return instance of String */ @JsonServerMethod(rpc = "NarrativeJobService.ver", async = true) public String ver(RpcContext jsonRpcContext) throws Exception { String returnVal = null; //BEGIN ver returnVal = VERSION; //END ver return returnVal; } /** * <p>Original spec-file function name: status</p> * <pre> * Simply check the status of this service to see queue details * </pre> * * @return instance of type {@link us.kbase.narrativejobservice.Status Status} */ @JsonServerMethod(rpc = "NarrativeJobService.status", async = true) public Status status(RpcContext jsonRpcContext) throws Exception { Status returnVal = null; //BEGIN status int queued = -1; int running = -1; Map<String, String> safeConfig = listConfig(null, jsonRpcContext); String gitCommit = null; try { Properties gitProps = new Properties(); InputStream is = this.getClass().getResourceAsStream("git.properties"); gitProps.load(is); is.close(); gitCommit = gitProps.getProperty("commit"); } catch (Exception ex) { gitCommit = "Error: " + ex.getMessage(); } returnVal = new Status().withRebootMode(-1L) .withStoppingMode(-1L) .withRunningTasksTotal((long) running) .withRunningTasksPerUser(null) .withTasksInQueue((long) queued) .withConfig(safeConfig) .withGitCommit(gitCommit); // make warnings shut up @SuppressWarnings("unused") String foo = gitUrl; @SuppressWarnings("unused") String bar = gitCommitHash; @SuppressWarnings("unused") String baz = version; //END status return returnVal; } /** * <p>Original spec-file function name: run_job</p> * <pre> * Start a new job (long running method of service registered in ServiceRegistery). * Such job runs Docker image for this service in script mode. * </pre> * * @param params instance of type {@link us.kbase.narrativejobservice.RunJobParams RunJobParams} * @return parameter "job_id" of original type "job_id" (A job id.) */ @JsonServerMethod(rpc = "NarrativeJobService.run_job", async = true) public String runJob(RunJobParams params, AuthToken authPart, RpcContext jsonRpcContext) throws Exception { String returnVal = null; //BEGIN run_job System.gc(); String aweClientGroups = SDKMethodRunner.requestClientGroups(config(), params.getMethod()); returnVal = SDKMethodRunner.runJob(params, authPart, null, config(), aweClientGroups); //END run_job return returnVal; } /** * <p>Original spec-file function name: get_job_params</p> * <pre> * Get job params necessary for job execution * </pre> * * @param jobId instance of original type "job_id" (A job id.) * @return multiple set: (1) parameter "params" of type {@link us.kbase.narrativejobservice.RunJobParams RunJobParams}, (2) parameter "config" of mapping from String to String */ @JsonServerMethod(rpc = "NarrativeJobService.get_job_params", tuple = true, async = true) public Tuple2<RunJobParams, Map<String, String>> getJobParams(String jobId, AuthToken authPart, RpcContext jsonRpcContext) throws Exception { RunJobParams return1 = null; Map<String, String> return2 = null; //BEGIN get_job_params System.gc(); return2 = new LinkedHashMap<String, String>(); return1 = SDKMethodRunner.getJobInputParams(jobId, authPart, config(), return2); //END get_job_params Tuple2<RunJobParams, Map<String, String>> returnVal = new Tuple2<RunJobParams, Map<String, String>>(); returnVal.setE1(return1); returnVal.setE2(return2); return returnVal; } /** * <p>Original spec-file function name: update_job</p> * <pre> * </pre> * * @param params instance of type {@link us.kbase.narrativejobservice.UpdateJobParams UpdateJobParams} * @return instance of type {@link us.kbase.narrativejobservice.UpdateJobResults UpdateJobResults} */ @JsonServerMethod(rpc = "NarrativeJobService.update_job", async = true) public UpdateJobResults updateJob(UpdateJobParams params, AuthToken authPart, RpcContext jsonRpcContext) throws Exception { UpdateJobResults returnVal = null; //BEGIN update_job System.gc(); returnVal = new UpdateJobResults().withMessages(SDKMethodRunner.updateJob(params, authPart, config())); //END update_job return returnVal; } /** * <p>Original spec-file function name: add_job_logs</p> * <pre> * </pre> * * @param jobId instance of original type "job_id" (A job id.) * @param lines instance of list of type {@link us.kbase.narrativejobservice.LogLine LogLine} * @return parameter "line_number" of Long */ @JsonServerMethod(rpc = "NarrativeJobService.add_job_logs", async = true) public Long addJobLogs(String jobId, List<LogLine> lines, AuthToken authPart, RpcContext jsonRpcContext) throws Exception { Long returnVal = null; //BEGIN add_job_logs returnVal = (long) SDKMethodRunner.addJobLogs(jobId, lines, authPart, config()); //END add_job_logs return returnVal; } /** * <p>Original spec-file function name: get_job_logs</p> * <pre> * </pre> * * @param params instance of type {@link us.kbase.narrativejobservice.GetJobLogsParams GetJobLogsParams} * @return instance of type {@link us.kbase.narrativejobservice.GetJobLogsResults GetJobLogsResults} */ @JsonServerMethod(rpc = "NarrativeJobService.get_job_logs", async = true) public GetJobLogsResults getJobLogs(GetJobLogsParams params, AuthToken authPart, RpcContext jsonRpcContext) throws Exception { GetJobLogsResults returnVal = null; //BEGIN get_job_logs returnVal = SDKMethodRunner.getJobLogs(params.getJobId(), params.getSkipLines(), authPart, getAdminUsers(), config()); //END get_job_logs return returnVal; } /** * <p>Original spec-file function name: finish_job</p> * <pre> * Register results of already started job * </pre> * * @param jobId instance of original type "job_id" (A job id.) * @param params instance of type {@link us.kbase.narrativejobservice.FinishJobParams FinishJobParams} */ @JsonServerMethod(rpc = "NarrativeJobService.finish_job", async = true) public void finishJob(String jobId, FinishJobParams params, AuthToken authPart, RpcContext jsonRpcContext) throws Exception { //BEGIN finish_job System.gc(); SDKMethodRunner.finishJob(jobId, params, authPart, logger, config()); //END finish_job } /** * <p>Original spec-file function name: check_job</p> * <pre> * Check if a job is finished and get results/error * </pre> * * @param jobId instance of original type "job_id" (A job id.) * @return parameter "job_state" of type {@link us.kbase.narrativejobservice.JobState JobState} */ @JsonServerMethod(rpc = "NarrativeJobService.check_job", async = true) public JobState checkJob(String jobId, AuthToken authPart, RpcContext jsonRpcContext) throws Exception { JobState returnVal = null; //BEGIN check_job returnVal = SDKMethodRunner.checkJob(jobId, authPart, config()); //END check_job return returnVal; } /** * <p>Original spec-file function name: check_jobs</p> * <pre> * </pre> * * @param params instance of type {@link us.kbase.narrativejobservice.CheckJobsParams CheckJobsParams} * @return instance of type {@link us.kbase.narrativejobservice.CheckJobsResults CheckJobsResults} */ @JsonServerMethod(rpc = "NarrativeJobService.check_jobs", async = true) public CheckJobsResults checkJobs(CheckJobsParams params, AuthToken authPart, RpcContext jsonRpcContext) throws Exception { CheckJobsResults returnVal = null; //BEGIN check_jobs returnVal = SDKMethodRunner.checkJobs(params, authPart, config()); //END check_jobs return returnVal; } /** * <p>Original spec-file function name: cancel_job</p> * <pre> * </pre> * * @param params instance of type {@link us.kbase.narrativejobservice.CancelJobParams CancelJobParams} */ @JsonServerMethod(rpc = "NarrativeJobService.cancel_job", async = true) public void cancelJob(CancelJobParams params, AuthToken authPart, RpcContext jsonRpcContext) throws Exception { //BEGIN cancel_job SDKMethodRunner.cancelJob(params, authPart, config()); //END cancel_job } /** * <p>Original spec-file function name: check_job_canceled</p> * <pre> * Check whether a job has been canceled. This method is lightweight compared to check_job. * </pre> * * @param params instance of type {@link us.kbase.narrativejobservice.CancelJobParams CancelJobParams} * @return parameter "result" of type {@link us.kbase.narrativejobservice.CheckJobCanceledResult CheckJobCanceledResult} */ @JsonServerMethod(rpc = "NarrativeJobService.check_job_canceled", async = true) public CheckJobCanceledResult checkJobCanceled(CancelJobParams params, AuthToken authPart, RpcContext jsonRpcContext) throws Exception { CheckJobCanceledResult returnVal = null; //BEGIN check_job_canceled returnVal = SDKMethodRunner.checkJobCanceled(params, authPart, config()); //END check_job_canceled return returnVal; } public static void main(String[] args) throws Exception { if (args.length == 1) { new NarrativeJobServiceServer().startupServer(Integer.parseInt(args[0])); } else if (args.length == 3) { JsonServerSyslog.setStaticUseSyslog(false); JsonServerSyslog.setStaticMlogFile(args[1] + ".log"); new NarrativeJobServiceServer().processRpcCall(new File(args[0]), new File(args[1]), args[2]); } else { System.out.println("Usage: <program> <server_port>"); System.out.println(" or: <program> <context_json_file> <output_json_file> <token>"); return; } } }
// This program is free software; you can redistribute it and/or modify // (at your option) any later version. // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // For more information contact: package org.opennms.web.notification; import java.sql.*; import java.util.*; import java.io.*; import java.net.*; import org.apache.log4j.Category; import org.opennms.core.resource.Vault; public class NotificationModel extends Object { // The whole bunch of constants. private final String USERID = "userID"; private final String NOTICE_TIME = "notifytime"; private final String TXT_MESG = "textMsg"; private final String NUM_MESG = "numericMsg"; private final String NOTIFY = "notifyID"; private final String TIME = "pageTime"; private final String REPLYTIME = "respondTime"; private final String ANS_BY = "answeredBy"; private final String CONTACT = "contactInfo"; private final String NODE = "nodeID"; private final String INTERFACE = "interfaceID"; private final String SERVICE = "serviceID"; private final String MEDIA = "media"; private final String EVENTID = "eventid"; private final String SELECT = "SELECT textmsg, numericmsg, notifyid, pagetime, respondtime, answeredby, nodeid, interfaceid, serviceid, eventid from NOTIFICATIONS;"; private final String NOTICE_ID = "SELECT textmsg, numericmsg, notifyid, pagetime, respondtime, answeredby, nodeid, interfaceid, serviceid, eventid from NOTIFICATIONS where NOTIFYID = ?"; private final String SENT_TO = "SELECT userid, notifytime, media, contactinfo FROM usersnotified WHERE notifyid=?"; private final String INSERT_NOTIFY = "INSERT INTO NOTIFICATIONS (notifyid, textmsg, numericmsg, pagetime, respondtime, answeredby, nodeid, interfaceid, serviceid, eventid) VALUES (NEXTVAL('notifyNxtId'), ?, ?, ?, ?, ?, ?, ?, ?, ?)"; //private final String UPDATE_NOTIFY = "UPDATE NOTIFICATIONS SET " + REPLYTIME + " = ? , " + ANS_BY + " = ? WHERE " + NOTIFY + " = ? "; private final String OUTSTANDING = "SELECT textmsg, numericmsg, notifyid, pagetime, respondtime, answeredby, nodeid, interfaceid, serviceid, eventid FROM NOTIFICATIONS WHERE respondTime is NULL"; private final String OUTSTANDING_COUNT = "SELECT COUNT(*) AS TOTAL FROM NOTIFICATIONS WHERE respondTime is NULL"; private final String USER_OUTSTANDING = "SELECT textmsg, numericmsg, notifyid, pagetime, respondtime, answeredby, nodeid, interfaceid, serviceid, eventid FROM NOTIFICATIONS WHERE (respondTime is NULL) AND notifications.notifyid in (SELECT DISTINCT usersnotified.notifyid FROM usersnotified WHERE usersnotified.userid=?)"; private final String USER_OUTSTANDING_COUNT = "SELECT COUNT(*) AS TOTAL FROM NOTIFICATIONS WHERE (respondTime is NULL) AND notifications.notifyid in (SELECT DISTINCT usersnotified.notifyid FROM usersnotified WHERE usersnotified.userid=?)"; /** * Static Log4j logging category */ private static Category m_logger = Category.getInstance(NotificationModel.class.getName()); public Notification getNoticeInfo(int id) throws SQLException { Notification nbean = new Notification(); Connection conn = Vault.getDbConnection(); try { //create the list of users the page was sent to PreparedStatement sentTo = conn.prepareStatement(SENT_TO); sentTo.setInt(1, id); ResultSet sentToResults = sentTo.executeQuery(); List sentToList = new ArrayList(); sentToResults.beforeFirst(); while(sentToResults.next()) { NoticeSentTo newSentTo = new NoticeSentTo(); newSentTo.setUserId( sentToResults.getString(USERID) ); Timestamp ts = sentToResults.getTimestamp(NOTICE_TIME); if (ts != null) newSentTo.setTime(ts.getTime()); else newSentTo.setTime(0); newSentTo.setMedia( sentToResults.getString(MEDIA) ); newSentTo.setContactInfo( sentToResults.getString(CONTACT) ); sentToList.add(newSentTo); } nbean.m_sentTo = sentToList; //fill out the rest of the bean PreparedStatement pstmt = conn.prepareStatement(NOTICE_ID); pstmt.setInt(1, id); ResultSet rs = pstmt.executeQuery(); rs.beforeFirst(); while(rs.next()) { Object element = rs.getString(TXT_MESG); nbean.m_txtMsg = (String)element; element = rs.getString(NUM_MESG); nbean.m_numMsg = (String)element; element = new Integer(rs.getInt(NOTIFY)); nbean.m_notifyID = ((Integer)element).intValue(); element = rs.getTimestamp(TIME); nbean.m_timeSent = ((Timestamp)element).getTime(); element = rs.getTimestamp(REPLYTIME); if (element != null) nbean.m_timeReply = ((Timestamp)element).getTime(); else nbean.m_timeReply = 0; element = rs.getString(ANS_BY); nbean.m_responder = (String)element; element = new Integer(rs.getInt(NODE)); nbean.m_nodeID = ((Integer)element).intValue(); element = rs.getString(INTERFACE); nbean.m_interfaceID = (String)element; element = new Integer(rs.getInt(SERVICE)); nbean.m_serviceId = ((Integer)element).intValue(); element = new Integer(rs.getInt(EVENTID)); nbean.m_eventId = ((Integer)element).intValue(); Statement stmttmp = conn.createStatement(); ResultSet rstmp = stmttmp.executeQuery("SELECT servicename from service where serviceid = " + nbean.m_serviceId); if(rstmp.next()) { element = rstmp.getString("servicename"); if(element != null) { nbean.m_serviceName = (String)element; } } } rs.close(); pstmt.close(); } catch( SQLException e ) { m_logger.debug("Problem getting data from the notifications table."); m_logger.debug("Error: " + e.getLocalizedMessage()); throw e; } finally { Vault.releaseDbConnection( conn ); } return nbean; } /** * Return all notifications, both outstanding and acknowledged. */ public Notification[] allNotifications() throws SQLException { Notification[] notices = null; Connection conn = Vault.getDbConnection(); try { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(SELECT); notices = rs2NotifyBean( conn, rs ); rs.close(); stmt.close(); } catch( SQLException e) { m_logger.debug("allNotifications: Problem getting data from the notifications table."); m_logger.debug("allNotifications: Error: " + e.getLocalizedMessage()); throw e; } finally { Vault.releaseDbConnection( conn ); } return( notices ); } /** * This method returns the data from the result set as an array of Notification objects. */ protected Notification[] rs2NotifyBean( Connection conn, ResultSet rs ) throws SQLException { Notification[] notices = null; Vector vector = new Vector(); // Format the results. try { rs.beforeFirst(); while(rs.next()) { Notification nbean = new Notification(); Object element = rs.getString(TXT_MESG); nbean.m_txtMsg = (String)element; element = rs.getString(NUM_MESG); nbean.m_numMsg = (String)element; element = new Integer(rs.getInt(NOTIFY)); nbean.m_notifyID = ((Integer)element).intValue(); element = rs.getTimestamp(TIME); nbean.m_timeSent = ((Timestamp)element).getTime(); element = rs.getTimestamp(REPLYTIME); if (element != null) nbean.m_timeReply = ((Timestamp)element).getTime(); else nbean.m_timeReply = 0; element = rs.getString(ANS_BY); nbean.m_responder = (String)element; element = new Integer(rs.getInt(NODE)); nbean.m_nodeID = ((Integer)element).intValue(); element = rs.getString(INTERFACE); nbean.m_interfaceID = (String)element; element = new Integer(rs.getInt(SERVICE)); nbean.m_serviceId = ((Integer)element).intValue(); element = new Integer(rs.getInt(EVENTID)); nbean.m_eventId = ((Integer)element).intValue(); Statement stmttmp = conn.createStatement(); ResultSet rstmp = stmttmp.executeQuery("SELECT servicename from service where serviceid = " + nbean.m_serviceId); if(rstmp.next()) { element = rstmp.getString("servicename"); if(element != null) { nbean.m_serviceName = (String)element; } } rstmp.close(); stmttmp.close(); vector.addElement( nbean ) ; } } catch( SQLException e) { m_logger.debug("Error:" + e.getLocalizedMessage()); m_logger.debug("Error occured in rs2NotifyBean"); throw e; } notices = new Notification[vector.size()]; for (int i = 0;i < notices.length; i++) { notices[i] = (Notification)vector.elementAt(i); } return notices; } /** * This method returns the count of all outstanding notices. */ public Notification[] getOutstandingNotices() throws SQLException { Notification[] notices = null; Connection conn = Vault.getDbConnection(); try { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(OUTSTANDING); notices = rs2NotifyBean( conn, rs ); rs.close(); stmt.close(); } catch( SQLException e ) { m_logger.debug("Problem getting data from the notifications table."); m_logger.debug("Error: " + e.getLocalizedMessage()); throw e; } finally { Vault.releaseDbConnection( conn ); } return( notices ); } /** * This method returns notices not yet acknowledged. */ public int getOutstandingNoticeCount() throws SQLException { int count = 0; Connection conn = Vault.getDbConnection(); try { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery( OUTSTANDING_COUNT ); if( rs.next() ) { count = rs.getInt( "TOTAL" ); } rs.close(); stmt.close(); } catch( SQLException e ) { m_logger.debug("Problem getting data from the notifications table."); m_logger.debug("Error: " + e.getLocalizedMessage()); throw e; } finally { Vault.releaseDbConnection( conn ); } return( count ); } /** * This method returns notices not yet acknowledged. */ public int getOutstandingNoticeCount( String username) throws SQLException { if( username == null ) { throw new IllegalArgumentException( "Cannot take null parameters." ); } int count = 0; Connection conn = Vault.getDbConnection(); try { PreparedStatement pstmt = conn.prepareStatement( USER_OUTSTANDING_COUNT ); pstmt.setString( 1, username ); ResultSet rs = pstmt.executeQuery(); if( rs.next() ) { count = rs.getInt( "TOTAL" ); } rs.close(); pstmt.close(); } catch( SQLException e ) { m_logger.debug("Problem getting data from the notifications table."); m_logger.debug("Error: " + e.getLocalizedMessage()); throw e; } finally { Vault.releaseDbConnection( conn ); } return( count ); } /** * This method returns notices not yet acknowledged. */ public Notification[] getOutstandingNotices(String name) throws SQLException { Notification[] notices = null; Connection conn = Vault.getDbConnection(); try { PreparedStatement pstmt = conn.prepareStatement(USER_OUTSTANDING); pstmt.setString(1, name); ResultSet rs = pstmt.executeQuery(); notices = rs2NotifyBean( conn, rs ); rs.close(); pstmt.close(); } catch( SQLException e ) { m_logger.debug("Problem getting data from the notifications table."); m_logger.debug("Error: " + e.getLocalizedMessage()); throw e; } finally { Vault.releaseDbConnection( conn ); } return( notices ); } /** * This method updates the table when the user acknowledges the pager information. */ public void acknowledged(String name, int noticeId) throws SQLException { if( name == null ) { throw new IllegalArgumentException( "Cannot take null parameters." ); } Connection conn = Vault.getDbConnection(); try { PreparedStatement pstmt = conn.prepareStatement("UPDATE notifications SET respondtime = ? , answeredby = ? WHERE notifyid= ?"); pstmt.setTimestamp(1, new Timestamp(System.currentTimeMillis())); pstmt.setString(2, name); pstmt.setInt(3, noticeId); pstmt.execute(); pstmt.close(); } catch( SQLException e ) { m_logger.debug("Problem acknowledging."); m_logger.debug("Error: " + e.getLocalizedMessage()); throw e; } finally { Vault.releaseDbConnection( conn ); } } /** * This method helps insert into the database. */ public void insert(Notification nbean) throws SQLException { if( nbean == null || nbean.m_txtMsg == null ) { throw new IllegalArgumentException( "Cannot take null parameters." ); } Connection conn = Vault.getDbConnection(); try { PreparedStatement pstmt = conn.prepareStatement(INSERT_NOTIFY); pstmt.setString(1, nbean.m_txtMsg); pstmt.setString(2, nbean.m_numMsg); pstmt.setLong(3, nbean.m_timeSent); pstmt.setLong(4, nbean.m_timeReply); pstmt.setString(5, nbean.m_responder); pstmt.setInt(6, nbean.m_nodeID); pstmt.setString(7, nbean.m_interfaceID); pstmt.setInt(8, nbean.m_serviceId); pstmt.setInt(9, nbean.m_eventId); pstmt.execute(); // Close prepared statement. pstmt.close(); } catch( SQLException e ) { m_logger.debug("Problem getting data from the notifications table."); m_logger.debug("Error: " + e.getLocalizedMessage()); throw e; } finally { Vault.releaseDbConnection( conn ); } } /** * This method may be used to insert / update the database. */ /* public void execute(String query) { if(m_dbConn == null) { m_logger.debug("Problem executing query."); m_logger.debug("We do not have a database connection yet"); } else { try { Statement stmt = m_dbConn.createStatement(); stmt.executeQuery(query); // Close statement. if(stmt != null) stmt.close(); } catch(Exception e) { m_logger.debug("Problem inserting"); m_logger.debug("Error: " + e.getLocalizedMessage()); } } }*/ /** * This method is used for formatting the date attributes in a proper format. */ private String appendZero(String values) { int len = values.length(); if(values != null) { if(len >= 0 && len < 2) { while(2 - len > 0) { values = "0" + values; len++; } } else if(len > 2) m_logger.debug("Incorrect attributes for time"); } return values; } }
package org.zstack.storage.volume; import org.springframework.beans.factory.annotation.Autowire; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.transaction.annotation.Transactional; import org.zstack.core.cascade.CascadeConstant; import org.zstack.core.cascade.CascadeFacade; import org.zstack.core.cloudbus.CloudBus; import org.zstack.core.cloudbus.CloudBusCallBack; import org.zstack.core.componentloader.PluginRegistry; import org.zstack.core.db.DatabaseFacade; import org.zstack.core.db.SimpleQuery; import org.zstack.core.db.SimpleQuery.Op; import org.zstack.core.errorcode.ErrorFacade; import org.zstack.core.thread.ChainTask; import org.zstack.core.thread.SyncTaskChain; import org.zstack.core.thread.ThreadFacade; import org.zstack.core.workflow.FlowChainBuilder; import org.zstack.core.workflow.ShareFlow; import org.zstack.header.core.Completion; import org.zstack.header.core.NoErrorCompletion; import org.zstack.header.core.NopeCompletion; import org.zstack.header.core.ReturnValueCompletion; import org.zstack.header.core.workflow.*; import org.zstack.header.errorcode.ErrorCode; import org.zstack.header.errorcode.OperationFailureException; import org.zstack.header.errorcode.SysErrors; import org.zstack.header.exception.CloudRuntimeException; import org.zstack.header.host.HostInventory; import org.zstack.header.host.HostVO; import org.zstack.header.image.ImageInventory; import org.zstack.header.image.ImageVO; import org.zstack.header.message.APIDeleteMessage.DeletionMode; import org.zstack.header.message.APIMessage; import org.zstack.header.message.Message; import org.zstack.header.message.MessageReply; import org.zstack.header.message.OverlayMessage; import org.zstack.header.storage.primary.*; import org.zstack.header.storage.snapshot.CreateVolumeSnapshotMsg; import org.zstack.header.storage.snapshot.CreateVolumeSnapshotReply; import org.zstack.header.storage.snapshot.VolumeSnapshotConstant; import org.zstack.header.storage.snapshot.VolumeSnapshotVO; import org.zstack.header.vm.*; import org.zstack.header.volume.*; import org.zstack.header.volume.VolumeConstant.Capability; import org.zstack.header.volume.VolumeDeletionPolicyManager.VolumeDeletionPolicy; import org.zstack.identity.AccountManager; import org.zstack.tag.TagManager; import org.zstack.utils.CollectionUtils; import org.zstack.utils.DebugUtils; import org.zstack.utils.Utils; import org.zstack.utils.function.ForEachFunction; import org.zstack.utils.logging.CLogger; import javax.persistence.TypedQuery; import java.util.*; import static org.zstack.utils.CollectionDSL.list; /** * Created with IntelliJ IDEA. * User: frank * Time: 9:20 PM * To change this template use File | Settings | File Templates. */ @Configurable(preConstruction = true, autowire = Autowire.BY_TYPE) public class VolumeBase implements Volume { private static final CLogger logger = Utils.getLogger(VolumeBase.class); @Autowired private CloudBus bus; @Autowired private DatabaseFacade dbf; @Autowired private ThreadFacade thdf; @Autowired private ErrorFacade errf; @Autowired private CascadeFacade casf; @Autowired private AccountManager acntMgr; @Autowired private TagManager tagMgr; @Autowired private PluginRegistry pluginRgty; @Autowired private VolumeDeletionPolicyManager deletionPolicyMgr; protected String syncThreadId; protected VolumeVO self; public VolumeBase(VolumeVO vo) { self = vo; syncThreadId = String.format("volume-%s", self.getUuid()); } protected void refreshVO() { self = dbf.reload(self); } @Override public void handleMessage(Message msg) { try { if (msg instanceof APIMessage) { handleApiMessage((APIMessage) msg); } else { handleLocalMessage(msg); } } catch (Exception e) { bus.logExceptionWithMessageDump(msg, e); bus.replyErrorByMessageType(msg, e); } } private void handleLocalMessage(Message msg) { if (msg instanceof VolumeDeletionMsg) { handle((VolumeDeletionMsg) msg); } else if (msg instanceof DeleteVolumeMsg) { handle((DeleteVolumeMsg) msg); } else if (msg instanceof VolumeCreateSnapshotMsg) { handle((VolumeCreateSnapshotMsg) msg); } else if (msg instanceof CreateDataVolumeTemplateFromDataVolumeMsg) { handle((CreateDataVolumeTemplateFromDataVolumeMsg) msg); } else if (msg instanceof ExpungeVolumeMsg) { handle((ExpungeVolumeMsg) msg); } else if (msg instanceof RecoverVolumeMsg) { handle((RecoverVolumeMsg) msg); } else if (msg instanceof SyncVolumeSizeMsg) { handle((SyncVolumeSizeMsg) msg); } else if (msg instanceof InstantiateVolumeMsg) { handle((InstantiateVolumeMsg) msg); } else if (msg instanceof OverlayMessage) { handle((OverlayMessage) msg); } else { bus.dealWithUnknownMessage(msg); } } private void handle(InstantiateVolumeMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return String.format("instantiate-volume-%s", self.getUuid()); } @Override public void run(SyncTaskChain chain) { doInstantiateVolume(msg, new NoErrorCompletion(msg, chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return "instantiate-volume"; } }); } private void doInstantiateVolume(InstantiateVolumeMsg msg, NoErrorCompletion completion) { InstantiateVolumeReply reply = new InstantiateVolumeReply(); FlowChain chain = FlowChainBuilder.newShareFlowChain(); chain.setName(String.format("instantiate-volume-%s", self.getUuid())); chain.then(new ShareFlow() { String installPath; String format; @Override public void setup() { if (!msg.isPrimaryStorageAllocated()) { flow(new Flow() { String __name__ = "allocate-primary-storage"; boolean success; @Override public void run(FlowTrigger trigger, Map data) { AllocatePrimaryStorageMsg amsg = new AllocatePrimaryStorageMsg(); amsg.setRequiredPrimaryStorageUuid(msg.getPrimaryStorageUuid()); amsg.setSize(self.getSize()); bus.makeTargetServiceIdByResourceUuid(amsg, PrimaryStorageConstant.SERVICE_ID, msg.getPrimaryStorageUuid()); bus.send(amsg, new CloudBusCallBack(trigger) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { trigger.fail(reply.getError()); } else { success = true; trigger.next(); } } }); } @Override public void rollback(FlowRollback trigger, Map data) { if (success) { ReturnPrimaryStorageCapacityMsg rmsg = new ReturnPrimaryStorageCapacityMsg(); rmsg.setPrimaryStorageUuid(msg.getPrimaryStorageUuid()); rmsg.setDiskSize(self.getSize()); bus.makeTargetServiceIdByResourceUuid(rmsg, PrimaryStorageConstant.SERVICE_ID, msg.getPrimaryStorageUuid()); bus.send(rmsg); } trigger.rollback(); } }); } flow(new Flow() { String __name__ = "instantiate-volume-on-primary-storage"; boolean success; @Override public void run(FlowTrigger trigger, Map data) { SimpleQuery<PrimaryStorageVO> q = dbf.createQuery(PrimaryStorageVO.class); q.select(PrimaryStorageVO_.type); q.add(PrimaryStorageVO_.uuid, Op.EQ, msg.getPrimaryStorageUuid()); String psType = q.findValue(); InstantiateDataVolumeOnCreationExtensionPoint ext = pluginRgty.getExtensionFromMap(psType, InstantiateDataVolumeOnCreationExtensionPoint.class); if (ext != null) { ext.instantiateDataVolumeOnCreation(msg, getSelfInventory(), new ReturnValueCompletion<VolumeInventory>(trigger) { @Override public void success(VolumeInventory ret) { success = true; installPath = ret.getInstallPath(); format = ret.getFormat(); trigger.next(); } @Override public void fail(ErrorCode errorCode) { trigger.fail(errorCode); } }); } else { if (msg instanceof InstantiateRootVolumeMsg) { instantiateRootVolume((InstantiateRootVolumeMsg) msg, trigger); } else { instantiateDataVolume(msg, trigger); } } } private void instantiateRootVolume(InstantiateRootVolumeMsg msg, FlowTrigger trigger) { InstantiateRootVolumeFromTemplateOnPrimaryStorageMsg imsg = new InstantiateRootVolumeFromTemplateOnPrimaryStorageMsg(); imsg.setPrimaryStorageUuid(msg.getPrimaryStorageUuid()); imsg.setVolume(getSelfInventory()); if (msg.getHostUuid() != null) { imsg.setDestHost(HostInventory.valueOf(dbf.findByUuid(msg.getHostUuid(), HostVO.class))); } imsg.setTemplateSpec(msg.getTemplateSpec()); bus.makeTargetServiceIdByResourceUuid(imsg, PrimaryStorageConstant.SERVICE_ID, msg.getPrimaryStorageUuid()); bus.send(imsg, new CloudBusCallBack(trigger) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { trigger.fail(reply.getError()); return; } success = true; InstantiateVolumeOnPrimaryStorageReply ir = reply.castReply(); installPath = ir.getVolume().getInstallPath(); format = ir.getVolume().getFormat(); trigger.next(); } }); } private void instantiateDataVolume(InstantiateVolumeMsg msg, FlowTrigger trigger) { InstantiateVolumeOnPrimaryStorageMsg imsg = new InstantiateVolumeOnPrimaryStorageMsg(); imsg.setPrimaryStorageUuid(msg.getPrimaryStorageUuid()); imsg.setVolume(getSelfInventory()); if (msg.getHostUuid() != null) { imsg.setDestHost(HostInventory.valueOf(dbf.findByUuid(msg.getHostUuid(), HostVO.class))); } bus.makeTargetServiceIdByResourceUuid(imsg, PrimaryStorageConstant.SERVICE_ID, msg.getPrimaryStorageUuid()); bus.send(imsg, new CloudBusCallBack(trigger) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { trigger.fail(reply.getError()); return; } success = true; InstantiateVolumeOnPrimaryStorageReply ir = reply.castReply(); installPath = ir.getVolume().getInstallPath(); format = ir.getVolume().getFormat(); trigger.next(); } }); } @Override public void rollback(FlowRollback trigger, Map data) { if (success) { DeleteVolumeOnPrimaryStorageMsg dmsg = new DeleteVolumeOnPrimaryStorageMsg(); dmsg.setUuid(msg.getPrimaryStorageUuid()); dmsg.setVolume(getSelfInventory()); bus.makeTargetServiceIdByResourceUuid(dmsg, PrimaryStorageConstant.SERVICE_ID, msg.getPrimaryStorageUuid()); bus.send(dmsg); } trigger.rollback(); } }); done(new FlowDoneHandler(msg, completion) { @Override public void handle(Map data) { VolumeStatus oldStatus = self.getStatus(); self.setPrimaryStorageUuid(msg.getPrimaryStorageUuid()); self.setInstallPath(installPath); DebugUtils.Assert(format != null, "format cannot be null"); self.setFormat(format); self.setStatus(VolumeStatus.Ready); self = dbf.updateAndRefresh(self); VolumeInventory vol = getSelfInventory(); new FireVolumeCanonicalEvent().fireVolumeStatusChangedEvent(oldStatus, vol); reply.setVolume(vol); bus.reply(msg, reply); } }); error(new FlowErrorHandler(msg, completion) { @Override public void handle(ErrorCode errCode, Map data) { reply.setError(errCode); bus.reply(msg, reply); } }); Finally(new FlowFinallyHandler(msg, completion) { @Override public void Finally() { completion.done(); } }); } }).start(); } private void handle(OverlayMessage msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadId; } @Override public void run(SyncTaskChain chain) { doOverlayMessage(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return "overlay-message"; } }); } private void doOverlayMessage(OverlayMessage msg, NoErrorCompletion noErrorCompletion) { bus.send(msg.getMessage(), new CloudBusCallBack(msg, noErrorCompletion) { @Override public void run(MessageReply reply) { bus.reply(msg, reply); noErrorCompletion.done(); } }); } private void handle(final SyncVolumeSizeMsg msg) { final SyncVolumeSizeReply reply = new SyncVolumeSizeReply(); syncVolumeVolumeSize(new ReturnValueCompletion<VolumeSize>(msg) { @Override public void success(VolumeSize ret) { reply.setActualSize(ret.actualSize); reply.setSize(ret.size); bus.reply(msg, reply); } @Override public void fail(ErrorCode errorCode) { reply.setError(errorCode); bus.reply(msg, reply); } }); } private void handle(final RecoverVolumeMsg msg) { final RecoverVolumeReply reply = new RecoverVolumeReply(); thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadId; } @Override public void run(SyncTaskChain chain) { recoverVolume(new Completion(chain, msg) { @Override public void success() { bus.reply(msg, reply); chain.next(); } @Override public void fail(ErrorCode errorCode) { reply.setError(errorCode); bus.reply(msg, reply); chain.next(); } }); } @Override public String getName() { return RecoverVolumeMsg.class.getName(); } }); } private void expunge(final Completion completion) { if (self.getStatus() != VolumeStatus.Deleted) { throw new OperationFailureException(errf.stringToOperationError( String.format("the volume[uuid:%s, name:%s] is not deleted yet, can't expunge it", self.getUuid(), self.getName()) )); } final VolumeInventory inv = getSelfInventory(); CollectionUtils.safeForEach(pluginRgty.getExtensionList(VolumeBeforeExpungeExtensionPoint.class), new ForEachFunction<VolumeBeforeExpungeExtensionPoint>() { @Override public void run(VolumeBeforeExpungeExtensionPoint arg) { arg.volumeBeforeExpunge(inv); } }); if (self.getPrimaryStorageUuid() != null) { DeleteVolumeOnPrimaryStorageMsg dmsg = new DeleteVolumeOnPrimaryStorageMsg(); dmsg.setVolume(getSelfInventory()); dmsg.setUuid(self.getPrimaryStorageUuid()); bus.makeTargetServiceIdByResourceUuid(dmsg, PrimaryStorageConstant.SERVICE_ID, self.getPrimaryStorageUuid()); bus.send(dmsg, new CloudBusCallBack(completion) { @Override public void run(MessageReply r) { if (!r.isSuccess()) { completion.fail(r.getError()); } else { ReturnPrimaryStorageCapacityMsg msg = new ReturnPrimaryStorageCapacityMsg(); msg.setPrimaryStorageUuid(self.getPrimaryStorageUuid()); msg.setDiskSize(self.getSize()); bus.makeTargetServiceIdByResourceUuid(msg, PrimaryStorageConstant.SERVICE_ID, self.getPrimaryStorageUuid()); bus.send(msg); CollectionUtils.safeForEach(pluginRgty.getExtensionList(VolumeAfterExpungeExtensionPoint.class), new ForEachFunction<VolumeAfterExpungeExtensionPoint>() { @Override public void run(VolumeAfterExpungeExtensionPoint arg) { arg.volumeAfterExpunge(inv); } }); dbf.remove(self); completion.success(); } } }); } else { CollectionUtils.safeForEach(pluginRgty.getExtensionList(VolumeAfterExpungeExtensionPoint.class), new ForEachFunction<VolumeAfterExpungeExtensionPoint>() { @Override public void run(VolumeAfterExpungeExtensionPoint arg) { arg.volumeAfterExpunge(inv); } }); dbf.remove(self); completion.success(); } } private void handle(final ExpungeVolumeMsg msg) { final ExpungeVolumeReply reply = new ExpungeVolumeReply(); thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadId; } @Override public void run(SyncTaskChain chain) { expunge(new Completion(msg, chain) { @Override public void success() { bus.reply(msg, reply); chain.next(); } @Override public void fail(ErrorCode errorCode) { reply.setError(errorCode); bus.reply(msg, reply); chain.next(); } }); } @Override public String getName() { return ExpungeVolumeMsg.class.getName(); } }); } private void handle(final CreateDataVolumeTemplateFromDataVolumeMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadId; } @Override public void run(SyncTaskChain chain) { doCreateDataVolumeTemplateFromDataVolumeMsg(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return CreateDataVolumeTemplateFromDataVolumeMsg.class.getName(); } }); } private void doCreateDataVolumeTemplateFromDataVolumeMsg(CreateDataVolumeTemplateFromDataVolumeMsg msg, NoErrorCompletion noErrorCompletion) { final CreateTemplateFromVolumeOnPrimaryStorageMsg cmsg = new CreateTemplateFromVolumeOnPrimaryStorageMsg(); cmsg.setBackupStorageUuid(msg.getBackupStorageUuid()); cmsg.setImageInventory(ImageInventory.valueOf(dbf.findByUuid(msg.getImageUuid(), ImageVO.class))); cmsg.setVolumeInventory(getSelfInventory()); bus.makeTargetServiceIdByResourceUuid(cmsg, PrimaryStorageConstant.SERVICE_ID, self.getPrimaryStorageUuid()); bus.send(cmsg, new CloudBusCallBack(msg, noErrorCompletion) { @Override public void run(MessageReply r) { CreateDataVolumeTemplateFromDataVolumeReply reply = new CreateDataVolumeTemplateFromDataVolumeReply(); if (!r.isSuccess()) { reply.setError(r.getError()); } else { CreateTemplateFromVolumeOnPrimaryStorageReply creply = r.castReply(); String backupStorageInstallPath = creply.getTemplateBackupStorageInstallPath(); reply.setFormat(creply.getFormat()); reply.setInstallPath(backupStorageInstallPath); reply.setMd5sum(null); reply.setBackupStorageUuid(msg.getBackupStorageUuid()); } bus.reply(msg, reply); noErrorCompletion.done(); } }); } private void handle(final DeleteVolumeMsg msg) { final DeleteVolumeReply reply = new DeleteVolumeReply(); delete(true, VolumeDeletionPolicy.valueOf(msg.getDeletionPolicy()), msg.isDetachBeforeDeleting(), new Completion(msg) { @Override public void success() { logger.debug(String.format("deleted data volume[uuid: %s]", msg.getUuid())); bus.reply(msg, reply); } @Override public void fail(ErrorCode errorCode) { reply.setError(errorCode); bus.reply(msg, reply); } }); } private void deleteVolume(final VolumeDeletionMsg msg, final NoErrorCompletion completion) { final VolumeDeletionReply reply = new VolumeDeletionReply(); for (VolumeDeletionExtensionPoint extp : pluginRgty.getExtensionList(VolumeDeletionExtensionPoint.class)) { extp.preDeleteVolume(getSelfInventory()); } CollectionUtils.safeForEach(pluginRgty.getExtensionList(VolumeDeletionExtensionPoint.class), new ForEachFunction<VolumeDeletionExtensionPoint>() { @Override public void run(VolumeDeletionExtensionPoint arg) { arg.beforeDeleteVolume(getSelfInventory()); } }); FlowChain chain = FlowChainBuilder.newShareFlowChain(); chain.setName(String.format("delete-volume-%s", self.getUuid())); // for NotInstantiated Volume, no flow to execute chain.allowEmptyFlow(); chain.then(new ShareFlow() { VolumeDeletionPolicy deletionPolicy; { if (msg.getDeletionPolicy() == null) { deletionPolicy = deletionPolicyMgr.getDeletionPolicy(self.getUuid()); } else { deletionPolicy = VolumeDeletionPolicy.valueOf(msg.getDeletionPolicy()); } } @Override public void setup() { if (self.getVmInstanceUuid() != null && self.getType() == VolumeType.Data && msg.isDetachBeforeDeleting()) { flow(new NoRollbackFlow() { String __name__ = "detach-volume-from-vm"; public void run(final FlowTrigger trigger, Map data) { DetachDataVolumeFromVmMsg dmsg = new DetachDataVolumeFromVmMsg(); dmsg.setVolume(getSelfInventory()); bus.makeTargetServiceIdByResourceUuid(dmsg, VmInstanceConstant.SERVICE_ID, dmsg.getVmInstanceUuid()); bus.send(dmsg, new CloudBusCallBack(trigger) { @Override public void run(MessageReply reply) { self.setVmInstanceUuid(null); self = dbf.updateAndRefresh(self); trigger.next(); } }); } }); } if (deletionPolicy == VolumeDeletionPolicy.Direct) { flow(new NoRollbackFlow() { String __name__ = "delete-data-volume-from-primary-storage"; @Override public void run(final FlowTrigger trigger, Map data) { if (self.getStatus() == VolumeStatus.Ready) { DeleteVolumeOnPrimaryStorageMsg dmsg = new DeleteVolumeOnPrimaryStorageMsg(); dmsg.setVolume(getSelfInventory()); dmsg.setUuid(self.getPrimaryStorageUuid()); bus.makeTargetServiceIdByResourceUuid(dmsg, PrimaryStorageConstant.SERVICE_ID, self.getPrimaryStorageUuid()); logger.debug(String.format("Asking primary storage[uuid:%s] to remove data volume[uuid:%s]", self.getPrimaryStorageUuid(), self.getUuid())); bus.send(dmsg, new CloudBusCallBack(trigger) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { logger.warn(String.format("failed to delete volume[uuid:%s, name:%s], %s", self.getUuid(), self.getName(), reply.getError())); } trigger.next(); } }); } else { trigger.next(); } } }); } if (self.getPrimaryStorageUuid() != null && deletionPolicy == VolumeDeletionPolicy.Direct) { flow(new NoRollbackFlow() { String __name__ = "return-primary-storage-capacity"; @Override public void run(FlowTrigger trigger, Map data) { ReturnPrimaryStorageCapacityMsg rmsg = new ReturnPrimaryStorageCapacityMsg(); rmsg.setPrimaryStorageUuid(self.getPrimaryStorageUuid()); rmsg.setDiskSize(self.getSize()); bus.makeTargetServiceIdByResourceUuid(rmsg, PrimaryStorageConstant.SERVICE_ID, self.getPrimaryStorageUuid()); bus.send(rmsg); trigger.next(); } }); } done(new FlowDoneHandler(msg) { @Override public void handle(Map data) { VolumeStatus oldStatus = self.getStatus(); if (deletionPolicy == VolumeDeletionPolicy.Direct) { self.setStatus(VolumeStatus.Deleted); self = dbf.updateAndRefresh(self); new FireVolumeCanonicalEvent().fireVolumeStatusChangedEvent(oldStatus, getSelfInventory()); dbf.remove(self); } else if (deletionPolicy == VolumeDeletionPolicy.Delay) { self.setStatus(VolumeStatus.Deleted); self = dbf.updateAndRefresh(self); new FireVolumeCanonicalEvent().fireVolumeStatusChangedEvent(oldStatus, getSelfInventory()); } else if (deletionPolicy == VolumeDeletionPolicy.Never) { self.setStatus(VolumeStatus.Deleted); self = dbf.updateAndRefresh(self); new FireVolumeCanonicalEvent().fireVolumeStatusChangedEvent(oldStatus, getSelfInventory()); } else { throw new CloudRuntimeException(String.format("Invalid deletionPolicy:%s", deletionPolicy)); } CollectionUtils.safeForEach(pluginRgty.getExtensionList(VolumeDeletionExtensionPoint.class), new ForEachFunction<VolumeDeletionExtensionPoint>() { @Override public void run(VolumeDeletionExtensionPoint arg) { arg.afterDeleteVolume(getSelfInventory()); } }); bus.reply(msg, reply); } }); error(new FlowErrorHandler(msg) { @Override public void handle(final ErrorCode errCode, Map data) { CollectionUtils.safeForEach(pluginRgty.getExtensionList(VolumeDeletionExtensionPoint.class), new ForEachFunction<VolumeDeletionExtensionPoint>() { @Override public void run(VolumeDeletionExtensionPoint arg) { arg.failedToDeleteVolume(getSelfInventory(), errCode); } }); reply.setError(errCode); bus.reply(msg, reply); } }); Finally(new FlowFinallyHandler() { @Override public void Finally() { completion.done(); } }); } }).start(); } private void handle(final VolumeDeletionMsg msg) { thdf.chainSubmit(new ChainTask() { @Override public String getSyncSignature() { return syncThreadId; } @Override public void run(final SyncTaskChain chain) { self = dbf.reload(self); if (self.getStatus() == VolumeStatus.Deleted) { // the volume has been deleted // we run into this case because the cascading framework // will send duplicate messages when deleting a vm as the cascading // framework has no knowledge about if the volume has been deleted VolumeDeletionReply reply = new VolumeDeletionReply(); bus.reply(msg, reply); chain.next(); return; } deleteVolume(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("delete-volume-%s", self.getUuid()); } }); } private void handleApiMessage(APIMessage msg) { if (msg instanceof APIChangeVolumeStateMsg) { handle((APIChangeVolumeStateMsg) msg); } else if (msg instanceof APICreateVolumeSnapshotMsg) { handle((APICreateVolumeSnapshotMsg) msg); } else if (msg instanceof APIDeleteDataVolumeMsg) { handle((APIDeleteDataVolumeMsg) msg); } else if (msg instanceof APIDetachDataVolumeFromVmMsg) { handle((APIDetachDataVolumeFromVmMsg) msg); } else if (msg instanceof APIAttachDataVolumeToVmMsg) { handle((APIAttachDataVolumeToVmMsg) msg); } else if (msg instanceof APIGetDataVolumeAttachableVmMsg) { handle((APIGetDataVolumeAttachableVmMsg) msg); } else if (msg instanceof APIUpdateVolumeMsg) { handle((APIUpdateVolumeMsg) msg); } else if (msg instanceof APIRecoverDataVolumeMsg) { handle((APIRecoverDataVolumeMsg) msg); } else if (msg instanceof APIExpungeDataVolumeMsg) { handle((APIExpungeDataVolumeMsg) msg); } else if (msg instanceof APISyncVolumeSizeMsg) { handle((APISyncVolumeSizeMsg) msg); } else if (msg instanceof APIGetVolumeCapabilitiesMsg) { handle((APIGetVolumeCapabilitiesMsg) msg); } else { bus.dealWithUnknownMessage(msg); } } private void handle(APIGetVolumeCapabilitiesMsg msg) { APIGetVolumeCapabilitiesReply reply = new APIGetVolumeCapabilitiesReply(); Map<String, Object> ret = new HashMap<String, Object>(); if (VolumeStatus.Ready == self.getStatus()) { getPrimaryStorageCapacities(ret); } reply.setCapabilities(ret); bus.reply(msg, reply); } private void getPrimaryStorageCapacities(Map<String, Object> ret) { SimpleQuery<PrimaryStorageVO> q = dbf.createQuery(PrimaryStorageVO.class); q.select(PrimaryStorageVO_.type); q.add(PrimaryStorageVO_.uuid, Op.EQ, self.getPrimaryStorageUuid()); String type = q.findValue(); PrimaryStorageType psType = PrimaryStorageType.valueOf(type); ret.put(Capability.MigrationInCurrentPrimaryStorage.toString(), psType.isSupportVolumeMigrationInCurrentPrimaryStorage()); ret.put(Capability.MigrationToOtherPrimaryStorage.toString(), psType.isSupportVolumeMigrationToOtherPrimaryStorage()); } class VolumeSize { long size; long actualSize; } private void syncVolumeVolumeSize(final ReturnValueCompletion<VolumeSize> completion) { SyncVolumeSizeOnPrimaryStorageMsg smsg = new SyncVolumeSizeOnPrimaryStorageMsg(); smsg.setPrimaryStorageUuid(self.getPrimaryStorageUuid()); smsg.setVolumeUuid(self.getUuid()); smsg.setInstallPath(self.getInstallPath()); bus.makeTargetServiceIdByResourceUuid(smsg, PrimaryStorageConstant.SERVICE_ID, self.getPrimaryStorageUuid()); bus.send(smsg, new CloudBusCallBack(completion) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { completion.fail(reply.getError()); return; } SyncVolumeSizeOnPrimaryStorageReply r = reply.castReply(); self.setSize(r.getSize()); // the actual size = volume actual size + all snapshot size long snapshotSize = calculateSnapshotSize(); self.setActualSize(r.getActualSize() + snapshotSize); self = dbf.updateAndRefresh(self); VolumeSize size = new VolumeSize(); size.actualSize = self.getActualSize(); size.size = self.getSize(); completion.success(size); } @Transactional(readOnly = true) private long calculateSnapshotSize() { String sql = "select sum(sp.size) from VolumeSnapshotVO sp where sp.volumeUuid = :uuid"; TypedQuery<Long> q = dbf.getEntityManager().createQuery(sql, Long.class); q.setParameter("uuid", self.getUuid()); Long size = q.getSingleResult(); return size == null ? 0 : size; } }); } private void handle(APISyncVolumeSizeMsg msg) { final APISyncVolumeSizeEvent evt = new APISyncVolumeSizeEvent(msg.getId()); if (self.getStatus() != VolumeStatus.Ready) { evt.setInventory(getSelfInventory()); bus.publish(evt); return; } syncVolumeVolumeSize(new ReturnValueCompletion<VolumeSize>(msg) { @Override public void success(VolumeSize ret) { evt.setInventory(getSelfInventory()); bus.publish(evt); } @Override public void fail(ErrorCode errorCode) { evt.setErrorCode(errorCode); bus.publish(evt); } }); } private void handle(APIExpungeDataVolumeMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadId; } @Override public void run(SyncTaskChain chain) { final APIExpungeDataVolumeEvent evt = new APIExpungeDataVolumeEvent(msg.getId()); expunge(new Completion(msg, chain) { @Override public void success() { bus.publish(evt); chain.next(); } @Override public void fail(ErrorCode errorCode) { evt.setErrorCode(errorCode); bus.publish(evt); chain.next(); } }); } @Override public String getName() { return msg.getClass().getName(); } }); } protected void recoverVolume(Completion completion) { final VolumeInventory vol = getSelfInventory(); List<RecoverDataVolumeExtensionPoint> exts = pluginRgty.getExtensionList(RecoverDataVolumeExtensionPoint.class); for (RecoverDataVolumeExtensionPoint ext : exts) { ext.preRecoverDataVolume(vol); } CollectionUtils.safeForEach(exts, new ForEachFunction<RecoverDataVolumeExtensionPoint>() { @Override public void run(RecoverDataVolumeExtensionPoint ext) { ext.beforeRecoverDataVolume(vol); } }); VolumeStatus oldStatus = self.getStatus(); if (self.getInstallPath() != null) { self.setStatus(VolumeStatus.Ready); } else { self.setStatus(VolumeStatus.NotInstantiated); } self = dbf.updateAndRefresh(self); new FireVolumeCanonicalEvent().fireVolumeStatusChangedEvent(oldStatus, getSelfInventory()); CollectionUtils.safeForEach(exts, new ForEachFunction<RecoverDataVolumeExtensionPoint>() { @Override public void run(RecoverDataVolumeExtensionPoint ext) { ext.afterRecoverDataVolume(vol); } }); completion.success(); } private void handle(APIRecoverDataVolumeMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadId; } @Override public void run(SyncTaskChain chain) { final APIRecoverDataVolumeEvent evt = new APIRecoverDataVolumeEvent(msg.getId()); recoverVolume(new Completion(msg, chain) { @Override public void success() { evt.setInventory(getSelfInventory()); bus.publish(evt); chain.next(); } @Override public void fail(ErrorCode errorCode) { evt.setInventory(getSelfInventory()); evt.setErrorCode(errorCode); bus.publish(evt); chain.next(); } }); } @Override public String getName() { return msg.getClass().getName(); } }); } private void handle(APIUpdateVolumeMsg msg) { boolean update = false; if (msg.getName() != null) { self.setName(msg.getName()); update = true; } if (msg.getDescription() != null) { self.setDescription(msg.getDescription()); update = true; } if (update) { self = dbf.updateAndRefresh(self); } APIUpdateVolumeEvent evt = new APIUpdateVolumeEvent(msg.getId()); evt.setInventory(getSelfInventory()); bus.publish(evt); } @Transactional(readOnly = true) private List<VmInstanceVO> getCandidateVmForAttaching(String accountUuid) { List<String> vmUuids = acntMgr.getResourceUuidsCanAccessByAccount(accountUuid, VmInstanceVO.class); if (vmUuids != null && vmUuids.isEmpty()) { return new ArrayList<VmInstanceVO>(); } TypedQuery<VmInstanceVO> q = null; String sql; if (vmUuids == null) { // all vms if (self.getStatus() == VolumeStatus.Ready) { sql = "select vm from VmInstanceVO vm, PrimaryStorageClusterRefVO ref, VolumeVO vol where vm.state in (:vmStates) and vol.uuid = :volUuid and vm.hypervisorType in (:hvTypes) and vm.clusterUuid = ref.clusterUuid and ref.primaryStorageUuid = vol.primaryStorageUuid group by vm.uuid"; q = dbf.getEntityManager().createQuery(sql, VmInstanceVO.class); q.setParameter("volUuid", self.getUuid()); List<String> hvTypes = VolumeFormat.valueOf(self.getFormat()).getHypervisorTypesSupportingThisVolumeFormatInString(); q.setParameter("hvTypes", hvTypes); } else if (self.getStatus() == VolumeStatus.NotInstantiated) { sql = "select vm from VmInstanceVO vm where vm.state in (:vmStates) group by vm.uuid"; q = dbf.getEntityManager().createQuery(sql, VmInstanceVO.class); } else { DebugUtils.Assert(false, String.format("should not reach here, volume[uuid:%s]", self.getUuid())); } } else { if (self.getStatus() == VolumeStatus.Ready) { sql = "select vm from VmInstanceVO vm, PrimaryStorageClusterRefVO ref, VolumeVO vol where vm.uuid in (:vmUuids) and vm.state in (:vmStates) and vol.uuid = :volUuid and vm.hypervisorType in (:hvTypes) and vm.clusterUuid = ref.clusterUuid and ref.primaryStorageUuid = vol.primaryStorageUuid group by vm.uuid"; q = dbf.getEntityManager().createQuery(sql, VmInstanceVO.class); q.setParameter("volUuid", self.getUuid()); List<String> hvTypes = VolumeFormat.valueOf(self.getFormat()).getHypervisorTypesSupportingThisVolumeFormatInString(); q.setParameter("hvTypes", hvTypes); } else if (self.getStatus() == VolumeStatus.NotInstantiated) { sql = "select vm from VmInstanceVO vm where vm.uuid in (:vmUuids) and vm.state in (:vmStates) group by vm.uuid"; q = dbf.getEntityManager().createQuery(sql, VmInstanceVO.class); } else { DebugUtils.Assert(false, String.format("should not reach here, volume[uuid:%s]", self.getUuid())); } q.setParameter("vmUuids", vmUuids); } q.setParameter("vmStates", Arrays.asList(VmInstanceState.Running, VmInstanceState.Stopped)); List<VmInstanceVO> vms = q.getResultList(); if (vms.isEmpty()) { return vms; } VolumeInventory vol = getSelfInventory(); for (VolumeGetAttachableVmExtensionPoint ext : pluginRgty.getExtensionList(VolumeGetAttachableVmExtensionPoint.class)) { vms = ext.returnAttachableVms(vol, vms); } return vms; } private void handle(APIGetDataVolumeAttachableVmMsg msg) { APIGetDataVolumeAttachableVmReply reply = new APIGetDataVolumeAttachableVmReply(); reply.setInventories(VmInstanceInventory.valueOf(getCandidateVmForAttaching(msg.getSession().getAccountUuid()))); bus.reply(msg, reply); } private void handle(final APIAttachDataVolumeToVmMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadId; } @Override public void run(SyncTaskChain chain) { self.setVmInstanceUuid(msg.getVmInstanceUuid()); self = dbf.updateAndRefresh(self); AttachDataVolumeToVmMsg amsg = new AttachDataVolumeToVmMsg(); amsg.setVolume(getSelfInventory()); amsg.setVmInstanceUuid(msg.getVmInstanceUuid()); bus.makeTargetServiceIdByResourceUuid(amsg, VmInstanceConstant.SERVICE_ID, amsg.getVmInstanceUuid()); bus.send(amsg, new CloudBusCallBack(msg, chain) { @Override public void run(MessageReply reply) { final APIAttachDataVolumeToVmEvent evt = new APIAttachDataVolumeToVmEvent(msg.getId()); self = dbf.reload(self); if (reply.isSuccess()) { AttachDataVolumeToVmReply ar = reply.castReply(); self.setVmInstanceUuid(msg.getVmInstanceUuid()); self.setFormat(VolumeFormat.getVolumeFormatByMasterHypervisorType(ar.getHypervisorType()).toString()); self = dbf.updateAndRefresh(self); evt.setInventory(getSelfInventory()); } else { self.setVmInstanceUuid(null); dbf.update(self); evt.setErrorCode(reply.getError()); } bus.publish(evt); chain.next(); } }); } @Override public String getName() { return msg.getClass().getName(); } }); } private void handle(final APIDetachDataVolumeFromVmMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadId; } @Override public void run(SyncTaskChain chain) { DetachDataVolumeFromVmMsg dmsg = new DetachDataVolumeFromVmMsg(); dmsg.setVolume(getSelfInventory()); bus.makeTargetServiceIdByResourceUuid(dmsg, VmInstanceConstant.SERVICE_ID, dmsg.getVmInstanceUuid()); bus.send(dmsg, new CloudBusCallBack(msg, chain) { @Override public void run(MessageReply reply) { APIDetachDataVolumeFromVmEvent evt = new APIDetachDataVolumeFromVmEvent(msg.getId()); if (reply.isSuccess()) { self.setVmInstanceUuid(null); self.setDeviceId(null); self = dbf.updateAndRefresh(self); evt.setInventory(getSelfInventory()); } else { evt.setErrorCode(reply.getError()); } bus.publish(evt); chain.next(); } }); } @Override public String getName() { return msg.getClass().getName(); } }); } protected VolumeInventory getSelfInventory() { return VolumeInventory.valueOf(self); } private void delete(boolean forceDelete, final Completion completion) { delete(forceDelete, true, completion); } // don't put this in queue, it will eventually send the VolumeDeletionMsg that will be in queue private void delete(boolean forceDelete, boolean detachBeforeDeleting, final Completion completion) { delete(forceDelete, null, detachBeforeDeleting, completion); } private void delete(boolean forceDelete, VolumeDeletionPolicy deletionPolicy, boolean detachBeforeDeleting, final Completion completion) { final String issuer = VolumeVO.class.getSimpleName(); VolumeDeletionStruct struct = new VolumeDeletionStruct(); struct.setInventory(getSelfInventory()); struct.setDetachBeforeDeleting(detachBeforeDeleting); struct.setDeletionPolicy(deletionPolicy != null ? deletionPolicy.toString() : deletionPolicyMgr.getDeletionPolicy(self.getUuid()).toString()); final List<VolumeDeletionStruct> ctx = list(struct); FlowChain chain = FlowChainBuilder.newSimpleFlowChain(); chain.setName("delete-data-volume"); if (!forceDelete) { chain.then(new NoRollbackFlow() { @Override public void run(final FlowTrigger trigger, Map data) { casf.asyncCascade(CascadeConstant.DELETION_CHECK_CODE, issuer, ctx, new Completion(trigger) { @Override public void success() { trigger.next(); } @Override public void fail(ErrorCode errorCode) { trigger.fail(errorCode); } }); } }).then(new NoRollbackFlow() { @Override public void run(final FlowTrigger trigger, Map data) { casf.asyncCascade(CascadeConstant.DELETION_DELETE_CODE, issuer, ctx, new Completion(trigger) { @Override public void success() { trigger.next(); } @Override public void fail(ErrorCode errorCode) { trigger.fail(errorCode); } }); } }); } else { chain.then(new NoRollbackFlow() { @Override public void run(final FlowTrigger trigger, Map data) { casf.asyncCascade(CascadeConstant.DELETION_FORCE_DELETE_CODE, issuer, ctx, new Completion(trigger) { @Override public void success() { trigger.next(); } @Override public void fail(ErrorCode errorCode) { trigger.fail(errorCode); } }); } }); } chain.done(new FlowDoneHandler(completion) { @Override public void handle(Map data) { casf.asyncCascadeFull(CascadeConstant.DELETION_CLEANUP_CODE, issuer, ctx, new NopeCompletion()); completion.success(); } }).error(new FlowErrorHandler(completion) { @Override public void handle(ErrorCode errCode, Map data) { completion.fail(errCode); } }).start(); } private void handle(APIDeleteDataVolumeMsg msg) { final APIDeleteDataVolumeEvent evt = new APIDeleteDataVolumeEvent(msg.getId()); delete(msg.getDeletionMode() == DeletionMode.Enforcing, new Completion(msg) { @Override public void success() { bus.publish(evt); } @Override public void fail(ErrorCode errorCode) { evt.setErrorCode(errf.instantiateErrorCode(SysErrors.DELETE_RESOURCE_ERROR, errorCode)); bus.publish(evt); } }); } private void handle(final VolumeCreateSnapshotMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadId; } @Override public void run(final SyncTaskChain chain) { CreateVolumeSnapshotMsg cmsg = new CreateVolumeSnapshotMsg(); cmsg.setName(msg.getName()); cmsg.setDescription(msg.getDescription()); cmsg.setResourceUuid(msg.getResourceUuid()); cmsg.setAccountUuid(msg.getAccountUuid()); cmsg.setVolumeUuid(msg.getVolumeUuid()); bus.makeLocalServiceId(cmsg, VolumeSnapshotConstant.SERVICE_ID); bus.send(cmsg, new CloudBusCallBack(msg, chain) { @Override public void run(MessageReply reply) { VolumeCreateSnapshotReply r = new VolumeCreateSnapshotReply(); if (reply.isSuccess()) { CreateVolumeSnapshotReply creply = (CreateVolumeSnapshotReply) reply; r.setInventory(creply.getInventory()); } else { r.setError(reply.getError()); } bus.reply(msg, r); chain.next(); } }); } @Override public String getName() { return String.format("create-snapshot-for-volume-%s", self.getUuid()); } }); } private void handle(final APICreateVolumeSnapshotMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadId; } @Override public void run(final SyncTaskChain chain) { CreateVolumeSnapshotMsg cmsg = new CreateVolumeSnapshotMsg(); cmsg.setName(msg.getName()); cmsg.setDescription(msg.getDescription()); cmsg.setResourceUuid(msg.getResourceUuid()); cmsg.setAccountUuid(msg.getSession().getAccountUuid()); cmsg.setVolumeUuid(msg.getVolumeUuid()); bus.makeLocalServiceId(cmsg, VolumeSnapshotConstant.SERVICE_ID); bus.send(cmsg, new CloudBusCallBack(msg, chain) { @Override public void run(MessageReply reply) { APICreateVolumeSnapshotEvent evt = new APICreateVolumeSnapshotEvent(msg.getId()); if (reply.isSuccess()) { CreateVolumeSnapshotReply creply = (CreateVolumeSnapshotReply) reply; evt.setInventory(creply.getInventory()); tagMgr.createTagsFromAPICreateMessage(msg, creply.getInventory().getUuid(), VolumeSnapshotVO.class.getSimpleName()); } else { evt.setErrorCode(reply.getError()); } bus.publish(evt); chain.next(); } }); } @Override public String getName() { return String.format("create-snapshot-for-volume-%s", self.getUuid()); } }); } private void handle(APIChangeVolumeStateMsg msg) { VolumeStateEvent sevt = VolumeStateEvent.valueOf(msg.getStateEvent()); if (sevt == VolumeStateEvent.enable) { self.setState(VolumeState.Enabled); } else { self.setState(VolumeState.Disabled); } self = dbf.updateAndRefresh(self); VolumeInventory inv = VolumeInventory.valueOf(self); APIChangeVolumeStateEvent evt = new APIChangeVolumeStateEvent(msg.getId()); evt.setInventory(inv); bus.publish(evt); } }
package org.zstack.storage.volume; import org.springframework.beans.factory.annotation.Autowire; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.transaction.annotation.Transactional; import org.zstack.core.cascade.CascadeConstant; import org.zstack.core.cascade.CascadeFacade; import org.zstack.core.cloudbus.CloudBus; import org.zstack.core.cloudbus.CloudBusCallBack; import org.zstack.core.componentloader.PluginRegistry; import org.zstack.core.db.DatabaseFacade; import org.zstack.core.db.SimpleQuery; import org.zstack.core.db.SimpleQuery.Op; import org.zstack.core.errorcode.ErrorFacade; import org.zstack.core.thread.ChainTask; import org.zstack.core.thread.SyncTaskChain; import org.zstack.core.thread.ThreadFacade; import org.zstack.core.workflow.FlowChainBuilder; import org.zstack.core.workflow.ShareFlow; import org.zstack.header.core.Completion; import org.zstack.header.core.NoErrorCompletion; import org.zstack.header.core.NopeCompletion; import org.zstack.header.core.ReturnValueCompletion; import org.zstack.header.core.workflow.*; import org.zstack.header.errorcode.ErrorCode; import org.zstack.header.errorcode.OperationFailureException; import org.zstack.header.errorcode.SysErrors; import org.zstack.header.exception.CloudRuntimeException; import org.zstack.header.host.HostInventory; import org.zstack.header.host.HostVO; import org.zstack.header.image.ImageInventory; import org.zstack.header.image.ImageVO; import org.zstack.header.message.APIDeleteMessage.DeletionMode; import org.zstack.header.message.APIMessage; import org.zstack.header.message.Message; import org.zstack.header.message.MessageReply; import org.zstack.header.message.OverlayMessage; import org.zstack.header.storage.primary.*; import org.zstack.header.storage.snapshot.CreateVolumeSnapshotMsg; import org.zstack.header.storage.snapshot.CreateVolumeSnapshotReply; import org.zstack.header.storage.snapshot.VolumeSnapshotConstant; import org.zstack.header.storage.snapshot.VolumeSnapshotVO; import org.zstack.header.vm.*; import org.zstack.header.volume.*; import org.zstack.header.volume.VolumeConstant.Capability; import org.zstack.header.volume.VolumeDeletionPolicyManager.VolumeDeletionPolicy; import org.zstack.identity.AccountManager; import org.zstack.tag.TagManager; import org.zstack.utils.CollectionUtils; import org.zstack.utils.DebugUtils; import org.zstack.utils.Utils; import org.zstack.utils.function.ForEachFunction; import org.zstack.utils.logging.CLogger; import javax.persistence.TypedQuery; import java.util.*; import static org.zstack.utils.CollectionDSL.list; /** * Created with IntelliJ IDEA. * User: frank * Time: 9:20 PM * To change this template use File | Settings | File Templates. */ @Configurable(preConstruction = true, autowire = Autowire.BY_TYPE) public class VolumeBase implements Volume { private static final CLogger logger = Utils.getLogger(VolumeBase.class); protected String syncThreadId; protected VolumeVO self; @Autowired private CloudBus bus; @Autowired private DatabaseFacade dbf; @Autowired private ThreadFacade thdf; @Autowired private ErrorFacade errf; @Autowired private CascadeFacade casf; @Autowired private AccountManager acntMgr; @Autowired private TagManager tagMgr; @Autowired private PluginRegistry pluginRgty; @Autowired private VolumeDeletionPolicyManager deletionPolicyMgr; public VolumeBase(VolumeVO vo) { self = vo; syncThreadId = String.format("volume-%s", self.getUuid()); } protected void refreshVO() { self = dbf.reload(self); } @Override public void handleMessage(Message msg) { try { if (msg instanceof APIMessage) { handleApiMessage((APIMessage) msg); } else { handleLocalMessage(msg); } } catch (Exception e) { bus.logExceptionWithMessageDump(msg, e); bus.replyErrorByMessageType(msg, e); } } private void handleLocalMessage(Message msg) { if (msg instanceof VolumeDeletionMsg) { handle((VolumeDeletionMsg) msg); } else if (msg instanceof DeleteVolumeMsg) { handle((DeleteVolumeMsg) msg); } else if (msg instanceof VolumeCreateSnapshotMsg) { handle((VolumeCreateSnapshotMsg) msg); } else if (msg instanceof CreateDataVolumeTemplateFromDataVolumeMsg) { handle((CreateDataVolumeTemplateFromDataVolumeMsg) msg); } else if (msg instanceof ExpungeVolumeMsg) { handle((ExpungeVolumeMsg) msg); } else if (msg instanceof RecoverVolumeMsg) { handle((RecoverVolumeMsg) msg); } else if (msg instanceof SyncVolumeSizeMsg) { handle((SyncVolumeSizeMsg) msg); } else if (msg instanceof InstantiateVolumeMsg) { handle((InstantiateVolumeMsg) msg); } else if (msg instanceof OverlayMessage) { handle((OverlayMessage) msg); } else { bus.dealWithUnknownMessage(msg); } } private void handle(InstantiateVolumeMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return String.format("instantiate-volume-%s", self.getUuid()); } @Override public void run(SyncTaskChain chain) { doInstantiateVolume(msg, new NoErrorCompletion(msg, chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return "instantiate-volume"; } }); } private void doInstantiateVolume(InstantiateVolumeMsg msg, NoErrorCompletion completion) { InstantiateVolumeReply reply = new InstantiateVolumeReply(); FlowChain chain = FlowChainBuilder.newShareFlowChain(); chain.setName(String.format("instantiate-volume-%s", self.getUuid())); chain.then(new ShareFlow() { String installPath; String format; @Override public void setup() { if (!msg.isPrimaryStorageAllocated()) { flow(new Flow() { String __name__ = "allocate-primary-storage"; boolean success; @Override public void run(FlowTrigger trigger, Map data) { AllocatePrimaryStorageMsg amsg = new AllocatePrimaryStorageMsg(); amsg.setRequiredPrimaryStorageUuid(msg.getPrimaryStorageUuid()); amsg.setSize(self.getSize()); bus.makeTargetServiceIdByResourceUuid(amsg, PrimaryStorageConstant.SERVICE_ID, msg.getPrimaryStorageUuid()); bus.send(amsg, new CloudBusCallBack(trigger) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { trigger.fail(reply.getError()); } else { success = true; trigger.next(); } } }); } @Override public void rollback(FlowRollback trigger, Map data) { if (success) { ReturnPrimaryStorageCapacityMsg rmsg = new ReturnPrimaryStorageCapacityMsg(); rmsg.setPrimaryStorageUuid(msg.getPrimaryStorageUuid()); rmsg.setDiskSize(self.getSize()); bus.makeTargetServiceIdByResourceUuid(rmsg, PrimaryStorageConstant.SERVICE_ID, msg.getPrimaryStorageUuid()); bus.send(rmsg); } trigger.rollback(); } }); } flow(new Flow() { String __name__ = "instantiate-volume-on-primary-storage"; boolean success; @Override public void run(FlowTrigger trigger, Map data) { SimpleQuery<PrimaryStorageVO> q = dbf.createQuery(PrimaryStorageVO.class); q.select(PrimaryStorageVO_.type); q.add(PrimaryStorageVO_.uuid, Op.EQ, msg.getPrimaryStorageUuid()); String psType = q.findValue(); InstantiateDataVolumeOnCreationExtensionPoint ext = pluginRgty.getExtensionFromMap(psType, InstantiateDataVolumeOnCreationExtensionPoint.class); if (ext != null) { ext.instantiateDataVolumeOnCreation(msg, getSelfInventory(), new ReturnValueCompletion<VolumeInventory>(trigger) { @Override public void success(VolumeInventory ret) { success = true; installPath = ret.getInstallPath(); format = ret.getFormat(); trigger.next(); } @Override public void fail(ErrorCode errorCode) { trigger.fail(errorCode); } }); } else { if (msg instanceof InstantiateRootVolumeMsg) { instantiateRootVolume((InstantiateRootVolumeMsg) msg, trigger); } else { instantiateDataVolume(msg, trigger); } } } private void instantiateRootVolume(InstantiateRootVolumeMsg msg, FlowTrigger trigger) { InstantiateRootVolumeFromTemplateOnPrimaryStorageMsg imsg = new InstantiateRootVolumeFromTemplateOnPrimaryStorageMsg(); imsg.setPrimaryStorageUuid(msg.getPrimaryStorageUuid()); imsg.setVolume(getSelfInventory()); if (msg.getHostUuid() != null) { imsg.setDestHost(HostInventory.valueOf(dbf.findByUuid(msg.getHostUuid(), HostVO.class))); } imsg.setTemplateSpec(msg.getTemplateSpec()); bus.makeTargetServiceIdByResourceUuid(imsg, PrimaryStorageConstant.SERVICE_ID, msg.getPrimaryStorageUuid()); bus.send(imsg, new CloudBusCallBack(trigger) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { trigger.fail(reply.getError()); return; } success = true; InstantiateVolumeOnPrimaryStorageReply ir = reply.castReply(); installPath = ir.getVolume().getInstallPath(); format = ir.getVolume().getFormat(); trigger.next(); } }); } private void instantiateDataVolume(InstantiateVolumeMsg msg, FlowTrigger trigger) { InstantiateVolumeOnPrimaryStorageMsg imsg = new InstantiateVolumeOnPrimaryStorageMsg(); imsg.setPrimaryStorageUuid(msg.getPrimaryStorageUuid()); imsg.setVolume(getSelfInventory()); if (msg.getHostUuid() != null) { imsg.setDestHost(HostInventory.valueOf(dbf.findByUuid(msg.getHostUuid(), HostVO.class))); } bus.makeTargetServiceIdByResourceUuid(imsg, PrimaryStorageConstant.SERVICE_ID, msg.getPrimaryStorageUuid()); bus.send(imsg, new CloudBusCallBack(trigger) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { trigger.fail(reply.getError()); return; } success = true; InstantiateVolumeOnPrimaryStorageReply ir = reply.castReply(); installPath = ir.getVolume().getInstallPath(); format = ir.getVolume().getFormat(); trigger.next(); } }); } @Override public void rollback(FlowRollback trigger, Map data) { if (success) { DeleteVolumeOnPrimaryStorageMsg dmsg = new DeleteVolumeOnPrimaryStorageMsg(); dmsg.setUuid(msg.getPrimaryStorageUuid()); dmsg.setVolume(getSelfInventory()); bus.makeTargetServiceIdByResourceUuid(dmsg, PrimaryStorageConstant.SERVICE_ID, msg.getPrimaryStorageUuid()); bus.send(dmsg); } trigger.rollback(); } }); done(new FlowDoneHandler(msg, completion) { @Override public void handle(Map data) { VolumeStatus oldStatus = self.getStatus(); self.setPrimaryStorageUuid(msg.getPrimaryStorageUuid()); self.setInstallPath(installPath); DebugUtils.Assert(format != null, "format cannot be null"); self.setFormat(format); self.setStatus(VolumeStatus.Ready); self = dbf.updateAndRefresh(self); VolumeInventory vol = getSelfInventory(); new FireVolumeCanonicalEvent().fireVolumeStatusChangedEvent(oldStatus, vol); reply.setVolume(vol); bus.reply(msg, reply); } }); error(new FlowErrorHandler(msg, completion) { @Override public void handle(ErrorCode errCode, Map data) { reply.setError(errCode); bus.reply(msg, reply); } }); Finally(new FlowFinallyHandler(msg, completion) { @Override public void Finally() { completion.done(); } }); } }).start(); } private void handle(OverlayMessage msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadId; } @Override public void run(SyncTaskChain chain) { doOverlayMessage(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return "overlay-message"; } }); } private void doOverlayMessage(OverlayMessage msg, NoErrorCompletion noErrorCompletion) { bus.send(msg.getMessage(), new CloudBusCallBack(msg, noErrorCompletion) { @Override public void run(MessageReply reply) { bus.reply(msg, reply); noErrorCompletion.done(); } }); } private void handle(final SyncVolumeSizeMsg msg) { final SyncVolumeSizeReply reply = new SyncVolumeSizeReply(); syncVolumeVolumeSize(new ReturnValueCompletion<VolumeSize>(msg) { @Override public void success(VolumeSize ret) { reply.setActualSize(ret.actualSize); reply.setSize(ret.size); bus.reply(msg, reply); } @Override public void fail(ErrorCode errorCode) { reply.setError(errorCode); bus.reply(msg, reply); } }); } private void handle(final RecoverVolumeMsg msg) { final RecoverVolumeReply reply = new RecoverVolumeReply(); thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadId; } @Override public void run(SyncTaskChain chain) { recoverVolume(new Completion(chain, msg) { @Override public void success() { bus.reply(msg, reply); chain.next(); } @Override public void fail(ErrorCode errorCode) { reply.setError(errorCode); bus.reply(msg, reply); chain.next(); } }); } @Override public String getName() { return RecoverVolumeMsg.class.getName(); } }); } private void expunge(final Completion completion) { if (self.getStatus() != VolumeStatus.Deleted) { throw new OperationFailureException(errf.stringToOperationError( String.format("the volume[uuid:%s, name:%s] is not deleted yet, can't expunge it", self.getUuid(), self.getName()) )); } final VolumeInventory inv = getSelfInventory(); CollectionUtils.safeForEach(pluginRgty.getExtensionList(VolumeBeforeExpungeExtensionPoint.class), new ForEachFunction<VolumeBeforeExpungeExtensionPoint>() { @Override public void run(VolumeBeforeExpungeExtensionPoint arg) { arg.volumeBeforeExpunge(inv); } }); if (self.getPrimaryStorageUuid() != null) { DeleteVolumeOnPrimaryStorageMsg dmsg = new DeleteVolumeOnPrimaryStorageMsg(); dmsg.setVolume(getSelfInventory()); dmsg.setUuid(self.getPrimaryStorageUuid()); bus.makeTargetServiceIdByResourceUuid(dmsg, PrimaryStorageConstant.SERVICE_ID, self.getPrimaryStorageUuid()); bus.send(dmsg, new CloudBusCallBack(completion) { @Override public void run(MessageReply r) { if (!r.isSuccess()) { completion.fail(r.getError()); } else { ReturnPrimaryStorageCapacityMsg msg = new ReturnPrimaryStorageCapacityMsg(); msg.setPrimaryStorageUuid(self.getPrimaryStorageUuid()); msg.setDiskSize(self.getSize()); bus.makeTargetServiceIdByResourceUuid(msg, PrimaryStorageConstant.SERVICE_ID, self.getPrimaryStorageUuid()); bus.send(msg); CollectionUtils.safeForEach(pluginRgty.getExtensionList(VolumeAfterExpungeExtensionPoint.class), new ForEachFunction<VolumeAfterExpungeExtensionPoint>() { @Override public void run(VolumeAfterExpungeExtensionPoint arg) { arg.volumeAfterExpunge(inv); } }); dbf.remove(self); completion.success(); } } }); } else { CollectionUtils.safeForEach(pluginRgty.getExtensionList(VolumeAfterExpungeExtensionPoint.class), new ForEachFunction<VolumeAfterExpungeExtensionPoint>() { @Override public void run(VolumeAfterExpungeExtensionPoint arg) { arg.volumeAfterExpunge(inv); } }); dbf.remove(self); completion.success(); } } private void handle(final ExpungeVolumeMsg msg) { final ExpungeVolumeReply reply = new ExpungeVolumeReply(); thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadId; } @Override public void run(SyncTaskChain chain) { expunge(new Completion(msg, chain) { @Override public void success() { bus.reply(msg, reply); chain.next(); } @Override public void fail(ErrorCode errorCode) { reply.setError(errorCode); bus.reply(msg, reply); chain.next(); } }); } @Override public String getName() { return ExpungeVolumeMsg.class.getName(); } }); } private void handle(final CreateDataVolumeTemplateFromDataVolumeMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadId; } @Override public void run(SyncTaskChain chain) { doCreateDataVolumeTemplateFromDataVolumeMsg(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return CreateDataVolumeTemplateFromDataVolumeMsg.class.getName(); } }); } private void doCreateDataVolumeTemplateFromDataVolumeMsg(CreateDataVolumeTemplateFromDataVolumeMsg msg, NoErrorCompletion noErrorCompletion) { final CreateTemplateFromVolumeOnPrimaryStorageMsg cmsg = new CreateTemplateFromVolumeOnPrimaryStorageMsg(); cmsg.setBackupStorageUuid(msg.getBackupStorageUuid()); cmsg.setImageInventory(ImageInventory.valueOf(dbf.findByUuid(msg.getImageUuid(), ImageVO.class))); cmsg.setVolumeInventory(getSelfInventory()); bus.makeTargetServiceIdByResourceUuid(cmsg, PrimaryStorageConstant.SERVICE_ID, self.getPrimaryStorageUuid()); bus.send(cmsg, new CloudBusCallBack(msg, noErrorCompletion) { @Override public void run(MessageReply r) { CreateDataVolumeTemplateFromDataVolumeReply reply = new CreateDataVolumeTemplateFromDataVolumeReply(); if (!r.isSuccess()) { reply.setError(r.getError()); } else { CreateTemplateFromVolumeOnPrimaryStorageReply creply = r.castReply(); String backupStorageInstallPath = creply.getTemplateBackupStorageInstallPath(); reply.setFormat(creply.getFormat()); reply.setInstallPath(backupStorageInstallPath); reply.setMd5sum(null); reply.setBackupStorageUuid(msg.getBackupStorageUuid()); } bus.reply(msg, reply); noErrorCompletion.done(); } }); } private void handle(final DeleteVolumeMsg msg) { final DeleteVolumeReply reply = new DeleteVolumeReply(); delete(true, VolumeDeletionPolicy.valueOf(msg.getDeletionPolicy()), msg.isDetachBeforeDeleting(), new Completion(msg) { @Override public void success() { logger.debug(String.format("deleted data volume[uuid: %s]", msg.getUuid())); bus.reply(msg, reply); } @Override public void fail(ErrorCode errorCode) { reply.setError(errorCode); bus.reply(msg, reply); } }); } private void deleteVolume(final VolumeDeletionMsg msg, final NoErrorCompletion completion) { final VolumeDeletionReply reply = new VolumeDeletionReply(); for (VolumeDeletionExtensionPoint extp : pluginRgty.getExtensionList(VolumeDeletionExtensionPoint.class)) { extp.preDeleteVolume(getSelfInventory()); } CollectionUtils.safeForEach(pluginRgty.getExtensionList(VolumeDeletionExtensionPoint.class), new ForEachFunction<VolumeDeletionExtensionPoint>() { @Override public void run(VolumeDeletionExtensionPoint arg) { arg.beforeDeleteVolume(getSelfInventory()); } }); FlowChain chain = FlowChainBuilder.newShareFlowChain(); chain.setName(String.format("delete-volume-%s", self.getUuid())); // for NotInstantiated Volume, no flow to execute chain.allowEmptyFlow(); chain.then(new ShareFlow() { VolumeDeletionPolicy deletionPolicy; { if (msg.getDeletionPolicy() == null) { deletionPolicy = deletionPolicyMgr.getDeletionPolicy(self.getUuid()); } else { deletionPolicy = VolumeDeletionPolicy.valueOf(msg.getDeletionPolicy()); } } @Override public void setup() { if (self.getVmInstanceUuid() != null && self.getType() == VolumeType.Data && msg.isDetachBeforeDeleting()) { flow(new NoRollbackFlow() { String __name__ = "detach-volume-from-vm"; public void run(final FlowTrigger trigger, Map data) { DetachDataVolumeFromVmMsg dmsg = new DetachDataVolumeFromVmMsg(); dmsg.setVolume(getSelfInventory()); String vmUuid; if (dmsg.getVmInstanceUuid() == null) { vmUuid = getSelfInventory().getVmInstanceUuid(); } else { vmUuid = dmsg.getVmInstanceUuid(); } bus.makeTargetServiceIdByResourceUuid(dmsg, VmInstanceConstant.SERVICE_ID, vmUuid); bus.send(dmsg, new CloudBusCallBack(trigger) { @Override public void run(MessageReply reply) { self.setVmInstanceUuid(null); self = dbf.updateAndRefresh(self); trigger.next(); } }); } }); } if (deletionPolicy == VolumeDeletionPolicy.Direct) { flow(new NoRollbackFlow() { String __name__ = "delete-data-volume-from-primary-storage"; @Override public void run(final FlowTrigger trigger, Map data) { if (self.getStatus() == VolumeStatus.Ready) { DeleteVolumeOnPrimaryStorageMsg dmsg = new DeleteVolumeOnPrimaryStorageMsg(); dmsg.setVolume(getSelfInventory()); dmsg.setUuid(self.getPrimaryStorageUuid()); bus.makeTargetServiceIdByResourceUuid(dmsg, PrimaryStorageConstant.SERVICE_ID, self.getPrimaryStorageUuid()); logger.debug(String.format("Asking primary storage[uuid:%s] to remove data volume[uuid:%s]", self.getPrimaryStorageUuid(), self.getUuid())); bus.send(dmsg, new CloudBusCallBack(trigger) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { logger.warn(String.format("failed to delete volume[uuid:%s, name:%s], %s", self.getUuid(), self.getName(), reply.getError())); } trigger.next(); } }); } else { trigger.next(); } } }); } if (self.getPrimaryStorageUuid() != null && deletionPolicy == VolumeDeletionPolicy.Direct) { flow(new NoRollbackFlow() { String __name__ = "return-primary-storage-capacity"; @Override public void run(FlowTrigger trigger, Map data) { ReturnPrimaryStorageCapacityMsg rmsg = new ReturnPrimaryStorageCapacityMsg(); rmsg.setPrimaryStorageUuid(self.getPrimaryStorageUuid()); rmsg.setDiskSize(self.getSize()); bus.makeTargetServiceIdByResourceUuid(rmsg, PrimaryStorageConstant.SERVICE_ID, self.getPrimaryStorageUuid()); bus.send(rmsg); trigger.next(); } }); } done(new FlowDoneHandler(msg) { @Override public void handle(Map data) { VolumeStatus oldStatus = self.getStatus(); if (deletionPolicy == VolumeDeletionPolicy.Direct) { self.setStatus(VolumeStatus.Deleted); self = dbf.updateAndRefresh(self); new FireVolumeCanonicalEvent().fireVolumeStatusChangedEvent(oldStatus, getSelfInventory()); dbf.remove(self); } else if (deletionPolicy == VolumeDeletionPolicy.Delay) { self.setStatus(VolumeStatus.Deleted); self = dbf.updateAndRefresh(self); new FireVolumeCanonicalEvent().fireVolumeStatusChangedEvent(oldStatus, getSelfInventory()); } else if (deletionPolicy == VolumeDeletionPolicy.Never) { self.setStatus(VolumeStatus.Deleted); self = dbf.updateAndRefresh(self); new FireVolumeCanonicalEvent().fireVolumeStatusChangedEvent(oldStatus, getSelfInventory()); } else { throw new CloudRuntimeException(String.format("Invalid deletionPolicy:%s", deletionPolicy)); } CollectionUtils.safeForEach(pluginRgty.getExtensionList(VolumeDeletionExtensionPoint.class), new ForEachFunction<VolumeDeletionExtensionPoint>() { @Override public void run(VolumeDeletionExtensionPoint arg) { arg.afterDeleteVolume(getSelfInventory()); } }); bus.reply(msg, reply); } }); error(new FlowErrorHandler(msg) { @Override public void handle(final ErrorCode errCode, Map data) { CollectionUtils.safeForEach(pluginRgty.getExtensionList(VolumeDeletionExtensionPoint.class), new ForEachFunction<VolumeDeletionExtensionPoint>() { @Override public void run(VolumeDeletionExtensionPoint arg) { arg.failedToDeleteVolume(getSelfInventory(), errCode); } }); reply.setError(errCode); bus.reply(msg, reply); } }); Finally(new FlowFinallyHandler() { @Override public void Finally() { completion.done(); } }); } }).start(); } private void handle(final VolumeDeletionMsg msg) { thdf.chainSubmit(new ChainTask() { @Override public String getSyncSignature() { return syncThreadId; } @Override public void run(final SyncTaskChain chain) { self = dbf.reload(self); if (self.getStatus() == VolumeStatus.Deleted) { // the volume has been deleted // we run into this case because the cascading framework // will send duplicate messages when deleting a vm as the cascading // framework has no knowledge about if the volume has been deleted VolumeDeletionReply reply = new VolumeDeletionReply(); bus.reply(msg, reply); chain.next(); return; } deleteVolume(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("delete-volume-%s", self.getUuid()); } }); } private void handleApiMessage(APIMessage msg) { if (msg instanceof APIChangeVolumeStateMsg) { handle((APIChangeVolumeStateMsg) msg); } else if (msg instanceof APICreateVolumeSnapshotMsg) { handle((APICreateVolumeSnapshotMsg) msg); } else if (msg instanceof APIDeleteDataVolumeMsg) { handle((APIDeleteDataVolumeMsg) msg); } else if (msg instanceof APIDetachDataVolumeFromVmMsg) { handle((APIDetachDataVolumeFromVmMsg) msg); } else if (msg instanceof APIAttachDataVolumeToVmMsg) { handle((APIAttachDataVolumeToVmMsg) msg); } else if (msg instanceof APIGetDataVolumeAttachableVmMsg) { handle((APIGetDataVolumeAttachableVmMsg) msg); } else if (msg instanceof APIUpdateVolumeMsg) { handle((APIUpdateVolumeMsg) msg); } else if (msg instanceof APIRecoverDataVolumeMsg) { handle((APIRecoverDataVolumeMsg) msg); } else if (msg instanceof APIExpungeDataVolumeMsg) { handle((APIExpungeDataVolumeMsg) msg); } else if (msg instanceof APISyncVolumeSizeMsg) { handle((APISyncVolumeSizeMsg) msg); } else if (msg instanceof APIGetVolumeCapabilitiesMsg) { handle((APIGetVolumeCapabilitiesMsg) msg); } else { bus.dealWithUnknownMessage(msg); } } private void handle(APIGetVolumeCapabilitiesMsg msg) { APIGetVolumeCapabilitiesReply reply = new APIGetVolumeCapabilitiesReply(); Map<String, Object> ret = new HashMap<String, Object>(); if (VolumeStatus.Ready == self.getStatus()) { getPrimaryStorageCapacities(ret); } reply.setCapabilities(ret); bus.reply(msg, reply); } private void getPrimaryStorageCapacities(Map<String, Object> ret) { SimpleQuery<PrimaryStorageVO> q = dbf.createQuery(PrimaryStorageVO.class); q.select(PrimaryStorageVO_.type); q.add(PrimaryStorageVO_.uuid, Op.EQ, self.getPrimaryStorageUuid()); String type = q.findValue(); PrimaryStorageType psType = PrimaryStorageType.valueOf(type); ret.put(Capability.MigrationInCurrentPrimaryStorage.toString(), psType.isSupportVolumeMigrationInCurrentPrimaryStorage()); ret.put(Capability.MigrationToOtherPrimaryStorage.toString(), psType.isSupportVolumeMigrationToOtherPrimaryStorage()); } private void syncVolumeVolumeSize(final ReturnValueCompletion<VolumeSize> completion) { SyncVolumeSizeOnPrimaryStorageMsg smsg = new SyncVolumeSizeOnPrimaryStorageMsg(); smsg.setPrimaryStorageUuid(self.getPrimaryStorageUuid()); smsg.setVolumeUuid(self.getUuid()); smsg.setInstallPath(self.getInstallPath()); bus.makeTargetServiceIdByResourceUuid(smsg, PrimaryStorageConstant.SERVICE_ID, self.getPrimaryStorageUuid()); bus.send(smsg, new CloudBusCallBack(completion) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { completion.fail(reply.getError()); return; } SyncVolumeSizeOnPrimaryStorageReply r = reply.castReply(); self.setSize(r.getSize()); // the actual size = volume actual size + all snapshot size long snapshotSize = calculateSnapshotSize(); self.setActualSize(r.getActualSize() + snapshotSize); self = dbf.updateAndRefresh(self); VolumeSize size = new VolumeSize(); size.actualSize = self.getActualSize(); size.size = self.getSize(); completion.success(size); } @Transactional(readOnly = true) private long calculateSnapshotSize() { String sql = "select sum(sp.size) from VolumeSnapshotVO sp where sp.volumeUuid = :uuid"; TypedQuery<Long> q = dbf.getEntityManager().createQuery(sql, Long.class); q.setParameter("uuid", self.getUuid()); Long size = q.getSingleResult(); return size == null ? 0 : size; } }); } private void handle(APISyncVolumeSizeMsg msg) { final APISyncVolumeSizeEvent evt = new APISyncVolumeSizeEvent(msg.getId()); if (self.getStatus() != VolumeStatus.Ready) { evt.setInventory(getSelfInventory()); bus.publish(evt); return; } syncVolumeVolumeSize(new ReturnValueCompletion<VolumeSize>(msg) { @Override public void success(VolumeSize ret) { evt.setInventory(getSelfInventory()); bus.publish(evt); } @Override public void fail(ErrorCode errorCode) { evt.setErrorCode(errorCode); bus.publish(evt); } }); } private void handle(APIExpungeDataVolumeMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadId; } @Override public void run(SyncTaskChain chain) { final APIExpungeDataVolumeEvent evt = new APIExpungeDataVolumeEvent(msg.getId()); expunge(new Completion(msg, chain) { @Override public void success() { bus.publish(evt); chain.next(); } @Override public void fail(ErrorCode errorCode) { evt.setErrorCode(errorCode); bus.publish(evt); chain.next(); } }); } @Override public String getName() { return msg.getClass().getName(); } }); } protected void recoverVolume(Completion completion) { final VolumeInventory vol = getSelfInventory(); List<RecoverDataVolumeExtensionPoint> exts = pluginRgty.getExtensionList(RecoverDataVolumeExtensionPoint.class); for (RecoverDataVolumeExtensionPoint ext : exts) { ext.preRecoverDataVolume(vol); } CollectionUtils.safeForEach(exts, new ForEachFunction<RecoverDataVolumeExtensionPoint>() { @Override public void run(RecoverDataVolumeExtensionPoint ext) { ext.beforeRecoverDataVolume(vol); } }); VolumeStatus oldStatus = self.getStatus(); if (self.getInstallPath() != null) { self.setStatus(VolumeStatus.Ready); } else { self.setStatus(VolumeStatus.NotInstantiated); } self = dbf.updateAndRefresh(self); new FireVolumeCanonicalEvent().fireVolumeStatusChangedEvent(oldStatus, getSelfInventory()); CollectionUtils.safeForEach(exts, new ForEachFunction<RecoverDataVolumeExtensionPoint>() { @Override public void run(RecoverDataVolumeExtensionPoint ext) { ext.afterRecoverDataVolume(vol); } }); completion.success(); } private void handle(APIRecoverDataVolumeMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadId; } @Override public void run(SyncTaskChain chain) { final APIRecoverDataVolumeEvent evt = new APIRecoverDataVolumeEvent(msg.getId()); recoverVolume(new Completion(msg, chain) { @Override public void success() { evt.setInventory(getSelfInventory()); bus.publish(evt); chain.next(); } @Override public void fail(ErrorCode errorCode) { evt.setInventory(getSelfInventory()); evt.setErrorCode(errorCode); bus.publish(evt); chain.next(); } }); } @Override public String getName() { return msg.getClass().getName(); } }); } private void handle(APIUpdateVolumeMsg msg) { boolean update = false; if (msg.getName() != null) { self.setName(msg.getName()); update = true; } if (msg.getDescription() != null) { self.setDescription(msg.getDescription()); update = true; } if (update) { self = dbf.updateAndRefresh(self); } APIUpdateVolumeEvent evt = new APIUpdateVolumeEvent(msg.getId()); evt.setInventory(getSelfInventory()); bus.publish(evt); } @Transactional(readOnly = true) private List<VmInstanceVO> getCandidateVmForAttaching(String accountUuid) { List<String> vmUuids = acntMgr.getResourceUuidsCanAccessByAccount(accountUuid, VmInstanceVO.class); if (vmUuids != null && vmUuids.isEmpty()) { return new ArrayList<VmInstanceVO>(); } TypedQuery<VmInstanceVO> q = null; String sql; if (vmUuids == null) { // all vms if (self.getStatus() == VolumeStatus.Ready) { sql = "select vm from VmInstanceVO vm, PrimaryStorageClusterRefVO ref, VolumeVO vol where vm.state in (:vmStates) and vol.uuid = :volUuid and vm.hypervisorType in (:hvTypes) and vm.clusterUuid = ref.clusterUuid and ref.primaryStorageUuid = vol.primaryStorageUuid group by vm.uuid"; q = dbf.getEntityManager().createQuery(sql, VmInstanceVO.class); q.setParameter("volUuid", self.getUuid()); List<String> hvTypes = VolumeFormat.valueOf(self.getFormat()).getHypervisorTypesSupportingThisVolumeFormatInString(); q.setParameter("hvTypes", hvTypes); } else if (self.getStatus() == VolumeStatus.NotInstantiated) { sql = "select vm from VmInstanceVO vm where vm.state in (:vmStates) group by vm.uuid"; q = dbf.getEntityManager().createQuery(sql, VmInstanceVO.class); } else { DebugUtils.Assert(false, String.format("should not reach here, volume[uuid:%s]", self.getUuid())); } } else { if (self.getStatus() == VolumeStatus.Ready) { sql = "select vm from VmInstanceVO vm, PrimaryStorageClusterRefVO ref, VolumeVO vol where vm.uuid in (:vmUuids) and vm.state in (:vmStates) and vol.uuid = :volUuid and vm.hypervisorType in (:hvTypes) and vm.clusterUuid = ref.clusterUuid and ref.primaryStorageUuid = vol.primaryStorageUuid group by vm.uuid"; q = dbf.getEntityManager().createQuery(sql, VmInstanceVO.class); q.setParameter("volUuid", self.getUuid()); List<String> hvTypes = VolumeFormat.valueOf(self.getFormat()).getHypervisorTypesSupportingThisVolumeFormatInString(); q.setParameter("hvTypes", hvTypes); } else if (self.getStatus() == VolumeStatus.NotInstantiated) { sql = "select vm from VmInstanceVO vm where vm.uuid in (:vmUuids) and vm.state in (:vmStates) group by vm.uuid"; q = dbf.getEntityManager().createQuery(sql, VmInstanceVO.class); } else { DebugUtils.Assert(false, String.format("should not reach here, volume[uuid:%s]", self.getUuid())); } q.setParameter("vmUuids", vmUuids); } q.setParameter("vmStates", Arrays.asList(VmInstanceState.Running, VmInstanceState.Stopped)); List<VmInstanceVO> vms = q.getResultList(); if (vms.isEmpty()) { return vms; } VolumeInventory vol = getSelfInventory(); for (VolumeGetAttachableVmExtensionPoint ext : pluginRgty.getExtensionList(VolumeGetAttachableVmExtensionPoint.class)) { vms = ext.returnAttachableVms(vol, vms); } return vms; } private void handle(APIGetDataVolumeAttachableVmMsg msg) { APIGetDataVolumeAttachableVmReply reply = new APIGetDataVolumeAttachableVmReply(); reply.setInventories(VmInstanceInventory.valueOf(getCandidateVmForAttaching(msg.getSession().getAccountUuid()))); bus.reply(msg, reply); } private void handle(final APIAttachDataVolumeToVmMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadId; } @Override public void run(SyncTaskChain chain) { self.setVmInstanceUuid(msg.getVmInstanceUuid()); self = dbf.updateAndRefresh(self); AttachDataVolumeToVmMsg amsg = new AttachDataVolumeToVmMsg(); amsg.setVolume(getSelfInventory()); amsg.setVmInstanceUuid(msg.getVmInstanceUuid()); bus.makeTargetServiceIdByResourceUuid(amsg, VmInstanceConstant.SERVICE_ID, amsg.getVmInstanceUuid()); bus.send(amsg, new CloudBusCallBack(msg, chain) { @Override public void run(MessageReply reply) { final APIAttachDataVolumeToVmEvent evt = new APIAttachDataVolumeToVmEvent(msg.getId()); self = dbf.reload(self); if (reply.isSuccess()) { AttachDataVolumeToVmReply ar = reply.castReply(); self.setVmInstanceUuid(msg.getVmInstanceUuid()); self.setFormat(VolumeFormat.getVolumeFormatByMasterHypervisorType(ar.getHypervisorType()).toString()); self = dbf.updateAndRefresh(self); evt.setInventory(getSelfInventory()); } else { self.setVmInstanceUuid(null); dbf.update(self); evt.setErrorCode(reply.getError()); } if (self.isShareable()) { self.setVmInstanceUuid(null); dbf.update(self); } bus.publish(evt); chain.next(); } }); } @Override public String getName() { return msg.getClass().getName(); } }); } private void handle(final APIDetachDataVolumeFromVmMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadId; } @Override public void run(SyncTaskChain chain) { DetachDataVolumeFromVmMsg dmsg = new DetachDataVolumeFromVmMsg(); dmsg.setVolume(getSelfInventory()); String vmUuid; if (msg.getVmUuid() != null) { vmUuid = msg.getVmUuid(); } else { vmUuid = getSelfInventory().getVmInstanceUuid(); } dmsg.setVmInstanceUuid(vmUuid); bus.makeTargetServiceIdByResourceUuid(dmsg, VmInstanceConstant.SERVICE_ID, vmUuid); bus.send(dmsg, new CloudBusCallBack(msg, chain) { @Override public void run(MessageReply reply) { APIDetachDataVolumeFromVmEvent evt = new APIDetachDataVolumeFromVmEvent(msg.getId()); if (reply.isSuccess()) { self.setVmInstanceUuid(null); self.setDeviceId(null); self = dbf.updateAndRefresh(self); evt.setInventory(getSelfInventory()); } else { evt.setErrorCode(reply.getError()); } bus.publish(evt); chain.next(); } }); } @Override public String getName() { return msg.getClass().getName(); } }); } protected VolumeInventory getSelfInventory() { return VolumeInventory.valueOf(self); } private void delete(boolean forceDelete, final Completion completion) { delete(forceDelete, true, completion); } // don't put this in queue, it will eventually send the VolumeDeletionMsg that will be in queue private void delete(boolean forceDelete, boolean detachBeforeDeleting, final Completion completion) { delete(forceDelete, null, detachBeforeDeleting, completion); } private void delete(boolean forceDelete, VolumeDeletionPolicy deletionPolicy, boolean detachBeforeDeleting, final Completion completion) { final String issuer = VolumeVO.class.getSimpleName(); VolumeDeletionStruct struct = new VolumeDeletionStruct(); struct.setInventory(getSelfInventory()); struct.setDetachBeforeDeleting(detachBeforeDeleting); struct.setDeletionPolicy(deletionPolicy != null ? deletionPolicy.toString() : deletionPolicyMgr.getDeletionPolicy(self.getUuid()).toString()); final List<VolumeDeletionStruct> ctx = list(struct); FlowChain chain = FlowChainBuilder.newSimpleFlowChain(); chain.setName("delete-data-volume"); if (!forceDelete) { chain.then(new NoRollbackFlow() { @Override public void run(final FlowTrigger trigger, Map data) { casf.asyncCascade(CascadeConstant.DELETION_CHECK_CODE, issuer, ctx, new Completion(trigger) { @Override public void success() { trigger.next(); } @Override public void fail(ErrorCode errorCode) { trigger.fail(errorCode); } }); } }).then(new NoRollbackFlow() { @Override public void run(final FlowTrigger trigger, Map data) { casf.asyncCascade(CascadeConstant.DELETION_DELETE_CODE, issuer, ctx, new Completion(trigger) { @Override public void success() { trigger.next(); } @Override public void fail(ErrorCode errorCode) { trigger.fail(errorCode); } }); } }); } else { chain.then(new NoRollbackFlow() { @Override public void run(final FlowTrigger trigger, Map data) { casf.asyncCascade(CascadeConstant.DELETION_FORCE_DELETE_CODE, issuer, ctx, new Completion(trigger) { @Override public void success() { trigger.next(); } @Override public void fail(ErrorCode errorCode) { trigger.fail(errorCode); } }); } }); } chain.done(new FlowDoneHandler(completion) { @Override public void handle(Map data) { casf.asyncCascadeFull(CascadeConstant.DELETION_CLEANUP_CODE, issuer, ctx, new NopeCompletion()); completion.success(); } }).error(new FlowErrorHandler(completion) { @Override public void handle(ErrorCode errCode, Map data) { completion.fail(errCode); } }).start(); } private void handle(APIDeleteDataVolumeMsg msg) { final APIDeleteDataVolumeEvent evt = new APIDeleteDataVolumeEvent(msg.getId()); delete(msg.getDeletionMode() == DeletionMode.Enforcing, new Completion(msg) { @Override public void success() { bus.publish(evt); } @Override public void fail(ErrorCode errorCode) { evt.setErrorCode(errf.instantiateErrorCode(SysErrors.DELETE_RESOURCE_ERROR, errorCode)); bus.publish(evt); } }); } private void handle(final VolumeCreateSnapshotMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadId; } @Override public void run(final SyncTaskChain chain) { CreateVolumeSnapshotMsg cmsg = new CreateVolumeSnapshotMsg(); cmsg.setName(msg.getName()); cmsg.setDescription(msg.getDescription()); cmsg.setResourceUuid(msg.getResourceUuid()); cmsg.setAccountUuid(msg.getAccountUuid()); cmsg.setVolumeUuid(msg.getVolumeUuid()); bus.makeLocalServiceId(cmsg, VolumeSnapshotConstant.SERVICE_ID); bus.send(cmsg, new CloudBusCallBack(msg, chain) { @Override public void run(MessageReply reply) { VolumeCreateSnapshotReply r = new VolumeCreateSnapshotReply(); if (reply.isSuccess()) { CreateVolumeSnapshotReply creply = (CreateVolumeSnapshotReply) reply; r.setInventory(creply.getInventory()); } else { r.setError(reply.getError()); } bus.reply(msg, r); chain.next(); } }); } @Override public String getName() { return String.format("create-snapshot-for-volume-%s", self.getUuid()); } }); } private void handle(final APICreateVolumeSnapshotMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadId; } @Override public void run(final SyncTaskChain chain) { CreateVolumeSnapshotMsg cmsg = new CreateVolumeSnapshotMsg(); cmsg.setName(msg.getName()); cmsg.setDescription(msg.getDescription()); cmsg.setResourceUuid(msg.getResourceUuid()); cmsg.setAccountUuid(msg.getSession().getAccountUuid()); cmsg.setVolumeUuid(msg.getVolumeUuid()); bus.makeLocalServiceId(cmsg, VolumeSnapshotConstant.SERVICE_ID); bus.send(cmsg, new CloudBusCallBack(msg, chain) { @Override public void run(MessageReply reply) { APICreateVolumeSnapshotEvent evt = new APICreateVolumeSnapshotEvent(msg.getId()); if (reply.isSuccess()) { CreateVolumeSnapshotReply creply = (CreateVolumeSnapshotReply) reply; evt.setInventory(creply.getInventory()); tagMgr.createTagsFromAPICreateMessage(msg, creply.getInventory().getUuid(), VolumeSnapshotVO.class.getSimpleName()); } else { evt.setErrorCode(reply.getError()); } bus.publish(evt); chain.next(); } }); } @Override public String getName() { return String.format("create-snapshot-for-volume-%s", self.getUuid()); } }); } private void handle(APIChangeVolumeStateMsg msg) { VolumeStateEvent sevt = VolumeStateEvent.valueOf(msg.getStateEvent()); if (sevt == VolumeStateEvent.enable) { self.setState(VolumeState.Enabled); } else { self.setState(VolumeState.Disabled); } self = dbf.updateAndRefresh(self); VolumeInventory inv = VolumeInventory.valueOf(self); APIChangeVolumeStateEvent evt = new APIChangeVolumeStateEvent(msg.getId()); evt.setInventory(inv); bus.publish(evt); } class VolumeSize { long size; long actualSize; } }
package org.bouncycastle.cms.test; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.security.Key; import java.security.KeyFactory; import java.security.KeyPair; import java.security.cert.X509Certificate; import java.security.spec.PKCS8EncodedKeySpec; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import javax.crypto.SecretKey; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.DEROutputStream; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.cms.CMSEnvelopedDataGenerator; import org.bouncycastle.cms.CMSEnvelopedDataParser; import org.bouncycastle.cms.CMSEnvelopedDataStreamGenerator; import org.bouncycastle.cms.CMSTypedStream; import org.bouncycastle.cms.RecipientInformation; import org.bouncycastle.cms.RecipientInformationStore; import org.bouncycastle.util.encoders.Base64; import org.bouncycastle.util.encoders.Hex; public class EnvelopedDataStreamTest extends TestCase { private static final int BUFFER_SIZE = 4000; private static String _signDN; private static KeyPair _signKP; private static X509Certificate _signCert; private static String _origDN; private static KeyPair _origKP; private static X509Certificate _origCert; private static String _reciDN; private static KeyPair _reciKP; private static X509Certificate _reciCert; private static boolean _initialised = false; public EnvelopedDataStreamTest() { } private static void init() throws Exception { if (!_initialised) { _initialised = true; _signDN = "O=Bouncy Castle, C=AU"; _signKP = CMSTestUtil.makeKeyPair(); _signCert = CMSTestUtil.makeCertificate(_signKP, _signDN, _signKP, _signDN); _origDN = "CN=Bob, OU=Sales, O=Bouncy Castle, C=AU"; _origKP = CMSTestUtil.makeKeyPair(); _origCert = CMSTestUtil.makeCertificate(_origKP, _origDN, _signKP, _signDN); _reciDN = "CN=Doug, OU=Sales, O=Bouncy Castle, C=AU"; _reciKP = CMSTestUtil.makeKeyPair(); _reciCert = CMSTestUtil.makeCertificate(_reciKP, _reciDN, _signKP, _signDN); } } public void setUp() throws Exception { init(); } public void testWorkingData() throws Exception { byte[] keyData = Base64.decode( "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKrAz/SQKrcQ" + "nj9IxHIfKDbuXsMqUpI06s2gps6fp7RDNvtUDDMOciWGFhD45YSy8GO0mPx3" + "Nkc7vKBqX4TLcqLUz7kXGOHGOwiPZoNF+9jBMPNROe/B0My0PkWg9tuq+nxN" + "64oD47+JvDwrpNOS5wsYavXeAW8Anv9ZzHLU7KwZAgMBAAECgYA/fqdVt+5K" + "WKGfwr1Z+oAHvSf7xtchiw/tGtosZ24DOCNP3fcTXUHQ9kVqVkNyzt9ZFCT3" + "bJUAdBQ2SpfuV4DusVeQZVzcROKeA09nPkxBpTefWbSDQGhb+eZq9L8JDRSW" + "HyYqs+MBoUpLw7GKtZiJkZyY6CsYkAnQ+uYVWq/TIQJBAP5zafO4HUV/w4KD" + "VJi+ua+GYF1Sg1t/dYL1kXO9GP1p75YAmtm6LdnOCas7wj70/G1YlPGkOP0V" + "GFzeG5KAmAUCQQCryvKU9nwWA+kypcQT9Yr1P4vGS0APYoBThnZq7jEPc5Cm" + "ZI82yseSxSeea0+8KQbZ5mvh1p3qImDLEH/iNSQFAkAghS+tboKPN10NeSt+" + "uiGRRWNbiggv0YJ7Uldcq3ZeLQPp7/naiekCRUsHD4Qr97OrZf7jQ1HlRqTu" + "eZScjMLhAkBNUMZCQnhwFAyEzdPkQ7LpU1MdyEopYmRssuxijZao5JLqQAGw" + "YCzXokGFa7hz72b09F4DQurJL/WuDlvvu4jdAkEAxwT9lylvfSfEQw4/qQgZ" + "MFB26gqB6Gqs1pHIZCzdliKx5BO3VDeUGfXMI8yOkbXoWbYx5xPid/+N8R "+sxLBw=="); byte[] envData = Base64.decode( "MIAGCSqGSIb3DQEHA6CAMIACAQAxgcQwgcECAQAwKjAlMRYwFAYDVQQKEw1C" + "b3VuY3kgQ2FzdGxlMQswCQYDVQQGEwJBVQIBHjANBgkqhkiG9w0BAQEFAASB" + "gDmnaDZ0vDJNlaUSYyEXsgbaUH+itNTjCOgv77QTX2ImXj+kTctM19PQF2I1" + "0/NL0fjakvCgBTHKmk13a7jqB6cX3bysenHNrglHsgNGgeXQ7ggAq5fV/JQQ" + "T7rSxEtuwpbuHQnoVUZahOHVKy/a0uLr9iIh1A3y+yZTZaG505ZJMIAGCSqG" + "SIb3DQEHATAdBglghkgBZQMEAQIEENmkYNbDXiZxJWtq82qIRZKggAQgkOGr" + "1JcTsADStez1eY4+rO4DtyBIyUYQ3pilnbirfPkAAAAAAAAAAAAA"); CMSEnvelopedDataParser ep = new CMSEnvelopedDataParser(envData); RecipientInformationStore recipients = ep.getRecipientInfos(); assertEquals(ep.getEncryptionAlgOID(), CMSEnvelopedDataGenerator.AES128_CBC); Collection c = recipients.getRecipients(); Iterator it = c.iterator(); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyData); KeyFactory keyFact = KeyFactory.getInstance("RSA", "BC"); Key priKey = keyFact.generatePrivate(keySpec); byte[] data = Hex.decode("57616c6c6157616c6c6157617368696e67746f6e"); while (it.hasNext()) { RecipientInformation recipient = (RecipientInformation)it.next(); assertEquals(recipient.getKeyEncryptionAlgOID(), PKCSObjectIdentifiers.rsaEncryption.getId()); CMSTypedStream recData = recipient.getContentStream(priKey, "BC"); assertEquals(true, Arrays.equals(data, CMSTestUtil.streamToByteArray(recData.getContentStream()))); } } private void verifyData( ByteArrayOutputStream encodedStream, String expectedOid, byte[] expectedData) throws Exception { CMSEnvelopedDataParser ep = new CMSEnvelopedDataParser(encodedStream.toByteArray()); RecipientInformationStore recipients = ep.getRecipientInfos(); assertEquals(ep.getEncryptionAlgOID(), expectedOid); Collection c = recipients.getRecipients(); Iterator it = c.iterator(); while (it.hasNext()) { RecipientInformation recipient = (RecipientInformation)it.next(); assertEquals(recipient.getKeyEncryptionAlgOID(), PKCSObjectIdentifiers.rsaEncryption.getId()); CMSTypedStream recData = recipient.getContentStream(_reciKP.getPrivate(), "BC"); assertEquals(true, Arrays.equals(expectedData, CMSTestUtil.streamToByteArray(recData.getContentStream()))); } } public void testKeyTransAES128BufferedStream() throws Exception { byte[] data = new byte[2000]; for (int i = 0; i != 2000; i++) { data[i] = (byte)(i & 0xff); } // unbuffered CMSEnvelopedDataStreamGenerator edGen = new CMSEnvelopedDataStreamGenerator(); edGen.addKeyTransRecipient(_reciCert); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); OutputStream out = edGen.open( bOut, CMSEnvelopedDataGenerator.AES128_CBC, "BC"); for (int i = 0; i != 2000; i++) { out.write(data[i]); } out.close(); verifyData(bOut, CMSEnvelopedDataGenerator.AES128_CBC, data); int unbufferedLength = bOut.toByteArray().length; // buffered edGen = new CMSEnvelopedDataStreamGenerator(); edGen.addKeyTransRecipient(_reciCert); bOut = new ByteArrayOutputStream(); out = edGen.open(bOut, CMSEnvelopedDataGenerator.AES128_CBC, "BC"); BufferedOutputStream bfOut = new BufferedOutputStream(out, 300); for (int i = 0; i != 2000; i++) { bfOut.write(data[i]); } bfOut.close(); verifyData(bOut, CMSEnvelopedDataGenerator.AES128_CBC, data); assertTrue(bOut.toByteArray().length < unbufferedLength); } public void testKeyTransAES128Buffered() throws Exception { byte[] data = new byte[2000]; for (int i = 0; i != 2000; i++) { data[i] = (byte)(i & 0xff); } // unbuffered CMSEnvelopedDataStreamGenerator edGen = new CMSEnvelopedDataStreamGenerator(); edGen.addKeyTransRecipient(_reciCert); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); OutputStream out = edGen.open( bOut, CMSEnvelopedDataGenerator.AES128_CBC, "BC"); for (int i = 0; i != 2000; i++) { out.write(data[i]); } out.close(); verifyData(bOut, CMSEnvelopedDataGenerator.AES128_CBC, data); int unbufferedLength = bOut.toByteArray().length; // buffered edGen = new CMSEnvelopedDataStreamGenerator(); edGen.setBufferSize(300); edGen.addKeyTransRecipient(_reciCert); bOut = new ByteArrayOutputStream(); out = edGen.open(bOut, CMSEnvelopedDataGenerator.AES128_CBC, "BC"); for (int i = 0; i != 2000; i++) { out.write(data[i]); } out.close(); verifyData(bOut, CMSEnvelopedDataGenerator.AES128_CBC, data); assertTrue(bOut.toByteArray().length < unbufferedLength); } public void testKeyTransAES128Der() throws Exception { byte[] data = new byte[2000]; for (int i = 0; i != 2000; i++) { data[i] = (byte)(i & 0xff); } CMSEnvelopedDataStreamGenerator edGen = new CMSEnvelopedDataStreamGenerator(); edGen.addKeyTransRecipient(_reciCert); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); OutputStream out = edGen.open( bOut, CMSEnvelopedDataGenerator.AES128_CBC, "BC"); for (int i = 0; i != 2000; i++) { out.write(data[i]); } out.close(); // convert to DER ASN1InputStream aIn = new ASN1InputStream(bOut.toByteArray()); bOut.reset(); DEROutputStream dOut = new DEROutputStream(bOut); dOut.writeObject(aIn.readObject()); verifyData(bOut, CMSEnvelopedDataGenerator.AES128_CBC, data); } public void testKeyTransAES128Throughput() throws Exception { byte[] data = new byte[40001]; for (int i = 0; i != data.length; i++) { data[i] = (byte)(i & 0xff); } // buffered CMSEnvelopedDataStreamGenerator edGen = new CMSEnvelopedDataStreamGenerator(); edGen.setBufferSize(BUFFER_SIZE); edGen.addKeyTransRecipient(_reciCert); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); OutputStream out = edGen.open(bOut, CMSEnvelopedDataGenerator.AES128_CBC, "BC"); for (int i = 0; i != data.length; i++) { out.write(data[i]); } out.close(); CMSEnvelopedDataParser ep = new CMSEnvelopedDataParser(bOut.toByteArray()); RecipientInformationStore recipients = ep.getRecipientInfos(); Collection c = recipients.getRecipients(); Iterator it = c.iterator(); if (it.hasNext()) { RecipientInformation recipient = (RecipientInformation)it.next(); assertEquals(recipient.getKeyEncryptionAlgOID(), PKCSObjectIdentifiers.rsaEncryption.getId()); CMSTypedStream recData = recipient.getContentStream(_reciKP.getPrivate(), "BC"); InputStream dataStream = recData.getContentStream(); ByteArrayOutputStream dataOut = new ByteArrayOutputStream(); int len; byte[] buf = new byte[BUFFER_SIZE]; int count = 0; while (count != 10 && (len = dataStream.read(buf)) > 0) { assertEquals(buf.length, len); dataOut.write(buf); count++; } len = dataStream.read(buf); dataOut.write(buf, 0, len); assertEquals(true, Arrays.equals(data, dataOut.toByteArray())); } else { fail("recipient not found."); } } public void testKeyTransAES128() throws Exception { byte[] data = "WallaWallaWashington".getBytes(); CMSEnvelopedDataStreamGenerator edGen = new CMSEnvelopedDataStreamGenerator(); edGen.addKeyTransRecipient(_reciCert); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); OutputStream out = edGen.open( bOut, CMSEnvelopedDataGenerator.AES128_CBC, "BC"); out.write(data); out.close(); CMSEnvelopedDataParser ep = new CMSEnvelopedDataParser(bOut.toByteArray()); RecipientInformationStore recipients = ep.getRecipientInfos(); assertEquals(ep.getEncryptionAlgOID(), CMSEnvelopedDataGenerator.AES128_CBC); Collection c = recipients.getRecipients(); Iterator it = c.iterator(); while (it.hasNext()) { RecipientInformation recipient = (RecipientInformation)it.next(); assertEquals(recipient.getKeyEncryptionAlgOID(), PKCSObjectIdentifiers.rsaEncryption.getId()); CMSTypedStream recData = recipient.getContentStream(_reciKP.getPrivate(), "BC"); assertEquals(true, Arrays.equals(data, CMSTestUtil.streamToByteArray(recData.getContentStream()))); } } public void testAESKEK() throws Exception { byte[] data = "WallaWallaWashington".getBytes(); SecretKey kek = CMSTestUtil.makeAES192Key(); CMSEnvelopedDataStreamGenerator edGen = new CMSEnvelopedDataStreamGenerator(); byte[] kekId = new byte[] { 1, 2, 3, 4, 5 }; edGen.addKEKRecipient(kek, kekId); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); OutputStream out = edGen.open( bOut, CMSEnvelopedDataGenerator.DES_EDE3_CBC, "BC"); out.write(data); out.close(); CMSEnvelopedDataParser ep = new CMSEnvelopedDataParser(bOut.toByteArray()); RecipientInformationStore recipients = ep.getRecipientInfos(); assertEquals(ep.getEncryptionAlgOID(), CMSEnvelopedDataGenerator.DES_EDE3_CBC); Collection c = recipients.getRecipients(); Iterator it = c.iterator(); while (it.hasNext()) { RecipientInformation recipient = (RecipientInformation)it.next(); assertEquals(recipient.getKeyEncryptionAlgOID(), "2.16.840.1.101.3.4.1.25"); CMSTypedStream recData = recipient.getContentStream(kek, "BC"); assertEquals(true, Arrays.equals(data, CMSTestUtil.streamToByteArray(recData.getContentStream()))); } } public static Test suite() throws Exception { return new CMSTestSetup(new TestSuite(EnvelopedDataStreamTest.class)); } }
package hudson.model; import static org.junit.Assert.*; import java.io.IOException; import java.net.URL; import javax.annotation.Nonnull; import com.gargoylesoftware.htmlunit.WebRequest; import org.hamcrest.Matchers; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.JenkinsRule.WebClient; import org.jvnet.hudson.test.MockFolder; import com.gargoylesoftware.htmlunit.HttpMethod; import com.gargoylesoftware.htmlunit.Page; import com.gargoylesoftware.htmlunit.WebResponse; public class DirectlyModifiableViewTest { @Rule public JenkinsRule j = new JenkinsRule(); @Test public void manipulateViewContent() throws IOException { FreeStyleProject projectA = j.createFreeStyleProject("projectA"); FreeStyleProject projectB = j.createFreeStyleProject("projectB"); ListView view = new ListView("a_view", j.jenkins); j.jenkins.addView(view); assertFalse(view.contains(projectA)); assertFalse(view.contains(projectB)); view.add(projectA); assertTrue(view.contains(projectA)); assertFalse(view.contains(projectB)); view.add(projectB); assertTrue(view.contains(projectA)); assertTrue(view.contains(projectB)); assertTrue(view.remove(projectA)); assertFalse(view.contains(projectA)); assertTrue(view.contains(projectB)); assertTrue(view.remove(projectB)); assertFalse(view.contains(projectA)); assertFalse(view.contains(projectB)); assertFalse(view.remove(projectB)); } @Test public void doAddJobToView() throws Exception { FreeStyleProject project = j.createFreeStyleProject("a_project"); ListView view = new ListView("a_view", j.jenkins); j.jenkins.addView(view); assertFalse(view.contains(project)); Page page = doPost(view, "addJobToView?name=a_project"); j.assertGoodStatus(page); assertTrue(view.contains(project)); page = doPost(view, "addJobToView?name=a_project"); j.assertGoodStatus(page); assertTrue(view.contains(project)); } @Test public void doAddNestedJobToRecursiveView() throws Exception { ListView view = new ListView("a_view", j.jenkins); view.setRecurse(true); j.jenkins.addView(view); MockFolder folder = j.createFolder("folder"); FreeStyleProject np = folder.createProject(FreeStyleProject.class, "nested_project"); view.add(np); assertTrue(view.contains(np)); view.remove(np); assertFalse(view.contains(np)); Page page = doPost(view, "addJobToView?name=folder/nested_project"); j.assertGoodStatus(page); assertTrue(view.contains(np)); page = doPost(view, "removeJobFromView?name=folder/nested_project"); j.assertGoodStatus(page); assertFalse(view.contains(np)); MockFolder nf = folder.createProject(MockFolder.class, "nested_folder"); FreeStyleProject nnp = nf.createProject(FreeStyleProject.class, "nested_nested_project"); ListView nestedView = new ListView("nested_view", folder); nestedView.setRecurse(true); folder.addView(nestedView); page = doPost(nestedView, "addJobToView?name=nested_folder/nested_nested_project"); j.assertGoodStatus(page); assertTrue(nestedView.contains(nnp)); page = doPost(nestedView, "removeJobFromView?name=nested_folder/nested_nested_project"); j.assertGoodStatus(page); assertFalse(nestedView.contains(nnp)); page = doPost(nestedView, "addJobToView?name=/folder/nested_folder/nested_nested_project"); j.assertGoodStatus(page); assertTrue(nestedView.contains(nnp)); page = doPost(nestedView, "removeJobFromView?name=/folder/nested_folder/nested_nested_project"); j.assertGoodStatus(page); assertFalse(nestedView.contains(nnp)); } @Test public void doRemoveJobFromView() throws Exception { FreeStyleProject project = j.createFreeStyleProject("a_project"); ListView view = new ListView("a_view", j.jenkins); j.jenkins.addView(view); Page page = doPost(view, "addJobToView?name=a_project"); assertTrue(view.contains(project)); page = doPost(view, "removeJobFromView?name=a_project"); j.assertGoodStatus(page); assertFalse(view.contains(project)); page = doPost(view, "removeJobFromView?name=a_project"); j.assertGoodStatus(page); assertFalse(view.contains(project)); } @Test public void failWebMethodForIllegalRequest() throws Exception { ListView view = new ListView("a_view", j.jenkins); j.jenkins.addView(view); assertBadStatus( doPost(view, "addJobToView"), "Query parameter 'name' is required" ); assertBadStatus( doPost(view, "addJobToView?name=no_project"), "Query parameter 'name' does not correspond to a known item" ); assertBadStatus( doPost(view, "removeJobFromView"), "Query parameter 'name' is required" ); MockFolder folder = j.createFolder("folder"); ListView folderView = new ListView("folder_view", folder); folder.addView(folderView); assertBadStatus( // Item is scoped to different ItemGroup doPost(folderView, "addJobToView?name=top_project"), "Query parameter 'name' does not correspond to a known item" ); } private Page doPost(View view, String path) throws Exception { WebClient wc = j.createWebClient(); // wc.setThrowExceptionOnFailingStatusCode(false); WebRequest req = new WebRequest( new URL(j.jenkins.getRootUrl() + view.getUrl() + path), HttpMethod.POST ); return wc.getPage(wc.addCrumb(req)); } private void assertBadStatus(Page page, String message) { WebResponse rsp = page.getWebResponse(); assertFalse("Status: " + rsp.getStatusCode(), j.isGoodHttpStatus(rsp.getStatusCode())); assertThat(rsp.getContentAsString(), Matchers.containsString(message)); } }
import java.util.*; /** * Given a binary tree, return the level order traversal of its nodes' values. * (ie, from left to right, level by level). * * For example: * Given binary tree {3,9,20,#,#,15,7}, * 3 * / \ * 9 20 * / \ * 15 7 * * return its level order traversal as: * [ * [3], * [9,20], * [15,7] * ] * * Tags: Tree, BFS */ class BTLevelOrder { public static void main(String[] args) { } /** * Queue * Get size of the queue each time * Iterate that many times to build current level */ private List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> res = new ArrayList<List<Integer>>(); if (root == null) return res; Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.add(root); while (!queue.isEmpty()) { List<Integer> curLevel = new ArrayList<Integer>(); int size = queue.size(); for (int i = 0; i < size; i++) { TreeNode n = queue.poll(); curLevel.add(n.val); if (n.left != null) queue.add(n.left); if (n.right != null) queue.add(n.right); } res.add(curLevel); } return res; } public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } }
package org.mozilla.javascript.tests.es5; import java.util.ArrayList; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mozilla.javascript.Context; import org.mozilla.javascript.EcmaError; import org.mozilla.javascript.ScriptableObject; import static org.junit.Assert.assertTrue; public class Test262RegExpTest { private Context cx; private ScriptableObject scope; @Before public void setUp() { cx = Context.enter(); scope = cx.initStandardObjects(); } @After public void tearDown() { Context.exit(); } @Test public void testS15_10_2_9_A1_T4() { String source = "/\\b(\\w+) \\2\\b/.test('do you listen the the band');"; String sourceName = "Conformance/15_Native/15.10_RegExp_Objects/15.10.2_Pattern_Semantics/15.10.2.9_AtomEscape/S15.10.2.9_A1_T4.js"; cx.evaluateString(scope, source, sourceName, 0, null); } @Test public void testS15_10_2_11_A1_T2() { List<String> sources = new ArrayList<String>(); sources.add("/\\1/.exec('');"); sources.add("/\\2/.exec('');"); sources.add("/\\3/.exec('');"); sources.add("/\\4/.exec('');"); sources.add("/\\5/.exec('');"); sources.add("/\\6/.exec('');"); sources.add("/\\7/.exec('');"); sources.add("/\\8/.exec('');"); sources.add("/\\9/.exec('');"); sources.add("/\\10/.exec('');"); String sourceName = "Conformance/15_Native/15.10_RegExp_Objects/15.10.2_Pattern_Semantics/15.10.2.11_DecimalEscape/S15.10.2.11_A1_T2.js"; for (String source : sources) { cx.evaluateString(scope, source, sourceName, 0, null); } } @Test public void testS15_10_2_11_A1_T3() { String source = "/(?:A)\\2/.exec('AA');"; String sourceName = "Conformance/15_Native/15.10_RegExp_Objects/15.10.2_Pattern_Semantics/15.10.2.11_DecimalEscape/S15.10.2.11_A1_T3.js"; cx.evaluateString(scope, source, sourceName, 0, null); } @Test(expected = EcmaError.class) public void testS15_10_2_15_A1_T4() { String source = "(new RegExp('[\\\\Db-G]').exec('a'))"; String sourceName = "Conformance/15_Native/15.10_RegExp_Objects/15.10.2_Pattern_Semantics/15.10.2.15_NonemptyClassRanges/S15.10.2.15_A1_T4.js"; cx.evaluateString(scope, source, sourceName, 0, null); } @Test(expected = EcmaError.class) public void testS15_10_2_15_A1_T5() { String source = "(new RegExp('[\\\\sb-G]').exec('a'))"; String sourceName = "Conformance/15_Native/15.10_RegExp_Objects/15.10.2_Pattern_Semantics/15.10.2.15_NonemptyClassRanges/S15.10.2.15_A1_T5.js"; cx.evaluateString(scope, source, sourceName, 0, null); } @Test(expected = EcmaError.class) public void testS15_10_2_15_A1_T6() { String source = "(new RegExp('[\\\\Sb-G]').exec('a'))"; String sourceName = "Conformance/15_Native/15.10_RegExp_Objects/15.10.2_Pattern_Semantics/15.10.2.15_NonemptyClassRanges/S15.10.2.15_A1_T6.js"; cx.evaluateString(scope, source, sourceName, 0, null); } @Test(expected = EcmaError.class) public void testS15_10_2_15_A1_T7() { String source = "(new RegExp('[\\\\wb-G]').exec('a'))"; String sourceName = "Conformance/15_Native/15.10_RegExp_Objects/15.10.2_Pattern_Semantics/15.10.2.15_NonemptyClassRanges/S15.10.2.15_A1_T7.js"; cx.evaluateString(scope, source, sourceName, 0, null); } @Test(expected = EcmaError.class) public void testS15_10_2_15_A1_T8() { String source = "(new RegExp('[\\\\Wb-G]').exec('a'))"; String sourceName = "Conformance/15_Native/15.10_RegExp_Objects/15.10.2_Pattern_Semantics/15.10.2.15_NonemptyClassRanges/S15.10.2.15_A1_T8.js"; cx.evaluateString(scope, source, sourceName, 0, null); } @Test public void testS15_10_4_1_T1() { String source = "new RegExp().test('AA');"; String sourceName = "Conformance/15_Native/15.10_RegExp_Objects/15.10.4_Pattern_Constructor/15.10.4.1_EmptyPattern/S15.10.4.1_T1.js"; assertTrue((Boolean) cx.evaluateString(scope, source, sourceName, 0, null)); } @Test public void testS15_10_4_1_T2_Undefined() { String source = "new RegExp(undefined).test('AA');"; String sourceName = "Conformance/15_Native/15.10_RegExp_Objects/15.10.4_Pattern_Constructor/15.10.4.1_UndefinedPattern/S15.10.4.1_T2_Undefined.js"; assertTrue((Boolean) cx.evaluateString(scope, source, sourceName, 0, null)); } }
package to.etc.domui.component.buttons; import javax.annotation.*; import to.etc.domui.component.menu.*; import to.etc.domui.dom.html.*; import to.etc.domui.server.*; import to.etc.domui.util.*; public class LinkButton extends ATag implements IActionControl { @Nullable private String m_text; @Nullable private String m_imageUrl; private boolean m_disabled; @Nullable private IUIAction<Void> m_action; @Nullable private Object m_actionInstance; public LinkButton() { setCssClass("ui-lnkb"); } public LinkButton(@Nonnull final String txt, @Nonnull final String image, @Nonnull final IClicked< ? extends NodeBase> clk) { setCssClass("ui-lnkb ui-lbtn"); setClicked(clk); m_text = txt; setImage(image); } public LinkButton(@Nonnull final String txt, @Nonnull final String image) { setCssClass("ui-lnkb ui-lbtn"); m_text = txt; setImage(image); } public LinkButton(@Nonnull final String txt) { setCssClass("ui-lnkb"); m_text = txt; } public LinkButton(@Nonnull final String txt, @Nonnull final IClicked< ? extends NodeBase> clk) { setCssClass("ui-lnkb"); setClicked(clk); m_text = txt; } public LinkButton(@Nonnull IUIAction<Void> action) throws Exception { this(); m_action = action; actionRefresh(); } public LinkButton(@Nonnull IUIAction<Void> action, @Nullable Object actionInstance) throws Exception { this(); m_action = action; m_actionInstance = actionInstance; actionRefresh(); } @Override public void createContent() throws Exception { setText(m_text); } /** * EXPERIMENTAL - UNSTABLE INTERFACE - Refresh the button regarding the state of the action. */ private void actionRefresh() throws Exception { final IUIAction<Object> action = (IUIAction<Object>) getAction(); if(null == action) return; String dt = action.getDisableReason(getActionInstance()); if(null == dt) { setTitle(action.getTitle(getActionInstance())); // The default tooltip or remove it if not present setDisabled(false); } else { setTitle(dt); // Shot reason for being disabled setDisabled(true); } setText(action.getName(getActionInstance())); setImage(action.getIcon(getActionInstance())); setClicked(new IClicked<LinkButton>() { @Override public void clicked(@Nonnull LinkButton clickednode) throws Exception { action.execute(LinkButton.this, getActionInstance()); } }); } public void setImage(@Nullable final String url) { if(DomUtil.isEqual(url, m_imageUrl)) return; m_imageUrl = url; updateStyle(); forceRebuild(); } public String getImage() { return m_imageUrl; } private void updateStyle() { String image = DomApplication.get().getThemedResourceRURL(m_imageUrl); if(image == null) { setBackgroundImage(null); setCssClass("ui-lnkb"); } else { setBackgroundImage(image); setCssClass("ui-lnkb ui-lbtn"); } if(isDisabled()) addCssClass("ui-lnkb-dis"); else removeCssClass("ui-lnkb-dis"); } @Override public void setText(final @Nullable String txt) { m_text = txt; super.setText(txt); } @Override @Nonnull public String getComponentInfo() { return "LinkButton:" + m_text; } @Nullable public IUIAction< ? > getAction() { return m_action; } @Nullable public Object getActionInstance() { return m_actionInstance; } public void setAction(@Nonnull IUIAction<Void> action) throws Exception { if(DomUtil.isEqual(m_action, action)) return; m_action = action; actionRefresh(); } public boolean isDisabled() { return m_disabled; } @Override public void setDisabled(boolean disabled) { if(m_disabled == disabled) return; m_disabled = disabled; updateStyle(); forceRebuild(); } @Override public void internalOnClicked(@Nonnull ClickInfo cli) throws Exception { if(isDisabled()) return; super.internalOnClicked(cli); } }
import java.io.*; import java.util.*; import org.json.simple.*; import org.json.simple.parser.*; public class JUnitPointsMerger { private static final class SingleReport { boolean success; String description; String message; } private static final class SingleReportComparator implements Comparator<SingleReport> { public int compare(SingleReport r1, SingleReport r2) { if (r1 == null && r2 == null) return 0; if (r1 == null) return -1; if (r2 == null) return 1; boolean t1 = r1.success; boolean t2 = r2.success; if (t1 == t2) { if (r1.description.compareTo(r2.description) == 0) { return r1.message.compareTo(r2.message); } return r1.description.compareTo(r2.description); } if (t1) return +1; return -1; } } static { Locale.setDefault(Locale.US); } private static String summary = ""; private static double points = 0; private static void merge(ArrayList<JSONObject> rexs, JSONObject vex) { // merges two exercises ArrayList<SingleReport> reps = new ArrayList<>(); double localpoints = 0; JSONArray vextests = (JSONArray) vex.get("tests"); for (JSONObject rex : rexs) { JSONArray rextests = (JSONArray) rex.get("tests"); if (rextests.size() != vextests.size()) { throw new RuntimeException("vanilla and one of replaced do have different number of tests for exercise " + rex.get("name")); } } for (int i = 0; i < vextests.size(); i++) { JSONObject vextest = (JSONObject) vextests.get(i); JSONObject usedresult = vextest; for (JSONObject rexIt : rexs) { boolean found = false; JSONArray rextests = (JSONArray) rexIt.get("tests"); for (int j = 0; !found && j < rextests.size(); j++) { JSONObject rextest = (JSONObject) rextests.get(i); if (rextest.get("id").equals(vextest.get("id"))) { if ((Boolean) rextest.get("success")) { usedresult = rextest; } found = true; } } if (!found) { throw new RuntimeException("could not find " + vextest.get("id") + " in replaced tests"); } } String localSummary = ""; if ((Boolean) vextest.get("success")) { usedresult = vextest; } double localscore = Double.parseDouble((String) usedresult.get("score")); localpoints += localscore; localSummary += ((Boolean) usedresult.get("success")) ? "" : ""; localSummary += String.format(" %1$6.2f", localscore) + " | "; localSummary += (String) usedresult.get("desc"); Object error = usedresult.get("error"); if (error != null) { localSummary += " | " + (String) error; } localSummary += "\n"; SingleReport r = new SingleReport(); r.success = ((Boolean) usedresult.get("success")); r.message = localSummary; r.description = (String)usedresult.get("id"); reps.add(r); } localpoints = Math.max(0., localpoints); localpoints = Math.ceil(2. * localpoints) / 2; // round up to half points localpoints = Math.min(localpoints, Double.parseDouble((String) vex.get("possiblePts"))); points += localpoints; summary += "\n" + (String) vex.get("name"); summary += String.format(" (%1$.1f points):", localpoints) + "\n"; Collections.sort(reps, new SingleReportComparator()); for (SingleReport r : reps) { summary += r.message; } } public static void main(String[] args) throws Exception { String inputFile = (args.length == 2) ? args[0] : "result.json"; String outputFile = (args.length == 2) ? args[1] : "mergedcomment.txt"; JSONParser parser = new JSONParser(); try { JSONObject obj = (JSONObject) parser.parse(new FileReader(inputFile)); JSONObject vanilla = (JSONObject) obj.get("vanilla"); JSONArray vanillaex = (JSONArray) vanilla.get("exercises"); JSONArray replaceds = (JSONArray) obj.get("replaced"); for (int i = 0; i < vanillaex.size(); i++) { JSONObject vex = (JSONObject) vanillaex.get(i); ArrayList<JSONObject> rexs = new ArrayList<>(); for (int k = 0; k < replaceds.size(); k++) { JSONObject replaced = (JSONObject) replaceds.get(k); JSONArray replacedex = (JSONArray) replaced.get("exercises"); if (vanillaex.size() != replacedex.size()) { throw new RuntimeException("vanilla and replaced #" + k + " do have different number of exercises"); } boolean found = false; for (int j = 0; !found && j < replacedex.size(); j++) { JSONObject rex = (JSONObject) replacedex.get(j); if (rex.get("name").equals(vex.get("name"))) { found = true; rexs.add(rex); } } if (!found) { throw new RuntimeException("could not find " + vex.get("name") + " in replaced exercises } } merge(rexs,vex); } summary = "Score: " + String.format("%1$.1f\n", points) + summary; File file = new File(outputFile); if (!file.exists()) { file.createNewFile(); } FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); bw.write(summary); bw.close(); } catch (Exception e) { e.printStackTrace(); System.out.println("invalid json"); throw e; } } }
package VASSAL.launch; import VASSAL.configure.StringConfigurer; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Font; import java.awt.Frame; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; import java.util.stream.Stream; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.BoxLayout; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JEditorPane; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTree; import javax.swing.KeyStroke; import javax.swing.ListSelectionModel; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.border.TitledBorder; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeWillExpandListener; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import javax.swing.text.html.HTMLEditorKit; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.TreePath; import net.miginfocom.swing.MigLayout; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.SystemUtils; import org.jdesktop.swingx.JXTreeTable; import org.jdesktop.swingx.treetable.DefaultMutableTreeTableNode; import org.jdesktop.swingx.treetable.DefaultTreeTableModel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import VASSAL.Info; import VASSAL.build.module.Documentation; import VASSAL.build.module.ExtensionsManager; import VASSAL.build.module.metadata.AbstractMetaData; import VASSAL.build.module.metadata.ExtensionMetaData; import VASSAL.build.module.metadata.MetaDataFactory; import VASSAL.build.module.metadata.ModuleMetaData; import VASSAL.build.module.metadata.SaveMetaData; import VASSAL.chat.CgiServerStatus; import VASSAL.chat.ui.ServerStatusView; import VASSAL.configure.BooleanConfigurer; import VASSAL.configure.DirectoryConfigurer; import VASSAL.configure.IntConfigurer; import VASSAL.configure.ShowHelpAction; import VASSAL.configure.StringArrayConfigurer; import VASSAL.i18n.Resources; import VASSAL.preferences.PositionOption; import VASSAL.preferences.Prefs; import VASSAL.tools.ApplicationIcons; import VASSAL.tools.BrowserSupport; import VASSAL.tools.ErrorDialog; import VASSAL.tools.SequenceEncoder; import VASSAL.tools.WriteErrorDialog; import VASSAL.tools.filechooser.FileChooser; import VASSAL.tools.filechooser.ModuleExtensionFileFilter; import VASSAL.tools.logging.LogPane; import VASSAL.tools.menu.CheckBoxMenuItemProxy; import VASSAL.tools.menu.MenuBarProxy; import VASSAL.tools.menu.MenuItemProxy; import VASSAL.tools.menu.MenuManager; import VASSAL.tools.menu.MenuProxy; import VASSAL.tools.swing.Dialogs; import VASSAL.tools.swing.SplitPane; import VASSAL.tools.swing.SwingUtils; import VASSAL.tools.version.UpdateCheckAction; import VASSAL.tools.version.VersionUtils; public class ModuleManagerWindow extends JFrame { private static final long serialVersionUID = 1L; private static final Logger logger = LoggerFactory.getLogger(ModuleManagerWindow.class); private static final String SHOW_STATUS_KEY = "showServerStatus"; //NON-NLS private static final String DIVIDER_LOCATION_KEY = "moduleManagerDividerLocation"; //NON-NLS private static final String DEVELOPER_INFO_KEY = "moduleManagerDeveloperInfo"; //NON-NLS private static final String COLUMN_WIDTHS_KEY = "moduleManagerColumnWidths"; //NON-NLS private static final int COLUMNS = 5; private static final int KEY_COLUMN = 0; private static final int VERSION_COLUMN = 1; private static final int SPARE_COLUMN = 2; private static final int VASSAL_COLUMN = 3; private static final int SAVED_COLUMN = 4; private static final String[] columnHeadings = new String[COLUMNS]; private static final TableColumn[] columns = new TableColumn[COLUMNS]; private final ImageIcon moduleIcon; private final ImageIcon activeExtensionIcon; private final ImageIcon inactiveExtensionIcon; private final ImageIcon openGameFolderIcon; private final ImageIcon closedGameFolderIcon; private final ImageIcon fileIcon; private StringArrayConfigurer recentModuleConfig; private StringArrayConfigurer moduleConfig; private File selectedModule; private final CardLayout modulePanelLayout; private final JPanel moduleView; private final SplitPane splitPane; private MyTreeNode rootNode; private MyTree tree; private MyTreeTableModel treeModel; protected MyTreeNode selectedNode; private long lastExpansionTime; private TreePath lastExpansionPath; private final IntConfigurer dividerLocationConfig; private static final long doubleClickInterval; static { final Object dci = Toolkit.getDefaultToolkit().getDesktopProperty("awt.multiClickInterval"); doubleClickInterval = dci instanceof Integer ? (Integer) dci : 200L; } public static ModuleManagerWindow getInstance() { return instance; } private static final ModuleManagerWindow instance = new ModuleManagerWindow(); public ModuleManagerWindow() { setTitle("VASSAL " + Info.getVersion()); //NON-NLS setLayout(new BoxLayout(getContentPane(), BoxLayout.X_AXIS)); ApplicationIcons.setFor(this); final AbstractAction shutDownAction = new AbstractAction() { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { saveColumnWidths(); final Prefs gp = Prefs.getGlobalPrefs(); try { gp.close(); } catch (IOException ex) { WriteErrorDialog.error(ex, gp.getFile()); } try { ModuleManager.getInstance().shutDown(); } catch (IOException ex) { ErrorDialog.bug(ex); } logger.info("Exiting"); //NON-NLS System.exit(0); } }; shutDownAction.putValue(Action.NAME, Resources.getString(Resources.QUIT)); setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { shutDownAction.actionPerformed(null); } }); // setup menubar and actions final MenuManager mm = MenuManager.getInstance(); final MenuBarProxy mb = mm.getMenuBarProxyFor(this); // file menu final MenuProxy fileMenu = new MenuProxy(Resources.getString("General.file")); fileMenu.setMnemonic(Resources.getString("General.file.shortcut").charAt(0)); fileMenu.add(mm.addKey("Main.play_module")); fileMenu.add(mm.addKey("Main.edit_module")); fileMenu.add(mm.addKey("Main.new_module")); fileMenu.addSeparator(); if (!SystemUtils.IS_OS_MAC) { fileMenu.add(mm.addKey("Prefs.edit_preferences")); fileMenu.addSeparator(); fileMenu.add(mm.addKey("General.quit")); } // tools menu final MenuProxy toolsMenu = new MenuProxy(Resources.getString("General.tools")); // Initialize Global Preferences Prefs.getGlobalPrefs().getEditor().initDialog(this); Prefs.initSharedGlobalPrefs(); final BooleanConfigurer serverStatusConfig = new BooleanConfigurer(SHOW_STATUS_KEY, null, Boolean.FALSE); Prefs.getGlobalPrefs().addOption(null, serverStatusConfig); dividerLocationConfig = new IntConfigurer(DIVIDER_LOCATION_KEY, null, -10); Prefs.getGlobalPrefs().addOption(null, dividerLocationConfig); final BooleanConfigurer developerInfoConfig = new BooleanConfigurer(DEVELOPER_INFO_KEY, Resources.getString("Prefs.developer_info"), false); Prefs.getGlobalPrefs().addOption(Resources.getString("Prefs.general_tab"), developerInfoConfig); developerInfoConfig.addPropertyChangeListener(e1 -> updateColumnDisplay()); toolsMenu.add(new CheckBoxMenuItemProxy(new AbstractAction( Resources.getString("Chat.server_status")) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { splitPane.toggleRight(); serverStatusConfig.setValue( serverStatusConfig.booleanValue() ? Boolean.FALSE : Boolean.TRUE); if (splitPane.isRightVisible()) { splitPane.setDividerLocation(getPreferredDividerLocation()); } } }, serverStatusConfig.booleanValue())); toolsMenu.add(mm.addKey("Main.import_module")); toolsMenu.add(new MenuItemProxy(new AbstractAction( Resources.getString("ModuleManager.clear_tilecache")) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent evt) { final int dialogResult = Dialogs.showConfirmDialog( ModuleManagerWindow.this, Resources.getString("ModuleManager.clear_tilecache_title"), Resources.getString("ModuleManager.clear_tilecache_heading"), Resources.getString("ModuleManager.clear_tilecache_message"), JOptionPane.WARNING_MESSAGE, JOptionPane.OK_CANCEL_OPTION); if (dialogResult == JOptionPane.OK_OPTION) { final File tdir = new File(Info.getConfDir(), "tiles"); if (tdir.exists()) { try { FileUtils.forceDelete(tdir); FileUtils.forceMkdir(tdir); } catch (IOException e) { WriteErrorDialog.error(e, tdir); } } } } })); // help menu final MenuProxy helpMenu = new MenuProxy(Resources.getString("General.help")); helpMenu.setMnemonic(Resources.getString("General.help.shortcut").charAt(0)); helpMenu.add(mm.addKey("General.help")); helpMenu.add(mm.addKey("Main.tour")); helpMenu.add(mm.addKey("Help.user_guide")); helpMenu.addSeparator(); helpMenu.add(mm.addKey("UpdateCheckAction.update_check")); helpMenu.add(mm.addKey("Help.error_log")); if (!SystemUtils.IS_OS_MAC) { helpMenu.addSeparator(); helpMenu.add(mm.addKey("AboutScreen.about_vassal")); } mb.add(fileMenu); mb.add(toolsMenu); mb.add(helpMenu); // add actions mm.addAction("Main.play_module", new Player.PromptLaunchAction(this)); mm.addAction("Main.edit_module", new Editor.PromptLaunchAction(this)); mm.addAction("Main.new_module", new Editor.NewModuleLaunchAction(this)); mm.addAction("Main.import_module", new Editor.PromptImportLaunchAction(this)); mm.addAction("Prefs.edit_preferences", Prefs.getGlobalPrefs().getEditor().getEditAction()); mm.addAction("General.quit", shutDownAction); try { final URL url = new File(Documentation.getDocumentationBaseDir(), "README.html").toURI().toURL(); mm.addAction("General.help", new ShowHelpAction(url, null)); } catch (MalformedURLException e) { ErrorDialog.bug(e); } try { final URL url = new File(Documentation.getDocumentationBaseDir(), "userguide/userguide.pdf").toURI().toURL(); mm.addAction("Help.user_guide", new ShowHelpAction("Help.user_guide", url, null)); } catch (MalformedURLException e) { ErrorDialog.bug(e); } mm.addAction("Main.tour", new LaunchTourAction(this)); mm.addAction("AboutScreen.about_vassal", new AboutVASSALAction(this)); mm.addAction("UpdateCheckAction.update_check", new UpdateCheckAction(this)); mm.addAction("Help.error_log", new ShowErrorLogAction(this)); setJMenuBar(mm.getMenuBarFor(this)); // Load Icons moduleIcon = new ImageIcon( getClass().getResource("/images/mm-module.png")); //NON-NLS activeExtensionIcon = new ImageIcon( getClass().getResource("/images/mm-extension-active.png")); //NON-NLS inactiveExtensionIcon = new ImageIcon( getClass().getResource("/images/mm-extension-inactive.png")); //NON-NLS openGameFolderIcon = new ImageIcon( getClass().getResource("/images/mm-gamefolder-open.png")); //NON-NLS closedGameFolderIcon = new ImageIcon( getClass().getResource("/images/mm-gamefolder-closed.png")); //NON-NLS fileIcon = new ImageIcon(getClass().getResource("/images/mm-file.png")); //NON-NLS // build module controls final JPanel moduleControls = new JPanel(new BorderLayout()); modulePanelLayout = new CardLayout(); moduleView = new JPanel(modulePanelLayout); buildTree(); final JScrollPane scroll = new JScrollPane(tree); moduleView.add(scroll, "modules"); //NON-NLS final JEditorPane l = new JEditorPane("text/html", Resources.getString("ModuleManager.quickstart")); l.setEditable(false); // Try to get background color and font from LookAndFeel; // otherwise, use dummy JLabel to get color and font. Color bg = UIManager.getColor("control"); Font font = UIManager.getFont("Label.font"); if (bg == null || font == null) { final JLabel dummy = new JLabel(); if (bg == null) bg = dummy.getBackground(); if (font == null) font = dummy.getFont(); } l.setBackground(bg); ((HTMLEditorKit) l.getEditorKit()).getStyleSheet().addRule( "body { font: " + font.getFamily() + " " + font.getSize() + "pt }"); l.addHyperlinkListener(BrowserSupport.getListener()); // FIXME: use MigLayout for this! // this is necessary to get proper vertical alignment final JPanel p = new JPanel(new GridBagLayout()); final GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.HORIZONTAL; c.anchor = GridBagConstraints.CENTER; p.add(l, c); moduleView.add(p, "quickStart"); //NON-NLS modulePanelLayout.show( moduleView, getModuleCount() == 0 ? "quickStart" : "modules"); moduleControls.add(moduleView, BorderLayout.CENTER); moduleControls.setBorder(new TitledBorder( Resources.getString("ModuleManager.recent_modules"))); add(moduleControls); // build server status controls final ServerStatusView serverStatusControls = new ServerStatusView(new CgiServerStatus()); serverStatusControls.setBorder( new TitledBorder(Resources.getString("Chat.server_status"))); splitPane = new SplitPane( SplitPane.HORIZONTAL_SPLIT, moduleControls, serverStatusControls ); // show the server status controls according to the prefs splitPane.setRightVisible(serverStatusConfig.booleanValue()); splitPane.setResizeWeight(1.0); splitPane.setDividerLocation(getPreferredDividerLocation()); splitPane.addPropertyChangeListener( "dividerLocation", e -> setPreferredDividerLocation((Integer) e.getNewValue()) ); add(splitPane); final Rectangle r = SwingUtils.getScreenBounds(this); serverStatusControls.setPreferredSize( new Dimension((int) (r.width / 3.5), 0)); setSize(3 * r.width / 4, 3 * r.height / 4); // Save/load the window position and size in prefs final PositionOption option = new PositionOption(PositionOption.key + "ModuleManager", this); //NON-NLS Prefs.getGlobalPrefs().addOption(option); } public void setWaitCursor(boolean wait) { setCursor(Cursor.getPredefinedCursor( wait ? Cursor.WAIT_CURSOR : Cursor.DEFAULT_CURSOR )); } protected void setPreferredDividerLocation(int i) { dividerLocationConfig.setValue(i); } protected int getPreferredDividerLocation() { return dividerLocationConfig.getIntValue(500); } // Show/Hide the two 'developer' columns depending on the pref value private void updateColumnDisplay() { final boolean showDeveloperInfo = (Boolean) Prefs.getGlobalPrefs().getValue(DEVELOPER_INFO_KEY); final TableColumnModel model = tree.getColumnModel(); if (showDeveloperInfo) { if (model.getColumnCount() < COLUMNS) { model.addColumn(columns[VASSAL_COLUMN]); model.addColumn(columns[SAVED_COLUMN]); } } else { model.removeColumn(columns[VASSAL_COLUMN]); model.removeColumn(columns[SAVED_COLUMN]); } } protected void buildTree() { final List<ModuleInfo> moduleList = new ArrayList<>(); final List<String> missingModules = new ArrayList<>(); // RecentModules key was used through 3.5.1, but 3.2 can't read the // buildFile.xml for 3.5+ modules. Hence we've switched to the Modules // key, but still collect whatever is in RecentModules for compatibility. recentModuleConfig = new StringArrayConfigurer("RecentModules", null); //NON-NLS Prefs.getGlobalPrefs().addOption(null, recentModuleConfig); moduleConfig = new StringArrayConfigurer("Modules", null); //NON-NLS Prefs.getGlobalPrefs().addOption(null, moduleConfig); Stream.concat( Arrays.stream(recentModuleConfig.getStringArray()), Arrays.stream(moduleConfig.getStringArray()) ).sorted().distinct().forEach(s -> { final ModuleInfo module = new ModuleInfo(s); if (module.getFile().exists() && module.isValid()) { moduleList.add(module); } else { missingModules.add(s); } }); for (final String s : missingModules) { logger.info(Resources.getString("ModuleManager.removing_module", s)); final ModuleInfo toRemove = moduleList .stream() .filter(moduleInfo -> moduleInfo.getModuleName().equals(s)) .findFirst() .orElse(null); moduleList.remove(toRemove); recentModuleConfig.removeValue(s); moduleConfig.removeValue(s); } moduleList.sort((a, b) -> { // sort module names in ascending order final int i = a.toString().compareTo(b.toString()); if (i == 0) { // sort versions in descending order return -VersionUtils.compareVersions(a.getVersion(), b.getVersion()); } else { return i; } }); rootNode = new MyTreeNode(new RootInfo()); for (final ModuleInfo moduleInfo : moduleList) { final MyTreeNode moduleNode = new MyTreeNode(moduleInfo); for (final ExtensionInfo ext : moduleInfo.getExtensions()) { final MyTreeNode extensionNode = new MyTreeNode(ext); moduleNode.add(extensionNode); } final ArrayList<File> missingFolders = new ArrayList<>(); for (final File f : moduleInfo.getFolders()) { if (f.exists() && f.isDirectory()) { final GameFolderInfo folderInfo = new GameFolderInfo(f, moduleInfo); final MyTreeNode folderNode = new MyTreeNode(folderInfo); moduleNode.add(folderNode); final ArrayList<File> l = new ArrayList<>(); final File[] files = f.listFiles(); if (files == null) continue; for (final File f1 : files) { if (f1.isFile()) { l.add(f1); } } Collections.sort(l); for (final File f2 : l) { final SaveFileInfo fileInfo = new SaveFileInfo(f2, folderInfo); if (fileInfo.isValid() && fileInfo.belongsToModule()) { final MyTreeNode fileNode = new MyTreeNode(fileInfo); folderNode.add(fileNode); } } } else { missingFolders.add(f); } } for (final File mf : missingFolders) { logger.info( Resources.getString("ModuleManager.removing_folder", mf.getPath())); moduleInfo.removeFolder(mf); } rootNode.add(moduleNode); } updateModuleList(); treeModel = new MyTreeTableModel(rootNode); tree = new MyTree(treeModel); tree.setRootVisible(false); tree.setEditable(false); tree.setTreeCellRenderer(new MyTreeCellRenderer()); tree.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2 && SwingUtils.isMainMouseButtonDown(e)) { final TreePath path = tree.getPathForLocation(e.getPoint().x, e.getPoint().y); // do nothing if not on a node, or if this node was expanded // or collapsed during the past doubleClickInterval milliseconds if (path == null || (lastExpansionPath == path && e.getWhen() - lastExpansionTime <= doubleClickInterval)) return; tree.activateOrExpandNode(path); } } @Override public void mousePressed(MouseEvent e) { maybePopup(e); } @Override public void mouseReleased(MouseEvent e) { maybePopup(e); } private void maybePopup(MouseEvent e) { if (e.isPopupTrigger()) { final TreePath path = tree.getPathForLocation(e.getPoint().x, e.getPoint().y); if (path == null) return; final int row = tree.getRowForPath(path); if (row >= 0) { selectedNode = (MyTreeNode) path.getLastPathComponent(); tree.clearSelection(); tree.addRowSelectionInterval(row, row); final AbstractInfo target = (AbstractInfo) selectedNode.getUserObject(); target.buildPopup(row).show(tree, e.getX(), e.getY()); } } } }); // We capture the time and location of clicks which would cause // expansion in order to distinguish these from clicks which // might launch a module or game. tree.addTreeWillExpandListener(new TreeWillExpandListener() { @Override public void treeWillCollapse(TreeExpansionEvent e) { lastExpansionTime = System.currentTimeMillis(); lastExpansionPath = e.getPath(); } @Override public void treeWillExpand(TreeExpansionEvent e) { lastExpansionTime = System.currentTimeMillis(); lastExpansionPath = e.getPath(); } }); // This ensures that double-clicks always start the module but // doesn't prevent single-clicks on the handles from working. tree.setToggleClickCount(3); tree.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); tree.addTreeSelectionListener(e -> { final MyTreeNode node = (MyTreeNode) e.getPath().getLastPathComponent(); final AbstractInfo target = node.getNodeInfo(); if (target instanceof ModuleInfo) { setSelectedModule(target.getFile()); } else { if (node.getParent() != null) { setSelectedModule(node.getParentModuleFile()); } } }); // Pref to hold the column widths. final StringConfigurer widthsConfig = new StringConfigurer(COLUMN_WIDTHS_KEY, null, ""); Prefs.getGlobalPrefs().addOption(null, widthsConfig); setColumnWidths(); // Set cell renderers for centered fields final TableColumnModel model = tree.getColumnModel(); final DefaultTableCellRenderer centerRenderer = new CenteringCellRenderer(); model.getColumn(VERSION_COLUMN).setCellRenderer(centerRenderer); model.getColumn(SAVED_COLUMN).setCellRenderer(centerRenderer); model.getColumn(VASSAL_COLUMN).setCellRenderer(centerRenderer); tree.getTableHeader().setAlignmentX(JComponent.CENTER_ALIGNMENT); // Save the columns so they can be removed/restored as needed for (int i = 0; i < COLUMNS; i++) { columns[i] = tree.getColumnModel().getColumn(i); } // Show/hide the developer columns updateColumnDisplay(); } // Set the preferred widths of the columns based on the recorded preference // All 5 columns are guaranteed to exist at this point. private void setColumnWidths() { final String widths = Prefs.getGlobalPrefs().getValue(COLUMN_WIDTHS_KEY).toString(); final SequenceEncoder.Decoder sd = new SequenceEncoder.Decoder(widths, ','); final TableColumnModel model = tree.getColumnModel(); model.getColumn(0).setPreferredWidth(sd.nextInt(250)); model.getColumn(0).setMinWidth(200); model.getColumn(1).setPreferredWidth(sd.nextInt(100)); model.getColumn(1).setMinWidth(100); model.getColumn(2).setPreferredWidth(sd.nextInt(500)); model.getColumn(2).setMinWidth(200); model.getColumn(3).setPreferredWidth(sd.nextInt(100)); model.getColumn(3).setMinWidth(100); model.getColumn(4).setPreferredWidth(sd.nextInt(100)); model.getColumn(4).setMinWidth(100); } // Save the current column widths in the preference // The Developer columns may not exist at this point. private void saveColumnWidths() { final SequenceEncoder se = new SequenceEncoder(','); final TableColumnModel model = tree.getColumnModel(); for (int i = 0; i < model.getColumnCount(); i++) { se.append(model.getColumn(i).getWidth()); } Prefs.getGlobalPrefs().setValue(COLUMN_WIDTHS_KEY, se.toString()); } public void updateRequest(File f) { SwingUtilities.invokeLater(() -> update(f)); } public void update(File f) { final AbstractMetaData data = MetaDataFactory.buildMetaData(f); if (data instanceof ModuleMetaData) { // Module. // If we already have this module, refresh it, otherwise add it. final MyTreeNode moduleNode = rootNode.findNode(f); if (moduleNode == null) { addModule(f); } else { moduleNode.refresh(); } } else if (data instanceof ExtensionMetaData) { // Extension. // Check if it has been saved into one of the extension directories // for any module we already know of. Refresh the module for (int i = 0; i < rootNode.getChildCount(); i++) { final MyTreeNode moduleNode = rootNode.getChild(i); final ModuleInfo moduleInfo = (ModuleInfo) moduleNode.getNodeInfo(); for (final ExtensionInfo ext : moduleInfo.getExtensions()) { if (ext.getFile().equals(f)) { moduleNode.refresh(); return; } } } } else if (data instanceof SaveMetaData) { // Save Game or Log file. // If the parent of the save file is already recorded as a Game Folder, // pass the file off to the Game Folder to handle. Otherwise, ignore it. for (int i = 0; i < rootNode.getChildCount(); i++) { final MyTreeNode moduleNode = rootNode.getChild(i); final MyTreeNode folderNode = moduleNode.findNode(f.getParentFile()); if (folderNode != null && folderNode.getNodeInfo() instanceof GameFolderInfo) { ((GameFolderInfo) folderNode.getNodeInfo()).update(f); return; } } } tree.repaint(); } /** * Return the number of Modules added to the Module Manager * * @return Number of modules */ private int getModuleCount() { return rootNode.getChildCount(); } public File getSelectedModule() { return selectedModule; } private void setSelectedModule(File selectedModule) { this.selectedModule = selectedModule; } public void addModule(File f) { if (!rootNode.contains(f)) { final ModuleInfo moduleInfo = new ModuleInfo(f); if (moduleInfo.isValid()) { final MyTreeNode moduleNode = new MyTreeNode(moduleInfo); treeModel.insertNodeInto(moduleNode, rootNode, rootNode.findInsertIndex(moduleInfo)); for (final ExtensionInfo ext : moduleInfo.getExtensions()) { final MyTreeNode extensionNode = new MyTreeNode(ext); treeModel.insertNodeInto(extensionNode, moduleNode, moduleNode.findInsertIndex(ext)); } updateModuleList(); } } } public void removeModule(File f) { final MyTreeNode moduleNode = rootNode.findNode(f); treeModel.removeNodeFromParent(moduleNode); updateModuleList(); } public File getModuleByName(String name) { if (name == null) return null; for (int i = 0; i < rootNode.getChildCount(); i++) { final ModuleInfo module = (ModuleInfo) rootNode.getChild(i).getNodeInfo(); if (name.equals(module.getModuleName())) return module.getFile(); } return null; } private void updateModuleList() { final List<String> l = new ArrayList<>(); for (int i = 0; i < rootNode.getChildCount(); i++) { final ModuleInfo module = (ModuleInfo) (rootNode.getChild(i)).getNodeInfo(); l.add(module.encode()); } recentModuleConfig.setValue(l.toArray(new String[0])); moduleConfig.setValue(l.toArray(new String[0])); modulePanelLayout.show( moduleView, getModuleCount() == 0 ? "quickStart" : "modules"); } private static class MyTreeTableModel extends DefaultTreeTableModel { public MyTreeTableModel(MyTreeNode rootNode) { super(rootNode); columnHeadings[KEY_COLUMN] = Resources.getString("ModuleManager.module"); columnHeadings[VERSION_COLUMN] = Resources.getString("ModuleManager.version"); columnHeadings[VASSAL_COLUMN] = Resources.getString("ModuleManager.created_by"); columnHeadings[SPARE_COLUMN] = Resources.getString("ModuleManager.description"); columnHeadings[SAVED_COLUMN] = Resources.getString("ModuleManager.last_saved"); } @Override public int getColumnCount() { return COLUMNS; } @Override public String getColumnName(int col) { return columnHeadings[col]; } @Override public Object getValueAt(Object node, int column) { return ((MyTreeNode) node).getValueAt(column); } } private static class MyTree extends JXTreeTable { private static final long serialVersionUID = 1L; public MyTree(MyTreeTableModel treeModel) { super(treeModel); createKeyBindings(this); } public void activateOrExpandNode(TreePath path) { final ModuleManagerWindow mmw = ModuleManagerWindow.getInstance(); mmw.selectedNode = (MyTreeNode) path.getLastPathComponent(); final AbstractInfo target = (AbstractInfo) mmw.selectedNode.getUserObject(); final int row = mmw.tree.getRowForPath(path); if (row < 0) return; // launch module or load save, otherwise expand or collapse node if (target instanceof ModuleInfo) { final ModuleInfo modInfo = (ModuleInfo) target; if (modInfo.isModuleTooNew()) { ErrorDialog.show( "Error.module_too_new", modInfo.getFile().getPath(), modInfo.getVassalVersion(), Info.getVersion() ); return; } else { ((ModuleInfo) target).play(); } } else if (target instanceof SaveFileInfo) { ((SaveFileInfo) target).play(); } else if (isExpanded(row)) { collapseRow(row); } else { expandRow(row); } } private void createKeyBindings(JTable table) { table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "Enter"); table.getActionMap().put("Enter", new AbstractAction() { @Override public void actionPerformed(ActionEvent ae) { //do something meaningful on JTable enter pressed final MyTree tree = ModuleManagerWindow.getInstance().tree; final int row = tree.getSelectedRow(); final TreePath path = tree.getPathForRow(row); if (path != null) { tree.activateOrExpandNode(path); } } }); } // FIXME: Where's the rest of the comment??? /** * There appears to be a bug/strange interaction between JXTreetable and the ComponentSplitter * when the Component */ @Override public String getToolTipText(MouseEvent event) { if (getComponentAt(event.getPoint().x, event.getPoint().y) == null) return null; return super.getToolTipText(event); } } /** * Custom Tree cell renderer:- * - Add file name as tooltip * - Handle expanded display (some nodes use the same icon for expanded/unexpanded) * - Gray out inactive extensions * - Gray out Save Games that belong to other modules */ private static class MyTreeCellRenderer extends DefaultTreeCellRenderer { private static final long serialVersionUID = 1L; @Override public Component getTreeCellRendererComponent( JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { super.getTreeCellRendererComponent( tree, value, selected, expanded, leaf, row, hasFocus); final AbstractInfo info = ((MyTreeNode) value).getNodeInfo(); setText(info.toString()); setToolTipText(info.getToolTipText()); setIcon(info.getIcon(expanded)); setForeground(info.getTreeCellFgColor()); return this; } } private static class CenteringCellRenderer extends DefaultTableCellRenderer { private static final long serialVersionUID = 1L; public CenteringCellRenderer() { super(); this.setHorizontalAlignment(CENTER); } @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); return this; } } private static class MyTreeNode extends DefaultMutableTreeTableNode { public MyTreeNode(AbstractInfo nodeInfo) { super(nodeInfo); nodeInfo.setTreeNode(this); } public AbstractInfo getNodeInfo() { return (AbstractInfo) getUserObject(); } public File getFile() { return getNodeInfo().getFile(); } public void refresh() { getNodeInfo().refresh(); } @Override public void setValueAt(Object aValue, int column) { } @Override public Object getValueAt(int column) { return getNodeInfo().getValueAt(column); } public MyTreeNode getChild(int index) { return (MyTreeNode) super.getChildAt(index); } public MyTreeNode findNode(File f) { for (int i = 0; i < getChildCount(); i++) { final MyTreeNode moduleNode = getChild(i); // NB: we canonicalize because File.equals() does not // always return true when one File is a relative path. try { f = f.getCanonicalFile(); } catch (IOException e) { f = f.getAbsoluteFile(); } if (f.equals(moduleNode.getNodeInfo().getFile())) { return moduleNode; } } return null; } public boolean contains(File f) { return findNode(f) != null; } public int findInsertIndex(AbstractInfo info) { for (int i = 0; i < getChildCount(); i++) { final MyTreeNode childNode = getChild(i); if (childNode.getNodeInfo().compareTo(info) >= 0) { return i; } } return getChildCount(); } /** * Return the Module node enclosing this node * * @return Parent Tree Node */ public MyTreeNode getParentModuleNode() { final AbstractInfo info = getNodeInfo(); if (info instanceof RootInfo) { return null; } else if (info instanceof ModuleInfo) { return this; } else if (getParent() == null) { return null; } else { return ((MyTreeNode) getParent()).getParentModuleNode(); } } /** * Return the Module file of the Module node enclosing this node * * @return Module File */ public File getParentModuleFile() { final MyTreeNode parentNode = getParentModuleNode(); return parentNode == null ? null : parentNode.getFile(); } } private abstract class AbstractInfo implements Comparable<AbstractInfo> { protected File file; protected Icon openIcon; protected Icon closedIcon; protected boolean valid = true; protected String error = ""; protected MyTreeNode node; public AbstractInfo(File f, Icon open, Icon closed) { setFile(f); setIcon(open, closed); } public AbstractInfo(File f, Icon i) { this (f, i, i); } public AbstractInfo(File f) { this(f, null); } public AbstractInfo() { } @Override public String toString() { return file == null ? "" : file.getName(); } public File getFile() { return file; } public void setFile(File f) { if (f == null) return; try { file = f.getCanonicalFile(); } catch (IOException e) { file = f.getAbsoluteFile(); } } public String getToolTipText() { if (file == null) { return ""; } else { return file.getPath(); } } @Override public int compareTo(AbstractInfo info) { return getSortKey().compareTo(info.getSortKey()); } public JPopupMenu buildPopup(int row) { return null; } public Icon getIcon(boolean expanded) { return expanded ? openIcon : closedIcon; } public void setIcon(Icon i) { setIcon(i, i); } public void setIcon(Icon open, Icon closed) { openIcon = open; closedIcon = closed; } public String getValueAt(int column) { switch (column) { case KEY_COLUMN: return toString(); case VERSION_COLUMN: return getVersion(); case VASSAL_COLUMN: return getVassalVersion(); case SAVED_COLUMN: return getLastSaved(); default: return null; } } public void setValid(boolean b) { valid = b; } public boolean isValid() { return valid; } public void setError(String s) { error = s; } public String getError() { return error; } public String getVersion() { return ""; } public String getVassalVersion() { return ""; } public String getComments() { return ""; } public String getLastSaved() { return ""; } public MyTreeNode getTreeNode() { return node; } public void setTreeNode(MyTreeNode n) { node = n; } /** * Return a String used to sort different types of AbstractInfo's that are * children of the same parent. * * @return sort key */ public abstract String getSortKey(); /** * Return the color of the text used to display the name in column 1. * Over-ride this to change color depending on item state. * * @return cell text color */ public Color getTreeCellFgColor() { return Color.black; } /** * Refresh yourself and any children */ public void refresh() { refreshChildren(); } public void refreshChildren() { for (int i = 0; i < node.getChildCount(); i++) { (node.getChild(i)).refresh(); } } } private class RootInfo extends AbstractInfo { public RootInfo() { super(null); } @Override public String getSortKey() { return ""; } } public class ModuleInfo extends AbstractInfo { private final ExtensionsManager extMgr; private final SortedSet<File> gameFolders = new TreeSet<>(); private ModuleMetaData metadata; private final Action newExtensionAction = new NewExtensionLaunchAction(ModuleManagerWindow.this); private final AbstractAction addExtensionAction = new AbstractAction( Resources.getString("ModuleManager.add_extension")) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { final FileChooser fc = FileChooser.createFileChooser( ModuleManagerWindow.this, (DirectoryConfigurer) Prefs.getGlobalPrefs().getOption(Prefs.MODULES_DIR_KEY)); if (fc.showOpenDialog() == FileChooser.APPROVE_OPTION) { final File selectedFile = fc.getSelectedFile(); final ExtensionInfo testExtInfo = new ExtensionInfo(selectedFile, true, null); if (testExtInfo.isValid()) { final File f = getExtensionsManager().setActive(fc.getSelectedFile(), true); final MyTreeNode moduleNode = rootNode.findNode(selectedModule); final ExtensionInfo extInfo = new ExtensionInfo(f, true, (ModuleInfo) moduleNode.getNodeInfo()); if (extInfo.isValid()) { final MyTreeNode extNode = new MyTreeNode(extInfo); treeModel.insertNodeInto(extNode, moduleNode, moduleNode.findInsertIndex(extInfo)); } } else { JOptionPane.showMessageDialog(ModuleManagerWindow.this, testExtInfo.getError(), null, JOptionPane.ERROR_MESSAGE); } } } }; private final AbstractAction addFolderAction = new AbstractAction( Resources.getString("ModuleManager.add_save_game_folder")) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { final FileChooser fc = FileChooser.createFileChooser( ModuleManagerWindow.this, (DirectoryConfigurer) Prefs.getGlobalPrefs().getOption(Prefs.MODULES_DIR_KEY), FileChooser.DIRECTORIES_ONLY); if (fc.showOpenDialog() == FileChooser.APPROVE_OPTION) { addFolder(fc.getSelectedFile()); } } }; public ModuleInfo(File f) { super(f, moduleIcon); extMgr = new ExtensionsManager(f); loadMetaData(); } protected void loadMetaData() { final AbstractMetaData data = MetaDataFactory.buildMetaData(file); if (data instanceof ModuleMetaData) { setValid(true); metadata = (ModuleMetaData) data; } else { setValid(false); } } protected boolean isModuleTooNew() { return metadata != null && Info.isModuleTooNew(metadata.getVassalVersion()); } @Override public String getVassalVersion() { return metadata == null ? "" : metadata.getVassalVersion(); } @Override public String getLastSaved() { return metadata == null ? "" : metadata.formatLastSaved(); } /** * Initialise ModuleInfo based on a saved preference string. * See encode(). * * @param s Preference String */ public ModuleInfo(String s) { final SequenceEncoder.Decoder sd = new SequenceEncoder.Decoder(s, ';'); setFile(new File(sd.nextToken())); setIcon(moduleIcon); loadMetaData(); extMgr = new ExtensionsManager(getFile()); while (sd.hasMoreTokens()) { gameFolders.add(new File(sd.nextToken())); } } /** * Refresh this module and all children */ @Override public void refresh() { loadMetaData(); // Remove any missing children final MyTreeNode[] nodes = new MyTreeNode[getTreeNode().getChildCount()]; for (int i = 0; i < getTreeNode().getChildCount(); i++) { nodes[i] = getTreeNode().getChild(i); } for (final MyTreeNode myTreeNode : nodes) { if (!myTreeNode.getFile().exists()) { treeModel.removeNodeFromParent(myTreeNode); } } // Refresh or add any existing children for (final ExtensionInfo ext : getExtensions()) { MyTreeNode extNode = getTreeNode().findNode(ext.getFile()); if (extNode == null) { if (ext.isValid()) { extNode = new MyTreeNode(ext); treeModel.insertNodeInto(extNode, getTreeNode(), getTreeNode().findInsertIndex(ext)); } } else { extNode.refresh(); } } } /** * Encode any information which needs to be recorded in the Preference entry for this module:- * - Path to Module File * - Paths to any child Save Game Folders * * @return encoded data */ public String encode() { final SequenceEncoder se = new SequenceEncoder(file.getPath(), ';'); for (final File f : gameFolders) { se.append(f.getPath()); } return se.getValue(); } public ExtensionsManager getExtensionsManager() { return extMgr; } public void addFolder(File f) { // try to create the directory if it doesn't exist if (!f.exists() && !f.mkdirs()) { JOptionPane.showMessageDialog( ModuleManagerWindow.this, Resources.getString("Install.error_unable_to_create", f.getPath()), "Error", //NON-NLS JOptionPane.ERROR_MESSAGE ); return; } gameFolders.add(f); final MyTreeNode moduleNode = rootNode.findNode(selectedModule); final GameFolderInfo folderInfo = new GameFolderInfo(f, (ModuleInfo) moduleNode.getNodeInfo()); final MyTreeNode folderNode = new MyTreeNode(folderInfo); final int idx = moduleNode.findInsertIndex(folderInfo); treeModel.insertNodeInto(folderNode, moduleNode, idx); for (final File file : f.listFiles()) { if (file.isFile()) { final SaveFileInfo fileInfo = new SaveFileInfo(file, folderInfo); if (fileInfo.isValid() && fileInfo.belongsToModule()) { final MyTreeNode fileNode = new MyTreeNode(fileInfo); treeModel.insertNodeInto(fileNode, folderNode, folderNode.findInsertIndex(fileInfo)); } } } updateModuleList(); } public void removeFolder(File f) { gameFolders.remove(f); } public SortedSet<File> getFolders() { return gameFolders; } public List<ExtensionInfo> getExtensions() { final List<ExtensionInfo> l = new ArrayList<>(); for (final File f : extMgr.getActiveExtensions()) { l.add(new ExtensionInfo(f, true, this)); } for (final File f : extMgr.getInactiveExtensions()) { l.add(new ExtensionInfo(f, false, this)); } Collections.sort(l); return l; } public void play() { new Player.LaunchAction( ModuleManagerWindow.this, file).actionPerformed(null); } @Override public JPopupMenu buildPopup(int row) { final boolean tooNew = Info.isModuleTooNew(metadata.getVassalVersion()); final JPopupMenu m = new JPopupMenu(); final Action playAction = new Player.LaunchAction(ModuleManagerWindow.this, file); playAction.setEnabled(playAction.isEnabled() && !tooNew); m.add(playAction); final Action editAction = new Editor.ListLaunchAction(ModuleManagerWindow.this, file); editAction.setEnabled(editAction.isEnabled() && !tooNew); m.add(editAction); m.add(new AbstractAction(Resources.getString("General.remove")) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { removeModule(file); cleanupTileCache(); } }); m.addSeparator(); m.add(addFolderAction); addFolderAction.setEnabled(!tooNew); m.addSeparator(); m.add(newExtensionAction); newExtensionAction.setEnabled(!tooNew); m.add(addExtensionAction); addExtensionAction.setEnabled(!tooNew); return m; } public void cleanupTileCache() { final String hstr = DigestUtils.sha1Hex( metadata.getName() + "_" + metadata.getVersion() ); final File tdir = new File(Info.getConfDir(), "tiles/" + hstr); if (tdir.exists()) { try { FileUtils.forceDelete(tdir); } catch (IOException e) { WriteErrorDialog.error(e, tdir); } } } /* * Is the module currently being Played or Edited? */ public boolean isInUse() { return AbstractLaunchAction.isInUse(file) || AbstractLaunchAction.isEditing(file); } @Override public String getVersion() { return metadata.getVersion(); } public String getLocalizedDescription() { return metadata.getLocalizedDescription(); } public String getModuleName() { return metadata.getName(); } @Override public String toString() { return metadata.getLocalizedName(); } @Override public String getValueAt(int column) { return column == SPARE_COLUMN ? getLocalizedDescription() : super.getValueAt(column); } @Override public String getSortKey() { return metadata == null ? "" : metadata.getLocalizedName(); } @Override public Color getTreeCellFgColor() { return Info.isModuleTooNew(getVassalVersion()) ? Color.GRAY : Color.BLACK; } } private class ExtensionInfo extends AbstractInfo { private boolean active; private final ModuleInfo moduleInfo; private ExtensionMetaData metadata; public ExtensionInfo(File file, boolean active, ModuleInfo module) { super(file, active ? activeExtensionIcon : inactiveExtensionIcon); this.active = active; moduleInfo = module; loadMetaData(); } protected void loadMetaData() { final AbstractMetaData data = MetaDataFactory.buildMetaData(file); if (data instanceof ExtensionMetaData) { setValid(true); metadata = (ExtensionMetaData) data; } else { setError(Resources.getString("ModuleManager.invalid_extension")); setValid(false); } } @Override public void refresh() { loadMetaData(); setActive(getExtensionsManager().isExtensionActive(getFile())); tree.repaint(); } public boolean isActive() { return active; } public void setActive(boolean b) { active = b; setIcon(active ? activeExtensionIcon : inactiveExtensionIcon); } @Override public String getVersion() { return metadata == null ? "" : metadata.getVersion(); } @Override public String getVassalVersion() { return metadata == null ? "" : metadata.getVassalVersion(); } @Override public String getLastSaved() { return metadata == null ? "" : metadata.formatLastSaved(); } public String getDescription() { return metadata == null ? "" : metadata.getDescription(); } public ExtensionsManager getExtensionsManager() { return moduleInfo == null ? null : moduleInfo.getExtensionsManager(); } @Override public String toString() { String s = getFile().getName(); String st = ""; if (metadata == null) { st = Resources.getString("ModuleManager.invalid"); } if (!active) { st += st.length() > 0 ? "," : ""; st += Resources.getString("ModuleManager.inactive"); } if (st.length() > 0) { s += " (" + st + ")"; } return s; } @Override public JPopupMenu buildPopup(int row) { final JPopupMenu m = new JPopupMenu(); final boolean tooNew = Info.isModuleTooNew(metadata.getVassalVersion()); final Action activateAction = new ActivateExtensionAction( Resources.getString(isActive() ? "ModuleManager.deactivate" : "ModuleManager.activate") ); activateAction.setEnabled(!tooNew); m.add(activateAction); final Action editAction = new EditExtensionLaunchAction( ModuleManagerWindow.this, getFile(), getSelectedModule()); editAction.setEnabled(!tooNew); m.add(editAction); return m; } @Override public Color getTreeCellFgColor() { // FIXME: should get colors from LAF if (isActive()) { return metadata == null ? Color.red : Color.black; } else { return metadata == null ? Color.pink : Color.gray; } } @Override public String getValueAt(int column) { return column == SPARE_COLUMN ? getDescription() : super.getValueAt(column); } /* * Is the extension, or its owning module currently being Played or Edited? */ public boolean isInUse() { return AbstractLaunchAction.isInUse(file) || AbstractLaunchAction.isEditing(file); } private class ActivateExtensionAction extends AbstractAction { private static final long serialVersionUID = 1L; public ActivateExtensionAction(String s) { super(s); setEnabled(!isInUse() && ! moduleInfo.isInUse()); } @Override public void actionPerformed(ActionEvent evt) { setFile(getExtensionsManager().setActive(getFile(), !isActive())); setActive(getExtensionsManager().isExtensionActive(getFile())); final TreePath path = tree.getPathForRow(tree.getSelectedRow()); final MyTreeNode extNode = (MyTreeNode) path.getLastPathComponent(); treeModel.setValueAt("", extNode, 0); } } /** * Sort Extensions by File Name */ @Override public String getSortKey() { return getFile().getName(); } } private class GameFolderInfo extends AbstractInfo { protected String comment; protected ModuleInfo moduleInfo; protected long dtm; public GameFolderInfo(File f, ModuleInfo m) { super(f, openGameFolderIcon, closedGameFolderIcon); moduleInfo = m; dtm = f.lastModified(); } @Override public JPopupMenu buildPopup(int row) { final boolean tooNew = Info.isModuleTooNew(moduleInfo.getVassalVersion()); final JPopupMenu m = new JPopupMenu(); final Action refreshAction = new AbstractAction(Resources.getString("General.refresh")) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { refresh(); } }; refreshAction.setEnabled(!tooNew); m.add(refreshAction); m.addSeparator(); final Action removeAction = new AbstractAction(Resources.getString("General.remove")) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { final MyTreeNode moduleNode = rootNode.findNode(moduleInfo.getFile()); final MyTreeNode folderNode = moduleNode.findNode(getFile()); treeModel.removeNodeFromParent(folderNode); moduleInfo.removeFolder(getFile()); updateModuleList(); } }; removeAction.setEnabled(!tooNew); m.add(removeAction); return m; } public ModuleInfo getModuleInfo() { return moduleInfo; } @Override public void refresh() { // Remove any files that no longer exist for (int i = getTreeNode().getChildCount() - 1; i >= 0; i final MyTreeNode fileNode = getTreeNode().getChild(i); final SaveFileInfo fileInfo = (SaveFileInfo) fileNode.getNodeInfo(); if (!fileInfo.getFile().exists()) { treeModel.removeNodeFromParent(fileNode); } } // Refresh any that are. Only include Save files belonging to this // module, or that are pre vassal 3.1 final File[] files = getFile().listFiles(); if (files == null) return; for (final File f : files) { final AbstractMetaData fdata = MetaDataFactory.buildMetaData(f); if (fdata != null) { if (fdata instanceof SaveMetaData) { final String moduleName = ((SaveMetaData) fdata).getModuleName(); if (moduleName == null || moduleName.length() == 0 || moduleName.equals(getModuleInfo().getModuleName())) { update(f); } } } } } /** * Update the display for the specified save File, or add it in if * we don't already know about it. * @param f Save File */ public void update(File f) { for (int i = 0; i < getTreeNode().getChildCount(); i++) { final SaveFileInfo fileInfo = (SaveFileInfo) (getTreeNode().getChild(i)).getNodeInfo(); if (fileInfo.getFile().equals(f)) { fileInfo.refresh(); return; } } final SaveFileInfo fileInfo = new SaveFileInfo(f, this); final MyTreeNode fileNode = new MyTreeNode(fileInfo); treeModel.insertNodeInto(fileNode, getTreeNode(), getTreeNode().findInsertIndex(fileInfo)); } /** * Force Game Folders to sort after extensions */ @Override public String getSortKey() { return "~~~" + getFile().getName(); } } private class SaveFileInfo extends AbstractInfo { protected GameFolderInfo folderInfo; // Owning Folder protected SaveMetaData metadata; // Save file metadata public SaveFileInfo(File f, GameFolderInfo folder) { super(f, fileIcon); folderInfo = folder; loadMetaData(); } protected void loadMetaData() { final AbstractMetaData data = MetaDataFactory.buildMetaData(file); if (data instanceof SaveMetaData) { metadata = (SaveMetaData) data; setValid(true); } else { setValid(false); } } @Override public void refresh() { loadMetaData(); tree.repaint(); } @Override public JPopupMenu buildPopup(int row) { final boolean tooNew = Info.isModuleTooNew(metadata.getVassalVersion()); final JPopupMenu m = new JPopupMenu(); final Action launchAction = new Player.LaunchAction( ModuleManagerWindow.this, getModuleFile(), file ); launchAction.setEnabled(!tooNew); m.add(launchAction); return m; } protected File getModuleFile() { return folderInfo.getModuleInfo().getFile(); } public void play() { new Player.LaunchAction( ModuleManagerWindow.this, getModuleFile(), file).actionPerformed(null); } @Override public String getValueAt(int column) { return column == SPARE_COLUMN ? buildComments() : super.getValueAt(column); } private String buildComments() { String comments = ""; if (!belongsToModule()) { if (metadata != null && metadata.getModuleName().length() > 0) { comments = "[" + metadata.getModuleName() + "] "; } } comments += (metadata == null ? "" : metadata.getDescription()); return comments; } private boolean belongsToModule() { return metadata != null && (metadata.getModuleName().length() == 0 || folderInfo.getModuleInfo().getModuleName().equals( metadata.getModuleName())); } @Override public Color getTreeCellFgColor() { // FIXME: should get colors from LAF return belongsToModule() ? Color.black : Color.gray; } @Override public String getVersion() { return metadata == null ? "" : metadata.getModuleVersion(); } /** * Sort Save Files by file name */ @Override public String getSortKey() { return this.getFile().getName(); } } /** * Action to create a New Extension and edit it in another process. */ private class NewExtensionLaunchAction extends AbstractLaunchAction { private static final long serialVersionUID = 1L; public NewExtensionLaunchAction(Frame frame) { super(Resources.getString("ModuleManager.new_extension"), frame, Editor.class.getName(), new LaunchRequest(LaunchRequest.Mode.NEW_EXT) ); } @Override public void actionPerformed(ActionEvent e) { lr.module = getSelectedModule(); // register that this module is being used if (isEditing(lr.module)) return; incrementUsed(lr.module); super.actionPerformed(e); } @Override protected LaunchTask getLaunchTask() { return new LaunchTask() { @Override protected void done() { super.done(); // reduce the using count decrementUsed(lr.module); } }; } } /** * Action to Edit an Extension in another process */ private static class EditExtensionLaunchAction extends AbstractLaunchAction { private static final long serialVersionUID = 1L; public EditExtensionLaunchAction(Frame frame, File extension, File module) { super(Resources.getString("Editor.edit_extension"), frame, Editor.class.getName(), new LaunchRequest(LaunchRequest.Mode.EDIT_EXT, module, extension) ); setEnabled(!isInUse(module) && !isInUse(extension)); } @Override public void actionPerformed(ActionEvent e) { // check that neither this module nor this extension is being edited if (isInUse(lr.module) || isInUse(lr.extension)) return; // register that this module is being used incrementUsed(lr.module); // register that this extension is being edited markEditing(lr.module); super.actionPerformed(e); setEnabled(false); } @Override protected void addFileFilters(FileChooser fc) { fc.addChoosableFileFilter(new ModuleExtensionFileFilter()); } @Override protected LaunchTask getLaunchTask() { return new LaunchTask() { @Override protected void done() { super.done(); // reduce the using count for module decrementUsed(lr.module); // register that this extension is done being edited unmarkEditing(lr.extension); setEnabled(true); } }; } } private static class ShowErrorLogAction extends AbstractAction { private static final long serialVersionUID = 1L; private final Frame frame; public ShowErrorLogAction(Frame frame) { super(Resources.getString("Help.error_log")); this.frame = frame; } @Override public void actionPerformed(ActionEvent e) { // FIXME: don't create a new one each time! final File logfile = Info.getErrorLogPath(); final LogPane lp = new LogPane(logfile); // FIXME: this should have its own key. Probably keys should be renamed // to reflect what they are labeling, e.g., Help.show_error_log_menu_item, // Help.error_log_dialog_title. final JDialog d = new JDialog(frame, Resources.getString("Help.error_log")); d.setLayout(new MigLayout("insets 0")); //NON-NLS d.add(new JScrollPane(lp), "grow, push, w 500, h 600"); //NON-NLS d.setLocationRelativeTo(frame); d.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); SwingUtils.repack(d); d.setVisible(true); } } }
package pzhao.com; import java.util.Iterator; public class Stack<Item>implements Iterable<Item> { private Item[] items; private int N; private int top; public Stack(){ this(10); } @SuppressWarnings("unchecked") public Stack(int n){ this.N=n; items=(Item[])new Object[N]; } public void push(Item item){ items[top++]=item; } public Item pop(){ if(top<=0)return null; return items[--top]; } public Item peek(){ return items[top-1]; } public String toString(){ StringBuilder sb=new StringBuilder(); for(int i=top-1;i>=0;i sb.append(items[i]+" "); } return sb.toString(); } @Override public Iterator<Item> iterator() { // TODO Auto-generated method stub return new Iterator<Item>() { @Override public boolean hasNext() { // TODO Auto-generated method stub return top>=0; } @Override public Item next() { // TODO Auto-generated method stub return pop(); } }; } public static void main(String[] args){ Stack<Integer> stack=new Stack<>(10); for(int i=0;i<10;i++){ stack.push(i); } // for(int i=0;i<10;i++){ // System.out.print(stack.pop()+" "); System.out.println(stack); //System.out.print(stack.peek()+" "); Iterator<Integer>iterator=stack.iterator(); while(iterator.hasNext()){ // System.out.print(iterator.next()+" "); } } }
package com.backendless; import com.backendless.async.callback.AsyncCallback; import com.backendless.core.responder.AdaptingResponder; import com.backendless.core.responder.policy.PoJoAdaptingPolicy; import com.backendless.exceptions.BackendlessException; import com.backendless.exceptions.BackendlessFault; import com.backendless.exceptions.ExceptionMessage; import com.backendless.persistence.BackendlessDataQuery; import com.backendless.persistence.QueryOptions; import com.backendless.property.ObjectProperty; import com.backendless.utils.ResponderHelper; import weborb.types.Types; import weborb.writer.IObjectSubstitutor; import weborb.writer.MessageWriter; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.*; public final class Persistence { private final static String PERSISTENCE_MANAGER_SERVER_ALIAS = "com.backendless.services.persistence.internal.PersistenceService"; private final static String DEFAULT_OBJECT_ID_GETTER = "getObjectId"; public final static String DEFAULT_OBJECT_ID_FIELD = "objectId"; public final static String DEFAULT_CREATED_FIELD = "created"; public final static String DEFAULT_UPDATED_FIELD = "updated"; public final static String DEFAULT_META_FIELD = "__meta"; public final static String LOAD_ALL_RELATIONS = "*"; public final static DataPermission Permissions = new DataPermission(); private static final Persistence instance = new Persistence(); private static final Class backendlessUserClass = BackendlessUser.class; static Persistence getInstance() { return instance; } private Persistence() { Types.addClientClassMapping( "com.backendless.services.persistence.BackendlessDataQuery", BackendlessDataQuery.class ); Types.addClientClassMapping( "com.backendless.services.persistence.BackendlessCollection", BackendlessCollection.class ); Types.addClientClassMapping( "com.backendless.services.persistence.ObjectProperty", ObjectProperty.class ); Types.addClientClassMapping( "com.backendless.services.persistence.QueryOptions", QueryOptions.class ); } public void mapTableToClass( String tableName, Class clazz ) { weborb.types.Types.addClientClassMapping( tableName, clazz ); } public <E> E save( final E entity ) throws BackendlessException { if( entity == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_ENTITY ); checkDeclaredType( entity.getClass() ); final Map serializedEntity = serializeToMap( entity ); MessageWriter.setObjectSubstitutor( new IObjectSubstitutor() { @Override public Object substitute( Object o ) { if( o == entity ) return serializedEntity; else return o; } } ); FootprintsManager.getInstance().Inner.putMissingPropsToEntityMap( entity, serializedEntity ); try { E newEntity = (E) Invoker.invokeSync( PERSISTENCE_MANAGER_SERVER_ALIAS, "save", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), getSimpleName( entity.getClass() ), serializedEntity }, ResponderHelper.getPOJOAdaptingResponder( entity.getClass() ) ); if( serializedEntity.get( Footprint.OBJECT_ID_FIELD_NAME ) == null ) { FootprintsManager.getInstance().Inner.duplicateFootprintForObject( entity, newEntity ); } else { FootprintsManager.getInstance().Inner.updateFootprintForObject( newEntity, entity ); } return newEntity; } finally { MessageWriter.setObjectSubstitutor( null ); } } public <E> void save( final E entity, final AsyncCallback<E> responder ) { try { if( entity == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_ENTITY ); checkDeclaredType( entity.getClass() ); final Map serializedEntity = serializeToMap( entity ); MessageWriter.setObjectSubstitutor( new IObjectSubstitutor() { @Override public Object substitute( Object o ) { if( o == entity ) return serializedEntity; else return o; } } ); FootprintsManager.getInstance().Inner.putMissingPropsToEntityMap( entity, serializedEntity ); AsyncCallback<E> callbackOverrider; if( serializedEntity.get( Footprint.OBJECT_ID_FIELD_NAME ) == null ) { callbackOverrider = new AsyncCallback<E>() { @Override public void handleResponse( E newEntity ) { MessageWriter.setObjectSubstitutor( null ); FootprintsManager.getInstance().Inner.duplicateFootprintForObject( entity, newEntity ); if( responder != null ) responder.handleResponse( newEntity ); } @Override public void handleFault( BackendlessFault fault ) { MessageWriter.setObjectSubstitutor( null ); if( responder != null ) responder.handleFault( fault ); } }; } else { callbackOverrider = new AsyncCallback<E>() { @Override public void handleResponse( E newEntity ) { FootprintsManager.getInstance().Inner.updateFootprintForObject( newEntity, entity ); if( responder != null ) responder.handleResponse( newEntity ); } @Override public void handleFault( BackendlessFault fault ) { if( responder != null ) responder.handleFault( fault ); } }; } Invoker.invokeAsync( PERSISTENCE_MANAGER_SERVER_ALIAS, "save", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), getSimpleName( entity.getClass() ), entity }, callbackOverrider, ResponderHelper.getPOJOAdaptingResponder( entity.getClass() ) ); } catch( Throwable e ) { if( responder != null ) responder.handleFault( new BackendlessFault( e ) ); } } private <E> E create( Class<E> aClass, Map entity ) throws BackendlessException { if( entity == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_ENTITY ); return (E) Invoker.invokeSync( PERSISTENCE_MANAGER_SERVER_ALIAS, "create", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), getSimpleName( aClass ), entity }, ResponderHelper.getPOJOAdaptingResponder( aClass ) ); } private <E> void create( final Class<E> aClass, final Map entity, final AsyncCallback<E> responder ) { try { if( entity == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_ENTITY ); Invoker.invokeAsync( PERSISTENCE_MANAGER_SERVER_ALIAS, "create", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), getSimpleName( aClass ), entity }, responder, ResponderHelper.getPOJOAdaptingResponder( aClass ) ); } catch( Throwable e ) { if( responder != null ) responder.handleFault( new BackendlessFault( e ) ); } } private <E> E update( Class<E> aClass, Map entity ) throws BackendlessException { if( entity == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_ENTITY ); return (E) Invoker.invokeSync( PERSISTENCE_MANAGER_SERVER_ALIAS, "update", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), getSimpleName( aClass ), entity }, ResponderHelper.getPOJOAdaptingResponder( aClass ) ); } private <E> void update( final Class<E> aClass, final Map entity, final AsyncCallback<E> responder ) { try { if( entity == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_ENTITY ); Invoker.invokeAsync( PERSISTENCE_MANAGER_SERVER_ALIAS, "update", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), getSimpleName( aClass ), entity }, responder, ResponderHelper.getPOJOAdaptingResponder( aClass ) ); } catch( Throwable e ) { if( responder != null ) responder.handleFault( new BackendlessFault( e ) ); } } protected <E> Long remove( final E entity ) throws BackendlessException { if( entity == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_ENTITY ); Object result = Invoker.invokeSync( PERSISTENCE_MANAGER_SERVER_ALIAS, "remove", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), getSimpleName( entity.getClass() ), entity } ); FootprintsManager.getInstance().Inner.removeFootprintForObject( entity ); return ((Number) result).longValue(); } protected <E> void remove( final E entity, final AsyncCallback<Long> responder ) { try { if( entity == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_ENTITY ); Invoker.invokeAsync( PERSISTENCE_MANAGER_SERVER_ALIAS, "remove", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), getSimpleName( entity.getClass() ), entity }, new AsyncCallback<Object>() { @Override public void handleResponse( Object response ) { FootprintsManager.getInstance().Inner.removeFootprintForObject( entity ); if( responder == null ) return; responder.handleResponse( ((Number) response).longValue() ); } @Override public void handleFault( BackendlessFault fault ) { if( responder != null ) responder.handleFault( fault ); } } ); } catch( Throwable e ) { if( responder != null ) responder.handleFault( new BackendlessFault( e ) ); } } protected <E> E findById( final Class<E> entity, final String id, final List<String> relations ) throws BackendlessException { if( entity == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_ENTITY_NAME ); if( id == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_ID ); return (E) Invoker.invokeSync( PERSISTENCE_MANAGER_SERVER_ALIAS, "findById", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), getSimpleName( entity ), id, relations }, ResponderHelper.getPOJOAdaptingResponder( entity ) ); } protected <E> E findById( final Class<E> entity, final String id, final List<String> relations, final int relationsDepth ) throws BackendlessException { if( entity == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_ENTITY_NAME ); if( id == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_ID ); return (E) Invoker.invokeSync( PERSISTENCE_MANAGER_SERVER_ALIAS, "findById", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), entity.getSimpleName(), id, relations, relationsDepth }, ResponderHelper.getPOJOAdaptingResponder( entity ) ); } protected <E> E findById( final E entity, List<String> relations, int relationsDepth ) { if( entity == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_ENTITY ); return Invoker.invokeSync( PERSISTENCE_MANAGER_SERVER_ALIAS, "findById", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), entity.getClass().getSimpleName(), entity, relations, relationsDepth }, ResponderHelper.getPOJOAdaptingResponder( entity.getClass() ) ); } protected <E> void findById( final Class<E> entity, final String id, final List<String> relations, AsyncCallback<E> responder ) { try { if( entity == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_ENTITY ); if( id == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_ID ); Invoker.invokeAsync( PERSISTENCE_MANAGER_SERVER_ALIAS, "findById", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), getSimpleName( entity ), id, relations }, responder, ResponderHelper.getPOJOAdaptingResponder( entity ) ); } catch( Throwable e ) { if( responder != null ) responder.handleFault( new BackendlessFault( e ) ); } } protected <E> void findById( final Class<E> entity, final String id, final List<String> relations, final int relationsDepth, AsyncCallback<E> responder ) { try { if( entity == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_ENTITY ); if( id == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_ID ); Invoker.invokeAsync( PERSISTENCE_MANAGER_SERVER_ALIAS, "findById", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), entity.getSimpleName(), id, relations, relationsDepth }, responder ); } catch( Throwable e ) { if( responder != null ) responder.handleFault( new BackendlessFault( e ) ); } } protected <E> void findById( E entity, List<String> relations, int relationsDepth, AsyncCallback<E> responder ) { try { if( entity == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_ENTITY ); Invoker.invokeAsync( PERSISTENCE_MANAGER_SERVER_ALIAS, "findById", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), entity.getClass().getSimpleName(), entity, relations, relationsDepth }, responder ); } catch( Throwable e ) { if( responder != null ) responder.handleFault( new BackendlessFault( e ) ); } } protected <E> void loadRelations( final E entity, final List<String> relations ) throws Exception { if( entity == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_ENTITY_NAME ); E loadedRelations = (E) Invoker.invokeSync( PERSISTENCE_MANAGER_SERVER_ALIAS, "loadRelations", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), getSimpleName( entity.getClass() ), entity, relations }, new AdaptingResponder<E>( (Class<E>) entity.getClass(), new PoJoAdaptingPolicy<E>() ) ); loadRelationsToEntity( entity, loadedRelations, relations ); } protected <E> void loadRelations( final E entity, final List<String> relations, final AsyncCallback<E> responder ) { try { if( entity == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_ENTITY ); Invoker.invokeAsync( PERSISTENCE_MANAGER_SERVER_ALIAS, "loadRelations", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), getSimpleName( entity.getClass() ), entity, relations }, new AsyncCallback<E>() { @Override public void handleResponse( E loadedRelations ) { try { loadRelationsToEntity( entity, loadedRelations, relations ); if( responder != null ) responder.handleResponse( entity ); } catch( Exception e ) { if( responder != null ) responder.handleFault( new BackendlessFault( e ) ); } } @Override public void handleFault( BackendlessFault fault ) { if( responder != null ) responder.handleFault( fault ); } }, new AdaptingResponder<E>( (Class<E>) entity.getClass(), new PoJoAdaptingPolicy<E>() ) ); } catch( Throwable e ) { if( responder != null ) responder.handleFault( new BackendlessFault( e ) ); } } private <E> void loadRelationsToEntity( E entity, E loadedRelations, List<String> relations ) throws IllegalAccessException { if( entity.getClass().equals( backendlessUserClass ) ) { BackendlessUser userWithRelations = (BackendlessUser) loadedRelations; BackendlessUser sourceUser = (BackendlessUser) entity; sourceUser.putProperties( userWithRelations.getProperties() ); } else { Field[] declaredFields = entity.getClass().getDeclaredFields(); for( Field declaredField : declaredFields ) { if( !relations.contains( declaredField.getName() ) ) continue; if( !declaredField.isAccessible() ) declaredField.setAccessible( true ); declaredField.set( entity, declaredField.get( loadedRelations ) ); } } } public List<ObjectProperty> describe( String classSimpleName ) throws BackendlessException { if( classSimpleName == null || classSimpleName.equals( "" ) ) throw new IllegalArgumentException( ExceptionMessage.NULL_ENTITY_NAME ); ObjectProperty[] response = Invoker.invokeSync( PERSISTENCE_MANAGER_SERVER_ALIAS, "describe", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), classSimpleName } ); return Arrays.asList( response ); } public void describe( String classSimpleName, final AsyncCallback<List<ObjectProperty>> responder ) { try { if( classSimpleName == null || classSimpleName.equals( "" ) ) throw new IllegalArgumentException( ExceptionMessage.NULL_ENTITY_NAME ); Invoker.invokeAsync( PERSISTENCE_MANAGER_SERVER_ALIAS, "describe", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), classSimpleName }, new AsyncCallback<ObjectProperty[]>() { @Override public void handleResponse( ObjectProperty[] response ) { if( responder != null ) responder.handleResponse( Arrays.asList( response ) ); } @Override public void handleFault( BackendlessFault fault ) { if( responder != null ) responder.handleFault( fault ); } } ); } catch( Throwable e ) { if( responder != null ) responder.handleFault( new BackendlessFault( e ) ); } } protected <E> BackendlessCollection<E> find( Class<E> entity, BackendlessDataQuery dataQuery ) throws BackendlessException { if( entity == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_ENTITY ); checkPageSizeAndOffset( dataQuery ); Object[] args = new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), getSimpleName( entity ), dataQuery }; BackendlessCollection<E> result = (BackendlessCollection<E>) Invoker.invokeSync( PERSISTENCE_MANAGER_SERVER_ALIAS, "find", args, ResponderHelper.getCollectionAdaptingResponder( entity ) ); result.setQuery( dataQuery ); result.setType( entity ); return result; } protected <E> void find( final Class<E> entity, final BackendlessDataQuery dataQuery, final AsyncCallback<BackendlessCollection<E>> responder ) { try { if( entity == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_ENTITY ); checkPageSizeAndOffset( dataQuery ); AsyncCallback<BackendlessCollection<E>> callback = new AsyncCallback<BackendlessCollection<E>>() { @Override public void handleResponse( BackendlessCollection<E> response ) { if( responder != null ) { response.setQuery( dataQuery ); response.setType( entity ); responder.handleResponse( response ); } } @Override public void handleFault( BackendlessFault fault ) { if( responder != null ) responder.handleFault( fault ); } }; Object[] args = new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), getSimpleName( entity ), dataQuery }; Invoker.invokeAsync( PERSISTENCE_MANAGER_SERVER_ALIAS, "find", args, callback, ResponderHelper.getCollectionAdaptingResponder( entity ) ); } catch( Throwable e ) { if( responder != null ) responder.handleFault( new BackendlessFault( e ) ); } } protected <E> E first( final Class<E> entity ) throws BackendlessException { if( entity == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_ENTITY ); return (E) Invoker.invokeSync( PERSISTENCE_MANAGER_SERVER_ALIAS, "first", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), getSimpleName( entity ) }, ResponderHelper.getPOJOAdaptingResponder( entity ) ); } protected <E> E first( final Class<E> entity, final List<String> relations, final int relationsDepth ) throws BackendlessException { if( entity == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_ENTITY ); return (E) Invoker.invokeSync( PERSISTENCE_MANAGER_SERVER_ALIAS, "first", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), entity.getSimpleName(), relations, relationsDepth }, ResponderHelper.getPOJOAdaptingResponder( entity ) ); } protected <E> void first( final Class<E> entity, final AsyncCallback<E> responder ) { try { if( entity == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_ENTITY ); Invoker.invokeAsync( PERSISTENCE_MANAGER_SERVER_ALIAS, "first", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), getSimpleName( entity ) }, responder, ResponderHelper.getPOJOAdaptingResponder( entity ) ); } catch( Throwable e ) { if( responder != null ) responder.handleFault( new BackendlessFault( e ) ); } } protected <E> void first( final Class<E> entity, final List<String> relations, final int relationsDepth, final AsyncCallback<E> responder ) { try { if( entity == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_ENTITY ); Invoker.invokeAsync( PERSISTENCE_MANAGER_SERVER_ALIAS, "first", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), entity.getSimpleName(), relations, relationsDepth }, responder, ResponderHelper.getPOJOAdaptingResponder( entity ) ); } catch( Throwable e ) { if( responder != null ) responder.handleFault( new BackendlessFault( e ) ); } } protected <E> E last( final Class<E> entity ) throws BackendlessException { if( entity == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_ENTITY ); return (E) Invoker.invokeSync( PERSISTENCE_MANAGER_SERVER_ALIAS, "last", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), getSimpleName( entity ) }, ResponderHelper.getPOJOAdaptingResponder( entity ) ); } protected <E> E last( final Class<E> entity, final List<String> relations, final int relationsDepth ) throws BackendlessException { if( entity == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_ENTITY ); return (E) Invoker.invokeSync( PERSISTENCE_MANAGER_SERVER_ALIAS, "last", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), entity.getSimpleName(), relations, relationsDepth }, ResponderHelper.getPOJOAdaptingResponder( entity ) ); } protected <E> void last( final Class<E> entity, final AsyncCallback<E> responder ) { try { if( entity == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_ENTITY ); Invoker.invokeAsync( PERSISTENCE_MANAGER_SERVER_ALIAS, "last", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), getSimpleName( entity ) }, responder, ResponderHelper.getPOJOAdaptingResponder( entity ) ); } catch( Throwable e ) { if( responder != null ) responder.handleFault( new BackendlessFault( e ) ); } } protected <E> void last( final Class<E> entity, final List<String> relations, final int relationsDepth, final AsyncCallback<E> responder ) { try { if( entity == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_ENTITY ); Invoker.invokeAsync( PERSISTENCE_MANAGER_SERVER_ALIAS, "last", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), entity.getSimpleName(), relations, relationsDepth }, responder, ResponderHelper.getPOJOAdaptingResponder( entity ) ); } catch( Throwable e ) { if( responder != null ) responder.handleFault( new BackendlessFault( e ) ); } } public <E> IDataStore<E> of( final Class<E> entityClass ) { if( entityClass == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_ENTITY ); return DataStoreFactory.createDataStore( entityClass ); } /*private Map<String,Object> getEntityMapWithFootprint( Object entity ) { }*/ static String getEntityId( Object entity ) throws BackendlessException { String id; try { Method declaredMethod = entity.getClass().getMethod( DEFAULT_OBJECT_ID_GETTER, new Class[ 0 ] ); if( !declaredMethod.isAccessible() ) declaredMethod.setAccessible( true ); id = (String) declaredMethod.invoke( entity ); } catch( Exception e ) { id = null; } if( id == null ) id = FootprintsManager.getInstance().getObjectId( entity ); return id; } private <T> void checkDeclaredType( Class<T> entityClass ) { if( entityClass.isArray() || entityClass.isAssignableFrom( Iterable.class ) || entityClass.isAssignableFrom( Map.class ) ) throw new IllegalArgumentException( ExceptionMessage.WRONG_ENTITY_TYPE ); try { Constructor[] constructors = entityClass.getConstructors(); if( constructors.length > 0 ) entityClass.getConstructor( new Class[ 0 ] ); } catch( NoSuchMethodException e ) { throw new IllegalArgumentException( ExceptionMessage.ENTITY_MISSING_DEFAULT_CONSTRUCTOR ); } } private void checkPageSizeAndOffset( BackendlessDataQuery dataQuery ) throws BackendlessException { if( dataQuery != null ) { if( dataQuery.getOffset() < 0 ) throw new IllegalArgumentException( ExceptionMessage.WRONG_OFFSET ); if( dataQuery.getPageSize() < 0 ) throw new IllegalArgumentException( ExceptionMessage.WRONG_PAGE_SIZE ); } } static <T> Map serializeToMap( T entity ) { if( entity.getClass().equals( backendlessUserClass ) ) return ((BackendlessUser) entity).getProperties(); HashMap result = new HashMap(); weborb.util.ObjectInspector.getObjectProperties( entity.getClass(), entity, result, new ArrayList(), true, true ); return result; } private String getSimpleName( Class clazz ) { if( clazz.equals( backendlessUserClass ) ) return "Users"; else return clazz.getSimpleName(); } }
package com.backendless; import com.backendless.async.callback.AsyncCallback; import com.backendless.core.responder.AdaptingResponder; import com.backendless.core.responder.policy.BackendlessUserAdaptingPolicy; import com.backendless.exceptions.BackendlessException; import com.backendless.exceptions.BackendlessFault; import com.backendless.exceptions.ExceptionMessage; import com.backendless.persistence.BackendlessSerializer; import com.backendless.persistence.local.UserIdStorageFactory; import com.backendless.persistence.local.UserTokenStorageFactory; import com.backendless.property.AbstractProperty; import com.backendless.property.UserProperty; import com.facebook.CallbackManager; import weborb.types.Types; import java.util.*; public final class UserService { final static String USER_MANAGER_SERVER_ALIAS = "com.backendless.services.users.UserService"; private final static String PREFS_NAME = "backendless_pref"; private static BackendlessUser currentUser = new BackendlessUser(); private final static Object currentUserLock = new Object(); public static final String USERS_TABLE_NAME = "Users"; private static final UserService instance = new UserService(); static UserService getInstance() { return instance; } private UserService() { Types.addClientClassMapping( "com.backendless.services.users.property.AbstractProperty", AbstractProperty.class ); Types.addClientClassMapping( "com.backendless.services.users.property.UserProperty", UserProperty.class ); Types.addClientClassMapping( "Users", BackendlessUser.class ); } public BackendlessUser CurrentUser() { if( currentUser != null && currentUser.getProperties().isEmpty() ) return null; return currentUser; } private UserServiceAndroidExtra getUserServiceAndroidExtra() { if( !Backendless.isAndroid() ) throw new RuntimeException( ExceptionMessage.NOT_ANDROID ); return UserServiceAndroidExtra.getInstance(); } public BackendlessUser register( BackendlessUser user ) throws BackendlessException { checkUserToBeProper( user ); BackendlessSerializer.serializeUserProperties( user ); String password = user.getPassword(); BackendlessUser userToReturn = Invoker.invokeSync( USER_MANAGER_SERVER_ALIAS, "register", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), user.getProperties() }, new AdaptingResponder( BackendlessUser.class, new BackendlessUserAdaptingPolicy() ) ); user.clearProperties(); userToReturn.setPassword( password ); user.putProperties( userToReturn.getProperties() ); return userToReturn; } public void register( final BackendlessUser user, final AsyncCallback<BackendlessUser> responder ) { try { checkUserToBeProper( user ); BackendlessSerializer.serializeUserProperties( user ); Invoker.invokeAsync( USER_MANAGER_SERVER_ALIAS, "register", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), user.getProperties() }, new AsyncCallback<BackendlessUser>() { @Override public void handleResponse( BackendlessUser response ) { response.setPassword( user.getPassword() ); user.clearProperties(); user.putProperties( response.getProperties() ); if( responder != null ) responder.handleResponse( response ); } @Override public void handleFault( BackendlessFault fault ) { if( responder != null ) responder.handleFault( fault ); } }, new AdaptingResponder( BackendlessUser.class, new BackendlessUserAdaptingPolicy() ) ); } catch( BackendlessException e ) { if( responder != null ) responder.handleFault( new BackendlessFault( e ) ); } } public BackendlessUser update( final BackendlessUser user ) throws BackendlessException { checkUserToBeProperForUpdate( user ); BackendlessSerializer.serializeUserProperties( user ); if( user.getUserId() != null && user.getUserId().equals( "" ) ) throw new IllegalArgumentException( ExceptionMessage.WRONG_USER_ID ); BackendlessUser userToReturn = Invoker.invokeSync( USER_MANAGER_SERVER_ALIAS, "update", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), user.getProperties() }, new AdaptingResponder( BackendlessUser.class, new BackendlessUserAdaptingPolicy() ) ); user.clearProperties(); user.putProperties( userToReturn.getProperties() ); return userToReturn; } public void update( final BackendlessUser user, final AsyncCallback<BackendlessUser> responder ) { try { checkUserToBeProperForUpdate( user ); BackendlessSerializer.serializeUserProperties( user ); if( user.getUserId() != null && user.getUserId().equals( "" ) ) throw new IllegalArgumentException( ExceptionMessage.WRONG_USER_ID ); Invoker.invokeAsync( USER_MANAGER_SERVER_ALIAS, "update", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), user.getProperties() }, new AsyncCallback<BackendlessUser>() { @Override public void handleResponse( BackendlessUser response ) { user.clearProperties(); user.putProperties( response.getProperties() ); if( responder != null ) responder.handleResponse( response ); } @Override public void handleFault( BackendlessFault fault ) { if( responder != null ) responder.handleFault( fault ); } }, new AdaptingResponder( BackendlessUser.class, new BackendlessUserAdaptingPolicy() ) ); } catch( Throwable e ) { if( responder != null ) responder.handleFault( new BackendlessFault( e ) ); } } public BackendlessUser login( final String login, final String password ) throws BackendlessException { return login( login, password, false ); } public BackendlessUser login( final String login, final String password, boolean stayLoggedIn ) throws BackendlessException { synchronized( currentUserLock ) { if( !currentUser.getProperties().isEmpty() ) logout(); if( login == null || login.equals( "" ) ) throw new IllegalArgumentException( ExceptionMessage.NULL_LOGIN ); if( password == null || password.equals( "" ) ) throw new IllegalArgumentException( ExceptionMessage.NULL_PASSWORD ); handleUserLogin( Invoker.<BackendlessUser>invokeSync( USER_MANAGER_SERVER_ALIAS, "login", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), login, password }, new AdaptingResponder( BackendlessUser.class, new BackendlessUserAdaptingPolicy() ) ), stayLoggedIn ); return currentUser; } } public void login( final String login, final String password, final AsyncCallback<BackendlessUser> responder ) { login( login, password, responder, false ); } public void login( final String login, final String password, final AsyncCallback<BackendlessUser> responder, boolean stayLoggedIn ) { if( !currentUser.getProperties().isEmpty() ) logout( new AsyncCallback<Void>() { @Override public void handleResponse( Void response ) { login( login, password, responder ); } @Override public void handleFault( BackendlessFault fault ) { if( responder != null ) responder.handleFault( fault ); } } ); else try { synchronized( currentUserLock ) { if( login == null || login.equals( "" ) ) throw new IllegalArgumentException( ExceptionMessage.NULL_LOGIN ); if( password == null || password.equals( "" ) ) throw new IllegalArgumentException( ExceptionMessage.NULL_PASSWORD ); else Invoker.invokeAsync( USER_MANAGER_SERVER_ALIAS, "login", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), login, password }, getUserLoginAsyncHandler( responder, stayLoggedIn ) , new AdaptingResponder( BackendlessUser.class, new BackendlessUserAdaptingPolicy() ) ); } } catch( Throwable e ) { if( responder != null ) responder.handleFault( new BackendlessFault( e ) ); } } public void loginWithFacebookSdk( android.app.Activity context, CallbackManager callbackManager, final AsyncCallback<BackendlessUser> responder ) { loginWithFacebookSdk(context, callbackManager, responder, false ); } public void loginWithFacebookSdk( android.app.Activity context, CallbackManager callbackManager, final AsyncCallback<BackendlessUser> responder, boolean stayLoggedIn ) { AsyncCallback<BackendlessUser> internalResponder = getUserLoginAsyncHandler( responder, stayLoggedIn ); getUserServiceAndroidExtra().loginWithFacebookSdk( context, callbackManager, internalResponder ); } public void loginWithFacebookSdk( android.app.Activity context, final Map<String, String> facebookFieldsMappings, final List<String> permissions, CallbackManager callbackManager, final AsyncCallback<BackendlessUser> responder ) { loginWithFacebookSdk( context, facebookFieldsMappings, permissions, callbackManager, responder, false ); } public void loginWithFacebookSdk( android.app.Activity context, final Map<String, String> facebookFieldsMappings, final List<String> permissions, CallbackManager callbackManager, final AsyncCallback<BackendlessUser> responder, boolean stayLoggedIn ) { AsyncCallback<BackendlessUser> internalResponder = getUserLoginAsyncHandler( responder, stayLoggedIn ); getUserServiceAndroidExtra().loginWithFacebookSdk( context, facebookFieldsMappings, permissions, callbackManager, internalResponder ); } public void loginWithFacebook( android.app.Activity context, final AsyncCallback<BackendlessUser> responder ) { loginWithFacebook( context, null, null, null, responder ); } public void loginWithFacebook( android.app.Activity context, android.webkit.WebView webView, final AsyncCallback<BackendlessUser> responder ) { loginWithFacebook( context, webView, null, null, responder ); } public void loginWithFacebook( android.app.Activity context, android.webkit.WebView webView, final AsyncCallback<BackendlessUser> responder, boolean stayLoggedIn ) { loginWithFacebook( context, webView, null, null, responder, stayLoggedIn ); } public void loginWithFacebook( android.app.Activity context, android.webkit.WebView webView, Map<String, String> facebookFieldsMappings, List<String> permissions, final AsyncCallback<BackendlessUser> responder ) { loginWithFacebook( context, webView, facebookFieldsMappings, permissions, responder, false ); } public void loginWithFacebook( android.app.Activity context, android.webkit.WebView webView, Map<String, String> facebookFieldsMappings, List<String> permissions, final AsyncCallback<BackendlessUser> responder, boolean stayLoggedIn ) { getUserServiceAndroidExtra().loginWithFacebook( context, webView, facebookFieldsMappings, permissions, getUserLoginAsyncHandler( responder, stayLoggedIn ) ); } public void loginWithTwitter( android.app.Activity context, AsyncCallback<BackendlessUser> responder ) { loginWithTwitter( context, null, null, responder, false ); } public void loginWithTwitter( android.app.Activity context, android.webkit.WebView webView, AsyncCallback<BackendlessUser> responder ) { loginWithTwitter( context, webView, null, responder, false ); } public void loginWithTwitter( android.app.Activity context, Map<String, String> twitterFieldsMappings, AsyncCallback<BackendlessUser> responder ) { loginWithTwitter( context, null, twitterFieldsMappings, responder, false ); } public void loginWithTwitter( android.app.Activity context, AsyncCallback<BackendlessUser> responder, boolean stayLoggedIn ) { loginWithTwitter( context, null, null, responder, stayLoggedIn ); } public void loginWithTwitter( android.app.Activity context, android.webkit.WebView webView, Map<String, String> twitterFieldsMappings, AsyncCallback<BackendlessUser> responder ) { loginWithTwitter( context, webView, twitterFieldsMappings, responder, false ); } public void loginWithTwitter( android.app.Activity context, android.webkit.WebView webView, AsyncCallback<BackendlessUser> responder, boolean stayLoggedIn ) { loginWithTwitter( context, webView, null, responder, stayLoggedIn ); } public void loginWithTwitter( android.app.Activity context, Map<String, String> twitterFieldsMappings, AsyncCallback<BackendlessUser> responder, boolean stayLoggedIn ) { loginWithTwitter( context, null, twitterFieldsMappings, responder, stayLoggedIn ); } public void loginWithTwitter( android.app.Activity context, android.webkit.WebView webView, Map<String, String> twitterFieldsMappings, AsyncCallback<BackendlessUser> responder, boolean stayLoggedIn ) { getUserServiceAndroidExtra().loginWithTwitter( context, webView, twitterFieldsMappings, getUserLoginAsyncHandler( responder, stayLoggedIn ) ); } public void loginWithGooglePlus( android.app.Activity context, final AsyncCallback<BackendlessUser> responder ) { loginWithGooglePlus( context, null, null, null, responder ); } public void loginWithGooglePlus( android.app.Activity context, android.webkit.WebView webView, final AsyncCallback<BackendlessUser> responder ) { loginWithGooglePlus( context, webView, null, null, responder ); } public void loginWithGooglePlus( android.app.Activity context, android.webkit.WebView webView, final AsyncCallback<BackendlessUser> responder, boolean stayLoggedIn ) { loginWithGooglePlus( context, webView, null, null, responder, stayLoggedIn ); } public void loginWithGooglePlus( android.app.Activity context, android.webkit.WebView webView, Map<String, String> googlePlusFieldsMappings, List<String> permissions, final AsyncCallback<BackendlessUser> responder ) { loginWithGooglePlus( context, webView, googlePlusFieldsMappings, permissions, responder, false ); } public void loginWithGooglePlus( android.app.Activity context, android.webkit.WebView webView, Map<String, String> googlePlusFieldsMappings, List<String> permissions, final AsyncCallback<BackendlessUser> responder, boolean stayLoggedIn ) { getUserServiceAndroidExtra().loginWithGooglePlus( context, webView, googlePlusFieldsMappings, permissions, getUserLoginAsyncHandler( responder, stayLoggedIn ) ); } public void loginWithGooglePlusSdk( String tokenId, String accessToken, final AsyncCallback<BackendlessUser> responder ) { loginWithGooglePlusSdk( tokenId, accessToken, null, null, responder ); } public void loginWithGooglePlusSdk( String tokenId, String accessToken, final AsyncCallback<BackendlessUser> responder, boolean stayLoggedIn ) { loginWithGooglePlusSdk( tokenId, accessToken, null, null, responder, stayLoggedIn ); } public void loginWithGooglePlusSdk( String tokenId, String accessToken, final Map<String, String> fieldsMappings, List<String> permissions, final AsyncCallback<BackendlessUser> responder ) { loginWithGooglePlusSdk( tokenId, accessToken, fieldsMappings, permissions, responder, false ); } public void loginWithGooglePlusSdk( String tokenId, String accessToken, final Map<String, String> fieldsMappings, List<String> permissions, final AsyncCallback<BackendlessUser> responder, boolean stayLoggedIn ) { AsyncCallback<BackendlessUser> internalResponder = getUserLoginAsyncHandler( responder, stayLoggedIn ); getUserServiceAndroidExtra().loginWithGooglePlusSdk( tokenId, accessToken, fieldsMappings, permissions, internalResponder ); } public void logout() throws BackendlessException { synchronized( currentUserLock ) { try { Invoker.invokeSync( USER_MANAGER_SERVER_ALIAS, "logout", new Object[] { Backendless.getApplicationId(), Backendless.getVersion() } ); } catch( BackendlessException fault ) { if( !isLogoutFaultAllowed( fault.getCode() ) ) throw fault; //else everything is OK } handleLogout(); } } private void handleLogout() { currentUser = new BackendlessUser(); HeadersManager.getInstance().removeHeader( HeadersManager.HeadersEnum.USER_TOKEN_KEY ); UserTokenStorageFactory.instance().getStorage().set( "" ); UserIdStorageFactory.instance().getStorage().set( "" ); } public void logout( final AsyncCallback<Void> responder ) { synchronized( currentUserLock ) { Invoker.invokeAsync( USER_MANAGER_SERVER_ALIAS, "logout", new Object[] { Backendless.getApplicationId(), Backendless.getVersion() }, new AsyncCallback<Void>() { @Override public void handleResponse( Void response ) { try { handleLogout(); } catch( Throwable e ) { if( responder != null ) responder.handleFault( new BackendlessFault( e ) ); } if( responder != null ) responder.handleResponse( response ); } @Override public void handleFault( BackendlessFault fault ) { if( isLogoutFaultAllowed( fault.getCode() ) ) { handleResponse( null ); return; } if( responder != null ) responder.handleFault( fault ); } } ); } } public void restorePassword( String identity ) throws BackendlessException { if( identity == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_IDENTITY ); Invoker.invokeSync( USER_MANAGER_SERVER_ALIAS, "restorePassword", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), identity } ); } public void restorePassword( final String identity, final AsyncCallback<Void> responder ) { try { if( identity == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_IDENTITY ); Invoker.invokeAsync( USER_MANAGER_SERVER_ALIAS, "restorePassword", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), identity }, responder ); } catch( Throwable e ) { if( responder != null ) responder.handleFault( new BackendlessFault( e ) ); } } public BackendlessUser findById( String id ) throws BackendlessException { if( id == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_IDENTITY ); return Invoker.invokeSync( USER_MANAGER_SERVER_ALIAS, "findById", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), id, new ArrayList() } ); } public void findById( final String id, final AsyncCallback<BackendlessUser> responder ) { try { if( id == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_IDENTITY ); Invoker.invokeAsync( USER_MANAGER_SERVER_ALIAS, "findById", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), id, new ArrayList() }, new AsyncCallback<BackendlessUser>() { @Override public void handleResponse( BackendlessUser response ) { if( responder != null ) responder.handleResponse( response ); } @Override public void handleFault( BackendlessFault fault ) { if( responder != null ) responder.handleFault( fault ); } } ); } catch( Throwable e ) { if( responder != null ) responder.handleFault( new BackendlessFault( e ) ); } } public void assignRole( String identity, String roleName ) throws BackendlessException { if( identity == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_IDENTITY ); if( roleName == null || roleName.equals( "" ) ) throw new IllegalArgumentException( ExceptionMessage.NULL_ROLE_NAME ); Invoker.invokeSync( USER_MANAGER_SERVER_ALIAS, "assignRole", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), identity, roleName } ); } public void assignRole( final String identity, final String roleName, final AsyncCallback<Void> responder ) { try { if( identity == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_IDENTITY ); if( roleName == null || roleName.equals( "" ) ) throw new IllegalArgumentException( ExceptionMessage.NULL_ROLE_NAME ); Invoker.invokeAsync( USER_MANAGER_SERVER_ALIAS, "assignRole", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), identity, roleName }, responder ); } catch( Throwable e ) { if( responder != null ) responder.handleFault( new BackendlessFault( e ) ); } } public void unassignRole( String identity, String roleName ) throws BackendlessException { if( identity == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_IDENTITY ); if( roleName == null || roleName.equals( "" ) ) throw new IllegalArgumentException( ExceptionMessage.NULL_ROLE_NAME ); Invoker.invokeSync( USER_MANAGER_SERVER_ALIAS, "unassignRole", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), identity, roleName } ); } public void unassignRole( final String identity, final String roleName, final AsyncCallback<Void> responder ) { try { if( identity == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_IDENTITY ); if( roleName == null || roleName.equals( "" ) ) throw new IllegalArgumentException( ExceptionMessage.NULL_ROLE_NAME ); Invoker.invokeAsync( USER_MANAGER_SERVER_ALIAS, "unassignRole", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), identity, roleName }, responder ); } catch( Throwable e ) { if( responder != null ) responder.handleFault( new BackendlessFault( e ) ); } } public List<String> getUserRoles() throws BackendlessException { return Arrays.asList( (String[]) Invoker.invokeSync( USER_MANAGER_SERVER_ALIAS, "getUserRoles", new Object[] { Backendless.getApplicationId(), Backendless.getVersion() } ) ); } public void getUserRoles( final AsyncCallback<List<String>> responder ) { try { AsyncCallback<String[]> callback = new AsyncCallback<String[]>() { @Override public void handleResponse( String[] response ) { if( responder != null ) responder.handleResponse( Arrays.asList( response ) ); } @Override public void handleFault( BackendlessFault fault ) { if( responder != null ) responder.handleFault( fault ); } }; Invoker.invokeAsync( USER_MANAGER_SERVER_ALIAS, "getUserRoles", new Object[] { Backendless.getApplicationId(), Backendless.getVersion() }, callback ); } catch( Throwable e ) { if( responder != null ) responder.handleFault( new BackendlessFault( e ) ); } } public List<UserProperty> describeUserClass() throws BackendlessException { UserProperty[] response = Invoker.invokeSync( USER_MANAGER_SERVER_ALIAS, "describeUserClass", new Object[] { Backendless.getApplicationId(), Backendless.getVersion() } ); return Arrays.asList( response ); } public void describeUserClass( final AsyncCallback<List<UserProperty>> responder ) { Invoker.invokeAsync( USER_MANAGER_SERVER_ALIAS, "describeUserClass", new Object[] { Backendless.getApplicationId(), Backendless.getVersion() }, new AsyncCallback<UserProperty[]>() { @Override public void handleResponse( UserProperty[] response ) { if( responder != null ) responder.handleResponse( Arrays.asList( response ) ); } @Override public void handleFault( BackendlessFault fault ) { if( responder != null ) responder.handleFault( fault ); } } ); } public void getFacebookServiceAuthorizationUrlLink( Map<String, String> facebookFieldsMappings, List<String> permissions, AsyncCallback<String> responder ) throws BackendlessException { if( facebookFieldsMappings == null ) facebookFieldsMappings = new HashMap<String, String>(); if( permissions == null ) permissions = new ArrayList<String>(); Invoker.invokeAsync( USER_MANAGER_SERVER_ALIAS, "getFacebookServiceAuthorizationUrlLink", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), HeadersManager.getInstance().getHeader( HeadersManager.HeadersEnum.APP_TYPE_NAME ), facebookFieldsMappings, permissions }, responder ); } public void getTwitterServiceAuthorizationUrlLink( Map<String, String> twitterFieldsMapping, AsyncCallback<String> responder ) { if( twitterFieldsMapping == null ) twitterFieldsMapping = new HashMap<String, String>(); Invoker.invokeAsync( USER_MANAGER_SERVER_ALIAS, "getTwitterServiceAuthorizationUrlLink", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), HeadersManager.getInstance().getHeader( HeadersManager.HeadersEnum.APP_TYPE_NAME ), twitterFieldsMapping }, responder ); } public void getGooglePlusServiceAuthorizationUrlLink( Map<String, String> googlePlusFieldsMappings, List<String> permissions, AsyncCallback<String> responder ) throws BackendlessException { if( googlePlusFieldsMappings == null ) googlePlusFieldsMappings = new HashMap<String, String>(); if( permissions == null ) permissions = new ArrayList<String>(); Invoker.invokeAsync( USER_MANAGER_SERVER_ALIAS, "getGooglePlusServiceAuthorizationUrlLink", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), HeadersManager.getInstance().getHeader( HeadersManager.HeadersEnum.APP_TYPE_NAME ), googlePlusFieldsMappings, permissions }, responder ); } private static void checkUserToBeProper( BackendlessUser user ) throws BackendlessException { checkUserToBeProperForUpdate( user ); if( user.getPassword() == null || user.getPassword().equals( "" ) ) throw new IllegalArgumentException( ExceptionMessage.NULL_PASSWORD ); } private static void checkUserToBeProperForUpdate( BackendlessUser user ) { if( user == null ) throw new IllegalArgumentException( ExceptionMessage.NULL_USER ); } /** * Returns user ID of the logged in user or empty string if user is not logged in. * * @return user id, if the user is logged in; else empty string */ public String loggedInUser() { return UserIdStorageFactory.instance().getStorage().get(); } /** * Sets the properties of the given user to current one. * * @param user a user from which properties should be taken */ public void setCurrentUser( BackendlessUser user ) { currentUser.setProperties( user.getProperties() ); } private void handleUserLogin( BackendlessUser invokeResult, boolean stayLoggedIn ) { String userToken = (String) invokeResult.getProperty( HeadersManager.HeadersEnum.USER_TOKEN_KEY.getHeader() ); HeadersManager.getInstance().addHeader( HeadersManager.HeadersEnum.USER_TOKEN_KEY, userToken ); currentUser = invokeResult; currentUser.removeProperty( HeadersManager.HeadersEnum.USER_TOKEN_KEY.getHeader() ); if( stayLoggedIn ) { UserTokenStorageFactory.instance().getStorage().set( userToken ); UserIdStorageFactory.instance().getStorage().set( Backendless.UserService.CurrentUser().getUserId() ); } } private AsyncCallback<BackendlessUser> getUserLoginAsyncHandler( final AsyncCallback<BackendlessUser> responder, final boolean stayLoggedIn ) { return new AsyncCallback<BackendlessUser>() { @Override public void handleResponse( BackendlessUser response ) { try { handleUserLogin( response, stayLoggedIn ); } catch( Throwable e ) { if( responder != null ) responder.handleFault( new BackendlessFault( e ) ); } if( responder != null ) responder.handleResponse( currentUser ); } @Override public void handleFault( BackendlessFault fault ) { if( responder != null ) responder.handleFault( fault ); } }; } /** * if user token has been saved from previous logins, the method checks if the user token is still valid; * if user token is not saved, but user logged in, the method checks if the user session is still valid * * @return true, if user token is valid or user is logged in, else false */ public boolean isValidLogin() { String userToken = UserTokenStorageFactory.instance().getStorage().get(); if( userToken != null && !userToken.equals( "" ) ) { return Invoker.<Boolean>invokeSync( USER_MANAGER_SERVER_ALIAS, "isValidUserToken", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), userToken } ); } else { return CurrentUser() != null; } } /** * if user token has been saved from previous logins, the method checks if the user token is still valid; * if user token is not saved, but user logged in, the method checks if the user session is still valid */ public void isValidLogin( AsyncCallback<Boolean> responder ) { String userToken = UserTokenStorageFactory.instance().getStorage().get(); if( userToken != null && !userToken.equals( "" ) ) { Invoker.invokeAsync( USER_MANAGER_SERVER_ALIAS, "isValidUserToken", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), userToken }, responder ); } else { responder.handleResponse( CurrentUser() != null ); } } private boolean isLogoutFaultAllowed( String errorCode ) { return errorCode.equals( "3064" ) || errorCode.equals( "3091" ) || errorCode.equals( "3090" ) || errorCode.equals( "3023" ); } }
package com.blackmoonit.net; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.lang.ref.WeakReference; import java.lang.reflect.Type; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.net.URLConnection; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import android.content.Context; import android.net.Uri; import android.util.Log; import com.blackmoonit.io.StreamUtils; import com.blackmoonit.net.ssl.CustomSSLTrustManager; import com.blackmoonit.net.ssl.CustomSSLTrustManager.SSLContextException; /** * A class to attempt a more generic solution to trying to open an http/https * web connection that may or may not require custom Certificate Authority chains * to authorize SSL connections with unknown or self-signed hosts. * * @author Ryan Fischbach */ public class WebConn { static private final String TAG = "androidBits."+WebConn.class.getSimpleName(); protected WeakReference<Context> mContext = null; protected URL mUrl = null; protected String mUrlKey = null; protected Uri mCAResource = null; protected SSLContext mSSLContext = null; public String myUserAgent = null; static public class WebConnInfo { public URL url = null; public String auth_key = null; public Uri custom_ca_uri = null; public Boolean is_polling_expected = null; } public WebConn(Context aContext) { mContext = new WeakReference<Context>(aContext); } public WebConn(Context aContext, URL aUrl) { mContext = new WeakReference<Context>(aContext); setUrl(aUrl); } public WebConn(Context aContext, WebConnInfo aInfo) { mContext = new WeakReference<Context>(aContext); setUrl(aInfo.url); setAuthKey(aInfo.auth_key); setCertAuthResource(aInfo.custom_ca_uri); } public Context getContext() { return (mContext!=null) ? mContext.get() : null; } public URL getUrl() { return mUrl; } /** * Specify the URL to use to connect. * @param aUrl - either an HTTP or HTTPS connection. * @return Returns THIS for chaining purposes. */ public WebConn setUrl(URL aUrl) { mUrl = aUrl; return this; } /** * Specify the URL string to use to connect. * @param aUrlStr - either an HTTP or HTTPS connection. * @return Returns THIS for chaining purposes. * @throws MalformedURLException */ public WebConn setUrl(String aUrlStr) throws MalformedURLException { return setUrl(new URL(aUrlStr)); } public String getAuthKey() { return mUrlKey; } /** * Basically a password needed to connect to the URL. * @param aAuthKey - string * @return Returns THIS for chaining purposes. */ public WebConn setAuthKey(String aAuthKey) { mUrlKey = aAuthKey; return this; } public Uri getCertAuthResource() { return mCAResource; } /** * When using PROTOCOL_HTTPS_CUSTOM, the custom CA needs to be supplied, * this is how to supply it. * @param aCAResource - either "asset://filename" or "file://filepath". * @return Returns THIS for chaining purposes. */ public WebConn setCertAuthResource(Uri aCAResource) { mCAResource = aCAResource; mSSLContext = null; return this; } /** * When using custom CAs, the custom CA chain needs to be loaded and used. * @return Returns the SSLContext with all the certificate magic already loaded. * @throws SSLContextException */ protected SSLContext getCustomSSLContext() throws SSLContextException { Context theContext = getContext(); if (mSSLContext==null && theContext!=null && mCAResource!=null) { CustomSSLTrustManager theTm = new CustomSSLTrustManager(theContext,mCAResource); mSSLContext = theTm.getSSLContext(); } return mSSLContext; } /** * Opens the web connection and provides the custom SSLContext, if necessary. * @return Returns the URLConnection or NULL if it failed to open. */ public URLConnection openConnection() { URLConnection theUrlConn = null; try { theUrlConn = mUrl.openConnection(); if (mCAResource!=null) { //use custom CA SSLContext theSSLContext = getCustomSSLContext(); ((HttpsURLConnection)theUrlConn).setSSLSocketFactory(theSSLContext.getSocketFactory()); } if (mUrlKey!=null) { theUrlConn.setRequestProperty("Authorization", WebUtils.getBasicAuthString(mUrlKey)); } if (myUserAgent!=null) { theUrlConn.setRequestProperty("User-Agent",myUserAgent); } } catch (IOException ioe) { Log.e(TAG,"openConnection",ioe); } catch (SSLContextException sce) { Log.e(TAG,"openConn (custom-ssl)",sce); } return theUrlConn; } /** * Given an open connection, upload the data string. * @param aUrlConn - open URLConnection. * @param aDataToSend - string data. * @throws IOException */ public void writeToUrl(URLConnection aUrlConn, String aDataToSend) throws IOException { URLConnection theUrlConn = aUrlConn; try { theUrlConn.setDoInput(true); theUrlConn.setDoOutput(true); ((HttpURLConnection)theUrlConn).setRequestMethod("POST"); OutputStream theOutStream = null; try { theOutStream = theUrlConn.getOutputStream(); BufferedWriter theWriter = null; try { theWriter = new BufferedWriter(new OutputStreamWriter(theOutStream,WebUtils.WEB_CHARSET)); theWriter.write(aDataToSend); theWriter.flush(); } finally { if (theWriter!=null) theWriter.close(); } } finally { if (theOutStream!=null) theOutStream.close(); } } catch (ProtocolException pe) { Log.e(TAG,"writeToUri",pe); throw new IOException(pe); } } /** * Simple method used to read the URL response and return the text as String. * @param aUrlConn - open URLConnection. * @return Returns the response text as a String. * @throws IOException */ public String readResponseFromUrl(URLConnection aUrlConn) throws IOException { InputStream theInStream = aUrlConn.getInputStream(); try { return StreamUtils.inputStreamToString(theInStream); } finally { theInStream.close(); } } /** * Given an open connection, upload the data string and return the response. * @param aUrlConn - open URLConnection. * @param aDataToSend - string data. * @return Returns the response text as a String. */ public String parleyWithUrl(URLConnection aUrlConn, String aDataToSend) { try { writeToUrl(aUrlConn, aDataToSend); return readResponseFromUrl(aUrlConn); } catch (IOException e) { Log.e(TAG,"parleyWithUrl",e); } return null; } /** * Given an open connection, return the downloaded text as a JSON-converted object. * @param aUrlConn - open URLConnection. * @param aResultClass - resulting class JSON data is converted into. * @return Returns the class filled in with appropriate data or NULL on failure. */ public <T> T jsonDownload(URLConnection aUrlConn, Class<T> aResultClass) { URLConnection theUrlConn = aUrlConn; try { String theResponse = readResponseFromUrl(theUrlConn); return WebUtils.fromJson(theResponse, aResultClass); } catch (IOException e) { Log.e(TAG,"downloadJson",e); } return null; } /** * Given an open connection, upload the object converted to a JSON string. * @param aUrlConn - open URLConnection. * @param aObject - object instance with data to convert to string. * @param aTypeOfObject - type of aObject so JSON conversion works. */ public void jsonUpload(URLConnection aUrlConn, Object aObject, Type aTypeOfObject) { URLConnection theUrlConn = aUrlConn; try { //theUrlConn.setRequestProperty("Content-Type", "application/json; charset="+CHARSET); //theUrlConn.setRequestProperty("Content-length", aDataToSend.length()+""); writeToUrl(theUrlConn, WebUtils.toJson(aObject,aTypeOfObject)); } catch (IOException e) { Log.e(TAG,"uploadJson",e); } } /** * Given an open connection, supply some string data to send and convert the text * response from JSON into the aResultClass. * @param aUrlConn - open URLConnection. * @param aObject - object instance with data to convert to string. * @param aTypeOfObject - type of aObject so JSON conversion works. * @param aResultClass - resulting class JSON data is converted into. * @return Returns the class filled in with appropriate data or NULL on failure. * @see WebConn#uploadJson(URLConnection, Object, Type) * @see WebConn#downloadJson(URLConnection, Class) */ public <T> T jsonParley(URLConnection aUrlConn, Object aObject, Type aTypeOfObject, Class<T> aResultClass) { jsonUpload(aUrlConn, aObject, aTypeOfObject); return jsonDownload(aUrlConn, aResultClass); } }
package com.example.timestamp; import com.example.timestamp.model.TimePost; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; public class Start extends Activity { final Context context = this; String[] projectsMenuString = {"Projekt 1", "Projekt 2", "Nytt projekt"}; String[] overviewMenuString = {"Graf", "Bar", "Summering"}; private Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.activity_start); //getWindow().requestFeature(Window.FEATURE_ACTION_BAR); getActionBar().hide(); setContentView(R.layout.activity_confirmreport); Toast.makeText(getApplicationContext(), new TimePost().printStartTime() , Toast.LENGTH_LONG).show(); activityInitConfirmReport(); } /*@Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_activity_actions, menu); return super.onCreateOptionsMenu(menu); }*/ public void activitySwitchOne(View v){ setContentView(R.layout.activity_confirmreport); activityInitConfirmReport(); } public void activitySwitchToMain(View v){ setContentView(R.layout.activity_start); activityInitMain(); } private void activityInitMain(){ //Letar efter en spinner i activity_main.xml med ett specifict id Spinner spinnerProjectView = (Spinner) findViewById(R.id.spinnerProjectView); //Spinner spinnerOverView = (Spinner) findViewById(R.id.spinnerOverView); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, projectsMenuString); //Fr att vlja vilken typ av graf man vill se. //ArrayAdapter<String> adapterView = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, overviewMenuString); //Spinnern anvnder items frn en valt adapter. spinnerProjectView.setAdapter(adapter); //Fr overview //spinnerOverView.setAdapter(adapterView); //Hur spinnern ska se ut //adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); } private void activityInitConfirmReport(){ //Letar efter en spinner i activity_main.xml med ett specifict id Spinner spinner = (Spinner) findViewById(R.id.projects_menu_spinner2); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, projectsMenuString){ public View getView(int position, View convertView,ViewGroup parent) { View v = super.getView(position, convertView, parent); ((TextView) v).setGravity(Gravity.CENTER); ((TextView) v).setTextSize(36); return v; } public View getDropDownView(int position, View convertView,ViewGroup parent) { View v = super.getDropDownView(position, convertView,parent); ((TextView) v).setGravity(Gravity.CENTER); ((TextView) v).setTextSize(20); return v; } }; spinner.setAdapter(adapter); button = (Button) findViewById(R.id.sendReportButton); button.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View arg0){ AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("Är du säker på att du vill skicka in rapporten?"); // 2. Chain together various setter methods to set the dialog characteristics builder.setPositiveButton("Skicka", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User clicked OK button } }); builder.setNegativeButton("Avbryt", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User cancelled the dialog } }); AlertDialog alertDialog = builder.create(); alertDialog.show(); } }); } public void startTime(View view){ AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); // set title alertDialogBuilder.setTitle("Timestamp"); // set dialog message alertDialogBuilder .setMessage("Du har nu stämplat in") .setCancelable(false) .setPositiveButton("Avsluta",new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { // if this button is clicked, close // current activity Start.this.finish(); } }) .setNegativeButton("Okej",new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { // if this button is clicked, just close // the dialog box and do nothing dialog.cancel(); } }); // create alert dialog AlertDialog alertDialog = alertDialogBuilder.create(); // show it alertDialog.show(); } } /* button = (Button) findViewById(R.id.sendReportButton); button.setOnClickListener(new OnClickListener(){ @Override public void onClick(View arg0){ AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("r du skert p att du vill skicka in rapporten?"); // 2. Chain together various setter methods to set the dialog characteristics builder.setPositiveButton("Skicka", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User clicked OK button } }); builder.setNegativeButton("Avbryt", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User cancelled the dialog } }); AlertDialog alertDialog = builder.create(); alertDialog.show(); } });*/
package com.qq; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.net.URLDecoder; import java.io.UnsupportedEncodingException; public class GetRequest { public static void main(String[] args) { // TODO Auto-generated method stub String httpUrl = "http://111.207.243.70:8088/IbotInfo/GetInfo"; String sendInfo="346786495@qq.com"; String recieveInfo="wnbupt@qq.com"; String timeInfo="2015-12-16-10:43"; String subjectInfo="demo"; String bodyInfo=""; //String[] appendInfo={"D:/ibotest/test.ppt","D:/ibotest/test.doc"}; String[] appendInfo={"null"};//null String httpArg = "sender="+sendInfo+"&reciever="+recieveInfo+"&sendtime="+timeInfo+"&subject="+subjectInfo+"&body="+bodyInfo+"&attachment="; int i; for(i=0;i<appendInfo.length-1;i++) { httpArg=httpArg+appendInfo[i]+'|'; } httpArg=httpArg+appendInfo[i]; GetRequest test=new GetRequest(); String jsonResult = test.request(httpUrl, httpArg); System.out.println(httpUrl+"?"+httpArg); System.out.println(jsonResult); } public static String request(String httpUrl,String httpArg) { BufferedReader reader = null; String result = null; StringBuffer sbf = new StringBuffer(); try { httpArg=URLEncoder.encode(httpArg,"utf-8"); httpUrl = httpUrl + "?" + httpArg; URL url = new URL(httpUrl); HttpURLConnection connection = (HttpURLConnection) url .openConnection(); //connection.setRequestMethod("POST"); connection.connect(); java.io.InputStream is = connection.getInputStream(); //InputStream is = (InputStream) connection.getInputStream(); reader = new BufferedReader(new InputStreamReader(is,"utf-8")); String strRead = null; while ((strRead = reader.readLine()) != null) { //System.out.println(strRead); sbf.append(strRead); sbf.append("\r\n"); } reader.close(); result = sbf.toString(); } catch (Exception e) { e.printStackTrace(); } return result; } }
package com.justjournal.ctl; import com.justjournal.db.UserLinkDao; import com.justjournal.db.UserLinkTo; import org.apache.log4j.Category; public class AddLink extends Protected { private static Category log = Category.getInstance(AddLink.class.getName()); protected String title; protected String uri; public String getMyLogin() { return this.currentLoginName(); } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } protected String insidePerform() throws Exception { if (log.isDebugEnabled()) log.debug("insidePerform(): Attempting to add link."); if (this.currentLoginId() < 1) addError("login", "The login timed out or is invalid."); if (!this.hasErrors()) { try { UserLinkDao dao = new UserLinkDao(); UserLinkTo ul = new UserLinkTo(); ul.setTitle(title); ul.setUri(uri); ul.setUserId(this.currentLoginId()); if (!dao.add(ul)) ; addError("Add Link", "Error adding link."); } catch (Exception e) { addError("Add Link", "Could not add the link."); if (log.isDebugEnabled()) log.debug("insidePerform(): " + e.getMessage()); } } if (this.hasErrors()) return ERROR; else return SUCCESS; } }
package com.shade.entities; import org.newdawn.slick.Animation; import org.newdawn.slick.Graphics; import org.newdawn.slick.SlickException; import org.newdawn.slick.SpriteSheet; import org.newdawn.slick.geom.Circle; import org.newdawn.slick.geom.RoundedRectangle; import org.newdawn.slick.geom.Shape; import org.newdawn.slick.geom.Transform; import org.newdawn.slick.geom.Vector2f; import org.newdawn.slick.state.StateBasedGame; import com.shade.base.Entity; import com.shade.base.Level; import com.shade.crash.Body; import com.shade.crash.util.CrashGeom; import com.shade.shadows.ShadowCaster; import com.shade.shadows.ShadowEntity; import com.shade.shadows.ShadowLevel; import com.shade.shadows.ShadowLevel.DayLightStatus; import com.shade.util.Geom; public class Gargoyle extends Linkable implements ShadowEntity, ShadowCaster { private static final int RADIUS = 20; private static final float SPEED = .5f; private static final int COOLDOWN_TIME = 8000; private enum Status { ASLEEP, ALERT, CHASING, CONFUSED } private ShadowLevel level; private Status status; private Player target; private float heading; private int timer, cooldown, wander; private Animation sniff, move, bored; private ShadowIntensity shadowStatus; public Gargoyle(int x, int y) throws SlickException { initShape(); initSprites(); shape.setLocation(x, y); status = Status.ASLEEP; cooldown = 0; heading = (float) Math.PI; wander = 0; } private void initShape() { shape = new Circle(300, 300, RADIUS); } private void initSprites() throws SlickException { SpriteSheet sniffs = new SpriteSheet("entities/mole/sniff.png", 40, 40); sniff = new Animation(sniffs, 300); sniff.setAutoUpdate(false); sniff.setPingPong(true); SpriteSheet moves = new SpriteSheet("entities/mole/move.png", 40, 40); move = new Animation(moves, 300); move.setAutoUpdate(false); SpriteSheet question = new SpriteSheet("entities/mole/move.png", 40, 40); bored = new Animation(question, 300); bored.setAutoUpdate(false); } public void addToLevel(Level l) { level = (ShadowLevel) l; } public Role getRole() { return Role.MONSTER; } public boolean hasIntensity(ShadowIntensity s) { return s == shadowStatus; } public void setIntensity(ShadowIntensity s) { shadowStatus = s; } public void onCollision(Entity obstacle) { if (obstacle.getRole() == Role.PLAYER && status != Status.ASLEEP) { // he got ya Player p = (Player) obstacle; p.getHit(this); cooldown = COOLDOWN_TIME; wander = 1; heading = (float) (Math.atan2(getCenterY() - p.getCenterY(), getCenterX() - p.getCenterX())); } else { Body b = (Body) obstacle; b.repel(this); return; } } public void removeFromLevel(Level l) { // TODO Auto-generated method stub } public void render(StateBasedGame game, Graphics g) { g.rotate(getCenterX(), getCenterY(), (float) Math.toDegrees(heading)); if (status == Status.ALERT) { sniff.draw(getX(), getY(), getWidth(), getHeight()); } if (status == Status.ASLEEP) { bored.draw(getX(), getY(), getWidth(), getHeight()); } if (status == Status.CHASING) { move.draw(getX(), getY(), getWidth(), getHeight()); } if (status == Status.CONFUSED) { // do nothing right now } g.resetTransform(); // g.draw(shape); } public void update(StateBasedGame game, int delta) { timer += delta; sniff.update(delta); move.update(delta); // let's let the ubermoles stay awake for now if (level.getDayLight() != DayLightStatus.NIGHT) { status = Status.ASLEEP; return; } status = Status.ALERT; if (findTarget() && cooldown < 1) { seekTarget(); } else { if (wander < 100 && wander > 0) { move(SPEED, heading); wander++; } else if (wander == 100) wander = -100; else if (wander < 0) { wander++; } else { wander = 1; heading = (float) (Math.random() * Math.PI * 2); } } cooldown -= delta; testAndWrap(); } private void seekTarget() { float[] d = new float[3]; d[0] = CrashGeom.distance2(target, this); if (d[0] > 500 && target.hasIntensity(ShadowIntensity.CASTSHADOWED)) { wander = 0; return; } d[1] = d[0]; d[2] = d[0]; // if I'm left of my target if (getX() < target.getX()) { d[1] = CrashGeom .distance2(target, getCenterX() + 800, getCenterY()); } else { d[1] = CrashGeom.distance2(this, target.getCenterX() + 800, target .getCenterY()); } // if I'm above my target if (getY() < target.getY()) { d[2] = CrashGeom .distance2(target, getCenterX(), getCenterY() + 600); } else { d[2] = CrashGeom.distance2(this, target.getCenterX(), target .getCenterY() + 600); } heading = CrashGeom.calculateAngle(target, this); if (d[1] < d[0] || d[2] < d[0]) { heading += Math.PI; } move(SPEED, heading); } private boolean findTarget() { ShadowEntity[] entities = level.nearByEntities(this, 300); boolean lineOfSight = false; int i = 0; while (!lineOfSight && i < entities.length) { if (((Entity) entities[i]).getRole() == Role.PLAYER) { lineOfSight = level.lineOfSight(this, entities[i]); } i++; } i if (lineOfSight) { target = (Player) entities[i]; status = Status.CHASING; move.restart(); return true; } return false; } /* Move the shape a given amount across two dimensions. */ private void move(float magnitude, float direction) { Vector2f d = Geom.calculateVector(magnitude, direction); shape.setCenterX(shape.getCenterX() + d.x); shape.setCenterY(shape.getCenterY() + d.y); xVelocity = d.x; yVelocity = d.y; } public void repel(Entity repellee) { Body b = (Body) repellee; double playerx = b.getCenterX(); double playery = b.getCenterY(); double dist_x = playerx - getCenterX(); double dist_y = playery - getCenterY(); double mag = Math.sqrt(dist_x * dist_x + dist_y * dist_y); double playradius = b.getWidth() / 2; double obstacleradius = getWidth() / 2; double angle = Math.atan2(dist_y, dist_x); double move = (playradius + obstacleradius - mag) * 1.5; b.move(Math.cos(angle) * move, Math.sin(angle) * move); } public boolean asleep() { return status == Status.ASLEEP; } public int getZIndex() { return 4; } public int compareTo(ShadowEntity s) { return getZIndex() - s.getZIndex(); } public Shape castShadow(float direction, float depth) { float r = ((Circle) shape).radius; float h = getZIndex() * depth * 1.6f; float x = getCenterX(); float y = getCenterY(); Transform t = Transform.createRotateTransform(direction + 3.14f, x, y); RoundedRectangle rr = new RoundedRectangle(getX(), getY(), r * 2, h, r); return rr.transform(t); } }
package com.techjar.ledcm.util; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.hackoeur.jglm.Mat3; import com.hackoeur.jglm.Mat4; import com.techjar.ledcm.LEDCubeManager; import com.techjar.ledcm.util.json.ShapeInfo; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.zip.DeflaterOutputStream; import java.util.zip.InflaterOutputStream; import lombok.Cleanup; import lombok.SneakyThrows; import org.lwjgl.BufferUtils; import org.lwjgl.input.Controller; import org.lwjgl.input.Mouse; import org.lwjgl.util.vector.Matrix3f; import org.lwjgl.util.vector.Matrix4f; import org.lwjgl.util.vector.Vector3f; import org.newdawn.slick.geom.Circle; import org.newdawn.slick.geom.Ellipse; import org.newdawn.slick.geom.Polygon; import org.newdawn.slick.geom.Rectangle; import org.newdawn.slick.geom.RoundedRectangle; import org.newdawn.slick.geom.Shape; import org.newdawn.slick.geom.Vector2f; /** * * @author Techjar */ public final class Util { private static final Map<String, ShapeInfo> shapeCache = new HashMap<>(); public static final Gson GSON = new GsonBuilder().create(); private Util() { } public static boolean isValidCharacter(char ch) { return ch >= 32 && ch <= 126; } public static String stackTraceToString(Throwable throwable) { StringWriter stackTrace = new StringWriter(); throwable.printStackTrace(new PrintWriter(stackTrace)); return stackTrace.toString(); } public static org.newdawn.slick.Color convertColor(org.lwjgl.util.Color color) { return new org.newdawn.slick.Color(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha()); } public static org.lwjgl.util.Color convertColor(org.newdawn.slick.Color color) { return new org.lwjgl.util.Color(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha()); } public static Vector2f convertVector(Vector2 vector) { return new Vector2f(vector.getX(), vector.getY()); } public static Vector2 convertVector(Vector2f vector) { return new Vector2(vector.getX(), vector.getY()); } public static Vector3f convertVector(Vector3 vector) { return new Vector3f(vector.getX(), vector.getY(), vector.getZ()); } public static Vector3 convertVector(Vector3f vector) { return new Vector3(vector.getX(), vector.getY(), vector.getZ()); } public static Matrix3f convertMatrix(Mat3 matrix) { Matrix3f out = new Matrix3f(); out.m00 = matrix.m00; out.m01 = matrix.m01; out.m02 = matrix.m02; out.m10 = matrix.m10; out.m11 = matrix.m11; out.m12 = matrix.m12; out.m20 = matrix.m20; out.m21 = matrix.m21; out.m22 = matrix.m22; return out; } public static Matrix4f convertMatrix(Mat4 matrix) { Matrix4f out = new Matrix4f(); out.m00 = matrix.m00; out.m01 = matrix.m01; out.m02 = matrix.m02; out.m03 = matrix.m03; out.m10 = matrix.m10; out.m11 = matrix.m11; out.m12 = matrix.m12; out.m13 = matrix.m13; out.m20 = matrix.m20; out.m21 = matrix.m21; out.m22 = matrix.m22; out.m23 = matrix.m23; out.m30 = matrix.m30; out.m31 = matrix.m31; out.m32 = matrix.m32; out.m33 = matrix.m33; return out; } public static float[] matrixToArray(Matrix3f matrix) { return new float[] { matrix.m00, matrix.m01, matrix.m02, matrix.m10, matrix.m11, matrix.m12, matrix.m20, matrix.m21, matrix.m22 }; } public static float[] matrixToArray(Matrix4f matrix) { return new float[] { matrix.m00, matrix.m01, matrix.m02, matrix.m03, matrix.m10, matrix.m11, matrix.m12, matrix.m13, matrix.m20, matrix.m21, matrix.m22, matrix.m23, matrix.m30, matrix.m31, matrix.m32, matrix.m33 }; } public static float[] matrixToArray(Mat3 matrix) { return new float[] { matrix.m00, matrix.m01, matrix.m02, matrix.m10, matrix.m11, matrix.m12, matrix.m20, matrix.m21, matrix.m22 }; } public static float[] matrixToArray(Mat4 matrix) { return new float[] { matrix.m00, matrix.m01, matrix.m02, matrix.m03, matrix.m10, matrix.m11, matrix.m12, matrix.m13, matrix.m20, matrix.m21, matrix.m22, matrix.m23, matrix.m30, matrix.m31, matrix.m32, matrix.m33 }; } public static void storeColorInBuffer(org.lwjgl.util.Color color, ByteBuffer buffer) { buffer.putFloat(color.getRed() / 255F); buffer.putFloat(color.getGreen() / 255F); buffer.putFloat(color.getBlue() / 255F); buffer.putFloat(color.getAlpha() / 255F); } public static void storeColorInBuffer(org.lwjgl.util.Color color, FloatBuffer buffer) { buffer.put(color.getRed() / 255F); buffer.put(color.getGreen() / 255F); buffer.put(color.getBlue() / 255F); buffer.put(color.getAlpha() / 255F); } public static void storeMatrixInBuffer(Matrix3f matrix, ByteBuffer buffer) { buffer.putFloat(matrix.m00); buffer.putFloat(matrix.m01); buffer.putFloat(matrix.m02); buffer.putFloat(matrix.m10); buffer.putFloat(matrix.m11); buffer.putFloat(matrix.m12); buffer.putFloat(matrix.m20); buffer.putFloat(matrix.m21); buffer.putFloat(matrix.m22); } public static void storeMatrixInBuffer(Matrix4f matrix, ByteBuffer buffer) { buffer.putFloat(matrix.m00); buffer.putFloat(matrix.m01); buffer.putFloat(matrix.m02); buffer.putFloat(matrix.m03); buffer.putFloat(matrix.m10); buffer.putFloat(matrix.m11); buffer.putFloat(matrix.m12); buffer.putFloat(matrix.m13); buffer.putFloat(matrix.m20); buffer.putFloat(matrix.m21); buffer.putFloat(matrix.m22); buffer.putFloat(matrix.m23); buffer.putFloat(matrix.m30); buffer.putFloat(matrix.m31); buffer.putFloat(matrix.m32); buffer.putFloat(matrix.m33); } public static void storeMatrixInBuffer(Mat3 matrix, ByteBuffer buffer) { buffer.putFloat(matrix.m00); buffer.putFloat(matrix.m01); buffer.putFloat(matrix.m02); buffer.putFloat(matrix.m10); buffer.putFloat(matrix.m11); buffer.putFloat(matrix.m12); buffer.putFloat(matrix.m20); buffer.putFloat(matrix.m21); buffer.putFloat(matrix.m22); } public static void storeMatrixInBuffer(Mat4 matrix, ByteBuffer buffer) { buffer.putFloat(matrix.m00); buffer.putFloat(matrix.m01); buffer.putFloat(matrix.m02); buffer.putFloat(matrix.m03); buffer.putFloat(matrix.m10); buffer.putFloat(matrix.m11); buffer.putFloat(matrix.m12); buffer.putFloat(matrix.m13); buffer.putFloat(matrix.m20); buffer.putFloat(matrix.m21); buffer.putFloat(matrix.m22); buffer.putFloat(matrix.m23); buffer.putFloat(matrix.m30); buffer.putFloat(matrix.m31); buffer.putFloat(matrix.m32); buffer.putFloat(matrix.m33); } public static void storeMatrixInBuffer(Mat3 matrix, FloatBuffer buffer) { buffer.put(matrix.m00); buffer.put(matrix.m01); buffer.put(matrix.m02); buffer.put(matrix.m10); buffer.put(matrix.m11); buffer.put(matrix.m12); buffer.put(matrix.m20); buffer.put(matrix.m21); buffer.put(matrix.m22); } public static void storeMatrixInBuffer(Mat4 matrix, FloatBuffer buffer) { buffer.put(matrix.m00); buffer.put(matrix.m01); buffer.put(matrix.m02); buffer.put(matrix.m03); buffer.put(matrix.m10); buffer.put(matrix.m11); buffer.put(matrix.m12); buffer.put(matrix.m13); buffer.put(matrix.m20); buffer.put(matrix.m21); buffer.put(matrix.m22); buffer.put(matrix.m23); buffer.put(matrix.m30); buffer.put(matrix.m31); buffer.put(matrix.m32); buffer.put(matrix.m33); } public static org.lwjgl.util.Color addColors(org.lwjgl.util.Color color1, org.lwjgl.util.Color color2) { return new org.lwjgl.util.Color(MathHelper.clamp(color1.getRed() + color2.getRed(), 0, 255), MathHelper.clamp(color1.getGreen() + color2.getGreen(), 0, 255), MathHelper.clamp(color1.getBlue() + color2.getBlue(), 0, 255)); } public static org.lwjgl.util.Color subtractColors(org.lwjgl.util.Color color1, org.lwjgl.util.Color color2) { return new org.lwjgl.util.Color(MathHelper.clamp(color1.getRed() - color2.getRed(), 0, 255), MathHelper.clamp(color1.getGreen() - color2.getGreen(), 0, 255), MathHelper.clamp(color1.getBlue() - color2.getBlue(), 0, 255)); } public static org.lwjgl.util.Color multiplyColor(org.lwjgl.util.Color color1, double mult) { return new org.lwjgl.util.Color(MathHelper.clamp((int)Math.round(color1.getRed() * mult), 0, 255), MathHelper.clamp((int)Math.round(color1.getGreen() * mult), 0, 255), MathHelper.clamp((int)Math.round(color1.getBlue() * mult), 0, 255)); } public static int encodeCubeVector(Vector3 vector) { Dimension3D bits = getRequiredBits(LEDCubeManager.getLEDManager().getDimensions()); return (int)vector.getZ() | ((int)vector.getX() << bits.z) | ((int)vector.getY() << (bits.x + bits.z)); } public static int encodeCubeVector(int x, int y, int z) { return encodeCubeVector(new Vector3(x, y, z)); } public static Vector3 decodeCubeVector(int number) { Dimension3D dim = LEDCubeManager.getLEDManager().getDimensions(); Dimension3D bits = getRequiredBits(dim); return new Vector3(number & (getNextPowerOfTwo(dim.x) - 1), (number >> (bits.x + bits.z)) & (getNextPowerOfTwo(dim.y) - 1), (number >> bits.z) & (getNextPowerOfTwo(dim.z) - 1)); } public static int getRequiredBits(long value) { int i = 0; for (; i < 64; i++) { if (value == 0) break; value >>= 1; } return i; } public static Dimension3D getRequiredBits(Dimension3D dimension) { return new Dimension3D(getRequiredBits(dimension.x - 1), getRequiredBits(dimension.y - 1), getRequiredBits(dimension.z - 1)); } public static float getAxisValue(Controller con, String name) { if (name == null) return 0; for (int i = 0; i < con.getAxisCount(); i++) { if (name.equals(con.getAxisName(i))) return con.getAxisValue(i); } return 0; } public static <T> List<T> arrayAsListCopy(T... array) { List<T> list = new ArrayList<>(); list.addAll(Arrays.asList(array)); return list; } public static void shuffleArray(Object[] array, Random random) { for (int i = array.length - 1; i > 0; i int index = random.nextInt(i + 1); Object obj = array[index]; array[index] = array[i]; array[i] = obj; } } public static void shuffleArray(int[] array, Random random) { for (int i = array.length - 1; i > 0; i int index = random.nextInt(i + 1); int obj = array[index]; array[index] = array[i]; array[i] = obj; } } public static void shuffleArray(Object[] array) { shuffleArray(array, new Random()); } public static int getMouseX() { //return (int)(Mouse.getX() / ((double)canvas.getWidth() / (double)displayMode.getWidth())); return Mouse.getX(); } public static int getMouseY() { //return (int)((canvas.getHeight() - Mouse.getY()) / ((double)canvas.getHeight() / (double)displayMode.getHeight())); return (int)(LEDCubeManager.getHeight() - Mouse.getY() - 1); } public static Vector2 getMousePos() { return new Vector2(getMouseX(), getMouseY()); } public static Vector2 getMouseCenterOffset() { return new Vector2(getMouseX() - LEDCubeManager.getWidth() / 2, getMouseY() - LEDCubeManager.getHeight() / 2 + 1); } public static Shape getMouseHitbox() { return new Rectangle(getMouseX(), getMouseY(), 1, 1); } /** * Will parse a valid IPv4/IPv6 address and port, may return garbage for invalid address formats. If no port was parsed it will be -1. */ public static IPInfo parseIPAddress(String str) throws UnknownHostException { String ip; int port = -1; boolean ipv6 = false; if (str.indexOf(':') != -1) { if (str.indexOf('[') != -1 && str.indexOf(']') != -1) { ip = str.substring(1, str.indexOf(']')); port = Integer.parseInt(str.substring(str.indexOf(']') + 2)); ipv6 = true; } else if (str.indexOf(':') == str.lastIndexOf(':')) { ip = str.substring(0, str.indexOf(':')); port = Integer.parseInt(str.substring(str.indexOf(':') + 1)); } else ip = str; } else ip = str; return new IPInfo(InetAddress.getByName(ip), port, ipv6); } public static String getFileMD5(File file) throws IOException, NoSuchAlgorithmException { @Cleanup FileInputStream fis = new FileInputStream(file); byte[] bytes = new byte[(int)file.length()]; fis.read(bytes); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(bytes); byte[] digest = md.digest(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < digest.length; i++) { sb.append(Integer.toString((digest[i] & 0xff) + 0x100, 16).substring(1)); } return sb.toString(); } public static String getFileMD5(String file) throws IOException, NoSuchAlgorithmException { return getFileMD5(new File(file)); } @SneakyThrows(FileNotFoundException.class) public static Shape loadShape(String file) { ShapeInfo info = shapeCache.get(file); if (info == null) { info = Util.GSON.fromJson(new FileReader(new File("resources/shapes/" + file + ".shape")), ShapeInfo.class); shapeCache.put(file, info); } switch (info.type.toLowerCase()) { case "circle": return new Circle(0, 0, info.radius); case "ellipse": return new Ellipse(0, 0, info.radius1, info.radius2); case "polygon": if (info.points.length % 2 != 0) throw new IllegalArgumentException("Invalid point array, must have even number of elements"); float[] points = new float[info.points.length]; for (int i = 0; i < points.length; i += 2) { points[i] = info.points[i] + info.pointOffsetX; points[i + 1] = info.points[i + 1] + info.pointOffsetY; } Vector2 pos = findMinimumPoint(points); Polygon poly = new Polygon(points); poly.setX(pos.getX()); poly.setY(pos.getY()); return poly; case "rectangle": Rectangle rect = new Rectangle(0, 0, info.width, info.height); rect.setCenterX(0); rect.setCenterY(0); return rect; case "roundedrectangle": if (info.cornerFlags != null) { int flags = 0; for (String flag : info.cornerFlags) { switch (flag.toUpperCase()) { case "TOP_LEFT": flags |= RoundedRectangle.TOP_LEFT; break; case "TOP_RIGHT": flags |= RoundedRectangle.TOP_RIGHT; break; case "BOTTOM_LEFT": flags |= RoundedRectangle.BOTTOM_LEFT; break; case "BOTTOM_RIGHT": flags |= RoundedRectangle.BOTTOM_RIGHT; break; case "ALL": flags = RoundedRectangle.ALL; break; default: throw new IllegalArgumentException("Invalid corner flag: " + flag); } } rect = new RoundedRectangle(0, 0, info.width, info.height, info.cornerRadius, 25, flags); } else { rect = new RoundedRectangle(0, 0, info.width, info.height, info.cornerRadius); } rect.setCenterX(0); rect.setCenterY(0); return rect; default: throw new IllegalArgumentException("Invalid shape type: " + info.type); } } private static Vector2 findMinimumPoint(float[] points) { if (points.length == 0) return new Vector2(); float minX = points[0]; float minY = points[1]; for (int i = 0; i < points.length; i += 2) { minX = Math.min(points[i], minX); minY = Math.min(points[i + 1], minY); } return new Vector2(minX, minY); } /** * Compresses the byte array using deflate algorithm. */ public static byte[] compresssBytes(byte[] bytes) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); try (DeflaterOutputStream dos = new DeflaterOutputStream(out)) { dos.write(bytes); } return out.toByteArray(); } /** * Decompresses the byte array using deflate algorithm. */ public static byte[] decompresssBytes(byte[] bytes) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); try (InflaterOutputStream dos = new InflaterOutputStream(out)) { dos.write(bytes); } return out.toByteArray(); } public static float[] floatListToArray(List<Float> list) { float[] array = new float[list.size()]; for (int i = 0; i < array.length; i++) { array[i] = list.get(i); } return array; } public static short floatToShortBits(float fval) { int fbits = Float.floatToIntBits(fval); int sign = fbits >>> 16 & 0x8000; int val = (fbits & 0x7fffffff) + 0x1000; if(val >= 0x47800000) { if((fbits & 0x7fffffff) >= 0x47800000) { if(val < 0x7f800000) return (short)(sign | 0x7c00); return (short)(sign | 0x7c00 | (fbits & 0x007fffff) >>> 13); } return (short)(sign | 0x7bff); } if(val >= 0x38800000) return (short)(sign | val - 0x38000000 >>> 13); if(val < 0x33000000) return (short)(sign); val = (fbits & 0x7fffffff) >>> 23; return (short)(sign | ((fbits & 0x7fffff | 0x800000) + (0x800000 >>> val - 102) >>> 126 - val)); } public static float shortBitsToFloat(short hbits) { int mant = hbits & 0x03ff; int exp = hbits & 0x7c00; if(exp == 0x7c00) exp = 0x3fc00; else if(exp != 0) { exp += 0x1c000; if(mant == 0 && exp > 0x1c400) return Float.intBitsToFloat((hbits & 0x8000) << 16 | exp << 13 | 0x3ff); } else if(mant != 0) { exp = 0x1c400; do { mant <<= 1; exp -= 0x400; } while((mant & 0x400) == 0); mant &= 0x3ff; } return Float.intBitsToFloat((hbits & 0x8000) << 16 | (exp | mant) << 13); } public static byte[] readFully(InputStream in) throws IOException { @Cleanup ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] bytes = new byte[4096]; int count; while ((count = in.read(bytes, 0, bytes.length)) != -1) { out.write(bytes, 0, count); } return out.toByteArray(); } public static String readFile(File file) throws FileNotFoundException, IOException { @Cleanup FileInputStream in = new FileInputStream(file); byte[] bytes = readFully(in); return new String(bytes, "UTF-8"); } public static long microTime() { return System.nanoTime() / 1000L; } public static long milliTime() { return System.nanoTime() / 1000000L; } public static Rectangle clipRectangle(Rectangle toClip, Rectangle clipTo) { if (!toClip.intersects(clipTo)) return new Rectangle(0, 0, 0, 0); float newX = MathHelper.clamp(toClip.getX(), clipTo.getX(), clipTo.getMaxX()); float newY = MathHelper.clamp(toClip.getY(), clipTo.getY(), clipTo.getMaxY()); float newWidth = MathHelper.clamp(toClip.getWidth(), 0, clipTo.getWidth() - (newX - clipTo.getX())); float newHeight = MathHelper.clamp(toClip.getHeight(), 0, clipTo.getHeight() - (newY - clipTo.getY())); return new Rectangle(newX, newY, newWidth, newHeight); } public static long bytesToMB(long bytes) { return bytes / 1048576; } public static String bytesToMBString(long bytes) { return bytesToMB(bytes) + " MB"; } public static int getNextPowerOfTwo(int number) { int ret = Integer.highestOneBit(number); return ret < number ? ret << 1 : ret; } public static boolean isPowerOfTwo(int number) { return (number != 0) && (number & (number - 1)) == 0; } public static final class IPInfo { private InetAddress address; private int port; private boolean ipv6; private IPInfo(InetAddress address, int port, boolean ipv6) { this.address = address; this.port = port; this.ipv6 = ipv6; } public InetAddress getAddress() { return address; } public int getPort() { return port; } public boolean isIPv6() { return ipv6; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final IPInfo other = (IPInfo)obj; if (this.address != other.address && (this.address == null || !this.address.equals(other.address))) { return false; } if (this.port != other.port) { return false; } return true; } @Override public int hashCode() { int hash = 5; hash = 67 * hash + (this.address != null ? this.address.hashCode() : 0); hash = 67 * hash + this.port; return hash; } @Override public String toString() { return port < 0 ? address.getHostAddress() : ipv6 ? '[' + address.getHostAddress() + "]:" + port : address.getHostAddress() + ':' + port; } } }
package com.sometrik.framework; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Timer; import java.util.TimerTask; import com.android.trivialdrivesample.util.IabHelper; import com.android.trivialdrivesample.util.IabHelper.IabAsyncInProgressException; import com.android.trivialdrivesample.util.IabResult; import com.android.trivialdrivesample.util.Inventory; import com.android.trivialdrivesample.util.Purchase; import android.R.style; import android.app.ActionBar; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.res.AssetManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Typeface; import android.text.Editable; import android.text.Html; import android.text.InputType; import android.text.TextUtils.TruncateAt; import android.text.TextWatcher; import android.text.method.LinkMovementMethod; import android.text.method.ScrollingMovementMethod; import android.util.Log; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.Window; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.GridView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.PopupMenu; import android.widget.PopupMenu.OnMenuItemClickListener; import android.widget.ScrollView; import android.widget.Switch; import android.widget.TableLayout; import android.widget.TextView; public class NativeCommand { private int internalId = 0; private int childInternalId = 0; private int value = 0; private int flags = 0; private String textValue = ""; private String textValue2 = ""; private CommandType command; private String key; private FrameWork frame; private ArrayList<PopupMenu> menuList = new ArrayList<PopupMenu>(); private int rowNumber = 0; private int columnNumber = 0; private final int FLAG_PADDING_LEFT = 1; private final int FLAG_PADDING_RIGHT = 2; private final int FLAG_PADDING_TOP = 4; private final int FLAG_PADDING_BOTTOM = 8; private final int FLAG_PASSWORD = 16; private final int FLAG_NUMERIC = 32; private final int FLAG_HYPERLINK = 64; private final int FLAG_USE_PURCHASES_API = 128; public enum CommandType { CREATE_PLATFORM, CREATE_APPLICATION, CREATE_BASICVIEW, CREATE_FORMVIEW, CREATE_OPENGL_VIEW, CREATE_TEXTFIELD, // For viewing single value CREATE_TEXTVIEW, // For viewing multiline text CREATE_LISTVIEW, // For viewing lists CREATE_GRIDVIEW, // For viewing tables CREATE_BUTTON, CREATE_SWITCH, CREATE_PICKER, // called Spinner in Android CREATE_LINEAR_LAYOUT, CREATE_TABLE_LAYOUT, CREATE_AUTO_COLUMN_LAYOUT, CREATE_HEADING_TEXT, CREATE_TEXT, CREATE_DIALOG, // For future CREATE_IMAGEVIEW, CREATE_ACTION_SHEET, CREATE_CHECKBOX, CREATE_RADIO_GROUP, CREATE_SEPARATOR, CREATE_SLIDER, CREATE_ACTIONBAR, DELETE_ELEMENT, SHOW_MESSAGE_DIALOG, SHOW_INPUT_DIALOG, SHOW_ACTION_SHEET, LAUNCH_BROWSER, POST_NOTIFICATION, HISTORY_GO_BACK, HISTORY_GO_FORWARD, SET_INT_VALUE, // Sets value of radio groups, checkboxes and pickers SET_TEXT_VALUE, // Sets value of textfields, labels and images SET_LABEL, // Sets label for buttons and checkboxes SET_ENABLED, SET_STYLE, SET_ERROR, UPDATE_PREFERENCE, ADD_OPTION, ADD_COLUMN, QUIT_APP, // Timers CREATE_TIMER, // In-app purchases LIST_PRODUCTS, BUY_PRODUCT, LIST_PURCHASES, CONSUME_PURCHASE } public NativeCommand(FrameWork frame, int messageTypeId, int internalId, int childInternalId, int value, byte[] textValue, byte[] textValue2, int flags, int rowNumber, int columnNumber){ this.frame = frame; command = CommandType.values()[messageTypeId]; this.internalId = internalId; this.childInternalId = childInternalId; this.value = value; this.flags = flags; this.rowNumber = rowNumber; this.columnNumber = columnNumber; if (textValue != null) { this.textValue = new String(textValue, frame.getCharset()); } if (textValue2 != null) { this.textValue2 = new String(textValue2, frame.getCharset()); } } public NativeCommand(FrameWork frame, int messageTypeId, int internalId, int childInternalId, int value, byte[] textValue, byte[] textValue2, int flags){ this.frame = frame; command = CommandType.values()[messageTypeId]; this.internalId = internalId; this.childInternalId = childInternalId; this.value = value; this.flags = flags; if (textValue != null) { this.textValue = new String(textValue, frame.getCharset()); } if (textValue2 != null) { this.textValue2 = new String(textValue2, frame.getCharset()); } } public void apply(NativeCommandHandler view) { System.out.println("Processing message " + command + " id: " + internalId + " Child id: " + getChildInternalId()); switch (command) { case CREATE_FORMVIEW: FWScrollView scrollView = new FWScrollView(frame); scrollView.setId(getChildInternalId()); FrameWork.addToViewList(scrollView); if (view == null){ System.out.println("view was null"); if (frame.getCurrentViewId() == 0){ scrollView.setValue(1); } } else { view.addChild(scrollView); } break; case CREATE_BASICVIEW: case CREATE_LINEAR_LAYOUT: FWLayout layout = createLinearLayout(); view.addChild(layout); break; case CREATE_AUTO_COLUMN_LAYOUT:{ FWAuto auto = new FWAuto(frame); auto.setId(getChildInternalId()); FrameWork.addToViewList(auto); view.addChild(auto); } break; case CREATE_TABLE_LAYOUT: FWTable table = createTableLayout(false); view.addChild(table); break; case CREATE_BUTTON: FWButton button = createButton(); view.addChild(button); break; case CREATE_PICKER: FWPicker picker = createSpinner(); view.addChild(picker); break; case CREATE_SWITCH: FWSwitch click = createSwitch(); view.addChild(click); break; case CREATE_GRIDVIEW: //TODO //Fix from being debug status FWLayout debugList = createDebugResultsScreen(); view.addChild(debugList); break; case CREATE_TIMER: Timer timer = new Timer(); timer.schedule((new TimerTask(){ @Override public void run() { FrameWork.timerEvent(System.currentTimeMillis() / 1000, internalId, childInternalId); } }), value, value); case CREATE_CHECKBOX: FWCheckBox checkBox = createCheckBox(); FrameWork.addToViewList(checkBox); view.addChild(checkBox); break; case CREATE_OPENGL_VIEW: NativeSurface surface = frame.createNativeOpenGLView(childInternalId); break; case CREATE_TEXTVIEW: FWEditText editTextView = createBigEditText(); view.addChild(editTextView); break; case CREATE_TEXTFIELD: FWEditText editText = createEditText(); view.addChild(editText); break; case CREATE_RADIO_GROUP: FWRadioGroup radioGroup = new FWRadioGroup(frame); radioGroup.setId(childInternalId); break; case CREATE_HEADING_TEXT: case CREATE_TEXT: FWTextView textView = createTextView(); view.addChild(textView); break; case CREATE_IMAGEVIEW: ImageView imageView = createImageView(); view.addChild(imageView); break; case ADD_OPTION: // Forward Command to FWPicker view.addOption(getValue(), getTextValue()); break; case POST_NOTIFICATION: frame.createNotification(getTextValue(), getTextValue2()); break; case CREATE_APPLICATION: frame.setAppId(getInternalId()); frame.setSharedPreferences(textValue); if (isSet(FLAG_USE_PURCHASES_API)) { System.out.println("Initializing purchaseHelper"); frame.initializePurchaseHelper(textValue2, new IabHelper.OnIabSetupFinishedListener() { @Override public void onIabSetupFinished(IabResult result) { if (result.isSuccess()) { System.out.println("PurchaseHelper successfully setup"); sendInventory(frame.getPurchaseHelperInventory()); } else { System.out.println("PurchaseHelper failed to setup"); } } }); } break; case SET_INT_VALUE: view.setValue(getValue()); break; case SET_TEXT_VALUE: if (view != null) { view.setValue(textValue); } else { Log.d("Command", "View null on set Text"); NativeCommandHandler list = FrameWork.views.get(9); if (list == null) { Log.d("Command", "Yes list was null"); } list.addData(rowNumber, columnNumber, textValue); // addDataToDebugList(rowNumber, columnNumber, textValue); } break; case SET_ENABLED: view.setViewEnabled(value != 0); break; case SET_STYLE: view.setStyle(textValue, textValue2); break; case SET_ERROR: view.setError(value != 0, textValue); break; case LAUNCH_BROWSER: frame.launchBrowser(getTextValue()); break; case SHOW_MESSAGE_DIALOG: showMessageDialog(textValue, textValue2); break; case SHOW_INPUT_DIALOG: showInputDialog(textValue, textValue2); break; case CREATE_ACTION_SHEET: createActionSheet(); break; case CREATE_ACTIONBAR: //TODO not everything is set ActionBar ab = frame.getActionBar(); ab.setTitle(textValue); break; case QUIT_APP: // TODO frame.finish(); break; case UPDATE_PREFERENCE: //Now stores String value to string key. frame.getPreferencesEditor().putString(textValue, textValue2); frame.getPreferencesEditor().apply(); break; case DELETE_ELEMENT: FrameWork.views.remove(childInternalId); ((ViewGroup) view).removeViewAt(childInternalId); break; case BUY_PRODUCT: try { launchPurchase(textValue); } catch (IabAsyncInProgressException e) { e.printStackTrace(); System.out.println("Error on launchPurchase with message: " + e.getMessage()); } default: System.out.println("Message couldn't be handled"); break; } } private void createActionSheet(){ PopupMenu menu = new PopupMenu(frame, null); menu.setOnMenuItemClickListener(new OnMenuItemClickListener(){ @Override public boolean onMenuItemClick(MenuItem item) { return false; } }); menuList.add(menu); } private FWTable createTableLayout(boolean autoSize){ FWTable table = new FWTable(frame); table.setId(getChildInternalId()); if (autoSize){ table.setAutoSize(true); } else { table.setColumnCount(value); } table.setStretchAllColumns(true); table.setShrinkAllColumns(true); FrameWork.addToViewList(table); return table; } private FWSwitch createSwitch() { FWSwitch click = new FWSwitch(frame); click.setId(childInternalId); if (textValue != "") { click.setTextOn(textValue); } if (textValue2 != "") { click.setTextOff(textValue2); } click.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { frame.intChangedEvent(System.currentTimeMillis() / 1000.0, buttonView.getId(), isChecked ? 1 : 0); } }); FrameWork.addToViewList(click); return click; } private ImageView createImageView() { ImageView imageView = new ImageView(frame); imageView.setId(childInternalId); try { InputStream is = frame.getAssets().open(textValue); Bitmap bitmap = BitmapFactory.decodeStream(is); imageView.setImageBitmap(bitmap); return imageView; } catch (IOException e) { e.printStackTrace(); System.out.println("error loading asset file to imageView"); System.exit(1); } return null; } private FWLayout createLinearLayout() { FWLayout layout = new FWLayout(frame); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); // params.weight = 1.0f; // params.gravity = Gravity.FILL; // layout.setBaselineAligned(false); layout.setLayoutParams(params); layout.setId(getChildInternalId()); FrameWork.addToViewList(layout); if (getValue() == 2) { layout.setOrientation(LinearLayout.HORIZONTAL); } else { layout.setOrientation(LinearLayout.VERTICAL); } return layout; } private FWButton createButton() { FWButton button = new FWButton(frame); button.setId(getChildInternalId()); button.setText(getTextValue()); ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); button.setLayoutParams(params); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { System.out.println("Java: my button was clicked with id " + getChildInternalId()); if (!FrameWork.transitionAnimation) { frame.intChangedEvent(System.currentTimeMillis() / 1000.0, getChildInternalId(), 1); } } }); FrameWork.addToViewList(button); return button; } private FWEditText createEditText(){ final FWEditText editText = new FWEditText(frame); editText.setId(getChildInternalId()); editText.setText(getTextValue()); editText.setSingleLine(); if (isSet(FLAG_PASSWORD) && isSet(FLAG_NUMERIC)){ editText.setInputType(InputType.TYPE_NUMBER_VARIATION_PASSWORD); } else if (isSet(FLAG_PASSWORD)) { editText.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD); } else if (isSet(FLAG_NUMERIC)){ editText.setInputType(InputType.TYPE_CLASS_NUMBER); } editText.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable editable) { String inputText = editable.toString(); byte[] b = inputText.getBytes(frame.getCharset()); frame.textChangedEvent(System.currentTimeMillis() / 1000.0, getChildInternalId(), b); } public void beforeTextChanged(CharSequence s, int start, int count, int after) {} public void onTextChanged(CharSequence s, int start, int before, int count) {} }); FrameWork.addToViewList(editText); return editText; } private FWEditText createBigEditText() { final FWEditText editText = new FWEditText(frame); editText.setId(getChildInternalId()); editText.setText(getTextValue()); editText.setVerticalScrollBarEnabled(true); editText.setMovementMethod(new ScrollingMovementMethod()); editText.addDelayedChangeListener(getChildInternalId()); FrameWork.addToViewList(editText); return editText; } private FWPicker createSpinner(){ FWPicker picker = new FWPicker(frame); picker.setId(getChildInternalId()); FrameWork.addToViewList(picker); return picker; } private FWCheckBox createCheckBox() { FWCheckBox checkBox = new FWCheckBox(frame); checkBox.setPadding(0, 0, 10, 0); checkBox.setId(childInternalId); if (textValue != "") { checkBox.setText(textValue); } checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton box, boolean isChecked) { frame.intChangedEvent(System.currentTimeMillis() / 1000.0, childInternalId, isChecked ? 1 : 0); } }); return checkBox; } private FWTextView createTextView() { FWTextView textView = new FWTextView(frame); textView.setId(getChildInternalId()); // textView.setSingleLine(); if (isSet(FLAG_HYPERLINK)) { textView.setMovementMethod(LinkMovementMethod.getInstance()); String text = "<a href='" + textValue2 + "'>" + textValue + "</a>"; textView.setText(Html.fromHtml(text)); } else { textView.setText(textValue); } FrameWork.addToViewList(textView); return textView; } // Create dialog with user text input private void showInputDialog(String title, String message) { System.out.println("Creating input dialog"); AlertDialog.Builder builder; builder = new AlertDialog.Builder(frame); // Building an alert builder.setTitle(title); builder.setMessage(message); builder.setCancelable(true); final EditText input = new EditText(frame); input.setInputType(InputType.TYPE_CLASS_TEXT); builder.setView(input); builder.setOnCancelListener(new OnCancelListener(){ @Override public void onCancel(DialogInterface arg0) { frame.endModal(System.currentTimeMillis() / 1000.0, 0, null); } }); // Negative button listener builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { frame.endModal(System.currentTimeMillis() / 1000.0, 0, null); dialog.cancel(); } }); // Positive button listener builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { String inputText = String.valueOf(input.getText()); byte[] b = inputText.getBytes(frame.getCharset()); frame.endModal(System.currentTimeMillis() / 1000.0, 1, b); dialog.cancel(); } }); // Create and show the alert AlertDialog alert = builder.create(); alert.show(); } // create Message dialog private void showMessageDialog(String title, String message) { System.out.println("creating message dialog"); AlertDialog.Builder builder; builder = new AlertDialog.Builder(frame); // Building an alert builder.setTitle(title); builder.setMessage(message); builder.setCancelable(true); builder.setOnCancelListener(new OnCancelListener(){ @Override public void onCancel(DialogInterface arg0) { frame.endModal(System.currentTimeMillis() / 1000.0, 0, null); } }); // Positive button listener builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { frame.endModal(System.currentTimeMillis() / 1000.0, 1, null); dialog.dismiss(); } }); // Create and show the alert AlertDialog alert = builder.create(); alert.show(); System.out.println("message dialog created"); } private FWLayout createDebugResultsScreen(){ FWLayout mainLayout = new FWLayout(frame); mainLayout.setOrientation(LinearLayout.VERTICAL); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); mainLayout.setLayoutParams(params); params.weight = 1; LinearLayout titleLayout = new LinearLayout(frame); LinearLayout.LayoutParams params2 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); titleLayout.setLayoutParams(params2); titleLayout.setOrientation(LinearLayout.HORIZONTAL); titleLayout.addView(createDebugTextView("Nimi")); titleLayout.addView(createDebugTextView("Etäisyys")); titleLayout.addView(createDebugTextView("Auki")); titleLayout.addView(createDebugTextView("Jono")); mainLayout.addView(titleLayout); ScrollView scrollView = new ScrollView(frame); FWList list = new FWList(frame, new FWAdapter(frame, null)); list.setId(childInternalId); frame.addToViewList(list); list.setLayoutParams(params2); mainLayout.addView(list); return mainLayout; } private TextView createDebugTextView(String text){ LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); params.weight = 1; TextView titleView = new TextView(frame); titleView.setTypeface(null, Typeface.BOLD); titleView.setText(text); titleView.setLayoutParams(params); return titleView; } private void launchPurchase(final String productId) throws IabAsyncInProgressException { // Sku = product id from google account frame.getPurchaseHelper().launchPurchaseFlow(frame, productId, IabHelper.ITEM_TYPE_INAPP, null, 1, new IabHelper.OnIabPurchaseFinishedListener() { @Override public void onIabPurchaseFinished(IabResult result, Purchase info) { if (result.isSuccess()) { System.out.println("Purchase of product id " + productId + " completed"); FrameWork.onPurchaseEvent(System.currentTimeMillis() / 1000.0, frame.getAppId(), info.getSku(), true, info.getPurchaseTime() / 1000.0); // TODO } else { System.out.println("Purchase of product id " + productId + " failed"); // TODO } } }, ""); } private void sendInventory(Inventory inventory) { List<Purchase> purchaseList = inventory.getAllPurchases(); System.out.println("getting purchase history. Purchase list size: " + purchaseList.size()); for (Purchase purchase : inventory.getAllPurchases()) { FrameWork.onPurchaseEvent(System.currentTimeMillis() / 1000.0, frame.getAppId(), purchase.getSku(), false, purchase.getPurchaseTime() / 1000.0); } } private Boolean isSet(int flag) { return (flags & flag) != 0; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public int getInternalId() { return internalId; } public int getChildInternalId() { return childInternalId; } public String getTextValue() { return textValue; } public String getTextValue2() { return textValue2; } public CommandType getCommand() { return command; } public int getValue() { return value; } }
package com.tradle.react; import android.content.Context; import android.net.wifi.WifiManager; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import android.util.SparseArray; import com.facebook.common.logging.FLog; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.Callback; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.WritableMap; import com.facebook.react.modules.core.DeviceEventManagerModule; import java.io.IOException; import java.net.SocketException; import java.net.UnknownHostException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * The NativeModule in charge of storing active {@link UdpSocketClient}s, and acting as an api layer. */ public final class UdpSockets extends ReactContextBaseJavaModule implements UdpSocketClient.OnDataReceivedListener, UdpSocketClient.OnRuntimeExceptionListener { private static final String TAG = "UdpSockets"; private static final int N_THREADS = 2; private WifiManager.MulticastLock mMulticastLock; private final SparseArray<UdpSocketClient> mClients = new SparseArray<>(); private final ExecutorService executorService = Executors.newFixedThreadPool(N_THREADS); public UdpSockets(ReactApplicationContext reactContext) { super(reactContext); } @NonNull @Override public String getName() { return TAG; } @Override public void onCatalystInstanceDestroy() { executorService.execute(new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < mClients.size(); i++) { UdpSocketClient client = mClients.valueAt(i); client.close(); if (mMulticastLock != null && mMulticastLock.isHeld() && client.isMulticast()) { // drop the multi-cast lock if this is a multi-cast client mMulticastLock.release(); } } mClients.clear(); } })); } /** * Private method to retrieve clients. */ private UdpSocketClient findClient(final Integer cId, final Callback callback) { final UdpSocketClient client = mClients.get(cId); if (client == null) { if (callback == null) { FLog.e(TAG, "missing callback parameter."); } else { callback.invoke(UdpErrorUtil.getError(null, "no client found with id " + cId), null); } } return client; } /** * Creates a {@link UdpSocketClient} with the given ID, and options */ @ReactMethod public void createSocket(final Integer cId, final ReadableMap options) { if (cId == null) { FLog.e(TAG, "createSocket called with nil id parameter."); return; } UdpSocketClient client = mClients.get(cId); if (client != null) { FLog.e(TAG, "createSocket called twice with the same id."); return; } mClients.put(cId, new UdpSocketClient(this, this)); } /** * Binds to a given port and address, and begins listening for data. */ @ReactMethod public void bind(final Integer cId, final Integer port, final @Nullable String address, final @Nullable ReadableMap options, final Callback callback) { executorService.execute(new Thread(new Runnable() { @Override public void run() { UdpSocketClient client = findClient(cId, callback); if (client == null) { return; } try { client.bind(port, address); WritableMap result = Arguments.createMap(); result.putString("address", address); result.putInt("port", port); callback.invoke(null, result); } catch (Exception e) { // Socket is already bound or a problem occurred during binding callback.invoke(UdpErrorUtil.getError(null, e.getMessage())); } } })); } /** * Joins a multi-cast group */ @SuppressWarnings("unused") @ReactMethod public void addMembership(final Integer cId, final String multicastAddress) { executorService.execute(new Thread(new Runnable() { @Override public void run() { UdpSocketClient client = findClient(cId, null); if (client == null) { return; } if (mMulticastLock == null) { WifiManager wifiMgr = (WifiManager) getReactApplicationContext() .getApplicationContext() .getSystemService(Context.WIFI_SERVICE); mMulticastLock = wifiMgr.createMulticastLock("react-native-udp"); mMulticastLock.setReferenceCounted(true); } try { mMulticastLock.acquire(); client.addMembership(multicastAddress); } catch (IllegalStateException ise) { // an exception occurred if (mMulticastLock != null && mMulticastLock.isHeld()) { mMulticastLock.release(); } FLog.e(TAG, "addMembership", ise); } catch (UnknownHostException uhe) { // an exception occurred if (mMulticastLock != null && mMulticastLock.isHeld()) { mMulticastLock.release(); } FLog.e(TAG, "addMembership", uhe); } catch (IOException ioe) { // an exception occurred if (mMulticastLock != null && mMulticastLock.isHeld()) { mMulticastLock.release(); } FLog.e(TAG, "addMembership", ioe); } } })); } /** * Leaves a multi-cast group */ @ReactMethod public void dropMembership(final Integer cId, final String multicastAddress) { executorService.execute(new Thread(new Runnable() { @Override public void run() { UdpSocketClient client = findClient(cId, null); if (client == null) { return; } try { client.dropMembership(multicastAddress); } catch (IOException ioe) { // an exception occurred FLog.e(TAG, "dropMembership", ioe); } finally { if (mMulticastLock != null && mMulticastLock.isHeld()) { mMulticastLock.release(); } } } })); } /** * Sends udp data via the {@link UdpSocketClient} */ @ReactMethod public void send(final Integer cId, final String base64String, final Integer port, final String address, final Callback callback) { executorService.execute(new Thread(new Runnable() { @Override public void run() { UdpSocketClient client = findClient(cId, callback); if (client == null) { return; } try { client.send(base64String, port, address, callback); } catch (Exception exception) { callback.invoke((UdpErrorUtil.getError(null, exception.getMessage()))); } } })); } /** * Closes a specific client's socket, and removes it from the list of known clients. */ @ReactMethod public void close(final Integer cId, final Callback callback) { executorService.execute(new Thread(new Runnable() { @Override public void run() { UdpSocketClient client = findClient(cId, callback); if (client == null) { return; } if (mMulticastLock != null && mMulticastLock.isHeld() && client.isMulticast()) { // drop the multi-cast lock if this is a multi-cast client mMulticastLock.release(); } client.close(); callback.invoke(); mClients.remove(cId); } })); } /** * Sets the broadcast flag for a given client. */ @ReactMethod public void setBroadcast(final Integer cId, final Boolean flag, final Callback callback) { executorService.execute(new Thread(new Runnable() { @Override public void run() { UdpSocketClient client = findClient(cId, callback); if (client == null) { return; } try { client.setBroadcast(flag); callback.invoke(); } catch (SocketException e) { callback.invoke(UdpErrorUtil.getError(null, e.getMessage())); } } })); } /** * Notifies the javascript layer upon data receipt. */ @Override public void didReceiveData(final UdpSocketClient socket, final String data, final String host, final int port) { final long ts = System.currentTimeMillis(); executorService.execute(new Thread(new Runnable() { @Override public void run() { int clientID = -1; for (int i = 0; i < mClients.size(); i++) { clientID = mClients.keyAt(i); // get the object by the key. if (socket.equals(mClients.get(clientID))) { break; } } if (clientID == -1) { return; } WritableMap eventParams = Arguments.createMap(); eventParams.putString("data", data); eventParams.putString("address", host); eventParams.putInt("port", port); // Use string for ts since it's 64 bits and putInt is only 32 eventParams.putString("ts", Long.toString(ts)); ReactContext reactContext = UdpSockets.this.getReactApplicationContext(); reactContext .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit("udp-" + clientID + "-data", eventParams); } })); } /** * Logs an error that happened during or prior to data reception. */ @Override public void didReceiveError(UdpSocketClient client, String message) { FLog.e(TAG, message); } /** * Sends RuntimeExceptions to the application context handler. */ @Override public void didReceiveException(RuntimeException exception) { getReactApplicationContext().handleException(exception); } }
package net.client.im; import android.app.Application; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.util.Log; import net.client.im.core.KeepAliveDaemon; import net.client.im.core.LocalUDPSocketProvider; public class ClientCoreSDK { private static final String TAG = ClientCoreSDK.class.getSimpleName(); public static boolean DEBUG = true; public static boolean autoReLogin = true; private static ClientCoreSDK instance = null; private boolean mIsInit = false; private boolean localDeviceNetworkOk = true; private boolean connectedToServer = true; private boolean loginHasInit = false; private int currentUserId = -1; private String currentLoginName = null; private String currentLoginPsw = null; private String currentLoginExtra = null; private ChatBaseEvent chatBaseEvent = null; private ChatTransDataEvent chatTransDataEvent = null; private MessageQoSEvent messageQoSEvent = null; private Context context = null; private final BroadcastReceiver networkConnectionStatusBroadcastReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { ConnectivityManager connectMgr = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE); NetworkInfo mobNetInfo = connectMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); NetworkInfo wifiNetInfo = connectMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (!(mobNetInfo != null && mobNetInfo.isConnected()) && !(wifiNetInfo != null && wifiNetInfo.isConnected())) { Log.e(ClientCoreSDK.TAG, "IMCORE!"); ClientCoreSDK.this.localDeviceNetworkOk = false; LocalUDPSocketProvider.getInstance().closeLocalUDPSocket(); } else { if (ClientCoreSDK.DEBUG) { Log.e(ClientCoreSDK.TAG, "IMCORE!"); } ClientCoreSDK.this.localDeviceNetworkOk = true; LocalUDPSocketProvider.getInstance().closeLocalUDPSocket(); } } }; public static ClientCoreSDK getInstance() { if (instance == null) instance = new ClientCoreSDK(); return instance; } public void init(Context context) { if (!this.mIsInit) { if (context == null) { throw new IllegalArgumentException("context can't be null!"); } // Applicationcontext // AndroidAPPApplicationActivity // MobileIMSDK // APPApplication if(context instanceof Application) this.context = context; else { this.context = context.getApplicationContext(); } IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); this.context.registerReceiver(networkConnectionStatusBroadcastReceiver, intentFilter); this.mIsInit = true; } } public void release() { AutoReLoginDaemon.getInstance(context).stop(); // QoS QoS4SendDaemon.getInstance(context).stop(); // Keep Alive KeepAliveDaemon.getInstance(context).stop(); LocalUDPDataReciever.getInstance(context).stop(); // QoS QoS4ReciveDaemon.getInstance(context).stop(); // Socket LocalUDPSocketProvider.getInstance().closeLocalUDPSocket(); try { this.context.unregisterReceiver(this.networkConnectionStatusBroadcastReceiver); } catch (Exception e) { Log.w(TAG, e.getMessage(), e); } this.mIsInit = false; setLoginHasInit(false); setConnectedToServer(false); } public int getCurrentUserId() { return this.currentUserId; } public ClientCoreSDK setCurrentUserId(int currentUserId) { this.currentUserId = currentUserId; return this; } public String getCurrentLoginName() { return this.currentLoginName; } public ClientCoreSDK setCurrentLoginName(String currentLoginName) { this.currentLoginName = currentLoginName; return this; } public String getCurrentLoginPsw() { return this.currentLoginPsw; } public void setCurrentLoginPsw(String currentLoginPsw) { this.currentLoginPsw = currentLoginPsw; } public String getCurrentLoginExtra() { return currentLoginExtra; } public ClientCoreSDK setCurrentLoginExtra(String currentLoginExtra) { this.currentLoginExtra = currentLoginExtra; return this; } public boolean isLoginHasInit() { return this.loginHasInit; } public ClientCoreSDK setLoginHasInit(boolean loginHasInit) { this.loginHasInit = loginHasInit; return this; } public boolean isConnectedToServer() { return this.connectedToServer; } public void setConnectedToServer(boolean connectedToServer) { this.connectedToServer = connectedToServer; } public boolean isInitialed() { return this.mIsInit; } public boolean isLocalDeviceNetworkOk() { return this.localDeviceNetworkOk; } public void setChatBaseEvent(ChatBaseEvent chatBaseEvent) { this.chatBaseEvent = chatBaseEvent; } public ChatBaseEvent getChatBaseEvent() { return this.chatBaseEvent; } public void setChatTransDataEvent(ChatTransDataEvent chatTransDataEvent) { this.chatTransDataEvent = chatTransDataEvent; } public ChatTransDataEvent getChatTransDataEvent() { return this.chatTransDataEvent; } public void setMessageQoSEvent(MessageQoSEvent messageQoSEvent) { this.messageQoSEvent = messageQoSEvent; } public MessageQoSEvent getMessageQoSEvent() { return this.messageQoSEvent; } }
package org.spine3.base; import com.google.common.base.Function; import com.google.common.collect.ImmutableMap; import com.google.protobuf.Any; import com.google.protobuf.Message; import com.google.protobuf.MessageOrBuilder; import com.google.protobuf.StringValue; import com.google.protobuf.Timestamp; import com.google.protobuf.UInt32Value; import com.google.protobuf.UInt64Value; import com.google.protobuf.util.Timestamps; import org.spine3.Internal; import javax.annotation.Nullable; import java.util.Collection; import java.util.Map; import java.util.UUID; import java.util.regex.Pattern; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.Maps.newHashMap; import static com.google.protobuf.TextFormat.shortDebugString; import static java.util.Collections.synchronizedMap; import static org.spine3.protobuf.AnyPacker.unpack; /** * This class manages conversion of identifies to/from string. * * <p>In addition to utility methods for the conversion, it provides {@link ConverterRegistry} * which allows to provide custom conversion logic for user-defined types of identifies. * * @author Alexander Litus */ public class Identifiers { /** A {@code null} ID string representation. */ public static final String NULL_ID = "NULL"; /** An empty ID string representation. */ public static final String EMPTY_ID = "EMPTY"; /** The suffix of ID fields. */ public static final String ID_PROPERTY_SUFFIX = "id"; private static final Pattern PATTERN_COLON_SPACE = Pattern.compile(": "); private static final Pattern PATTERN_COLON = Pattern.compile(":"); private static final Pattern PATTERN_T = Pattern.compile("T"); private static final String EQUAL_SIGN = "="; private Identifiers() {} public static <I> String idToString(@Nullable I id) { if (id == null) { return NULL_ID; } final Identifier<?> identifier; if (id instanceof Any) { final Message unpacked = unpack((Any) id); identifier = Identifier.fromMessage(unpacked); } else { identifier = Identifier.from(id); } final String result = identifier.toString(); return result; } static String idMessageToString(Message message) { final String result; final ConverterRegistry registry = ConverterRegistry.getInstance(); if (registry.containsConverter(message)) { final Function<Message, String> converter = registry.getConverter(message); result = converter.apply(message); } else { result = convert(message); } return result; } private static String convert(Message message) { final Collection<Object> values = message.getAllFields().values(); final String result; if (values.isEmpty()) { result = EMPTY_ID; } else if (values.size() == 1) { final Object object = values.iterator().next(); if (object instanceof Message) { result = idMessageToString((Message) object); } else { result = object.toString(); } } else { result = messageWithMultipleFieldsToString(message); } return result; } private static String messageWithMultipleFieldsToString(MessageOrBuilder message) { String result = shortDebugString(message); result = PATTERN_COLON_SPACE.matcher(result).replaceAll(EQUAL_SIGN); return result; } public static <I> Any idToAny(I id) { final Identifier<I> identifier = Identifier.from(id); final Any anyId = identifier.pack(); return anyId; } /** * Extracts ID object from the passed {@link Any} instance. * * <p>Returned type depends on the type of the message wrapped into {@code Any}. * * @param any the ID value wrapped into {@code Any} * @return <ul> * <li>{@code String} value if {@link StringValue} is unwrapped * <li>{@code Integer} value if {@link UInt32Value} is unwrapped * <li>{@code Long} value if {@link UInt64Value} is unwrapped * <li>unwrapped {@code Message} instance if its type is none of the above * </ul> */ public static Object idFromAny(Any any) { final Object result = Identifier.Type.unpack(any); return result; } /** * Converts the passed timestamp to the string, which will serve as ID. * * @param timestamp the value to convert * @return string representation of timestamp-based ID */ public static String timestampToIdString(Timestamp timestamp) { String result = Timestamps.toString(timestamp); result = PATTERN_COLON.matcher(result).replaceAll("-"); result = PATTERN_T.matcher(result).replaceAll("_T"); return result; } /** * Generates a new random UUID. * * @return the generated value * @see UUID#randomUUID() */ public static String newUuid() { final String id = UUID.randomUUID().toString(); return id; } /** * Obtains a default value for an identifier of the passed class. */ @Internal public static <I> I getDefaultValue(Class<I> idClass) { return Identifier.getDefaultValue(idClass); } /** The registry of converters of ID types to string representations. */ public static class ConverterRegistry { private final Map<Class<?>, Function<?, String>> entries = synchronizedMap( newHashMap( ImmutableMap.<Class<?>, Function<?, String>>builder() .put(Timestamp.class, new TimestampToStringConverter()) .put(EventId.class, new EventIdToStringConverter()) .put(CommandId.class, new CommandIdToStringConverter()) .build() ) ); private ConverterRegistry() { } public <I extends Message> void register(Class<I> idClass, Function<I, String> converter) { checkNotNull(idClass); checkNotNull(converter); entries.put(idClass, converter); } public <I> Function<I, String> getConverter(I id) { checkNotNull(id); checkNotClass(id); final Function<?, String> func = entries.get(id.getClass()); @SuppressWarnings("unchecked") /** The cast is safe as we check the first type when adding. @see #register(Class, com.google.common.base.Function) */ final Function<I, String> result = (Function<I, String>) func; return result; } private static <I> void checkNotClass(I id) { if (id instanceof Class) { throw new IllegalArgumentException("Class instance passed instead of value: " + id.toString()); } } public synchronized <I> boolean containsConverter(I id) { final Class<?> idClass = id.getClass(); final boolean contains = entries.containsKey(idClass) && (entries.get(idClass) != null); return contains; } private enum Singleton { INSTANCE; @SuppressWarnings("NonSerializableFieldInSerializableClass") private final ConverterRegistry value = new ConverterRegistry(); } public static ConverterRegistry getInstance() { return Singleton.INSTANCE.value; } } private static class TimestampToStringConverter implements Function<Timestamp, String> { @Override public String apply(@Nullable Timestamp timestamp) { if (timestamp == null) { return NULL_ID; } final String result = timestampToIdString(timestamp); return result; } } public static class EventIdToStringConverter implements Function<EventId, String> { @Override public String apply(@Nullable EventId eventId) { if (eventId == null) { return NULL_ID; } return eventId.getUuid(); } } public static class CommandIdToStringConverter implements Function<CommandId, String> { @Override public String apply(@Nullable CommandId commandId) { if (commandId == null) { return NULL_ID; } return commandId.getUuid(); } } }
package fm.libre.droid; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.CoreProtocolPNames; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.MediaScannerConnection; import android.media.MediaScannerConnection.MediaScannerConnectionClient; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.os.IBinder; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.MenuItem.OnMenuItemClickListener; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; import android.widget.Toast; import android.widget.ViewAnimator; public class LibreDroid extends Activity { private LibreServiceConnection libreServiceConn; private String username; private String password; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); libreServiceConn = new LibreServiceConnection(); bindService(new Intent(this, LibreService.class), libreServiceConn, Context.BIND_AUTO_CREATE); this.registerReceiver(new MediaButtonReceiver(), new IntentFilter(Intent.ACTION_MEDIA_BUTTON)); this.registerReceiver(new UIUpdateReceiver(), new IntentFilter("LibreDroidNewSong")); setContentView(R.layout.main); // Load settings final SharedPreferences settings = getSharedPreferences("LibreDroid", MODE_PRIVATE); username = settings.getString("Username", ""); password = settings.getString("Password", ""); final EditText usernameEntry = (EditText) findViewById(R.id.usernameEntry); final EditText passwordEntry = (EditText) findViewById(R.id.passwordEntry); usernameEntry.setText(username); passwordEntry.setText(password); final Button loginButton = (Button) findViewById(R.id.loginButton); loginButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { Editor editor = settings.edit(); editor.putString("Username", usernameEntry.getText().toString()); editor.putString("Password", passwordEntry.getText().toString()); editor.commit(); LibreDroid.this.login(); } }); // Setup buttons String radioButtons[] = { "Folk", "Rock", "Metal", "Classical", "Pop", "Punk", "Jazz", "Blues", "Rap", "Ambient" }; int i = 0; TableRow row = (TableRow) findViewById(R.id.TableRow01); for (String buttonStr : radioButtons) { Button button = new Button(this); button.setText(buttonStr); button.setOnClickListener(new OnClickListener() { public void onClick(View v) { Button b = (Button) v; LibreDroid.this.libreServiceConn.service.tuneStation("globaltags", b.getText().toString().toLowerCase()); LibreDroid.this.nextPage(); } }); row.addView(button); i++; if (i == 5) { row = (TableRow) findViewById(R.id.TableRow02); } } TableLayout table = (TableLayout) findViewById(R.id.TableLayout01); Button loveStation = new Button(this); loveStation.setText("Your Loved Tracks"); loveStation.setOnClickListener(new OnClickListener() { public void onClick(View v) { LibreDroid.this.libreServiceConn.service.tuneStation("user", username + "/loved"); LibreDroid.this.nextPage(); } }); table.addView(loveStation); Button communityLoveStation = new Button(this); communityLoveStation.setText("Community's Loved Tracks"); communityLoveStation.setOnClickListener(new OnClickListener() { public void onClick(View v) { LibreDroid.this.libreServiceConn.service.tuneStation("community", "loved"); LibreDroid.this.nextPage(); } }); table.addView(communityLoveStation); final ImageButton nextButton = (ImageButton) findViewById(R.id.nextButton); nextButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { LibreDroid.this.libreServiceConn.service.next(); } }); final ImageButton prevButton = (ImageButton) findViewById(R.id.prevButton); prevButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { LibreDroid.this.libreServiceConn.service.prev(); } }); final ImageButton playPauseButton = (ImageButton) findViewById(R.id.playPauseButton); playPauseButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { LibreDroid.this.togglePause(); } }); final ImageButton saveButton = (ImageButton) findViewById(R.id.saveButton); saveButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { LibreDroid.this.save(); } }); final ImageButton loveButton = (ImageButton) findViewById(R.id.loveButton); loveButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { LibreDroid.this.libreServiceConn.service.love(); } }); final ImageButton banButton = (ImageButton) findViewById(R.id.banButton); banButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { LibreDroid.this.libreServiceConn.service.ban(); } }); } @Override public void onDestroy() { super.onDestroy(); } public void updateSong() { Song song = libreServiceConn.service.getSong(); final TextView titleText = (TextView) findViewById(R.id.titleText); final TextView artistText = (TextView) findViewById(R.id.artistText); final TextView stationText = (TextView) findViewById(R.id.stationNameText); final ImageView albumImage = (ImageView) findViewById(R.id.albumImage); final ImageButton playPauseButton = (ImageButton) findViewById(R.id.playPauseButton); playPauseButton.setImageResource(R.drawable.pause); titleText.setText(song.title); artistText.setText(song.artist); stationText.setText(libreServiceConn.service.getStationName()); if (song.imageURL.length() > 0) { new AlbumImageTask().execute(song.imageURL); } else { albumImage.setImageResource(R.drawable.album); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_BACK)) { if (this.libreServiceConn.service.getCurrentPage() > 0) { LibreDroid.this.libreServiceConn.service.stop(); this.prevPage(); return true; } } return super.onKeyDown(keyCode, event); } public String httpGet(String url) throws URISyntaxException, ClientProtocolException, IOException { DefaultHttpClient client = new DefaultHttpClient(); URI uri = new URI(url); HttpGet method = new HttpGet(uri); HttpResponse res = client.execute(method); ByteArrayOutputStream outstream = new ByteArrayOutputStream(); res.getEntity().writeTo(outstream); return outstream.toString(); } public String httpPost(String url, String... params) throws URISyntaxException, ClientProtocolException, IOException { DefaultHttpClient client = new DefaultHttpClient(); URI uri = new URI(url); HttpPost method = new HttpPost(uri); List<NameValuePair> paramPairs = new ArrayList<NameValuePair>(2); for (int i = 0; i < params.length; i += 2) { paramPairs.add(new BasicNameValuePair(params[i], params[i + 1])); } method.setEntity(new UrlEncodedFormEntity(paramPairs)); method.getParams().setBooleanParameter( CoreProtocolPNames.USE_EXPECT_CONTINUE, false); // Disable // expect-continue, // caching // server // doesn't like // this HttpResponse res = client.execute(method); ByteArrayOutputStream outstream = new ByteArrayOutputStream(); res.getEntity().writeTo(outstream); return outstream.toString(); } public void togglePause() { final ImageButton playPauseButton = (ImageButton) findViewById(R.id.playPauseButton); if (libreServiceConn.service.isPlaying()) { playPauseButton.setImageResource(R.drawable.play); } else { playPauseButton.setImageResource(R.drawable.pause); } libreServiceConn.service.togglePause(); } public void login() { final EditText usernameEntry = (EditText) findViewById(R.id.usernameEntry); final EditText passwordEntry = (EditText) findViewById(R.id.passwordEntry); username = usernameEntry.getText().toString(); password = passwordEntry.getText().toString(); boolean loggedIn = libreServiceConn.service.login(username, password); if (loggedIn) { nextPage(); } } public void nextPage() { final ViewAnimator view = (ViewAnimator) findViewById(R.id.viewAnimator); view.showNext(); libreServiceConn.service.setCurrentPage(view.getDisplayedChild()); } public void prevPage() { final ViewAnimator view = (ViewAnimator) findViewById(R.id.viewAnimator); view.showPrevious(); libreServiceConn.service.setCurrentPage(view.getDisplayedChild()); } public void save() { Song song = this.libreServiceConn.service.getSong(); Toast.makeText(LibreDroid.this, "Downloading \"" + song.title + "\" to your SD card.", Toast.LENGTH_LONG).show(); new DownloadTrackTask().execute(song); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuItem changeStation = menu.add(0, Menu.FIRST, 0, "Change Station") .setIcon(R.drawable.back); MenuItem quit = menu.add(0, 2, 0, "Quit").setIcon(R.drawable.quit); changeStation.setOnMenuItemClickListener(new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { final ViewAnimator view = (ViewAnimator) findViewById(R.id.viewAnimator); if (view.getDisplayedChild() == 2) { LibreDroid.this.libreServiceConn.service.stop(); LibreDroid.this.prevPage(); return true; } else { return false; } } }); quit.setOnMenuItemClickListener(new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { LibreDroid.this.libreServiceConn.service.stop(); LibreDroid.this.finish(); return true; } }); return super.onCreateOptionsMenu(menu); } private class AlbumImageTask extends AsyncTask<String, String, Bitmap> { protected Bitmap doInBackground(String... params) { String url = params[0]; Bitmap bm = null; try { URL aURL = new URL(url); URLConnection conn = aURL.openConnection(); conn.connect(); InputStream is = conn.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); bm = BitmapFactory.decodeStream(bis); bis.close(); is.close(); } catch (IOException e) { } return bm; } protected void onPostExecute(Bitmap bm) { final ImageView albumImage = (ImageView) findViewById(R.id.albumImage); albumImage.setImageBitmap(bm); } } private class DownloadTrackTask extends AsyncTask<Song, String, List<Object>> implements MediaScannerConnectionClient { private MediaScannerConnection msc; private String path; @Override protected List<Object> doInBackground(Song... params) { Song song = params[0]; List<Object> res = new ArrayList<Object>(); try { File root = Environment.getExternalStorageDirectory(); if (!Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { res.add(false); res.add("Please ensure an SD card is inserted before attempting to download songs. " + Environment.getExternalStorageState()); return res; } File musicDir = new File(root, "Music"); if (!musicDir.exists()) { musicDir.mkdir(); } File f = new File(musicDir, song.artist + " - " + song.title + ".ogg"); this.path = f.getAbsolutePath(); FileOutputStream fo = new FileOutputStream(f); URL aURL = new URL(song.location); HttpURLConnection conn = (HttpURLConnection) aURL .openConnection(); conn.connect(); if (conn.getResponseCode() == 301 || conn.getResponseCode() == 302 || conn.getResponseCode() == 307) { // Redirected aURL = new URL(conn.getHeaderField("Location")); conn = (HttpURLConnection) aURL.openConnection(); } InputStream is = conn.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); BufferedOutputStream bos = new BufferedOutputStream(fo); byte buf[] = new byte[1024]; int count = 0; while ((count = bis.read(buf, 0, 1024)) != -1) { bos.write(buf, 0, count); } bos.close(); fo.close(); bis.close(); is.close(); res.add(true); res.add("Finished downloading \"" + song.title + "\""); } catch (Exception ex) { res.add(false); res.add("Unable to download \"" + song.title + "\": " + ex.getMessage()); } return res; } protected void onPostExecute(List<Object> result) { Boolean res = (Boolean) result.get(0); String msg = (String) result.get(1); if (res.booleanValue() == true) { // Update the media library so it knows about the new file this.msc = new MediaScannerConnection(LibreDroid.this, this); this.msc.connect(); } Toast.makeText(LibreDroid.this, msg, Toast.LENGTH_LONG).show(); } public void onMediaScannerConnected() { this.msc.scanFile(this.path, null); } public void onScanCompleted(String path, Uri uri) { } } private class UIUpdateReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { LibreDroid.this.runOnUiThread(new Runnable() { public void run() { LibreDroid.this.updateSong(); } }); } } private class MediaButtonReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { KeyEvent ev = (KeyEvent) intent.getExtras().get( Intent.EXTRA_KEY_EVENT); if (ev.getAction() == KeyEvent.ACTION_UP) { // Only perform the action on keydown/multiple return; } switch (ev.getKeyCode()) { case KeyEvent.KEYCODE_MEDIA_NEXT: LibreDroid.this.libreServiceConn.service.next(); this.abortBroadcast(); break; case KeyEvent.KEYCODE_MEDIA_PREVIOUS: LibreDroid.this.libreServiceConn.service.prev(); this.abortBroadcast(); break; case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE: LibreDroid.this.togglePause(); this.abortBroadcast(); break; } } } private class LibreServiceConnection implements ServiceConnection { public ILibreService service = null; public void onServiceConnected(ComponentName name, IBinder service) { this.service = (ILibreService) service; LibreDroid.this.runOnUiThread(new Runnable() { public void run() { final ViewAnimator view = (ViewAnimator) LibreDroid.this.findViewById(R.id.viewAnimator); view.setDisplayedChild(LibreServiceConnection.this.service.getCurrentPage()); if (LibreServiceConnection.this.service.getCurrentPage() == 2) { LibreDroid.this.updateSong(); } } }); } public void onServiceDisconnected(ComponentName name) { } } }
import managed_dll.*; import managed_dll.properties.*; import managed_dll.first.*; import managed_dll.first.second.*; import managed_dll.exceptions.*; import managed_dll.constructors.*; import managed_dll.enums.*; import managed_dll.methods.*; import managed_dll.structs.*; import mono.embeddinator.*; import static org.junit.Assert.*; import org.junit.*; public class Tests { private static boolean doublesAreEqual(double value1, double value2) { return Double.doubleToLongBits(value1) == Double.doubleToLongBits(value2); } @Test public void testProperties() { assertFalse(Platform.getIsWindows()); Platform.setExitCode(255); assertEquals(Platform.getExitCode(), 255); assertEquals(Query.getUniversalAnswer(), 42); Query query = new Query(); assertTrue(query.getIsGood()); assertFalse(query.getIsBad()); assertEquals(query.getAnswer(), 42); query.setAnswer(911); assertEquals(query.getAnswer(), 911); assertFalse(query.getIsSecret()); query.setSecret(1); assertTrue(query.getIsSecret()); } @Test public void testNamespaces() { ClassWithoutNamespace nonamespace = new ClassWithoutNamespace(); assertEquals(nonamespace.toString(), "ClassWithoutNamespace"); ClassWithSingleNamespace singlenamespace = new ClassWithSingleNamespace(); assertEquals(singlenamespace.toString(), "First.ClassWithSingleNamespace"); ClassWithNestedNamespace nestednamespaces = new ClassWithNestedNamespace(); assertEquals(nestednamespaces.toString(), "First.Second.ClassWithNestedNamespace"); managed_dll.first.second.third.ClassWithNestedNamespace nestednamespaces2 = new managed_dll.first.second.third.ClassWithNestedNamespace(); assertEquals(nestednamespaces2.toString(), "First.Second.Third.ClassWithNestedNamespace"); } @Test public void testExceptions() { Throwable e = null; try { Throwers throwers = new Throwers(); } catch(Exception ex) { e = ex; } assertTrue(e instanceof mono.embeddinator.RuntimeException); e = null; try { ThrowInStaticCtor static_thrower = new ThrowInStaticCtor(); } catch(Exception ex) { e = ex; } assertTrue(e instanceof mono.embeddinator.RuntimeException); try { Super sup1 = new Super(false); } catch(Exception ex) { fail(); } e = null; try { Super sup2 = new Super(true); } catch(Exception ex) { e = ex; } assertTrue(e instanceof mono.embeddinator.RuntimeException); } @Test public void testConstructors() { Unique unique = new Unique(); assertEquals(1, unique.getId()); Unique unique_init_id = new Unique(911); assertEquals(911, unique_init_id.getId()); SuperUnique super_unique_default_init = new SuperUnique(); assertEquals(411, super_unique_default_init.getId()); Implicit implicit = new Implicit(); assertEquals("OK", implicit.getTestResult()); AllTypeCode all1 = new AllTypeCode(true, (char)USHRT_MAX, "Mono"); assertTrue(all1.getTestResult()); AllTypeCode all2 = new AllTypeCode(Byte.MAX_VALUE, Short.MAX_VALUE, Integer.MAX_VALUE, Long.MAX_VALUE); assertTrue(all2.getTestResult()); // TODO: Use BigDecimal for unsigned 64-bit integer types. //AllTypeCode all3 = new AllTypeCode(new UnsignedByte(UCHAR_MAX), new UnsignedShort(USHRT_MAX), // new UnsignedInt(UINT_MAX), new UnsignedLong(ULONG_MAX)); //assertTrue(all3.getTestResult()); AllTypeCode all4 = new AllTypeCode(Float.MAX_VALUE, Double.MAX_VALUE); assertTrue(all4.getTestResult()); } @Test public void testMethods() { Static static_method = Static.create(1); assertEquals(1, static_method.getId()); assertEquals(null, Parameters.concat(null, null)); assertEquals("first", Parameters.concat("first", null)); assertEquals("second", Parameters.concat(null, "second")); assertEquals("firstsecond", Parameters.concat("first", "second")); Ref<Boolean> b = new Ref<Boolean>(true); Ref<String> s = new Ref<String>(null); Parameters.ref(b, s); assertFalse(b.get()); assertEquals("hello", s.get()); Parameters.ref(b, s); assertTrue(b.get()); assertEquals(null, s.get()); Out<Integer> l = new Out<Integer>(); Out<String> os = new Out<String>(); Parameters.out(null, l, os); assertEquals(new Integer(0), l.get()); assertEquals(null, os.get()); Parameters.out("Xamarin", l, os); assertEquals(new Integer(7), l.get()); assertEquals("XAMARIN", os.get()); Item item = Factory.createItem(1); assertEquals(1, item.getInteger()); Collection collection = new Collection(); assertEquals(0, collection.getCount()); collection.add(item); assertEquals(1, collection.getCount()); assertEquals(item.getInteger(), collection.getItem(0).getInteger()); Item item2 = Factory.createItem(2); collection.setItem(0, item2); assertEquals(1, collection.getCount()); assertEquals(item2.getInteger(), collection.getItem(0).getInteger()); collection.remove(item); assertEquals(1, collection.getCount()); collection.remove(item2); assertEquals(0, collection.getCount()); } @Test public void testStructs() { Point p1 = new Point(1.0f, -1.0f); doublesAreEqual(1.0f, p1.getX()); doublesAreEqual(-1.0f, p1.getY()); Point p2 = new Point(2.0f, -2.0f); doublesAreEqual(2.0f, p2.getX()); doublesAreEqual(-2.0f, p2.getY()); assertTrue(Point.opEquality(p1, p1)); assertTrue(Point.opEquality(p2, p2)); assertTrue(Point.opInequality(p1, p2)); Point p3 = Point.opAddition(p1, p2); doublesAreEqual(3.0f, p3.getX()); doublesAreEqual(-3.0f, p3.getY()); Point p4 = Point.opSubtraction(p3, p2); assertTrue(Point.opEquality(p4, p1)); } @Test public void testEnums() { Ref<IntEnum> i = new Ref<IntEnum>(IntEnum.Min); Out<ShortEnum> s = new Out<ShortEnum>(ShortEnum.Min); ByteFlags f = Enumer.test(ByteEnum.Max, i, s); assertEquals(0x22, f.getValue()); assertEquals(IntEnum.Max, i.get()); assertEquals(ShortEnum.Max, s.get()); f = Enumer.test(ByteEnum.Zero, i, s); assertEquals(IntEnum.Min, i.get()); assertEquals(ShortEnum.Min, s.get()); } static long UCHAR_MAX = (long)(Math.pow(2, Byte.SIZE) - 1); static long USHRT_MAX = (long)(Math.pow(2, Short.SIZE) - 1); static long UINT_MAX = (long)(Math.pow(2, Integer.SIZE) - 1); static long ULONG_MAX = (long)(Math.pow(2, Long.SIZE) - 1); @Test public void testTypes() { assertEquals(Byte.MIN_VALUE, Type_SByte.getMin()); assertEquals(Byte.MAX_VALUE, Type_SByte.getMax()); assertEquals(Short.MIN_VALUE, Type_Int16.getMin()); assertEquals(Short.MAX_VALUE, Type_Int16.getMax()); assertEquals(Integer.MIN_VALUE, Type_Int32.getMin()); assertEquals(Integer.MAX_VALUE, Type_Int32.getMax()); assertEquals(Long.MIN_VALUE, Type_Int64.getMin()); assertEquals(Long.MAX_VALUE, Type_Int64.getMax()); assertEquals(0, Type_Byte.getMin().longValue()); assertEquals(UCHAR_MAX, Type_Byte.getMax().longValue()); assertEquals(0, Type_UInt16.getMin().longValue()); assertEquals(USHRT_MAX, Type_UInt16.getMax().longValue()); assertEquals(0, Type_UInt32.getMin().longValue()); assertEquals(UINT_MAX, Type_UInt32.getMax().longValue()); assertEquals(0, Type_UInt64.getMin().longValue()); // TODO: Use BigDecimal for unsigned 64-bit integer types. //assertEquals(ULONG_MAX, Type_UInt64.getMax().longValue()); doublesAreEqual(-Float.MAX_VALUE, Type_Single.getMin()); doublesAreEqual(Float.MAX_VALUE, Type_Single.getMax()); doublesAreEqual(-Double.MAX_VALUE, Type_Double.getMin()); doublesAreEqual(Double.MAX_VALUE, Type_Double.getMax()); assertEquals(Character.MIN_VALUE, Type_Char.getMin()); assertEquals(Character.MAX_VALUE, Type_Char.getMax()); assertEquals(0, Type_Char.getZero()); } }
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.ObjectInputStream; public class run_tagger { private static Model model; private static File modelFile; private static File testFile; private static File outFile; /** * run_tagger.java * usage: run_tagger <sents.test> <model_file> <sents.out> */ public static void main(String[] args) { validateArguments(args); loadModel(args); test(); System.exit(0); } public static void validateArguments(String[] args) { if (args.length >= 3) { testFile = new File(args[0]); modelFile = new File(args[1]); outFile = new File(args[2]); } else { System.err.println("usage: run_tagger <sents.test> <model_file> <sents.out>"); System.exit(1); } } public static void loadModel(String[] args) { try { FileInputStream fileStream = new FileInputStream(modelFile); ObjectInputStream objectStream = new ObjectInputStream(fileStream); try { model = (Model) objectStream.readObject(); } finally { objectStream.close(); fileStream.close(); } } catch(IOException e) { e.printStackTrace(); } catch(ClassNotFoundException e) { e.printStackTrace(); } } public static void test() { try { BufferedReader reader = new BufferedReader(new FileReader(testFile)); BufferedWriter writer = new BufferedWriter(new FileWriter(outFile)); try { String line; while ((line = reader.readLine()) != null) { String[] words = line.split(" "); Tag[] tags = model.tag(words); writer.write(words[0] + "/" + tags[0]); for (int i = 1; i < words.length; i++) { writer.write(" " + words[i] + "/" + tags[i]); } writer.newLine(); } } finally { reader.close(); writer.flush(); writer.close(); } } catch(IOException e) { e.printStackTrace(); } } }
package agersant.polaris; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.app.TaskStackBuilder; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Bitmap; import android.graphics.drawable.Icon; import android.media.AudioManager; import android.os.Binder; import android.os.IBinder; import android.widget.Toast; import com.google.android.exoplayer2.source.MediaSource; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import agersant.polaris.api.API; import agersant.polaris.api.FetchImageTask; import agersant.polaris.api.local.LocalAPI; import agersant.polaris.api.local.OfflineCache; import agersant.polaris.api.remote.DownloadQueue; import agersant.polaris.api.remote.ServerAPI; import agersant.polaris.features.player.PlayerActivity; public class PolarisService extends Service { private static final int MEDIA_NOTIFICATION = 1; private static final String MEDIA_INTENT_PAUSE = "MEDIA_INTENT_PAUSE"; private static final String MEDIA_INTENT_PLAY = "MEDIA_INTENT_PLAY"; private static final String MEDIA_INTENT_SKIP_NEXT = "MEDIA_INTENT_SKIP_NEXT"; private static final String MEDIA_INTENT_SKIP_PREVIOUS = "MEDIA_INTENT_SKIP_PREVIOUS"; private static final String MEDIA_INTENT_DISMISS = "MEDIA_INTENT_DISMISS"; private static final String NOTIFICATION_CHANNEL_ID = "POLARIS_NOTIFICATION_CHANNEL_ID"; private final IBinder binder = new PolarisService.PolarisBinder(); private BroadcastReceiver receiver; private Notification notification; private CollectionItem notificationItem; private API api; private PolarisPlayer player; private PlaybackQueue playbackQueue; @Override public void onCreate() { super.onCreate(); PolarisState state = PolarisApplication.getState(); api = state.api; player = state.player; playbackQueue = state.playbackQueue; pushSystemNotification(); restoreStateFromDisk(); IntentFilter filter = new IntentFilter(); filter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY); filter.addAction(PolarisPlayer.PLAYING_TRACK); filter.addAction(PolarisPlayer.PAUSED_TRACK); filter.addAction(PolarisPlayer.RESUMED_TRACK); filter.addAction(PolarisPlayer.PLAYBACK_ERROR); filter.addAction(PolarisPlayer.COMPLETED_TRACK); receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { switch (intent.getAction()) { case PolarisPlayer.PLAYBACK_ERROR: displayError(); break; case PolarisPlayer.PLAYING_TRACK: case PolarisPlayer.RESUMED_TRACK: pushSystemNotification(); break; case PolarisPlayer.PAUSED_TRACK: pushSystemNotification(); saveStateToDisk(); break; case AudioManager.ACTION_AUDIO_BECOMING_NOISY: player.pause(); break; } } }; registerReceiver(receiver, filter); } @Override public void onDestroy() { unregisterReceiver(receiver); super.onDestroy(); } @Override public IBinder onBind(Intent intent) { return binder; } public class PolarisBinder extends Binder { } @Override public int onStartCommand(Intent intent, int flags, int startId) { handleIntent(intent); super.onStartCommand(intent, flags, startId); return START_NOT_STICKY; } // Internals private void displayError() { Toast toast = Toast.makeText(this, R.string.playback_error, Toast.LENGTH_SHORT); toast.show(); } private void handleIntent(Intent intent) { if (intent == null || intent.getAction() == null) { return; } String action = intent.getAction(); switch (action) { case MEDIA_INTENT_PAUSE: player.pause(); break; case MEDIA_INTENT_PLAY: player.resume(); break; case MEDIA_INTENT_SKIP_NEXT: player.skipNext(); break; case MEDIA_INTENT_SKIP_PREVIOUS: player.skipPrevious(); break; case MEDIA_INTENT_DISMISS: stopSelf(); break; } } private void pushSystemNotification() { boolean isPlaying = player.isPlaying(); final CollectionItem item = player.getCurrentItem(); if (item == null) { return; } // On tap action TaskStackBuilder stackBuilder = TaskStackBuilder.create(this) .addParentStack(PlayerActivity.class) .addNextIntent(new Intent(this, PlayerActivity.class)); PendingIntent tapPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); // On dismiss action Intent dismissIntent = new Intent(this, PolarisService.class); dismissIntent.setAction(MEDIA_INTENT_DISMISS); PendingIntent dismissPendingIntent = PendingIntent.getService(this, 0, dismissIntent, 0); // Create notification final Notification.Builder notificationBuilder = new Notification.Builder(this, NOTIFICATION_CHANNEL_ID) .setShowWhen(false) .setSmallIcon(R.drawable.notification_icon) .setContentTitle(item.getTitle()) .setContentText(item.getArtist()) .setVisibility(Notification.VISIBILITY_PUBLIC) .setContentIntent(tapPendingIntent) .setDeleteIntent(dismissPendingIntent) .setStyle(new Notification.MediaStyle() .setShowActionsInCompactView() ); // Add album art if (item == notificationItem && notification != null && notification.getLargeIcon() != null) { notificationBuilder.setLargeIcon(notification.getLargeIcon()); } if (item.getArtwork() != null) { api.loadImage(item, new FetchImageTask.Callback() { @Override public void onSuccess(Bitmap bitmap) { if (item != player.getCurrentItem()) { return; } notificationBuilder.setLargeIcon(bitmap); emitNotification(notificationBuilder, item); } }); } // Add media control actions notificationBuilder.addAction(generateAction(R.drawable.ic_skip_previous_black_24dp, R.string.player_next_track, MEDIA_INTENT_SKIP_PREVIOUS)); if (isPlaying) { notificationBuilder.addAction(generateAction(R.drawable.ic_pause_black_24dp, R.string.player_pause, MEDIA_INTENT_PAUSE)); } else { notificationBuilder.addAction(generateAction(R.drawable.ic_play_arrow_black_24dp, R.string.player_play, MEDIA_INTENT_PLAY)); } notificationBuilder.addAction(generateAction(R.drawable.ic_skip_next_black_24dp, R.string.player_previous_track, MEDIA_INTENT_SKIP_NEXT)); // Emit notification emitNotification(notificationBuilder, item); if (isPlaying) { startForeground(MEDIA_NOTIFICATION, notification); } else { stopForeground(false); } } private void emitNotification(Notification.Builder notificationBuilder, CollectionItem item) { notificationItem = item; notification = notificationBuilder.build(); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); NotificationChannel mChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Polaris", NotificationManager.IMPORTANCE_DEFAULT); mChannel.setDescription("Notifications for current song playing in Polaris."); mChannel.enableLights(false); mChannel.enableVibration(false); mChannel.setShowBadge(false); notificationManager.createNotificationChannel(mChannel); notificationManager.notify(MEDIA_NOTIFICATION, notification); } private Notification.Action generateAction(int icon, int text, String intentAction) { Intent intent = new Intent(this, PolarisService.class); intent.setAction(intentAction); PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, 0); return new Notification.Action.Builder(Icon.createWithResource(this, icon), getResources().getString(text), pendingIntent).build(); } private void saveStateToDisk() { File storage = new File(getCacheDir(), "playlist.v" + PlaybackQueueState.VERSION); // Gather state PlaybackQueueState state = new PlaybackQueueState(); state.queueContent = playbackQueue.getContent(); state.queueOrdering = playbackQueue.getOrdering(); CollectionItem currentItem = player.getCurrentItem(); state.queueIndex = state.queueContent.indexOf(currentItem); state.trackProgress = player.getPositionRelative(); // Persist try (FileOutputStream out = new FileOutputStream(storage)) { try (ObjectOutputStream objOut = new ObjectOutputStream(out)) { objOut.writeObject(state); } catch (IOException e) { System.out.println("Error while saving PlaybackQueueState object: " + e); } } catch (IOException e) { System.out.println("Error while writing PlaybackQueueState file: " + e); } } private void restoreStateFromDisk() { File storage = new File(getCacheDir(), "playlist.v" + PlaybackQueueState.VERSION); try (FileInputStream in = new FileInputStream(storage)) { try (ObjectInputStream objIn = new ObjectInputStream(in)) { Object obj = objIn.readObject(); if (obj instanceof PlaybackQueueState) { PlaybackQueueState state = (PlaybackQueueState) obj; playbackQueue.setContent(state.queueContent); playbackQueue.setOrdering(state.queueOrdering); if (state.queueIndex >= 0 && player.isIdle()) { CollectionItem currentItem = playbackQueue.getItem(state.queueIndex); player.play(currentItem); player.pause(); player.seekToRelative(state.trackProgress); } } } catch (ClassNotFoundException e) { System.out.println("Error while loading PlaybackQueueState object: " + e); } } catch (IOException e) { System.out.println("Error while reading PlaybackQueueState file: " + e); } } }
package ca.knoblauch.dialog; import android.util.Log; import java.util.ArrayList; import java.lang.String; import java.util.HashMap; import java.util.Map; public class speechModel { ArrayList<String> watchWords = new ArrayList<String>(); private int targetTime; private int actualTime; private String actualText; private String targetText=""; private int actualWordCount; private int targetWordCount=0; private Map actualWordDicCount; private Map targetWordDicCount; private int actualSyllableCount; private int targetSyllableCount = 0; private int totalFlaggedWords =0; private String voiceInputString; private int AVERAGEWORDPERSENTANCES =17; private double TARGETSPM = 150.0; private boolean targetIsSet = false; private static speechModel firstInstance = null; private speechModel() {}; public static speechModel getInstance(){ if(firstInstance == null){ synchronized(speechModel.class){ if(firstInstance == null){ firstInstance = new speechModel(); } } } return firstInstance; } public void importVoiceText(String inputString){ voiceInputString = inputString.toLowerCase(); actualWordCount =0; actualSyllableCount=0; actualWordDicCount= countActualWords(voiceInputString); } public void setTargetText (String targText){ targetWordCount =0; targetSyllableCount=0; targetText=targText; targetWordDicCount= countTargetWords(targetText); targetTime = (int) (1.0/TARGETSPM)/targetSyllableCount *60 ; if(targetTime == 0){ targetTime = 1; } Log.d("TEA", ""+targetTime); targetIsSet = true; } public boolean isTargetIsSet(){ return targetIsSet; } public int getTargetTime(){ return targetTime; } public Map getActualWordDicCount(){ return actualWordDicCount; } public void setActualTime(int inputTime){ actualTime = inputTime; } public int getActualTime(){ return actualTime; } public Integer getTimeDifference(){ return targetTime - actualTime; } private Map countTargetWords(String inputString){ Map <String, Integer> dictionary = new HashMap<String, Integer>(); String[] words = inputString.replaceAll("[^a-zA-Z ]", "").toLowerCase().split("\\s+"); targetWordCount= words.length; for(String word: words) { targetSyllableCount+= countSyllables(word); } return dictionary; } private Map countActualWords(String inputString){ watchWords.add("fuck"); watchWords.add("fucked"); watchWords.add("fucking"); watchWords.add("shit"); watchWords.add("um"); watchWords.add("uh"); watchWords.add("like"); watchWords.add("damn"); watchWords.add("darn"); Map <String, Integer> dictionary = new HashMap<String, Integer>(); String[] words = inputString.replaceAll("[^a-zA-Z ]", "").toLowerCase().split("\\s+"); actualWordCount= words.length; for(String word: words) { actualSyllableCount+= countSyllables(word); word = word.replace("ing",""); word = word.replace("ed",""); word = word.replace("ter",""); word = word.replace("ing",""); if(word.equals( "fuc")){ word="fuck"; } boolean isWatchWord = watchWords.contains(word); if(isWatchWord ) { if (dictionary.containsKey(word)) { int val = (int) dictionary.get(word); dictionary.put(word, val + 1); } else { dictionary.put(word, 1); } totalFlaggedWords++; } } return dictionary; } public int getTotalFlaggedWords(){ return totalFlaggedWords; } private int countSyllables(String word) { int count = 0; word = word.toLowerCase(); for (int i = 0; i < word.length(); i++) { if (word.charAt(i) == '\"' || word.charAt(i) == '\'' || word.charAt(i) == '-' || word.charAt(i) == ',' || word.charAt(i) == ')' || word.charAt(i) == '(') { word = word.substring(0,i)+word.substring(i+1, word.length()); } } boolean isPrevVowel = false; for (int j = 0; j < word.length(); j++) { if (word.contains("a") || word.contains("e") || word.contains("i") || word.contains("o") || word.contains("u")) { if (isVowel(word.charAt(j)) && !((word.charAt(j) == 'e') && (j == word.length()-1))) { if (isPrevVowel == false) { count++; isPrevVowel = true; } } else { isPrevVowel = false; } } else { count++; break; } } return count; } public boolean isVowel(char c) { if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') { return true; } else { return false; } } public int getActualSyllabeCount(){ return actualSyllableCount; } public int getTargetSyllableCount(){ return targetSyllableCount; } public String getVoiceText(){ return voiceInputString; } public int getActualPacing(){ int wordsPerMinute = (int) (actualWordCount/ (actualTime / 60.0)); return wordsPerMinute; } public int getTargetPacing(){ int wordsPerMinute = (int) (targetWordCount / (targetTime / 60.0)); return wordsPerMinute; } public int getActualWordCount(){ return actualWordCount; } private int spwActual = (int)((double)actualSyllableCount/(double) actualWordCount); public int getSPWActual(){ return spwActual; } public int getActualReadingLevel(){ double totalSentences = (double) actualWordCount/17.0; double wordsPerSentance = ((double) actualWordCount/totalSentences); double syllablesPerWord = ((double)actualSyllableCount/(double) actualWordCount); double firstPart = 0.39 * wordsPerSentance; double secondPart = 11.8*syllablesPerWord; double summation = firstPart + secondPart - 15.59; return (int) Math.round(summation); } public int getTargetReadingLevel(){ double totalSentences = (double) targetWordCount/17.0; double wordsPerSentance = ((double) targetWordCount/totalSentences); double syllablesPerWord = ((double)targetSyllableCount/(double) targetWordCount); double firstPart = 0.39 * wordsPerSentance; double secondPart = 11.8*syllablesPerWord; double summation = firstPart + secondPart - 15.59; return (int) Math.round(summation); } public int getLevnshteinDistance (){ if(targetText==null){ return 0; } else { return levenshteinDistance(targetText, voiceInputString); } } private int levenshteinDistance (CharSequence lhs, CharSequence rhs) { int len0 = lhs.length() + 1; int len1 = rhs.length() + 1; // the array of distances int[] cost = new int[len0]; int[] newcost = new int[len0]; // initial cost of skipping prefix in String s0 for (int i = 0; i < len0; i++) cost[i] = i; // dynamically computing the array of distances // transformation cost for each letter in s1 for (int j = 1; j < len1; j++) { // initial cost of skipping prefix in String s1 newcost[0] = j; // transformation cost for each letter in s0 for(int i = 1; i < len0; i++) { // matching current letters in both strings int match = (lhs.charAt(i - 1) == rhs.charAt(j - 1)) ? 0 : 1; // computing cost for each transformation int cost_replace = cost[i - 1] + match; int cost_insert = cost[i] + 1; int cost_delete = newcost[i - 1] + 1; // keep minimum cost newcost[i] = Math.min(Math.min(cost_insert, cost_delete), cost_replace); } // swap cost/newcost arrays int[] swap = cost; cost = newcost; newcost = swap; } // the distance is the cost for transforming all letters in both strings return cost[len0 - 1]; } }
package com.example.idk.myuber; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.Toast; import android.widget.Button; import org.json.JSONArray; import org.json.JSONObject; public class PostBike extends Fragment implements View.OnClickListener { private int requestCode; private int resultCode; private Intent data; Button next; View view; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // test(); view = inflater.inflate(R.layout.activity_postbike1, container, false); Button launch = (Button) view.findViewById(R.id.launch_camera_button); next = (Button) view.findViewById(R.id.next_button); launch.setOnClickListener(this); return view; } private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } public void launch_camera() { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(intent,CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE); } public void next_page() { Intent intent = new Intent() } @Override public void onActivityResult(int requestCode, int resultCode, Intent intent) { if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) { if (resultCode == getActivity().RESULT_OK) { // Image captured and saved to fileUri specified in the Intent // Toast.makeText(getActivity(), "Image saved to:\n" + //intent.getData(), Toast.LENGTH_LONG).show(); ImageView imgview =(ImageView)view.findViewById(R.id.pic_of_bike_post); Uri imgUri=Uri.parse(intent.getData().toString()); imgview.setImageURI(null); imgview.setImageURI(imgUri); } else if (resultCode == getActivity().RESULT_CANCELED) { // User cancelled the image capture } else { // Image capture failed, advise user } } } public void test() { String first_name; String last_name; Httpget tst = new Httpget(); JSONArray obj = new JSONArray(); //obj = tst.getUser("1"); tst.parseUser(obj); first_name = tst.getOwner_first_name(); last_name = tst.getOwner_last_name(); Log.v("Post", first_name) ; Log.v("Post", last_name); } @Override public void onClick(View v) { switch(v.getId()) { case R.id.launch_camera_button: launch_camera(); break; case R.id.next_button: } } }
package com.samourai.wallet.JSONRPC; import org.bitcoinj.core.Sha256Hash; import org.bitcoinj.core.Utils; import org.bitcoinj.params.MainNetParams; import org.json.JSONException; import org.json.JSONObject; import org.bouncycastle.util.encoders.Hex; import java.math.BigInteger; import static org.bouncycastle.util.Arrays.reverse; import android.util.Log; import com.samourai.wallet.SamouraiWallet; public class PoW { private String strHash = null; private String strVersionHex = null; private String strPrevBlock = null; private String strMerkleRoot = null; private long ts = -1L; private String strTS = null; private String strBits = null; private long nonce = -1L; private String strNonce = null; private BigInteger target = null; private PoW() { ; } public PoW(String hash) { strHash = hash; } public String getHash() { return strHash; } public String getVersionHex() { return strVersionHex; } public String getPrevBlock() { return strPrevBlock; } public String getMerkleRoot() { return strMerkleRoot; } public long getTs() { return ts; } public String getBits() { return strBits; } public long getNonce() { return nonce; } public BigInteger getTarget() { return target; } public String calcHash(JSONObject resultObj) { String hash = null; try { strVersionHex = Hex.toHexString(reverse(Hex.decode(resultObj.getString("versionHex")))); Log.i("PoW", "version:" + strVersionHex); strPrevBlock = Hex.toHexString(reverse(Hex.decode(resultObj.getString("previousblockhash")))); Log.i("PoW", "prev block:" + strPrevBlock); strMerkleRoot = Hex.toHexString(reverse(Hex.decode(resultObj.getString("merkleroot")))); Log.i("PoW", "merkle root:" + strMerkleRoot); ts = resultObj.getLong("time"); strTS = Hex.toHexString(reverse(Hex.decode(String.format("%08X", ts)))); Log.i("PoW", "timestamp:" + strTS); strBits = Hex.toHexString(reverse(Hex.decode(resultObj.getString("bits")))); Log.i("PoW", "bits:" + strBits); nonce = resultObj.getLong("nonce"); strNonce = Hex.toHexString(reverse(Hex.decode(String.format("%08X", nonce)))); Log.i("PoW", "nonce:" + strNonce); String strHeader = strVersionHex + strPrevBlock + strMerkleRoot + strTS + strBits + strNonce; byte[] buf = Hex.decode(strHeader); hash = Hex.toHexString(reverse(Sha256Hash.hashTwice(buf))); Log.i("PoW", "hash:" + hash); } catch(org.bouncycastle.util.encoders.DecoderException de) { de.printStackTrace(); return null; } catch(JSONException je) { return null; } return hash; } // Prove the block was as difficult to make as it claims to be. // Check value of difficultyTarget to prevent and attack that might have us read a different chain. public boolean check(JSONObject headerObj, JSONObject nodeObj, String hash) { try { double dDifficulty = headerObj.getDouble("difficulty"); Log.i("PoW", "difficulty:" + dDifficulty); long difficultyTarget = Long.parseLong(nodeObj.getString("bits"), 16); target = Utils.decodeCompactBits(difficultyTarget); if (target.signum() <= 0 || target.compareTo(SamouraiWallet.getInstance().getCurrentNetworkParams().getMaxTarget()) > 0) { Log.i("PoW", "invalid target"); return false; } else if(new Sha256Hash(hash).toBigInteger().compareTo(target) > 0) { Log.i("PoW", "hash is higher than target"); Log.i("PoW", "target as integer:" + target.toString()); Log.i("PoW", "hash as integer:" + new Sha256Hash(hash).toBigInteger().toString()); return false; } else { Log.i("PoW", "target as integer:" + target.toString()); Log.i("PoW", "hash as integer:" + new Sha256Hash(hash).toBigInteger().toString()); return true; } } catch(JSONException je) { return false; } } }
package org.ieeeguc.ieeeguc.models; import org.ieeeguc.ieeeguc.HTTPResponse; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.Date; import java.util.HashMap; import okhttp3.Call; import okhttp3.Callback; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; public class User{ public static final MediaType contentType = MediaType.parse("application/json; charset=utf-8"); public static enum Type { ADMIN, HIGH_BOARD, MEMBER, UPPER_BOARD } public static enum Gender { MALE, FEMALE } private int id; private Type type; private String firstName; private String lastName; private String email; private Gender gender; private Date birthdate; private String ieeeMembershipID; private int committeeID; private String committeeName; private String phoneNumber; private JSONObject settings; public User(int id, Type type, String firstName, String lastName, Gender gender, String email, Date birthdate, String ieeeMembershipID, int committeeID, String committeeName, String phoneNumber, JSONObject settings) { this.type = type; this.firstName = firstName; this.lastName = lastName; this.gender = gender; this.email = email; this.birthdate = birthdate; this.ieeeMembershipID = ieeeMembershipID; this.committeeID = committeeID; this.committeeName = committeeName; this.id = id; this.phoneNumber = phoneNumber; this.settings = settings; } public int getId() { return id; } public String getPhoneNumber() { return phoneNumber; } public JSONObject getSettings() { return settings; } public Type getType() { return type; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public String getEmail() { return email; } public Date getBirthdate() { return birthdate; } public Gender getGender() { return gender; } public String getIeeeMembershipID() { return ieeeMembershipID; } public int getCommitteeID() { return committeeID; } public String getCommitteeName() { return committeeName; } /* this method is called when the user forgrt the password and send an email to the user email adress @params email (is the user email adress) @params Httpr (is the interface instance) */ public static void ForgetPassword(String email, final HTTPResponse HttpResponse) { HashMap <String,String>body = new HashMap(); body.put("email",email) ; OkHttpClient client = new OkHttpClient(); final Request request = new Request.Builder() .url("http://ieeeguc.org/api/login") .post(RequestBody.create(contentType,( new JSONObject(body)).toString())) .build(); client.newCall(request).enqueue(new Callback() { public void onFailure(Call call, IOException e) { e.printStackTrace(); HttpResponse.onFailure(0, null); call.cancel(); } @Override public void onResponse(Call call, final Response response) { try { HttpResponse.onSuccess(200,new JSONObject(response.body().toString())) ; } catch (JSONException e) { e.printStackTrace(); HttpResponse.onFailure(500, null); ; } response.close(); } }); } /** * This Method is used by the user to login to the Server * @param {string} email [email of the user] * @param {string} password [password of the user] * @param {HttpResponse} HTTP_RESPONSE [http interface instance which is the response coming from the server after logging in containing info of the user in the Database] * @return {void} */ public static void login(String email , String password ,final HTTPResponse HTTP_RESPONSE){ OkHttpClient client = new OkHttpClient(); JSONObject jsonBody = new JSONObject(); try{ jsonBody.put("email",email); jsonBody.put("password",password); RequestBody body = RequestBody.create(contentType, jsonBody.toString()); Request request = new Request.Builder() .url("http://ieeeguc.org/api/login") .header("user_agent","Android") .post(body) .build(); client.newCall(request).enqueue(new Callback() { public void onFailure(Call call, IOException e) { HTTP_RESPONSE.onFailure(-1,null); call.cancel(); } @Override public void onResponse(Call call, final Response response) throws IOException { try { String responseData = response.body().toString(); JSONObject json = new JSONObject(responseData); int x = response.code(); String y = Integer.toString(x); if(y.charAt(0)== '2'){ HTTP_RESPONSE.onSuccess(x,json); } else{ HTTP_RESPONSE.onFailure(x,json); } } catch (JSONException e) { HTTP_RESPONSE.onFailure(500,null); } response.close(); } }); }catch(JSONException e){ HTTP_RESPONSE.onFailure(-1,null); } } /** * this method is called when the user to get information about some other user , the returned body will differ according to type of requested user * @param {String} token [token of the user] * @param {int} id [id of the user] * @param {HTTPResponse} httpResponse [httpResponse interface instance] * @return {void} */ public static void getUser(String token, int id, final HTTPResponse httpResponse){ OkHttpClient client= new OkHttpClient(); Request request=new Request.Builder() .url("http://ieeeguc.org/api/User/"+id) .addHeader("Authorization",token) .addHeader("user_agent","Android") .build(); client.newCall(request).enqueue(new Callback() { public void onFailure(Call call, IOException e) { httpResponse.onFailure(-1,null); call.cancel(); } public void onResponse(Call call, okhttp3.Response response) throws IOException { int code=response.code(); String c=code+""; String body=response.body().toString(); try { JSONObject rr =new JSONObject(body); if(c.charAt(0)=='2'){ httpResponse.onSuccess(code,rr); }else { httpResponse.onFailure(code,rr); } }catch (JSONException e){ httpResponse.onFailure(code,null); } response.close(); } }); } /** * This method is called when the user performs an editing operation on his profile. * @param {String} token [user's token] * @param {String} oldPassword [user's current password] * @param {String} newPassword [user's new password] * @param {String} IeeeMembershipID [user's IEEE membership id] * @param {String} phoneNumber [user's phone number] * @param {HTTPResponse} httpResponse [HTTPResponse interface instance] * @return {void} */ public void editProfile(String token, String oldPassword, String newPassword, String IeeeMembershipID, String phoneNumber, final HTTPResponse httpResponse) { OkHttpClient client = new OkHttpClient(); HashMap<String, String> body = new HashMap<>(); body.put("old_password",oldPassword); body.put("new_password",newPassword); body.put("IEEE_membership_ID",IeeeMembershipID); body.put("phone_number",phoneNumber); Request request = new Request.Builder().put(RequestBody.create(MediaType.parse("application/json"), new JSONObject(body).toString())) .addHeader("Authorization", token) .addHeader("user_agent", "Android") .url("http://ieeeguc.org/api/user").build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { //No Internet Connection. httpResponse.onFailure(-1, null); call.cancel(); } @Override public void onResponse(Call call, Response response) throws IOException { //Getting the status code. int statusCode = response.code(); String code = String.valueOf(statusCode); if (code.charAt(0) == '2') { // The received code is of the format 2xx, and the call was successful. try { JSONObject responseBody = new JSONObject(response.body().toString()); httpResponse.onSuccess(statusCode, responseBody); } catch (JSONException e) { httpResponse.onFailure(500, null); } } else { // The received code is of the format 3xx or 4xx or 5xx, // and the call wasn't successful. try { JSONObject responseBody = new JSONObject(response.body().toString()); httpResponse.onFailure(statusCode, responseBody); } catch (JSONException e) { httpResponse.onFailure(500, null); } } response.close(); } }); } /** * This method is called when the user logs out. * @param {String} token [token of the user] * @param {HTTPResponse} httpResponse [httpResponse interface instance] * @return {void} */ public void logout(String token, final HTTPResponse httpResponse){ OkHttpClient ok = new OkHttpClient(); Request request = new Request.Builder() .addHeader("Authorization",token) .addHeader("user_agent","Android") .url("http://ieeeguc.org/api/logout") .build(); ok.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { httpResponse.onFailure(-1, null); call.cancel(); } @Override public void onResponse(Call call, Response response) throws IOException { int code = response.code(); String body = response.body().string(); try { JSONObject j = new JSONObject(body); if(code/100 == 2) { httpResponse.onSuccess(code,j); } else { httpResponse.onFailure(code,j); } } catch (JSONException e) { httpResponse.onFailure(500,null); } response.close(); } }); } }
package org.luaj.vm2; import java.io.ByteArrayInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import org.luaj.vm2.lib.MathLib; /** * Subclass of {@link LuaValue} for representing lua strings. * <p> * Because lua string values are more nearly sequences of bytes than * sequences of characters or unicode code points, the {@link LuaString} * implementation holds the string value in an internal byte array. * <p> * {@link LuaString} values are not considered mutable once constructed, * so multiple {@link LuaString} values can chare a single byte array. * <p> * Currently {@link LuaString}s are pooled via a centrally managed weak table. * To ensure that as many string values as possible take advantage of this, * Constructors are not exposed directly. As with number, booleans, and nil, * instance construction should be via {@link LuaValue#valueOf(byte[])} or similar API. * <p> * Because of this pooling, users of LuaString <em>must not directly alter the * bytes in a LuaString</em>, or undefined behavior will result. * <p> * When Java Strings are used to initialize {@link LuaString} data, the UTF8 encoding is assumed. * The functions * {@link #lengthAsUtf8(char[])}, * {@link #encodeToUtf8(char[], int, byte[], int)}, and * {@link #decodeAsUtf8(byte[], int, int)} * are used to convert back and forth between UTF8 byte arrays and character arrays. * * @see LuaValue * @see LuaValue#valueOf(String) * @see LuaValue#valueOf(byte[]) */ public class LuaString extends LuaValue { /** The singleton instance for string metatables that forwards to the string functions. * Typically, this is set to the string metatable as a side effect of loading the string * library, and is read-write to provide flexible behavior by default. When used in a * server environment where there may be roge scripts, this should be replaced with a * read-only table since it is shared across all lua code in this Java VM. */ public static LuaValue s_metatable; /** The bytes for the string. These <em><b>must not be mutated directly</b></em> because * the backing may be shared by multiple LuaStrings, and the hash code is * computed only at construction time. * It is exposed only for performance and legacy reasons. */ public final byte[] m_bytes; /** The offset into the byte array, 0 means start at the first byte */ public final int m_offset; /** The number of bytes that comprise this string */ public final int m_length; /** The hashcode for this string. Computed at construct time. */ private final int m_hashcode; /** Size of cache of recent short strings. This is the maximum number of LuaStrings that * will be retained in the cache of recent short strings. Exposed to package for testing. */ static final int RECENT_STRINGS_CACHE_SIZE = 128; /** Maximum length of a string to be considered for recent short strings caching. * This effectively limits the total memory that can be spent on the recent strings cache, * because no LuaString whose backing exceeds this length will be put into the cache. * Exposed to package for testing. */ static final int RECENT_STRINGS_MAX_LENGTH = 32; /** Simple cache of recently created strings that are short. * This is simply a list of strings, indexed by their hash codes modulo the cache size * that have been recently constructed. If a string is being constructed frequently * from different contexts, it will generally show up as a cache hit and resolve * to the same value. */ private static final class RecentShortStrings { private static final LuaString recent_short_strings[] = new LuaString[RECENT_STRINGS_CACHE_SIZE]; } /** * Get a {@link LuaString} instance whose bytes match * the supplied Java String using the UTF8 encoding. * @param string Java String containing characters to encode as UTF8 * @return {@link LuaString} with UTF8 bytes corresponding to the supplied String */ public static LuaString valueOf(String string) { char[] c = string.toCharArray(); byte[] b = new byte[lengthAsUtf8(c)]; encodeToUtf8(c, c.length, b, 0); return valueUsing(b, 0, b.length); } /** Construct a {@link LuaString} for a portion of a byte array. * <p> * The array is first be used as the backing for this object, so clients must not change contents. * If the supplied value for 'len' is more than half the length of the container, the * supplied byte array will be used as the backing, otherwise the bytes will be copied to a * new byte array, and cache lookup may be performed. * <p> * @param bytes byte buffer * @param off offset into the byte buffer * @param len length of the byte buffer * @return {@link LuaString} wrapping the byte buffer */ public static LuaString valueOf(byte[] bytes, int off, int len) { if (len > RECENT_STRINGS_MAX_LENGTH) return valueFromCopy(bytes, off, len); final int hash = hashCode(bytes, off, len); final int bucket = hash & (RECENT_STRINGS_CACHE_SIZE - 1); final LuaString t = RecentShortStrings.recent_short_strings[bucket]; if (t != null && t.m_hashcode == hash && t.byteseq(bytes, off, len)) return t; final LuaString s = valueFromCopy(bytes, off, len); RecentShortStrings.recent_short_strings[bucket] = s; return s; } /** Construct a new LuaString using a copy of the bytes array supplied */ private static LuaString valueFromCopy(byte[] bytes, int off, int len) { final byte[] copy = new byte[len]; System.arraycopy(bytes, off, copy, 0, len); return new LuaString(copy, 0, len); } /** Construct a {@link LuaString} around, possibly using the the supplied * byte array as the backing store. * <p> * The caller must ensure that the array is not mutated after the call. * However, if the string is short enough the short-string cache is checked * for a match which may be used instead of the supplied byte array. * <p> * @param bytes byte buffer * @return {@link LuaString} wrapping the byte buffer, or an equivalent string. */ static public LuaString valueUsing(byte[] bytes, int off, int len) { if (bytes.length > RECENT_STRINGS_MAX_LENGTH) return new LuaString(bytes, off, len); final int hash = hashCode(bytes, off, len); final int bucket = hash & (RECENT_STRINGS_CACHE_SIZE - 1); final LuaString t = RecentShortStrings.recent_short_strings[bucket]; if (t != null && t.m_hashcode == hash && t.byteseq(bytes, off, len)) return t; final LuaString s = new LuaString(bytes, off, len); RecentShortStrings.recent_short_strings[bucket] = s; return s; } /** Construct a {@link LuaString} using the supplied characters as byte values. * <p> * Only the low-order 8-bits of each character are used, the remainder is ignored. * <p> * This is most useful for constructing byte sequences that do not conform to UTF8. * @param bytes array of char, whose values are truncated at 8-bits each and put into a byte array. * @return {@link LuaString} wrapping a copy of the byte buffer */ public static LuaString valueOf(char[] bytes) { return valueOf(bytes, 0, bytes.length); } /** Construct a {@link LuaString} using the supplied characters as byte values. * <p> * Only the low-order 8-bits of each character are used, the remainder is ignored. * <p> * This is most useful for constructing byte sequences that do not conform to UTF8. * @param bytes array of char, whose values are truncated at 8-bits each and put into a byte array. * @return {@link LuaString} wrapping a copy of the byte buffer */ public static LuaString valueOf(char[] bytes, int off, int len) { byte[] b = new byte[len]; for ( int i=0; i<len; i++ ) b[i] = (byte) bytes[i + off]; return valueUsing(b, 0, len); } /** Construct a {@link LuaString} for all the bytes in a byte array. * <p> * The LuaString returned will either be a new LuaString containing a copy * of the bytes array, or be an existing LuaString used already having the same value. * <p> * @param bytes byte buffer * @return {@link LuaString} wrapping the byte buffer */ public static LuaString valueOf(byte[] bytes) { return valueOf(bytes, 0, bytes.length); } /** Construct a {@link LuaString} for all the bytes in a byte array, possibly using * the supplied array as the backing store. * <p> * The LuaString returned will either be a new LuaString containing the byte array, * or be an existing LuaString used already having the same value. * <p> * The caller must not mutate the contents of the byte array after this call, as * it may be used elsewhere due to recent short string caching. * @param bytes byte buffer * @return {@link LuaString} wrapping the byte buffer */ public static LuaString valueUsing(byte[] bytes) { return valueUsing(bytes, 0, bytes.length); } /** Construct a {@link LuaString} around a byte array without copying the contents. * <p> * The array is used directly after this is called, so clients must not change contents. * <p> * @param bytes byte buffer * @param offset offset into the byte buffer * @param length length of the byte buffer * @return {@link LuaString} wrapping the byte buffer */ private LuaString(byte[] bytes, int offset, int length) { this.m_bytes = bytes; this.m_offset = offset; this.m_length = length; this.m_hashcode = hashCode(bytes, offset, length); } public boolean isstring() { return true; } public LuaValue getmetatable() { return s_metatable; } public int type() { return LuaValue.TSTRING; } public String typename() { return "string"; } public String tojstring() { return decodeAsUtf8(m_bytes, m_offset, m_length); } // unary operators public LuaValue neg() { double d = scannumber(); return Double.isNaN(d)? super.neg(): valueOf(-d); } // basic binary arithmetic public LuaValue add( LuaValue rhs ) { double d = scannumber(); return Double.isNaN(d)? arithmt(ADD,rhs): rhs.add(d); } public LuaValue add( double rhs ) { return valueOf( checkarith() + rhs ); } public LuaValue add( int rhs ) { return valueOf( checkarith() + rhs ); } public LuaValue sub( LuaValue rhs ) { double d = scannumber(); return Double.isNaN(d)? arithmt(SUB,rhs): rhs.subFrom(d); } public LuaValue sub( double rhs ) { return valueOf( checkarith() - rhs ); } public LuaValue sub( int rhs ) { return valueOf( checkarith() - rhs ); } public LuaValue subFrom( double lhs ) { return valueOf( lhs - checkarith() ); } public LuaValue mul( LuaValue rhs ) { double d = scannumber(); return Double.isNaN(d)? arithmt(MUL,rhs): rhs.mul(d); } public LuaValue mul( double rhs ) { return valueOf( checkarith() * rhs ); } public LuaValue mul( int rhs ) { return valueOf( checkarith() * rhs ); } public LuaValue pow( LuaValue rhs ) { double d = scannumber(); return Double.isNaN(d)? arithmt(POW,rhs): rhs.powWith(d); } public LuaValue pow( double rhs ) { return MathLib.dpow(checkarith(),rhs); } public LuaValue pow( int rhs ) { return MathLib.dpow(checkarith(),rhs); } public LuaValue powWith( double lhs ) { return MathLib.dpow(lhs, checkarith()); } public LuaValue powWith( int lhs ) { return MathLib.dpow(lhs, checkarith()); } public LuaValue div( LuaValue rhs ) { double d = scannumber(); return Double.isNaN(d)? arithmt(DIV,rhs): rhs.divInto(d); } public LuaValue div( double rhs ) { return LuaDouble.ddiv(checkarith(),rhs); } public LuaValue div( int rhs ) { return LuaDouble.ddiv(checkarith(),rhs); } public LuaValue divInto( double lhs ) { return LuaDouble.ddiv(lhs, checkarith()); } public LuaValue mod( LuaValue rhs ) { double d = scannumber(); return Double.isNaN(d)? arithmt(MOD,rhs): rhs.modFrom(d); } public LuaValue mod( double rhs ) { return LuaDouble.dmod(checkarith(), rhs); } public LuaValue mod( int rhs ) { return LuaDouble.dmod(checkarith(), rhs); } public LuaValue modFrom( double lhs ) { return LuaDouble.dmod(lhs, checkarith()); } // relational operators, these only work with other strings public LuaValue lt( LuaValue rhs ) { return rhs.isstring() ? (rhs.strcmp(this)>0? LuaValue.TRUE: FALSE) : super.lt(rhs); } public boolean lt_b( LuaValue rhs ) { return rhs.isstring() ? rhs.strcmp(this)>0 : super.lt_b(rhs); } public boolean lt_b( int rhs ) { typerror("attempt to compare string with number"); return false; } public boolean lt_b( double rhs ) { typerror("attempt to compare string with number"); return false; } public LuaValue lteq( LuaValue rhs ) { return rhs.isstring() ? (rhs.strcmp(this)>=0? LuaValue.TRUE: FALSE) : super.lteq(rhs); } public boolean lteq_b( LuaValue rhs ) { return rhs.isstring() ? rhs.strcmp(this)>=0 : super.lteq_b(rhs); } public boolean lteq_b( int rhs ) { typerror("attempt to compare string with number"); return false; } public boolean lteq_b( double rhs ) { typerror("attempt to compare string with number"); return false; } public LuaValue gt( LuaValue rhs ) { return rhs.isstring() ? (rhs.strcmp(this)<0? LuaValue.TRUE: FALSE) : super.gt(rhs); } public boolean gt_b( LuaValue rhs ) { return rhs.isstring() ? rhs.strcmp(this)<0 : super.gt_b(rhs); } public boolean gt_b( int rhs ) { typerror("attempt to compare string with number"); return false; } public boolean gt_b( double rhs ) { typerror("attempt to compare string with number"); return false; } public LuaValue gteq( LuaValue rhs ) { return rhs.isstring() ? (rhs.strcmp(this)<=0? LuaValue.TRUE: FALSE) : super.gteq(rhs); } public boolean gteq_b( LuaValue rhs ) { return rhs.isstring() ? rhs.strcmp(this)<=0 : super.gteq_b(rhs); } public boolean gteq_b( int rhs ) { typerror("attempt to compare string with number"); return false; } public boolean gteq_b( double rhs ) { typerror("attempt to compare string with number"); return false; } // concatenation public LuaValue concat(LuaValue rhs) { return rhs.concatTo(this); } public Buffer concat(Buffer rhs) { return rhs.concatTo(this); } public LuaValue concatTo(LuaNumber lhs) { return concatTo(lhs.strvalue()); } public LuaValue concatTo(LuaString lhs) { byte[] b = new byte[lhs.m_length+this.m_length]; System.arraycopy(lhs.m_bytes, lhs.m_offset, b, 0, lhs.m_length); System.arraycopy(this.m_bytes, this.m_offset, b, lhs.m_length, this.m_length); return valueUsing(b, 0, b.length); } // string comparison public int strcmp(LuaValue lhs) { return -lhs.strcmp(this); } public int strcmp(LuaString rhs) { for ( int i=0, j=0; i<m_length && j<rhs.m_length; ++i, ++j ) { if ( m_bytes[m_offset+i] != rhs.m_bytes[rhs.m_offset+j] ) { return ((int)m_bytes[m_offset+i]) - ((int) rhs.m_bytes[rhs.m_offset+j]); } } return m_length - rhs.m_length; } /** Check for number in arithmetic, or throw aritherror */ private double checkarith() { double d = scannumber(); if ( Double.isNaN(d) ) aritherror(); return d; } public int checkint() { return (int) (long) checkdouble(); } public LuaInteger checkinteger() { return valueOf(checkint()); } public long checklong() { return (long) checkdouble(); } public double checkdouble() { double d = scannumber(); if ( Double.isNaN(d) ) argerror("number"); return d; } public LuaNumber checknumber() { return valueOf(checkdouble()); } public LuaNumber checknumber(String msg) { double d = scannumber(); if ( Double.isNaN(d) ) error(msg); return valueOf(d); } public boolean isnumber() { double d = scannumber(); return ! Double.isNaN(d); } public boolean isint() { double d = scannumber(); if ( Double.isNaN(d) ) return false; int i = (int) d; return i == d; } public boolean islong() { double d = scannumber(); if ( Double.isNaN(d) ) return false; long l = (long) d; return l == d; } public byte tobyte() { return (byte) toint(); } public char tochar() { return (char) toint(); } public double todouble() { double d=scannumber(); return Double.isNaN(d)? 0: d; } public float tofloat() { return (float) todouble(); } public int toint() { return (int) tolong(); } public long tolong() { return (long) todouble(); } public short toshort() { return (short) toint(); } public double optdouble(double defval) { return checkdouble(); } public int optint(int defval) { return checkint(); } public LuaInteger optinteger(LuaInteger defval) { return checkinteger(); } public long optlong(long defval) { return checklong(); } public LuaNumber optnumber(LuaNumber defval) { return checknumber(); } public LuaString optstring(LuaString defval) { return this; } public LuaValue tostring() { return this; } public String optjstring(String defval) { return tojstring(); } public LuaString strvalue() { return this; } /** Take a substring using Java zero-based indexes for begin and end or range. * @param beginIndex The zero-based index of the first character to include. * @param endIndex The zero-based index of position after the last character. * @return LuaString which is a substring whose first character is at offset * beginIndex and extending for (endIndex - beginIndex ) characters. */ public LuaString substring( int beginIndex, int endIndex ) { final int off = m_offset + beginIndex; final int len = endIndex - beginIndex; return len >= m_length / 2? valueUsing(m_bytes, off, len): valueOf(m_bytes, off, len); } public int hashCode() { return m_hashcode; } /** Compute the hash code of a sequence of bytes within a byte array using * lua's rules for string hashes. For long strings, not all bytes are hashed. * @param bytes byte array containing the bytes. * @param offset offset into the hash for the first byte. * @param length number of bytes starting with offset that are part of the string. * @return hash for the string defined by bytes, offset, and length. */ public static int hashCode(byte[] bytes, int offset, int length) { int h = length; /* seed */ int step = (length>>5)+1; /* if string is too long, don't hash all its chars */ for (int l1=length; l1>=step; l1-=step) /* compute hash */ h = h ^ ((h<<5)+(h>>2)+(((int) bytes[offset+l1-1] ) & 0x0FF )); return h; } // object comparison, used in key comparison public boolean equals( Object o ) { if ( o instanceof LuaString ) { return raweq( (LuaString) o ); } return false; } // equality w/ metatable processing public LuaValue eq( LuaValue val ) { return val.raweq(this)? TRUE: FALSE; } public boolean eq_b( LuaValue val ) { return val.raweq(this); } // equality w/o metatable processing public boolean raweq( LuaValue val ) { return val.raweq(this); } public boolean raweq( LuaString s ) { if ( this == s ) return true; if ( s.m_length != m_length ) return false; if ( s.m_bytes == m_bytes && s.m_offset == m_offset ) return true; if ( s.hashCode() != hashCode() ) return false; for ( int i=0; i<m_length; i++ ) if ( s.m_bytes[s.m_offset+i] != m_bytes[m_offset+i] ) return false; return true; } public static boolean equals( LuaString a, int i, LuaString b, int j, int n ) { return equals( a.m_bytes, a.m_offset + i, b.m_bytes, b.m_offset + j, n ); } /** Return true if the bytes in the supplied range match this LuaStrings bytes. */ private boolean byteseq(byte[] bytes, int off, int len) { return (m_length == len && equals(m_bytes, m_offset, bytes, off, len)); } public static boolean equals( byte[] a, int i, byte[] b, int j, int n ) { if ( a.length < i + n || b.length < j + n ) return false; while ( --n>=0 ) if ( a[i++]!=b[j++] ) return false; return true; } public void write(DataOutputStream writer, int i, int len) throws IOException { writer.write(m_bytes,m_offset+i,len); } public LuaValue len() { return LuaInteger.valueOf(m_length); } public int length() { return m_length; } public int rawlen() { return m_length; } public int luaByte(int index) { return m_bytes[m_offset + index] & 0x0FF; } public int charAt( int index ) { if ( index < 0 || index >= m_length ) throw new IndexOutOfBoundsException(); return luaByte( index ); } public String checkjstring() { return tojstring(); } public LuaString checkstring() { return this; } /** Convert value to an input stream. * * @return {@link InputStream} whose data matches the bytes in this {@link LuaString} */ public InputStream toInputStream() { return new ByteArrayInputStream(m_bytes, m_offset, m_length); } /** * Copy the bytes of the string into the given byte array. * @param strOffset offset from which to copy * @param bytes destination byte array * @param arrayOffset offset in destination * @param len number of bytes to copy */ public void copyInto( int strOffset, byte[] bytes, int arrayOffset, int len ) { System.arraycopy( m_bytes, m_offset+strOffset, bytes, arrayOffset, len ); } /** Java version of strpbrk - find index of any byte that in an accept string. * @param accept {@link LuaString} containing characters to look for. * @return index of first match in the {@code accept} string, or -1 if not found. */ public int indexOfAny( LuaString accept ) { final int ilimit = m_offset + m_length; final int jlimit = accept.m_offset + accept.m_length; for ( int i = m_offset; i < ilimit; ++i ) { for ( int j = accept.m_offset; j < jlimit; ++j ) { if ( m_bytes[i] == accept.m_bytes[j] ) { return i - m_offset; } } } return -1; } /** * Find the index of a byte starting at a point in this string * @param b the byte to look for * @param start the first index in the string * @return index of first match found, or -1 if not found. */ public int indexOf( byte b, int start ) { for ( int i=start; i < m_length; ++i ) { if ( m_bytes[m_offset+i] == b ) return i; } return -1; } /** * Find the index of a string starting at a point in this string * @param s the string to search for * @param start the first index in the string * @return index of first match found, or -1 if not found. */ public int indexOf( LuaString s, int start ) { final int slen = s.length(); final int limit = m_length - slen; for ( int i=start; i <= limit; ++i ) { if ( equals( m_bytes, m_offset+i, s.m_bytes, s.m_offset, slen ) ) return i; } return -1; } /** * Find the last index of a string in this string * @param s the string to search for * @return index of last match found, or -1 if not found. */ public int lastIndexOf( LuaString s ) { final int slen = s.length(); final int limit = m_length - slen; for ( int i=limit; i >= 0; --i ) { if ( equals( m_bytes, m_offset+i, s.m_bytes, s.m_offset, slen ) ) return i; } return -1; } /** * Convert to Java String interpreting as utf8 characters. * * @param bytes byte array in UTF8 encoding to convert * @param offset starting index in byte array * @param length number of bytes to convert * @return Java String corresponding to the value of bytes interpreted using UTF8 * @see #lengthAsUtf8(char[]) * @see #encodeToUtf8(char[], int, byte[], int) * @see #isValidUtf8() */ public static String decodeAsUtf8(byte[] bytes, int offset, int length) { int i,j,n,b; for ( i=offset,j=offset+length,n=0; i<j; ++n ) { switch ( 0xE0 & bytes[i++] ) { case 0xE0: ++i; case 0xC0: ++i; } } char[] chars=new char[n]; for ( i=offset,j=offset+length,n=0; i<j; ) { chars[n++] = (char) ( ((b=bytes[i++])>=0||i>=j)? b: (b<-32||i+1>=j)? (((b&0x3f) << 6) | (bytes[i++]&0x3f)): (((b&0xf) << 12) | ((bytes[i++]&0x3f)<<6) | (bytes[i++]&0x3f))); } return new String(chars); } /** * Count the number of bytes required to encode the string as UTF-8. * @param chars Array of unicode characters to be encoded as UTF-8 * @return count of bytes needed to encode using UTF-8 * @see #encodeToUtf8(char[], int, byte[], int) * @see #decodeAsUtf8(byte[], int, int) * @see #isValidUtf8() */ public static int lengthAsUtf8(char[] chars) { int i,b; char c; for ( i=b=chars.length; --i>=0; ) if ( (c=chars[i]) >=0x80 ) b += (c>=0x800)? 2: 1; return b; } /** * Encode the given Java string as UTF-8 bytes, writing the result to bytes * starting at offset. * <p> * The string should be measured first with lengthAsUtf8 * to make sure the given byte array is large enough. * @param chars Array of unicode characters to be encoded as UTF-8 * @param nchars Number of characters in the array to convert. * @param bytes byte array to hold the result * @param off offset into the byte array to start writing * @return number of bytes converted. * @see #lengthAsUtf8(char[]) * @see #decodeAsUtf8(byte[], int, int) * @see #isValidUtf8() */ public static int encodeToUtf8(char[] chars, int nchars, byte[] bytes, int off) { char c; int j = off; for ( int i=0; i<nchars; i++ ) { if ( (c = chars[i]) < 0x80 ) { bytes[j++] = (byte) c; } else if ( c < 0x800 ) { bytes[j++] = (byte) (0xC0 | ((c>>6) & 0x1f)); bytes[j++] = (byte) (0x80 | ( c & 0x3f)); } else { bytes[j++] = (byte) (0xE0 | ((c>>12) & 0x0f)); bytes[j++] = (byte) (0x80 | ((c>>6) & 0x3f)); bytes[j++] = (byte) (0x80 | ( c & 0x3f)); } } return j - off; } /** Check that a byte sequence is valid UTF-8 * @return true if it is valid UTF-8, otherwise false * @see #lengthAsUtf8(char[]) * @see #encodeToUtf8(char[], int, byte[], int) * @see #decodeAsUtf8(byte[], int, int) */ public boolean isValidUtf8() { for (int i=m_offset,j=m_offset+m_length; i<j;) { int c = m_bytes[i++]; if ( c >= 0 ) continue; if ( ((c & 0xE0) == 0xC0) && i<j && (m_bytes[i++] & 0xC0) == 0x80) continue; if ( ((c & 0xF0) == 0xE0) && i+1<j && (m_bytes[i++] & 0xC0) == 0x80 && (m_bytes[i++] & 0xC0) == 0x80) continue; return false; } return true; } /** * convert to a number using baee 10 or base 16 if it starts with '0x', * or NIL if it can't be converted * @return IntValue, DoubleValue, or NIL depending on the content of the string. * @see LuaValue#tonumber() */ public LuaValue tonumber() { double d = scannumber(); return Double.isNaN(d)? NIL: valueOf(d); } /** * convert to a number using a supplied base, or NIL if it can't be converted * @param base the base to use, such as 10 * @return IntValue, DoubleValue, or NIL depending on the content of the string. * @see LuaValue#tonumber() */ public LuaValue tonumber( int base ) { double d = scannumber( base ); return Double.isNaN(d)? NIL: valueOf(d); } /** * Convert to a number in base 10, or base 16 if the string starts with '0x', * or return Double.NaN if it cannot be converted to a number. * @return double value if conversion is valid, or Double.NaN if not */ public double scannumber() { int i=m_offset,j=m_offset+m_length; while ( i<j && m_bytes[i]==' ' ) ++i; while ( i<j && m_bytes[j-1]==' ' ) --j; if ( i>=j ) return Double.NaN; if ( m_bytes[i]=='0' && i+1<j && (m_bytes[i+1]=='x'||m_bytes[i+1]=='X')) return scanlong(16, i+2, j); double l = scanlong(10, i, j); return Double.isNaN(l)? scandouble(i,j): l; } /** * Convert to a number in a base, or return Double.NaN if not a number. * @param base the base to use between 2 and 36 * @return double value if conversion is valid, or Double.NaN if not */ public double scannumber(int base) { if ( base < 2 || base > 36 ) return Double.NaN; int i=m_offset,j=m_offset+m_length; while ( i<j && m_bytes[i]==' ' ) ++i; while ( i<j && m_bytes[j-1]==' ' ) --j; if ( i>=j ) return Double.NaN; return scanlong( base, i, j ); } /** * Scan and convert a long value, or return Double.NaN if not found. * @param base the base to use, such as 10 * @param start the index to start searching from * @param end the first index beyond the search range * @return double value if conversion is valid, * or Double.NaN if not */ private double scanlong( int base, int start, int end ) { long x = 0; boolean neg = (m_bytes[start] == '-'); for ( int i=(neg?start+1:start); i<end; i++ ) { int digit = m_bytes[i] - (base<=10||(m_bytes[i]>='0'&&m_bytes[i]<='9')? '0': m_bytes[i]>='A'&&m_bytes[i]<='Z'? ('A'-10): ('a'-10)); if ( digit < 0 || digit >= base ) return Double.NaN; x = x * base + digit; if ( x < 0 ) return Double.NaN; // overflow } return neg? -x: x; } /** * Scan and convert a double value, or return Double.NaN if not a double. * @param start the index to start searching from * @param end the first index beyond the search range * @return double value if conversion is valid, * or Double.NaN if not */ private double scandouble(int start, int end) { if ( end>start+64 ) end=start+64; for ( int i=start; i<end; i++ ) { switch ( m_bytes[i] ) { case '-': case '+': case '.': case 'e': case 'E': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': break; default: return Double.NaN; } } char [] c = new char[end-start]; for ( int i=start; i<end; i++ ) c[i-start] = (char) m_bytes[i]; try { return Double.parseDouble(new String(c)); } catch ( Exception e ) { return Double.NaN; } } /** * Print the bytes of the LuaString to a PrintStream as if it were * an ASCII string, quoting and escaping control characters. * @param ps PrintStream to print to. */ public void printToStream(PrintStream ps) { for (int i = 0, n = m_length; i < n; i++) { int c = m_bytes[m_offset+i]; ps.print((char) c); } } }
package org.wikipedia.page; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.SearchManager; import android.appwidget.AppWidgetManager; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.location.Location; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.VisibleForTesting; import android.support.design.widget.BottomSheetDialog; import android.support.design.widget.BottomSheetDialogFragment; import android.support.v4.app.Fragment; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.preference.PreferenceManager; import android.support.v7.view.ActionMode; import android.support.v7.widget.Toolbar; import android.text.format.DateUtils; import android.view.KeyEvent; import android.view.MenuItem; import android.view.View; import android.view.WindowManager; import android.widget.ProgressBar; import com.squareup.otto.Bus; import com.squareup.otto.Subscribe; import net.hockeyapp.android.metrics.MetricsManager; import org.apache.commons.lang3.StringUtils; import org.wikipedia.Constants; import org.wikipedia.R; import org.wikipedia.WikipediaApp; import org.wikipedia.activity.ThemedActionBarActivity; import org.wikipedia.analytics.IntentFunnel; import org.wikipedia.analytics.LinkPreviewFunnel; import org.wikipedia.dataclient.WikiSite; import org.wikipedia.descriptions.DescriptionEditRevertHelpView; import org.wikipedia.events.ChangeTextSizeEvent; import org.wikipedia.gallery.GalleryActivity; import org.wikipedia.history.HistoryEntry; import org.wikipedia.language.LangLinksActivity; import org.wikipedia.page.linkpreview.LinkPreviewDialog; import org.wikipedia.page.snippet.CompatActionMode; import org.wikipedia.page.tabs.TabsProvider; import org.wikipedia.page.tabs.TabsProvider.TabPosition; import org.wikipedia.readinglist.AddToReadingListDialog; import org.wikipedia.search.SearchFragment; import org.wikipedia.search.SearchInvokeSource; import org.wikipedia.settings.SettingsActivity; import org.wikipedia.staticdata.MainPageNameData; import org.wikipedia.theme.ThemeChooserDialog; import org.wikipedia.tooltip.ToolTipUtil; import org.wikipedia.useroption.sync.UserOptionContentResolver; import org.wikipedia.util.ClipboardUtil; import org.wikipedia.util.DeviceUtil; import org.wikipedia.util.FeedbackUtil; import org.wikipedia.util.ShareUtil; import org.wikipedia.util.log.L; import org.wikipedia.widgets.WidgetProviderFeaturedPage; import org.wikipedia.wiktionary.WiktionaryDialog; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.Unbinder; import static org.wikipedia.util.DeviceUtil.isBackKeyUp; import static org.wikipedia.util.UriUtil.visitInExternalBrowser; public class PageActivity extends ThemedActionBarActivity implements PageFragment.Callback, LinkPreviewDialog.Callback, SearchFragment.Callback, WiktionaryDialog.Callback, AddToReadingListDialog.Callback { public static final String ACTION_PAGE_FOR_TITLE = "org.wikipedia.page_for_title"; public static final String ACTION_SHOW_TAB_LIST = "org.wikipedia.show_tab_list"; public static final String ACTION_RESUME_READING = "org.wikipedia.resume_reading"; public static final String EXTRA_PAGETITLE = "org.wikipedia.pagetitle"; public static final String EXTRA_HISTORYENTRY = "org.wikipedia.history.historyentry"; private static final String LANGUAGE_CODE_BUNDLE_KEY = "language"; @BindView(R.id.tabs_container) View tabsContainerView; @BindView(R.id.page_progress_bar) ProgressBar progressBar; @BindView(R.id.page_toolbar_container) View toolbarContainerView; @BindView(R.id.page_toolbar) Toolbar toolbar; private Unbinder unbinder; private PageFragment pageFragment; private WikipediaApp app; private Bus bus; private EventBusMethods busMethods; private CompatActionMode currentActionMode; private PageToolbarHideHandler toolbarHideHandler; private ExclusiveBottomSheetPresenter bottomSheetPresenter = new ExclusiveBottomSheetPresenter(); @Nullable private PageLoadCallbacks pageLoadCallbacks; private DialogInterface.OnDismissListener listDialogDismissListener = new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialogInterface) { pageFragment.updateBookmark(); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); app = (WikipediaApp) getApplicationContext(); MetricsManager.register(app, app); app.checkCrashes(this); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); } PreferenceManager.setDefaultValues(this, R.xml.preferences, false); setContentView(R.layout.activity_page); unbinder = ButterKnife.bind(this); busMethods = new EventBusMethods(); registerBus(); updateProgressBar(false, true, 0); pageFragment = (PageFragment) getSupportFragmentManager().findFragmentById(R.id.page_fragment); setSupportActionBar(toolbar); getSupportActionBar().setTitle(""); getSupportActionBar().setDisplayHomeAsUpEnabled(true); toolbarHideHandler = new PageToolbarHideHandler(toolbarContainerView); boolean languageChanged = false; if (savedInstanceState != null) { if (savedInstanceState.getBoolean("isSearching")) { openSearchFragment(SearchInvokeSource.TOOLBAR, null); } String language = savedInstanceState.getString(LANGUAGE_CODE_BUNDLE_KEY); languageChanged = !app.getAppOrSystemLanguageCode().equals(language); // Note: when system language is enabled, and the system language is changed outside of // the app, MRU languages are not updated. There's no harm in doing that here but since // the user didin't choose that language in app, it may be unexpected. } if (languageChanged) { app.resetWikiSite(); loadMainPageInForegroundTab(); } if (savedInstanceState == null) { // if there's no savedInstanceState, and we're not coming back from a Theme change, // then we must have been launched with an Intent, so... handle it! handleIntent(getIntent()); } UserOptionContentResolver.requestManualSync(); } private void finishActionMode() { currentActionMode.finish(); } private void nullifyActionMode() { currentActionMode = null; } public void hideSoftKeyboard() { DeviceUtil.hideSoftKeyboard(this); } // Note: this method is invoked even when in CAB mode. @Override public boolean dispatchKeyEvent(@NonNull KeyEvent event) { return isBackKeyUp(event) && ToolTipUtil.dismissToolTip(this) || super.dispatchKeyEvent(event); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: if (shouldRecreateMainActivity()) { startActivity(getSupportParentActivityIntent() .putExtra(Constants.INTENT_RETURN_TO_MAIN, true)); } finish(); return true; default: return super.onOptionsItemSelected(item); } } @Override public boolean onSearchRequested() { showToolbar(); openSearchFragment(SearchInvokeSource.TOOLBAR, null); return true; } public void showToolbar() { // TODO: make toolbar visible, via CoordinatorLayout } /** @return True if the contextual action bar is open. */ public boolean isCabOpen() { return currentActionMode != null; } @NonNull public static Intent newIntent(@NonNull Context context) { return new Intent(ACTION_RESUME_READING).setClass(context, PageActivity.class); } @NonNull public static Intent newIntent(@NonNull Context context, @NonNull String title) { PageTitle pageTitle = new PageTitle(title, WikipediaApp.getInstance().getWikiSite()); return newIntent(context, new HistoryEntry(pageTitle, HistoryEntry.SOURCE_INTERNAL_LINK), pageTitle); } @NonNull public static Intent newIntent(@NonNull Context context, @NonNull HistoryEntry entry, @NonNull PageTitle title) { return new Intent(ACTION_PAGE_FOR_TITLE) .setClass(context, PageActivity.class) .putExtra(EXTRA_HISTORYENTRY, entry) .putExtra(EXTRA_PAGETITLE, title); } @NonNull public static Intent newIntentForTabList(@NonNull Context context) { return new Intent(ACTION_SHOW_TAB_LIST).setClass(context, PageActivity.class); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); setIntent(intent); handleIntent(intent); } private void handleIntent(@NonNull Intent intent) { if (Intent.ACTION_VIEW.equals(intent.getAction()) && intent.getData() != null) { WikiSite wiki = new WikiSite(intent.getData().getAuthority()); PageTitle title = wiki.titleForUri(intent.getData()); HistoryEntry historyEntry = new HistoryEntry(title, HistoryEntry.SOURCE_EXTERNAL_LINK); loadPageInForegroundTab(title, historyEntry); } else if (ACTION_PAGE_FOR_TITLE.equals(intent.getAction())) { PageTitle title = intent.getParcelableExtra(EXTRA_PAGETITLE); HistoryEntry historyEntry = intent.getParcelableExtra(EXTRA_HISTORYENTRY); loadPageInForegroundTab(title, historyEntry); if (intent.hasExtra(Constants.INTENT_EXTRA_REVERT_QNUMBER)) { showDescriptionEditRevertDialog(intent.getStringExtra(Constants.INTENT_EXTRA_REVERT_QNUMBER)); } } else if (ACTION_SHOW_TAB_LIST.equals(intent.getAction()) || ACTION_RESUME_READING.equals(intent.getAction())) { // do nothing, since this will be handled indirectly by PageFragment. } else if (Intent.ACTION_SEARCH.equals(intent.getAction())) { String query = intent.getStringExtra(SearchManager.QUERY); PageTitle title = new PageTitle(query, app.getWikiSite()); HistoryEntry historyEntry = new HistoryEntry(title, HistoryEntry.SOURCE_SEARCH); loadPageInForegroundTab(title, historyEntry); } else if (intent.hasExtra(Constants.INTENT_FEATURED_ARTICLE_FROM_WIDGET)) { new IntentFunnel(app).logFeaturedArticleWidgetTap(); loadMainPageInForegroundTab(); } else { loadMainPageInCurrentTab(); } } /** * Update the state of the main progress bar that is shown inside the ActionBar of the activity. * @param visible Whether the progress bar is visible. * @param indeterminate Whether the progress bar is indeterminate. * @param value Value of the progress bar (may be between 0 and 10000). Ignored if the * progress bar is indeterminate. */ public void updateProgressBar(boolean visible, boolean indeterminate, int value) { progressBar.setIndeterminate(indeterminate); if (!indeterminate) { progressBar.setProgress(value); } progressBar.setVisibility(visible ? View.VISIBLE : View.GONE); } /** * Returns whether we're currently in a "searching" state (i.e. the search fragment is shown). * @return True if currently searching, false otherwise. */ public boolean isSearching() { SearchFragment searchFragment = searchFragment(); return searchFragment != null && searchFragment.isSearchActive(); } /** * Load a new page, and put it on top of the backstack. * @param title Title of the page to load. * @param entry HistoryEntry associated with this page. */ public void loadPage(PageTitle title, HistoryEntry entry) { loadPage(title, entry, TabPosition.CURRENT_TAB); } /** * Load a new page, and put it on top of the backstack, optionally allowing state loss of the * fragment manager. Useful for when this function is called from an AsyncTask result. * @param title Title of the page to load. * @param entry HistoryEntry associated with this page. * @param position Whether to open this page in the current tab, a new background tab, or new * foreground tab. */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) public void loadPage(final PageTitle title, final HistoryEntry entry, final TabPosition position) { if (isDestroyed()) { return; } if (entry.getSource() != HistoryEntry.SOURCE_INTERNAL_LINK || !app.isLinkPreviewEnabled()) { new LinkPreviewFunnel(app, entry.getSource()).logNavigate(); } app.putCrashReportProperty("api", title.getWikiSite().authority()); app.putCrashReportProperty("title", title.toString()); if (title.isSpecial()) { visitInExternalBrowser(this, Uri.parse(title.getMobileUri())); return; } tabsContainerView.post(new Runnable() { @Override public void run() { if (!pageFragment.isAdded()) { return; } // Close the link preview, if one is open. hideLinkPreview(); pageFragment.closeFindInPage(); if (position == TabPosition.CURRENT_TAB) { pageFragment.loadPage(title, entry, true); } else if (position == TabPosition.NEW_TAB_BACKGROUND) { pageFragment.openInNewBackgroundTabFromMenu(title, entry); } else { pageFragment.openInNewForegroundTabFromMenu(title, entry); } app.getSessionFunnel().pageViewed(entry); } }); } public void loadPageInForegroundTab(PageTitle title, HistoryEntry entry) { loadPage(title, entry, TabPosition.NEW_TAB_FOREGROUND); } public void loadMainPageInForegroundTab() { loadMainPage(TabPosition.NEW_TAB_FOREGROUND); } private void loadMainPageInCurrentTab() { loadMainPage(TabPosition.CURRENT_TAB); } /** * Go directly to the Main Page of the current Wiki, optionally allowing state loss of the * fragment manager. Useful for when this function is called from an AsyncTask result. */ public void loadMainPage(TabPosition position) { PageTitle title = new PageTitle(MainPageNameData.valueFor(app.getAppOrSystemLanguageCode()), app.getWikiSite()); HistoryEntry historyEntry = new HistoryEntry(title, HistoryEntry.SOURCE_MAIN_PAGE); loadPage(title, historyEntry, position); } public void showLinkPreview(PageTitle title, int entrySource) { showLinkPreview(title, entrySource, null); } public void showLinkPreview(PageTitle title, int entrySource, @Nullable Location location) { bottomSheetPresenter.show(getSupportFragmentManager(), LinkPreviewDialog.newInstance(title, entrySource, location)); } private void hideLinkPreview() { bottomSheetPresenter.dismiss(getSupportFragmentManager()); } public void showAddToListDialog(@NonNull PageTitle title, @NonNull AddToReadingListDialog.InvokeSource source) { bottomSheetPresenter.showAddToListDialog(getSupportFragmentManager(), title, source, listDialogDismissListener); } @Override public void showReadingListAddedMessage(@NonNull String message) { FeedbackUtil.makeSnackbar(this, message, FeedbackUtil.LENGTH_DEFAULT).show(); } // Note: back button first handled in {@link #onOptionsItemSelected()}; @Override public void onBackPressed() { if (ToolTipUtil.dismissToolTip(this)) { return; } if (isCabOpen()) { finishActionMode(); return; } SearchFragment searchFragment = searchFragment(); if (searchFragment != null && searchFragment.onBackPressed()) { if (searchFragment.isLaunchedFromIntent()) { finish(); } return; } app.getSessionFunnel().backPressed(); if (pageFragment.onBackPressed()) { return; } finish(); } @Override public void onPageShowBottomSheet(@NonNull BottomSheetDialog dialog) { bottomSheetPresenter.show(getSupportFragmentManager(), dialog); } @Override public void onPageShowBottomSheet(@NonNull BottomSheetDialogFragment dialog) { bottomSheetPresenter.show(getSupportFragmentManager(), dialog); } @Override public void onPageDismissBottomSheet() { bottomSheetPresenter.dismiss(getSupportFragmentManager()); } @Nullable @Override public PageToolbarHideHandler onPageGetToolbarHideHandler() { return toolbarHideHandler; } @Override public void onPageLoadPage(@NonNull PageTitle title, @NonNull HistoryEntry entry) { loadPage(title, entry); } @Override public void onPageShowLinkPreview(@NonNull PageTitle title, int source) { showLinkPreview(title, source); } @Override public void onPageLoadMainPageInForegroundTab() { loadMainPageInForegroundTab(); } @Override public void onPageUpdateProgressBar(boolean visible, boolean indeterminate, int value) { updateProgressBar(visible, indeterminate, value); } @Override public boolean onPageIsSearching() { return isSearching(); } @Nullable @Override public Fragment onPageGetTopFragment() { return pageFragment; } @Override public void onPageShowThemeChooser() { bottomSheetPresenter.show(getSupportFragmentManager(), new ThemeChooserDialog()); } @Nullable @Override public ActionMode onPageStartSupportActionMode(@NonNull ActionMode.Callback callback) { return startSupportActionMode(callback); } @Override public void onPageShowToolbar() { showToolbar(); } @Override public void onPageHideSoftKeyboard() { hideSoftKeyboard(); } @Nullable @Override public PageLoadCallbacks onPageGetPageLoadCallbacks() { return pageLoadCallbacks; } @Override public void onPageLoadPage(@NonNull PageTitle title, @NonNull HistoryEntry entry, @NonNull TabPosition tabPosition) { loadPage(title, entry, tabPosition); } @Override public void onPageAddToReadingList(@NonNull PageTitle title, @NonNull AddToReadingListDialog.InvokeSource source) { showAddToListDialog(title, source); } @Nullable @Override public View onPageGetContentView() { return pageFragment.getView(); } @Nullable @Override public View onPageGetTabsContainerView() { return tabsContainerView; } @Override public void onPagePopFragment() { finish(); } @Override public void onPageInvalidateOptionsMenu() { supportInvalidateOptionsMenu(); } @Override public void onPageSearchRequested() { openSearchFragment(SearchInvokeSource.TOOLBAR, null); } @Override public void onSearchSelectPage(@NonNull HistoryEntry entry, boolean inNewTab) { loadPage(entry.getTitle(), entry, inNewTab ? TabsProvider.TabPosition.NEW_TAB_BACKGROUND : TabsProvider.TabPosition.CURRENT_TAB); } @Override public void onSearchOpen() { toolbarContainerView.setVisibility(View.GONE); } @Override public void onSearchClose(boolean launchedFromIntent) { SearchFragment fragment = searchFragment(); if (fragment != null) { closeSearchFragment(fragment); } toolbarContainerView.setVisibility(View.VISIBLE); hideSoftKeyboard(); } @Override public void onSearchResultAddToList(@NonNull PageTitle title, @NonNull AddToReadingListDialog.InvokeSource source) { showAddToListDialog(title, source); } @Override public void onSearchResultShareLink(@NonNull PageTitle title) { ShareUtil.shareText(this, title); } @Override public void onLinkPreviewLoadPage(@NonNull PageTitle title, @NonNull HistoryEntry entry, boolean inNewTab) { loadPage(title, entry, inNewTab ? TabPosition.NEW_TAB_BACKGROUND : TabPosition.CURRENT_TAB); } @Override public void onLinkPreviewCopyLink(@NonNull PageTitle title) { copyLink(title.getCanonicalUri()); showCopySuccessMessage(); } @Override public void onLinkPreviewAddToList(@NonNull PageTitle title) { showAddToListDialog(title, AddToReadingListDialog.InvokeSource.LINK_PREVIEW_MENU); } @Override public void onLinkPreviewShareLink(@NonNull PageTitle title) { ShareUtil.shareText(this, title); } @Override public void onSearchResultCopyLink(@NonNull PageTitle title) { copyLink(title.getCanonicalUri()); showCopySuccessMessage(); } @Override public void wiktionaryShowDialogForTerm(@NonNull String term) { pageFragment.getShareHandler().showWiktionaryDefinition(term); } @Override public boolean shouldLoadFromBackStack() { return getIntent() != null && (ACTION_SHOW_TAB_LIST.equals(getIntent().getAction()) || ACTION_RESUME_READING.equals(getIntent().getAction())); } @Override public boolean shouldShowTabList() { return getIntent() != null && ACTION_SHOW_TAB_LIST.equals(getIntent().getAction()); } private void copyLink(@NonNull String url) { ClipboardUtil.setPlainText(this, null, url); } private void showCopySuccessMessage() { FeedbackUtil.showMessage(this, R.string.address_copied); } @Nullable @Override public AppCompatActivity getActivity() { return this; } private boolean shouldRecreateMainActivity() { return getIntent().getAction() == null || getIntent().getAction().equals(Intent.ACTION_VIEW); } @Override protected void onResume() { super.onResume(); app.resetWikiSite(); app.getSessionFunnel().touchSession(); } @Override public void onPause() { if (isCabOpen()) { // Explicitly close any current ActionMode (see T147191) finishActionMode(); } super.onPause(); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); saveState(outState); } private void saveState(Bundle outState) { outState.putBoolean("isSearching", isSearching()); outState.putString(LANGUAGE_CODE_BUNDLE_KEY, app.getAppOrSystemLanguageCode()); } @Override public void onActivityResult(int requestCode, int resultCode, final Intent data) { if (settingsActivityRequested(requestCode)) { handleSettingsActivityResult(resultCode); } else if (newArticleLanguageSelected(requestCode, resultCode) || galleryPageSelected(requestCode, resultCode)) { handleLangLinkOrPageResult(data); } else { super.onActivityResult(requestCode, resultCode, data); } } private void handleLangLinkOrPageResult(final Intent data) { tabsContainerView.post(new Runnable() { @Override public void run() { handleIntent(data); } }); } @Override protected void onStop() { app.getSessionFunnel().persistSession(); super.onStop(); } @Override public void onDestroy() { unbinder.unbind(); unregisterBus(); super.onDestroy(); } /** * ActionMode that is invoked when the user long-presses inside the WebView. * @param mode ActionMode under which this context is starting. */ @Override public void onSupportActionModeStarted(@NonNull ActionMode mode) { if (!isCabOpen()) { conditionallyInjectCustomCabMenu(mode); } super.onSupportActionModeStarted(mode); } @Override public void onSupportActionModeFinished(@NonNull ActionMode mode) { super.onSupportActionModeFinished(mode); nullifyActionMode(); } @Override public void onActionModeStarted(android.view.ActionMode mode) { if (!isCabOpen()) { conditionallyInjectCustomCabMenu(mode); } super.onActionModeStarted(mode); } @Override public void onActionModeFinished(android.view.ActionMode mode) { super.onActionModeFinished(mode); nullifyActionMode(); } private <T> void conditionallyInjectCustomCabMenu(T mode) { currentActionMode = new CompatActionMode(mode); if (currentActionMode.shouldInjectCustomMenu()) { currentActionMode.injectCustomMenu(pageFragment); } } private void registerBus() { bus = app.getBus(); bus.register(busMethods); L.d("Registered bus."); } private void unregisterBus() { bus.unregister(busMethods); bus = null; L.d("Unregistered bus."); } private void handleSettingsActivityResult(int resultCode) { if (languageChanged(resultCode)) { loadNewLanguageMainPage(); } } private boolean settingsActivityRequested(int requestCode) { return requestCode == SettingsActivity.ACTIVITY_REQUEST_SHOW_SETTINGS; } private boolean newArticleLanguageSelected(int requestCode, int resultCode) { return requestCode == Constants.ACTIVITY_REQUEST_LANGLINKS && resultCode == LangLinksActivity.ACTIVITY_RESULT_LANGLINK_SELECT; } private boolean galleryPageSelected(int requestCode, int resultCode) { return requestCode == Constants.ACTIVITY_REQUEST_GALLERY && resultCode == GalleryActivity.ACTIVITY_RESULT_PAGE_SELECTED; } private boolean languageChanged(int resultCode) { return resultCode == SettingsActivity.ACTIVITY_RESULT_LANGUAGE_CHANGED; } /** * Reload the main page in the new language, after delaying for one second in order to: * (1) Make sure that onStart in MainActivity gets called, thus registering the activity for the bus. * (2) Ensure a smooth transition, which is very jarring without a delay. */ private void loadNewLanguageMainPage() { Handler uiThread = new Handler(Looper.getMainLooper()); uiThread.postDelayed(new Runnable() { @Override public void run() { loadMainPageInForegroundTab(); updateFeaturedPageWidget(); } }, DateUtils.SECOND_IN_MILLIS); } /** * Update any instances of our Featured Page widget, since it will change with the currently selected language. */ private void updateFeaturedPageWidget() { Intent widgetIntent = new Intent(this, WidgetProviderFeaturedPage.class); widgetIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); int[] ids = AppWidgetManager.getInstance(getApplication()).getAppWidgetIds( new ComponentName(this, WidgetProviderFeaturedPage.class)); widgetIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids); sendBroadcast(widgetIntent); } private void showDescriptionEditRevertDialog(@NonNull String qNumber) { new AlertDialog.Builder(this) .setTitle(R.string.notification_reverted_title) .setView(new DescriptionEditRevertHelpView(this, qNumber)) .setPositiveButton(android.R.string.ok, null) .create() .show(); } @VisibleForTesting public void setPageLoadCallbacks(@Nullable PageLoadCallbacks pageLoadCallbacks) { this.pageLoadCallbacks = pageLoadCallbacks; } @SuppressLint("CommitTransaction") private void openSearchFragment(@NonNull SearchInvokeSource source, @Nullable String query) { Fragment fragment = searchFragment(); if (fragment == null) { fragment = SearchFragment.newInstance(source, StringUtils.trim(query), true); getSupportFragmentManager() .beginTransaction() .add(R.id.activity_page_container, fragment) .commitNowAllowingStateLoss(); } } @SuppressLint("CommitTransaction") private void closeSearchFragment(@NonNull SearchFragment fragment) { getSupportFragmentManager().beginTransaction().remove(fragment).commitNowAllowingStateLoss(); } @Nullable private SearchFragment searchFragment() { return (SearchFragment) getSupportFragmentManager() .findFragmentById(R.id.activity_page_container); } private class EventBusMethods { @Subscribe public void onChangeTextSize(ChangeTextSizeEvent event) { if (pageFragment != null && pageFragment.getWebView() != null) { pageFragment.updateFontSize(); } } } }
package org.wikipedia.page; import android.app.SearchManager; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.text.TextUtils; import android.view.ActionMode; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.widget.Toolbar; import androidx.preference.PreferenceManager; import com.google.android.material.bottomsheet.BottomSheetDialog; import com.google.android.material.bottomsheet.BottomSheetDialogFragment; import org.apache.commons.lang3.StringUtils; import org.wikipedia.Constants; import org.wikipedia.Constants.InvokeSource; import org.wikipedia.R; import org.wikipedia.WikipediaApp; import org.wikipedia.activity.BaseActivity; import org.wikipedia.analytics.IntentFunnel; import org.wikipedia.analytics.LinkPreviewFunnel; import org.wikipedia.dataclient.WikiSite; import org.wikipedia.descriptions.DescriptionEditRevertHelpView; import org.wikipedia.events.ArticleSavedOrDeletedEvent; import org.wikipedia.events.ChangeTextSizeEvent; import org.wikipedia.gallery.GalleryActivity; import org.wikipedia.history.HistoryEntry; import org.wikipedia.language.LangLinksActivity; import org.wikipedia.main.MainActivity; import org.wikipedia.navtab.NavTab; import org.wikipedia.page.linkpreview.LinkPreviewDialog; import org.wikipedia.page.tabs.TabActivity; import org.wikipedia.readinglist.database.ReadingListPage; import org.wikipedia.search.SearchActivity; import org.wikipedia.settings.Prefs; import org.wikipedia.theme.ThemeChooserDialog; import org.wikipedia.util.ClipboardUtil; import org.wikipedia.util.DeviceUtil; import org.wikipedia.util.DimenUtil; import org.wikipedia.util.FeedbackUtil; import org.wikipedia.util.ReleaseUtil; import org.wikipedia.util.ShareUtil; import org.wikipedia.util.ThrowableUtil; import org.wikipedia.views.ObservableWebView; import org.wikipedia.views.PageActionOverflowView; import org.wikipedia.views.TabCountsView; import org.wikipedia.views.ViewUtil; import org.wikipedia.wiktionary.WiktionaryDialog; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.Unbinder; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.functions.Consumer; import static org.wikipedia.Constants.INTENT_EXTRA_ACTION; import static org.wikipedia.Constants.InvokeSource.LINK_PREVIEW_MENU; import static org.wikipedia.Constants.InvokeSource.TOOLBAR; import static org.wikipedia.descriptions.DescriptionEditActivity.Action.ADD_CAPTION; import static org.wikipedia.settings.Prefs.isLinkPreviewEnabled; import static org.wikipedia.util.UriUtil.visitInExternalBrowser; public class PageActivity extends BaseActivity implements PageFragment.Callback, LinkPreviewDialog.Callback, ThemeChooserDialog.Callback, WiktionaryDialog.Callback{ public static final String ACTION_LOAD_IN_NEW_TAB = "org.wikipedia.load_in_new_tab"; public static final String ACTION_LOAD_IN_CURRENT_TAB = "org.wikipedia.load_in_current_tab"; public static final String ACTION_LOAD_IN_CURRENT_TAB_SQUASH = "org.wikipedia.load_in_current_tab_squash"; public static final String ACTION_LOAD_FROM_EXISTING_TAB = "org.wikipedia.load_from_existing_tab"; public static final String ACTION_CREATE_NEW_TAB = "org.wikipedia.create_new_tab"; public static final String ACTION_RESUME_READING = "org.wikipedia.resume_reading"; public static final String EXTRA_PAGETITLE = "org.wikipedia.pagetitle"; public static final String EXTRA_HISTORYENTRY = "org.wikipedia.history.historyentry"; private static final String LANGUAGE_CODE_BUNDLE_KEY = "language"; public enum TabPosition { CURRENT_TAB, CURRENT_TAB_SQUASH, NEW_TAB_BACKGROUND, NEW_TAB_FOREGROUND, EXISTING_TAB } @BindView(R.id.page_progress_bar) ProgressBar progressBar; @BindView(R.id.page_toolbar_container) View toolbarContainerView; @BindView(R.id.page_toolbar) Toolbar toolbar; @BindView(R.id.page_toolbar_button_search) ImageView searchButton; @BindView(R.id.page_toolbar_button_tabs) TabCountsView tabsButton; @BindView(R.id.page_toolbar_button_show_overflow_menu) ImageView overflowButton; @Nullable private Unbinder unbinder; private PageFragment pageFragment; private WikipediaApp app; private Set<ActionMode> currentActionModes = new HashSet<>(); private CompositeDisposable disposables = new CompositeDisposable(); private PageToolbarHideHandler toolbarHideHandler; private OverflowCallback overflowCallback = new OverflowCallback(); private ExclusiveBottomSheetPresenter bottomSheetPresenter = new ExclusiveBottomSheetPresenter(); private DialogInterface.OnDismissListener listDialogDismissListener = new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialogInterface) { pageFragment.updateBookmarkAndMenuOptionsFromDao(); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); app = (WikipediaApp) getApplicationContext(); PreferenceManager.setDefaultValues(this, R.xml.preferences, false); try { setContentView(R.layout.activity_page); } catch (Exception e) { if ((!TextUtils.isEmpty(e.getMessage()) && e.getMessage().toLowerCase().contains("webview")) || (!TextUtils.isEmpty(ThrowableUtil.getInnermostThrowable(e).getMessage()) && ThrowableUtil.getInnermostThrowable(e).getMessage().toLowerCase().contains("webview"))) { // If the system failed to inflate our activity because of the WebView (which could // be one of several types of exceptions), it likely means that the system WebView // is in the process of being updated. In this case, show the user a message and // bail immediately. Toast.makeText(app, R.string.error_webview_updating, Toast.LENGTH_LONG).show(); finish(); return; } throw e; } unbinder = ButterKnife.bind(this); disposables.add(app.getBus().subscribe(new EventBusConsumer())); updateProgressBar(false, true, 0); pageFragment = (PageFragment) getSupportFragmentManager().findFragmentById(R.id.page_fragment); setSupportActionBar(toolbar); clearActionBarTitle(); getSupportActionBar().setDisplayHomeAsUpEnabled(true); FeedbackUtil.setToolbarButtonLongPressToast(searchButton, tabsButton, overflowButton); toolbarHideHandler = new PageToolbarHideHandler(pageFragment, toolbarContainerView, toolbar, tabsButton); boolean languageChanged = false; if (savedInstanceState != null) { if (savedInstanceState.getBoolean("isSearching")) { openSearchActivity(); } String language = savedInstanceState.getString(LANGUAGE_CODE_BUNDLE_KEY); languageChanged = !app.getAppOrSystemLanguageCode().equals(language); } if (languageChanged) { app.resetWikiSite(); loadEmptyPage(TabPosition.EXISTING_TAB); } if (savedInstanceState == null) { // if there's no savedInstanceState, and we're not coming back from a Theme change, // then we must have been launched with an Intent, so... handle it! handleIntent(getIntent()); } } @OnClick(R.id.page_toolbar_button_search) public void onSearchButtonClicked() { openSearchActivity(); } @OnClick(R.id.page_toolbar_button_tabs) public void onShowTabsButtonClicked() { TabActivity.captureFirstTabBitmap(pageFragment.getContainerView()); startActivityForResult(TabActivity.newIntentFromPageActivity(this), Constants.ACTIVITY_REQUEST_BROWSE_TABS); } @OnClick(R.id.page_toolbar_button_show_overflow_menu) public void onShowOverflowMenuButtonClicked() { showOverflowMenu(toolbar.findViewById(R.id.page_toolbar_button_show_overflow_menu)); } public void animateTabsButton() { Animation anim = AnimationUtils.loadAnimation(this, R.anim.tab_list_zoom_enter); tabsButton.startAnimation(anim); tabsButton.updateTabCount(); } public void hideSoftKeyboard() { DeviceUtil.hideSoftKeyboard(this); } @Override public boolean onPrepareOptionsMenu(Menu menu) { if (!isDestroyed()) { tabsButton.updateTabCount(); } return false; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: if (app.haveMainActivity()) { onBackPressed(); } else { goToMainTab(NavTab.EXPLORE); } return true; default: return super.onOptionsItemSelected(item); } } private void goToMainTab(@NonNull NavTab tab) { startActivity(MainActivity.newIntent(this) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) .putExtra(Constants.INTENT_RETURN_TO_MAIN, true) .putExtra(Constants.INTENT_EXTRA_GO_TO_MAIN_TAB, tab.code())); finish(); } /** @return True if the contextual action bar is open. */ private boolean isCabOpen() { return !currentActionModes.isEmpty(); } @NonNull public static Intent newIntent(@NonNull Context context) { return new Intent(ACTION_RESUME_READING).setClass(context, PageActivity.class); } @NonNull public static Intent newIntentForNewTab(@NonNull Context context) { return new Intent(ACTION_CREATE_NEW_TAB) .setClass(context, PageActivity.class); } @NonNull public static Intent newIntentForNewTab(@NonNull Context context, @NonNull HistoryEntry entry, @NonNull PageTitle title) { return new Intent(ACTION_LOAD_IN_NEW_TAB) .setClass(context, PageActivity.class) .putExtra(EXTRA_HISTORYENTRY, entry) .putExtra(EXTRA_PAGETITLE, title); } public static Intent newIntentForCurrentTab(@NonNull Context context, @NonNull HistoryEntry entry, @NonNull PageTitle title) { return newIntentForCurrentTab(context, entry, title, true); } public static Intent newIntentForCurrentTab(@NonNull Context context, @NonNull HistoryEntry entry, @NonNull PageTitle title, boolean squashBackstack) { return new Intent(squashBackstack ? ACTION_LOAD_IN_CURRENT_TAB_SQUASH : ACTION_LOAD_IN_CURRENT_TAB) .setClass(context, PageActivity.class) .putExtra(EXTRA_HISTORYENTRY, entry) .putExtra(EXTRA_PAGETITLE, title); } public static Intent newIntentForExistingTab(@NonNull Context context, @NonNull HistoryEntry entry, @NonNull PageTitle title) { return new Intent(ACTION_LOAD_FROM_EXISTING_TAB) .setClass(context, PageActivity.class) .putExtra(EXTRA_HISTORYENTRY, entry) .putExtra(EXTRA_PAGETITLE, title); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); setIntent(intent); handleIntent(intent); } private void handleIntent(@NonNull Intent intent) { if (Intent.ACTION_VIEW.equals(intent.getAction()) && intent.getData() != null) { Uri uri = intent.getData(); if (ReleaseUtil.isProdRelease() && uri.getScheme() != null && uri.getScheme().equals("http")) { // For external links, ensure that they're using https. uri = uri.buildUpon().scheme(WikiSite.DEFAULT_SCHEME).build(); } WikiSite wiki = new WikiSite(uri); PageTitle title = wiki.titleForUri(intent.getData()); HistoryEntry historyEntry = new HistoryEntry(title, intent.hasExtra(Constants.INTENT_EXTRA_VIEW_FROM_NOTIFICATION) ? HistoryEntry.SOURCE_NOTIFICATION_SYSTEM : HistoryEntry.SOURCE_EXTERNAL_LINK); if (intent.hasExtra(Intent.EXTRA_REFERRER)) { // Populate the referrer with the externally-referring URL, e.g. an external Browser URL. // This can be a Uri or a String, so let's extract it safely as an Object. historyEntry.setReferrer(intent.getExtras().get(Intent.EXTRA_REFERRER).toString()); } if (title.isSpecial()) { visitInExternalBrowser(this, intent.getData()); finish(); return; } loadPage(title, historyEntry, TabPosition.NEW_TAB_FOREGROUND); } else if ((ACTION_LOAD_IN_NEW_TAB.equals(intent.getAction()) || ACTION_LOAD_IN_CURRENT_TAB.equals(intent.getAction()) || ACTION_LOAD_IN_CURRENT_TAB_SQUASH.equals(intent.getAction())) && intent.hasExtra(EXTRA_HISTORYENTRY)) { PageTitle title = intent.getParcelableExtra(EXTRA_PAGETITLE); HistoryEntry historyEntry = intent.getParcelableExtra(EXTRA_HISTORYENTRY); if (ACTION_LOAD_IN_NEW_TAB.equals(intent.getAction())) { loadPage(title, historyEntry, TabPosition.NEW_TAB_FOREGROUND); } else if (ACTION_LOAD_IN_CURRENT_TAB.equals(intent.getAction())) { loadPage(title, historyEntry, TabPosition.CURRENT_TAB); } else if (ACTION_LOAD_IN_CURRENT_TAB_SQUASH.equals(intent.getAction())) { loadPage(title, historyEntry, TabPosition.CURRENT_TAB_SQUASH); } if (intent.hasExtra(Constants.INTENT_EXTRA_REVERT_QNUMBER)) { showDescriptionEditRevertDialog(intent.getStringExtra(Constants.INTENT_EXTRA_REVERT_QNUMBER)); } } else if (ACTION_LOAD_FROM_EXISTING_TAB.equals(intent.getAction()) && intent.hasExtra(EXTRA_HISTORYENTRY)) { PageTitle title = intent.getParcelableExtra(EXTRA_PAGETITLE); HistoryEntry historyEntry = intent.getParcelableExtra(EXTRA_HISTORYENTRY); loadPage(title, historyEntry, TabPosition.EXISTING_TAB); } else if (ACTION_RESUME_READING.equals(intent.getAction()) || intent.hasExtra(Constants.INTENT_APP_SHORTCUT_CONTINUE_READING)) { // do nothing, since this will be handled indirectly by PageFragment. } else if (Intent.ACTION_SEARCH.equals(intent.getAction())) { String query = intent.getStringExtra(SearchManager.QUERY); PageTitle title = new PageTitle(query, app.getWikiSite()); HistoryEntry historyEntry = new HistoryEntry(title, HistoryEntry.SOURCE_SEARCH); loadPage(title, historyEntry, TabPosition.EXISTING_TAB); } else if (intent.hasExtra(Constants.INTENT_FEATURED_ARTICLE_FROM_WIDGET)) { new IntentFunnel(app).logFeaturedArticleWidgetTap(); PageTitle title = intent.getParcelableExtra(EXTRA_PAGETITLE); HistoryEntry historyEntry = new HistoryEntry(title, HistoryEntry.SOURCE_WIDGET); loadPage(title, historyEntry, TabPosition.EXISTING_TAB); } else if (ACTION_CREATE_NEW_TAB.equals(intent.getAction())) { loadEmptyPage(TabPosition.NEW_TAB_FOREGROUND); } else { loadEmptyPage(TabPosition.CURRENT_TAB); } } /** * Update the state of the main progress bar that is shown inside the ActionBar of the activity. * @param visible Whether the progress bar is visible. * @param indeterminate Whether the progress bar is indeterminate. * @param value Value of the progress bar (may be between 0 and 10000). Ignored if the * progress bar is indeterminate. */ public void updateProgressBar(boolean visible, boolean indeterminate, int value) { progressBar.setIndeterminate(indeterminate); if (!indeterminate) { progressBar.setProgress(value); } progressBar.setVisibility(visible ? View.VISIBLE : View.GONE); } /** * Load a new page, and put it on top of the backstack, optionally allowing state loss of the * fragment manager. Useful for when this function is called from an AsyncTask result. * @param title Title of the page to load. * @param entry HistoryEntry associated with this page. * @param position Whether to open this page in the current tab, a new background tab, or new * foreground tab. */ public void loadPage(@NonNull final PageTitle title, @NonNull final HistoryEntry entry, @NonNull final TabPosition position) { if (isDestroyed()) { return; } if (entry.getSource() != HistoryEntry.SOURCE_INTERNAL_LINK || !isLinkPreviewEnabled()) { new LinkPreviewFunnel(app, entry.getSource()).logNavigate(); } app.putCrashReportProperty("api", title.getWikiSite().authority()); app.putCrashReportProperty("title", title.toString()); if (title.isSpecial()) { visitInExternalBrowser(this, Uri.parse(title.getUri())); return; } toolbarContainerView.post(() -> { if (!pageFragment.isAdded()) { return; } // Close the link preview, if one is open. hideLinkPreview(); onPageCloseActionMode(); if (position == TabPosition.CURRENT_TAB) { pageFragment.loadPage(title, entry, true, false); } else if (position == TabPosition.CURRENT_TAB_SQUASH) { pageFragment.loadPage(title, entry, true, true); } else if (position == TabPosition.NEW_TAB_BACKGROUND) { pageFragment.openInNewBackgroundTab(title, entry); } else if (position == TabPosition.NEW_TAB_FOREGROUND) { pageFragment.openInNewForegroundTab(title, entry); } else { pageFragment.openFromExistingTab(title, entry); } app.getSessionFunnel().pageViewed(entry); }); } public void loadEmptyPage(TabPosition position) { PageTitle title = new PageTitle(Constants.EMPTY_PAGE_TITLE, app.getWikiSite()); HistoryEntry historyEntry = new HistoryEntry(title, HistoryEntry.SOURCE_INTERNAL_LINK); loadPage(title, historyEntry, position); } private void hideLinkPreview() { bottomSheetPresenter.dismiss(getSupportFragmentManager()); } public void showAddToListDialog(@NonNull PageTitle title, @NonNull InvokeSource source) { bottomSheetPresenter.showAddToListDialog(getSupportFragmentManager(), title, source, listDialogDismissListener); } // Note: back button first handled in {@link #onOptionsItemSelected()}; @Override public void onBackPressed() { if (isCabOpen()) { onPageCloseActionMode(); return; } app.getSessionFunnel().backPressed(); if (pageFragment.onBackPressed()) { return; } super.onBackPressed(); } @Override public void onPageShowBottomSheet(@NonNull BottomSheetDialog dialog) { bottomSheetPresenter.show(getSupportFragmentManager(), dialog); } @Override public void onPageShowBottomSheet(@NonNull BottomSheetDialogFragment dialog) { bottomSheetPresenter.show(getSupportFragmentManager(), dialog); } @Override public void onPageDismissBottomSheet() { bottomSheetPresenter.dismiss(getSupportFragmentManager()); } @Override public void onPageInitWebView(@NonNull ObservableWebView webView) { toolbarHideHandler.setScrollView(webView); } @Override public void onPageLoadPage(@NonNull PageTitle title, @NonNull HistoryEntry entry) { loadPage(title, entry, TabPosition.CURRENT_TAB); } @Override public void onPageShowLinkPreview(@NonNull HistoryEntry entry) { bottomSheetPresenter.show(getSupportFragmentManager(), LinkPreviewDialog.newInstance(entry, null)); } @Override public void onPageLoadEmptyPageInForegroundTab() { loadEmptyPage(TabPosition.EXISTING_TAB); } @Override public void onPageUpdateProgressBar(boolean visible, boolean indeterminate, int value) { updateProgressBar(visible, indeterminate, value); } @Override public void onPageShowThemeChooser() { bottomSheetPresenter.show(getSupportFragmentManager(), new ThemeChooserDialog()); } @Override public void onPageStartSupportActionMode(@NonNull ActionMode.Callback callback) { startActionMode(callback); } @Override public void onPageHideSoftKeyboard() { hideSoftKeyboard(); } @Override public void onPageAddToReadingList(@NonNull PageTitle title, @NonNull InvokeSource source) { showAddToListDialog(title, source); } @Override public void onPageRemoveFromReadingLists(@NonNull PageTitle title) { if (!pageFragment.isAdded()) { return; } FeedbackUtil.showMessage(this, getString(R.string.reading_list_item_deleted, title.getDisplayText())); pageFragment.updateBookmarkAndMenuOptionsFromDao(); } @Override public void onPageLoadError(@NonNull PageTitle title) { getSupportActionBar().setTitle(title.getDisplayText()); } @Override public void onPageLoadErrorBackPressed() { finish(); } @Override public void onPageHideAllContent() { toolbarHideHandler.setFadeEnabled(false); } @Override public void onPageSetToolbarFadeEnabled(boolean enabled) { toolbarHideHandler.setFadeEnabled(enabled); } @Override public void onPageSetToolbarElevationEnabled(boolean enabled) { toolbarContainerView.setElevation(DimenUtil.dpToPx(enabled ? DimenUtil.getDimension(R.dimen.toolbar_default_elevation) : 0)); } @Override public void onPageCloseActionMode() { Set<ActionMode> actionModesToFinish = new HashSet<>(currentActionModes); for (ActionMode mode : actionModesToFinish) { mode.finish(); } currentActionModes.clear(); } @Override public void onLinkPreviewLoadPage(@NonNull PageTitle title, @NonNull HistoryEntry entry, boolean inNewTab) { loadPage(title, entry, inNewTab ? TabPosition.NEW_TAB_BACKGROUND : TabPosition.CURRENT_TAB); } @Override public void onLinkPreviewCopyLink(@NonNull PageTitle title) { copyLink(title.getUri()); showCopySuccessMessage(); } @Override public void onLinkPreviewAddToList(@NonNull PageTitle title) { showAddToListDialog(title, LINK_PREVIEW_MENU); } @Override public void onLinkPreviewShareLink(@NonNull PageTitle title) { ShareUtil.shareText(this, title); } @Override public void wiktionaryShowDialogForTerm(@NonNull String term) { pageFragment.getShareHandler().showWiktionaryDefinition(term); } @Override public void onToggleDimImages() { recreate(); } @Override public void onCancel() { } private void copyLink(@NonNull String url) { ClipboardUtil.setPlainText(this, null, url); } private void showCopySuccessMessage() { FeedbackUtil.showMessage(this, R.string.address_copied); } private void showOverflowMenu(@NonNull View anchor) { PageActionOverflowView overflowView = new PageActionOverflowView(this); overflowView.show(anchor, overflowCallback, pageFragment.getCurrentTab()); } private class OverflowCallback implements PageActionOverflowView.Callback { @Override public void forwardClick() { pageFragment.goForward(); } @Override public void feedClick() { goToMainTab(NavTab.EXPLORE); } @Override public void readingListsClick() { if (Prefs.getOverflowReadingListsOptionClickCount() < 2) { Prefs.setOverflowReadingListsOptionClickCount(Prefs.getOverflowReadingListsOptionClickCount() + 1); } goToMainTab(NavTab.READING_LISTS); } @Override public void historyClick() { goToMainTab(NavTab.HISTORY); } } @Override protected void onResume() { super.onResume(); app.resetWikiSite(); } @Override public void onPause() { if (isCabOpen()) { // Explicitly close any current ActionMode (see T147191) onPageCloseActionMode(); } super.onPause(); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(LANGUAGE_CODE_BUNDLE_KEY, app.getAppOrSystemLanguageCode()); } @Override public void onActivityResult(int requestCode, int resultCode, final Intent data) { if (newArticleLanguageSelected(requestCode, resultCode) || galleryPageSelected(requestCode, resultCode)) { toolbarContainerView.post(() -> handleIntent(data)); } else if (galleryImageCaptionAdded(requestCode, resultCode)) { pageFragment.refreshPage(); } else if (requestCode == Constants.ACTIVITY_REQUEST_BROWSE_TABS) { if (app.getTabCount() == 0 && resultCode != TabActivity.RESULT_NEW_TAB) { // They browsed the tabs and cleared all of them, without wanting to open a new tab. finish(); return; } if (resultCode == TabActivity.RESULT_NEW_TAB) { loadEmptyPage(TabPosition.NEW_TAB_FOREGROUND); animateTabsButton(); } else if (resultCode == TabActivity.RESULT_LOAD_FROM_BACKSTACK) { pageFragment.reloadFromBackstack(); } } else if (requestCode == Constants.ACTIVITY_REQUEST_IMAGE_CAPTION_EDIT && resultCode == RESULT_OK) { pageFragment.refreshPage(); String editLanguage = StringUtils.defaultString(pageFragment.getLeadImageEditLang(), app.language().getAppLanguageCode()); FeedbackUtil.makeSnackbar(this, data.getSerializableExtra(INTENT_EXTRA_ACTION) == ADD_CAPTION ? getString(R.string.description_edit_success_saved_image_caption_snackbar) : getString(R.string.description_edit_success_saved_image_caption_in_lang_snackbar, app.language().getAppLanguageLocalizedName(editLanguage)), FeedbackUtil.LENGTH_DEFAULT) .setAction(R.string.suggested_edits_article_cta_snackbar_action, v -> pageFragment.openImageInGallery(editLanguage)).show(); } else { super.onActivityResult(requestCode, resultCode, data); } } @Override public void onDestroy() { if (unbinder != null) { unbinder.unbind(); } disposables.clear(); Prefs.setHasVisitedArticlePage(true); super.onDestroy(); } @Override public void onActionModeStarted(ActionMode mode) { super.onActionModeStarted(mode); if (!isCabOpen() && mode.getTag() == null) { modifyMenu(mode); ViewUtil.setCloseButtonInActionMode(pageFragment.requireContext(), mode); pageFragment.onActionModeShown(mode); } currentActionModes.add(mode); } private void modifyMenu(ActionMode mode) { Menu menu = mode.getMenu(); ArrayList<MenuItem> menuItemsList = new ArrayList<>(); for (int i = 0; i < menu.size(); i++) { String title = menu.getItem(i).getTitle().toString(); if (!title.contains(getString(R.string.search_hint)) && !title.contains(getString(R.string.menu_text_select_define))) { menuItemsList.add(menu.getItem(i)); } } menu.clear(); mode.getMenuInflater().inflate(R.menu.menu_text_select, menu); for (MenuItem menuItem : menuItemsList) { menu.add(menuItem.getGroupId(), menuItem.getItemId(), Menu.NONE, menuItem.getTitle()).setIntent(menuItem.getIntent()).setIcon(menuItem.getIcon()); } } @Override public void onActionModeFinished(ActionMode mode) { super.onActionModeFinished(mode); currentActionModes.remove(mode); toolbarHideHandler.onScrolled(pageFragment.getWebView().getScrollY(), pageFragment.getWebView().getScrollY()); } protected void clearActionBarTitle() { getSupportActionBar().setTitle(""); } private boolean newArticleLanguageSelected(int requestCode, int resultCode) { return requestCode == Constants.ACTIVITY_REQUEST_LANGLINKS && resultCode == LangLinksActivity.ACTIVITY_RESULT_LANGLINK_SELECT; } private boolean galleryPageSelected(int requestCode, int resultCode) { return requestCode == Constants.ACTIVITY_REQUEST_GALLERY && resultCode == GalleryActivity.ACTIVITY_RESULT_PAGE_SELECTED; } private boolean galleryImageCaptionAdded(int requestCode, int resultCode) { return requestCode == Constants.ACTIVITY_REQUEST_GALLERY && resultCode == GalleryActivity.ACTIVITY_RESULT_IMAGE_CAPTION_ADDED; } private void showDescriptionEditRevertDialog(@NonNull String qNumber) { new AlertDialog.Builder(this) .setTitle(R.string.notification_reverted_title) .setView(new DescriptionEditRevertHelpView(this, qNumber)) .setPositiveButton(R.string.reverted_edit_dialog_ok_button_text, null) .create() .show(); } private void openSearchActivity() { Intent intent = SearchActivity.newIntent(this, TOOLBAR, null); startActivity(intent); } private class EventBusConsumer implements Consumer<Object> { @Override public void accept(Object event) { if (event instanceof ChangeTextSizeEvent) { if (pageFragment != null && pageFragment.getWebView() != null) { pageFragment.updateFontSize(); } } else if (event instanceof ArticleSavedOrDeletedEvent) { if (((ArticleSavedOrDeletedEvent) event).isAdded()) { Prefs.shouldShowBookmarkToolTip(false); } if (pageFragment == null || !pageFragment.isAdded() || pageFragment.getTitleOriginal() == null) { return; } for (ReadingListPage page : ((ArticleSavedOrDeletedEvent) event).getPages()) { if (page.title().equals(pageFragment.getTitleOriginal().getDisplayText())) { pageFragment.updateBookmarkAndMenuOptionsFromDao(); } } } } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if ((event.isCtrlPressed() && keyCode == KeyEvent.KEYCODE_F) || (!event.isCtrlPressed() && keyCode == KeyEvent.KEYCODE_F3)) { pageFragment.showFindInPage(); return true; } return super.onKeyDown(keyCode, event); } }
package smida.haroun.listview; public class DataModel { String name; String type; String version_number; String test; String feature; public DataModel() { } public DataModel(String name, String type, String version_number, String feature ) { this.name=name; this.type=type; this.version_number=version_number; this.feature=feature; } public String getName() { return name; } public String getType() { return type; } public String getVersion_number() { return version_number; } public String getFeature() { return feature; } public void setName(String name) { this.name = name; } public void setType(String type) { this.type = type; } public void setVersion_number(String version_number) { this.version_number = version_number; } public void setFeature(String feature) { this.feature = feature; } }
package org.commcare.network; import android.content.SharedPreferences; import android.net.Uri; import android.net.http.AndroidHttpClient; import android.util.Log; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.Credentials; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.params.HttpClientParams; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.ExecutionContext; import org.apache.http.protocol.HttpContext; import org.commcare.CommCareApp; import org.commcare.CommCareApplication; import org.commcare.android.database.user.models.ACase; import org.commcare.cases.util.CaseDBUtils; import org.commcare.core.network.ModernHttpRequester; import org.commcare.interfaces.HttpRequestEndpoints; import org.commcare.logging.AndroidLogger; import org.commcare.models.database.SqlStorage; import org.commcare.provider.DebugControlsReceiver; import org.javarosa.core.model.User; import org.javarosa.core.model.utils.DateUtils; import org.javarosa.core.services.Logger; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Date; import java.util.Vector; /** * @author ctsims */ public class HttpRequestGenerator implements HttpRequestEndpoints { private static final String TAG = HttpRequestGenerator.class.getSimpleName(); /** * A possible domain that further qualifies the username of any account in use */ public static final String USER_DOMAIN_SUFFIX = "cc_user_domain"; public static final String LOG_COMMCARE_NETWORK = "commcare-network"; /** * The type of authentication that we're capable of providing to the server (digest if this isn't present) */ public static final String AUTH_REQUEST_TYPE = "authtype"; /** * No Authentication will be possible, there isn't a user account to authenticate this request */ public static final String AUTH_REQUEST_TYPE_NO_AUTH = "noauth"; private static final String SUBMIT_MODE = "submit_mode"; private static final String SUBMIT_MODE_DEMO = "demo"; private final Credentials credentials; private final String username; private final String password; private final String userType; /** * Keep track of current request to allow for early aborting */ private HttpRequestBase currentRequest; public HttpRequestGenerator(User user) { this(user.getUsername(), user.getCachedPwd(), user.getUserType()); } public HttpRequestGenerator(String username, String password) { this(username, password, null); } private HttpRequestGenerator(String username, String password, String userType) { String domainedUsername = buildDomainUser(username); this.password = password; this.userType = userType; if (username != null && !User.TYPE_DEMO.equals(userType)) { this.credentials = new UsernamePasswordCredentials(domainedUsername, password); this.username = username; } else { this.credentials = null; this.username = null; } } protected static String buildDomainUser(String username) { if (username != null) { SharedPreferences prefs = CommCareApplication._().getCurrentApp().getAppPreferences(); if (prefs.contains(USER_DOMAIN_SUFFIX)) { username += "@" + prefs.getString(USER_DOMAIN_SUFFIX, null); } } return username; } public static HttpRequestGenerator buildNoAuthGenerator() { return new HttpRequestGenerator(null, null, null); } public HttpResponse get(String uri) throws ClientProtocolException, IOException { HttpClient client = client(); Log.d(TAG, "Fetching from: " + uri); HttpGet request = new HttpGet(uri); addHeaders(request, ""); HttpResponse response = execute(client, request); //May need to manually process a valid redirect if (response.getStatusLine().getStatusCode() == 301) { String newGetUri = request.getURI().toString(); Log.d(LOG_COMMCARE_NETWORK, "Following valid redirect from " + uri + " to " + newGetUri); request.abort(); //Make a new response to the redirect request = new HttpGet(newGetUri); addHeaders(request, ""); response = execute(client, request); } return response; } @Override public HttpResponse makeCaseFetchRequest(String baseUri, boolean includeStateFlags) throws ClientProtocolException, IOException { HttpClient client = client(); Uri serverUri = Uri.parse(baseUri); String vparam = serverUri.getQueryParameter("version"); if (vparam == null) { serverUri = serverUri.buildUpon().appendQueryParameter("version", "2.0").build(); } String syncToken = null; if (includeStateFlags) { syncToken = getSyncToken(username); String digest = getDigest(); if (syncToken != null) { serverUri = serverUri.buildUpon().appendQueryParameter("since", syncToken).build(); } if (digest != null) { serverUri = serverUri.buildUpon().appendQueryParameter("state", "ccsh:" + digest).build(); } } //Add items count to fetch request serverUri = serverUri.buildUpon().appendQueryParameter("items", "true").build(); if (CommCareApplication._().shouldInvalidateCacheOnRestore()) { // Currently used for testing purposes only, in order to ensure that a full sync will // occur when we want to test one serverUri = serverUri.buildUpon().appendQueryParameter("overwrite_cache", "true").build(); // Always wipe this flag after we have used it once CommCareApplication._().setInvalidateCacheFlag(false); } String uri = serverUri.toString(); Log.d(TAG, "Fetching from: " + uri); currentRequest = new HttpGet(uri); AndroidHttpClient.modifyRequestToAcceptGzipResponse(currentRequest); addHeaders(currentRequest, syncToken); HttpResponse response = execute(client, currentRequest); currentRequest = null; return response; } @Override public HttpResponse makeKeyFetchRequest(String baseUri, Date lastRequest) throws ClientProtocolException, IOException { HttpClient client = client(); Uri url = Uri.parse(baseUri); if (lastRequest != null) { url = url.buildUpon().appendQueryParameter("last_issued", DateUtils.formatTime(lastRequest, DateUtils.FORMAT_ISO8601)).build(); } HttpGet get = new HttpGet(url.toString()); return execute(client, get); } private void addHeaders(HttpRequestBase base, String lastToken) { //base.addHeader("Accept-Language", lang) base.addHeader("X-OpenRosa-Version", "1.0"); if (lastToken != null) { base.addHeader("X-CommCareHQ-LastSyncToken", lastToken); } base.addHeader("x-openrosa-deviceid", CommCareApplication._().getPhoneId()); } private String getSyncToken(String username) { if (username == null) { return null; } SqlStorage<User> storage = CommCareApplication._().getUserStorage(User.STORAGE_KEY, User.class); Vector<Integer> users = storage.getIDsForValue(User.META_USERNAME, username); //should be exactly one user if (users.size() != 1) { return null; } return storage.getMetaDataFieldForRecord(users.firstElement(), User.META_SYNC_TOKEN); } private static String getDigest() { String fakeHash = DebugControlsReceiver.getFakeCaseDbHash(); if (fakeHash != null) { // For integration tests, use fake hash to trigger 412 recovery on this sync return fakeHash; } else { return CaseDBUtils.computeCaseDbHash(CommCareApplication._().getUserStorage(ACase.STORAGE_KEY, ACase.class)); } } @Override public HttpResponse postData(String url, MultipartEntity entity) throws ClientProtocolException, IOException { // setup client HttpClient httpclient = client(); //If we're going to try to post with no credentials, we need to be explicit about the fact that we're //not ready if (credentials == null) { url = Uri.parse(url).buildUpon().appendQueryParameter(AUTH_REQUEST_TYPE, AUTH_REQUEST_TYPE_NO_AUTH).build().toString(); } if (User.TYPE_DEMO.equals(userType)) { url = Uri.parse(url).buildUpon().appendQueryParameter(SUBMIT_MODE, SUBMIT_MODE_DEMO).build().toString(); } HttpPost httppost = new HttpPost(url); httppost.setEntity(entity); addHeaders(httppost, this.getSyncToken(username)); return execute(httpclient, httppost); } private HttpClient client() { HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, ModernHttpRequester.CONNECTION_TIMEOUT); HttpConnectionParams.setSoTimeout(params, ModernHttpRequester.CONNECTION_SO_TIMEOUT); HttpClientParams.setRedirecting(params, true); DefaultHttpClient client = new DefaultHttpClient(params); client.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials); System.setProperty("http.keepAlive", "false"); return client; } /** * Http requests are not so simple as "opening a request". Occasionally we may have to deal * with redirects. We don't want to just accept any redirect, though, since we may be directed * away from a secure connection. For now we'll only accept redirects from HTTP -> * servers, * or HTTPS -> HTTPS severs on the same domain */ private HttpResponse execute(HttpClient client, HttpUriRequest request) throws IOException { HttpContext context = new BasicHttpContext(); HttpResponse response = client.execute(request, context); HttpUriRequest currentReq = (HttpUriRequest)context.getAttribute(ExecutionContext.HTTP_REQUEST); HttpHost currentHost = (HttpHost)context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); String currentUrl = currentHost.toURI() + currentReq.getURI(); //Don't allow redirects _from_ https _to_ https unless they are redirecting to the same server. URL originalRequest = request.getURI().toURL(); URL finalRedirect = new URL(currentUrl); if (!isValidRedirect(originalRequest, finalRedirect)) { Logger.log(AndroidLogger.TYPE_WARNING_NETWORK, "Invalid redirect from " + originalRequest.toString() + " to " + finalRedirect.toString()); throw new IOException("Invalid redirect from secure server to insecure server"); } return response; } public static boolean isValidRedirect(URL url, URL newUrl) { //unless it's https, don't worry about it if (!url.getProtocol().equals("https")) { return true; } // If https, verify that we're on the same server. // Not being so means we got redirected from a secure link to a // different link, which isn't acceptable for now. return url.getHost().equals(newUrl.getHost()); } @Override public InputStream simpleGet(URL url) throws IOException { if (android.os.Build.VERSION.SDK_INT > 11) { InputStream requestResult = SimpleGetRequest.makeRequest(username, password, url); if (requestResult != null) { return requestResult; } } // On earlier versions of android use the apache libraries, they work much much better. Log.i(LOG_COMMCARE_NETWORK, "Falling back to Apache libs for network request"); HttpResponse get = get(url.toString()); if (get.getStatusLine().getStatusCode() == 404) { throw new FileNotFoundException("No Data available at URL " + url.toString()); } //TODO: Double check response code return get.getEntity().getContent(); } @Override public void abortCurrentRequest() { if (currentRequest != null) { try { currentRequest.abort(); } catch (Exception e) { Log.i(TAG, "Error thrown while aborting http: " + e.getMessage()); } } } }
package com.thoughtworks.xstream.core.util; import java.lang.reflect.Field; import com.thoughtworks.xstream.converters.reflection.ObjectAccessException; /** * Slightly nicer way to find, get and set fields in classes. Wraps standard java.lang.reflect.Field calls but wraps * wraps exception in XStreamExceptions. * * @author Joe Walnes */ public class Fields { public static Field find(Class type, String name) { try { Field result = type.getDeclaredField(name); result.setAccessible(true); return result; } catch (NoSuchFieldException e) { throw new IllegalArgumentException("Could not access " + type.getName() + "." + name + " field: " + e.getMessage()); } } public static void write(Field field, Object instance, Object value) { try { field.set(instance, value); } catch (IllegalAccessException e) { throw new ObjectAccessException("Could not write " + field.getType().getName() + "." + field.getName() + " field"); } } public static Object read(Field field, Object instance) { try { return field.get(instance); } catch (IllegalAccessException e) { throw new ObjectAccessException("Could not read " + field.getType().getName() + "." + field.getName() + " field"); } } }
package com.thoughtworks.acceptance; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.converters.basic.AbstractSingleValueConverter; import com.thoughtworks.xstream.testutil.TimeZoneChanger; /** * @author Paul Hammant * @author Ian Cartwright * @author Mauro Talevi * @author J&ouml;rg Schaible * @author Guilherme Silveira */ public class AttributeTest extends AbstractAcceptanceTest { protected void setUp() throws Exception { super.setUp(); TimeZoneChanger.change("GMT"); } protected void tearDown() throws Exception { TimeZoneChanger.reset(); super.tearDown(); } public static class One implements HasID { public ID id; public Two two; public void setID(ID id) { this.id = id; } } public static interface HasID { void setID(ID id); } public static class Two {} public static class Three { public Date date; } public static class ID { public ID(String value) { this.value = value; } public String value; } private static class MyIDConverter extends AbstractSingleValueConverter { public boolean canConvert(Class type) { return type.equals(ID.class); } public String toString(Object obj) { return obj == null ? null : ((ID) obj).value; } public Object fromString(String str) { return new ID(str); } } static class C { private Date dt; private String str; private int i; C() { // for JDK 1.3 } C(Date dt, String st, int i) { this.dt = dt; this.str = st; this.i = i; } } public void testAllowsAttributeWithCustomConverterAndFieldName() { One one = new One(); one.two = new Two(); one.id = new ID("hullo"); xstream.alias("one", One.class); xstream.useAttributeFor("id", ID.class); xstream.registerConverter(new MyIDConverter()); String expected = "<one id=\"hullo\">\n" + " <two/>\n" + "</one>"; assertBothWays(one, expected); } public void testDoesNotAllowAttributeWithCustomConverterAndDifferentFieldName() { One one = new One(); one.two = new Two(); one.id = new ID("hullo"); xstream.alias("one", One.class); xstream.useAttributeFor("foo", ID.class); xstream.registerConverter(new MyIDConverter()); String expected = "<one>\n" + " <id>hullo</id>\n" + " <two/>\n" + "</one>"; assertBothWays(one, expected); } public void testAllowsAttributeWithKnownConverterAndFieldName() throws Exception { Three three = new Three(); DateFormat format = new SimpleDateFormat("dd/MM/yyyy"); three.date = format.parse("19/02/2006"); xstream.alias("three", Three.class); xstream.useAttributeFor("date", Date.class); String expected = "<three date=\"2006-02-19 00:00:00.0 GMT\"/>"; assertBothWays(three, expected); } public void testAllowsAttributeWithArbitraryFieldType() { One one = new One(); one.two = new Two(); one.id = new ID("hullo"); xstream.alias("one", One.class); xstream.useAttributeFor(ID.class); xstream.registerConverter(new MyIDConverter()); String expected = "<one id=\"hullo\">\n" + " <two/>\n" + "</one>"; assertBothWays(one, expected); } public void testDoesNotAllowAttributeWithNullAttribute() { One one = new One(); one.two = new Two(); xstream.alias("one", One.class); xstream.useAttributeFor(ID.class); xstream.registerConverter(new MyIDConverter()); String expected = "<one>\n" + " <two/>\n" + "</one>"; assertBothWays(one, expected); } public void testAllowsAttributeToBeAliased() { One one = new One(); one.two = new Two(); one.id = new ID("hullo"); xstream.alias("one", One.class); xstream.aliasAttribute("id-alias", "id"); xstream.useAttributeFor("id", ID.class); xstream.registerConverter(new MyIDConverter()); String expected = "<one id-alias=\"hullo\">\n" + " <two/>\n" + "</one>"; assertBothWays(one, expected); } public void testCanHandleNullValues() { C c = new C(null, null, 0); xstream.alias("C", C.class); xstream.useAttributeFor(Date.class); xstream.useAttributeFor(String.class); String expected = "<C>\n" + " <i>0</i>\n" + "</C>"; assertBothWays(c, expected); } public void testCanHandlePrimitiveValues() { C c = new C(null, null, 0); xstream.alias("C", C.class); xstream.useAttributeFor(Date.class); xstream.useAttributeFor(String.class); xstream.useAttributeFor(int.class); String expected ="<C i=\"0\"/>"; assertBothWays(c, expected); } static class Name { private String name; Name() { // for JDK 1.3 } Name(String name) { this.name = name; } } static class Camera { private String name; protected Name n; Camera() { // for JDK 1.3 } Camera(String name) { this.name = name; } } public void testAllowsAnAttributeForASpecificField() { xstream.alias("camera", Camera.class); xstream.useAttributeFor(Camera.class, "name"); Camera camera = new Camera("Rebel 350"); camera.n = new Name("foo"); String expected = "" + "<camera name=\"Rebel 350\">\n" + " <n>\n" + " <name>foo</name>\n" + " </n>\n" + "</camera>"; assertBothWays(camera, expected); } public void testAllowsAnAttributeForASpecificAliasedField() { xstream.alias("camera", Camera.class); xstream.useAttributeFor(Camera.class, "name"); xstream.aliasAttribute(Camera.class, "name", "model"); Camera camera = new Camera("Rebel 350"); camera.n = new Name("foo"); String expected = "" + "<camera model=\"Rebel 350\">\n" + " <n>\n" + " <name>foo</name>\n" + " </n>\n" + "</camera>"; assertBothWays(camera, expected); } static class PersonalizedCamera extends Camera { private String owner; PersonalizedCamera() { // for JDK 1.3 } PersonalizedCamera(String name, String owner) { super(name); this.owner = owner; } } public void testAllowsAnAttributeForASpecificFieldInASuperClass() { xstream.alias("camera", PersonalizedCamera.class); xstream.useAttributeFor(Camera.class, "name"); PersonalizedCamera camera = new PersonalizedCamera("Rebel 350", "Guilherme"); camera.n = new Name("foo"); String expected = "" + "<camera name=\"Rebel 350\">\n" + " <n>\n" + " <name>foo</name>\n" + " </n>\n" + " <owner>Guilherme</owner>\n" + "</camera>"; assertBothWays(camera, expected); } public void testAllowsAnAttributeForAFieldOfASpecialTypeAlsoInASuperClass() { xstream.alias("camera", PersonalizedCamera.class); xstream.useAttributeFor("name", String.class); PersonalizedCamera camera = new PersonalizedCamera("Rebel 350", "Guilherme"); camera.n = new Name("foo"); String expected = "" + "<camera name=\"Rebel 350\">\n" + " <n name=\"foo\"/>\n" + " <owner>Guilherme</owner>\n" + "</camera>"; assertBothWays(camera, expected); } public static class TransientIdField { transient String id; String name; public TransientIdField() { // for JDK 1.3 } public TransientIdField(String id, String name) { this.id = id; this.name = name; } public boolean equals(Object obj) { return name.equals(((TransientIdField)obj).name); } } public void testAttributeNamedLikeTransientFieldDoesNotAbortDeserializationOfFollowingFields() { xstream.setMode(XStream.ID_REFERENCES); xstream.alias("transient", TransientIdField.class); TransientIdField field = new TransientIdField("foo", "test"); String xml = "" + "<transient id=\"1\">\n" + " <name>test</name>\n" + "</transient>"; assertBothWays(field, xml); } }
package org.zanata.async; import java.security.Principal; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import javax.annotation.Nonnull; import javax.security.auth.Subject; import lombok.extern.slf4j.Slf4j; import org.jboss.seam.ScopeType; import org.jboss.seam.annotations.AutoCreate; import org.jboss.seam.annotations.Create; import org.jboss.seam.annotations.Destroy; import org.jboss.seam.annotations.In; import org.jboss.seam.annotations.Name; import org.jboss.seam.annotations.Scope; import org.jboss.seam.contexts.Lifecycle; import org.jboss.seam.security.RunAsOperation; import org.zanata.action.AuthenticationEvents; import org.zanata.config.AsyncConfig; import org.zanata.dao.AccountDAO; import org.zanata.model.HAccount; import org.zanata.security.ZanataIdentity; import org.zanata.security.ZanataJpaIdentityStore; import org.zanata.util.ServiceLocator; import com.google.common.util.concurrent.ListenableFuture; /** * @author Carlos Munoz <a * href="mailto:camunoz@redhat.com">camunoz@redhat.com</a> */ @Name("asyncTaskManager") @Scope(ScopeType.APPLICATION) @AutoCreate @Slf4j public class AsyncTaskManager { private ExecutorService scheduler; @In private AsyncConfig asyncConfig; @Create public void init() { scheduler = Executors.newFixedThreadPool(asyncConfig.getThreadPoolSize()); } @Destroy public void cleanup() { scheduler.shutdown(); } public <V> ListenableFuture<V> startTask( final @Nonnull AsyncTask<Future<V>> task) { HAccount taskOwner = ServiceLocator.instance() .getInstance(ZanataJpaIdentityStore.AUTHENTICATED_USER, HAccount.class); ZanataIdentity ownerIdentity = ZanataIdentity.instance(); // Extract security context from current thread final String taskOwnerUsername = taskOwner != null ? taskOwner.getUsername() : null; final Principal runAsPpal = ownerIdentity.getPrincipal(); final Subject runAsSubject = ownerIdentity.getSubject(); // final result final AsyncTaskResult<V> taskFuture = new AsyncTaskResult<V>(); final RunnableOperation runnableOp = new RunnableOperation() { @Override public void execute() { try { prepareSecurityContext(taskOwnerUsername); V returnValue = getReturnValue(task.call()); taskFuture.set(returnValue); } catch (Throwable t) { taskFuture.setException(t); log.warn( "Exception when executing an asynchronous task.", t); } } @Override public Principal getPrincipal() { return runAsPpal; } @Override public Subject getSubject() { return runAsSubject; } }; scheduler.execute(runnableOp); return taskFuture; } private static <V> V getReturnValue(Future<V> asyncTaskFuture) throws Exception { // If the async method returns void if (asyncTaskFuture == null) { return null; } return asyncTaskFuture.get(); } /** * Prepares the Drools security context so that it contains all the * necessary facts for security checking. */ private static void prepareSecurityContext(String username) { /* * TODO This should be changed to not need the username. There should be * a way to simulate a login for asyn tasks, or at least to inherit the * caller's context */ if (username != null) { // Only if it's an authenticated task should it try and do this // injection AccountDAO accountDAO = ServiceLocator.instance().getInstance(AccountDAO.class); ZanataJpaIdentityStore idStore = ServiceLocator.instance().getInstance( ZanataJpaIdentityStore.class); AuthenticationEvents authEvts = ServiceLocator.instance().getInstance( AuthenticationEvents.class); HAccount authenticatedAccount = accountDAO.getByUsername(username); idStore.setAuthenticateUser(authenticatedAccount); } } public abstract class RunnableOperation extends RunAsOperation implements Runnable { @Override public void run() { Lifecycle.beginCall(); // Start contexts super.run(); Lifecycle.endCall(); // End contexts } } }
// Math.java // // Copyright (c) 2012, // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // all copies or substantial portions of the Software. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package de.fhpotsdam.util.math; import java.math.BigDecimal; import java.math.RoundingMode; public class Math { /** * Rounds a float * @param value the float to round * @param precision the precision for rounding * @return the float with new precision */ public static float round(float value, int precision) { if (precision <= 0) { throw new IllegalArgumentException("Precision cannot be zero or less."); } BigDecimal decimal = BigDecimal.valueOf(value); return decimal.setScale(precision, RoundingMode.FLOOR).floatValue(); } /** * * @param values * @return */ public static float getSum(String[] values){ return getSum(values, 0, values.length); } /** * Parses the String array as float and calculates the sum of all elements. * The calculation will sum up all elements between startIndex until endIndex-1, so endIndex is <b>excluded</b>. * @param startIndex start index * @param endIndex end index * @return the biggest value within the range */ public static float getSum(String[] values, int startIndex, int endIndex){ float sum = 0; if(startIndex<0 || endIndex > values.length || startIndex >= endIndex ){ throw new IllegalArgumentException("Start index needs to be smaller than end index and withing range of the array!"); } for(int i=startIndex; i<endIndex; i++){ try{ sum += Float.parseFloat(values[i]); }catch(NumberFormatException e){ throw new IllegalArgumentException("'" + values[i] + "' could not be parsed to float!"); } } return sum; } /** * Parses the row with index rowIndex to float and sums up all values. * @param values the two-dimnensional string array containing floats at [][columnIndex] * @param columnIndex the column index containing floats to sum up * @param startIndex row start index * @param endIndex row end index * @return the sum of all values in the specific column */ public static float getSum(String[][] values, int columnIndex, int startIndex, int endIndex){ float sum = 0.0f; if(values == null || values.length == 0){ throw new IllegalArgumentException("Values array is null or does not contain any data"); } else if(startIndex<0 || endIndex > values[0].length || startIndex >= endIndex ){ throw new IllegalArgumentException("Start index needs to be smaller than end index and withing range of the array!"); } for(int i=startIndex; i<endIndex; i++){ try{ sum += Float.parseFloat(values[i][columnIndex]); }catch(NumberFormatException e){ throw new IllegalArgumentException("'" + values[i][columnIndex] + "' could not be parsed to float!"); } } return sum; } /** * Parses the row with index rowIndex to float and sums up all values. * @param values the two-dimnensional string array containing floats at [][columnIndex] * @param columnIndex the column index containing floats to sum up * @return the sum of all values in the specific column */ public static float getSum(String[][] values, int columnIndex){ if(values == null){ throw new IllegalArgumentException("Values array is null"); } else{ return getSum(values, columnIndex, 0, values.length); } } }
package de.phip1611.matrices; import javax.naming.OperationNotSupportedException; import java.util.Arrays; /** * A matrix as we know it from mathematics. */ public class Matrix implements BasicMatrixArithmetic, Comparable<Matrix> { protected MatrixDimension dim; protected int[] [] matrix; public Matrix(String dimension) { if (dimension.matches("([0-9])+([x])([0-9])+")) { int rows, cols; String[] split = dimension.split("x"); rows = Integer.valueOf(split[0]); cols = Integer.valueOf(split[1]); this.dim = new MatrixDimension(rows, cols); this.matrix = new int[dim.rows()][dim.cols()]; } else { throw new IllegalArgumentException("Dimension-String has to match" + " with \"([0-9])+([x])([0-9])+\", for example 3x2, 0x0, 20x7"); } } public Matrix(int rows, int cols) { this.dim = new MatrixDimension(rows, cols); this.matrix = new int[dim.rows()][dim.cols()]; } /** * Inits a matrix with a set of values. For examle if you have a 3x3 matrix * and want to have it look like * { * [1,2,3] * [4,-2,6] * [1,4,0] * } * use .init(1, 2, 3, 4, -2, 6, 1, 4, 0) * @param args */ public void init(int... args) throws MatrixDimension.MatrixDimensionOutOfBoundsException { if (args.length > this.dim.cols()*this.dim.rows()) { throw new MatrixDimension.MatrixDimensionOutOfBoundsException("If you init values make sure to have rows*cols values!"); } int index = 0; for (int i = 0; i < this.dim.rows(); i++) { for (int j = 0; j < this.dim.cols(); j++) { // wenn z.b. nur drei Elemente eingegeben wurden bei einer 3x3 Matrix if (index+1 > args.length) { break; } this.matrix[i][j] = args[index]; index++; } } } /** * Returns the value at the index. * @param row * @param col */ public int get(int row, int col) { this.dim.check(row, col); return this.matrix[row-1][col-1]; } /** * Sets the value at the index. * @param row * @param col * @param value */ public void set(int row, int col, int value) { this.dim.check(row, col); this.matrix[row-1][col-1] = value; } /** * Returns a whole row of the matrix as an array of ints with the corresponding values. * @param row * @return */ public int[] getRow(int row) { this.dim.check(row, 1); return this.matrix[row-1]; } /** * Returns a whole column of the matrix as an array of ints with the corresponding values. * @param col * @return */ public int[] getCol(int col) { this.dim.check(1, col); int[] result = new int[this.dim.rows()]; int i = 0; while (i < this.dim.rows()) { result[i] = this.matrix[i][col-1]; i++; } return result; } /** * Set's all fields of the matrix to the value. * @param value */ public void setAll(int value) { for (int i = 0; i < dim.rows(); i++) { for (int j = 0; j < dim.cols(); j++) { this.matrix[i][j] = value; } } } @Override public void addAll(int value) { for (int i = 0; i < dim.rows(); i++) { for (int j = 0; j < dim.cols(); j++) { this.matrix[i][j] += value; } } } @Override public void subAll(int value) { for (int i = 0; i < dim.rows(); i++) { for (int j = 0; j < dim.cols(); j++) { this.matrix[i][j] -= value; } } } @Override public void multAll(int value) { for (int i = 0; i < dim.rows(); i++) { for (int j = 0; j < dim.cols(); j++) { this.matrix[i][j] *= value; } } } @Override public void divAll(int value) { for (int i = 0; i < dim.rows(); i++) { for (int j = 0; j < dim.cols(); j++) { this.matrix[i][j] /= value; } } } @Override public void modAll(int value) { for (int i = 0; i < dim.rows(); i++) { for (int j = 0; j < dim.cols(); j++) { this.matrix[i][j] %= value; } } } /** * Adds a row to another one: rowDestination = rowDestination + row. * For example: [1,2,3] + [4,5,6] = [1+4, 2+5, 3+6] * * @param row * @param rowDestination */ @Override public void addRowToRow(int row, int rowDestination) { this.dim.check(row, 1); this.dim.check(rowDestination, 1); for (int i = 0; i < this.dim.cols(); i++) { this.matrix[rowDestination-1][i] += this.matrix[row-1][i]; } } /** * Subtracts a row to another one: rowDestination = rowDestination - row. * For example: [1,2,3] - [4,5,6] = [1-4, 2-5, 3-6] * * @param row * @param rowDestination */ @Override public void subRowToRow(int row, int rowDestination) { this.dim.check(row, 1); this.dim.check(rowDestination, 1); for (int i = 0; i < this.dim.cols(); i++) { this.matrix[rowDestination-1][i] -= this.matrix[row-1][i]; } } /** * Multiplies a row to another one: rowDestination = rowDestination * row. * For example: [1,2,3] * [4,5,6] = [1*4, 2*5, 3*6] * * @param row * @param rowDestination */ @Override public void multRowToRow(int row, int rowDestination) { this.dim.check(row, 1); this.dim.check(rowDestination, 1); for (int i = 0; i < this.dim.cols(); i++) { this.matrix[rowDestination-1][i] *= this.matrix[row-1][i]; } } /** * Divides a row to another one: rowDestination = rowDestination / row. * For example: [1,2,3] / [4,5,6] = [1/4, 2/5, 3/6] * * @param row * @param rowDestination */ @Override public void divRowToRow(int row, int rowDestination) { this.dim.check(row, 1); this.dim.check(rowDestination, 1); for (int i = 0; i < this.dim.cols(); i++) { this.matrix[rowDestination-1][i] /= this.matrix[row-1][i]; } } /** * Modulo a row to another one: rowDestination = rowDestination * row. * For example: [1,2,3] % [4,5,6] = [1%4, 2%5, 3%6] * * @param row * @param rowDestination */ @Override public void modRowToRow(int row, int rowDestination) { this.dim.check(row, 1); this.dim.check(rowDestination, 1); for (int i = 0; i < this.dim.cols(); i++) { this.matrix[rowDestination-1][i] %= this.matrix[row-1][i]; } } /** * Adds a value to all elements of a row. * * @param row * @param value */ @Override public void addToRow(int row, int value) { this.dim.check(row, 1); for (int i = 0; i < this.dim.cols(); i++) { this.matrix[row-1][i] += value; } } /** * Subtracts a value to all elements of a row. * * @param row * @param value */ @Override public void subToRow(int row, int value) { this.dim.check(row, 1); for (int i = 0; i < this.dim.cols(); i++) { this.matrix[row-1][i] -= value; } } /** * Multiplies a value to all elements of a row. * * @param row * @param value */ @Override public void multToRow(int row, int value) { this.dim.check(row, 1); for (int i = 0; i < this.dim.cols(); i++) { this.matrix[row-1][i] *= value; } } /** * Divides a value to all elements of a row. * * @param row * @param value */ @Override public void divToRow(int row, int value) { this.dim.check(row, 1); for (int i = 0; i < this.dim.cols(); i++) { this.matrix[row-1][i] /= value; } } /** * Divides a value to all elements of a row. * * @param row * @param value */ @Override public void modToRow(int row, int value) { this.dim.check(row, 1); for (int i = 0; i < this.dim.cols(); i++) { this.matrix[row-1][i] %= value; } } /** * Adds a value to all elements of a column. * * @param col * @param value */ @Override public void addToCol(int col, int value) { System.err.println("NOT AVAILABLE: addToCol() isn't implemented yet"); } /** * Subtracts a value to all elements of a column. * * @param col * @param value */ @Override public void subToCol(int col, int value) { System.err.println("NOT AVAILABLE: subToCol() isn't implemented yet"); } /** * Adds a value to all elements of a column. * * @param col * @param value */ @Override public void multToCol(int col, int value) { System.err.println("NOT AVAILABLE: multToCol() isn't implemented yet"); } /** * Divides a value to all elements of a column. * * @param col * @param value */ @Override public void divToCol(int col, int value) { System.err.println("NOT AVAILABLE: divToCol() isn't implemented yet"); } /** * Modulo a value to all elements of a column. * * @param col * @param value */ @Override public void modToCol(int col, int value) { System.err.println("NOT AVAILABLE: divToCol() isn't implemented yet"); } @Override public void add(int col, int row, int value) { this.dim.check(col, row); this.matrix[row-1][col-1] += value; } @Override public void sub(int col, int row, int value) { this.dim.check(col, row); this.matrix[row-1][col-1] -= value; } @Override public void mult(int col, int row, int value) { this.dim.check(col, row); this.matrix[row-1][col-1] *= value; } @Override public void div(int col, int row, int value) { this.dim.check(col, row); this.matrix[row-1][col-1] /= value; } @Override public void mod(int col, int row, int value) { this.dim.check(col, row); this.matrix[row-1][col-1] %= value; } public void print() { int i = 0; while (i < dim.rows()) { System.out.println(Arrays.toString(this.matrix[i])); i++; } } public boolean isInvertable() throws OperationNotSupportedException, NonQuadraticMatrixException { if (det() == 0) { return true; } return false; } /** * Calculates the determinant of a matrix. * (For now only 0x0 up to 3x3 matrices) * @return */ public int det() throws NonQuadraticMatrixException, OperationNotSupportedException { if (!isQuadraticMatrix()) throw new NonQuadraticMatrixException(); if (dim.rows() == 0) return 0; if (dim.rows() == 1) return this.matrix[0][0]; if (dim.rows() == 2) { return matrix[0][0]*matrix[1][1]-matrix[1][0]*matrix[0][1]; } if (dim.rows() == 3) { return matrix[0][0]*matrix[1][1]*matrix[2][2]+matrix[0][1]*matrix[1][2]*matrix[2][0]+matrix[0][2]*matrix[1][0]*matrix[2][1] -matrix[2][0]*matrix[1][1]*matrix[0][2]-matrix[2][1]*matrix[1][2]*matrix[0][0]-matrix[2][2]*matrix[1][0]*matrix[0][1]; } else { throw new OperationNotSupportedException("For now you only can calc the determinant of 2x2 and 3x3 matrices!"); } } public boolean isQuadraticMatrix() { return dim.rows() == dim.cols(); } /** * (generated by IntelliJ) * @param o * @return */ @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Matrix)) return false; Matrix matrix1 = (Matrix) o; if (!dim.equals(matrix1.dim)) return false; return Arrays.deepEquals(matrix, matrix1.matrix); } /** * (generated by IntelliJ) * @return */ @Override public int hashCode() { int result = dim.hashCode(); result = 31 * result + Arrays.deepHashCode(matrix); return result; } @Override public String toString() { return "Matrix: " + "dim=" + dim; } public int getColCount() { return this.dim.cols(); } public int getRowCount() { return this.dim.rows(); } /** * Compares a matrix to the current one by their dimensions. */ @Override public int compareTo(Matrix o) { return dim.compareTo(o.dim); } public class NonQuadraticMatrixException extends Exception {} }
package helper; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Charsets; import com.google.common.io.CharStreams; import models.Etikett; /** * @author Jan Schnasse * */ public class CrossrefLabelResolver extends LabelResolverService implements LabelResolver { public CrossrefLabelResolver() { super(); } public final static String DOMAIN = "dx.doi.org"; protected void lookupAsync(String uri, String language) { if (isCrossrefFunderUrl(uri)) { HashMap<String, String> headers = new HashMap<String, String>(); headers.put("Accept", "text/html"); try (InputStream in = urlToInputStream(new URL(uri), headers)) { play.Logger.debug("Stream: " + in.toString()); String str = CharStreams.toString(new InputStreamReader(in, Charsets.UTF_8)); JsonNode hit = new ObjectMapper().readValue(str, JsonNode.class); String label = hit.at("/prefLabel/Label/literalForm/content").asText(); if (label != null) { etikett.setLabel(label); cacheEtikett(etikett); } } catch (Exception e) { play.Logger.warn("Failed to find label for " + uri); } } else { play.Logger.debug("Nothing to do here: DOI is not a CrossrefFunder DOI"); } } private boolean isCrossrefFunderUrl(String urlString) { boolean isFunderUrl = false; if (urlString.contains("10.13039")) { isFunderUrl = true; } return isFunderUrl; } }
package fr.xtof54.jsgo; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.util.ArrayList; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.json.JSONException; import org.json.JSONObject; import com.example.testbrowser.R; import fr.xtof54.jsgo.EventManager.eventType; import fr.xtof54.jsgo.ServerConnection.DetLogger; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.preference.PreferenceManager; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.content.res.AssetManager; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import android.support.v4.app.DialogFragment; import android.support.v4.app.FragmentActivity; /** * TODO: * - create a dir in externalStorage - done * - copy in there the eidogo dir - done * - load games from DGS - done * - create an example.html file with the sgf inline - done * - init goban zoom from physical screen size * * @author xtof * */ public class GoJsActivity extends FragmentActivity { ServerConnection server=null; static int debugdevel=0; // String server; enum guistate {nogame, play, markDeadStones, checkScore, message}; guistate curstate = guistate.nogame; File eidogodir; final boolean forcecopy=false; HttpClient httpclient=null; WebView wv; ArrayList<Game> games2play = new ArrayList<Game>(); int curgidx2play=0,moveid=0; final String netErrMsg = "Connection errors or timeout, you may retry"; static GoJsActivity main; // private static void copyFile(InputStream in, OutputStream out) throws IOException { // byte[] buffer = new byte[1024]; // int read; // while((read = in.read(buffer)) != -1){ // out.write(buffer, 0, read); private void setButtons(final String b1, final String b2, final String b3, final String b4) { this.runOnUiThread(new Runnable() { @Override public void run() { Button but1 = (Button)findViewById(R.id.but1); but1.setText(b1); Button but2 = (Button)findViewById(R.id.but2); but2.setText(b2); Button but3 = (Button)findViewById(R.id.but3); but3.setText(b3); Button but4 = (Button)findViewById(R.id.but4); but4.setText(b4); } }); } private guistate lastGameState; private void changeState(guistate newstate) { if (curstate==guistate.markDeadStones && newstate!=guistate.markDeadStones) wv.loadUrl("javascript:eidogo.autoPlayers[0].detmarkp()"); System.out.println("inchangestate "+curstate+" .. "+newstate); switch (newstate) { case nogame: setButtons("Getgame","Zoom+","Zoom-","Msg"); break; case play: setButtons("Send","Zoom+","Zoom-","Reset"); break; case markDeadStones: showMessage("Scoring phase: put one X marker on each dead group and click SEND to check score (you can still change after)"); // just in case the board is already rendered... // normally, detmarkx() is called right after the board is displayed, // but here, the board is displayed long ago, so we have to call it manually wv.loadUrl("javascript:eidogo.autoPlayers[0].detmarkx()"); setButtons("Score","Zoom+","Zoom-","Play"); break; case checkScore: setButtons("Accept","Zoom+","Zoom-","Refuse"); break; case message: lastGameState=curstate; setButtons("GetMsg","Invite","SendMsg","Back2game"); break; default: } curstate=newstate; } public String showCounting(JSONObject o) { String sc=""; try { sc = o.getString("score"); String bt = o.getString("black_territory").trim(); for (int i=0;i<bt.length();i+=2) { String coords = bt.substring(i, i+2); wv.loadUrl("javascript:eidogo.autoPlayers[0].cursor.node.pushProperty(\"TB\",\""+coords+"\")"); } String wt = o.getString("white_territory").trim(); for (int i=0;i<wt.length();i+=2) { String coords = wt.substring(i, i+2); wv.loadUrl("javascript:eidogo.autoPlayers[0].cursor.node.pushProperty(\"TW\",\""+coords+"\")"); } wv.loadUrl("javascript:eidogo.autoPlayers[0].refresh()"); } catch (JSONException e) { e.printStackTrace(); showMessage("warning: error counting"); } return sc; } void copyEidogo(final String edir, final File odir) { AssetManager mgr = getResources().getAssets(); try { String[] fs = mgr.list(edir); for (String s : fs) { try { InputStream i = mgr.open(edir+"/"+s); // this is a file File f0 = new File(odir,s); FileOutputStream f = new FileOutputStream(f0); for (;;) { int d = i.read(); if (d<0) break; f.write(d); } f.close(); i.close(); } catch (FileNotFoundException e) { // this is a directory and not a file File f = new File(odir,s); f.mkdirs(); copyEidogo(edir+"/"+s,f); } } } catch (IOException e) { e.printStackTrace(); showMessage("DISK ERROR: "+e.toString()); } System.out.println("endof copy"); } void initFinished() { System.out.println("init finished"); final TextView wv = (TextView)findViewById(R.id.textView1); wv.setText("init done. You can play !"); final Button button1 = (Button)findViewById(R.id.but1); button1.setClickable(true); button1.setEnabled(true); final Button button2 = (Button)findViewById(R.id.but2); button2.setClickable(true); button2.setEnabled(true); final Button button3 = (Button)findViewById(R.id.but3); button3.setClickable(true); button3.setEnabled(true); button1.invalidate(); button2.invalidate(); button3.invalidate(); wv.invalidate(); } private String getMarkedStones(String sgf) { String res = null; int i=0; for (;;) { System.out.println("debug "+sgf.substring(i)); int j=sgf.indexOf("MA[",i); if (j<0) { return res; } else { i=j+2; while (i<sgf.length()) { if (sgf.charAt(i)!='[') break; j=sgf.indexOf(']',i); if (j<0) break; String stone = sgf.substring(i+1,j); if (res==null) res=stone; else res+=stone; i=j+1; } } } } // private boolean sendCmd2server(String cmd, String msg) { // HttpGet httpget = new HttpGet(server+cmd); // try { // HttpResponse response = httpclient.execute(httpget); // System.out.println("answer to send move:"); // Header[] heds = response.getAllHeaders(); // for (Header s : heds) // System.out.println("[HEADER] "+s); // HttpEntity entity = response.getEntity(); // String jsonansw=null; // if (entity != null) { // InputStream instream = entity.getContent(); // BufferedReader fin = new BufferedReader(new InputStreamReader(instream, Charset.forName("UTF-8"))); // for (;;) { // String s = fin.readLine(); // if (s==null) break; // System.out.println("LOGINlog "+s); // if (s.contains("#Error")) showMessage("Error login; check credentials"); // if (s.length()>0&&s.charAt(0)=='{') jsonansw = s; // fin.close(); // if (curstate==guistate.markDeadStones) { // String sc = showCounting(jsonansw); // showMessage("dead stones sent; score="+sc); // changeState(guistate.checkScore); // } else { // showMessage("sent to server: "+msg); // return true; // } catch (Exception e) { // e.printStackTrace(); // showMessage(netErrMsg); // return false; private class myWebViewClient extends WebViewClient { @Override public void onPageFinished(WebView view, String url) { view.loadUrl("javascript:eidogo.autoPlayers[0].last()"); if (curstate==guistate.markDeadStones) view.loadUrl("javascript:eidogo.autoPlayers[0].detmarkx()"); } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { System.out.println("mywebclient detecting command from javascript: "+url); int i=url.indexOf("androidcall01"); if (i>=0) { int j=url.lastIndexOf('|')+1; String lastMove = url.substring(j); // this is trigerred when the user clicks the SEND button final Game g = Game.gameShown; if (curstate==guistate.markDeadStones) { String sgfdata = url.substring(i+14, j); String deadstones=getMarkedStones(sgfdata); final EventManager em = EventManager.getEventManager(); EventManager.EventListener f = new EventManager.EventListener() { @Override public String getName() {return "mywebclient";} @Override public synchronized void reactToEvent() { em.unregisterListener(eventType.moveSentEnd, this); JSONObject o = server.o; if (o==null) { // error: do nothing return; } String err = o.getString("error"); if (err!=null&&err.length()>0) { // error: do nothing return; } // show territories String sc = showCounting(o); showMessage("dead stones sent; score="+sc); changeState(guistate.checkScore); } }; em.registerListener(eventType.moveSentEnd, f); g.sendDeadstonesToServer(deadstones, server); } else { final EventManager em = EventManager.getEventManager(); EventManager.EventListener f = new EventManager.EventListener() { @Override public String getName() {return "mywebclient";} @Override public synchronized void reactToEvent() { em.unregisterListener(eventType.moveSentEnd, this); JSONObject o = server.o; if (o==null) { // error: don't switch game return; } String err = o.getString("error"); if (err!=null&&err.length()>0) { // error: don't switch game return; } // switch to next game g.finishedWithThisGame(); if (Game.getGames().size()==0) { showMessage("No more games locally"); changeState(guistate.nogame); } else downloadAndShowGame(); } }; em.registerListener(eventType.moveSentEnd, f); g.sendMove2server(lastMove,server); } // if (sendCmd2server(cmd, msg) && curstate==guistate.play) { // // if the move has been correctly sent to the server and it's really a move, not a score request, // // then we can switch to the next game // moveid=0; // games2play.remove(curgidx2play); // if (games2play.size()==0) { // showMessage("No more games locally"); // changeState(guistate.nogame); // } else // downloadAndShowGame(); return true; } else { // its not an android call back // let the browser navigate normally return false; } } } void showGame(Game g) { g.showGame(); // detect if in scoring phase // TODO: replace this by checking the game STATUS ! if (g.isTwoPasses()) { System.out.println("scoring phase detected !"); changeState(guistate.markDeadStones); } // show the board game String f=eidogodir+"/example.html"; System.out.println("debugloadurl file: wv.loadUrl("file: } void downloadAndShowGame() { int ngames = Game.getGames().size(); if (curgidx2play>=ngames) { if (ngames==0) { showMessage("No game to show"); return; } else { curgidx2play=0; } } System.out.println("showing game "+curgidx2play); final Game g = Game.getGames().get(curgidx2play); g.downloadGame(server); final EventManager em = EventManager.getEventManager(); em.registerListener(eventType.GameOK, new EventManager.EventListener() { @Override public String getName() {return "downloadAndShowGame";} @Override public synchronized void reactToEvent() { em.unregisterListener(eventType.GameOK, this); showGame(g); } }); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); wv = (WebView)findViewById(R.id.web1); wv.setWebViewClient(new myWebViewClient()); wv.getSettings().setJavaScriptEnabled(true); wv.getSettings().setSupportZoom(true); // String myHTML = "<html><body><a href='androidcall01|123456'>Call Back to Android 01 with param 123456</a>my Content<p>my Content<p>my Content<p><a href='androidcall02|7890123'>Call Back to Android 01 with param 7890123</a></body></html>"; // wv.loadDataWithBaseURL("about:blank", myHTML, "text/html", "utf-8", ""); // wv.addJavascriptInterface(new WebAppInterface(this), "Android"); { final Button button = (Button)findViewById(R.id.morebutts); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { System.out.println("press last button on state "+curstate); showMoreButtons(); } }); } { final Button button = (Button)findViewById(R.id.but1); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { System.out.println("press button1 on state "+curstate); switch(curstate) { case nogame: // download games downloadListOfGames(); break; case play: // send the move // ask eidogo to send last move; it will be captured by the web listener wv.loadUrl("javascript:eidogo.autoPlayers[0].detsonSend()"); break; case markDeadStones: // send a request to the server to compute the score // ask eidogo to send sgf, which shall contain X wv.loadUrl("javascript:eidogo.autoPlayers[0].detsonSend()"); break; case checkScore: // accept the current score evaluation // acceptScore(); break; case message: // get messages initServer(); Message.downloadMessages(server,main); break; } // Intent intent = new Intent(Intent.ACTION_VIEW); // intent.addCategory(Intent.CATEGORY_BROWSABLE); // intent.setDataAndType(Uri.fromFile(ff), "application/x-webarchive-xml"); // // intent.setDataAndType(Uri.fromFile(ff), "text/html"); // intent.setClassName("com.android.browser", "com.android.browser.BrowserActivity"); // // intent.setClassName("Lnu.tommie.inbrowser", "com.android.browser.BrowserActivity"); // startActivity(intent); // // to launch a browser: // // Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("file:///mnt/sdcard/")); } }); } { final Button button = (Button)findViewById(R.id.but2); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { System.out.println("press button2 on state "+curstate); switch(curstate) { case nogame: case play: case markDeadStones: case checkScore: wv.zoomIn(); wv.invalidate(); break; case message: // send invitation // TODO break; } } }); } { final Button button = (Button)findViewById(R.id.but3); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { System.out.println("press button3 on state "+curstate); switch(curstate) { case nogame: case play: case markDeadStones: case checkScore: wv.zoomOut(); wv.invalidate(); case message: // send message Message.send(); break; } } }); } { final Button button = (Button)findViewById(R.id.but4); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { System.out.println("press button4 on state "+curstate); switch(curstate) { case nogame: // send message (TODO) changeState(guistate.message); break; case play: // reset to the original download SGF showGame(Game.gameShown); break; case markDeadStones: // cancels marking stones and comes back to playing changeState(guistate.play); break; case checkScore: // refuse score and continues to mark stones break; case message: // go back to last game mode changeState(lastGameState); break; } } }); } // copy the eidogo dir into the external sdcard // only copy if it does not exist already // this takes time, so do it in a thread and show a message for the user to wait boolean mExternalStorageAvailable = false; boolean mExternalStorageWriteable = false; String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { mExternalStorageAvailable = mExternalStorageWriteable = true; } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { mExternalStorageAvailable = true; mExternalStorageWriteable = false; } else { mExternalStorageAvailable = mExternalStorageWriteable = false; } if (mExternalStorageAvailable&&mExternalStorageWriteable) { File d = getExternalCacheDir(); eidogodir = new File(d, "eidogo"); if (forcecopy||!eidogodir.exists()) { eidogodir.mkdirs(); final Button button3 = (Button)findViewById(R.id.but3); button3.setClickable(false); button3.setEnabled(false); final Button button2= (Button)findViewById(R.id.but2); button2.setClickable(false); button2.setEnabled(false); final Button button1= (Button)findViewById(R.id.but1); button1.setClickable(false); button1.setEnabled(false); button1.invalidate(); button2.invalidate(); button3.invalidate(); new CopyEidogoTask().execute("noparms"); } else { showMessage("eidogo already on disk"); initFinished(); } } else { showMessage("R/W ERROR sdcard"); } } private void downloadSgf(HttpClient httpclient, String url) { try { HttpGet httpget = new HttpGet(url); HttpResponse response = httpclient.execute(httpget); System.out.println(response.getStatusLine()); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); try { BufferedInputStream bis = new BufferedInputStream(instream); String filePath = eidogodir+"/example.html"; BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(filePath))); int inByte; while ((inByte = bis.read()) != -1 ) { bos.write(inByte); } bis.close(); bos.close(); } catch (IOException ex) { throw ex; } catch (RuntimeException ex) { httpget.abort(); throw ex; } finally { instream.close(); } } } catch (Exception e) { e.printStackTrace(); } } static class PrefUtils { public static final String PREFS_LOGIN_USERNAME_KEY = "__USERNAME__" ; public static final String PREFS_LOGIN_PASSWORD_KEY = "__PASSWORD__" ; public static final String PREFS_LOGIN_USERNAME2_KEY = "__USERNAME2__" ; public static final String PREFS_LOGIN_PASSWORD2_KEY = "__PASSWORD2__" ; /** * Called to save supplied value in shared preferences against given key. * @param context Context of caller activity * @param key Key of value to save against * @param value Value to save */ public static void saveToPrefs(Context context, String key, String value) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); final SharedPreferences.Editor editor = prefs.edit(); editor.putString(key,value); editor.commit(); } /** * Called to retrieve required value from shared preferences, identified by given key. * Default value will be returned of no value found or error occurred. * @param context Context of caller activity * @param key Key to find value against * @param defaultValue Value to return if no data found against given key * @return Return the value found against given key, default if not found or any error occurs */ public static String getFromPrefs(Context context, String key, String defaultValue) { SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); try { return sharedPrefs.getString(key, defaultValue); } catch (Exception e) { e.printStackTrace(); return defaultValue; } } } /* * This method must not be blocking, otherwise the waiting dialog window is never displayed. */ public Thread runInWaitingThread(final Runnable method) { final Thread computingThread = new Thread(new Runnable() { @Override public void run() { // this is blocking method.run(); try { // just in case, wait for the waiting dialog to be visible for (;;) { if (waitdialog!=null && waitdialog.getDialog()!=null) break; Thread.sleep(500); } // then dismisses it waitdialog.getDialog().cancel(); } catch (Exception e) { e.printStackTrace(); } // I notify potential threads that wait for computing to be finished synchronized (waiterComputingFinished) { waiterComputingFinished.notifyAll(); } } }); computingThread.start(); return computingThread; } private Boolean waiterComputingFinished=true; private void initServer() { if (server!=null) return; String tu = PrefUtils.getFromPrefs(this, PrefUtils.PREFS_LOGIN_USERNAME_KEY,null); String tp = PrefUtils.getFromPrefs(this, PrefUtils.PREFS_LOGIN_PASSWORD_KEY,null); int numserver=0; if (tu==null||tp==null) { showMessage("Please enter your credentials first via menu Settings"); return; } if (debugdevel==1) { tu = PrefUtils.getFromPrefs(this, PrefUtils.PREFS_LOGIN_USERNAME2_KEY,null); tp = PrefUtils.getFromPrefs(this, PrefUtils.PREFS_LOGIN_PASSWORD2_KEY,null); numserver=1; } final String u = tu, p=tp; System.out.println("credentials passed to server "+u+" "+p); if (server==null) { server = new ServerConnection(numserver, u, p); DetLogger l = new DetLogger() { @Override public void showMsg(String s) { showMessage(s); } }; server.setLogget(l); } } private void downloadListOfGames() { initServer(); final EventManager em = EventManager.getEventManager(); EventManager.EventListener l = new EventManager.EventListener() { @Override public String getName() {return "downloadListOfGames";} @Override public void reactToEvent() { em.unregisterListener(eventType.downloadListGamesEnd, this); int ngames = Game.getGames().size(); System.out.println("in downloadList listener "+ngames); if (ngames>=0) showMessage("Nb games to play: "+ngames); if (ngames>0) { curgidx2play=0; downloadAndShowGame(); // download detects if 2 passes and auto change state to markdeadstones if (curstate!=guistate.markDeadStones) changeState(guistate.play); } else return; } }; em.registerListener(eventType.downloadListGamesEnd, l); Game.loadStatusGames(server); } private class CopyEidogoTask extends AsyncTask<String, Void, String> { protected String doInBackground(String... parms) { copyEidogo("eidogo",eidogodir); return "init done"; } protected void onPostExecute(String res) { System.out.println("eidogo copy finished"); initFinished(); } } public static class WaitDialogFragment extends DialogFragment { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); // Get the layout inflater LayoutInflater inflater = getActivity().getLayoutInflater(); // Inflate and set the layout for the dialog // Pass null as the parent view because its going in the dialog layout builder.setView(inflater.inflate(R.layout.waiting, null)) // Add action buttons .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { WaitDialogFragment.this.getDialog().cancel(); // TODO stop thread } }); return builder.create(); } } private WaitDialogFragment waitdialog; private int numEventsReceived = 0; boolean isWaitingDialogShown = false; @Override public void onStart() { super.onStart(); // server = getString(R.string.server1); main = this; final EventManager em = EventManager.getEventManager(); EventManager.EventListener waitDialogShower = new EventManager.EventListener() { @Override public String getName() {return "onStartShowWaitDialog";} @Override public synchronized void reactToEvent() { try { if (!isWaitingDialogShown) { waitdialog = new WaitDialogFragment(); waitdialog.show(getSupportFragmentManager(),"waiting"); isWaitingDialogShown=true; } } catch (Exception e) { e.printStackTrace(); } numEventsReceived++; } }; // we put here all events that should trigger the "waiting" dialog em.registerListener(eventType.downloadGameStarted, waitDialogShower); em.registerListener(eventType.downloadListStarted, waitDialogShower); em.registerListener(eventType.loginStarted, waitDialogShower); em.registerListener(eventType.moveSentStart, waitDialogShower); EventManager.EventListener waitDialogHider = new EventManager.EventListener() { @Override public String getName() {return "onStartHideWaitDialog";} @Override public synchronized void reactToEvent() { try { --numEventsReceived; if (numEventsReceived<0) { System.out.println("ERROR events stream..."); return; } if (numEventsReceived==0) { waitdialog.dismiss(); isWaitingDialogShown=false; } } catch (Exception e) { e.printStackTrace(); } } }; em.registerListener(eventType.downloadGameEnd, waitDialogHider); em.registerListener(eventType.downloadListEnd, waitDialogHider); em.registerListener(eventType.loginEnd, waitDialogHider); em.registerListener(eventType.moveSentEnd, waitDialogHider); changeState(guistate.nogame); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_settings: ask4credentials(); return true; default: return super.onOptionsItemSelected(item); } } void showMessage(final String txt) { this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getBaseContext(), txt, Toast.LENGTH_LONG).show(); } }); } private void ask4credentials() { System.out.println("calling settings"); final Context c = this; class LoginDialogFragment extends DialogFragment { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); // Get the layout inflater LayoutInflater inflater = getActivity().getLayoutInflater(); // Inflate and set the layout for the dialog // Pass null as the parent view because its going in the dialog layout builder.setView(inflater.inflate(R.layout.dialog_signin, null)) // Add action buttons .setPositiveButton(R.string.signin, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { // sign in the user ... TextView username = (TextView)LoginDialogFragment.this.getDialog().findViewById(R.id.username); TextView pwd = (TextView)LoginDialogFragment.this.getDialog().findViewById(R.id.password); PrefUtils.saveToPrefs(c, PrefUtils.PREFS_LOGIN_USERNAME_KEY, username.getText().toString()); PrefUtils.saveToPrefs(c, PrefUtils.PREFS_LOGIN_PASSWORD_KEY, (String)pwd.getText().toString()); showMessage("Credentials saved"); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { LoginDialogFragment.this.getDialog().cancel(); } }); return builder.create(); } } LoginDialogFragment dialog = new LoginDialogFragment(); dialog.show(getSupportFragmentManager(),"dgs signin"); } private void ask4credentials2() { System.out.println("calling debug settings"); final Context c = this; class LoginDialogFragment extends DialogFragment { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); // Get the layout inflater LayoutInflater inflater = getActivity().getLayoutInflater(); // Inflate and set the layout for the dialog // Pass null as the parent view because its going in the dialog layout builder.setView(inflater.inflate(R.layout.dialog_signin, null)) // Add action buttons .setPositiveButton(R.string.signin, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { // sign in the user ... TextView username = (TextView)LoginDialogFragment.this.getDialog().findViewById(R.id.username); TextView pwd = (TextView)LoginDialogFragment.this.getDialog().findViewById(R.id.password); PrefUtils.saveToPrefs(c, PrefUtils.PREFS_LOGIN_USERNAME2_KEY, username.getText().toString()); PrefUtils.saveToPrefs(c, PrefUtils.PREFS_LOGIN_PASSWORD2_KEY, (String)pwd.getText().toString()); showMessage("Credentials2 saved"); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { LoginDialogFragment.this.getDialog().cancel(); } }); return builder.create(); } } LoginDialogFragment dialog = new LoginDialogFragment(); dialog.show(getSupportFragmentManager(),"dgs signin"); } private void skipGame() { if (Game.getGames().size()<=1) { showMessage("No more games downloaded; retry GetGames ?"); changeState(guistate.nogame); return; } if (++curgidx2play>=Game.getGames().size()) curgidx2play=0; downloadAndShowGame(); } private void resignGame() { String cmd = "quick_do.php?obj=game&cmd=resign&gid="+Game.gameShown.getGameID()+"&move_id="+moveid; HttpGet httpget = new HttpGet(server+cmd); try { HttpResponse response = httpclient.execute(httpget); // TODO: check if move has correctly been sent showMessage("resign sent !"); moveid=0; games2play.remove(curgidx2play); downloadAndShowGame(); } catch (Exception e) { e.printStackTrace(); showMessage(netErrMsg); } } private void loadSgf() { System.out.println("eidogodir: "+eidogodir); String f=eidogodir+"/example.html"; wv.loadUrl("file: } private void showMoreButtons() { System.out.println("showing more buttons"); final GoJsActivity c = this; class MoreButtonsDialogFragment extends DialogFragment { private final MoreButtonsDialogFragment dialog = this; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); // Get the layout inflater LayoutInflater inflater = getActivity().getLayoutInflater(); // Inflate and set the layout for the dialog // Pass null as the parent view because its going in the dialog layout View v = inflater.inflate(R.layout.other_buttons, null); Button bdebug = (Button)v.findViewById(R.id.loadSgf); bdebug.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View vv) { System.out.println("loading sgf"); loadSgf(); changeState(guistate.play); Game.createDebugGame(); dialog.dismiss(); } }); Button bserver2 = (Button)v.findViewById(R.id.devServer); bserver2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View vv) { debugdevel=1-debugdevel; showMessage("debug devel mode ON"); System.out.println("next connections to devel server"); // server = getString(R.string.server2); final String u = PrefUtils.getFromPrefs(c, PrefUtils.PREFS_LOGIN_USERNAME2_KEY,null); System.out.println("debugcred2 "+u); dialog.dismiss(); if (u==null) ask4credentials2(); } }); Button beidogo = (Button)v.findViewById(R.id.copyEidogo); beidogo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View vv) { System.out.println("copy eidogo"); new CopyEidogoTask().execute("noparms"); dialog.dismiss(); } }); Button bcycle = (Button)v.findViewById(R.id.cycleStates); bcycle.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View vv) { switch (curstate) { case nogame: changeState(guistate.play); break; case play: changeState(guistate.markDeadStones); break; case markDeadStones: changeState(guistate.checkScore); break; case checkScore: changeState(guistate.nogame); break; default: } System.out.println("cycle state "+curstate); } }); Button bskip = (Button)v.findViewById(R.id.skipGame); bskip.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View vv) { System.out.println("skip game"); skipGame(); dialog.dismiss(); } }); Button bresign= (Button)v.findViewById(R.id.resign); bresign.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View vv) { System.out.println("resign game"); resignGame(); dialog.dismiss(); } }); builder.setView(v); return builder.create(); } } MoreButtonsDialogFragment dialog = new MoreButtonsDialogFragment(); dialog.show(getSupportFragmentManager(),"more actions"); } }
package gamepack.data.drawable; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.newdawn.slick.Color; import org.newdawn.slick.Graphics; import org.newdawn.slick.geom.Rectangle; public class Grid implements DrawableObject { private int sizeX; private int sizeY; private Color bgColor = new Color(0xC1B8B0); private Color interiorColor = new Color(0xD6CDC4); private List<Rectangle> rectangleList; public Grid(int x, int y) { // Initialization of the base attributes of the grid : int gridSize = 4; float padX = 20; float padY = 20; float marginY = 30; float leftMarginX = 30; float rightMarginX = 50; float rectSizeX, rectSizeY, minRectSize; this.sizeX = x; this.sizeY = y; float min = (sizeX < sizeY ? sizeX : sizeY); // To let the grid be squared padX *= min / 800; padY *= min / 800; marginY *= min / 800; leftMarginX *= min/800; rightMarginX *= min/800; rectSizeX = (min - (leftMarginX + rightMarginX) - (gridSize-1)*padX)/(gridSize); rectSizeY = (min - (2*marginY) - (gridSize-1)*padY)/(gridSize); minRectSize = (float) Math.floor((rectSizeX < rectSizeY ? rectSizeX : rectSizeY)); rectangleList = new ArrayList<Rectangle>(); for (int i = 0; i < gridSize; i++) { for (int j = 0; j < gridSize; j++) { rectangleList.add(new Rectangle(leftMarginX + j * (minRectSize + padX), marginY + i * (minRectSize + padY), minRectSize, minRectSize)); } } } public Collection<Rectangle> getRectangles() { return this.rectangleList; } public int squareSize() { return (int) ((Rectangle)rectangleList.get(0)).getWidth(); } public void beDrawn(Graphics g) { /* BackGround */ g.setColor(bgColor); g.fillRect(0, 0, sizeX, sizeY); /* Rectangles */ g.setColor(interiorColor); for (Rectangle rectangle : rectangleList) { g.fill(rectangle); } } }
/** * * $Id: Constants.java,v 1.69 2005-11-08 17:46:20 pandyas Exp $ * * $Log: not supported by cvs2svn $ * Revision 1.68 2005/11/08 16:46:33 georgeda * Changes for images * * Revision 1.67 2005/11/07 21:55:10 georgeda * Changes for images * * Revision 1.66 2005/11/03 13:57:58 georgeda * Delete functionality changes * * Revision 1.65 2005/11/02 20:56:04 schroedn * Added Staining to Image submission * * Revision 1.64 2005/11/02 20:28:59 pandyas * modified GeneDelivery dropdown source * * Revision 1.63 2005/11/02 17:15:58 schroedn * Updated Image viewer, added constants and properties to camod.properties, merged code to ease changes later * * Revision 1.62 2005/11/02 16:33:41 georgeda * Misc fixes * * Revision 1.61 2005/10/28 12:47:11 georgeda * Action constant * * Revision 1.60 2005/10/27 18:31:50 georgeda * New dropdown options * * Revision 1.59 2005/10/27 17:13:19 guruswas * added publications to capture all publications * * Revision 1.58 2005/10/27 15:29:59 georgeda * Cleanup * * Revision 1.57 2005/10/26 20:40:30 schroedn * Added AssocExpression to EngineeredTransgene submission page * * Revision 1.56 2005/10/24 22:00:48 pandyas * added back availability_list so it doesn't break everyone else * * Revision 1.55 2005/10/24 21:16:59 pandyas * added availability constants * * Revision 1.54 2005/10/24 21:04:03 schroedn * Added Image to submission * * Revision 1.53 2005/10/24 18:44:41 georgeda * Do species from dropdown * * Revision 1.52 2005/10/24 13:26:28 georgeda * Cleanup changes * * Revision 1.51 2005/10/21 20:46:21 georgeda * Added user registration settings * * Revision 1.50 2005/10/21 19:36:56 schroedn * Added Constants for Image upload and retrieval * * Revision 1.49 2005/10/20 21:35:22 georgeda * Added xenograft constant * * Revision 1.48 2005/10/20 21:20:17 pandyas * add animal availability list * * Revision 1.47 2005/10/20 21:14:15 stewardd * added constants used in e-mail generation of InducedMutationManagerImpl and TargetedModificationManagerImpl classe. * * Revision 1.46 2005/10/20 19:28:28 georgeda * Added TOC constants * * Revision 1.45 2005/10/19 18:56:26 guruswas * implemented invivo details page * * Revision 1.44 2005/10/17 13:25:17 georgeda * Work for comments/users * * Revision 1.43 2005/10/13 16:18:51 pandyas * added constant for growth factor dose units * * Revision 1.42 2005/10/11 20:51:12 schroedn * Added constant for ENGINEEREDTRANSGENE_LIST * * Revision 1.41 2005/10/11 19:56:19 pandyas * added constant for assc met list * * Revision 1.40 2005/10/11 18:12:08 georgeda * More comment changes * * Revision 1.39 2005/10/10 14:05:38 georgeda * Cleanup and additions for comment curation * * Revision 1.37 2005/10/05 20:27:59 guruswas * implementation of drug screening search page * * Revision 1.36 2005/10/05 19:24:14 pandyas * added clinical marker list * * Revision 1.35 2005/10/05 16:21:50 pandyas * added histopthology and therapy lists * * Revision 1.34 2005/10/04 20:18:48 georgeda * Updates from search changes * * Revision 1.33 2005/10/04 20:09:41 schroedn * Added Spontaneous Mutation, InducedMutation, Histopathology, TargetedModification and GenomicSegment * * Revision 1.32 2005/10/03 16:07:39 pandyas * modified histopathology constant name to reflect contents * * Revision 1.31 2005/10/03 15:31:00 pandyas * added clinical marker and histopathology constants * * Revision 1.30 2005/10/03 13:04:19 georgeda * Updates from search changes * * Revision 1.29 2005/09/30 18:47:46 pandyas * added all differences to my copy before uploading * * Revision 1.25 2005/09/27 16:34:31 georgeda * Changed administravive route drop down * * */ package gov.nih.nci.camod; /** * Constant values used throughout the application. * * <p> * <a href="Constants.java.html"><i>View Source</i></a> * </p> */ public class Constants { // ~ Static fields/initializers /** The name of the camod resource bundle used in this application */ public static final String CAMOD_BUNDLE = "camod"; /** The name of the ResourceBundle used in this application */ public static final String BUNDLE_KEY = "ApplicationResources"; /** The application scoped attribute for persistence engine used */ public static final String DAO_TYPE = "daoType"; public static final String DAO_TYPE_HIBERNATE = "hibernate"; /** Application scoped attributes for SSL Switching */ public static final String HTTP_PORT = "httpPort"; public static final String HTTPS_PORT = "httpsPort"; /** * The name of the Administrator role, as specified in web.xml */ public static final String ADMIN_ROLE = "admin"; /** * The name of the configuration hashmap stored in application scope. */ public static final String CONFIG = "appConfig"; public static final String UPT_CONTEXT_NAME = "camod"; /** * Used to store list of models currently logged on user has previous * entered */ public static final String USERMODELLIST = "usermodellist"; public interface BundleKeys { /** * The key for the coordinator username in the camod.properties file */ public static final String COORDINATOR_USERNAME_KEY = "coordinator.username"; /** * The key for the coordinator username in the camod.properties file */ public static final String NEW_UNCONTROLLED_VOCAB_NOTIFY_KEY = "model.new_unctrl_vocab_notify"; /** * The key for the coordinator username in the camod.properties file */ public static final String NEW_UNCONTROLLED_VOCAB_SUBJECT_KEY = "model.new_unctrl_vocab_subject"; /** * The key for the coordinator username in the camod.properties file */ public static final String USER_UPDATE_NOTIFY_KEY = "user_settings.user_update_notify"; } /** * Used to store lists for drop down menus */ public interface CaArray { public static final String URI_START = "caarray.uri_start"; public static final String URI_END = "caarray.uri_end"; } /** * Used in table of contents searching */ public interface TOCSearch { public static final String TOC_QUERY_FILE = "config/TOCQueryConfig.xml"; public static final String TOC_QUERY_RESULTS = "TOC_QUERY_RESULTS"; } /** * Used to store lists for drop down menus */ public interface Dropdowns { public static final String ADD_BLANK = "ADD_BLANK"; public static final String ADD_OTHER = "ADD_OTHER"; public static final String ADD_BLANK_AND_OTHER = "ADD_BLANK_AND_OTHER"; public static final String ADD_BLANK_OPTION = "ADD_BLANK_OPTION"; public static final String ADD_OTHER_OPTION = "ADD_OTHER_OPTION"; public static final String ADD_BLANK_AND_OTHER_OPTION = "ADD_BLANK_AND_OTHER_OPTION"; public static final String OTHER_OPTION = "Other"; public static final String SPECIESDROP = "speciesdrop.db"; public static final String NEWSPECIESDROP = "ModelSpecies.txt"; public static final String STRAINDROP = "straindrop.db"; public static final String SEXDISTRIBUTIONDROP = "SexDistributions.txt"; public static final String DOSAGEUNITSDROP = "DoseUnits.txt"; public static final String ADMINISTRATIVEROUTEDROP = "AdministrativeRoutes.txt"; public static final String AGEUNITSDROP = "AgeUnits.txt"; public static final String PUBDROP = "PublicationStatus.txt"; public static final String TOXICITYGRADESDROP = "ToxicityGrades.txt"; public static final String CLINICALMARKERSDROP = "ClinicalMarkers.txt"; public static final String HOSTSPECIESDROP = "HostSpecies.txt"; // Various Dose Units public static final String CHEMTHERAPYDOSEUNITSDROP = "ChemTherapyDoseUnits.txt"; public static final String ENVFACTORUNITSDROP = "EnvFactorUnits.txt"; public static final String GENOMESEGSIZEUNITSDROP = "GenomeSegSizeUnits.txt"; public static final String HISTOPATHVOLUMEUNITSDROP = "HistopathVolumeUnits.txt"; public static final String HISTOPATHWEIGHTUNITSDROP = "HistopathWeightUnits.txt"; public static final String HORMONEUNITSDROP = "HormoneUnits.txt"; public static final String NUTFACTORUNITSDROP = "NutFactorUnits.txt"; public static final String RADIATIONUNITSDROP = "RadiationUnits.txt"; public static final String VIRALTREATUNITSDROP = "ViralTreatUnits.txt"; public static final String TARGETEDMODIFICATIONDROP = "TargetedModificationTypes.txt"; public static final String GENOMICSEGMENTDROP = "SegmentTypes.txt"; public static final String GROWTHFACTORDOSEUNITSDROP = "GrowthFactorDoseUnits.txt"; public static final String STAININGDROP = "Staining.txt"; // Specific to a single screen public static final String CHEMICALDRUGDROP = "chemdrugdrop.db"; public static final String ENVIRONFACTORDROP = "envfactordrop.db"; public static final String GROWTHFACTORDROP = "growfactordrop.db"; public static final String HORMONEDROP = "hormonedrop.db"; public static final String NUTRITIONFACTORDROP = "nutritionfactordrop.db"; public static final String RADIATIONDROP = "radiationdrop.db"; public static final String SURGERYDROP = "surgerydrop.db"; public static final String VIRUSDROP = "virusdrop.db"; public static final String VIRALVECTORDROP = "ViralVectors.txt"; public static final String GRAFTTYPEDROP = "GraftTypes.txt"; public static final String XENOGRAFTADMINSITESDROP = "XenograftAdministrativeSites.txt"; public static final String PRINCIPALINVESTIGATORDROP = "principalinvestigatordrop.db"; public static final String INDUCEDMUTATIONDROP = "InducedMutations.txt"; public static final String EXPRESSIONLEVEL = "expressionlevel.db"; // Query dropdowns public static final String CHEMICALDRUGQUERYDROP = "chemdrugquerydrop.db"; public static final String GROWTHFACTORQUERYDROP = "growfactorquerydrop.db"; public static final String HORMONEQUERYDROP = "hormonequerydrop.db"; public static final String RADIATIONQUERYDROP = "radiationquerydrop.db"; public static final String VIRUSQUERYDROP = "virusquerydrop.db"; public static final String SURGERYQUERYDROP = "surgeryquerydrop.db"; public static final String SPECIESQUERYDROP = "speciesquerydrop.db"; public static final String PRINCIPALINVESTIGATORQUERYDROP = "principalinvestigatorquerydrop.db"; public static final String INDUCEDMUTATIONAGENTQUERYDROP = "inducedmutationagentquerydrop.db"; // These two are used to display the species and strain currently in the // AnimalModelCharacteristics public static final String MODELSPECIES = "modelspecies"; public static final String MODELSTRAIN = "modelstrain"; public static final String CHEMICALCLASSESDROP = "ChemicalClasses.txt"; public static final String BIOLOGICALPROCESSDROP = "BiologicalProcess.txt"; public static final String THERAPEUTICTARGETSDROP = "TherapeuticTargets.txt"; // Used for user management public static final String USERSDROP = "users.db"; // Used for curation public static final String CURATIONSTATESDROP = "curationstates.db"; // Used for curation public static final String USERSFORROLEDROP = "usersforrole.db"; // Used for role assignment public static final String ROLESDROP = "roles.db"; } /** * Defines the global constants used as parameters for ftp requests */ public interface CaImage { public static final String FTPSERVER = "caimage.ftp.server"; public static final String FTPUSERNAME = "caimage.ftp.username"; public static final String FTPPASSWORD = "caimage.ftp.password"; public static final String FTPMODELSTORAGEDIRECTORY = "caimage.ftp.modelstoragedirectory"; public static final String FTPGENCONSTORAGEDIRECTORY = "caimage.ftp.genconstoragedirectory"; public static final String CAIMAGEMODELSERVERVIEW = "caimage.modelview.uri"; public static final String CAIMAGEGENCONSERVERVIEW = "caimage.modelview.uri"; public static final String CAIMAGESIDTHUMBVIEW = "caimage.sidthumbview.uri"; public static final String CAIMAGESIDVIEWURISTART = "caimage.sidview.uri_start"; public static final String CAIMAGESIDVIEWURIEND = "caimage.sidview.uri_end"; public static final String CAIMAGEWINDOWSTART = "caimage.window.start"; public static final String CAIMAGEWINDOWEND = "caimage.window.end"; public static final String CAIMAGEMODEL = "caimage.model"; public static final String CAIMAGEGENCON = "caimage.gencon"; public static final String LEGACYJSP = "catalogviewtumors.jsp?"; public static final String FILESEP = ";"; public static final String IMGTAG = "img="; } /** * Defines the global constants used as parameters to requests */ public interface Parameters { public static final String ACTION = "action"; public static final String MODELID = "aModelID"; public static final String PERSONID = "aPersonID"; public static final String MODELSECTIONNAME = "aModelSectionName"; public static final String MODELSECTIONVALUE = "modelSectionValue"; public static final String COMMENTSID = "aCommentsID"; public static final String COMMENTSLIST = "aCommentsList"; public static final String TOCQUERYKEY = "aTOCQueryKey"; public static final String EVENT = "aEvent"; public static final String DELETED = "deleted"; } public interface Pages { public static final String MODEL_CHARACTERISTICS = "General Information Page"; public static final String CARCINOGENIC_INTERVENTION = "Carcinogenic Interventions Page"; public static final String PUBLICATIONS = "Publications page"; public static final String HISTOPATHOLOGY = "Histopathology Page"; public static final String THERAPEUTIC_APPROACHES = "Therapeutic Approaches Page"; public static final String CELL_LINES = "Cell Lines Page"; public static final String IMAGES = "Images Page"; public static final String MICROARRAY = "Microarray Page"; public static final String GENETIC_DESCRIPTION = "Genetic Description Page"; public static final String XENOGRAFT = "Xenograft Page"; } /** * Used to determine the current model to edit on submission/edit also used * to display the name of the model and it's current status */ public static final String MODELID = "modelid"; public static final String MODELDESCRIPTOR = "modeldescriptor"; public static final String MODELSTATUS = "modelstatus"; /** * Used to prepopulate forms */ public static final String FORMDATA = "formdata"; public static final String ANIMALMODEL = "animalmodel"; public static final String XENOGRAFTMODEL = "xenograftmodel"; public static final String XENOGRAFTRESULTLIST = "xenograftresultlist"; /** * Used to store username for current user */ public static final String CURRENTUSER = "camod.loggedon.username"; public static final String CURRENTUSERROLES = "camod.loggedon.userroles"; public static final String LOGINFAILED = "loginfailed"; /** * Used for search results */ public static final String SEARCH_RESULTS = "searchResults"; public static final String ADMIN_COMMENTS_SEARCH_RESULTS = "adminCommentsSearchResults"; public static final String ADMIN_MODEL_SEARCH_RESULTS = "adminModelSearchResults"; public static final String ADMIN_ROLES_SEARCH_RESULTS = "adminRolesSearchResults"; public static final String TRANSGENE_COLL = "transgeneColl"; public static final String GENOMIC_SEG_COLL = "genomicSegColl"; public static final String TARGETED_MOD_COLL = "targetedModColl"; public static final String TARGETED_MOD_GENE_MAP = "targetedModGeneMap"; public static final String INDUCED_MUT_COLL = "inducedMutColl"; public static final String TRANSGENE_CNT = "transgeneCnt"; public static final String GENOMIC_SEG_CNT = "genomicSegCnt"; public static final String TARGETED_MOD_CNT = "targetedModCnt"; public static final String INDUCED_MUT_CNT = "inducedMutCnt"; public static final String THERAPEUTIC_APPROACHES_COLL = "therapeuticApproachesColl"; public static final String CLINICAL_PROTOCOLS = "clinProtocols"; public static final String YEAST_DATA = "yeastData"; public static final String INVIVO_DATA = "invivoData"; public static final String PRECLINICAL_MODELS = "preClinicalModels"; public static final String PUBLICATIONS = "publications"; public static final String CARCINOGENIC_INTERVENTIONS_COLL = "carcinogenicInterventionColl"; public static final String DRUG_SCREEN_OPTIONS = "drugScreenSearchOptions"; public static final String NSC_NUMBER = "nsc"; // Submission specific constants public interface Submit { /** * Used to store required lists for the cardiogentic intervention * section of the sidebar menu of the submission section */ public static final String CHEMICALDRUG_LIST = "chemicaldrug_list"; public static final String ENVIRONMENTALFACTOR_LIST = "environmentalfactor_list"; public static final String GENEDELIVERY_LIST = "genedelivery_list"; public static final String GROWTHFACTORS_LIST = "growthfactors_list"; public static final String HORMONE_LIST = "hormone_list"; public static final String NUTRITIONALFACTORS_LIST = "nutritionalfactors_list"; public static final String RADIATION_LIST = "radiation_list"; public static final String SURGERYOTHER_LIST = "surgeryother_list"; public static final String VIRALTREATMENT_LIST = "viraltreatment_list"; public static final String XENOGRAFT_LIST = "xenograft_list"; public static final String SPONTANEOUSMUTATION_LIST = "spontaneousmutation_list"; public static final String INDUCEDMUTATION_LIST = "inducedmutation_list"; public static final String TARGETEDMODIFICATION_LIST = "targetedmodification_list"; public static final String GENOMICSEGMENT_LIST = "genomicsegment_list"; public static final String HISTOPATHOLOGY_LIST = "histopathology_list"; public static final String ASSOCMETASTSIS_LIST = "associatedmetastatis_list"; public static final String ENGINEEREDTRANSGENE_LIST = "engineeredtransgene_list"; public static final String THERAPY_LIST = "therapy_list"; public static final String CLINICALMARKER_LIST = "clinicalmarker_list"; public static final String IMAGE_LIST = "image_list"; public static final String ASSOCIATEDEXPRESSION_LIST = "associatedexpression_list"; /** * Used to store a list of names for the Publication section of the * sidebar menu of the submission section */ public static final String PUBLICATION_LIST = "publication_list"; /** * Used to store a list of names for the Cell Line section of the * sidebar menu of the submission section */ public static final String CELLLINE_LIST = "cellline_list"; public static final String ANIMALAVAILABILITY_LIST = "availability_list"; /** * Used to store animal model availability for the Model Availability section of the * sidebar menu of the submission section */ public static final String INVESTIGATOR_LIST = "investigator_list"; public static final String JACKSONLAB_LIST = "jacksonlab_list"; public static final String MMHCC_LIST = "mmhcc_list"; public static final String IMSR_LIST = "imsr_list"; } // Admin specific constants public interface Admin { /** * Defines the different roles in the system */ public interface Roles { /** * A constant that defines the submitter role */ public static final String ALL = "All"; /** * A constant that defines the submitter role */ public static final String SUBMITTER = "Public Submitter"; /** * A constant that defines the coordinator role */ public static final String COORDINATOR = "MMHCC Coordinator"; /** * A constant that defines the Editor role */ public static final String EDITOR = "MMHCC Editor"; /** * A constant that defines the screener role */ public static final String SCREENER = "MMHCC Screener"; } /** * Defines the different roles in the system */ public interface Actions { /** * A constant that defines the text for the generic approved action */ public static final String APPROVE = "approve"; /** * A constant that defines the text for the assign editor action */ public static final String ASSIGN_EDITOR = "assign_editor"; /** * A constant that defines the text for the assign screener action */ public static final String ASSIGN_SCREENER = "assign_screener"; /** * A constant that defines the text for the need more information * action */ public static final String NEED_MORE_INFO = "need_more_info"; /** * A constant that defines the text for the generic reject action */ public static final String REJECT = "reject"; /** * A constant that defines the text for the complete */ public static final String COMPLETE = "complete"; } /** * A constant that defines string used as a variable name in e-mail */ public static final String INDUCED_MUTATION_AGENT_NAME = "inducedmutationagentname"; /** * A constant that defines string used as a variable name in e-mail */ public static final String INDUCED_MUTATION_AGENT_TYPE = "inducedmutationagenttype"; /** * A constant that defines string used as key for e-mail content * associated with induced mutation agent additions */ public static final String INDUCED_MUTATION_AGENT_ADDED = "inducedmutationagentadded"; /** * A constant that defines string used as a variable name in e-mail */ public static final String TARGETED_MODIFICATION_NAME = "targetedmodificationname"; /** * A constant that defines string used as a variable name in e-mail */ public static final String TARGETED_MODIFICATION_TYPE = "targetedmodificationtype"; /** * A constant that defines string used as key for e-mail content * associated with targeted modification additions */ public static final String TARGETED_MODIFICATION_ADDED = "targetedmodificationadded"; /** * A constant that defines string used as key for e-mail content * associated with non-controlled vocabulary use */ public static final String NONCONTROLLED_VOCABULARY = "noncontrolledvocab"; /** * A constant that defines what file is used for the model curation * process */ public static final String MODEL_CURATION_WORKFLOW = "config/CurationConfig.xml"; /** * A constant that defines what file is used for the comment curation * process */ public static final String COMMENT_CURATION_WORKFLOW = "config/CommentCurationConfig.xml"; /** * Used to set/pull the objects needing to be reviewed out of the * request */ public static final String COMMENTS_NEEDING_REVIEW = "commentsNeedingReview"; /** * Used to set/pull the objects needing to be reviewed out of the * request */ public static final String COMMENTS_NEEDING_ASSIGNMENT = "commentsNeedingAssignment"; /** Used to set/pull the objects needing to be edited out of the request */ public static final String MODELS_NEEDING_EDITING = "modelsNeedingEditing"; /** * Used to set/pull the objects needing to be assigned an editor out of * the request */ public static final String MODELS_NEEDING_EDITOR_ASSIGNMENT = "modelsNeedingEditorAssignment"; /** Used to set/pull the objects needing to be edited out of the request */ public static final String MODELS_NEEDING_MORE_INFO = "modelsNeedingMoreInfo"; /** * Used to set/pull the objects needing to be screened out of the * request */ public static final String MODELS_NEEDING_SCREENING = "modelsNeedingScreening"; /** * Used to set/pull the objects needing to be assigned a screener out of * the request */ public static final String MODELS_NEEDING_SCREENER_ASSIGNMENT = "modelsNeedingScreenerAssignment"; } public interface EmailMessage { public static final String SENDER = "email.sender"; public static final String RECIPIENTS = "email.recipients"; public static final String FROM = "email.from"; public static final String MESSAGE = "email.message"; public static final String SUBJECT = "email.subject"; } /** * * Constants used for fetching EVS data * */ public interface Evs { /** * The namespace to fetch the concepts from */ public static final String NAMESPACE = "NCI_Thesaurus"; /** * The tag used to get the display name */ public static final String DISPLAY_NAME_TAG = "Display_Name"; /** * The key for the URI in the camod.properties file */ public static final String URI_KEY = "evs.uri"; } }
package implementation; import java.util.Stack; /** * @author by Group4 on 2017-01-27. */ public class PhaseOneImpl implements PhaseOne { private int POSITION = 0; private int IS_EMPTY_COUNTER = 0; public int[] carStatus = {POSITION, IS_EMPTY_COUNTER}; private Stack<Integer> parkingPlaces = new Stack<>(); public boolean isParked = false; public int[] moveForward() { if (whereIs() < 500 && !isParked) { // Added so that it doesn't move past 500 carStatus[0] += 1; // Increments the position of the car if (isEmpty() == 1) { carStatus[1]++; if (carStatus[1] == 5) parkingPlaces.push(whereIs()); } } return carStatus; // Return the status of the car } public int[] moveBackward() { if (whereIs() > 0 && !isParked) { // Added so that it doesn't move past 0 carStatus[0] -= 1; // Decrements the position of the car if (isEmpty() == 1) { carStatus[1]++; } } return carStatus; // Return the status of the car } public void park() { int i = whereIs(); // Initialize basic counter if (!parkingPlaces.empty()) { if (whereIs() == parkingPlaces.peek()) { isParked = true; // Set the parking state of the car to parked (true) } else { do { // Do While loop for iterating 500 times or until 5 consecutive free spaces are registered moveForward(); // Move the car 1 meter and returns the status of the car if (carStatus[1] == 5) { // Check if there is enough spaces (5) to park the car or not isParked = true; // Set the parking state of the car to parked (true) carStatus[1] = 0; // Reset the IS_EMPTY_COUNTER of the car } i++; } while (i < 500 && !isParked); } } else { do { // Do While loop for iterating 500 times or until 5 consecutive free spaces are registered moveForward(); // Move the car 1 meter and returns the status of the car if (carStatus[1] == 5) { // Check if there is enough spaces (5) to park the car or not isParked = true; // Set the parking state of the car to parked (true) carStatus[1] = 0; // Reset the IS_EMPTY_COUNTER of the car } i++; } while (i < 500 && !isParked); } } public void unPark() { if (isParked) { isParked = false; if (whereIs() != 500) carStatus[0] += 1; } } public int whereIs() { return carStatus[0]; // Return the position of the car } public int isEmpty() { // return (int) (Math.random() * 2); // return 0; // Returns the integer o int i = whereIs(); // Store the position of the car if ((i > 495 && i < 501) || (i > 30 && i < 36)) { // Hard coded "empty" space 31 - 35 return 1; // 1 == empty } return 0; // 0 != empty } }
package infn.bed.view.plot; import java.awt.Color; import java.util.Collection; import cnuphys.bCNU.view.PlotView; import cnuphys.splot.fit.FitType; import cnuphys.splot.pdata.DataColumn; import cnuphys.splot.pdata.DataColumnType; import cnuphys.splot.pdata.DataSet; import cnuphys.splot.plot.HorizontalLine; import cnuphys.splot.plot.PlotParameters; import cnuphys.splot.plot.VerticalLine; import cnuphys.splot.style.SymbolType; /** * Plots ADC (analog-to-digital converter) and TDC (time-to-digital converter) waveforms. * * @author Andy Beiter * @author Angelo Licastro */ @SuppressWarnings("serial") public class WavePlot extends PlotView { /** * The constructor. */ public WavePlot() { super(); } /** * Returns the column names for the plot. * * @return names An array of column names for the plot. */ public static String[] getColumnNames() { return new String[]{"X", "Y"}; } /** * Returns the y-axis label for the plot. * * @return The y-axis label for the plot. */ private String getYAxisLabel() { return "ADC"; } /** * Returns the x-axis label for the plot. * * @return The x-axis label for the plot. */ private String getXAxisLabel() { return "TDC"; } /** * Sets the preferences for the plot. * * @param isLeft true if the left PMT (photomultiplier tube) is sampling, false otherwise. */ private void setPreferences(boolean isLeft) { Color fillColor = new Color(255, 0, 0, 96); DataSet dataSet = _plotCanvas.getDataSet(); Collection<DataColumn> yDataColumns = dataSet.getAllColumnsByType(DataColumnType.Y); for (DataColumn dataColumn : yDataColumns) { dataColumn.getFit().setFitType(FitType.CONNECT); dataColumn.getStyle().setSymbolType(SymbolType.CIRCLE); dataColumn.getStyle().setSymbolSize(4); dataColumn.getStyle().setFillColor(fillColor); dataColumn.getStyle().setLineColor(Color.black); } PlotParameters plotParameters = _plotCanvas.getParameters(); plotParameters.mustIncludeXZero(true); plotParameters.mustIncludeYZero(true); plotParameters.addPlotLine(new HorizontalLine(_plotCanvas, 0)); plotParameters.addPlotLine(new VerticalLine(_plotCanvas, 0)); plotParameters.setXLabel(getXAxisLabel()); plotParameters.setYLabel(getYAxisLabel()); if (isLeft) { plotParameters.setPlotTitle("ADC Left"); } else { plotParameters.setPlotTitle("ADC Right"); } } /** * Sets the data set for the plot and calls setPreferences(). * * @param dataSet The data set for the plot. * @param isLeft true if the left PMT (photomultiplier tube) is sampling, false otherwise. */ public void addData(DataSet dataSet, boolean isLeft) { this._plotCanvas.setDataSet(dataSet); setPreferences(isLeft); } }
package io.socket; /** * The Class SocketIOException. */ public class SocketIOException extends Exception { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 4965561569568761814L; /** * Instantiates a new SocketIOException. * * @param message * the message */ public SocketIOException(String message) { super(message); } /** * Instantiates a new SocketIOException. * * @param ex * the exception. */ public SocketIOException(String message, Exception ex) { super(message, ex); } }
package jade.gui; //#J2ME_EXCLUDE_FILE import javax.swing.JPanel; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.BoxLayout; import javax.swing.BorderFactory; import java.awt.Dimension; import java.util.Iterator; import java.awt.GridBagLayout; import java.awt.GridBagConstraints; import jade.domain.FIPAAgentManagement.APDescription; import jade.domain.FIPAAgentManagement.APService; import javax.swing.JCheckBox; import java.awt.Frame; import javax.swing.JDialog; import javax.swing.JButton; import java.awt.BorderLayout; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.Component; /** This class permits to show the APDescription of a platform. @author Tiziana Trucco - CSELT S.p.A @version $Date$ $Revision$ **/ public class APDescriptionPanel extends JPanel { private JTextField platformName_Field; private VisualAPServiceList MTPs_List; /** creates a panel ho show an APDescription. All the fields are not editable. */ public APDescriptionPanel(Component owner){ super(); GridBagLayout gridBag = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.HORIZONTAL; c.anchor = GridBagConstraints.SOUTH; setLayout(gridBag); JLabel label = new JLabel("AgentPlatform Description"); c.weightx = 0.5; c.ipadx = 15; c.ipady = 20; c.gridx = 0; c.gridy = 0; c.gridwidth = 2; gridBag.setConstraints(label,c); add(label); label = new JLabel("Platform Name: "); c.ipady = 0; c.gridx = 0; c.gridy = 1; c.gridwidth = 1; gridBag.setConstraints(label,c); add(label); platformName_Field = new JTextField(); platformName_Field.setEditable(false); platformName_Field.setBackground(java.awt.Color.white); c.ipadx = 30; c.gridx = 1; c.gridy = 1; gridBag.setConstraints(platformName_Field,c); add(platformName_Field); JPanel profilePanel = new JPanel(); profilePanel.setLayout(new BoxLayout(profilePanel,BoxLayout.Y_AXIS)); profilePanel.setBorder(BorderFactory.createTitledBorder("AP Services")); MTPs_List = new VisualAPServiceList((new java.util.ArrayList()).iterator(), owner); c.gridx = 0; c.gridy = 4; c.gridwidth = 2; gridBag.setConstraints(profilePanel,c); MTPs_List.setEnabled(false); MTPs_List.setDimension(new Dimension(250,50)); profilePanel.add(MTPs_List); add(profilePanel); } /** To set the field with the valued of a given APDescription. */ public void setAPDescription(APDescription desc){ try{ platformName_Field.setText(desc.getName()); MTPs_List.resetContent(desc.getAllAPServices()); }catch(Exception e){e.printStackTrace();} } /** To show an APDescription in a JDialog */ public static void showAPDescriptionInDialog(APDescription desc, Frame parent,String title) { final JDialog tempDlg = new JDialog(parent, title, true); APDescriptionPanel AP_Panel = new APDescriptionPanel(tempDlg); AP_Panel.setAPDescription(desc); JButton okButton = new JButton("OK"); JPanel buttonPanel = new JPanel(); // Use default (FlowLayout) layout manager to dispose the OK button buttonPanel.add(okButton); tempDlg.getContentPane().setLayout(new BorderLayout()); tempDlg.getContentPane().add("Center", AP_Panel); tempDlg.getContentPane().add("South", buttonPanel); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { tempDlg.dispose(); } } ); tempDlg.pack(); tempDlg.setResizable(false); if (parent != null) { int locx = parent.getX() + (parent.getWidth() - tempDlg.getWidth()) / 2; if (locx < 0) locx = 0; int locy = parent.getY() + (parent.getHeight() - tempDlg.getHeight()) / 2; if (locy < 0) locy = 0; tempDlg.setLocation(locx,locy); } tempDlg.show(); } }
// BUI - a user interface library for the JME 3D engine // 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.jmex.bui; import java.util.ArrayList; import com.jme.renderer.Renderer; import com.jmex.bui.background.BBackground; import com.jmex.bui.event.ActionEvent; import com.jmex.bui.event.BEvent; import com.jmex.bui.event.MouseEvent; import com.jmex.bui.icon.BIcon; import com.jmex.bui.util.Dimension; import com.jmex.bui.util.Insets; /** * Displays a selected value and allows that value to be changed by selecting from a popup menu. */ public class BComboBox extends BLabel { /** Used for displaying a label that is associated with a particular non-displayable value. */ public static class Item { public Object value; public Item (Object value, String label) { this.value = value; _label = label; } public String toString () { return _label; } protected String _label; } /** * Creates an empty combo box. */ public BComboBox () { super(""); setFit(Fit.TRUNCATE); } /** * Creates a combo box with the supplied set of items. The result of {@link Object#toString} * for each item will be displayed in the list. */ public BComboBox (Object[] items) { super(""); setItems(items); } /** * Creates a combo box with the supplied set of items. The result of {@link Object#toString} * for each item will be displayed in the list. */ public BComboBox (Iterable<?> items) { super(""); setItems(items); } /** * Appends an item to our list of items. The result of {@link Object#toString} for the item * will be displayed in the list. */ public void addItem (Object item) { addItem(_items.size(), item); } /** * Inserts an item into our list of items at the specified position (zero being before all * other items and so forth). The result of {@link Object#toString} for the item will be * displayed in the list. */ public void addItem (int index, Object item) { _items.add(index, new ComboMenuItem(item)); clearCache(); } /** * Replaces any existing items in this combo box with the supplied items. */ public void setItems (Iterable<?> items) { clearItems(); for (Object item : items) { addItem(item); } } /** * Replaces any existing items in this combo box with the supplied items. */ public void setItems (Object[] items) { clearItems(); for (int ii = 0; ii < items.length; ii++) { addItem(items[ii]); } } /** * Returns the index of the selected item or -1 if no item is selected. */ public int getSelectedIndex () { return _selidx; } /** * Returns the selected item or null if no item is selected. */ public Object getSelectedItem () { return _selidx == -1 ? null : _items.get(_selidx).item; } /** * Requires that the combo box be configured with {@link Item} items, returns the @{link * Item#value} of the currently selected item. */ public Object getSelectedValue () { return (_selidx == -1) ? null : ((Item)_items.get(_selidx).item).value; } /** * Selects the item with the specified index. */ public void selectItem (int index) { selectItem(index, 0L, 0); } /** * Selects the item with the specified index. <em>Note:</em> the supplied item is compared with * the item list using {@link Object#equals}. */ public void selectItem (Object item) { int selidx = -1; for (int ii = 0, ll = _items.size(); ii < ll; ii++) { ComboMenuItem mitem = _items.get(ii); if (mitem.item.equals(item)) { selidx = ii; break; } } selectItem(selidx); } /** * Returns the number of items in this combo box. */ public int getItemCount () { return _items.size(); } /** * Removes all items from this combo box. */ public void clearItems () { clearCache(); _items.clear(); _selidx = -1; } @Override // from BComponent public boolean dispatchEvent (BEvent event) { if (event instanceof MouseEvent && isEnabled()) { MouseEvent mev = (MouseEvent)event; switch (mev.getType()) { case MouseEvent.MOUSE_PRESSED: if (_menu == null) { _menu = new ComboPopupMenu(); } _menu.popup(getAbsoluteX(), getAbsoluteY(), false); break; case MouseEvent.MOUSE_RELEASED: break; default: return super.dispatchEvent(event); } return true; } return super.dispatchEvent(event); } @Override // from BComponent protected String getDefaultStyleClass () { return "combobox"; } @Override // from BComponent protected Dimension computePreferredSize (int whint, int hhint) { // our preferred size is based on the widest of our items; computing this is rather // expensive, so we cache it like we do the menu if (_psize == null || _phint.width != whint || _phint.height != hhint) { _phint.width = whint; _phint.height = hhint; _psize = new Dimension(); Label label = new Label(this); for (ComboMenuItem mitem : _items) { if (mitem.item instanceof BIcon) { label.setIcon((BIcon)mitem.item); } else { label.setText(mitem.item == null ? "" : mitem.item.toString()); } Dimension lsize = label.computePreferredSize(whint, hhint); _psize.width = Math.max(_psize.width, lsize.width); _psize.height = Math.max(_psize.height, lsize.height); } } return new Dimension(_psize); } protected void selectItem (int index, long when, int modifiers) { if (_selidx == index) { return; } _selidx = index; Object item = getSelectedItem(); if (item instanceof BIcon) { setIcon((BIcon)item); } else { setText(item == null ? "" : item.toString()); } emitEvent(new ActionEvent(this, when, modifiers, "selectionChanged")); } protected void clearCache () { if (_menu != null) { _menu.removeAll(); _menu = null; } _psize = null; } protected class ComboPopupMenu extends BPopupMenu { public ComboPopupMenu () { super(BComboBox.this.getWindow()); for (int ii = 0; ii < _items.size(); ii++) { addMenuItem(_items.get(ii)); } } protected void itemSelected (BMenuItem item, long when, int modifiers) { selectItem(_items.indexOf(item), when, modifiers); dismiss(); } protected Dimension computePreferredSize (int whint, int hhint) { // prefer a size that is at least as wide as the combobox from which we will popup Dimension d = super.computePreferredSize(whint, hhint); d.width = Math.max(d.width, BComboBox.this.getWidth() - getInsets().getHorizontal()); return d; } }; protected class ComboMenuItem extends BMenuItem { public Object item; public ComboMenuItem (Object item) { super(null, null, "select"); if (item instanceof BIcon) { setIcon((BIcon)item); } else { setText(item.toString()); } this.item = item; } } /** The index of the currently selected item. */ protected int _selidx = -1; /** The list of items in this combo box. */ protected ArrayList<ComboMenuItem> _items = new ArrayList<ComboMenuItem>(); /** A cached popup menu containing our items. */ protected ComboPopupMenu _menu; /** Our cached preferred size. */ protected Dimension _psize; /** The hints provided for our cached preferred size. */ protected Dimension _phint = new Dimension(); }
// BUI - a user interface library for the JME 3D engine // 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.jmex.bui; import java.util.ArrayList; import java.util.logging.Level; import com.jme.intersection.CollisionResults; import com.jme.intersection.PickResults; import com.jme.math.Ray; import com.jme.renderer.Renderer; import com.jme.scene.Geometry; import com.jme.scene.Spatial; import com.jmex.bui.Log; import com.jmex.bui.event.FocusEvent; import com.jmex.bui.event.MouseEvent; /** * Connects the BUI system into the JME scene graph. */ public abstract class BRootNode extends Geometry { public BRootNode () { super("BUI Root Node"); // we need to render in the ortho queue setRenderQueueMode(Renderer.QUEUE_ORTHO); } /** * Registers a top-level window with the input system. */ public void addWindow (BWindow window) { _windows.add(window); window.setRootNode(this); // if this window is modal, make it the default event target if (window.isModal()) { pushDefaultEventTarget(window); } // recompute the hover component; the window may be under the mouse computeHoverComponent(_mouseX, _mouseY); } /** * Removes a window from participation in the input system. */ public void removeWindow (BWindow window) { // if our focus is in this window, clear it if (_focus != null && _focus.getWindow() == window) { setFocus(null); } // first remove the window from our list if (!_windows.remove(window)) { Log.log.warning("Requested to remove unmanaged window " + "[window=" + window + "]."); Thread.dumpStack(); return; } // if the window is modal, pop the default event target if (window.isModal()) { popDefaultEventTarget(window); } // then remove the hover component (which may result in a mouse // exited even being dispatched to the window or one of its // children) computeHoverComponent(_mouseX, _mouseY); // finally remove the window from the interface heirarchy window.setRootNode(null); } /** * This is called by a window or a scroll pane when it has become invalid. * The root node should schedule a revalidation of this component on the * next tick or the next time an event is processed. */ public abstract void rootInvalidated (BComponent root); /** * Configures a component (which would generally not be part of a * normal interface hierarchy) to receive all events that are not sent * to some other component. */ public void pushDefaultEventTarget (BComponent component) { if (_dcomponent != null) { _defaults.add(0, _dcomponent); } _dcomponent = component; } /** * Pops the default event target off the stack. */ public void popDefaultEventTarget (BComponent component) { if (_dcomponent == component) { if (_defaults.size() > 0) { _dcomponent = (BComponent)_defaults.remove(0); } else { _dcomponent = null; } } else { _defaults.remove(component); } } /** * Requests that the specified component be given the input focus. * Pass null to clear the focus. */ public void requestFocus (BComponent component) { setFocus(component); } /** * Generates a string representation of this instance. */ public String toString () { return "BRootNode@" + hashCode(); } // documentation inherited public void onDraw (Renderer renderer) { // we're rendered in the ortho queue, so we just add ourselves to // the queue here and we'll get a call directly to draw() later // when the ortho queue is rendered if (!renderer.isProcessingQueue()) { renderer.checkAndAdd(this); } } // documentation inherited public void draw (Renderer renderer) { super.draw(renderer); // render all of our windows for (int ii = 0, ll = _windows.size(); ii < ll; ii++) { BWindow win = (BWindow)_windows.get(ii); try { win.render(renderer); } catch (Throwable t) { Log.log.log(Level.WARNING, win + " failed in render()", t); } } } // documentation inherited public void findCollisions (Spatial scene, CollisionResults results) { // nothing doing } // documentation inherited public boolean hasCollision (Spatial scene, boolean checkTriangles) { return false; // nothing doing } /** * Configures the component that has keyboard focus. */ protected void setFocus (BComponent focus) { // allow the component we clicked on to adjust the focus target if (focus != null) { focus = focus.getFocusTarget(); } // if the focus is changing, dispatch an event to report it if (_focus != focus) { if (_focus != null) { _focus.dispatchEvent( new FocusEvent(this, _tickStamp, FocusEvent.FOCUS_LOST)); } _focus = focus; if (_focus != null) { _focus.dispatchEvent( new FocusEvent(this, _tickStamp, FocusEvent.FOCUS_GAINED)); } } } /** * Recomputes the component over which the mouse is hovering, * generating mouse exit and entry events as necessary. */ protected void computeHoverComponent (int mx, int my) { // check for a new hover component starting with each of our root // components BComponent nhcomponent = null; for (int ii = _windows.size()-1; ii >= 0; ii BWindow comp = (BWindow)_windows.get(ii); nhcomponent = comp.getHitComponent(mx, my); if (nhcomponent != null) { break; } // if this window is modal, stop here if (comp.isModal()) { break; } } // generate any necessary mouse entry or exit events if (_hcomponent != nhcomponent) { // inform the previous component that the mouse has exited if (_hcomponent != null) { _hcomponent.dispatchEvent( new MouseEvent(this, _tickStamp, _modifiers, MouseEvent.MOUSE_EXITED, mx, my)); } // inform the new component that the mouse has entered if (nhcomponent != null) { nhcomponent.dispatchEvent( new MouseEvent(this, _tickStamp, _modifiers, MouseEvent.MOUSE_ENTERED, mx, my)); } _hcomponent = nhcomponent; } } protected long _tickStamp; protected int _modifiers; protected int _mouseX, _mouseY; protected ArrayList _windows = new ArrayList(); protected BComponent _hcomponent, _ccomponent; protected BComponent _dcomponent, _focus; protected ArrayList _defaults = new ArrayList(); }
package org.sqsh.commands; import java.util.Arrays; import org.sqsh.ColumnDescription; import org.sqsh.Command; import org.sqsh.HelpTopic; import org.sqsh.Renderer; import org.sqsh.Session; import org.sqsh.SqshOptions; import org.sqsh.Variable; /** * Implements the 'help' command. */ public class Help extends Command { @Override public int execute (Session session, SqshOptions options) throws Exception { int nArgs = options.arguments.size(); if (nArgs > 1) { session.err.println("use: help [command]"); return 1; } if (nArgs == 0) { displayHelpCategories(session); return 0; } String word = options.arguments.get(0); int rc = 0; if (word.equals("topics")) { displayTopics(session); } else if (word.equals("vars")) { displayVariables(session); } else if (word.equals("commands")) { displayCommands(session); } else { rc = displayHelpText(session, word); } return rc; } /** * Looks up a specific help topic and displays it. * * @param session The session to use for display. * @param word The topic to look for. * @return 0 if the topic was found and displayed, 1 otherwise. */ private int displayHelpText(Session session, String word) { int rc = 0; HelpTopic topic = (HelpTopic) session.getCommandManager().getCommand(word); /* * If we fail to find the command the user asked for it * *could* be because the shell interpreted the back slash * in front of the command name, so will will append one * and try again. */ if (topic == null) { topic = (HelpTopic) session.getCommandManager().getCommand('\\' + word); } /* * If we fail that, try to see if it is a variable that * we are talking about. */ if (topic == null) { topic = (HelpTopic) session.getVariableManager().getVariable(word); if (topic != null && topic.getDescription() == null) { topic = null; } } /* * If we're still null, then we'll check to see if it is * a general topic that is being requested. */ if (topic == null) { topic = session.getHelpManager().getTopic(word); } /* * At this point we're S.O.L. */ if (topic == null) { session.err.println("No such command or topic '" + word + "'"); rc = 1; } else { session.out.println(topic.getHelp()); } return rc; } /** * Displays available help categories. * * @param session The session to be used for displaying. */ private void displayHelpCategories(Session session) { session.out.println("Available help categories. Use " + "\"\\help <category>\" to display topics within that category"); ColumnDescription []columns = new ColumnDescription[2]; columns[0] = new ColumnDescription("Category", -1); columns[1] = new ColumnDescription("Description", -1); Renderer renderer = session.getRendererManager().getCommandRenderer(session); renderer.header(columns); renderer.row( new String[] { "commands", "Help on all avaiable commands" }); renderer.row( new String[] { "vars", "Help on all avaiable configuration variables" }); renderer.row( new String[] { "topics", "General help topics for jsqsh" }); renderer.flush(); } /** * Displays available commands. * * @param session The session to be used for displaying. */ private void displayCommands(Session session) { session.out.println("Available commands. " + "Use \"\\help <command>\"" + " to display detailed help for a given command"); Renderer renderer = session.getRendererManager().getCommandRenderer(session); Command []commands = session.getCommandManager().getCommands(); Arrays.sort(commands); ColumnDescription []columns = new ColumnDescription[2]; columns[0] = new ColumnDescription("Command", -1); columns[1] = new ColumnDescription("Description", -1); renderer.header(columns); for (int i = 0; i < commands.length; i++) { String []row = new String[2]; row[0] = commands[i].getName(); row[1] = commands[i].getDescription(); renderer.row(row); } renderer.flush(); } /** * Displays available variables. * * @param session The session to be used for displaying. */ private void displayVariables(Session session) { session.out.println("Available configuration variables. " + "Use \"\\help <variable>\" to display detailed " + "help for a given variable"); Renderer renderer = session.getRendererManager().getCommandRenderer(session); Variable[] variables = session.getVariableManager().getVariables(true); Arrays.sort(variables); ColumnDescription []columns = new ColumnDescription[2]; columns[0] = new ColumnDescription("Variable", -1); columns[1] = new ColumnDescription("Description", -1); renderer.header(columns); for (int i = 0; i < variables.length; i++) { if (variables[i].getDescription() != null) { String []row = new String[2]; row[0] = variables[i].getName(); row[1] = variables[i].getDescription(); renderer.row(row); } } renderer.flush(); } /** * Displays available topics. * * @param session The session to be used for displaying. */ private void displayTopics(Session session) { session.out.println("Available help topics. " + "Use \"\\help <topic>\" to display detailed " + "help for a given variable"); Renderer renderer = session.getRendererManager().getCommandRenderer(session); ColumnDescription []columns = new ColumnDescription[2]; columns[0] = new ColumnDescription("Topic", -1); columns[1] = new ColumnDescription("Description", -1); renderer.header(columns); HelpTopic []topics = session.getHelpManager().getTopics(); Arrays.sort(topics); for (int i = 0; i < topics.length; i++) { String []row = new String[2]; row[0] = topics[i].getTopic(); row[1] = topics[i].getDescription(); renderer.row(row); } renderer.flush(); } }
package jmetest.sound; import java.net.URL; import jmetest.effects.RenParticleEditor; import com.jme.app.SimpleGame; import com.jme.bounding.BoundingBox; import com.jme.effects.ParticleManager; import com.jme.image.Texture; import com.jme.input.KeyBindingManager; import com.jme.input.KeyInput; import com.jme.input.action.AbstractInputAction; import com.jme.intersection.Intersection; import com.jme.math.Vector3f; import com.jme.renderer.ColorRGBA; import com.jme.scene.Controller; import com.jme.scene.Node; import com.jme.scene.shape.Box; import com.jme.scene.shape.Sphere; import com.jme.scene.state.AlphaState; import com.jme.scene.state.TextureState; import com.jme.sound.SoundAPIController; import com.jme.sound.SoundPool; import com.jme.sound.scene.ProgrammableSound; import com.jme.sound.scene.SoundNode; import com.jme.ui.UIText; import com.jme.util.TextureManager; /** * @author Arman OZCELIK * */ public class PongRevisited extends SimpleGame { private Box player; private Box computer; private Sphere ball; private Box lowerWall; private Box upperWall; private Node particleNode; private ParticleManager manager, bmanager; private SoundNode snode; private ProgrammableSound ballSound; private static final int BOUNCE_EVENT = 1; private static final int WALL_BOUNCE_EVENT = 2; private static final int MISS_EVENT = 3; private float ballXSpeed = -5f; private float ballYSpeed = 0.0f; private int difficulty = 10; private UIText playerScoreText, computerScoreText; private int computerScore, playerScore; private Node uiNode; protected void simpleInitGame() { SoundAPIController.getSoundSystem(properties.getRenderer()); SoundAPIController.getRenderer().setCamera(cam); snode = new SoundNode(); uiNode = new Node("UINODE"); playerScoreText = new UIText("UINODE", "jmetest/data/font/conc_font.png", 600, 0, 1.0f, 50.0f, 5.0f); computerScoreText = new UIText("UINODE", "jmetest/data/font/conc_font.png", 100, 0, 1.0f, 50.0f, 5.0f); playerScoreText.setText("Player : 0"); computerScoreText.setText("Computer : 0"); uiNode.attachChild(playerScoreText); uiNode.attachChild(computerScoreText); display.getRenderer().setBackgroundColor(new ColorRGBA(0, 0, 0, 1)); cam.setFrustum(1f, 5000F, -0.55f, 0.55f, 0.4125f, -0.4125f); Vector3f loc = new Vector3f(0, 0, -850); Vector3f left = new Vector3f(1, 0, 0); Vector3f up = new Vector3f(0, 1, 0f); Vector3f dir = new Vector3f(0, 0, 1); cam.setFrame(loc, left, up, dir); display.getRenderer().setCamera(cam); player = new Box("Player", new Vector3f(0, 0, 0), 5f, 50f, 5f); player.getLocalTranslation().x = -400; player.setModelBound(new BoundingBox()); player.updateModelBound(); computer = new Box("Computer", new Vector3f(0, 0, 0), 5f, 50f, 5f); computer.getLocalTranslation().x = 400; computer.setModelBound(new BoundingBox()); computer.updateModelBound(); ball = new Sphere("Ball", 15, 15, 5f); ball.setModelBound(new BoundingBox()); ball.getLocalTranslation().z = -00f; ball.updateModelBound(); ballSound = new ProgrammableSound(); /*URL laserURL = PongRevisited.class.getClassLoader().getResource( "data/sound/ESPARK.wav"); */ URL explodeURL = PongRevisited.class.getClassLoader().getResource( "jmetest/data/sound/explosion.wav"); URL wallURL = PongRevisited.class.getClassLoader().getResource( "jmetest/data/sound/turn.wav"); //ballSound.bindEvent(BOUNCE_EVENT, SoundPool // .compile(new URL[] { laserURL })); ballSound.bindEvent(MISS_EVENT, SoundPool .compile(new URL[] { explodeURL })); ballSound.bindEvent(WALL_BOUNCE_EVENT, SoundPool .compile(new URL[] { wallURL })); ballSound.setMaxDistance(5000); snode.attachChild(ballSound); lowerWall = new Box("Left Wall", new Vector3f(0, -300, 0), 450f, 5f, 5f); lowerWall.setModelBound(new BoundingBox()); lowerWall.updateModelBound(); upperWall = new Box("Right Wall", new Vector3f(0, 300, 0), 450f, 5f, 5f); upperWall.setModelBound(new BoundingBox()); upperWall.updateModelBound(); manager = new ParticleManager(300, display.getRenderer().getCamera()); manager.setGravityForce(new Vector3f(0.0f, 0.0f, 0.0f)); manager.setEmissionDirection(new Vector3f(0.0f, 1.0f, 0.0f)); manager.setEmissionMaximumAngle(3.1415927f); manager.setSpeed(1.4f); manager.setParticlesMinimumLifeTime(1000.0f); manager.setStartSize(5.0f); manager.setEndSize(5.0f); manager.setStartColor(new ColorRGBA(1.0f, 0.312f, 0.121f, 1.0f)); manager.setEndColor(new ColorRGBA(1.0f, 0.24313726f, 0.03137255f, 0.0f)); manager.setRandomMod(0.0f); manager.setControlFlow(false); manager.setReleaseRate(300); manager.setReleaseVariance(0.0f); manager.setInitialVelocity(1.0f); manager.setParticleSpinSpeed(0.0f); manager.warmUp(1000); manager.getParticles().addController(manager); bmanager = new ParticleManager(100, display.getRenderer().getCamera()); bmanager.setGravityForce(new Vector3f(0.0f, 0.0f, 0.0f)); bmanager.setEmissionDirection(new Vector3f(-1.0f, 0.0f, 0.0f)); bmanager.setEmissionMaximumAngle(0.1f); bmanager.setSpeed(0.4f); bmanager.setParticlesMinimumLifeTime(100.0f); bmanager.setStartSize(5.0f); bmanager.setEndSize(5.0f); bmanager.setStartColor(new ColorRGBA(1.0f, 0.312f, 0.121f, 1.0f)); bmanager.setEndColor(new ColorRGBA(1.0f, 0.24313726f, 0.03137255f, 0.0f)); bmanager.setRandomMod(0.0f); bmanager.setControlFlow(false); bmanager.setReleaseRate(300); bmanager.setReleaseVariance(0.0f); bmanager.setInitialVelocity(0.3f); bmanager.setParticleSpinSpeed(-0.5f); bmanager.warmUp(1000); bmanager.getParticles().addController(bmanager); AlphaState as1 = display.getRenderer().getAlphaState(); as1.setBlendEnabled(true); as1.setSrcFunction(AlphaState.SB_SRC_ALPHA); as1.setDstFunction(AlphaState.DB_ONE); as1.setTestEnabled(true); as1.setTestFunction(AlphaState.TF_GREATER); as1.setEnabled(true); TextureState ts = display.getRenderer().getTextureState(); ts.setTexture( TextureManager.loadTexture( RenParticleEditor.class.getClassLoader().getResource( "jmetest/data/texture/flaresmall.jpg"), Texture.MM_LINEAR_LINEAR, Texture.FM_LINEAR, true)); ts.setEnabled(true); manager.setRepeatType(Controller.RT_CLAMP); Node myNode = new Node("Particle Nodes"); myNode.setRenderState(as1); myNode.setRenderState(ts); Node mybNode = new Node("Particle Nodes"); mybNode.setRenderState(as1); mybNode.setRenderState(ts); mybNode.attachChild(bmanager.getParticles()); myNode.attachChild(manager.getParticles()); rootNode.attachChild(myNode); rootNode.attachChild(mybNode); rootNode.attachChild(player); lightState.setEnabled(!lightState.isEnabled()); rootNode.attachChild(computer); rootNode.attachChild(lowerWall); rootNode.attachChild(upperWall); rootNode.attachChild(ball); rootNode.attachChild(uiNode); input.setMouseSpeed(0); input.setKeySpeed(40); input.addKeyboardAction("moveUp", KeyInput.KEY_UP, new MoveUpAction()); input.addKeyboardAction("moveDown", KeyInput.KEY_DOWN, new MoveDownAction()); //KeyBindingManager.getKeyBindingManager().remove("forward"); //KeyBindingManager.getKeyBindingManager().remove("backward"); KeyBindingManager.getKeyBindingManager().remove("lookUp"); KeyBindingManager.getKeyBindingManager().remove("lookDown"); } public void simpleUpdate() { manager.setRepeatType(Controller.RT_CLAMP); if (checkPlayer()) { ballSound.setPosition(cam.getLocation().x - 5, cam.getLocation().y, cam.getLocation().z); snode.onEvent(WALL_BOUNCE_EVENT); } if (checkComputer()) { ballSound.setPosition(cam.getLocation().x + 5, cam.getLocation().y, cam.getLocation().z); snode.onEvent(WALL_BOUNCE_EVENT); } if (checkWalls()) { ballSound.setPosition(cam.getLocation().x + 5, cam.getLocation().y, cam.getLocation().z); snode.onEvent(WALL_BOUNCE_EVENT); } moveBall(); moveComputer(); if (ball.getLocalTranslation().x < player.getWorldTranslation().x) { ballSound.setPosition(cam.getLocation().x - 5, cam.getLocation().y, cam.getLocation().z); ballSound.fireEvent(MISS_EVENT); computerScoreText.setText("Computer : " + (++computerScore)); manager.setRepeatType(Controller.RT_WRAP); manager.forceRespawn(); manager.getParticles().setLocalTranslation(new Vector3f(ball.getLocalTranslation().x, ball.getLocalTranslation().y, ball.getLocalTranslation().z)); reset(); } if (ball.getLocalTranslation().x > computer.getWorldTranslation().x) { ballSound.setPosition(cam.getLocation().x - 5, cam.getLocation().y, cam.getLocation().z); ballSound.fireEvent(MISS_EVENT); playerScoreText.setText("Player : " + (++playerScore)); manager.setRepeatType(Controller.RT_WRAP); manager.forceRespawn(); manager.getParticles().setLocalTranslation(new Vector3f(ball.getLocalTranslation().x, ball.getLocalTranslation().y, ball.getLocalTranslation().z)); if(difficulty>2) difficulty reset(); } fps.print(""); snode.updateGeometricState(tpf, true); super.simpleUpdate(); } private void moveBall() { ball.getLocalTranslation().x += ballXSpeed; ball.getLocalTranslation().y += ballYSpeed; bmanager.getParticles().getLocalTranslation().x=ball.getLocalTranslation().x; bmanager.getParticles().getLocalTranslation().y=ball.getLocalTranslation().y; if(ballXSpeed < 0){ bmanager.setEmissionDirection(new Vector3f(1,ballYSpeed, 0)); }else{ bmanager.setEmissionDirection(new Vector3f(-1,-ballYSpeed, 0)); } } private void moveComputer() { float dist = Math.abs(ball.getLocalTranslation().y - computer.getLocalTranslation().y); if (ballXSpeed > 0) { if (computer.getLocalTranslation().y < ball.getLocalTranslation().y) { computer.getLocalTranslation().y += Math .rint(dist / difficulty); } else { computer.getLocalTranslation().y -= Math .rint(dist / difficulty); } } else { if (computer.getLocalTranslation().y < 0) computer.getLocalTranslation().y += 2; else if (computer.getLocalTranslation().y > 0) computer.getLocalTranslation().y -= 2; } } private boolean checkPlayer() { if (Intersection.intersection(ball.getWorldBound(), player .getWorldBound())) { ballXSpeed = 0 - ballXSpeed; float racketHit = (ball.getLocalTranslation().y - (player .getLocalTranslation().y)); ballYSpeed += (racketHit / 4); return true; } return false; } public boolean checkComputer() { if (Intersection.intersection(ball.getWorldBound(), computer .getWorldBound())) { ballXSpeed = 0 - ballXSpeed; ballSound.setPosition(cam.getLocation().x - 5, cam.getLocation().y, cam.getLocation().z); float racketHit = (ball.getLocalTranslation().y - (computer .getLocalTranslation().y)); ballYSpeed += (racketHit / 4); return true; } return false; } public boolean checkWalls() { if (Intersection.intersection(ball.getWorldBound(), lowerWall .getWorldBound())) { ballYSpeed = 0 - ballYSpeed; return true; } if (Intersection.intersection(ball.getWorldBound(), upperWall .getWorldBound())) { ballYSpeed = 0 - ballYSpeed; return true; } return false; } public void simpleRender() { SoundAPIController.getRenderer().draw(snode); display.getRenderer().draw(particleNode); super.simpleRender(); } public static void main(String[] args) { PongRevisited app = new PongRevisited(); app.setDialogBehaviour(ALWAYS_SHOW_PROPS_DIALOG); app.start(); } private void reset() { player.getLocalTranslation().x = -400; player.getLocalTranslation().y = 0; player.getLocalTranslation().z = 0; computer.getLocalTranslation().x = 400; computer.getLocalTranslation().y = 0; computer.getLocalTranslation().z = 0; ball.getLocalTranslation().x = 0; ball.getLocalTranslation().y = 0; ball.getLocalTranslation().z = 0; ballXSpeed = 5f; ballYSpeed = 0; } class MoveUpAction extends AbstractInputAction { int numBullets; MoveUpAction() { setAllowsRepeats(true); } public void performAction(float time) { player.getLocalTranslation().y += 5; } } class MoveDownAction extends AbstractInputAction { int numBullets; MoveDownAction() { setAllowsRepeats(true); } public void performAction(float time) { player.getLocalTranslation().y -= 5; } } }
package joshua.decoder; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import joshua.decoder.chart_parser.Chart; import joshua.decoder.ff.FeatureFunction; import joshua.decoder.ff.state_maintenance.StateComputer; import joshua.decoder.ff.tm.Grammar; import joshua.decoder.ff.tm.GrammarFactory; import joshua.decoder.ff.tm.hash_based.MemoryBasedBatchGrammar; import joshua.decoder.hypergraph.DiskHyperGraph; import joshua.decoder.hypergraph.HyperGraph; import joshua.decoder.hypergraph.KBestExtractor; import joshua.decoder.segment_file.Sentence; import joshua.lattice.Lattice; import joshua.oracle.OracleExtractor; import joshua.ui.hypergraph_visualizer.HyperGraphViewer; import edu.jhu.thrax.util.TestSetFilter; // BUG: known synchronization problem: LM cache; srilm call; public class ParserThread extends Thread { /* these variables may be the same across all threads (e.g., * just copy from DecoderFactory), or differ from thread * to thread */ private final List<GrammarFactory> grammarFactories; private final List<FeatureFunction> featureFunctions; private final List<StateComputer> stateComputers; //more test set specific private final InputHandler inputHandler; // final String nbestFile; // package-private for DecoderFactory private BufferedWriter nbestWriter; // set in decodeTestFile private final KBestExtractor kbestExtractor; DiskHyperGraph hypergraphSerializer; // package-private for DecoderFactory private static final Logger logger = Logger.getLogger(ParserThread.class.getName()); // Constructor public ParserThread( List<GrammarFactory> grammarFactories, List<FeatureFunction> featureFunctions, List<StateComputer> stateComputers, InputHandler inputHandler ) throws IOException { this.grammarFactories = grammarFactories; this.featureFunctions = featureFunctions; this.stateComputers = stateComputers; this.inputHandler = inputHandler; this.kbestExtractor = new KBestExtractor( JoshuaConfiguration.use_unique_nbest, JoshuaConfiguration.use_tree_nbest, JoshuaConfiguration.include_align_index, JoshuaConfiguration.add_combined_cost, false, true); // if (JoshuaConfiguration.save_disk_hg) { // FeatureFunction languageModel = null; // for (FeatureFunction ff : this.featureFunctions) { // if (ff instanceof LanguageModelFF) { // languageModel = ff; // break; // int lmFeatID = -1; // if (null == languageModel) { // logger.warning("No language model feature function found, but save disk hg"); // } else { // lmFeatID = languageModel.getFeatureID(); // this.hypergraphSerializer = new DiskHyperGraph( // Vocabulary, // lmFeatID, // true, // always store model cost // this.featureFunctions); // this.hypergraphSerializer.initWrite( // "out." + Integer.toString(sentence.id()) + ".hg.items", // JoshuaConfiguration.forest_pruning, // JoshuaConfiguration.forest_pruning_threshold); } // Methods // Overriding of Thread.run() cannot throw anything public void run() { try { this.parseAll(); //this.hypergraphSerializer.closeReaders(); } catch (Throwable e) { // if we throw anything (e.g. OutOfMemoryError) // we should stop all threads // because it is impossible for decoding // to finish successfully e.printStackTrace(); System.exit(1); } } /** * Repeatedly fetches input sentences and calls translate() on * them, registering the results with the InputManager upon * completion. */ public void parseAll() throws IOException { for (;;) { Sentence sentence = inputHandler.next(); if (sentence == null) break; HyperGraph hypergraph = parse(sentence, null); Translation translation = null; String oracleSentence = inputHandler.oracleSentence(); if (oracleSentence != null) { OracleExtractor extractor = new OracleExtractor(); HyperGraph oracle = extractor.getOracle(hypergraph, 3, oracleSentence); translation = new Translation(sentence, oracle, featureFunctions); } else { translation = new Translation(sentence, hypergraph, featureFunctions); // if (null != this.hypergraphSerializer) { // if(JoshuaConfiguration.use_kbest_hg){ // HyperGraph kbestHG = this.kbestExtractor.extractKbestIntoHyperGraph(hypergraph, JoshuaConfiguration.topN); // this.hypergraphSerializer.saveHyperGraph(kbestHG); // }else{ // this.hypergraphSerializer.saveHyperGraph(hypergraph); } inputHandler.register(translation); //debug //g_con.get_confusion_in_hyper_graph_cell_specific(hypergraph, hypergraph.sent_len); } } /** * Parse a sentence. * * @param segment The sentence to be parsed. * @param oracleSentence */ public HyperGraph parse(Sentence sentence, String oracleSentence) throws IOException { logger.info("Parsing sentence pair #" + sentence.id() + " [thread " + getId() + "]\n" + sentence.sentence()); long startTime = System.currentTimeMillis(); Chart chart; String [] sentencePair = sentence.sentence().split("\\|\\|\\|"); int sentenceId = sentence.id(); System.err.printf("FOREIGN: %s\n", sentencePair[0]); System.err.printf("ENGLISH: %s\n", sentencePair[1]); Sentence foreign = new Sentence(sentencePair[0], sentenceId); Sentence english = new Sentence(sentencePair[1], sentenceId); Lattice<Integer> input_lattice = foreign.intLattice(); int numGrammars = (JoshuaConfiguration.use_sent_specific_tm) ? grammarFactories.size() + 1 : grammarFactories.size(); Grammar[] grammars = new Grammar[numGrammars]; for (int i = 0; i< grammarFactories.size(); i++) grammars[i] = grammarFactories.get(i).getGrammarForSentence(foreign); // load the sentence-specific grammar boolean alreadyExisted = true; // whether it already existed String tmFile = null; if (JoshuaConfiguration.use_sent_specific_tm) { // figure out the sentence-level file name tmFile = JoshuaConfiguration.tm_file; tmFile = tmFile.endsWith(".gz") ? tmFile.substring(0, tmFile.length()-3) + "." + sentence.id() + ".gz" : tmFile + "." + sentence.id(); // look in a subdirectory named "filtered" e.g., // /some/path/grammar.gz will have sentence-level // grammars in /some/path/filtered/grammar.SENTNO.gz int lastSlashPos = tmFile.lastIndexOf('/'); String dirPart = tmFile.substring(0,lastSlashPos + 1); String filePart = tmFile.substring(lastSlashPos + 1); tmFile = dirPart + "filtered/" + filePart; File filteredDir = new File(dirPart + "filtered"); if (! filteredDir.exists()) { logger.info("Creating sentence-level grammar directory '" + dirPart + "filtered'"); filteredDir.mkdirs(); } logger.info("Using sentence-specific TM file '" + tmFile + "'"); if (! new File(tmFile).exists()) { alreadyExisted = false; // filter grammar and write it to a file if (logger.isLoggable(Level.INFO)) logger.info("Automatically producing file " + tmFile); TestSetFilter.filterGrammarToFile(JoshuaConfiguration.tm_file, sentence.sentence(), tmFile, true); } else { if (logger.isLoggable(Level.INFO)) logger.info("Using existing sentence-specific tm file " + tmFile); } grammars[numGrammars-1] = new MemoryBasedBatchGrammar(JoshuaConfiguration.tm_format, tmFile, JoshuaConfiguration.phrase_owner, JoshuaConfiguration.default_non_terminal, JoshuaConfiguration.span_limit, JoshuaConfiguration.oov_feature_cost); // sort the sentence-specific grammar grammars[numGrammars-1].sortGrammar(this.featureFunctions); } /* Seeding: the chart only sees the grammars, not the factories */ chart = new Chart(input_lattice, this.featureFunctions, this.stateComputers, foreign.id(), grammars, false, JoshuaConfiguration.goal_symbol, foreign.constraints(), foreign.syntax_tree()); /* Parsing */ HyperGraph hypergraph = chart.expand(); // delete the sentence-specific grammar if it didn't // already exist and we weren't asked to keep it around if (! alreadyExisted && ! JoshuaConfiguration.keep_sent_specific_tm && JoshuaConfiguration.use_sent_specific_tm) { File file = new File(tmFile); file.delete(); logger.info("Deleting sentence-level grammar file '" + tmFile + "'"); } else if (JoshuaConfiguration.keep_sent_specific_tm) { // logger.info("Keeping sentence-level grammar (keep_sent_specific_tm=true)"); } else if (alreadyExisted) { // logger.info("Keeping sentence-level grammar (already existed)"); } long seconds = (System.currentTimeMillis() - startTime) / 1000; logger.info("translation of sentence " + sentence.id() + " took " + seconds + " seconds [" + getId() + "]"); return hypergraph; } }
package jtermios.linux; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.IOException; import java.nio.Buffer; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.regex.Pattern; import jtermios.FDSet; import jtermios.JTermios; import jtermios.Pollfd; import jtermios.Termios; import jtermios.TimeVal; import jtermios.JTermios.JTermiosInterface; import jtermios.linux.JTermiosImpl.Linux_C_lib.pollfd; import jtermios.linux.JTermiosImpl.Linux_C_lib.serial_struct; import com.sun.jna.Library; import com.sun.jna.Native; import com.sun.jna.NativeLong; import com.sun.jna.Pointer; import com.sun.jna.Structure; import com.sun.jna.ptr.IntByReference; import com.sun.jna.ptr.NativeLongByReference; import static jtermios.JTermios.*; import static jtermios.JTermios.JTermiosLogging.log; public class JTermiosImpl implements jtermios.JTermios.JTermiosInterface { private static String DEVICE_DIR_PATH = "/dev/"; private static final boolean IS64B = NativeLong.SIZE == 8; static Linux_C_lib_DirectMapping m_ClibDM = new Linux_C_lib_DirectMapping(); static Linux_C_lib m_Clib = m_ClibDM; private final static int TIOCGSERIAL = 0x0000541E; private final static int TIOCSSERIAL = 0x0000541F; private final static int ASYNC_SPD_MASK = 0x00001030; private final static int ASYNC_SPD_CUST = 0x00000030; private final static int[] m_BaudRates = { 50, 0000001, 75, 0000002, 110, 0000003, 134, 0000004, 150, 0000005, 200, 0000006, 300, 0000007, 600, 0000010, 1200, 0000011, 1800, 0000012, 2400, 0000013, 4800, 0000014, 9600, 0000015, 19200, 0000016, 38400, 0000017, 57600, 0010001, 115200, 0010002, 230400, 0010003, 460800, 0010004, 500000, 0010005, 576000, 0010006, 921600, 0010007, 1000000, 0010010, 1152000, 0010011, 1500000, 0010012, 2000000, 0010013, 2500000, 0010014, 3000000, 0010015, 3500000, 0010016, 4000000, 0010017 }; public static class Linux_C_lib_DirectMapping implements Linux_C_lib { native public long memcpy(int[] dst, short[] src, long n); native public int memcpy(int[] dst, short[] src, int n); native public int pipe(int[] fds); native public int tcdrain(int fd); native public void cfmakeraw(termios termios); native public int fcntl(int fd, int cmd, int arg); native public int ioctl(int fd, int cmd, int[] arg); native public int ioctl(int fd, int cmd, serial_struct arg); native public int open(String path, int flags); native public int close(int fd); native public int tcgetattr(int fd, termios termios); native public int tcsetattr(int fd, int cmd, termios termios); native public int cfsetispeed(termios termios, NativeLong i); native public int cfsetospeed(termios termios, NativeLong i); native public NativeLong cfgetispeed(termios termios); native public NativeLong cfgetospeed(termios termios); native public int write(int fd, byte[] buffer, int count); native public int read(int fd, byte[] buffer, int count); native public long write(int fd, byte[] buffer, long count); native public long read(int fd, byte[] buffer, long count); native public int select(int n, int[] read, int[] write, int[] error, timeval timeout); native public int poll(int[] fds, int nfds, int timeout); public int poll(pollfd[] fds, int nfds, int timeout) { throw new IllegalArgumentException(); } native public int tcflush(int fd, int qs); native public void perror(String msg); native public int tcsendbreak(int fd, int duration); static { try { Native.register("c"); } catch (Exception e) { e.printStackTrace(); } } } public interface Linux_C_lib extends com.sun.jna.Library { public long memcpy(int[] dst, short[] src, long n); public int memcpy(int[] dst, short[] src, int n); public int pipe(int[] fds); public int tcdrain(int fd); public void cfmakeraw(termios termios); public int fcntl(int fd, int cmd, int arg); public int ioctl(int fd, int cmd, int[] arg); public int ioctl(int fd, int cmd, serial_struct arg); public int open(String path, int flags); public int close(int fd); public int tcgetattr(int fd, termios termios); public int tcsetattr(int fd, int cmd, termios termios); public int cfsetispeed(termios termios, NativeLong i); public int cfsetospeed(termios termios, NativeLong i); public NativeLong cfgetispeed(termios termios); public NativeLong cfgetospeed(termios termios); public int write(int fd, byte[] buffer, int count); public int read(int fd, byte[] buffer, int count); public long write(int fd, byte[] buffer, long count); public long read(int fd, byte[] buffer, long count); public int select(int n, int[] read, int[] write, int[] error, timeval timeout); public int poll(pollfd[] fds, int nfds, int timeout); public int poll(int[] fds, int nfds, int timeout); public int tcflush(int fd, int qs); public void perror(String msg); public int tcsendbreak(int fd, int duration); static public class timeval extends Structure { public NativeLong tv_sec; public NativeLong tv_usec; @Override protected List getFieldOrder() { return Arrays.asList( "tv_sec", "tv_usec" ); } public timeval(jtermios.TimeVal timeout) { tv_sec = new NativeLong(timeout.tv_sec); tv_usec = new NativeLong(timeout.tv_usec); } } static public class pollfd extends Structure { public int fd; public short events; public short revents; @Override protected List getFieldOrder() { return Arrays.asList( "fd", "events", "revents" ); } public pollfd(Pollfd pfd) { fd = pfd.fd; events = pfd.events; revents = pfd.revents; } } public static class serial_struct extends Structure { public int type; public int line; public int port; public int irq; public int flags; public int xmit_fifo_size; public int custom_divisor; public int baud_base; public short close_delay; public short io_type; //public char io_type; //public char reserved_char; public int hub6; public short closing_wait; public short closing_wait2; public Pointer iomem_base; public short iomem_reg_shift; public int port_high; public NativeLong iomap_base; @Override protected List getFieldOrder() { return Arrays.asList( "type", "line", "port", "irq", "flags", "xmit_fifo_size", "custom_divisor", "baud_base", "close_delay", "io_type", //public char io_type; //public char reserved_char; "hub6", "closing_wait", "closing_wait2", "iomem_base", "iomem_reg_shift", "port_high", "iomap_base" ); } }; static public class termios extends Structure { public int c_iflag; public int c_oflag; public int c_cflag; public int c_lflag; public byte c_line; public byte[] c_cc = new byte[32]; public int c_ispeed; public int c_ospeed; @Override protected List getFieldOrder() { return Arrays.asList( "c_iflag", "c_oflag", "c_cflag", "c_lflag", "c_line", "c_cc", "c_ispeed", "c_ospeed" ); } public termios() { } public termios(jtermios.Termios t) { c_iflag = t.c_iflag; c_oflag = t.c_oflag; c_cflag = t.c_cflag; c_lflag = t.c_lflag; System.arraycopy(t.c_cc, 0, c_cc, 0, t.c_cc.length); c_ispeed = t.c_ispeed; c_ospeed = t.c_ospeed; } public void update(jtermios.Termios t) { t.c_iflag = c_iflag; t.c_oflag = c_oflag; t.c_cflag = c_cflag; t.c_lflag = c_lflag; System.arraycopy(c_cc, 0, t.c_cc, 0, t.c_cc.length); t.c_ispeed = c_ispeed; t.c_ospeed = c_ospeed; } } } static private class FDSetImpl extends FDSet { static final int FD_SET_SIZE = 1024; static final int NFBBITS = 32; int[] bits = new int[(FD_SET_SIZE + NFBBITS - 1) / NFBBITS]; public String toString() { return String.format("%08X%08X", bits[0], bits[1]); } } public JTermiosImpl() { log = log && log(1, "instantiating %s\n", getClass().getCanonicalName()); //linux/serial.h stuff FIONREAD = 0x541B; // Looked up manually //fcntl.h stuff O_RDWR = 0x00000002; O_NONBLOCK = 0x00000800; O_NOCTTY = 0x00000100; O_NDELAY = 0x00000800; F_GETFL = 0x00000003; F_SETFL = 0x00000004; //errno.h stuff EAGAIN = 11; EACCES = 13; EEXIST = 17; EINTR = 4; EINVAL = 22; EIO = 5; EISDIR = 21; ELOOP = 40; EMFILE = 24; ENAMETOOLONG = 36; ENFILE = 23; ENOENT = 2; ENOSR = 63; ENOSPC = 28; ENOTDIR = 20; ENXIO = 6; EOVERFLOW = 75; EROFS = 30; ENOTSUP = 95; //termios.h stuff TIOCM_RNG = 0x00000080; TIOCM_CAR = 0x00000040; IGNBRK = 0x00000001; BRKINT = 0x00000002; PARMRK = 0x00000008; INLCR = 0x00000040; IGNCR = 0x00000080; ICRNL = 0x00000100; ECHONL = 0x00000040; IEXTEN = 0x00008000; CLOCAL = 0x00000800; OPOST = 0x00000001; VSTART = 0x00000008; TCSANOW = 0x00000000; VSTOP = 0x00000009; VMIN = 0x00000006; VTIME = 0x00000005; VEOF = 0x00000004; TIOCMGET = 0x00005415; TIOCM_CTS = 0x00000020; TIOCM_DSR = 0x00000100; TIOCM_RI = 0x00000080; TIOCM_CD = 0x00000040; TIOCM_DTR = 0x00000002; TIOCM_RTS = 0x00000004; ICANON = 0x00000002; ECHO = 0x00000008; ECHOE = 0x00000010; ISIG = 0x00000001; TIOCMSET = 0x00005418; IXON = 0x00000400; IXOFF = 0x00001000; IXANY = 0x00000800; CRTSCTS = 0x80000000; TCSADRAIN = 0x00000001; INPCK = 0x00000010; ISTRIP = 0x00000020; CSIZE = 0x00000030; TCIFLUSH = 0x00000000; TCOFLUSH = 0x00000001; TCIOFLUSH = 0x00000002; CS5 = 0x00000000; CS6 = 0x00000010; CS7 = 0x00000020; CS8 = 0x00000030; CSTOPB = 0x00000040; CREAD = 0x00000080; PARENB = 0x00000100; PARODD = 0x00000200; B0 = 0; B50 = 1; B75 = 2; B110 = 3; B134 = 4; B150 = 5; B200 = 6; B300 = 7; B600 = 8; B1200 = 9; B1800 = 10; B2400 = 11; B4800 = 12; B9600 = 13; B19200 = 14; B38400 = 15; B57600 = 4097; B115200 = 4098; B230400 = 4099; //poll.h stuff POLLIN = 0x0001; POLLPRI = 0x0002; POLLOUT = 0x0004; POLLERR = 0x0008; POLLNVAL = 0x0020; // these depend on the endianness off the machine POLLIN_IN = pollMask(0, POLLIN); POLLOUT_IN = pollMask(0, POLLOUT); POLLIN_OUT = pollMask(1, POLLIN); POLLOUT_OUT = pollMask(1, POLLOUT); POLLNVAL_OUT = pollMask(1, POLLNVAL); } public static int pollMask(int i, short n) { short[] s = new short[2]; int[] d = new int[1]; s[i] = n; // the native call depends on weather this is 32 or 64 bit arc if (IS64B) m_ClibDM.memcpy(d, s, (long) 4); else m_ClibDM.memcpy(d, s, (int) 4); return d[0]; } public int errno() { return Native.getLastError(); } public void cfmakeraw(Termios termios) { Linux_C_lib.termios t = new Linux_C_lib.termios(termios); m_Clib.cfmakeraw(t); t.update(termios); } public int fcntl(int fd, int cmd, int arg) { return m_Clib.fcntl(fd, cmd, arg); } public int tcdrain(int fd) { return m_Clib.tcdrain(fd); } public int cfgetispeed(Termios termios) { return m_Clib.cfgetispeed(new Linux_C_lib.termios(termios)).intValue(); } public int cfgetospeed(Termios termios) { return m_Clib.cfgetospeed(new Linux_C_lib.termios(termios)).intValue(); } public int cfsetispeed(Termios termios, int speed) { Linux_C_lib.termios t = new Linux_C_lib.termios(termios); int ret = m_Clib.cfsetispeed(t, new NativeLong(speed)); t.update(termios); return ret; } public int cfsetospeed(Termios termios, int speed) { Linux_C_lib.termios t = new Linux_C_lib.termios(termios); int ret = m_Clib.cfsetospeed(t, new NativeLong(speed)); t.update(termios); return ret; } public int open(String s, int t) { if (s != null && !s.startsWith("/")) s = DEVICE_DIR_PATH + s; return m_Clib.open(s, t); } public int read(int fd, byte[] buffer, int len) { if (IS64B) return (int) m_Clib.read(fd, buffer, (long) len); else return m_Clib.read(fd, buffer, len); } public int write(int fd, byte[] buffer, int len) { if (IS64B) return (int) m_Clib.write(fd, buffer, (long) len); else return m_Clib.write(fd, buffer, len); } public int close(int fd) { return m_Clib.close(fd); } public int tcflush(int fd, int b) { return m_Clib.tcflush(fd, b); } public int tcgetattr(int fd, Termios termios) { Linux_C_lib.termios t = new Linux_C_lib.termios(); int ret = m_Clib.tcgetattr(fd, t); t.update(termios); return ret; } public void perror(String msg) { m_Clib.perror(msg); } public int tcsendbreak(int fd, int duration) { // If duration is not zero, it sends zero-valued bits for duration*N seconds, // where N is at least 0.25, and not more than 0.5. return m_Clib.tcsendbreak(fd, duration / 250); } public int tcsetattr(int fd, int cmd, Termios termios) { return m_Clib.tcsetattr(fd, cmd, new Linux_C_lib.termios(termios)); } public void FD_CLR(int fd, FDSet set) { if (set == null) return; FDSetImpl p = (FDSetImpl) set; p.bits[fd / FDSetImpl.NFBBITS] &= ~(1 << (fd % FDSetImpl.NFBBITS)); } public boolean FD_ISSET(int fd, FDSet set) { if (set == null) return false; FDSetImpl p = (FDSetImpl) set; return (p.bits[fd / FDSetImpl.NFBBITS] & (1 << (fd % FDSetImpl.NFBBITS))) != 0; } public void FD_SET(int fd, FDSet set) { if (set == null) return; FDSetImpl p = (FDSetImpl) set; p.bits[fd / FDSetImpl.NFBBITS] |= 1 << (fd % FDSetImpl.NFBBITS); } public void FD_ZERO(FDSet set) { if (set == null) return; FDSetImpl p = (FDSetImpl) set; java.util.Arrays.fill(p.bits, 0); } public int select(int nfds, FDSet rfds, FDSet wfds, FDSet efds, TimeVal timeout) { Linux_C_lib.timeval tout = null; if (timeout != null) tout = new Linux_C_lib.timeval(timeout); int[] r = rfds != null ? ((FDSetImpl) rfds).bits : null; int[] w = wfds != null ? ((FDSetImpl) wfds).bits : null; int[] e = efds != null ? ((FDSetImpl) efds).bits : null; return m_Clib.select(nfds, r, w, e, tout); } public int poll(Pollfd fds[], int nfds, int timeout) { pollfd[] pfds = new pollfd[fds.length]; for (int i = 0; i < nfds; i++) pfds[i] = new pollfd(fds[i]); int ret = m_Clib.poll(pfds, nfds, timeout); for (int i = 0; i < nfds; i++) fds[i].revents = pfds[i].revents; return ret; } public int poll(int fds[], int nfds, int timeout) { return m_Clib.poll(fds, nfds, timeout); } public FDSet newFDSet() { return new FDSetImpl(); } public int ioctl(int fd, int cmd, int[] data) { return m_Clib.ioctl(fd, cmd, data); } // This ioctl is Linux specific, so keep it private for now private int ioctl(int fd, int cmd, serial_struct data) { // Do the logging here as this does not go through the JTermios which normally does the logging log = log && log(5, "> ioctl(%d,%d,%s)\n", fd, cmd, data); int ret = m_Clib.ioctl(fd, cmd, data); log = log && log(3, "< tcsetattr(%d,%d,%s) => %d\n", fd, cmd, data, ret); return ret; } public String getPortNamePattern() { // First we have to determine which serial drivers exist and which // prefixes they use final List<String> prefixes = new ArrayList<String>(); try { BufferedReader drivers = new BufferedReader(new InputStreamReader(new FileInputStream("/proc/tty/drivers"), "US-ASCII")); String line; while ((line = drivers.readLine()) != null) { // /proc/tty/drivers contains the prefix in the second column // and "serial" in the fifth String[] parts = line.split(" +"); if (parts.length != 5) { continue; } if (!"serial".equals(parts[4])) { continue; } // Sanity check the prefix if (!parts[1].startsWith("/dev/")) { continue; } prefixes.add(parts[1].substring(5)); } drivers.close(); } catch (IOException e) { log = log && log(1, "failed to read /proc/tty/drivers\n"); prefixes.add("ttyS"); prefixes.add("ttyUSB"); prefixes.add("ttyACM"); } // Now build the pattern from the known prefixes StringBuilder pattern = new StringBuilder(); pattern.append('^'); boolean first = false; for (String prefix : prefixes) { if (!first) { first = true; } else { pattern.append('|'); } pattern.append("("); pattern.append(prefix); pattern.append(".+)"); } return pattern.toString(); } public List<String> getPortList() { File dir = new File(DEVICE_DIR_PATH); if (!dir.isDirectory()) { log = log && log(1, "device directory %s does not exist\n", DEVICE_DIR_PATH); return null; } String[] devs = dir.list(); LinkedList<String> list = new LinkedList<String>(); Pattern p = JTermios.getPortNamePattern(this); if (devs != null) { for (int i = 0; i < devs.length; i++) { String s = devs[i]; if (p.matcher(s).matches()) list.add(s); } } return list; } public void shutDown() { } public int setspeed(int fd, Termios termios, int speed) { int c = speed; int r; for (int i = 0; i < m_BaudRates.length; i += 2) { if (m_BaudRates[i] == speed) { // found the baudrate from the table // just in case custom divisor was in use, try to turn it off first serial_struct ss = new serial_struct(); r = ioctl(fd, TIOCGSERIAL, ss); if (r == 0) { ss.flags &= ~ASYNC_SPD_MASK; r = ioctl(fd, TIOCSSERIAL, ss); } // now set the speed with the constant from the table c = m_BaudRates[i + 1]; if ((r = JTermios.cfsetispeed(termios, c)) != 0) return r; if ((r = JTermios.cfsetospeed(termios, c)) != 0) return r; if ((r = JTermios.tcsetattr(fd, TCSANOW, termios)) != 0) return r; return 0; } } // baudrate not defined in the table, try custom divisor approach // configure port to use custom speed instead of 38400 serial_struct ss = new serial_struct(); if ((r = ioctl(fd, TIOCGSERIAL, ss)) != 0) return r; ss.flags = (ss.flags & ~ASYNC_SPD_MASK) | ASYNC_SPD_CUST; if (speed == 0) { log = log && log(1, "unable to set custom baudrate %d \n", speed); return -1; } ss.custom_divisor = (ss.baud_base + (speed / 2)) / speed; if (ss.custom_divisor == 0) { log = log && log(1, "unable to set custom baudrate %d (possible division by zero)\n", speed); return -1; } int closestSpeed = ss.baud_base / ss.custom_divisor; if (closestSpeed < speed * 98 / 100 || closestSpeed > speed * 102 / 100) { log = log && log(1, "best available baudrate %d not close enough to requested %d \n", closestSpeed, speed); return -1; } if ((r = ioctl(fd, TIOCSSERIAL, ss)) != 0) return r; if ((r = JTermios.cfsetispeed(termios, B38400)) != 0) return r; if ((r = JTermios.cfsetospeed(termios, B38400)) != 0) return r; if ((r = JTermios.tcsetattr(fd, TCSANOW, termios)) != 0) return r; return 0; } public int pipe(int[] fds) { return m_Clib.pipe(fds); } }
package lbms.plugins.mldht.kad; import static java.lang.Math.max; import static java.lang.Math.min; import static lbms.plugins.mldht.kad.Node.InsertOptions.ALWAYS_SPLIT_IF_FULL; import static lbms.plugins.mldht.kad.Node.InsertOptions.FORCE_INTO_MAIN_BUCKET; import static lbms.plugins.mldht.kad.Node.InsertOptions.NEVER_SPLIT; import static lbms.plugins.mldht.kad.Node.InsertOptions.RELAXED_SPLIT; import static lbms.plugins.mldht.kad.Node.InsertOptions.REMOVE_IF_FULL; import static the8472.utils.Functional.typedGet; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.SeekableByteChannel; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.EnumSet; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import lbms.plugins.mldht.DHTConfiguration; import lbms.plugins.mldht.kad.DHT.LogLevel; import lbms.plugins.mldht.kad.messages.MessageBase; import lbms.plugins.mldht.kad.messages.MessageBase.Type; import lbms.plugins.mldht.kad.tasks.NodeLookup; import lbms.plugins.mldht.kad.tasks.PingRefreshTask; import lbms.plugins.mldht.kad.tasks.Task; import lbms.plugins.mldht.kad.utils.AddressUtils; import lbms.plugins.mldht.kad.utils.ThreadLocalUtils; import the8472.bencode.BEncoder; import the8472.utils.CowSet; import the8472.utils.Pair; import the8472.utils.concurrent.SerializedTaskExecutor; import the8472.utils.io.NetMask; /** * @author Damokles * */ public class Node { /* * Verification Strategy: * * - trust incoming requests less than responses to outgoing requests * - most outgoing requests will have an expected ID - expected ID may come from external nodes, so don't take it at face value * - if response does not match expected ID drop the packet for routing table accounting purposes without penalizing any existing routing table entry * - map routing table entries to IP addresses * - verified responses trump unverified entries * - lookup all routing table entry for incoming messages based on IP address (not node ID!) and ignore them if ID does not match * - also ignore if port changed * - drop, not just ignore, if we are sure that the incoming message is not fake (mtid-verified response) * - allow duplicate addresses for unverified entries * - scrub later when one becomes verified * - never hand out unverified entries to other nodes * * other stuff to keep in mind: * * - non-reachable nodes may spam -> floods replacements -> makes it hard to get proper replacements without active lookups * */ public static final class RoutingTableEntry implements Comparable<RoutingTableEntry> { public RoutingTableEntry(Prefix prefix, KBucket bucket, Predicate<Prefix> checkHome) { this.prefix = prefix; this.bucket = bucket; this.homeBucket = checkHome.test(prefix); } public final Prefix prefix; final KBucket bucket; final boolean homeBucket; public KBucket getBucket() { return bucket; } public int compareTo(RoutingTableEntry o) { return prefix.compareTo(o.prefix); } @Override public String toString() { return prefix.toString() + " " + bucket.toString(); } } public static final class RoutingTable { final RoutingTableEntry[] entries; final int[] indexCache; RoutingTable(RoutingTableEntry... entries) { this.entries = entries; if(entries.length > 64) { indexCache = buildCache(); } else { indexCache = new int[] {0, entries.length}; } } public RoutingTable() { this(new RoutingTableEntry[] {new RoutingTableEntry(new Prefix(), new KBucket(), (x) -> true)}); } int[] buildCache() { int[] cache = new int[256]; assert(Integer.bitCount(cache.length) == 1); int lsb = Integer.bitCount((cache.length/2)-1)-1; Key increment = Key.setBit(lsb); Key trailingBits = new Prefix(Key.MAX_KEY, lsb).distance(Key.MAX_KEY); Key currentLower = new Key(new Prefix(Key.MIN_KEY, lsb)); Key currentUpper = new Prefix(Key.MIN_KEY, lsb).distance(trailingBits); int innerOffset = 0; for(int i=0;i<cache.length;i+=2) { cache[i+1] = entries.length; for(int j=innerOffset;j<entries.length;j++) { Prefix p = entries[j].prefix; if(p.compareTo(currentLower) <= 0) { innerOffset = cache[i] = max(cache[i],j); } if(p.compareTo(currentUpper) >= 0) { cache[i+1] = min(cache[i+1],j); break; } } currentLower = new Key(new Prefix(currentLower.add(increment), lsb)); currentUpper = currentLower.distance(trailingBits); } // System.out.println(IntStream.of(cache).mapToObj(Integer::toString).collect(Collectors.joining(", "))); return cache; } public int indexForId(Key id) { int mask = indexCache.length/2 - 1; int bits = Integer.bitCount(mask); int cacheIdx = id.getInt(0); cacheIdx = Integer.rotateLeft(cacheIdx, bits); cacheIdx = cacheIdx & mask; cacheIdx <<= 1; int lowerBound = indexCache[cacheIdx]; int upperBound = indexCache[cacheIdx+1]; Prefix pivot = null; while(true) { int pivotIdx = (lowerBound + upperBound) >>> 1; pivot = entries[pivotIdx].prefix; if(pivotIdx == lowerBound) break; if (pivot.compareTo(id) <= 0) lowerBound = pivotIdx; else upperBound = pivotIdx; } assert(pivot != null && pivot.isPrefixOf(id)); return lowerBound; } public RoutingTableEntry entryForId(Key id) { return entries[indexForId(id)]; } public int size() { return entries.length; } public RoutingTableEntry get(int idx) { return entries[idx]; } public List<RoutingTableEntry> list() { return Collections.unmodifiableList(Arrays.asList(entries)); } public Stream<RoutingTableEntry> stream() { return Arrays.stream(entries); } public RoutingTable modify(Collection<RoutingTableEntry> toRemove, Collection<RoutingTableEntry> toAdd) { List<RoutingTableEntry> temp = new ArrayList<>(Arrays.asList(entries)); if(toRemove != null) temp.removeAll(toRemove); if(toAdd != null) temp.addAll(toAdd); return new RoutingTable(temp.stream().sorted().toArray(RoutingTableEntry[]::new)); } } private Object CoWLock = new Object(); private volatile RoutingTable routingTableCOW = new RoutingTable(); private DHT dht; private int num_receives; private int numReceivesAtLastCheck; private long timeOfLastPingCheck; private long timeOfLastReceiveCountChange; private long timeOfRecovery; private int num_entries; private Key baseKey; private final CowSet<Key> usedIDs = new CowSet<>(); private volatile Map<InetAddress,RoutingTableEntry> knownNodes = new HashMap<>(); private ConcurrentHashMap<InetAddress , Long> unsolicitedThrottle = new ConcurrentHashMap<>(); private Map<KBucket, Task> maintenanceTasks = new IdentityHashMap<>(); Collection<NetMask> trustedNodes = Collections.emptyList(); /** * @param srv */ public Node(DHT dht) { this.dht = dht; num_receives = 0; num_entries = 0; } /** * An RPC message was received, the node must now update the right bucket. * @param msg The message */ void recieved(MessageBase msg) { InetAddress ip = msg.getOrigin().getAddress(); Key id = msg.getID(); Optional<RPCCall> associatedCall = Optional.ofNullable(msg.getAssociatedCall()); Optional<Key> expectedId = associatedCall.map(RPCCall::getExpectedID); Optional<Pair<KBucket, KBucketEntry>> entryByIp = bucketForIP(ip); if(entryByIp.isPresent()) { KBucket oldBucket = entryByIp.get().a; KBucketEntry oldEntry = entryByIp.get().b; // this might happen if // a) multiple nodes on a single IP -> ignore anything but the node we already have in the table // b) one node changes ports (broken NAT?) -> ignore until routing table entry times out if(oldEntry.getAddress().getPort() != msg.getOrigin().getPort()) return; if(!oldEntry.getID().equals(id)) { // ID mismatch if(associatedCall.isPresent()) { /* * we are here because: * a) a node with that IP is in our routing table * b) port matches too * c) the message is a response (mtid-verified) * d) the ID does not match our routing table entry * * That means we are certain that the node either changed its node ID or does some ID-spoofing. * In either case we don't want it in our routing table */ DHT.logInfo("force-removing routing table entry "+oldEntry+" because ID-change was detected; new ID:" + msg.getID()); oldBucket.removeEntryIfBad(oldEntry, true); // might be pollution attack, check other entries in the same bucket too in case random pings can't keep up with scrubbing. RPCServer srv = msg.getServer(); tryPingMaintenance(oldBucket, "checking sibling bucket entries after ID change was detected", srv, (t) -> t.checkGoodEntries(true)); if(oldEntry.verifiedReachable()) { // old verified // new verified // -> probably misbehaving node. don't insert return; } /* * old never verified * new verified * -> may allow insert, as if the old one has never been there * * but still need to check expected ID match. * TODO: if this results in an insert then the known nodes list may be stale */ } else { // new message is *not* a response -> not verified -> fishy due to ID mismatch -> ignore return; } } } KBucket bucketById = routingTableCOW.entryForId(id).bucket; Optional<KBucketEntry> entryById = bucketById.findByIPorID(null, id); // entry is claiming the same ID as entry with different IP in our routing table -> ignore if(entryById.isPresent() && !entryById.get().getAddress().getAddress().equals(ip)) return; // ID mismatch from call (not the same as ID mismatch from routing table) // it's fishy at least. don't insert even if it proves useful during a lookup if(!entryById.isPresent() && expectedId.isPresent() && !expectedId.get().equals(id)) return; KBucketEntry newEntry = new KBucketEntry(msg.getOrigin(), id); msg.getVersion().ifPresent(newEntry::setVersion); // throttle the insert-attempts for unsolicited requests, update-only once they exceed the threshold // does not apply to responses if(!associatedCall.isPresent() && updateAndCheckThrottle(newEntry.getAddress().getAddress())) { refreshOnly(newEntry); return; } associatedCall.ifPresent(c -> { newEntry.signalResponse(c.getRTT()); newEntry.mergeRequestTime(c.getSentTime()); }); // force trusted entry into the routing table (by splitting if necessary) if it passed all preliminary tests and it's not yet in the table // although we can only trust responses, anything else might be spoofed to clobber our routing table boolean trustedAndNotPresent = !entryById.isPresent() && msg.getType() == Type.RSP_MSG && trustedNodes.stream().anyMatch(mask -> mask.contains(ip)); Set<InsertOptions> opts = EnumSet.noneOf(InsertOptions.class); if(trustedAndNotPresent) opts.addAll(EnumSet.of(FORCE_INTO_MAIN_BUCKET, REMOVE_IF_FULL)); if(msg.getType() == Type.RSP_MSG) opts.add(RELAXED_SPLIT); insertEntry(newEntry, opts); // we already should have the bucket. might be an old one by now due to splitting // but it doesn't matter, we just need to update the entry, which should stay the same object across bucket splits if(msg.getType() == Type.RSP_MSG) { bucketById.notifyOfResponse(msg); } num_receives++; } public static final long throttleIncrement = 10; public static final long throttleSaturation = 1000; public static final long throttleThreshold = 30; public static final long throttleUpdateIntervalMinutes = 1; /** * @return true if it should be throttled */ boolean updateAndCheckThrottle(InetAddress addr) { long now = System.currentTimeMillis(); long oldVal = unsolicitedThrottle.getOrDefault(addr, 0L); unsolicitedThrottle.put(addr, Math.min(oldVal + throttleIncrement, throttleSaturation)); return oldVal > throttleThreshold; } private Optional<Pair<KBucket, KBucketEntry>> bucketForIP(InetAddress addr) { return Optional.ofNullable(knownNodes.get(addr)).map(RoutingTableEntry::getBucket).flatMap(bucket -> bucket.findByIPorID(addr, null).map(Pair.of(bucket))); } public void insertEntry(KBucketEntry entry, boolean internalInsert) { insertEntry(entry, internalInsert ? EnumSet.of(FORCE_INTO_MAIN_BUCKET) : EnumSet.noneOf(InsertOptions.class) ); } static enum InsertOptions { ALWAYS_SPLIT_IF_FULL, NEVER_SPLIT, RELAXED_SPLIT, REMOVE_IF_FULL, FORCE_INTO_MAIN_BUCKET } void refreshOnly(KBucketEntry toRefresh) { KBucket bucket = routingTableCOW.entryForId(toRefresh.getID()).getBucket(); bucket.refresh(toRefresh); } void insertEntry(KBucketEntry toInsert, Set<InsertOptions> opts) { if(usedIDs.contains(toInsert.getID()) || AddressUtils.isBogon(toInsert.getAddress())) return; if(!dht.getType().PREFERRED_ADDRESS_TYPE.isInstance(toInsert.getAddress().getAddress())) throw new IllegalArgumentException("attempting to insert "+toInsert+" expected address type: "+dht.getType().PREFERRED_ADDRESS_TYPE.getSimpleName()); Key nodeID = toInsert.getID(); RoutingTableEntry tableEntry = routingTableCOW.entryForId(nodeID); while(!opts.contains(NEVER_SPLIT) && tableEntry.bucket.isFull() && (opts.contains(FORCE_INTO_MAIN_BUCKET) || toInsert.verifiedReachable()) && tableEntry.prefix.getDepth() < Key.KEY_BITS - 1) { if(!opts.contains(ALWAYS_SPLIT_IF_FULL) && !canSplit(tableEntry, toInsert, opts.contains(RELAXED_SPLIT))) break; splitEntry(tableEntry); tableEntry = routingTableCOW.entryForId(nodeID); } int oldSize = tableEntry.bucket.getNumEntries(); KBucketEntry toRemove = null; if(opts.contains(REMOVE_IF_FULL)) { toRemove = tableEntry.bucket.getEntries().stream().filter(e -> trustedNodes.stream().noneMatch(mask -> mask.contains(e.getAddress().getAddress()))).max(KBucketEntry.AGE_ORDER).orElse(null); } if(opts.contains(FORCE_INTO_MAIN_BUCKET)) tableEntry.bucket.modifyMainBucket(toRemove,toInsert); else tableEntry.bucket.insertOrRefresh(toInsert); // add delta to the global counter. inaccurate, but will be rebuilt by the bucket checks num_entries += tableEntry.bucket.getNumEntries() - oldSize; } boolean canSplit(RoutingTableEntry entry, KBucketEntry toInsert, boolean relaxedSplitting) { if(entry.homeBucket) return true; if(!relaxedSplitting) return false; Comparator<Key> comp = new Key.DistanceOrder(toInsert.getID()); Key closestLocalId = usedIDs.stream().min(comp).orElseThrow(() -> new IllegalStateException("expected to find a local ID")); KClosestNodesSearch search = new KClosestNodesSearch(closestLocalId, DHTConstants.MAX_ENTRIES_PER_BUCKET, dht); search.filter = x -> true; search.fill(); List<KBucketEntry> found = search.getEntries(); if(found.size() < DHTConstants.MAX_ENTRIES_PER_BUCKET) return true; KBucketEntry max = found.get(found.size()-1); return closestLocalId.threeWayDistance(max.getID(), toInsert.getID()) > 0; } private void splitEntry(RoutingTableEntry entry) { synchronized (CoWLock) { RoutingTable current = routingTableCOW; // check if we haven't entered the sync block after some other thread that did the same split operation if(current.stream().noneMatch(e -> e == entry)) return; RoutingTableEntry a = new RoutingTableEntry(entry.prefix.splitPrefixBranch(false), new KBucket(), this::isLocalBucket); RoutingTableEntry b = new RoutingTableEntry(entry.prefix.splitPrefixBranch(true), new KBucket(), this::isLocalBucket); RoutingTable newTable = current.modify(Arrays.asList(entry), Arrays.asList(a, b)); routingTableCOW = newTable; // suppress recursive splitting to relinquish the lock faster. this method is generally called in a loop anyway for(KBucketEntry e : entry.bucket.getEntries()) insertEntry(e, EnumSet.of(InsertOptions.NEVER_SPLIT, InsertOptions.FORCE_INTO_MAIN_BUCKET)); } // replacements are less important, transfer outside lock for(KBucketEntry e : entry.bucket.getReplacementEntries()) insertEntry(e, EnumSet.noneOf(InsertOptions.class)); } public RoutingTable table() { return routingTableCOW; } public Stream<Map.Entry<InetAddress, Long>> throttledEntries() { return unsolicitedThrottle.entrySet().stream(); } /** * @return OurID */ public Key getRootID () { return baseKey; } public boolean isLocalId(Key id) { return usedIDs.contains(id); } public boolean isLocalBucket(Prefix p) { return usedIDs.stream().anyMatch(p::isPrefixOf); } public Collection<Key> localIDs() { return usedIDs.snapshot(); } public DHT getDHT() { return dht; } /** * Increase the failed queries count of the bucket entry we sent the message to */ void onTimeout (RPCCall call) { // don't timeout anything if we don't have a connection if(isInSurvivalMode()) return; if(!call.getRequest().getServer().isReachable()) return; InetSocketAddress dest = call.getRequest().getDestination(); if(call.getExpectedID() != null) { routingTableCOW.entryForId(call.getExpectedID()).bucket.onTimeout(dest); } else { RoutingTableEntry entry = knownNodes.get(dest.getAddress()); if(entry != null) entry.bucket.onTimeout(dest); } } void decayThrottle() { unsolicitedThrottle.replaceAll((addr, i) -> { return i - 1; }); unsolicitedThrottle.values().removeIf(e -> e <= 0); } public boolean isInSurvivalMode() { return dht.getServerManager().getActiveServerCount() == 0; } void removeId(Key k) { usedIDs.remove(k); dht.getScheduler().execute(singleThreadedUpdateHomeBuckets); } void registerServer(RPCServer srv) { srv.onEnqueue(this::onOutgoingRequest); } private void onOutgoingRequest(RPCCall c) { Key expectedId = c.getExpectedID(); if(expectedId == null) return; KBucket bucket = routingTableCOW.entryForId(expectedId).getBucket(); bucket.findByIPorID(c.getRequest().getDestination().getAddress(), expectedId).ifPresent(entry -> { entry.signalScheduledRequest(); }); bucket.replacementsStream().filter(r -> r.getAddress().equals(c.getRequest().getDestination())).findAny().ifPresent(KBucketEntry::signalScheduledRequest); } Key registerId() { int idx = 0; Key k = null; while(true) { k = getRootID().getDerivedKey(idx); if(usedIDs.add(k)) break; idx++; } dht.getScheduler().execute(singleThreadedUpdateHomeBuckets); return k; } /** * Check if a buckets needs to be refreshed, and refresh if necessary. */ public void doBucketChecks (long now) { boolean survival = isInSurvivalMode(); // don't spam the checks if we're not receiving anything. // we don't want to cause too many stray packets somewhere in a network if(survival && now - timeOfLastPingCheck > DHTConstants.BOOTSTRAP_MIN_INTERVAL) return; timeOfLastPingCheck = now; mergeBuckets(); int newEntryCount = 0; Map<InetAddress, KBucket> addressDedup = new HashMap<>(num_entries); for (RoutingTableEntry e : routingTableCOW.entries) { KBucket b = e.bucket; List<KBucketEntry> entries = b.getEntries(); Set<Key> localIds = usedIDs.snapshot(); boolean wasFull = b.getNumEntries() >= DHTConstants.MAX_ENTRIES_PER_BUCKET; for (KBucketEntry entry : entries) { // remove really old entries, ourselves and bootstrap nodes if the bucket is full if (localIds.contains(entry.getID()) || (wasFull && DHTConstants.BOOTSTRAP_NODE_ADDRESSES.contains(entry.getAddress()))) { b.removeEntryIfBad(entry, true); continue; } // remove duplicate addresses. prefer to keep reachable entries addressDedup.compute(entry.getAddress().getAddress(), (addr, oldBucket) -> { if(oldBucket != null) { KBucketEntry oldEntry = oldBucket.findByIPorID(addr, null).orElse(null); if(oldEntry != null) { if(oldEntry.verifiedReachable()) { b.removeEntryIfBad(entry, true); return oldBucket; } else if(entry.verifiedReachable()) { oldBucket.removeEntryIfBad(oldEntry, true); } } } return b; }); } boolean refreshNeeded = b.needsToBeRefreshed(); boolean replacementNeeded = b.needsReplacementPing(); if(refreshNeeded || replacementNeeded) tryPingMaintenance(b, "Refreshing Bucket #" + e.prefix, null, (task) -> { task.probeUnverifiedReplacement(replacementNeeded); }); if(!survival) { // only replace 1 bad entry with a replacement bucket entry at a time (per bucket) b.promoteVerifiedReplacement(); } newEntryCount += e.bucket.getNumEntries(); } num_entries = newEntryCount; rebuildAddressCache(); decayThrottle(); } void tryPingMaintenance(KBucket b, String reason, RPCServer srv, Consumer<PingRefreshTask> taskConfig) { if(srv == null) srv = dht.getServerManager().getRandomActiveServer(true); if(maintenanceTasks.containsKey(b)) return; if(srv != null) { PingRefreshTask prt = new PingRefreshTask(srv, this, null, false); if(taskConfig != null) taskConfig.accept(prt); prt.setInfo(reason); prt.addBucket(b); if(prt.getTodoCount() > 0 && maintenanceTasks.putIfAbsent(b, prt) == null) { prt.addListener(x -> maintenanceTasks.remove(b, prt)); dht.getTaskManager().addTask(prt); } } } void mergeBuckets() { int i = 0; // perform bucket merge operations where possible while(true) { i++; if(i < 1) continue; // fine-grained locking to interfere less with other operations synchronized (CoWLock) { if(i >= routingTableCOW.size()) break; RoutingTableEntry e1 = routingTableCOW.get(i - 1); RoutingTableEntry e2 = routingTableCOW.get(i); if (e1.prefix.isSiblingOf(e2.prefix)) { int effectiveSize1 = (int) (e1.getBucket().entriesStream().filter(e -> !e.removableWithoutReplacement()).count() + e1.getBucket().replacementsStream().filter(KBucketEntry::eligibleForNodesList).count()); int effectiveSize2 = (int) (e2.getBucket().entriesStream().filter(e -> !e.removableWithoutReplacement()).count() + e2.getBucket().replacementsStream().filter(KBucketEntry::eligibleForNodesList).count()); // uplift siblings if the other one is dead if (effectiveSize1 == 0 || effectiveSize2 == 0) { KBucket toLift = effectiveSize1 == 0 ? e2.getBucket() : e1.getBucket(); RoutingTable table = routingTableCOW; routingTableCOW = table.modify(Arrays.asList(e1, e2), Arrays.asList(new RoutingTableEntry(e2.prefix.getParentPrefix(), toLift, this::isLocalBucket))); i -= 2; continue; } // check if the buckets can be merged without losing entries if (effectiveSize1 + effectiveSize2 <= DHTConstants.MAX_ENTRIES_PER_BUCKET) { RoutingTable table = routingTableCOW; routingTableCOW = table.modify(Arrays.asList(e1, e2), Arrays.asList(new RoutingTableEntry(e1.prefix.getParentPrefix(), new KBucket(), this::isLocalBucket))); // no splitting to avoid fibrillation between merge and split operations for (KBucketEntry e : e1.bucket.getEntries()) insertEntry(e, EnumSet.of(InsertOptions.NEVER_SPLIT, InsertOptions.FORCE_INTO_MAIN_BUCKET)); for (KBucketEntry e : e2.bucket.getEntries()) insertEntry(e, EnumSet.of(InsertOptions.NEVER_SPLIT, InsertOptions.FORCE_INTO_MAIN_BUCKET)); e1.bucket.replacementsStream().forEach(r -> { insertEntry(r, EnumSet.of(InsertOptions.NEVER_SPLIT)); }); e2.bucket.replacementsStream().forEach(r -> { insertEntry(r, EnumSet.of(InsertOptions.NEVER_SPLIT)); }); i -= 2; continue; } } } } } final Runnable singleThreadedUpdateHomeBuckets = SerializedTaskExecutor.onceMore(this::updateHomeBuckets); void updateHomeBuckets() { while(true) { RoutingTable t = table(); List<RoutingTableEntry> changed = new ArrayList<>(); for(int i=0;i < t.size();i++) { RoutingTableEntry e = routingTableCOW.get(i); // update home bucket status on local ID change if(isLocalBucket(e.prefix) != e.homeBucket) changed.add(e); } synchronized (CoWLock) { if(routingTableCOW != t) continue; if(changed.isEmpty()) break; routingTableCOW = t.modify(changed, changed.stream().map(e -> new RoutingTableEntry(e.prefix, e.bucket, this::isLocalBucket)).collect(Collectors.toList())); break; } } } void rebuildAddressCache() { Map<InetAddress, RoutingTableEntry> newKnownMap = new HashMap<>(num_entries); RoutingTable table = routingTableCOW; for(int i=0,n=table.size();i<n;i++) { RoutingTableEntry entry = table.get(i); Stream<KBucketEntry> entries = entry.bucket.entriesStream(); entries.forEach(e -> { newKnownMap.put(e.getAddress().getAddress(), entry); }); } knownNodes = newKnownMap; } /** * Check if a buckets needs to be refreshed, and refresh if necesarry * * @param dh_table */ public void fillBuckets (DHTBase dh_table) { RoutingTable table = routingTableCOW; for (int i = 0;i<table.size();i++) { RoutingTableEntry entry = table.get(i); int num = entry.bucket.getNumEntries(); // just try to fill partially populated buckets // not empty ones, they may arise as artifacts from deep splitting if (num > 0 && num < DHTConstants.MAX_ENTRIES_PER_BUCKET) { NodeLookup nl = dh_table.fillBucket(entry.prefix.createRandomKeyFromPrefix(), entry.bucket); if (nl != null) { nl.setInfo("Filling Bucket #" + entry.prefix); } } } } /** * Saves the routing table to a file * * @param file to save to * @throws IOException */ void saveTable(Path saveTo) throws IOException { ByteBuffer tableBuffer = ByteBuffer.allocateDirect(50*1024*1024); Map<String,Object> tableMap = new TreeMap<>(); RoutingTable table = routingTableCOW; List<Map<String, Object>> main = new ArrayList<>(); List<Map<String, Object>> replacements = new ArrayList<>(); table.stream().map(RoutingTableEntry::getBucket).forEach(b -> { b.entriesStream().map(KBucketEntry::toBencoded).collect(Collectors.toCollection(() -> main)); b.getReplacementEntries().stream().map(KBucketEntry::toBencoded).collect(Collectors.toCollection(() -> replacements)); }); tableMap.put("mainEntries", main); tableMap.put("replacements", replacements); ByteBuffer doubleBuf = ByteBuffer.wrap(new byte[8]); doubleBuf.putDouble(0, dht.getEstimator().getRawDistanceEstimate()); tableMap.put("log2estimate", doubleBuf); tableMap.put("timestamp", System.currentTimeMillis()); tableMap.put("oldKey", getRootID().getHash()); new BEncoder().encodeInto(tableMap, tableBuffer); Path tempFile = Files.createTempFile(saveTo.getParent(), "saveTable", "tmp"); try(SeekableByteChannel chan = Files.newByteChannel(tempFile, StandardOpenOption.WRITE, StandardOpenOption.SYNC)) { chan.write(tableBuffer); chan.close(); Files.move(tempFile, saveTo, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); }; } void initKey(DHTConfiguration config) { // TODO: refactor into an external key-supplier? if(config != null && config.isPersistingID()) { Path keyPath = config.getStoragePath().resolve("baseID.config"); File keyFile = keyPath.toFile(); if (keyFile.exists() && keyFile.isFile()) { try { List<String> raw = Files.readAllLines(keyPath); baseKey = raw.stream().map(String::trim).filter(Key.STRING_PATTERN.asPredicate()).findAny().map(Key::new).orElseThrow(() -> new IllegalArgumentException(keyPath.toString()+" did not contain valid node ID")); return; } catch (Exception e) { e.printStackTrace(); } } } baseKey = Key.createRandomKey(); persistKey(); } void persistKey() { DHTConfiguration config = dht.getConfig(); if(config == null) return; Path keyPath = config.getStoragePath().resolve("baseID.config"); try { if(!Files.isDirectory(config.getStoragePath())) return; Path tmpFile = Files.createTempFile(config.getStoragePath(), "baseID", ".tmp"); Files.write(tmpFile, Collections.singleton(baseKey.toString(false)), StandardCharsets.ISO_8859_1); Files.move(tmpFile, keyPath, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Loads the routing table from a file * * @param file * @param runWhenLoaded is executed when all load operations are finished * @throws IOException */ void loadTable (Path tablePath) { File f = tablePath.toFile(); if(!f.exists() || !f.isFile()) return; try(FileChannel chan = FileChannel.open(tablePath, StandardOpenOption.READ)) { // don't use mmap, that would keep the file undeletable on windows, which would interfere with write-atomicmove persistence ByteBuffer buf = ByteBuffer.allocateDirect((int)chan.size()); chan.read(buf); buf.flip(); Map<String, Object> table = ThreadLocalUtils.getDecoder().decode(buf); AtomicInteger counter = new AtomicInteger(); Key oldKey = typedGet(table, "oldKey", byte[].class).filter(b -> b.length == Key.SHA1_HASH_LENGTH).map(Key::new).orElse(null); boolean reuseKey = getRootID().equals(oldKey); typedGet(table, "mainEntries", List.class).ifPresent(l -> { l.stream().filter(Map.class::isInstance).map(Map.class::cast).forEach(entryMap -> { KBucketEntry be = KBucketEntry.fromBencoded((Map<String, Object>) entryMap, dht.getType()); insertEntry(be, reuseKey ? EnumSet.of(ALWAYS_SPLIT_IF_FULL, FORCE_INTO_MAIN_BUCKET) : EnumSet.noneOf(InsertOptions.class)); counter.incrementAndGet(); }); }); typedGet(table, "replacements", List.class).ifPresent(l -> { l.stream().filter(Map.class::isInstance).map(Map.class::cast).forEach(replacementMap -> { KBucketEntry be = KBucketEntry.fromBencoded((Map<String, Object>) replacementMap, dht.getType()); routingTableCOW.entryForId(be.getID()).bucket.insertInReplacementBucket(be); counter.incrementAndGet(); }); }); typedGet(table, "log2estimate", byte[].class).filter(b -> b.length == 8).ifPresent(b -> { ByteBuffer doubleBuf = ByteBuffer.wrap(b); dht.getEstimator().setInitialRawDistanceEstimate(doubleBuf.getDouble()); }); long timeStamp = typedGet(table, "timestamp", Long.class).orElse(-1L); DHT.logInfo("Loaded " + counter.get() + " entries from cache. Cache was " + ((System.currentTimeMillis() - timeStamp) / (60 * 1000)) + "min old. Reusing old id = " + reuseKey); rebuildAddressCache(); } catch (IOException e) { DHT.log(e, LogLevel.Error); }; } /** * Get the number of entries in the routing table * * @return */ public int getNumEntriesInRoutingTable () { return num_entries; } public void setTrustedNetMasks(Collection<NetMask> masks) { trustedNodes = masks; } public Collection<NetMask> getTrustedNetMasks() { return trustedNodes; } public Optional<KBucketEntry> getRandomEntry() { RoutingTable table = routingTableCOW; int offset = ThreadLocalRandom.current().nextInt(table.size()); // sweep from a random offset in case there are empty buckets return IntStream.range(0, table.size()).mapToObj(i -> table.get((i + offset) % table.size()).getBucket().randomEntry()).filter(Optional::isPresent).map(Optional::get).findAny(); } @Override public String toString() { StringBuilder b = new StringBuilder(10000); RoutingTable table = routingTableCOW; Collection<Key> localIds = localIDs(); b.append("buckets: ").append(table.size()).append(" / entries: ").append(num_entries).append('\n'); for(RoutingTableEntry e : table.entries) { b.append(e.prefix).append(" num:").append(e.bucket.getNumEntries()).append(" rep:").append(e.bucket.getNumReplacements()); if(localIds.stream().anyMatch(e.prefix::isPrefixOf)) b.append(" [Home]"); b.append('\n'); } return b.toString(); } }
package ch.fhnw.main; public class Main { public static void main(String[] args) { System.out.println("Start App"); } private int getOptimalNumberOfHashfunctions(int inFilterSize, int inNumberOfInsertedElements){ int m = inFilterSize; int n = inNumberOfInsertedElements; return (int) ( m / n * Math.log(2) ); } }
package channels; import core.AgentEngine; import com.researchworx.cresco.library.messaging.MsgEvent; public class MsgRoute implements Runnable { private MsgEvent rm; public MsgRoute(MsgEvent rm) { this.rm = rm; } public void run() { try { if (!getTTL()) { return; } int routePath = getRoutePath(); MsgEvent re = null; switch (routePath) { case 52: //System.out.println("AGENT ROUTE TO EXTERNAL VIA CONTROLLER : 52 " + rm.getParams()); sendToController(); break; case 53: //System.out.println("AGENT REGIONAL WATCHDOG : 53 " + rm.getParams()); sendToController(); break; case 56: //System.out.println("AGENT ROUTE TO COMMANDEXEC : 56 " + rm.getParams()); re = getCommandExec(); break; case 61: //System.out.println("AGENT ROUTE TO COMMANDEXEC : 61 " + rm.getParams()); re = getCommandExec(); break; case 62: //System.out.println("PLUGIN RPC CALL TO HOST AGENT : 62 " + rm.getParams()); sendToPlugin(); break; case 63: //System.out.println("PLUGIN DIRECT MESSAGE TO ANOTHER PLUGIN ON SAME AGENT : 63 " + rm.getParams()); sendToPlugin(); break; default: System.out.println("AGENT ROUTE CASE " + routePath + " " + rm.getParams()); break; } if (re != null) { re.setReturn(); //reverse to-from for return AgentEngine.msgInQueue.offer(re); //new Thread(new MsgRoute(re)).start(); } } catch (Exception ex) { ex.printStackTrace(); System.out.println("Agent : MsgRoute : Route Failed " + ex.toString()); } } private MsgEvent getCommandExec() { try { String callId = "callId-" + AgentEngine.region + "_" + AgentEngine.agent; //calculate callID if (rm.getParam(callId) != null) { //send message to RPC hash AgentEngine.rpcMap.put(rm.getParam(callId), rm); } else { return AgentEngine.commandExec.cmdExec(rm); } } catch (Exception ex) { System.out.println("AgentEngine : MsgRoute : getCommandExec Error : " + ex.getMessage()); } return null; } private void sendToController() { try { AgentEngine.pluginMap.get(AgentEngine.controllerPluginSlot).Message(rm); } catch (Exception ex) { System.out.println("AgentEngine : MsgRoute Error : " + ex.getMessage()); } } private void sendToPlugin() { try { AgentEngine.pluginMap.get(rm.getParam("dst_plugin")).Message(rm); } catch (Exception ex) { System.out.println("AgentEngine : sendToPlugin : " + ex.getMessage()); } } private int getRoutePath() { int routePath; try { //determine if local or controller String RXr = "0"; String RXa = "0"; String RXp = "0"; String TXr = "0"; String TXa = "0"; String TXp = "0"; if (rm.getParam("dst_region") != null) { if (rm.getParam("dst_region").equals(AgentEngine.region)) { RXr = "1"; if (rm.getParam("dst_agent") != null) { if (rm.getParam("dst_agent").equals(AgentEngine.agent)) { RXa = "1"; if (rm.getParam("dst_plugin") != null) { RXp = "1"; } } } } } if (rm.getParam("src_region") != null) { if (rm.getParam("src_region").equals(AgentEngine.region)) { TXr = "1"; if (rm.getParam("src_agent") != null) { if (rm.getParam("src_agent").equals(AgentEngine.agent)) { TXa = "1"; if (rm.getParam("src_plugin") != null) { TXp = "1"; } } } } } String routeString = RXr + TXr + RXa + TXa + RXp + TXp; routePath = Integer.parseInt(routeString, 2); } catch (Exception ex) { System.out.println("AgentEngine : MsgRoute : getRoutePath Error: " + ex.getMessage()); ex.printStackTrace(); routePath = -1; } //System.out.println("AGENT ROUTEPATH=" + routePath + " MsgType=" + rm.getMsgType() + " Params=" + rm.getParams()); return routePath; } private boolean getTTL() { boolean isValid = true; try { if (rm.getParam("ttl") != null) //loop detection { int ttlCount = Integer.valueOf(rm.getParam("ttl")); if (ttlCount > 10) { System.out.println("**Agent : MsgRoute : High Loop Count**"); System.out.println("MsgType=" + rm.getMsgType().toString()); System.out.println("Region=" + rm.getMsgRegion() + " Agent=" + rm.getMsgAgent() + " plugin=" + rm.getMsgPlugin()); System.out.println("params=" + rm.getParams()); isValid = false; } ttlCount++; rm.setParam("ttl", String.valueOf(ttlCount)); } else { rm.setParam("ttl", "0"); } } catch (Exception ex) { isValid = false; } return isValid; } }
package com.tterrag.k9; import java.io.File; import java.io.FilePermission; import java.io.IOException; import java.nio.file.Paths; import java.security.AccessControlException; import java.security.AccessController; import java.util.Scanner; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import com.google.common.base.Charsets; import com.google.common.io.Files; import com.tterrag.k9.commands.api.CommandRegistrar; import com.tterrag.k9.irc.IRC; import com.tterrag.k9.listeners.CommandListener; import com.tterrag.k9.listeners.EnderIOListener; import com.tterrag.k9.listeners.IncrementListener; import com.tterrag.k9.logging.PrettifyMessageCreate; import com.tterrag.k9.mappings.mcp.McpDownloader; import com.tterrag.k9.mappings.yarn.YarnDownloader; import com.tterrag.k9.util.annotation.NonNull; import com.tterrag.k9.util.PaginatedMessageFactory; import com.tterrag.k9.util.Threads; import discord4j.core.DiscordClient; import discord4j.core.DiscordClientBuilder; import discord4j.core.event.domain.lifecycle.ReadyEvent; import discord4j.core.event.domain.message.MessageCreateEvent; import discord4j.core.event.domain.message.ReactionAddEvent; import discord4j.core.object.presence.Activity; import discord4j.core.object.presence.Presence; import lombok.extern.slf4j.Slf4j; import reactor.core.publisher.Hooks; import reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; @Slf4j public class K9 { private static class Arguments { @Parameter(names = { "-a", "--auth" }, description = "The Discord app key to authenticate with.", required = true) private String authKey; @Parameter(names = { "--ircnick" }, hidden = true) private String ircNickname; @Parameter(names = { "--ircpw" }, hidden = true) private String ircPassword; @Parameter(names = "--ltkey", hidden = true) private String loveTropicsKey; @Parameter(names = " --mindonation", hidden = true) private int minDonation = 25; } private static Arguments args; public static @NonNull CommandRegistrar commands = new CommandRegistrar(null); public static void main(String[] argv) { try { AccessController.checkPermission(new FilePermission(".", "read")); } catch (AccessControlException e) { throw new RuntimeException("Invalid policy settings!", e); } args = new Arguments(); JCommander.newBuilder().addObject(args).build().parse(argv); String protocol = K9.class.getResource("").getProtocol(); if (!"jar".equals(protocol)) { // Only enable this in IDEs Hooks.onOperatorDebug(); } DiscordClient client = new DiscordClientBuilder(args.authKey) .build(); PrettifyMessageCreate.client = client; commands = new CommandRegistrar(client); client.getEventDispatcher().on(ReadyEvent.class).subscribe(new K9()::onReady); new CommandListener(commands).subscribe(client.getEventDispatcher()); client.getEventDispatcher().on(ReactionAddEvent.class) .flatMap(evt -> PaginatedMessageFactory.INSTANCE.onReactAdd(evt) .onErrorContinue((t, $) -> log.error("Error paging message", t))) .subscribe(); client.getEventDispatcher().on(MessageCreateEvent.class) .flatMap(IncrementListener.INSTANCE::onMessage) .doOnNext(EnderIOListener.INSTANCE::onMessage) .doOnNext(IRC.INSTANCE::onMessage) .subscribe(); // Make sure shutdown things are run, regardless of where shutdown came from // The above System.exit(0) will trigger this hook Runtime.getRuntime().addShutdownHook(new Thread(() -> { commands.onShutdown(); client.logout().block(); })); // Handle "stop" and any future commands Mono.fromCallable(() -> { Scanner scan = new Scanner(System.in); while (true) { while (scan.hasNextLine()) { if (scan.nextLine().equals("stop")) { scan.close(); System.exit(0); } } Threads.sleep(100); } }).subscribeOn(Schedulers.newSingle("Console Listener")) .subscribe(); if(args.ircNickname != null && args.ircPassword != null) { Mono.fromRunnable(() -> IRC.INSTANCE.connect(args.ircNickname, args.ircPassword)) .publishOn(Schedulers.newSingle("IRC Thread")) .subscribe(); } commands.slurpCommands(); client.login().block(); } public void onReady(ReadyEvent event) { log.info("Bot connected, starting up..."); McpDownloader.INSTANCE.start(); YarnDownloader.INSTANCE.start(); // if (args.loveTropicsKey != null) { // instance.getDispatcher().registerListener(new LoveTropicsListener(args.loveTropicsKey, args.minDonation)); commands.complete(); // Change playing text to global help command event.getClient().getSelf() .map(u -> "@" + u.getUsername() + " help") .flatMap(s -> event.getClient().updatePresence(Presence.online(Activity.playing(s)))) .subscribe(); } public static String getVersion() { String ver = K9.class.getPackage().getImplementationVersion(); if (ver == null) { File head = Paths.get(".git", "HEAD").toFile(); if (head.exists()) { try { String refpath = Files.asCharSource(head, Charsets.UTF_8).readFirstLine().replace("ref: ", ""); File ref = head.toPath().getParent().resolve(refpath).toFile(); String hash = Files.asCharSource(ref, Charsets.UTF_8).readFirstLine(); ver = "DEV " + hash.substring(0, 8); } catch (IOException e) { log.error("Could not load version from git data: ", e); ver = "DEV"; } } else { ver = "DEV (no HEAD)"; } } return ver; } }
package com.workerbee; import org.apache.hadoop.io.Text; import java.util.HashMap; import java.util.Map; public class Row<T extends Table> { private Map<Column, Object> map; private Table table; public Row(Table<T> table, String record){ this.table = table; this.map = parseRecordUsing(table, record); } public Row(Table<T> table, Text record){ this(table, record.toString()); } public Row(Table<T> table){ this(table, ""); } private static Map<Column, Object> parseRecordUsing(Table<? extends Table> table, String record) { Map<Column, Object> map = new HashMap<Column, Object>(table.getColumns().size()); RecordParser recordParser = new RecordParser(record, table.getColumnSeparator(), table.getHiveNull()); int index = 0; for (Column column : table.getColumns()) { map.put(column, column.parseValueUsing(recordParser, index++)); } for (Column column : table.getPartitions()) { map.put(column, column.parseValueUsing(recordParser, index++)); } return map; } public Object get(Column column) { return map.get(column); } public String getString(Column column) { return (String) get(column); } public Integer getInt(Column column) { return (Integer) get(column); } public Float getFloat(Column column) { return (Float) get(column); } public Row<T> set(Column column, Object value) { if (map.containsKey(column)){ map.put(column, column.convert(value)); } return this; } public String generateRecord() { return Row.generateRecordFor(table, this); } public Text generateTextRecord() { return new Text(Row.generateRecordFor(table, this)); } public static String generateRecordFor(Table<? extends Table> table, Row row) { StringBuilder result = new StringBuilder(); for (Column column : table.getColumns()) { Object value = row.get(column); result.append(value == null ? table.getHiveNull() : value.toString()); result.append(table.getColumnSeparator()); } for (Column column : table.getPartitions()) { Object value = row.get(column); result.append(value == null ? table.getHiveNull() : value.toString()); result.append(table.getColumnSeparator()); } result.delete(result.lastIndexOf(table.getColumnSeparator()), result.length()); return result.toString(); } }
package dominio; import java.io.Serializable; import java.util.HashMap; /** * establece el personaje usado por el jugador, con su nombre, alianza, * habilidades y atributos */ public abstract class Personaje extends Character implements Peleable, Serializable { private static final long serialVersionUID = 1L; protected int energia; protected int ataque; protected int magia; protected int saludTope; protected int destreza; protected int inteligencia; protected int energiaTope; protected int experiencia; protected int idPersonaje; protected int x; protected int y; public static int[] tablaDeNiveles; protected String nombreRaza; protected String nombreCasta; protected String[] habilidadesRaza = new String[CANTHABILIDADESRAZA]; protected String[] habilidadesCasta = new String[CANTHABILIDADESCASTA]; protected Casta casta; protected Alianza clan = null; protected static final int SALUDINICIAL = 100; protected static final int FUERZAINICIAL = 10; protected static final int DEFENSAINICIAL = 10; protected static final int TABLANIVELES = 101; protected static final int TABLANIVELES50 = 50; protected static final int INTELIGENCIAINICIAL = 10; protected static final int DESTREZAINICIAL = 10; protected static final int SALUDTOPEINICIAL = 100; protected static final int ENERGIATOPEINICIAL = 100; protected static final int ENERGIAMINIMA = 10; protected static final int MAXIMONIVEL = 100; protected static final int MAXIMAFUERZA = 200; protected static final int MAXIMADESTREZA = 200; protected static final int MAXIMAINTELIGENCIA = 200; protected static final double MULTIPLICADORFUERZA = 1.5; protected static final double MULTIPLICADORINTELIGENCIA = 1.5; protected static final int DIVISORDEDESTREZA = 1000; protected static final int EXPERIENCIAPORNIVEL = 40; protected static final int SALUDEXTRAPORNIVEL = 25; protected static final int ENERGIAEXTRAPORNIVEL = 20; protected static final int CANTHABILIDADESRAZA = 2; protected static final int CANTHABILIDADESCASTA = 3; /** * Devuelve las habilidades de la casta * @return String[] */ public String[] getHabilidadesCasta() { return casta.getHabilidadesCasta(); } /** * establece la experencia necesaria para alcanzar cada uno de los niveles * del personaje */ public static void cargarTablaNivel() { Personaje.tablaDeNiveles = new int[TABLANIVELES]; Personaje.tablaDeNiveles[0] = 0; Personaje.tablaDeNiveles[1] = 0; for (int i = 2; i < TABLANIVELES; i++) { Personaje.tablaDeNiveles[i] = Personaje.tablaDeNiveles[i - 1] + TABLANIVELES50; } } /** * crea un personaje nivel 1 de una casta determinada, con atributos * predeterminados ligeramente cambiantes dependiendo de dicha casta { * @param nombre * Nombre del Personaje * @param casta * Casta del Personaje * @param id * ID unica del personaje */ public Personaje(final String nombre, final Casta casta, final int id) { super(SALUDINICIAL, FUERZAINICIAL, DEFENSAINICIAL, nombre, 1); this.casta = casta; this.idPersonaje = id; experiencia = 0; inteligencia = INTELIGENCIAINICIAL; destreza = DESTREZAINICIAL; saludTope = SALUDTOPEINICIAL; energiaTope = ENERGIATOPEINICIAL; this.aumentarSaludTope(getSALUDEXTRA()); this.aumentarEnergiaTope(getENERGIAEXTRA()); this.aumentarFuerza(casta.getBonusFuerza()); this.aumentarDestreza(casta.getBonusDestreza()); this.aumentarInteligencia(casta.getBonusInteligencia()); nombreRaza = getNombreRaza(); nombreCasta = casta.getNombreCasta(); habilidadesRaza = getHabilidadesRaza(); habilidadesCasta = casta.getHabilidadesCasta(); x = 0; y = 0; this.aumentarSalud(getSALUDEXTRA()); this.aumentarEnergia(energiaTope); ataque = this.calcularPuntosDeAtaque(); magia = this.calcularPuntosDeMagia(); } /** * crea un personaje con nivel y demas atributos enviados por parametro { * @param nombre * Nombre del Personaje * @param salud * Cantidad de salud * @param energia * Cantidad de energia * @param fuerza * Cantidad de fuerza * @param destreza * Cantidad de destreza * @param inteligencia * Cantidad de inteligencia * @param casta * Clase Casta * @param experiencia * Cantidad de experiencia * @param nivel * Cantidad de nivel * @param idPersonaje * ID del personaje */ public Personaje(final String nombre, final int salud, final int energia, final int fuerza, final int destreza, final int inteligencia, final Casta casta, final int experiencia, final int nivel, final int idPersonaje) { super(salud, fuerza, destreza, nombre, nivel); this.energia = energia; this.destreza = destreza; this.inteligencia = inteligencia; this.casta = casta; this.experiencia = experiencia; this.saludTope = this.getSalud(); this.energiaTope = this.energia; this.idPersonaje = idPersonaje; this.ataque = this.calcularPuntosDeAtaque(); this.magia = this.calcularPuntosDeMagia(); } /** * Establece el nombre de la raza * @param nombreRaza * Nombre de la Raza */ public void setNombreRaza(final String nombreRaza) { this.nombreRaza = nombreRaza; } /** * devuelve el valor del atributo "ataque" * @return ataque Valor de la ataque */ public int getAtaque() { return ataque; } /** * establece un valor para el atributo "ataque" * @param ataque * Valor de la ataque */ public void setAtaque(final int ataque) { this.ataque = ataque; } /** * Devuelve el valor del aributo "magia" * @return int Valor de la magia */ public int getMagia() { return magia; } /** * Establece un valor para el atributo "magia" * @param magia * Valor de la magia */ public void setMagia(final int magia) { this.magia = magia; } /** * Devuelve el valor del atributo "clan" * @return Alianza Lista de la Alianza */ public Alianza getClan() { return clan; } /** * Establece un valor para el atributo "clan" * @param clan * Se establece el clan */ public void setClan(final Alianza clan) { this.clan = clan; clan.agregarPersonaje(this); } /** * Devuelve el valor del atributo "energia" * @return int Valor de la energia */ public int getEnergia() { return energia; } /** * Devuelve el valor del atributo "destreza" * @return int Valor de la destreza */ public int getDestreza() { return destreza; } /** * Devuelve el valor del atributo "inteligencia" * @return int Valor de la inteligencia */ public int getInteligencia() { return inteligencia; } /** * Devuelve el valor del atributo "casta" * @return Casta Valor de la Casta */ public Casta getCasta() { return casta; } /** * Devuelve el valor del atributo "experiencia" * @return int Valor de la experiencia */ public int getExperiencia() { return experiencia; } /** * Devuelve el valor del atributo "idPersonaje" * @return int ID unica del Personaje */ public int getIdPersonaje() { return idPersonaje; } /** * Devuelve el valor del atributo "saludTope" * @return int Valor de la Salud al tope */ public int getSaludTope() { return saludTope; } /** * Devuelve el valor del atributo "energiaTope" * @return int Valor de la energia al tope */ public int getEnergiaTope() { return energiaTope; } /** * Permite un ataque de un personaje a otro, estableciendo condiciones para * el mismo y efectos random define la probabilidad de golpe critico * @param atacado * Peleable al que se le ataca * @param random * Numero Random para evitar el ataque * @return int Devuelve el danio */ public int atacar(final Peleable atacado, final RandomGenerator random) { int dano; if (this.getSalud() == 0) { return 0; } if (atacado.getSalud() > 0) { if (random.nextDouble() <= this.casta.getProbabilidadGolpeCritico() + this.destreza / DIVISORDEDESTREZA) { dano = atacado.serAtacado(this.golpeCritico(), random); } else { dano = atacado.serAtacado(this.ataque, random); } if (atacado.estaVivo() == false) { this.ganarObjeto(); } return dano; } return 0; } /** * Gana un objeto y sus estadisticas * @return Objeto Retorna el objeto ganado */ public Objeto ganarObjeto() { HashMap<String, Integer> mapa = new HashMap<String, Integer>(); Objeto obj = inventario.agregarObjeto(); // Objeto obj= new Objeto(2); para test if (obj.atributoModificado.equals("saludTope")) { mapa.put(obj.atributoModificado, this.getSaludTope() + obj.getValor()); } if (obj.atributoModificado.equals("destreza")) { mapa.put(obj.atributoModificado, this.getDestreza() + obj.getValor()); } if (obj.atributoModificado.equals("fuerza")) { mapa.put(obj.atributoModificado, this.getFuerza() + obj.getValor()); } if (obj.atributoModificado.equals("defensa")) { mapa.put(obj.atributoModificado, this.getDefensa() + obj.getValor()); } if (obj.atributoModificado.equals("inteligencia")) { mapa.put(obj.atributoModificado, this.getInteligencia() + obj.getValor()); } if (obj.atributoModificado.equals("energiaTope")) { mapa.put(obj.atributoModificado, this.getEnergiaTope() + obj.getValor()); } this.actualizar(mapa); return obj; } /** * Se agrega un objeto al inventario y sus estadisticas */ public void agregarObjeto(Objeto obj) { HashMap<String, Integer> mapa = new HashMap<String, Integer>(); inventario.agregar(obj); if (obj.atributoModificado.equals("saludTope")) mapa.put(obj.atributoModificado, this.getSaludTope() + obj.getValor()); if (obj.atributoModificado.equals("destreza")) mapa.put(obj.atributoModificado, this.getDestreza() + obj.getValor()); if (obj.atributoModificado.equals("fuerza")) mapa.put(obj.atributoModificado, this.getFuerza() + obj.getValor()); if (obj.atributoModificado.equals("defensa")) mapa.put(obj.atributoModificado, this.getDefensa() + obj.getValor()); if (obj.atributoModificado.equals("inteligencia")) mapa.put(obj.atributoModificado, this.getInteligencia() + obj.getValor()); if (obj.atributoModificado.equals("energiaTope")) mapa.put(obj.atributoModificado, this.getEnergiaTope() + obj.getValor()); this.actualizar(mapa); } /** * Se elimina el objeto y sus estadisticas ganadas * @param obj Objeto a perder y con el sus estadisticas */ public void perderObjeto(final Objeto obj) { HashMap<String, Integer> mapa = new HashMap<String, Integer>(); if (obj.atributoModificado.equals("saludTope")) { mapa.put(obj.atributoModificado, this.getSaludTope() - obj.getValor()); } if (obj.atributoModificado.equals("destreza")) { mapa.put(obj.atributoModificado, this.getDestreza() - obj.getValor()); } if (obj.atributoModificado.equals("fuerza")) { mapa.put(obj.atributoModificado, this.getFuerza() - obj.getValor()); } if (obj.atributoModificado.equals("defensa")) { mapa.put(obj.atributoModificado, this.getDefensa() - obj.getValor()); } if (obj.atributoModificado.equals("inteligencia")) { mapa.put(obj.atributoModificado, this.getInteligencia() - obj.getValor()); } if (obj.atributoModificado.equals("energiaTope")) { mapa.put(obj.atributoModificado, this.getEnergiaTope() - obj.getValor()); } inventario.quitarObjeto(obj); this.actualizar(mapa); } /** * Permite que el personaje realize un "golpe critico", que hace mas danio * del normal * @return int Valor del golpe critico */ public int golpeCritico() { return (int) (this.ataque * this.getCasta().getDanoCritico()); } /** * Devuelve True o False, si puede atacar el personaje o no * @return true Si puede atacar */ public boolean puedeAtacar() { return energia > ENERGIAMINIMA; } /** * Devuelve el valor del atributo "Ataque" multiplicado por 1.5, depende de * la Fuerza * @return int Puntos de Ataque */ public int calcularPuntosDeAtaque() { return (int) (this.getFuerza() * MULTIPLICADORFUERZA); } /** * Devuelve el valor del atributo "Destreza" multiplicado por 1,5, depende * de la Destreza * @return int Puntos de Defensa */ public int calcularPuntosDeDefensa() { return (int) (this.getDestreza()); } /** * Devuelve el valor del atributo "Magia" multiplicado por 1,5, depende de * la Inteligencia * @return int Puntos de Magia */ public int calcularPuntosDeMagia() { return (int) (this.getInteligencia() * MULTIPLICADORINTELIGENCIA); } /** * establece el valor del atributo "salud" en el maximo posible */ public void restablecerSalud() { this.setSalud(this.saludTope); } /** * establece el valor del atributo "energia" en el maximo posible */ public void restablecerEnergia() { this.energia = this.energiaTope; } /** * modifica los valores de los atributos "ataque", "defensa" y "magia" */ public void modificarAtributos() { this.ataque = this.calcularPuntosDeAtaque(); this.setDefensa(this.calcularPuntosDeDefensa()); this.magia = this.calcularPuntosDeMagia(); } /** * permite que el personaje sea atacado por otro y establece los efectos y * condiciones de dicha accion * @param danio * Danio a realizar * @param random * Numero random para evitar el danio * @return int danio realizado */ public int serAtacado(final int danio, final RandomGenerator random) { if (random.nextDouble() >= this.getCasta().getProbabilidadEvitarDano()) { int auxDanio = danio; auxDanio -= this.getDefensa(); if (auxDanio > 0) { if (this.getSalud() <= auxDanio) { auxDanio = this.getSalud(); this.setSalud(0); } else { this.setSalud(this.getSalud() - auxDanio); } return auxDanio; } return 0; } return 0; } /** * El personaje ve reducido su atributo "salud", debido a un danio enviado * por parametro, siempre y cuando dicho danio sea mayor que la defensa del * personaje * @param danio * danio a realizar * @return int danio realizado */ public int serRobadoSalud(final int danio) { int auxDanio = danio; auxDanio -= this.getDefensa(); if (auxDanio <= 0) { return 0; } if ((this.getDefensa() - auxDanio) >= 0) { this.setSalud(this.getSalud() - auxDanio); } else { auxDanio = this.getSalud(); this.setSalud(0); } return auxDanio; } /** * El personaje ve reducido su atributo "energia", debido a un danio enviado * por parametro, siempre y cuando dicho danio sea mayor que la defensa del * personaje * @param danio * Danio a realizar * @return int danio realizado */ public int serDesernegizado(final int danio) { int auxDanio = danio; auxDanio -= this.getDefensa(); if (auxDanio <= 0) { return 0; } if ((energia - auxDanio) >= 0) { energia -= auxDanio; } else { auxDanio = energia; energia = 0; } return auxDanio; } /** * Aumenta la salud del personaje * @param salud * Cantidad de Salud a incrementar */ public void serCurado(final int salud) { if ((this.getSalud() + salud) <= this.saludTope) { this.setSalud(this.getSalud() + salud); } else { this.setSalud(this.saludTope); } } /** * Aumenta el valor del atributo "energia" * @param aumentoEnergia * Cantidad de Energia a incrementar */ public void serEnergizado(final int aumentoEnergia) { if ((this.energia + aumentoEnergia) <= this.energiaTope) { this.energia += aumentoEnergia; } else { this.energia = this.energiaTope; } } /** * Crea una alianza y establece al personaje como miembro de la misma * @param nombreAlianza * Nombre de la nueva alianza */ public void crearAlianza(final String nombreAlianza) { this.clan = new Alianza(nombreAlianza); this.clan.agregarPersonaje(this); } /** * Remueve al personaje de la alianza en que se encuentre */ public void salirDeAlianza() { if (this.clan != null) { this.clan.eliminarPersonaje(this); this.clan = null; } } /** * Establece una alianza entre este personaje y otro * @param nuevoAliado * Personaje a establecer la alianza * @return true Si se pudo completar la alianza */ public boolean aliar(final Personaje nuevoAliado) { if (this.clan == null) { Alianza a = new Alianza("Alianza 1"); this.clan = a; a.agregarPersonaje(this); } if (nuevoAliado.clan == null) { nuevoAliado.clan = this.clan; this.clan.agregarPersonaje(nuevoAliado); return true; } else { return false; } } /** * Aumenta los valores de los atributos "fuerza", "destreza" e * "inteligencia" y llama al metodo "modificarAtributos", que modifica los * valores de "ataque", "defensa" y "magia" * @param aumentoFuerza * Aumento de fuerza * @param aumentoDestreza * Aumento de destreza * @param aumentoInteligencia * Aumento de inteligencia */ public void asignarPuntosSkills(final int aumentoFuerza, final int aumentoDestreza, final int aumentoInteligencia) { if (this.getFuerza() + aumentoFuerza <= MAXIMAFUERZA) { this.setFuerza(this.getFuerza() + aumentoFuerza); } if (this.destreza + aumentoDestreza <= MAXIMADESTREZA) { this.destreza += aumentoDestreza; } if (this.inteligencia + aumentoInteligencia <= MAXIMAINTELIGENCIA) { this.inteligencia += aumentoInteligencia; } this.modificarAtributos(); } /** * Aumenta en 1 el nivel del personaje, con las modificaciones de atributos * que dicha accion implica */ public void subirNivel() { int acumuladorExperiencia = 0; if (this.getNivel() == MAXIMONIVEL) { return; } while (this.getNivel() != MAXIMONIVEL && (this.experiencia >= Personaje. tablaDeNiveles[this.getNivel() + 1] + acumuladorExperiencia)) { acumuladorExperiencia += Personaje.tablaDeNiveles[this.getNivel() + 1]; this.aumentarNivel(); this.modificarAtributos(); this.saludTope += SALUDEXTRAPORNIVEL; this.energiaTope += ENERGIAEXTRAPORNIVEL; } this.experiencia -= acumuladorExperiencia; } /** * aumenta la experiencia del personaje y sube de nivel si corresponde * @param exp * Experiencia que gana * @return true Si pudo subir de nivel */ public boolean ganarExperiencia(final int exp) { this.experiencia += exp; if (experiencia >= Personaje.tablaDeNiveles[this.getNivel() + 1]) { subirNivel(); return true; } return false; } /** * Devuelve el valor del atributo "nivel" multiplicado por 40 * @return int Experiencia por nivel */ public int otorgarExp() { return this.getNivel() * EXPERIENCIAPORNIVEL; } /** * Clona el objeto "personaje" * @return Object Devuelve el objeto clonado */ @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } /** * Devuelve la distancia entre el personaje y otro * @param p * Personaje que se le compara la distancia * @return double Es la distancia entre ambos personajes */ public double distanciaCon(final Personaje p) { return Math.sqrt(Math.pow(this.x - p.x, 2) + Math.pow(this.y - p.y, 2)); } /** * La Habilidad propia del Casta del personaje * @param atacado * En quien se realiza la Habilidad * @return true Si se pudo realizar la Habilidad */ public boolean habilidadCasta1(final Peleable atacado) { return this.getCasta().habilidad1(this, atacado); } /** * La Habilidad propia del Casta del personaje * @param atacado * En quien se realiza la Habilidad * @return true Si se pudo realizar la Habilidad */ public boolean habilidadCasta2(final Peleable atacado) { return this.getCasta().habilidad2(this, atacado); } /** * La Habilidad propia del Casta del personaje * @param atacado * En quien se realiza la Habilidad * @return true Si se pudo realizar la Habilidad */ public boolean habilidadCasta3(final Peleable atacado) { return this.getCasta().habilidad3(this, atacado); } /** * Habilidad propia de la raza del personaje * @param atacado * Peleable en que se utiliza la Habilidad * @param random * Numero Random para evitar la Habilidad * @return true Si se pudo realizar la Habilidad */ public abstract boolean habilidadRaza1(final Peleable atacado, final RandomGenerator random); /** * Habilidad propia de la raza del personaje * @param atacado * Peleable en que se utiliza la Habilidad * @param random * Numero Random para evitar la Habilidad * @return true Si se pudo realizar la Habilidad */ public abstract boolean habilidadRaza2(final Peleable atacado, final RandomGenerator random); /** * Se establece la posicion del Personaje * @param distanciaX Posicion X * @param distanciaY Posicion Y */ public void setDistancia(final int distanciaX, final int distanciaY) { this.x = distanciaX; this.y = distanciaY; } /** * Devuelve la posicion X del personaje * @return x La posicion X */ public int getX() { return x; } /** * Devuelve la posicion Y del personaje * @return y La posicion Y */ public int getY() { return y; } /** * Determina si es un NonPlayableCharacter * @return boolean Devuelve False siempre */ public boolean isNPC() { return false; } /** * Devuelve el Extra de Salud por la Raza * @return int Es la salud extra, puede ser 0(Elfo) , 5(Humano) o 10 (Orco) */ public abstract int getSALUDEXTRA(); /** * Devuelve el Extra de Energia por la Raza * @return int Es la Energia extra, * puede ser 0(Orco) , 5(Humano) o 10 (Elfo) */ public abstract int getENERGIAEXTRA(); /** * Devuelve el nombre de la raza * @return String Nombre de la Raza */ public abstract String getNombreRaza(); /** * devuelve las habilidades de la raza * @return String[] Las habilidades de la Raza */ public abstract String[] getHabilidadesRaza(); /** * Aumenta el valor actual de la saludTope con el parametro * @param aumento Valor que se le suma al actual */ public final void aumentarSaludTope(final int aumento) { saludTope += aumento; } /** * Aumenta el valor actual de la energiaTope con el parametro * @param aumento Valor que se le suma al actual */ public final void aumentarEnergiaTope(final int aumento) { energiaTope += aumento; } /** * Aumenta el valor actual de la energia con el parametro * @param aumento Valor que se le suma al actual */ public final void aumentarEnergia(final int aumento) { energia += aumento; } /** * Aumenta el valor actual de la ataque con el parametro * @param aumento Valor que se le suma al actual */ public final void aumentarAtaque(final int aumento) { ataque += aumento; } /** * Aumenta el valor actual de la destreza con el parametro * @param aumento Valor que se le suma al actual */ public final void aumentarDestreza(final int aumento) { destreza += aumento; } /** * Aumenta el valor actual de la magia con el parametro * @param aumento Valor que se le suma al actual */ public final void aumentarMagia(final int aumento) { magia += aumento; } /** * Aumenta el valor actual de la inteligencia con el parametro * @param aumento Valor que se le suma al actual */ public final void aumentarInteligencia(final int aumento) { inteligencia += aumento; } /** * Actualiza las estadisticas del Personaje * @param mapa Mapa de los atributos modificados */ public void actualizar(HashMap<String, ?> mapa) { // se va actualizando durante la batalla if (mapa.containsKey("salud")) { this.salud = (Integer) mapa.get("salud"); } if (mapa.containsKey("energia")) { this.energia = (Integer) mapa.get("energia"); } if (mapa.containsKey("casta")) { this.casta = (Casta) mapa.get("casta"); } if (mapa.containsKey("defensa")) { this.defensa = (Integer) mapa.get("defensa"); } if (mapa.containsKey("destreza")) { this.destreza = (Integer) mapa.get("destreza"); } if (mapa.containsKey("energiaTope")) { this.energiaTope = (Integer) mapa.get("energiaTope"); } if (mapa.containsKey("experiencia")) { this.experiencia = (Integer) mapa.get("experiencia"); } if (mapa.containsKey("fuerza")) { this.fuerza = (Integer) mapa.get("fuerza"); } if (mapa.containsKey("idPersonaje")) { this.idPersonaje = (Integer) mapa.get("idPersonaje"); } if (mapa.containsKey("inteligencia")) { this.inteligencia = (Integer) mapa.get("inteligencia"); } if (mapa.containsKey("nivel")) { this.nivel = (Integer) mapa.get("nivel"); } if (mapa.containsKey("saludTope")) { this.saludTope = (Integer) mapa.get("saludTope"); } } /** * Obtener el inventario * @return Inventario Lista de objetos */ public Inventario getInventario() { return this.inventario; } /** * Reestablece todos los objetos del inventario * @param ids Vector de ids de los objetos en el inventario */ public void reestablecerInventario(final int[] ids) { inventario.reestablecerObjetos(ids); } /** * Retorna la cantidad de objetos en el inventario * @return int Cantidad de objetos del inventario */ public int getCantidadObjetos() { return inventario.getCantidadObjetos(); } /** * Quito un objeto del Inventario * @param obj Objeto a eliminar del inventario */ public void quitarObjeto(final Objeto obj) { inventario.quitarObjeto(obj); } }
package eloquent; import eloquent.adapters.AdapterInterface; import eloquent.exceptions.EloquentException; import eloquent.models.Directory; import eloquent.models.File; import eloquent.models.Metadata; public class Eloquent { protected AdapterInterface adapter; /** * Create a new Eloquent Instance * * @param adapter {@link AdapterInterface} */ public Eloquent(AdapterInterface adapter) { this.setAdapater(adapter); } /** * Get the Adapter * * @return {@link AdapterInterface} */ public AdapterInterface getAdapater() { return this.adapter; } /** * Set the Adapter * * @param adapter {@link AdapterInterface} */ public void setAdapater(AdapterInterface adapter) { this.adapter = adapter; } /** * Read a file * * @param path Path to File * * @return {@link File} * * @throws EloquentException Eloquent Exception */ public File read(String path) throws EloquentException { return this.getAdapater().read(path); } /** * Write a file * * @param path Path to file * @param contents Contents to write * * @return {@link File} * * @throws EloquentException Eloquent Exception */ public File write(String path, String contents) throws EloquentException { return this.getAdapater().write(path, contents); } /** * Update a file. * * @param path File Path * @param contents File contents * * @return {@link File} * * @throws EloquentException Eloquent Exception */ File update(String path, String contents) throws EloquentException { return this.getAdapater().update(path, contents); } /** * Create or Update a file. * * @param path File Path * @param contents File contents * * @return {@link File} * * @throws EloquentException Eloquent Exception */ File put(String path, String contents) throws EloquentException { return this.getAdapater().put(path, contents); } /** * Check if a File exists or not * * @param path File Path * * @return boolean * * @throws EloquentException Eloquent Exception */ boolean has(String path) throws EloquentException { return this.getAdapater().has(path); } /** * Rename a file * * @param path File Path * @param newPath New path * * @return boolean * * @throws EloquentException Eloquent Exception */ boolean rename(String path, String newPath) throws EloquentException { return this.getAdapater().rename(path, newPath); } /** * Copy a file * * @param path File Path * @param newPath New path * * @return boolean * * @throws EloquentException Eloquent Exception */ File copy(String path, String newPath) throws EloquentException { return this.getAdapater().copy(path, newPath); } /** * Delete a file * * @param path File Path * * @return boolean * * @throws EloquentException Eloquent Exception */ boolean delete(String path) throws EloquentException { return this.getAdapater().delete(path); } /** * Delete a directory * * @param path File Path * * @return boolean * * @throws EloquentException Eloquent Exception */ boolean deleteDir(String path) throws EloquentException { return this.getAdapater().deleteDir(path); } /** * Create a directory * * @param path File Path * * @return boolean * * @throws EloquentException Eloquent Exception */ Directory createDir(String path) throws EloquentException { return this.getAdapater().createDir(path); } /** * Get metadata of a File or Directory * * @param path Path to file or folder * * @return {@link Metadata} * * @throws EloquentException */ public Metadata getMetadata(String path) throws EloquentException { return this.getAdapater().getMetadata(path); } /** * Read / View a directory * * @param path File Path * * @return {@link Directory} * * @throws EloquentException Eloquent Exception */ public Directory readDir(String path) throws EloquentException { return this.getAdapater().readDir(path); } /** * File Transfer from current FileSystem * to Another Filesystem. * * @param path Path of file to transfer * * @return */ public Transfer transfer(String path) { Transfer transfer = new Transfer(path); return transfer.from(this.getAdapater()); } }
package entidades; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import javax.swing.JOptionPane; import com.google.gson.Gson; import chat.VentanaContactos; import dominio.Enemigo; import estados.Estado; import frames.MenuEscape; import frames.MenuInventario; import interfaz.MenuInfoPersonaje; import juego.Juego; import juego.Pantalla; import mensajeria.PaqueteBatalla; import mensajeria.PaqueteBatallaNPC; import mensajeria.PaqueteComerciar; import mensajeria.PaqueteEnemigo; import mensajeria.PaqueteMovimiento; import mundo.Grafo; import mundo.Mundo; import mundo.Nodo; /** * Clase Entidad. */ public class Entidad { /** * The juego. */ private Juego juego; /** * The ancho. */ private int ancho; /** * The alto. */ private int alto; /** * The x. */ // Posiciones private float x; /** * The y. */ private float y; /** * The dx. */ private float dx; /** * The dy. */ private float dy; /** * The x inicio. */ private float xInicio; /** * The y inicio. */ private float yInicio; /** * The x final. */ private float xFinal; /** * The y final. */ private float yFinal; /** * The x offset. */ private int xOffset; /** * The y offset. */ private int yOffset; /** * The draw X. */ private int drawX; /** * The draw Y. */ private int drawY; /** * The pos mouse recorrido. */ private int[] posMouseRecorrido; /** * The pos mouse. */ private int[] posMouse; /** * The tile. */ private int[] tile; /** * The Constant horizontalIzq. */ private static final int HORIZONTALIZQ = 0; /** * The Constant diagonalSupIzq. */ private static final int DIAGONALSUPIZQ = 1; /** * The Constant verticalSup. */ private static final int VERTICALSUP = 2; /** * The Constant diagonalSupDer. */ private static final int DIAGONALSUPDER = 3; /** * The Constant horizontalDer. */ // Movimiento Actual private static final int HORIZONTALDER = 4; /** * The Constant diagonalInfDer. */ private static final int DIAGONALINFDER = 5; /** * The Constant verticalInf. */ private static final int VERTICALINF = 6; /** * The Constant diagonalInfIzq. */ private static final int DIAGONALINFIZQ = 7; /** * The movimiento hacia. */ private int movimientoHacia = 6; /** * ArrayList de animaciones que contiene los frames de los personajes. */ private final ArrayList<Animacion> mov; /** * The en movimiento. */ private boolean enMovimiento; /** * The gson. */ private final Gson gson = new Gson(); /** * The intervalo envio. */ private int intervaloEnvio = 0; /** * The pila movimiento. */ // pila de movimiento private PilaDeTiles pilaMovimiento; /** * The tile actual. */ private int[] tileActual; /** * The tile final. */ private int[] tileFinal; /** * The tile moverme. */ private int[] tileMoverme; /** * The mundo. */ private Mundo mundo; /** * The nombre. */ private String nombre; /** * The tile personajes. */ private int[] tilePersonajes; /** * The id enemigo. */ private int idEnemigo; /** * The x comercio. */ // Ubicacion para abrir comerciar. private float xComercio; /** * The y comercio. */ private float yComercio; /** * The comercio. */ private float[] comercio; /** * Constructor de la clase Entidad. * * @param juegoParam * juego con el que se instancia Entidad * @param mundoParam * mundo con el que se instancia Entidad * @param anchoParam * ancho * @param altoParam * alto * @param nombreParam * nombre del personaje * @param spawnX * tile X donde spawnea * @param spawnY * tile Y donde spawnea * @param animaciones * animaciones del personaje * @param velAnimacion * velocidad de animacion del personaje */ public Entidad(final Juego juegoParam, final Mundo mundoParam, final int anchoParam, final int altoParam, final String nombreParam, final float spawnX, final float spawnY, final LinkedList<BufferedImage[]> animaciones, final int velAnimacion) { this.juego = juegoParam; this.ancho = anchoParam; this.alto = altoParam; this.nombre = nombreParam; this.mundo = mundoParam; xOffset = ancho / 2; yOffset = alto / 2; x = (int) (spawnX / 64) * 64; y = (int) (spawnY / 32) * 32; mov = new ArrayList<Animacion>(); mov.add(new Animacion(velAnimacion, animaciones.get(0))); mov.add(new Animacion(velAnimacion, animaciones.get(1))); mov.add(new Animacion(velAnimacion, animaciones.get(2))); mov.add(new Animacion(velAnimacion, animaciones.get(3))); mov.add(new Animacion(velAnimacion, animaciones.get(4))); mov.add(new Animacion(velAnimacion, animaciones.get(5))); mov.add(new Animacion(velAnimacion, animaciones.get(6))); mov.add(new Animacion(velAnimacion, animaciones.get(7))); // Informo mi posicion actual juego.getUbicacionPersonaje().setPosX(x); juego.getUbicacionPersonaje().setPosY(y); juego.getUbicacionPersonaje().setDireccion(getDireccion()); juego.getUbicacionPersonaje().setFrame(getFrame()); } /** * Actualiza el personaje. */ public void actualizar() { if (enMovimiento) { for (int i = 0; i < mov.size(); i++) { mov.get(i).actualizar(); } } else { for (int i = 0; i < mov.size(); i++) { mov.get(i).reset(); } } getEntrada(); mover(); juego.getCamara().centrar(this); } /** * Devuelve la entrada. */ public void getEntrada() { posMouseRecorrido = juego.getHandlerMouse().getPosMouseRecorrido(); posMouse = juego.getHandlerMouse().getPosMouse(); if (juego.getHandlerMouse().getNuevoClick() && posMouse[0] >= 738 && posMouse[0] <= 797 && posMouse[1] >= 545 && posMouse[1] <= 597) { if (Pantalla.getMenuInventario() == null) { Pantalla.setMenuInventario( new MenuInventario(juego.getCliente())); Pantalla.getMenuInventario().setVisible(true); } juego.getHandlerMouse().setNuevoClick(false); } if (juego.getHandlerMouse().getNuevoClick() && posMouse[0] >= 3 && posMouse[0] <= 105 && posMouse[1] >= 562 && posMouse[1] <= 597) { if (Pantalla.getMenuEscp() == null) { Pantalla.setMenuEscp(new MenuEscape(juego.getCliente())); Pantalla.getMenuEscp().setVisible(true); } juego.getHandlerMouse().setNuevoClick(false); } if (juego.getHandlerMouse().getNuevoClick() && posMouse[0] >= 3 && posMouse[0] <= 105 && posMouse[1] >= 524 && posMouse[1] <= 559) { if (Pantalla.getVentContac() == null) { Pantalla.setVentContac(new VentanaContactos(juego)); Pantalla.getVentContac().setVisible(true); } juego.getHandlerMouse().setNuevoClick(false); } // Tomo el click izquierdo if (juego.getHandlerMouse().getNuevoClick()) { if (juego.getEstadoJuego().getHaySolicitud()) { if (juego.getEstadoJuego().getMenuEnemigo() .clickEnMenu(posMouse[0], posMouse[1])) { if (juego.getEstadoJuego().getMenuEnemigo() .clickEnBoton(posMouse[0], posMouse[1])) { // Pregunto si menuBatallar o menuComerciar, sino no me // interesa hacer esto if (juego.getEstadoJuego().getTipoSolicitud() == MenuInfoPersonaje.MENUBATALLAR || juego.getEstadoJuego().getTipoSolicitud() == MenuInfoPersonaje.MENUCOMERCIAR) { // Guardo las poss con el que quiero comerciar xComercio = juego.getUbicacionPersonajes() .get(idEnemigo).getPosX(); yComercio = juego.getUbicacionPersonajes() .get(idEnemigo).getPosY(); comercio = Mundo.isoA2D(xComercio, yComercio); } // pregunto si el menu emergente es de tipo batalla if (juego.getEstadoJuego().getTipoSolicitud() == MenuInfoPersonaje.MENUBATALLAR) { // ME FIJO SI CON EL QUE QUIERO BATALLAR ESTA EN LA // ZONA DE COMERCIO if (!((int) comercio[0] >= 44 && (int) comercio[0] <= 71 && (int) comercio[1] >= 0 && (int) comercio[1] <= 29)) { juego.getEstadoJuego().setHaySolicitud(false, null, MenuInfoPersonaje.MENUBATALLAR); PaqueteBatalla pBatalla = new PaqueteBatalla(); pBatalla.setId(juego.getPersonaje().getId()); pBatalla.setIdEnemigo(idEnemigo); juego.getEstadoJuego().setHaySolicitud(false, null, MenuInfoPersonaje.MENUBATALLAR); try { juego.getCliente().getSalida() .writeObject(gson.toJson(pBatalla)); } catch (IOException e) { JOptionPane.showMessageDialog(null, "Fallo la conexión " + "con el servidor al enviar pBatalla"); } } else { JOptionPane.showMessageDialog(null, "El otro usuario se encuentra" + "dentro de la zona de comercio"); } } else { // PREGUNTO SI EL MENU EMERGENTE ES DE TIPO COMERCIO if (juego.getEstadoJuego().getTipoSolicitud() == MenuInfoPersonaje.MENUCOMERCIAR) { if ((int) comercio[0] >= 44 && (int) comercio[0] <= 71 && (int) comercio[1] >= 0 && (int) comercio[1] <= 29) { if (juego.getCliente().getM1() == null) { juego.getCliente().setPaqueteComercio( new PaqueteComerciar()); juego.getCliente().getPaqueteComercio() .setId(juego.getPersonaje() .getId()); juego.getCliente().getPaqueteComercio() .setIdEnemigo(idEnemigo); try { juego.getCliente().getSalida() .writeObject(gson.toJson( juego.getCliente().getPaqueteComercio())); } catch (IOException e) { JOptionPane.showMessageDialog(null, "Fallo la conexión " + "con el servidor al comerciar"); } } else { JOptionPane.showMessageDialog(null, "Ya te encuentras comerciando!"); } } else { JOptionPane.showMessageDialog(null, "El otro usuario no se encuentra " + "dentro de la zona de comercio"); } } } juego.getEstadoJuego().setHaySolicitud(false, null, MenuInfoPersonaje.MENUBATALLAR); } else if (juego.getEstadoJuego().getMenuEnemigo() .clickEnCerrar(posMouse[0], posMouse[1])) { juego.getEstadoJuego().setHaySolicitud(false, null, MenuInfoPersonaje.MENUBATALLAR); } } else { juego.getEstadoJuego().setHaySolicitud(false, null, MenuInfoPersonaje.MENUBATALLAR); } } else { Iterator<Integer> it = juego.getUbicacionPersonajes().keySet() .iterator(); int key; int[] tileMoverme = Mundo.mouseATile( posMouse[0] + juego.getCamara().getxOffset() - xOffset, posMouse[1] + juego.getCamara().getyOffset() - yOffset); PaqueteMovimiento actual; while (it.hasNext()) { key = it.next(); actual = juego.getUbicacionPersonajes().get(key); tilePersonajes = Mundo.mouseATile(actual.getPosX(), actual.getPosY()); if (actual != null && actual.getIdPersonaje() != juego.getPersonaje() .getId() && juego.getPersonajesConectados() .get(actual.getIdPersonaje()) != null && juego.getPersonajesConectados() .get(actual.getIdPersonaje()) .getEstado() == Estado.ESTADOJUEGO) { if (tileMoverme[0] == tilePersonajes[0] && tileMoverme[1] == tilePersonajes[1]) { idEnemigo = actual.getIdPersonaje(); float[] xY = Mundo.isoA2D(x, y); // ESTA ESTE PARA NO MOVERME HASTA EL LUGAR. if (xY[0] >= 44 && xY[0] <= 71 && xY[1] >= 0 && xY[1] <= 29) { // SI ESTOY DENTRO DE LA ZONA DE COMERCIO SETEO // QUE SE ABRA EL MENU // DE COMERCIO juego.getEstadoJuego().setHaySolicitud(true, juego.getPersonajesConectados() .get(idEnemigo), MenuInfoPersonaje.MENUCOMERCIAR); } else { // SI ESTOY DENTRO DE LA ZONA DE BATALLA SETEO // QUE SE ABRA EL MENU // DE BATALLA juego.getEstadoJuego().setHaySolicitud(true, juego.getPersonajesConectados() .get(idEnemigo), MenuInfoPersonaje.MENUBATALLAR); } juego.getHandlerMouse().setNuevoClick(false); } } } } } if (juego.getHandlerMouse().getNuevoRecorrido() && !juego.getEstadoJuego().getHaySolicitud()) { tileMoverme = Mundo.mouseATile( posMouseRecorrido[0] + juego.getCamara().getxOffset() - xOffset, posMouseRecorrido[1] + juego.getCamara().getyOffset() - yOffset); juego.getHandlerMouse().setNuevoRecorrido(false); pilaMovimiento = null; juego.getEstadoJuego().setHaySolicitud(false, null, MenuInfoPersonaje.MENUBATALLAR); } if (!enMovimiento && tileMoverme != null) { enMovimiento = false; setxInicio(x); setyInicio(y); tileActual = Mundo.mouseATile(x, y); if (tileMoverme[0] < 0 || tileMoverme[1] < 0 || tileMoverme[0] >= mundo.obtenerAncho() || tileMoverme[1] >= mundo.obtenerAlto()) { enMovimiento = false; juego.getHandlerMouse().setNuevoRecorrido(false); pilaMovimiento = null; tileMoverme = null; return; } if (tileMoverme[0] == tileActual[0] && tileMoverme[1] == tileActual[1] || mundo.getTile(tileMoverme[0], tileMoverme[1]) .esSolido()) { tileMoverme = null; enMovimiento = false; juego.getHandlerMouse().setNuevoRecorrido(false); pilaMovimiento = null; return; } if (pilaMovimiento == null) { pilaMovimiento = caminoMasCorto(tileActual[0], tileActual[1], tileMoverme[0], tileMoverme[1]); } // Me muevo al primero de la pila NodoDePila nodoActualTile = pilaMovimiento.pop(); if (nodoActualTile == null) { enMovimiento = false; juego.getHandlerMouse().setNuevoRecorrido(false); pilaMovimiento = null; tileMoverme = null; return; } tileFinal = new int[2]; tileFinal[0] = nodoActualTile.obtenerX(); tileFinal[1] = nodoActualTile.obtenerY(); xFinal = Mundo.dosDaIso(tileFinal[0], tileFinal[1])[0]; yFinal = Mundo.dosDaIso(tileFinal[0], tileFinal[1])[1]; if (tileFinal[0] == tileActual[0] - 1 && tileFinal[1] == tileActual[1] - 1) { movimientoHacia = VERTICALSUP; } if (tileFinal[0] == tileActual[0] + 1 && tileFinal[1] == tileActual[1] + 1) { movimientoHacia = VERTICALINF; } if (tileFinal[0] == tileActual[0] - 1 && tileFinal[1] == tileActual[1] + 1) { movimientoHacia = HORIZONTALIZQ; } if (tileFinal[0] == tileActual[0] + 1 && tileFinal[1] == tileActual[1] - 1) { movimientoHacia = HORIZONTALDER; } if (tileFinal[0] == tileActual[0] - 1 && tileFinal[1] == tileActual[1]) { movimientoHacia = DIAGONALSUPIZQ; } if (tileFinal[0] == tileActual[0] + 1 && tileFinal[1] == tileActual[1]) { movimientoHacia = DIAGONALINFDER; } if (tileFinal[0] == tileActual[0] && tileFinal[1] == tileActual[1] - 1) { movimientoHacia = DIAGONALSUPDER; } if (tileFinal[0] == tileActual[0] && tileFinal[1] == tileActual[1] + 1) { movimientoHacia = DIAGONALINFIZQ; } enMovimiento = true; } } /** * Mueve el personaje. */ public void mover() { dx = 0; dy = 0; double paso = 1; if (enMovimiento && !(x == xFinal && y == yFinal - 32)) { if (movimientoHacia == VERTICALSUP) { dy -= paso; } else if (movimientoHacia == VERTICALINF) { dy += paso; } else if (movimientoHacia == HORIZONTALDER) { dx += paso; } else if (movimientoHacia == HORIZONTALIZQ) { dx -= paso; } else if (movimientoHacia == DIAGONALINFDER) { dx += paso; dy += paso / 2; } else if (movimientoHacia == DIAGONALINFIZQ) { dx -= paso; dy += paso / 2; } else if (movimientoHacia == DIAGONALSUPDER) { dx += paso; dy -= paso / 2; } else if (movimientoHacia == DIAGONALSUPIZQ) { dx -= paso; dy -= paso / 2; } x += dx; y += dy; // Le envio la posicion if (intervaloEnvio == 2) { verificarRangoEnemigo(); enviarPosicion(); intervaloEnvio = 0; } intervaloEnvio++; if (x == xFinal && y == yFinal - 32) { enMovimiento = false; } } } /** * Verificar rango enemigo. */ @SuppressWarnings({ "unchecked", "rawtypes" }) private void verificarRangoEnemigo() { if (juego.getEnemigos() != null) { Map<Integer, PaqueteEnemigo> enemigos; enemigos = new HashMap(juego.getEnemigos()); Iterator<Integer> it = enemigos.keySet().iterator(); int key; PaqueteEnemigo actual; while (it.hasNext()) { key = it.next(); actual = enemigos.get(key); if (actual != null && actual.getEstado() == Estado.ESTADOJUEGO && juego.getPersonaje().getEstado() == Estado.ESTADOJUEGO) { if (Math.sqrt(Math.pow(actual.getX() - x, 2) + Math .pow(actual.getY() - y, 2)) <= Enemigo.RANGO) { PaqueteBatallaNPC pBatalla = new PaqueteBatallaNPC(); pBatalla.setId(juego.getPersonaje().getId()); pBatalla.setIdEnemigo(key); juego.getPersonaje().setEstado(Estado.ESTADOBATALLANPC); try { juego.getCliente().getSalida( ).writeObject(gson.toJson(pBatalla)); } catch (IOException e) { JOptionPane.showMessageDialog(null, "Fallo la conexión " + "con el servidor al enviar pBatallaNPC"); } break; } } } } } /** * Grafica el frame del personaje. * * @param g * se recibe grafico. */ public void graficar(final Graphics g) { drawX = (int) (x - juego.getCamara().getxOffset()); drawY = (int) (y - juego.getCamara().getyOffset()); g.drawImage(getFrameAnimacionActual(), drawX, drawY + 4, ancho, alto, null); } /** * Grafica el nombre. * * @param g * se recibe el grafico. */ public void graficarNombre(final Graphics g) { g.setColor(Color.WHITE); g.setFont(new Font("Book Antiqua", Font.BOLD, 15)); Pantalla.centerString(g, new java.awt.Rectangle(drawX + 32, drawY - 20, 0, 10), nombre); } /** * Obtiene el frameActual del personaje. * * @return frameActual */ private BufferedImage getFrameAnimacionActual() { return mov.get(movimientoHacia).getFrameActual(); } /** * Pide la direccion donde va. * * @return devuelve el movimiento hacia donde va */ private int getDireccion() { return movimientoHacia; } /** * Obtiene el frame donde esta el personaje. * * @return frame */ private int getFrame() { return mov.get(movimientoHacia).getFrame(); } /** * Envia la posicion del personaje. */ private void enviarPosicion() { juego.getUbicacionPersonaje().setPosX(x); juego.getUbicacionPersonaje().setPosY(y); juego.getUbicacionPersonaje().setDireccion(getDireccion()); juego.getUbicacionPersonaje().setFrame(getFrame()); try { juego.getCliente().getSalida().writeObject(gson.toJson( juego.getUbicacionPersonaje(), PaqueteMovimiento.class)); } catch (IOException e) { JOptionPane.showMessageDialog(null, "Fallo la conexión con el servidor"); } } private PilaDeTiles caminoMasCorto(final int xInicialParam, final int yInicialParam, final int xFinalParam, final int yFinalParam) { Grafo grafoLibres = mundo.obtenerGrafoDeTilesNoSolidos(); // Transformo las coordenadas iniciales y finales en indices int nodoInicial = (yInicialParam - grafoLibres.obtenerNodos()[0].obtenerY()) * (int) Math.sqrt(grafoLibres.obtenerCantidadDeNodosTotal()) + xInicialParam - grafoLibres.obtenerNodos()[0].obtenerX(); int nodoFinal = (yFinalParam - grafoLibres.obtenerNodos()[0].obtenerY()) * (int) Math.sqrt(grafoLibres.obtenerCantidadDeNodosTotal()) + xFinalParam - grafoLibres.obtenerNodos()[0].obtenerX(); // Hago todo double[] vecCostos = new double[grafoLibres .obtenerCantidadDeNodosTotal()]; int[] vecPredecesores = new int[grafoLibres .obtenerCantidadDeNodosTotal()]; boolean[] conjSolucion = new boolean[grafoLibres .obtenerCantidadDeNodosTotal()]; int cantSolucion = 0; // Lleno la matriz de costos de numeros grandes for (int i = 0; i < grafoLibres.obtenerCantidadDeNodosTotal(); i++) { vecCostos[i] = Double.MAX_VALUE; } // Adyacentes al nodo inicial conjSolucion[nodoInicial] = true; cantSolucion++; vecCostos[nodoInicial] = 0; Nodo[] adyacentes = grafoLibres.obtenerNodos()[nodoInicial] .obtenerNodosAdyacentes(); for (int i = 0; i < grafoLibres.obtenerNodos()[nodoInicial] .obtenerCantidadDeAdyacentes(); i++) { if (estanEnDiagonal(grafoLibres.obtenerNodos()[nodoInicial], grafoLibres.obtenerNodos()[adyacentes[i] .obtenerIndice()])) { vecCostos[adyacentes[i].obtenerIndice()] = 1.5; } else { vecCostos[adyacentes[i].obtenerIndice()] = 1; } vecPredecesores[adyacentes[i].obtenerIndice()] = nodoInicial; } // Aplico Dijkstra while (cantSolucion < grafoLibres.obtenerCantidadDeNodosTotal()) { // Elijo W perteneciente al conjunto restante tal que el costo de W // sea minimo double minimo = Double.MAX_VALUE; int indiceMinimo = 0; @SuppressWarnings("unused") Nodo nodoW = null; for (int i = 0; i < grafoLibres .obtenerCantidadDeNodosTotal(); i++) { if (!conjSolucion[i] && vecCostos[i] < minimo) { nodoW = grafoLibres.obtenerNodos()[i]; minimo = vecCostos[i]; indiceMinimo = i; } } // Pongo a W en el conj solucion conjSolucion[indiceMinimo] = true; cantSolucion++; // Por cada nodo I adyacente a W del conj restante // Le sumo 1 al costo de ir hasta W y luego ir hasta su adyacente adyacentes = grafoLibres.obtenerNodos()[indiceMinimo] .obtenerNodosAdyacentes(); for (int i = 0; i < grafoLibres.obtenerNodos()[indiceMinimo] .obtenerCantidadDeAdyacentes(); i++) { double valorASumar = 1; if (estanEnDiagonal(grafoLibres.obtenerNodos()[indiceMinimo], grafoLibres.obtenerNodos()[adyacentes[i] .obtenerIndice()])) { valorASumar = 1.5; } if (vecCostos[indiceMinimo] + valorASumar < vecCostos[adyacentes[i] .obtenerIndice()]) { vecCostos[adyacentes[i] .obtenerIndice()] = vecCostos[indiceMinimo] + valorASumar; vecPredecesores[adyacentes[i] .obtenerIndice()] = indiceMinimo; } } } // Creo el vector de nodos hasta donde quiere llegar PilaDeTiles camino = new PilaDeTiles(); while (nodoFinal != nodoInicial) { camino.push(new NodoDePila( grafoLibres.obtenerNodos()[nodoFinal].obtenerX(), grafoLibres.obtenerNodos()[nodoFinal].obtenerY())); nodoFinal = vecPredecesores[nodoFinal]; } return camino; } /** * Pregunta si los personajes estan en diagonal. * * @param nodoUno * personaje 1 * @param nodoDos * personaje 2 * @return true or false */ private boolean estanEnDiagonal(final Nodo nodoUno, final Nodo nodoDos) { return (!(nodoUno.obtenerX() == nodoDos.obtenerX() || nodoUno.obtenerY() == nodoDos.obtenerY())); } /** * Pide el valor de X. * * @return devuelve la ubicacion en X */ public float getX() { return x; } /** * Setea el valor de X. * * @param xParam * valor nuevo de la ubicacion en X. */ public void setX(final float xParam) { this.x = xParam; } /** * Pide el valor de Y. * * @return devuelve la ubicacion en Y */ public float getY() { return y; } /** * Setea el valor de Y. * * @param yParam * valor nuevo de la ubicacion en Y. */ public void setY(final float yParam) { this.y = yParam; } /** * Pide el ancho. * * @return devuelve el ancho */ public int getAncho() { return ancho; } /** * Setea el ancho. * * @param anchoParam * nuevo ancho a setear. */ public void setAncho(final int anchoParam) { this.ancho = anchoParam; } /** * Pide el alto. * * @return devuelve el alto */ public int getAlto() { return alto; } /** * Setea el alto. * * @param altoParam * nuevo alto a setear. */ public void setAlto(final int altoParam) { this.alto = altoParam; } /** * Pide el offset de X. * * @return devuelve el offset de X */ public int getxOffset() { return xOffset; } /** * Pide el offset de Y. * * @return devuelve el offset de Y */ public int getYOffset() { return yOffset; } /** * Gets the x inicio. * * @return the x inicio */ public float getxInicio() { return xInicio; } /** * Sets the x inicio. * * @param xInicioParam * the new x inicio */ public void setxInicio(final float xInicioParam) { this.xInicio = xInicioParam; } /** * Gets the y inicio. * * @return the y inicio */ public float getyInicio() { return yInicio; } /** * Sets the y inicio. * * @param yInicioParam * the new y inicio */ public void setyInicio(final float yInicioParam) { this.yInicio = yInicioParam; } /** * Gets the tile. * * @return the tile */ public int[] getTile() { return tile; } /** * Sets the tile. * * @param tileParam * the new tile */ public void setTile(final int[] tileParam) { this.tile = tileParam; } }
package net.querz.nbt; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern; public abstract class Tag<T> implements Comparable<Tag<T>>, Cloneable { /** * The maximum depth of the NBT structure. * */ public static final int DEFAULT_MAX_DEPTH = 512; private static final Map<String, String> ESCAPE_CHARACTERS; static { final Map<String, String> temp = new HashMap<>(); temp.put("\\", "\\\\\\\\"); temp.put("\n", "\\\\n"); temp.put("\t", "\\\\t"); temp.put("\r", "\\\\r"); temp.put("\"", "\\\\\""); ESCAPE_CHARACTERS = Collections.unmodifiableMap(temp); } private static final Pattern ESCAPE_PATTERN = Pattern.compile("[\\\\\n\t\r\"]"); private static final Pattern NON_QUOTE_PATTERN = Pattern.compile("[a-zA-Z0-9_\\-+]+"); private T value; /** * Initializes this Tag with a {@code null} value. */ protected Tag() {} /** * Initializes this Tag with some value. If the value is {@code null}, it will * throw a {@code NullPointerException} * @param value The value to be set for this Tag. * */ public Tag(T value) { setValue(value); } /** * @return This Tag's ID, usually used for serialization and deserialization. * */ public byte getID() { return TagFactory.idFromClass(getClass()); } /** * @return The value of this Tag. * */ protected T getValue() { return value; } /** * Sets the value for this Tag directly. * @param value The value to be set. * */ protected void setValue(T value) { this.value = Objects.requireNonNull(value); } /** * Calls {@link Tag#serialize(DataOutputStream, String, int)} with an empty name. * @see Tag#serialize(DataOutputStream, String, int) * @param dos The DataOutputStream to write to * @param depth The current depth of the structure * @throws IOException If something went wrong during serialization * */ public final void serialize(DataOutputStream dos, int depth) throws IOException { serialize(dos, "", depth); } /** * Serializes this Tag starting at the gives depth. * @param dos The DataOutputStream to write to. * @param name The name of this Tag, if this is the root Tag. * @param depth The current depth of the structure. * @throws IOException If something went wrong during serialization. * @exception NullPointerException If {@code dos} or {@code name} is {@code null}. * @exception MaxDepthReachedException If the structure depth exceeds {@link Tag#DEFAULT_MAX_DEPTH}. * */ public final void serialize(DataOutputStream dos, String name, int depth) throws IOException { dos.writeByte(getID()); if (getID() != 0) { dos.writeUTF(name); } serializeValue(dos, depth); } /** * Deserializes this Tag starting at the given depth. * The name of the root Tag is ignored. * @param dis The DataInputStream to read from. * @param depth The current depth of the structure. * @throws IOException If something went wrong during deserialization. * @exception NullPointerException If {@code dis} is {@code null}. * @exception MaxDepthReachedException If the structure depth exceeds {@link Tag#DEFAULT_MAX_DEPTH}. * @return The deserialized NBT structure. * */ public static Tag<?> deserialize(DataInputStream dis, int depth) throws IOException { int id = dis.readByte() & 0xFF; Tag<?> tag = TagFactory.fromID(id); if (id != 0) { dis.readUTF(); tag.deserializeValue(dis, depth); } return tag; } /** * Serializes only the value of this Tag. * @param dos The DataOutputStream to write to. * @param depth The current depth of the structure. * @throws IOException If something went wrong during serialization. * @exception MaxDepthReachedException If the structure depth exceeds {@link Tag#DEFAULT_MAX_DEPTH}. * */ public abstract void serializeValue(DataOutputStream dos, int depth) throws IOException; /** * Deserializes only the value of this Tag. * @param dis The DataInputStream to read from. * @param depth The current depth of the structure. * @throws IOException If something went wrong during deserialization. * @exception MaxDepthReachedException If the structure depth exceeds {@link Tag#DEFAULT_MAX_DEPTH}. * */ public abstract void deserializeValue(DataInputStream dis, int depth) throws IOException; /** * Calls {@link Tag#toString(int)} with an initial depth of {@code 0}. * @see Tag#toString(int) * */ @Override public final String toString() { return toString(DEFAULT_MAX_DEPTH); } /** * Creates a string representation of this Tag in a valid JSON format. * @param depth The current depth of the structure. * @return The string representation of this Tag. * @exception MaxDepthReachedException If the structure depth exceeds {@link Tag#DEFAULT_MAX_DEPTH}. * */ public String toString(int depth) { return "{\"type\":\""+ getClass().getSimpleName() + "\"," + "\"value\":" + valueToString(depth) + "}"; } /** * Returns a JSON representation of the value of this Tag. * @param depth The current depth of the structure. * @return The string representation of the value of this Tag. * @exception MaxDepthReachedException If the structure depth exceeds {@link Tag#DEFAULT_MAX_DEPTH}. * */ public abstract String valueToString(int depth); /** * Calls {@link Tag#toTagString(int)} with an initial depth of {@code 0}. * @see Tag#toTagString(int) * @return The JSON-like string representation of this Tag. * */ public final String toTagString() { return toTagString(DEFAULT_MAX_DEPTH); } /** * Returns a JSON-like representation of the value of this Tag, usually used for Minecraft commands. * @param depth The current depth of the structure. * @return The JSON-like string representation of this Tag. * @exception MaxDepthReachedException If the structure depth exceeds {@link Tag#DEFAULT_MAX_DEPTH}. * */ public String toTagString(int depth) { return valueToTagString(depth); } /** * Returns a JSON-like representation of the value of this Tag. * @param depth The current depth of the structure. * @return The JSON-like string representation of the value of this Tag. * @exception MaxDepthReachedException If the structure depth exceeds {@link Tag#DEFAULT_MAX_DEPTH}. * */ public abstract String valueToTagString(int depth); /** * Returns whether this Tag and some other Tag are equal. * They are equal if {@code other} is not {@code null} and they are of the same class. * Custom Tag implementations should overwrite this but check the result * of this {@code super}-method while comparing. * @param other The Tag to compare to. * @return {@code true} if they are equal based on the conditions mentioned above. * */ @Override public boolean equals(Object other) { return other != null && getClass() == other.getClass(); } /** * Calculates the hash code of this Tag. Tags which are equal according to {@link Tag#equals(Object)} * must return an equal hash code. * @return The hash code of this Tag. * */ @Override public int hashCode() { return value.hashCode(); } /** * Creates a clone of this Tag. * @return A clone of this Tag. * */ @SuppressWarnings("CloneDoesntDeclareCloneNotSupportedException") public abstract Tag<T> clone(); /** * Decrements {@code depth} by {@code 1}. * @param depth The value to decrement. * @return The decremented value. * @exception MaxDepthReachedException If {@code depth <= 0}. * */ protected int decrementDepth(int depth) { if (depth <= 0) { throw new MaxDepthReachedException("reached maximum depth of NBT structure"); } return --depth; } /** * Escapes a string to fit into a JSON-like string representation for Minecraft * or to create the JSON string representation of a Tag returned from {@link Tag#toString()} * @param s The string to be escaped. * @param lenient {@code true} if it should force double quotes ({@code "}) at the start and * the end of the string. * @return The escaped string. * */ protected static String escapeString(String s, boolean lenient) { StringBuffer sb = new StringBuffer(); Matcher m = ESCAPE_PATTERN.matcher(s); while (m.find()) { m.appendReplacement(sb, ESCAPE_CHARACTERS.get(m.group())); } m.appendTail(sb); m = NON_QUOTE_PATTERN.matcher(s); if (!lenient || !m.matches()) { sb.insert(0, "\"").append("\""); } return sb.toString(); } }