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.Graphics2D; import java.awt.Paint; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.ResourceBundle; import java.util.Set; import java.util.TreeMap; import org.jfree.chart.JFreeChart; import org.jfree.chart.LegendItem; import org.jfree.chart.LegendItemCollection; import org.jfree.chart.annotations.Annotation; import org.jfree.chart.annotations.XYAnnotation; import org.jfree.chart.annotations.XYAnnotationBoundsInfo; import org.jfree.chart.axis.Axis; import org.jfree.chart.axis.AxisCollection; import org.jfree.chart.axis.AxisLocation; import org.jfree.chart.axis.AxisSpace; import org.jfree.chart.axis.AxisState; import org.jfree.chart.axis.TickType; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.axis.ValueTick; import org.jfree.chart.event.AnnotationChangeEvent; import org.jfree.chart.event.ChartChangeEventType; import org.jfree.chart.event.PlotChangeEvent; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.event.RendererChangeListener; import org.jfree.chart.renderer.RendererUtilities; import org.jfree.chart.renderer.xy.AbstractXYItemRenderer; import org.jfree.chart.renderer.xy.XYItemRenderer; import org.jfree.chart.renderer.xy.XYItemRendererState; import org.jfree.chart.util.CloneUtils; import org.jfree.chart.util.ParamChecks; import org.jfree.chart.util.ResourceBundleWrapper; import org.jfree.chart.util.ShadowGenerator; import org.jfree.data.Range; import org.jfree.data.general.DatasetChangeEvent; import org.jfree.data.general.DatasetUtilities; import org.jfree.data.xy.XYDataset; import org.jfree.io.SerialUtilities; import org.jfree.ui.Layer; import org.jfree.ui.RectangleEdge; import org.jfree.ui.RectangleInsets; import org.jfree.util.ObjectUtilities; import org.jfree.util.PaintUtilities; import org.jfree.util.PublicCloneable; /** * A general class for plotting data in the form of (x, y) pairs. This plot can * use data from any class that implements the {@link XYDataset} interface. * <P> * {@code XYPlot} makes use of an {@link XYItemRenderer} to draw each point * on the plot. By using different renderers, various chart types can be * produced. * <p> * The {@link org.jfree.chart.ChartFactory} class contains static methods for * creating pre-configured charts. */ public class XYPlot extends Plot implements ValueAxisPlot, Pannable, Zoomable, RendererChangeListener, Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = 7044148245716569264L; /** The default grid line stroke. */ public static final Stroke DEFAULT_GRIDLINE_STROKE = new BasicStroke(0.5f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0.0f, new float[] {2.0f, 2.0f}, 0.0f); /** The default grid line paint. */ public static final Paint DEFAULT_GRIDLINE_PAINT = Color.lightGray; /** The default crosshair visibility. */ public static final boolean DEFAULT_CROSSHAIR_VISIBLE = false; /** The default crosshair stroke. */ public static final Stroke DEFAULT_CROSSHAIR_STROKE = DEFAULT_GRIDLINE_STROKE; /** The default crosshair paint. */ public static final Paint DEFAULT_CROSSHAIR_PAINT = Color.blue; /** The resourceBundle for the localization. */ protected static ResourceBundle localizationResources = ResourceBundleWrapper.getBundle( "org.jfree.chart.plot.LocalizationBundle"); /** The plot orientation. */ private PlotOrientation orientation; /** The offset between the data area and the axes. */ private RectangleInsets axisOffset; /** The domain axis / axes (used for the x-values). */ private Map<Integer, ValueAxis> domainAxes; /** The domain axis locations. */ private Map<Integer, AxisLocation> domainAxisLocations; /** The range axis (used for the y-values). */ private Map<Integer, ValueAxis> rangeAxes; /** The range axis location. */ private Map<Integer, AxisLocation> rangeAxisLocations; /** Storage for the datasets. */ private Map<Integer, XYDataset> datasets; /** Storage for the renderers. */ private Map<Integer, XYItemRenderer> renderers; /** * Storage for the mapping between datasets/renderers and domain axes. The * keys in the map are Integer objects, corresponding to the dataset * index. The values in the map are List objects containing Integer * objects (corresponding to the axis indices). If the map contains no * entry for a dataset, it is assumed to map to the primary domain axis * (index = 0). */ private Map<Integer, List<Integer>> datasetToDomainAxesMap; /** * Storage for the mapping between datasets/renderers and range axes. The * keys in the map are Integer objects, corresponding to the dataset * index. The values in the map are List objects containing Integer * objects (corresponding to the axis indices). If the map contains no * entry for a dataset, it is assumed to map to the primary domain axis * (index = 0). */ private Map<Integer, List<Integer>> datasetToRangeAxesMap; /** The origin point for the quadrants (if drawn). */ private transient Point2D quadrantOrigin = new Point2D.Double(0.0, 0.0); /** The paint used for each quadrant. */ private transient Paint[] quadrantPaint = new Paint[] {null, null, null, null}; /** A flag that controls whether the domain grid-lines are visible. */ private boolean domainGridlinesVisible; /** The stroke used to draw the domain grid-lines. */ private transient Stroke domainGridlineStroke; /** The paint used to draw the domain grid-lines. */ private transient Paint domainGridlinePaint; /** A flag that controls whether the range grid-lines are visible. */ private boolean rangeGridlinesVisible; /** The stroke used to draw the range grid-lines. */ private transient Stroke rangeGridlineStroke; /** The paint used to draw the range grid-lines. */ private transient Paint rangeGridlinePaint; /** * A flag that controls whether the domain minor grid-lines are visible. * * @since 1.0.12 */ private boolean domainMinorGridlinesVisible; /** * The stroke used to draw the domain minor grid-lines. * * @since 1.0.12 */ private transient Stroke domainMinorGridlineStroke; /** * The paint used to draw the domain minor grid-lines. * * @since 1.0.12 */ private transient Paint domainMinorGridlinePaint; /** * A flag that controls whether the range minor grid-lines are visible. * * @since 1.0.12 */ private boolean rangeMinorGridlinesVisible; /** * The stroke used to draw the range minor grid-lines. * * @since 1.0.12 */ private transient Stroke rangeMinorGridlineStroke; /** * The paint used to draw the range minor grid-lines. * * @since 1.0.12 */ private transient Paint rangeMinorGridlinePaint; /** * A flag that controls whether or not the zero baseline against the domain * axis is visible. * * @since 1.0.5 */ private boolean domainZeroBaselineVisible; /** * The stroke used for the zero baseline against the domain axis. * * @since 1.0.5 */ private transient Stroke domainZeroBaselineStroke; /** * The paint used for the zero baseline against the domain axis. * * @since 1.0.5 */ private transient Paint domainZeroBaselinePaint; /** * A flag that controls whether or not the zero baseline against the range * axis is visible. */ private boolean rangeZeroBaselineVisible; /** The stroke used for the zero baseline against the range axis. */ private transient Stroke rangeZeroBaselineStroke; /** The paint used for the zero baseline against the range axis. */ private transient Paint rangeZeroBaselinePaint; /** A flag that controls whether or not a domain crosshair is drawn..*/ private boolean domainCrosshairVisible; /** The domain crosshair value. */ private double domainCrosshairValue; /** The pen/brush used to draw the crosshair (if any). */ private transient Stroke domainCrosshairStroke; /** The color used to draw the crosshair (if any). */ private transient Paint domainCrosshairPaint; /** * A flag that controls whether or not the crosshair locks onto actual * data points. */ private boolean domainCrosshairLockedOnData = true; /** A flag that controls whether or not a range crosshair is drawn..*/ private boolean rangeCrosshairVisible; /** The range crosshair value. */ private double rangeCrosshairValue; /** The pen/brush used to draw the crosshair (if any). */ private transient Stroke rangeCrosshairStroke; /** The color used to draw the crosshair (if any). */ private transient Paint rangeCrosshairPaint; /** * A flag that controls whether or not the crosshair locks onto actual * data points. */ private boolean rangeCrosshairLockedOnData = true; /** A map of lists of foreground markers (optional) for the domain axes. */ private Map foregroundDomainMarkers; /** A map of lists of background markers (optional) for the domain axes. */ private Map backgroundDomainMarkers; /** A map of lists of foreground markers (optional) for the range axes. */ private Map foregroundRangeMarkers; /** A map of lists of background markers (optional) for the range axes. */ private Map backgroundRangeMarkers; /** * A (possibly empty) list of annotations for the plot. The list should * be initialised in the constructor and never allowed to be * {@code null}. */ private List<XYAnnotation> annotations; /** The paint used for the domain tick bands (if any). */ private transient Paint domainTickBandPaint; /** The paint used for the range tick bands (if any). */ private transient Paint rangeTickBandPaint; /** The fixed domain axis space. */ private AxisSpace fixedDomainAxisSpace; /** The fixed range axis space. */ private AxisSpace fixedRangeAxisSpace; /** * The order of the dataset rendering (REVERSE draws the primary dataset * last so that it appears to be on top). */ private DatasetRenderingOrder datasetRenderingOrder = DatasetRenderingOrder.REVERSE; /** * The order of the series rendering (REVERSE draws the primary series * last so that it appears to be on top). */ private SeriesRenderingOrder seriesRenderingOrder = SeriesRenderingOrder.REVERSE; /** * The weight for this plot (only relevant if this is a subplot in a * combined plot). */ private int weight; /** * An optional collection of legend items that can be returned by the * getLegendItems() method. */ private LegendItemCollection fixedLegendItems; /** * A flag that controls whether or not panning is enabled for the domain * axis/axes. * * @since 1.0.13 */ private boolean domainPannable; /** * A flag that controls whether or not panning is enabled for the range * axis/axes. * * @since 1.0.13 */ private boolean rangePannable; /** * The shadow generator ({@code null} permitted). * * @since 1.0.14 */ private ShadowGenerator shadowGenerator; /** * Creates a new {@code XYPlot} instance with no dataset, no axes and * no renderer. You should specify these items before using the plot. */ public XYPlot() { this(null, null, null, null); } /** * Creates a new plot with the specified dataset, axes and renderer. Any * of the arguments can be {@code null}, but in that case you should * take care to specify the value before using the plot (otherwise a * {@code NullPointerException} may be thrown). * * @param dataset the dataset ({@code null} permitted). * @param domainAxis the domain axis ({@code null} permitted). * @param rangeAxis the range axis ({@code null} permitted). * @param renderer the renderer ({@code null} permitted). */ public XYPlot(XYDataset dataset, ValueAxis domainAxis, ValueAxis rangeAxis, XYItemRenderer renderer) { super(); this.orientation = PlotOrientation.VERTICAL; this.weight = 1; // only relevant when this is a subplot this.axisOffset = RectangleInsets.ZERO_INSETS; // allocate storage for datasets, axes and renderers (all optional) this.domainAxes = new HashMap<Integer, ValueAxis>(); this.domainAxisLocations = new HashMap<Integer, AxisLocation>(); this.foregroundDomainMarkers = new HashMap(); this.backgroundDomainMarkers = new HashMap(); this.rangeAxes = new HashMap<Integer, ValueAxis>(); this.rangeAxisLocations = new HashMap<Integer, AxisLocation>(); this.foregroundRangeMarkers = new HashMap(); this.backgroundRangeMarkers = new HashMap(); this.datasets = new HashMap<Integer, XYDataset>(); this.renderers = new HashMap<Integer, XYItemRenderer>(); this.datasetToDomainAxesMap = new TreeMap(); this.datasetToRangeAxesMap = new TreeMap(); this.annotations = new java.util.ArrayList(); this.datasets.put(0, dataset); if (dataset != null) { dataset.addChangeListener(this); } this.renderers.put(0, renderer); if (renderer != null) { renderer.setPlot(this); renderer.addChangeListener(this); } this.domainAxes.put(0, domainAxis); mapDatasetToDomainAxis(0, 0); if (domainAxis != null) { domainAxis.setPlot(this); domainAxis.addChangeListener(this); } this.domainAxisLocations.put(0, AxisLocation.BOTTOM_OR_LEFT); this.rangeAxes.put(0, rangeAxis); mapDatasetToRangeAxis(0, 0); if (rangeAxis != null) { rangeAxis.setPlot(this); rangeAxis.addChangeListener(this); } this.rangeAxisLocations.put(0, AxisLocation.BOTTOM_OR_LEFT); configureDomainAxes(); configureRangeAxes(); this.domainGridlinesVisible = true; this.domainGridlineStroke = DEFAULT_GRIDLINE_STROKE; this.domainGridlinePaint = DEFAULT_GRIDLINE_PAINT; this.domainMinorGridlinesVisible = false; this.domainMinorGridlineStroke = DEFAULT_GRIDLINE_STROKE; this.domainMinorGridlinePaint = Color.white; this.domainZeroBaselineVisible = false; this.domainZeroBaselinePaint = Color.black; this.domainZeroBaselineStroke = new BasicStroke(0.5f); this.rangeGridlinesVisible = true; this.rangeGridlineStroke = DEFAULT_GRIDLINE_STROKE; this.rangeGridlinePaint = DEFAULT_GRIDLINE_PAINT; this.rangeMinorGridlinesVisible = false; this.rangeMinorGridlineStroke = DEFAULT_GRIDLINE_STROKE; this.rangeMinorGridlinePaint = Color.white; this.rangeZeroBaselineVisible = false; this.rangeZeroBaselinePaint = Color.black; this.rangeZeroBaselineStroke = new BasicStroke(0.5f); this.domainCrosshairVisible = false; this.domainCrosshairValue = 0.0; this.domainCrosshairStroke = DEFAULT_CROSSHAIR_STROKE; this.domainCrosshairPaint = DEFAULT_CROSSHAIR_PAINT; this.rangeCrosshairVisible = false; this.rangeCrosshairValue = 0.0; this.rangeCrosshairStroke = DEFAULT_CROSSHAIR_STROKE; this.rangeCrosshairPaint = DEFAULT_CROSSHAIR_PAINT; this.shadowGenerator = null; } /** * Returns the plot type as a string. * * @return A short string describing the type of plot. */ @Override public String getPlotType() { return localizationResources.getString("XY_Plot"); } /** * Returns the orientation of the plot. * * @return The orientation (never {@code null}). * * @see #setOrientation(PlotOrientation) */ @Override public PlotOrientation getOrientation() { return this.orientation; } /** * Sets the orientation for the plot and sends a {@link PlotChangeEvent} to * all registered listeners. * * @param orientation the orientation ({@code null} not allowed). * * @see #getOrientation() */ public void setOrientation(PlotOrientation orientation) { ParamChecks.nullNotPermitted(orientation, "orientation"); if (orientation != this.orientation) { this.orientation = orientation; fireChangeEvent(); } } /** * Returns the axis offset. * * @return The axis offset (never {@code null}). * * @see #setAxisOffset(RectangleInsets) */ public RectangleInsets getAxisOffset() { return this.axisOffset; } /** * Sets the axis offsets (gap between the data area and the axes) and sends * a {@link PlotChangeEvent} to all registered listeners. * * @param offset the offset ({@code null} not permitted). * * @see #getAxisOffset() */ public void setAxisOffset(RectangleInsets offset) { ParamChecks.nullNotPermitted(offset, "offset"); this.axisOffset = offset; fireChangeEvent(); } /** * Returns the domain axis with index 0. If the domain axis for this plot * is {@code null}, then the method will return the parent plot's * domain axis (if there is a parent plot). * * @return The domain axis (possibly {@code null}). * * @see #getDomainAxis(int) * @see #setDomainAxis(ValueAxis) */ public ValueAxis getDomainAxis() { return getDomainAxis(0); } /** * Returns the domain axis with the specified index, or {@code null} if * there is no axis with that index. * * @param index the axis index. * * @return The axis ({@code null} possible). * * @see #setDomainAxis(int, ValueAxis) */ public ValueAxis getDomainAxis(int index) { ValueAxis result = this.domainAxes.get(index); if (result == null) { Plot parent = getParent(); if (parent instanceof XYPlot) { XYPlot xy = (XYPlot) parent; result = xy.getDomainAxis(index); } } return result; } /** * Sets the domain axis for the plot and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param axis the new axis ({@code null} permitted). * * @see #getDomainAxis() * @see #setDomainAxis(int, ValueAxis) */ public void setDomainAxis(ValueAxis axis) { setDomainAxis(0, axis); } /** * Sets a domain axis and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param index the axis index. * @param axis the axis ({@code null} permitted). * * @see #getDomainAxis(int) * @see #setRangeAxis(int, ValueAxis) */ public void setDomainAxis(int index, ValueAxis axis) { setDomainAxis(index, axis, true); } /** * Sets a domain axis and, if requested, sends a {@link PlotChangeEvent} to * all registered listeners. * * @param index the axis index. * @param axis the axis. * @param notify notify listeners? * * @see #getDomainAxis(int) */ public void setDomainAxis(int index, ValueAxis axis, boolean notify) { ValueAxis existing = getDomainAxis(index); if (existing != null) { existing.removeChangeListener(this); } if (axis != null) { axis.setPlot(this); } this.domainAxes.put(index, axis); if (axis != null) { axis.configure(); axis.addChangeListener(this); } if (notify) { fireChangeEvent(); } } /** * Sets the domain axes for this plot and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param axes the axes ({@code null} not permitted). * * @see #setRangeAxes(ValueAxis[]) */ public void setDomainAxes(ValueAxis[] axes) { for (int i = 0; i < axes.length; i++) { setDomainAxis(i, axes[i], false); } fireChangeEvent(); } /** * Returns the location of the primary domain axis. * * @return The location (never {@code null}). * * @see #setDomainAxisLocation(AxisLocation) */ public AxisLocation getDomainAxisLocation() { return (AxisLocation) this.domainAxisLocations.get(0); } /** * Sets the location of the primary domain axis and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param location the location ({@code null} not permitted). * * @see #getDomainAxisLocation() */ public void setDomainAxisLocation(AxisLocation location) { // delegate... setDomainAxisLocation(0, location, true); } /** * Sets the location of the domain axis and, if requested, sends a * {@link PlotChangeEvent} to all registered listeners. * * @param location the location ({@code null} not permitted). * @param notify notify listeners? * * @see #getDomainAxisLocation() */ public void setDomainAxisLocation(AxisLocation location, boolean notify) { // delegate... setDomainAxisLocation(0, location, notify); } /** * Returns the edge for the primary domain axis (taking into account the * plot's orientation). * * @return The edge. * * @see #getDomainAxisLocation() * @see #getOrientation() */ public RectangleEdge getDomainAxisEdge() { return Plot.resolveDomainAxisLocation(getDomainAxisLocation(), this.orientation); } /** * Returns the number of domain axes. * * @return The axis count. * * @see #getRangeAxisCount() */ public int getDomainAxisCount() { return this.domainAxes.size(); } /** * Clears the domain axes from the plot and sends a {@link PlotChangeEvent} * to all registered listeners. * * @see #clearRangeAxes() */ public void clearDomainAxes() { for (ValueAxis axis: this.domainAxes.values()) { if (axis != null) { axis.removeChangeListener(this); } } this.domainAxes.clear(); fireChangeEvent(); } /** * Configures the domain axes. */ public void configureDomainAxes() { for (ValueAxis axis: this.domainAxes.values()) { if (axis != null) { axis.configure(); } } } /** * Returns the location for a domain axis. If this hasn't been set * explicitly, the method returns the location that is opposite to the * primary domain axis location. * * @param index the axis index (must be &gt;= 0). * * @return The location (never {@code null}). * * @see #setDomainAxisLocation(int, AxisLocation) */ public AxisLocation getDomainAxisLocation(int index) { AxisLocation result = this.domainAxisLocations.get(index); if (result == null) { result = AxisLocation.getOpposite(getDomainAxisLocation()); } return result; } /** * Sets the location for a domain axis and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param index the axis index. * @param location the location ({@code null} not permitted for index * 0). * * @see #getDomainAxisLocation(int) */ public void setDomainAxisLocation(int index, AxisLocation location) { // delegate... setDomainAxisLocation(index, location, true); } /** * Sets the axis location for a domain axis and, if requested, sends a * {@link PlotChangeEvent} to all registered listeners. * * @param index the axis index (must be &gt;= 0). * @param location the location ({@code null} not permitted for * index 0). * @param notify notify listeners? * * @since 1.0.5 * * @see #getDomainAxisLocation(int) * @see #setRangeAxisLocation(int, AxisLocation, boolean) */ public void setDomainAxisLocation(int index, AxisLocation location, boolean notify) { if (index == 0 && location == null) { throw new IllegalArgumentException( "Null 'location' for index 0 not permitted."); } this.domainAxisLocations.put(index, location); if (notify) { fireChangeEvent(); } } /** * Returns the edge for a domain axis. * * @param index the axis index. * * @return The edge. * * @see #getRangeAxisEdge(int) */ public RectangleEdge getDomainAxisEdge(int index) { AxisLocation location = getDomainAxisLocation(index); return Plot.resolveDomainAxisLocation(location, this.orientation); } /** * Returns the range axis for the plot. If the range axis for this plot is * {@code null}, then the method will return the parent plot's range * axis (if there is a parent plot). * * @return The range axis. * * @see #getRangeAxis(int) * @see #setRangeAxis(ValueAxis) */ public ValueAxis getRangeAxis() { return getRangeAxis(0); } /** * Sets the range axis for the plot and sends a {@link PlotChangeEvent} to * all registered listeners. * * @param axis the axis ({@code null} permitted). * * @see #getRangeAxis() * @see #setRangeAxis(int, ValueAxis) */ public void setRangeAxis(ValueAxis axis) { if (axis != null) { axis.setPlot(this); } // plot is likely registered as a listener with the existing axis... ValueAxis existing = getRangeAxis(); if (existing != null) { existing.removeChangeListener(this); } this.rangeAxes.put(0, axis); if (axis != null) { axis.configure(); axis.addChangeListener(this); } fireChangeEvent(); } /** * Returns the location of the primary range axis. * * @return The location (never {@code null}). * * @see #setRangeAxisLocation(AxisLocation) */ public AxisLocation getRangeAxisLocation() { return (AxisLocation) this.rangeAxisLocations.get(0); } /** * Sets the location of the primary range axis and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param location the location ({@code null} not permitted). * * @see #getRangeAxisLocation() */ public void setRangeAxisLocation(AxisLocation location) { // delegate... setRangeAxisLocation(0, location, true); } /** * Sets the location of the primary range axis and, if requested, sends a * {@link PlotChangeEvent} to all registered listeners. * * @param location the location ({@code null} not permitted). * @param notify notify listeners? * * @see #getRangeAxisLocation() */ public void setRangeAxisLocation(AxisLocation location, boolean notify) { // delegate... setRangeAxisLocation(0, location, notify); } /** * Returns the edge for the primary range axis. * * @return The range axis edge. * * @see #getRangeAxisLocation() * @see #getOrientation() */ public RectangleEdge getRangeAxisEdge() { return Plot.resolveRangeAxisLocation(getRangeAxisLocation(), this.orientation); } /** * Returns the range axis with the specified index, or {@code null} if * there is no axis with that index. * * @param index the axis index (must be &gt;= 0). * * @return The axis ({@code null} possible). * * @see #setRangeAxis(int, ValueAxis) */ public ValueAxis getRangeAxis(int index) { ValueAxis result = this.rangeAxes.get(index); if (result == null) { Plot parent = getParent(); if (parent instanceof XYPlot) { XYPlot xy = (XYPlot) parent; result = xy.getRangeAxis(index); } } return result; } /** * Sets a range axis and sends a {@link PlotChangeEvent} to all registered * listeners. * * @param index the axis index. * @param axis the axis ({@code null} permitted). * * @see #getRangeAxis(int) */ public void setRangeAxis(int index, ValueAxis axis) { setRangeAxis(index, axis, true); } /** * Sets a range axis and, if requested, sends a {@link PlotChangeEvent} to * all registered listeners. * * @param index the axis index. * @param axis the axis ({@code null} permitted). * @param notify notify listeners? * * @see #getRangeAxis(int) */ public void setRangeAxis(int index, ValueAxis axis, boolean notify) { ValueAxis existing = getRangeAxis(index); if (existing != null) { existing.removeChangeListener(this); } if (axis != null) { axis.setPlot(this); } this.rangeAxes.put(index, axis); if (axis != null) { axis.configure(); axis.addChangeListener(this); } if (notify) { fireChangeEvent(); } } /** * Sets the range axes for this plot and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param axes the axes ({@code null} not permitted). * * @see #setDomainAxes(ValueAxis[]) */ public void setRangeAxes(ValueAxis[] axes) { for (int i = 0; i < axes.length; i++) { setRangeAxis(i, axes[i], false); } fireChangeEvent(); } /** * Returns the number of range axes. * * @return The axis count. * * @see #getDomainAxisCount() */ public int getRangeAxisCount() { return this.rangeAxes.size(); } /** * Clears the range axes from the plot and sends a {@link PlotChangeEvent} * to all registered listeners. * * @see #clearDomainAxes() */ public void clearRangeAxes() { for (ValueAxis axis: this.rangeAxes.values()) { if (axis != null) { axis.removeChangeListener(this); } } this.rangeAxes.clear(); fireChangeEvent(); } /** * Configures the range axes. * * @see #configureDomainAxes() */ public void configureRangeAxes() { for (ValueAxis axis: this.rangeAxes.values()) { if (axis != null) { axis.configure(); } } } /** * Returns the location for a range axis. If this hasn't been set * explicitly, the method returns the location that is opposite to the * primary range axis location. * * @param index the axis index (must be &gt;= 0). * * @return The location (never {@code null}). * * @see #setRangeAxisLocation(int, AxisLocation) */ public AxisLocation getRangeAxisLocation(int index) { AxisLocation result = this.rangeAxisLocations.get(index); if (result == null) { result = AxisLocation.getOpposite(getRangeAxisLocation()); } return result; } /** * Sets the location for a range axis and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param index the axis index. * @param location the location ({@code null} permitted). * * @see #getRangeAxisLocation(int) */ public void setRangeAxisLocation(int index, AxisLocation location) { // delegate... setRangeAxisLocation(index, location, true); } /** * Sets the axis location for a domain axis and, if requested, sends a * {@link PlotChangeEvent} to all registered listeners. * * @param index the axis index. * @param location the location ({@code null} not permitted for * index 0). * @param notify notify listeners? * * @since 1.0.5 * * @see #getRangeAxisLocation(int) * @see #setDomainAxisLocation(int, AxisLocation, boolean) */ public void setRangeAxisLocation(int index, AxisLocation location, boolean notify) { if (index == 0 && location == null) { throw new IllegalArgumentException( "Null 'location' for index 0 not permitted."); } this.rangeAxisLocations.put(index, location); if (notify) { fireChangeEvent(); } } /** * Returns the edge for a range axis. * * @param index the axis index. * * @return The edge. * * @see #getRangeAxisLocation(int) * @see #getOrientation() */ public RectangleEdge getRangeAxisEdge(int index) { AxisLocation location = getRangeAxisLocation(index); return Plot.resolveRangeAxisLocation(location, this.orientation); } /** * Returns the primary dataset for the plot. * * @return The primary dataset (possibly {@code null}). * * @see #getDataset(int) * @see #setDataset(XYDataset) */ public XYDataset getDataset() { return getDataset(0); } /** * Returns the dataset with the specified index, or {@code null} if there * is no dataset with that index. * * @param index the dataset index (must be &gt;= 0). * * @return The dataset (possibly {@code null}). * * @see #setDataset(int, XYDataset) */ public XYDataset getDataset(int index) { return (XYDataset) this.datasets.get(index); } /** * Sets the primary dataset for the plot, replacing the existing dataset if * there is one. * * @param dataset the dataset ({@code null} permitted). * * @see #getDataset() * @see #setDataset(int, XYDataset) */ public void setDataset(XYDataset dataset) { setDataset(0, dataset); } /** * Sets a dataset for the plot and sends a change event to all registered * listeners. * * @param index the dataset index (must be &gt;= 0). * @param dataset the dataset ({@code null} permitted). * * @see #getDataset(int) */ public void setDataset(int index, XYDataset dataset) { XYDataset existing = getDataset(index); if (existing != null) { existing.removeChangeListener(this); } this.datasets.put(index, dataset); if (dataset != null) { dataset.addChangeListener(this); } // send a dataset change event to self... DatasetChangeEvent event = new DatasetChangeEvent(this, dataset); datasetChanged(event); } /** * Returns the number of datasets. * * @return The number of datasets. */ public int getDatasetCount() { return this.datasets.size(); } /** * Returns the index of the specified dataset, or {@code -1} if the * dataset does not belong to the plot. * * @param dataset the dataset ({@code null} not permitted). * * @return The index or -1. */ public int indexOf(XYDataset dataset) { for (Map.Entry<Integer, XYDataset> entry: this.datasets.entrySet()) { if (dataset == entry.getValue()) { return entry.getKey(); } } return -1; } /** * Maps a dataset to a particular domain axis. All data will be plotted * against axis zero by default, no mapping is required for this case. * * @param index the dataset index (zero-based). * @param axisIndex the axis index. * * @see #mapDatasetToRangeAxis(int, int) */ public void mapDatasetToDomainAxis(int index, int axisIndex) { List axisIndices = new java.util.ArrayList(1); axisIndices.add(new Integer(axisIndex)); mapDatasetToDomainAxes(index, axisIndices); } /** * Maps the specified dataset to the axes in the list. Note that the * conversion of data values into Java2D space is always performed using * the first axis in the list. * * @param index the dataset index (zero-based). * @param axisIndices the axis indices ({@code null} permitted). * * @since 1.0.12 */ public void mapDatasetToDomainAxes(int index, List axisIndices) { ParamChecks.requireNonNegative(index, "index"); checkAxisIndices(axisIndices); Integer key = new Integer(index); this.datasetToDomainAxesMap.put(key, new ArrayList(axisIndices)); // fake a dataset change event to update axes... datasetChanged(new DatasetChangeEvent(this, getDataset(index))); } /** * Maps a dataset to a particular range axis. All data will be plotted * against axis zero by default, no mapping is required for this case. * * @param index the dataset index (zero-based). * @param axisIndex the axis index. * * @see #mapDatasetToDomainAxis(int, int) */ public void mapDatasetToRangeAxis(int index, int axisIndex) { List axisIndices = new java.util.ArrayList(1); axisIndices.add(new Integer(axisIndex)); mapDatasetToRangeAxes(index, axisIndices); } /** * Maps the specified dataset to the axes in the list. Note that the * conversion of data values into Java2D space is always performed using * the first axis in the list. * * @param index the dataset index (zero-based). * @param axisIndices the axis indices ({@code null} permitted). * * @since 1.0.12 */ public void mapDatasetToRangeAxes(int index, List axisIndices) { ParamChecks.requireNonNegative(index, "index"); checkAxisIndices(axisIndices); Integer key = new Integer(index); this.datasetToRangeAxesMap.put(key, new ArrayList(axisIndices)); // fake a dataset change event to update axes... datasetChanged(new DatasetChangeEvent(this, getDataset(index))); } /** * This method is used to perform argument checking on the list of * axis indices passed to mapDatasetToDomainAxes() and * mapDatasetToRangeAxes(). * * @param indices the list of indices ({@code null} permitted). */ private void checkAxisIndices(List<Integer> indices) { // axisIndices can be: // 1. null; // 2. non-empty, containing only Integer objects that are unique. if (indices == null) { return; } int count = indices.size(); if (count == 0) { throw new IllegalArgumentException("Empty list not permitted."); } Set<Integer> set = new HashSet<Integer>(); for (Integer item : indices) { if (set.contains(item)) { throw new IllegalArgumentException("Indices must be unique."); } set.add(item); } } /** * Returns the number of renderer slots for this plot. * * @return The number of renderer slots. * * @since 1.0.11 */ public int getRendererCount() { return this.renderers.size(); } /** * Returns the renderer for the primary dataset. * * @return The item renderer (possibly {@code null}). * * @see #setRenderer(XYItemRenderer) */ public XYItemRenderer getRenderer() { return getRenderer(0); } /** * Returns the renderer with the specified index, or {@code null}. * * @param index the renderer index (must be &gt;= 0). * * @return The renderer (possibly {@code null}). * * @see #setRenderer(int, XYItemRenderer) */ public XYItemRenderer getRenderer(int index) { return (XYItemRenderer) this.renderers.get(index); } /** * Sets the renderer for the primary dataset and sends a change event to * all registered listeners. If the renderer is set to {@code null}, * no data will be displayed. * * @param renderer the renderer ({@code null} permitted). * * @see #getRenderer() */ public void setRenderer(XYItemRenderer renderer) { setRenderer(0, renderer); } /** * Sets the renderer for the dataset with the specified index and sends a * change event to all registered listeners. Note that each dataset should * have its own renderer, you should not use one renderer for multiple * datasets. * * @param index the index (must be &gt;= 0). * @param renderer the renderer. * * @see #getRenderer(int) */ public void setRenderer(int index, XYItemRenderer renderer) { setRenderer(index, renderer, true); } /** * Sets the renderer for the dataset with the specified index and, if * requested, sends a change event to all registered listeners. Note that * each dataset should have its own renderer, you should not use one * renderer for multiple datasets. * * @param index the index (must be &gt;= 0). * @param renderer the renderer. * @param notify notify listeners? * * @see #getRenderer(int) */ public void setRenderer(int index, XYItemRenderer renderer, boolean notify) { XYItemRenderer existing = getRenderer(index); if (existing != null) { existing.removeChangeListener(this); } this.renderers.put(index, renderer); if (renderer != null) { renderer.setPlot(this); renderer.addChangeListener(this); } configureDomainAxes(); configureRangeAxes(); if (notify) { fireChangeEvent(); } } /** * Sets the renderers for this plot and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param renderers the renderers ({@code null} not permitted). */ public void setRenderers(XYItemRenderer[] renderers) { for (int i = 0; i < renderers.length; i++) { setRenderer(i, renderers[i], false); } fireChangeEvent(); } /** * Returns the dataset rendering order. * * @return The order (never {@code null}). * * @see #setDatasetRenderingOrder(DatasetRenderingOrder) */ public DatasetRenderingOrder getDatasetRenderingOrder() { return this.datasetRenderingOrder; } /** * Sets the rendering order and sends a {@link PlotChangeEvent} to all * registered listeners. By default, the plot renders the primary dataset * last (so that the primary dataset overlays the secondary datasets). * You can reverse this if you want to. * * @param order the rendering order ({@code null} not permitted). * * @see #getDatasetRenderingOrder() */ public void setDatasetRenderingOrder(DatasetRenderingOrder order) { ParamChecks.nullNotPermitted(order, "order"); this.datasetRenderingOrder = order; fireChangeEvent(); } /** * Returns the series rendering order. * * @return the order (never {@code null}). * * @see #setSeriesRenderingOrder(SeriesRenderingOrder) */ public SeriesRenderingOrder getSeriesRenderingOrder() { return this.seriesRenderingOrder; } /** * Sets the series order and sends a {@link PlotChangeEvent} to all * registered listeners. By default, the plot renders the primary series * last (so that the primary series appears to be on top). * You can reverse this if you want to. * * @param order the rendering order ({@code null} not permitted). * * @see #getSeriesRenderingOrder() */ public void setSeriesRenderingOrder(SeriesRenderingOrder order) { ParamChecks.nullNotPermitted(order, "order"); this.seriesRenderingOrder = order; fireChangeEvent(); } /** * Returns the index of the specified renderer, or {@code -1} if the * renderer is not assigned to this plot. * * @param renderer the renderer ({@code null} permitted). * * @return The renderer index. */ public int getIndexOf(XYItemRenderer renderer) { for (Map.Entry<Integer, XYItemRenderer> entry : this.renderers.entrySet()) { if (entry.getValue() == renderer) { return entry.getKey(); } } return -1; } /** * Returns the renderer for the specified dataset (this is either the * renderer with the same index as the dataset or, if there isn't a * renderer with the same index, the default renderer). If the dataset * does not belong to the plot, this method will return {@code null}. * * @param dataset the dataset ({@code null} permitted). * * @return The renderer (possibly {@code null}). */ public XYItemRenderer getRendererForDataset(XYDataset dataset) { int datasetIndex = indexOf(dataset); if (datasetIndex < 0) { return null; } XYItemRenderer result = this.renderers.get(datasetIndex); if (result == null) { result = getRenderer(); } return result; } /** * Returns the weight for this plot when it is used as a subplot within a * combined plot. * * @return The weight. * * @see #setWeight(int) */ public int getWeight() { return this.weight; } /** * Sets the weight for the plot and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param weight the weight. * * @see #getWeight() */ public void setWeight(int weight) { this.weight = weight; fireChangeEvent(); } /** * Returns {@code true} if the domain gridlines are visible, and * {@code false} otherwise. * * @return {@code true} or {@code false}. * * @see #setDomainGridlinesVisible(boolean) */ public boolean isDomainGridlinesVisible() { return this.domainGridlinesVisible; } /** * Sets the flag that controls whether or not the domain grid-lines are * visible. * <p> * If the flag value is changed, a {@link PlotChangeEvent} is sent to all * registered listeners. * * @param visible the new value of the flag. * * @see #isDomainGridlinesVisible() */ public void setDomainGridlinesVisible(boolean visible) { if (this.domainGridlinesVisible != visible) { this.domainGridlinesVisible = visible; fireChangeEvent(); } } /** * Returns {@code true} if the domain minor gridlines are visible, and * {@code false} otherwise. * * @return {@code true} or {@code false}. * * @see #setDomainMinorGridlinesVisible(boolean) * * @since 1.0.12 */ public boolean isDomainMinorGridlinesVisible() { return this.domainMinorGridlinesVisible; } /** * Sets the flag that controls whether or not the domain minor grid-lines * are visible. * <p> * If the flag value is changed, a {@link PlotChangeEvent} is sent to all * registered listeners. * * @param visible the new value of the flag. * * @see #isDomainMinorGridlinesVisible() * * @since 1.0.12 */ public void setDomainMinorGridlinesVisible(boolean visible) { if (this.domainMinorGridlinesVisible != visible) { this.domainMinorGridlinesVisible = visible; fireChangeEvent(); } } /** * Returns the stroke for the grid-lines (if any) plotted against the * domain axis. * * @return The stroke (never {@code null}). * * @see #setDomainGridlineStroke(Stroke) */ public Stroke getDomainGridlineStroke() { return this.domainGridlineStroke; } public void setDomainGridlineStroke(Stroke stroke) { ParamChecks.nullNotPermitted(stroke, "stroke"); this.domainGridlineStroke = stroke; fireChangeEvent(); } /** * Returns the stroke for the minor grid-lines (if any) plotted against the * domain axis. * * @return The stroke (never {@code null}). * * @see #setDomainMinorGridlineStroke(Stroke) * * @since 1.0.12 */ public Stroke getDomainMinorGridlineStroke() { return this.domainMinorGridlineStroke; } public void setDomainMinorGridlineStroke(Stroke stroke) { ParamChecks.nullNotPermitted(stroke, "stroke"); this.domainMinorGridlineStroke = stroke; fireChangeEvent(); } /** * Returns the paint for the grid lines (if any) plotted against the domain * axis. * * @return The paint (never {@code null}). * * @see #setDomainGridlinePaint(Paint) */ public Paint getDomainGridlinePaint() { return this.domainGridlinePaint; } public void setDomainGridlinePaint(Paint paint) { ParamChecks.nullNotPermitted(paint, "paint"); this.domainGridlinePaint = paint; fireChangeEvent(); } /** * Returns the paint for the minor grid lines (if any) plotted against the * domain axis. * * @return The paint (never {@code null}). * * @see #setDomainMinorGridlinePaint(Paint) * * @since 1.0.12 */ public Paint getDomainMinorGridlinePaint() { return this.domainMinorGridlinePaint; } public void setDomainMinorGridlinePaint(Paint paint) { ParamChecks.nullNotPermitted(paint, "paint"); this.domainMinorGridlinePaint = paint; fireChangeEvent(); } /** * Returns {@code true} if the range axis grid is visible, and * {@code false} otherwise. * * @return A boolean. * * @see #setRangeGridlinesVisible(boolean) */ public boolean isRangeGridlinesVisible() { return this.rangeGridlinesVisible; } /** * Sets the flag that controls whether or not the range axis grid lines * are visible. * <p> * If the flag value is changed, a {@link PlotChangeEvent} is sent to all * registered listeners. * * @param visible the new value of the flag. * * @see #isRangeGridlinesVisible() */ public void setRangeGridlinesVisible(boolean visible) { if (this.rangeGridlinesVisible != visible) { this.rangeGridlinesVisible = visible; fireChangeEvent(); } } /** * Returns the stroke for the grid lines (if any) plotted against the * range axis. * * @return The stroke (never {@code null}). * * @see #setRangeGridlineStroke(Stroke) */ public Stroke getRangeGridlineStroke() { return this.rangeGridlineStroke; } /** * Sets the stroke for the grid lines plotted against the range axis, * and sends a {@link PlotChangeEvent} to all registered listeners. * * @param stroke the stroke ({@code null} not permitted). * * @see #getRangeGridlineStroke() */ public void setRangeGridlineStroke(Stroke stroke) { ParamChecks.nullNotPermitted(stroke, "stroke"); this.rangeGridlineStroke = stroke; fireChangeEvent(); } /** * Returns the paint for the grid lines (if any) plotted against the range * axis. * * @return The paint (never {@code null}). * * @see #setRangeGridlinePaint(Paint) */ public Paint getRangeGridlinePaint() { return this.rangeGridlinePaint; } /** * Sets the paint for the grid lines plotted against the range axis and * sends a {@link PlotChangeEvent} to all registered listeners. * * @param paint the paint ({@code null} not permitted). * * @see #getRangeGridlinePaint() */ public void setRangeGridlinePaint(Paint paint) { ParamChecks.nullNotPermitted(paint, "paint"); this.rangeGridlinePaint = paint; fireChangeEvent(); } /** * Returns {@code true} if the range axis minor grid is visible, and * {@code false} otherwise. * * @return A boolean. * * @see #setRangeMinorGridlinesVisible(boolean) * * @since 1.0.12 */ public boolean isRangeMinorGridlinesVisible() { return this.rangeMinorGridlinesVisible; } /** * Sets the flag that controls whether or not the range axis minor grid * lines are visible. * <p> * If the flag value is changed, a {@link PlotChangeEvent} is sent to all * registered listeners. * * @param visible the new value of the flag. * * @see #isRangeMinorGridlinesVisible() * * @since 1.0.12 */ public void setRangeMinorGridlinesVisible(boolean visible) { if (this.rangeMinorGridlinesVisible != visible) { this.rangeMinorGridlinesVisible = visible; fireChangeEvent(); } } /** * Returns the stroke for the minor grid lines (if any) plotted against the * range axis. * * @return The stroke (never {@code null}). * * @see #setRangeMinorGridlineStroke(Stroke) * * @since 1.0.12 */ public Stroke getRangeMinorGridlineStroke() { return this.rangeMinorGridlineStroke; } /** * Sets the stroke for the minor grid lines plotted against the range axis, * and sends a {@link PlotChangeEvent} to all registered listeners. * * @param stroke the stroke ({@code null} not permitted). * * @see #getRangeMinorGridlineStroke() * * @since 1.0.12 */ public void setRangeMinorGridlineStroke(Stroke stroke) { ParamChecks.nullNotPermitted(stroke, "stroke"); this.rangeMinorGridlineStroke = stroke; fireChangeEvent(); } /** * Returns the paint for the minor grid lines (if any) plotted against the * range axis. * * @return The paint (never {@code null}). * * @see #setRangeMinorGridlinePaint(Paint) * * @since 1.0.12 */ public Paint getRangeMinorGridlinePaint() { return this.rangeMinorGridlinePaint; } /** * Sets the paint for the minor grid lines plotted against the range axis * and sends a {@link PlotChangeEvent} to all registered listeners. * * @param paint the paint ({@code null} not permitted). * * @see #getRangeMinorGridlinePaint() * * @since 1.0.12 */ public void setRangeMinorGridlinePaint(Paint paint) { ParamChecks.nullNotPermitted(paint, "paint"); this.rangeMinorGridlinePaint = paint; fireChangeEvent(); } /** * Returns a flag that controls whether or not a zero baseline is * displayed for the domain axis. * * @return A boolean. * * @since 1.0.5 * * @see #setDomainZeroBaselineVisible(boolean) */ public boolean isDomainZeroBaselineVisible() { return this.domainZeroBaselineVisible; } /** * Sets the flag that controls whether or not the zero baseline is * displayed for the domain axis, and sends a {@link PlotChangeEvent} to * all registered listeners. * * @param visible the flag. * * @since 1.0.5 * * @see #isDomainZeroBaselineVisible() */ public void setDomainZeroBaselineVisible(boolean visible) { this.domainZeroBaselineVisible = visible; fireChangeEvent(); } /** * Returns the stroke used for the zero baseline against the domain axis. * * @return The stroke (never {@code null}). * * @since 1.0.5 * * @see #setDomainZeroBaselineStroke(Stroke) */ public Stroke getDomainZeroBaselineStroke() { return this.domainZeroBaselineStroke; } /** * Sets the stroke for the zero baseline for the domain axis, * and sends a {@link PlotChangeEvent} to all registered listeners. * * @param stroke the stroke ({@code null} not permitted). * * @since 1.0.5 * * @see #getRangeZeroBaselineStroke() */ public void setDomainZeroBaselineStroke(Stroke stroke) { ParamChecks.nullNotPermitted(stroke, "stroke"); this.domainZeroBaselineStroke = stroke; fireChangeEvent(); } /** * Returns the paint for the zero baseline (if any) plotted against the * domain axis. * * @since 1.0.5 * * @return The paint (never {@code null}). * * @see #setDomainZeroBaselinePaint(Paint) */ public Paint getDomainZeroBaselinePaint() { return this.domainZeroBaselinePaint; } /** * Sets the paint for the zero baseline plotted against the domain axis and * sends a {@link PlotChangeEvent} to all registered listeners. * * @param paint the paint ({@code null} not permitted). * * @since 1.0.5 * * @see #getDomainZeroBaselinePaint() */ public void setDomainZeroBaselinePaint(Paint paint) { ParamChecks.nullNotPermitted(paint, "paint"); this.domainZeroBaselinePaint = paint; fireChangeEvent(); } /** * Returns a flag that controls whether or not a zero baseline is * displayed for the range axis. * * @return A boolean. * * @see #setRangeZeroBaselineVisible(boolean) */ public boolean isRangeZeroBaselineVisible() { return this.rangeZeroBaselineVisible; } /** * Sets the flag that controls whether or not the zero baseline is * displayed for the range axis, and sends a {@link PlotChangeEvent} to * all registered listeners. * * @param visible the flag. * * @see #isRangeZeroBaselineVisible() */ public void setRangeZeroBaselineVisible(boolean visible) { this.rangeZeroBaselineVisible = visible; fireChangeEvent(); } /** * Returns the stroke used for the zero baseline against the range axis. * * @return The stroke (never {@code null}). * * @see #setRangeZeroBaselineStroke(Stroke) */ public Stroke getRangeZeroBaselineStroke() { return this.rangeZeroBaselineStroke; } /** * Sets the stroke for the zero baseline for the range axis, * and sends a {@link PlotChangeEvent} to all registered listeners. * * @param stroke the stroke ({@code null} not permitted). * * @see #getRangeZeroBaselineStroke() */ public void setRangeZeroBaselineStroke(Stroke stroke) { ParamChecks.nullNotPermitted(stroke, "stroke"); this.rangeZeroBaselineStroke = stroke; fireChangeEvent(); } /** * Returns the paint for the zero baseline (if any) plotted against the * range axis. * * @return The paint (never {@code null}). * * @see #setRangeZeroBaselinePaint(Paint) */ public Paint getRangeZeroBaselinePaint() { return this.rangeZeroBaselinePaint; } /** * Sets the paint for the zero baseline plotted against the range axis and * sends a {@link PlotChangeEvent} to all registered listeners. * * @param paint the paint ({@code null} not permitted). * * @see #getRangeZeroBaselinePaint() */ public void setRangeZeroBaselinePaint(Paint paint) { ParamChecks.nullNotPermitted(paint, "paint"); this.rangeZeroBaselinePaint = paint; fireChangeEvent(); } /** * Returns the paint used for the domain tick bands. If this is * {@code null}, no tick bands will be drawn. * * @return The paint (possibly {@code null}). * * @see #setDomainTickBandPaint(Paint) */ public Paint getDomainTickBandPaint() { return this.domainTickBandPaint; } /** * Sets the paint for the domain tick bands. * * @param paint the paint ({@code null} permitted). * * @see #getDomainTickBandPaint() */ public void setDomainTickBandPaint(Paint paint) { this.domainTickBandPaint = paint; fireChangeEvent(); } /** * Returns the paint used for the range tick bands. If this is * {@code null}, no tick bands will be drawn. * * @return The paint (possibly {@code null}). * * @see #setRangeTickBandPaint(Paint) */ public Paint getRangeTickBandPaint() { return this.rangeTickBandPaint; } /** * Sets the paint for the range tick bands. * * @param paint the paint ({@code null} permitted). * * @see #getRangeTickBandPaint() */ public void setRangeTickBandPaint(Paint paint) { this.rangeTickBandPaint = paint; fireChangeEvent(); } /** * Returns the origin for the quadrants that can be displayed on the plot. * This defaults to (0, 0). * * @return The origin point (never {@code null}). * * @see #setQuadrantOrigin(Point2D) */ public Point2D getQuadrantOrigin() { return this.quadrantOrigin; } /** * Sets the quadrant origin and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param origin the origin ({@code null} not permitted). * * @see #getQuadrantOrigin() */ public void setQuadrantOrigin(Point2D origin) { ParamChecks.nullNotPermitted(origin, "origin"); this.quadrantOrigin = origin; fireChangeEvent(); } /** * Returns the paint used for the specified quadrant. * * @param index the quadrant index (0-3). * * @return The paint (possibly {@code null}). * * @see #setQuadrantPaint(int, Paint) */ public Paint getQuadrantPaint(int index) { if (index < 0 || index > 3) { throw new IllegalArgumentException("The index value (" + index + ") should be in the range 0 to 3."); } return this.quadrantPaint[index]; } /** * Sets the paint used for the specified quadrant and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param index the quadrant index (0-3). * @param paint the paint ({@code null} permitted). * * @see #getQuadrantPaint(int) */ public void setQuadrantPaint(int index, Paint paint) { if (index < 0 || index > 3) { throw new IllegalArgumentException("The index value (" + index + ") should be in the range 0 to 3."); } this.quadrantPaint[index] = paint; fireChangeEvent(); } /** * Adds a marker for the domain axis and sends a {@link PlotChangeEvent} * to all registered listeners. * <P> * Typically a marker will be drawn by the renderer as a line perpendicular * to the domain axis, however this is entirely up to the renderer. * * @param marker the marker ({@code null} not permitted). * * @see #addDomainMarker(Marker, Layer) * @see #clearDomainMarkers() */ public void addDomainMarker(Marker marker) { // defer argument checking... addDomainMarker(marker, Layer.FOREGROUND); } /** * Adds a marker for the domain axis in the specified layer and sends a * {@link PlotChangeEvent} to all registered listeners. * <P> * Typically a marker will be drawn by the renderer as a line perpendicular * to the domain axis, however this is entirely up to the renderer. * * @param marker the marker ({@code null} not permitted). * @param layer the layer (foreground or background). * * @see #addDomainMarker(int, Marker, Layer) */ public void addDomainMarker(Marker marker, Layer layer) { addDomainMarker(0, marker, layer); } /** * Clears all the (foreground and background) domain markers and sends a * {@link PlotChangeEvent} to all registered listeners. * * @see #addDomainMarker(int, Marker, Layer) */ public void clearDomainMarkers() { if (this.backgroundDomainMarkers != null) { Set<Integer> keys = this.backgroundDomainMarkers.keySet(); for (Integer key : keys) { clearDomainMarkers(key); } this.backgroundDomainMarkers.clear(); } if (this.foregroundDomainMarkers != null) { Set<Integer> keys = this.foregroundDomainMarkers.keySet(); for (Integer key : keys) { clearDomainMarkers(key); } this.foregroundDomainMarkers.clear(); } fireChangeEvent(); } /** * Clears the (foreground and background) domain markers for a particular * renderer and sends a {@link PlotChangeEvent} to all registered listeners. * * @param index the renderer index. * * @see #clearRangeMarkers(int) */ public void clearDomainMarkers(int index) { Integer key = new Integer(index); if (this.backgroundDomainMarkers != null) { Collection markers = (Collection) this.backgroundDomainMarkers.get(key); if (markers != null) { Iterator iterator = markers.iterator(); while (iterator.hasNext()) { Marker m = (Marker) iterator.next(); m.removeChangeListener(this); } markers.clear(); } } if (this.foregroundRangeMarkers != null) { Collection markers = (Collection) this.foregroundDomainMarkers.get(key); if (markers != null) { Iterator iterator = markers.iterator(); while (iterator.hasNext()) { Marker m = (Marker) iterator.next(); m.removeChangeListener(this); } markers.clear(); } } fireChangeEvent(); } /** * Adds a marker for a specific dataset/renderer and sends a * {@link PlotChangeEvent} to all registered listeners. * <P> * Typically a marker will be drawn by the renderer as a line perpendicular * to the domain axis (that the renderer is mapped to), however this is * entirely up to the renderer. * * @param index the dataset/renderer index. * @param marker the marker. * @param layer the layer (foreground or background). * * @see #clearDomainMarkers(int) * @see #addRangeMarker(int, Marker, Layer) */ public void addDomainMarker(int index, Marker marker, Layer layer) { addDomainMarker(index, marker, layer, true); } /** * Adds a marker for a specific dataset/renderer and, if requested, sends a * {@link PlotChangeEvent} to all registered listeners. * <P> * Typically a marker will be drawn by the renderer as a line perpendicular * to the domain axis (that the renderer is mapped to), however this is * entirely up to the renderer. * * @param index the dataset/renderer index. * @param marker the marker. * @param layer the layer (foreground or background). * @param notify notify listeners? * * @since 1.0.10 */ public void addDomainMarker(int index, Marker marker, Layer layer, boolean notify) { ParamChecks.nullNotPermitted(marker, "marker"); ParamChecks.nullNotPermitted(layer, "layer"); Collection markers; if (layer == Layer.FOREGROUND) { markers = (Collection) this.foregroundDomainMarkers.get( new Integer(index)); if (markers == null) { markers = new java.util.ArrayList(); this.foregroundDomainMarkers.put(new Integer(index), markers); } markers.add(marker); } else if (layer == Layer.BACKGROUND) { markers = (Collection) this.backgroundDomainMarkers.get( new Integer(index)); if (markers == null) { markers = new java.util.ArrayList(); this.backgroundDomainMarkers.put(new Integer(index), markers); } markers.add(marker); } marker.addChangeListener(this); if (notify) { fireChangeEvent(); } } /** * Removes a marker for the domain axis and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param marker the marker. * * @return A boolean indicating whether or not the marker was actually * removed. * * @since 1.0.7 */ public boolean removeDomainMarker(Marker marker) { return removeDomainMarker(marker, Layer.FOREGROUND); } /** * Removes a marker for the domain axis in the specified layer and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param marker the marker ({@code null} not permitted). * @param layer the layer (foreground or background). * * @return A boolean indicating whether or not the marker was actually * removed. * * @since 1.0.7 */ public boolean removeDomainMarker(Marker marker, Layer layer) { return removeDomainMarker(0, marker, layer); } /** * Removes a marker for a specific dataset/renderer and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param index the dataset/renderer index. * @param marker the marker. * @param layer the layer (foreground or background). * * @return A boolean indicating whether or not the marker was actually * removed. * * @since 1.0.7 */ public boolean removeDomainMarker(int index, Marker marker, Layer layer) { return removeDomainMarker(index, marker, layer, true); } /** * Removes a marker for a specific dataset/renderer and, if requested, * sends a {@link PlotChangeEvent} to all registered listeners. * * @param index the dataset/renderer index. * @param marker the marker. * @param layer the layer (foreground or background). * @param notify notify listeners? * * @return A boolean indicating whether or not the marker was actually * removed. * * @since 1.0.10 */ public boolean removeDomainMarker(int index, Marker marker, Layer layer, boolean notify) { ArrayList markers; if (layer == Layer.FOREGROUND) { markers = (ArrayList) this.foregroundDomainMarkers.get( new Integer(index)); } else { markers = (ArrayList) this.backgroundDomainMarkers.get( new Integer(index)); } if (markers == null) { return false; } boolean removed = markers.remove(marker); if (removed && notify) { fireChangeEvent(); } return removed; } /** * Adds a marker for the range axis and sends a {@link PlotChangeEvent} to * all registered listeners. * <P> * Typically a marker will be drawn by the renderer as a line perpendicular * to the range axis, however this is entirely up to the renderer. * * @param marker the marker ({@code null} not permitted). * * @see #addRangeMarker(Marker, Layer) */ public void addRangeMarker(Marker marker) { addRangeMarker(marker, Layer.FOREGROUND); } /** * Adds a marker for the range axis in the specified layer and sends a * {@link PlotChangeEvent} to all registered listeners. * <P> * Typically a marker will be drawn by the renderer as a line perpendicular * to the range axis, however this is entirely up to the renderer. * * @param marker the marker ({@code null} not permitted). * @param layer the layer (foreground or background). * * @see #addRangeMarker(int, Marker, Layer) */ public void addRangeMarker(Marker marker, Layer layer) { addRangeMarker(0, marker, layer); } /** * Clears all the range markers and sends a {@link PlotChangeEvent} to all * registered listeners. * * @see #clearRangeMarkers() */ public void clearRangeMarkers() { if (this.backgroundRangeMarkers != null) { Set<Integer> keys = this.backgroundRangeMarkers.keySet(); for (Integer key : keys) { clearRangeMarkers(key); } this.backgroundRangeMarkers.clear(); } if (this.foregroundRangeMarkers != null) { Set<Integer> keys = this.foregroundRangeMarkers.keySet(); for (Integer key : keys) { clearRangeMarkers(key); } this.foregroundRangeMarkers.clear(); } fireChangeEvent(); } /** * Adds a marker for a specific dataset/renderer and sends a * {@link PlotChangeEvent} to all registered listeners. * <P> * Typically a marker will be drawn by the renderer as a line perpendicular * to the range axis, however this is entirely up to the renderer. * * @param index the dataset/renderer index. * @param marker the marker. * @param layer the layer (foreground or background). * * @see #clearRangeMarkers(int) * @see #addDomainMarker(int, Marker, Layer) */ public void addRangeMarker(int index, Marker marker, Layer layer) { addRangeMarker(index, marker, layer, true); } /** * Adds a marker for a specific dataset/renderer and, if requested, sends a * {@link PlotChangeEvent} to all registered listeners. * <P> * Typically a marker will be drawn by the renderer as a line perpendicular * to the range axis, however this is entirely up to the renderer. * * @param index the dataset/renderer index. * @param marker the marker. * @param layer the layer (foreground or background). * @param notify notify listeners? * * @since 1.0.10 */ public void addRangeMarker(int index, Marker marker, Layer layer, boolean notify) { Collection markers; if (layer == Layer.FOREGROUND) { markers = (Collection) this.foregroundRangeMarkers.get( new Integer(index)); if (markers == null) { markers = new java.util.ArrayList(); this.foregroundRangeMarkers.put(new Integer(index), markers); } markers.add(marker); } else if (layer == Layer.BACKGROUND) { markers = (Collection) this.backgroundRangeMarkers.get( new Integer(index)); if (markers == null) { markers = new java.util.ArrayList(); this.backgroundRangeMarkers.put(new Integer(index), markers); } markers.add(marker); } marker.addChangeListener(this); if (notify) { fireChangeEvent(); } } /** * Clears the (foreground and background) range markers for a particular * renderer. * * @param index the renderer index. */ public void clearRangeMarkers(int index) { Integer key = new Integer(index); if (this.backgroundRangeMarkers != null) { Collection markers = (Collection) this.backgroundRangeMarkers.get(key); if (markers != null) { Iterator iterator = markers.iterator(); while (iterator.hasNext()) { Marker m = (Marker) iterator.next(); m.removeChangeListener(this); } markers.clear(); } } if (this.foregroundRangeMarkers != null) { Collection markers = (Collection) this.foregroundRangeMarkers.get(key); if (markers != null) { Iterator iterator = markers.iterator(); while (iterator.hasNext()) { Marker m = (Marker) iterator.next(); m.removeChangeListener(this); } markers.clear(); } } fireChangeEvent(); } /** * Removes a marker for the range axis and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param marker the marker. * * @return A boolean indicating whether or not the marker was actually * removed. * * @since 1.0.7 */ public boolean removeRangeMarker(Marker marker) { return removeRangeMarker(marker, Layer.FOREGROUND); } /** * Removes a marker for the range axis in the specified layer and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param marker the marker ({@code null} not permitted). * @param layer the layer (foreground or background). * * @return A boolean indicating whether or not the marker was actually * removed. * * @since 1.0.7 */ public boolean removeRangeMarker(Marker marker, Layer layer) { return removeRangeMarker(0, marker, layer); } /** * Removes a marker for a specific dataset/renderer and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param index the dataset/renderer index. * @param marker the marker ({@code null} not permitted). * @param layer the layer (foreground or background). * * @return A boolean indicating whether or not the marker was actually * removed. * * @since 1.0.7 */ public boolean removeRangeMarker(int index, Marker marker, Layer layer) { return removeRangeMarker(index, marker, layer, true); } /** * Removes a marker for a specific dataset/renderer and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param index the dataset/renderer index. * @param marker the marker ({@code null} not permitted). * @param layer the layer (foreground or background) ({@code null} not permitted). * @param notify notify listeners? * * @return A boolean indicating whether or not the marker was actually * removed. * * @since 1.0.10 */ public boolean removeRangeMarker(int index, Marker marker, Layer layer, boolean notify) { ParamChecks.nullNotPermitted(marker, "marker"); ParamChecks.nullNotPermitted(layer, "layer"); List markers; if (layer == Layer.FOREGROUND) { markers = (List) this.foregroundRangeMarkers.get( new Integer(index)); } else { markers = (List) this.backgroundRangeMarkers.get( new Integer(index)); } if (markers == null) { return false; } boolean removed = markers.remove(marker); if (removed && notify) { fireChangeEvent(); } return removed; } /** * Adds an annotation to the plot and sends a {@link PlotChangeEvent} to * all registered listeners. * * @param annotation the annotation ({@code null} not permitted). * * @see #getAnnotations() * @see #removeAnnotation(XYAnnotation) */ public void addAnnotation(XYAnnotation annotation) { addAnnotation(annotation, true); } /** * Adds an annotation to the plot and, if requested, sends a * {@link PlotChangeEvent} to all registered listeners. * * @param annotation the annotation ({@code null} not permitted). * @param notify notify listeners? * * @since 1.0.10 */ public void addAnnotation(XYAnnotation annotation, boolean notify) { ParamChecks.nullNotPermitted(annotation, "annotation"); this.annotations.add(annotation); annotation.addChangeListener(this); if (notify) { fireChangeEvent(); } } /** * Removes an annotation from the plot and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param annotation the annotation ({@code null} not permitted). * * @return A boolean (indicates whether or not the annotation was removed). * * @see #addAnnotation(XYAnnotation) * @see #getAnnotations() */ public boolean removeAnnotation(XYAnnotation annotation) { return removeAnnotation(annotation, true); } /** * Removes an annotation from the plot and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param annotation the annotation ({@code null} not permitted). * @param notify notify listeners? * * @return A boolean (indicates whether or not the annotation was removed). * * @since 1.0.10 */ public boolean removeAnnotation(XYAnnotation annotation, boolean notify) { ParamChecks.nullNotPermitted(annotation, "annotation"); boolean removed = this.annotations.remove(annotation); annotation.removeChangeListener(this); if (removed && notify) { fireChangeEvent(); } return removed; } /** * Returns the list of annotations. * * @return The list of annotations. * * @since 1.0.1 * * @see #addAnnotation(XYAnnotation) */ public List getAnnotations() { return new ArrayList(this.annotations); } /** * Clears all the annotations and sends a {@link PlotChangeEvent} to all * registered listeners. * * @see #addAnnotation(XYAnnotation) */ public void clearAnnotations() { for (XYAnnotation annotation : this.annotations) { annotation.removeChangeListener(this); } this.annotations.clear(); fireChangeEvent(); } /** * Returns the shadow generator for the plot, if any. * * @return The shadow generator (possibly {@code null}). * * @since 1.0.14 */ public ShadowGenerator getShadowGenerator() { return this.shadowGenerator; } /** * Sets the shadow generator for the plot and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param generator the generator ({@code null} permitted). * * @since 1.0.14 */ public void setShadowGenerator(ShadowGenerator generator) { this.shadowGenerator = generator; fireChangeEvent(); } /** * Calculates the space required for all the axes in the plot. * * @param g2 the graphics device. * @param plotArea the plot area. * * @return The required space. */ protected AxisSpace calculateAxisSpace(Graphics2D g2, Rectangle2D plotArea) { AxisSpace space = new AxisSpace(); space = calculateRangeAxisSpace(g2, plotArea, space); Rectangle2D revPlotArea = space.shrink(plotArea, null); space = calculateDomainAxisSpace(g2, revPlotArea, space); return space; } /** * Calculates the space required for the domain axis/axes. * * @param g2 the graphics device. * @param plotArea the plot area. * @param space a carrier for the result ({@code null} permitted). * * @return The required space. */ protected AxisSpace calculateDomainAxisSpace(Graphics2D g2, Rectangle2D plotArea, AxisSpace space) { if (space == null) { space = new AxisSpace(); } // reserve some space for the domain axis... if (this.fixedDomainAxisSpace != null) { if (this.orientation == PlotOrientation.HORIZONTAL) { space.ensureAtLeast(this.fixedDomainAxisSpace.getLeft(), RectangleEdge.LEFT); space.ensureAtLeast(this.fixedDomainAxisSpace.getRight(), RectangleEdge.RIGHT); } else if (this.orientation == PlotOrientation.VERTICAL) { space.ensureAtLeast(this.fixedDomainAxisSpace.getTop(), RectangleEdge.TOP); space.ensureAtLeast(this.fixedDomainAxisSpace.getBottom(), RectangleEdge.BOTTOM); } } else { // reserve space for the domain axes... for (ValueAxis axis: this.domainAxes.values()) { if (axis != null) { RectangleEdge edge = getDomainAxisEdge( findDomainAxisIndex(axis)); space = axis.reserveSpace(g2, this, plotArea, edge, space); } } } return space; } /** * Calculates the space required for the range axis/axes. * * @param g2 the graphics device. * @param plotArea the plot area. * @param space a carrier for the result ({@code null} permitted). * * @return The required space. */ protected AxisSpace calculateRangeAxisSpace(Graphics2D g2, Rectangle2D plotArea, AxisSpace space) { if (space == null) { space = new AxisSpace(); } // reserve some space for the range axis... if (this.fixedRangeAxisSpace != null) { if (this.orientation == PlotOrientation.HORIZONTAL) { space.ensureAtLeast(this.fixedRangeAxisSpace.getTop(), RectangleEdge.TOP); space.ensureAtLeast(this.fixedRangeAxisSpace.getBottom(), RectangleEdge.BOTTOM); } else if (this.orientation == PlotOrientation.VERTICAL) { space.ensureAtLeast(this.fixedRangeAxisSpace.getLeft(), RectangleEdge.LEFT); space.ensureAtLeast(this.fixedRangeAxisSpace.getRight(), RectangleEdge.RIGHT); } } else { // reserve space for the range axes... for (ValueAxis axis: this.rangeAxes.values()) { if (axis != null) { RectangleEdge edge = getRangeAxisEdge( findRangeAxisIndex(axis)); space = axis.reserveSpace(g2, this, plotArea, edge, space); } } } return space; } /** * Trims a rectangle to integer coordinates. * * @param rect the incoming rectangle. * * @return A rectangle with integer coordinates. */ private Rectangle integerise(Rectangle2D rect) { int x0 = (int) Math.ceil(rect.getMinX()); int y0 = (int) Math.ceil(rect.getMinY()); int x1 = (int) Math.floor(rect.getMaxX()); int y1 = (int) Math.floor(rect.getMaxY()); return new Rectangle(x0, y0, (x1 - x0), (y1 - y0)); } /** * Draws the plot within the specified area on a graphics device. * * @param g2 the graphics device. * @param area the plot area (in Java2D space). * @param anchor an anchor point in Java2D space ({@code null} * permitted). * @param parentState the state from the parent plot, if there is one * ({@code null} permitted). * @param info collects chart drawing information ({@code null} * permitted). */ @Override public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor, PlotState parentState, PlotRenderingInfo info) { // if the plot area is too small, just return... boolean b1 = (area.getWidth() <= MINIMUM_WIDTH_TO_DRAW); boolean b2 = (area.getHeight() <= MINIMUM_HEIGHT_TO_DRAW); if (b1 || b2) { return; } // record the plot area... if (info != null) { info.setPlotArea(area); } // adjust the drawing area for the plot insets (if any)... RectangleInsets insets = getInsets(); insets.trim(area); AxisSpace space = calculateAxisSpace(g2, area); Rectangle2D dataArea = space.shrink(area, null); this.axisOffset.trim(dataArea); dataArea = integerise(dataArea); if (dataArea.isEmpty()) { return; } createAndAddEntity((Rectangle2D) dataArea.clone(), info, null, null); if (info != null) { info.setDataArea(dataArea); } // draw the plot background and axes... drawBackground(g2, dataArea); Map axisStateMap = drawAxes(g2, area, dataArea, info); PlotOrientation orient = getOrientation(); // the anchor point is typically the point where the mouse last // clicked - the crosshairs will be driven off this point... if (anchor != null && !dataArea.contains(anchor)) { anchor = null; } CrosshairState crosshairState = new CrosshairState(); crosshairState.setCrosshairDistance(Double.POSITIVE_INFINITY); crosshairState.setAnchor(anchor); crosshairState.setAnchorX(Double.NaN); crosshairState.setAnchorY(Double.NaN); if (anchor != null) { ValueAxis domainAxis = getDomainAxis(); if (domainAxis != null) { double x; if (orient == PlotOrientation.VERTICAL) { x = domainAxis.java2DToValue(anchor.getX(), dataArea, getDomainAxisEdge()); } else { x = domainAxis.java2DToValue(anchor.getY(), dataArea, getDomainAxisEdge()); } crosshairState.setAnchorX(x); } ValueAxis rangeAxis = getRangeAxis(); if (rangeAxis != null) { double y; if (orient == PlotOrientation.VERTICAL) { y = rangeAxis.java2DToValue(anchor.getY(), dataArea, getRangeAxisEdge()); } else { y = rangeAxis.java2DToValue(anchor.getX(), dataArea, getRangeAxisEdge()); } crosshairState.setAnchorY(y); } } crosshairState.setCrosshairX(getDomainCrosshairValue()); crosshairState.setCrosshairY(getRangeCrosshairValue()); Shape originalClip = g2.getClip(); Composite originalComposite = g2.getComposite(); g2.clip(dataArea); g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getForegroundAlpha())); AxisState domainAxisState = (AxisState) axisStateMap.get( getDomainAxis()); if (domainAxisState == null) { if (parentState != null) { domainAxisState = (AxisState) parentState.getSharedAxisStates() .get(getDomainAxis()); } } AxisState rangeAxisState = (AxisState) axisStateMap.get(getRangeAxis()); if (rangeAxisState == null) { if (parentState != null) { rangeAxisState = (AxisState) parentState.getSharedAxisStates() .get(getRangeAxis()); } } if (domainAxisState != null) { drawDomainTickBands(g2, dataArea, domainAxisState.getTicks()); } if (rangeAxisState != null) { drawRangeTickBands(g2, dataArea, rangeAxisState.getTicks()); } if (domainAxisState != null) { drawDomainGridlines(g2, dataArea, domainAxisState.getTicks()); drawZeroDomainBaseline(g2, dataArea); } if (rangeAxisState != null) { drawRangeGridlines(g2, dataArea, rangeAxisState.getTicks()); drawZeroRangeBaseline(g2, dataArea); } Graphics2D savedG2 = g2; BufferedImage dataImage = null; boolean suppressShadow = Boolean.TRUE.equals(g2.getRenderingHint( JFreeChart.KEY_SUPPRESS_SHADOW_GENERATION)); if (this.shadowGenerator != null && !suppressShadow) { dataImage = new BufferedImage((int) dataArea.getWidth(), (int)dataArea.getHeight(), BufferedImage.TYPE_INT_ARGB); g2 = dataImage.createGraphics(); g2.translate(-dataArea.getX(), -dataArea.getY()); g2.setRenderingHints(savedG2.getRenderingHints()); } // draw the markers that are associated with a specific dataset... for (XYDataset dataset: this.datasets.values()) { int datasetIndex = indexOf(dataset); drawDomainMarkers(g2, dataArea, datasetIndex, Layer.BACKGROUND); } for (XYDataset dataset: this.datasets.values()) { int datasetIndex = indexOf(dataset); drawRangeMarkers(g2, dataArea, datasetIndex, Layer.BACKGROUND); } // now draw annotations and render data items... boolean foundData = false; DatasetRenderingOrder order = getDatasetRenderingOrder(); List<Integer> rendererIndices = getRendererIndices(order); List<Integer> datasetIndices = getDatasetIndices(order); // draw background annotations for (int i : rendererIndices) { XYItemRenderer renderer = getRenderer(i); if (renderer != null) { ValueAxis domainAxis = getDomainAxisForDataset(i); ValueAxis rangeAxis = getRangeAxisForDataset(i); renderer.drawAnnotations(g2, dataArea, domainAxis, rangeAxis, Layer.BACKGROUND, info); } } // render data items... for (int datasetIndex : datasetIndices) { XYDataset dataset = this.getDataset(datasetIndex); foundData = render(g2, dataArea, datasetIndex, info, crosshairState) || foundData; } // draw foreground annotations for (int i : rendererIndices) { XYItemRenderer renderer = getRenderer(i); if (renderer != null) { ValueAxis domainAxis = getDomainAxisForDataset(i); ValueAxis rangeAxis = getRangeAxisForDataset(i); renderer.drawAnnotations(g2, dataArea, domainAxis, rangeAxis, Layer.FOREGROUND, info); } } // draw domain crosshair if required... int datasetIndex = crosshairState.getDatasetIndex(); ValueAxis xAxis = getDomainAxisForDataset(datasetIndex); RectangleEdge xAxisEdge = getDomainAxisEdge(getDomainAxisIndex(xAxis)); if (!this.domainCrosshairLockedOnData && anchor != null) { double xx; if (orient == PlotOrientation.VERTICAL) { xx = xAxis.java2DToValue(anchor.getX(), dataArea, xAxisEdge); } else { xx = xAxis.java2DToValue(anchor.getY(), dataArea, xAxisEdge); } crosshairState.setCrosshairX(xx); } setDomainCrosshairValue(crosshairState.getCrosshairX(), false); if (isDomainCrosshairVisible()) { double x = getDomainCrosshairValue(); Paint paint = getDomainCrosshairPaint(); Stroke stroke = getDomainCrosshairStroke(); drawDomainCrosshair(g2, dataArea, orient, x, xAxis, stroke, paint); } // draw range crosshair if required... ValueAxis yAxis = getRangeAxisForDataset(datasetIndex); RectangleEdge yAxisEdge = getRangeAxisEdge(getRangeAxisIndex(yAxis)); if (!this.rangeCrosshairLockedOnData && anchor != null) { double yy; if (orient == PlotOrientation.VERTICAL) { yy = yAxis.java2DToValue(anchor.getY(), dataArea, yAxisEdge); } else { yy = yAxis.java2DToValue(anchor.getX(), dataArea, yAxisEdge); } crosshairState.setCrosshairY(yy); } setRangeCrosshairValue(crosshairState.getCrosshairY(), false); if (isRangeCrosshairVisible()) { double y = getRangeCrosshairValue(); Paint paint = getRangeCrosshairPaint(); Stroke stroke = getRangeCrosshairStroke(); drawRangeCrosshair(g2, dataArea, orient, y, yAxis, stroke, paint); } if (!foundData) { drawNoDataMessage(g2, dataArea); } for (int i : rendererIndices) { drawDomainMarkers(g2, dataArea, i, Layer.FOREGROUND); } for (int i : rendererIndices) { drawRangeMarkers(g2, dataArea, i, Layer.FOREGROUND); } drawAnnotations(g2, dataArea, info); if (this.shadowGenerator != null && !suppressShadow) { BufferedImage shadowImage = this.shadowGenerator.createDropShadow(dataImage); g2 = savedG2; g2.drawImage(shadowImage, (int) dataArea.getX() + this.shadowGenerator.calculateOffsetX(), (int) dataArea.getY() + this.shadowGenerator.calculateOffsetY(), null); g2.drawImage(dataImage, (int) dataArea.getX(), (int) dataArea.getY(), null); } g2.setClip(originalClip); g2.setComposite(originalComposite); drawOutline(g2, dataArea); } /** * Returns the indices of the non-null datasets in the specified order. * * @param order the order ({@code null} not permitted). * * @return The list of indices. */ private List<Integer> getDatasetIndices(DatasetRenderingOrder order) { List<Integer> result = new ArrayList<Integer>(); for (Entry<Integer, XYDataset> entry : this.datasets.entrySet()) { if (entry.getValue() != null) { result.add(entry.getKey()); } } Collections.sort(result); if (order == DatasetRenderingOrder.REVERSE) { Collections.reverse(result); } return result; } private List<Integer> getRendererIndices(DatasetRenderingOrder order) { List<Integer> result = new ArrayList<Integer>(); for (Entry<Integer, XYItemRenderer> entry : this.renderers.entrySet()) { if (entry.getValue() != null) { result.add(entry.getKey()); } } Collections.sort(result); if (order == DatasetRenderingOrder.REVERSE) { Collections.reverse(result); } return result; } /** * Draws the background for the plot. * * @param g2 the graphics device. * @param area the area. */ @Override public void drawBackground(Graphics2D g2, Rectangle2D area) { fillBackground(g2, area, this.orientation); drawQuadrants(g2, area); drawBackgroundImage(g2, area); } /** * Draws the quadrants. * * @param g2 the graphics device. * @param area the area. * * @see #setQuadrantOrigin(Point2D) * @see #setQuadrantPaint(int, Paint) */ protected void drawQuadrants(Graphics2D g2, Rectangle2D area) { // 0 | 1 // 2 | 3 boolean somethingToDraw = false; ValueAxis xAxis = getDomainAxis(); if (xAxis == null) { // we can't draw quadrants without a valid x-axis return; } double x = xAxis.getRange().constrain(this.quadrantOrigin.getX()); double xx = xAxis.valueToJava2D(x, area, getDomainAxisEdge()); ValueAxis yAxis = getRangeAxis(); if (yAxis == null) { // we can't draw quadrants without a valid y-axis return; } double y = yAxis.getRange().constrain(this.quadrantOrigin.getY()); double yy = yAxis.valueToJava2D(y, area, getRangeAxisEdge()); double xmin = xAxis.getLowerBound(); double xxmin = xAxis.valueToJava2D(xmin, area, getDomainAxisEdge()); double xmax = xAxis.getUpperBound(); double xxmax = xAxis.valueToJava2D(xmax, area, getDomainAxisEdge()); double ymin = yAxis.getLowerBound(); double yymin = yAxis.valueToJava2D(ymin, area, getRangeAxisEdge()); double ymax = yAxis.getUpperBound(); double yymax = yAxis.valueToJava2D(ymax, area, getRangeAxisEdge()); Rectangle2D[] r = new Rectangle2D[] {null, null, null, null}; if (this.quadrantPaint[0] != null) { if (x > xmin && y < ymax) { if (this.orientation == PlotOrientation.HORIZONTAL) { r[0] = new Rectangle2D.Double(Math.min(yymax, yy), Math.min(xxmin, xx), Math.abs(yy - yymax), Math.abs(xx - xxmin)); } else { // PlotOrientation.VERTICAL r[0] = new Rectangle2D.Double(Math.min(xxmin, xx), Math.min(yymax, yy), Math.abs(xx - xxmin), Math.abs(yy - yymax)); } somethingToDraw = true; } } if (this.quadrantPaint[1] != null) { if (x < xmax && y < ymax) { if (this.orientation == PlotOrientation.HORIZONTAL) { r[1] = new Rectangle2D.Double(Math.min(yymax, yy), Math.min(xxmax, xx), Math.abs(yy - yymax), Math.abs(xx - xxmax)); } else { // PlotOrientation.VERTICAL r[1] = new Rectangle2D.Double(Math.min(xx, xxmax), Math.min(yymax, yy), Math.abs(xx - xxmax), Math.abs(yy - yymax)); } somethingToDraw = true; } } if (this.quadrantPaint[2] != null) { if (x > xmin && y > ymin) { if (this.orientation == PlotOrientation.HORIZONTAL) { r[2] = new Rectangle2D.Double(Math.min(yymin, yy), Math.min(xxmin, xx), Math.abs(yy - yymin), Math.abs(xx - xxmin)); } else { // PlotOrientation.VERTICAL r[2] = new Rectangle2D.Double(Math.min(xxmin, xx), Math.min(yymin, yy), Math.abs(xx - xxmin), Math.abs(yy - yymin)); } somethingToDraw = true; } } if (this.quadrantPaint[3] != null) { if (x < xmax && y > ymin) { if (this.orientation == PlotOrientation.HORIZONTAL) { r[3] = new Rectangle2D.Double(Math.min(yymin, yy), Math.min(xxmax, xx), Math.abs(yy - yymin), Math.abs(xx - xxmax)); } else { // PlotOrientation.VERTICAL r[3] = new Rectangle2D.Double(Math.min(xx, xxmax), Math.min(yymin, yy), Math.abs(xx - xxmax), Math.abs(yy - yymin)); } somethingToDraw = true; } } if (somethingToDraw) { Composite originalComposite = g2.getComposite(); g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getBackgroundAlpha())); for (int i = 0; i < 4; i++) { if (this.quadrantPaint[i] != null && r[i] != null) { g2.setPaint(this.quadrantPaint[i]); g2.fill(r[i]); } } g2.setComposite(originalComposite); } } /** * Draws the domain tick bands, if any. * * @param g2 the graphics device. * @param dataArea the data area. * @param ticks the ticks. * * @see #setDomainTickBandPaint(Paint) */ public void drawDomainTickBands(Graphics2D g2, Rectangle2D dataArea, List ticks) { Paint bandPaint = getDomainTickBandPaint(); if (bandPaint != null) { boolean fillBand = false; ValueAxis xAxis = getDomainAxis(); double previous = xAxis.getLowerBound(); Iterator iterator = ticks.iterator(); while (iterator.hasNext()) { ValueTick tick = (ValueTick) iterator.next(); double current = tick.getValue(); if (fillBand) { getRenderer().fillDomainGridBand(g2, this, xAxis, dataArea, previous, current); } previous = current; fillBand = !fillBand; } double end = xAxis.getUpperBound(); if (fillBand) { getRenderer().fillDomainGridBand(g2, this, xAxis, dataArea, previous, end); } } } /** * Draws the range tick bands, if any. * * @param g2 the graphics device. * @param dataArea the data area. * @param ticks the ticks. * * @see #setRangeTickBandPaint(Paint) */ public void drawRangeTickBands(Graphics2D g2, Rectangle2D dataArea, List ticks) { Paint bandPaint = getRangeTickBandPaint(); if (bandPaint != null) { boolean fillBand = false; ValueAxis axis = getRangeAxis(); double previous = axis.getLowerBound(); Iterator iterator = ticks.iterator(); while (iterator.hasNext()) { ValueTick tick = (ValueTick) iterator.next(); double current = tick.getValue(); if (fillBand) { getRenderer().fillRangeGridBand(g2, this, axis, dataArea, previous, current); } previous = current; fillBand = !fillBand; } double end = axis.getUpperBound(); if (fillBand) { getRenderer().fillRangeGridBand(g2, this, axis, dataArea, previous, end); } } } /** * A utility method for drawing the axes. * * @param g2 the graphics device ({@code null} not permitted). * @param plotArea the plot area ({@code null} not permitted). * @param dataArea the data area ({@code null} not permitted). * @param plotState collects information about the plot ({@code null} * permitted). * * @return A map containing the state for each axis drawn. */ protected Map<Axis, AxisState> drawAxes(Graphics2D g2, Rectangle2D plotArea, Rectangle2D dataArea, PlotRenderingInfo plotState) { AxisCollection axisCollection = new AxisCollection(); // add domain axes to lists... for (ValueAxis axis : this.domainAxes.values()) { if (axis != null) { int axisIndex = findDomainAxisIndex(axis); axisCollection.add(axis, getDomainAxisEdge(axisIndex)); } } // add range axes to lists... for (ValueAxis axis : this.rangeAxes.values()) { if (axis != null) { int axisIndex = findRangeAxisIndex(axis); axisCollection.add(axis, getRangeAxisEdge(axisIndex)); } } Map axisStateMap = new HashMap(); // draw the top axes double cursor = dataArea.getMinY() - this.axisOffset.calculateTopOutset( dataArea.getHeight()); Iterator iterator = axisCollection.getAxesAtTop().iterator(); while (iterator.hasNext()) { ValueAxis axis = (ValueAxis) iterator.next(); AxisState info = axis.draw(g2, cursor, plotArea, dataArea, RectangleEdge.TOP, plotState); cursor = info.getCursor(); axisStateMap.put(axis, info); } // draw the bottom axes cursor = dataArea.getMaxY() + this.axisOffset.calculateBottomOutset(dataArea.getHeight()); iterator = axisCollection.getAxesAtBottom().iterator(); while (iterator.hasNext()) { ValueAxis axis = (ValueAxis) iterator.next(); AxisState info = axis.draw(g2, cursor, plotArea, dataArea, RectangleEdge.BOTTOM, plotState); cursor = info.getCursor(); axisStateMap.put(axis, info); } // draw the left axes cursor = dataArea.getMinX() - this.axisOffset.calculateLeftOutset(dataArea.getWidth()); iterator = axisCollection.getAxesAtLeft().iterator(); while (iterator.hasNext()) { ValueAxis axis = (ValueAxis) iterator.next(); AxisState info = axis.draw(g2, cursor, plotArea, dataArea, RectangleEdge.LEFT, plotState); cursor = info.getCursor(); axisStateMap.put(axis, info); } // draw the right axes cursor = dataArea.getMaxX() + this.axisOffset.calculateRightOutset(dataArea.getWidth()); iterator = axisCollection.getAxesAtRight().iterator(); while (iterator.hasNext()) { ValueAxis axis = (ValueAxis) iterator.next(); AxisState info = axis.draw(g2, cursor, plotArea, dataArea, RectangleEdge.RIGHT, plotState); cursor = info.getCursor(); axisStateMap.put(axis, info); } return axisStateMap; } /** * Draws a representation of the data within the dataArea region, using the * current renderer. * <P> * The {@code info} and {@code crosshairState} arguments may be * {@code null}. * * @param g2 the graphics device. * @param dataArea the region in which the data is to be drawn. * @param index the dataset index. * @param info an optional object for collection dimension information. * @param crosshairState collects crosshair information * ({@code null} permitted). * * @return A flag that indicates whether any data was actually rendered. */ public boolean render(Graphics2D g2, Rectangle2D dataArea, int index, PlotRenderingInfo info, CrosshairState crosshairState) { boolean foundData = false; XYDataset dataset = getDataset(index); if (!DatasetUtilities.isEmptyOrNull(dataset)) { foundData = true; ValueAxis xAxis = getDomainAxisForDataset(index); ValueAxis yAxis = getRangeAxisForDataset(index); if (xAxis == null || yAxis == null) { return foundData; // can't render anything without axes } XYItemRenderer renderer = getRenderer(index); if (renderer == null) { renderer = getRenderer(); if (renderer == null) { // no default renderer available return foundData; } } XYItemRendererState state = renderer.initialise(g2, dataArea, this, dataset, info); int passCount = renderer.getPassCount(); SeriesRenderingOrder seriesOrder = getSeriesRenderingOrder(); if (seriesOrder == SeriesRenderingOrder.REVERSE) { //render series in reverse order for (int pass = 0; pass < passCount; pass++) { int seriesCount = dataset.getSeriesCount(); for (int series = seriesCount - 1; series >= 0; series int firstItem = 0; int lastItem = dataset.getItemCount(series) - 1; if (lastItem == -1) { continue; } if (state.getProcessVisibleItemsOnly()) { int[] itemBounds = RendererUtilities.findLiveItems( dataset, series, xAxis.getLowerBound(), xAxis.getUpperBound()); firstItem = Math.max(itemBounds[0] - 1, 0); lastItem = Math.min(itemBounds[1] + 1, lastItem); } state.startSeriesPass(dataset, series, firstItem, lastItem, pass, passCount); for (int item = firstItem; item <= lastItem; item++) { renderer.drawItem(g2, state, dataArea, info, this, xAxis, yAxis, dataset, series, item, crosshairState, pass); } state.endSeriesPass(dataset, series, firstItem, lastItem, pass, passCount); } } } else { //render series in forward order for (int pass = 0; pass < passCount; pass++) { int seriesCount = dataset.getSeriesCount(); for (int series = 0; series < seriesCount; series++) { int firstItem = 0; int lastItem = dataset.getItemCount(series) - 1; if (state.getProcessVisibleItemsOnly()) { int[] itemBounds = RendererUtilities.findLiveItems( dataset, series, xAxis.getLowerBound(), xAxis.getUpperBound()); firstItem = Math.max(itemBounds[0] - 1, 0); lastItem = Math.min(itemBounds[1] + 1, lastItem); } state.startSeriesPass(dataset, series, firstItem, lastItem, pass, passCount); for (int item = firstItem; item <= lastItem; item++) { renderer.drawItem(g2, state, dataArea, info, this, xAxis, yAxis, dataset, series, item, crosshairState, pass); } state.endSeriesPass(dataset, series, firstItem, lastItem, pass, passCount); } } } } return foundData; } /** * Returns the domain axis for a dataset. * * @param index the dataset index (must be &gt;= 0). * * @return The axis. */ public ValueAxis getDomainAxisForDataset(int index) { ParamChecks.requireNonNegative(index, "index"); ValueAxis valueAxis; List axisIndices = (List) this.datasetToDomainAxesMap.get( new Integer(index)); if (axisIndices != null) { // the first axis in the list is used for data <--> Java2D Integer axisIndex = (Integer) axisIndices.get(0); valueAxis = getDomainAxis(axisIndex.intValue()); } else { valueAxis = getDomainAxis(0); } return valueAxis; } /** * Returns the range axis for a dataset. * * @param index the dataset index (must be &gt;= 0). * * @return The axis. */ public ValueAxis getRangeAxisForDataset(int index) { ParamChecks.requireNonNegative(index, "index"); ValueAxis valueAxis; List axisIndices = (List) this.datasetToRangeAxesMap.get( new Integer(index)); if (axisIndices != null) { // the first axis in the list is used for data <--> Java2D Integer axisIndex = (Integer) axisIndices.get(0); valueAxis = getRangeAxis(axisIndex.intValue()); } else { valueAxis = getRangeAxis(0); } return valueAxis; } /** * Draws the gridlines for the plot, if they are visible. * * @param g2 the graphics device. * @param dataArea the data area. * @param ticks the ticks. * * @see #drawRangeGridlines(Graphics2D, Rectangle2D, List) */ protected void drawDomainGridlines(Graphics2D g2, Rectangle2D dataArea, List ticks) { // no renderer, no gridlines... if (getRenderer() == null) { return; } // draw the domain grid lines, if any... if (isDomainGridlinesVisible() || isDomainMinorGridlinesVisible()) { Stroke gridStroke = null; Paint gridPaint = null; Iterator iterator = ticks.iterator(); boolean paintLine; while (iterator.hasNext()) { paintLine = false; ValueTick tick = (ValueTick) iterator.next(); if ((tick.getTickType() == TickType.MINOR) && isDomainMinorGridlinesVisible()) { gridStroke = getDomainMinorGridlineStroke(); gridPaint = getDomainMinorGridlinePaint(); paintLine = true; } else if ((tick.getTickType() == TickType.MAJOR) && isDomainGridlinesVisible()) { gridStroke = getDomainGridlineStroke(); gridPaint = getDomainGridlinePaint(); paintLine = true; } XYItemRenderer r = getRenderer(); if ((r instanceof AbstractXYItemRenderer) && paintLine) { ((AbstractXYItemRenderer) r).drawDomainLine(g2, this, getDomainAxis(), dataArea, tick.getValue(), gridPaint, gridStroke); } } } } /** * Draws the gridlines for the plot's primary range axis, if they are * visible. * * @param g2 the graphics device. * @param area the data area. * @param ticks the ticks. * * @see #drawDomainGridlines(Graphics2D, Rectangle2D, List) */ protected void drawRangeGridlines(Graphics2D g2, Rectangle2D area, List ticks) { // no renderer, no gridlines... if (getRenderer() == null) { return; } // draw the range grid lines, if any... if (isRangeGridlinesVisible() || isRangeMinorGridlinesVisible()) { Stroke gridStroke = null; Paint gridPaint = null; ValueAxis axis = getRangeAxis(); if (axis != null) { Iterator iterator = ticks.iterator(); boolean paintLine; while (iterator.hasNext()) { paintLine = false; ValueTick tick = (ValueTick) iterator.next(); if ((tick.getTickType() == TickType.MINOR) && isRangeMinorGridlinesVisible()) { gridStroke = getRangeMinorGridlineStroke(); gridPaint = getRangeMinorGridlinePaint(); paintLine = true; } else if ((tick.getTickType() == TickType.MAJOR) && isRangeGridlinesVisible()) { gridStroke = getRangeGridlineStroke(); gridPaint = getRangeGridlinePaint(); paintLine = true; } if ((tick.getValue() != 0.0 || !isRangeZeroBaselineVisible()) && paintLine) { getRenderer().drawRangeLine(g2, this, getRangeAxis(), area, tick.getValue(), gridPaint, gridStroke); } } } } } /** * Draws a base line across the chart at value zero on the domain axis. * * @param g2 the graphics device. * @param area the data area. * * @see #setDomainZeroBaselineVisible(boolean) * * @since 1.0.5 */ protected void drawZeroDomainBaseline(Graphics2D g2, Rectangle2D area) { if (isDomainZeroBaselineVisible()) { XYItemRenderer r = getRenderer(); // FIXME: the renderer interface doesn't have the drawDomainLine() // method, so we have to rely on the renderer being a subclass of // AbstractXYItemRenderer (which is lame) if (r instanceof AbstractXYItemRenderer) { AbstractXYItemRenderer renderer = (AbstractXYItemRenderer) r; renderer.drawDomainLine(g2, this, getDomainAxis(), area, 0.0, this.domainZeroBaselinePaint, this.domainZeroBaselineStroke); } } } /** * Draws a base line across the chart at value zero on the range axis. * * @param g2 the graphics device. * @param area the data area. * * @see #setRangeZeroBaselineVisible(boolean) */ protected void drawZeroRangeBaseline(Graphics2D g2, Rectangle2D area) { if (isRangeZeroBaselineVisible()) { getRenderer().drawRangeLine(g2, this, getRangeAxis(), area, 0.0, this.rangeZeroBaselinePaint, this.rangeZeroBaselineStroke); } } /** * Draws the annotations for the plot. * * @param g2 the graphics device. * @param dataArea the data area. * @param info the chart rendering info. */ public void drawAnnotations(Graphics2D g2, Rectangle2D dataArea, PlotRenderingInfo info) { Iterator iterator = this.annotations.iterator(); while (iterator.hasNext()) { XYAnnotation annotation = (XYAnnotation) iterator.next(); ValueAxis xAxis = getDomainAxis(); ValueAxis yAxis = getRangeAxis(); annotation.draw(g2, this, dataArea, xAxis, yAxis, 0, info); } } /** * Draws the domain markers (if any) for an axis and layer. This method is * typically called from within the draw() method. * * @param g2 the graphics device. * @param dataArea the data area. * @param index the dataset/renderer index. * @param layer the layer (foreground or background). */ protected void drawDomainMarkers(Graphics2D g2, Rectangle2D dataArea, int index, Layer layer) { XYItemRenderer r = getRenderer(index); if (r == null) { return; } // check that the renderer has a corresponding dataset (it doesn't // matter if the dataset is null) if (index >= getDatasetCount()) { return; } Collection markers = getDomainMarkers(index, layer); ValueAxis axis = getDomainAxisForDataset(index); if (markers != null && axis != null) { Iterator iterator = markers.iterator(); while (iterator.hasNext()) { Marker marker = (Marker) iterator.next(); r.drawDomainMarker(g2, this, axis, marker, dataArea); } } } /** * Draws the range markers (if any) for a renderer and layer. This method * is typically called from within the draw() method. * * @param g2 the graphics device. * @param dataArea the data area. * @param index the renderer index. * @param layer the layer (foreground or background). */ protected void drawRangeMarkers(Graphics2D g2, Rectangle2D dataArea, int index, Layer layer) { XYItemRenderer r = getRenderer(index); if (r == null) { return; } // check that the renderer has a corresponding dataset (it doesn't // matter if the dataset is null) if (index >= getDatasetCount()) { return; } Collection markers = getRangeMarkers(index, layer); ValueAxis axis = getRangeAxisForDataset(index); if (markers != null && axis != null) { Iterator iterator = markers.iterator(); while (iterator.hasNext()) { Marker marker = (Marker) iterator.next(); r.drawRangeMarker(g2, this, axis, marker, dataArea); } } } /** * Returns the list of domain markers (read only) for the specified layer. * * @param layer the layer (foreground or background). * * @return The list of domain markers. * * @see #getRangeMarkers(Layer) */ public Collection getDomainMarkers(Layer layer) { return getDomainMarkers(0, layer); } /** * Returns the list of range markers (read only) for the specified layer. * * @param layer the layer (foreground or background). * * @return The list of range markers. * * @see #getDomainMarkers(Layer) */ public Collection getRangeMarkers(Layer layer) { return getRangeMarkers(0, layer); } /** * Returns a collection of domain markers for a particular renderer and * layer. * * @param index the renderer index. * @param layer the layer. * * @return A collection of markers (possibly {@code null}). * * @see #getRangeMarkers(int, Layer) */ public Collection getDomainMarkers(int index, Layer layer) { Collection result = null; Integer key = new Integer(index); if (layer == Layer.FOREGROUND) { result = (Collection) this.foregroundDomainMarkers.get(key); } else if (layer == Layer.BACKGROUND) { result = (Collection) this.backgroundDomainMarkers.get(key); } if (result != null) { result = Collections.unmodifiableCollection(result); } return result; } /** * Returns a collection of range markers for a particular renderer and * layer. * * @param index the renderer index. * @param layer the layer. * * @return A collection of markers (possibly {@code null}). * * @see #getDomainMarkers(int, Layer) */ public Collection getRangeMarkers(int index, Layer layer) { Collection result = null; Integer key = new Integer(index); if (layer == Layer.FOREGROUND) { result = (Collection) this.foregroundRangeMarkers.get(key); } else if (layer == Layer.BACKGROUND) { result = (Collection) this.backgroundRangeMarkers.get(key); } if (result != null) { result = Collections.unmodifiableCollection(result); } return result; } /** * Utility method for drawing a horizontal line across the data area of the * plot. * * @param g2 the graphics device. * @param dataArea the data area. * @param value the coordinate, where to draw the line. * @param stroke the stroke to use. * @param paint the paint to use. */ protected void drawHorizontalLine(Graphics2D g2, Rectangle2D dataArea, double value, Stroke stroke, Paint paint) { ValueAxis axis = getRangeAxis(); if (getOrientation() == PlotOrientation.HORIZONTAL) { axis = getDomainAxis(); } if (axis.getRange().contains(value)) { double yy = axis.valueToJava2D(value, dataArea, RectangleEdge.LEFT); Line2D line = new Line2D.Double(dataArea.getMinX(), yy, dataArea.getMaxX(), yy); g2.setStroke(stroke); g2.setPaint(paint); g2.draw(line); } } /** * Draws a domain crosshair. * * @param g2 the graphics target. * @param dataArea the data area. * @param orientation the plot orientation. * @param value the crosshair value. * @param axis the axis against which the value is measured. * @param stroke the stroke used to draw the crosshair line. * @param paint the paint used to draw the crosshair line. * * @since 1.0.4 */ protected void drawDomainCrosshair(Graphics2D g2, Rectangle2D dataArea, PlotOrientation orientation, double value, ValueAxis axis, Stroke stroke, Paint paint) { if (!axis.getRange().contains(value)) { return; } Line2D line; if (orientation == PlotOrientation.VERTICAL) { double xx = axis.valueToJava2D(value, dataArea, RectangleEdge.BOTTOM); line = new Line2D.Double(xx, dataArea.getMinY(), xx, dataArea.getMaxY()); } else { double yy = axis.valueToJava2D(value, dataArea, RectangleEdge.LEFT); line = new Line2D.Double(dataArea.getMinX(), yy, dataArea.getMaxX(), yy); } Object saved = g2.getRenderingHint(RenderingHints.KEY_STROKE_CONTROL); g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE); g2.setStroke(stroke); g2.setPaint(paint); g2.draw(line); g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, saved); } /** * Utility method for drawing a vertical line on the data area of the plot. * * @param g2 the graphics device. * @param dataArea the data area. * @param value the coordinate, where to draw the line. * @param stroke the stroke to use. * @param paint the paint to use. */ protected void drawVerticalLine(Graphics2D g2, Rectangle2D dataArea, double value, Stroke stroke, Paint paint) { ValueAxis axis = getDomainAxis(); if (getOrientation() == PlotOrientation.HORIZONTAL) { axis = getRangeAxis(); } if (axis.getRange().contains(value)) { double xx = axis.valueToJava2D(value, dataArea, RectangleEdge.BOTTOM); Line2D line = new Line2D.Double(xx, dataArea.getMinY(), xx, dataArea.getMaxY()); g2.setStroke(stroke); g2.setPaint(paint); g2.draw(line); } } /** * Draws a range crosshair. * * @param g2 the graphics target. * @param dataArea the data area. * @param orientation the plot orientation. * @param value the crosshair value. * @param axis the axis against which the value is measured. * @param stroke the stroke used to draw the crosshair line. * @param paint the paint used to draw the crosshair line. * * @since 1.0.4 */ protected void drawRangeCrosshair(Graphics2D g2, Rectangle2D dataArea, PlotOrientation orientation, double value, ValueAxis axis, Stroke stroke, Paint paint) { if (!axis.getRange().contains(value)) { return; } Object saved = g2.getRenderingHint(RenderingHints.KEY_STROKE_CONTROL); g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE); Line2D line; if (orientation == PlotOrientation.HORIZONTAL) { double xx = axis.valueToJava2D(value, dataArea, RectangleEdge.BOTTOM); line = new Line2D.Double(xx, dataArea.getMinY(), xx, dataArea.getMaxY()); } else { double yy = axis.valueToJava2D(value, dataArea, RectangleEdge.LEFT); line = new Line2D.Double(dataArea.getMinX(), yy, dataArea.getMaxX(), yy); } g2.setStroke(stroke); g2.setPaint(paint); g2.draw(line); g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, saved); } /** * Handles a 'click' on the plot by updating the anchor values. * * @param x the x-coordinate, where the click occurred, in Java2D space. * @param y the y-coordinate, where the click occurred, in Java2D space. * @param info object containing information about the plot dimensions. */ @Override public void handleClick(int x, int y, PlotRenderingInfo info) { Rectangle2D dataArea = info.getDataArea(); if (dataArea.contains(x, y)) { // set the anchor value for the horizontal axis... ValueAxis xaxis = getDomainAxis(); if (xaxis != null) { double hvalue = xaxis.java2DToValue(x, info.getDataArea(), getDomainAxisEdge()); setDomainCrosshairValue(hvalue); } // set the anchor value for the vertical axis... ValueAxis yaxis = getRangeAxis(); if (yaxis != null) { double vvalue = yaxis.java2DToValue(y, info.getDataArea(), getRangeAxisEdge()); setRangeCrosshairValue(vvalue); } } } /** * A utility method that returns a list of datasets that are mapped to a * particular axis. * * @param axisIndex the axis index ({@code null} not permitted). * * @return A list of datasets. */ private List<XYDataset> getDatasetsMappedToDomainAxis(Integer axisIndex) { ParamChecks.nullNotPermitted(axisIndex, "axisIndex"); List<XYDataset> result = new ArrayList<XYDataset>(); for (Entry<Integer, XYDataset> entry : this.datasets.entrySet()) { int index = entry.getKey(); List<Integer> mappedAxes = this.datasetToDomainAxesMap.get(index); if (mappedAxes == null) { if (axisIndex.equals(ZERO)) { result.add(entry.getValue()); } } else { if (mappedAxes.contains(axisIndex)) { result.add(entry.getValue()); } } } return result; } /** * A utility method that returns a list of datasets that are mapped to a * particular axis. * * @param axisIndex the axis index ({@code null} not permitted). * * @return A list of datasets. */ private List<XYDataset> getDatasetsMappedToRangeAxis(Integer axisIndex) { ParamChecks.nullNotPermitted(axisIndex, "axisIndex"); List<XYDataset> result = new ArrayList<XYDataset>(); for (Entry<Integer, XYDataset> entry : this.datasets.entrySet()) { int index = entry.getKey(); List<Integer> mappedAxes = this.datasetToRangeAxesMap.get(index); if (mappedAxes == null) { if (axisIndex.equals(ZERO)) { result.add(entry.getValue()); } } else { if (mappedAxes.contains(axisIndex)) { result.add(entry.getValue()); } } } return result; } /** * Returns the index of the given domain axis. * * @param axis the axis. * * @return The axis index. * * @see #getRangeAxisIndex(ValueAxis) */ public int getDomainAxisIndex(ValueAxis axis) { int result = findDomainAxisIndex(axis); if (result < 0) { // try the parent plot Plot parent = getParent(); if (parent instanceof XYPlot) { XYPlot p = (XYPlot) parent; result = p.getDomainAxisIndex(axis); } } return result; } private int findDomainAxisIndex(ValueAxis axis) { for (Map.Entry<Integer, ValueAxis> entry : this.domainAxes.entrySet()) { if (entry.getValue() == axis) { return entry.getKey(); } } return -1; } /** * Returns the index of the given range axis. * * @param axis the axis. * * @return The axis index. * * @see #getDomainAxisIndex(ValueAxis) */ public int getRangeAxisIndex(ValueAxis axis) { int result = findRangeAxisIndex(axis); if (result < 0) { // try the parent plot Plot parent = getParent(); if (parent instanceof XYPlot) { XYPlot p = (XYPlot) parent; result = p.getRangeAxisIndex(axis); } } return result; } private int findRangeAxisIndex(ValueAxis axis) { for (Map.Entry<Integer, ValueAxis> entry : this.rangeAxes.entrySet()) { if (entry.getValue() == axis) { return entry.getKey(); } } return -1; } /** * Returns the range for the specified axis. * * @param axis the axis. * * @return The range. */ @Override public Range getDataRange(ValueAxis axis) { Range result = null; List<XYDataset> mappedDatasets = new ArrayList<XYDataset>(); List<XYAnnotation> includedAnnotations = new ArrayList<XYAnnotation>(); boolean isDomainAxis = true; // is it a domain axis? int domainIndex = getDomainAxisIndex(axis); if (domainIndex >= 0) { isDomainAxis = true; mappedDatasets.addAll(getDatasetsMappedToDomainAxis(domainIndex)); if (domainIndex == 0) { // grab the plot's annotations Iterator iterator = this.annotations.iterator(); while (iterator.hasNext()) { XYAnnotation annotation = (XYAnnotation) iterator.next(); if (annotation instanceof XYAnnotationBoundsInfo) { includedAnnotations.add(annotation); } } } } // or is it a range axis? int rangeIndex = getRangeAxisIndex(axis); if (rangeIndex >= 0) { isDomainAxis = false; mappedDatasets.addAll(getDatasetsMappedToRangeAxis(rangeIndex)); if (rangeIndex == 0) { Iterator iterator = this.annotations.iterator(); while (iterator.hasNext()) { XYAnnotation annotation = (XYAnnotation) iterator.next(); if (annotation instanceof XYAnnotationBoundsInfo) { includedAnnotations.add(annotation); } } } } // iterate through the datasets that map to the axis and get the union // of the ranges. for (XYDataset d : mappedDatasets) { if (d != null) { XYItemRenderer r = getRendererForDataset(d); if (isDomainAxis) { if (r != null) { result = Range.combine(result, r.findDomainBounds(d)); } else { result = Range.combine(result, DatasetUtilities.findDomainBounds(d)); } } else { if (r != null) { result = Range.combine(result, r.findRangeBounds(d)); } else { result = Range.combine(result, DatasetUtilities.findRangeBounds(d)); } } // FIXME: the XYItemRenderer interface doesn't specify the // getAnnotations() method but it should if (r instanceof AbstractXYItemRenderer) { AbstractXYItemRenderer rr = (AbstractXYItemRenderer) r; Collection c = rr.getAnnotations(); Iterator i = c.iterator(); while (i.hasNext()) { XYAnnotation a = (XYAnnotation) i.next(); if (a instanceof XYAnnotationBoundsInfo) { includedAnnotations.add(a); } } } } } Iterator it = includedAnnotations.iterator(); while (it.hasNext()) { XYAnnotationBoundsInfo xyabi = (XYAnnotationBoundsInfo) it.next(); if (xyabi.getIncludeInDataBounds()) { if (isDomainAxis) { result = Range.combine(result, xyabi.getXRange()); } else { result = Range.combine(result, xyabi.getYRange()); } } } return result; } /** * Receives notification of a change to an {@link Annotation} added to * this plot. * * @param event information about the event (not used here). * * @since 1.0.14 */ @Override public void annotationChanged(AnnotationChangeEvent event) { if (getParent() != null) { getParent().annotationChanged(event); } else { PlotChangeEvent e = new PlotChangeEvent(this); notifyListeners(e); } } /** * Receives notification of a change to the plot's dataset. * <P> * The axis ranges are updated if necessary. * * @param event information about the event (not used here). */ @Override public void datasetChanged(DatasetChangeEvent event) { configureDomainAxes(); configureRangeAxes(); if (getParent() != null) { getParent().datasetChanged(event); } else { PlotChangeEvent e = new PlotChangeEvent(this); e.setType(ChartChangeEventType.DATASET_UPDATED); notifyListeners(e); } } /** * Receives notification of a renderer change event. * * @param event the event. */ @Override public void rendererChanged(RendererChangeEvent event) { // if the event was caused by a change to series visibility, then // the axis ranges might need updating... if (event.getSeriesVisibilityChanged()) { configureDomainAxes(); configureRangeAxes(); } fireChangeEvent(); } /** * Returns a flag indicating whether or not the domain crosshair is visible. * * @return The flag. * * @see #setDomainCrosshairVisible(boolean) */ public boolean isDomainCrosshairVisible() { return this.domainCrosshairVisible; } /** * Sets the flag indicating whether or not the domain crosshair is visible * and, if the flag changes, sends a {@link PlotChangeEvent} to all * registered listeners. * * @param flag the new value of the flag. * * @see #isDomainCrosshairVisible() */ public void setDomainCrosshairVisible(boolean flag) { if (this.domainCrosshairVisible != flag) { this.domainCrosshairVisible = flag; fireChangeEvent(); } } /** * Returns a flag indicating whether or not the crosshair should "lock-on" * to actual data values. * * @return The flag. * * @see #setDomainCrosshairLockedOnData(boolean) */ public boolean isDomainCrosshairLockedOnData() { return this.domainCrosshairLockedOnData; } /** * Sets the flag indicating whether or not the domain crosshair should * "lock-on" to actual data values. If the flag value changes, this * method sends a {@link PlotChangeEvent} to all registered listeners. * * @param flag the flag. * * @see #isDomainCrosshairLockedOnData() */ public void setDomainCrosshairLockedOnData(boolean flag) { if (this.domainCrosshairLockedOnData != flag) { this.domainCrosshairLockedOnData = flag; fireChangeEvent(); } } /** * Returns the domain crosshair value. * * @return The value. * * @see #setDomainCrosshairValue(double) */ public double getDomainCrosshairValue() { return this.domainCrosshairValue; } /** * Sets the domain crosshair value and sends a {@link PlotChangeEvent} to * all registered listeners (provided that the domain crosshair is visible). * * @param value the value. * * @see #getDomainCrosshairValue() */ public void setDomainCrosshairValue(double value) { setDomainCrosshairValue(value, true); } /** * Sets the domain crosshair value and, if requested, sends a * {@link PlotChangeEvent} to all registered listeners (provided that the * domain crosshair is visible). * * @param value the new value. * @param notify notify listeners? * * @see #getDomainCrosshairValue() */ public void setDomainCrosshairValue(double value, boolean notify) { this.domainCrosshairValue = value; if (isDomainCrosshairVisible() && notify) { fireChangeEvent(); } } /** * Returns the {@link Stroke} used to draw the crosshair (if visible). * * @return The crosshair stroke (never {@code null}). * * @see #setDomainCrosshairStroke(Stroke) * @see #isDomainCrosshairVisible() * @see #getDomainCrosshairPaint() */ public Stroke getDomainCrosshairStroke() { return this.domainCrosshairStroke; } /** * Sets the Stroke used to draw the crosshairs (if visible) and notifies * registered listeners that the axis has been modified. * * @param stroke the new crosshair stroke ({@code null} not * permitted). * * @see #getDomainCrosshairStroke() */ public void setDomainCrosshairStroke(Stroke stroke) { ParamChecks.nullNotPermitted(stroke, "stroke"); this.domainCrosshairStroke = stroke; fireChangeEvent(); } /** * Returns the domain crosshair paint. * * @return The crosshair paint (never {@code null}). * * @see #setDomainCrosshairPaint(Paint) * @see #isDomainCrosshairVisible() * @see #getDomainCrosshairStroke() */ public Paint getDomainCrosshairPaint() { return this.domainCrosshairPaint; } /** * Sets the paint used to draw the crosshairs (if visible) and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param paint the new crosshair paint ({@code null} not permitted). * * @see #getDomainCrosshairPaint() */ public void setDomainCrosshairPaint(Paint paint) { ParamChecks.nullNotPermitted(paint, "paint"); this.domainCrosshairPaint = paint; fireChangeEvent(); } /** * Returns a flag indicating whether or not the range crosshair is visible. * * @return The flag. * * @see #setRangeCrosshairVisible(boolean) * @see #isDomainCrosshairVisible() */ public boolean isRangeCrosshairVisible() { return this.rangeCrosshairVisible; } /** * Sets the flag indicating whether or not the range crosshair is visible. * If the flag value changes, this method sends a {@link PlotChangeEvent} * to all registered listeners. * * @param flag the new value of the flag. * * @see #isRangeCrosshairVisible() */ public void setRangeCrosshairVisible(boolean flag) { if (this.rangeCrosshairVisible != flag) { this.rangeCrosshairVisible = flag; fireChangeEvent(); } } /** * Returns a flag indicating whether or not the crosshair should "lock-on" * to actual data values. * * @return The flag. * * @see #setRangeCrosshairLockedOnData(boolean) */ public boolean isRangeCrosshairLockedOnData() { return this.rangeCrosshairLockedOnData; } /** * Sets the flag indicating whether or not the range crosshair should * "lock-on" to actual data values. If the flag value changes, this method * sends a {@link PlotChangeEvent} to all registered listeners. * * @param flag the flag. * * @see #isRangeCrosshairLockedOnData() */ public void setRangeCrosshairLockedOnData(boolean flag) { if (this.rangeCrosshairLockedOnData != flag) { this.rangeCrosshairLockedOnData = flag; fireChangeEvent(); } } /** * Returns the range crosshair value. * * @return The value. * * @see #setRangeCrosshairValue(double) */ public double getRangeCrosshairValue() { return this.rangeCrosshairValue; } /** * Sets the range crosshair value. * <P> * Registered listeners are notified that the plot has been modified, but * only if the crosshair is visible. * * @param value the new value. * * @see #getRangeCrosshairValue() */ public void setRangeCrosshairValue(double value) { setRangeCrosshairValue(value, true); } /** * Sets the range crosshair value and sends a {@link PlotChangeEvent} to * all registered listeners, but only if the crosshair is visible. * * @param value the new value. * @param notify a flag that controls whether or not listeners are * notified. * * @see #getRangeCrosshairValue() */ public void setRangeCrosshairValue(double value, boolean notify) { this.rangeCrosshairValue = value; if (isRangeCrosshairVisible() && notify) { fireChangeEvent(); } } /** * Returns the stroke used to draw the crosshair (if visible). * * @return The crosshair stroke (never {@code null}). * * @see #setRangeCrosshairStroke(Stroke) * @see #isRangeCrosshairVisible() * @see #getRangeCrosshairPaint() */ public Stroke getRangeCrosshairStroke() { return this.rangeCrosshairStroke; } /** * Sets the stroke used to draw the crosshairs (if visible) and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param stroke the new crosshair stroke ({@code null} not * permitted). * * @see #getRangeCrosshairStroke() */ public void setRangeCrosshairStroke(Stroke stroke) { ParamChecks.nullNotPermitted(stroke, "stroke"); this.rangeCrosshairStroke = stroke; fireChangeEvent(); } /** * Returns the range crosshair paint. * * @return The crosshair paint (never {@code null}). * * @see #setRangeCrosshairPaint(Paint) * @see #isRangeCrosshairVisible() * @see #getRangeCrosshairStroke() */ public Paint getRangeCrosshairPaint() { return this.rangeCrosshairPaint; } /** * Sets the paint used to color the crosshairs (if visible) and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param paint the new crosshair paint ({@code null} not permitted). * * @see #getRangeCrosshairPaint() */ public void setRangeCrosshairPaint(Paint paint) { ParamChecks.nullNotPermitted(paint, "paint"); this.rangeCrosshairPaint = paint; fireChangeEvent(); } /** * Returns the fixed domain axis space. * * @return The fixed domain axis space (possibly {@code null}). * * @see #setFixedDomainAxisSpace(AxisSpace) */ public AxisSpace getFixedDomainAxisSpace() { return this.fixedDomainAxisSpace; } /** * Sets the fixed domain axis space and sends a {@link PlotChangeEvent} to * all registered listeners. * * @param space the space ({@code null} permitted). * * @see #getFixedDomainAxisSpace() */ public void setFixedDomainAxisSpace(AxisSpace space) { setFixedDomainAxisSpace(space, true); } /** * Sets the fixed domain axis space and, if requested, sends a * {@link PlotChangeEvent} to all registered listeners. * * @param space the space ({@code null} permitted). * @param notify notify listeners? * * @see #getFixedDomainAxisSpace() * * @since 1.0.9 */ public void setFixedDomainAxisSpace(AxisSpace space, boolean notify) { this.fixedDomainAxisSpace = space; if (notify) { fireChangeEvent(); } } /** * Returns the fixed range axis space. * * @return The fixed range axis space (possibly {@code null}). * * @see #setFixedRangeAxisSpace(AxisSpace) */ public AxisSpace getFixedRangeAxisSpace() { return this.fixedRangeAxisSpace; } /** * Sets the fixed range axis space and sends a {@link PlotChangeEvent} to * all registered listeners. * * @param space the space ({@code null} permitted). * * @see #getFixedRangeAxisSpace() */ public void setFixedRangeAxisSpace(AxisSpace space) { setFixedRangeAxisSpace(space, true); } /** * Sets the fixed range axis space and, if requested, sends a * {@link PlotChangeEvent} to all registered listeners. * * @param space the space ({@code null} permitted). * @param notify notify listeners? * * @see #getFixedRangeAxisSpace() * * @since 1.0.9 */ public void setFixedRangeAxisSpace(AxisSpace space, boolean notify) { this.fixedRangeAxisSpace = space; if (notify) { fireChangeEvent(); } } /** * Returns {@code true} if panning is enabled for the domain axes, * and {@code false} otherwise. * * @return A boolean. * * @since 1.0.13 */ @Override public boolean isDomainPannable() { return this.domainPannable; } /** * Sets the flag that enables or disables panning of the plot along the * domain axes. * * @param pannable the new flag value. * * @since 1.0.13 */ public void setDomainPannable(boolean pannable) { this.domainPannable = pannable; } /** * Returns {@code true} if panning is enabled for the range axis/axes, * and {@code false} otherwise. The default value is {@code false}. * * @return A boolean. * * @since 1.0.13 */ @Override public boolean isRangePannable() { return this.rangePannable; } /** * Sets the flag that enables or disables panning of the plot along * the range axis/axes. * * @param pannable the new flag value. * * @since 1.0.13 */ public void setRangePannable(boolean pannable) { this.rangePannable = pannable; } /** * Pans the domain axes by the specified percentage. * * @param percent the distance to pan (as a percentage of the axis length). * @param info the plot info * @param source the source point where the pan action started. * * @since 1.0.13 */ @Override public void panDomainAxes(double percent, PlotRenderingInfo info, Point2D source) { if (!isDomainPannable()) { return; } int domainAxisCount = getDomainAxisCount(); for (int i = 0; i < domainAxisCount; i++) { ValueAxis axis = getDomainAxis(i); if (axis == null) { continue; } axis.pan(axis.isInverted() ? -percent : percent); } } /** * Pans the range axes by the specified percentage. * * @param percent the distance to pan (as a percentage of the axis length). * @param info the plot info * @param source the source point where the pan action started. * * @since 1.0.13 */ @Override public void panRangeAxes(double percent, PlotRenderingInfo info, Point2D source) { if (!isRangePannable()) { return; } int rangeAxisCount = getRangeAxisCount(); for (int i = 0; i < rangeAxisCount; i++) { ValueAxis axis = getRangeAxis(i); if (axis == null) { continue; } axis.pan(axis.isInverted() ? -percent : percent); } } /** * Multiplies the range on the domain axis/axes by the specified factor. * * @param factor the zoom factor. * @param info the plot rendering info. * @param source the source point (in Java2D space). * * @see #zoomRangeAxes(double, PlotRenderingInfo, Point2D) */ @Override public void zoomDomainAxes(double factor, PlotRenderingInfo info, Point2D source) { // delegate to other method zoomDomainAxes(factor, info, source, false); } /** * Multiplies the range on the domain axis/axes by the specified factor. * * @param factor the zoom factor. * @param info the plot rendering info. * @param source the source point (in Java2D space). * @param useAnchor use source point as zoom anchor? * * @see #zoomRangeAxes(double, PlotRenderingInfo, Point2D, boolean) * * @since 1.0.7 */ @Override public void zoomDomainAxes(double factor, PlotRenderingInfo info, Point2D source, boolean useAnchor) { // perform the zoom on each domain axis for (ValueAxis xAxis : this.domainAxes.values()) { if (xAxis == null) { continue; } if (useAnchor) { // get the relevant source coordinate given the plot orientation double sourceX = source.getX(); if (this.orientation == PlotOrientation.HORIZONTAL) { sourceX = source.getY(); } double anchorX = xAxis.java2DToValue(sourceX, info.getDataArea(), getDomainAxisEdge()); xAxis.resizeRange2(factor, anchorX); } else { xAxis.resizeRange(factor); } } } /** * Zooms in on the domain axis/axes. The new lower and upper bounds are * specified as percentages of the current axis range, where 0 percent is * the current lower bound and 100 percent is the current upper bound. * * @param lowerPercent a percentage that determines the new lower bound * for the axis (e.g. 0.20 is twenty percent). * @param upperPercent a percentage that determines the new upper bound * for the axis (e.g. 0.80 is eighty percent). * @param info the plot rendering info. * @param source the source point (ignored). * * @see #zoomRangeAxes(double, double, PlotRenderingInfo, Point2D) */ @Override public void zoomDomainAxes(double lowerPercent, double upperPercent, PlotRenderingInfo info, Point2D source) { for (ValueAxis xAxis : this.domainAxes.values()) { if (xAxis != null) { xAxis.zoomRange(lowerPercent, upperPercent); } } } /** * Multiplies the range on the range axis/axes by the specified factor. * * @param factor the zoom factor. * @param info the plot rendering info. * @param source the source point. * * @see #zoomDomainAxes(double, PlotRenderingInfo, Point2D, boolean) */ @Override public void zoomRangeAxes(double factor, PlotRenderingInfo info, Point2D source) { // delegate to other method zoomRangeAxes(factor, info, source, false); } /** * Multiplies the range on the range axis/axes by the specified factor. * * @param factor the zoom factor. * @param info the plot rendering info. * @param source the source point. * @param useAnchor a flag that controls whether or not the source point * is used for the zoom anchor. * * @see #zoomDomainAxes(double, PlotRenderingInfo, Point2D, boolean) * * @since 1.0.7 */ @Override public void zoomRangeAxes(double factor, PlotRenderingInfo info, Point2D source, boolean useAnchor) { // perform the zoom on each range axis for (ValueAxis yAxis : this.rangeAxes.values()) { if (yAxis == null) { continue; } if (useAnchor) { // get the relevant source coordinate given the plot orientation double sourceY = source.getY(); if (this.orientation == PlotOrientation.HORIZONTAL) { sourceY = source.getX(); } double anchorY = yAxis.java2DToValue(sourceY, info.getDataArea(), getRangeAxisEdge()); yAxis.resizeRange2(factor, anchorY); } else { yAxis.resizeRange(factor); } } } /** * Zooms in on the range axes. * * @param lowerPercent the lower bound. * @param upperPercent the upper bound. * @param info the plot rendering info. * @param source the source point. * * @see #zoomDomainAxes(double, double, PlotRenderingInfo, Point2D) */ @Override public void zoomRangeAxes(double lowerPercent, double upperPercent, PlotRenderingInfo info, Point2D source) { for (ValueAxis yAxis : this.rangeAxes.values()) { if (yAxis != null) { yAxis.zoomRange(lowerPercent, upperPercent); } } } /** * Returns {@code true}, indicating that the domain axis/axes for this * plot are zoomable. * * @return A boolean. * * @see #isRangeZoomable() */ @Override public boolean isDomainZoomable() { return true; } /** * Returns {@code true}, indicating that the range axis/axes for this * plot are zoomable. * * @return A boolean. * * @see #isDomainZoomable() */ @Override public boolean isRangeZoomable() { return true; } /** * Returns the number of series in the primary dataset for this plot. If * the dataset is {@code null}, the method returns 0. * * @return The series count. */ public int getSeriesCount() { int result = 0; XYDataset dataset = getDataset(); if (dataset != null) { result = dataset.getSeriesCount(); } return result; } /** * Returns the fixed legend items, if any. * * @return The legend items (possibly {@code null}). * * @see #setFixedLegendItems(LegendItemCollection) */ public LegendItemCollection getFixedLegendItems() { return this.fixedLegendItems; } /** * Sets the fixed legend items for the plot. Leave this set to * {@code null} if you prefer the legend items to be created * automatically. * * @param items the legend items ({@code null} permitted). * * @see #getFixedLegendItems() */ public void setFixedLegendItems(LegendItemCollection items) { this.fixedLegendItems = items; fireChangeEvent(); } /** * Returns the legend items for the plot. Each legend item is generated by * the plot's renderer, since the renderer is responsible for the visual * representation of the data. * * @return The legend items. */ @Override public LegendItemCollection getLegendItems() { if (this.fixedLegendItems != null) { return this.fixedLegendItems; } LegendItemCollection result = new LegendItemCollection(); for (XYDataset dataset : this.datasets.values()) { if (dataset == null) { continue; } int datasetIndex = indexOf(dataset); XYItemRenderer renderer = getRenderer(datasetIndex); if (renderer == null) { renderer = getRenderer(0); } if (renderer != null) { int seriesCount = dataset.getSeriesCount(); for (int i = 0; i < seriesCount; i++) { if (renderer.isSeriesVisible(i) && renderer.isSeriesVisibleInLegend(i)) { LegendItem item = renderer.getLegendItem( datasetIndex, i); if (item != null) { result.add(item); } } } } } return result; } /** * Tests this plot for equality with another object. * * @param obj the object ({@code null} permitted). * * @return {@code true} or {@code false}. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof XYPlot)) { return false; } XYPlot that = (XYPlot) obj; if (this.weight != that.weight) { return false; } if (this.orientation != that.orientation) { return false; } if (!this.domainAxes.equals(that.domainAxes)) { return false; } if (!this.domainAxisLocations.equals(that.domainAxisLocations)) { return false; } if (this.rangeCrosshairLockedOnData != that.rangeCrosshairLockedOnData) { return false; } if (this.domainGridlinesVisible != that.domainGridlinesVisible) { return false; } if (this.rangeGridlinesVisible != that.rangeGridlinesVisible) { return false; } if (this.domainMinorGridlinesVisible != that.domainMinorGridlinesVisible) { return false; } if (this.rangeMinorGridlinesVisible != that.rangeMinorGridlinesVisible) { return false; } if (this.domainZeroBaselineVisible != that.domainZeroBaselineVisible) { return false; } if (this.rangeZeroBaselineVisible != that.rangeZeroBaselineVisible) { return false; } if (this.domainCrosshairVisible != that.domainCrosshairVisible) { return false; } if (this.domainCrosshairValue != that.domainCrosshairValue) { return false; } if (this.domainCrosshairLockedOnData != that.domainCrosshairLockedOnData) { return false; } if (this.rangeCrosshairVisible != that.rangeCrosshairVisible) { return false; } if (this.rangeCrosshairValue != that.rangeCrosshairValue) { return false; } if (!ObjectUtilities.equal(this.axisOffset, that.axisOffset)) { return false; } if (!ObjectUtilities.equal(this.renderers, that.renderers)) { return false; } if (!ObjectUtilities.equal(this.rangeAxes, that.rangeAxes)) { return false; } if (!this.rangeAxisLocations.equals(that.rangeAxisLocations)) { return false; } if (!ObjectUtilities.equal(this.datasetToDomainAxesMap, that.datasetToDomainAxesMap)) { return false; } if (!ObjectUtilities.equal(this.datasetToRangeAxesMap, that.datasetToRangeAxesMap)) { return false; } if (!ObjectUtilities.equal(this.domainGridlineStroke, that.domainGridlineStroke)) { return false; } if (!PaintUtilities.equal(this.domainGridlinePaint, that.domainGridlinePaint)) { return false; } if (!ObjectUtilities.equal(this.rangeGridlineStroke, that.rangeGridlineStroke)) { return false; } if (!PaintUtilities.equal(this.rangeGridlinePaint, that.rangeGridlinePaint)) { return false; } if (!ObjectUtilities.equal(this.domainMinorGridlineStroke, that.domainMinorGridlineStroke)) { return false; } if (!PaintUtilities.equal(this.domainMinorGridlinePaint, that.domainMinorGridlinePaint)) { return false; } if (!ObjectUtilities.equal(this.rangeMinorGridlineStroke, that.rangeMinorGridlineStroke)) { return false; } if (!PaintUtilities.equal(this.rangeMinorGridlinePaint, that.rangeMinorGridlinePaint)) { return false; } if (!PaintUtilities.equal(this.domainZeroBaselinePaint, that.domainZeroBaselinePaint)) { return false; } if (!ObjectUtilities.equal(this.domainZeroBaselineStroke, that.domainZeroBaselineStroke)) { return false; } if (!PaintUtilities.equal(this.rangeZeroBaselinePaint, that.rangeZeroBaselinePaint)) { return false; } if (!ObjectUtilities.equal(this.rangeZeroBaselineStroke, that.rangeZeroBaselineStroke)) { return false; } if (!ObjectUtilities.equal(this.domainCrosshairStroke, that.domainCrosshairStroke)) { return false; } if (!PaintUtilities.equal(this.domainCrosshairPaint, that.domainCrosshairPaint)) { return false; } if (!ObjectUtilities.equal(this.rangeCrosshairStroke, that.rangeCrosshairStroke)) { return false; } if (!PaintUtilities.equal(this.rangeCrosshairPaint, that.rangeCrosshairPaint)) { return false; } if (!ObjectUtilities.equal(this.foregroundDomainMarkers, that.foregroundDomainMarkers)) { return false; } if (!ObjectUtilities.equal(this.backgroundDomainMarkers, that.backgroundDomainMarkers)) { return false; } if (!ObjectUtilities.equal(this.foregroundRangeMarkers, that.foregroundRangeMarkers)) { return false; } if (!ObjectUtilities.equal(this.backgroundRangeMarkers, that.backgroundRangeMarkers)) { return false; } if (!ObjectUtilities.equal(this.foregroundDomainMarkers, that.foregroundDomainMarkers)) { return false; } if (!ObjectUtilities.equal(this.backgroundDomainMarkers, that.backgroundDomainMarkers)) { return false; } if (!ObjectUtilities.equal(this.foregroundRangeMarkers, that.foregroundRangeMarkers)) { return false; } if (!ObjectUtilities.equal(this.backgroundRangeMarkers, that.backgroundRangeMarkers)) { return false; } if (!ObjectUtilities.equal(this.annotations, that.annotations)) { return false; } if (!ObjectUtilities.equal(this.fixedLegendItems, that.fixedLegendItems)) { return false; } if (!PaintUtilities.equal(this.domainTickBandPaint, that.domainTickBandPaint)) { return false; } if (!PaintUtilities.equal(this.rangeTickBandPaint, that.rangeTickBandPaint)) { return false; } if (!this.quadrantOrigin.equals(that.quadrantOrigin)) { return false; } for (int i = 0; i < 4; i++) { if (!PaintUtilities.equal(this.quadrantPaint[i], that.quadrantPaint[i])) { return false; } } if (!ObjectUtilities.equal(this.shadowGenerator, that.shadowGenerator)) { return false; } return super.equals(obj); } /** * Returns a clone of the plot. * * @return A clone. * * @throws CloneNotSupportedException this can occur if some component of * the plot cannot be cloned. */ @Override public Object clone() throws CloneNotSupportedException { XYPlot clone = (XYPlot) super.clone(); clone.domainAxes = CloneUtils.cloneMapValues(this.domainAxes); for (ValueAxis axis : clone.domainAxes.values()) { if (axis != null) { axis.setPlot(clone); axis.addChangeListener(clone); } } clone.rangeAxes = CloneUtils.cloneMapValues(this.rangeAxes); for (ValueAxis axis : clone.rangeAxes.values()) { if (axis != null) { axis.setPlot(clone); axis.addChangeListener(clone); } } clone.domainAxisLocations = new HashMap<Integer, AxisLocation>( this.domainAxisLocations); clone.rangeAxisLocations = new HashMap<Integer, AxisLocation>( this.rangeAxisLocations); // the datasets are not cloned, but listeners need to be added... clone.datasets = new HashMap<Integer, XYDataset>(this.datasets); for (XYDataset dataset : clone.datasets.values()) { if (dataset != null) { dataset.addChangeListener(clone); } } clone.datasetToDomainAxesMap = new TreeMap(); clone.datasetToDomainAxesMap.putAll(this.datasetToDomainAxesMap); clone.datasetToRangeAxesMap = new TreeMap(); clone.datasetToRangeAxesMap.putAll(this.datasetToRangeAxesMap); clone.renderers = CloneUtils.cloneMapValues(this.renderers); for (XYItemRenderer renderer : clone.renderers.values()) { if (renderer != null) { renderer.setPlot(clone); renderer.addChangeListener(clone); } } clone.foregroundDomainMarkers = (Map) ObjectUtilities.clone( this.foregroundDomainMarkers); clone.backgroundDomainMarkers = (Map) ObjectUtilities.clone( this.backgroundDomainMarkers); clone.foregroundRangeMarkers = (Map) ObjectUtilities.clone( this.foregroundRangeMarkers); clone.backgroundRangeMarkers = (Map) ObjectUtilities.clone( this.backgroundRangeMarkers); clone.annotations = (List) ObjectUtilities.deepClone(this.annotations); if (this.fixedDomainAxisSpace != null) { clone.fixedDomainAxisSpace = (AxisSpace) ObjectUtilities.clone( this.fixedDomainAxisSpace); } if (this.fixedRangeAxisSpace != null) { clone.fixedRangeAxisSpace = (AxisSpace) ObjectUtilities.clone( this.fixedRangeAxisSpace); } if (this.fixedLegendItems != null) { clone.fixedLegendItems = (LegendItemCollection) this.fixedLegendItems.clone(); } clone.quadrantOrigin = (Point2D) ObjectUtilities.clone( this.quadrantOrigin); clone.quadrantPaint = this.quadrantPaint.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.writeStroke(this.domainGridlineStroke, stream); SerialUtilities.writePaint(this.domainGridlinePaint, stream); SerialUtilities.writeStroke(this.rangeGridlineStroke, stream); SerialUtilities.writePaint(this.rangeGridlinePaint, stream); SerialUtilities.writeStroke(this.domainMinorGridlineStroke, stream); SerialUtilities.writePaint(this.domainMinorGridlinePaint, stream); SerialUtilities.writeStroke(this.rangeMinorGridlineStroke, stream); SerialUtilities.writePaint(this.rangeMinorGridlinePaint, stream); SerialUtilities.writeStroke(this.rangeZeroBaselineStroke, stream); SerialUtilities.writePaint(this.rangeZeroBaselinePaint, stream); SerialUtilities.writeStroke(this.domainCrosshairStroke, stream); SerialUtilities.writePaint(this.domainCrosshairPaint, stream); SerialUtilities.writeStroke(this.rangeCrosshairStroke, stream); SerialUtilities.writePaint(this.rangeCrosshairPaint, stream); SerialUtilities.writePaint(this.domainTickBandPaint, stream); SerialUtilities.writePaint(this.rangeTickBandPaint, stream); SerialUtilities.writePoint2D(this.quadrantOrigin, stream); for (int i = 0; i < 4; i++) { SerialUtilities.writePaint(this.quadrantPaint[i], stream); } SerialUtilities.writeStroke(this.domainZeroBaselineStroke, stream); SerialUtilities.writePaint(this.domainZeroBaselinePaint, 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.domainGridlineStroke = SerialUtilities.readStroke(stream); this.domainGridlinePaint = SerialUtilities.readPaint(stream); this.rangeGridlineStroke = SerialUtilities.readStroke(stream); this.rangeGridlinePaint = SerialUtilities.readPaint(stream); this.domainMinorGridlineStroke = SerialUtilities.readStroke(stream); this.domainMinorGridlinePaint = SerialUtilities.readPaint(stream); this.rangeMinorGridlineStroke = SerialUtilities.readStroke(stream); this.rangeMinorGridlinePaint = SerialUtilities.readPaint(stream); this.rangeZeroBaselineStroke = SerialUtilities.readStroke(stream); this.rangeZeroBaselinePaint = SerialUtilities.readPaint(stream); this.domainCrosshairStroke = SerialUtilities.readStroke(stream); this.domainCrosshairPaint = SerialUtilities.readPaint(stream); this.rangeCrosshairStroke = SerialUtilities.readStroke(stream); this.rangeCrosshairPaint = SerialUtilities.readPaint(stream); this.domainTickBandPaint = SerialUtilities.readPaint(stream); this.rangeTickBandPaint = SerialUtilities.readPaint(stream); this.quadrantOrigin = SerialUtilities.readPoint2D(stream); this.quadrantPaint = new Paint[4]; for (int i = 0; i < 4; i++) { this.quadrantPaint[i] = SerialUtilities.readPaint(stream); } this.domainZeroBaselineStroke = SerialUtilities.readStroke(stream); this.domainZeroBaselinePaint = SerialUtilities.readPaint(stream); // register the plot as a listener with its axes, datasets, and // renderers... for (ValueAxis axis : this.domainAxes.values()) { if (axis != null) { axis.setPlot(this); axis.addChangeListener(this); } } for (ValueAxis axis : this.rangeAxes.values()) { if (axis != null) { axis.setPlot(this); axis.addChangeListener(this); } } for (XYDataset dataset : this.datasets.values()) { if (dataset != null) { dataset.addChangeListener(this); } } for (XYItemRenderer renderer : this.renderers.values()) { if (renderer != null) { renderer.addChangeListener(this); } } } }
package TestingHarness; import java.io.IOException; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import java.util.UUID; import javax.ws.rs.QueryParam; import org.apache.log4j.Logger; import org.jboss.resteasy.client.jaxrs.ResteasyClient; import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; import com.puppycrawl.tools.checkstyle.api.CheckstyleException; /** * For JavaDoc, see TestServiceInterface * @author as2388 * @author kls2510 */ // full path to here is /tester/API/ public class TestService implements TestServiceInterface { //initialise log4j logger static Logger log = Logger.getLogger(TestService.class.getName()); /* * Maps the ID of a test to in-progress tests. TestService is responsible * for generating unique IDs Class users are responsible for remembering the * ID so that they can poll its status and get its report when done */ private static Map<String, Tester> ticksInProgress; // TODO: should we be // keeping these in a DB // instead? public TestService() { if (ticksInProgress == null) { log.info("ticksInProgress Initialised"); ticksInProgress = new HashMap<String, Tester>(); } } public TestService(Map<String, Tester> ticksInProgress) { TestService.ticksInProgress = ticksInProgress; } @Override public String runNewTest(@QueryParam("repoAddress") String repoAddress) throws IOException{ log.info("New test request received"); // generate a UUID for the tester String id; do { id = UUID.randomUUID().toString(); } while (TestService.ticksInProgress.containsKey(id)); log.info(id + ": runNewTest: test creation started"); Map<String, LinkedList<String>> tests = new HashMap<String, LinkedList<String>>(); // add corresponding git file to tests log.info(id + ": runNewTest: Creating new client for accessing git API"); ResteasyClient c = new ResteasyClientBuilder().build(); ResteasyWebTarget t = c.target("http://localhost:8080/TestingSystem/"); // to be provided as dependency by git team WebInterface proxy = t.proxy(WebInterface.class); log.info(id + ": runNewTest: Connecting to git API to obtain list of files in repo"); LinkedList<String> filesInRepo = proxy .listFiles("removeThisExampleString" + repoAddress); log.info(id + ": runNewTest: List of files obtained"); LinkedList<String> filesToTest = new LinkedList<String>(); LinkedList<String> staticTests = new LinkedList<String>(); for (String file : filesInRepo) { String ext = file.substring(file.lastIndexOf('.') + 1, file.length()); // TODO: note that dynamic tests will also be java files! - what to // do? as2388: the dynamic tests should be in a different repository if (ext.equals("java")) { filesToTest.add(file); } else if (ext.equals("xml")) { staticTests.add(file); } else { System.out.println("File not recognised"); //TODO: is printing this in anyway useful? } } log.info(id + ": runNewTest: creating Tester object"); for (String test : staticTests) { tests.put(test, filesToTest); } c.close(); // create a new Tester object final Tester tester = new Tester(tests); // add the object to the list of in-progress tests ticksInProgress.put(id, tester); // start the test in an asynchronous thread new Thread(new Runnable() { public void run() { tester.runTests(); } }).start(); log.info(id + ": runNewTest: Test started"); return id; } @Override public String pollStatus(@QueryParam("testID") String testID) throws TestIDNotFoundException { log.info(testID + ": pollStatus: request received"); if (ticksInProgress.containsKey(testID)) { String status = ticksInProgress.get(testID).getStatus(); log.info(testID + ": pollStatus: returning " + status); return status; } else { log.error(testID + ": pollStatus: testID not found"); throw new TestIDNotFoundException(testID); } } @Override public Report getReport(@QueryParam("testID") String testID) throws TestIDNotFoundException, CheckstyleException, WrongFileTypeException, TestHarnessException { log.info(testID + ": getReport: request received"); if (ticksInProgress.containsKey(testID)) { Tester tester = ticksInProgress.get(testID); // Assuming we're not responsible for storing tests, we should // remove the test at this point. So I am. ticksInProgress.remove(testID); if (!(tester.getStatus().equals("error"))) { // test completed normally; return the report log.info(testID + ": getReport: report found; returning it"); return tester.getReport(); } else { /*test failed, throw the exception causing the problem. Exceptions are thrown lazily because we need to run Tester instances in separate threads, so that we can return the ID of the test to the UI team when they call runNewTest. The UI team needs this ID to poll the status of this test. To do this, exceptions are stored in a variable of type Exception, but to provide better error information to the ticking team, the Exception is casted back to its original type before being lazily thrown, hence why this bit is so yucky*/ log.error(testID + ": getReport: Report didn't complete successfully, lazily throwing the exception it generated"); Exception failCause = tester.getFailCause(); if (failCause instanceof CheckstyleException) { throw (CheckstyleException) failCause; } else if (failCause instanceof WrongFileTypeException) { throw (WrongFileTypeException) failCause; } else { throw (TestHarnessException) failCause; } } } else { log.error(testID + ": getReport: testID not found"); throw new TestIDNotFoundException(testID); } } @Override public String getException() { log.info("getException: accessing get exception method on git API"); //TODO: query git API for an exception log.error("getException: Didn't get an exception back :("); return "Exception not generated by git team"; } /** * Used for manually testing that the three main API functions work * @param testID * @return * @throws TestIDNotFoundException */ public String test(@QueryParam("testID") String testID) throws TestIDNotFoundException { ResteasyClient c = new ResteasyClientBuilder().build(); ResteasyWebTarget t = c.target("http://localhost:8080/TestingSystem/"); TestServiceInterface proxy = t.proxy(TestServiceInterface.class); return proxy.pollStatus(testID); } }
package org.jpc.util; import javafx.application.Application; import javafx.application.Platform; import javafx.stage.Stage; /** * A utility class for facilitating launching JavaFX applications from the Prolog side. * This class is not intended to be used directly from the Java side. * If employed from the Java side, users of this class should explicitly call "Platform.exit()" before quitting the application. * @author sergioc * */ public class JavaFXLauncher extends Application { private static boolean launched; private static final Object appInitLock = new Object(); private static class WrappedStage { Stage stage; Exception ex; } public static Stage show(Class<? extends Stage> stageClass) { launchIfNeeded(); final Object stageInitLock = new Object(); WrappedStage wStage = new WrappedStage(); javafx.application.Platform.runLater(new Runnable() { Stage stage; @Override public void run() { synchronized(stageInitLock) { try { stage = stageClass.newInstance(); //this must be executed in the user interface thread. } catch (InstantiationException | IllegalAccessException e) { wStage.ex = e; throw new RuntimeException(e); } finally { stageInitLock.notify(); } } wStage.stage = stage; stage.show(); } }); synchronized(stageInitLock) { while(wStage.stage == null && wStage.ex == null) { try { stageInitLock.wait(); } catch (InterruptedException e) { throw new RuntimeException(e); } } } return wStage.stage; } @Override public void init() { synchronized(appInitLock) { Platform.setImplicitExit(false); launched = true; appInitLock.notifyAll(); } } public static void launchIfNeeded() { synchronized(appInitLock) { if(!launched) { new Thread() { @Override public void run() { try { Application.launch(JavaFXLauncher.class); } catch(Exception e) { System.out.println(e); throw(e); } } }.start(); while(!launched) { try { appInitLock.wait(); } catch (InterruptedException e) { throw new RuntimeException(e); } } } } } @Override public void start(Stage primaryStage) { } }
package application; import javafx.event.Event; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.Node; import javafx.scene.control.*; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.stage.DirectoryChooser; import org.apache.commons.io.FileUtils; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPReply; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.InetAddress; import java.net.URL; import java.time.chrono.ChronoPeriod; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.ResourceBundle; public class MainController implements Initializable { // UI elements @FXML private TreeView<String> fileTreeView; @FXML private TextField addressTF; @FXML private TextField usernameTF; @FXML private PasswordField passwordPF; @FXML private Button loginBT; @FXML private Label messageLB; @FXML private Button outputDirBT; @FXML private Label outputDirLB; // variables FTPClient client = new FTPClient(); InetAddress address; DirectoryChooser directoryChooser = new DirectoryChooser(); File outputDir = new File("downloadedFiles"); OutputStream outStream; private Image dirIcon = new Image(getClass().getResourceAsStream("/icons/directory_icon.png")); public void initialize(URL location, ResourceBundle resources) { // make the output directory outputDir.mkdir(); // set up directory chooser directoryChooser.setTitle("Select Download Location"); // set up file tree TreeItem<String> rootItem = new TreeItem<> ("Root: /", new ImageView(dirIcon)); rootItem.setExpanded(true); // set the tree root fileTreeView.setRoot(rootItem); // set the login details to make testing faster addressTF.setText("ftp.vaultfortress.net"); usernameTF.setText("ross@vaultfortress.net"); passwordPF.setText("TopGun666"); } // initialize() // onClick method for login button @FXML void loginButtonClick_OnAction(){ //System.out.println("Login Click"); // clear message label messageLB.setText(""); // clear the file tree TreeItem<String> rootItem = new TreeItem<String> ("Root: /", new ImageView(dirIcon)); rootItem.setExpanded(true); // set the tree root fileTreeView.setRoot(rootItem); // check that server address is entered // check that username and password are entered if(addressTF.getCharacters().length() < 3){ this.messageLB.setText("Error, enter ftp server address."); return; } if(usernameTF.getCharacters().length() < 1){ this.messageLB.setText("Error, enter Username."); return; } if(passwordPF.getCharacters().length() < 1){ this.messageLB.setText("Error, enter Password."); return; } // try login connectToServer(this.addressTF.getText(), this.usernameTF.getText(), this.passwordPF.getText()); } // loginButtonClick() @FXML void outputDirBT_OnAction(){ // open output directory chooser outputDir = directoryChooser.showDialog(null); // show selected folder if(outputDir != null) outputDirLB.setText(outputDir.getAbsolutePath()); } // outputDirBT_OnAction() private void connectToServer(String serverAddress, String username, String password){ // try connect if(this.client.isConnected() == false){ try { // create a server address this.address = InetAddress.getByName(serverAddress); // connect to the address client.connect(address, 21); // try and login client.login(username, password); if (client.isConnected()) { System.out.print(client.getReplyString()); if (!FTPReply.isPositiveCompletion(client.getReplyCode())){ messageLB.setText("Error: " + client.getReplyString()); client.disconnect(); return; } // enter passive mode client.enterLocalPassiveMode(); // logged in ok messageLB.setText(client.getReplyString()); // display files buildFileTree(fileTreeView.getRoot(), client, ""); // download the files System.out.println("Starting to download files"); syncFiles(client, ""); System.out.println("Finished downloading files"); } }catch (Exception e){ System.out.println("Error: " + e.getMessage()); messageLB.setText("Error: " + e.getMessage()); } finally { try { // disconnect client client.disconnect(); // close outStream //outStream.close(); System.out.println("Disconnecting"); } catch (IOException e) { //e.printStackTrace(); System.out.println("Error Disconnecting"); } catch (Exception e){ e.printStackTrace(); } } // try } } // connectToServer() // builds the tree view of the files private void buildFileTree(TreeItem treeNode, FTPClient client, String path) throws Exception { // display the files FTPFile[] files = client.listFiles(path, FTPFile::isFile); for (FTPFile file : files) { // add file to file tree treeNode.getChildren().add(new TreeItem<>(file.getName() + " | " + file.getTimestamp().toInstant())); } // for // get the directories FTPFile[] directories = client.listDirectories(path); for (FTPFile dir : directories) { if(!dir.getName().startsWith(".")) { // create treeItem to represent new Directory TreeItem newDir = new TreeItem<>(dir.getName(), new ImageView(dirIcon)); // add directory to file tree treeNode.getChildren().add(newDir); // build path to new directory in server String newPath = path + File.separator + dir.getName(); System.out.println("Discovering Files in: " + newPath); // recursively call method to add files and directories to new directory buildFileTree(newDir, client, newPath); } } // for } // buildFileTree() // sync files, by download files that need to be downloaded private void syncFiles(FTPClient client, String path) throws Exception { // display the files FTPFile[] files = client.listFiles(path, FTPFile::isFile); for (FTPFile file : files) { System.out.println("Downloading: " + file.getName()); // create outputStream for file outStream = new FileOutputStream(outputDir.getName() + File.separator + file.getName()); // retrieve the files client.retrieveFile(path + file.getName(), outStream); } // for // get the directories FTPFile[] directories = client.listDirectories(path); for (FTPFile dir : directories) { if(!dir.getName().startsWith(".")) { // build path to new directory in server String newPath = path + File.separator + dir.getName(); System.out.println("Downloading Files in: " + newPath); // recursively call method to add files and directories to new directory syncFiles(client, newPath); } } // for } // syncFiles() public void ftpTest() { String server = "localhost"; try { address = InetAddress.getByName(server); client.connect(address); client.login("bob", "qwerty"); if (client.isConnected()) { // enter passive mode client.enterLocalPassiveMode(); //client.enterRemoteActiveMode(addr,3000); System.out.println("Connected"); System.out.print(client.getReplyString()); FTPFile[] files = client.listFiles(); System.out.println("No of Files: " + files.length); // Obtain a list of filenames in the current working // directory. When no file found an empty array will // be returned. String[] names = client.listNames(); //System.out.println("No of files: " + names.length); for (String name : names) { System.out.println("Name = " + name); fileTreeView.getRoot().getChildren().add(new TreeItem<>(name)); } FTPFile[] ftpFiles = client.listFiles(); for (FTPFile ftpFile : ftpFiles) { // Check if FTPFile is a regular file if (ftpFile.getType() == FTPFile.FILE_TYPE) { System.out.printf("FTPFile: %s; %s; %s%n", ftpFile.getName(), FileUtils.byteCountToDisplaySize(ftpFile.getSize()), ftpFile.getTimestamp().getTime().toString()); } } } client.logout(); } catch (IOException e) { System.out.println("Error: " + e.getMessage()); } finally { try { client.disconnect(); } catch (IOException e) { //e.printStackTrace(); System.out.println("Error Disconnecting"); } } } // ftpTest() } // class
package org.lightmare.config; import java.util.Arrays; import java.util.HashSet; import org.lightmare.cache.DeploymentDirectory; /** * Keeps keys and default values for configuration * * @author Levan * */ public enum Config { // Default properties // Path where stored administrative users ADMIN_USERS_PATH("adminUsersPath", "./config/admin/users.properties"), // Netty server / client configuration properties for RPC calls IP_ADDRESS("listeningIp", "0.0.0.0"), PORT("listeningPort", "1199"), // Port BOSS_POOL("bossPoolSize", 1), // Boss pool WORKER_POOL("workerPoolSize", 3), // Worker pool CONNECTION_TIMEOUT("timeout", 1000), // Connection timeout // Properties for data source path and deployment path DEMPLOYMENT_PATH("deploymentPath", new HashSet<DeploymentDirectory>( Arrays.asList(new DeploymentDirectory("./deploy", Boolean.TRUE)))), DATA_SOURCE_PATH("dataSourcePath", new HashSet<String>( Arrays.asList("./ds"))), // Data // source // path // Properties which version of server is running remote it requires server // client RPC infrastructure or local (embedded mode) SERVER("server", Boolean.TRUE), REMOTE("remote", Boolean.FALSE), CLIENT("client", Boolean.FALSE), // Configuration keys properties for deployment DEPLOY_CONFIG("deployConfiguration"), // Deploy CONFIG ADMIN_USER_PATH("adminPath", "./config/admin/users.properties"), // ADMIN // user // path HOT_DEPLOYMENT("hotDeployment"), // Hot deployment WATCH_STATUS("watchStatus"), // Watch status LIBRARY_PATH("libraryPaths"), // Library path // Persistence provider property keys PERSISTENCE_CONFIG("persistenceConfig"), // Persistence CONFIG SCAN_FOR_ENTITIES("scanForEntities"), // Scan for entities ANNOTATED_UNIT_NAME("annotatedUnitName"), // Annotated unit PERSISTENCE_XML_PATH("persistanceXmlPath"), // Persistence XML PERSISTENCE_XML_FROM_JAR("persistenceXmlFromJar"), // Persistence XML from // jar SWAP_DATASOURCE("swapDataSource"), // Swap data source SCAN_ARCHIVES("scanArchives"), // Scan archives POOLED_DATA_SOURCE("pooledDataSource", Boolean.TRUE), // Pooled data source PERSISTENCE_PROPERTIES("persistenceProperties"), // Persistence properties // Connection pool provider property keys POOL_CONFIG("poolConfig"), // Pool CONFIG POOL_PROPERTIES_PATH("poolPropertiesPath"), // Pool properties path POOL_PROVIDER_TYPE("poolProviderType"), // Pool provider type POOL_PROPERTIES("poolProperties"), // Pool properties // Default configuration file location CONFIG_FILE("configFile", "./config/configuration.yaml"); public String key; public Object value; private Config(String key) { this.key = key; } private Config(String key, Object value) { this(key); this.value = value; } }
package browserview; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebDriverException; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import java.util.NoSuchElementException; // acts as a middleman for ChromeDriver when not in testing mode, // and as a stub when testing public class ChromeDriverEx { private static final Logger logger = LogManager.getLogger(ChromeDriverEx.class.getName()); private boolean isTestChromeDriver; private ChromeDriver driver; ChromeDriverEx(ChromeOptions options, boolean isTestChromeDriver) { this.isTestChromeDriver = isTestChromeDriver; initialise(options); } private void initialise(ChromeOptions options) { if (!isTestChromeDriver) driver = new ChromeDriver(options); } public WebDriver.Options manage() { return !isTestChromeDriver ? driver.manage() : null; } public void quit() { if (!isTestChromeDriver) driver.quit(); } public void get(String url) throws WebDriverException { if (isTestChromeDriver) { logger.info("Test loading page: " + url); testGet(); } else { if (driver.getCurrentUrl().toLowerCase().equals(url.toLowerCase())) { logger.info("Already on page: " + url + " will not load it again. "); } else { logger.info("Previous page was: " + driver.getCurrentUrl()); logger.info("Loading page: " + url); driver.get(url); } } } public void testGet() throws WebDriverException { double chance = Math.random(); if (chance < 0.25) { throw new WebDriverException("no such window"); } else if (chance < 0.5) { throw new WebDriverException("no such element"); } else if (chance < 0.75) { throw new WebDriverException("unexpected alert open"); } } public String getCurrentUrl() { return !isTestChromeDriver ? driver.getCurrentUrl() : "https://github.com/HubTurbo/HubTurbo/issues/1"; } public WebElement findElementById(String id) throws NoSuchElementException { if (!isTestChromeDriver) return driver.findElementById(id); throw new NoSuchElementException(); } public WebElement findElementByTagName(String tag) throws NoSuchElementException { if (!isTestChromeDriver) return driver.findElementByTagName(tag); throw new NoSuchElementException(); } public WebDriver.TargetLocator switchTo() throws WebDriverException { if (!isTestChromeDriver) { return driver.switchTo(); } else { // ~25% chance to throw an exception which is used to test resetBrowser if (Math.random() < 0.25) { throw new WebDriverException(); } } return null; } public String getWindowHandle() { return !isTestChromeDriver ? driver.getWindowHandle() : ""; } public WebElement findElement(By by) throws NoSuchElementException { if (!isTestChromeDriver) return driver.findElement(by); throw new NoSuchElementException(); } public Object executeScript(String script) { return !isTestChromeDriver ? driver.executeScript(script) : ""; } }
package org.sbrubbles.genericcons; import java.lang.reflect.ParameterizedType; import java.util.ArrayList; import java.util.List; import org.javaruntype.type.Type; import org.javaruntype.type.Types; /** * Captures and represents an open-ended list of types. This class isn't * supposed to be instantiated or subclassed; it's used to build the * list in the type declaration, like below: * * <pre> * Function&lt;?, ?&gt; f = new Function&lt;String, C&lt;Object, C&lt;Number, C&lt;String, Integer&gt;&gt;&gt;&gt;() { * { // the no-arg constructor * this.types = C.extractTypesFromSuperclass(this.getClass(), 1); * } * }; * </pre> * * It was supposed to be {@code Cons} (hence the {@code C}), but using only * one letter kept type arguments (slightly) more readable. * * @author Humberto Anjos * @param <First> The first type. * @param <Rest> The last type, or a C holding the rest of the types. */ public final class C<First, Rest> { // preventing instantiation private C() { /* empty block */ } /** * Searches the given base class' superclass for the list of types indexed by * {@code parameterIndex}. * * @param baseClass the class whose generic superclass holds the list of * type arguments. * @param parameterIndex where in the given base class' generic superclass' * type argument list is the desired list of types. * @return a list of the types found. * @throws TypeParametersNotFoundException if no type parameters are found. * @throws InvalidTypeException if there is a problem converting the standard * Java {@linkplain java.lang.reflect.Type type} to a {@linkplain Type fuller * representation}. */ public static List<? extends Type<?>> extractTypesFromSuperclass(Class<?> baseClass, int parameterIndex) throws TypeParametersNotFoundException, InvalidTypeException { if(baseClass == null) throw new IllegalArgumentException("The base class cannot be null!"); java.lang.reflect.Type superclass = baseClass.getGenericSuperclass(); if(! (superclass instanceof ParameterizedType)) throw new TypeParametersNotFoundException(baseClass); ParameterizedType cons = (ParameterizedType) superclass; try { return extractTypesFromCons(cons.getActualTypeArguments()[parameterIndex]); } catch (IndexOutOfBoundsException e) { throw new TypeParametersNotFoundException(baseClass, e); } } // TODO match a list of types against a list of objects private static List<? extends Type<?>> extractTypesFromCons(java.lang.reflect.Type type) throws InvalidTypeException { assert type != null; List<Type<?>> result = new ArrayList<Type<?>>(); // end of recursion, add it and return if(! (type instanceof ParameterizedType) || ((ParameterizedType) type).getRawType() != C.class) { result.add(convertToFullType(type)); return result; } // recurse ParameterizedType cons = (ParameterizedType) type; java.lang.reflect.Type[] actualTypes = cons.getActualTypeArguments(); result.add(convertToFullType(actualTypes[0])); result.addAll(extractTypesFromCons(actualTypes[1])); return result; } private static Type<?> convertToFullType(java.lang.reflect.Type type) throws InvalidTypeException { try { return Types.forJavaLangReflectType(type); } catch (Throwable t) { throw new InvalidTypeException(type, t); } } }
// VisBio.java package loci.visbio; import java.awt.Color; import java.io.IOException; import java.lang.reflect.*; import loci.visbio.util.InstanceServer; import loci.visbio.util.SplashScreen; public final class VisBio extends Thread { // -- Constants -- /** Application title. */ public static final String TITLE = "VisBio"; private static final String V = "@visbio.version@"; /** Application version (of the form "#.##"). */ public static final String VERSION = V.equals("@visbio" + ".version@") ? "(internal build)" : (V.substring(0, 1) + "." + V.substring(1)); /** Application authors. */ public static final String AUTHOR = "Curtis Rueden and Abraham Sorber, LOCI"; /** Application build date. */ public static final String DATE = "@date@"; /** Port to use for communicating between application instances. */ public static final int INSTANCE_PORT = 0xabcd; // -- Constructor -- /** Ensure this class can't be externally instantiated. */ private VisBio() { } // -- VisBio API methods -- /** Launches the VisBio GUI with no arguments, in a separate thread. */ public static void startProgram() { new VisBio().start(); } /** Launches VisBio, returning the newly constructed VisBioFrame object. */ public static Object launch(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException { // check whether VisBio is already running boolean isRunning = true; try { InstanceServer.sendArguments(args, INSTANCE_PORT); } catch (IOException exc) { isRunning = false; } if (isRunning) return null; // display splash screen String[] msg = { TITLE + " " + VERSION + " - " + AUTHOR, "VisBio is starting up..." }; SplashScreen ss = new SplashScreen( VisBio.class.getResource("visbio-logo.png"), msg, new Color(255, 255, 220), new Color(255, 50, 50)); ss.setVisible(true); // toggle window decoration mode via reflection boolean b = "true".equals(System.getProperty("visbio.decorateWindows")); Class jf = Class.forName("javax.swing.JFrame"); Method m = jf.getMethod("setDefaultLookAndFeelDecorated", new Class[] {boolean.class}); m.invoke(null, new Object[] {new Boolean(b)}); // construct VisBio interface via reflection Class vb = Class.forName("loci.visbio.VisBioFrame"); Constructor con = vb.getConstructor(new Class[] { ss.getClass(), String[].class }); return con.newInstance(new Object[] {ss, args}); } // -- Thread API methods -- /** Launches the VisBio GUI with no arguments. */ public void run() { try { launch(new String[0]); } catch (Exception exc) { exc.printStackTrace(); } } // -- Main -- /** Launches the VisBio GUI. */ public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException { Object o = launch(args); if (o == null) System.out.println("VisBio is already running."); } }
package com.acme; import java.util.Map; import javax.jms.ConnectionFactory; import org.apache.camel.CamelContext; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.Message; import org.apache.camel.Body; import org.apache.camel.CamelContext; import org.apache.camel.ProducerTemplate; import org.apache.camel.impl.DefaultProducerTemplate; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.jms.JmsComponent; import org.apache.camel.model.ModelCamelContext; import org.apache.camel.model.language.JsonPathExpression; import org.apache.camel.model.dataformat.JsonLibrary; import javax.script.ScriptContext; import javax.script.ScriptEngine; import javax.script.ScriptEngineFactory; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import java.util.Map; import java.util.HashMap; import java.util.concurrent.atomic.AtomicReference; import java.math.BigDecimal; import java.io.InputStreamReader; import java.io.IOException; import org.springframework.core.io.ClassPathResource; /** * A Camel Java DSL Router */ public class IBankRouteBuilder extends RouteBuilder { private static final ScriptEngineManager manager = new ScriptEngineManager(); private static final ScriptEngine engine = manager.getEngineByName("JavaScript"); private static final AtomicReference<Map> accountsRef = new AtomicReference<Map>(null); private final ConnectionFactory connectionFactory; public IBankRouteBuilder(ConnectionFactory connectionFactory){ this.connectionFactory = connectionFactory; } protected void initializeEngine(CamelContext ctx) throws IOException, ScriptException, Exception { ProducerTemplate producer = new DefaultProducerTemplate(ctx); producer.start(); engine.put("producer", producer); engine.put("accountsRef", accountsRef); engine.eval(new InputStreamReader(new ClassPathResource("js/bank.js").getInputStream())); } protected Double getDoubleValue(Object obj){ if(obj instanceof BigDecimal){ return ((BigDecimal)obj).doubleValue(); } else if(obj instanceof Double){ return (Double)obj; } else if(obj instanceof Integer){ return ((Number)obj).doubleValue(); } else { throw new java.lang.ClassCastException("Class " + obj.getClass().getName() + " can't be casted to Double"); } } /** * Let's configure the Camel routing rules using Java code... */ public void configure() throws IOException, ScriptException, Exception { initializeEngine(getContext()); // Note we can explicit name the component if(getContext().getComponent("jms", false) == null){ getContext().addComponent("jms", JmsComponent.jmsComponentAutoAcknowledge(connectionFactory)); } onException(java.lang.IllegalStateException.class) .handled(true) .logExhausted(false) .logStackTrace(false) .to("file:out/bank/failed?fileName=${date:now:yyyyMMdd-hhmmssSSSS}.${in.header.operation}") .to("jms:queue:das.failed"); interceptSendToEndpoint("jms:queue:bank.operate") .to("jms:queue:das.completed"); interceptFrom("seda:bank.*") .marshal().json(JsonLibrary.Jackson) .choice() .when().jsonpath("$..from[?(@.account.number != $.to.account.number)]") // Trying to perform transaction. Throwing exception if not possible .process(new Processor(){ public void process(Exchange outExchange) { Message message = outExchange.getIn(); String operation = message.getHeader("operation").toString(); Map accountFrom = (Map)accountsRef.get().get(new JsonPathExpression("$.from.customer").evaluate(outExchange).toString()); Map accountTo = (Map)accountsRef.get().get(new JsonPathExpression("$.to.customer").evaluate(outExchange).toString()); Double amount = getDoubleValue(new JsonPathExpression("$.amount").evaluate(outExchange)); System.out.println(accountFrom.get("balance")); switch(operation.toLowerCase()){ case "send": { // Operation should be atomic synchronized(this){ if(getDoubleValue(accountFrom.get("balance")) < amount){ throw new java.lang.IllegalStateException("Insufficient funds"); } else { accountFrom.put("balance", getDoubleValue(accountFrom.get("balance")) - amount); accountTo.put("balance", getDoubleValue(accountTo.get("balance")) + amount); } } }; case "receive": { // Operation should be atomic synchronized(this){ if(getDoubleValue(accountTo.get("balance")) < getDoubleValue(new JsonPathExpression("$.amount").evaluate(outExchange))){ throw new java.lang.IllegalStateException("Insufficient funds"); } else { accountFrom.put("balance", getDoubleValue(accountFrom.get("balance")) + amount); accountTo.put("balance", getDoubleValue(accountTo.get("balance")) - amount); } } }; case "withdraw": { if(getDoubleValue(accountFrom.get("balance")) < getDoubleValue(new JsonPathExpression("$.amount").evaluate(outExchange))){ throw new java.lang.IllegalStateException("Insufficient funds"); } else { accountFrom.put("balance", getDoubleValue(accountFrom.get("balance")) - amount); } } } } }) .to("jms:queue:bank.operate") .otherwise() .filter(header("operation").isNotEqualTo("withdraw")) // Checking if from and to is the same customer .process(new Processor(){ public void process(Exchange outExchange) throws Exception{ throw new java.lang.IllegalStateException("Can't transfer within same account!"); } }) .end(); from("seda:bank.send") .log("${in.header.operation}:${in.body}"); from("seda:bank.receive") .log("${in.header.operation}:${in.body}"); from("seda:bank.withdraw") .log("${in.header.operation}:${in.body}"); } }
package com.github.albertopeam.infrastructure.concurrency; import android.arch.lifecycle.Lifecycle; import android.arch.lifecycle.LifecycleObserver; import android.arch.lifecycle.LifecycleOwner; import android.arch.lifecycle.OnLifecycleEvent; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.github.albertopeam.infrastructure.exceptions.ExceptionController; public abstract class UseCase<Args, Response> implements LifecycleObserver { private LifecycleOwner lifecycleOwner; private ExceptionController exceptionController; private LifecycleState lifecycleState; protected UseCase(@NonNull ExceptionController exceptionController, @NonNull LifecycleOwner lifecycleOwner){ this.exceptionController = exceptionController; this.lifecycleOwner = lifecycleOwner; this.lifecycleOwner.getLifecycle().addObserver(this); this.lifecycleState = LifecycleState.INITIALIZED; } protected abstract Response run(Args args) throws Exception; @NonNull ExceptionController exceptionController() { return exceptionController; } boolean canRespond(){ if (lifecycleOwner == null){ return false; } Lifecycle lifecycle = lifecycleOwner.getLifecycle(); boolean isInitialized = lifecycle.getCurrentState().isAtLeast(Lifecycle.State.INITIALIZED); boolean isNotDestroyed = lifecycleState != LifecycleState.DESTROYED; return isInitialized && isNotDestroyed; } boolean canRun(){ if (lifecycleOwner == null){ return false; } Lifecycle lifecycle = lifecycleOwner.getLifecycle(); boolean isInitialized = lifecycle.getCurrentState().isAtLeast(Lifecycle.State.INITIALIZED); boolean isNotDestroyed = lifecycleState != LifecycleState.DESTROYED; return isInitialized && isNotDestroyed; } @Nullable LifecycleOwner lifecycleOwner(){ return lifecycleOwner; } @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) public void destroy() { lifecycleState = LifecycleState.DESTROYED; lifecycleOwner = null; } }
package com.conveyal.gtfs; import com.conveyal.gtfs.error.GTFSError; import com.conveyal.gtfs.model.*; import com.conveyal.gtfs.model.Calendar; import com.conveyal.gtfs.validator.DuplicateStopsValidator; import com.conveyal.gtfs.validator.GTFSValidator; import com.conveyal.gtfs.validator.HopSpeedsReasonableValidator; import com.conveyal.gtfs.validator.MisplacedStopValidator; import com.conveyal.gtfs.validator.MissingStopCoordinatesValidator; import com.conveyal.gtfs.validator.NamesValidator; import com.conveyal.gtfs.validator.OverlappingTripsValidator; import com.conveyal.gtfs.validator.ReversedTripsValidator; import com.conveyal.gtfs.validator.TripTimesValidator; import com.conveyal.gtfs.validator.UnusedStopValidator; import com.conveyal.gtfs.stats.FeedStats; import com.conveyal.gtfs.validator.service.GeoUtils; import com.google.common.collect.*; import com.google.common.eventbus.EventBus; import com.vividsolutions.jts.algorithm.ConvexHull; import com.vividsolutions.jts.geom.*; import com.vividsolutions.jts.index.strtree.STRtree; import com.vividsolutions.jts.simplify.DouglasPeuckerSimplifier; import org.geotools.referencing.GeodeticCalculator; import org.mapdb.BTreeMap; import org.mapdb.Bind; import org.mapdb.DB; import org.mapdb.DBMaker; import org.mapdb.Fun; import org.mapdb.Fun.Tuple2; import org.mapdb.Serializer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.time.ZoneId; import java.util.*; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentNavigableMap; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; import static com.conveyal.gtfs.util.Util.human; /** * All entities must be from a single feed namespace. * Composed of several GTFSTables. */ public class GTFSFeed implements Cloneable, Closeable { private static final Logger LOG = LoggerFactory.getLogger(GTFSFeed.class); private DB db; public String feedId = null; // TODO make all of these Maps MapDBs so the entire GTFSFeed is persistent and uses constant memory /* Some of these should be multimaps since they don't have an obvious unique key. */ public final Map<String, Agency> agency; public final Map<String, FeedInfo> feedInfo; public final NavigableSet<Tuple2<String, Frequency>> frequencies; public final Map<String, Route> routes; public final Map<String, Stop> stops; public final Map<String, Transfer> transfers; public final Map<String, Trip> trips; public final Set<String> transitIds = new HashSet<>(); /** CRC32 of the GTFS file this was loaded from */ public long checksum; /* Map from 2-tuples of (shape_id, shape_pt_sequence) to shape points */ public final ConcurrentNavigableMap<Tuple2<String, Integer>, ShapePoint> shape_points; /* Map from 2-tuples of (trip_id, stop_sequence) to stoptimes. */ public final BTreeMap<Tuple2, StopTime> stop_times; public final ConcurrentMap<String, Long> stopCountByStopTime; public final NavigableSet<Tuple2<String, Tuple2>> stopStopTimeSet; /* A fare is a fare_attribute and all fare_rules that reference that fare_attribute. */ public final Map<String, Fare> fares; /* A service is a calendar entry and all calendar_dates that modify that calendar entry. */ public final Map<String, Service> services; /* A place to accumulate errors while the feed is loaded. Tolerate as many errors as possible and keep on loading. */ public final NavigableSet<GTFSError> errors; /* Stops spatial index which gets built lazily by getSpatialIndex() */ private transient STRtree spatialIndex; /* Convex hull of feed (based on stops) built lazily by getConvexHull() */ private transient Polygon convexHull; /* Merged stop buffers polygon built lazily by getMergedBuffers() */ private transient Geometry mergedBuffers; /* Create geometry factory to produce LineString geometries. */ GeometryFactory gf = new GeometryFactory(); /* Map routes to associated trip patterns. */ // TODO: Hash Multimapping in guava (might need dependency). public final Map<String, Pattern> patterns; // TODO bind this to map above so that it is kept up to date automatically public final Map<String, String> tripPatternMap; private boolean loaded = false; /* A place to store an event bus that is passed through constructor. */ public transient EventBus eventBus; /** * The order in which we load the tables is important for two reasons. * 1. We must load feed_info first so we know the feed ID before loading any other entities. This could be relaxed * by having entities point to the feed object rather than its ID String. * 2. Referenced entities must be loaded before any entities that reference them. This is because we check * referential integrity while the files are being loaded. This is done on the fly during loading because it allows * us to associate a line number with errors in objects that don't have any other clear identifier. * * Interestingly, all references are resolvable when tables are loaded in alphabetical order. */ public void loadFromFile(ZipFile zip, String fid) throws Exception { if (this.loaded) throw new UnsupportedOperationException("Attempt to load GTFS into existing database"); // NB we don't have a single CRC for the file, so we combine all the CRCs of the component files. NB we are not // simply summing the CRCs because CRCs are (I assume) uniformly randomly distributed throughout the width of a // long, so summing them is a convolution which moves towards a Gaussian with mean 0 (i.e. more concentrated // probability in the center), degrading the quality of the hash. Instead we XOR. Assuming each bit is independent, // this will yield a nice uniformly distributed result, because when combining two bits there is an equal // probability of any input, which means an equal probability of any output. At least I think that's all correct. // Repeated XOR is not commutative but zip.stream returns files in the order they are in the central directory // of the zip file, so that's not a problem. checksum = zip.stream().mapToLong(ZipEntry::getCrc).reduce((l1, l2) -> l1 ^ l2).getAsLong(); db.getAtomicLong("checksum").set(checksum); new FeedInfo.Loader(this).loadTable(zip); // maybe we should just point to the feed object itself instead of its ID, and null out its stoptimes map after loading if (fid != null) { feedId = fid; LOG.info("Feed ID is undefined, pester maintainers to include a feed ID. Using file name {}.", feedId); // TODO log an error, ideally feeds should include a feedID } else if (feedId == null || feedId.isEmpty()) { feedId = new File(zip.getName()).getName().replaceAll("\\.zip$", ""); LOG.info("Feed ID is undefined, pester maintainers to include a feed ID. Using file name {}.", feedId); // TODO log an error, ideally feeds should include a feedID } else { LOG.info("Feed ID is '{}'.", feedId); } db.getAtomicString("feed_id").set(feedId); new Agency.Loader(this).loadTable(zip); // calendars and calendar dates are joined into services. This means a lot of manipulating service objects as // they are loaded; since mapdb keys/values are immutable, load them in memory then copy them to MapDB once // we're done loading them Map<String, Service> serviceTable = new HashMap<>(); new Calendar.Loader(this, serviceTable).loadTable(zip); new CalendarDate.Loader(this, serviceTable).loadTable(zip); this.services.putAll(serviceTable); serviceTable = null; // free memory // Same deal Map<String, Fare> fares = new HashMap<>(); new FareAttribute.Loader(this, fares).loadTable(zip); new FareRule.Loader(this, fares).loadTable(zip); this.fares.putAll(fares); fares = null; // free memory new Route.Loader(this).loadTable(zip); new ShapePoint.Loader(this).loadTable(zip); new Stop.Loader(this).loadTable(zip); new Transfer.Loader(this).loadTable(zip); new Trip.Loader(this).loadTable(zip); new Frequency.Loader(this).loadTable(zip); new StopTime.Loader(this).loadTable(zip); // comment out this line for quick testing using NL feed LOG.info("{} errors", errors.size()); for (GTFSError error : errors) { LOG.info("{}", error); LOG.info("{}", error); } Bind.histogram(stop_times, stopCountByStopTime, (key, stopTime) -> stopTime.stop_id); Bind.secondaryKeys(stop_times, stopStopTimeSet, (key, stopTime) -> new String[] {stopTime.stop_id}); loaded = true; } public void loadFromFile(ZipFile zip) throws Exception { loadFromFile(zip, null); } public void toFile (String file) { try { File out = new File(file); OutputStream os = new FileOutputStream(out); ZipOutputStream zip = new ZipOutputStream(os); // write everything // TODO: fare attributes, fare rules, shapes // don't write empty feed_info.txt if (!this.feedInfo.isEmpty()) new FeedInfo.Writer(this).writeTable(zip); new Agency.Writer(this).writeTable(zip); new Calendar.Writer(this).writeTable(zip); new CalendarDate.Writer(this).writeTable(zip); new Frequency.Writer(this).writeTable(zip); new Route.Writer(this).writeTable(zip); new Stop.Writer(this).writeTable(zip); new ShapePoint.Writer(this).writeTable(zip); new Transfer.Writer(this).writeTable(zip); new Trip.Writer(this).writeTable(zip); new StopTime.Writer(this).writeTable(zip); zip.close(); LOG.info("GTFS file written"); } catch (Exception e) { LOG.error("Error saving GTFS: {}", e.getMessage()); throw new RuntimeException(e); } } // public void validate (EventBus eventBus, GTFSValidator... validators) { // if (eventBus == null) { // for (GTFSValidator validator : validators) { // validator.getClass().getSimpleName(); // validator.validate(this, false); public void validate (boolean repair, GTFSValidator... validators) { long startValidation = System.currentTimeMillis(); for (GTFSValidator validator : validators) { try { long startValidator = System.currentTimeMillis(); validator.validate(this, repair); long endValidator = System.currentTimeMillis(); long diff = endValidator - startValidator; LOG.info("{} finished in {} milliseconds.", validator.getClass().getSimpleName(), diff); } catch (Exception e) { LOG.error("Could not run {} validator.", validator.getClass().getSimpleName()); // LOG.error(e.toString()); e.printStackTrace(); } } long endValidation = System.currentTimeMillis(); long total = endValidation - startValidation; LOG.info("{} validators completed in {} milliseconds.", validators.length, total); } // validate function call that should explicitly list each validator to run on GTFSFeed public void validate () { validate(false, new DuplicateStopsValidator(), new HopSpeedsReasonableValidator(), new MisplacedStopValidator(), new MissingStopCoordinatesValidator(), new NamesValidator(), new OverlappingTripsValidator(), new ReversedTripsValidator(), new TripTimesValidator(), new UnusedStopValidator() ); } public void validateAndRepair () { validate(true, new DuplicateStopsValidator(), new HopSpeedsReasonableValidator(), new MisplacedStopValidator(), new MissingStopCoordinatesValidator(), new NamesValidator(), new OverlappingTripsValidator(), new ReversedTripsValidator(), new TripTimesValidator(), new UnusedStopValidator() ); } public FeedStats calculateStats() { FeedStats feedStats = new FeedStats(this); return feedStats; } public static GTFSFeed fromFile(String file) { return fromFile(file, null); } public static GTFSFeed fromFile(String file, String feedId) { GTFSFeed feed = new GTFSFeed(); ZipFile zip; try { zip = new ZipFile(file); if (feedId == null) { feed.loadFromFile(zip); } else { feed.loadFromFile(zip, feedId); } zip.close(); return feed; } catch (Exception e) { LOG.error("Error loading GTFS: {}", e.getMessage()); throw new RuntimeException(e); } } /** * For the given trip ID, fetch all the stop times in order of increasing stop_sequence. * This is an efficient iteration over a tree map. */ public Iterable<StopTime> getOrderedStopTimesForTrip (String trip_id) { Map<Fun.Tuple2, StopTime> tripStopTimes = stop_times.subMap( Fun.t2(trip_id, null), Fun.t2(trip_id, Fun.HI) ); return tripStopTimes.values(); } public STRtree getSpatialIndex () { if (this.spatialIndex == null) { synchronized (this) { if (this.spatialIndex == null) { // build spatial index STRtree stopIndex = new STRtree(); for(Stop stop : this.stops.values()) { try { if (Double.isNaN(stop.stop_lat) || Double.isNaN(stop.stop_lon)) { continue; } Coordinate stopCoord = new Coordinate(stop.stop_lat, stop.stop_lon); stopIndex.insert(new Envelope(stopCoord), stop); } catch (Exception e) { e.printStackTrace(); } } try { stopIndex.build(); this.spatialIndex = stopIndex; } catch (Exception e) { e.printStackTrace(); } } } } return this.spatialIndex; } /** Get the shape for the given shape ID */ public Shape getShape (String shape_id) { Shape shape = new Shape(this, shape_id); return shape.shape_dist_traveled.length > 0 ? shape : null; } /** * For the given trip ID, fetch all the stop times in order, and interpolate stop-to-stop travel times. */ public Iterable<StopTime> getInterpolatedStopTimesForTrip (String trip_id) throws FirstAndLastStopsDoNotHaveTimes { // clone stop times so as not to modify base GTFS structures StopTime[] stopTimes = StreamSupport.stream(getOrderedStopTimesForTrip(trip_id).spliterator(), false) .map(st -> st.clone()) .toArray(i -> new StopTime[i]); // avoid having to make sure that the array has length below. if (stopTimes.length == 0) return Collections.emptyList(); // first pass: set all partially filled stop times for (StopTime st : stopTimes) { if (st.arrival_time != Entity.INT_MISSING && st.departure_time == Entity.INT_MISSING) { st.departure_time = st.arrival_time; } if (st.arrival_time == Entity.INT_MISSING && st.departure_time != Entity.INT_MISSING) { st.arrival_time = st.departure_time; } } // quick check: ensure that first and last stops have times. // technically GTFS requires that both arrival_time and departure_time be filled at both the first and last stop, // but we are slightly more lenient and only insist that one of them be filled at both the first and last stop. // The meaning of the first stop's arrival time is unclear, and same for the last stop's departure time (except // in the case of interlining). // it's fine to just check departure time, as the above pass ensures that all stop times have either both // arrival and departure times, or neither if (stopTimes[0].departure_time == Entity.INT_MISSING || stopTimes[stopTimes.length - 1].departure_time == Entity.INT_MISSING) { throw new FirstAndLastStopsDoNotHaveTimes(); } // second pass: fill complete stop times int startOfInterpolatedBlock = -1; for (int stopTime = 0; stopTime < stopTimes.length; stopTime++) { if (stopTimes[stopTime].departure_time == Entity.INT_MISSING && startOfInterpolatedBlock == -1) { startOfInterpolatedBlock = stopTime; } else if (stopTimes[stopTime].departure_time != Entity.INT_MISSING && startOfInterpolatedBlock != -1) { // we have found the end of the interpolated section int nInterpolatedStops = stopTime - startOfInterpolatedBlock; double totalLengthOfInterpolatedSection = 0; double[] lengthOfInterpolatedSections = new double[nInterpolatedStops]; GeodeticCalculator calc = new GeodeticCalculator(); for (int stopTimeToInterpolate = startOfInterpolatedBlock, i = 0; stopTimeToInterpolate < stopTime; stopTimeToInterpolate++, i++) { Stop start = stops.get(stopTimes[stopTimeToInterpolate - 1].stop_id); Stop end = stops.get(stopTimes[stopTimeToInterpolate].stop_id); calc.setStartingGeographicPoint(start.stop_lon, start.stop_lat); calc.setDestinationGeographicPoint(end.stop_lon, end.stop_lat); double segLen = calc.getOrthodromicDistance(); totalLengthOfInterpolatedSection += segLen; lengthOfInterpolatedSections[i] = segLen; } // add the segment post-last-interpolated-stop Stop start = stops.get(stopTimes[stopTime - 1].stop_id); Stop end = stops.get(stopTimes[stopTime].stop_id); calc.setStartingGeographicPoint(start.stop_lon, start.stop_lat); calc.setDestinationGeographicPoint(end.stop_lon, end.stop_lat); totalLengthOfInterpolatedSection += calc.getOrthodromicDistance(); int departureBeforeInterpolation = stopTimes[startOfInterpolatedBlock - 1].departure_time; int arrivalAfterInterpolation = stopTimes[stopTime].arrival_time; int totalTime = arrivalAfterInterpolation - departureBeforeInterpolation; double lengthSoFar = 0; for (int stopTimeToInterpolate = startOfInterpolatedBlock, i = 0; stopTimeToInterpolate < stopTime; stopTimeToInterpolate++, i++) { lengthSoFar += lengthOfInterpolatedSections[i]; int time = (int) (departureBeforeInterpolation + totalTime * (lengthSoFar / totalLengthOfInterpolatedSection)); stopTimes[stopTimeToInterpolate].arrival_time = stopTimes[stopTimeToInterpolate].departure_time = time; } // we're done with this block startOfInterpolatedBlock = -1; } } return Arrays.asList(stopTimes); } public Collection<Frequency> getFrequencies (String trip_id) { // IntelliJ tells me all these casts are unnecessary, and that's also my feeling, but the code won't compile // without them return (List<Frequency>) frequencies.subSet(new Fun.Tuple2(trip_id, null), new Fun.Tuple2(trip_id, Fun.HI)).stream() .map(t2 -> ((Tuple2<String, Frequency>) t2).b) .collect(Collectors.toList()); } public List<String> getOrderedStopListForTrip (String trip_id) { Iterable<StopTime> orderedStopTimes = getOrderedStopTimesForTrip(trip_id); List<String> stops = Lists.newArrayList(); // In-order traversal of StopTimes within this trip. The 2-tuple keys determine ordering. for (StopTime stopTime : orderedStopTimes) { stops.add(stopTime.stop_id); } return stops; } /** * Bin all trips by the sequence of stops they visit. * @return A map from a list of stop IDs to a list of Trip IDs that visit those stops in that sequence. */ public void findPatterns() { int n = 0; Multimap<TripPatternKey, String> tripsForPattern = HashMultimap.create(); for (String trip_id : trips.keySet()) { if (++n % 100000 == 0) { LOG.info("trip {}", human(n)); } Trip trip = trips.get(trip_id); // no need to scope ID here, this is in the context of a single object TripPatternKey key = new TripPatternKey(trip.route_id); StreamSupport.stream(getOrderedStopTimesForTrip(trip_id).spliterator(), false) .forEach(key::addStopTime); tripsForPattern.put(key, trip_id); } // create an in memory list because we will rename them and they need to be immutable once they hit mapdb List<Pattern> patterns = tripsForPattern.asMap().entrySet() .stream() .map((e) -> new Pattern(this, e.getKey().stops, new ArrayList<>(e.getValue()))) .collect(Collectors.toList()); namePatterns(patterns); patterns.stream().forEach(p -> { this.patterns.put(p.pattern_id, p); p.associatedTrips.stream().forEach(t -> this.tripPatternMap.put(t, p.pattern_id)); }); LOG.info("Total patterns: {}", tripsForPattern.keySet().size()); } /** destructively rename passed in patterns */ private void namePatterns(Collection<Pattern> patterns) { LOG.info("Generating unique names for patterns"); Map<String, PatternNamingInfo> namingInfoForRoute = new HashMap<>(); for (Pattern pattern : patterns) { if (pattern.associatedTrips.isEmpty() || pattern.orderedStops.isEmpty()) continue; Trip trip = trips.get(pattern.associatedTrips.get(0)); // TODO this assumes there is only one route associated with a pattern String route = trip.route_id; // names are unique at the route level if (!namingInfoForRoute.containsKey(route)) namingInfoForRoute.put(route, new PatternNamingInfo()); PatternNamingInfo namingInfo = namingInfoForRoute.get(route); if (trip.trip_headsign != null) namingInfo.headsigns.put(trip.trip_headsign, pattern); // use stop names not stop IDs as stops may have duplicate names and we want unique pattern names String fromName = stops.get(pattern.orderedStops.get(0)).stop_name; String toName = stops.get(pattern.orderedStops.get(pattern.orderedStops.size() - 1)).stop_name; namingInfo.fromStops.put(fromName, pattern); namingInfo.toStops.put(toName, pattern); pattern.orderedStops.stream().map(stops::get).forEach(stop -> { if (fromName.equals(stop.stop_name) || toName.equals(stop.stop_name)) return; namingInfo.vias.put(stop.stop_name, pattern); }); namingInfo.patternsOnRoute.add(pattern); } // name the patterns on each route for (PatternNamingInfo info : namingInfoForRoute.values()) { for (Pattern pattern : info.patternsOnRoute) { pattern.name = null; // clear this now so we don't get confused later on String headsign = trips.get(pattern.associatedTrips.get(0)).trip_headsign; String fromName = stops.get(pattern.orderedStops.get(0)).stop_name; String toName = stops.get(pattern.orderedStops.get(pattern.orderedStops.size() - 1)).stop_name; /* We used to use this code but decided it is better to just always have the from/to info, with via if necessary. if (headsign != null && info.headsigns.get(headsign).size() == 1) { // easy, unique headsign, we're done pattern.name = headsign; continue; } if (info.toStops.get(toName).size() == 1) { pattern.name = String.format(Locale.US, "to %s", toName); continue; } if (info.fromStops.get(fromName).size() == 1) { pattern.name = String.format(Locale.US, "from %s", fromName); continue; } */ // check if combination from, to is unique Set<Pattern> intersection = new HashSet<>(info.fromStops.get(fromName)); intersection.retainAll(info.toStops.get(toName)); if (intersection.size() == 1) { pattern.name = String.format(Locale.US, "from %s to %s", fromName, toName); continue; } // check for unique via stop pattern.orderedStops.stream().map(stops::get).forEach(stop -> { Set<Pattern> viaIntersection = new HashSet<>(intersection); viaIntersection.retainAll(info.vias.get(stop.stop_name)); if (viaIntersection.size() == 1) { pattern.name = String.format(Locale.US, "from %s to %s via %s", fromName, toName, stop.stop_name); } }); if (pattern.name == null) { // no unique via, one pattern is subset of other. if (intersection.size() == 2) { Iterator<Pattern> it = intersection.iterator(); Pattern p0 = it.next(); Pattern p1 = it.next(); if (p0.orderedStops.size() > p1.orderedStops.size()) { p1.name = String.format(Locale.US, "from %s to %s express", fromName, toName); p0.name = String.format(Locale.US, "from %s to %s local", fromName, toName); } else if (p1.orderedStops.size() > p0.orderedStops.size()){ p0.name = String.format(Locale.US, "from %s to %s express", fromName, toName); p1.name = String.format(Locale.US, "from %s to %s local", fromName, toName); } } } if (pattern.name == null) { // give up pattern.name = String.format(Locale.US, "from %s to %s like trip %s", fromName, toName, pattern.associatedTrips.get(0)); } } // attach a stop and trip count to each for (Pattern pattern : info.patternsOnRoute) { pattern.name = String.format(Locale.US, "%s stops %s (%s trips)", pattern.orderedStops.size(), pattern.name, pattern.associatedTrips.size()); } } } public LineString getStraightLineForStops(String trip_id) { CoordinateList coordinates = new CoordinateList(); LineString ls = null; Trip trip = trips.get(trip_id); Iterable<StopTime> stopTimes; stopTimes = getOrderedStopTimesForTrip(trip.trip_id); if (Iterables.size(stopTimes) > 1) { for (StopTime stopTime : stopTimes) { Stop stop = stops.get(stopTime.stop_id); Double lat = stop.stop_lat; Double lon = stop.stop_lon; coordinates.add(new Coordinate(lon, lat)); } ls = gf.createLineString(coordinates.toCoordinateArray()); } // set ls equal to null if there is only one stopTime to avoid an exception when creating linestring else{ ls = null; } return ls; } /** * Returns a trip geometry object (LineString) for a given trip id. * If the trip has a shape reference, this will be used for the geometry. * Otherwise, the ordered stoptimes will be used. * * @param trip_id trip id of desired trip geometry * @return the LineString representing the trip geometry. * @see LineString */ public LineString getTripGeometry(String trip_id){ CoordinateList coordinates = new CoordinateList(); LineString ls = null; Trip trip = trips.get(trip_id); // If trip has shape_id, use it to generate geometry. if (trip.shape_id != null) { Shape shape = getShape(trip.shape_id); if (shape != null) ls = shape.geometry; } // Use the ordered stoptimes. if (ls == null) { ls = getStraightLineForStops(trip_id); } return ls; } /** Get the length of a trip in meters. */ public double getTripDistance (String trip_id, boolean straightLine) { return straightLine ? GeoUtils.getDistance(this.getStraightLineForStops(trip_id)) : GeoUtils.getDistance(this.getTripGeometry(trip_id)); } /** Get trip speed (using trip shape if available) in meters per second. */ public double getTripSpeed (String trip_id) { return getTripSpeed(trip_id, false); } /** Get trip speed in meters per second. */ public double getTripSpeed (String trip_id, boolean straightLine) { StopTime firstStopTime = this.stop_times.ceilingEntry(Fun.t2(trip_id, null)).getValue(); StopTime lastStopTime = this.stop_times.floorEntry(Fun.t2(trip_id, Fun.HI)).getValue(); // ensure that stopTime returned matches trip id (i.e., that the trip has stoptimes) if (!firstStopTime.trip_id.equals(trip_id) || !lastStopTime.trip_id.equals(trip_id)) { return Double.NaN; } double distance = getTripDistance(trip_id, straightLine); // trip time (in seconds) int time = lastStopTime.arrival_time - firstStopTime.departure_time; return distance / time; // meters per second } /** Get list of stop_times ordered by arrival time for a given stop_id. */ public List<StopTime> getStopTimesForStop (String stop_id) { SortedSet<Tuple2<String, Tuple2>> index = this.stopStopTimeSet .subSet(new Tuple2<>(stop_id, null), new Tuple2(stop_id, Fun.HI)); return index.stream() .map(tuple -> this.stop_times.get(tuple.b)) .sorted((a, b) -> Integer.compare(a.arrival_time, b.arrival_time)) .collect(Collectors.toList()); } /** Get list of distinct trips (filters out multiple visits by a trip) a given stop_id. */ public List<Trip> getDistinctTripsForStop (String stop_id) { return getStopTimesForStop(stop_id).stream() .map(stopTime -> this.trips.get(stopTime.trip_id)) .distinct() .collect(Collectors.toList()); } /** Get the likely time zone for a stop using the agency of the first stop time encountered for the stop. */ public ZoneId getAgencyTimeZoneForStop (String stop_id) { StopTime stopTime = getStopTimesForStop(stop_id).iterator().next(); Trip trip = this.trips.get(stopTime.trip_id); Route route = this.routes.get(trip.route_id); Agency agency = route.agency_id != null ? this.agency.get(route.agency_id) : this.agency.get(0); return ZoneId.of(agency.agency_timezone); } // TODO: code review public Geometry getMergedBuffers() { if (this.mergedBuffers == null) { // synchronized (this) { Collection<Geometry> polygons = new ArrayList<>(); for (Stop stop : this.stops.values()) { if (stopCountByStopTime != null && !stopCountByStopTime.containsKey(stop.stop_id)) { continue; } if (stop.stop_lat > -1 && stop.stop_lat < 1 || stop.stop_lon > -1 && stop.stop_lon < 1) { continue; } Point stopPoint = gf.createPoint(new Coordinate(stop.stop_lon, stop.stop_lat)); Polygon stopBuffer = (Polygon) stopPoint.buffer(.01); polygons.add(stopBuffer); } Geometry multiGeometry = gf.buildGeometry(polygons); this.mergedBuffers = multiGeometry.union(); if (polygons.size() > 100) { this.mergedBuffers = DouglasPeuckerSimplifier.simplify(this.mergedBuffers, .001); } } return this.mergedBuffers; } public Polygon getConvexHull() { if (this.convexHull == null) { synchronized (this) { List<Coordinate> coordinates = this.stops.values().stream().map( stop -> new Coordinate(stop.stop_lon, stop.stop_lat) ).collect(Collectors.toList()); Coordinate[] coords = coordinates.toArray(new Coordinate[coordinates.size()]); ConvexHull convexHull = new ConvexHull(coords, gf); this.convexHull = (Polygon) convexHull.getConvexHull(); } } return this.convexHull; } /** * Cloning can be useful when you want to make only a few modifications to an existing feed. * Keep in mind that this is a shallow copy, so you'll have to create new maps in the clone for tables you want * to modify. */ @Override public GTFSFeed clone() { try { return (GTFSFeed) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } public void close () { db.close(); } /** Thrown when we cannot interpolate stop times because the first or last stops do not have times */ public class FirstAndLastStopsDoNotHaveTimes extends Exception { /** do nothing */ } private static class PatternNamingInfo { Multimap<String, Pattern> headsigns = HashMultimap.create(); Multimap<String, Pattern> fromStops = HashMultimap.create(); Multimap<String, Pattern> toStops = HashMultimap.create(); Multimap<String, Pattern> vias = HashMultimap.create(); List<Pattern> patternsOnRoute = new ArrayList<>(); } /** Create a GTFS feed in a temp file */ public GTFSFeed () { // calls to this must be first operation in constructor - why, Java? this(DBMaker.newTempFileDB() .transactionDisable() .mmapFileEnable() .asyncWriteEnable() .deleteFilesAfterClose() .compressionEnable() // .cacheSize(1024 * 1024) this bloats memory consumption .make()); // TODO db.close(); } /** Create a GTFS feed connected to a particular DB, which will be created if it does not exist. */ public GTFSFeed (String dbFile) { this(DBMaker.newFileDB(new File(dbFile)) .transactionDisable() .mmapFileEnable() .asyncWriteEnable() .compressionEnable() // .cacheSize(1024 * 1024) this bloats memory consumption .make()); // TODO db.close(); } private GTFSFeed (DB db) { this.db = db; agency = db.getTreeMap("agency"); feedInfo = db.getTreeMap("feed_info"); routes = db.getTreeMap("routes"); trips = db.getTreeMap("trips"); stop_times = db.getTreeMap("stop_times"); frequencies = db.getTreeSet("frequencies"); transfers = db.getTreeMap("transfers"); stops = db.getTreeMap("stops"); fares = db.getTreeMap("fares"); services = db.getTreeMap("services"); shape_points = db.getTreeMap("shape_points"); feedId = db.getAtomicString("feed_id").get(); checksum = db.getAtomicLong("checksum").get(); // use Java serialization because MapDB serialization is very slow with JTS as they have a lot of references. // nothing else contains JTS objects patterns = db.createTreeMap("patterns") .valueSerializer(Serializer.JAVA) .makeOrGet(); tripPatternMap = db.getTreeMap("patternForTrip"); stopCountByStopTime = db.getTreeMap("stopCountByStopTime"); stopStopTimeSet = db.getTreeSet("stopStopTimeSet"); errors = db.getTreeSet("errors"); } }
package com.sequenceiq.it.cloudbreak.action.sdx; import java.util.Collections; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.sequenceiq.it.cloudbreak.SdxClient; import com.sequenceiq.it.cloudbreak.action.Action; import com.sequenceiq.it.cloudbreak.context.TestContext; import com.sequenceiq.it.cloudbreak.dto.sdx.SdxTestDto; import com.sequenceiq.it.cloudbreak.log.Log; import com.sequenceiq.sdx.api.model.SdxClusterDetailResponse; import com.sequenceiq.sdx.api.model.SdxClusterResponse; public class SdxCreateAction implements Action<SdxTestDto, SdxClient> { private static final Logger LOGGER = LoggerFactory.getLogger(SdxCreateAction.class); @Override public SdxTestDto action(TestContext testContext, SdxTestDto testDto, SdxClient client) throws Exception { Log.when(LOGGER, " SDX endpoint: %s" + client.getSdxClient().sdxEndpoint() + ", SDX's environment: " + testDto.getRequest().getEnvironment()); Log.whenJson(LOGGER, " SDX create request: ", testDto.getRequest()); SdxClusterResponse sdxClusterResponse = client.getSdxClient() .sdxEndpoint() .create(testDto.getName(), testDto.getRequest()); testDto.setFlow("SDX create", sdxClusterResponse.getFlowIdentifier()); SdxClusterDetailResponse detailedResponse = client.getSdxClient() .sdxEndpoint() .getDetailByCrn(sdxClusterResponse.getCrn(), Collections.emptySet()); testDto.setResponse(detailedResponse); Log.whenJson(LOGGER, " SDX create response: ", client.getSdxClient().sdxEndpoint().get(testDto.getName())); return testDto; } }
package com.google.appengine; import java.io.File; /** * * @author ludo */ public class Utils { public static String getPythonExecutableLocation() { String pythonLocation = "python"; //default in the path for Linux boolean isWindows = System.getProperty("os.name").contains("Windows"); if (isWindows) { pythonLocation = System.getenv("CLOUDSDK_PYTHON"); if (pythonLocation == null) { // getLog().info("CLOUDSDK_PYTHON env variable is not defined. Choosing a default python.exe interpreter."); // getLog().info("If this does not work, please set CLOUDSDK_PYTHON to a correct Python interpreter location."); pythonLocation = "python.exe"; } } else { String possibleLinuxPythonLocation = System.getenv("CLOUDSDK_PYTHON"); if (possibleLinuxPythonLocation != null) { // getLog().info("Found a python interpreter specified via CLOUDSDK_PYTHON at: " + possibleLinuxPythonLocation); pythonLocation = possibleLinuxPythonLocation; } } return pythonLocation; } public static String getCloudSDKLocation() { String gcloudDir; boolean isWindows = System.getProperty("os.name").contains("Windows"); if (isWindows) { String programFiles = System.getenv("ProgramFiles"); if (programFiles == null) { programFiles = System.getenv("ProgramFiles(x86)"); } if (programFiles == null) { gcloudDir = "cannotFindProgramFiles"; } else { gcloudDir = programFiles + "\\Google\\Cloud SDK\\google-cloud-sdk"; } } else { gcloudDir = System.getProperty("user.home") + "/google-cloud-sdk"; if (!new File(gcloudDir).exists()) { // try devshell VM: gcloudDir = "/google/google-cloud-sdk"; if (!new File(gcloudDir).exists()) { // try bitnani Jenkins VM: gcloudDir = "/usr/local/share/google/google-cloud-sdk"; } } } return gcloudDir; } /** * Checks if either CLOUDSDK_PYTHON_SITEPACKAGES or VIRTUAL_ENV is defined. * * <p> If either variable is defined, we shall not disable import of module * 'site. * * @return true if it is OK to disable import of module 'site' (python -S) */ public static boolean canDisableImportOfPythonModuleSite() { String sitePackages = System.getenv("CLOUDSDK_PYTHON_SITEPACKAGES"); String virtualEnv = System.getenv("VIRTUAL_ENV"); boolean noSiteDefined = sitePackages == null || sitePackages.isEmpty(); boolean noVirtEnvDefined = virtualEnv == null || virtualEnv.isEmpty(); if (noSiteDefined && noVirtEnvDefined) { return true; } return false; } }
package seedu.ezdo.model; import java.util.EmptyStackException; /* * Array-based implementation for a stack with fixed size. Used for undo & redo stacks. * If stack goes past max capacity, the oldest item to be pushed is replaced. */ public class FixedStack<T> { private int index; private T[] array; public FixedStack(int capacity) { array = (T[]) new Object[capacity]; index = -1; } public void push(T item) { index = (index + 1) % ModelManager.STACK_CAPACITY; // wraps around array[index] = item; } public T pop() throws EmptyStackException { if (index == -1 || array[index] == null) { throw new EmptyStackException(); } T item = array[index]; array[index] = null; if (index == 0) { index = array.length - 1; } else { index = index - 1; } return item; } public boolean isEmpty() { for (int i = 0; i < array.length; i++) { if (array[i] != null) { return false; } } return true; } public void clear() { for (int i = 0; i < array.length; i++) { array[i] = null; } index = -1; } }
package com.sequenceiq.it.cloudbreak.testcase.mock; import static com.sequenceiq.it.cloudbreak.cloud.HostGroupType.IDBROKER; import static com.sequenceiq.it.cloudbreak.cloud.HostGroupType.MASTER; import static com.sequenceiq.it.cloudbreak.context.RunningParameter.key; import java.io.IOException; import java.util.List; import java.util.Optional; import javax.inject.Inject; import org.json.JSONObject; import org.testng.annotations.Test; import com.sequenceiq.cloudbreak.api.endpoint.v4.stacks.request.customdomain.CustomDomainSettingsV4Request; import com.sequenceiq.environment.api.v1.environment.model.EnvironmentNetworkMockParams; import com.sequenceiq.environment.api.v1.environment.model.response.EnvironmentStatus; import com.sequenceiq.it.cloudbreak.client.SdxTestClient; import com.sequenceiq.it.cloudbreak.context.Description; import com.sequenceiq.it.cloudbreak.context.MockedTestContext; import com.sequenceiq.it.cloudbreak.context.TestContext; import com.sequenceiq.it.cloudbreak.dto.environment.EnvironmentNetworkTestDto; import com.sequenceiq.it.cloudbreak.dto.environment.EnvironmentTestDto; import com.sequenceiq.it.cloudbreak.dto.sdx.SdxInternalTestDto; import com.sequenceiq.it.cloudbreak.testcase.AbstractIntegrationTest; import com.sequenceiq.it.cloudbreak.util.SdxUtil; import com.sequenceiq.it.cloudbreak.util.wait.WaitUtil; import com.sequenceiq.it.util.ResourceUtil; import com.sequenceiq.sdx.api.model.SdxClusterStatusResponse; import com.sequenceiq.sdx.api.model.SdxDatabaseAvailabilityType; import com.sequenceiq.sdx.api.model.SdxDatabaseRequest; public class MockSdxTests extends AbstractIntegrationTest { private static final String TEMPLATE_JSON = "classpath:/templates/sdx-cluster-template.json"; @Inject private SdxTestClient sdxTestClient; @Inject private WaitUtil waitUtil; @Inject private SdxUtil sdxUtil; protected void setupTest(TestContext testContext) { createDefaultUser(testContext); createDefaultCredential(testContext); createDefaultImageCatalog(testContext); initializeDefaultBlueprints(testContext); } @Test(dataProvider = TEST_CONTEXT_WITH_MOCK) @Description( given = "there is a running Cloudbreak", when = "a valid SDX Internal Create request is sent", then = "SDX should be available AND deletable" ) public void testDefaultSDXCanBeCreatedThenDeletedSuccessfully(MockedTestContext testContext) { String sdxInternal = resourcePropertyProvider().getName(); String envKey = "sdxEnvKey"; String networkKey = "someNetwork"; testContext .given(networkKey, EnvironmentNetworkTestDto.class) .withMock(new EnvironmentNetworkMockParams()) .given(envKey, EnvironmentTestDto.class) .withNetwork(networkKey) .withCreateFreeIpa(Boolean.FALSE) .withName(resourcePropertyProvider().getEnvironmentName()) .when(getEnvironmentTestClient().create()) .await(EnvironmentStatus.AVAILABLE) .given(sdxInternal, SdxInternalTestDto.class) .withDefaultSDXSettings(Optional.of(testContext.getSparkServer().getPort())) .withEnvironmentKey(key(envKey)) .when(sdxTestClient.createInternal(), key(sdxInternal)) .awaitForFlow(key(sdxInternal)) .await(SdxClusterStatusResponse.RUNNING) .then((tc, testDto, client) -> sdxTestClient.deleteInternal().action(tc, testDto, client)) .awaitForFlow(key(sdxInternal)) .await(SdxClusterStatusResponse.DELETED) .validate(); } @Test(dataProvider = TEST_CONTEXT_WITH_MOCK) @Description( given = "there is a running Cloudbreak", when = "a valid SDX Internal Create request is sent with Cluster Template", then = "SDX should be available AND deletable" ) public void testSDXFromTemplateCanBeCreatedThenDeletedSuccessfully(MockedTestContext testContext) throws IOException { String sdxInternal = resourcePropertyProvider().getName(); String networkKey = "someOtherNetwork"; String envKey = "sdxEnvKey"; JSONObject jsonObject = ResourceUtil.readResourceAsJson(applicationContext, TEMPLATE_JSON); testContext .given(networkKey, EnvironmentNetworkTestDto.class) .withMock(new EnvironmentNetworkMockParams()) .given(envKey, EnvironmentTestDto.class) .withNetwork(networkKey) .withCreateFreeIpa(Boolean.FALSE) .withName(resourcePropertyProvider().getEnvironmentName()) .when(getEnvironmentTestClient().create()) .await(EnvironmentStatus.AVAILABLE) .given(sdxInternal, SdxInternalTestDto.class) .withTemplate(jsonObject) .withEnvironmentKey(key(envKey)) .when(sdxTestClient.createInternal(), key(sdxInternal)) .awaitForFlow(key(sdxInternal)) .await(SdxClusterStatusResponse.RUNNING) .then((tc, testDto, client) -> sdxTestClient.deleteInternal().action(tc, testDto, client)) .awaitForFlow(key(sdxInternal)) .await(SdxClusterStatusResponse.DELETED) .validate(); } @Test(dataProvider = TEST_CONTEXT_WITH_MOCK) @Description( given = "there is a running Cloudbreak", when = "start an sdx cluster", then = "SDX should be available" ) public void testSdxStopStart(MockedTestContext testContext) { String sdxInternal = resourcePropertyProvider().getName(); String networkKey = "someOtherNetwork"; String envKey = "sdxEnvKey"; testContext .given(networkKey, EnvironmentNetworkTestDto.class) .withMock(new EnvironmentNetworkMockParams()) .given(envKey, EnvironmentTestDto.class) .withNetwork(networkKey) .withCreateFreeIpa(Boolean.FALSE) .withName(resourcePropertyProvider().getEnvironmentName()) .when(getEnvironmentTestClient().create()) .await(EnvironmentStatus.AVAILABLE) .given(sdxInternal, SdxInternalTestDto.class) .withDefaultSDXSettings(Optional.of(testContext.getSparkServer().getPort())) .withEnvironmentKey(key(envKey)) .when(sdxTestClient.createInternal(), key(sdxInternal)) .awaitForFlow(key(sdxInternal)) .await(SdxClusterStatusResponse.RUNNING) .when(sdxTestClient.stopInternal()) .awaitForFlow(key(sdxInternal)) .await(SdxClusterStatusResponse.STOPPED) .when(sdxTestClient.startInternal()) .awaitForFlow(key(sdxInternal)) .await(SdxClusterStatusResponse.RUNNING) .validate(); } @Test(dataProvider = TEST_CONTEXT_WITH_MOCK) @Description( given = "there is a running Cloudbreak", when = "stop and repair an sdx cluster", then = "SDX should be available" ) public void testSdxRepairWithTerminatedMasterAndIdbroker(MockedTestContext testContext) { String sdxInternal = resourcePropertyProvider().getName(); String networkKey = "someOtherNetwork"; String envKey = "sdxEnvKey"; SdxDatabaseRequest sdxDatabaseRequest = new SdxDatabaseRequest(); sdxDatabaseRequest.setAvailabilityType(SdxDatabaseAvailabilityType.NON_HA); CustomDomainSettingsV4Request customDomain = new CustomDomainSettingsV4Request(); customDomain.setDomainName("dummydomainname"); customDomain.setHostname("dummyhostname"); customDomain.setClusterNameAsSubdomain(true); customDomain.setHostgroupNameAsHostname(true); testContext .given(networkKey, EnvironmentNetworkTestDto.class) .withMock(new EnvironmentNetworkMockParams()) .given(envKey, EnvironmentTestDto.class) .withNetwork(networkKey) .withCreateFreeIpa(Boolean.FALSE) .withName(resourcePropertyProvider().getEnvironmentName()) .when(getEnvironmentTestClient().create()) .await(EnvironmentStatus.AVAILABLE) .given(sdxInternal, SdxInternalTestDto.class) .withDefaultSDXSettings(Optional.of(testContext.getSparkServer().getPort())) .withDatabase(sdxDatabaseRequest) .withCustomDomain(customDomain) .withEnvironmentKey(key(envKey)) .when(sdxTestClient.createInternal(), key(sdxInternal)) .awaitForFlow(key(sdxInternal)) .await(SdxClusterStatusResponse.RUNNING) .then((tc, testDto, client) -> { List<String> instancesToDelete = sdxUtil.getInstanceIds(testDto, client, MASTER.getName()); instancesToDelete.addAll(sdxUtil.getInstanceIds(testDto, client, IDBROKER.getName())); instancesToDelete.forEach(id -> testContext.getModel().terminateInstance(testContext.getModel().getInstanceMap(), id)); return testDto; }) .await(SdxClusterStatusResponse.DELETED_ON_PROVIDER_SIDE) .when(sdxTestClient.repairInternal()) .awaitForFlow(key(sdxInternal)) .await(SdxClusterStatusResponse.RUNNING) .validate(); } }
package com.hkamran.mocking; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpObject; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpResponse; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import org.apache.commons.lang3.time.StopWatch; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.json.JSONObject; import org.littleshoot.proxy.HttpFilters; import org.littleshoot.proxy.HttpFiltersAdapter; import org.littleshoot.proxy.HttpFiltersSourceAdapter; import com.hkamran.mocking.servers.WebSocket; /** * This class handles the logic of filtering requests * and responses. It determines whether to return a mocked response, record * or just allow through each request. * * @author Hooman Kamran */ public class Filter extends HttpFiltersSourceAdapter { private final static Logger log = LogManager.getLogger(Filter.class); private static final int MAX_SIZE = 8388608; private Tape tape; public Set<Request> tmp = new HashSet<Request>(); private List<Event> events = new ArrayList<Event>(); private Integer counter = 0; public State state = Filter.State.PROXY; public String host = "localhost"; public Integer port = 80; public Boolean redirect = true; public Boolean recordMock = false; public Integer id; public static enum State { MOCK, PROXY, RECORD; } public Filter(Integer id) { this.id = id; this.tape = new Tape(); } @Override public HttpFilters filterRequest(HttpRequest originalRequest) { return new HttpFiltersAdapter(originalRequest) { Request req; Response res; StopWatch watch; @Override public HttpResponse clientToProxyRequest(HttpObject httpObject) { log.info("handling pre-request"); try { if (httpObject instanceof FullHttpRequest) { FullHttpRequest httpFullObj = (FullHttpRequest) httpObject; if (redirect) { HttpHeaders headers = httpFullObj.headers(); headers.set("Host", host + ":" + port); } } } catch (Exception e) { e.printStackTrace(); } return null; } @Override public HttpResponse proxyToServerRequest(HttpObject httpObject) { log.info("handling post-request"); try { if (httpObject instanceof FullHttpRequest) { FullHttpRequest httpFullObj = (FullHttpRequest) httpObject; req = new Request(httpFullObj, state); log.info("Request incoming: " + req.hashCode()); watch = new StopWatch(); watch.start(); if (state == State.PROXY) { // No need } else if (state == State.MOCK) { if (!tmp.contains(req) && tape.hasRequest(req)) { HttpResponse response = sendToMock(req, watch); if (!redirect && response == null) { return handleNoRedirect(); } return response; } else { if (recordMock) { tmp.add(req); } } } else if (state == State.RECORD) { // No Need } if (!redirect) { return handleNoRedirect(); } addEvent(counter, res, req, watch); } else { throw new RuntimeException("HttpObject is not " + FullHttpRequest.class); } } catch (Exception e) { e.printStackTrace(); } return null; } private HttpResponse handleNoRedirect() { Map<String, String> headers = new HashMap<String, String>(); String content = ""; String protocol = "HTTP/1.1"; Integer status = 500; State resState = state; Response response = new Response(headers, content, protocol, status, resState); this.res = response; this.res.setParent(req.hashCode()); if (state == State.RECORD) { sendToRecorder(res, req); } try { watch.stop(); } catch (IllegalStateException e) {} addEvent(counter, res, req, watch); return response.getHTTPObject(); } @Override public HttpObject serverToProxyResponse(HttpObject httpObject) { log.info("handling post-response"); try { if (httpObject instanceof FullHttpResponse) { FullHttpResponse httpFullObj = (FullHttpResponse) httpObject; res = new Response(httpFullObj, state); res.setParent(req.hashCode()); try { watch.stop(); } catch (IllegalStateException e) { } log.info("Response outgoing: " + res.hashCode() + " for " + req.hashCode()); if (state == State.PROXY) { // No need. } else if (state == State.MOCK) { if (recordMock) { req.setState(State.RECORD); res.setState(State.RECORD); sendToRecorder(res, req); } } else if (state == State.RECORD) { sendToRecorder(res, req); } addEvent(counter++, res, req, watch); } else { throw new RuntimeException("HttpObject is not " + FullHttpResponse.class); } return httpObject; } catch (Exception e) { e.printStackTrace(); return null; } } }; } private void addEvent(Integer id, Response res, Request req, StopWatch watch) { Long duration = TimeUnit.MILLISECONDS.toMillis(watch.getTime()); Event event = new Event(id, req, res, new Date(watch.getStartTime()), duration, state); Payload payload = new Payload(this.id, Payload.Action.INSERT, Payload.Type.EVENT, event); WebSocket.broadcast(payload); } /** * Request Handlers * * @param watch */ public HttpResponse sendToMock(final Request request, StopWatch watch) { if (tape == null) { return null; } Response response = tape.getResponse(request); if (response != null) { watch.stop(); log.info("Mocked Response outgoing: " + response.hashCode() + " for " + request.hashCode()); addEvent(counter++, response, request, watch); return (HttpResponse) response.getHTTPObject(); } else { log.info("Mocked Response outgoing: null for " + request.hashCode()); addEvent(counter, response, request, watch); return null; } } public HttpResponse sendToRecorder(Response res, Request req) { tape.put(req, res); return null; } /** * Setter and Getters */ public void setState(State state) { log.info("State set to " + state.toString()); if (state != State.MOCK) { this.tmp.clear(); } this.state = state; } public void setRecordMock(Boolean val) { log.info("Setting RecordMocked: " + val); this.recordMock = val; } public Boolean getRecordMock() { return this.recordMock; } public Tape getTape() { return this.tape; } public void setTape(Tape tape) { if (tape == null) { return; } log.info("Settings Tape: " + tape.hashCode()); this.tape = tape; } public void setRedirectInfo(String host, Integer port) { this.host = host; this.port = port; log.info("Setting Redirect: " + host + ":" + port); } public void setRedirectState(boolean state) { log.info("Redirecting state: " + state); this.redirect = state; } public Boolean getRedirectState() { return this.redirect; } public String getHost() { return this.host; } public Integer getPort() { return this.port; } public State getState() { return this.state; } public List<Event> getEvents() { List<Event> events = this.events; this.events = new ArrayList<Event>(); return events; } @Override public int getMaximumRequestBufferSizeInBytes() { return MAX_SIZE; } @Override public int getMaximumResponseBufferSizeInBytes() { return MAX_SIZE; } public JSONObject toJSON() { JSONObject json = new JSONObject(); json.put("host", this.host); json.put("port", this.port); json.put("redirect", this.redirect); json.put("state", this.state); json.put("id", this.id); json.put("recordMock", this.recordMock); return json; } public static Filter parseJSON(String source) { JSONObject json = new JSONObject(source); Integer id = json.getInt("id"); String host = json.getString("host"); Integer port = json.getInt("port"); Boolean redirect = json.getBoolean("redirect"); State state = State.valueOf(json.getString("state")); Boolean recordMock = json.getBoolean("recordMock"); Filter filter = new Filter(id); filter.setRedirectInfo(host, port); filter.setRedirectState(redirect); filter.setState(state); filter.setRecordMock(recordMock); return filter; } }
package tc.oc.projectares.api; import java.util.Collection; import java.util.Set; import java.util.UUID; import javax.annotation.Nonnull; import org.bukkit.World; public interface Match { @Nonnull World getWorld(); @Nonnull UUID getUUID(); @Nonnull boolean isRunning(); @Nonnull boolean start(); @Nonnull boolean end(); @Nonnull boolean end(@Nonnull Team winningTeam); @Nonnull Collection<Player> getPlayers(); @Nonnull Set<Player> getParticipatingPlayers(); @Nonnull Set<Player> getObservingPlayers(); void broadcast(String message); @Nonnull Set<Team> getTeams(); @Nonnull Set<Team> getParticipatingTeams(); @Nonnull Set<Team> getObservingTeams(); Team getFirstOther(Team exclude); }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package tsdaggregator; import java.io.*; import java.nio.charset.Charset; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.cli.*; import org.apache.log4j.Logger; import org.joda.time.Period; import org.joda.time.format.ISOPeriodFormat; import org.joda.time.format.PeriodFormatter; /** * * @author brandarp */ public class TsdAggregator { static final Logger _Logger = Logger.getLogger(TsdAggregator.class); /** * @param args the command line arguments */ public static void main(String[] args) { Options options = new Options(); options.addOption("f", "file", true, "file to be parsed"); options.addOption("s", "service", true, "service name"); options.addOption("h", "host", true, "host the metrics were generated on"); options.addOption("u", "uri", true, "metrics server uri"); options.addOption("o", "output", true, "output file"); options.addOption("p", "parser", true, "parser to use to parse log lines"); options.addOption("d", "period", true, "aggregation time period in ISO 8601 standard notation (multiple allowed)"); options.addOption("t", "statistic", true, "statistic of aggregation to record (multiple allowed)"); options.addOption("e", "extension", true, "extension of files to parse - uses a union of arguments as a regex (multiple allowed)"); CommandLineParser parser = new PosixParser(); CommandLine cl; try { cl = parser.parse(options, args); } catch (ParseException e1) { printUsage(options); return; } if (!cl.hasOption("f")) { System.err.println("no file found, must specify file on the command line"); printUsage(options); return; } if (!cl.hasOption("s")) { System.err.println("service name must be specified"); printUsage(options); return; } if (!cl.hasOption("h")) { System.err.println("host name must be specified"); printUsage(options); return; } if (!cl.hasOption("u") && !cl.hasOption("o")) { System.err.println("metrics server uri or output file not specified"); printUsage(options); return; } Class parserClass = QueryLogLineData.class; if (cl.hasOption("p")) { String lineParser = cl.getOptionValue("p"); try { parserClass = Class.forName(lineParser); if (!LogLine.class.isAssignableFrom(parserClass)) { _Logger.error("parser class [" + lineParser + "] does not implement requried LogLine interface"); return; } } catch (ClassNotFoundException ex) { _Logger.error("could not find parser class [" + lineParser + "] on classpath"); return; } } String[] periodOptions = {"PT1M", "PT5M", "PT1H"}; if (cl.hasOption("d")) { periodOptions = cl.getOptionValues("d"); } Pattern filter = Pattern.compile(".*"); if (cl.hasOption("e")) { String[] filters = cl.getOptionValues("e"); StringBuilder builder = new StringBuilder(); int x = 0; for (String f : filters) { if (x > 0) { builder.append(" || "); } builder.append("(").append(f).append(")"); } filter = Pattern.compile(builder.toString(), Pattern.CASE_INSENSITIVE); } Set<Statistic> statisticsClasses = new HashSet<Statistic>(); if (cl.hasOption("t")) { String[] statisticsStrings = cl.getOptionValues("t"); for (String statString : statisticsStrings) { try { _Logger.info("Looking up statistic " + statString); Class statClass = ClassLoader.getSystemClassLoader().loadClass(statString); Statistic stat = null; try { stat = (Statistic)statClass.newInstance(); statisticsClasses.add(stat); } catch (InstantiationException ex) { _Logger.error("Could not instantiate statistic [" + statString + "]", ex); return; } catch (IllegalAccessException ex) { _Logger.error("Could not instantiate statistic [" + statString + "]", ex); return; } if (!Statistic.class.isAssignableFrom(statClass)) { _Logger.error("Statistic class [" + statString + "] does not implement requried Statistic interface"); return; } } catch (ClassNotFoundException ex) { _Logger.error("could not find statistic class [" + statString + "] on classpath"); return; } } } else { statisticsClasses.add(new TP0()); statisticsClasses.add(new TP50()); statisticsClasses.add(new TP100()); statisticsClasses.add(new TP90()); statisticsClasses.add(new TP99()); statisticsClasses.add(new TP99p9()); statisticsClasses.add(new MeanStatistic()); statisticsClasses.add(new NStatistic()); } String fileName = cl.getOptionValue("f"); String hostName = cl.getOptionValue("h"); String serviceName = cl.getOptionValue("s"); String metricsUri = ""; String outputFile = ""; if (cl.hasOption("u")) { metricsUri = cl.getOptionValue("u"); } if (cl.hasOption("o")) { outputFile = cl.getOptionValue("o"); } _Logger.info("using file " + fileName); _Logger.info("using hostname " + hostName); _Logger.info("using servicename " + serviceName); _Logger.info("using uri " + metricsUri); _Logger.info("using output file " + outputFile); _Logger.info("using filter (" + filter.pattern() + ")"); Set<Period> periods = new HashSet<Period>(); PeriodFormatter periodParser = ISOPeriodFormat.standard(); for (String p : periodOptions) { periods.add(periodParser.parsePeriod(p)); } AggregationListener listener = null; if (!metricsUri.equals("")) { AggregationListener httpListener = new HttpPostListener(metricsUri); listener = new BufferingListener(httpListener, 50); } else if (!outputFile.equals("")) { AggregationListener fileListener = new FileListener(outputFile); listener = new BufferingListener(fileListener, 500); } HashMap<String, TSData> aggregations = new HashMap<String, TSData>(); ArrayList<String> files = new ArrayList<String>(); File file = new File(fileName); if (file.isFile()) { files.add(fileName); } else if (file.isDirectory()) { _Logger.info("File given is a directory, will recursively process"); findFilesRecursive(file, files, filter); } for (String f : files) { try { _Logger.info("Reading file " + f); //check the first 4 bytes of the file for utf markers FileInputStream fis = new FileInputStream(f); byte[] header = new byte[4]; fis.read(header); String encoding = "UTF-8"; if (header[0] == -1 && header[1] == -2) { _Logger.info("Detected UTF-16 encoding"); encoding = "UTF-16"; } InputStreamReader fileReader = new InputStreamReader(new FileInputStream(f), Charset.forName(encoding)); BufferedReader reader = new BufferedReader(fileReader); String line; Integer lineNum = 0; while ((line = reader.readLine()) != null) { lineNum++; //System.out.println(line); LogLine data = null; try { data = (LogLine)parserClass.newInstance(); } catch (InstantiationException ex) { _Logger.error("Could not instantiate LogLine parser", ex); return; } catch (IllegalAccessException ex) { _Logger.error("Could not instantiate LogLine parser", ex); return; } data.parseLogLine(line); for (Map.Entry<String, ArrayList<Double>> entry : data.getVariables().entrySet()) { TSData tsdata = aggregations.get(entry.getKey()); if (tsdata == null) { tsdata = new TSData(entry.getKey(), periods, listener, hostName, serviceName, statisticsClasses); aggregations.put(entry.getKey(), tsdata); } tsdata.addMetric(entry.getValue(), data.getTime()); } } //close all aggregations for (Map.Entry<String, TSData> entry : aggregations.entrySet()) { entry.getValue().close(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } listener.close(); } private static void findFilesRecursive(File dir, ArrayList<String> files, Pattern filter) { String[] list = dir.list(); Arrays.sort(list); for (String f : list) { File entry = new File(dir, f); if (entry.isFile()) { Matcher m = filter.matcher(entry.getPath()); if (m.find()) { files.add(entry.getAbsolutePath()); } else { } } else if (entry.isDirectory()) { findFilesRecursive(entry, files, filter); } } } public static void printUsage(Options options) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("tsdaggregator", options, true); } }
package de.tr7zw.changeme.nbtapi.utils.nmsmappings; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.Method; import java.util.UUID; import org.bukkit.inventory.ItemStack; import de.tr7zw.changeme.nbtapi.NbtApiException; import de.tr7zw.changeme.nbtapi.utils.MinecraftVersion; /** * This class caches method reflections, keeps track of method name changes between versions and allows early checking for problems * * @author tr7zw * */ @SuppressWarnings("javadoc") public enum ReflectionMethod { COMPOUND_SET_FLOAT(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class, float.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "setFloat")), COMPOUND_SET_STRING(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class, String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "setString")), COMPOUND_SET_INT(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class, int.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "setInt")), COMPOUND_SET_BYTEARRAY(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class, byte[].class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "setByteArray")), COMPOUND_SET_INTARRAY(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class, int[].class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "setIntArray")), COMPOUND_SET_LONG(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class, long.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "setLong")), COMPOUND_SET_SHORT(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class, short.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "setShort")), COMPOUND_SET_BYTE(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class, byte.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "setByte")), COMPOUND_SET_DOUBLE(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class, double.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "setDouble")), COMPOUND_SET_BOOLEAN(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class, boolean.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "setBoolean")), COMPOUND_SET_UUID(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class, UUID.class}, MinecraftVersion.MC1_16_R1, new Since(MinecraftVersion.MC1_16_R1, "a")), COMPOUND_MERGE(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_8_R3, new Since(MinecraftVersion.MC1_8_R3, "a")), //FIXME: No Spigot mapping! COMPOUND_SET(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class, ClassWrapper.NMS_NBTBASE.getClazz()}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "set")), COMPOUND_GET(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "get")), COMPOUND_GET_LIST(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class, int.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getList")), COMPOUND_OWN_TYPE(ClassWrapper.NMS_NBTBASE.getClazz(), new Class[]{}, MinecraftVersion.MC1_7_R4, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getTypeId")), // Only needed for 1.7.10 getType COMPOUND_GET_FLOAT(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getFloat")), COMPOUND_GET_STRING(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getString")), COMPOUND_GET_INT(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getInt")), COMPOUND_GET_BYTEARRAY(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getByteArray")), COMPOUND_GET_INTARRAY(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getIntArray")), COMPOUND_GET_LONG(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getLong")), COMPOUND_GET_SHORT(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getShort")), COMPOUND_GET_BYTE(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getByte")), COMPOUND_GET_DOUBLE(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getDouble")), COMPOUND_GET_BOOLEAN(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getBoolean")), COMPOUND_GET_UUID(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_16_R1, new Since(MinecraftVersion.MC1_16_R1, "a")), COMPOUND_GET_COMPOUND(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getCompound")), NMSITEM_GETTAG(ClassWrapper.NMS_ITEMSTACK.getClazz(), new Class[] {}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getTag")), NMSITEM_SAVE(ClassWrapper.NMS_ITEMSTACK.getClazz(), new Class[] {ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "save")), NMSITEM_CREATESTACK(ClassWrapper.NMS_ITEMSTACK.getClazz(), new Class[] {ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_7_R4, MinecraftVersion.MC1_10_R1, new Since(MinecraftVersion.MC1_7_R4, "createStack")), COMPOUND_REMOVE_KEY(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "remove")), COMPOUND_HAS_KEY(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "hasKey")), COMPOUND_GET_TYPE(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_8_R3, new Since(MinecraftVersion.MC1_8_R3, "b"), new Since(MinecraftVersion.MC1_9_R1, "d"), new Since(MinecraftVersion.MC1_15_R1, "e"), new Since(MinecraftVersion.MC1_16_R1, "d")), //FIXME: No Spigot mapping! COMPOUND_GET_KEYS(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "c"), new Since(MinecraftVersion.MC1_13_R1, "getKeys")), LISTCOMPOUND_GET_KEYS(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "c"), new Since(MinecraftVersion.MC1_13_R1, "getKeys")), LIST_REMOVE_KEY(ClassWrapper.NMS_NBTTAGLIST.getClazz(), new Class[]{int.class}, MinecraftVersion.MC1_8_R3, new Since(MinecraftVersion.MC1_8_R3, "a"), new Since(MinecraftVersion.MC1_9_R1, "remove")), LIST_SIZE(ClassWrapper.NMS_NBTTAGLIST.getClazz(), new Class[]{}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "size")), LIST_SET(ClassWrapper.NMS_NBTTAGLIST.getClazz(), new Class[]{int.class, ClassWrapper.NMS_NBTBASE.getClazz()}, MinecraftVersion.MC1_8_R3, new Since(MinecraftVersion.MC1_8_R3, "a"), new Since(MinecraftVersion.MC1_13_R1, "set")), LEGACY_LIST_ADD(ClassWrapper.NMS_NBTTAGLIST.getClazz(), new Class[]{ClassWrapper.NMS_NBTBASE.getClazz()}, MinecraftVersion.MC1_7_R4, MinecraftVersion.MC1_13_R2, new Since(MinecraftVersion.MC1_7_R4, "add")), LIST_ADD(ClassWrapper.NMS_NBTTAGLIST.getClazz(), new Class[]{int.class, ClassWrapper.NMS_NBTBASE.getClazz()}, MinecraftVersion.MC1_14_R1, new Since(MinecraftVersion.MC1_14_R1, "add")), LIST_GET_STRING(ClassWrapper.NMS_NBTTAGLIST.getClazz(), new Class[]{int.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getString")), LIST_GET_COMPOUND(ClassWrapper.NMS_NBTTAGLIST.getClazz(), new Class[]{int.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "get")), LIST_GET(ClassWrapper.NMS_NBTTAGLIST.getClazz(), new Class[]{int.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "get"), new Since(MinecraftVersion.MC1_8_R3, "g"), new Since(MinecraftVersion.MC1_9_R1, "h"), new Since(MinecraftVersion.MC1_12_R1, "i"), new Since(MinecraftVersion.MC1_13_R1, "get")), ITEMSTACK_SET_TAG(ClassWrapper.NMS_ITEMSTACK.getClazz(), new Class[]{ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "setTag")), ITEMSTACK_NMSCOPY(ClassWrapper.CRAFT_ITEMSTACK.getClazz(), new Class[]{ItemStack.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "asNMSCopy")), ITEMSTACK_BUKKITMIRROR(ClassWrapper.CRAFT_ITEMSTACK.getClazz(), new Class[]{ClassWrapper.NMS_ITEMSTACK.getClazz()}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "asCraftMirror")), CRAFT_WORLD_GET_HANDLE(ClassWrapper.CRAFT_WORLD.getClazz(), new Class[]{}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getHandle")), NMS_WORLD_GET_TILEENTITY(ClassWrapper.NMS_WORLDSERVER.getClazz(), new Class[]{ClassWrapper.NMS_BLOCKPOSITION.getClazz()}, MinecraftVersion.MC1_8_R3, new Since(MinecraftVersion.MC1_8_R3, "getTileEntity")), NMS_WORLD_SET_TILEENTITY(ClassWrapper.NMS_WORLDSERVER.getClazz(), new Class[]{ClassWrapper.NMS_BLOCKPOSITION.getClazz(), ClassWrapper.NMS_TILEENTITY.getClazz()}, MinecraftVersion.MC1_8_R3, new Since(MinecraftVersion.MC1_8_R3, "setTileEntity")), NMS_WORLD_REMOVE_TILEENTITY(ClassWrapper.NMS_WORLDSERVER.getClazz(), new Class[]{ClassWrapper.NMS_BLOCKPOSITION.getClazz()}, MinecraftVersion.MC1_8_R3, new Since(MinecraftVersion.MC1_8_R3, "t"), new Since(MinecraftVersion.MC1_9_R1, "s"), new Since(MinecraftVersion.MC1_13_R1, "n"), new Since(MinecraftVersion.MC1_14_R1, "removeTileEntity")), NMS_WORLD_GET_TILEENTITY_1_7_10(ClassWrapper.NMS_WORLDSERVER.getClazz(), new Class[]{int.class, int.class, int.class}, MinecraftVersion.MC1_7_R4, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getTileEntity")), TILEENTITY_LOAD_LEGACY191(ClassWrapper.NMS_TILEENTITY.getClazz(), new Class[]{ClassWrapper.NMS_MINECRAFTSERVER.getClazz(), ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_9_R1, MinecraftVersion.MC1_9_R1, new Since(MinecraftVersion.MC1_9_R1, "a")), //FIXME: No Spigot mapping! TILEENTITY_LOAD_LEGACY183(ClassWrapper.NMS_TILEENTITY.getClazz(), new Class[]{ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_8_R3, MinecraftVersion.MC1_9_R2, new Since(MinecraftVersion.MC1_8_R3, "c"), new Since(MinecraftVersion.MC1_9_R1, "a"), new Since(MinecraftVersion.MC1_9_R2, "c")), //FIXME: No Spigot mapping! TILEENTITY_LOAD_LEGACY1121(ClassWrapper.NMS_TILEENTITY.getClazz(), new Class[]{ClassWrapper.NMS_WORLD.getClazz(), ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_10_R1, MinecraftVersion.MC1_12_R1, new Since(MinecraftVersion.MC1_10_R1, "a"), new Since(MinecraftVersion.MC1_12_R1, "create")), TILEENTITY_LOAD_LEGACY1151(ClassWrapper.NMS_TILEENTITY.getClazz(), new Class[]{ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_13_R1, MinecraftVersion.MC1_15_R1, new Since(MinecraftVersion.MC1_12_R1, "create")), TILEENTITY_LOAD(ClassWrapper.NMS_TILEENTITY.getClazz(), new Class[]{ClassWrapper.NMS_IBLOCKDATA.getClazz(), ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_16_R1, new Since(MinecraftVersion.MC1_16_R1, "create")), TILEENTITY_GET_NBT(ClassWrapper.NMS_TILEENTITY.getClazz(), new Class[]{ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "b"), new Since(MinecraftVersion.MC1_9_R1, "save")), TILEENTITY_SET_NBT_LEGACY1151(ClassWrapper.NMS_TILEENTITY.getClazz(), new Class[]{ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_7_R4, MinecraftVersion.MC1_15_R1, new Since(MinecraftVersion.MC1_7_R4, "a"), new Since(MinecraftVersion.MC1_12_R1, "load")), TILEENTITY_SET_NBT(ClassWrapper.NMS_TILEENTITY.getClazz(), new Class[]{ClassWrapper.NMS_IBLOCKDATA.getClazz(), ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_16_R1, new Since(MinecraftVersion.MC1_16_R1, "load")), TILEENTITY_GET_BLOCKDATA(ClassWrapper.NMS_TILEENTITY.getClazz(), new Class[]{}, MinecraftVersion.MC1_16_R1, new Since(MinecraftVersion.MC1_16_R1, "getBlock")), CRAFT_ENTITY_GET_HANDLE(ClassWrapper.CRAFT_ENTITY.getClazz(), new Class[]{}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getHandle")), NMS_ENTITY_SET_NBT(ClassWrapper.NMS_ENTITY.getClazz(), new Class[]{ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "f"), new Since(MinecraftVersion.MC1_16_R1, "load")), //FIXME: No Spigot mapping! NMS_ENTITY_GET_NBT(ClassWrapper.NMS_ENTITY.getClazz(), new Class[]{ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "e"), new Since(MinecraftVersion.MC1_12_R1, "save")), NMS_ENTITY_GETSAVEID(ClassWrapper.NMS_ENTITY.getClazz(), new Class[]{}, MinecraftVersion.MC1_14_R1,new Since(MinecraftVersion.MC1_14_R1, "getSaveID")), NBTFILE_READ(ClassWrapper.NMS_NBTCOMPRESSEDSTREAMTOOLS.getClazz(), new Class[]{InputStream.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "a")), //FIXME: No Spigot mapping! NBTFILE_WRITE(ClassWrapper.NMS_NBTCOMPRESSEDSTREAMTOOLS.getClazz(), new Class[]{ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), OutputStream.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "a")), //FIXME: No Spigot mapping! PARSE_NBT(ClassWrapper.NMS_MOJANGSONPARSER.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "parse")), REGISTRY_KEYSET (ClassWrapper.NMS_REGISTRYSIMPLE.getClazz(), new Class[]{}, MinecraftVersion.MC1_11_R1, MinecraftVersion.MC1_13_R1, new Since(MinecraftVersion.MC1_11_R1, "keySet")), REGISTRY_GET (ClassWrapper.NMS_REGISTRYSIMPLE.getClazz(), new Class[]{Object.class}, MinecraftVersion.MC1_11_R1, MinecraftVersion.MC1_13_R1, new Since(MinecraftVersion.MC1_11_R1, "get")), REGISTRY_SET (ClassWrapper.NMS_REGISTRYSIMPLE.getClazz(), new Class[]{Object.class, Object.class}, MinecraftVersion.MC1_11_R1, MinecraftVersion.MC1_13_R1, new Since(MinecraftVersion.MC1_11_R1, "a")), //FIXME: No Spigot mapping! REGISTRY_GET_INVERSE (ClassWrapper.NMS_REGISTRYMATERIALS.getClazz(), new Class[]{Object.class}, MinecraftVersion.MC1_11_R1, MinecraftVersion.MC1_13_R1, new Since(MinecraftVersion.MC1_11_R1, "b")), //FIXME: No Spigot mapping! REGISTRYMATERIALS_KEYSET (ClassWrapper.NMS_REGISTRYMATERIALS.getClazz(), new Class[]{}, MinecraftVersion.MC1_13_R1, new Since(MinecraftVersion.MC1_13_R1, "keySet")), REGISTRYMATERIALS_GET (ClassWrapper.NMS_REGISTRYMATERIALS.getClazz(), new Class[]{ClassWrapper.NMS_MINECRAFTKEY.getClazz()}, MinecraftVersion.MC1_13_R1, new Since(MinecraftVersion.MC1_13_R1, "get")), REGISTRYMATERIALS_GETKEY (ClassWrapper.NMS_REGISTRYMATERIALS.getClazz(), new Class[]{Object.class}, MinecraftVersion.MC1_13_R2, new Since(MinecraftVersion.MC1_13_R2, "getKey")), GAMEPROFILE_DESERIALIZE (ClassWrapper.NMS_GAMEPROFILESERIALIZER.getClazz(), new Class[]{ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "deserialize")), GAMEPROFILE_SERIALIZE (ClassWrapper.NMS_GAMEPROFILESERIALIZER.getClazz(), new Class[]{ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), ClassWrapper.GAMEPROFILE.getClazz()}, MinecraftVersion.MC1_8_R3, new Since(MinecraftVersion.MC1_8_R3, "serialize")); private MinecraftVersion removedAfter; private Since targetVersion; private Method method; private boolean loaded = false; private boolean compatible = false; private String methodName = null; ReflectionMethod(Class<?> targetClass, Class<?>[] args, MinecraftVersion addedSince, MinecraftVersion removedAfter, Since... methodnames){ this.removedAfter = removedAfter; MinecraftVersion server = MinecraftVersion.getVersion(); if(server.compareTo(addedSince) < 0 || (this.removedAfter != null && server.getVersionId() > this.removedAfter.getVersionId()))return; compatible = true; Since target = methodnames[0]; for(Since s : methodnames){ if(s.version.getVersionId() <= server.getVersionId() && target.version.getVersionId() < s.version.getVersionId()) target = s; } targetVersion = target; try{ method = targetClass.getMethod(targetVersion.name, args); method.setAccessible(true); loaded = true; methodName = targetVersion.name; }catch(NullPointerException | NoSuchMethodException | SecurityException ex){ System.out.println("[NBTAPI] Unable to find the method '" + targetVersion.name + "' in '" + (targetClass == null ? "null" : targetClass.getSimpleName()) + "' Enum: " + this); //NOSONAR This gets loaded before the logger is loaded } } ReflectionMethod(Class<?> targetClass, Class<?>[] args, MinecraftVersion addedSince, Since... methodnames){ this(targetClass, args, addedSince, null, methodnames); } /** * Runs the method on a given target object using the given args. * * @param target * @param args * @return Value returned by the method */ public Object run(Object target, Object... args){ if(method == null) throw new NbtApiException("Method not loaded! '" + this + "'"); try{ return method.invoke(target, args); }catch(Exception ex){ throw new NbtApiException("Error while calling the method '" + methodName + "', loaded: " + loaded + ", Enum: " + this, ex); } } /** * @return The MethodName, used in this Minecraft Version */ public String getMethodName() { return methodName; } /** * @return Has this method been linked */ public boolean isLoaded() { return loaded; } /** * @return Is this method available in this Minecraft Version */ public boolean isCompatible() { return compatible; } protected static class Since{ public final MinecraftVersion version; public final String name; public Since(MinecraftVersion version, String name) { this.version = version; this.name = name; } } }
package com.kodedu.boot; import com.install4j.api.launcher.StartupNotification; import com.kodedu.config.ConfigurationService; import com.kodedu.config.EditorConfigBean; import com.kodedu.controller.ApplicationController; import com.kodedu.service.FileOpenListener; import com.kodedu.service.ThreadService; import com.kodedu.service.ui.TabService; import de.tototec.cmdoption.CmdlineParser; import de.tototec.cmdoption.CmdlineParserException; import javafx.application.Application; import javafx.application.Platform; import javafx.fxml.FXMLLoader; import javafx.geometry.Rectangle2D; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyCodeCombination; import javafx.scene.layout.AnchorPane; import javafx.stage.Modality; import javafx.stage.Screen; import javafx.stage.Stage; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.context.ConfigurableApplicationContext; import java.io.File; import java.io.InputStream; import static javafx.scene.input.KeyCombination.SHORTCUT_DOWN; public class AppStarter extends Application { private static Logger logger = LoggerFactory.getLogger(AppStarter.class); private static ApplicationController controller; private static ConfigurableApplicationContext context; private EditorConfigBean editorConfigBean; private Stage stage; private ThreadService threadService; private ConfigurationService configurationService; @Override public void start(final Stage stage) { Thread.setDefaultUncaughtExceptionHandler((t, e) -> logger.error(e.getMessage(), e)); // System.setProperty("nashorn.typeInfo.maxFiles", "5"); System.setProperty("jsse.enableSNIExtension", "false"); // System.setProperty("https.protocols", "SSLv3"); System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); final CmdlineConfig config = new CmdlineConfig(); final CmdlineParser cp = new CmdlineParser(config); try { cp.parse(getParameters().getRaw().toArray(new String[0])); } catch (final CmdlineParserException e) { System.err.println("Invalid commandline given: " + e.getMessage()); System.exit(1); } if (config.help) { cp.usage(); System.exit(0); } new Thread(() -> { try { startApp(stage, config); } catch (final Throwable e) { logger.error("Problem occured while starting AsciidocFX", e); } }).start(); } private void startApp(final Stage stage, final CmdlineConfig config) throws Throwable { this.stage = stage; context = SpringApplication.run(SpringAppConfig.class); editorConfigBean = context.getBean(EditorConfigBean.class); controller = context.getBean(ApplicationController.class); threadService = context.getBean(ThreadService.class); configurationService = context.getBean(ConfigurationService.class); final FXMLLoader parentLoader = new FXMLLoader(); parentLoader.setControllerFactory(context::getBean); InputStream sceneStream = AppStarter.class.getResourceAsStream("/fxml/AsciidocFX_Scene.fxml"); Parent root = parentLoader.load(sceneStream); Scene scene = new Scene(root); stage.setTitle("AsciidocFX"); InputStream logoStream = AppStarter.class.getResourceAsStream("/logo.png"); stage.getIcons().add(new Image(logoStream)); threadService.runActionLater(stage::setScene, scene); controller.initializeApp(); stage.setOnShowing(e -> { controller.setStage(stage); controller.setScene(scene); controller.setHostServices(getHostServices()); configurationService.loadConfigurations(); controller.applyInitialConfigurations(); }); stage.setOnShown(e -> { controller.bindConfigurations(); controller.showConfigLoaderOnNewInstall(); }); threadService.runActionLater(() -> { setMaximized(); if (controller.getTabPane().getTabs().isEmpty()) { controller.newDoc(); } stage.show(); }); IOUtils.closeQuietly(sceneStream); IOUtils.closeQuietly(logoStream); final FXMLLoader asciidocTableLoader = new FXMLLoader(); final FXMLLoader markdownTableLoader = new FXMLLoader(); asciidocTableLoader.setControllerFactory(context::getBean); markdownTableLoader.setControllerFactory(context::getBean); InputStream asciidocTableStream = AppStarter.class.getResourceAsStream("/fxml/AsciidocTablePopup.fxml"); AnchorPane asciidocTableAnchor = asciidocTableLoader.load(asciidocTableStream); InputStream markdownTableStream = AppStarter.class.getResourceAsStream("/fxml/MarkdownTablePopup.fxml"); AnchorPane markdownTableAnchor = markdownTableLoader.load(markdownTableStream); Stage asciidocTableStage = threadService.supply(Stage::new); threadService.runActionLater(asciidocTableStage::setScene, new Scene(asciidocTableAnchor)); asciidocTableStage.setTitle("Table Generator"); asciidocTableStage.initModality(Modality.WINDOW_MODAL); asciidocTableStage.initOwner(scene.getWindow()); asciidocTableStage.getIcons().add(new Image(logoStream)); Stage markdownTableStage = threadService.supply(Stage::new); threadService.runActionLater(markdownTableStage::setScene, new Scene(markdownTableAnchor)); markdownTableStage.setTitle("Table Generator"); markdownTableStage.initModality(Modality.WINDOW_MODAL); markdownTableStage.initOwner(scene.getWindow()); markdownTableStage.getIcons().add(new Image(logoStream)); IOUtils.closeQuietly(asciidocTableStream); IOUtils.closeQuietly(markdownTableStream); controller.setAsciidocTableAnchor(asciidocTableAnchor); controller.setMarkdownTableAnchor(markdownTableAnchor); controller.setAsciidocTableStage(asciidocTableStage); controller.setAsciidocTableScene(asciidocTableStage.getScene()); controller.setMarkdownTableStage(markdownTableStage); controller.setMarkdownTableScene(markdownTableStage.getScene()); controller.applyCurrentTheme(asciidocTableStage, markdownTableStage); controller.initializeSaveOnBlur(); scene.getAccelerators().put(new KeyCodeCombination(KeyCode.S, SHORTCUT_DOWN), controller::saveDoc); scene.getAccelerators().put(new KeyCodeCombination(KeyCode.M, SHORTCUT_DOWN), controller::adjustSplitPane); scene.getAccelerators().put(new KeyCodeCombination(KeyCode.N, SHORTCUT_DOWN), controller::newDoc); scene.getAccelerators().put(new KeyCodeCombination(KeyCode.O, SHORTCUT_DOWN), controller::openDoc); scene.getAccelerators().put(new KeyCodeCombination(KeyCode.W, SHORTCUT_DOWN), controller::saveAndCloseCurrentTab); final ThreadService threadService = context.getBean(ThreadService.class); controller.initializeTabWatchListener(); threadService.start(() -> { try { registerStartupListener(config); } catch (Exception e) { logger.error("Problem occured in startup listener", e); } }); scene.getWindow().setOnCloseRequest(controller::closeAllTabs); stage.widthProperty().addListener(controller::stageWidthChanged); stage.heightProperty().addListener(controller::stageWidthChanged); } private void setMaximized() { Rectangle2D bounds = Screen.getPrimary().getVisualBounds(); stage.setX(bounds.getMinX()); stage.setY(bounds.getMinY()); stage.setWidth(bounds.getWidth()); stage.setHeight(bounds.getHeight()); } private void registerStartupListener(CmdlineConfig config) { final ThreadService threadService = context.getBean(ThreadService.class); final TabService tabService = context.getBean(TabService.class); final FileOpenListener fileOpenListener = context.getBean(FileOpenListener.class); StartupNotification.registerStartupListener(fileOpenListener); if (!config.files.isEmpty()) { threadService.runActionLater(() -> { config.files.stream().forEach(f -> { File file = new File(f).getAbsoluteFile(); if (file.exists()) { logger.info("Opening file as requsted from cmdline: {}", file); tabService.addTab(file.toPath()); } else { // TODO: do we want to create such a file on demand? logger.error("Cannot open non-existent file: {}", file); } }); }); } } @Override public void stop() throws Exception { controller.closeApp(null); context.registerShutdownHook(); Platform.exit(); System.exit(0); } /** * The main() method is ignored in correctly deployed JavaFX application. * main() serves only as fallback in case the application can not be * launched through deployment artifacts, e.g., in IDEs with limited FX * support. NetBeans ignores main(). * * @param args the command line arguments */ public static void main(String[] args) { launch(args); } }
package com.sebworks.vaadstrap; import com.vaadin.ui.CssLayout; /** * @author seb * */ public class Row extends CssLayout { private String defaultStyle = "row"; public Row() { setImmediate(true); clearStyles(); } /** * Add a column with given styles. * @see ColMod * @see ColOffsetMod * @see MarginMod * @return the added column */ public Col addCol(Style...styles){ Col col = new Col(); col.addStyles(styles); addComponent(col); return col; } public Row clearStyles() { setStyleName(defaultStyle); return this; } public Row addStyles(Style... styles) { for (Style style : styles) { addStyleName(style.getStyleName()); } return this; } }
abstract class IdeaBugTest<M extends IdeaBugTest.Mapping> { static class Mapping {} } class BugTestSub extends IdeaBugTest<<error descr="SubMapping is not accessible in current context">BugTestSub.SubMapping</error>> { public abstract static class SubMapping extends Mapping {} } class BugTestSub1 extends IdeaBugTest<BugTestSub1.SubMapping> { public abstract static class SubMapping extends IdeaBugTest.Mapping {} //fqn here } class AbstractSettings { interface State {} } interface SomeInterface<T> {} class Settings extends AbstractSettings implements SomeInterface<Settings.MyState> { static class MyState implements State {} } class Records { interface RecordCategory { } static abstract class Record<CATEGORY_TYPE extends RecordCategory> extends Records {} static class ResultRecord extends Record<ResultRecord.Category> { public enum Category implements RecordCategory { kind(); } } } class Parent<T extends Parent.NestedParent> { protected static interface NestedParent { } } class Test { public final static class Child extends Parent<<error descr="NestedChild is not accessible in current context">Child.NestedChild</error>> { private static interface NestedChild extends NestedParent { } } }
package creator; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import de.ust.skill.common.java.internal.SkillObject; public class SkillObjectCreator { private static final String FIELD_DECLARATION_CLASS_NAME = "de.ust.skill.common.java.api.FieldDeclaration"; public static void main(String[] args) { String className = "age.Age"; String fieldToSet = "age"; String fieldTypeToSet = "long"; Long valueToSet = 255L; Map<String, Object> values = new HashMap<>(); Map<String, String> fieldTypes = new HashMap<>(); values.put(fieldToSet, valueToSet); fieldTypes.put(fieldToSet, fieldTypeToSet); try { SkillObject obj = instantiateSkillObject(className, values, fieldTypes); System.out.println(obj.prettyString()); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } /** * Create an empty SkillObject from a fully specified class name * * @param className * fully classified class name incl. package identifier * @return empty SkillObject of the specified class */ public static SkillObject createSkillObject(String className) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { Class<?> refClass = Class.forName(className); Constructor<?> refConstructor = refClass.getConstructor(); SkillObject refVar = (SkillObject) refConstructor.newInstance(); return refVar; } /** * Create and fill a SkillObject with the provided values * * @param className * fully specified class name incl. package identifier of the * object to be created * @param values * mapping of field names to values * @param fieldTypes * mapping of field names to the corresponding types of values * @return a SkillObject with the provided values as attributes */ public static SkillObject instantiateSkillObject(String className, Map<String, Object> values, Map<String, String> fieldTypes) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { SkillObject obj = createSkillObject(className); Map<String, Type> fieldMapping = getFieldMapping(className); for (String key : fieldMapping.keySet()) { String type = fieldMapping.get(key).getTypeName(); System.out.println("Present field: " + key + "(Type: " + type + ")"); if (values.containsKey(key)) { System.out.println("Setting field '" + key + "'"); reflectiveSetValue(obj, values.get(key), key, fieldTypes.get(key)); } } return obj; } /** * Set the specified field of a SkillObject to a given value * * @param obj * the SkillObject for which the field is to be set * @param value * the value to set the field of the SkillObject to * @param fieldName * the name of the field to be set * @param fieldType * fully qualified class name of the field to be set * @return the provided SkillObject with a set new value */ public static SkillObject reflectiveSetValue(SkillObject obj, Object value, String fieldName, String fieldType) { try { Method setterMethod = obj.getClass().getMethod(getSetterName(fieldName), getAptClass(fieldType)); System.out.println("Found method " + setterMethod.getName()); setterMethod.invoke(obj, value); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return null; } /** * Get a Class object from a fully qualified class name incl. package * identifier * * @param type * fully qualified class name * @return Class object for the provided class name * @throws ClassNotFoundException */ private static Class<?> getAptClass(String type) throws ClassNotFoundException { if (!isBuiltInType(type)) { return Class.forName(type); } else { switch (type) { case "byte": return byte.class; case "short": return short.class; case "int": return int.class; case "long": return long.class; case "float": return float.class; case "double": return double.class; case "boolean": return boolean.class; case "char": return char.class; default: return null; } } } /** * Parse a value encoded in a string to the specified type * * @param type * @param valueString * @return instance of the actual class of the provided value */ public static Object valueOf(String type, String valueString) { switch (type) { case "byte": return Byte.valueOf(valueString); case "short": return Short.valueOf(valueString); case "int": return Integer.valueOf(valueString); case "long": return Long.valueOf(valueString); case "float": return Float.valueOf(valueString); case "double": return Double.valueOf(valueString); case "boolean": return Boolean.valueOf(valueString); case "char": return Character.valueOf(valueString.charAt(0)); default: return null; } } /** * Checks whether a provided class name is a primitive type * * @param type * the name of the class to be checked * @return true, if type is a primitive type. False, otherwise. */ public static boolean isBuiltInType(String type) { return SKilLType.fromString(type) != null; } /** * Return the method name of the setter method responsible for the field * with the name 'fieldName'. * * @param fieldName * the name of the field for which to get the name of the setter * method * @return the name of the setter method */ public static String getSetterName(String fieldName) { return "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); } /** * Create a mapping of field names and their corresponding types of the * given class. * * @param className * the name of the class for which to generate the mapping * @return a mapping of field names to Type objects */ public static Map<String, Type> getFieldMapping(String className) { Map<String, Type> fieldTypeMapping; try { Class<?> cls = Class.forName(className); Field[] declaredFields = cls.getDeclaredFields(); fieldTypeMapping = new HashMap<>(declaredFields.length); for (Field field : declaredFields) { fieldTypeMapping.put(field.getName(), field.getGenericType()); } return fieldTypeMapping; } catch (ClassNotFoundException e) { e.printStackTrace(); } return null; } /** * Create a mapping of field names and their corresponding types of the * given class. * * @param cls * the class for which to generate the mapping * @return a mapping of field names to Type objects */ public static Map<String, Type> getFieldMapping(Class<?> cls) { Map<String, Type> fieldTypeMapping; Field[] declaredFields = cls.getDeclaredFields(); fieldTypeMapping = new HashMap<>(declaredFields.length); for (Field field : declaredFields) { fieldTypeMapping.put(field.getName(), field.getGenericType()); } return fieldTypeMapping; } }
package org.broadinstitute.sting.gatk.walkers.genotyper; import net.sf.samtools.SAMRecord; import net.sf.samtools.SAMUtils; import org.broadinstitute.sting.utils.*; import org.broadinstitute.sting.utils.exceptions.UserException; import org.broadinstitute.sting.utils.sam.GATKSAMRecord; import org.broadinstitute.sting.utils.pileup.ReadBackedPileup; import org.broadinstitute.sting.utils.pileup.PileupElement; import org.broadinstitute.sting.utils.genotype.DiploidGenotype; import static java.lang.Math.log10; import static java.lang.Math.pow; /** * Stable, error checking version of the Bayesian genotyper. Useful for calculating the likelihoods, priors, * and posteriors given a pile of bases and quality scores * * Suppose we have bases b1, b2, ..., bN with qualities scores q1, q2, ..., qN. This object * calculates: * * P(G | D) = P(G) * P(D | G) * * where * * P(D | G) = sum_i log10 P(bi | G) * * and * * P(bi | G) = 1 - P(error | q1) if bi is in G * = P(error | q1) / 3 if bi is not in G * * for homozygous genotypes and for heterozygous genotypes: * * P(bi | G) = 1 - P(error | q1) / 2 + P(error | q1) / 6 if bi is in G * = P(error | q1) / 3 if bi is not in G * * for each of the 10 unique diploid genotypes AA, AC, AG, .., TT * * Everything is stored as arrays indexed by DiploidGenotype.ordinal() values in log10 space. * * The priors contain the relative probabilities of each genotype, and must be provided at object creation. * From then on, you can call any of the add() routines to update the likelihoods and posteriors in the above * model. */ public class DiploidSNPGenotypeLikelihoods implements Cloneable { protected final static int FIXED_PLOIDY = 2; protected final static int MAX_PLOIDY = FIXED_PLOIDY + 1; protected final static double ploidyAdjustment = log10(FIXED_PLOIDY); protected final static double log10_3 = log10(3.0); protected boolean VERBOSE = false; // The fundamental data arrays associated with a Genotype Likelhoods object protected double[] log10Likelihoods = null; protected double[] log10Posteriors = null; protected DiploidSNPGenotypePriors priors = null; /** * Create a new GenotypeLikelhoods object with flat priors for each diploid genotype * */ public DiploidSNPGenotypeLikelihoods() { this.priors = new DiploidSNPGenotypePriors(); setToZero(); } /** * Create a new GenotypeLikelhoods object with given priors for each diploid genotype * * @param priors priors */ public DiploidSNPGenotypeLikelihoods(DiploidSNPGenotypePriors priors) { this.priors = priors; setToZero(); } /** * Cloning of the object * @return clone * @throws CloneNotSupportedException */ protected Object clone() throws CloneNotSupportedException { DiploidSNPGenotypeLikelihoods c = (DiploidSNPGenotypeLikelihoods)super.clone(); c.priors = priors; c.log10Likelihoods = log10Likelihoods.clone(); c.log10Posteriors = log10Posteriors.clone(); return c; } protected void setToZero() { log10Likelihoods = genotypeZeros.clone(); // likelihoods are all zeros log10Posteriors = priors.getPriors().clone(); // posteriors are all the priors } /** * Returns an array of log10 likelihoods for each genotype, indexed by DiploidGenotype.ordinal values() * @return likelihoods array */ public double[] getLikelihoods() { return log10Likelihoods; } /** * Returns the likelihood associated with DiploidGenotype g * @param g genotype * @return log10 likelihood as a double */ public double getLikelihood(DiploidGenotype g) { return getLikelihoods()[g.ordinal()]; } /** * Returns an array of posteriors for each genotype, indexed by DiploidGenotype.ordinal values(). * * @return raw log10 (not-normalized posteriors) as a double array */ public double[] getPosteriors() { return log10Posteriors; } /** * Returns the posterior associated with DiploidGenotype g * @param g genotpe * @return raw log10 (not-normalized posteror) as a double */ public double getPosterior(DiploidGenotype g) { return getPosteriors()[g.ordinal()]; } /** * Returns an array of posteriors for each genotype, indexed by DiploidGenotype.ordinal values(). * * @return normalized posterors as a double array */ public double[] getNormalizedPosteriors() { double[] normalized = new double[log10Posteriors.length]; double sum = 0.0; // for precision purposes, we need to add (or really subtract, since everything is negative) // the largest posterior value from all entries so that numbers don't get too small double maxValue = log10Posteriors[0]; for (int i = 1; i < log10Posteriors.length; i++) { if ( maxValue < log10Posteriors[i] ) maxValue = log10Posteriors[i]; } // collect the posteriors for ( DiploidGenotype g : DiploidGenotype.values() ) { double posterior = Math.pow(10, getPosterior(g) - maxValue); normalized[g.ordinal()] = posterior; sum += posterior; } // normalize for (int i = 0; i < normalized.length; i++) normalized[i] /= sum; return normalized; } public DiploidSNPGenotypePriors getPriorObject() { return priors; } /** * Returns an array of priors for each genotype, indexed by DiploidGenotype.ordinal values(). * * @return log10 prior as a double array */ public double[] getPriors() { return priors.getPriors(); } /** * Sets the priors * @param priors priors */ public void setPriors(DiploidSNPGenotypePriors priors) { this.priors = priors; log10Posteriors = genotypeZeros.clone(); for ( DiploidGenotype g : DiploidGenotype.values() ) { int i = g.ordinal(); log10Posteriors[i] = priors.getPriors()[i] + log10Likelihoods[i]; } } /** * Returns the prior associated with DiploidGenotype g * @param g genotype * @return log10 prior as a double */ public double getPrior(DiploidGenotype g) { return getPriors()[g.ordinal()]; } public int add(ReadBackedPileup pileup) { return add(pileup, false, false); } /** * Updates likelihoods and posteriors to reflect the additional observations contained within the * read-based pileup up by calling add(observedBase, qualityScore) for each base / qual in the * pileup * * @param pileup read pileup * @param ignoreBadBases should we ignore bad bases? * @param capBaseQualsAtMappingQual should we cap a base's quality by its read's mapping quality? * @return the number of good bases found in the pileup */ public int add(ReadBackedPileup pileup, boolean ignoreBadBases, boolean capBaseQualsAtMappingQual) { int n = 0; // todo: first validate that my changes were good by passing in fragments representing just a single read... //Set<PerFragmentPileupElement> fragments = new HashSet<PerFragmentPileupElement>(); for ( PileupElement p : pileup ) { if ( usableBase(p, ignoreBadBases) ) { byte qual = capBaseQualsAtMappingQual ? (byte)Math.min((int)p.getQual(), p.getMappingQual()) : p.getQual(); n += add(p.getBase(), qual, p.getRead(), p.getOffset()); } } return n; } // public int add(PerFragmentPileupElement fragment, boolean capBaseQualsAtMappingQual) { public int add(byte observedBase, byte qualityScore, SAMRecord read, int offset) { if ( qualityScore == 0 ) { // zero quals are wrong return 0; } // Just look up the cached result if it's available, or compute and store it DiploidSNPGenotypeLikelihoods gl; if ( ! inCache( observedBase, qualityScore, FIXED_PLOIDY, read) ) { gl = calculateCachedGenotypeLikelihoods(observedBase, qualityScore, FIXED_PLOIDY, read, offset); } else { gl = getCachedGenotypeLikelihoods(observedBase, qualityScore, FIXED_PLOIDY, read); } // for bad bases, there are no likelihoods if ( gl == null ) return 0; double[] likelihoods = gl.getLikelihoods(); for ( DiploidGenotype g : DiploidGenotype.values() ) { double likelihood = likelihoods[g.ordinal()]; if ( VERBOSE ) { boolean fwdStrand = ! read.getReadNegativeStrandFlag(); System.out.printf(" L(%c | G=%s, Q=%d, S=%s) = %f / %f%n", observedBase, g, qualityScore, fwdStrand ? "+" : "-", pow(10,likelihood) * 100, likelihood); } log10Likelihoods[g.ordinal()] += likelihood; log10Posteriors[g.ordinal()] += likelihood; } return 1; } static DiploidSNPGenotypeLikelihoods[][][][] CACHE = new DiploidSNPGenotypeLikelihoods[BaseUtils.BASES.length][QualityUtils.MAX_QUAL_SCORE+1][MAX_PLOIDY][2]; protected boolean inCache( byte observedBase, byte qualityScore, int ploidy, SAMRecord read) { return getCache(CACHE, observedBase, qualityScore, ploidy, read) != null; } protected DiploidSNPGenotypeLikelihoods getCachedGenotypeLikelihoods( byte observedBase, byte qualityScore, int ploidy, SAMRecord read) { DiploidSNPGenotypeLikelihoods gl = getCache(CACHE, observedBase, qualityScore, ploidy, read); if ( gl == null ) throw new RuntimeException(String.format("BUG: trying to fetch an unset cached genotype likelihood at base=%c, qual=%d, ploidy=%d, read=%s", observedBase, qualityScore, ploidy, read)); return gl; } protected DiploidSNPGenotypeLikelihoods calculateCachedGenotypeLikelihoods(byte observedBase, byte qualityScore, int ploidy, SAMRecord read, int offset) { DiploidSNPGenotypeLikelihoods gl = calculateGenotypeLikelihoods(observedBase, qualityScore, read, offset); setCache(CACHE, observedBase, qualityScore, ploidy, read, gl); return gl; } protected void setCache( DiploidSNPGenotypeLikelihoods[][][][] cache, byte observedBase, byte qualityScore, int ploidy, SAMRecord read, DiploidSNPGenotypeLikelihoods val ) { int i = BaseUtils.simpleBaseToBaseIndex(observedBase); int j = qualityScore; if ( j > SAMUtils.MAX_PHRED_SCORE ) throw new UserException.MalformedBam(read, String.format("the maximum allowed quality score is %d, but a quality of %d was observed in read %s. Perhaps your BAM incorrectly encodes the quality scores in Sanger format; see http://en.wikipedia.org/wiki/FASTQ_format for more details", SAMUtils.MAX_PHRED_SCORE, j, read.getReadName())); int k = ploidy; int x = strandIndex(! read.getReadNegativeStrandFlag() ); cache[i][j][k][x] = val; } protected DiploidSNPGenotypeLikelihoods getCache( DiploidSNPGenotypeLikelihoods[][][][] cache, byte observedBase, byte qualityScore, int ploidy, SAMRecord read) { int i = BaseUtils.simpleBaseToBaseIndex(observedBase); int j = qualityScore; if ( j > SAMUtils.MAX_PHRED_SCORE ) throw new UserException.MalformedBam(read, String.format("the maximum allowed quality score is %d, but a quality of %d was observed in read %s. Perhaps your BAM incorrectly encodes the quality scores in Sanger format; see http://en.wikipedia.org/wiki/FASTQ_format for more details", SAMUtils.MAX_PHRED_SCORE, j, read.getReadName())); int k = ploidy; int x = strandIndex(! read.getReadNegativeStrandFlag() ); return cache[i][j][k][x]; } protected DiploidSNPGenotypeLikelihoods calculateGenotypeLikelihoods(byte observedBase, byte qualityScore, SAMRecord read, int offset) { double[] log10FourBaseLikelihoods = computeLog10Likelihoods(observedBase, qualityScore, read); try { DiploidSNPGenotypeLikelihoods gl = (DiploidSNPGenotypeLikelihoods)this.clone(); gl.setToZero(); // we need to adjust for ploidy. We take the raw p(obs | chrom) / ploidy, which is -log10(ploidy) in log space for ( DiploidGenotype g : DiploidGenotype.values() ) { // todo assumes ploidy is 2 -- should be generalized. Obviously the below code can be turned into a loop double p_base = 0.0; p_base += pow(10, log10FourBaseLikelihoods[BaseUtils.simpleBaseToBaseIndex(g.base1)] - ploidyAdjustment); p_base += pow(10, log10FourBaseLikelihoods[BaseUtils.simpleBaseToBaseIndex(g.base2)] - ploidyAdjustment); double likelihood = log10(p_base); gl.log10Likelihoods[g.ordinal()] += likelihood; gl.log10Posteriors[g.ordinal()] += likelihood; } if ( VERBOSE ) { for ( DiploidGenotype g : DiploidGenotype.values() ) { System.out.printf("%s\t", g); } System.out.println(); for ( DiploidGenotype g : DiploidGenotype.values() ) { System.out.printf("%.2f\t", gl.log10Likelihoods[g.ordinal()]); } System.out.println(); } return gl; } catch ( CloneNotSupportedException e ) { throw new RuntimeException(e); } } /** * Updates likelihoods and posteriors to reflect an additional observation of observedBase with * qualityScore. * * @param observedBase observed base * @param qualityScore base quality * @param read SAM read * @return likelihoods for this observation or null if the base was not considered good enough to add to the likelihoods (Q0 or 'N', for example) */ protected double[] computeLog10Likelihoods(byte observedBase, byte qualityScore, SAMRecord read) { double[] log10FourBaseLikelihoods = baseZeros.clone(); for ( byte base : BaseUtils.BASES ) { double likelihood = log10PofObservingBaseGivenChromosome(observedBase, base, qualityScore); if ( VERBOSE ) { boolean fwdStrand = ! read.getReadNegativeStrandFlag(); System.out.printf(" L(%c | b=%s, Q=%d, S=%s) = %f / %f%n", observedBase, base, qualityScore, fwdStrand ? "+" : "-", pow(10,likelihood) * 100, likelihood); } log10FourBaseLikelihoods[BaseUtils.simpleBaseToBaseIndex(base)] = likelihood; } return log10FourBaseLikelihoods; } /** * * @param observedBase observed base * @param chromBase target base * @param qual base quality * @return log10 likelihood */ protected double log10PofObservingBaseGivenChromosome(byte observedBase, byte chromBase, byte qual) { double logP; if ( observedBase == chromBase ) { // the base is consistent with the chromosome -- it's 1 - e //logP = oneMinusData[qual]; double e = pow(10, (qual / -10.0)); logP = log10(1.0 - e); } else { // the base is inconsistent with the chromosome -- it's e * P(chromBase | observedBase is an error) logP = qual / -10.0 + (-log10_3); } //System.out.printf("%c %c %d => %f%n", observedBase, chromBase, qual, logP); return logP; } // helper routines public static int strandIndex(boolean fwdStrand) { return fwdStrand ? 0 : 1; } /** * Returns true when the observedBase is considered usable. * @param p pileup element * @param ignoreBadBases should we ignore bad bases? * @return true if the base is a usable base */ protected static boolean usableBase(PileupElement p, boolean ignoreBadBases) { // ignore deletions and filtered bases if ( p.isDeletion() || (p.getRead() instanceof GATKSAMRecord && !((GATKSAMRecord)p.getRead()).isGoodBase(p.getOffset())) ) return false; return ( !ignoreBadBases || !badBase(p.getBase()) ); } /** * Returns true when the observedBase is considered bad and shouldn't be processed by this object. A base * is considered bad if: * * Criterion 1: observed base isn't a A,C,T,G or lower case equivalent * * @param observedBase observed base * @return true if the base is a bad base */ protected static boolean badBase(byte observedBase) { return BaseUtils.simpleBaseToBaseIndex(observedBase) == -1; } /** * Return a string representation of this object in a moderately usable form * * @return string representation */ public String toString() { double sum = 0; StringBuilder s = new StringBuilder(); for (DiploidGenotype g : DiploidGenotype.values()) { s.append(String.format("%s %.10f ", g, log10Likelihoods[g.ordinal()])); sum += Math.pow(10,log10Likelihoods[g.ordinal()]); } s.append(String.format(" %f", sum)); return s.toString(); } // Validation routines public boolean validate() { return validate(true); } public boolean validate(boolean throwException) { try { priors.validate(throwException); for ( DiploidGenotype g : DiploidGenotype.values() ) { String bad = null; int i = g.ordinal(); if ( ! MathUtils.wellFormedDouble(log10Likelihoods[i]) || ! MathUtils.isNegativeOrZero(log10Likelihoods[i]) ) { bad = String.format("Likelihood %f is badly formed", log10Likelihoods[i]); } else if ( ! MathUtils.wellFormedDouble(log10Posteriors[i]) || ! MathUtils.isNegativeOrZero(log10Posteriors[i]) ) { bad = String.format("Posterior %f is badly formed", log10Posteriors[i]); } if ( bad != null ) { throw new IllegalStateException(String.format("At %s: %s", g.toString(), bad)); } } } catch ( IllegalStateException e ) { if ( throwException ) throw new RuntimeException(e); else return false; } return true; } // Constant static data private final static double[] genotypeZeros = new double[DiploidGenotype.values().length]; private final static double[] baseZeros = new double[BaseUtils.BASES.length]; static { for ( DiploidGenotype g : DiploidGenotype.values() ) { genotypeZeros[g.ordinal()] = 0.0; } for ( byte base : BaseUtils.BASES ) { baseZeros[BaseUtils.simpleBaseToBaseIndex(base)] = 0.0; } } }
package creator; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import de.ust.skill.common.java.internal.SkillObject; public class SkillObjectCreator { private static final String FIELD_DECLARATION_CLASS_NAME = "de.ust.skill.common.java.api.FieldDeclaration"; public static void main(String[] args){ String className = "age.Age"; String fieldToSet = "age"; String fieldTypeToSet = "long"; Long valueToSet = 255L; Map<String, Object> values = new HashMap<>(); Map<String, String> fieldTypes = new HashMap<>(); values.put(fieldToSet, valueToSet); fieldTypes.put(fieldToSet, fieldTypeToSet); try { SkillObject obj = instantiateSkillObject(className, values, fieldTypes); System.out.println(obj.prettyString()); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } /** * Create an empty SkillObject from a fully specified class name * @param className fully classified class name incl. package identifier * @return empty SkillObject of the specified class */ public static SkillObject createSkillObject(String className) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{ Class<?> refClass = Class.forName(className); Constructor<?> refConstructor = refClass.getConstructor(); SkillObject refVar = (SkillObject) refConstructor.newInstance(); return refVar; } /** * Create and fill a SkillObject with the provided values * @param className fully specified class name incl. package identifier of the object to be created * @param values mapping of field names to values * @param fieldTypes mapping of field names to the corresponding types of values * @return a SkillObject with the provided values as attributes */ public static SkillObject instantiateSkillObject(String className, Map<String, Object> values, Map<String, String> fieldTypes) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{ SkillObject obj = createSkillObject(className); Map<String, Type> fieldMapping = getFieldMapping(className); for(String key : fieldMapping.keySet()){ String type = fieldMapping.get(key).getTypeName(); System.out.println("Present field: " + key + "(Type: " + type + ")"); if(values.containsKey(key)){ System.out.println("Setting field '" + key + "'"); reflectiveSetValue(obj, values.get(key) , key, fieldTypes.get(key)); } } return obj; } /** * Set the specified field of a SkillObject to a given value * @param obj the SkillObject for which the field is to be set * @param value the value to set the field of the SkillObject to * @param fieldName the name of the field to be set * @param fieldType fully qualified class name of the field to be set * @return the provided SkillObject with a set new value */ public static SkillObject reflectiveSetValue(SkillObject obj, Object value, String fieldName, String fieldType){ try { Method setterMethod = obj.getClass().getMethod(getSetterName(fieldName), getAptClass(fieldType)); System.out.println("Found method " + setterMethod.getName()); setterMethod.invoke(obj, value); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return null; } /** * Get a Class object from a fully qualified class name incl. package identifier * @param type fully qualified class name * @return Class object for the provided class name * @throws ClassNotFoundException */ private static Class<?> getAptClass(String type) throws ClassNotFoundException { if(!isPrimitive(type)){ return Class.forName(type); }else{ switch(type){ case "byte": return byte.class; case "short": return short.class; case "int": return int.class; case "long": return long.class; case "float": return float.class; case "double": return double.class; case "boolean": return boolean.class; case "char": return char.class; default: return null; } } } /** * Parse a value encoded in a string to the specified type * @param type * @param valueString * @return instance of the actual class of the provided value */ public static Object valueOf(String type, String valueString){ switch(type){ case "byte": return Byte.valueOf(valueString); case "short": return Short.valueOf(valueString); case "int": return Integer.valueOf(valueString); case "long": return Long.valueOf(valueString); case "float": return Float.valueOf(valueString); case "double": return Double.valueOf(valueString); case "boolean": return Boolean.valueOf(valueString); case "char": return Character.valueOf(valueString.charAt(0)); default: return null; } } /** * Checks whether a provided class name is a primitive type * @param type the name of the class to be checked * @return true, if type is a primitive type. False, otherwise. */ private static boolean isPrimitive(String type) { String[] primitiveTypes = {"byte", "short", "int", "long", "float", "double", "boolean", "char"}; return Arrays.asList(primitiveTypes).contains(type); } /** * Return the method name of the setter method responsible for the field * with the name 'fieldName'. * * @param fieldName the name of the field for which to get the name of the setter method * @return the name of the setter method */ public static String getSetterName(String fieldName){ return "set" + fieldName.substring(0,1).toUpperCase() + fieldName.substring(1); } /** * Create a mapping of field names and their corresponding types of the given class. * @param className the name of the class for which to generate the mapping * @return a mapping of field names to Type objects */ public static Map<String, Type> getFieldMapping(String className){ Map<String, Type> fieldTypeMapping; try { Class<?> cls = Class.forName(className); Field[] declaredFields = cls.getDeclaredFields(); fieldTypeMapping = new HashMap<>(declaredFields.length); for(Field field : declaredFields){ fieldTypeMapping.put(field.getName(), field.getGenericType()); } return fieldTypeMapping; } catch (ClassNotFoundException e) { e.printStackTrace(); } return null; } /** * Create a mapping of field names and their corresponding types of the given class. * @param cls the class for which to generate the mapping * @return a mapping of field names to Type objects */ public static Map<String, Type> getFieldMapping(Class<?> cls){ Map<String, Type> fieldTypeMapping; Field[] declaredFields = cls.getDeclaredFields(); fieldTypeMapping = new HashMap<>(declaredFields.length); for(Field field : declaredFields){ fieldTypeMapping.put(field.getName(), field.getGenericType()); } return fieldTypeMapping; } }
package de.gbv.ole; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.text.Normalizer; import java.util.HashMap; import java.util.Map; import java.util.ResourceBundle; import java.util.SortedMap; import java.util.TreeMap; import javax.xml.transform.OutputKeys; import javax.xml.transform.Result; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.sax.TransformerHandler; import javax.xml.transform.stream.StreamResult; import org.apache.commons.lang3.StringUtils; import org.marc4j.Constants; import org.marc4j.MarcException; import org.marc4j.MarcStreamReader; import org.marc4j.MarcWriter; import org.marc4j.converter.CharConverter; import org.marc4j.marc.ControlField; import org.marc4j.marc.DataField; import org.marc4j.marc.MarcFactory; import org.marc4j.marc.Record; import org.marc4j.marc.Subfield; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; public class Marc21ToOleBulk implements MarcWriter { /** Factory to create MARC data structures */ protected static final MarcFactory marcFactory = MarcFactory.newInstance(); /** Suffix .mrc der MARC21-Datei. */ private static final String MRCSUFFIX = ".mrc"; /** XML-Tagname. */ protected static final String COLLECTION = "collection"; /** XML-Tagname. */ protected static final String RECORD = "record"; /** XML-Tagname. */ protected static final String LEADER = "leader"; /** XML-Tagname. */ protected static final String CONTROL_FIELD = "controlfield"; /** XML-Tagname. */ protected static final String DATA_FIELD = "datafield"; /** XML-Tagname. */ protected static final String SUBFIELD = "subfield"; protected static final Map<String,String> convertLocation = new HashMap<String,String>(); static { convertLocation.put("ALT", "UB/BIBO"); convertLocation.put("Alt", "UB/BIBO"); convertLocation.put("AMI", "UB/BIBO"); convertLocation.put("Arbeitsbibliothek Holthusen", "UB/BIBO"); convertLocation.put("AZP", "UB/BIBO"); convertLocation.put("HA", "UB/BIBO"); convertLocation.put("HB", "UB/BIBO"); convertLocation.put("HI/UB/LS", "UB/BIBO"); convertLocation.put("LEIHSTELLE", "UB/BIBO"); convertLocation.put("Leihstelle", "UB/BIBO"); convertLocation.put("Leselounge", "UB/BIBO"); convertLocation.put("LS-NUTZUNG", "UB/BIBO"); convertLocation.put("!MAGAZIN", "UB/MAG"); convertLocation.put("HI/UB/MG", "UB/MAG"); convertLocation.put("MAGAZIN", "UB/MAG"); convertLocation.put("Magazin", "UB/MAG"); convertLocation.put("Verlust", "UB/MAG"); convertLocation.put("ZSS-Dublettenlager", "UB/MAG"); convertLocation.put("ZSS-MAGAZIN", "UB/MAG"); convertLocation.put("ZSS-Magazin", "UB/MAG"); convertLocation.put("MEDIENARCHIV", "UB/BIBO"); convertLocation.put("Medienarchiv", "UB/BIBO"); convertLocation.put("MEDIOTHEK", "UB/BIBO"); convertLocation.put("Mediothek", "UB/BIBO"); convertLocation.put("MIKROFORM", "UB/BIBO"); convertLocation.put("MiKROFORM", "UB/BIBO"); convertLocation.put("ATLANTENSCHRANK", "UB/BIBO"); convertLocation.put("Ausgeschieden", "UB/BIBO"); convertLocation.put("HI", "UB/BIBO"); convertLocation.put("Makuliert", "UB/BIBO"); convertLocation.put("PRF", "UB/BIBO"); convertLocation.put("PRZ", "UB/BIBO"); convertLocation.put("RARA", "UB/BIBO"); convertLocation.put("Rara", "UB/BIBO"); convertLocation.put("STA", "UB/BIBO"); convertLocation.put("", "UB/BIBO"); } /** * Type of an item * <li>{@link #BUA}</li> * <li>{@link #BUP}</li> * <li>{@link #BUZ}</li> * <li>{@link #AVA}</li> * <li>{@link #AVP}</li> * <li>{@link #AVZ}</li> * <li>{@link #ZSP}</li> * <li>{@link #MKP}</li> */ enum ItemType { /** BUA Buch ausleihbar */ BUA(90), BUP(91), /** BUZ Buch nach Zustimmung ausleihbar */ BUZ(92), /** AVA AV ausleihbar */ AVA(93), AVP(94), /** AVZ AV nach Zustimmung ausleihbar */ AVZ(95), ZSP(96), MKP(97); private int value; private ItemType(int value) { this.value = value; } } /** True to output only PPNs with 5 before check digit */ private boolean ppn5 = false; /** XML transformer handler. */ private TransformerHandler handler = null; /** bib output stream. */ private Writer bibWriter = null; /** holdings output stream. */ private Writer holdingsWriter = null; /** item output stream. */ private Writer itemWriter = null; /** * Print usage to System.err and exit the program. */ private static void usageExit() { ResourceBundle messages = ResourceBundle.getBundle("application"); System.err.println(messages.getString("usage")); System.exit(1); } /** * Setup of output. * @param bib bib destination * @param holdings holdings destination * @param item item destination * @param ppn5 true to output only PPNs with 5 before check digit */ public Marc21ToOleBulk(final Writer bibWriter, final Writer holdingsWriter, final Writer itemWriter, final boolean ppn5) { this.bibWriter = bibWriter; this.holdingsWriter = holdingsWriter; this.itemWriter = itemWriter; setHandler(new StreamResult(bibWriter)); this.ppn5 = ppn5; } /** * Set the <code>Result</code> associated with this * <code>TransformerHandler</code> to be used for the transformation. * * @param result the Result to be used for the transformation */ protected final void setHandler(final Result result) { try { TransformerFactory factory = TransformerFactory.newInstance(); if (!factory.getFeature(SAXTransformerFactory.FEATURE)) { throw new UnsupportedOperationException( "SAXTransformerFactory is not supported"); } SAXTransformerFactory saxFactory = (SAXTransformerFactory) factory; handler = saxFactory.newTransformerHandler(); handler.getTransformer() .setOutputProperty(OutputKeys.METHOD, "xml"); handler.setResult(result); } catch (Exception e) { throw new MarcException(e.getMessage(), e); } } /** * Return the input without the tailing check digit. * * Example: * withoutCheckdigit("123456789X") = "123456789" * withoutCheckdigit("987654321") = "98765432" * * @param numberWithCheckdigit - number including check digit * @return number without check digit */ static final String withoutCheckdigit(final String numberWithCheckdigit) { return StringUtils.left(numberWithCheckdigit, numberWithCheckdigit.length() - 1); } static final String isbn10checkdigit(final int number) { if (number < 0 || number > 999999999) { throw new IllegalArgumentException( "number from range 0 .. 999999999 expected, " + "but found " + number); } int n = number; int sum = 0; int factor = 9; while (n != 0) { sum += (n % 10) * factor; factor n /= 10; } int checkdigit = sum % 11; if (checkdigit == 10) { return "X"; } return Integer.toString(checkdigit); } /** * Throws a MarcException if the parameter is not a valid isbn10 number * with valid check digit. * * Valid: "00", "19", "27", * "2121212124", * "9999999980", * "9999999999" * * @param isbn10 the number to validate */ static void validateIsbn10(final String isbn10) { if (StringUtils.isEmpty(isbn10)) { throw new MarcException("null or empty number"); } if (StringUtils.isWhitespace(isbn10)) { throw new MarcException( "number expected, found only whitespace"); } if (StringUtils.containsWhitespace(isbn10)) { throw new MarcException( "number plus check digit expected, but contains " + "whitespace: '" + isbn10 + "'"); } if (isbn10.length() < 2) { throw new MarcException("number plus check digit expected, " + "but found: " + isbn10); } if (isbn10.length() > 10) { throw new MarcException("maximum length of number plus " + "check digit is 10 (9 + 1 check digit),\n" + "input is " + isbn10.length() + " characters long: " + isbn10); } String checkdigit = StringUtils.right(isbn10, 1); if (!StringUtils.containsOnly(checkdigit, "0123456789xX")) { throw new MarcException("check digit must be 0-9, x or X, " + "but is " + checkdigit); } String number = withoutCheckdigit(isbn10); if (!StringUtils.containsOnly(number, "0123456789")) { throw new MarcException("number before check digit must " + "contain 0-9 only, but is " + checkdigit); } String calculatedCheckdigit = isbn10checkdigit(Integer.parseInt(number)); if (! StringUtils.equalsIgnoreCase(checkdigit, calculatedCheckdigit)) { throw new MarcException("wrong checkdigit " + checkdigit + ", correct check digit is " + calculatedCheckdigit + ": " + isbn10); } } /** * Write the Record object to the output files. * * @param record - the <code>Record</code> object */ public final void write(final Record record) { /* get control field 001 */ String ppn = record.getControlNumber(); if (ppn5) { // das reduziert den Datenumfang auf ca. 10 % if (! StringUtils.substring(ppn, -2, -1).equals("5")) { return; } } try { validateIsbn10(ppn); bibWriter.write(withoutCheckdigit(ppn)); bibWriter.write("\t"); toXml(ppn, record); bibWriter.write("\n"); } catch (Exception e) { throw new MarcException("Control field 001 (PPN): " + ppn, e); } } /** * Start the element using <code>handler</code>. * * @param name used for localName and qName * @param atts the attributes to attach to the element * @throws SAXException bei XML-Fehler */ private void startElement(final String name, final Attributes atts) throws SAXException { handler.startElement(Constants.MARCXML_NS_URI, name, name, atts); } /** * Start the element without attributes using <code>handler</code>. * * @param name used for localName and qName * @throws SAXException bei XML-Fehler */ private void startElement(final String name) throws SAXException { AttributesImpl atts = new AttributesImpl(); startElement(name, atts); } /** * End the element using <code>handler</code>. * * @param name used for localName and qName * @throws SAXException bei XML-Fehler */ private void endElement(final String name) throws SAXException { handler.endElement(Constants.MARCXML_NS_URI, name, name); } /** * Add an CDATA attribute. * * @param atts where to add * @param name used for localName and qName * @param value attribute value */ private void add(final AttributesImpl atts, final String name, final String value) { atts.addAttribute("", name, name, "CDATA", value); } /** * Add an CDATA attribute. * * @param atts where to add * @param name used for localName and qName * @param value attribute value */ private void add(final AttributesImpl atts, final String name, final char value) { atts.addAttribute("", name, name, "CDATA", String.valueOf(value)); } /** * Write data to bib output. * * Does Unicode NFC normalization. * * Masks these four characters: \n \r \t \\ * This masking is needed for LOAD DATA INFILE. * * @param data data to write * @throws SAXException on write error */ private void write(final String data) throws SAXException { String normalized = Normalizer.normalize(data, Normalizer.Form.NFC); char [] charArray = StringUtils.replaceEach(normalized, new String[]{ "\n", "\r", "\t", "\\", }, new String[]{"\\\n", "\\\r", "\\\t", "\\\\", }).toCharArray(); handler.characters(charArray, 0, charArray.length); } /** * Print the content of field as a multiline String. * @param field content to print * @return multiline String */ final static String print(final DataField field) { StringBuffer s = new StringBuffer(); s.append(field.getTag()); s.append(' ').append(field.getIndicator1()); s.append(' ').append(field.getIndicator2()); s.append('\n'); for (Subfield subfield : field.getSubfields()) { s.append(subfield.getCode()).append(' '). append(subfield.getData()).append('\n'); } return s.toString(); } void write(String ppn, Record record, Map<String, Exemplar> exemplare) throws IOException { SortedMap<String, Exemplar> sort = new TreeMap<String, Exemplar>(exemplare); for (Map.Entry<String, Exemplar> e : sort.entrySet()) { String exemplarnummer = e.getKey(); Exemplar exemplar = e.getValue(); fetchItemType(record, exemplar); write(ppn, exemplarnummer, exemplar); } } void write(String ppn, String exemplarnummer, Exemplar exemplar) throws IOException { String ppnCut = withoutCheckdigit(ppn); String epnCut = withoutCheckdigit(exemplar.epn); // holdings_id=epnCut, bib_id=ppnCut holdingsWriter.write( epnCut + "\t" // holdings_id + ppnCut + "\t" // bib_id + exemplar.location + "\t" + exemplar.callnumber + "\t" + exemplar.shelvingOrder + "\n"); // item_id=epnCut, holdings_id=epnCut itemWriter.write( epnCut + "\t" // item_id + epnCut + "\t" // holdings_id + exemplar.barcode + "\t" + exemplar.itemType + "\n"); // item_type_id (ole_cat_itm_typ_t) } /** * Writes a Record object to the result. * * @param ppn PPN of the record * @param record - * the <code>Record</code> object * @throws SAXException */ protected final void toXml(final String ppn, final Record record) throws SAXException, IOException { if (!marcFactory.validateRecord(record)) { throw new MarcException("Marc record didn't validate"); } startElement(COLLECTION); startElement(RECORD); startElement(LEADER); write(record.getLeader().toString()); endElement(LEADER); for (ControlField field : record.getControlFields()) { AttributesImpl atts = new AttributesImpl(); add(atts, "tag", field.getTag()); startElement(CONTROL_FIELD, atts); write(field.getData()); endElement(CONTROL_FIELD); } Map<String, Exemplar> exemplare = new HashMap<String, Exemplar>(); for (DataField field : record.getDataFields()) { if (field == null) { throw new MarcException("DataField is null"); } try { { AttributesImpl atts = new AttributesImpl(); add(atts, "tag", field.getTag()); add(atts, "ind1", field.getIndicator1()); add(atts, "ind2", field.getIndicator2()); startElement(DATA_FIELD, atts); } for (Subfield subfield : field.getSubfields()) { AttributesImpl atts = new AttributesImpl(); add(atts, "code", subfield.getCode()); startElement(SUBFIELD, atts); write(subfield.getData()); endElement(SUBFIELD); } endElement(DATA_FIELD); exemplar(field, exemplare); } catch (Exception e) { throw new MarcException( "Marc data field: " + print(field), e); } } endElement(RECORD); endElement(COLLECTION); write(ppn, record, exemplare); } /** * Returns true iff c is a digit from 0 .. 9. * @param c char to test * @return true if digit, false otherwise */ final static boolean isDigit(final char c) { return '0' <= c && c <= '9'; } /** * Liest Exemplarinformationen aus dem DataField, * schreibt sie nach exemplare, getrennt nach * Exemplarnummer. * @param field Datenquelle * @param exemplare Datenziel */ static void exemplar(final DataField field, Map<String, Exemplar> exemplare) { String tag = field.getTag(); if (!StringUtils.equals(tag, "980") && !StringUtils.equals(tag, "984") ) { return; } Subfield ilnSubfield = field.getSubfield('2'); if (ilnSubfield == null) { throw new MarcException( "ILN expected, but subfield 2 is missing"); } String iln = ilnSubfield.getData(); if (StringUtils.isBlank(iln)) { throw new MarcException( "ILN expected, but subfield 2 is empty"); } // wir wollen nur Hildesheimer Daten, ILN 90 if (!"90".equals(iln.trim())) { return; } Subfield exemplarmummerSubfield = field.getSubfield('1'); if (exemplarmummerSubfield == null) { throw new MarcException( "Exemplarnummer expected, but subfield 1 is missing"); } String exemplarnummer = exemplarmummerSubfield.getData(); if (StringUtils.isBlank(exemplarnummer)) { throw new MarcException( "Exemplarnummer expected, but subfield 1 is empty"); } exemplarnummer = exemplarnummer.trim(); if (exemplarnummer.length() != 2) { throw new MarcException( "Exemplarnummer with 2 digits expected, but found " + exemplarnummer); } if (! isDigit(exemplarnummer.charAt(0)) || ! isDigit(exemplarnummer.charAt(1)) ) { throw new MarcException( "Exemplarnummer with 2 digits expected, but found " + "a non-digit character: " + exemplarnummer); } Exemplar exemplar = exemplare.get(exemplarnummer); if (exemplar == null) { exemplar = new Exemplar(); exemplare.put(exemplarnummer, exemplar); } if ("980".equals(tag)) { fetchEPN(field, exemplar); fetchCallnumber(field, exemplar); fetchLocation(field, exemplar); fetchAusleihindikator(field, exemplar); } else if ("984".equals(tag)) { fetchBarcode(field, exemplar); } } final static String requiredSubfield( final DataField field, char subfieldName, String subfieldDescription) { Subfield subfield = field.getSubfield(subfieldName); if (subfield == null) { throw new MarcException( subfieldDescription + " expected, subfield " + subfieldName + " is missing"); } String value = subfield.getData(); if (StringUtils.isBlank(value)) { throw new MarcException( subfieldDescription + " expected, subfield " + subfieldName + " is empty"); } return value.trim(); } /** * Holt den Wert aus dem angegebenen Subfeld, macht trim(), * liefert "" statt null. * @param field MARC-Feld, in dem nach dem Subfeld gesucht wird * @param subfieldName Name des gesuchten Subfeldes * @return gesuchter Wert */ final static String optionalSubfield(final DataField field, char subfieldName) { Subfield subfield = field.getSubfield(subfieldName); if (subfield == null) { return ""; } return StringUtils.defaultString(subfield.getData()).trim(); } final static void fetchEPN(final DataField field, Exemplar exemplar) { exemplar.epn = requiredSubfield(field, 'b', "EPN"); validateIsbn10(exemplar.epn); } /** * Liest aus Subfeld a des MARC-Felds den optionalen Barcode und * schreibt ihn das Exemplar. * @param field MARC-Feld, das den Barcode enthalten kann * @param exemplar das Exemplar */ final static void fetchBarcode(final DataField field, Exemplar exemplar) { Subfield barcodeField = field.getSubfield('a'); if (barcodeField == null) { return; } String barcode = barcodeField.getData(); if (StringUtils.isBlank(barcode)) { throw new MarcException( "Barcode expected, subfield a is empty"); } exemplar.barcode = barcode.trim(); } final static void fetchCallnumber(final DataField field, Exemplar exemplar) { exemplar.callnumber = optionalSubfield(field, 'd'); exemplar.shelvingOrder = CallNumber.getShelvingOrder(exemplar.callnumber); } /** * Liest aus Subfeld f des MARC-Felds die optionale Location und * schreibt sie in das Exemplar. * @param field MARC-Feld, das die Location enthalten kann * @param exemplar das Exemplar */ final static void fetchLocation(final DataField field, Exemplar exemplar) { String location = optionalSubfield(field, 'f'); location = StringUtils.defaultString( convertLocation.get(location), location); exemplar.location = location; } /** * Return s if not empty, a single space otherwise. * @param s zu bearbeitender String, darf null sein * @return String, nicht null und nicht leer. */ final static String empty2space(String s) { if (s == null || "".equals(s)) { return " "; } return s; } /** * Liest aus Subfeld e des MARC-Felds den optionale Ausleihindikator * und schreibt ihn in das Exemplar. * @param field MARC-Feld, das den Ausleihindikator enthalten kann * @param exemplar das Exemplar */ final static void fetchAusleihindikator(final DataField field, Exemplar exemplar) { exemplar.ausleihindikator = empty2space( optionalSubfield(field, 'e')); } /** * Return the data of the control field with number tag with whitespace * trimmed. * @param record Where to search for the control field. * @param tag The number of the control field. * @return The data of the control field. * @throws MarcException if the control field does not exist, * is empty or contains only whitespace */ final static String getRequiredControlField(Record record, String tag) { for (ControlField controlField : record.getControlFields()) { if (! tag.equals(controlField.getTag())) { continue; } String data = StringUtils.trimToEmpty(controlField.getData()); if ("".equals(data)) { throw new MarcException("Control field " + tag + " is empty."); } return data; } throw new MarcException("Control field " + tag + " expected " + "but not found."); } /** * Return the data of the control field with number tag with * whitespace trimmed. * @param record Where to search for the control field. * @param tag The number of the control field. * @return The data of the control field, or an empty String if * the field does not exist or contains only whitespace */ final static String getOptionalControlField(Record record, String tag) { for (ControlField controlField : record.getControlFields()) { if (! tag.equals(controlField.getTag())) { continue; } return StringUtils.trimToEmpty(controlField.getData()); } return ""; } final static void fetchItemType(Record record, Exemplar exemplar) { int itemType = getItemType(record, exemplar); exemplar.itemType = Integer.toString(itemType); } final static int getItemType(Record record, Exemplar exemplar) { String leader = record.getLeader().toString(); String typeOfRecord = leader.substring(6, 7); String bibliographicLevel = leader.substring(7, 8); String field007 = getOptionalControlField(record, "007"); String categoryOfMaterial = empty2space( StringUtils.substring(field007, 0, 1)); String materialDesignation = empty2space( StringUtils.substring(field007, 1, 2)); if (typeOfRecord.equals("a") && "mb".contains(bibliographicLevel)) { if ("ubc".contains(exemplar.ausleihindikator)) { return ItemType.BUA.value; } if ("sd".contains(exemplar.ausleihindikator)) { return ItemType.BUZ.value; } if ("ifgaoz".contains(exemplar.ausleihindikator)) { return ItemType.BUP.value; } } // eBook if (typeOfRecord.equals("m") && bibliographicLevel.equals("m") && categoryOfMaterial.equals("c") && materialDesignation.equals("r") ) { return ItemType.BUA.value; } // Zeitschrift if (typeOfRecord.equals("a") && bibliographicLevel.equals("s")) { return ItemType.ZSP.value; } // eZeitschrift if (typeOfRecord.equals("m") && bibliographicLevel.equals("s")) { return ItemType.BUA.value; } // Aufsatz if (typeOfRecord.equals("a") && bibliographicLevel.equals("a")) { return ItemType.ZSP.value; } // eAufsatz if (bibliographicLevel.equals("a")) { return ItemType.BUA.value; } // Handschrift if ("dft".contains(typeOfRecord)) { return ItemType.BUP.value; } // Mikroform if (categoryOfMaterial.equals("h")) { return ItemType.MKP.value; } if ("ubc".contains(exemplar.ausleihindikator)) { return ItemType.AVA.value; } if ("sd".contains(exemplar.ausleihindikator)) { return ItemType.AVZ.value; } // ifgaoz return ItemType.AVP.value; } @Override public final void setConverter(final org.marc4j.converter.CharConverter aConverter) { throw new UnsupportedOperationException( "setConverter(CharConverter) is not implemented"); } @Override public final CharConverter getConverter() { throw new UnsupportedOperationException("getConverter() is not implemented"); } public void close() { // nothing to do } private static Writer utf8Writer(String filename) throws IOException { FileOutputStream stream = new FileOutputStream(filename); return new OutputStreamWriter(stream, "UTF8"); } /** * Convertiert eine MARC21-Datei in eine MarcXML-Bulk-Import-SQL-Datei. * @param args Pfad mit auf .mrc endendem Dateinamen der MARC21-Datei. * @throws IOException Fehler beim Dateilesen oder -schreiben */ public static void main(final String[] args) throws IOException { if (args.length < 1 || args.length > 2) { usageExit(); } boolean ppn5 = false; if (args.length == 2) { if ("-5".equals(args[0])) { ppn5 = true; } else { usageExit(); } } String infile = args[args.length-1]; if (!infile.endsWith(MRCSUFFIX)) { System.err.println("Filename ending in .mrc expected, " + "but found filename: " + infile); usageExit(); } InputStream in = new FileInputStream(infile); MarcStreamReader reader = new MarcStreamReader(in); String filename = infile.substring( 0, infile.length() - MRCSUFFIX.length()); Writer bib = utf8Writer(filename + "-bib.sql"); Writer holdings = utf8Writer(filename + "-holdings.sql"); Writer item = utf8Writer(filename + "-item.sql"); while (reader.hasNext()) { MarcWriter writer = new Marc21ToOleBulk(bib, holdings, item, ppn5); writer.write(reader.next()); writer.close(); } in.close(); item.close(); holdings.close(); bib.close(); } }
// $Id: IntervalManager.java,v 1.2 2001/05/26 23:16:56 mdb Exp $ package com.samskivert.util; import java.util.*; import com.samskivert.Log; /** * Interval: can be used to register an object that is to be called once * or repeatedly after an interval has expired. * * <p> A caveat: be careful about deadlocks kids. The number of helper * threads should exceed the number of times you nest calls to Interval * stuff from inside the intervalExpired method of an Interval. Normally, * if all you're using this for is interrupting other threads or calling * repaint you can get by with 0 helpers. If you want to do some more * complicated stuff in intervalExpired() then you probably want a few * threads in the pool. If you're doing extensive processing and setting * up other timeouts on that thread then you want to make sure you've got * plenty of threads. */ public class IntervalManager extends Thread { /** * Sets the maximum number of helper threads to run methods in * Intervals. Defaults to 0, meaning that the main thread does all * the work. Setting this to a nonzero value makes it such that a * pool of helper threads is created to do all the actual work. */ public static synchronized void setMaxHelperThreads (int newmax) { newmax = Math.max(newmax, 0); // if we are moving down, we need to kill some threads. if (_helpers > newmax) { for (int ii=0; ii < _helpers - newmax; ii++) { _queue.append(KILLHELPER); } _helpers = newmax; } // finally, set the new maximum thread pool size. _maxhelpers = newmax; } /** * Increment the number of maximum helper threads. This is useful if * you may have many packages which use the IntervalMgr as a * threadpool to do work, each package can statically initialize the * number of threads they want to be available by calling this method * and they'll all be added together. */ public static synchronized void incrementHelperThreads (int amt) { setMaxHelperThreads(_maxhelpers + amt); } /** * Schedule the intervaled object to get called after an interval. * * @param i the intervaled object * @param timout # of ms until interval is up. * @param arg object to be passed when interval expires * @param recur if true, interval gets called every timeout until * removed. * * @return an ID number that will passed to the intervalExpired method * of i along with arg */ public static int register (Interval i, long delay, Object arg, boolean recur) { synchronized (_mgr) { IntervalItem item = new IntervalItem(i, delay, arg, recur); _hash.put(item.id, item); _schedule.add(item); Collections.sort(_schedule); if (item.endtime < _nextwake) { _mgr.notify(); } return item.id; } } /** * Non-recurring intervals are removed automatically after they are * run! This method is only useful if you want to remove a recurring * Interval or if you want to remove a non-recurring Interval before * it gets run. */ public static void remove (int id) { synchronized (_mgr) { IntervalItem item = (IntervalItem) _hash.remove(id); if (item != null) { _schedule.remove(item); return; } } Log.warning("remove() called on non-registered " + "interval [id=" + id + "]."); Thread.dumpStack(); } /** * Do our interval thing. */ public void run () { while (_mgr == Thread.currentThread()) { // check to see if an interval has expired, if so call // expired from an unsynchronized position. // TrackedThread.setState("Checking intervals"); IntervalItem item = checkInterval(); if (item != null) { if (_maxhelpers > 0) { helperHandle(item); } else { item.expired(); // we have no helpers, do it ourselves. } } // now attempt to sleep // TrackedThread.setState("Waiting for Interval event..."); doWait(); } } /** * Have a helper thread handle the expiration of this interval. */ protected static synchronized void helperHandle (IntervalItem item) { // put the item on the queue... _busyhelpers++; _queue.append(item); // possibly create a new thread in the pool to do this work. if ((_busyhelpers > _helpers) && (_helpers < _maxhelpers)) { IntervalExpirer helper = new IntervalExpirer(_queue); _helpers++; helper.start(); } } /** * A helper thread lets us know when it has finished its work. */ protected static synchronized void helperFinished () { _busyhelpers } /** * Check to see if anything needs calling. */ private synchronized IntervalItem checkInterval () { // TrackedThread.setState("Checking intervals"); if (_schedule.size() > 0) { IntervalItem item = (IntervalItem) _schedule.get(0); // it's totally valid for us to wake up early.. // so make sure we really want to run the first item on the queue. if (item.endtime <= System.currentTimeMillis()) { // we gotta deal with this monster! // first, remove it. _schedule.remove(0); if (item.checkRecur()) { // since we're definitionally not sleeping, we can just // insert into the queue without checking wait times.. _schedule.add(item); Collections.sort(_schedule); } else { // otherwise, get rid of this interval altogether _hash.remove(item.id); } return item; } } return null; } /** * Sleep until the next Interval needs to be attended to. */ private synchronized void doWait () { // TrackedThread.setState("Waiting for Interval event..."); if (_schedule.size() == 0) { _nextwake = Long.MAX_VALUE; } else { IntervalItem item = (IntervalItem) _schedule.get(0); _nextwake = item.endtime; } long waittime = _nextwake - System.currentTimeMillis(); if (waittime > 0L) { try { wait(waittime); } catch (InterruptedException e) { } } } private IntervalManager () { super("IntervalManager"); setDaemon(true); start(); } // there can be only one! protected static IntervalManager _mgr = new IntervalManager(); // We just use a sorted list for now since we aren't likely to have // too many monitorables at any time. Insertions are O(log n), // removals are O(n) since we search then entire queue to find the // intervaleds to remove. // If we someday find that we have a lot of intervaleds, we may want // to rewrite this such that we can add and remove intervaleds much // faster. protected static ArrayList _schedule = new ArrayList(); protected static IntMap _hash = new IntMap(); protected static long _nextwake = Long.MAX_VALUE; protected static int _helpers = 0; // # of created helpers protected static int _maxhelpers = 0; // max # of helpers we can create protected static int _busyhelpers = 0; // # of outstanding requests protected static Queue _queue = new Queue(); protected static final Object KILLHELPER = new Object(); } class IntervalItem implements Comparable { public long endtime; public int id; protected long _timeout; protected boolean _recur; protected Interval _i; protected Object _arg; public IntervalItem (Interval i, long timeout, Object arg, boolean recur) { _i = i; _timeout = Math.max(timeout, 0); _arg = arg; _recur = recur; id = nextID(); endtime = System.currentTimeMillis() + timeout; } public int compareTo (Object other) { return (int) (endtime - ((IntervalItem) other).endtime); } /** * Test-n-set recurring stuff. If we do recur, increment the time we * are to next wake. */ public boolean checkRecur () { if (_recur) { endtime += _timeout; } return _recur; } /** * Run the interval. It's synchronized so that if we someday have * multiple threads, the same interval won't be called multiple times. */ public synchronized void expired () { // protect our ass. try { _i.intervalExpired(id, _arg); } catch (Exception e) { Log.warning("Exception while expiring interval: " + e); Log.logStackTrace(e); } } /** * For debugging. */ public String toString() { return "Interval: " + _i + " (wakes in " + (endtime - System.currentTimeMillis()) + "ms)" + (_recur ? (" [recurring every " + _timeout + "ms]") : ""); } /** * Unique ids for each interval item. */ private static synchronized int nextID () { return _idseq++; } private static int _idseq = 0; } /** * These are the helper threads for the IntervalManager. */ class IntervalExpirer extends Thread { public IntervalExpirer (Queue queue) { super("IntervalExpirer"); setDaemon(true); _queue = queue; } public void run () { while (true) { // TrackedThread.setState("Waiting for Interval to run..."); Object o = _queue.get(); if (o == IntervalManager.KILLHELPER) { break; //exit } // otherwise run the bashtard! ((IntervalItem) o).expired(); IntervalManager.helperFinished(); } } protected Queue _queue; }
package imagej.patcher; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.List; /** * Extension points for ImageJ 1.x. * <p> * These extension points will be patched into ImageJ 1.x by the * {@link CodeHacker}. To override the behavior of ImageJ 1.x, a new instance of * this interface needs to be installed into <code>ij.IJ._hooks</code>. * </p> * <p> * The essential functionality of the hooks is provided in the * {@link EssentialLegacyHooks} class, which makes an excellent base class for * project-specific implementations. * </p> * * @author Johannes Schindelin */ public abstract class LegacyHooks { /** * Determines whether the image windows should be displayed or not. * * @return false if ImageJ 1.x should be prevented from opening image * windows. */ public boolean isLegacyMode() { return true; } /** * Return the current context, if any. * <p> * For ImageJ2-specific hooks, the returned object will be the current * SciJava context, or null if the context is not yet initialized. * </p> * * @return the context, or null */ public Object getContext() { return null; } /** * Disposes and prepares for quitting. * * @return whether ImageJ 1.x should be allowed to call System.exit() */ public boolean quit() { return true; } /** * Runs when the hooks are installed into an existing legacy environment. */ public void installed() { // ignore } /** * Disposes of the hooks. * <p> * This method is called when ImageJ 1.x is quitting or when new hooks are * installed. * </p> */ public void dispose() { // ignore } /** * Intercepts the call to {@link ij.IJ#runPlugIn(String, String)}. * * @param className * the class name * @param arg * the argument passed to the {@code runPlugIn} method * @return the object to return, or null to let ImageJ 1.x handle the call */ public Object interceptRunPlugIn(String className, String arg) { return null; } /** * Updates the progress bar, where 0 <= progress <= 1.0. * * @param value * between 0.0 and 1.0 */ public void showProgress(double progress) { } /** * Updates the progress bar, where the length of the bar is set to ( * <code>currentValue + 1) / finalValue</code> of the maximum bar length. * The bar is erased if <code>currentValue &gt;= finalValue</code>. * * @param currentIndex * the step that was just started * @param finalIndex * the final step. */ public void showProgress(int currentIndex, int finalIndex) { } /** * Shows a status message. * * @param status * the message */ public void showStatus(String status) { } /** * Logs a message. * * @param message * the message */ public void log(String message) { } /** * Registers an image (possibly not seen before). * * @param image * the new image */ public void registerImage(final Object image) { } /** * Releases an image. * * @param imagej * the image */ public void unregisterImage(final Object image) { } /** * Logs a debug message (to be shown only in debug mode). * * @param string * the debug message */ public void debug(String string) { System.err.println(string); } /** * Shows an exception. * * @param t * the exception */ public void error(Throwable t) { // ignore } /** * Returns the name to use in place of "ImageJ". * * @return the application name */ public String getAppName() { return "ImageJ"; } /** * Returns the icon to use in place of the ImageJ microscope. * * @return the URL to the icon to use, or null */ public URL getIconURL() { return null; } /** * Extension point to override ImageJ 1.x' editor. * * @param path * the path to the file to open * @return true if the hook opened a different editor */ public boolean openInEditor(String path) { return false; } /** * Extension point to override ImageJ 1.x' editor. * * @param fileName * the name of the new file * @param content * the initial content * @return true if the hook opened a different editor */ public boolean createInEditor(String fileName, String content) { return false; } /** * Extension point to add to ImageJ 1.x' PluginClassLoader's class path. * * @return a list of class path elements to add */ public List<File> handleExtraPluginJars() { final List<File> result = new ArrayList<File>(); final String extraPluginDirs = System.getProperty("ij1.plugin.dirs"); if (extraPluginDirs != null) { for (final String dir : extraPluginDirs.split(File.pathSeparator)) { handleExtraPluginJars(new File(dir), result); } return result; } final String userHome = System.getProperty("user.home"); if (userHome != null) handleExtraPluginJars(new File(userHome, ".plugins"), result); return result; } private void handleExtraPluginJars(final File directory, final List<File> result) { final File[] list = directory.listFiles(); if (list == null) return; for (final File file : list) { if (file.isDirectory()) handleExtraPluginJars(file, result); else if (file.isFile() && file.getName().endsWith(".jar")) { result.add(file); } } } /** * Extension point to run after <i>Help&gt;Refresh Menus</i> */ public void runAfterRefreshMenus() { // ignore } /** * Extension point to enhance ImageJ 1.x' error reporting upon * {@link NoSuchMethodError}. * * @param e * the exception to handle * @return true if the error was handled by the legacy hook */ public boolean handleNoSuchMethodError(NoSuchMethodError e) { return false; // not handled } /** * Extension point to run after a new PluginClassLoader was initialized. * * @param loader * the PluginClassLoader instance */ public void newPluginClassLoader(final ClassLoader loader) { // do nothing } /** * First extension point to run just after ImageJ 1.x spun up. */ public void initialized() { // do nothing by default } }
package io.coinswap.net; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; import org.bitcoinj.utils.Threading; import net.minidev.json.JSONObject; import net.minidev.json.JSONStyle; import net.minidev.json.JSONValue; import org.slf4j.LoggerFactory; import javax.net.ssl.SSLSocket; import java.io.*; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.Future; import java.util.concurrent.locks.ReentrantLock; import static com.google.common.base.Preconditions.checkNotNull; public class Connection extends Thread { private static final org.slf4j.Logger log = LoggerFactory.getLogger(Connection.class); public static final int PORT = 16800; private SSLSocket socket; private Map<String, List<ReceiveListener>> listeners; private BufferedWriter out; private BufferedReader in; private SettableFuture disconnectFuture; private int id = 0; private final ReentrantLock lock = Threading.lock("io.coinswap.net.Connection"); public Connection(SSLSocket socket) { this.socket = socket; this.listeners = new HashMap<String, List<ReceiveListener>>(); this.disconnectFuture = SettableFuture.create(); try { out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); } catch(IOException ex) { log.error(ex.getMessage()); } } public void onMessage(String channel, ReceiveListener listener) { List<ReceiveListener> list; lock.lock(); try { if (!listeners.containsKey(channel)) { list = new LinkedList<ReceiveListener>(); listeners.put(channel, list); } else { list = listeners.get(channel); } list.add(listener); } finally { lock.unlock(); } } public void onDisconnect(Runnable listener) { disconnectFuture.addListener(listener, Threading.SAME_THREAD); } public void removeMessageListener(String channel, ReceiveListener listener) { lock.lock(); try { if(!listeners.containsKey(channel)) return; List<ReceiveListener> list = listeners.get(channel); list.remove(listener); if(list.isEmpty()) listeners.remove(channel); } finally { lock.unlock(); } } public void write(Map obj) { String data = ((JSONObject) obj).toJSONString(JSONStyle.LT_COMPRESS); log.info(">> " + data); lock.lock(); try { out.write(data); out.write("\r\n"); out.flush(); } catch (IOException ex) { log.error(ex.getMessage()); } finally { lock.unlock(); } } public Map request(Map req) { SettableFuture<Map> responseFuture = SettableFuture.create(); String channel = (String) checkNotNull(req.get("channel")); String requestId = id++ + ""; req.put("request", requestId); ReceiveListener onRes = new ReceiveListener() { @Override public void onReceive(Map data) { String responseId = (String) data.get("response"); if(responseId != null && responseId.equals(requestId)) responseFuture.set(data); } }; onMessage(channel, onRes); write(req); Map res = null; try { res = responseFuture.get(); } catch(Exception e) { e.printStackTrace(); } finally { removeMessageListener(channel, onRes); } return res; } public void run() { try { String data; while (socket.isConnected() && (data = in.readLine()) != null) { log.info("<< " + data); JSONObject obj = (JSONObject) JSONValue.parse(data); List<ReceiveListener> channelListeners; lock.lock(); try { channelListeners = listeners.get((String) obj.get("channel")); } finally { lock.unlock(); } if (channelListeners != null) { for (ReceiveListener listener : channelListeners) { // TODO: run listeners on different threads? listener.onReceive(obj); } } } } catch (Exception ex) { log.error(ex.getClass().getName() + ": " + ex.getMessage()); ex.printStackTrace(); } finally { try { socket.close(); in.close(); out.close(); } catch(IOException ex) { log.error(ex.getMessage()); } finally { // TODO: maybe indicate how the connection closed? disconnectFuture.set(null); } } } public SSLSocket getSocket() { return socket; } public interface ReceiveListener { public void onReceive(Map data); } }
package javaslang.collection; import javaslang.Tuple; import javaslang.Tuple2; import javaslang.control.None; import javaslang.control.Option; import javaslang.control.Some; import java.util.ArrayList; import java.util.Comparator; import java.util.NoSuchElementException; import java.util.Objects; import java.util.function.*; import java.util.stream.Collector; /** * A {@code Queue} stores elements allowing a first-in-first-out (FIFO) retrieval. * <p> * Queue API: * * <ul> * <li>{@link #dequeue()}</li> * <li>{@link #dequeueOption()}</li> * <li>{@link #enqueue(Object)}</li> * <li>{@link #enqueue(Object[])}</li> * <li>{@link #enqueueAll(Iterable)}</li> * <li>{@link #peek()}</li> * <li>{@link #peekOption()}</li> * </ul> * * A Queue internally consists of a front List containing the front elements of the Queue in the correct order and a * rear List containing the rear elements of the Queue in reverse order. * <p> * See Okasaki, Chris: <em>Purely Functional Data Structures</em> (p. 42 ff.). Cambridge, 2003. * * @param <T> Component type of the Queue * @since 1.3.0 */ public class Queue<T> implements Seq<T>implements Serializable { private static final long serialVersionUID = 1L; private static final Queue<?> EMPTY = new Queue<>(List.nil(), List.nil()); private final List<T> front; private final List<T> rear; /** * Creates a Queue consisting of a front List and a rear List. * <p> * For a {@code Queue(front, rear)} the following invariant holds: {@code Queue is empty <=> front is empty}. * In other words: If the Queue is not empty, the front List contains at least one element. * * @param front A List of front elements, in correct order. * @param rear A List of rear elements, in reverse order. */ private Queue(List<T> front, List<T> rear) { final boolean isFrontEmpty = front.isEmpty(); this.front = isFrontEmpty ? rear.reverse() : front; this.rear = isFrontEmpty ? front : rear; } /** * Returns a {@link java.util.stream.Collector} which may be used in conjunction with * {@link java.util.stream.Stream#collect(java.util.stream.Collector)} to obtain a {@link javaslang.collection.Queue} * . * * @param <T> Component type of the Queue. * @return A javaslang.collection.Queue Collector. */ public static <T> Collector<T, ArrayList<T>, Queue<T>> collector() { final Supplier<ArrayList<T>> supplier = ArrayList::new; final BiConsumer<ArrayList<T>, T> accumulator = ArrayList::add; final BinaryOperator<ArrayList<T>> combiner = (left, right) -> { left.addAll(right); return left; }; final Function<ArrayList<T>, Queue<T>> finisher = Queue::ofAll; return Collector.of(supplier, accumulator, combiner, finisher); } /** * Returns the empty Queue. * * @param <T> Component type * @return The empty Queue. */ @SuppressWarnings("unchecked") public static <T> Queue<T> empty() { return (Queue<T>) EMPTY; } /** * Returns a singleton {@code Queue}, i.e. a {@code Queue} of one element. * * @param element An element. * @param <T> The component type * @return A new Queue instance containing the given element */ public static <T> Queue<T> of(T element) { return new Queue<>(List.of(element), List.nil()); } /** * Creates a Queue of the given elements. * * @param <T> Component type of the Queue. * @param elements Zero or more elements. * @return A queue containing the given elements in the same order. * @throws NullPointerException if {@code elements} is null */ @SafeVarargs @SuppressWarnings({"unchecked", "varargs"}) public static <T> Queue<T> of(T... elements) { Objects.requireNonNull(elements, "elements is null"); return new Queue<>(List.of(elements), List.nil()); } /** * Creates a Queue of the given elements. * * @param <T> Component type of the Queue. * @param elements An Iterable of elements. * @return A queue containing the given elements in the same order. * @throws NullPointerException if {@code elements} is null */ @SuppressWarnings("unchecked") public static <T> Queue<T> ofAll(Iterable<? extends T> elements) { Objects.requireNonNull(elements, "elements is null"); if (elements instanceof Queue) { return (Queue<T>) elements; } else if (elements instanceof List) { return new Queue<>((List<T>) elements, List.nil()); } else { return new Queue<>(List.ofAll(elements), List.nil()); } } /** * Creates a Queue of int numbers starting from {@code from}, extending to {@code toExclusive - 1}. * * @param from the first number * @param toExclusive the last number + 1 * @return a range of int values as specified or {@code Nil} if {@code from >= toExclusive} */ public static Queue<Integer> range(int from, int toExclusive) { return new Queue<>(List.range(from, toExclusive), List.nil()); } /** * Creates a Queue of int numbers starting from {@code from}, extending to {@code toInclusive}. * * @param from the first number * @param toInclusive the last number * @return a range of int values as specified or {@code Nil} if {@code from > toInclusive} */ public static Queue<Integer> rangeClosed(int from, int toInclusive) { return new Queue<>(List.rangeClosed(from, toInclusive), List.nil()); } /** * Removes an element from this Queue. * * @return a tuple containing the first element and the remaining elements of this Queue * @throws java.util.NoSuchElementException if this Queue is empty */ public Tuple2<T, Queue<T>> dequeue() { if (isEmpty()) { throw new NoSuchElementException("dequeue of empty Queue"); } else { return Tuple.of(head(), tail()); } } /** * Removes an element from this Queue. * * @return {@code None} if this Queue is empty, otherwise {@code Some} {@code Tuple} containing the first element and the remaining elements of this Queue */ public Option<Tuple2<T, Queue<T>>> dequeueOption() { return isEmpty() ? None.instance() : new Some<>(dequeue()); } /** * Enqueues a new element. * * @param element The new element * @return a new {@code Queue} instance, containing the new element */ public Queue<T> enqueue(T element) { return new Queue<>(front, rear.prepend(element)); } /** * Enqueues the given elements. A queue has FIFO order, i.e. the first of the given elements is * the first which will be retrieved. * * @param elements Elements, may be empty * @return a new {@code Queue} instance, containing the new elements * @throws NullPointerException if elements is null */ public Queue<T> enqueue(T... elements) { List<T> temp = rear; for (T element : elements) { temp = temp.prepend(element); } return new Queue<>(front, temp); } /** * Enqueues the given elements. A queue has FIFO order, i.e. the first of the given elements is * the first which will be retrieved. * * @param elements An Iterable of elements, may be empty * @return a new {@code Queue} instance, containing the new elements * @throws NullPointerException if elements is null */ public Queue<T> enqueueAll(Iterable<? extends T> elements) { List<T> temp = rear; for (T element : elements) { temp = temp.prepend(element); } return new Queue<>(front, temp); } /** * Returns the first element without modifying the Queue. * * @return the first element * @throws java.util.NoSuchElementException if this Queue is empty */ public T peek() { if (isEmpty()) { throw new NoSuchElementException("peek of empty Queue"); } else { return front.head(); } } /** * Returns the first element without modifying the Queue. * * @return {@code None} if this Queue is empty, otherwise a {@code Some} containing the first element */ public Option<T> peekOption() { return isEmpty() ? None.instance() : new Some<>(front.head()); } // -- Adjusted return types of Seq methods @Override public Queue<T> append(T element) { return enqueue(element); } @Override public Queue<T> appendAll(Iterable<? extends T> elements) { return enqueueAll(elements); } @Override public Queue<T> clear() { return Queue.empty(); } @Override public Queue<Queue<T>> combinations() { return toList().combinations().map(Queue::ofAll).toQueue(); } @Override public Queue<Queue<T>> combinations(int k) { return toList().combinations(k).map(Queue::ofAll).toQueue(); } @Override public Queue<T> distinct() { return toList().distinct().toQueue(); } @Override public <U> Queue<T> distinct(Function<? super T, ? extends U> keyExtractor) { return toList().distinct(keyExtractor).toQueue(); } @Override public Queue<T> drop(int n) { } @Override public Queue<T> dropRight(int n) { } @Override public Queue<T> dropWhile(Predicate<? super T> predicate) { } @Override public Queue<T> filter(Predicate<? super T> predicate) { } @Override public Queue<T> findAll(Predicate<? super T> predicate) { } @Override public <U> Queue<U> flatMap(Function<? super T, ? extends Iterable<U>> mapper) { } @Override public <U> Queue<U> flatten(Function<? super T, ? extends Iterable<U>> f) { } @Override public T get(int index) { } @Override public Queue<Queue<T>> grouped(int size) { } @Override public T head() { if (isEmpty()) { throw new NoSuchElementException("head of empty queue"); } else { return front.head(); } } @Override public int indexOf(T element) { } @Override public Queue<T> init() { if (isEmpty()) { throw new NoSuchElementException("init of empty Queue"); } else if (rear.isEmpty()) { return new Queue<>(front.init(), rear); } else { return new Queue<>(front, rear.tail()); } } @Override public Option<Queue<T>> initOption() { return isEmpty() ? None.instance() : new Some<>(init()); } @Override public Queue<T> insert(int index, T element) { } @Override public Queue<T> insertAll(int index, Iterable<? extends T> elements) { } @Override public Queue<T> intersperse(T element) { } @Override public int lastIndexOf(T element) { } @Override public <U> Queue<U> map(Function<? super T, ? extends U> mapper) { } @Override public Tuple2<Queue<T>, Queue<T>> partition(Predicate<? super T> predicate) { } @Override public Queue<T> peek(Consumer<? super T> action) { } @Override public Queue<Queue<T>> permutations() { } @Override public Queue<T> prepend(T element) { } @Override public Queue<T> prependAll(Iterable<? extends T> elements) { } @Override public Queue<T> remove(T element) { } @Override public Queue<T> removeAll(T element) { } @Override public Queue<T> removeAll(Iterable<? extends T> elements) { } @Override public Queue<T> replace(T currentElement, T newElement) { } @Override public Queue<T> replaceAll(T currentElement, T newElement) { } @Override public Queue<T> replaceAll(UnaryOperator<T> operator) { } @Override public Queue<T> retainAll(Iterable<? extends T> elements) { } @Override public Queue<T> reverse() { } @Override public Queue<T> set(int index, T element) { } @Override public Queue<Queue<T>> sliding(int size) { } @Override public Queue<Queue<T>> sliding(int size, int step) { } @Override public Queue<T> sort() { } @Override public Queue<T> sort(Comparator<? super T> comparator) { } @Override public Tuple2<Queue<T>, Queue<T>> span(Predicate<? super T> predicate) { } @Override public Tuple2<Queue<T>, Queue<T>> splitAt(int n) { } @Override public Queue<T> subsequence(int beginIndex) { } @Override public Queue<T> subsequence(int beginIndex, int endIndex) { } @Override public Queue<T> tail() { } @Override public Option<Queue<T>> tailOption() { return isEmpty() ? None.instance() : new Some<>(tail()); } @Override public Queue<T> take(int n) { } @Override public Queue<T> takeRight(int n) { } @Override public Queue<T> takeWhile(Predicate<? super T> predicate) { } @Override public <T1, T2> Tuple2<Queue<T1>, Queue<T2>> unzip(Function<? super T, Tuple2<? extends T1, ? extends T2>> unzipper) { } @Override public <U> Queue<Tuple2<T, U>> zip(Iterable<U> that) { } @Override public <U> Queue<Tuple2<T, U>> zipAll(Iterable<U> that, T thisElem, U thatElem) { } @Override public Queue<Tuple2<T, Integer>> zipWithIndex() { } @Override public boolean equals(Object o) { if (o == this) { return true; } else if (o instanceof Queue) { List<?> list1 = this.toList(); List<?> list2 = ((Queue<?>) o).toList(); while (!list1.isEmpty() && !list2.isEmpty()) { final boolean isEqual = Objects.equals(list1.head(), list2.head()); if (!isEqual) { return false; } list1 = list1.tail(); list2 = list2.tail(); } return list1.isEmpty() && list2.isEmpty(); } else { return false; } } @Override public int hashCode() { int hashCode = 1; for (T element : this) { hashCode = 31 * hashCode + Objects.hashCode(element); } return hashCode; } @Override public String toString() { return map(String::valueOf).join(", ", "Queue(", ")"); } }
package org.basex.gui; import static org.basex.gui.GUICommands.*; import java.awt.Color; import java.awt.Container; import java.awt.Cursor; import java.awt.Event; import java.awt.Font; import javax.swing.Icon; import javax.swing.UIManager; import org.basex.core.Prop; import org.basex.core.Text; import org.basex.gui.layout.BaseXLayout; import org.basex.gui.view.View; import org.basex.gui.view.map.MapView; public final class GUIConstants { /** Internal name of the Map View. */ public static final String MAPVIEW = "map"; /** Internal name of the Tree View. */ public static final String FOLDERVIEW = "folder"; /** Internal name of the Text View. */ public static final String TEXTVIEW = "text"; /** Internal name of the Table View. */ public static final String TABLEVIEW = "table"; /** Internal name of the Info View. */ public static final String INFOVIEW = "info"; /** Internal name of the Explore View. */ public static final String EXPLOREVIEW = "explore"; /** Internal name of the Plot View. */ public static final String PLOTVIEW = "plot"; /** Internal name of the Tree View. */ public static final String TREEVIEW = "tree"; /** Internal name of the Editor View. */ public static final String EDITORVIEW = "editor"; /** * Default GUI Layout. The layout is formatted as follows: * The character 'H' or 'V' adds a new horizontal or vertical level, * and a level is closed again with the '-' character. All views are * separated with spaces, and all views must be specified in this layout. * This layout is displayed as soon as a database is opened. */ public static final String VIEWS = "V H " + EDITORVIEW + ' ' + FOLDERVIEW + ' ' + MAPVIEW + ' ' + PLOTVIEW + ' ' + " - H " + TEXTVIEW + ' ' + INFOVIEW + ' ' + TABLEVIEW + ' ' + TREEVIEW + ' ' + EXPLOREVIEW + " - -"; /** Toolbar entries, containing the button commands. */ static final GUICommands[] TOOLBAR = { C_CREATE, C_OPEN_MANAGE, C_INFO, C_CLOSE, null, C_GOHOME, C_GOBACK, C_GOUP, C_GOFORWARD, null, C_SHOWEDITOR, C_SHOWINFO, null, C_SHOWTEXT, C_SHOWMAP, C_SHOWTREE, C_SHOWFOLDER, C_SHOWPLOT, C_SHOWTABLE, C_SHOWEXPLORE }; /** Top menu entries. */ static final String[] MENUBAR = { Text.DATABASE, Text.EDITOR, Text.VIEW, Text.NODES, Text.OPTIONS, Text.HELP }; /** * Two-dimensional menu entries, containing the menu item commands. * {@link #EMPTY} references serve as menu separators. */ static final GUICommand[][] MENUITEMS = { { C_CREATE, C_OPEN_MANAGE, EMPTY, C_INFO, C_EXPORT, C_CLOSE, EMPTY, C_SERVER, Prop.MAC ? null : EMPTY, Prop.MAC ? null : C_EXIT }, { C_EDITNEW, C_EDITOPEN, C_EDITSAVE, C_EDITSAVEAS, C_EDITCLOSE, EMPTY, C_SHOWEDITOR, C_SHOWINFO }, { C_SHOWBUTTONS, C_SHOWINPUT, C_SHOWSTATUS, EMPTY, C_SHOWTEXT, C_SHOWMAP, C_SHOWTREE, C_SHOWFOLDER, C_SHOWPLOT, C_SHOWTABLE, C_SHOWEXPLORE, EMPTY, C_FULL }, { C_COPY, C_PASTE, C_DELETE, C_INSERT, C_EDIT, EMPTY, C_COPYPATH, C_FILTER }, { C_RTEXEC, C_RTFILTER, EMPTY, C_COLOR, C_FONTS, C_MAPLAYOUT, C_TREEOPTIONS, Prop.MAC ? null : EMPTY, C_PACKAGES, Prop.MAC ? null : C_PREFS }, { C_HELP, Prop.MAC ? null : EMPTY, C_COMMUNITY, C_UPDATES, Prop.MAC ? null : EMPTY, Prop.MAC ? null : C_ABOUT }}; /** Context menu entries. */ public static final GUICommands[] POPUP = { C_GOBACK, C_FILTER, null, C_COPY, C_PASTE, C_DELETE, C_INSERT, C_EDIT, null, C_COPYPATH }; /** Arrow cursor. */ public static final Cursor CURSORARROW = new Cursor(Cursor.DEFAULT_CURSOR); /** Hand cursor. */ public static final Cursor CURSORHAND = new Cursor(Cursor.HAND_CURSOR); /** Wait cursor. */ public static final Cursor CURSORWAIT = new Cursor(Cursor.WAIT_CURSOR); /** Left/Right arrow cursor. */ public static final Cursor CURSORMOVEH = new Cursor(Cursor.E_RESIZE_CURSOR); /** Move cursor. */ public static final Cursor CURSORMOVEV = new Cursor(Cursor.N_RESIZE_CURSOR); /** Text cursor. */ public static final Cursor CURSORTEXT = new Cursor(Cursor.TEXT_CURSOR); /** Move cursor. */ public static final Cursor CURSORMOVE = new Cursor(Cursor.MOVE_CURSOR); /** Icon type. */ public enum Msg { /** Warning message. */ WARN("warn", "warning"), /** Error message. */ ERROR("error", "error"), /** Success message. */ SUCCESS("ok", "information"), /** Question message. */ QUESTION("warn", "question"), /** Yes/no/cancel message. */ YESNOCANCEL("warn", "question"); /** Small icon. */ public final Icon small; /** Large icon. */ public final Icon large; /** * Constructor. * @param s small icon * @param l large icon */ Msg(final String s, final String l) { small = BaseXLayout.icon(s); large = UIManager.getIcon("OptionPane." + l + "Icon"); } } /** Background fill options. */ public enum Fill { /** Opaque fill mode. */ PLAIN, /** Transparent mode. */ NONE, /** Downward gradient. */ GRADIENT } /** Cell color. */ public static final Color LGRAY = new Color(224, 224, 224); /** Button color. */ public static final Color GRAY = new Color(160, 160, 160); /** Background color. */ public static final Color DGRAY = new Color(64, 64, 64); /** Bright GUI color. */ public static final Color WHITE = Color.white; /** Color for control characters. */ public static final Color RED = new Color(208, 0, 0); /** Color for highlighting errors. */ public static final Color LRED = new Color(255, 200, 180); /** Color for highlighting full-text hits. */ public static final Color GREEN = new Color(0, 176, 0); /** Color for highlighting quotes. */ public static final Color BLUE = new Color(0, 64, 192); /** Color for control characters. */ public static final Color PINK = new Color(160, 0, 160); /** Second bright GUI color. */ public static Color color1; /** Middle color. */ public static Color color2; /** Middle color. */ public static Color color3; /** Dark color. */ public static Color color4; /** Mark color. */ public static Color colormark1; /** Second mark color. */ public static Color colormark2; /** Third mark color. */ public static Color colormark3; /** Fourth mark color. */ public static Color colormark4; /** Alpha color. */ public static Color color1A; /** Transparent background color. */ public static Color color2A; /** Transparent frame color. */ public static Color color3A; /** Mark color, custom alpha value. */ public static Color colormark1A; /** Second mark color, custom alpha value. */ public static Color colormark2A; /** Cached color gradient. */ private static final Color[] COLORS = new Color[100]; /** Default monospace font. */ public static Font dfont; /** Large font. */ public static Font lfont; /** Font. */ public static Font font; /** Bold Font. */ public static Font bfont; /** Monospace font. */ public static Font mfont; /** Default monospace font widths. */ private static int[] dwidth; /** Character large character widths. */ private static int[] lwidth; /** Character widths. */ private static int[] fwidth; /** Bold character widths. */ private static int[] bwidth; /** Monospace character widths. */ public static int[] mfwidth; /** Shift key. */ public static final int SHF = Event.SHIFT_MASK; /** Alt key. */ public static final int ALT = Event.ALT_MASK; /** Control key. */ public static final int CTRL = Event.CTRL_MASK; /** Shortcut key (CTRL/META). */ public static final int SC = Prop.MAC ? Event.META_MASK : Event.CTRL_MASK; /** Private constructor, preventing class instantiation. */ private GUIConstants() { } /** * Initializes colors. * @param prop gui properties */ public static void init(final GUIProp prop) { final int r = prop.num(GUIProp.COLORRED); final int g = prop.num(GUIProp.COLORGREEN); final int b = prop.num(GUIProp.COLORBLUE); // calculate color c: // c = (255 - expectedColor) * 10 / factor (= GUIRED/BLUE/GREEN) color1 = new Color(col(r, 24), col(g, 25), col(b, 40)); color2 = new Color(col(r, 32), col(g, 32), col(b, 44)); color3 = new Color(col(r, 48), col(g, 50), col(b, 40)); color4 = new Color(col(r, 140), col(g, 100), col(b, 70)); color1A = new Color(col(r, 110), col(g, 150), col(b, 160), 100); colormark1A = new Color(col(r, 32), col(g, 160), col(b, 320), 100); colormark2A = new Color(col(r, 16), col(g, 80), col(b, 160), 100); colormark1 = new Color(col(r, 16), col(g, 120), col(b, 240)); colormark2 = new Color(col(r, 16), col(g, 80), col(b, 160)); colormark3 = new Color(col(r, 32), col(g, 160), col(b, 320)); colormark4 = new Color(col(r, 1), col(g, 40), col(b, 80)); // create color array for(int l = 1; l < COLORS.length + 1; ++l) { COLORS[l - 1] = new Color(Math.max(255 - l * r, 0), Math.max(255 - l * g, 0), Math.max(255 - l * b, 0)); } final Color c = COLORS[16]; color2A = new Color(c.getRed(), c.getGreen(), c.getBlue(), 40); color3A = new Color(c.getRed(), c.getGreen(), c.getBlue(), 100); final String f = prop.get(GUIProp.FONT); final int type = prop.num(GUIProp.FONTTYPE); final int size = prop.num(GUIProp.FONTSIZE); font = new Font(f, type, size); mfont = new Font(prop.get(GUIProp.MONOFONT), type, size); bfont = new Font(f, Font.BOLD, size); lfont = new Font(f, type, size + 10); dfont = new Font(prop.get(GUIProp.MONOFONT), 0, UIManager.getFont("TextArea.font").getSize() - 1); final Container comp = new Container(); dwidth = comp.getFontMetrics(dfont).getWidths(); fwidth = comp.getFontMetrics(font).getWidths(); lwidth = comp.getFontMetrics(lfont).getWidths(); mfwidth = comp.getFontMetrics(mfont).getWidths(); bwidth = comp.getFontMetrics(bfont).getWidths(); } /** * Returns the specified color from the color gradient. * @param i color index * @return color */ public static Color color(final int i) { return COLORS[Math.min(COLORS.length - 1, i)]; } /** * Returns the character widths for the current font. * @param f font reference * @return character widths */ public static int[] fontWidths(final Font f) { if(f == font) return fwidth; if(f == mfont) return mfwidth; if(f == bfont) return bwidth; if(f == lfont) return lwidth; if(f == dfont) return dwidth; return new Container().getFontMetrics(f).getWidths(); } /** * Converts color value with specified factor. * @param c color * @param f factor * @return converted color value */ private static int col(final int c, final int f) { return Math.max(0, 255 - c * f / 10); } }
package org.btc4j.client; import java.io.File; import java.math.BigDecimal; import java.util.List; import org.btc4j.core.BtcAccount; import org.btc4j.core.BtcAddedNode; import org.btc4j.core.BtcAddress; import org.btc4j.core.BtcApi; import org.btc4j.core.BtcBlock; import org.btc4j.core.BtcException; import org.btc4j.core.BtcLastBlock; import org.btc4j.core.BtcMiningInfo; import org.btc4j.core.BtcMultiSignatureAddress; import org.btc4j.core.BtcNode; import org.btc4j.core.BtcPeer; import org.btc4j.core.BtcInfo; import org.btc4j.core.BtcRawTransaction; import org.btc4j.core.BtcTransaction; import org.btc4j.core.BtcTransactionOutput; import org.btc4j.core.BtcTransactionOutputSet; public class BtcClient implements BtcApi { @Override public String addMultiSignatureAddress(long required, List<String> keys, String account) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public void addNode(String node, BtcNode.Operation operation) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public void backupWallet(File destination) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public BtcMultiSignatureAddress createMultiSignatureAddress(long required, List<String> keys) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public String createRawTransaction(List<Object> transactionIds, List<Object> addresses) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public BtcRawTransaction decodeRawTransaction(String hex) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public String dumpPrivateKey(String address) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public String getAccount(String address) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public String getAccountAddress(String account) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public List<BtcAddedNode> getAddedNodeInformation(boolean dns, String node) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public List<String> getAddressesByAccount(String account) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public BigDecimal getBalance(String account, long minConfirms) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public BtcBlock getBlock(String hash) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public long getBlockCount() throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public String getBlockHash(long index) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public String getBlockTemplate(String params) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public long getConnectionCount() throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public BigDecimal getDifficulty() throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public boolean getGenerate() throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public long getHashesPerSecond() throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public BtcInfo getInformation() throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public BtcMiningInfo getMiningInformation() throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public String getNewAddress(String account) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public List<BtcPeer> getPeerInformation() throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public List<String> getRawMemoryPool() throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public BtcRawTransaction getRawTransaction(String transactionId, boolean verbose) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public BigDecimal getReceivedByAccount(String account, long minConfirms) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public BigDecimal getReceivedByAddress(String address, long minConfirms) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public BtcTransaction getTransaction(String transactionId) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public BtcTransactionOutput getTransactionOutput(String transactionId, long index, boolean includeMemoryPool) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public BtcTransactionOutputSet getTransactionOutputSetInformation() throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public String getWork(String data) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } public String help() throws BtcException { return help(""); } public String help(String command) throws BtcException { return "Bitcoin Client not yet implemented"; } @Override public String importPrivateKey(String privateKey, String label, boolean rescan) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public void keyPoolRefill() throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public List<BtcAccount> listAccounts(long minConfirms) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public List<BtcAddress> listAddressGroupings() throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public List<String> listLockUnspent() throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public List<BtcAccount> listReceivedByAccount(long minConfirms, boolean includeEmpty) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public List<BtcAddress> listReceivedByAddress(long minConfirms, boolean includeEmpty) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public BtcLastBlock listSinceBlock(String blockHash, long targetConfirms) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public List<BtcTransaction> listTransactions(String account, long count, long from) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public List<String> listUnspent(long minConfirms, long maxConfirms) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public void lockUnspent(boolean unlock, List<Object> outputs) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public void move(String fromAccount, String toAccount, BigDecimal amount, long minConfirms, String comment) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public String sendFrom(String fromAccount, String toAddress, BigDecimal amount, long minConfirms, String commentFrom, String commentTo) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public String sendMany(String fromAccount, List<Object> addresses, long minConfirms, String commentFrom, String commentTo) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public void sendRawTransaction(String transactionId) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public String sendToAddress(String toAddress, BigDecimal amount, String commentFrom, String commentTo) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public void setAccount(String address, String account) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public void setGenerate(boolean generate, long generateProcessorsLimit) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public boolean setTransactionFee(BigDecimal amount) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public void signMessage(String address, String message) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public void signRawTransaction(String transactionId, List<Object> signatures, List<String> keys) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } public String stop() throws BtcException { return "Stopping Bitcoin Client"; } @Override public void submitBlock(String data, List<Object> params) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public BtcAddress validateAddress(String address) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } @Override public String verifyMessage(String address, String signature, String message) throws BtcException { throw new BtcException(BtcException.BTC4J_ERROR_CODE, BtcException.BTC4J_ERROR_MESSAGE + ": " + BtcException.BTC4J_ERROR_DATA_NOT_IMPLEMENTED); } }
package org.cactoos.iterable; import java.util.Iterator; import java.util.NoSuchElementException; import org.cactoos.Func; import org.cactoos.Scalar; import org.cactoos.func.UncheckedFunc; import org.cactoos.scalar.Sticky; import org.cactoos.scalar.Unchecked; /** * Paged iterable. * Elements will continue to be provided so long as {@code next} produces * non-empty iterators. * * <p>There is no thread-safety guarantee. * * @param <X> Type of item * @since 0.47 * @todo #1183:30m Continue refactoring and add `iterator.Paged` by * extracting inner anon class from this class. The checkstyle suppression * should be removed after that. */ @SuppressWarnings("PMD.OnlyOneConstructorShouldDoInitialization") public final class Paged<X> extends IterableEnvelope<X> { /** * Ctor. * <p> * @param first First bag of elements * @param next Subsequent bags of elements * @param <I> Custom iterator */ @SuppressWarnings("PMD.ConstructorOnlyInitializesOrCallOtherConstructors") public <I extends Iterator<X>> Paged( final Scalar<I> first, final Func<I, I> next ) { // @checkstyle AnonInnerLengthCheck (30 lines) super( new IterableOf<>( () -> new Iterator<X>() { private Unchecked<I> current = new Unchecked<>( new Sticky<>(first) ); private final UncheckedFunc<I, I> subsequent = new UncheckedFunc<>(next); @Override public boolean hasNext() { if (!this.current.value().hasNext()) { final I next = this.subsequent.apply( this.current.value() ); this.current = new Unchecked<>( new Sticky<>(() -> next) ); } return this.current.value().hasNext(); } @Override public X next() { if (this.hasNext()) { return this.current.value().next(); } throw new NoSuchElementException(); } } ) ); } }
package org.cactoos.list; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import org.cactoos.Scalar; import org.cactoos.iterable.IterableOf; import org.cactoos.scalar.And; import org.cactoos.scalar.Folded; import org.cactoos.scalar.Or; import org.cactoos.scalar.SumOfInt; import org.cactoos.scalar.Unchecked; import org.cactoos.text.TextOf; import org.cactoos.text.UncheckedText; /** * {@link List} envelope that doesn't allow mutations. * * <p>There is no thread-safety guarantee.</p> * * @param <T> Element type * @since 1.16 * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) * @todo #898:30min Replace all the Collections.unmodifiableList * with the {@link org.cactoos.list.Immutable} from the cactoos codebase. * That should be done because Elegant Object principles are against static methods. */ @SuppressWarnings( { "PMD.TooManyMethods", "PMD.AbstractNaming", "PMD.AvoidDuplicateLiterals" } ) public final class Immutable<T> implements List<T> { /** * Encapsulated list. */ private final List<T> list; /** * Ctor. * @param items Source array */ @SafeVarargs public Immutable(final T... items) { this(new IterableOf<>(items)); } /** * Ctor. * @param src Source collection */ public Immutable(final Collection<T> src) { this(new IterableOf<>(src.iterator())); } /** * Ctor. * @param src Source list */ public Immutable(final List<T> src) { this(new IterableOf<>(src.iterator())); } /** * Ctor. * @param src Source iterable */ public Immutable(final Iterable<T> src) { this(() -> { final List<T> copy = new ArrayList<>(1); for (final T item : src) { copy.add(item); } return copy; }); } /** * Ctor. * @param slr The scalar */ public Immutable(final Scalar<List<T>> slr) { this.list = new Unchecked<>(slr).value(); } @Override public int size() { return this.list.size(); } @Override public boolean isEmpty() { return this.list.isEmpty(); } @Override public boolean contains(final Object item) { return this.list.contains(item); } @Override public Iterator<T> iterator() { return this.list.iterator(); } @Override public Object[] toArray() { return this.list.toArray(); } @Override @SuppressWarnings("PMD.UseVarargs") public <X> X[] toArray(final X[] array) { return this.list.toArray(array); } @Override public boolean add(final T item) { throw new UnsupportedOperationException( "#add(T): the list is read-only" ); } @Override public boolean remove(final Object item) { throw new UnsupportedOperationException( "#remove(Object): the list is read-only" ); } @Override public boolean containsAll(final Collection<?> items) { return this.list.containsAll(items); } @Override public boolean addAll(final Collection<? extends T> items) { throw new UnsupportedOperationException( "#addAll(Collection): the list is read-only" ); } @Override public boolean addAll(final int index, final Collection<? extends T> items) { throw new UnsupportedOperationException( "#addAll(int, Collection): the list is read-only" ); } @Override public boolean removeAll(final Collection<?> items) { throw new UnsupportedOperationException( "#removeAll(): the list is read-only" ); } @Override public boolean retainAll(final Collection<?> items) { throw new UnsupportedOperationException( "#retainAll(): the list is read-only" ); } @Override public void clear() { throw new UnsupportedOperationException( "#clear(): the list is read-only" ); } @Override public T get(final int index) { return this.list.get(index); } @Override public T set(final int index, final T item) { throw new UnsupportedOperationException( "#set(): the list is read-only" ); } @Override public void add(final int index, final T item) { throw new UnsupportedOperationException( "#add(int, T): the list is read-only" ); } @Override public T remove(final int index) { throw new UnsupportedOperationException( "#remove(int): the list is read-only" ); } @Override public int indexOf(final Object item) { return this.list.indexOf(item); } @Override public int lastIndexOf(final Object item) { return this.list.lastIndexOf(item); } @Override public ListIterator<T> listIterator() { return new ImmutableListIterator<>( this.list.listIterator() ); } @Override public ListIterator<T> listIterator(final int index) { return new ImmutableListIterator<>( this.list.listIterator(index) ); } @Override public List<T> subList(final int start, final int end) { return new Immutable<>( this.list.subList(start, end) ); } @Override @edu.umd.cs.findbugs.annotations.SuppressFBWarnings("EQ_UNUSUAL") public boolean equals(final Object other) { return new Unchecked<>( new Or( () -> other == this, new And( () -> other != null, () -> List.class.isAssignableFrom(other.getClass()), () -> { final List<?> compared = (List<?>) other; final Iterator<?> iterator = compared.iterator(); return new Unchecked<>( new And( (T input) -> input.equals(iterator.next()), this ) ).value(); } ) ) ).value(); } // @checkstyle MagicNumberCheck (30 lines) @Override public int hashCode() { return new Unchecked<>( new Folded<>( 42, (hash, entry) -> new SumOfInt( () -> 37 * hash, entry::hashCode ).value(), this ) ).value(); } @Override public String toString() { return new UncheckedText(new TextOf(this)).asString(); } }
package org.jenetics.stat; import org.jenetics.util.AdaptableAccumulator; import java.util.Arrays; public class Quantile<N extends Number> extends AdaptableAccumulator<N> { // The desired quantile. private double _quantile; // Marker heights. private final double[] _q = {0, 0, 0, 0, 0}; // Marker positions. private final double[] _n = {0, 0, 0, 0, 0}; // Desired marker positions. private final double[] _nn = {0, 0, 0}; // Desired marker position increments. private final double[] _dn = {0, 0, 0}; private boolean _initialized; public Quantile(double quantile) { if (quantile < 0.0 || quantile > 1) { throw new IllegalArgumentException(String.format( "Quantile (%s) not in the valid range of [0, 1]", quantile )); } _quantile = quantile; _n[0] = -1.0; _q[2] = 0.0; _initialized = Double.compare(_quantile, 0.0) == 0 || Double.compare(_quantile, 1.0) == 0; } public double getQuantile() { return _q[2]; } @Override public void accumulate(final N value) { if (!_initialized) { initialize(value.doubleValue()); } else { update(value.doubleValue()); } ++_samples; } private void initialize(double value) { if (_n[0] < 0.0) { _n[0] = 0.0; _q[0] = value; } else if (_n[1] == 0.0) { _n[1] = 1.0; _q[1] = value; } else if (_n[2] == 0.0) { _n[2] = 2.0; _q[2] = value; } else if (_n[3] == 0.0) { _n[3] = 3.0; _q[3] = value; } else if (_n[4] == 0.0) { _n[4] = 4.0; _q[4] = value; } if (_n[4] != 0.0) { Arrays.sort(_q); _nn[0] = 2.0*_quantile; _nn[1] = 4.0*_quantile; _nn[2] = 2.0*_quantile + 2.0; _dn[0] = _quantile/2.0; _dn[1] = _quantile; _dn[2] = (1.0 + _quantile)/2.0; _initialized = true; } } private void update(double value) { assert (_initialized); // If min or max, handle as special case; otherwise, ... if (_quantile == 0.0) { if (value < _q[2]) { _q[2] = value; } } else if (_quantile == 1.0) { if (value > _q[2]) { _q[2] = value; } } else { // Increment marker locations and update min and max. if (value < _q[0]) { ++_n[1]; ++_n[2]; ++_n[3]; ++_n[4]; _q[0] = value; } else if (value < _q[1]) { ++_n[1]; ++_n[2]; ++_n[3]; ++_n[4]; } else if (value < _q[2]) { ++_n[2]; ++_n[3]; ++_n[4]; } else if (value < _q[3]) { ++_n[3]; ++_n[4]; } else if (value < _q[4]) { ++_n[4]; } else { ++_n[4]; _q[4] = value; } // Increment positions of markers k + 1 _nn[0] += _dn[0]; _nn[1] += _dn[1]; _nn[2] += _dn[2]; // Adjust heights of markers 0 to 2 if necessary double mm = _n[1] - 1.0; double mp = _n[1] + 1.0; if (_nn[0] >= mp && _n[2] > mp) { _q[1] = qPlus(mp, _n[0], _n[1], _n[2], _q[0], _q[1], _q[2]); _n[1] = mp; } else if (_nn[0] <= mm && _n[0] < mm) { _q[1] = qMinus(mm, _n[0], _n[1], _n[2], _q[0], _q[1], _q[2]); _n[1] = mm; } mm = _n[2] - 1.0; mp = _n[2] + 1.0; if (_nn[1] >= mp && _n[3] > mp) { _q[2] = qPlus(mp, _n[1], _n[2], _n[3], _q[1], _q[2], _q[3]); _n[2] = mp; } else if (_nn[1] <= mm && _n[1] < mm) { _q[2] = qMinus(mm, _n[1], _n[2], _n[3], _q[1], _q[2], _q[3]); _n[2] = mm; } mm = _n[3] - 1.0; mp = _n[3] + 1.0; if (_nn[2] >= mp && _n[4] > mp) { _q[3] = qPlus(mp, _n[2], _n[3], _n[4], _q[2], _q[3], _q[4]); _n[3] = mp; } else if (_nn[2] <= mm && _n[2] < mm) { _q[3] = qMinus(mm, _n[2], _n[3], _n[4], _q[2], _q[3], _q[4]); _n[3] = mm; } } } private static double qPlus( final double mp, final double m0, final double m1, final double m2, final double q0, final double q1, final double q2 ) { double result = q1 + ((mp - m0)*(q2 - q1)/(m2 - m1) + (m2 - mp)*(q1 - q0)/(m1 - m0))/(m2 - m0); if (result > q2) { result = q1 + (q2 - q1)/(m2 - m1); } return result; } private static double qMinus( final double mm, final double m0, final double m1, final double m2, final double q0, final double q1, final double q2 ) { double result = q1 - ((mm - m0)*(q2 - q1)/(m2 - m1) + (m2 - mm)*(q1 - q0)/(m1 - m0))/(m2 - m0); if (q0 > result) { result = q1 + (q0 - q1)/(m0 - m1); } return result; } @Override public String toString() { return String.format( "%s[samples=%d, qantile=%f]", getClass().getSimpleName(), getSamples(), getQuantile() ); } }
package org.jfree.chart; import java.awt.AWTEvent; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Composite; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.Image; import java.awt.Insets; import java.awt.Paint; import java.awt.Point; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.Transparency; import java.awt.datatransfer.Clipboard; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.print.PageFormat; import java.awt.print.Printable; import java.awt.print.PrinterException; import java.awt.print.PrinterJob; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.EventListener; import java.util.List; import java.util.ResourceBundle; import javax.swing.JFileChooser; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.SwingUtilities; import javax.swing.ToolTipManager; import javax.swing.event.EventListenerList; import javax.swing.filechooser.FileNameExtensionFilter; import org.jfree.chart.editor.ChartEditor; import org.jfree.chart.editor.ChartEditorManager; import org.jfree.chart.entity.ChartEntity; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.ChartChangeEvent; import org.jfree.chart.event.ChartChangeListener; import org.jfree.chart.event.ChartProgressEvent; import org.jfree.chart.event.ChartProgressListener; import org.jfree.chart.panel.Overlay; import org.jfree.chart.event.OverlayChangeEvent; import org.jfree.chart.event.OverlayChangeListener; import org.jfree.chart.plot.Pannable; import org.jfree.chart.plot.Plot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.plot.Zoomable; import org.jfree.chart.util.Args; import org.jfree.chart.util.ResourceBundleWrapper; import org.jfree.chart.util.SerialUtils; /** * A Swing GUI component for displaying a {@link JFreeChart} object. * <P> * The panel registers with the chart to receive notification of changes to any * component of the chart. The chart is redrawn automatically whenever this * notification is received. */ public class ChartPanel extends JPanel implements ChartChangeListener, ChartProgressListener, ActionListener, MouseListener, MouseMotionListener, OverlayChangeListener, Printable, Serializable { /** For serialization. */ protected static final long serialVersionUID = 6046366297214274674L; /** * Default setting for buffer usage. The default has been changed to * {@code true} from version 1.0.13 onwards, because of a severe * performance problem with drawing the zoom rectangle using XOR (which * now happens only when the buffer is NOT used). */ public static final boolean DEFAULT_BUFFER_USED = true; /** The default panel width. */ public static final int DEFAULT_WIDTH = 1024; /** The default panel height. */ public static final int DEFAULT_HEIGHT = 768; /** The default limit below which chart scaling kicks in. */ public static final int DEFAULT_MINIMUM_DRAW_WIDTH = 300; /** The default limit below which chart scaling kicks in. */ public static final int DEFAULT_MINIMUM_DRAW_HEIGHT = 200; /** The default limit above which chart scaling kicks in. */ public static final int DEFAULT_MAXIMUM_DRAW_WIDTH = 1024; /** The default limit above which chart scaling kicks in. */ public static final int DEFAULT_MAXIMUM_DRAW_HEIGHT = 768; /** The minimum size required to perform a zoom on a rectangle */ public static final int DEFAULT_ZOOM_TRIGGER_DISTANCE = 10; /** Properties action command. */ public static final String PROPERTIES_COMMAND = "PROPERTIES"; /** * Copy action command. * * @since 1.0.13 */ public static final String COPY_COMMAND = "COPY"; /** Save action command. */ public static final String SAVE_COMMAND = "SAVE"; /** Action command to save as PNG. */ protected static final String SAVE_AS_PNG_COMMAND = "SAVE_AS_PNG"; /** Action command to save as PNG - use screen size */ protected static final String SAVE_AS_PNG_SIZE_COMMAND = "SAVE_AS_PNG_SIZE"; /** Action command to save as SVG. */ protected static final String SAVE_AS_SVG_COMMAND = "SAVE_AS_SVG"; /** Action command to save as PDF. */ protected static final String SAVE_AS_PDF_COMMAND = "SAVE_AS_PDF"; /** Print action command. */ public static final String PRINT_COMMAND = "PRINT"; /** Zoom in (both axes) action command. */ public static final String ZOOM_IN_BOTH_COMMAND = "ZOOM_IN_BOTH"; /** Zoom in (domain axis only) action command. */ public static final String ZOOM_IN_DOMAIN_COMMAND = "ZOOM_IN_DOMAIN"; /** Zoom in (range axis only) action command. */ public static final String ZOOM_IN_RANGE_COMMAND = "ZOOM_IN_RANGE"; /** Zoom out (both axes) action command. */ public static final String ZOOM_OUT_BOTH_COMMAND = "ZOOM_OUT_BOTH"; /** Zoom out (domain axis only) action command. */ public static final String ZOOM_OUT_DOMAIN_COMMAND = "ZOOM_DOMAIN_BOTH"; /** Zoom out (range axis only) action command. */ public static final String ZOOM_OUT_RANGE_COMMAND = "ZOOM_RANGE_BOTH"; /** Zoom reset (both axes) action command. */ public static final String ZOOM_RESET_BOTH_COMMAND = "ZOOM_RESET_BOTH"; /** Zoom reset (domain axis only) action command. */ public static final String ZOOM_RESET_DOMAIN_COMMAND = "ZOOM_RESET_DOMAIN"; /** Zoom reset (range axis only) action command. */ public static final String ZOOM_RESET_RANGE_COMMAND = "ZOOM_RESET_RANGE"; /** The chart that is displayed in the panel. */ protected JFreeChart chart; /** Storage for registered (chart) mouse listeners. */ protected transient EventListenerList chartMouseListeners; /** A flag that controls whether or not the off-screen buffer is used. */ protected boolean useBuffer; /** A flag that indicates that the buffer should be refreshed. */ protected boolean refreshBuffer; /** A buffer for the rendered chart. */ protected transient Image chartBuffer; /** The height of the chart buffer. */ protected int chartBufferHeight; /** The width of the chart buffer. */ protected int chartBufferWidth; /** * The minimum width for drawing a chart (uses scaling for smaller widths). */ protected int minimumDrawWidth; /** * The minimum height for drawing a chart (uses scaling for smaller * heights). */ protected int minimumDrawHeight; /** * The maximum width for drawing a chart (uses scaling for bigger * widths). */ protected int maximumDrawWidth; /** * The maximum height for drawing a chart (uses scaling for bigger * heights). */ protected int maximumDrawHeight; /** The popup menu for the frame. */ protected JPopupMenu popup; /** The drawing info collected the last time the chart was drawn. */ protected ChartRenderingInfo info; /** The chart anchor point. */ protected Point2D anchor; /** The scale factor used to draw the chart. */ protected double scaleX; /** The scale factor used to draw the chart. */ protected double scaleY; /** The plot orientation. */ protected PlotOrientation orientation = PlotOrientation.VERTICAL; /** A flag that controls whether or not domain zooming is enabled. */ protected boolean domainZoomable = false; /** A flag that controls whether or not range zooming is enabled. */ protected boolean rangeZoomable = false; /** * The zoom rectangle starting point (selected by the user with a mouse * click). This is a point on the screen, not the chart (which may have * been scaled up or down to fit the panel). */ protected Point2D zoomPoint = null; /** The zoom rectangle (selected by the user with the mouse). */ protected transient Rectangle2D zoomRectangle = null; /** Controls if the zoom rectangle is drawn as an outline or filled. */ protected boolean fillZoomRectangle = true; /** The minimum distance required to drag the mouse to trigger a zoom. */ protected int zoomTriggerDistance; /** Menu item for zooming in on a chart (both axes). */ protected JMenuItem zoomInBothMenuItem; /** Menu item for zooming in on a chart (domain axis). */ protected JMenuItem zoomInDomainMenuItem; /** Menu item for zooming in on a chart (range axis). */ protected JMenuItem zoomInRangeMenuItem; /** Menu item for zooming out on a chart. */ protected JMenuItem zoomOutBothMenuItem; /** Menu item for zooming out on a chart (domain axis). */ protected JMenuItem zoomOutDomainMenuItem; /** Menu item for zooming out on a chart (range axis). */ protected JMenuItem zoomOutRangeMenuItem; /** Menu item for resetting the zoom (both axes). */ protected JMenuItem zoomResetBothMenuItem; /** Menu item for resetting the zoom (domain axis only). */ protected JMenuItem zoomResetDomainMenuItem; /** Menu item for resetting the zoom (range axis only). */ protected JMenuItem zoomResetRangeMenuItem; /** * The default directory for saving charts to file. * * @since 1.0.7 */ protected File defaultDirectoryForSaveAs; /** A flag that controls whether or not file extensions are enforced. */ protected boolean enforceFileExtensions; /** A flag that indicates if original tooltip delays are changed. */ protected boolean ownToolTipDelaysActive; /** Original initial tooltip delay of ToolTipManager.sharedInstance(). */ protected int originalToolTipInitialDelay; /** Original reshow tooltip delay of ToolTipManager.sharedInstance(). */ protected int originalToolTipReshowDelay; /** Original dismiss tooltip delay of ToolTipManager.sharedInstance(). */ protected int originalToolTipDismissDelay; /** Own initial tooltip delay to be used in this chart panel. */ protected int ownToolTipInitialDelay; /** Own reshow tooltip delay to be used in this chart panel. */ protected int ownToolTipReshowDelay; /** Own dismiss tooltip delay to be used in this chart panel. */ protected int ownToolTipDismissDelay; /** The factor used to zoom in on an axis range. */ protected double zoomInFactor = 0.5; /** The factor used to zoom out on an axis range. */ protected double zoomOutFactor = 2.0; /** * A flag that controls whether zoom operations are centred on the * current anchor point, or the centre point of the relevant axis. * * @since 1.0.7 */ protected boolean zoomAroundAnchor; /** * The paint used to draw the zoom rectangle outline. * * @since 1.0.13 */ protected transient Paint zoomOutlinePaint; /** * The zoom fill paint (should use transparency). * * @since 1.0.13 */ protected transient Paint zoomFillPaint; /** The resourceBundle for the localization. */ protected static ResourceBundle localizationResources = ResourceBundleWrapper.getBundle( "org.jfree.chart.LocalizationBundle"); /** * Temporary storage for the width and height of the chart * drawing area during panning. */ protected double panW, panH; /** The last mouse position during panning. */ protected Point panLast; /** * The mask for mouse events to trigger panning. * * @since 1.0.13 */ protected int panMask = InputEvent.CTRL_MASK; /** * A list of overlays for the panel. * * @since 1.0.13 */ protected List<Overlay> overlays; /** * Constructs a panel that displays the specified chart. * * @param chart the chart. */ public ChartPanel(JFreeChart chart) { this(chart, DEFAULT_WIDTH, DEFAULT_HEIGHT, DEFAULT_MINIMUM_DRAW_WIDTH, DEFAULT_MINIMUM_DRAW_HEIGHT, DEFAULT_MAXIMUM_DRAW_WIDTH, DEFAULT_MAXIMUM_DRAW_HEIGHT, DEFAULT_BUFFER_USED, true, // properties true, // save true, // print true, // zoom true // tooltips ); } /** * Constructs a panel containing a chart. The {@code useBuffer} flag * controls whether or not an offscreen {@code BufferedImage} is * maintained for the chart. If the buffer is used, more memory is * consumed, but panel repaints will be a lot quicker in cases where the * chart itself hasn't changed (for example, when another frame is moved * to reveal the panel). WARNING: If you set the {@code useBuffer} * flag to false, note that the mouse zooming rectangle will (in that case) * be drawn using XOR, and there is a SEVERE performance problem with that * on JRE6 on Windows. * * @param chart the chart. * @param useBuffer a flag controlling whether or not an off-screen buffer * is used (read the warning above before setting this * to {@code false}). */ public ChartPanel(JFreeChart chart, boolean useBuffer) { this(chart, DEFAULT_WIDTH, DEFAULT_HEIGHT, DEFAULT_MINIMUM_DRAW_WIDTH, DEFAULT_MINIMUM_DRAW_HEIGHT, DEFAULT_MAXIMUM_DRAW_WIDTH, DEFAULT_MAXIMUM_DRAW_HEIGHT, useBuffer, true, // properties true, // save true, // print true, // zoom true // tooltips ); } /** * Constructs a JFreeChart panel. * * @param chart the chart. * @param properties a flag indicating whether or not the chart property * editor should be available via the popup menu. * @param save a flag indicating whether or not save options should be * available via the popup menu. * @param print a flag indicating whether or not the print option * should be available via the popup menu. * @param zoom a flag indicating whether or not zoom options should * be added to the popup menu. * @param tooltips a flag indicating whether or not tooltips should be * enabled for the chart. */ public ChartPanel(JFreeChart chart, boolean properties, boolean save, boolean print, boolean zoom, boolean tooltips) { this(chart, DEFAULT_WIDTH, DEFAULT_HEIGHT, DEFAULT_MINIMUM_DRAW_WIDTH, DEFAULT_MINIMUM_DRAW_HEIGHT, DEFAULT_MAXIMUM_DRAW_WIDTH, DEFAULT_MAXIMUM_DRAW_HEIGHT, DEFAULT_BUFFER_USED, properties, save, print, zoom, tooltips); } /** * Constructs a JFreeChart panel. * * @param chart the chart. * @param width the preferred width of the panel. * @param height the preferred height of the panel. * @param minimumDrawWidth the minimum drawing width. * @param minimumDrawHeight the minimum drawing height. * @param maximumDrawWidth the maximum drawing width. * @param maximumDrawHeight the maximum drawing height. * @param useBuffer a flag that indicates whether to use the off-screen * buffer to improve performance (at the expense of * memory). * @param properties a flag indicating whether or not the chart property * editor should be available via the popup menu. * @param save a flag indicating whether or not save options should be * available via the popup menu. * @param print a flag indicating whether or not the print option * should be available via the popup menu. * @param zoom a flag indicating whether or not zoom options should be * added to the popup menu. * @param tooltips a flag indicating whether or not tooltips should be * enabled for the chart. */ public ChartPanel(JFreeChart chart, int width, int height, int minimumDrawWidth, int minimumDrawHeight, int maximumDrawWidth, int maximumDrawHeight, boolean useBuffer, boolean properties, boolean save, boolean print, boolean zoom, boolean tooltips) { this(chart, width, height, minimumDrawWidth, minimumDrawHeight, maximumDrawWidth, maximumDrawHeight, useBuffer, properties, true, save, print, zoom, tooltips); } /** * Constructs a JFreeChart panel. * * @param chart the chart. * @param width the preferred width of the panel. * @param height the preferred height of the panel. * @param minimumDrawWidth the minimum drawing width. * @param minimumDrawHeight the minimum drawing height. * @param maximumDrawWidth the maximum drawing width. * @param maximumDrawHeight the maximum drawing height. * @param useBuffer a flag that indicates whether to use the off-screen * buffer to improve performance (at the expense of * memory). * @param properties a flag indicating whether or not the chart property * editor should be available via the popup menu. * @param copy a flag indicating whether or not a copy option should be * available via the popup menu. * @param save a flag indicating whether or not save options should be * available via the popup menu. * @param print a flag indicating whether or not the print option * should be available via the popup menu. * @param zoom a flag indicating whether or not zoom options should be * added to the popup menu. * @param tooltips a flag indicating whether or not tooltips should be * enabled for the chart. * * @since 1.0.13 */ public ChartPanel(JFreeChart chart, int width, int height, int minimumDrawWidth, int minimumDrawHeight, int maximumDrawWidth, int maximumDrawHeight, boolean useBuffer, boolean properties, boolean copy, boolean save, boolean print, boolean zoom, boolean tooltips) { setChart(chart); this.chartMouseListeners = new EventListenerList(); this.info = new ChartRenderingInfo(); setPreferredSize(new Dimension(width, height)); this.useBuffer = useBuffer; this.refreshBuffer = false; this.minimumDrawWidth = minimumDrawWidth; this.minimumDrawHeight = minimumDrawHeight; this.maximumDrawWidth = maximumDrawWidth; this.maximumDrawHeight = maximumDrawHeight; this.zoomTriggerDistance = DEFAULT_ZOOM_TRIGGER_DISTANCE; // set up popup menu... this.popup = null; if (properties || copy || save || print || zoom) { this.popup = createPopupMenu(properties, copy, save, print, zoom); } enableEvents(AWTEvent.MOUSE_EVENT_MASK); enableEvents(AWTEvent.MOUSE_MOTION_EVENT_MASK); setDisplayToolTips(tooltips); addMouseListener(this); addMouseMotionListener(this); this.defaultDirectoryForSaveAs = null; this.enforceFileExtensions = true; // initialize ChartPanel-specific tool tip delays with // values the from ToolTipManager.sharedInstance() ToolTipManager ttm = ToolTipManager.sharedInstance(); this.ownToolTipInitialDelay = ttm.getInitialDelay(); this.ownToolTipDismissDelay = ttm.getDismissDelay(); this.ownToolTipReshowDelay = ttm.getReshowDelay(); this.zoomAroundAnchor = false; this.zoomOutlinePaint = Color.BLUE; this.zoomFillPaint = new Color(0, 0, 255, 63); this.panMask = InputEvent.CTRL_MASK; // for MacOSX we can't use the CTRL key for mouse drags, see: String osName = System.getProperty("os.name").toLowerCase(); if (osName.startsWith("mac os x")) { this.panMask = InputEvent.ALT_MASK; } this.overlays = new ArrayList<>(); } /** * Returns the chart contained in the panel. * * @return The chart (possibly {@code null}). */ public JFreeChart getChart() { return this.chart; } /** * Sets the chart that is displayed in the panel. * * @param chart the chart ({@code null} permitted). */ public void setChart(JFreeChart chart) { // stop listening for changes to the existing chart if (this.chart != null) { this.chart.removeChangeListener(this); this.chart.removeProgressListener(this); } // add the new chart this.chart = chart; if (chart != null) { this.chart.addChangeListener(this); this.chart.addProgressListener(this); Plot plot = chart.getPlot(); this.domainZoomable = false; this.rangeZoomable = false; if (plot instanceof Zoomable) { Zoomable z = (Zoomable) plot; this.domainZoomable = z.isDomainZoomable(); this.rangeZoomable = z.isRangeZoomable(); this.orientation = z.getOrientation(); } } else { this.domainZoomable = false; this.rangeZoomable = false; } if (this.useBuffer) { this.refreshBuffer = true; } repaint(); } /** * Returns the minimum drawing width for charts. * <P> * If the width available on the panel is less than this, then the chart is * drawn at the minimum width then scaled down to fit. * * @return The minimum drawing width. */ public int getMinimumDrawWidth() { return this.minimumDrawWidth; } /** * Sets the minimum drawing width for the chart on this panel. * <P> * At the time the chart is drawn on the panel, if the available width is * less than this amount, the chart will be drawn using the minimum width * then scaled down to fit the available space. * * @param width The width. */ public void setMinimumDrawWidth(int width) { this.minimumDrawWidth = width; } /** * Returns the maximum drawing width for charts. * <P> * If the width available on the panel is greater than this, then the chart * is drawn at the maximum width then scaled up to fit. * * @return The maximum drawing width. */ public int getMaximumDrawWidth() { return this.maximumDrawWidth; } /** * Sets the maximum drawing width for the chart on this panel. * <P> * At the time the chart is drawn on the panel, if the available width is * greater than this amount, the chart will be drawn using the maximum * width then scaled up to fit the available space. * * @param width The width. */ public void setMaximumDrawWidth(int width) { this.maximumDrawWidth = width; } /** * Returns the minimum drawing height for charts. * <P> * If the height available on the panel is less than this, then the chart * is drawn at the minimum height then scaled down to fit. * * @return The minimum drawing height. */ public int getMinimumDrawHeight() { return this.minimumDrawHeight; } /** * Sets the minimum drawing height for the chart on this panel. * <P> * At the time the chart is drawn on the panel, if the available height is * less than this amount, the chart will be drawn using the minimum height * then scaled down to fit the available space. * * @param height The height. */ public void setMinimumDrawHeight(int height) { this.minimumDrawHeight = height; } /** * Returns the maximum drawing height for charts. * <P> * If the height available on the panel is greater than this, then the * chart is drawn at the maximum height then scaled up to fit. * * @return The maximum drawing height. */ public int getMaximumDrawHeight() { return this.maximumDrawHeight; } /** * Sets the maximum drawing height for the chart on this panel. * <P> * At the time the chart is drawn on the panel, if the available height is * greater than this amount, the chart will be drawn using the maximum * height then scaled up to fit the available space. * * @param height The height. */ public void setMaximumDrawHeight(int height) { this.maximumDrawHeight = height; } /** * Returns the X scale factor for the chart. This will be 1.0 if no * scaling has been used. * * @return The scale factor. */ public double getScaleX() { return this.scaleX; } /** * Returns the Y scale factory for the chart. This will be 1.0 if no * scaling has been used. * * @return The scale factor. */ public double getScaleY() { return this.scaleY; } /** * Returns the anchor point. * * @return The anchor point (possibly {@code null}). */ public Point2D getAnchor() { return this.anchor; } /** * Sets the anchor point. This method is provided for the use of * subclasses, not end users. * * @param anchor the anchor point ({@code null} permitted). */ protected void setAnchor(Point2D anchor) { this.anchor = anchor; } /** * Returns the popup menu. * * @return The popup menu. */ public JPopupMenu getPopupMenu() { return this.popup; } /** * Sets the popup menu for the panel. * * @param popup the popup menu ({@code null} permitted). */ public void setPopupMenu(JPopupMenu popup) { this.popup = popup; } /** * Returns the chart rendering info from the most recent chart redraw. * * @return The chart rendering info. */ public ChartRenderingInfo getChartRenderingInfo() { return this.info; } /** * A convenience method that switches on mouse-based zooming. * * @param flag {@code true} enables zooming and rectangle fill on * zoom. */ public void setMouseZoomable(boolean flag) { setMouseZoomable(flag, true); } /** * A convenience method that switches on mouse-based zooming. * * @param flag {@code true} if zooming enabled * @param fillRectangle {@code true} if zoom rectangle is filled, * false if rectangle is shown as outline only. */ public void setMouseZoomable(boolean flag, boolean fillRectangle) { setDomainZoomable(flag); setRangeZoomable(flag); setFillZoomRectangle(fillRectangle); } /** * Returns the flag that determines whether or not zooming is enabled for * the domain axis. * * @return A boolean. */ public boolean isDomainZoomable() { return this.domainZoomable; } /** * Sets the flag that controls whether or not zooming is enabled for the * domain axis. A check is made to ensure that the current plot supports * zooming for the domain values. * * @param flag {@code true} enables zooming if possible. */ public void setDomainZoomable(boolean flag) { if (flag) { Plot plot = this.chart.getPlot(); if (plot instanceof Zoomable) { Zoomable z = (Zoomable) plot; this.domainZoomable = flag && (z.isDomainZoomable()); } } else { this.domainZoomable = false; } } /** * Returns the flag that determines whether or not zooming is enabled for * the range axis. * * @return A boolean. */ public boolean isRangeZoomable() { return this.rangeZoomable; } /** * A flag that controls mouse-based zooming on the vertical axis. * * @param flag {@code true} enables zooming. */ public void setRangeZoomable(boolean flag) { if (flag) { Plot plot = this.chart.getPlot(); if (plot instanceof Zoomable) { Zoomable z = (Zoomable) plot; this.rangeZoomable = flag && (z.isRangeZoomable()); } } else { this.rangeZoomable = false; } } /** * Returns the flag that controls whether or not the zoom rectangle is * filled when drawn. * * @return A boolean. */ public boolean getFillZoomRectangle() { return this.fillZoomRectangle; } /** * A flag that controls how the zoom rectangle is drawn. * * @param flag {@code true} instructs to fill the rectangle on * zoom, otherwise it will be outlined. */ public void setFillZoomRectangle(boolean flag) { this.fillZoomRectangle = flag; } /** * Returns the zoom trigger distance. This controls how far the mouse must * move before a zoom action is triggered. * * @return The distance (in Java2D units). */ public int getZoomTriggerDistance() { return this.zoomTriggerDistance; } /** * Sets the zoom trigger distance. This controls how far the mouse must * move before a zoom action is triggered. * * @param distance the distance (in Java2D units). */ public void setZoomTriggerDistance(int distance) { this.zoomTriggerDistance = distance; } /** * Returns the default directory for the "save as" option. * * @return The default directory (possibly {@code null}). * * @since 1.0.7 */ public File getDefaultDirectoryForSaveAs() { return this.defaultDirectoryForSaveAs; } /** * Sets the default directory for the "save as" option. If you set this * to {@code null}, the user's default directory will be used. * * @param directory the directory ({@code null} permitted). * * @since 1.0.7 */ public void setDefaultDirectoryForSaveAs(File directory) { if (directory != null) { if (!directory.isDirectory()) { throw new IllegalArgumentException( "The 'directory' argument is not a directory."); } } this.defaultDirectoryForSaveAs = directory; } /** * Returns {@code true} if file extensions should be enforced, and * {@code false} otherwise. * * @return The flag. * * @see #setEnforceFileExtensions(boolean) */ public boolean isEnforceFileExtensions() { return this.enforceFileExtensions; } /** * Sets a flag that controls whether or not file extensions are enforced. * * @param enforce the new flag value. * * @see #isEnforceFileExtensions() */ public void setEnforceFileExtensions(boolean enforce) { this.enforceFileExtensions = enforce; } /** * Returns the flag that controls whether or not zoom operations are * centered around the current anchor point. * * @return A boolean. * * @since 1.0.7 * * @see #setZoomAroundAnchor(boolean) */ public boolean getZoomAroundAnchor() { return this.zoomAroundAnchor; } /** * Sets the flag that controls whether or not zoom operations are * centered around the current anchor point. * * @param zoomAroundAnchor the new flag value. * * @since 1.0.7 * * @see #getZoomAroundAnchor() */ public void setZoomAroundAnchor(boolean zoomAroundAnchor) { this.zoomAroundAnchor = zoomAroundAnchor; } /** * Returns the zoom rectangle fill paint. * * @return The zoom rectangle fill paint (never {@code null}). * * @see #setZoomFillPaint(java.awt.Paint) * @see #setFillZoomRectangle(boolean) * * @since 1.0.13 */ public Paint getZoomFillPaint() { return this.zoomFillPaint; } /** * Sets the zoom rectangle fill paint. * * @param paint the paint ({@code null} not permitted). * * @see #getZoomFillPaint() * @see #getFillZoomRectangle() * * @since 1.0.13 */ public void setZoomFillPaint(Paint paint) { Args.nullNotPermitted(paint, "paint"); this.zoomFillPaint = paint; } /** * Returns the zoom rectangle outline paint. * * @return The zoom rectangle outline paint (never {@code null}). * * @see #setZoomOutlinePaint(java.awt.Paint) * @see #setFillZoomRectangle(boolean) * * @since 1.0.13 */ public Paint getZoomOutlinePaint() { return this.zoomOutlinePaint; } /** * Sets the zoom rectangle outline paint. * * @param paint the paint ({@code null} not permitted). * * @see #getZoomOutlinePaint() * @see #getFillZoomRectangle() * * @since 1.0.13 */ public void setZoomOutlinePaint(Paint paint) { this.zoomOutlinePaint = paint; } /** * The mouse wheel handler. */ protected MouseWheelHandler mouseWheelHandler; /** * Returns {@code true} if the mouse wheel handler is enabled, and * {@code false} otherwise. * * @return A boolean. * * @since 1.0.13 */ public boolean isMouseWheelEnabled() { return this.mouseWheelHandler != null; } /** * Enables or disables mouse wheel support for the panel. * * @param flag a boolean. * * @since 1.0.13 */ public void setMouseWheelEnabled(boolean flag) { if (flag && this.mouseWheelHandler == null) { this.mouseWheelHandler = new MouseWheelHandler(this); } else if (!flag && this.mouseWheelHandler != null) { this.removeMouseWheelListener(this.mouseWheelHandler); this.mouseWheelHandler = null; } } /** * Add an overlay to the panel. * * @param overlay the overlay ({@code null} not permitted). * * @since 1.0.13 */ public void addOverlay(Overlay overlay) { Args.nullNotPermitted(overlay, "overlay"); this.overlays.add(overlay); overlay.addChangeListener(this); repaint(); } /** * Removes an overlay from the panel. * * @param overlay the overlay to remove ({@code null} not permitted). * * @since 1.0.13 */ public void removeOverlay(Overlay overlay) { Args.nullNotPermitted(overlay, "overlay"); boolean removed = this.overlays.remove(overlay); if (removed) { overlay.removeChangeListener(this); repaint(); } } /** * Handles a change to an overlay by repainting the panel. * * @param event the event. * * @since 1.0.13 */ @Override public void overlayChanged(OverlayChangeEvent event) { repaint(); } /** * Switches the display of tooltips for the panel on or off. Note that * tooltips can only be displayed if the chart has been configured to * generate tooltip items. * * @param flag {@code true} to enable tooltips, {@code false} to * disable tooltips. */ public void setDisplayToolTips(boolean flag) { if (flag) { ToolTipManager.sharedInstance().registerComponent(this); } else { ToolTipManager.sharedInstance().unregisterComponent(this); } } /** * Returns a string for the tooltip. * * @param e the mouse event. * * @return A tool tip or {@code null} if no tooltip is available. */ @Override public String getToolTipText(MouseEvent e) { String result = null; if (this.info != null) { EntityCollection entities = this.info.getEntityCollection(); if (entities != null) { Insets insets = getInsets(); ChartEntity entity = entities.getEntity( (int) ((e.getX() - insets.left) / this.scaleX), (int) ((e.getY() - insets.top) / this.scaleY)); if (entity != null) { result = entity.getToolTipText(); } } } return result; } /** * Translates a Java2D point on the chart to a screen location. * * @param java2DPoint the Java2D point. * * @return The screen location. */ public Point translateJava2DToScreen(Point2D java2DPoint) { Insets insets = getInsets(); int x = (int) (java2DPoint.getX() * this.scaleX + insets.left); int y = (int) (java2DPoint.getY() * this.scaleY + insets.top); return new Point(x, y); } /** * Translates a panel (component) location to a Java2D point. * * @param screenPoint the screen location ({@code null} not * permitted). * * @return The Java2D coordinates. */ public Point2D translateScreenToJava2D(Point screenPoint) { Insets insets = getInsets(); double x = (screenPoint.getX() - insets.left) / this.scaleX; double y = (screenPoint.getY() - insets.top) / this.scaleY; return new Point2D.Double(x, y); } /** * Applies any scaling that is in effect for the chart drawing to the * given rectangle. * * @param rect the rectangle ({@code null} not permitted). * * @return A new scaled rectangle. */ public Rectangle2D scale(Rectangle2D rect) { Insets insets = getInsets(); double x = rect.getX() * getScaleX() + insets.left; double y = rect.getY() * getScaleY() + insets.top; double w = rect.getWidth() * getScaleX(); double h = rect.getHeight() * getScaleY(); return new Rectangle2D.Double(x, y, w, h); } /** * Returns the chart entity at a given point. * <P> * This method will return null if there is (a) no entity at the given * point, or (b) no entity collection has been generated. * * @param viewX the x-coordinate. * @param viewY the y-coordinate. * * @return The chart entity (possibly {@code null}). */ public ChartEntity getEntityForPoint(int viewX, int viewY) { ChartEntity result = null; if (this.info != null) { Insets insets = getInsets(); double x = (viewX - insets.left) / this.scaleX; double y = (viewY - insets.top) / this.scaleY; EntityCollection entities = this.info.getEntityCollection(); result = entities != null ? entities.getEntity(x, y) : null; } return result; } /** * Returns the flag that controls whether or not the offscreen buffer * needs to be refreshed. * * @return A boolean. */ public boolean getRefreshBuffer() { return this.refreshBuffer; } /** * Sets the refresh buffer flag. This flag is used to avoid unnecessary * redrawing of the chart when the offscreen image buffer is used. * * @param flag {@code true} indicates that the buffer should be * refreshed. */ public void setRefreshBuffer(boolean flag) { this.refreshBuffer = flag; } /** * Paints the component by drawing the chart to fill the entire component, * but allowing for the insets (which will be non-zero if a border has been * set for this component). To increase performance (at the expense of * memory), an off-screen buffer image can be used. * * @param g the graphics device for drawing on. */ @Override public void paintComponent(Graphics g) { super.paintComponent(g); if (this.chart == null) { return; } Graphics2D g2 = (Graphics2D) g.create(); // first determine the size of the chart rendering area... Dimension size = getSize(); Insets insets = getInsets(); Rectangle2D available = new Rectangle2D.Double(insets.left, insets.top, size.getWidth() - insets.left - insets.right, size.getHeight() - insets.top - insets.bottom); // work out if scaling is required... boolean scale = false; double drawWidth = available.getWidth(); double drawHeight = available.getHeight(); this.scaleX = 1.0; this.scaleY = 1.0; if (drawWidth < this.minimumDrawWidth) { this.scaleX = drawWidth / this.minimumDrawWidth; drawWidth = this.minimumDrawWidth; scale = true; } else if (drawWidth > this.maximumDrawWidth) { this.scaleX = drawWidth / this.maximumDrawWidth; drawWidth = this.maximumDrawWidth; scale = true; } if (drawHeight < this.minimumDrawHeight) { this.scaleY = drawHeight / this.minimumDrawHeight; drawHeight = this.minimumDrawHeight; scale = true; } else if (drawHeight > this.maximumDrawHeight) { this.scaleY = drawHeight / this.maximumDrawHeight; drawHeight = this.maximumDrawHeight; scale = true; } Rectangle2D chartArea = new Rectangle2D.Double(0.0, 0.0, drawWidth, drawHeight); // are we using the chart buffer? if (this.useBuffer) { // for better rendering on the HiDPI monitors upscaling the buffer to the "native" resoution // instead of using logical one provided by Swing final AffineTransform globalTransform = ((Graphics2D) g).getTransform(); final double globalScaleX = globalTransform.getScaleX(); final double globalScaleY = globalTransform.getScaleY(); final int scaledWidth = (int) (available.getWidth() * globalScaleX); final int scaledHeight = (int) (available.getHeight() * globalScaleY); // do we need to resize the buffer? if ((this.chartBuffer == null) || (this.chartBufferWidth != scaledWidth) || (this.chartBufferHeight != scaledHeight)) { this.chartBufferWidth = scaledWidth; this.chartBufferHeight = scaledHeight; GraphicsConfiguration gc = g2.getDeviceConfiguration(); this.chartBuffer = gc.createCompatibleImage( this.chartBufferWidth, this.chartBufferHeight, Transparency.TRANSLUCENT); this.refreshBuffer = true; } // do we need to redraw the buffer? if (this.refreshBuffer) { this.refreshBuffer = false; // clear the flag // scale graphics of the buffer to the same value as global // Swing graphics - this allow to paint all elements as usual // but applies all necessary smoothing Graphics2D bufferG2 = (Graphics2D) this.chartBuffer.getGraphics(); bufferG2.scale(globalScaleX, globalScaleY); Rectangle2D bufferArea = new Rectangle2D.Double( 0, 0, available.getWidth(), available.getHeight()); // make the background of the buffer clear and transparent Composite savedComposite = bufferG2.getComposite(); bufferG2.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, 0.0f)); Rectangle r = new Rectangle(0, 0, (int) available.getWidth(), (int) available.getHeight()); bufferG2.fill(r); bufferG2.setComposite(savedComposite); if (scale) { AffineTransform saved = bufferG2.getTransform(); AffineTransform st = AffineTransform.getScaleInstance( this.scaleX, this.scaleY); bufferG2.transform(st); this.chart.draw(bufferG2, chartArea, this.anchor, this.info); bufferG2.setTransform(saved); } else { this.chart.draw(bufferG2, bufferArea, this.anchor, this.info); } bufferG2.dispose(); } // zap the buffer onto the panel... g2.drawImage(this.chartBuffer, insets.left, insets.top, (int) available.getWidth(), (int) available.getHeight(), this); } else { // redrawing the chart every time... AffineTransform saved = g2.getTransform(); g2.translate(insets.left, insets.top); if (scale) { AffineTransform st = AffineTransform.getScaleInstance( this.scaleX, this.scaleY); g2.transform(st); } this.chart.draw(g2, chartArea, this.anchor, this.info); g2.setTransform(saved); } for (Overlay overlay : this.overlays) { overlay.paintOverlay(g2, this); } // redraw the zoom rectangle (if present) - if useBuffer is false, // we use XOR so we can XOR the rectangle away again without redrawing // the chart drawZoomRectangle(g2, !this.useBuffer); g2.dispose(); this.anchor = null; } /** * Receives notification of changes to the chart, and redraws the chart. * * @param event details of the chart change event. */ @Override public void chartChanged(ChartChangeEvent event) { this.refreshBuffer = true; Plot plot = this.chart.getPlot(); if (plot instanceof Zoomable) { Zoomable z = (Zoomable) plot; this.orientation = z.getOrientation(); } repaint(); } /** * Receives notification of a chart progress event. * * @param event the event. */ @Override public void chartProgress(ChartProgressEvent event) { // does nothing - override if necessary } /** * Handles action events generated by the popup menu. * * @param event the event. */ @Override public void actionPerformed(ActionEvent event) { String command = event.getActionCommand(); // many of the zoom methods need a screen location - all we have is // the zoomPoint, but it might be null. Here we grab the x and y // coordinates, or use defaults... double screenX = -1.0; double screenY = -1.0; if (this.zoomPoint != null) { screenX = this.zoomPoint.getX(); screenY = this.zoomPoint.getY(); } if (command.equals(PROPERTIES_COMMAND)) { doEditChartProperties(); } else if (command.equals(COPY_COMMAND)) { doCopy(); } else if (command.equals(SAVE_AS_PNG_COMMAND)) { try { doSaveAs(); } catch (IOException e) { JOptionPane.showMessageDialog(this, "I/O error occurred.", localizationResources.getString("Save_as_PNG"), JOptionPane.WARNING_MESSAGE); } } else if (command.equals(SAVE_AS_PNG_SIZE_COMMAND)) { try{ final Dimension ss = Toolkit.getDefaultToolkit().getScreenSize(); doSaveAs(ss.width, ss.height); } catch (IOException e){ JOptionPane.showMessageDialog(ChartPanel.this, "I/O error occurred.", localizationResources.getString("Save_as_PNG"), JOptionPane.WARNING_MESSAGE); } } else if (command.equals(SAVE_AS_SVG_COMMAND)) { try { saveAsSVG(null); } catch (IOException e) { JOptionPane.showMessageDialog(this, "I/O error occurred.", localizationResources.getString("Save_as_SVG"), JOptionPane.WARNING_MESSAGE); } } else if (command.equals(SAVE_AS_PDF_COMMAND)) { saveAsPDF(null); } else if (command.equals(PRINT_COMMAND)) { createChartPrintJob(); } else if (command.equals(ZOOM_IN_BOTH_COMMAND)) { zoomInBoth(screenX, screenY); } else if (command.equals(ZOOM_IN_DOMAIN_COMMAND)) { zoomInDomain(screenX, screenY); } else if (command.equals(ZOOM_IN_RANGE_COMMAND)) { zoomInRange(screenX, screenY); } else if (command.equals(ZOOM_OUT_BOTH_COMMAND)) { zoomOutBoth(screenX, screenY); } else if (command.equals(ZOOM_OUT_DOMAIN_COMMAND)) { zoomOutDomain(screenX, screenY); } else if (command.equals(ZOOM_OUT_RANGE_COMMAND)) { zoomOutRange(screenX, screenY); } else if (command.equals(ZOOM_RESET_BOTH_COMMAND)) { restoreAutoBounds(); } else if (command.equals(ZOOM_RESET_DOMAIN_COMMAND)) { restoreAutoDomainBounds(); } else if (command.equals(ZOOM_RESET_RANGE_COMMAND)) { restoreAutoRangeBounds(); } } /** * Handles a 'mouse entered' event. This method changes the tooltip delays * of ToolTipManager.sharedInstance() to the possibly different values set * for this chart panel. * * @param e the mouse event. */ @Override public void mouseEntered(MouseEvent e) { if (!this.ownToolTipDelaysActive) { ToolTipManager ttm = ToolTipManager.sharedInstance(); this.originalToolTipInitialDelay = ttm.getInitialDelay(); ttm.setInitialDelay(this.ownToolTipInitialDelay); this.originalToolTipReshowDelay = ttm.getReshowDelay(); ttm.setReshowDelay(this.ownToolTipReshowDelay); this.originalToolTipDismissDelay = ttm.getDismissDelay(); ttm.setDismissDelay(this.ownToolTipDismissDelay); this.ownToolTipDelaysActive = true; } } /** * Handles a 'mouse exited' event. This method resets the tooltip delays of * ToolTipManager.sharedInstance() to their * original values in effect before mouseEntered() * * @param e the mouse event. */ @Override public void mouseExited(MouseEvent e) { if (this.ownToolTipDelaysActive) { // restore original tooltip dealys ToolTipManager ttm = ToolTipManager.sharedInstance(); ttm.setInitialDelay(this.originalToolTipInitialDelay); ttm.setReshowDelay(this.originalToolTipReshowDelay); ttm.setDismissDelay(this.originalToolTipDismissDelay); this.ownToolTipDelaysActive = false; } } /** * Handles a 'mouse pressed' event. * <P> * This event is the popup trigger on Unix/Linux. For Windows, the popup * trigger is the 'mouse released' event. * * @param e The mouse event. */ @Override public void mousePressed(MouseEvent e) { if (this.chart == null) { return; } Plot plot = this.chart.getPlot(); int mods = e.getModifiers(); if ((mods & this.panMask) == this.panMask) { // can we pan this plot? if (plot instanceof Pannable) { Pannable pannable = (Pannable) plot; if (pannable.isDomainPannable() || pannable.isRangePannable()) { Rectangle2D screenDataArea = getScreenDataArea(e.getX(), e.getY()); if (screenDataArea != null && screenDataArea.contains( e.getPoint())) { this.panW = screenDataArea.getWidth(); this.panH = screenDataArea.getHeight(); this.panLast = e.getPoint(); setCursor(Cursor.getPredefinedCursor( Cursor.MOVE_CURSOR)); } } // the actual panning occurs later in the mouseDragged() // method } } else if (this.zoomRectangle == null) { Rectangle2D screenDataArea = getScreenDataArea(e.getX(), e.getY()); if (screenDataArea != null) { this.zoomPoint = getPointInRectangle(e.getX(), e.getY(), screenDataArea); } else { this.zoomPoint = null; } if (e.isPopupTrigger()) { if (this.popup != null) { displayPopupMenu(e.getX(), e.getY()); } } } } /** * Returns a point based on (x, y) but constrained to be within the bounds * of the given rectangle. This method could be moved to JCommon. * * @param x the x-coordinate. * @param y the y-coordinate. * @param area the rectangle ({@code null} not permitted). * * @return A point within the rectangle. */ protected Point2D getPointInRectangle(int x, int y, Rectangle2D area) { double xx = Math.max(area.getMinX(), Math.min(x, area.getMaxX())); double yy = Math.max(area.getMinY(), Math.min(y, area.getMaxY())); return new Point2D.Double(xx, yy); } /** * Handles a 'mouse dragged' event. * * @param e the mouse event. */ @Override public void mouseDragged(MouseEvent e) { // if the popup menu has already been triggered, then ignore dragging... if (this.popup != null && this.popup.isShowing()) { return; } // handle panning if we have a start point if (this.panLast != null) { double dx = e.getX() - this.panLast.getX(); double dy = e.getY() - this.panLast.getY(); if (dx == 0.0 && dy == 0.0) { return; } double wPercent = -dx / this.panW; double hPercent = dy / this.panH; boolean old = this.chart.getPlot().isNotify(); this.chart.getPlot().setNotify(false); Pannable p = (Pannable) this.chart.getPlot(); if (p.getOrientation() == PlotOrientation.VERTICAL) { p.panDomainAxes(wPercent, this.info.getPlotInfo(), this.panLast); p.panRangeAxes(hPercent, this.info.getPlotInfo(), this.panLast); } else { p.panDomainAxes(hPercent, this.info.getPlotInfo(), this.panLast); p.panRangeAxes(wPercent, this.info.getPlotInfo(), this.panLast); } this.panLast = e.getPoint(); this.chart.getPlot().setNotify(old); return; } // if no initial zoom point was set, ignore dragging... if (this.zoomPoint == null) { return; } Graphics2D g2 = (Graphics2D) getGraphics(); // erase the previous zoom rectangle (if any). We only need to do // this is we are using XOR mode, which we do when we're not using // the buffer (if there is a buffer, then at the end of this method we // just trigger a repaint) if (!this.useBuffer) { drawZoomRectangle(g2, true); } boolean hZoom, vZoom; if (this.orientation == PlotOrientation.HORIZONTAL) { hZoom = this.rangeZoomable; vZoom = this.domainZoomable; } else { hZoom = this.domainZoomable; vZoom = this.rangeZoomable; } Rectangle2D scaledDataArea = getScreenDataArea( (int) this.zoomPoint.getX(), (int) this.zoomPoint.getY()); if (hZoom && vZoom) { // selected rectangle shouldn't extend outside the data area... double xmax = Math.min(e.getX(), scaledDataArea.getMaxX()); double ymax = Math.min(e.getY(), scaledDataArea.getMaxY()); this.zoomRectangle = new Rectangle2D.Double( this.zoomPoint.getX(), this.zoomPoint.getY(), xmax - this.zoomPoint.getX(), ymax - this.zoomPoint.getY()); } else if (hZoom) { double xmax = Math.min(e.getX(), scaledDataArea.getMaxX()); this.zoomRectangle = new Rectangle2D.Double( this.zoomPoint.getX(), scaledDataArea.getMinY(), xmax - this.zoomPoint.getX(), scaledDataArea.getHeight()); } else if (vZoom) { double ymax = Math.min(e.getY(), scaledDataArea.getMaxY()); this.zoomRectangle = new Rectangle2D.Double( scaledDataArea.getMinX(), this.zoomPoint.getY(), scaledDataArea.getWidth(), ymax - this.zoomPoint.getY()); } // Draw the new zoom rectangle... if (this.useBuffer) { repaint(); } else { // with no buffer, we use XOR to draw the rectangle "over" the // chart... drawZoomRectangle(g2, true); } g2.dispose(); } /** * Handles a 'mouse released' event. On Windows, we need to check if this * is a popup trigger, but only if we haven't already been tracking a zoom * rectangle. * * @param e information about the event. */ @Override public void mouseReleased(MouseEvent e) { // if we've been panning, we need to reset now that the mouse is // released... if (this.panLast != null) { this.panLast = null; setCursor(Cursor.getDefaultCursor()); } else if (this.zoomRectangle != null) { boolean hZoom, vZoom; if (this.orientation == PlotOrientation.HORIZONTAL) { hZoom = this.rangeZoomable; vZoom = this.domainZoomable; } else { hZoom = this.domainZoomable; vZoom = this.rangeZoomable; } boolean zoomTrigger1 = hZoom && Math.abs(e.getX() - this.zoomPoint.getX()) >= this.zoomTriggerDistance; boolean zoomTrigger2 = vZoom && Math.abs(e.getY() - this.zoomPoint.getY()) >= this.zoomTriggerDistance; if (zoomTrigger1 || zoomTrigger2) { if ((hZoom && (e.getX() < this.zoomPoint.getX())) || (vZoom && (e.getY() < this.zoomPoint.getY()))) { restoreAutoBounds(); } else { double x, y, w, h; Rectangle2D screenDataArea = getScreenDataArea( (int) this.zoomPoint.getX(), (int) this.zoomPoint.getY()); double maxX = screenDataArea.getMaxX(); double maxY = screenDataArea.getMaxY(); // for mouseReleased event, (horizontalZoom || verticalZoom) // will be true, so we can just test for either being false; // otherwise both are true if (!vZoom) { x = this.zoomPoint.getX(); y = screenDataArea.getMinY(); w = Math.min(this.zoomRectangle.getWidth(), maxX - this.zoomPoint.getX()); h = screenDataArea.getHeight(); } else if (!hZoom) { x = screenDataArea.getMinX(); y = this.zoomPoint.getY(); w = screenDataArea.getWidth(); h = Math.min(this.zoomRectangle.getHeight(), maxY - this.zoomPoint.getY()); } else { x = this.zoomPoint.getX(); y = this.zoomPoint.getY(); w = Math.min(this.zoomRectangle.getWidth(), maxX - this.zoomPoint.getX()); h = Math.min(this.zoomRectangle.getHeight(), maxY - this.zoomPoint.getY()); } Rectangle2D zoomArea = new Rectangle2D.Double(x, y, w, h); zoom(zoomArea); } this.zoomPoint = null; this.zoomRectangle = null; } else { // erase the zoom rectangle Graphics2D g2 = (Graphics2D) getGraphics(); if (this.useBuffer) { repaint(); } else { drawZoomRectangle(g2, true); } g2.dispose(); this.zoomPoint = null; this.zoomRectangle = null; } } else if (e.isPopupTrigger()) { if (this.popup != null) { displayPopupMenu(e.getX(), e.getY()); } } } /** * Receives notification of mouse clicks on the panel. These are * translated and passed on to any registered {@link ChartMouseListener}s. * * @param event Information about the mouse event. */ @Override public void mouseClicked(MouseEvent event) { Insets insets = getInsets(); int x = (int) ((event.getX() - insets.left) / this.scaleX); int y = (int) ((event.getY() - insets.top) / this.scaleY); this.anchor = new Point2D.Double(x, y); if (this.chart == null) { return; } this.chart.setNotify(true); // force a redraw // new entity code... Object[] listeners = this.chartMouseListeners.getListeners( ChartMouseListener.class); if (listeners.length == 0) { return; } ChartEntity entity = null; if (this.info != null) { EntityCollection entities = this.info.getEntityCollection(); if (entities != null) { entity = entities.getEntity(x, y); } } ChartMouseEvent chartEvent = new ChartMouseEvent(getChart(), event, entity); for (int i = listeners.length - 1; i >= 0; i -= 1) { ((ChartMouseListener) listeners[i]).chartMouseClicked(chartEvent); } } /** * Implementation of the MouseMotionListener's method. * * @param e the event. */ @Override public void mouseMoved(MouseEvent e) { Graphics2D g2 = (Graphics2D) getGraphics(); g2.dispose(); Object[] listeners = this.chartMouseListeners.getListeners( ChartMouseListener.class); if (listeners.length == 0) { return; } Insets insets = getInsets(); int x = (int) ((e.getX() - insets.left) / this.scaleX); int y = (int) ((e.getY() - insets.top) / this.scaleY); ChartEntity entity = null; if (this.info != null) { EntityCollection entities = this.info.getEntityCollection(); if (entities != null) { entity = entities.getEntity(x, y); } } // we can only generate events if the panel's chart is not null // (see bug report 1556951) if (this.chart != null) { ChartMouseEvent event = new ChartMouseEvent(getChart(), e, entity); for (int i = listeners.length - 1; i >= 0; i -= 1) { ((ChartMouseListener) listeners[i]).chartMouseMoved(event); } } } /** * Zooms in on an anchor point (specified in screen coordinate space). * * @param x the x value (in screen coordinates). * @param y the y value (in screen coordinates). */ public void zoomInBoth(double x, double y) { Plot plot = this.chart.getPlot(); if (plot == null) { return; } // here we tweak the notify flag on the plot so that only // one notification happens even though we update multiple // axes... boolean savedNotify = plot.isNotify(); plot.setNotify(false); zoomInDomain(x, y); zoomInRange(x, y); plot.setNotify(savedNotify); } /** * Decreases the length of the domain axis, centered about the given * coordinate on the screen. The length of the domain axis is reduced * by the value of {@link #getZoomInFactor()}. * * @param x the x coordinate (in screen coordinates). * @param y the y-coordinate (in screen coordinates). */ public void zoomInDomain(double x, double y) { Plot plot = this.chart.getPlot(); if (plot instanceof Zoomable) { // here we tweak the notify flag on the plot so that only // one notification happens even though we update multiple // axes... boolean savedNotify = plot.isNotify(); plot.setNotify(false); Zoomable z = (Zoomable) plot; z.zoomDomainAxes(this.zoomInFactor, this.info.getPlotInfo(), translateScreenToJava2D(new Point((int) x, (int) y)), this.zoomAroundAnchor); plot.setNotify(savedNotify); } } /** * Decreases the length of the range axis, centered about the given * coordinate on the screen. The length of the range axis is reduced by * the value of {@link #getZoomInFactor()}. * * @param x the x-coordinate (in screen coordinates). * @param y the y coordinate (in screen coordinates). */ public void zoomInRange(double x, double y) { Plot plot = this.chart.getPlot(); if (plot instanceof Zoomable) { // here we tweak the notify flag on the plot so that only // one notification happens even though we update multiple // axes... boolean savedNotify = plot.isNotify(); plot.setNotify(false); Zoomable z = (Zoomable) plot; z.zoomRangeAxes(this.zoomInFactor, this.info.getPlotInfo(), translateScreenToJava2D(new Point((int) x, (int) y)), this.zoomAroundAnchor); plot.setNotify(savedNotify); } } /** * Zooms out on an anchor point (specified in screen coordinate space). * * @param x the x value (in screen coordinates). * @param y the y value (in screen coordinates). */ public void zoomOutBoth(double x, double y) { Plot plot = this.chart.getPlot(); if (plot == null) { return; } // here we tweak the notify flag on the plot so that only // one notification happens even though we update multiple // axes... boolean savedNotify = plot.isNotify(); plot.setNotify(false); zoomOutDomain(x, y); zoomOutRange(x, y); plot.setNotify(savedNotify); } /** * Increases the length of the domain axis, centered about the given * coordinate on the screen. The length of the domain axis is increased * by the value of {@link #getZoomOutFactor()}. * * @param x the x coordinate (in screen coordinates). * @param y the y-coordinate (in screen coordinates). */ public void zoomOutDomain(double x, double y) { Plot plot = this.chart.getPlot(); if (plot instanceof Zoomable) { // here we tweak the notify flag on the plot so that only // one notification happens even though we update multiple // axes... boolean savedNotify = plot.isNotify(); plot.setNotify(false); Zoomable z = (Zoomable) plot; z.zoomDomainAxes(this.zoomOutFactor, this.info.getPlotInfo(), translateScreenToJava2D(new Point((int) x, (int) y)), this.zoomAroundAnchor); plot.setNotify(savedNotify); } } /** * Increases the length the range axis, centered about the given * coordinate on the screen. The length of the range axis is increased * by the value of {@link #getZoomOutFactor()}. * * @param x the x coordinate (in screen coordinates). * @param y the y-coordinate (in screen coordinates). */ public void zoomOutRange(double x, double y) { Plot plot = this.chart.getPlot(); if (plot instanceof Zoomable) { // here we tweak the notify flag on the plot so that only // one notification happens even though we update multiple // axes... boolean savedNotify = plot.isNotify(); plot.setNotify(false); Zoomable z = (Zoomable) plot; z.zoomRangeAxes(this.zoomOutFactor, this.info.getPlotInfo(), translateScreenToJava2D(new Point((int) x, (int) y)), this.zoomAroundAnchor); plot.setNotify(savedNotify); } } /** * Zooms in on a selected region. * * @param selection the selected region. */ public void zoom(Rectangle2D selection) { // get the origin of the zoom selection in the Java2D space used for // drawing the chart (that is, before any scaling to fit the panel) Point2D selectOrigin = translateScreenToJava2D(new Point( (int) Math.ceil(selection.getX()), (int) Math.ceil(selection.getY()))); PlotRenderingInfo plotInfo = this.info.getPlotInfo(); Rectangle2D scaledDataArea = getScreenDataArea( (int) selection.getCenterX(), (int) selection.getCenterY()); if ((selection.getHeight() > 0) && (selection.getWidth() > 0)) { double hLower = (selection.getMinX() - scaledDataArea.getMinX()) / scaledDataArea.getWidth(); double hUpper = (selection.getMaxX() - scaledDataArea.getMinX()) / scaledDataArea.getWidth(); double vLower = (scaledDataArea.getMaxY() - selection.getMaxY()) / scaledDataArea.getHeight(); double vUpper = (scaledDataArea.getMaxY() - selection.getMinY()) / scaledDataArea.getHeight(); Plot p = this.chart.getPlot(); if (p instanceof Zoomable) { // here we tweak the notify flag on the plot so that only // one notification happens even though we update multiple // axes... boolean savedNotify = p.isNotify(); p.setNotify(false); Zoomable z = (Zoomable) p; if (z.getOrientation() == PlotOrientation.HORIZONTAL) { z.zoomDomainAxes(vLower, vUpper, plotInfo, selectOrigin); z.zoomRangeAxes(hLower, hUpper, plotInfo, selectOrigin); } else { z.zoomDomainAxes(hLower, hUpper, plotInfo, selectOrigin); z.zoomRangeAxes(vLower, vUpper, plotInfo, selectOrigin); } p.setNotify(savedNotify); } } } /** * Restores the auto-range calculation on both axes. */ public void restoreAutoBounds() { Plot plot = this.chart.getPlot(); if (plot == null) { return; } // here we tweak the notify flag on the plot so that only // one notification happens even though we update multiple // axes... boolean savedNotify = plot.isNotify(); plot.setNotify(false); restoreAutoDomainBounds(); restoreAutoRangeBounds(); plot.setNotify(savedNotify); } /** * Restores the auto-range calculation on the domain axis. */ public void restoreAutoDomainBounds() { Plot plot = this.chart.getPlot(); if (plot instanceof Zoomable) { Zoomable z = (Zoomable) plot; // here we tweak the notify flag on the plot so that only // one notification happens even though we update multiple // axes... boolean savedNotify = plot.isNotify(); plot.setNotify(false); // we need to guard against this.zoomPoint being null Point2D zp = (this.zoomPoint != null ? this.zoomPoint : new Point()); z.zoomDomainAxes(0.0, this.info.getPlotInfo(), zp); plot.setNotify(savedNotify); } } /** * Restores the auto-range calculation on the range axis. */ public void restoreAutoRangeBounds() { Plot plot = this.chart.getPlot(); if (plot instanceof Zoomable) { Zoomable z = (Zoomable) plot; // here we tweak the notify flag on the plot so that only // one notification happens even though we update multiple // axes... boolean savedNotify = plot.isNotify(); plot.setNotify(false); // we need to guard against this.zoomPoint being null Point2D zp = (this.zoomPoint != null ? this.zoomPoint : new Point()); z.zoomRangeAxes(0.0, this.info.getPlotInfo(), zp); plot.setNotify(savedNotify); } } /** * Returns the data area for the chart (the area inside the axes) with the * current scaling applied (that is, the area as it appears on screen). * * @return The scaled data area. */ public Rectangle2D getScreenDataArea() { Rectangle2D dataArea = this.info.getPlotInfo().getDataArea(); Insets insets = getInsets(); double x = dataArea.getX() * this.scaleX + insets.left; double y = dataArea.getY() * this.scaleY + insets.top; double w = dataArea.getWidth() * this.scaleX; double h = dataArea.getHeight() * this.scaleY; return new Rectangle2D.Double(x, y, w, h); } /** * Returns the data area (the area inside the axes) for the plot or subplot, * with the current scaling applied. * * @param x the x-coordinate (for subplot selection). * @param y the y-coordinate (for subplot selection). * * @return The scaled data area. */ public Rectangle2D getScreenDataArea(int x, int y) { PlotRenderingInfo plotInfo = this.info.getPlotInfo(); Rectangle2D result; if (plotInfo.getSubplotCount() == 0) { result = getScreenDataArea(); } else { // get the origin of the zoom selection in the Java2D space used for // drawing the chart (that is, before any scaling to fit the panel) Point2D selectOrigin = translateScreenToJava2D(new Point(x, y)); int subplotIndex = plotInfo.getSubplotIndex(selectOrigin); if (subplotIndex == -1) { return null; } result = scale(plotInfo.getSubplotInfo(subplotIndex).getDataArea()); } return result; } /** * Returns the initial tooltip delay value used inside this chart panel. * * @return An integer representing the initial delay value, in milliseconds. * * @see javax.swing.ToolTipManager#getInitialDelay() */ public int getInitialDelay() { return this.ownToolTipInitialDelay; } /** * Returns the reshow tooltip delay value used inside this chart panel. * * @return An integer representing the reshow delay value, in milliseconds. * * @see javax.swing.ToolTipManager#getReshowDelay() */ public int getReshowDelay() { return this.ownToolTipReshowDelay; } /** * Returns the dismissal tooltip delay value used inside this chart panel. * * @return An integer representing the dismissal delay value, in * milliseconds. * * @see javax.swing.ToolTipManager#getDismissDelay() */ public int getDismissDelay() { return this.ownToolTipDismissDelay; } /** * Specifies the initial delay value for this chart panel. * * @param delay the number of milliseconds to delay (after the cursor has * paused) before displaying. * * @see javax.swing.ToolTipManager#setInitialDelay(int) */ public void setInitialDelay(int delay) { this.ownToolTipInitialDelay = delay; } /** * Specifies the amount of time before the user has to wait initialDelay * milliseconds before a tooltip will be shown. * * @param delay time in milliseconds * * @see javax.swing.ToolTipManager#setReshowDelay(int) */ public void setReshowDelay(int delay) { this.ownToolTipReshowDelay = delay; } /** * Specifies the dismissal delay value for this chart panel. * * @param delay the number of milliseconds to delay before taking away the * tooltip * * @see javax.swing.ToolTipManager#setDismissDelay(int) */ public void setDismissDelay(int delay) { this.ownToolTipDismissDelay = delay; } /** * Returns the zoom in factor. * * @return The zoom in factor. * * @see #setZoomInFactor(double) */ public double getZoomInFactor() { return this.zoomInFactor; } /** * Sets the zoom in factor. * * @param factor the factor. * * @see #getZoomInFactor() */ public void setZoomInFactor(double factor) { this.zoomInFactor = factor; } /** * Returns the zoom out factor. * * @return The zoom out factor. * * @see #setZoomOutFactor(double) */ public double getZoomOutFactor() { return this.zoomOutFactor; } /** * Sets the zoom out factor. * * @param factor the factor. * * @see #getZoomOutFactor() */ public void setZoomOutFactor(double factor) { this.zoomOutFactor = factor; } /** * Draws zoom rectangle (if present). * The drawing is performed in XOR mode, therefore * when this method is called twice in a row, * the second call will completely restore the state * of the canvas. * * @param g2 the graphics device. * @param xor use XOR for drawing? */ protected void drawZoomRectangle(Graphics2D g2, boolean xor) { if (this.zoomRectangle != null) { if (xor) { // Set XOR mode to draw the zoom rectangle g2.setXORMode(Color.GRAY); } if (this.fillZoomRectangle) { g2.setPaint(this.zoomFillPaint); g2.fill(this.zoomRectangle); } else { g2.setPaint(this.zoomOutlinePaint); g2.draw(this.zoomRectangle); } if (xor) { // Reset to the default 'overwrite' mode g2.setPaintMode(); } } } /** * Displays a dialog that allows the user to edit the properties for the * current chart. * * @since 1.0.3 */ public void doEditChartProperties() { ChartEditor editor = ChartEditorManager.getChartEditor(this.chart); int result = JOptionPane.showConfirmDialog(this, editor, localizationResources.getString("Chart_Properties"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); if (result == JOptionPane.OK_OPTION) { editor.updateChart(this.chart); } } /** * Copies the current chart to the system clipboard. * * @since 1.0.13 */ public void doCopy() { Clipboard systemClipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); Insets insets = getInsets(); int w = getWidth() - insets.left - insets.right; int h = getHeight() - insets.top - insets.bottom; ChartTransferable selection = new ChartTransferable(this.chart, w, h, getMinimumDrawWidth(), getMinimumDrawHeight(), getMaximumDrawWidth(), getMaximumDrawHeight(), true); systemClipboard.setContents(selection, null); } /** * Opens a file chooser and gives the user an opportunity to save the chart * in PNG format. * * @throws IOException if there is an I/O error. */ public void doSaveAs() throws IOException { doSaveAs(-1, -1); } /** * Opens a file chooser and gives the user an opportunity to save the chart * in PNG format. * * @param w the width for the saved image (if less than or equal to zero, * the panel width will be used); * @param h the height for the PNG image (if less than or equal to zero, * the panel height will be used); * * @throws IOException if there is an I/O error. */ public void doSaveAs(int w, int h) throws IOException { JFileChooser fileChooser = new JFileChooser(); fileChooser.setCurrentDirectory(this.defaultDirectoryForSaveAs); FileNameExtensionFilter filter = new FileNameExtensionFilter( localizationResources.getString("PNG_Image_Files"), "png"); fileChooser.addChoosableFileFilter(filter); fileChooser.setFileFilter(filter); int option = fileChooser.showSaveDialog(this); if (option == JFileChooser.APPROVE_OPTION) { String filename = fileChooser.getSelectedFile().getPath(); if (isEnforceFileExtensions()) { if (!filename.endsWith(".png")) { filename = filename + ".png"; } } if (w <= 0) { w = getWidth(); } if (h <= 0) { h = getHeight(); } ChartUtils.saveChartAsPNG(new File(filename), this.chart, w, h); } } /** * Saves the chart in SVG format (a filechooser will be displayed so that * the user can specify the filename). Note that this method only works * if the JFreeSVG library is on the classpath...if this library is not * present, the method will fail. */ protected void saveAsSVG(File f) throws IOException { File file = f; if (file == null) { JFileChooser fileChooser = new JFileChooser(); fileChooser.setCurrentDirectory(this.defaultDirectoryForSaveAs); FileNameExtensionFilter filter = new FileNameExtensionFilter( localizationResources.getString("SVG_Files"), "svg"); fileChooser.addChoosableFileFilter(filter); fileChooser.setFileFilter(filter); int option = fileChooser.showSaveDialog(this); if (option == JFileChooser.APPROVE_OPTION) { String filename = fileChooser.getSelectedFile().getPath(); if (isEnforceFileExtensions()) { if (!filename.endsWith(".svg")) { filename = filename + ".svg"; } } file = new File(filename); if (file.exists()) { String fileExists = localizationResources.getString( "FILE_EXISTS_CONFIRM_OVERWRITE"); int response = JOptionPane.showConfirmDialog(this, fileExists, localizationResources.getString("Save_as_SVG"), JOptionPane.OK_CANCEL_OPTION); if (response == JOptionPane.CANCEL_OPTION) { file = null; } } } } if (file != null) { // use reflection to get the SVG string String svg = generateSVG(getWidth(), getHeight()); BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(file)); writer.write("<!DOCTYPE svg PUBLIC \"- writer.write(svg + "\n"); writer.flush(); } finally { try { if (writer != null) { writer.close(); } } catch (IOException ex) { throw new RuntimeException(ex); } } } } /** * Generates a string containing a rendering of the chart in SVG format. * This feature is only supported if the JFreeSVG library is included on * the classpath. * * @return A string containing an SVG element for the current chart, or * {@code null} if there is a problem with the method invocation * by reflection. */ protected String generateSVG(int width, int height) { Graphics2D g2 = createSVGGraphics2D(width, height); if (g2 == null) { throw new IllegalStateException("JFreeSVG library is not present."); } // we suppress shadow generation, because SVG is a vector format and // the shadow effect is applied via bitmap effects... g2.setRenderingHint(JFreeChart.KEY_SUPPRESS_SHADOW_GENERATION, true); String svg = null; Rectangle2D drawArea = new Rectangle2D.Double(0, 0, width, height); this.chart.draw(g2, drawArea); try { Method m = g2.getClass().getMethod("getSVGElement"); svg = (String) m.invoke(g2); } catch (NoSuchMethodException e) { // null will be returned } catch (SecurityException e) { // null will be returned } catch (IllegalAccessException e) { // null will be returned } catch (IllegalArgumentException e) { // null will be returned } catch (InvocationTargetException e) { // null will be returned } return svg; } /** * Creates an {@code SVGGraphics2D} instance (from JFreeSVG) using reflection. * If JFreeSVG is not on the classpath, this method returns {@code null}. * * @param w the width. * @param h the height. * * @return An {@code SVGGraphics2D} instance or {@code null}. */ protected Graphics2D createSVGGraphics2D(int w, int h) { try { Class svgGraphics2d = Class.forName("org.jfree.graphics2d.svg.SVGGraphics2D"); Constructor ctor = svgGraphics2d.getConstructor(int.class, int.class); return (Graphics2D) ctor.newInstance(w, h); } catch (ClassNotFoundException ex) { return null; } catch (NoSuchMethodException ex) { return null; } catch (SecurityException ex) { return null; } catch (InstantiationException ex) { return null; } catch (IllegalAccessException ex) { return null; } catch (IllegalArgumentException ex) { return null; } catch (InvocationTargetException ex) { return null; } } /** * Saves the chart in PDF format (a filechooser will be displayed so that * the user can specify the filename). Note that this method only works * if the OrsonPDF library is on the classpath...if this library is not * present, the method will fail. */ protected void saveAsPDF(File f) { File file = f; if (file == null) { JFileChooser fileChooser = new JFileChooser(); fileChooser.setCurrentDirectory(this.defaultDirectoryForSaveAs); FileNameExtensionFilter filter = new FileNameExtensionFilter( localizationResources.getString("PDF_Files"), "pdf"); fileChooser.addChoosableFileFilter(filter); fileChooser.setFileFilter(filter); int option = fileChooser.showSaveDialog(this); if (option == JFileChooser.APPROVE_OPTION) { String filename = fileChooser.getSelectedFile().getPath(); if (isEnforceFileExtensions()) { if (!filename.endsWith(".pdf")) { filename = filename + ".pdf"; } } file = new File(filename); if (file.exists()) { String fileExists = localizationResources.getString( "FILE_EXISTS_CONFIRM_OVERWRITE"); int response = JOptionPane.showConfirmDialog(this, fileExists, localizationResources.getString("Save_as_PDF"), JOptionPane.OK_CANCEL_OPTION); if (response == JOptionPane.CANCEL_OPTION) { file = null; } } } } if (file != null) { writeAsPDF(file, getWidth(), getHeight()); } } /** * Writes the current chart to the specified file in PDF format. This * will only work when the OrsonPDF library is found on the classpath. * Reflection is used to ensure there is no compile-time dependency on * OrsonPDF (which is non-free software). * * @param file the output file ({@code null} not permitted). * @param w the chart width. * @param h the chart height. */ private void writeAsPDF(File file, int w, int h) { if (!ChartUtils.isOrsonPDFAvailable()) { throw new IllegalStateException( "OrsonPDF is not present on the classpath."); } Args.nullNotPermitted(file, "file"); try { Class pdfDocClass = Class.forName("com.orsonpdf.PDFDocument"); Object pdfDoc = pdfDocClass.newInstance(); Method m = pdfDocClass.getMethod("createPage", Rectangle2D.class); Rectangle2D rect = new Rectangle(w, h); Object page = m.invoke(pdfDoc, rect); Method m2 = page.getClass().getMethod("getGraphics2D"); Graphics2D g2 = (Graphics2D) m2.invoke(page); // we suppress shadow generation, because PDF is a vector format and // the shadow effect is applied via bitmap effects... g2.setRenderingHint(JFreeChart.KEY_SUPPRESS_SHADOW_GENERATION, true); Rectangle2D drawArea = new Rectangle2D.Double(0, 0, w, h); this.chart.draw(g2, drawArea); Method m3 = pdfDocClass.getMethod("writeToFile", File.class); m3.invoke(pdfDoc, file); } catch (ClassNotFoundException ex) { throw new RuntimeException(ex); } catch (InstantiationException ex) { throw new RuntimeException(ex); } catch (IllegalAccessException ex) { throw new RuntimeException(ex); } catch (NoSuchMethodException ex) { throw new RuntimeException(ex); } catch (SecurityException ex) { throw new RuntimeException(ex); } catch (IllegalArgumentException ex) { throw new RuntimeException(ex); } catch (InvocationTargetException ex) { throw new RuntimeException(ex); } } /** * Creates a print job for the chart. */ public void createChartPrintJob() { PrinterJob job = PrinterJob.getPrinterJob(); PageFormat pf = job.defaultPage(); PageFormat pf2 = job.pageDialog(pf); if (pf2 != pf) { job.setPrintable(this, pf2); if (job.printDialog()) { try { job.print(); } catch (PrinterException e) { JOptionPane.showMessageDialog(this, e); } } } } /** * Prints the chart on a single page. * * @param g the graphics context. * @param pf the page format to use. * @param pageIndex the index of the page. If not {@code 0}, nothing * gets printed. * * @return The result of printing. */ @Override public int print(Graphics g, PageFormat pf, int pageIndex) { if (pageIndex != 0) { return NO_SUCH_PAGE; } Graphics2D g2 = (Graphics2D) g; double x = pf.getImageableX(); double y = pf.getImageableY(); double w = pf.getImageableWidth(); double h = pf.getImageableHeight(); this.chart.draw(g2, new Rectangle2D.Double(x, y, w, h), this.anchor, null); return PAGE_EXISTS; } /** * Adds a listener to the list of objects listening for chart mouse events. * * @param listener the listener ({@code null} not permitted). */ public void addChartMouseListener(ChartMouseListener listener) { Args.nullNotPermitted(listener, "listener"); this.chartMouseListeners.add(ChartMouseListener.class, listener); } /** * Removes a listener from the list of objects listening for chart mouse * events. * * @param listener the listener. */ public void removeChartMouseListener(ChartMouseListener listener) { this.chartMouseListeners.remove(ChartMouseListener.class, listener); } /** * Returns an array of the listeners of the given type registered with the * panel. * * @param listenerType the listener type. * * @return An array of listeners. */ @Override public EventListener[] getListeners(Class listenerType) { if (listenerType == ChartMouseListener.class) { // fetch listeners from local storage return this.chartMouseListeners.getListeners(listenerType); } else { return super.getListeners(listenerType); } } /** * Creates a popup menu for the panel. * * @param properties include a menu item for the chart property editor. * @param save include a menu item for saving the chart. * @param print include a menu item for printing the chart. * @param zoom include menu items for zooming. * * @return The popup menu. * * @deprecated Use #createPopupMenu(boolean, boolean, boolean, boolean, boolean) * as this includes an explicit flag for the {@code copy} menu item. */ protected JPopupMenu createPopupMenu(boolean properties, boolean save, boolean print, boolean zoom) { return createPopupMenu(properties, false, save, print, zoom); } /** * Creates a popup menu for the panel. This method includes code that * auto-detects JFreeSVG and OrsonPDF (via reflection) and, if they are * present (and the {@code save} argument is {@code true}, adds a menu item * for each. * * @param properties include a menu item for the chart property editor. * @param copy include a menu item for copying to the clipboard. * @param save include one or more menu items for saving the chart to * supported image formats. * @param print include a menu item for printing the chart. * @param zoom include menu items for zooming. * * @return The popup menu. * * @since 1.0.13 */ protected JPopupMenu createPopupMenu(boolean properties, boolean copy, boolean save, boolean print, boolean zoom) { JPopupMenu result = new JPopupMenu(localizationResources.getString("Chart") + ":"); boolean separator = false; if (properties) { JMenuItem propertiesItem = new JMenuItem( localizationResources.getString("Properties...")); propertiesItem.setActionCommand(PROPERTIES_COMMAND); propertiesItem.addActionListener(this); result.add(propertiesItem); separator = true; } if (copy) { if (separator) { result.addSeparator(); } JMenuItem copyItem = new JMenuItem( localizationResources.getString("Copy")); copyItem.setActionCommand(COPY_COMMAND); copyItem.addActionListener(this); result.add(copyItem); separator = !save; } if (save) { if (separator) { result.addSeparator(); } JMenu saveSubMenu = new JMenu(localizationResources.getString("Save_as")); // PNG - current res { JMenuItem pngItem = new JMenuItem(localizationResources.getString( "PNG...")); pngItem.setActionCommand(SAVE_AS_PNG_COMMAND); pngItem.addActionListener(this); saveSubMenu.add(pngItem); } // PNG - screen res { final Dimension ss = Toolkit.getDefaultToolkit().getScreenSize(); final String pngName = "PNG ("+ss.width+"x"+ss.height+") ..."; JMenuItem pngItem = new JMenuItem(pngName); pngItem.setActionCommand(SAVE_AS_PNG_SIZE_COMMAND); pngItem.addActionListener(this); saveSubMenu.add(pngItem); } if (ChartUtils.isJFreeSVGAvailable()) { JMenuItem svgItem = new JMenuItem(localizationResources.getString( "SVG...")); svgItem.setActionCommand(SAVE_AS_SVG_COMMAND); svgItem.addActionListener(this); saveSubMenu.add(svgItem); } if (ChartUtils.isOrsonPDFAvailable()) { JMenuItem pdfItem = new JMenuItem( localizationResources.getString("PDF...")); pdfItem.setActionCommand(SAVE_AS_PDF_COMMAND); pdfItem.addActionListener(this); saveSubMenu.add(pdfItem); } result.add(saveSubMenu); separator = true; } if (print) { if (separator) { result.addSeparator(); } JMenuItem printItem = new JMenuItem( localizationResources.getString("Print...")); printItem.setActionCommand(PRINT_COMMAND); printItem.addActionListener(this); result.add(printItem); separator = true; } if (zoom) { if (separator) { result.addSeparator(); } JMenu zoomInMenu = new JMenu( localizationResources.getString("Zoom_In")); this.zoomInBothMenuItem = new JMenuItem( localizationResources.getString("All_Axes")); this.zoomInBothMenuItem.setActionCommand(ZOOM_IN_BOTH_COMMAND); this.zoomInBothMenuItem.addActionListener(this); zoomInMenu.add(this.zoomInBothMenuItem); zoomInMenu.addSeparator(); this.zoomInDomainMenuItem = new JMenuItem( localizationResources.getString("Domain_Axis")); this.zoomInDomainMenuItem.setActionCommand(ZOOM_IN_DOMAIN_COMMAND); this.zoomInDomainMenuItem.addActionListener(this); zoomInMenu.add(this.zoomInDomainMenuItem); this.zoomInRangeMenuItem = new JMenuItem( localizationResources.getString("Range_Axis")); this.zoomInRangeMenuItem.setActionCommand(ZOOM_IN_RANGE_COMMAND); this.zoomInRangeMenuItem.addActionListener(this); zoomInMenu.add(this.zoomInRangeMenuItem); result.add(zoomInMenu); JMenu zoomOutMenu = new JMenu( localizationResources.getString("Zoom_Out")); this.zoomOutBothMenuItem = new JMenuItem( localizationResources.getString("All_Axes")); this.zoomOutBothMenuItem.setActionCommand(ZOOM_OUT_BOTH_COMMAND); this.zoomOutBothMenuItem.addActionListener(this); zoomOutMenu.add(this.zoomOutBothMenuItem); zoomOutMenu.addSeparator(); this.zoomOutDomainMenuItem = new JMenuItem( localizationResources.getString("Domain_Axis")); this.zoomOutDomainMenuItem.setActionCommand( ZOOM_OUT_DOMAIN_COMMAND); this.zoomOutDomainMenuItem.addActionListener(this); zoomOutMenu.add(this.zoomOutDomainMenuItem); this.zoomOutRangeMenuItem = new JMenuItem( localizationResources.getString("Range_Axis")); this.zoomOutRangeMenuItem.setActionCommand(ZOOM_OUT_RANGE_COMMAND); this.zoomOutRangeMenuItem.addActionListener(this); zoomOutMenu.add(this.zoomOutRangeMenuItem); result.add(zoomOutMenu); JMenu autoRangeMenu = new JMenu( localizationResources.getString("Auto_Range")); this.zoomResetBothMenuItem = new JMenuItem( localizationResources.getString("All_Axes")); this.zoomResetBothMenuItem.setActionCommand( ZOOM_RESET_BOTH_COMMAND); this.zoomResetBothMenuItem.addActionListener(this); autoRangeMenu.add(this.zoomResetBothMenuItem); autoRangeMenu.addSeparator(); this.zoomResetDomainMenuItem = new JMenuItem( localizationResources.getString("Domain_Axis")); this.zoomResetDomainMenuItem.setActionCommand( ZOOM_RESET_DOMAIN_COMMAND); this.zoomResetDomainMenuItem.addActionListener(this); autoRangeMenu.add(this.zoomResetDomainMenuItem); this.zoomResetRangeMenuItem = new JMenuItem( localizationResources.getString("Range_Axis")); this.zoomResetRangeMenuItem.setActionCommand( ZOOM_RESET_RANGE_COMMAND); this.zoomResetRangeMenuItem.addActionListener(this); autoRangeMenu.add(this.zoomResetRangeMenuItem); result.addSeparator(); result.add(autoRangeMenu); } return result; } /** * The idea is to modify the zooming options depending on the type of chart * being displayed by the panel. * * @param x horizontal position of the popup. * @param y vertical position of the popup. */ protected void displayPopupMenu(int x, int y) { if (this.popup == null) { return; } // go through each zoom menu item and decide whether or not to // enable it... boolean isDomainZoomable = false; boolean isRangeZoomable = false; Plot plot = (this.chart != null ? this.chart.getPlot() : null); if (plot instanceof Zoomable) { Zoomable z = (Zoomable) plot; isDomainZoomable = z.isDomainZoomable(); isRangeZoomable = z.isRangeZoomable(); } if (this.zoomInDomainMenuItem != null) { this.zoomInDomainMenuItem.setEnabled(isDomainZoomable); } if (this.zoomOutDomainMenuItem != null) { this.zoomOutDomainMenuItem.setEnabled(isDomainZoomable); } if (this.zoomResetDomainMenuItem != null) { this.zoomResetDomainMenuItem.setEnabled(isDomainZoomable); } if (this.zoomInRangeMenuItem != null) { this.zoomInRangeMenuItem.setEnabled(isRangeZoomable); } if (this.zoomOutRangeMenuItem != null) { this.zoomOutRangeMenuItem.setEnabled(isRangeZoomable); } if (this.zoomResetRangeMenuItem != null) { this.zoomResetRangeMenuItem.setEnabled(isRangeZoomable); } if (this.zoomInBothMenuItem != null) { this.zoomInBothMenuItem.setEnabled(isDomainZoomable && isRangeZoomable); } if (this.zoomOutBothMenuItem != null) { this.zoomOutBothMenuItem.setEnabled(isDomainZoomable && isRangeZoomable); } if (this.zoomResetBothMenuItem != null) { this.zoomResetBothMenuItem.setEnabled(isDomainZoomable && isRangeZoomable); } this.popup.show(this, x, y); } /** * Updates the UI for a LookAndFeel change. */ @Override public void updateUI() { // here we need to update the UI for the popup menu, if the panel // has one... if (this.popup != null) { SwingUtilities.updateComponentTreeUI(this.popup); } super.updateUI(); } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ protected void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtils.writePaint(this.zoomFillPaint, stream); SerialUtils.writePaint(this.zoomOutlinePaint, 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. */ protected void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.zoomFillPaint = SerialUtils.readPaint(stream); this.zoomOutlinePaint = SerialUtils.readPaint(stream); // we create a new but empty chartMouseListeners list this.chartMouseListeners = new EventListenerList(); // register as a listener with sub-components... if (this.chart != null) { this.chart.addChangeListener(this); } } }
package org.mvel.block; import org.mvel.ExecutableStatement; import static org.mvel.MVEL.compileExpression; import org.mvel.Token; import org.mvel.integration.VariableResolverFactory; /** * @author Christopher Brock */ public class AssertToken extends Token { public ExecutableStatement assertion; public AssertToken(char[] expr, int fields) { super(expr, fields); assertion = (ExecutableStatement) compileExpression(expr); } public Object getReducedValueAccelerated(Object ctx, Object thisValue, VariableResolverFactory factory) { Boolean bool = (Boolean) assertion.getValue(ctx, thisValue, factory); if (!bool) throw new AssertionError("assertion failed in expression: " + new String(this.name)); return bool; } public Object getReducedValue(Object ctx, Object thisValue, VariableResolverFactory factory) { return getReducedValueAccelerated(ctx, thisValue, factory); } }
package org.osgl.mvc.result; import org.osgl.exception.FastRuntimeException; import org.osgl.http.H; import org.osgl.http.Http; import org.osgl.mvc.MvcConfig; import org.osgl.util.KVStore; import org.osgl.util.S; public class Result extends FastRuntimeException { protected static class Payload extends KVStore { public String message; public Integer errorCode; public Throwable cause; public H.Format format; public H.Status status; public Object attachment; public String etag; public Payload message(String message) { this.message = message; return this; } public Payload message(String message, Object... args) { this.message = S.fmt(message, args); return this; } public Payload errorCode(int errorCode) { this.errorCode = errorCode; return this; } public Payload cause(Throwable cause) { this.cause = cause; return this; } public Payload format(H.Format format) { this.format = format; return this; } public Payload status(H.Status status) { this.status = status; return this; } public Payload attach(Object attachment) { this.attachment = attachment; return this; } public Payload etag(String etag) { this.etag = etag; return this; } public String etag() { return this.etag; } } protected static final ThreadLocal<Payload> payload = new ThreadLocal<Payload>() { @Override protected Payload initialValue() { return new Payload(); } }; protected Payload payload() { return payload.get(); } private Http.Status status; protected Result() {status = Http.Status.OK;} protected Result(Http.Status status) { this.status = status; } protected Result(Http.Status status, String message) { super(message); this.status = status; } protected Result(Http.Status status, String message, Object... args) { super(message, args); this.status = status; } protected Result(Http.Status status, Throwable cause) { super(cause); this.status = status; } protected Result(Http.Status status, Throwable cause, String message, Object... args) { super(cause, message, args); this.status = status; } public Http.Status status() { return status; } public int statusCode() { return status().code(); } public Result status(H.Status status) { this.status = status; return this; } protected final void applyStatus(H.Response response) { response.status(statusCode()); } protected final void applyBeforeCommitHandler(H.Request req, H.Response resp) { MvcConfig.applyBeforeCommitResultHandler(this, req, resp); } protected final void applyAfterCommitHandler(H.Request req, H.Response resp) { MvcConfig.applyAfterCommitResultHandler(this, req, resp); } protected void applyMessage(H.Request request, H.Response response) { String msg = getMessage(); if (S.notBlank(msg)) { response.writeContent(msg); } else { response.commit(); } } public void apply(H.Request req, H.Response resp) { try { applyStatus(resp); applyBeforeCommitHandler(req, resp); applyMessage(req, resp); applyAfterCommitHandler(req, resp); } finally { clearThreadLocals(); } } public static void clearThreadLocals() { payload.remove(); } }
package org.xelasov.ejdbc; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.SQLException; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.List; import javax.sql.DataSource; import org.xelasov.ejdbc.base.Assert; import org.xelasov.ejdbc.base.CallableStatementWrapper; import org.xelasov.ejdbc.base.SqlUtils; import org.xelasov.ejdbc.types.DBBool; import org.xelasov.ejdbc.types.DBByte; import org.xelasov.ejdbc.types.DBDate; import org.xelasov.ejdbc.types.DBDateTime; import org.xelasov.ejdbc.types.DBDouble; import org.xelasov.ejdbc.types.DBFloat; import org.xelasov.ejdbc.types.DBInteger; import org.xelasov.ejdbc.types.DBIntegerArray; import org.xelasov.ejdbc.types.DBLong; import org.xelasov.ejdbc.types.DBLongArray; import org.xelasov.ejdbc.types.DBShort; import org.xelasov.ejdbc.types.DBShortArray; import org.xelasov.ejdbc.types.DBString; import org.xelasov.ejdbc.types.DBStringArray; /** * Function class is a simple way to execute a database function-style stored procedure (one that returns a single return value). * Output parameters are also supported. * <p> * For example, to call a sproc that takes user id and password, creates a 'user' record and returns its PK as a long: * <p> * Long pk = new Function<Long>(new DBLong(), "account.user_add").inString(userId).inString(passwd).execute(dataSource); * <p> * To call a sproc that takes user PK and returns a single-row ResultSet with all fields in the user record: * <p> * User user = new Function<User>(new DBBeanResultSet<User>(new UserRowMapper()), "account.user_get").inLong(userPK).execute(dataSource); */ public class Function<RetValT> { private final String name; private final Parameter<RetValT> retVal; private final ParameterList params; public Function(final Parameter<RetValT> retVal, final String name, final Parameter<?>... params) { this(retVal, name, new ParameterList(params)); } public Function(Parameter<RetValT> retVal, final String name, ParameterList params) { Assert.argument(name != null && !name.isEmpty()); Assert.argument(retVal == null || retVal.isOutput()); Assert.argumentNotNull(params); this.name = name; this.retVal = retVal; this.params = params; } public Function<RetValT> inString(String v) { params.addParameter(new DBString(v)); return this; } public Function<RetValT> inBool(Boolean v) { params.addParameter(new DBBool(v)); return this; } public Function<RetValT> inByte(Byte v) { params.addParameter(new DBByte(v)); return this; } public Function<RetValT> inShort(Short v) { params.addParameter(new DBShort(v)); return this; } public Function<RetValT> inInteger(Integer v) { params.addParameter(new DBInteger(v)); return this; } public Function<RetValT> inLong(Long v) { params.addParameter(new DBLong(v)); return this; } public Function<RetValT> inFloat(Float v) { params.addParameter(new DBFloat(v)); return this; } public Function<RetValT> inDouble(Double v) { params.addParameter(new DBDouble(v)); return this; } public Function<RetValT> inDate(LocalDate v) { params.addParameter(new DBDate(v)); return this; } public Function<RetValT> inDateTime(LocalDateTime v) { params.addParameter(new DBDateTime(v)); return this; } public Function<RetValT> inShortArray(Short[] v) { params.addParameter(new DBShortArray(v)); return this; } public Function<RetValT> inShortArray(List<Short> v) { params.addParameter(new DBShortArray(v)); return this; } public Function<RetValT> inLongArray(Long[] v) { params.addParameter(new DBLongArray(v)); return this; } public Function<RetValT> inLongArray(List<Long> v) { params.addParameter(new DBLongArray(v)); return this; } public Function<RetValT> inIntegerArray(Integer[] v) { params.addParameter(new DBIntegerArray(v)); return this; } public Function<RetValT> inIntegerArray(List<Integer> v) { params.addParameter(new DBIntegerArray(v)); return this; } public Function<RetValT> inStringArray(String[] v) { params.addParameter(new DBStringArray(v)); return this; } public Function<RetValT> inStringArray(List<String> v) { params.addParameter(new DBStringArray(v)); return this; } public RetValT execute(Connection conn) throws SQLException { Assert.argumentNotNull(conn); CallableStatement stmt = null; try { final String sql = SqlUtils.buildFunctionCallString(name, retVal != null, params.getParameterCount()); stmt = conn.prepareCall(sql); final CallableStatementWrapper csw = new CallableStatementWrapper(stmt); applyParams(csw); stmt.execute(); extractParams(csw); return retVal.getValueOrNull(); } finally { SqlUtils.closeSafely(stmt); } } public RetValT execute(DataSource ds) throws SQLException { Assert.argumentNotNull(ds); final Connection conn = SqlUtils.getConnection(ds, false); try { final RetValT rv = execute(conn); SqlUtils.commitSafely(conn); return rv; } catch (SQLException e) { SqlUtils.rollbackSafely(conn); throw e; } finally { SqlUtils.closeSafely(conn); } } private void extractParams(CallableStatementWrapper stmt) throws SQLException { int pos = 1; if (retVal != null) retVal.extract(stmt, pos++); params.extractParams(stmt, pos); } private void applyParams(CallableStatementWrapper stmt) throws SQLException { int pos = 1; if (retVal != null) retVal.apply(stmt, pos++); params.applyParams(stmt, pos); } }
package org.yidu.novel.utils; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.security.MessageDigest; import java.util.Collection; import java.util.Map; import java.util.Random; import net.sourceforge.pinyin4j.PinyinHelper; import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType; import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat; import net.sourceforge.pinyin4j.format.HanyuPinyinToneType; import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType; import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.apache.struts2.ServletActionContext; import org.yidu.novel.constant.YiDuConfig; import org.yidu.novel.constant.YiDuConstants; import org.yidu.novel.entity.TChapter; public class Utils { /** * logger */ protected static Log logger = LogFactory.getLog(Utils.class); /** * MD5 * * @param input * * @return MD5 */ public static String convert2MD5(final String input) { char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; try { byte[] btInput = input.getBytes(); // MD5 MessageDigest MessageDigest mdInst = MessageDigest.getInstance("MD5"); mdInst.update(btInput); byte[] md = mdInst.digest(); int j = md.length; char[] str = new char[j * 2]; int k = 0; for (int i = 0; i < j; i++) { byte byte0 = md[i]; str[k++] = hexDigits[byte0 >>> 4 & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; } return new String(str).toLowerCase(); } catch (Exception e) { e.printStackTrace(); return null; } } /** * * * @param chapter * * @param escape * HTML * @return */ public static String getContext(TChapter chapter, boolean escape) { return getContext(chapter, escape, false); } /** * * * @param chapter * * @param escape * HTML * @param pseudo * * @return */ public static String getContext(TChapter chapter, boolean escape, boolean pseudo) { String result = null; StringBuilder sb = new StringBuilder(); String path = getTextFilePathByChapterno(chapter.getArticleno(), chapter.getChapterno()); File file = new File(path); try { if (file.isFile() && file.exists()) { InputStreamReader read = new InputStreamReader(new FileInputStream(file), YiDuConstants.yiduConf.getString(YiDuConfig.TXT_ENCODING)); BufferedReader bufferedReader = new BufferedReader(read); String lineTxt = null; while ((lineTxt = bufferedReader.readLine()) != null) { sb.append(lineTxt); if (escape) { sb.append("<br/>"); } else { sb.append("\n"); } } bufferedReader.close(); read.close(); if (escape) { result = sb.toString().replaceAll("\\s", "&nbsp;"); } else { result = sb.toString(); } if (pseudo) { if (YiDuConstants.pseudoConf.getBoolean("replace_keywords")) { result = PseudoUtils.replaceKeywords(result); } if (YiDuConstants.pseudoConf.getBoolean("is_top_append")) { result = PseudoUtils.topAppend(result); } if (YiDuConstants.pseudoConf.getBoolean("is_bottom_append")) { result = PseudoUtils.bottomAppend(chapter, result); } if (YiDuConstants.pseudoConf.getBoolean("fetch_keywords_from_chapter")) { result = PseudoUtils.fetchKeywords(result); } } } else { logger.info("can not find chapter. articleno:" + chapter.getArticleno() + " chapterno:" + chapter.getChapterno()); } } catch (Exception e) { logger.error(e.getMessage(), e); } return result; } /** * TXT * * @param articleno * * @param chapterno * * @return TXT */ public static String getTextFilePathByChapterno(int articleno, int chapterno) { String path = YiDuConstants.yiduConf.getString(YiDuConfig.FILE_PATH); path = path + "/" + articleno / YiDuConstants.SUB_DIR_ARTICLES + "/" + articleno + "/" + chapterno + ".txt"; return path; } /** * txt * * @param articleno * * @return txt */ public static String getTextDirectoryPathByArticleno(int articleno) { String path = YiDuConstants.yiduConf.getString(YiDuConfig.FILE_PATH); // path = ServletActionContext.getServletContext().getRealPath("/") + // "/" + path + "/" + articleno / YiDuConstants.SUB_DIR_ARTICLES + "/" // + articleno + "/" + chapterno + ".txt"; path = path + "/" + articleno / YiDuConstants.SUB_DIR_ARTICLES + "/" + articleno + "/"; return path; } /** * * * @param articleno * * @return */ public static String getImgDirectoryPathByArticleno(int articleno) { String path = YiDuConstants.yiduConf.getString(YiDuConfig.RELATIVE_IAMGE_PATH); path = ServletActionContext.getServletContext().getRealPath("/") + "/" + path + "/" + articleno / YiDuConstants.SUB_DIR_ARTICLES + "/" + articleno + "/"; return path; } /** * * * @param articleno * * @param chapterno * * @param content * * @throws IOException * IO */ public static void saveContext(int articleno, int chapterno, String content) throws IOException { String path = getTextFilePathByChapterno(articleno, chapterno); File file = new File(path); File parentPath = file.getParentFile(); if (!parentPath.exists()) { parentPath.mkdirs(); } try { OutputStreamWriter outputStream = new OutputStreamWriter(new FileOutputStream(file), YiDuConstants.yiduConf.getString(YiDuConfig.TXT_ENCODING)); outputStream.write(content); outputStream.flush(); outputStream.close(); } catch (IOException e) { logger.error(e.getMessage(), e); } } /** * URI * * @param uri * URI * @return */ public static String getContentFromUri(String uri) { CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpGet httpget = new HttpGet(uri); ResponseHandler<String> responseHandler = new ResponseHandler<String>() { public String handleResponse(final HttpResponse response) throws IOException { int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { HttpEntity entity = response.getEntity(); return entity != null ? EntityUtils.toString(entity) : null; } else { throw new ClientProtocolException("Unexpected response status: " + status); } } }; return httpclient.execute(httpget, responseHandler); } catch (Exception e) { logger.error(e); } finally { try { httpclient.close(); } catch (IOException e) { logger.error(e); } } return null; } /** * * * @param sPath * * @return truefalse */ public static boolean deleteDirectory(String sPath) { // sPath if (!sPath.endsWith(File.separator)) { sPath = sPath + File.separator; } File dirFile = new File(sPath); // dir if (!dirFile.exists() || !dirFile.isDirectory()) { return false; } boolean flag = true; File[] files = dirFile.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isFile()) { flag = deleteFile(files[i].getAbsolutePath()); if (!flag) { break; } } else { flag = deleteDirectory(files[i].getAbsolutePath()); if (!flag) { break; } } } if (!flag) { return false; } return dirFile.delete(); } /** * * * @param sPath * * @return truefalse */ public static boolean deleteFile(String sPath) { boolean flag = false; File file = new File(sPath); if (file.isFile() && file.exists()) { file.delete(); flag = true; } return flag; } /** * * * @param articleno * * @param file * * @param fileName * * @throws Exception * */ public static void saveArticlespic(int articleno, File file, String fileName) throws Exception { String path = YiDuConstants.yiduConf.getString(YiDuConfig.RELATIVE_IAMGE_PATH); path = ServletActionContext.getServletContext().getRealPath("/") + "/" + path + "/" + articleno / YiDuConstants.SUB_DIR_ARTICLES + "/" + articleno + "/" + articleno + "s." + StringUtils.substringAfterLast(fileName, "."); File savefile = new File(path); if (!savefile.getParentFile().exists()) { savefile.getParentFile().mkdirs(); } FileUtils.copyFile(file, savefile); } /** * * * @param articleno * * @return */ public static String getArticlePicPath(int articleno) { String path = YiDuConstants.yiduConf.getString(YiDuConfig.RELATIVE_IAMGE_PATH); path = ServletActionContext.getServletContext().getRealPath("/") + "/" + path + "/" + articleno / YiDuConstants.SUB_DIR_ARTICLES + "/" + articleno + "/"; return path; } /** * * * @param src * * @return */ public static String getPinYin(String src) { char[] charArray = null; charArray = src.toCharArray(); String[] strArr = new String[charArray.length]; HanyuPinyinOutputFormat pinyinFormat = new HanyuPinyinOutputFormat(); pinyinFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE); pinyinFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE); pinyinFormat.setVCharType(HanyuPinyinVCharType.WITH_V); String retStr = ""; try { for (int i = 0; i < charArray.length; i++) { if (Character.toString(charArray[i]).matches("[\\u4E00-\\u9FA5]+")) { // strArr strArr = PinyinHelper.toHanyuPinyinStringArray(charArray[i], pinyinFormat); // retStr retStr += strArr[0]; } else { // retStr retStr += Character.toString(charArray[i]); } } } catch (BadHanyuPinyinOutputFormatCombination e) { logger.error(e.getMessage(), e); } return retStr; } /** * * * @param src * * @return */ public static String getPinYinHeadChar(String src) { char[] charArray = null; charArray = src.toCharArray(); String[] strArr = new String[charArray.length]; HanyuPinyinOutputFormat pinyinFormat = new HanyuPinyinOutputFormat(); pinyinFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE); pinyinFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE); pinyinFormat.setVCharType(HanyuPinyinVCharType.WITH_V); String retStr = ""; try { for (int i = 0; i < charArray.length; i++) { if (Character.toString(charArray[i]).matches("[\\u4E00-\\u9FA5]+")) { // strArr strArr = PinyinHelper.toHanyuPinyinStringArray(charArray[i], pinyinFormat); // retStr retStr += strArr[0].charAt(0); } else { // retStr retStr += Character.toString(charArray[i]); } } } catch (BadHanyuPinyinOutputFormatCombination e) { logger.error(e.getMessage(), e); } return retStr; } /** * <br> * ListNULL<br> * NULL<br> * IntegerNULL0<br> * * @param obj * * @return */ public static boolean isDefined(Object obj) { if (obj instanceof Collection) { return CollectionUtils.isNotEmpty((Collection<?>) obj); } if (obj instanceof Map) { return MapUtils.isNotEmpty((Map<?, ?>) obj); } if (obj instanceof String) { return StringUtils.isNotEmpty((String) obj); } if (obj instanceof Integer) { return obj != null && (Integer) obj != 0; } return obj != null; } /** * * * @param length * * @return */ public static final String getRandomString(int length) { Random randGen = null; char[] numbersAndLetters = null; if (length < 1) { return null; } if (randGen == null) { randGen = new Random(); numbersAndLetters = ("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\" .toCharArray(); } char[] randBuffer = new char[length]; for (int i = 0; i < randBuffer.length; i++) { randBuffer[i] = numbersAndLetters[randGen.nextInt(numbersAndLetters.length)]; } return new String(randBuffer); } /** * KeyValueMapkey1 * * @param length * * @return */ public static final void putValueIntoMap(Map<String, Integer> map, String key, Integer value) { int index = 0; while (true) { Integer mapValue = null; if (index == 0) { mapValue = map.get(key); } else { mapValue = map.get(key + index); } if (mapValue == null) { key = key + (index == 0 ? "" : index); map.put(key, value); break; } index++; } } }
package com.jetbrains.python.actions; import com.google.common.collect.Lists; import com.intellij.execution.ExecutionHelper; import com.intellij.execution.console.LanguageConsoleView; import com.intellij.execution.process.ProcessHandler; import com.intellij.execution.ui.ExecutionConsole; import com.intellij.execution.ui.RunContentDescriptor; import com.intellij.ide.DataManager; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.actionSystem.Presentation; import com.intellij.openapi.editor.*; import com.intellij.openapi.editor.ex.util.EditorUtil; import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.wm.IdeFocusManager; import com.intellij.openapi.wm.ToolWindow; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import com.intellij.ui.content.Content; import com.intellij.ui.content.ContentManager; import com.intellij.util.Consumer; import com.intellij.util.containers.ContainerUtil; import com.intellij.xdebugger.XDebugSession; import com.intellij.xdebugger.XDebuggerManager; import com.jetbrains.python.PyBundle; import com.jetbrains.python.console.*; import com.jetbrains.python.psi.PyFile; import com.jetbrains.python.run.PythonRunConfiguration; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Collection; public class PyExecuteSelectionAction extends DumbAwareAction { public PyExecuteSelectionAction() { super(PyBundle.messagePointer("python.execute.selection.action.execute.selection.in.console")); } @Override public void actionPerformed(@NotNull AnActionEvent e) { Editor editor = e.getData(CommonDataKeys.EDITOR); if (editor != null) { final String selectionText = getSelectionText(editor); if (selectionText != null) { showConsoleAndExecuteCode(e, selectionText); } else { String line = getLineUnderCaret(editor); if (line != null) { showConsoleAndExecuteCode(e, line.trim()); moveCaretDown(editor); } } } } private static void moveCaretDown(Editor editor) { VisualPosition pos = editor.getCaretModel().getVisualPosition(); Pair<LogicalPosition, LogicalPosition> lines = EditorUtil.calcSurroundingRange(editor, pos, pos); int offset = editor.getCaretModel().getOffset(); LogicalPosition lineStart = lines.first; LogicalPosition nextLineStart = lines.second; int start = editor.logicalPositionToOffset(lineStart); int end = editor.logicalPositionToOffset(nextLineStart); Document document = editor.getDocument(); if (nextLineStart.line < document.getLineCount()) { int newOffset = end + offset - start; int nextLineEndOffset = document.getLineEndOffset(nextLineStart.line); if (newOffset >= nextLineEndOffset) { newOffset = nextLineEndOffset; } editor.getCaretModel().moveToOffset(newOffset); editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); } } /** * Finds existing or creates a new console and then executes provided code there. * * @param e * @param selectionText null means that there is no code to execute, only open a console */ public static void showConsoleAndExecuteCode(@NotNull final AnActionEvent e, @Nullable final String selectionText) { final Editor editor = e.getData(CommonDataKeys.EDITOR); Project project = e.getProject(); final boolean requestFocusToConsole = selectionText == null; findCodeExecutor(e.getDataContext(), codeExecutor -> executeInConsole(codeExecutor, selectionText, editor), editor, project, requestFocusToConsole); } /** * Find existing or start a new console with sdk path given and execute provided text * Used to run file in Python Console * * @param project current Project * @param selectionText text to execute * */ public static void selectConsoleAndExecuteCode(@NotNull Project project, @Nullable final String selectionText) { final DataContext dataContext = DataManager.getInstance().getDataContext(); selectConsole(dataContext, project, codeExecutor -> executeInConsole(codeExecutor, selectionText, null), null, true); } private static String getLineUnderCaret(Editor editor) { VisualPosition caretPos = editor.getCaretModel().getVisualPosition(); Pair<LogicalPosition, LogicalPosition> lines = EditorUtil.calcSurroundingRange(editor, caretPos, caretPos); LogicalPosition lineStart = lines.first; LogicalPosition nextLineStart = lines.second; int start = editor.logicalPositionToOffset(lineStart); int end = editor.logicalPositionToOffset(nextLineStart); if (end <= start) { return null; } return editor.getDocument().getCharsSequence().subSequence(start, end).toString(); } @Nullable private static String getSelectionText(@NotNull Editor editor) { if (editor.getSelectionModel().hasSelection()) { SelectionModel model = editor.getSelectionModel(); return model.getSelectedText(); } else { return null; } } @Override public void update(@NotNull AnActionEvent e) { Editor editor = e.getData(CommonDataKeys.EDITOR); Presentation presentation = e.getPresentation(); boolean enabled = false; if (isPython(editor)) { String text = getSelectionText(editor); if (text != null) { presentation.setText(PyBundle.message("python.execute.selection.action.execute.selection.in.console")); } else { text = getLineUnderCaret(editor); if (text != null) { presentation.setText(PyBundle.message("python.execute.selection.action.execute.line.in.console")); } } enabled = !StringUtil.isEmpty(text); } presentation.setEnabledAndVisible(enabled); } public static boolean isPython(Editor editor) { if (editor == null) { return false; } Project project = editor.getProject(); if (project == null) { return false; } PsiFile psi = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); return psi instanceof PyFile; } private static void selectConsole(@NotNull DataContext dataContext, @NotNull Project project, @NotNull final Consumer<PyCodeExecutor> consumer, @Nullable Editor editor, boolean requestFocusToConsole) { Collection<RunContentDescriptor> consoles = getConsoles(project); ExecutionHelper .selectContentDescriptor(dataContext, project, consoles, PyBundle.message("python.execute.selection.action.select.console.to.execute.in"), descriptor -> { if (descriptor != null && descriptor.getExecutionConsole() instanceof PyCodeExecutor) { ExecutionConsole console = descriptor.getExecutionConsole(); consumer.consume((PyCodeExecutor)console); if (console instanceof PythonDebugLanguageConsoleView) { XDebugSession currentSession = XDebuggerManager.getInstance(project).getCurrentSession(); if (currentSession != null) { // Select "Console" tab in case of Debug console ContentManager contentManager = currentSession.getUI().getContentManager(); Content content = contentManager.findContent("Console"); if (content != null) { contentManager.setSelectedContent(content); } // It's necessary to request focus again after tab selection if (requestFocusToConsole) { ((PythonDebugLanguageConsoleView)console).getPydevConsoleView().requestFocus(); } else { if (editor != null) { IdeFocusManager.findInstance().requestFocus(editor.getContentComponent(), true); } } } } else { PythonConsoleToolWindow consoleToolWindow = PythonConsoleToolWindow.getInstance(project); ToolWindow toolWindow = consoleToolWindow != null ? consoleToolWindow.getToolWindow() : null; if (toolWindow != null && !toolWindow.isVisible()) { toolWindow.show(null); ContentManager contentManager = toolWindow.getContentManager(); Content content = contentManager.findContent(descriptor.getDisplayName()); if (content != null) { contentManager.setSelectedContent(content); } } } } }); } private static Collection<RunContentDescriptor> getConsoles(Project project) { PythonConsoleToolWindow toolWindow = PythonConsoleToolWindow.getInstance(project); if (toolWindow != null && toolWindow.getToolWindow().isVisible()) { RunContentDescriptor selectedContentDescriptor = toolWindow.getSelectedContentDescriptor(); return selectedContentDescriptor != null && isAlive(selectedContentDescriptor) ? Lists.newArrayList(selectedContentDescriptor) : new ArrayList<>(); } Collection<RunContentDescriptor> descriptors = ExecutionHelper.findRunningConsole(project, dom -> dom.getExecutionConsole() instanceof PyCodeExecutor && isAlive(dom)); if (descriptors.isEmpty() && toolWindow != null && toolWindow.isInitialized()) { return ContainerUtil.filter(toolWindow.getConsoleContentDescriptors(), PyExecuteSelectionAction::isAlive); } else { return descriptors; } } private static boolean isAlive(RunContentDescriptor dom) { ProcessHandler processHandler = dom.getProcessHandler(); return processHandler != null && !processHandler.isProcessTerminated(); } public static void findCodeExecutor(@NotNull DataContext dataContext, @NotNull Consumer<PyCodeExecutor> consumer, @Nullable Editor editor, @Nullable Project project, boolean requestFocusToConsole) { if (project != null) { if (canFindConsole(project, null)) { selectConsole(dataContext, project, consumer, editor, requestFocusToConsole); } else { showConsole(project, consumer); } } } private static void showConsole(final Project project, final Consumer<PyCodeExecutor> consumer) { final PythonConsoleToolWindow toolWindow = PythonConsoleToolWindow.getInstance(project); final Collection<RunContentDescriptor> descriptors = getConsoles(project); if (toolWindow != null && !descriptors.isEmpty()) { toolWindow.activate(() -> { RunContentDescriptor descriptor = descriptors.stream().findFirst().orElse(null); if (descriptor != null && descriptor.getExecutionConsole() instanceof PyCodeExecutor) { consumer.consume((PyCodeExecutor)descriptor.getExecutionConsole()); } }); } else { startNewConsoleInstance(project, consumer, null, null); } } public static void startNewConsoleInstance(@NotNull final Project project, @NotNull final Consumer<? super PyCodeExecutor> consumer, @Nullable String runFileText, @Nullable PythonRunConfiguration config) { PythonConsoleRunnerFactory consoleRunnerFactory = PythonConsoleRunnerFactory.getInstance(); PydevConsoleRunner runner; if (runFileText == null || config == null) { runner = consoleRunnerFactory.createConsoleRunner(project, null); } else { runner = consoleRunnerFactory.createConsoleRunnerWithFile(project, null, runFileText, config); } final PythonConsoleToolWindow toolWindow = PythonConsoleToolWindow.getInstance(project); runner.addConsoleListener(new PydevConsoleRunner.ConsoleListener() { @Override public void handleConsoleInitialized(@NotNull LanguageConsoleView consoleView) { if (consoleView instanceof PyCodeExecutor) { consumer.consume((PyCodeExecutor)consoleView); if (toolWindow != null) { toolWindow.getToolWindow().show(null); } } } }); runner.run(false); } public static boolean canFindConsole(@Nullable Project project, @Nullable String sdkHomePath) { if (project != null) { Collection<RunContentDescriptor> descriptors = getConsoles(project); if (sdkHomePath == null) { return descriptors.size() > 0; } else { for (RunContentDescriptor descriptor : descriptors) { final ExecutionConsole console = descriptor.getExecutionConsole(); if (console instanceof PythonConsoleView) { final PythonConsoleView pythonConsole = (PythonConsoleView)console; if (sdkHomePath.equals(pythonConsole.getSdkHomePath())) { return true; } } } return false; } } else { return false; } } public static void executeInConsole(@NotNull PyCodeExecutor codeExecutor, @Nullable String text, @Nullable Editor editor) { codeExecutor.executeCode(text, editor); } }
package refinedstorage.gui; import java.io.IOException; import java.util.ArrayList; import java.util.Comparator; import java.util.Iterator; import java.util.List; import net.minecraft.client.audio.PositionedSoundRecord; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.GuiTextField; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.RenderHelper; import net.minecraft.init.SoundEvents; import net.minecraft.inventory.Slot; import org.lwjgl.input.Mouse; import refinedstorage.RefinedStorage; import refinedstorage.block.EnumGridType; import refinedstorage.container.ContainerGrid; import refinedstorage.gui.sidebutton.SideButtonGridSortingDirection; import refinedstorage.gui.sidebutton.SideButtonGridSortingType; import refinedstorage.gui.sidebutton.SideButtonRedstoneMode; import refinedstorage.network.MessageGridCraftingClear; import refinedstorage.network.MessageStoragePull; import refinedstorage.network.MessageStoragePush; import refinedstorage.storage.StorageItem; import refinedstorage.tile.TileController; import refinedstorage.tile.TileGrid; public class GuiGrid extends GuiBase { private ContainerGrid container; private TileGrid grid; private GuiTextField searchField; private int hoveringSlotId; private int hoveringId; private int offset; private float currentScroll; private boolean wasClicking = false; private boolean isScrolling = false; public GuiGrid(ContainerGrid container, TileGrid grid) { super(container, 193, grid.getType() == EnumGridType.CRAFTING ? 256 : 190); this.container = container; this.grid = grid; } @Override public void init(int x, int y) { addSideButton(new SideButtonRedstoneMode(grid)); addSideButton(new SideButtonGridSortingDirection(grid)); addSideButton(new SideButtonGridSortingType(grid)); searchField = new GuiTextField(0, fontRendererObj, x + 80 + 1, y + 6 + 1, 88 - 6, fontRendererObj.FONT_HEIGHT); searchField.setEnableBackgroundDrawing(false); searchField.setVisible(true); searchField.setTextColor(16777215); searchField.setCanLoseFocus(false); searchField.setFocused(true); } @Override public void update(int x, int y) { int wheel = Mouse.getDWheel(); wheel = Math.max(Math.min(-wheel, 1), -1); if (canScroll(wheel)) { offset += wheel; } if (offset > getMaxOffset()) { offset = getMaxOffset(); } } public void handleScrolling(int mouseX, int mouseY) { boolean down = Mouse.isButtonDown(0); if (!wasClicking && down && inBounds(174, 20, 12, 70, mouseX, mouseY)) { isScrolling = true; } if (!down) { isScrolling = false; } wasClicking = down; if (isScrolling) { currentScroll = mouseY - 20; } } private int getMaxOffset() { if (!grid.isConnected()) { return 0; } int max = ((int) Math.ceil((float) getItems().size() / (float) 9)) - 4; return max < 0 ? 0 : max; } private boolean canScroll(int delta) { if (offset + delta < 0) { return false; } return offset + delta <= getMaxOffset(); } private boolean isHoveringOverValidSlot(List<StorageItem> items) { return grid.isConnected() && isHoveringOverSlot() && hoveringSlotId < items.size(); } private boolean isHoveringOverSlot() { return hoveringSlotId >= 0; } public boolean isHoveringOverClear(int mouseX, int mouseY) { if (grid.getType() == EnumGridType.CRAFTING) { return inBounds(81, 105, 7, 7, mouseX, mouseY); } return false; } @Override public void drawBackground(int x, int y, int mouseX, int mouseY) { if (grid.getType() == EnumGridType.CRAFTING) { bindTexture("gui/crafting_grid.png"); } else { bindTexture("gui/grid.png"); } drawTexture(x, y, 0, 0, width, height); drawTexture(x + 174, y + 20 + (int) currentScroll, 232, 0, 12, 15); searchField.drawTextBox(); } @Override public void drawForeground(int mouseX, int mouseY) { handleScrolling(mouseX, mouseY); drawString(7, 7, t("gui.refinedstorage:grid")); if (grid.getType() == EnumGridType.CRAFTING) { drawString(7, 94, t("container.crafting")); } drawString(7, grid.getType() == EnumGridType.CRAFTING ? 163 : 96, t("container.inventory")); int x = 8; int y = 20; List<StorageItem> items = getItems(); hoveringSlotId = -1; int slot = offset * 9; RenderHelper.enableGUIStandardItemLighting(); for (int i = 0; i < 9 * 4; ++i) { if (slot < items.size()) { drawItem(x, y, items.get(slot).toItemStack(), true); } if (inBounds(x, y, 16, 16, mouseX, mouseY) || !grid.isConnected()) { hoveringSlotId = slot; if (slot < items.size()) { // We need to use the ID, because if we filter, the client-side index will change // while the serverside's index will still be the same. hoveringId = items.get(slot).getId(); } int color = grid.isConnected() ? -2130706433 : 0xFF5B5B5B; GlStateManager.disableLighting(); GlStateManager.disableDepth(); zLevel = 190; GlStateManager.colorMask(true, true, true, false); drawGradientRect(x, y, x + 16, y + 16, color, color); zLevel = 0; GlStateManager.colorMask(true, true, true, true); GlStateManager.enableLighting(); GlStateManager.enableDepth(); } slot++; x += 18; if ((i + 1) % 9 == 0) { x = 8; y += 18; } } if (isHoveringOverValidSlot(items)) { drawTooltip(mouseX, mouseY, items.get(hoveringSlotId).toItemStack()); } if (isHoveringOverClear(mouseX, mouseY)) { drawTooltip(mouseX, mouseY, t("misc.refinedstorage:clear")); } } public List<StorageItem> getItems() { List<StorageItem> items = new ArrayList<StorageItem>(); if (!grid.isConnected()) { return items; } items.addAll(grid.getController().getItems()); if (!searchField.getText().trim().isEmpty()) { Iterator<StorageItem> t = items.iterator(); while (t.hasNext()) { StorageItem item = t.next(); if (!item.toItemStack().getDisplayName().toLowerCase().contains(searchField.getText().toLowerCase())) { t.remove(); } } } items.sort(new Comparator<StorageItem>() { @Override public int compare(StorageItem o1, StorageItem o2) { if (grid.getSortingDirection() == TileGrid.SORTING_DIRECTION_ASCENDING) { return o2.toItemStack().getDisplayName().compareTo(o1.toItemStack().getDisplayName()); } else if (grid.getSortingDirection() == TileGrid.SORTING_DIRECTION_DESCENDING) { return o1.toItemStack().getDisplayName().compareTo(o2.toItemStack().getDisplayName()); } return 0; } }); if (grid.getSortingType() == TileGrid.SORTING_TYPE_QUANTITY) { items.sort(new Comparator<StorageItem>() { @Override public int compare(StorageItem o1, StorageItem o2) { if (grid.getSortingDirection() == TileGrid.SORTING_DIRECTION_ASCENDING) { return Integer.valueOf(o2.getQuantity()).compareTo(o1.getQuantity()); } else if (grid.getSortingDirection() == TileGrid.SORTING_DIRECTION_DESCENDING) { return Integer.valueOf(o1.getQuantity()).compareTo(o2.getQuantity()); } return 0; } }); } return items; } @Override public void mouseClicked(int mouseX, int mouseY, int clickedButton) throws IOException { super.mouseClicked(mouseX, mouseY, clickedButton); boolean clickedClear = clickedButton == 0 && isHoveringOverClear(mouseX - guiLeft, mouseY - guiTop); if (grid.isConnected()) { TileController controller = grid.getController(); if (isHoveringOverSlot() && container.getPlayer().inventory.getItemStack() != null) { RefinedStorage.NETWORK.sendToServer(new MessageStoragePush(controller.getPos().getX(), controller.getPos().getY(), controller.getPos().getZ(), -1, clickedButton == 1)); } else if (isHoveringOverValidSlot(getItems()) && container.getPlayer().inventory.getItemStack() == null) { boolean half = clickedButton == 1; boolean shift = GuiScreen.isShiftKeyDown(); boolean one = clickedButton == 2; RefinedStorage.NETWORK.sendToServer(new MessageStoragePull(controller.getPos().getX(), controller.getPos().getY(), controller.getPos().getZ(), hoveringId, half, one, shift)); } else if (clickedClear) { RefinedStorage.NETWORK.sendToServer(new MessageGridCraftingClear(grid)); } else { for (Slot slot : container.getPlayerInventorySlots()) { if (inBounds(slot.xDisplayPosition, slot.yDisplayPosition, 16, 16, mouseX - guiLeft, mouseY - guiTop)) { if (GuiScreen.isShiftKeyDown()) { RefinedStorage.NETWORK.sendToServer(new MessageStoragePush(controller.getPos().getX(), controller.getPos().getY(), controller.getPos().getZ(), slot.slotNumber, clickedButton == 1)); } } } } } if (clickedClear) { mc.getSoundHandler().playSound(PositionedSoundRecord.getMasterRecord(SoundEvents.ui_button_click, 1.0F)); } } @Override protected void keyTyped(char character, int keyCode) throws IOException { if (!checkHotbarKeys(keyCode) && searchField.textboxKeyTyped(character, keyCode)) { } else { super.keyTyped(character, keyCode); } } }
package com.jetbrains.python.remote; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.util.text.StringUtil; import com.intellij.remotesdk.RemoteSdkAdditionalData; import com.intellij.remotesdk.RemoteSdkData; import com.intellij.remotesdk.RemoteSdkDataHolder; import com.jetbrains.python.sdk.PythonSdkAdditionalData; import com.jetbrains.python.sdk.flavors.PythonSdkFlavor; import com.jetbrains.python.sdk.flavors.UnixPythonSdkFlavor; import com.jetbrains.python.sdk.flavors.WinPythonSdkFlavor; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.util.ArrayList; import java.util.List; /** * @author traff */ public final class PyRemoteSdkAdditionalData extends PythonSdkAdditionalData implements RemoteSdkAdditionalData { private static final String HELPERS_DIR = ".pycharm_helpers"; private final static String SKELETONS_PATH = "SKELETONS_PATH"; private final RemoteSdkDataHolder myRemoteSdkDataHolder = new RemoteSdkDataHolder(HELPERS_DIR); private String mySkeletonsPath; public PyRemoteSdkAdditionalData(@Nullable PythonSdkFlavor flavor) { super(flavor); } public PyRemoteSdkAdditionalData(@NotNull final String interpreterPath) { super(computeFlavor(interpreterPath)); setInterpreterPath(interpreterPath); } public void setSkeletonsPath(String path) { mySkeletonsPath = path; } public String getSkeletonsPath() { return mySkeletonsPath; } @Override public String getInterpreterPath() { return myRemoteSdkDataHolder.getInterpreterPath(); } @Override public void setInterpreterPath(String interpreterPath) { myRemoteSdkDataHolder.setInterpreterPath(interpreterPath); } @Override public String getFullInterpreterPath() { return myRemoteSdkDataHolder.getFullInterpreterPath(); } @Override public String getHelpersPath() { return myRemoteSdkDataHolder.getHelpersPath(); } @Override public String getDefaultHelpersName() { return myRemoteSdkDataHolder.getDefaultHelpersName(); } @Override public void setHelpersPath(String tempFilesPath) { myRemoteSdkDataHolder.setHelpersPath(tempFilesPath); } @Override public String getHost() { return myRemoteSdkDataHolder.getHost(); } @Override public void setHost(String host) { myRemoteSdkDataHolder.setHost(host); } @Override public int getPort() { return myRemoteSdkDataHolder.getPort(); } @Override public void setPort(int port) { myRemoteSdkDataHolder.setPort(port); } @Override public String getUserName() { return myRemoteSdkDataHolder.getUserName(); } @Override public void setUserName(String userName) { myRemoteSdkDataHolder.setUserName(userName); } @Override public String getPassword() { return myRemoteSdkDataHolder.getPassword(); } @Override public void setPassword(String password) { myRemoteSdkDataHolder.setPassword(password); } @Override public void setStorePassword(boolean storePassword) { myRemoteSdkDataHolder.setStorePassword(storePassword); } @Override public void setStorePassphrase(boolean storePassphrase) { myRemoteSdkDataHolder.setStorePassphrase(storePassphrase); } @Override public boolean isStorePassword() { return myRemoteSdkDataHolder.isStorePassword(); } @Override public boolean isStorePassphrase() { return myRemoteSdkDataHolder.isStorePassphrase(); } @Override public boolean isAnonymous() { return myRemoteSdkDataHolder.isAnonymous(); } @Override public void setAnonymous(boolean anonymous) { myRemoteSdkDataHolder.setAnonymous(anonymous); } @Override public String getPrivateKeyFile() { return myRemoteSdkDataHolder.getPrivateKeyFile(); } @Override public void setPrivateKeyFile(String privateKeyFile) { myRemoteSdkDataHolder.setPrivateKeyFile(privateKeyFile); } @Override public String getKnownHostsFile() { return myRemoteSdkDataHolder.getKnownHostsFile(); } @Override public void setKnownHostsFile(String knownHostsFile) { myRemoteSdkDataHolder.setKnownHostsFile(knownHostsFile); } @Override public String getPassphrase() { return myRemoteSdkDataHolder.getPassphrase(); } @Override public void setPassphrase(String passphrase) { myRemoteSdkDataHolder.setPassphrase(passphrase); } @Override public boolean isUseKeyPair() { return myRemoteSdkDataHolder.isUseKeyPair(); } @Override public void setUseKeyPair(boolean useKeyPair) { myRemoteSdkDataHolder.setUseKeyPair(useKeyPair); } @Override public void addRemoteRoot(String remoteRoot) { myRemoteSdkDataHolder.addRemoteRoot(remoteRoot); } @Override public void clearRemoteRoots() { myRemoteSdkDataHolder.clearRemoteRoots(); } @Override public List<String> getRemoteRoots() { return myRemoteSdkDataHolder.getRemoteRoots(); } @Override public void setRemoteRoots(List<String> remoteRoots) { myRemoteSdkDataHolder.setRemoteRoots(remoteRoots); } @Override public boolean isHelpersVersionChecked() { return myRemoteSdkDataHolder.isHelpersVersionChecked(); } @Override public void setHelpersVersionChecked(boolean helpersVersionChecked) { myRemoteSdkDataHolder.setHelpersVersionChecked(helpersVersionChecked); } @Override public void completeInitialization() { } @NotNull public static PyRemoteSdkAdditionalData loadRemote(Sdk sdk, @Nullable Element element) { final String path = sdk.getHomePath(); assert path != null; final PyRemoteSdkAdditionalData data = new PyRemoteSdkAdditionalData(path); load(element, data); if (element != null) { data.myRemoteSdkDataHolder.loadRemoteSdkData(element); data.setSkeletonsPath(StringUtil.nullize(element.getAttributeValue(SKELETONS_PATH))); String helpersPath = StringUtil.nullize(element.getAttributeValue("PYCHARM_HELPERS_PATH")); if (helpersPath != null) { data.setHelpersPath(helpersPath); } } return data; } @Nullable private static PythonSdkFlavor computeFlavor(@Nullable String sdkPath) { if (sdkPath == null) { return null; } for (PythonSdkFlavor flavor : getApplicableFlavors(sdkPath.contains("\\"))) { if (flavor.isValidSdkPath(new File(sdkPath))) { return flavor; } } return null; } private static List<PythonSdkFlavor> getApplicableFlavors(boolean isWindows) { List<PythonSdkFlavor> result = new ArrayList<PythonSdkFlavor>(); if (isWindows) { result.add(WinPythonSdkFlavor.INSTANCE); } else { result.add(UnixPythonSdkFlavor.INSTANCE); } result.addAll(PythonSdkFlavor.getPlatformIndependentFlavors()); return result; } @Override public void save(@NotNull final Element rootElement) { super.save(rootElement); myRemoteSdkDataHolder.saveRemoteSdkData(rootElement); rootElement.setAttribute(SKELETONS_PATH, StringUtil.notNullize(getSkeletonsPath())); } @Nullable @Override public Object clone() throws CloneNotSupportedException { try { final PyRemoteSdkAdditionalData copy = (PyRemoteSdkAdditionalData)super.clone(); copyTo(copy); return copy; } catch (CloneNotSupportedException e) { return null; } } public void copyTo(PyRemoteSdkAdditionalData copy) { copy.setHost(getHost()); copy.setPort(getPort()); copy.setAnonymous(isAnonymous()); copy.setUserName(getUserName()); copy.setPassword(getPassword()); copy.setPrivateKeyFile(getPrivateKeyFile()); copy.setKnownHostsFile(getKnownHostsFile()); copy.setPassphrase(getPassphrase()); copy.setUseKeyPair(isUseKeyPair()); copy.setInterpreterPath(getInterpreterPath()); copy.setHelpersPath(getHelpersPath()); copy.setStorePassword(isStorePassword()); copy.setStorePassphrase(isStorePassphrase()); copy.setHelpersVersionChecked(isHelpersVersionChecked()); copy.setSkeletonsPath(getSkeletonsPath()); copy.setRemoteRoots(getRemoteRoots()); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PyRemoteSdkAdditionalData data = (PyRemoteSdkAdditionalData)o; if (!myRemoteSdkDataHolder.equals(data.myRemoteSdkDataHolder)) return false; if (!mySkeletonsPath.equals(data.mySkeletonsPath)) return false; return true; } @Override public int hashCode() { int result = myRemoteSdkDataHolder.hashCode(); result = 31 * result + mySkeletonsPath.hashCode(); return result; } }
package seedu.task.model.task; import seedu.address.commons.exceptions.IllegalValueException; /** * Represents a Task's name in the task book. * Guarantees: immutable; is valid as declared in {@link #isValidName(String)} */ public class Name { public static final String MESSAGE_NAME_CONSTRAINTS = "Task names can contain any characters and spaces, and it should not be blank"; /* * The first character of the name must not be a whitespace, * otherwise " " (a blank string) becomes a valid input. */ public static final String NAME_VALIDATION_REGEX = "."; public final String taskName; public Name(String name) throws IllegalValueException { assert name != null; String trimmedName = name.trim(); if (!isValidName(trimmedName)) { throw new IllegalValueException(MESSAGE_NAME_CONSTRAINTS); } this.taskName = trimmedName; } /** * Returns true if a given string is a valid person name. */ public static boolean isValidName(String test) { return test.matches(NAME_VALIDATION_REGEX); } @Override public String toString() { return taskName; } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof Name // instanceof handles nulls && this.taskName.equals(((Name) other).taskName)); // state check } @Override public int hashCode() { return taskName.hashCode(); } }
package seedu.taskell.ui; import com.google.common.eventbus.Subscribe; import javafx.application.Platform; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.image.Image; import javafx.stage.Stage; import seedu.taskell.MainApp; import seedu.taskell.commons.core.ComponentManager; import seedu.taskell.commons.core.Config; import seedu.taskell.commons.core.LogsCenter; import seedu.taskell.commons.events.model.DisplayListChangedEvent; import seedu.taskell.commons.events.storage.DataSavingExceptionEvent; import seedu.taskell.commons.events.ui.JumpToListRequestEvent; import seedu.taskell.commons.events.ui.TaskPanelSelectionChangedEvent; import seedu.taskell.commons.events.ui.ShowHelpRequestEvent; import seedu.taskell.commons.util.StringUtil; import seedu.taskell.logic.Logic; import seedu.taskell.model.UserPrefs; import java.util.logging.Logger; /** * The manager of the UI component. */ public class UiManager extends ComponentManager implements Ui { private static final Logger logger = LogsCenter.getLogger(UiManager.class); private static final String ICON_APPLICATION = "/images/task_manager_32.png"; private Logic logic; private Config config; private UserPrefs prefs; private MainWindow mainWindow; public UiManager(Logic logic, Config config, UserPrefs prefs) { super(); this.logic = logic; this.config = config; this.prefs = prefs; } @Override public void start(Stage primaryStage) { logger.info("Starting UI..."); primaryStage.setTitle(config.getAppTitle()); //Set the application icon. primaryStage.getIcons().add(getImage(ICON_APPLICATION)); try { mainWindow = MainWindow.load(primaryStage, config, prefs, logic); mainWindow.show(); //This should be called before creating other UI parts mainWindow.fillInnerParts(); } catch (Throwable e) { logger.severe(StringUtil.getDetails(e)); showFatalErrorDialogAndShutdown("Fatal error during initializing", e); } } @Override public void stop() { prefs.updateLastUsedGuiSetting(mainWindow.getCurrentGuiSetting()); mainWindow.hide(); //mainWindow.releaseResources(); } private void showFileOperationAlertAndWait(String description, String details, Throwable cause) { final String content = details + ":\n" + cause.toString(); showAlertDialogAndWait(AlertType.ERROR, "File Op Error", description, content); } private Image getImage(String imagePath) { return new Image(MainApp.class.getResourceAsStream(imagePath)); } void showAlertDialogAndWait(Alert.AlertType type, String title, String headerText, String contentText) { showAlertDialogAndWait(mainWindow.getPrimaryStage(), type, title, headerText, contentText); } private static void showAlertDialogAndWait(Stage owner, AlertType type, String title, String headerText, String contentText) { final Alert alert = new Alert(type); alert.getDialogPane().getStylesheets().add("view/TaskellCyanTheme.css"); alert.initOwner(owner); alert.setTitle(title); alert.setHeaderText(headerText); alert.setContentText(contentText); alert.showAndWait(); } private void showFatalErrorDialogAndShutdown(String title, Throwable e) { logger.severe(title + " " + e.getMessage() + StringUtil.getDetails(e)); showAlertDialogAndWait(Alert.AlertType.ERROR, title, e.getMessage(), e.toString()); Platform.exit(); System.exit(1); } @Subscribe private void handleDataSavingExceptionEvent(DataSavingExceptionEvent event) { logger.info(LogsCenter.getEventHandlingLogMessage(event)); showFileOperationAlertAndWait("Could not save data", "Could not save data to file", event.exception); } @Subscribe private void handleShowHelpEvent(ShowHelpRequestEvent event) { logger.info(LogsCenter.getEventHandlingLogMessage(event)); mainWindow.handleHelp(); } @Subscribe private void handleJumpToListRequestEvent(JumpToListRequestEvent event) { logger.info(LogsCenter.getEventHandlingLogMessage(event)); mainWindow.getTaskListPanel().scrollTo(event.targetIndex); } @Subscribe private void handleTaskPanelSelectionChangedEvent(TaskPanelSelectionChangedEvent event){ logger.info(LogsCenter.getEventHandlingLogMessage(event)); //mainWindow.loadTaskPage(event.getNewSelection()); } @Subscribe private void handleDisplayList(DisplayListChangedEvent event) { logger.info(LogsCenter.getEventHandlingLogMessage(event)); logger.info("Displaying"); mainWindow.loadList(event.getList()); } }
package services; import java.io.IOException; import java.util.Calendar; import java.util.Collection; import java.util.Date; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.Assert; import com.paypal.base.rest.PayPalRESTException; import com.paypal.exception.ClientActionRequiredException; import com.paypal.exception.HttpErrorException; import com.paypal.exception.InvalidCredentialException; import com.paypal.exception.InvalidResponseDataException; import com.paypal.exception.MissingCredentialException; import com.paypal.exception.SSLConfigurationException; import com.paypal.sdk.exceptions.OAuthException; import domain.CreditCard; import domain.FeePayment; import domain.PayPalObject; import domain.RouteOffer; import domain.ShipmentOffer; import domain.User; import repositories.FeePaymentRepository; @Service @Transactional public class FeePaymentService { static Logger log = Logger.getLogger(FeePaymentService.class); @Autowired private FeePaymentRepository feePaymentRepository; @Autowired private UserService userService; @Autowired private ActorService actorService; @Autowired private RouteOfferService routeOfferService; @Autowired private ShipmentOfferService shipmentOfferService; @Autowired private PayPalService payPalService; @Autowired private RouteService routeService; public FeePaymentService() { super(); } public FeePayment create() { Assert.isTrue(actorService.checkAuthority("USER"), "Only an user can create a feepayment"); FeePayment result; User user; result = new FeePayment(); user = userService.findByPrincipal(); result.setPurchaser(user); result.setPaymentMoment(new Date()); result.setType("Pending"); result.setIsPayed(false); return result; } public FeePayment save(FeePayment feePayment) { Assert.notNull(feePayment); Assert.isTrue(actorService.checkAuthority("USER"), "Only an user can save a feepayment"); User user; FeePayment feePaymentPreSave; PayPalObject po; user = userService.findByPrincipal(); po = payPalService.findByFeePaymentId(feePayment.getId()); if(feePayment.getId() == 0) { if(feePayment.getCreditCard() != null) { Assert.isTrue(compruebaFecha(feePayment.getCreditCard()), "Credit card cannot be expired"); } feePayment.setPurchaser(user); feePayment.setPaymentMoment(new Date()); feePayment.setType("Pending"); feePayment.setCommission(feePayment.getAmount()/10); feePayment = feePaymentRepository.save(feePayment); } else { Assert.isTrue(po != null ^ feePayment.getCreditCard() != null, "FeePaymentService.save.error.OrCreditCardOrPayPal"); feePaymentPreSave = this.findOne(feePayment.getId()); feePaymentPreSave.setType(feePayment.getType()); feePayment = feePaymentRepository.save(feePaymentPreSave); } feePayment.setIsPayed(po != null || feePayment.getCreditCard() != null); return feePayment; } public FeePayment manageFeePayment(int feepaymentId, String type) { FeePayment feePayment; FeePayment res = null; PayPalObject payPal; feePayment = this.findOne(feepaymentId); feePayment.setType(type); try { payPal = payPalService.findByFeePaymentId(feepaymentId); if (payPal != null) { payPalService.payToShipper(feepaymentId); } res = this.save(feePayment); } catch (SSLConfigurationException | InvalidCredentialException | HttpErrorException | InvalidResponseDataException | ClientActionRequiredException | MissingCredentialException | OAuthException | PayPalRESTException | IOException | InterruptedException e) { log.error(e,e); } return res; } public FeePayment findOne(int feePaymentId) { FeePayment result; result = feePaymentRepository.findOne(feePaymentId); return result; } public Collection<FeePayment> findAll() { Collection<FeePayment> result; result = feePaymentRepository.findAll(); return result; } public Page<FeePayment> findAllPendingByUser(Pageable pageable) { Page<FeePayment> result; User user; user = userService.findByPrincipal(); result = feePaymentRepository.findAllPendingByUser(user.getId(), pageable); Assert.notNull(result); return result; } public FeePayment createAndSave(int type, int id, int sizePriceId, double amount, String description){ FeePayment res; RouteOffer ro; ShipmentOffer so; res = this.create(); /** * Type == 1 -> Contract a route * Type == 2 -> Create a routeOffer * Type == 3 -> Accept a shipmentOffer */ switch (type) { case 1: ro = routeService.contractRoute(id, sizePriceId); res.setRouteOffer(ro); res.setAmount(ro.getAmount()); res.setCarrier(ro.getRoute().getCreator()); res.setPurchaser(ro.getUser()); break; case 2: ro = routeOfferService.create(id); ro.setAmount(amount); ro.setDescription(description); ro = routeOfferService.save(ro); res.setRouteOffer(ro); res.setAmount(ro.getAmount()); res.setCarrier(ro.getRoute().getCreator()); res.setPurchaser(ro.getUser()); break; case 3: so = shipmentOfferService.findOne(id); res.setShipmentOffer(so); res.setAmount(so.getAmount()); res.setCarrier(so.getUser()); res.setPurchaser(so.getShipment().getCreator()); break; default: break; } res = this.save(res); return res; } public Page<FeePayment> findAllRejected(Pageable page) { Page<FeePayment> result; result = feePaymentRepository.findAllRejected(page); Assert.notNull(result); return result; } public Page<FeePayment> findAllPending(Pageable page) { Page<FeePayment> result; result = feePaymentRepository.findAllPending(page); Assert.notNull(result); return result; } public Page<FeePayment> findAllAccepted(Pageable page) { Page<FeePayment> result; result = feePaymentRepository.findAllAccepted(page); Assert.notNull(result); return result; } private boolean compruebaFecha(CreditCard creditCard) { boolean result; Calendar c; int cMonth, cYear; result = false; c = Calendar.getInstance(); cMonth = c.get(2) + 1; //Obtenemos numero del mes (Enero es 0) cYear = c.get(1); //Obtenemos ao if(creditCard.getExpirationYear() > cYear) { result = true; } else if(creditCard.getExpirationYear() == cYear) { if(creditCard.getExpirationMonth() >= cMonth) { result = true; } } return result; } }
package com.yahoo; import com.yahoo.osgi.maven.ProjectBundleClassPaths; import com.yahoo.vespa.config.VespaVersion; import org.junit.Before; import org.junit.Test; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Paths; import java.util.Collection; import java.util.jar.Attributes; import java.util.jar.JarFile; import java.util.jar.Manifest; import java.util.zip.ZipEntry; import static com.yahoo.osgi.maven.ProjectBundleClassPaths.CLASSPATH_MAPPINGS_FILENAME; import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.CoreMatchers.anyOf; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.endsWith; import static org.hamcrest.CoreMatchers.hasItems; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; /** * Verifies the bundle jar file built and its manifest. * @author Tony Vaagenes */ public class BundleIT { private JarFile jarFile; private Attributes mainAttributes; @Before public void setup() { try { File componentJar = findBundleJar(); jarFile = new JarFile(componentJar); Manifest manifest = jarFile.getManifest(); mainAttributes = manifest.getMainAttributes(); } catch (IOException e) { throw new RuntimeException(e); } } private File findBundleJar() { File[] componentFile = new File("target").listFiles(new FilenameFilter() { @Override public boolean accept(File file, String fileName) { return fileName.endsWith("-deploy.jar") || fileName.endsWith("-jar-with-dependencies.jar"); } }); if (componentFile.length != 1) { throw new RuntimeException("Failed finding component jar file"); } return componentFile[0]; } @Test public void require_that_bundle_version_is_added_to_manifest() { String bundleVersion = mainAttributes.getValue("Bundle-Version"); // Because of snapshot builds, we can only verify the major version. int majorBundleVersion = Integer.valueOf(bundleVersion.substring(0, bundleVersion.indexOf('.'))); assertThat(majorBundleVersion, is(VespaVersion.major)); } @Test public void require_that_bundle_symbolic_name_matches_pom_artifactId() { assertThat(mainAttributes.getValue("Bundle-SymbolicName"), is("bundle-plugin-test")); } @Test public void require_that_manifest_contains_inferred_imports() { String importPackage = mainAttributes.getValue("Import-Package"); // From SimpleSearcher assertThat(importPackage, containsString("com.yahoo.prelude.hitfield")); assertThat(importPackage, containsString("org.json")); // From SimpleSearcher2 assertThat(importPackage, containsString("com.yahoo.processing")); assertThat(importPackage, containsString("com.yahoo.metrics.simple")); assertThat(importPackage, containsString("com.google.inject")); } @Test public void require_that_manifest_contains_manual_imports() { String importPackage = mainAttributes.getValue("Import-Package"); assertThat(importPackage, containsString("manualImport.withoutVersion")); assertThat(importPackage, containsString("manualImport.withVersion;version=\"12.3.4\"")); for (int i=1; i<=2; ++i) assertThat(importPackage, containsString("multiple.packages.with.the.same.version" + i + ";version=\"[1,2)\"")); } @Test public void require_that_manifest_contains_exports() { String exportPackage = mainAttributes.getValue("Export-Package"); assertThat(exportPackage, containsString("com.yahoo.test;version=1.2.3.RELEASE")); } @Test // TODO: use another jar than jrt, which now pulls in a lot of dependencies that pollute the manifest of the // generated bundle. (It's compile scoped in pom.xml to be added to the bundle-cp.) public void require_that_manifest_contains_bundle_class_path() { String bundleClassPath = mainAttributes.getValue("Bundle-ClassPath"); assertThat(bundleClassPath, containsString(".,")); // If bundle-plugin-test is compiled in a mvn command that also built jrt, // the jrt artifact is jrt.jar, otherwise the installed and versioned artifact // is used: jrt-7-SNAPSHOT.jar. assertThat(bundleClassPath, anyOf( containsString("dependencies/jrt-7-SNAPSHOT.jar"), containsString("dependencies/jrt.jar"))); } @Test public void require_that_component_jar_file_contains_compile_artifacts() { ZipEntry versionedEntry = jarFile.getEntry("dependencies/jrt-7-SNAPSHOT.jar"); ZipEntry unversionedEntry = jarFile.getEntry("dependencies/jrt.jar"); if (versionedEntry == null) { assertNotNull(unversionedEntry); } else { assertNull(unversionedEntry); } } @Test public void require_that_web_inf_url_is_propagated_to_the_manifest() { String webInfUrl = mainAttributes.getValue("WebInfUrl"); assertThat(webInfUrl, containsString("/WEB-INF/web.xml")); } @SuppressWarnings("unchecked") @Test public void bundle_class_path_mappings_are_generated() throws URISyntaxException, IOException { URL mappingsUrl = getClass().getResource("/" + CLASSPATH_MAPPINGS_FILENAME); assertNotNull( "Could not find " + CLASSPATH_MAPPINGS_FILENAME + " in the test output directory", mappingsUrl); ProjectBundleClassPaths bundleClassPaths = ProjectBundleClassPaths.load(Paths.get(mappingsUrl.toURI())); assertThat(bundleClassPaths.mainBundle.bundleSymbolicName, is("bundle-plugin-test")); Collection<String> mainBundleClassPaths = bundleClassPaths.mainBundle.classPathElements; assertThat(mainBundleClassPaths, hasItems( endsWith("target/classes"), anyOf( allOf(containsString("jrt"), containsString(".jar"), containsString("m2/repository")), containsString("jrt/target/jrt.jar")))); } }
package techreborn.init; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import net.minecraft.block.Block; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraftforge.common.ForgeModContainer; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.UniversalBucket; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.oredict.OreDictionary; import org.apache.commons.lang3.ArrayUtils; import reborncore.api.recipe.RecipeHandler; import reborncore.common.util.CraftingHelper; import reborncore.common.util.OreUtil; import reborncore.common.util.StringUtils; import techreborn.Core; import techreborn.api.ScrapboxList; import techreborn.api.TechRebornAPI; import techreborn.api.reactor.FusionReactorRecipe; import techreborn.api.reactor.FusionReactorRecipeHelper; import techreborn.api.recipe.RecyclerRecipe; import techreborn.api.recipe.ScrapboxRecipe; import techreborn.api.recipe.machines.*; import techreborn.blocks.*; import techreborn.compat.CompatManager; import techreborn.config.ConfigTechReborn; import techreborn.items.*; import techreborn.parts.powerCables.ItemStandaloneCables; import techreborn.utils.RecipeUtils; import techreborn.utils.StackWIPHandler; import java.security.InvalidParameterException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static techreborn.utils.OreDictUtils.getDictData; import static techreborn.utils.OreDictUtils.getDictOreOrNull; import static techreborn.utils.OreDictUtils.isDictPrefixed; import static techreborn.utils.OreDictUtils.joinDictName; public class ModRecipes { public static ConfigTechReborn config; public static ItemStack batteryStack = new ItemStack(ModItems.reBattery, 1, OreDictionary.WILDCARD_VALUE); public static ItemStack crystalStack = new ItemStack(ModItems.energyCrystal, 1, OreDictionary.WILDCARD_VALUE); public static ItemStack lapcrystalStack = new ItemStack(ModItems.lapotronCrystal, 1, OreDictionary.WILDCARD_VALUE); public static ItemStack dyes = new ItemStack(Items.DYE, 1, OreDictionary.WILDCARD_VALUE); public static Item diamondDrill = ModItems.diamondDrill; public static ItemStack diamondDrillStack = new ItemStack(diamondDrill, 1, OreDictionary.WILDCARD_VALUE); public static Item ironChainsaw = ModItems.ironChainsaw; public static ItemStack ironChainsawStack = new ItemStack(ironChainsaw, 1, OreDictionary.WILDCARD_VALUE); public static Item diamondChainsaw = ModItems.diamondChainsaw; public static ItemStack diamondChainsawStack = new ItemStack(diamondChainsaw, 1, OreDictionary.WILDCARD_VALUE); public static Item steelJackhammer = ModItems.steelJackhammer; public static ItemStack steelJackhammerStack = new ItemStack(steelJackhammer, 1, OreDictionary.WILDCARD_VALUE); public static Item diamondJackhammer = ModItems.diamondJackhammer; public static ItemStack diamondJackhammerStack = new ItemStack(diamondJackhammer, 1, OreDictionary.WILDCARD_VALUE); public static void init() { //Done again incase we loaded before QuantumStorage CompatManager.isQuantumStorageLoaded = Loader.isModLoaded("quantumstorage"); addShapelessRecipes(); addGeneralShapedRecipes(); addMachineRecipes(); addSmeltingRecipes(); addUUrecipes(); addAlloySmelterRecipes(); addPlateCuttingMachineRecipes(); addIndustrialCentrifugeRecipes(); addChemicalReactorRecipes(); addIndustrialElectrolyzerRecipes(); addBlastFurnaceRecipes(); addIndustrialGrinderRecipes(); addImplosionCompressorRecipes(); addVacuumFreezerRecipes(); addReactorRecipes(); addIc2Recipes(); addGrinderRecipes(); // addHammerRecipes(); addIc2ReplacementReicpes(); addExtractorRecipes(); addCompressorRecipes(); addWireRecipes(); addScrapBoxloot(); } static void addScrapBoxloot() { ScrapboxList.addItemStackToList(new ItemStack(Items.DIAMOND)); ScrapboxList.addItemStackToList(new ItemStack(Items.STICK)); ScrapboxList.addItemStackToList(new ItemStack(Items.COAL)); ScrapboxList.addItemStackToList(new ItemStack(Items.APPLE)); ScrapboxList.addItemStackToList(new ItemStack(Items.BAKED_POTATO)); ScrapboxList.addItemStackToList(new ItemStack(Items.BLAZE_POWDER)); ScrapboxList.addItemStackToList(new ItemStack(Items.WHEAT)); ScrapboxList.addItemStackToList(new ItemStack(Items.CARROT)); ScrapboxList.addItemStackToList(new ItemStack(Items.BOAT)); ScrapboxList.addItemStackToList(new ItemStack(Items.ACACIA_BOAT)); ScrapboxList.addItemStackToList(new ItemStack(Items.BIRCH_BOAT)); ScrapboxList.addItemStackToList(new ItemStack(Items.DARK_OAK_BOAT)); ScrapboxList.addItemStackToList(new ItemStack(Items.JUNGLE_BOAT)); ScrapboxList.addItemStackToList(new ItemStack(Items.SPRUCE_BOAT)); ScrapboxList.addItemStackToList(new ItemStack(Items.BLAZE_ROD)); ScrapboxList.addItemStackToList(new ItemStack(Items.COMPASS)); ScrapboxList.addItemStackToList(new ItemStack(Items.MAP)); ScrapboxList.addItemStackToList(new ItemStack(Items.LEATHER_LEGGINGS)); ScrapboxList.addItemStackToList(new ItemStack(Items.BOW)); ScrapboxList.addItemStackToList(new ItemStack(Items.COOKED_CHICKEN)); ScrapboxList.addItemStackToList(new ItemStack(Items.CAKE)); ScrapboxList.addItemStackToList(new ItemStack(Items.ACACIA_DOOR)); ScrapboxList.addItemStackToList(new ItemStack(Items.DARK_OAK_DOOR)); ScrapboxList.addItemStackToList(new ItemStack(Items.BIRCH_DOOR)); ScrapboxList.addItemStackToList(new ItemStack(Items.JUNGLE_DOOR)); ScrapboxList.addItemStackToList(new ItemStack(Items.OAK_DOOR)); ScrapboxList.addItemStackToList(new ItemStack(Items.SPRUCE_DOOR)); ScrapboxList.addItemStackToList(new ItemStack(Items.WOODEN_AXE)); ScrapboxList.addItemStackToList(new ItemStack(Items.WOODEN_HOE)); ScrapboxList.addItemStackToList(new ItemStack(Items.WOODEN_PICKAXE)); ScrapboxList.addItemStackToList(new ItemStack(Items.WOODEN_SHOVEL)); ScrapboxList.addItemStackToList(new ItemStack(Items.WOODEN_SWORD)); ScrapboxList.addItemStackToList(new ItemStack(Items.BED)); ScrapboxList.addItemStackToList(new ItemStack(Items.SKULL, 1, 0)); ScrapboxList.addItemStackToList(new ItemStack(Items.SKULL, 1, 2)); ScrapboxList.addItemStackToList(new ItemStack(Items.SKULL, 1, 4)); for (int i = 0; i < StackWIPHandler.devHeads.size(); i++) ScrapboxList.addItemStackToList(StackWIPHandler.devHeads.get(i)); ScrapboxList.addItemStackToList(new ItemStack(Items.DYE, 1, 3)); ScrapboxList.addItemStackToList(new ItemStack(Items.GLOWSTONE_DUST)); ScrapboxList.addItemStackToList(new ItemStack(Items.STRING)); ScrapboxList.addItemStackToList(new ItemStack(Items.MINECART)); ScrapboxList.addItemStackToList(new ItemStack(Items.CHEST_MINECART)); ScrapboxList.addItemStackToList(new ItemStack(Items.HOPPER_MINECART)); ScrapboxList.addItemStackToList(new ItemStack(Items.PRISMARINE_SHARD)); ScrapboxList.addItemStackToList(new ItemStack(Items.SHEARS)); ScrapboxList.addItemStackToList(new ItemStack(Items.EXPERIENCE_BOTTLE)); ScrapboxList.addItemStackToList(new ItemStack(Items.BONE)); ScrapboxList.addItemStackToList(new ItemStack(Items.BOWL)); ScrapboxList.addItemStackToList(new ItemStack(Items.BRICK)); ScrapboxList.addItemStackToList(new ItemStack(Items.FISHING_ROD)); ScrapboxList.addItemStackToList(new ItemStack(Items.BOOK)); ScrapboxList.addItemStackToList(new ItemStack(Items.PAPER)); ScrapboxList.addItemStackToList(new ItemStack(Items.SUGAR)); ScrapboxList.addItemStackToList(new ItemStack(Items.REEDS)); ScrapboxList.addItemStackToList(new ItemStack(Items.SPIDER_EYE)); ScrapboxList.addItemStackToList(new ItemStack(Items.SLIME_BALL)); ScrapboxList.addItemStackToList(new ItemStack(Items.ROTTEN_FLESH)); ScrapboxList.addItemStackToList(new ItemStack(Items.SIGN)); ScrapboxList.addItemStackToList(new ItemStack(Items.WRITABLE_BOOK)); ScrapboxList.addItemStackToList(new ItemStack(Items.COOKED_BEEF)); ScrapboxList.addItemStackToList(new ItemStack(Items.NAME_TAG)); ScrapboxList.addItemStackToList(new ItemStack(Items.SADDLE)); ScrapboxList.addItemStackToList(new ItemStack(Items.REDSTONE)); ScrapboxList.addItemStackToList(new ItemStack(Items.GUNPOWDER)); ScrapboxList.addItemStackToList(new ItemStack(Items.RABBIT_HIDE)); ScrapboxList.addItemStackToList(new ItemStack(Items.RABBIT_FOOT)); ScrapboxList.addItemStackToList(new ItemStack(Items.APPLE)); ScrapboxList.addItemStackToList(new ItemStack(Items.GOLDEN_APPLE)); ScrapboxList.addItemStackToList(new ItemStack(Items.GOLD_NUGGET)); ScrapboxList.addItemStackToList(ItemCells.getCellByName("empty")); ScrapboxList.addItemStackToList(ItemCells.getCellByName("water")); ScrapboxList.addItemStackToList(ItemParts.getPartByName("scrap")); ScrapboxList.addItemStackToList(ItemParts.getPartByName("rubber")); ScrapboxList.addItemStackToList(new ItemStack(Blocks.TRAPDOOR)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.STONE_BUTTON)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.WOODEN_BUTTON)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.ACACIA_FENCE)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.ACACIA_FENCE_GATE)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.BIRCH_FENCE)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.BIRCH_FENCE_GATE)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.DARK_OAK_FENCE)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.DARK_OAK_FENCE_GATE)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.JUNGLE_FENCE)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.JUNGLE_FENCE_GATE)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.NETHER_BRICK_FENCE)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.OAK_FENCE)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.OAK_FENCE_GATE)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.SPRUCE_FENCE)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.SPRUCE_FENCE_GATE)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.BRICK_BLOCK)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.CRAFTING_TABLE)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.PUMPKIN)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.NETHERRACK)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.GRASS)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.DIRT, 1, 0)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.DIRT, 1, 1)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.SAND, 1, 0)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.SAND, 1, 1)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.GLOWSTONE)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.GRAVEL)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.HARDENED_CLAY)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.GLASS)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.GLASS_PANE)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.CACTUS)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.TALLGRASS, 1, 0)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.TALLGRASS, 1, 1)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.DEADBUSH)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.CHEST)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.TNT)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.RAIL)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.DETECTOR_RAIL)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.GOLDEN_RAIL)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.ACTIVATOR_RAIL)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.YELLOW_FLOWER)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.RED_FLOWER, 1, 0)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.RED_FLOWER, 1, 1)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.RED_FLOWER, 1, 2)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.RED_FLOWER, 1, 3)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.RED_FLOWER, 1, 4)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.RED_FLOWER, 1, 5)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.RED_FLOWER, 1, 6)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.RED_FLOWER, 1, 7)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.RED_FLOWER, 1, 8)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.BROWN_MUSHROOM)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.RED_MUSHROOM)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.BROWN_MUSHROOM_BLOCK)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.RED_MUSHROOM_BLOCK)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.SAPLING, 1, 0)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.SAPLING, 1, 1)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.SAPLING, 1, 2)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.SAPLING, 1, 3)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.SAPLING, 1, 4)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.SAPLING, 1, 5)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.LEAVES, 1, 0)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.LEAVES, 1, 1)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.LEAVES, 1, 2)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.LEAVES, 1, 3)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.LEAVES2, 1, 0)); ScrapboxList.addItemStackToList(new ItemStack(Blocks.LEAVES2, 1, 1)); ScrapboxList.addItemStackToList(new ItemStack(ModBlocks.rubberSapling)); for (String i : ItemDusts.types) { if (!i.equals(ModItems.META_PLACEHOLDER)) { ScrapboxList.addItemStackToList(ItemDusts.getDustByName(i)); } } for (String i : ItemNuggets.types) { if (!i.equals(ModItems.META_PLACEHOLDER)) { ScrapboxList.addItemStackToList(ItemNuggets.getNuggetByName(i)); } } for (String i : ItemGems.types) { if (!i.equals(ModItems.META_PLACEHOLDER)) { ScrapboxList.addItemStackToList(ItemGems.getGemByName(i)); } } registerDyable(Blocks.CARPET); registerDyable(Blocks.STAINED_GLASS); registerDyable(Blocks.STAINED_GLASS_PANE); registerDyable(Blocks.STAINED_HARDENED_CLAY); for (int i = 0; i < ScrapboxList.stacks.size(); i++) { RecipeHandler.addRecipe(new ScrapboxRecipe(ScrapboxList.stacks.get(i))); } boolean showAllItems = false; if (showAllItems) { //This is bad, laggy and slow List<Item> items = Lists .newArrayList(Iterables.filter(Item.REGISTRY, item -> item.getRegistryName() != null)); Collections.sort(items, (i1, i2) -> i1.getRegistryName().toString().compareTo(i2.getRegistryName().toString())); for (Item item : items) { List<ItemStack> stacks = new ArrayList<>(); if (item.getHasSubtypes()) { for (int i = 0; i < item.getMaxDamage(); i++) { stacks.add(new ItemStack(item, 1, i)); } } else { stacks.add(new ItemStack(item, 1, 0)); } for (ItemStack stack : stacks) { RecipeHandler.addRecipe(new RecyclerRecipe(stack)); } } } else { for (int i = 0; i < ScrapboxList.stacks.size(); i++) { RecipeHandler.addRecipe(new RecyclerRecipe(ScrapboxList.stacks.get(i))); } } } static void registerMetadataItem(ItemStack item) { for (int i = 0; i < item.getItem().getMaxDamage(); i++) { ScrapboxList.addItemStackToList(new ItemStack(item.getItem(), 1, i)); } } static void registerDyable(Block block) { for (int i = 0; i < 16; i++) ScrapboxList.stacks.add(new ItemStack(block, 1, i)); } static void addWireRecipes() { CraftingHelper.addShapedOreRecipe(ItemStandaloneCables.getCableByName("copper", 6), "CCC", 'C', "ingotCopper"); CraftingHelper.addShapedOreRecipe(ItemStandaloneCables.getCableByName("tin", 9), "CCC", 'C', "ingotTin"); CraftingHelper.addShapedOreRecipe(ItemStandaloneCables.getCableByName("gold", 12), "CCC", 'C', "ingotGold"); CraftingHelper .addShapedOreRecipe(ItemStandaloneCables.getCableByName("hv", 12), "CCC", 'C', "ingotRefinedIron"); CraftingHelper .addShapedOreRecipe(ItemStandaloneCables.getCableByName("glassfiber", 4), "GGG", "SDS", "GGG", 'G', "blockGlass", 'S', "dustRedstone", 'D', "diamondTR"); CraftingHelper .addShapedOreRecipe(ItemStandaloneCables.getCableByName("glassfiber", 6), "GGG", "SDS", "GGG", 'G', "blockGlass", 'S', "dustRedstone", 'D', "gemRuby"); CraftingHelper .addShapedOreRecipe(ItemStandaloneCables.getCableByName("glassfiber", 6), "GGG", "SDS", "GGG", 'G', "blockGlass", 'S', "ingotSilver", 'D', "diamondTR"); CraftingHelper .addShapedOreRecipe(ItemStandaloneCables.getCableByName("glassfiber", 8), "GGG", "SDS", "GGG", 'G', "blockGlass", 'S', "ingotElectrum", 'D', "diamondTR"); CraftingHelper.addShapelessOreRecipe(ItemStandaloneCables.getCableByName("insulatedcopper"), "materialRubber", ItemStandaloneCables.getCableByName("copper")); CraftingHelper.addShapelessOreRecipe(ItemStandaloneCables.getCableByName("insulatedgold"), "materialRubber", "materialRubber", ItemStandaloneCables.getCableByName("gold")); CraftingHelper.addShapelessOreRecipe(ItemStandaloneCables.getCableByName("insulatedhv"), "materialRubber", "materialRubber", ItemStandaloneCables.getCableByName("hv")); CraftingHelper .addShapedOreRecipe(ItemStandaloneCables.getCableByName("insulatedcopper", 6), "RRR", "III", "RRR", 'R', "materialRubber", 'I', "ingotCopper"); CraftingHelper .addShapedOreRecipe(ItemStandaloneCables.getCableByName("insulatedgold", 4), "RRR", "RIR", "RRR", 'R', "materialRubber", 'I', "ingotGold"); CraftingHelper .addShapedOreRecipe(ItemStandaloneCables.getCableByName("insulatedhv", 4), "RRR", "RIR", "RRR", 'R', "materialRubber", 'I', "ingotRefinedIron"); } private static void addCompressorRecipes() { RecipeHandler.addRecipe(new CompressorRecipe(ItemIngots.getIngotByName("advancedAlloy"), ItemPlates.getPlateByName("advancedAlloy"), 400, 20)); RecipeHandler.addRecipe( new CompressorRecipe(ItemParts.getPartByName("carbonmesh"), ItemPlates.getPlateByName("carbon"), 400, 2)); RecipeHandler.addRecipe( new CompressorRecipe(new ItemStack(Items.IRON_INGOT), ItemPlates.getPlateByName("iron"), 400, 2)); RecipeHandler.addRecipe( new CompressorRecipe(ItemIngots.getIngotByName("copper"), ItemPlates.getPlateByName("copper"), 400, 2)); RecipeHandler.addRecipe( new CompressorRecipe(ItemIngots.getIngotByName("tin"), ItemPlates.getPlateByName("tin"), 400, 2)); RecipeHandler.addRecipe( new CompressorRecipe(ItemIngots.getIngotByName("aluminum"), ItemPlates.getPlateByName("aluminum"), 400, 2)); RecipeHandler.addRecipe( new CompressorRecipe(ItemIngots.getIngotByName("brass"), ItemPlates.getPlateByName("brass"), 400, 2)); RecipeHandler.addRecipe( new CompressorRecipe(ItemIngots.getIngotByName("bronze"), ItemPlates.getPlateByName("bronze"), 400, 2)); RecipeHandler.addRecipe( new CompressorRecipe(ItemIngots.getIngotByName("lead"), ItemPlates.getPlateByName("lead"), 400, 2)); RecipeHandler.addRecipe( new CompressorRecipe(ItemIngots.getIngotByName("silver"), ItemPlates.getPlateByName("silver"), 400, 2)); } static void addExtractorRecipes() { RecipeHandler.addRecipe( new ExtractorRecipe(ItemParts.getPartByName("rubberSap"), ItemParts.getPartByName("rubber", 3), 400, 2)); RecipeHandler.addRecipe( new ExtractorRecipe(new ItemStack(ModBlocks.rubberLog), ItemParts.getPartByName("rubber"), 400, 2, true)); } static void addIc2ReplacementReicpes() { // TODO: Replace item pump with block /*CraftingHelper.addShapedOreRecipe(ItemParts.getPartByName("pump"), "CEC", "CMC", "PTP", 'C', ItemCells.getCellByName("empty"), 'T', new ItemStack(ModItems.treeTap), 'M', "machineBlockBasic", 'P', new ItemStack(Blocks.iron_bars), 'E', "circuitBasic"); // TODO: Replace item teleporter with block CraftingHelper .addShapedOreRecipe(ItemParts.getPartByName("teleporter"), "CTC", "WMW", "CDC", 'C', "circuitAdvanced", 'T', new ItemStack(ModItems.frequencyTransmitter), 'M', "machineBlockAdvanced", 'W', ItemStandaloneCables.getCableByName("glassfiber"), 'D', "gemDiamond", 'E', "circuitBasic"); */ } static void addGrinderRecipes() { // Vanilla int eutick = 2; int ticktime = 300; RecipeHandler.addRecipe(new GrinderRecipe( new ItemStack(Items.BONE), new ItemStack(Items.DYE, 6, 15), 170, 19)); RecipeHandler.addRecipe(new GrinderRecipe( new ItemStack(Blocks.COBBLESTONE), new ItemStack(Blocks.SAND), 230, 23)); RecipeHandler.addRecipe(new GrinderRecipe( new ItemStack(Blocks.GRAVEL), new ItemStack(Items.FLINT), 200, 20)); RecipeHandler.addRecipe(new GrinderRecipe( new ItemStack(Blocks.NETHERRACK), ItemDusts.getDustByName("netherrack"), 300, 27)); for (String oreDictionaryName : OreDictionary.getOreNames()) { if (isDictPrefixed(oreDictionaryName, "ore", "gem", "ingot")) { ItemStack oreStack = getDictOreOrNull(oreDictionaryName, 1); String[] data = getDictData(oreDictionaryName); //High-level ores shouldn't grind here if (data[0].equals("ore") && ( data[1].equals("tungsten") || data[1].equals("titanium") || data[1].equals("aluminium") || data[1].equals("iridium") || data[1].equals("saltpeter")) || oreStack == null) continue; boolean ore = data[0].equals("ore"); Core.logHelper.debug("Ore: " + data[1]); ItemStack dust = getDictOreOrNull(joinDictName("dust", data[1]), ore ? 2 : 1); if (dust == null || dust.getItem() == null) { continue; } dust = dust.copy(); if(ore){ dust.stackSize = 2; } RecipeHandler.addRecipe(new GrinderRecipe(oreStack, dust, ore ? 270 : 200, ore ? 31 : 22)); } } } static void addReactorRecipes() { FusionReactorRecipeHelper.registerRecipe( new FusionReactorRecipe(ItemCells.getCellByName("helium3"), ItemCells.getCellByName("deuterium"), ItemCells.getCellByName("heliumplasma"), 40000000, 32768, 1024)); FusionReactorRecipeHelper.registerRecipe( new FusionReactorRecipe(ItemCells.getCellByName("tritium"), ItemCells.getCellByName("deuterium"), ItemCells.getCellByName("helium3"), 60000000, 32768, 2048)); FusionReactorRecipeHelper.registerRecipe( new FusionReactorRecipe(ItemCells.getCellByName("wolframium"), ItemCells.getCellByName("Berylium"), ItemDusts.getDustByName("platinum"), 80000000, -2048, 1024)); FusionReactorRecipeHelper.registerRecipe( new FusionReactorRecipe(ItemCells.getCellByName("wolframium"), ItemCells.getCellByName("lithium"), BlockOre.getOreByName("iridium"), 90000000, -2048, 1024)); } static void addGeneralShapedRecipes() { // Storage Blocks for (String name : ArrayUtils.addAll(BlockStorage.types, BlockStorage2.types)) { CraftingHelper.addShapedOreRecipe(BlockStorage.getStorageBlockByName(name), "AAA", "AAA", "AAA", 'A', "ingot" + name.substring(0, 1).toUpperCase() + name.substring(1)); } CraftingHelper .addShapedOreRecipe(ItemCells.getCellByName("empty", 16, false), " T ", "T T", " T ", 'T', "ingotTin"); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.ironFence, 6), " ", "RRR", "RRR", 'R', ItemIngots.getIngotByName("refinedIron")); if (ConfigTechReborn.enableGemArmorAndTools) { addGemToolRecipes(new ItemStack(ModItems.rubySword), new ItemStack(ModItems.rubyPickaxe), new ItemStack(ModItems.rubyAxe), new ItemStack(ModItems.rubyHoe), new ItemStack(ModItems.rubySpade), new ItemStack(ModItems.rubyHelmet), new ItemStack(ModItems.rubyChestplate), new ItemStack(ModItems.rubyLeggings), new ItemStack(ModItems.rubyBoots), "gemRuby"); addGemToolRecipes(new ItemStack(ModItems.sapphireSword), new ItemStack(ModItems.sapphirePickaxe), new ItemStack(ModItems.sapphireAxe), new ItemStack(ModItems.sapphireHoe), new ItemStack(ModItems.sapphireSpade), new ItemStack(ModItems.sapphireHelmet), new ItemStack(ModItems.sapphireChestplate), new ItemStack(ModItems.sapphireLeggings), new ItemStack(ModItems.sapphireBoots), "gemSapphire"); addGemToolRecipes(new ItemStack(ModItems.peridotSword), new ItemStack(ModItems.peridotPickaxe), new ItemStack(ModItems.peridotAxe), new ItemStack(ModItems.peridotHoe), new ItemStack(ModItems.peridotSpade), new ItemStack(ModItems.peridotHelmet), new ItemStack(ModItems.peridotChestplate), new ItemStack(ModItems.peridotLeggings), new ItemStack(ModItems.peridotBoots), "gemPeridot"); addGemToolRecipes(new ItemStack(ModItems.bronzeSword), new ItemStack(ModItems.bronzePickaxe), new ItemStack(ModItems.bronzeAxe), new ItemStack(ModItems.bronzeHoe), new ItemStack(ModItems.bronzeSpade), new ItemStack(ModItems.bronzeHelmet), new ItemStack(ModItems.bronzeChestplate), new ItemStack(ModItems.bronzeLeggings), new ItemStack(ModItems.bronzeBoots), "ingotBronze"); } CraftingHelper .addShapedOreRecipe(new ItemStack(ModItems.ironChainsaw), " SS", "SCS", "BS ", 'S', "ingotSteel", 'B', "reBattery", 'C', "circuitBasic"); CraftingHelper .addShapedOreRecipe(new ItemStack(ModItems.diamondChainsaw), " DD", "TBD", "CT ", 'T', "ingotTitanium", 'B', ironChainsawStack, 'C', "circuitAdvanced", 'D', "diamondTR"); CraftingHelper .addShapedOreRecipe(new ItemStack(ModItems.steelJackhammer), "SBS", "SCS", " S ", 'S', "ingotSteel", 'B', "reBattery", 'C', "circuitBasic"); CraftingHelper.addShapedOreRecipe(new ItemStack(ModItems.diamondJackhammer), "DCD", "TBT", " D ", 'T', "ingotTitanium", 'B', steelJackhammerStack, 'C', "circuitAdvanced", 'D', "diamondTR"); CraftingHelper.addShapelessOreRecipe(ItemParts.getPartByName("carbonfiber"), ItemDusts.getDustByName("coal"), ItemDusts.getDustByName("coal"), ItemDusts.getDustByName("coal"), ItemDusts.getDustByName("coal")); CraftingHelper.addShapelessOreRecipe(ItemParts.getPartByName("carbonfiber"), ItemCells.getCellByName("carbon"), ItemCells.getCellByName("carbon"), ItemCells.getCellByName("carbon"), ItemCells.getCellByName("carbon"), ItemCells.getCellByName("carbon"), ItemCells.getCellByName("carbon"), ItemCells.getCellByName("carbon"), ItemCells.getCellByName("carbon"), ItemCells.getCellByName("carbon")); CraftingHelper .addShapelessOreRecipe(ItemParts.getPartByName("carbonmesh"), ItemParts.getPartByName("carbonfiber"), ItemParts.getPartByName("carbonfiber")); CraftingHelper .addShapedOreRecipe(ItemParts.getPartByName("computerMonitor"), "ADA", "DGD", "ADA", 'D', dyes, 'A', "ingotAluminum", 'G', Blocks.GLASS_PANE); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.reinforcedglass, 7), "GAG", "GGG", "GAG", 'A', ItemIngots.getIngotByName("advancedAlloy"), 'G', Blocks.GLASS); CraftingHelper .addShapedOreRecipe(new ItemStack(ModBlocks.windMill, 2), "IXI", "XGX", "IXI", 'I', "ingotIron", 'G', ModBlocks.Generator); CraftingHelper .addShapedOreRecipe(new ItemStack(ModBlocks.waterMill), "SWS", "WGW", "SWS", 'S', Items.STICK, 'W', "plankWood", 'G', ModBlocks.Generator); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.hvt), "XHX", "XMX", "XHX", 'M', ModBlocks.mvt, 'H', ItemStandaloneCables.getCableByName("insulatedhv")); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.mvt), "XGX", "XMX", "XGX", 'M', BlockMachineFrame.getFrameByName("machine", 1), 'G', ItemStandaloneCables.getCableByName("insulatedgold")); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.lvt), "PWP", "CCC", "PPP", 'P', "plankWood", 'C', "ingotCopper", 'W', ItemStandaloneCables.getCableByName("insulatedcopper")); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.MachineCasing, 4, 0), "RRR", "CAC", "RRR", 'R', ItemIngots.getIngotByName("refinedIron"), 'C', "circuitBasic", 'A', BlockMachineFrame.getFrameByName("machine", 1)); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.MachineCasing, 4, 1), "RRR", "CAC", "RRR", 'R', "ingotSteel", 'C', "circuitAdvanced", 'A', BlockMachineFrame.getFrameByName("advancedMachine", 1)); CraftingHelper.addShapedOreRecipe(ItemParts.getPartByName("dataOrb"), "DDD", "DID", "DDD", 'D', "circuitData", 'I', "circuitElite"); CraftingHelper.addShapedOreRecipe(ItemParts.getPartByName("dataControlCircuit", 4), "CDC", "DID", "CDC", 'I', ItemPlates.getPlateByName("iridium"), 'D', "circuitData", 'C', "circuitAdvanced"); CraftingHelper .addShapedOreRecipe(new ItemStack(ModBlocks.thermalGenerator), "III", "IRI", "CGC", 'I', "ingotInvar", 'R', ModBlocks.reinforcedglass, 'G', ModBlocks.Generator, 'C', "circuitBasic"); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.recycler), "XEX", "DCD", "GDG", 'D', Blocks.DIRT, 'C', ModBlocks.Compressor, 'G', Items.GLOWSTONE_DUST, 'E', "circuitBasic"); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.batBox), "WCW", "BBB", "WWW", 'W', "plankWood", 'B', batteryStack, 'C', ItemStandaloneCables.getCableByName("insulatedcopper")); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.mfe), "GEG", "EME", "GEG", 'M', BlockMachineFrame.getFrameByName("machine", 1), 'E', crystalStack, 'G', ItemStandaloneCables.getCableByName("insulatedgold")); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.mfsu), "LAL", "LML", "LOL", 'A', "circuitAdvanced", 'L', lapcrystalStack, 'M', new ItemStack(ModBlocks.mfe), 'O', BlockMachineFrame.getFrameByName("advancedMachine", 1)); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.IndustrialElectrolyzer), "RER", "CEC", "RER", 'R', ItemIngots.getIngotByName("refinediron"), 'E', new ItemStack(ModBlocks.Extractor), 'C', "circuitAdvanced"); // Mixed Metal Ingot Recipes :P CraftingHelper.addShapedOreRecipe(ItemIngots.getIngotByName("mixedmetal", 2), "RRR", "BBB", "TTT", 'R', "ingotRefinedIron", 'B', "ingotBronze", 'T', "ingotTin"); CraftingHelper.addShapedOreRecipe(ItemIngots.getIngotByName("mixedmetal", 2), "RRR", "BBB", "TTT", 'R', "ingotRefinedIron", 'B', "ingotBronze", 'T', "ingotZinc"); CraftingHelper.addShapedOreRecipe(ItemIngots.getIngotByName("mixedmetal", 2), "RRR", "BBB", "TTT", 'R', "ingotRefinedIron", 'B', "ingotBrass", 'T', "ingotTin"); CraftingHelper.addShapedOreRecipe(ItemIngots.getIngotByName("mixedmetal", 2), "RRR", "BBB", "TTT", 'R', "ingotRefinedIron", 'B', "ingotBrass", 'T', "ingotZinc"); CraftingHelper .addShapedOreRecipe(ItemIngots.getIngotByName("mixedmetal", 3), "RRR", "BBB", "TTT", 'R', "ingotNickel", 'B', "ingotBronze", 'T', "ingotTin"); CraftingHelper .addShapedOreRecipe(ItemIngots.getIngotByName("mixedmetal", 3), "RRR", "BBB", "TTT", 'R', "ingotNickel", 'B', "ingotBronze", 'T', "ingotZinc"); CraftingHelper .addShapedOreRecipe(ItemIngots.getIngotByName("mixedmetal", 3), "RRR", "BBB", "TTT", 'R', "ingotNickel", 'B', "ingotBrass", 'T', "ingotTin"); CraftingHelper .addShapedOreRecipe(ItemIngots.getIngotByName("mixedmetal", 3), "RRR", "BBB", "TTT", 'R', "ingotNickel", 'B', "ingotBrass", 'T', "ingotZinc"); CraftingHelper .addShapedOreRecipe(ItemIngots.getIngotByName("mixedmetal", 4), "RRR", "BBB", "TTT", 'R', "ingotNickel", 'B', "ingotBronze", 'T', "ingotAluminum"); CraftingHelper .addShapedOreRecipe(ItemIngots.getIngotByName("mixedmetal", 4), "RRR", "BBB", "TTT", 'R', "ingotNickel", 'B', "ingotBrass", 'T', "ingotAluminum"); CraftingHelper .addShapedOreRecipe(ItemIngots.getIngotByName("mixedmetal", 4), "RRR", "BBB", "TTT", 'R', "ingotInvar", 'B', "ingotBronze", 'T', "ingotTin"); CraftingHelper .addShapedOreRecipe(ItemIngots.getIngotByName("mixedmetal", 4), "RRR", "BBB", "TTT", 'R', "ingotInvar", 'B', "ingotBronze", 'T', "ingotZinc"); CraftingHelper .addShapedOreRecipe(ItemIngots.getIngotByName("mixedmetal", 4), "RRR", "BBB", "TTT", 'R', "ingotInvar", 'B', "ingotBrass", 'T', "ingotTin"); CraftingHelper .addShapedOreRecipe(ItemIngots.getIngotByName("mixedmetal", 4), "RRR", "BBB", "TTT", 'R', "ingotInvar", 'B', "ingotBrass", 'T', "ingotZinc"); CraftingHelper .addShapedOreRecipe(ItemIngots.getIngotByName("mixedmetal", 5), "RRR", "BBB", "TTT", 'R', "ingotInvar", 'B', "ingotBronze", 'T', "ingotAluminum"); CraftingHelper .addShapedOreRecipe(ItemIngots.getIngotByName("mixedmetal", 5), "RRR", "BBB", "TTT", 'R', "ingotInvar", 'B', "ingotBrass", 'T', "ingotAluminum"); CraftingHelper.addShapedOreRecipe(ItemIngots.getIngotByName("mixedmetal", 5), "RRR", "BBB", "TTT", 'R', "ingotTitanium", 'B', "ingotBronze", 'T', "ingotTin"); CraftingHelper.addShapedOreRecipe(ItemIngots.getIngotByName("mixedmetal", 5), "RRR", "BBB", "TTT", 'R', "ingotTitanium", 'B', "ingotBronze", 'T', "ingotZinc"); CraftingHelper.addShapedOreRecipe(ItemIngots.getIngotByName("mixedmetal", 5), "RRR", "BBB", "TTT", 'R', "ingotTitanium", 'B', "ingotBrass", 'T', "ingotTin"); CraftingHelper.addShapedOreRecipe(ItemIngots.getIngotByName("mixedmetal", 5), "RRR", "BBB", "TTT", 'R', "ingotTitanium", 'B', "ingotBrass", 'T', "ingotZinc"); CraftingHelper.addShapedOreRecipe(ItemIngots.getIngotByName("mixedmetal", 6), "RRR", "BBB", "TTT", 'R', "ingotTitanium", 'B', "ingotBronze", 'T', "ingotAluminum"); CraftingHelper.addShapedOreRecipe(ItemIngots.getIngotByName("mixedmetal", 6), "RRR", "BBB", "TTT", 'R', "ingotTitanium", 'B', "ingotBrass", 'T', "ingotAluminum"); CraftingHelper.addShapedOreRecipe(ItemIngots.getIngotByName("mixedmetal", 5), "RRR", "BBB", "TTT", 'R', "ingotTungsten", 'B', "ingotBronze", 'T', "ingotTin"); CraftingHelper.addShapedOreRecipe(ItemIngots.getIngotByName("mixedmetal", 5), "RRR", "BBB", "TTT", 'R', "ingotTungsten", 'B', "ingotBronze", 'T', "ingotZinc"); CraftingHelper.addShapedOreRecipe(ItemIngots.getIngotByName("mixedmetal", 5), "RRR", "BBB", "TTT", 'R', "ingotTungsten", 'B', "ingotBrass", 'T', "ingotTin"); CraftingHelper.addShapedOreRecipe(ItemIngots.getIngotByName("mixedmetal", 5), "RRR", "BBB", "TTT", 'R', "ingotTungsten", 'B', "ingotBrass", 'T', "ingotZinc"); CraftingHelper.addShapedOreRecipe(ItemIngots.getIngotByName("mixedmetal", 6), "RRR", "BBB", "TTT", 'R', "ingotTungsten", 'B', "ingotBronze", 'T', "ingotAluminum"); CraftingHelper.addShapedOreRecipe(ItemIngots.getIngotByName("mixedmetal", 6), "RRR", "BBB", "TTT", 'R', "ingotTungsten", 'B', "ingotBrass", 'T', "ingotAluminum"); CraftingHelper.addShapedOreRecipe(ItemIngots.getIngotByName("mixedmetal", 8), "RRR", "BBB", "TTT", 'R', "ingotTungstensteel", 'B', "ingotBronze", 'T', "ingotTin"); CraftingHelper.addShapedOreRecipe(ItemIngots.getIngotByName("mixedmetal", 8), "RRR", "BBB", "TTT", 'R', "ingotTungstensteel", 'B', "ingotBronze", 'T', "ingotZinc"); CraftingHelper.addShapedOreRecipe(ItemIngots.getIngotByName("mixedmetal", 8), "RRR", "BBB", "TTT", 'R', "ingotTungstensteel", 'B', "ingotBrass", 'T', "ingotTin"); CraftingHelper.addShapedOreRecipe(ItemIngots.getIngotByName("mixedmetal", 8), "RRR", "BBB", "TTT", 'R', "ingotTungstensteel", 'B', "ingotBrass", 'T', "ingotZinc"); CraftingHelper.addShapedOreRecipe(ItemIngots.getIngotByName("mixedmetal", 9), "RRR", "BBB", "TTT", 'R', "ingotTungstensteel", 'B', "ingotBronze", 'T', "ingotAluminum"); CraftingHelper.addShapedOreRecipe(ItemIngots.getIngotByName("mixedmetal", 9), "RRR", "BBB", "TTT", 'R', "ingotTungstensteel", 'B', "ingotBrass", 'T', "ingotAluminum"); CraftingHelper .addShapedOreRecipe(new ItemStack(ModBlocks.Compressor), "SXS", "SCS", "SMS", 'C', "circuitBasic", 'M', BlockMachineFrame.getFrameByName("machine", 1), 'S', Blocks.STONE); CraftingHelper .addShapedOreRecipe(new ItemStack(ModBlocks.ElectricFurnace), "XCX", "RFR", "XXX", 'C', "circuitBasic", 'F', new ItemStack(ModBlocks.ironFurnace), 'R', Items.REDSTONE); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.ironFurnace), "III", "IXI", "III", 'I', "ingotIron"); CraftingHelper .addShapedOreRecipe(new ItemStack(ModBlocks.ironFurnace), "XIX", "IXI", "IFI", 'I', "ingotIron", 'F', Blocks.FURNACE); CraftingHelper.addShapedOreRecipe(ItemParts.getPartByName("electronicCircuit"), "WWW", "SRS", "WWW", 'R', "ingotRefinedIron", 'S', Items.REDSTONE, 'W', ItemStandaloneCables.getCableByName("insulatedcopper")); CraftingHelper.addShapedOreRecipe(new ItemStack(ModItems.reBattery), "XWX", "TRT", "TRT", 'T', "ingotTin", 'R', Items.REDSTONE, 'W', ItemStandaloneCables.getCableByName("insulatedcopper")); CraftingHelper.addShapedOreRecipe(new ItemStack(ModItems.wrench), "BAB", "BBB", "ABA", 'B', "ingotBronze"); CraftingHelper .addShapedOreRecipe(new ItemStack(ModBlocks.Extractor), "TMT", "TCT", "XXX", 'T', ModItems.treeTap, 'M', BlockMachineFrame.getFrameByName("machine", 1), 'C', "circuitBasic"); CraftingHelper .addShapedOreRecipe(new ItemStack(ModBlocks.centrifuge), "RCR", "AEA", "RCR", 'R', "ingotRefinedIron", 'E', new ItemStack(ModBlocks.Extractor), 'A', "machineBlockAdvanced", 'C', "circuitBasic"); CraftingHelper.addShapedOreRecipe(ItemParts.getPartByName("advancedCircuit"), "RGR", "LCL", "RGR", 'R', Items.REDSTONE, 'G', Items.GLOWSTONE_DUST, 'L', "dyeBlue", 'C', "circuitBasic"); CraftingHelper .addShapedOreRecipe(new ItemStack(ModItems.energyCrystal), "RRR", "RDR", "RRR", 'R', Items.REDSTONE, 'D', Items.DIAMOND); CraftingHelper .addShapedOreRecipe(new ItemStack(ModItems.lapotronCrystal), "LCL", "LEL", "LCL", 'L', "dyeBlue", 'E', "energyCrystal", 'C', "circuitBasic"); CraftingHelper.addShapelessOreRecipe(new ItemStack(ModBlocks.Generator), batteryStack, BlockMachineFrame.getFrameByName("machine", 1), Blocks.FURNACE); CraftingHelper.addShapedOreRecipe(BlockMachineFrame.getFrameByName("machine", 1), "AAA", "AXA", "AAA", 'A', ItemIngots.getIngotByName("refinediron")); CraftingHelper .addShapedOreRecipe(BlockMachineFrame.getFrameByName("advancedMachine", 1), "XCX", "AMA", "XCX", 'A', ItemIngots.getIngotByName("advancedAlloy"), 'C', ItemPlates.getPlateByName("carbon"), 'M', BlockMachineFrame.getFrameByName("machine", 1)); CraftingHelper.addShapedOreRecipe(ItemParts.getPartByName("dataStorageCircuit", 8), "EEE", "ECE", "EEE", 'E', new ItemStack(Items.EMERALD), 'C', "circuitBasic"); CraftingHelper .addShapedOreRecipe(new ItemStack(ModItems.parts, 4, 8), "DSD", "S S", "DSD", 'D', "dustDiamond", 'S', "ingotSteel"); CraftingHelper .addShapedOreRecipe(new ItemStack(ModItems.parts, 1, 15), "AAA", "AMA", "AAA", 'A', "ingotAluminium", 'M', new ItemStack(ModItems.parts, 1, 13)); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.Supercondensator), "EOE", "SAS", "EOE", 'E', "circuitMaster", 'O', ModItems.lapotronicOrb, 'S', ItemParts.getPartByName("superconductor"), 'A', BlockMachineFrame.getFrameByName("highlyAdvancedMachine", 1)); CraftingHelper .addShapedOreRecipe(ItemParts.getPartByName("diamondSawBlade"), "DSD", "S S", "DSD", 'S', "plateSteel", 'D', "dustDiamond"); CraftingHelper.addShapedOreRecipe(ItemParts.getPartByName("tungstenGrindingHead", 2), "TST", "SBS", "TST", 'T', "plateTungsten", 'S', "plateSteel", 'B', "blockSteel"); /* TODO: Make destructopack seperate item CraftingHelper.addShapedOreRecipe(ItemParts.getPartByName("destructoPack"), "CIC", "IBI", "CIC", 'C', "circuitAdvanced", 'I', "ingotAluminum", 'B', new ItemStack(Items.lava_bucket)); CraftingHelper.addShapedOreRecipe(ItemParts.getPartByName("destructoPack"), "CIC", "IBI", "CIC", 'C', "circuitAdvanced", 'I', "ingotRefinedIron", 'B', new ItemStack(Items.lava_bucket)); */ CraftingHelper .addShapedOreRecipe(new ItemStack(ModItems.cloakingDevice), "CIC", "IOI", "CIC", 'C', "ingotChrome", 'I', "plateIridium", 'O', new ItemStack(ModItems.lapotronicOrb)); CraftingHelper.addShapedOreRecipe(new ItemStack(ModItems.treeTap), " S ", "PPP", "P ", 'S', "stickWood", 'P', "plankWood"); CraftingHelper .addShapedOreRecipe(new ItemStack(ModItems.rockCutter), "DT ", "DT ", "DCB", 'D', "dustDiamond", 'T', "ingotTitanium", 'C', "circuitBasic", 'B', batteryStack); for (String part : ItemParts.types) { if (part.endsWith("Gear")) { CraftingHelper.addShapedOreRecipe(ItemParts.getPartByName(part), " O ", "OIO", " O ", 'I', new ItemStack(Items.IRON_INGOT), 'O', "ingot" + StringUtils.toFirstCapital(part.replace("Gear", ""))); } } CraftingHelper.addShapedOreRecipe(ItemParts.getPartByName("nichromeHeatingCoil"), " N ", "NCN", " N ", 'N', "ingotNickel", 'C', "ingotChrome"); CraftingHelper.addShapedOreRecipe(ItemParts.getPartByName("kanthalHeatingCoil"), "III", "CAA", "AAA", 'I', "ingotSteel", 'C', "ingotChrome", 'A', "ingotAluminum"); CraftingHelper.addShapedOreRecipe(ItemParts.getPartByName("heliumCoolantSimple"), " T ", "TCT", " T ", 'T', "ingotTin", 'C', ItemCells.getCellByName("helium", 1, false)); CraftingHelper.addShapedOreRecipe(ItemParts.getPartByName("HeliumCoolantTriple"), "TTT", "CCC", "TTT", 'T', "ingotTin", 'C', ItemParts.getPartByName("heliumCoolantSimple")); CraftingHelper .addShapedOreRecipe(ItemParts.getPartByName("HeliumCoolantSix"), "THT", "TCT", "THT", 'T', "ingotTin", 'C', "ingotCopper", 'H', ItemParts.getPartByName("HeliumCoolantTriple")); CraftingHelper .addShapedOreRecipe(ItemParts.getPartByName("NaKCoolantTriple"), "TTT", "CCC", "TTT", 'T', "ingotTin", 'C', ItemParts.getPartByName("NaKCoolantSimple")); CraftingHelper .addShapedOreRecipe(ItemParts.getPartByName("NaKCoolantSix"), "THT", "TCT", "THT", 'T', "ingotTin", 'C', "ingotCopper", 'H', ItemParts.getPartByName("NaKCoolantTriple")); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.Aesu), "LLL", "LCL", "LLL", 'L', new ItemStack(ModItems.lapotronicOrb), 'C', new ItemStack(ModBlocks.ComputerCube)); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.Idsu), "PAP", "ACA", "PAP", 'P', ItemPlates.getPlateByName("iridium"), 'C', new ItemStack(Blocks.ENDER_CHEST), 'A', new ItemStack(ModBlocks.Aesu)); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.FusionControlComputer), "CCC", "PTP", "CCC", 'P', new ItemStack(ModBlocks.ComputerCube), 'T', new ItemStack(ModBlocks.FusionCoil), 'C', "circuitMaster"); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.LightningRod), "CAC", "ACA", "CAC", 'A', new ItemStack(ModBlocks.MachineCasing, 1, 2), 'S', ItemParts.getPartByName("superConductor"), 'C', "circuitMaster"); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.FusionCoil), "CSC", "NAN", "CRC", 'A', new ItemStack(ModBlocks.MachineCasing, 1, 2), 'N', ItemParts.getPartByName("nichromeHeatingCoil"), 'C', "circuitMaster", 'S', ItemParts.getPartByName("superConductor"), 'R', ItemParts.getPartByName("iridiumNeutronReflector")); CraftingHelper.addShapedOreRecipe(ItemParts.getPartByName("iridiumNeutronReflector"), "PPP", "PIP", "PPP", 'P', ItemParts.getPartByName("thickNeutronReflector"), 'I', "ingotIridium"); CraftingHelper.addShapedOreRecipe(ItemParts.getPartByName("thickNeutronReflector"), " P ", "PCP", " P ", 'P', ItemParts.getPartByName("neutronReflector"), 'C', ItemCells.getCellByName("Berylium")); CraftingHelper .addShapedOreRecipe(ItemParts.getPartByName("neutronReflector"), "TCT", "CPC", "TCT", 'T', "dustTin", 'C', "dustCoal", 'P', "plateCopper"); CraftingHelper.addShapedOreRecipe(new ItemStack(ModItems.scrapBox), "SSS", "SSS", "SSS", 'S', ItemParts.getPartByName("scrap")); CraftingHelper.addShapedOreRecipe(ItemUpgrades.getUpgradeByName("Overclock"), "TTT", "WCW", 'T', ItemParts.getPartByName("CoolantSimple"), 'W', ItemStandaloneCables.getCableByName("insulatedcopper"), 'C', "circuitBasic"); CraftingHelper.addShapedOreRecipe(ItemUpgrades.getUpgradeByName("Overclock", 2), " T ", "WCW", 'T', ItemParts.getPartByName("heliumCoolantSimple"), 'W', ItemStandaloneCables.getCableByName("insulatedcopper"), 'C', "circuitBasic"); CraftingHelper.addShapedOreRecipe(ItemUpgrades.getUpgradeByName("Overclock", 2), " T ", "WCW", 'T', ItemParts.getPartByName("NaKCoolantSimple"), 'W', ItemStandaloneCables.getCableByName("insulatedcopper"), 'C', "circuitBasic"); CraftingHelper.addShapedOreRecipe(ItemUpgrades.getUpgradeByName("Transformer"), "GGG", "WTW", "GCG", 'G', "blockGlass", 'W', ItemStandaloneCables.getCableByName("insulatedgold"), 'C', "circuitBasic", 'T', ModBlocks.mvt); CraftingHelper.addShapedOreRecipe(ItemUpgrades.getUpgradeByName("EnergyStorage"), "PPP", "WBW", "PCP", 'P', "plankWood", 'W', ItemStandaloneCables.getCableByName("insulatedcopper"), 'C', "circuitBasic", 'B', ModItems.reBattery); CraftingHelper .addShapedOreRecipe(ItemParts.getPartByName("CoolantSimple"), " T ", "TWT", " T ", 'T', "ingotTin", 'W', "containerWater"); CraftingHelper .addShapedOreRecipe(ItemParts.getPartByName("CoolantTriple"), "TTT", "CCC", "TTT", 'T', "ingotTin", 'C', ItemParts.getPartByName("CoolantSimple")); CraftingHelper .addShapedOreRecipe(ItemParts.getPartByName("CoolantSix"), "TCT", "TPT", "TCT", 'T', "ingotTin", 'C', ItemParts.getPartByName("CoolantTriple"), 'P', ItemPlates.getPlateByName("copper")); CraftingHelper .addShapedOreRecipe(ItemParts.getPartByName("NaKCoolantSimple"), "TST", "PCP", "TST", 'T', "ingotTin", 'C', ItemParts.getPartByName("CoolantSimple"), 'S', ItemCells.getCellByName("sodium"), 'P', ItemCells.getCellByName("potassium")); CraftingHelper .addShapedOreRecipe(ItemParts.getPartByName("NaKCoolantSimple"), "TPT", "SCS", "TPT", 'T', "ingotTin", 'C', ItemParts.getPartByName("CoolantSimple"), 'S', ItemCells.getCellByName("sodium"), 'P', ItemCells.getCellByName("potassium")); CraftingHelper.addShapedOreRecipe(new ItemStack(ModItems.advancedDrill), "ODO", "AOA", 'O', ItemUpgrades.getUpgradeByName("Overclock"), 'D', diamondDrillStack, 'A', "circuitAdvanced"); CraftingHelper.addShapedOreRecipe(new ItemStack(ModItems.advancedChainsaw), "ODO", "AOA", 'O', ItemUpgrades.getUpgradeByName("Overclock"), 'D', diamondChainsawStack, 'A', "circuitAdvanced"); CraftingHelper.addShapedOreRecipe(new ItemStack(ModItems.advancedJackhammer), "ODO", "AOA", 'O', ItemUpgrades.getUpgradeByName("Overclock"), 'D', diamondJackhammerStack, 'A', "circuitAdvanced"); CraftingHelper .addShapedOreRecipe(ItemParts.getPartByName("dataControlCircuit"), "ADA", "DID", "ADA", 'I', "ingotIridium", 'A', ItemParts.getPartByName("advancedCircuit"), 'D', ItemParts.getPartByName("dataStorageCircuit")); CraftingHelper .addShapedOreRecipe(ItemParts.getPartByName("dataOrb"), "DDD", "DSD", "DDD", 'D', ItemParts.getPartByName("dataStorageCircuit"), 'S', ItemParts.getPartByName("dataStorageCircuit")); Core.logHelper.info("Shapped Recipes Added"); } static void addShapelessRecipes() { for (String name : ArrayUtils.addAll(BlockStorage.types, BlockStorage2.types)) { ItemStack item = null; try { item = ItemIngots.getIngotByName(name, 9); } catch (InvalidParameterException e) { try { item = ItemGems.getGemByName(name, 9); } catch (InvalidParameterException e2) { continue; } } if (item == null) { continue; } CraftingHelper .addShapelessRecipe(BlockStorage.getStorageBlockByName(name), item, item, item, item, item, item, item, item, item); CraftingHelper.addShapelessRecipe(item, BlockStorage.getStorageBlockByName(name, 9)); } CraftingHelper.addShapelessRecipe(new ItemStack(ModBlocks.rubberPlanks, 4), ModBlocks.rubberLog); CraftingHelper.addShapelessOreRecipe(new ItemStack(ModItems.frequencyTransmitter), ItemStandaloneCables.getCableByName("insulatedcopper"), "circuitBasic"); for (String name : ItemDustsSmall.types) { if (name.equals(ModItems.META_PLACEHOLDER)) { continue; } CraftingHelper .addShapelessRecipe(ItemDustsSmall.getSmallDustByName(name, 4), ItemDusts.getDustByName(name)); CraftingHelper.addShapelessRecipe(ItemDusts.getDustByName(name, 1), ItemDustsSmall.getSmallDustByName(name), ItemDustsSmall.getSmallDustByName(name), ItemDustsSmall.getSmallDustByName(name), ItemDustsSmall.getSmallDustByName(name)); } Core.logHelper.info("Shapeless Recipes Added"); } static void addMachineRecipes() { if (!CompatManager.isQuantumStorageLoaded) { CraftingHelper .addShapedOreRecipe(new ItemStack(ModBlocks.quantumTank), "EPE", "PCP", "EPE", 'P', "ingotPlatinum", 'E', "circuitAdvanced", 'C', ModBlocks.quantumChest); } CraftingHelper .addShapedOreRecipe(new ItemStack(ModBlocks.digitalChest), "PPP", "PDP", "PCP", 'P', "plateAluminum", 'D', ItemParts.getPartByName("dataOrb"), 'C', ItemParts.getPartByName("computerMonitor")); CraftingHelper .addShapedOreRecipe(new ItemStack(ModBlocks.digitalChest), "PPP", "PDP", "PCP", 'P', "plateSteel", 'D', ItemParts.getPartByName("dataOrb"), 'C', ItemParts.getPartByName("computerMonitor")); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.AlloySmelter), "XCX", "FMF", "XXX", 'C', "circuitBasic", 'F', new ItemStack(ModBlocks.ElectricFurnace), 'M', BlockMachineFrame.getFrameByName("machine", 1)); CraftingHelper .addShapedOreRecipe(new ItemStack(ModBlocks.LesuStorage), "LLL", "LCL", "LLL", 'L', "blockLapis", 'C', "circuitBasic"); TechRebornAPI .addRollingOreMachinceRecipe(ItemParts.getPartByName("cupronickelHeatingCoil"), "NCN", "C C", "NCN", 'N', "ingotCupronickel", 'C', "ingotCopper"); RecipeHandler.addRecipe(new VacuumFreezerRecipe(ItemIngots.getIngotByName("hotTungstensteel"), ItemIngots.getIngotByName("tungstensteel"), 440, 128)); RecipeHandler.addRecipe(new VacuumFreezerRecipe(ItemCells.getCellByName("heliumplasma"), ItemCells.getCellByName("helium"), 440, 128)); RecipeHandler.addRecipe( new VacuumFreezerRecipe(ItemCells.getCellByName("water"), ItemCells.getCellByName("cell"), 60, 128)); } static void addVacuumFreezerRecipes() { RecipeHandler.addRecipe(new VacuumFreezerRecipe( new ItemStack(Blocks.ICE, 2), new ItemStack(Blocks.PACKED_ICE), 60, 100 )); RecipeHandler.addRecipe(new VacuumFreezerRecipe( ItemIngots.getIngotByName("hotTungstensteel"), ItemIngots.getIngotByName("tungstensteel"), 440, 120)); RecipeHandler.addRecipe(new VacuumFreezerRecipe( ItemCells.getCellByName("heliumplasma"), ItemCells.getCellByName("helium"), 440, 128)); RecipeHandler.addRecipe( new VacuumFreezerRecipe( ItemCells.getCellByName("water"), ItemCells.getCellByName("cell"), 60, 87)); } static void addSmeltingRecipes() { CraftingHelper.addSmelting(ItemDusts.getDustByName("iron", 1), new ItemStack(Items.IRON_INGOT), 1F); CraftingHelper.addSmelting(ItemDusts.getDustByName("gold", 1), new ItemStack(Items.GOLD_INGOT), 1F); CraftingHelper.addSmelting(ItemParts.getPartByName("rubberSap"), ItemParts.getPartByName("rubber"), 1F); CraftingHelper.addSmelting(new ItemStack(Items.IRON_INGOT), ItemIngots.getIngotByName("refinediron"), 1F); CraftingHelper.addSmelting(BlockOre2.getOreByName("copper"), ItemIngots.getIngotByName("copper"), 1F); CraftingHelper.addSmelting(BlockOre2.getOreByName("tin"), ItemIngots.getIngotByName("tin"), 1F); CraftingHelper.addSmelting(BlockOre.getOreByName("Silver"), ItemIngots.getIngotByName("silver"), 1F); CraftingHelper.addSmelting(BlockOre.getOreByName("Lead"), ItemIngots.getIngotByName("lead"), 1F); CraftingHelper.addSmelting(BlockOre.getOreByName("Sheldonite"), ItemIngots.getIngotByName("platinum"), 1F); CraftingHelper .addSmelting(ItemIngots.getIngotByName("mixedMetal"), ItemIngots.getIngotByName("advancedAlloy"), 1F); CraftingHelper.addSmelting(ItemDusts.getDustByName("nickel", 1), ItemIngots.getIngotByName("nickel"), 1F); CraftingHelper.addSmelting(ItemDusts.getDustByName("platinum", 1), ItemIngots.getIngotByName("platinum"), 1F); CraftingHelper.addSmelting(ItemDusts.getDustByName("zinc", 1), ItemIngots.getIngotByName("zinc"), 1F); Core.logHelper.info("Smelting Recipes Added"); } static void addAlloySmelterRecipes() { // Bronze RecipeHandler.addRecipe( new AlloySmelterRecipe(ItemIngots.getIngotByName("copper", 3), ItemIngots.getIngotByName("tin", 1), ItemIngots.getIngotByName("bronze", 4), 200, 16)); RecipeHandler.addRecipe( new AlloySmelterRecipe(ItemIngots.getIngotByName("copper", 3), ItemDusts.getDustByName("tin", 1), ItemIngots.getIngotByName("bronze", 4), 200, 16)); RecipeHandler.addRecipe( new AlloySmelterRecipe(ItemDusts.getDustByName("copper", 3), ItemIngots.getIngotByName("tin", 1), ItemIngots.getIngotByName("bronze", 4), 200, 16)); RecipeHandler.addRecipe( new AlloySmelterRecipe(ItemDusts.getDustByName("copper", 3), ItemDusts.getDustByName("tin", 1), ItemIngots.getIngotByName("bronze", 4), 200, 16)); // Electrum RecipeHandler.addRecipe( new AlloySmelterRecipe(new ItemStack(Items.GOLD_INGOT, 1), ItemIngots.getIngotByName("silver", 1), ItemIngots.getIngotByName("electrum", 2), 200, 16)); RecipeHandler.addRecipe( new AlloySmelterRecipe(new ItemStack(Items.GOLD_INGOT, 1), ItemDusts.getDustByName("silver", 1), ItemIngots.getIngotByName("electrum", 2), 200, 16)); RecipeHandler.addRecipe( new AlloySmelterRecipe(ItemDusts.getDustByName("gold", 1), ItemIngots.getIngotByName("silver", 1), ItemIngots.getIngotByName("electrum", 2), 200, 16)); RecipeHandler.addRecipe( new AlloySmelterRecipe(ItemDusts.getDustByName("gold", 1), ItemDusts.getDustByName("silver", 1), ItemIngots.getIngotByName("electrum", 2), 200, 16)); // Invar RecipeHandler.addRecipe( new AlloySmelterRecipe(new ItemStack(Items.IRON_INGOT, 2), ItemIngots.getIngotByName("nickel", 1), ItemIngots.getIngotByName("invar", 3), 200, 16)); RecipeHandler.addRecipe( new AlloySmelterRecipe(new ItemStack(Items.IRON_INGOT, 2), ItemDusts.getDustByName("nickel", 1), ItemIngots.getIngotByName("invar", 3), 200, 16)); RecipeHandler.addRecipe( new AlloySmelterRecipe(ItemDusts.getDustByName("iron", 2), ItemIngots.getIngotByName("nickel", 1), ItemIngots.getIngotByName("invar", 3), 200, 16)); RecipeHandler.addRecipe( new AlloySmelterRecipe(ItemDusts.getDustByName("iron", 2), ItemDusts.getDustByName("nickel", 1), ItemIngots.getIngotByName("invar", 3), 200, 16)); // Brass if (OreUtil.doesOreExistAndValid("ingotBrass")) { ItemStack brassStack = OreDictionary.getOres("ingotBrass").get(0); brassStack.stackSize = 4; RecipeHandler.addRecipe( new AlloySmelterRecipe(ItemIngots.getIngotByName("copper", 3), ItemIngots.getIngotByName("zinc", 1), brassStack, 200, 16)); RecipeHandler.addRecipe( new AlloySmelterRecipe(ItemIngots.getIngotByName("copper", 3), ItemDusts.getDustByName("zinc", 1), brassStack, 200, 16)); RecipeHandler.addRecipe( new AlloySmelterRecipe(ItemDusts.getDustByName("copper", 3), ItemIngots.getIngotByName("zinc", 1), brassStack, 200, 16)); RecipeHandler.addRecipe( new AlloySmelterRecipe(ItemDusts.getDustByName("copper", 3), ItemDusts.getDustByName("zinc", 1), brassStack, 200, 16)); } // Red Alloy if (OreUtil.doesOreExistAndValid("ingotRedAlloy")) { ItemStack redAlloyStack = OreDictionary.getOres("ingotRedAlloy").get(0); redAlloyStack.stackSize = 1; RecipeHandler.addRecipe( new AlloySmelterRecipe(new ItemStack(Items.REDSTONE, 4), ItemIngots.getIngotByName("copper", 1), redAlloyStack, 200, 16)); RecipeHandler.addRecipe( new AlloySmelterRecipe(new ItemStack(Items.REDSTONE, 4), new ItemStack(Items.IRON_INGOT, 1), redAlloyStack, 200, 16)); } // Blue Alloy if (OreUtil.doesOreExistAndValid("ingotBlueAlloy")) { ItemStack blueAlloyStack = OreDictionary.getOres("ingotBlueAlloy").get(0); blueAlloyStack.stackSize = 1; RecipeHandler.addRecipe(new AlloySmelterRecipe(ItemDusts.getDustByName("teslatite", 4), ItemIngots.getIngotByName("silver", 1), blueAlloyStack, 200, 16)); } // Blue Alloy if (OreUtil.doesOreExistAndValid("ingotPurpleAlloy") && OreUtil.doesOreExistAndValid("dustInfusedTeslatite")) { ItemStack purpleAlloyStack = OreDictionary.getOres("ingotPurpleAlloy").get(0); purpleAlloyStack.stackSize = 1; ItemStack infusedTeslatiteStack = OreDictionary.getOres("ingotPurpleAlloy").get(0); infusedTeslatiteStack.stackSize = 8; RecipeHandler.addRecipe(new AlloySmelterRecipe(ItemIngots.getIngotByName("redAlloy", 1), ItemIngots.getIngotByName("blueAlloy", 1), purpleAlloyStack, 200, 16)); RecipeHandler.addRecipe( new AlloySmelterRecipe(new ItemStack(Items.GOLD_INGOT, 1), infusedTeslatiteStack, purpleAlloyStack, 200, 16)); } // Aluminum Brass if (OreUtil.doesOreExistAndValid("ingotAluminumBrass")) { ItemStack aluminumBrassStack = OreDictionary.getOres("ingotAluminumBrass").get(0); aluminumBrassStack.stackSize = 4; RecipeHandler.addRecipe(new AlloySmelterRecipe(ItemIngots.getIngotByName("copper", 3), ItemIngots.getIngotByName("aluminum", 1), aluminumBrassStack, 200, 16)); RecipeHandler.addRecipe(new AlloySmelterRecipe(ItemIngots.getIngotByName("copper", 3), ItemDusts.getDustByName("aluminum", 1), aluminumBrassStack, 200, 16)); RecipeHandler.addRecipe(new AlloySmelterRecipe(ItemDusts.getDustByName("copper", 3), ItemIngots.getIngotByName("aluminum", 1), aluminumBrassStack, 200, 16)); RecipeHandler.addRecipe( new AlloySmelterRecipe(ItemDusts.getDustByName("copper", 3), ItemDusts.getDustByName("aluminum", 1), aluminumBrassStack, 200, 16)); } // Manyullyn if (OreUtil.doesOreExistAndValid("ingotManyullyn") && OreUtil.doesOreExistAndValid("ingotCobalt") && OreUtil .doesOreExistAndValid("ingotArdite")) { ItemStack manyullynStack = OreDictionary.getOres("ingotManyullyn").get(0); manyullynStack.stackSize = 1; ItemStack cobaltStack = OreDictionary.getOres("ingotCobalt").get(0); cobaltStack.stackSize = 1; ItemStack arditeStack = OreDictionary.getOres("ingotArdite").get(0); arditeStack.stackSize = 1; RecipeHandler.addRecipe(new AlloySmelterRecipe(cobaltStack, arditeStack, manyullynStack, 200, 16)); RecipeHandler.addRecipe( new AlloySmelterRecipe(cobaltStack, ItemDusts.getDustByName("ardite", 1), manyullynStack, 200, 16)); RecipeHandler.addRecipe( new AlloySmelterRecipe(ItemDusts.getDustByName("cobalt", 1), arditeStack, manyullynStack, 200, 16)); RecipeHandler.addRecipe( new AlloySmelterRecipe(ItemDusts.getDustByName("cobalt", 1), ItemDusts.getDustByName("ardite", 1), manyullynStack, 200, 16)); } // Conductive Iron if (OreUtil.doesOreExistAndValid("ingotConductiveIron")) { ItemStack conductiveIronStack = OreDictionary.getOres("ingotConductiveIron").get(0); conductiveIronStack.stackSize = 1; RecipeHandler.addRecipe( new AlloySmelterRecipe(new ItemStack(Items.REDSTONE, 1), new ItemStack(Items.IRON_INGOT, 1), conductiveIronStack, 200, 16)); } // Redstone Alloy if (OreUtil.doesOreExistAndValid("ingotRedstoneAlloy") && OreUtil.doesOreExistAndValid("itemSilicon")) { ItemStack redstoneAlloyStack = OreDictionary.getOres("ingotRedstoneAlloy").get(0); redstoneAlloyStack.stackSize = 1; ItemStack siliconStack = OreDictionary.getOres("itemSilicon").get(0); siliconStack.stackSize = 1; RecipeHandler.addRecipe( new AlloySmelterRecipe(new ItemStack(Items.REDSTONE, 1), siliconStack, redstoneAlloyStack, 200, 16)); } // Pulsating Iron if (OreUtil.doesOreExistAndValid("ingotPhasedIron")) { ItemStack pulsatingIronStack = OreDictionary.getOres("ingotPhasedIron").get(0); pulsatingIronStack.stackSize = 1; RecipeHandler.addRecipe( new AlloySmelterRecipe(new ItemStack(Items.IRON_INGOT, 1), new ItemStack(Items.ENDER_PEARL, 1), pulsatingIronStack, 200, 16)); RecipeHandler.addRecipe( new AlloySmelterRecipe(new ItemStack(Items.IRON_INGOT, 1), ItemDusts.getDustByName("enderPearl", 1), pulsatingIronStack, 200, 16)); } // Vibrant Alloy if (OreUtil.doesOreExistAndValid("ingotEnergeticAlloy") && OreUtil.doesOreExistAndValid("ingotPhasedGold")) { ItemStack energeticAlloyStack = OreDictionary.getOres("ingotEnergeticAlloy").get(0); energeticAlloyStack.stackSize = 1; ItemStack vibrantAlloyStack = OreDictionary.getOres("ingotPhasedGold").get(0); vibrantAlloyStack.stackSize = 1; RecipeHandler.addRecipe( new AlloySmelterRecipe(energeticAlloyStack, new ItemStack(Items.ENDER_PEARL, 1), vibrantAlloyStack, 200, 16)); RecipeHandler.addRecipe( new AlloySmelterRecipe(energeticAlloyStack, ItemDusts.getDustByName("enderPearl", 1), vibrantAlloyStack, 200, 16)); } // Soularium if (OreUtil.doesOreExistAndValid("ingotSoularium")) { ItemStack soulariumStack = OreDictionary.getOres("ingotSoularium").get(0); soulariumStack.stackSize = 1; RecipeHandler.addRecipe( new AlloySmelterRecipe(new ItemStack(Blocks.SOUL_SAND, 1), new ItemStack(Items.GOLD_INGOT, 1), soulariumStack, 200, 16)); } } static void addPlateCuttingMachineRecipes() { for (String ore : OreUtil.oreNames) { if (OreUtil.hasBlock(ore) && OreUtil.hasPlate(ore)) { RecipeHandler.addRecipe(new PlateCuttingMachineRecipe( OreUtil.getStackFromName("block" + StringUtils.toFirstCapital(ore)), OreUtil.getStackFromName("plate" + StringUtils.toFirstCapital(ore), 9), 200, 16)); } } // Obsidian RecipeHandler.addRecipe( new PlateCuttingMachineRecipe(new ItemStack(Blocks.OBSIDIAN), ItemPlates.getPlateByName("obsidian", 9), 100, 4)); } static void addBlastFurnaceRecipes() { RecipeHandler.addRecipe( new BlastFurnaceRecipe(ItemDusts.getDustByName("titanium"), null, ItemIngots.getIngotByName("titanium"), null, 3600, 120, 1500)); RecipeHandler.addRecipe(new BlastFurnaceRecipe(ItemDustsSmall.getSmallDustByName("titanium", 4), null, ItemIngots.getIngotByName("titanium"), null, 3600, 120, 1500)); RecipeHandler.addRecipe( new BlastFurnaceRecipe(ItemDusts.getDustByName("aluminum"), null, ItemIngots.getIngotByName("aluminum"), null, 2200, 120, 1700)); RecipeHandler.addRecipe(new BlastFurnaceRecipe(ItemDustsSmall.getSmallDustByName("aluminum", 4), null, ItemIngots.getIngotByName("aluminum"), null, 2200, 120, 1700)); RecipeHandler.addRecipe( new BlastFurnaceRecipe(ItemDusts.getDustByName("tungsten"), null, ItemIngots.getIngotByName("tungsten"), null, 18000, 120, 2500)); RecipeHandler.addRecipe(new BlastFurnaceRecipe(ItemDustsSmall.getSmallDustByName("tungsten", 4), null, ItemIngots.getIngotByName("tungsten"), null, 18000, 120, 2500)); RecipeHandler.addRecipe( new BlastFurnaceRecipe(ItemDusts.getDustByName("chrome"), null, ItemIngots.getIngotByName("chrome"), null, 4420, 120, 1700)); RecipeHandler.addRecipe(new BlastFurnaceRecipe(ItemDustsSmall.getSmallDustByName("chrome", 4), null, ItemIngots.getIngotByName("chrome"), null, 4420, 120, 1700)); RecipeHandler.addRecipe( new BlastFurnaceRecipe(ItemDusts.getDustByName("steel"), null, ItemIngots.getIngotByName("steel"), null, 2800, 120, 1000)); RecipeHandler.addRecipe(new BlastFurnaceRecipe(ItemDustsSmall.getSmallDustByName("steel", 4), null, ItemIngots.getIngotByName("steel"), null, 2800, 120, 1000)); RecipeHandler.addRecipe( new BlastFurnaceRecipe(ItemDusts.getDustByName("galena", 2), null, ItemIngots.getIngotByName("silver"), ItemIngots.getIngotByName("lead"), 80, 120, 1500)); RecipeHandler.addRecipe( new BlastFurnaceRecipe(new ItemStack(Items.IRON_INGOT), ItemDusts.getDustByName("coal", 2), ItemIngots.getIngotByName("steel"), ItemDusts.getDustByName("darkAshes", 2), 500, 120, 1000)); RecipeHandler.addRecipe( new BlastFurnaceRecipe(ItemIngots.getIngotByName("tungsten"), ItemIngots.getIngotByName("steel"), ItemIngots.getIngotByName("hotTungstensteel"), ItemDusts.getDustByName("darkAshes", 4), 500, 500, 3000)); RecipeHandler.addRecipe( new BlastFurnaceRecipe(new ItemStack(Blocks.IRON_ORE), ItemDusts.getDustByName("calcite"), new ItemStack(Items.IRON_INGOT, 3), ItemDusts.getDustByName("darkAshes"), 140, 120, 1000)); RecipeHandler.addRecipe( new BlastFurnaceRecipe(BlockOre.getOreByName("Pyrite"), ItemDusts.getDustByName("calcite"), new ItemStack(Items.IRON_INGOT, 2), ItemDusts.getDustByName("darkAshes"), 140, 120, 1000)); } static void addUUrecipes() { if (ConfigTechReborn.UUrecipesWood) CraftingHelper .addShapedOreRecipe(new ItemStack(Blocks.LOG, 8), " U ", " ", " ", 'U', ModItems.uuMatter); if (ConfigTechReborn.UUrecipesStone) CraftingHelper .addShapedOreRecipe(new ItemStack(Blocks.STONE, 16), " ", " U ", " ", 'U', ModItems.uuMatter); if (ConfigTechReborn.UUrecipesSnowBlock) CraftingHelper .addShapedOreRecipe(new ItemStack(Blocks.SNOW, 16), "U U", " ", " ", 'U', ModItems.uuMatter); if (ConfigTechReborn.UUrecipesGrass) CraftingHelper .addShapedOreRecipe(new ItemStack(Blocks.GRASS, 16), " ", "U ", "U ", 'U', ModItems.uuMatter); if (ConfigTechReborn.UUrecipesObsidian) CraftingHelper.addShapedOreRecipe(new ItemStack(Blocks.OBSIDIAN, 12), "U U", "U U", " ", 'U', ModItems.uuMatter); if (ConfigTechReborn.UUrecipesGlass) CraftingHelper .addShapedOreRecipe(new ItemStack(Blocks.GLASS, 32), " U ", "U U", " U ", 'U', ModItems.uuMatter); if (ConfigTechReborn.UUrecipesCocoa) CraftingHelper .addShapedOreRecipe(new ItemStack(Items.DYE, 32, 3), "UU ", " U", "UU ", 'U', ModItems.uuMatter); if (ConfigTechReborn.UUrecipesGlowstoneBlock) CraftingHelper.addShapedOreRecipe(new ItemStack(Blocks.GLOWSTONE, 8), " U ", "U U", "UUU", 'U', ModItems.uuMatter); if (ConfigTechReborn.UUrecipesCactus) CraftingHelper .addShapedOreRecipe(new ItemStack(Blocks.CACTUS, 48), " U ", "UUU", "U U", 'U', ModItems.uuMatter); if (ConfigTechReborn.UUrecipesSugarCane) CraftingHelper .addShapedOreRecipe(new ItemStack(Items.REEDS, 48), "U U", "U U", "U U", 'U', ModItems.uuMatter); if (ConfigTechReborn.UUrecipesVine) CraftingHelper .addShapedOreRecipe(new ItemStack(Blocks.VINE, 24), "U ", "U ", "U ", 'U', ModItems.uuMatter); if (ConfigTechReborn.UUrecipesSnowBall) CraftingHelper .addShapedOreRecipe(new ItemStack(Items.SNOWBALL, 16), " ", " ", "UUU", 'U', ModItems.uuMatter); CraftingHelper .addShapedOreRecipe(new ItemStack(Items.CLAY_BALL, 48), "UU ", "U ", "UU ", 'U', ModItems.uuMatter); if (ConfigTechReborn.UUrecipeslilypad) CraftingHelper.addShapedOreRecipe(new ItemStack(Blocks.WATERLILY, 64), "U U", " U ", " U ", 'U', ModItems.uuMatter); if (ConfigTechReborn.UUrecipesGunpowder) CraftingHelper.addShapedOreRecipe(new ItemStack(Items.GUNPOWDER, 15), "UUU", "U ", "UUU", 'U', ModItems.uuMatter); if (ConfigTechReborn.UUrecipesBone) CraftingHelper .addShapedOreRecipe(new ItemStack(Items.BONE, 32), "U ", "UU ", "U ", 'U', ModItems.uuMatter); if (ConfigTechReborn.UUrecipesFeather) CraftingHelper .addShapedOreRecipe(new ItemStack(Items.FEATHER, 32), " U ", " U ", "U U", 'U', ModItems.uuMatter); if (ConfigTechReborn.UUrecipesInk) CraftingHelper .addShapedOreRecipe(new ItemStack(Items.DYE, 48), " UU", " UU", " U ", 'U', ModItems.uuMatter); if (ConfigTechReborn.UUrecipesEnderPearl) CraftingHelper.addShapedOreRecipe(new ItemStack(Items.ENDER_PEARL, 1), "UUU", "U U", " U ", 'U', ModItems.uuMatter); if (ConfigTechReborn.UUrecipesCoal) CraftingHelper .addShapedOreRecipe(new ItemStack(Items.COAL, 5), " U", "U ", " U", 'U', ModItems.uuMatter); if (ConfigTechReborn.UUrecipesIronOre) CraftingHelper .addShapedOreRecipe(new ItemStack(Blocks.IRON_ORE, 2), "U U", " U ", "U U", 'U', ModItems.uuMatter); if (ConfigTechReborn.UUrecipesGoldOre) CraftingHelper .addShapedOreRecipe(new ItemStack(Blocks.GOLD_ORE, 2), " U ", "UUU", " U ", 'U', ModItems.uuMatter); if (ConfigTechReborn.UUrecipesRedStone) CraftingHelper .addShapedOreRecipe(new ItemStack(Items.REDSTONE, 24), " ", " U ", "UUU", 'U', ModItems.uuMatter); if (ConfigTechReborn.UUrecipesLapis) CraftingHelper .addShapedOreRecipe(new ItemStack(Items.DYE, 9, 4), " U ", " U ", " UU", 'U', ModItems.uuMatter); if (ConfigTechReborn.UUrecipesEmeraldOre) CraftingHelper.addShapedOreRecipe(new ItemStack(Blocks.EMERALD_ORE, 1), "UU ", "U U", " UU", 'U', ModItems.uuMatter); if (ConfigTechReborn.UUrecipesEmerald) CraftingHelper .addShapedOreRecipe(new ItemStack(Items.EMERALD, 2), "UUU", "UUU", " U ", 'U', ModItems.uuMatter); if (ConfigTechReborn.UUrecipesDiamond) CraftingHelper .addShapedOreRecipe(new ItemStack(Items.DIAMOND, 1), "UUU", "UUU", "UUU", 'U', ModItems.uuMatter); if (ConfigTechReborn.UUrecipesTinDust) CraftingHelper.addShapedOreRecipe(new ItemStack(ModItems.dusts, 10, 77), " ", "U U", " U", 'U', ModItems.uuMatter); if (ConfigTechReborn.UUrecipesCopperDust) CraftingHelper.addShapedOreRecipe(new ItemStack(ModItems.dusts, 10, 21), " U", "U U", " ", 'U', ModItems.uuMatter); if (ConfigTechReborn.UUrecipesLeadDust) CraftingHelper.addShapedOreRecipe(new ItemStack(ModItems.dusts, 14, 42), "UUU", "UUU", "U ", 'U', ModItems.uuMatter); if (ConfigTechReborn.UUrecipesPlatinumDust) CraftingHelper.addShapedOreRecipe(new ItemStack(ModItems.dusts, 1, 58), " U", "UUU", "UUU", 'U', ModItems.uuMatter); if (ConfigTechReborn.UUrecipesTungstenDust) CraftingHelper.addShapedOreRecipe(new ItemStack(ModItems.dusts, 1, 79), "U ", "UUU", "UUU", 'U', ModItems.uuMatter); if (ConfigTechReborn.UUrecipesTitaniumDust) CraftingHelper.addShapedOreRecipe(new ItemStack(ModItems.dusts, 2, 78), "UUU", " U ", " U ", 'U', ModItems.uuMatter); if (ConfigTechReborn.UUrecipesAluminumDust) CraftingHelper.addShapedOreRecipe(new ItemStack(ModItems.dusts, 16, 2), " U ", " U ", "UUU", 'U', ModItems.uuMatter); if (ConfigTechReborn.HideUuRecipes) hideUUrecipes(); } static void hideUUrecipes() { // TODO } static void addIndustrialCentrifugeRecipes() { // Mycelium Byproducts RecipeHandler.addRecipe( new CentrifugeRecipe(new ItemStack(Blocks.MYCELIUM, 8), null, new ItemStack(Blocks.BROWN_MUSHROOM, 2), new ItemStack(Blocks.RED_MUSHROOM, 2), new ItemStack(Items.CLAY_BALL, 1), new ItemStack(Blocks.SAND, 4), 1640, 5)); // Blaze Powder Byproducts RecipeHandler.addRecipe( new CentrifugeRecipe(new ItemStack(Items.BLAZE_POWDER), null, ItemDusts.getDustByName("darkAshes", 1), ItemDusts.getDustByName("sulfur", 1), null, null, 1240, 5)); // Magma Cream Products RecipeHandler.addRecipe( new CentrifugeRecipe(new ItemStack(Items.MAGMA_CREAM, 1), null, new ItemStack(Items.BLAZE_POWDER, 1), new ItemStack(Items.SLIME_BALL, 1), null, null, 2500, 5)); // Dust Byproducts // RecipeHandler.addRecipe(new // CentrifugeRecipe(ItemDusts.getDustByName("platinum", 1), null, // ItemDustsTiny.getTinyDustByName("Iridium", 1), // ItemDustsSmall.getSmallDustByName("Nickel", 1), null, null, 3000, RecipeHandler.addRecipe( new CentrifugeRecipe(ItemDusts.getDustByName("electrum", 2), null, ItemDusts.getDustByName("silver", 1), ItemDusts.getDustByName("gold", 1), null, null, 2400, 5)); RecipeHandler.addRecipe( new CentrifugeRecipe(ItemDusts.getDustByName("invar", 3), null, ItemDusts.getDustByName("iron", 2), ItemDusts.getDustByName("nickel", 1), null, null, 1340, 5)); RecipeHandler.addRecipe(new CentrifugeRecipe(ItemDusts.getDustByName("marble", 8), null, ItemDusts.getDustByName("magnesium", 1), ItemDusts.getDustByName("calcite", 7), null, null, 1280, 5)); // Deprecated // RecipeHandler.addRecipe( // new CentrifugeRecipe(ItemDusts.getDustByName("redrock", 4), null, ItemDusts.getDustByName("calcite", 2), // ItemDusts.getDustByName("flint", 1), ItemDusts.getDustByName("clay", 1), null, 640, 5)); RecipeHandler.addRecipe( new CentrifugeRecipe(ItemDusts.getDustByName("basalt", 16), null, ItemDusts.getDustByName("peridot", 1), ItemDusts.getDustByName("calcite", 3), ItemDusts.getDustByName("magnesium", 8), ItemDusts.getDustByName("darkAshes", 4), 2680, 5)); RecipeHandler.addRecipe(new CentrifugeRecipe(ItemDusts.getDustByName("yellowGarnet", 16), null, ItemDusts.getDustByName("andradite", 5), ItemDusts.getDustByName("grossular", 8), ItemDusts.getDustByName("uvarovite", 3), null, 2940, 5)); RecipeHandler.addRecipe(new CentrifugeRecipe(ItemDusts.getDustByName("redGarnet", 16), null, ItemDusts.getDustByName("pyrope", 3), ItemDusts.getDustByName("almandine", 5), ItemDusts.getDustByName("spessartine", 8), null, 2940, 5)); RecipeHandler.addRecipe( new CentrifugeRecipe(ItemDusts.getDustByName("darkAshes", 2), null, ItemDusts.getDustByName("ashes", 2), null, null, null, 240, 5)); RecipeHandler.addRecipe( new CentrifugeRecipe(ItemDusts.getDustByName("brass", 4), null, ItemDusts.getDustByName("zinc", 1), ItemDusts.getDustByName("copper", 3), null, null, 2000, 5)); RecipeHandler.addRecipe( new CentrifugeRecipe(ItemDusts.getDustByName("bronze", 4), null, ItemDusts.getDustByName("tin", 1), ItemDusts.getDustByName("copper", 3), null, null, 2420, 5)); RecipeHandler.addRecipe( new CentrifugeRecipe(ItemDusts.getDustByName("netherrack", 16), null, new ItemStack(Items.REDSTONE, 1), ItemDusts.getDustByName("sulfur", 4), ItemDusts.getDustByName("basalt", 1), new ItemStack(Items.GOLD_NUGGET, 1), 2400, 5)); RecipeHandler.addRecipe(new CentrifugeRecipe(ItemDusts.getDustByName("enderEye", 1), null, ItemDusts.getDustByName("enderPearl", 1), new ItemStack(Items.BLAZE_POWDER, 1), null, null, 1280, 5)); RecipeHandler.addRecipe( new CentrifugeRecipe(new ItemStack(Items.GLOWSTONE_DUST, 16), RecipeUtils.getEmptyCell(1), ItemCells.getCellByName("helium", 1, false), ItemDusts.getDustByName("gold", 8), new ItemStack(Items.REDSTONE), null, 25000, 20)); } static void addIndustrialGrinderRecipes() { for (String ore : OreUtil.oreNames) { if (OreUtil.hasIngot(ore) && OreUtil.hasDustSmall(ore) && OreUtil.hasBlock(ore)) { RecipeHandler.addRecipe( new IndustrialGrinderRecipe(OreUtil.getStackFromName("block" + StringUtils.toFirstCapital(ore)), new FluidStack(FluidRegistry.WATER, 1000), OreUtil.getStackFromName("ingot" + StringUtils.toFirstCapital(ore)), OreUtil.getStackFromName("dustSmall" + StringUtils.toFirstCapital(ore), 6), OreUtil.getStackFromName("dustSmall" + StringUtils.toFirstCapital(ore), 2), null, 100, 120)); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(OreUtil.getStackFromName("block" + StringUtils.toFirstCapital(ore)), new FluidStack(FluidRegistry.WATER, 1000), OreUtil.getStackFromName("ingot" + StringUtils.toFirstCapital(ore)), OreUtil.getStackFromName("dustSmall" + StringUtils.toFirstCapital(ore), 6), OreUtil.getStackFromName("dustSmall" + StringUtils.toFirstCapital(ore), 2), new ItemStack(Items.BUCKET), 100, 120)); } } // Copper Ore if (OreUtil.doesOreExistAndValid("oreCopper")) { try { ItemStack oreStack = OreDictionary.getOres("oreCopper").get(0); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("copper", 2), ItemDustsSmall.getSmallDustByName("Gold", 1), ItemDustsSmall.getSmallDustByName("Nickel", 1), null, 100, 120)); RecipeHandler.addRecipe(new IndustrialGrinderRecipe(oreStack, new FluidStack(ModFluids.fluidSodiumpersulfate, 1000), ItemDusts.getDustByName("copper", 2), ItemDusts.getDustByName("gold", 1), ItemDustsSmall.getSmallDustByName("Nickel", 1), null, 100, 120)); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(ModFluids.fluidMercury, 1000), ItemDusts.getDustByName("copper", 2), ItemDustsSmall.getSmallDustByName("Gold", 1), ItemDusts.getDustByName("nickel", 1), null, 100, 120)); } catch (Exception e) { Core.logHelper.info("Failed to Load Grinder Recipe for Copper Ore"); } } // Tin Ore if (OreUtil.doesOreExistAndValid("oreTin")) { try { ItemStack oreStack = OreDictionary.getOres("oreTin").get(0); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("tin", 2), ItemDustsSmall.getSmallDustByName("Iron", 1), ItemDustsSmall.getSmallDustByName("Zinc", 1), null, 100, 120)); RecipeHandler.addRecipe(new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("tin", 2), ItemDustsSmall.getSmallDustByName("Iron", 1), ItemDustsSmall.getSmallDustByName("Zinc", 1), new ItemStack(Items.BUCKET), 100, 120)); RecipeHandler.addRecipe(new IndustrialGrinderRecipe(oreStack, new FluidStack(ModFluids.fluidSodiumpersulfate, 1000), ItemDusts.getDustByName("tin", 2), ItemDustsSmall.getSmallDustByName("Iron", 1), ItemDusts.getDustByName("zinc", 1), null, 100, 120)); } catch (Exception e) { Core.logHelper.info("Failed to Load Grinder Recipe for Tin Ore"); } } // Nickel Ore if (OreUtil.doesOreExistAndValid("oreNickel")) { try { ItemStack oreStack = OreDictionary.getOres("oreNickel").get(0); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("nickel", 2), ItemDustsSmall.getSmallDustByName("Iron", 1), ItemDustsSmall.getSmallDustByName("Platinum", 1), null, 100, 120)); RecipeHandler.addRecipe(new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("nickel", 2), ItemDustsSmall.getSmallDustByName("Iron", 1), ItemDustsSmall.getSmallDustByName("Platinum", 1), new ItemStack(Items.BUCKET), 100, 120)); RecipeHandler.addRecipe(new IndustrialGrinderRecipe(oreStack, new FluidStack(ModFluids.fluidSodiumpersulfate, 1000), ItemDusts.getDustByName("nickel", 3), ItemDustsSmall.getSmallDustByName("Iron", 1), ItemDustsSmall.getSmallDustByName("Platinum", 1), null, 100, 120)); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(ModFluids.fluidMercury, 1000), ItemDusts.getDustByName("nickel", 2), ItemDustsSmall.getSmallDustByName("Iron", 1), ItemDusts.getDustByName("platinum", 1), null, 100, 120)); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(ModFluids.fluidMercury, 1000), ItemDusts.getDustByName("nickel", 2), ItemDustsSmall.getSmallDustByName("Iron", 1), ItemDusts.getDustByName("platinum", 1), new ItemStack(Items.BUCKET), 100, 120)); } catch (Exception e) { Core.logHelper.info("Failed to Load Grinder Recipe for Nickel Ore"); } } // Zinc Ore if (OreUtil.doesOreExistAndValid("oreZinc")) { try { ItemStack oreStack = OreDictionary.getOres("oreZinc").get(0); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("zinc", 2), ItemDustsSmall.getSmallDustByName("Iron", 1), ItemDustsSmall.getSmallDustByName("Tin", 1), null, 100, 120)); RecipeHandler.addRecipe(new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("zinc", 2), ItemDustsSmall.getSmallDustByName("Iron", 1), ItemDustsSmall.getSmallDustByName("Tin", 1), new ItemStack(Items.BUCKET), 100, 120)); RecipeHandler.addRecipe(new IndustrialGrinderRecipe(oreStack, new FluidStack(ModFluids.fluidSodiumpersulfate, 1000), ItemDusts.getDustByName("zinc", 2), ItemDustsSmall.getSmallDustByName("Iron", 1), ItemDusts.getDustByName("iron", 1), null, 100, 120)); } catch (Exception e) { Core.logHelper.info("Failed to Load Grinder Recipe for Zinc Ore"); } } // Silver Ore if (OreUtil.doesOreExistAndValid("oreSilver")) { try { ItemStack oreStack = OreDictionary.getOres("oreSilver").get(0); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("silver", 2), ItemDustsSmall.getSmallDustByName("Lead", 1), ItemDustsSmall.getSmallDustByName("Sulfur", 1), null, 100, 120)); RecipeHandler.addRecipe(new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("silver", 2), ItemDustsSmall.getSmallDustByName("Lead", 1), ItemDustsSmall.getSmallDustByName("Sulfur", 1), new ItemStack(Items.BUCKET), 100, 120)); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(ModFluids.fluidMercury, 1000), ItemDusts.getDustByName("silver", 3), ItemDustsSmall.getSmallDustByName("Lead", 1), ItemDustsSmall.getSmallDustByName("Sulfur", 1), null, 100, 120)); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(ModFluids.fluidMercury, 1000), ItemDusts.getDustByName("silver", 3), ItemDustsSmall.getSmallDustByName("Lead", 1), ItemDustsSmall.getSmallDustByName("Sulfur", 1), new ItemStack(Items.BUCKET), 100, 120)); } catch (Exception e) { Core.logHelper.info("Failed to Load Grinder Recipe for Silver Ore"); } } // Lead Ore if (OreUtil.doesOreExistAndValid("oreLead")) { try { ItemStack oreStack = OreDictionary.getOres("oreLead").get(0); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("lead", 2), ItemDustsSmall.getSmallDustByName("Silver", 1), ItemDustsSmall.getSmallDustByName("Sulfur", 1), null, 100, 120)); RecipeHandler.addRecipe(new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("lead", 2), ItemDustsSmall.getSmallDustByName("Silver", 1), ItemDustsSmall.getSmallDustByName("Sulfur", 1), new ItemStack(Items.BUCKET), 100, 120)); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(ModFluids.fluidMercury, 1000), ItemDusts.getDustByName("lead", 2), ItemDusts.getDustByName("silver", 1), ItemDustsSmall.getSmallDustByName("Sulfur", 1), null, 100, 120)); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(ModFluids.fluidMercury, 1000), ItemDusts.getDustByName("lead", 2), ItemDusts.getDustByName("silver", 1), ItemDustsSmall.getSmallDustByName("Sulfur", 1), new ItemStack(Items.BUCKET), 100, 120)); } catch (Exception e) { Core.logHelper.info("Failed to Load Grinder Recipe for Lead Ore"); } } // Apatite Ore if (OreUtil.doesOreExistAndValid("oreApatite") & OreUtil.doesOreExistAndValid("gemApatite")) { try { ItemStack oreStack = OreDictionary.getOres("oreApatite").get(0); ItemStack gemStack = OreDictionary.getOres("gemApatite").get(0); gemStack.stackSize = 6; RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), gemStack, gemStack, ItemDustsSmall.getSmallDustByName("Phosphorous", 4), null, 100, 120)); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), gemStack, gemStack, ItemDustsSmall.getSmallDustByName("Phosphorous", 4), new ItemStack(Items.BUCKET), 100, 120)); } catch (Exception e) { Core.logHelper.info("Failed to Load Grinder Recipe for Apatite Ore"); } } // Nether Quartz Ore if (OreUtil.doesOreExistAndValid("dustNetherQuartz")) { try { ItemStack dustStack = OreDictionary.getOres("dustNetherQuartz").get(0); dustStack.stackSize = 4; RecipeHandler.addRecipe(new IndustrialGrinderRecipe(new ItemStack(Blocks.QUARTZ_ORE, 1), new FluidStack(FluidRegistry.WATER, 1000), new ItemStack(Items.QUARTZ, 2), dustStack, ItemDustsSmall.getSmallDustByName("Netherrack", 2), null, 100, 120)); } catch (Exception e) { Core.logHelper.info("Failed to Load Grinder Recipe for Nether Quartz Ore"); } } // Certus Quartz Ore if (OreUtil.doesOreExistAndValid("oreCertusQuartz")) { try { ItemStack oreStack = OreDictionary.getOres("oreCertusQuartz").get(0); ItemStack gemStack = OreDictionary.getOres("crystalCertusQuartz").get(0); ItemStack dustStack = OreDictionary.getOres("dustCertusQuartz").get(0); dustStack.stackSize = 2; RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), gemStack, dustStack, null, null, 100, 120)); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), gemStack, dustStack, null, new ItemStack(Items.BUCKET), 100, 120)); } catch (Exception e) { Core.logHelper.info("Failed to Load Grinder Recipe for Certus Quartz Ore"); } } // Charged Certus Quartz Ore if (OreUtil.doesOreExistAndValid("oreChargedCertusQuartz")) { try { ItemStack oreStack = OreDictionary.getOres("oreChargedCertusQuartz").get(0); ItemStack gemStack = OreDictionary.getOres("crystalChargedCertusQuartz").get(0); ItemStack dustStack = OreDictionary.getOres("dustCertusQuartz").get(0); dustStack.stackSize = 2; RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), gemStack, dustStack, null, null, 100, 120)); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), gemStack, dustStack, null, new ItemStack(Items.BUCKET), 100, 120)); } catch (Exception e) { Core.logHelper.info("Failed to Load Grinder Recipe for Charged Certus Quartz Ore"); } } // Amethyst Ore if (OreUtil.doesOreExistAndValid("oreAmethyst") && OreUtil.doesOreExistAndValid("gemAmethyst")) { try { ItemStack oreStack = OreDictionary.getOres("oreAmethyst").get(0); ItemStack gemStack = OreDictionary.getOres("gemAmethyst").get(0); gemStack.stackSize = 2; ItemStack dustStack = OreDictionary.getOres("gemAmethyst").get(0); dustStack.stackSize = 1; RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), gemStack, dustStack, null, null, 100, 120)); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), gemStack, dustStack, null, new ItemStack(Items.BUCKET), 100, 120)); } catch (Exception e) { Core.logHelper.info("Failed to Load Grinder Recipe for Certus Quartz Ore"); } } // Topaz Ore if (OreUtil.doesOreExistAndValid("oreTopaz") && OreUtil.doesOreExistAndValid("gemTopaz")) { try { ItemStack oreStack = OreDictionary.getOres("oreTopaz").get(0); ItemStack gemStack = OreDictionary.getOres("gemTopaz").get(0); gemStack.stackSize = 2; ItemStack dustStack = OreDictionary.getOres("gemTopaz").get(0); dustStack.stackSize = 1; RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), gemStack, dustStack, null, null, 100, 120)); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), gemStack, dustStack, null, new ItemStack(Items.BUCKET), 100, 120)); } catch (Exception e) { Core.logHelper.info("Failed to Load Grinder Recipe for Topaz Ore"); } } // Tanzanite Ore if (OreUtil.doesOreExistAndValid("oreTanzanite") && OreUtil.doesOreExistAndValid("gemTanzanite")) { try { ItemStack oreStack = OreDictionary.getOres("oreTanzanite").get(0); ItemStack gemStack = OreDictionary.getOres("gemTanzanite").get(0); gemStack.stackSize = 2; ItemStack dustStack = OreDictionary.getOres("gemTanzanite").get(0); dustStack.stackSize = 1; RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), gemStack, dustStack, null, null, 100, 120)); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), gemStack, dustStack, null, new ItemStack(Items.BUCKET), 100, 120)); } catch (Exception e) { Core.logHelper.info("Failed to Load Grinder Recipe for Tanzanite Ore"); } } // Malachite Ore if (OreUtil.doesOreExistAndValid("oreMalachite") && OreUtil.doesOreExistAndValid("gemMalachite")) { try { ItemStack oreStack = OreDictionary.getOres("oreMalachite").get(0); ItemStack gemStack = OreDictionary.getOres("gemMalachite").get(0); gemStack.stackSize = 2; ItemStack dustStack = OreDictionary.getOres("gemMalachite").get(0); dustStack.stackSize = 1; RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), gemStack, dustStack, null, null, 100, 120)); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), gemStack, dustStack, null, new ItemStack(Items.BUCKET), 100, 120)); } catch (Exception e) { Core.logHelper.info("Failed to Load Grinder Recipe for Malachite Ore"); } } // Galena Ore RecipeHandler.addRecipe(new IndustrialGrinderRecipe(new ItemStack(ModBlocks.ore, 1, 0), new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("galena", 2), ItemDustsSmall.getSmallDustByName("Sulfur", 1), ItemDustsSmall.getSmallDustByName("Silver", 1), null, 100, 120)); RecipeHandler.addRecipe(new IndustrialGrinderRecipe(new ItemStack(ModBlocks.ore, 1, 0), new FluidStack(ModFluids.fluidMercury, 1000), ItemDusts.getDustByName("galena", 2), ItemDustsSmall.getSmallDustByName("Sulfur", 1), ItemDusts.getDustByName("silver", 1), null, 100, 120)); // Ruby Ore RecipeHandler.addRecipe(new IndustrialGrinderRecipe(new ItemStack(ModBlocks.ore, 1, 2), new FluidStack(FluidRegistry.WATER, 1000), ItemGems.getGemByName("ruby", 1), ItemDustsSmall.getSmallDustByName("Ruby", 6), ItemDustsSmall.getSmallDustByName("Chrome", 2), null, 100, 120)); // Sapphire Ore RecipeHandler.addRecipe(new IndustrialGrinderRecipe(new ItemStack(ModBlocks.ore, 1, 3), new FluidStack(FluidRegistry.WATER, 1000), ItemGems.getGemByName("sapphire", 1), ItemDustsSmall.getSmallDustByName("Sapphire", 6), ItemDustsSmall.getSmallDustByName("Aluminum", 2), null, 100, 120)); // Bauxite Ore RecipeHandler.addRecipe(new IndustrialGrinderRecipe(new ItemStack(ModBlocks.ore, 1, 4), new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("bauxite", 2), ItemDustsSmall.getSmallDustByName("Grossular", 4), ItemDustsSmall.getSmallDustByName("Titanium", 4), null, 100, 120)); // Pyrite Ore RecipeHandler.addRecipe(new IndustrialGrinderRecipe(new ItemStack(ModBlocks.ore, 1, 5), new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("pyrite", 2), ItemDustsSmall.getSmallDustByName("Sulfur", 1), ItemDustsSmall.getSmallDustByName("Phosphorous", 1), null, 100, 120)); // Cinnabar Ore RecipeHandler.addRecipe(new IndustrialGrinderRecipe(new ItemStack(ModBlocks.ore, 1, 6), new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("cinnabar", 2), ItemDustsSmall.getSmallDustByName("Redstone", 1), ItemDustsSmall.getSmallDustByName("Glowstone", 1), null, 100, 120)); // Sphalerite Ore RecipeHandler.addRecipe(new IndustrialGrinderRecipe(new ItemStack(ModBlocks.ore, 1, 7), new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("sphalerite", 2), ItemDustsSmall.getSmallDustByName("Zinc", 1), ItemDustsSmall.getSmallDustByName("YellowGarnet", 1), null, 100, 120)); RecipeHandler.addRecipe(new IndustrialGrinderRecipe(new ItemStack(ModBlocks.ore, 1, 7), new FluidStack(ModFluids.fluidSodiumpersulfate, 1000), ItemDusts.getDustByName("sphalerite", 2), ItemDusts.getDustByName("zinc", 1), ItemDustsSmall.getSmallDustByName("YellowGarnet", 1), null, 100, 120)); // Tungsten Ore RecipeHandler.addRecipe( new IndustrialGrinderRecipe(new ItemStack(ModBlocks.ore, 1, 8), new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("tungsten", 2), ItemDustsSmall.getSmallDustByName("Manganese", 1), ItemDustsSmall.getSmallDustByName("Silver", 1), null, 100, 120)); RecipeHandler.addRecipe(new IndustrialGrinderRecipe(new ItemStack(ModBlocks.ore, 1, 8), new FluidStack(ModFluids.fluidMercury, 1000), ItemDusts.getDustByName("tungsten", 2), ItemDustsSmall.getSmallDustByName("Manganese", 1), ItemDusts.getDustByName("silver", 2), null, 100, 120)); // Sheldonite Ore RecipeHandler.addRecipe(new IndustrialGrinderRecipe(new ItemStack(ModBlocks.ore, 1, 9), new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("platinum", 2), ItemNuggets.getNuggetByName("iridium", 2), ItemDusts.getDustByName("nickel", 1), null, 100, 120)); RecipeHandler.addRecipe(new IndustrialGrinderRecipe(new ItemStack(ModBlocks.ore, 1, 9), new FluidStack(ModFluids.fluidMercury, 1000), ItemDusts.getDustByName("platinum", 3), ItemNuggets.getNuggetByName("iridium", 2), ItemDusts.getDustByName("nickel", 1), null, 100, 120)); // Peridot Ore RecipeHandler.addRecipe(new IndustrialGrinderRecipe(new ItemStack(ModBlocks.ore, 1, 10), new FluidStack(FluidRegistry.WATER, 1000), ItemGems.getGemByName("peridot", 1), ItemDustsSmall.getSmallDustByName("Peridot", 6), ItemDustsSmall.getSmallDustByName("Pyrope", 2), null, 100, 120)); // Sodalite Ore RecipeHandler.addRecipe(new IndustrialGrinderRecipe(new ItemStack(ModBlocks.ore, 1, 11), new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("sodalite", 12), ItemDusts.getDustByName("aluminum", 3), null, null, 100, 120)); } static void addImplosionCompressorRecipes() { } static void addChemicalReactorRecipes() { RecipeHandler.addRecipe( new ChemicalReactorRecipe(ItemCells.getCellByName("calcium", 1), ItemCells.getCellByName("carbon", 1), ItemCells.getCellByName("calciumCarbonate", 2), 240, 30)); RecipeHandler.addRecipe( new ChemicalReactorRecipe(new ItemStack(Items.GOLD_NUGGET, 8), new ItemStack(Items.MELON, 1), new ItemStack(Items.SPECKLED_MELON, 1), 40, 30)); RecipeHandler.addRecipe( new ChemicalReactorRecipe(ItemCells.getCellByName("nitrogen", 1), ItemCells.getCellByName("carbon", 1), ItemCells.getCellByName("nitrocarbon", 2), 1500, 30)); RecipeHandler.addRecipe( new ChemicalReactorRecipe(ItemCells.getCellByName("carbon", 1), ItemCells.getCellByName("hydrogen", 4), ItemCells.getCellByName("methane", 5), 3500, 30)); RecipeHandler.addRecipe( new ChemicalReactorRecipe(ItemCells.getCellByName("sulfur", 1), ItemCells.getCellByName("sodium", 1), ItemCells.getCellByName("sodiumSulfide", 2), 100, 30)); RecipeHandler.addRecipe( new ChemicalReactorRecipe(new ItemStack(Items.BLAZE_POWDER, 1), new ItemStack(Items.ENDER_PEARL, 1), new ItemStack(Items.ENDER_EYE, 1), 40, 30)); RecipeHandler.addRecipe( new ChemicalReactorRecipe(new ItemStack(Items.GOLD_NUGGET, 8), new ItemStack(Items.CARROT, 1), new ItemStack(Items.GOLDEN_CARROT, 1), 40, 30)); RecipeHandler.addRecipe( new ChemicalReactorRecipe(ItemCells.getCellByName("glyceryl", 1), ItemCells.getCellByName("diesel", 4), ItemCells.getCellByName("nitroDiesel", 5), 1000, 30)); RecipeHandler.addRecipe( new ChemicalReactorRecipe(new ItemStack(Items.GOLD_INGOT, 8), new ItemStack(Items.APPLE, 1), new ItemStack(Items.GOLDEN_APPLE, 1), 40, 30)); RecipeHandler.addRecipe( new ChemicalReactorRecipe(new ItemStack(Blocks.GOLD_BLOCK, 8), new ItemStack(Items.APPLE, 1), new ItemStack(Items.GOLDEN_APPLE, 1, 1), 40, 30)); RecipeHandler.addRecipe( new ChemicalReactorRecipe(new ItemStack(Items.BLAZE_POWDER, 1), new ItemStack(Items.SLIME_BALL, 1), new ItemStack(Items.MAGMA_CREAM, 1), 40, 30)); } static void addIndustrialElectrolyzerRecipes() { RecipeHandler.addRecipe(new IndustrialElectrolyzerRecipe(ItemCells.getCellByName("nitrocarbon", 2), null, ItemCells.getCellByName("nitrogen"), ItemCells.getCellByName("carbon"), null, null, 80, 60)); RecipeHandler.addRecipe(new IndustrialElectrolyzerRecipe(ItemDusts.getDustByName("pyrite", 3), null, ItemDusts.getDustByName("iron"), ItemDusts.getDustByName("sulfur", 2), null, null, 120, 128)); RecipeHandler.addRecipe(new IndustrialElectrolyzerRecipe(ItemDusts.getDustByName("sphalerite", 2), null, ItemDusts.getDustByName("zinc"), ItemDusts.getDustByName("sulfur"), null, null, 150, 100)); } static void addIc2Recipes() { CraftingHelper.addShapelessOreRecipe(new ItemStack(ModItems.manual), ItemIngots.getIngotByName("refinedIron"), Items.BOOK); CraftingHelper .addShapedOreRecipe(ItemParts.getPartByName("machineParts", 16), "CSC", "SCS", "CSC", 'S', "ingotSteel", 'C', "circuitBasic"); CraftingHelper.addShapedOreRecipe(ItemParts.getPartByName("energyFlowCircuit", 4), "ATA", "LIL", "ATA", 'T', "ingotTungsten", 'I', "plateIridium", 'A', "circuitAdvanced", 'L', "lapotronCrystal"); CraftingHelper.addShapedOreRecipe(ItemParts.getPartByName("superconductor", 4), "CCC", "TIT", "EEE", 'E', "circuitMaster", 'C', ItemParts.getPartByName("heliumCoolantSimple"), 'T', "ingotTungsten", 'I', "plateIridium"); CraftingHelper.addShapedOreRecipe(new ItemStack(ModItems.lapotronicOrb), "LLL", "LPL", "LLL", 'L', "lapotronCrystal", 'P', "plateIridium"); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.industrialSawmill), "PAP", "SSS", "ACA", 'P', ItemIngots.getIngotByName("refinedIron"), 'A', "circuitAdvanced", 'S', ItemParts.getPartByName("diamondSawBlade"), 'C', "machineBlockAdvanced"); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.ComputerCube), "DME", "MAM", "EMD", 'E', "circuitMaster", 'D', ItemParts.getPartByName("dataOrb"), 'M', ItemParts.getPartByName("computerMonitor"), 'A', "machineBlockAdvanced"); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.chargeBench), "ETE", "COC", "EAD", 'E', "circuitMaster", 'T', ModBlocks.ComputerCube, 'C', Blocks.CHEST, 'O', ModItems.lapotronicOrb, 'A', "machineBlockAdvanced"); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.MatterFabricator), "ETE", "AOA", "ETE", 'E', "circuitMaster", 'T', ModBlocks.Extractor, 'A', BlockMachineFrame.getFrameByName("highlyAdvancedMachine", 1), 'O', ModItems.lapotronicOrb); CraftingHelper .addShapedOreRecipe(new ItemStack(ModBlocks.heatGenerator), "III", "IHI", "CGC", 'I', "plateIron", 'H', new ItemStack(Blocks.IRON_BARS), 'C', "circuitBasic", 'G', ModBlocks.Generator); CraftingHelper .addShapedOreRecipe(new ItemStack(ModBlocks.Gasturbine), "IAI", "WGW", "IAI", 'I', "ingotInvar", 'A', "circuitAdvanced", 'W', getOre("ic2Windmill"), 'G', getOre("glassReinforced")); CraftingHelper .addShapedOreRecipe(new ItemStack(ModBlocks.Gasturbine), "IAI", "WGW", "IAI", 'I', "ingotAluminum", 'A', "circuitAdvanced", 'W', getOre("ic2Windmill"), 'G', getOre("glassReinforced")); CraftingHelper .addShapedOreRecipe(new ItemStack(ModBlocks.Semifluidgenerator), "III", "IHI", "CGC", 'I', "plateIron", 'H', ModBlocks.reinforcedglass, 'C', "circuitBasic", 'G', ModBlocks.Generator); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.Semifluidgenerator), "AAA", "AHA", "CGC", 'A', "plateAluminum", 'H', ModBlocks.reinforcedglass, 'C', "circuitBasic", 'G', ModBlocks.Generator); CraftingHelper .addShapedOreRecipe(new ItemStack(ModBlocks.DieselGenerator), "III", "I I", "CGC", 'I', "refinedIron", 'C', "circuitBasic", 'G', ModBlocks.Generator); CraftingHelper .addShapedOreRecipe(new ItemStack(ModBlocks.DieselGenerator), "AAA", "A A", "CGC", 'A', "ingotAluminum", 'C', "circuitBasic", 'G', ModBlocks.Generator); // CraftingHelper.addShapedOreRecipe(new // ItemStack(ModBlocks.MagicalAbsorber), // "CSC", "IBI", "CAC", // 'C', "circuitMaster", // 'S', "craftingSuperconductor", // 'B', Blocks.beacon, // 'A', ModBlocks.Magicenergeyconverter, // 'I', "plateIridium"); // CraftingHelper.addShapedOreRecipe(new // ItemStack(ModBlocks.Magicenergeyconverter), // "CTC", "PBP", "CLC", // 'C', "circuitAdvanced", // 'P', "platePlatinum", // 'B', Blocks.beacon, // 'L', "lapotronCrystal", // 'T', TechRebornAPI.recipeCompact.getItem("teleporter")); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.Dragoneggenergysiphoner), "CTC", "ISI", "CBC", 'I', "plateIridium", 'C', "circuitBasic", 'B', ModItems.lithiumBattery, 'S', ModBlocks.Supercondensator, 'T', ModBlocks.Extractor); CraftingHelper .addShapedOreRecipe(new ItemStack(ModBlocks.centrifuge), "SCS", "BEB", "SCS", 'S', "plateSteel", 'C', "circuitAdvanced", 'B', "machineBlockAdvanced", 'E', getOre("ic2Extractor")); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.BlastFurnace), "CHC", "HBH", "FHF", 'H', ItemParts.getPartByName("cupronickelHeatingCoil"), 'C', "circuitAdvanced", 'B', BlockMachineFrame.getFrameByName("advancedMachine", 1), 'F', ModBlocks.ElectricFurnace); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.IndustrialGrinder), "ECP", "GGG", "CBC", 'E', ModBlocks.IndustrialElectrolyzer, 'P', ModBlocks.Extractor, 'C', "circuitAdvanced", 'B', "machineBlockAdvanced", 'G', ModBlocks.Grinder); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.ImplosionCompressor), "ABA", "CPC", "ABA", 'A', ItemIngots.getIngotByName("advancedAlloy"), 'C', "circuitAdvanced", 'B', BlockMachineFrame.getFrameByName("advancedMachine", 1), 'P', ModBlocks.Compressor); CraftingHelper .addShapedOreRecipe(new ItemStack(ModBlocks.VacuumFreezer), "SPS", "CGC", "SPS", 'S', "plateSteel", 'C', "circuitAdvanced", 'G', ModBlocks.reinforcedglass, 'P', ModBlocks.Extractor); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.Distillationtower), "CMC", "PBP", "EME", 'E', ModBlocks.IndustrialElectrolyzer, 'M', "circuitMaster", 'B', "machineBlockAdvanced", 'C', ModBlocks.centrifuge, 'P', ModBlocks.Extractor); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.AlloyFurnace), "III", "F F", "III", 'I', ItemIngots.getIngotByName("refinediron"), 'F', new ItemStack(ModBlocks.ironFurnace)); CraftingHelper .addShapedOreRecipe(new ItemStack(ModBlocks.ChemicalReactor), "IMI", "CPC", "IEI", 'I', "ingotInvar", 'C', "circuitAdvanced", 'M', ModBlocks.Extractor, 'P', ModBlocks.Compressor, 'E', ModBlocks.Extractor); CraftingHelper .addShapedOreRecipe(new ItemStack(ModBlocks.RollingMachine), "PCP", "MBM", "PCP", 'P', Blocks.PISTON, 'C', "circuitAdvanced", 'M', ModBlocks.Compressor, 'B', BlockMachineFrame.getFrameByName("machine", 1)); // CraftingHelper.addShapedOreRecipe(new // ItemStack(ModBlocks.ElectricCraftingTable), // "ITI", "IBI", "ICI", // 'I', "plateIron", // 'C', "circuitAdvanced", // 'T', "crafterWood", // 'B', "machineBlockBasic"); // CraftingHelper.addShapedOreRecipe(new // ItemStack(ModBlocks.ElectricCraftingTable), // "ATA", "ABA", "ACA", // 'A', "plateAluminum", // 'C', "circuitAdvanced", // 'T', "crafterWood", // 'B', "machineBlockBasic"); // CraftingHelper.addShapedOreRecipe(new // ItemStack(ModBlocks.ChunkLoader), // "SCS", "CMC", "SCS", // 'S', "plateSteel", // 'C', "circuitMaster", // 'M', new ItemStack(ModItems.parts, 1, 39)); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.Lesu), " L ", "CBC", " M ", 'L', ModBlocks.lvt, 'C', "circuitAdvanced", 'M', ModBlocks.mvt, 'B', ModBlocks.LesuStorage); CraftingHelper .addShapedOreRecipe(BlockMachineFrame.getFrameByName("highlyAdvancedMachine", 1), "CTC", "TBT", "CTC", 'C', "ingotChrome", 'T', "ingotTitanium", 'B', "machineBlockAdvanced"); CraftingHelper .addShapedOreRecipe(new ItemStack(ModBlocks.MachineCasing, 4, 0), "III", "CBC", "III", 'I', "plateIron", 'C', "circuitBasic", 'B', "machineBlockBasic"); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.MachineCasing, 4, 1), "SSS", "CBC", "SSS", 'S', "plateSteel", 'C', "circuitAdvanced", 'B', "machineBlockAdvanced"); CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.MachineCasing, 4, 2), "HHH", "CBC", "HHH", 'H', "ingotChrome", 'C', "circuitElite", 'B', BlockMachineFrame.getFrameByName("highlyAdvancedMachine", 1)); if (!CompatManager.isQuantumStorageLoaded) { CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.quantumChest), "DCD", "ATA", "DQD", 'D', ItemParts.getPartByName("dataOrb"), 'C', ItemParts.getPartByName("computerMonitor"), 'A', BlockMachineFrame.getFrameByName("highlyAdvancedMachine", 1), 'Q', ModBlocks.digitalChest, 'T', ModBlocks.Compressor); } CraftingHelper.addShapedOreRecipe(new ItemStack(ModBlocks.PlasmaGenerator), "PPP", "PTP", "CGC", 'P', ItemPlates.getPlateByName("tungstensteel"), 'T', getOre("hvTransformer"), 'G', "ic2Generator", 'C', "circuitMaster"); // Smetling CraftingHelper .addSmelting(ItemDusts.getDustByName("copper", 1), getOre("ingotCopper"), 1F); CraftingHelper .addSmelting(ItemDusts.getDustByName("tin", 1), ItemIngots.getIngotByName("tin"), 1F); CraftingHelper .addSmelting(ItemDusts.getDustByName("bronze", 1), ItemIngots.getIngotByName("bronze"), 1F); CraftingHelper .addSmelting(ItemDusts.getDustByName("lead", 1), ItemIngots.getIngotByName("lead"), 1F); CraftingHelper .addSmelting(ItemDusts.getDustByName("silver", 1), ItemIngots.getIngotByName("silver"), 1F); if (ConfigTechReborn.UUrecipesIridiamOre) CraftingHelper .addShapedOreRecipe((OreDictionary.getOres("oreIridium").get(0)), "UUU", " U ", "UUU", 'U', ModItems.uuMatter); // Blast Furnace RecipeHandler.addRecipe(new BlastFurnaceRecipe(ItemCells.getCellByName("silicon", 2), null, ItemPlates.getPlateByName("silicon"), ItemCells.getCellByName("empty", 2), 1000, 120, 1500)); // CentrifugeRecipes // Plantball/Bio Chaff // FIX with ic2 // RecipeHandler.addRecipe(new CentrifugeRecipe(new // ItemStack(Blocks.grass, 16), null, new // ItemStack(TechRebornAPI.recipeCompact.getItem("biochaff").getItem(), // 8), new // ItemStack(TechRebornAPI.recipeCompact.getItem("plantBall").getItem(), // 8), new ItemStack(Items.clay_ball), new ItemStack(Blocks.sand, 8), // 2500, 5)); // RecipeHandler.addRecipe(new CentrifugeRecipe(new // ItemStack(Blocks.dirt, 16), null, new // ItemStack(TechRebornAPI.recipeCompact.getItem("biochaff").getItem(), // 4), new // ItemStack(TechRebornAPI.recipeCompact.getItem("plantBall").getItem(), // 4), new ItemStack(Items.clay_ball), new ItemStack(Blocks.sand, 8), // 2500, 5)); // Methane RecipeHandler.addRecipe( new CentrifugeRecipe(new ItemStack(Items.MUSHROOM_STEW, 16), ItemCells.getCellByName("empty"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHandler.addRecipe(new CentrifugeRecipe(new ItemStack(Items.APPLE, 32), ItemCells.getCellByName("empty"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHandler.addRecipe( new CentrifugeRecipe(new ItemStack(Items.PORKCHOP, 12), ItemCells.getCellByName("empty"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHandler.addRecipe( new CentrifugeRecipe(new ItemStack(Items.COOKED_PORKCHOP, 16), ItemCells.getCellByName("empty"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHandler.addRecipe(new CentrifugeRecipe(new ItemStack(Items.BREAD, 64), ItemCells.getCellByName("empty"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHandler.addRecipe(new CentrifugeRecipe(new ItemStack(Items.FISH, 12), ItemCells.getCellByName("empty"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHandler.addRecipe( new CentrifugeRecipe(new ItemStack(Items.COOKED_FISH, 16), ItemCells.getCellByName("empty"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHandler.addRecipe(new CentrifugeRecipe(new ItemStack(Items.BEEF, 12), ItemCells.getCellByName("empty"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHandler.addRecipe( new CentrifugeRecipe(new ItemStack(Items.COOKED_BEEF, 16), ItemCells.getCellByName("empty"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHandler.addRecipe( new CentrifugeRecipe(new ItemStack(Blocks.PUMPKIN, 16), ItemCells.getCellByName("empty"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHandler.addRecipe( new CentrifugeRecipe(new ItemStack(Items.SPECKLED_MELON, 1), ItemCells.getCellByName("empty"), ItemCells.getCellByName("methane", 1), new ItemStack(Items.GOLD_NUGGET, 6), null, null, 5000, 5)); RecipeHandler.addRecipe( new CentrifugeRecipe(new ItemStack(Items.SPIDER_EYE, 32), ItemCells.getCellByName("empty"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHandler.addRecipe(new CentrifugeRecipe(new ItemStack(Items.CHICKEN, 12), ItemCells.getCellByName("empty"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHandler.addRecipe( new CentrifugeRecipe(new ItemStack(Items.COOKED_CHICKEN, 16), ItemCells.getCellByName("empty"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHandler.addRecipe( new CentrifugeRecipe(new ItemStack(Items.ROTTEN_FLESH, 16), ItemCells.getCellByName("empty"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHandler.addRecipe(new CentrifugeRecipe(new ItemStack(Items.MELON, 64), ItemCells.getCellByName("empty"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHandler.addRecipe(new CentrifugeRecipe(new ItemStack(Items.COOKIE, 64), ItemCells.getCellByName("empty"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHandler.addRecipe(new CentrifugeRecipe(new ItemStack(Items.CAKE, 8), ItemCells.getCellByName("empty"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHandler.addRecipe( new CentrifugeRecipe(new ItemStack(Items.GOLDEN_CARROT, 1), ItemCells.getCellByName("empty"), ItemCells.getCellByName("methane", 1), new ItemStack(Items.GOLD_NUGGET, 6), null, null, 5000, 5)); RecipeHandler.addRecipe(new CentrifugeRecipe(new ItemStack(Items.CARROT, 16), ItemCells.getCellByName("empty"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHandler.addRecipe( new CentrifugeRecipe(new ItemStack(Items.BAKED_POTATO, 24), ItemCells.getCellByName("empty"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHandler.addRecipe(new CentrifugeRecipe(new ItemStack(Items.POTATO, 16), ItemCells.getCellByName("empty"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHandler.addRecipe( new CentrifugeRecipe(new ItemStack(Items.POISONOUS_POTATO, 12), ItemCells.getCellByName("empty"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHandler.addRecipe( new CentrifugeRecipe(new ItemStack(Items.NETHER_WART, 1), ItemCells.getCellByName("empty"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); // Fix with ic2 // RecipeHandler.addRecipe(new CentrifugeRecipe(new // ItemStack(TechRebornAPI.recipeCompact.getItem("terraWart").getItem(), // 16), ItemCells.getCellByName("empty"), // ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHandler.addRecipe( new CentrifugeRecipe(new ItemStack(Blocks.BROWN_MUSHROOM, 1), ItemCells.getCellByName("empty"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); RecipeHandler.addRecipe( new CentrifugeRecipe(new ItemStack(Blocks.RED_MUSHROOM, 1), ItemCells.getCellByName("empty"), ItemCells.getCellByName("methane", 1), null, null, null, 5000, 5)); // Rubber Wood Yields RecipeHandler.addRecipe( new CentrifugeRecipe(new ItemStack(getOre("rubberWood").getItem(), 16), ItemCells.getCellByName("empty", 5), ItemParts.getPartByName("rubber", 8), new ItemStack(Blocks.SAPLING, 6), ItemCells.getCellByName("methane", 1), ItemCells.getCellByName("carbon", 4), 5000, 5, true)); // Soul Sand Byproducts RecipeHandler.addRecipe( new CentrifugeRecipe(new ItemStack(Blocks.SOUL_SAND, 16), ItemCells.getCellByName("empty"), ItemCells.getCellByName("oil", 1), ItemDusts.getDustByName("saltpeter", 4), ItemDusts.getDustByName("coal", 1), new ItemStack(Blocks.SAND, 10), 2500, 5)); // Dust Byproducts RecipeHandler.addRecipe( new CentrifugeRecipe(new ItemStack(Items.GLOWSTONE_DUST, 16), ItemCells.getCellByName("empty"), new ItemStack(Items.REDSTONE, 8), ItemDusts.getDustByName("gold", 8), ItemCells.getCellByName("helium", 1), null, 25000, 5)); RecipeHandler.addRecipe( new CentrifugeRecipe(ItemDusts.getDustByName("phosphorous", 5), ItemCells.getCellByName("empty", 3), ItemCells.getCellByName("calcium", 3), null, null, null, 1280, 5)); RecipeHandler.addRecipe( new CentrifugeRecipe(ItemDusts.getDustByName("ashes", 1), ItemCells.getCellByName("empty"), ItemCells.getCellByName("carbon"), null, null, null, 80, 5)); RecipeHandler.addRecipe( new CentrifugeRecipe(new ItemStack(Items.REDSTONE, 10), ItemCells.getCellByName("empty", 4), ItemCells.getCellByName("silicon", 1), ItemDusts.getDustByName("pyrite", 3), ItemDusts.getDustByName("ruby", 1), ItemCells.getCellByName("mercury", 3), 6800, 5)); RecipeHandler.addRecipe( new CentrifugeRecipe(ItemDusts.getDustByName("endstone", 16), ItemCells.getCellByName("empty", 2), ItemCells.getCellByName("helium3", 1), ItemCells.getCellByName("helium"), ItemDustsSmall.getSmallDustByName("Tungsten", 1), new ItemStack(Blocks.SAND, 12), 4800, 5)); RecipeHandler.addRecipe( new CentrifugeRecipe(ItemDusts.getDustByName("cinnabar", 2), ItemCells.getCellByName("empty"), ItemCells.getCellByName("mercury", 1), ItemDusts.getDustByName("sulfur", 1), null, null, 80, 5)); // Deuterium/Tritium RecipeHandler.addRecipe( new CentrifugeRecipe(ItemCells.getCellByName("helium", 16), null, ItemCells.getCellByName("helium3", 1), ItemCells.getCellByName("empty", 15), null, null, 10000, 5)); RecipeHandler.addRecipe(new CentrifugeRecipe(ItemCells.getCellByName("deuterium", 4), null, ItemCells.getCellByName("tritium", 1), ItemCells.getCellByName("empty", 3), null, null, 3000, 5)); RecipeHandler.addRecipe(new CentrifugeRecipe(ItemCells.getCellByName("hydrogen", 4), null, ItemCells.getCellByName("deuterium", 1), ItemCells.getCellByName("empty", 3), null, null, 3000, 5)); // Lava Cell Byproducts ItemStack lavaCells = ItemCells.getCellByName("lava"); lavaCells.stackSize = 8; RecipeHandler.addRecipe(new CentrifugeRecipe(lavaCells, null, ItemNuggets.getNuggetByName("electrum", 4), ItemIngots.getIngotByName("copper", 2), ItemDustsSmall.getSmallDustByName("Tungsten", 1), ItemIngots.getIngotByName("tin", 2), 6000, 5)); // IndustrialGrinderRecipes RecipeHandler.addRecipe(new IndustrialGrinderRecipe(new ItemStack(Blocks.COAL_ORE, 1), new FluidStack(FluidRegistry.WATER, 1000), new ItemStack(Items.COAL, 1), ItemDustsSmall.getSmallDustByName("Coal", 6), ItemDustsSmall.getSmallDustByName("Coal", 2), null, 100, 120)); RecipeHandler.addRecipe(new IndustrialGrinderRecipe(new ItemStack(Blocks.IRON_ORE, 1), new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("iron", 2), ItemDustsSmall.getSmallDustByName("Nickel", 1), ItemDustsSmall.getSmallDustByName("Tin", 1), null, 100, 120)); RecipeHandler.addRecipe(new IndustrialGrinderRecipe(new ItemStack(Blocks.GOLD_ORE, 1), new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("gold", 2), ItemDustsSmall.getSmallDustByName("Copper", 1), ItemDustsSmall.getSmallDustByName("Nickel", 1), null, 100, 120)); RecipeHandler.addRecipe(new IndustrialGrinderRecipe(new ItemStack(Blocks.IRON_ORE, 1), new FluidStack(ModFluids.fluidSodiumpersulfate, 1000), ItemDusts.getDustByName("iron", 2), ItemDusts.getDustByName("nickel", 1), ItemDustsSmall.getSmallDustByName("Tin", 1), null, 100, 120)); RecipeHandler.addRecipe(new IndustrialGrinderRecipe(new ItemStack(Blocks.GOLD_ORE, 1), new FluidStack(ModFluids.fluidSodiumpersulfate, 1000), ItemDusts.getDustByName("gold", 2), ItemDusts.getDustByName("copper", 1), ItemDustsSmall.getSmallDustByName("Nickel", 1), null, 100, 120)); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(new ItemStack(Blocks.GOLD_ORE, 1), new FluidStack(ModFluids.fluidMercury, 1000), ItemDusts.getDustByName("gold", 3), ItemDustsSmall.getSmallDustByName("Copper", 1), ItemDustsSmall.getSmallDustByName("Nickel", 1), null, 100, 120)); RecipeHandler.addRecipe(new IndustrialGrinderRecipe(new ItemStack(Blocks.DIAMOND_ORE, 1), new FluidStack(FluidRegistry.WATER, 1000), new ItemStack(Items.DIAMOND, 1), ItemDustsSmall.getSmallDustByName("Diamond", 6), ItemDustsSmall.getSmallDustByName("Coal", 2), null, 100, 120)); RecipeHandler.addRecipe(new IndustrialGrinderRecipe(new ItemStack(Blocks.EMERALD_ORE, 1), new FluidStack(FluidRegistry.WATER, 1000), new ItemStack(Items.EMERALD, 1), ItemDustsSmall.getSmallDustByName("Emerald", 6), ItemDustsSmall.getSmallDustByName("Aluminum", 2), null, 100, 120)); RecipeHandler.addRecipe(new IndustrialGrinderRecipe(new ItemStack(Blocks.REDSTONE_ORE, 1), new FluidStack(FluidRegistry.WATER, 1000), new ItemStack(Items.REDSTONE, 10), ItemDustsSmall.getSmallDustByName("Cinnabar", 1), ItemDustsSmall.getSmallDustByName("Glowstone", 1), null, 100, 120)); RecipeHandler.addRecipe(new IndustrialGrinderRecipe(new ItemStack(Blocks.LAPIS_ORE, 1), new FluidStack(FluidRegistry.WATER, 1000), new ItemStack(Items.DYE, 6, 4), ItemDustsSmall.getSmallDustByName("Lazurite", 3), null, null, 100, 120)); // Copper Ore if (OreUtil.doesOreExistAndValid("oreCopper")) { try { ItemStack oreStack = OreDictionary.getOres("oreCopper").get(0); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("copper", 2), ItemDustsSmall.getSmallDustByName("Gold", 1), ItemDustsSmall.getSmallDustByName("Nickel", 1), ItemCells.getCellByName("empty"), 100, 120)); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(ModFluids.fluidSodiumpersulfate, 1000), ItemDusts.getDustByName("copper", 2), ItemDusts.getDustByName("gold", 1), ItemDustsSmall.getSmallDustByName("Nickel", 1), null, 100, 120)); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(ModFluids.fluidMercury, 1000), ItemDusts.getDustByName("copper", 2), ItemDustsSmall.getSmallDustByName("Gold", 1), ItemDusts.getDustByName("nickel", 1), null, 100, 120)); } catch (Exception e) { Core.logHelper.info("Failed to Load Grinder Recipe for Copper Ore"); } } // Tin Ore if (OreUtil.doesOreExistAndValid("oreTin")) { try { ItemStack oreStack = OreDictionary.getOres("oreTin").get(0); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("tin", 2), ItemDustsSmall.getSmallDustByName("Iron", 1), ItemDustsSmall.getSmallDustByName("Zinc", 1), null, 100, 120)); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(ModFluids.fluidSodiumpersulfate, 1000), ItemDusts.getDustByName("tin", 2), ItemDustsSmall.getSmallDustByName("Iron", 1), ItemDusts.getDustByName("zinc", 1), null, 100, 120)); } catch (Exception e) { Core.logHelper.info("Failed to Load Grinder Recipe for Tin Ore"); } } // Nickel Ore if (OreUtil.doesOreExistAndValid("oreNickel")) { try { ItemStack oreStack = OreDictionary.getOres("oreNickel").get(0); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("nickel", 2), ItemDustsSmall.getSmallDustByName("Iron", 1), ItemDustsSmall.getSmallDustByName("Platinum", 1), ItemCells.getCellByName("empty"), 100, 120)); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(ModFluids.fluidSodiumpersulfate, 1000), ItemDusts.getDustByName("nickel", 3), ItemDustsSmall.getSmallDustByName("Iron", 1), ItemDustsSmall.getSmallDustByName("Platinum", 1), null, 100, 120)); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(ModFluids.fluidMercury, 1000), ItemDusts.getDustByName("nickel", 2), ItemDustsSmall.getSmallDustByName("Iron", 1), ItemDusts.getDustByName("platinum", 1), null, 100, 120)); } catch (Exception e) { Core.logHelper.info("Failed to Load Grinder Recipe for Nickel Ore"); } } // Zinc Ore if (OreUtil.doesOreExistAndValid("oreZinc")) { try { ItemStack oreStack = OreDictionary.getOres("oreZinc").get(0); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("zinc", 2), ItemDustsSmall.getSmallDustByName("Iron", 1), ItemDustsSmall.getSmallDustByName("Tin", 1), null, 100, 120)); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(ModFluids.fluidSodiumpersulfate, 1000), ItemDusts.getDustByName("zinc", 2), ItemDustsSmall.getSmallDustByName("Iron", 1), ItemDusts.getDustByName("iron", 1), null, 100, 120)); } catch (Exception e) { Core.logHelper.info("Failed to Load Grinder Recipe for Zinc Ore"); } } // Silver Ore if (OreUtil.doesOreExistAndValid("oreSilver")) { try { ItemStack oreStack = OreDictionary.getOres("oreSilver").get(0); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("silver", 2), ItemDustsSmall.getSmallDustByName("Lead", 1), ItemDustsSmall.getSmallDustByName("Sulfur", 1), null, 100, 120)); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(ModFluids.fluidMercury, 1000), ItemDusts.getDustByName("silver", 3), ItemDustsSmall.getSmallDustByName("Lead", 1), ItemDustsSmall.getSmallDustByName("Sulfur", 1), null, 100, 120)); } catch (Exception e) { Core.logHelper.info("Failed to Load Grinder Recipe for Silver Ore"); } } // Lead Ore if (OreUtil.doesOreExistAndValid("oreLead")) { try { ItemStack oreStack = OreDictionary.getOres("oreLead").get(0); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("lead", 2), ItemDustsSmall.getSmallDustByName("Silver", 1), ItemDustsSmall.getSmallDustByName("Sulfur", 1), null, 100, 120)); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(ModFluids.fluidMercury, 1000), ItemDusts.getDustByName("lead", 2), ItemDusts.getDustByName("silver", 1), ItemDustsSmall.getSmallDustByName("Sulfur", 1), null, 100, 120)); } catch (Exception e) { Core.logHelper.info("Failed to Load Grinder Recipe for Lead Ore"); } } // Uranium Ore if (OreUtil.doesOreExistAndValid("oreUranium")) { try { ItemStack oreStack = OreDictionary.getOres("oreUranium").get(0); ItemStack uranium238Stack = getOre("uran238"); uranium238Stack.stackSize = 8; ItemStack uranium235Stack = getOre("smallUran235"); uranium235Stack.stackSize = 2; RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), uranium238Stack, uranium235Stack, null, null, 100, 120)); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), uranium238Stack, uranium235Stack, null, ItemCells.getCellByName("empty"), 100, 120)); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), uranium238Stack, uranium235Stack, null, new ItemStack(Items.BUCKET), 100, 120)); } catch (Exception e) { Core.logHelper.info("Failed to Load Grinder Recipe for Uranium Ore"); } } // Pitchblende Ore if (OreUtil.doesOreExistAndValid("orePitchblende")) { try { ItemStack oreStack = OreDictionary.getOres("orePitchblende").get(0); ItemStack uranium238Stack = getOre("uran238"); uranium238Stack.stackSize = 8; ItemStack uranium235Stack = getOre("uran235"); uranium235Stack.stackSize = 2; RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), uranium238Stack, uranium235Stack, null, null, 100, 120)); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), uranium238Stack, uranium235Stack, null, ItemCells.getCellByName("empty"), 100, 120)); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), uranium238Stack, uranium235Stack, null, new ItemStack(Items.BUCKET), 100, 120)); } catch (Exception e) { Core.logHelper.info("Failed to Load Grinder Recipe for Uranium Ore"); } } // Aluminum Ore if (OreUtil.doesOreExistAndValid("oreAluminum")) { try { ItemStack oreStack = OreDictionary.getOres("oreAluminum").get(0); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("aluminum", 2), ItemDustsSmall.getSmallDustByName("Bauxite", 1), ItemDustsSmall.getSmallDustByName("Bauxite", 1), ItemCells.getCellByName("empty"), 100, 120)); } catch (Exception e) { Core.logHelper.info("Failed to Load Grinder Recipe for Lead Ore"); } } // Ardite Ore if (OreUtil.doesOreExistAndValid("oreArdite")) { try { ItemStack oreStack = OreDictionary.getOres("oreArdite").get(0); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("ardite", 2), ItemDustsSmall.getSmallDustByName("Ardite", 1), ItemDustsSmall.getSmallDustByName("Ardite", 1), ItemCells.getCellByName("empty"), 100, 120)); } catch (Exception e) { Core.logHelper.info("Failed to Load Grinder Recipe for Ardite Ore"); } } // Cobalt Ore if (OreUtil.doesOreExistAndValid("oreCobalt")) { try { ItemStack oreStack = OreDictionary.getOres("oreCobalt").get(0); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("cobalt", 2), ItemDustsSmall.getSmallDustByName("Cobalt", 1), ItemDustsSmall.getSmallDustByName("Cobalt", 1), ItemCells.getCellByName("empty"), 100, 120)); } catch (Exception e) { Core.logHelper.info("Failed to Load Grinder Recipe for Cobalt Ore"); } } // Dark Iron Ore if (OreUtil.doesOreExistAndValid("oreDarkIron")) { try { ItemStack oreStack = OreDictionary.getOres("oreDarkIron").get(0); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("darkIron", 2), ItemDustsSmall.getSmallDustByName("DarkIron", 1), ItemDustsSmall.getSmallDustByName("Iron", 1), ItemCells.getCellByName("empty"), 100, 120)); } catch (Exception e) { Core.logHelper.info("Failed to Load Grinder Recipe for Dark Iron Ore"); } } // Cadmium Ore if (OreUtil.doesOreExistAndValid("oreCadmium")) { try { ItemStack oreStack = OreDictionary.getOres("oreCadmium").get(0); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("cadmium", 2), ItemDustsSmall.getSmallDustByName("Cadmium", 1), ItemDustsSmall.getSmallDustByName("Cadmium", 1), ItemCells.getCellByName("empty"), 100, 120)); } catch (Exception e) { Core.logHelper.info("Failed to Load Grinder Recipe for Cadmium Ore"); } } // Indium Ore if (OreUtil.doesOreExistAndValid("oreIndium")) { try { ItemStack oreStack = OreDictionary.getOres("oreIndium").get(0); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("indium", 2), ItemDustsSmall.getSmallDustByName("Indium", 1), ItemDustsSmall.getSmallDustByName("Indium", 1), ItemCells.getCellByName("empty"), 100, 120)); } catch (Exception e) { Core.logHelper.info("Failed to Load Grinder Recipe for Indium Ore"); } } // Calcite Ore if (OreUtil.doesOreExistAndValid("oreCalcite") && OreUtil.doesOreExistAndValid("gemCalcite")) { try { ItemStack oreStack = OreDictionary.getOres("oreCalcite").get(0); ItemStack gemStack = OreDictionary.getOres("gemCalcite").get(0); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), gemStack, ItemDustsSmall.getSmallDustByName("Calcite", 6), null, ItemCells.getCellByName("empty"), 100, 120)); } catch (Exception e) { Core.logHelper.info("Failed to Load Grinder Recipe for Calcite Ore"); } } // Magnetite Ore if (OreUtil.doesOreExistAndValid("oreMagnetite") && OreUtil.doesOreExistAndValid("chunkMagnetite")) { try { ItemStack oreStack = OreDictionary.getOres("oreMagnetite").get(0); ItemStack chunkStack = OreDictionary.getOres("chunkMagnetite").get(0); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), chunkStack, ItemDustsSmall.getSmallDustByName("Magnetite", 6), null, ItemCells.getCellByName("empty"), 100, 120)); } catch (Exception e) { Core.logHelper.info("Failed to Load Grinder Recipe for Magnetite Ore"); } } // Graphite Ore if (OreUtil.doesOreExistAndValid("oreGraphite") && OreUtil.doesOreExistAndValid("chunkGraphite")) { try { ItemStack oreStack = OreDictionary.getOres("oreGraphite").get(0); ItemStack chunkStack = OreDictionary.getOres("chunkGraphite").get(0); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), chunkStack, ItemDustsSmall.getSmallDustByName("Graphite", 6), null, ItemCells.getCellByName("empty"), 100, 120)); } catch (Exception e) { Core.logHelper.info("Failed to Load Grinder Recipe for Graphite Ore"); } } // Osmium Ore if (OreUtil.doesOreExistAndValid("oreOsmium")) { try { ItemStack oreStack = OreDictionary.getOres("oreOsmium").get(0); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("osmium", 2), ItemDustsSmall.getSmallDustByName("Osmium", 1), ItemDustsSmall.getSmallDustByName("Osmium", 1), ItemCells.getCellByName("empty"), 100, 120)); } catch (Exception e) { Core.logHelper.info("Failed to Load Grinder Recipe for Osmium Ore"); } } // Teslatite Ore if (OreUtil.doesOreExistAndValid("oreTeslatite") && OreUtil.doesOreExistAndValid("dustTeslatite")) { try { ItemStack oreStack = OreDictionary.getOres("oreTeslatite").get(0); ItemStack dustStack = OreDictionary.getOres("dustTeslatite").get(0); dustStack.stackSize = 10; RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), dustStack, ItemDustsSmall.getSmallDustByName("Sodalite", 1), ItemDustsSmall.getSmallDustByName("Glowstone", 1), ItemCells.getCellByName("empty"), 100, 120)); } catch (Exception e) { Core.logHelper.info("Failed to Load Grinder Recipe for Teslatite Ore"); } } // Sulfur Ore if (OreUtil.doesOreExistAndValid("oreSulfur")) { try { ItemStack oreStack = OreDictionary.getOres("oreSulfur").get(0); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("sulfur", 2), ItemDustsSmall.getSmallDustByName("Sulfur", 1), ItemDustsSmall.getSmallDustByName("Sulfur", 1), ItemCells.getCellByName("empty"), 100, 120)); } catch (Exception e) { Core.logHelper.info("Failed to Load Grinder Recipe for Sulfur Ore"); } } // Saltpeter Ore if (OreUtil.doesOreExistAndValid("oreSaltpeter")) { try { ItemStack oreStack = OreDictionary.getOres("oreSaltpeter").get(0); RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("saltpeter", 2), ItemDustsSmall.getSmallDustByName("Saltpeter", 1), ItemDustsSmall.getSmallDustByName("Saltpeter", 1), ItemCells.getCellByName("empty"), 100, 120)); } catch (Exception e) { Core.logHelper.info("Failed to Load Grinder Recipe for Saltpeter Ore"); } } // Apatite Ore if (OreUtil.doesOreExistAndValid("oreApatite") & OreUtil.doesOreExistAndValid("gemApatite")) { try { ItemStack oreStack = OreDictionary.getOres("oreApatite").get(0); ItemStack gemStack = OreDictionary.getOres("gemApatite").get(0); gemStack.stackSize = 6; RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), gemStack, gemStack, ItemDustsSmall.getSmallDustByName("Phosphorous", 4), ItemCells.getCellByName("empty"), 100, 120)); } catch (Exception e) { Core.logHelper.info("Failed to Load Grinder Recipe for Apatite Ore"); } } // Nether Quartz Ore if (OreUtil.doesOreExistAndValid("dustNetherQuartz")) { try { ItemStack dustStack = OreDictionary.getOres("dustNetherQuartz").get(0); dustStack.stackSize = 4; RecipeHandler.addRecipe(new IndustrialGrinderRecipe(new ItemStack(Blocks.QUARTZ_ORE, 1), new FluidStack(FluidRegistry.WATER, 1000), new ItemStack(Items.QUARTZ, 2), dustStack, ItemDustsSmall.getSmallDustByName("Netherrack", 2), ItemCells.getCellByName("empty"), 100, 120)); } catch (Exception e) { Core.logHelper.info("Failed to Load Grinder Recipe for Nether Quartz Ore"); } } // Certus Quartz Ore if (OreUtil.doesOreExistAndValid("oreCertusQuartz")) { try { ItemStack oreStack = OreDictionary.getOres("oreCertusQuartz").get(0); ItemStack gemStack = OreDictionary.getOres("crystalCertusQuartz").get(0); ItemStack dustStack = OreDictionary.getOres("dustCertusQuartz").get(0); dustStack.stackSize = 2; RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), gemStack, dustStack, null, ItemCells.getCellByName("empty"), 100, 120)); } catch (Exception e) { Core.logHelper.info("Failed to Load Grinder Recipe for Certus Quartz Ore"); } } // Charged Certus Quartz Ore if (OreUtil.doesOreExistAndValid("oreChargedCertusQuartz")) { try { ItemStack oreStack = OreDictionary.getOres("oreChargedCertusQuartz").get(0); ItemStack gemStack = OreDictionary.getOres("crystalChargedCertusQuartz").get(0); ItemStack dustStack = OreDictionary.getOres("dustCertusQuartz").get(0); dustStack.stackSize = 2; RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), gemStack, dustStack, null, ItemCells.getCellByName("empty"), 100, 120)); } catch (Exception e) { Core.logHelper.info("Failed to Load Grinder Recipe for Charged Certus Quartz Ore"); } } // Amethyst Ore if (OreUtil.doesOreExistAndValid("oreAmethyst") && OreUtil.doesOreExistAndValid("gemAmethyst")) { try { ItemStack oreStack = OreDictionary.getOres("oreAmethyst").get(0); ItemStack gemStack = OreDictionary.getOres("gemAmethyst").get(0); gemStack.stackSize = 2; ItemStack dustStack = OreDictionary.getOres("gemAmethyst").get(0); dustStack.stackSize = 1; RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), gemStack, dustStack, null, ItemCells.getCellByName("empty"), 100, 120)); } catch (Exception e) { Core.logHelper.info("Failed to Load Grinder Recipe for Certus Quartz Ore"); } } // Topaz Ore if (OreUtil.doesOreExistAndValid("oreTopaz") && OreUtil.doesOreExistAndValid("gemTopaz")) { try { ItemStack oreStack = OreDictionary.getOres("oreTopaz").get(0); ItemStack gemStack = OreDictionary.getOres("gemTopaz").get(0); gemStack.stackSize = 2; ItemStack dustStack = OreDictionary.getOres("gemTopaz").get(0); dustStack.stackSize = 1; RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), gemStack, dustStack, null, null, 100, 120)); } catch (Exception e) { Core.logHelper.info("Failed to Load Grinder Recipe for Topaz Ore"); } } // Tanzanite Ore if (OreUtil.doesOreExistAndValid("oreTanzanite") && OreUtil.doesOreExistAndValid("gemTanzanite")) { try { ItemStack oreStack = OreDictionary.getOres("oreTanzanite").get(0); ItemStack gemStack = OreDictionary.getOres("gemTanzanite").get(0); gemStack.stackSize = 2; ItemStack dustStack = OreDictionary.getOres("gemTanzanite").get(0); dustStack.stackSize = 1; RecipeHandler.addRecipe( new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), gemStack, dustStack, null, null, 100, 120)); } catch (Exception e) { Core.logHelper.info("Failed to Load Grinder Recipe for Tanzanite Ore"); } } // Malachite Ore if (OreUtil.doesOreExistAndValid("oreMalachite") && OreUtil.doesOreExistAndValid("gemMalachite")) { try { ItemStack oreStack = OreDictionary.getOres("oreMalachite").get(0); ItemStack gemStack = OreDictionary.getOres("gemMalachite").get(0); gemStack.stackSize = 2; ItemStack dustStack = OreDictionary.getOres("gemMalachite").get(0); dustStack.stackSize = 1; RecipeHandler.addRecipe(new IndustrialGrinderRecipe(oreStack, new FluidStack(FluidRegistry.WATER, 1000), gemStack, dustStack, null, null, 100, 120)); } catch (Exception e) { Core.logHelper.info("Failed to Load Grinder Recipe for Malachite Ore"); } } // Implosion Compressor RecipeHandler.addRecipe(new ImplosionCompressorRecipe(ItemIngots.getIngotByName("iridiumAlloy"), new ItemStack(Blocks.TNT, 8), OreDictionary.getOres("plateIridium").get(0).copy(), ItemDusts.getDustByName("darkAshes", 4), 20, 30)); RecipeHandler.addRecipe(new ImplosionCompressorRecipe(ItemDusts.getDustByName("diamond", 4), new ItemStack(Blocks.TNT, 32), new ItemStack(Items.DIAMOND, 3), ItemDusts.getDustByName("darkAshes", 16), 20, 30)); RecipeHandler.addRecipe(new ImplosionCompressorRecipe(ItemDusts.getDustByName("emerald", 4), new ItemStack(Blocks.TNT, 24), new ItemStack(Items.EMERALD, 3), ItemDusts.getDustByName("darkAshes", 12), 20, 30)); RecipeHandler.addRecipe(new ImplosionCompressorRecipe(ItemDusts.getDustByName("sapphire", 4), new ItemStack(Blocks.TNT, 24), ItemGems.getGemByName("sapphire", 3), ItemDusts.getDustByName("darkAshes", 12), 20, 30)); RecipeHandler.addRecipe(new ImplosionCompressorRecipe(ItemDusts.getDustByName("ruby", 4), new ItemStack(Blocks.TNT, 24), ItemGems.getGemByName("ruby", 3), ItemDusts.getDustByName("darkAshes", 12), 20, 30)); RecipeHandler.addRecipe(new ImplosionCompressorRecipe(ItemDusts.getDustByName("yellowGarnet", 4), new ItemStack(Blocks.TNT, 24), ItemGems.getGemByName("yellowGarnet", 3), ItemDusts.getDustByName("darkAshes", 12), 20, 30)); RecipeHandler.addRecipe(new ImplosionCompressorRecipe(ItemDusts.getDustByName("redGarnet", 4), new ItemStack(Blocks.TNT, 24), ItemGems.getGemByName("redGarnet", 3), ItemDusts.getDustByName("darkAshes", 12), 20, 30)); RecipeHandler.addRecipe(new ImplosionCompressorRecipe(ItemDusts.getDustByName("peridot", 4), new ItemStack(Blocks.TNT, 24), ItemGems.getGemByName("peridot", 3), ItemDusts.getDustByName("darkAshes", 12), 20, 30)); // Grinder RecipeHandler.addRecipe(new IndustrialGrinderRecipe( new ItemStack(ModBlocks.ore, 1, 0), new FluidStack(ModFluids.fluidMercury, 1000), ItemDusts.getDustByName("galena", 2), ItemDustsSmall.getSmallDustByName("Sulfur", 1), ItemDustsSmall.getSmallDustByName("Silver", 1), null, 100, 120)); // Iridium Ore RecipeHandler.addRecipe(new IndustrialGrinderRecipe( new ItemStack(ModBlocks.ore, 1, 1), new FluidStack(FluidRegistry.WATER, 1000), OreDictionary.getOres("oreIridium").get(0), ItemDustsSmall.getSmallDustByName("Platinum", 2), null, null, 100, 120)); RecipeHandler.addRecipe(new IndustrialGrinderRecipe( new ItemStack(ModBlocks.ore, 1, 1), new FluidStack(ModFluids.fluidMercury, 1000), OreDictionary.getOres("oreIridium").get(0), ItemDustsSmall.getSmallDustByName("Platinum", 2), null, null, 100, 120)); RecipeHandler.addRecipe(new IndustrialGrinderRecipe( new ItemStack(ModBlocks.ore, 1, 1), new FluidStack(ModFluids.fluidMercury, 1000), OreDictionary.getOres("oreIridium").get(0), ItemDustsSmall.getSmallDustByName("Platinum", 2), null, null, 100, 120)); RecipeHandler.addRecipe(new IndustrialGrinderRecipe( new ItemStack(ModBlocks.ore, 1, 2), new FluidStack(FluidRegistry.WATER, 1000), ItemGems.getGemByName("ruby", 1), ItemDustsSmall.getSmallDustByName("Ruby", 6), ItemDustsSmall.getSmallDustByName("Chrome", 2), null, 100, 120)); RecipeHandler.addRecipe(new IndustrialGrinderRecipe( new ItemStack(ModBlocks.ore, 1, 3), new FluidStack(FluidRegistry.WATER, 1000), ItemGems.getGemByName("sapphire", 1), ItemDustsSmall.getSmallDustByName("Sapphire", 6), ItemDustsSmall.getSmallDustByName("Aluminum", 2), null, 100, 120)); RecipeHandler.addRecipe(new IndustrialGrinderRecipe( new ItemStack(ModBlocks.ore, 1, 4), new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("bauxite", 2), ItemDustsSmall.getSmallDustByName("Grossular", 4), ItemDustsSmall.getSmallDustByName("Titanium", 4), null, 100, 120)); RecipeHandler.addRecipe(new IndustrialGrinderRecipe( new ItemStack(ModBlocks.ore, 1, 5), new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("pyrite", 2), ItemDustsSmall.getSmallDustByName("Sulfur", 1), ItemDustsSmall.getSmallDustByName("Phosphorous", 1), null, 100, 120)); RecipeHandler.addRecipe(new IndustrialGrinderRecipe( new ItemStack(ModBlocks.ore, 1, 6), new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("cinnabar", 2), ItemDustsSmall.getSmallDustByName("Redstone", 1), ItemDustsSmall.getSmallDustByName("Glowstone", 1), null, 100, 120)); RecipeHandler.addRecipe(new IndustrialGrinderRecipe( new ItemStack(ModBlocks.ore, 1, 7), new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("sphalerite", 2), ItemDustsSmall.getSmallDustByName("Zinc", 1), ItemDustsSmall.getSmallDustByName("YellowGarnet", 1), null, 100, 120)); RecipeHandler.addRecipe(new IndustrialGrinderRecipe( new ItemStack(ModBlocks.ore, 1, 7), new FluidStack(ModFluids.fluidSodiumpersulfate, 1000), ItemDusts.getDustByName("sphalerite", 2), ItemDusts.getDustByName("zinc", 1), ItemDustsSmall.getSmallDustByName("YellowGarnet", 1), null, 100, 120)); RecipeHandler.addRecipe(new IndustrialGrinderRecipe( new ItemStack(ModBlocks.ore, 1, 8), new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("tungsten", 2), ItemDustsSmall.getSmallDustByName("Manganese", 1), ItemDustsSmall.getSmallDustByName("Silver", 1), null, 100, 120)); RecipeHandler.addRecipe( new IndustrialGrinderRecipe( new ItemStack(ModBlocks.ore, 1, 8), new FluidStack(ModFluids.fluidMercury, 1000), ItemDusts.getDustByName("tungsten", 2), ItemDustsSmall.getSmallDustByName("Manganese", 2), ItemDusts.getDustByName("silver", 3), null, 100, 120)); RecipeHandler.addRecipe(new IndustrialGrinderRecipe( new ItemStack(ModBlocks.ore, 1, 9), new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("platinum", 2), ItemDusts.getDustByName("nickel", 1), ItemNuggets.getNuggetByName("iridium", 2), null, 100, 120)); RecipeHandler.addRecipe( new IndustrialGrinderRecipe( new ItemStack(ModBlocks.ore, 1, 9), new FluidStack(ModFluids.fluidMercury, 1000), ItemDusts.getDustByName("platinum", 3), ItemDusts.getDustByName("nickel", 1), ItemNuggets.getNuggetByName("iridium", 3), null, 100, 120)); RecipeHandler.addRecipe(new IndustrialGrinderRecipe( new ItemStack(ModBlocks.ore, 1, 10), new FluidStack(FluidRegistry.WATER, 1000), ItemGems.getGemByName("peridot", 1), ItemDustsSmall.getSmallDustByName("Peridot", 6), ItemDustsSmall.getSmallDustByName("Pyrope", 2), null, 100, 120)); RecipeHandler.addRecipe(new IndustrialGrinderRecipe( new ItemStack(ModBlocks.ore, 1, 11), new FluidStack(FluidRegistry.WATER, 1000), ItemDusts.getDustByName("sodalite", 12), ItemDustsSmall.getSmallDustByName("aluminum", 3), null, null, 100, 120)); // Chemical Reactor RecipeHandler.addRecipe(new ChemicalReactorRecipe(ItemDusts.getDustByName("calcite", 1), null, new ItemStack(OreDictionary.getOres("fertilizer").get(0).getItem(), 1), 100, 30)); RecipeHandler.addRecipe(new ChemicalReactorRecipe(ItemDusts.getDustByName("calcite", 1), ItemDusts.getDustByName("phosphorous", 1), new ItemStack(OreDictionary.getOres("fertilizer").get(0).getItem(), 3), 100, 30)); RecipeHandler.addRecipe(new ChemicalReactorRecipe(ItemCells.getCellByName("sodiumSulfide", 1), ItemCells.getCellByName("empty"), ItemCells.getCellByName("sodiumPersulfate", 2), 2000, 30)); RecipeHandler.addRecipe(new ChemicalReactorRecipe(ItemCells.getCellByName("nitrocarbon", 1), ItemCells.getCellByName("water"), ItemCells.getCellByName("glyceryl", 2), 580, 30)); RecipeHandler.addRecipe( new ChemicalReactorRecipe(ItemDusts.getDustByName("calcite", 1), ItemDusts.getDustByName("sulfur", 1), new ItemStack(OreDictionary.getOres("fertilizer").get(0).getItem(), 2), 100, 30)); ItemStack waterCells = ItemCells.getCellByName("water").copy(); waterCells.stackSize = 2; RecipeHandler.addRecipe(new ChemicalReactorRecipe(ItemCells.getCellByName("sulfur", 1), waterCells, ItemCells.getCellByName("sulfuricAcid", 3), 1140, 30)); ItemStack waterCells2 = ItemCells.getCellByName("water").copy(); waterCells2.stackSize = 5; RecipeHandler.addRecipe(new ChemicalReactorRecipe(ItemCells.getCellByName("hydrogen", 4), ItemCells.getCellByName("empty"), waterCells2, 10, 30)); RecipeHandler.addRecipe(new ChemicalReactorRecipe(ItemCells.getCellByName("nitrogen", 1), ItemCells.getCellByName("empty"), ItemCells.getCellByName("nitrogenDioxide", 2), 1240, 30)); // IndustrialElectrolyzer RecipeHandler.addRecipe(new IndustrialElectrolyzerRecipe(ItemCells.getCellByName("sulfuricAcid", 7), null, ItemCells.getCellByName("hydrogen", 2), ItemDusts.getDustByName("sulfur"), ItemCells.getCellByName("empty", 2), ItemCells.getCellByName("empty", 3), 400, 90)); RecipeHandler.addRecipe( new IndustrialElectrolyzerRecipe(ItemDusts.getDustByName("ruby", 9), ItemCells.getCellByName("empty"), ItemDusts.getDustByName("aluminum", 2), ItemCells.getCellByName("empty", 1), ItemDusts.getDustByName("chrome", 1), null, 140, 90)); RecipeHandler.addRecipe(new IndustrialElectrolyzerRecipe(ItemDusts.getDustByName("sapphire", 8), ItemCells.getCellByName("empty"), ItemDusts.getDustByName("aluminum", 2), ItemCells.getCellByName("empty"), null, null, 100, 60)); RecipeHandler.addRecipe(new IndustrialElectrolyzerRecipe(ItemCells.getCellByName("sodiumSulfide", 2), null, ItemCells.getCellByName("sodium", 1), ItemDusts.getDustByName("sulfur", 1), null, ItemCells.getCellByName("empty"), 200, 60)); RecipeHandler.addRecipe(new IndustrialElectrolyzerRecipe(ItemDusts.getDustByName("peridot", 5), ItemCells.getCellByName("empty"), ItemDusts.getDustByName("aluminum", 2), ItemCells.getCellByName("empty"), null, null, 100, 60)); RecipeHandler.addRecipe(new IndustrialElectrolyzerRecipe(ItemDusts.getDustByName("emerald", 29), ItemCells.getCellByName("empty", 18), ItemCells.getCellByName("berylium", 3), ItemDusts.getDustByName("aluminum", 2), ItemCells.getCellByName("silicon", 6), ItemCells.getCellByName("empty", 9), 520, 120)); RecipeHandler.addRecipe( new IndustrialElectrolyzerRecipe(new ItemStack(Items.DYE, 3, 15), ItemCells.getCellByName("empty", 1), null, ItemCells.getCellByName("calcium", 1), null, null, 20, 106)); RecipeHandler.addRecipe(new IndustrialElectrolyzerRecipe(ItemCells.getCellByName("glyceryl", 20), null, ItemCells.getCellByName("carbon", 3), ItemCells.getCellByName("hydrogen", 5), ItemCells.getCellByName("nitrogen", 3), ItemCells.getCellByName("empty", 9), 800, 90)); RecipeHandler.addRecipe(new IndustrialElectrolyzerRecipe(ItemDusts.getDustByName("peridot", 9), ItemCells.getCellByName("empty", 4), ItemDusts.getDustByName("magnesium", 2), ItemDusts.getDustByName("iron"), ItemCells.getCellByName("silicon", 2), ItemCells.getCellByName("empty", 2), 200, 120)); RecipeHandler.addRecipe(new IndustrialElectrolyzerRecipe(ItemCells.getCellByName("calciumCarbonate", 5), null, ItemCells.getCellByName("carbon"), ItemCells.getCellByName("calcium"), ItemCells.getCellByName("empty", 1), ItemCells.getCellByName("empty", 2), 400, 90)); RecipeHandler.addRecipe(new IndustrialElectrolyzerRecipe(ItemCells.getCellByName("sodiumPersulfate", 6), null, ItemCells.getCellByName("sodium"), ItemDusts.getDustByName("sulfur"), ItemCells.getCellByName("empty", 2), ItemCells.getCellByName("empty", 3), 420, 90)); RecipeHandler.addRecipe(new IndustrialElectrolyzerRecipe(ItemDusts.getDustByName("pyrope", 20), ItemCells.getCellByName("empty", 9), ItemDusts.getDustByName("aluminum", 2), ItemDusts.getDustByName("magnesium", 3), ItemCells.getCellByName("silicon", 3), ItemCells.getCellByName("empty", 6), 400, 120)); ItemStack sand = new ItemStack(Blocks.SAND); sand.stackSize = 16; RecipeHandler.addRecipe(new IndustrialElectrolyzerRecipe(sand, ItemCells.getCellByName("empty", 2), ItemCells.getCellByName("silicon", 1), ItemCells.getCellByName("empty"), null, null, 1000, 25)); RecipeHandler.addRecipe(new IndustrialElectrolyzerRecipe(ItemDusts.getDustByName("almandine", 20), ItemCells.getCellByName("empty", 9), ItemDusts.getDustByName("aluminum", 2), ItemDusts.getDustByName("iron", 3), ItemCells.getCellByName("silicon", 3), ItemCells.getCellByName("empty", 6), 480, 120)); RecipeHandler.addRecipe(new IndustrialElectrolyzerRecipe(ItemDusts.getDustByName("spessartine", 20), ItemCells.getCellByName("empty", 9), ItemDusts.getDustByName("aluminum", 2), ItemDusts.getDustByName("manganese", 3), ItemCells.getCellByName("silicon", 3), ItemCells.getCellByName("empty", 6), 480, 120)); RecipeHandler.addRecipe(new IndustrialElectrolyzerRecipe(ItemDusts.getDustByName("andradite", 20), ItemCells.getCellByName("empty", 12), ItemCells.getCellByName("calcium", 3), ItemDusts.getDustByName("iron", 2), ItemCells.getCellByName("silicon", 3), ItemCells.getCellByName("empty", 6), 480, 120)); RecipeHandler.addRecipe(new IndustrialElectrolyzerRecipe(ItemDusts.getDustByName("grossular", 20), ItemCells.getCellByName("empty", 12), ItemCells.getCellByName("calcium", 3), ItemDusts.getDustByName("aluminum", 2), ItemCells.getCellByName("silicon", 3), ItemCells.getCellByName("empty", 6), 440, 120)); RecipeHandler.addRecipe(new IndustrialElectrolyzerRecipe(ItemDusts.getDustByName("Uvarovite", 20), ItemCells.getCellByName("empty", 12), ItemCells.getCellByName("calcium", 3), ItemDusts.getDustByName("chrome", 2), ItemCells.getCellByName("silicon", 3), ItemCells.getCellByName("empty", 6), 480, 120)); // RecipeHandler.addRecipe(new IndustrialElectrolyzerRecipe(ItemCells.getCellByName("empty", 6), null, // ItemCells.getCellByName("hydrogen", 4), ItemCells.getCellByName("empty", 5), // ItemCells.getCellByName("empty", 1), null, 100, 30)); RecipeHandler.addRecipe(new IndustrialElectrolyzerRecipe(ItemDusts.getDustByName("darkAshes"), ItemCells.getCellByName("empty", 2), ItemCells.getCellByName("carbon", 2), null, null, null, 20, 30)); if (OreUtil.doesOreExistAndValid("dustSalt")) { ItemStack salt = OreDictionary.getOres("dustSalt").get(0); salt.stackSize = 2; RecipeHandler.addRecipe(new IndustrialElectrolyzerRecipe(salt, ItemCells.getCellByName("empty", 2), ItemCells.getCellByName("sodium"), ItemCells.getCellByName("chlorine"), null, null, 40, 60)); } Item drill = OreDictionary.getOres("drillBasic").get(0).getItem(); ItemStack drillStack = new ItemStack(drill, 1, OreDictionary.WILDCARD_VALUE); if (ConfigTechReborn.ExpensiveMacerator) CraftingHelper .addShapedOreRecipe(getOre("ic2Macerator"), "FDF", "DMD", "FCF", 'F', Items.FLINT, 'D', Items.DIAMOND, 'M', "machineBlockBasic", 'C', "circuitBasic"); if (ConfigTechReborn.ExpensiveDrill) CraftingHelper .addShapedOreRecipe(OreDictionary.getOres("drillBasic").get(0).copy(), " S ", "SCS", "SBS", 'S', "ingotSteel", 'B', "reBattery", 'C', "circuitBasic"); if (ConfigTechReborn.ExpensiveDiamondDrill) CraftingHelper .addShapedOreRecipe(OreDictionary.getOres("drillDiamond").get(0).copy(), " D ", "DBD", "TCT", 'D', "diamondTR", 'T', "ingotTitanium", 'B', drillStack, 'C', "circuitAdvanced"); if (ConfigTechReborn.ExpensiveSolar) CraftingHelper .addShapedOreRecipe(OreDictionary.getOres("ic2SolarPanel").get(0).copy(), "PPP", "SZS", "CGC", 'P', "paneGlass", 'S', ItemPlates.getPlateByName("silicon"), 'Z', "plateCarbon", 'G', "ic2Generator", 'C', "circuitBasic"); CraftingHelper.addShapedOreRecipe(ItemIngots.getIngotByName("iridiumAlloy"), "IAI", "ADA", "IAI", 'I', "ingotIridium", 'D', ItemDusts.getDustByName("diamond"), 'A', "plateAdvancedAlloy"); CraftingHelper .addShapedOreRecipe(new ItemStack(ModItems.lithiumBatpack, 1, OreDictionary.WILDCARD_VALUE), "BCB", "BPB", "B B", 'B', new ItemStack(ModItems.lithiumBattery), 'P', "plateAluminum", 'C', "circuitAdvanced"); CraftingHelper .addShapedOreRecipe(new ItemStack(ModItems.lithiumBattery, 1, OreDictionary.WILDCARD_VALUE), " C ", "PFP", "PFP", 'F', ItemCells.getCellByName("lithium"), 'P', "plateAluminum", 'C', "insulatedGoldCableItem"); CraftingHelper .addShapedOreRecipe(new ItemStack(ModItems.lapotronpack, 1, OreDictionary.WILDCARD_VALUE), "FOF", "SPS", "FIF", 'F', "circuitMaster", 'O', new ItemStack(ModItems.lapotronicOrb), 'S', ItemParts.getPartByName("superConductor"), 'I', "ingotIridium", 'P', new ItemStack(ModItems.lithiumBatpack)); } static void addGemToolRecipes(ItemStack gemsword, ItemStack gempick, ItemStack gemaxe, ItemStack gemHoe, ItemStack gemspade, ItemStack gemhelmet, ItemStack gemchestplate, ItemStack gemleggings, ItemStack gemboots, String gem) { CraftingHelper.addShapedOreRecipe(gemsword, "G", "G", "S", 'S', Items.STICK, 'G', gem); CraftingHelper.addShapedOreRecipe(gempick, "GGG", " S ", " S ", 'S', Items.STICK, 'G', gem); CraftingHelper.addShapedOreRecipe(gemaxe, "GG", " SG", " S", 'S', Items.STICK, 'G', gem); CraftingHelper.addShapedOreRecipe(gemHoe, "GG", " S", " S", 'S', Items.STICK, 'G', gem); CraftingHelper.addShapedOreRecipe(gemspade, "G", "S", "S", 'S', Items.STICK, 'G', gem); CraftingHelper.addShapedOreRecipe(gemhelmet, "GGG", "G G", 'G', gem); CraftingHelper.addShapedOreRecipe(gemchestplate, "G G", "GGG", "GGG", 'G', gem); CraftingHelper.addShapedOreRecipe(gemleggings, "GGG", "G G", "G G", 'G', gem); CraftingHelper.addShapedOreRecipe(gemboots, "G G", "G G", 'G', gem); } public static ItemStack getBucketWithFluid(Fluid fluid) { return UniversalBucket.getFilledBucket(ForgeModContainer.getInstance().universalBucket, fluid); } public static ItemStack getOre(String name) { if (OreDictionary.getOres(name).isEmpty()) { return new ItemStack(ModItems.missingRecipe); } return OreDictionary.getOres(name).get(0).copy(); } }
// $Id:Dorade2Dataset.java 51 2006-07-12 17:13:13Z caron $ package ucar.nc2.dt.radial; import ucar.nc2.dataset.*; import ucar.nc2.dataset.conv._Coordinate; import ucar.nc2.dt.*; import ucar.nc2.units.DateUnit; import ucar.nc2.units.SimpleUnit; import ucar.nc2.VariableSimpleIF; import ucar.nc2.Variable; import ucar.ma2.*; import ucar.ma2.DataType; import java.io.IOException; import java.util.List; import java.util.Date; import java.util.Iterator; import java.util.ArrayList; import thredds.catalog.*; public class Dorade2Dataset extends RadialDatasetSweepAdapter implements TypedDatasetFactoryIF { protected ucar.nc2.units.DateUnit dateUnits; private NetcdfDataset ncd; float [] elev, aziv, disv, lonv, altv, latv; double[] timv; float ranv, cellv, angv, nyqv, rangv, contv, rgainv, bwidthv; // TypedDatasetFactoryIF public boolean isMine(NetcdfDataset ds) { String convention = ds.findAttValueIgnoreCase(null, "Conventions", null); if ((null != convention) && convention.equals(_Coordinate.Convention)) { String format = ds.findAttValueIgnoreCase(null, "Format", null); if (format.equals("Unidata/netCDF/Dorade")) return true; } return false; } public TypedDataset open(NetcdfDataset ncd, ucar.nc2.util.CancelTask task, StringBuffer errlog) throws IOException { return new Dorade2Dataset(ncd); } public thredds.catalog.DataType getScientificDataType() { return thredds.catalog.DataType.RADIAL; } public Dorade2Dataset() {} /** * Constructor. * * @param ds must be from dorade IOSP */ public Dorade2Dataset(NetcdfDataset ds) { super(ds); this.ncd = ds; desc = "dorade radar dataset"; //EarthLocation y = getEarthLocation() ; try { elev = (float []) ncd.findVariable("elevation").read().get1DJavaArray(Float.TYPE); aziv = (float []) ncd.findVariable("azimuth").read().get1DJavaArray(Float.TYPE); altv = (float []) ncd.findVariable("altitudes_1").read().get1DJavaArray(Float.TYPE); lonv = (float []) ncd.findVariable("longitudes_1").read().get1DJavaArray(Float.TYPE); latv = (float []) ncd.findVariable("latitudes_1").read().get1DJavaArray(Float.TYPE); disv = (float []) ncd.findVariable("distance_1").read().get1DJavaArray(Float.TYPE); timv = (double []) ncd.findVariable("rays_time").read().get1DJavaArray(Double.TYPE); angv = ncd.findVariable("Fixed_Angle").readScalarFloat(); nyqv = ncd.findVariable("Nyquist_Velocity").readScalarFloat(); rangv = ncd.findVariable("Unambiguous_Range").readScalarFloat(); contv = ncd.findVariable("Radar_Constant").readScalarFloat(); rgainv = ncd.findVariable("rcvr_gain").readScalarFloat(); //bwidthv = ncd.findVariable("bm_width").readScalarFloat(); } catch (IOException e) { e.printStackTrace(); } setStartDate(); setEndDate(); } public String getRadarID() { return ncd.findGlobalAttribute("radar_name").getStringValue(); } public String getRadarName() { return "Dorade Radar"; } public String getDataFormat() { return "DORADE"; } public ucar.nc2.dt.EarthLocation getCommonOrigin() { if (isStationary()) return new EarthLocationImpl(latv[0], lonv[0], elev[0]); return null; } public boolean isStationary() { String t = ncd.findGlobalAttribute("IsStationary").getStringValue(); return t.equals("1"); // if t == "1" return true } //public boolean isRadial() { // return true; public boolean isVolume() { return false; } protected void setEarthLocation() { if (isStationary()) origin = new EarthLocationImpl(latv[0], lonv[0], elev[0]); origin = null; } protected void addRadialVariable(NetcdfDataset nds, Variable var) { RadialVariable rsvar = null; String vName = var.getShortName() ; int rnk = var.getRank(); if(rnk == 2) { VariableSimpleIF v = new MyRadialVariableAdapter(vName); rsvar = makeRadialVariable(nds, v, var); } if(rsvar != null) dataVariables.add(rsvar); } protected RadialVariable makeRadialVariable(NetcdfDataset nds, VariableSimpleIF v, Variable v0) { return new Dorade2Variable(nds, v, v0); } public java.util.List getDataVariables() { return dataVariables; } protected void setStartDate() { Date da = new Date((long) timv[0]); String start_datetime = da.toString(); if (start_datetime != null) startDate = da; else parseInfo.append("*** start_datetime not Found\n"); } protected void setEndDate() { Date da = new Date((long) timv[timv.length - 1]); String end_datetime = da.toString(); if (end_datetime != null) endDate = da; else parseInfo.append("*** end_datetime not Found\n"); } protected void setTimeUnits() { List axes = ncd.getCoordinateAxes(); for (int i = 0; i < axes.size(); i++) { CoordinateAxis axis = (CoordinateAxis) axes.get(i); if (axis.getAxisType() == AxisType.Time) { String units = axis.getUnitsString(); dateUnits = (DateUnit) SimpleUnit.factory(units); return; } } parseInfo.append("*** Time Units not Found\n"); } public List getAttributes() { return ncd.getRootGroup().getAttributes(); } public ucar.nc2.units.DateUnit getTimeUnits() { return dateUnits; } public void getTimeUnits(ucar.nc2.units.DateUnit dateUnits) { this.dateUnits = dateUnits; } public void clearDatasetMemory() { List rvars = getDataVariables(); Iterator iter = rvars.iterator(); while (iter.hasNext()) { RadialVariable radVar = (RadialVariable)iter.next(); radVar.clearVariableMemory(); } } private class Dorade2Variable extends MyRadialVariableAdapter implements RadialDatasetSweep.RadialVariable {//extends VariableSimpleAdapter { ArrayList sweeps; int nsweeps; String name; float ele, azi, alt, lon, lat; //float rt; //RadialDatasetSweep.Sweep sweep; public int getNumSweeps() { return 1; } public Sweep getSweep(int nsw) { return (Sweep) sweeps.get(nsw); } private Dorade2Variable(NetcdfDataset nds, VariableSimpleIF v, Variable v0) { super(v.getName()); sweeps = new ArrayList(); nsweeps = 0; name = v.getName(); int[] shape = v0.getShape(); int count = v0.getRank() - 1; int ngates = shape[count]; count int nrays = shape[count]; sweeps.add( new Dorade2Sweep(v0, 0, nrays, ngates)) ; } public String toString() { return name; } public float[] readAllData() throws java.io.IOException { Array allData; Sweep spn = (Sweep)sweeps.get(0); Variable v = spn.getsweepVar(); try { allData = v.read(); } catch (IOException e) { throw new IOException(e.getMessage()); } return (float []) allData.get1DJavaArray(Float.TYPE); } public void clearVariableMemory() { // doing nothing } private class Dorade2Sweep implements RadialDatasetSweep.Sweep { int nrays, ngates; double meanElevation = Double.NaN; Variable sweepVar; int sweepno; //int[] shape, origi; Dorade2Sweep(Variable v, int sweepno, int rays, int gates){ this.sweepVar = v; this.nrays = rays; this.ngates = gates; this.sweepno = sweepno; } public Variable getsweepVar(){ return sweepVar; } public RadialDatasetSweep.Type getType() { return null; } public float getLon(int ray) { return lonv[ray]; } public int getGateNumber() { return ngates; } public int getRadialNumber() { return nrays; } public int getSweepIndex() { return 0; } public float[] readData() throws java.io.IOException { return readAllData(); } public float[] readData(int ray) throws java.io.IOException { Array rayData; int [] shape = sweepVar.getShape(); int [] origi = new int[ sweepVar.getRank()]; shape[0] = 1; origi[0] = ray; try { rayData = sweepVar.read(origi, shape); } catch (ucar.ma2.InvalidRangeException e) { throw new IOException(e.getMessage()); } return (float []) rayData.get1DJavaArray(Float.TYPE); } public float getBeamWidth() { // degrees try { bwidthv = ncd.findVariable("bm_width").readScalarFloat(); } catch (java.io.IOException e) { e.printStackTrace(); } return bwidthv; } public float getNyquistFrequency() { return 0.0f; } public float getRangeToFirstGate() { // meters try { ranv = ncd.findVariable("Range_to_First_Cell").readScalarFloat(); } catch (java.io.IOException e) { e.printStackTrace(); } return ranv; } public float getGateSize() { // meters try { cellv = ncd.findVariable("Cell_Spacing").readScalarFloat(); } catch (java.io.IOException e) { e.printStackTrace(); } return cellv; } // coordinates of the radial data, relative to radial origin. public float getMeanElevation() {// degrees from horisontal earth tangent, towards zenith int[] shapeRadial = new int[1]; shapeRadial[0] = nrays; Array data = Array.factory(Float.class, shapeRadial, elev); meanElevation = MAMath.sumDouble(data) / data.getSize(); return (float) meanElevation; } public float getElevation(int ray) {// degrees from horisontal earth tangent, towards zenith return elev[ray]; } public float[] getElevation() {// degrees from horisontal earth tangent, towards zenith return elev; } public float getAzimuth(int ray) { // degrees clockwise from true North return aziv[ray]; } public float[] getAzimuth() { // degrees clockwise from true North return aziv; } public float getTime() { return (float) timv[0]; } public float getTime(int ray) { return (float) timv[ray]; } /** * Location of the origin of the radial */ public ucar.nc2.dt.EarthLocation getOrigin(int ray) { return new EarthLocationImpl(latv[ray], lonv[ray], altv[ray]); } public float getMeanAzimuth() { if (getType() != null) return azi; return 0f; } public Date getStartingTime() { return startDate; } public Date getEndingTime() { return endDate; } public void clearSweepMemory() { // doing nothing for dorade adapter } } // Dorade2Sweep class } // Dorade2Variable private static void testRadialVariable(RadialDatasetSweep.RadialVariable rv) throws IOException { //ucar.nc2.dt.radial.RadialCoordSys rcsys = rv.getRadialCoordSys(); //assert rcsys != null; int nsweep = rv.getNumSweeps(); if (nsweep != 1) { } Sweep sw = rv.getSweep(0); int nrays = sw.getRadialNumber(); float [] ddd = sw.readData(); for (int i = 0; i < nrays; i++) { int ngates = sw.getGateNumber(); float [] d = sw.readData(i); float azi = sw.getAzimuth(i); float ele = sw.getElevation(i); double t = sw.getTime(i); Date da = new Date((long) t); //da.setTime((long)t); String start_datetime = da.toString(); float dis = sw.getRangeToFirstGate(); float beamW = sw.getBeamWidth(); float gsize = sw.getGateSize(); float la = (float) sw.getOrigin(i).getLatitude(); float lo = (float) sw.getOrigin(i).getLongitude(); float al = (float) sw.getOrigin(i).getAltitude(); } } public static void main(String args[]) throws Exception, IOException, InstantiationException, IllegalAccessException { String fileIn = "/home/yuanho/dorade/swp.1020511015815.SP0L.573.1.2_SUR_v1"; RadialDatasetSweep rds = (RadialDatasetSweep) TypedDatasetFactory.open( thredds.catalog.DataType.RADIAL, fileIn, null, new StringBuffer()); String st = rds.getStartDate().toString(); String et = rds.getEndDate().toString(); if (rds.isStationary()) { System.out.println("*** radar is stationary\n"); } List rvars = rds.getDataVariables(); RadialDatasetSweep.RadialVariable vDM = (RadialDatasetSweep.RadialVariable) rds.getDataVariable("DM"); testRadialVariable(vDM); for (int i = 0; i < rvars.size(); i++) { RadialDatasetSweep.RadialVariable rv = (RadialDatasetSweep.RadialVariable) rvars.get(i); testRadialVariable(rv); // RadialCoordSys.makeRadialCoordSys( "desc", CoordinateSystem cs, VariableEnhanced v); // ucar.nc2.dt.radial.RadialCoordSys rcsys = rv.getRadialCoordSys(); } } } // Dorade2Dataset
package org.languagetool.rules.de; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.ResourceBundle; import java.util.Set; import org.apache.commons.lang3.StringUtils; import org.jetbrains.annotations.Nullable; import org.languagetool.AnalyzedSentence; import org.languagetool.AnalyzedToken; import org.languagetool.AnalyzedTokenReadings; import org.languagetool.JLanguageTool; import org.languagetool.language.German; import org.languagetool.rules.Categories; import org.languagetool.rules.Example; import org.languagetool.rules.Rule; import org.languagetool.rules.RuleMatch; import org.languagetool.rules.patterns.PatternToken; import org.languagetool.rules.patterns.PatternTokenBuilder; import org.languagetool.tagging.de.AnalyzedGermanToken; import org.languagetool.tagging.de.GermanToken; import org.languagetool.tagging.de.GermanToken.POSType; import org.languagetool.tagging.disambiguation.rules.DisambiguationPatternRule; /** * Simple agreement checker for German noun phrases. Checks agreement in: * * <ul> * <li>DET/PRO NOUN: e.g. "mein Auto", "der Mann", "die Frau" (correct), "die Haus" (incorrect)</li> * <li>DET/PRO ADJ NOUN: e.g. "der riesige Tisch" (correct), "die riesigen Tisch" (incorrect)</li> * </ul> * * Note that this rule only checks agreement inside the noun phrase, not whether * e.g. the correct case is used. For example, "Es ist das Haus dem Mann" is not * detected as incorrect. * * <p>TODO: the implementation could use a re-write that first detects the relevant noun phrases and then checks agreement * * @author Daniel Naber */ public class AgreementRule extends Rule { private final German language; private enum GrammarCategory { KASUS("Kasus (Fall: Wer/Was, Wessen, Wem, Wen/Was - Beispiel: 'das Fahrrads' statt 'des Fahrrads')"), GENUS("Genus (männlich, weiblich, sächlich - Beispiel: 'der Fahrrad' statt 'das Fahrrad')"), NUMERUS("Numerus (Einzahl, Mehrzahl - Beispiel: 'das Fahrräder' statt 'die Fahrräder')"); private final String displayName; GrammarCategory(String displayName) { this.displayName = displayName; } } private static final List<List<PatternToken>> ANTI_PATTERNS = Arrays.asList( Arrays.asList( new PatternTokenBuilder().posRegex("VER:.*").build(), new PatternTokenBuilder().token("das").build(), new PatternTokenBuilder().tokenRegex("nächste[ns]?").build(), new PatternTokenBuilder().tokenRegex("Montag|Dienstag|Mittwoch|Donnerstag|Freitag|Samstag|Sonntag|Woche|Monat|Jahr").build() ), Arrays.asList( new PatternTokenBuilder().tokenRegex("(?i:ist|war)").build(), new PatternTokenBuilder().token("das").build(), new PatternTokenBuilder().token("Zufall").build() ), Arrays.asList( // "So hatte das Vorteile|Auswirkungen|Konsequenzen..." new PatternTokenBuilder().tokenRegex("(?i:hat(te)?)").build(), new PatternTokenBuilder().token("das").build() ), Arrays.asList( new PatternTokenBuilder().tokenRegex("von|bei").build(), new PatternTokenBuilder().tokenRegex("(vielen|allen)").build(), new PatternTokenBuilder().posRegex("PA2:.*|ADJ:AKK:PLU:.*").build() // "ein von vielen bewundertes Haus" / "Das weckte bei vielen ungute Erinnerungen." ), Arrays.asList( new PatternTokenBuilder().token("für").build(), new PatternTokenBuilder().tokenRegex("(viele|alle|[dm]ich|ihn|sie|uns)").build(), new PatternTokenBuilder().posRegex("ADJ:AKK:.*").build() ), Arrays.asList( new PatternTokenBuilder().tokenRegex("das|die|der").build(), new PatternTokenBuilder().token("einem").build(), new PatternTokenBuilder().token("Angst").build() // "Dinge, die/ Etwas, das einem Angst macht" ), Arrays.asList( new PatternTokenBuilder().token("einem").build(), new PatternTokenBuilder().token("geschenkten").build(), new PatternTokenBuilder().token("Gaul").build() ), Arrays.asList( new PatternTokenBuilder().token("einer").build(), new PatternTokenBuilder().token("jeden").build(), new PatternTokenBuilder().posRegex("SUB:GEN:.*").build() ), Arrays.asList( new PatternTokenBuilder().token("kein").build(), new PatternTokenBuilder().token("schöner").build(), new PatternTokenBuilder().token("Land").build() ), Arrays.asList( new PatternTokenBuilder().pos("SENT_START").build(), new PatternTokenBuilder().tokenRegex("Ist|Sind").build(), new PatternTokenBuilder().token("das").build(), new PatternTokenBuilder().posRegex("SUB:.*").build(), new PatternTokenBuilder().posRegex("PKT|KON:NEB").build()// "Ist das Kunst?" / "Ist das Kunst oder Abfall?" ), Arrays.asList( new PatternTokenBuilder().pos("SENT_START").build(), new PatternTokenBuilder().tokenRegex("Meist(ens)?|Oft(mals)?|Häufig|Selten").build(), new PatternTokenBuilder().tokenRegex("sind|waren|ist").build(), new PatternTokenBuilder().token("das").build(), new PatternTokenBuilder().posRegex("SUB:.*").build() ), Arrays.asList( new PatternTokenBuilder().token("des").build(), new PatternTokenBuilder().token("Lied").build(), new PatternTokenBuilder().token("ich").build()// Wes Brot ich ess, des Lied ich sing ), Arrays.asList( new PatternTokenBuilder().pos("SENT_START").build(), new PatternTokenBuilder().tokenRegex("Das|Dies").build(), new PatternTokenBuilder().posRegex("VER:[123]:.*").build(), new PatternTokenBuilder().posRegex("SUB:NOM:.*").build() ), Arrays.asList( new PatternTokenBuilder().posRegex("ART:.*").build(), // "Das wenige Kilometer breite Tal" new PatternTokenBuilder().posRegex("ADJ:.*").build(), new PatternTokenBuilder().tokenRegex("(Kilo|Zenti|Milli)?meter|Jahre|Monate|Wochen|Tage|Stunden|Minuten|Sekunden").build() ), Arrays.asList( new PatternTokenBuilder().token("Van").build(), new PatternTokenBuilder().token("der").build(), new PatternTokenBuilder().token("Bellen").build() ), Arrays.asList( new PatternTokenBuilder().token("mehrere").build(), new PatternTokenBuilder().pos("SUB:NOM:SIN:FEM:ADJ").build() ), Arrays.asList( new PatternTokenBuilder().token("allen").build(), new PatternTokenBuilder().token("Besitz").build() ), Arrays.asList( new PatternTokenBuilder().tokenRegex("die|den|[md]einen?").build(), new PatternTokenBuilder().token("Top").build(), new PatternTokenBuilder().tokenRegex("\\d+").build() ), Arrays.asList( new PatternTokenBuilder().posRegex("VER:3:SIN:.*").build(), new PatternTokenBuilder().token("das").build(), new PatternTokenBuilder().posRegex("ADJ:AKK:.*").build(), new PatternTokenBuilder().posRegex("SUB:AKK:.*").build(), new PatternTokenBuilder().pos("ZUS").build(), new PatternTokenBuilder().pos("SENT_END").build() ), Arrays.asList( new PatternTokenBuilder().posRegex("VER:3:SIN:.*").build(), new PatternTokenBuilder().token("das").build(), new PatternTokenBuilder().posRegex("SUB:AKK:.*").build(), new PatternTokenBuilder().pos("ZUS").build(), new PatternTokenBuilder().pos("SENT_END").build() ), Arrays.asList( new PatternTokenBuilder().token("Außenring").build(), new PatternTokenBuilder().token("Autobahn").build() ), Arrays.asList( new PatternTokenBuilder().tokenRegex("[dw]em").build(), new PatternTokenBuilder().csToken("Ehre").build(), new PatternTokenBuilder().csToken("gebührt").build() ), Arrays.asList( new PatternTokenBuilder().token("Eurovision").build(), new PatternTokenBuilder().token("Song").build(), new PatternTokenBuilder().token("Contest").build() ), Arrays.asList( // "Das Holocaust Memorial Museum." new PatternTokenBuilder().posRegex("ART:.*").build(), new PatternTokenBuilder().posRegex("SUB:.*").build(), new PatternTokenBuilder().pos("UNKNOWN").build() ), Arrays.asList( new PatternTokenBuilder().csToken(",").build(), new PatternTokenBuilder().posRegex("KON:UNT|ADV:INR").build(), new PatternTokenBuilder().csToken("das").build(), new PatternTokenBuilder().posRegex("SUB:.*").build(), new PatternTokenBuilder().posRegex("VER:3:SIN.*").build() ), Arrays.asList( // "Es gibt viele solcher Bilder" new PatternTokenBuilder().tokenRegex("viele|wenige|einige|mehrere").build(), new PatternTokenBuilder().csToken("solcher").build(), new PatternTokenBuilder().posRegex("SUB:GEN:PLU:.*").build() ), Arrays.asList( new PatternTokenBuilder().tokenRegex("[dD](ie|er)").build(), new PatternTokenBuilder().csToken("First").build(), new PatternTokenBuilder().csToken("Lady").build() ), Arrays.asList( new PatternTokenBuilder().tokenRegex("[dD](ie|er)").build(), new PatternTokenBuilder().posRegex("ADJ:.*").build(), new PatternTokenBuilder().csToken("First").build(), new PatternTokenBuilder().csToken("Lady").build() ), Arrays.asList( new PatternTokenBuilder().tokenRegex("[dD]e[rn]").build(), new PatternTokenBuilder().csToken("Gold").build(), new PatternTokenBuilder().csToken("Cup").build() ), Arrays.asList( new PatternTokenBuilder().token("das").build(), new PatternTokenBuilder().tokenRegex("viele|wenige").build(), new PatternTokenBuilder().posRegex("SUB:.*").build() ), Arrays.asList( // "Er verspricht allen/niemandem/jedem hohe Gewinne." new PatternTokenBuilder().tokenRegex("allen|(nieman|je)dem").build(), new PatternTokenBuilder().posRegex("ADJ:AKK:PLU:.*").build(), new PatternTokenBuilder().posRegex("SUB:AKK:PLU:.*").build() ), Arrays.asList( new PatternTokenBuilder().token("für").setSkip(2).build(), new PatternTokenBuilder().tokenRegex("ist|war").build(), new PatternTokenBuilder().csToken("das").build(), new PatternTokenBuilder().posRegex("SUB:NOM:.*").build(), new PatternTokenBuilder().pos("PKT").build() ) ); private static final Set<String> MODIFIERS = new HashSet<>(Arrays.asList( "besonders", "fast", "geradezu", "sehr", "überaus", "ziemlich" )); private static final Set<String> VIELE_WENIGE_LOWERCASE = new HashSet<>(Arrays.asList( "viele", "vieler", "wenige", "weniger", "einige", "einiger", "mehrerer", "mehrere" )); private static final Set<String> REL_PRONOUN = new HashSet<>(); static { REL_PRONOUN.add("der"); REL_PRONOUN.add("die"); REL_PRONOUN.add("das"); REL_PRONOUN.add("dessen"); REL_PRONOUN.add("deren"); REL_PRONOUN.add("dem"); REL_PRONOUN.add("den"); REL_PRONOUN.add("denen"); REL_PRONOUN.add("welche"); REL_PRONOUN.add("welcher"); REL_PRONOUN.add("welchen"); REL_PRONOUN.add("welchem"); REL_PRONOUN.add("welches"); } private static final Set<String> PREPOSITIONS = new HashSet<>(); static { PREPOSITIONS.add("in"); PREPOSITIONS.add("auf"); PREPOSITIONS.add("an"); PREPOSITIONS.add("ab"); PREPOSITIONS.add("aus"); PREPOSITIONS.add("für"); PREPOSITIONS.add("zu"); PREPOSITIONS.add("bei"); PREPOSITIONS.add("nach"); PREPOSITIONS.add("über"); PREPOSITIONS.add("von"); PREPOSITIONS.add("mit"); PREPOSITIONS.add("durch"); PREPOSITIONS.add("während"); PREPOSITIONS.add("unter"); PREPOSITIONS.add("ohne"); // TODO: add more } private static final Set<String> PRONOUNS_TO_BE_IGNORED = new HashSet<>(Arrays.asList( "ich", "dir", "du", "er", "sie", "es", "wir", "mir", "uns", "ihnen", "euch", "ihm", "ihr", "ihn", "dessen", "deren", "denen", "sich", "unser", "aller", "man", "beide", "beiden", "beider", "wessen", "a", "alle", "etwas", "was", "wer", "jenen", // "...und mit jenen anderer Arbeitsgruppen verwoben" "diejenigen", "jemand", "jemandes", "niemand", "niemandes" )); private static final Set<String> NOUNS_TO_BE_IGNORED = new HashSet<>(Arrays.asList( "Prozent", // Plural "Prozente", trotzdem ist "mehrere Prozent" korrekt "Gramm", "Kilogramm", "Uhr" // "um ein Uhr" )); public AgreementRule(ResourceBundle messages, German language) { this.language = language; super.setCategory(Categories.GRAMMAR.getCategory(messages)); addExamplePair(Example.wrong("<marker>Der Haus</marker> wurde letztes Jahr gebaut."), Example.fixed("<marker>Das Haus</marker> wurde letztes Jahr gebaut.")); } @Override public String getId() { return "DE_AGREEMENT"; } @Override public String getDescription() { return "Kongruenz von Nominalphrasen (unvollständig!), z.B. 'mein kleiner(kleines) Haus'"; } @Override public RuleMatch[] match(AnalyzedSentence sentence) { List<RuleMatch> ruleMatches = new ArrayList<>(); AnalyzedTokenReadings[] tokens = getSentenceWithImmunization(sentence).getTokensWithoutWhitespace(); for (int i = 0; i < tokens.length; i++) { //defaulting to the first reading //TODO: check for all readings String posToken = tokens[i].getAnalyzedToken(0).getPOSTag(); if (posToken != null && posToken.equals(JLanguageTool.SENTENCE_START_TAGNAME)) { continue; } if (tokens[i].isImmunized()) { continue; } AnalyzedTokenReadings tokenReadings = tokens[i]; boolean relevantPronoun = isRelevantPronoun(tokens, i); boolean ignore = couldBeRelativeOrDependentClause(tokens, i); if (i > 0) { String prevToken = tokens[i-1].getToken().toLowerCase(); if ((tokens[i].getToken().equals("eine") || tokens[i].getToken().equals("einen")) && (prevToken.equals("der") || prevToken.equals("die") || prevToken.equals("das") || prevToken.equals("des") || prevToken.equals("dieses"))) { // TODO: "der eine Polizist" -> nicht ignorieren, sondern "der polizist" checken; "auf der einen Seite" ignore = true; } } // avoid false alarm on "nichts Gutes" and "alles Gute" if (tokenReadings.getToken().equals("nichts") || tokenReadings.getToken().equals("alles") || tokenReadings.getToken().equals("dies")) { ignore = true; } // avoid false alarm on "Art. 1" and "bisherigen Art. 1" (Art. = Artikel): boolean detAbbrev = i < tokens.length-2 && tokens[i+1].getToken().equals("Art") && tokens[i+2].getToken().equals("."); boolean detAdjAbbrev = i < tokens.length-3 && tokens[i+2].getToken().equals("Art") && tokens[i+3].getToken().equals("."); boolean followingParticiple = i < tokens.length-3 && (tokens[i+2].hasPartialPosTag("PA1") || tokens[i+2].getToken().matches("zugeschriebenen?|genannten?")); if (detAbbrev || detAdjAbbrev || followingParticiple) { ignore = true; } if ((GermanHelper.hasReadingOfType(tokenReadings, POSType.DETERMINER) || relevantPronoun) && !ignore) { int tokenPosAfterModifier = getPosAfterModifier(i+1, tokens); int tokenPos = tokenPosAfterModifier; if (tokenPos >= tokens.length) { break; } AnalyzedTokenReadings nextToken = tokens[tokenPos]; if (isNonPredicativeAdjective(nextToken) || isParticiple(nextToken)) { tokenPos = tokenPosAfterModifier + 1; if (tokenPos >= tokens.length) { break; } if (GermanHelper.hasReadingOfType(tokens[tokenPos], POSType.NOMEN)) { // TODO: add a case (checkAdjNounAgreement) for special cases like "deren", // e.g. "deren komisches Geschenke" isn't yet detected as incorrect if (i >= 2 && GermanHelper.hasReadingOfType(tokens[i-2], POSType.ADJEKTIV) && "als".equals(tokens[i-1].getToken()) && "das".equals(tokens[i].getToken())) { continue; } RuleMatch ruleMatch = checkDetAdjNounAgreement(tokens[i], nextToken, tokens[tokenPos]); if (ruleMatch != null) { ruleMatches.add(ruleMatch); } } } else if (GermanHelper.hasReadingOfType(nextToken, POSType.NOMEN) && !"Herr".equals(nextToken.getToken())) { RuleMatch ruleMatch = checkDetNounAgreement(tokens[i], nextToken); if (ruleMatch != null) { ruleMatches.add(ruleMatch); } } } } // for each token return toRuleMatchArray(ruleMatches); } /** * Search for modifiers (such as "sehr", "1,4 Meter") which can expand a * determiner - adjective - noun group ("ein hohes Haus" -> "ein sehr hohes Haus", * "ein 500 Meter hohes Haus") and return the index of the first non-modifier token ("Haus") * @param startAt index of array where to start searching for modifier * @return index of first non-modifier token */ private int getPosAfterModifier(int startAt, AnalyzedTokenReadings[] tokens) { if ((startAt + 1) < tokens.length && MODIFIERS.contains(tokens[startAt].getToken())) { startAt++; } if ((startAt + 1) < tokens.length && (StringUtils.isNumeric(tokens[startAt].getToken()) || tokens[startAt].hasPosTag("ZAL"))) { int posAfterModifier = startAt + 1; if ((startAt + 3) < tokens.length && ",".equals(tokens[startAt+1].getToken()) && StringUtils.isNumeric(tokens[startAt+2].getToken())) { posAfterModifier = startAt + 3; } if (tokens[posAfterModifier].getToken().matches(".*([gG]ramm|[mM]eter)")) { return posAfterModifier + 1; } } return startAt; } @Override public List<DisambiguationPatternRule> getAntiPatterns() { return makeAntiPatterns(ANTI_PATTERNS, language); } private boolean isNonPredicativeAdjective(AnalyzedTokenReadings tokensReadings) { for (AnalyzedToken reading : tokensReadings.getReadings()) { String posTag = reading.getPOSTag(); if (posTag != null && posTag.startsWith("ADJ:") && !posTag.contains("PRD")) { return true; } } return false; } private boolean isParticiple(AnalyzedTokenReadings tokensReadings) { return tokensReadings.hasPartialPosTag("PA1") || tokensReadings.hasPartialPosTag("PA2"); } private boolean isRelevantPronoun(AnalyzedTokenReadings[] tokens, int pos) { AnalyzedTokenReadings analyzedToken = tokens[pos]; boolean relevantPronoun = GermanHelper.hasReadingOfType(analyzedToken, POSType.PRONOMEN); // avoid false alarms: String token = tokens[pos].getToken(); if (PRONOUNS_TO_BE_IGNORED.contains(token.toLowerCase()) || (pos > 0 && tokens[pos-1].getToken().equalsIgnoreCase("vor") && token.equalsIgnoreCase("allem"))) { relevantPronoun = false; } return relevantPronoun; } // TODO: improve this so it only returns true for real relative clauses private boolean couldBeRelativeOrDependentClause(AnalyzedTokenReadings[] tokens, int pos) { boolean comma; boolean relPronoun; if (pos >= 1) { // avoid false alarm: "Das Wahlrecht, das Frauen zugesprochen bekamen." etc: comma = tokens[pos-1].getToken().equals(","); String term = tokens[pos].getToken(); relPronoun = comma && REL_PRONOUN.contains(term); if (relPronoun && pos+3 < tokens.length) { return true; } } if (pos >= 2) { // avoid false alarm: "Der Mann, in dem quadratische Fische schwammen." comma = tokens[pos-2].getToken().equals(","); if(comma) { String term1 = tokens[pos-1].getToken(); String term2 = tokens[pos].getToken(); boolean prep = PREPOSITIONS.contains(term1); relPronoun = REL_PRONOUN.contains(term2); return prep && relPronoun || (tokens[pos-1].hasPosTag("KON:UNT") && term2.matches("(dies|jen)e[rmns]?")); } } return false; } @Nullable private RuleMatch checkDetNounAgreement(AnalyzedTokenReadings token1, AnalyzedTokenReadings token2) { // TODO: remove "-".equals(token2.getToken()) after the bug fix if (NOUNS_TO_BE_IGNORED.contains(token2.getToken()) || "-".equals(token2.getToken())) { return null; } if (token2.isImmunized()) { return null; } Set<String> set1 = getAgreementCategories(token1); if (set1 == null) { return null; // word not known, assume it's correct } Set<String> set2 = getAgreementCategories(token2); if (set2 == null) { return null; } set1.retainAll(set2); RuleMatch ruleMatch = null; if (set1.isEmpty() && !isException(token1, token2)) { List<String> errorCategories = getCategoriesCausingError(token1, token2); String errorDetails = errorCategories.size() > 0 ? String.join(" und ", errorCategories) : "Kasus, Genus oder Numerus"; String msg = "Möglicherweise fehlende grammatische Übereinstimmung zwischen Artikel und Nomen " + "bezüglich " + errorDetails + "."; String shortMsg = "Möglicherweise keine Übereinstimmung bezüglich " + errorDetails; ruleMatch = new RuleMatch(this, token1.getStartPos(), token2.getEndPos(), msg, shortMsg); AgreementSuggestor suggestor = new AgreementSuggestor(language.getSynthesizer(), token1, token2); List<String> suggestions = suggestor.getSuggestions(); ruleMatch.setSuggestedReplacements(suggestions); } return ruleMatch; } private boolean isException(AnalyzedTokenReadings token1, AnalyzedTokenReadings token2) { String phrase = token1.getToken() + " " + token2.getToken(); return "allen Grund".equals(phrase); } private List<String> getCategoriesCausingError(AnalyzedTokenReadings token1, AnalyzedTokenReadings token2) { List<String> categories = new ArrayList<>(); List<GrammarCategory> categoriesToCheck = Arrays.asList(GrammarCategory.KASUS, GrammarCategory.GENUS, GrammarCategory.NUMERUS); for (GrammarCategory category : categoriesToCheck) { if (agreementWithCategoryRelaxation(token1, token2, category)) { categories.add(category.displayName); } } return categories; } private RuleMatch checkDetAdjNounAgreement(AnalyzedTokenReadings token1, AnalyzedTokenReadings token2, AnalyzedTokenReadings token3) { // TODO: remove (token3 == null || token3.getToken().length() < 2) if(token3 == null || token3.getToken().length() < 2) { return null; } Set<String> set = retainCommonCategories(token1, token2, token3); RuleMatch ruleMatch = null; if (set == null || set.isEmpty()) { // TODO: more detailed error message: String msg = "Möglicherweise fehlende grammatische Übereinstimmung zwischen Artikel, Adjektiv und " + "Nomen bezüglich Kasus, Numerus oder Genus. Beispiel: 'mein kleiner Haus' " + "statt 'mein kleines Haus'"; String shortMsg = "Möglicherweise keine Übereinstimmung bezüglich Kasus, Numerus oder Genus"; ruleMatch = new RuleMatch(this, token1.getStartPos(), token3.getEndPos(), msg, shortMsg); } return ruleMatch; } private boolean agreementWithCategoryRelaxation(AnalyzedTokenReadings token1, AnalyzedTokenReadings token2, GrammarCategory categoryToRelax) { Set<GrammarCategory> categoryToRelaxSet; if (categoryToRelax != null) { categoryToRelaxSet = Collections.singleton(categoryToRelax); } else { categoryToRelaxSet = Collections.emptySet(); } Set<String> set1 = getAgreementCategories(token1, categoryToRelaxSet, true); if (set1 == null) { return true; // word not known, assume it's correct } Set<String> set2 = getAgreementCategories(token2, categoryToRelaxSet, true); if (set2 == null) { return true; } set1.retainAll(set2); return set1.size() > 0; } @Nullable private Set<String> retainCommonCategories(AnalyzedTokenReadings token1, AnalyzedTokenReadings token2, AnalyzedTokenReadings token3) { Set<GrammarCategory> categoryToRelaxSet = Collections.emptySet(); Set<String> set1 = getAgreementCategories(token1, categoryToRelaxSet, true); if (set1 == null) { return null; // word not known, assume it's correct } boolean skipSol = !VIELE_WENIGE_LOWERCASE.contains(token1.getToken().toLowerCase()); Set<String> set2 = getAgreementCategories(token2, categoryToRelaxSet, skipSol); if (set2 == null) { return null; } Set<String> set3 = getAgreementCategories(token3, categoryToRelaxSet, true); if (set3 == null) { return null; } set1.retainAll(set2); set1.retainAll(set3); return set1; } private Set<String> getAgreementCategories(AnalyzedTokenReadings aToken) { return getAgreementCategories(aToken, new HashSet<>(), false); } /** Return Kasus, Numerus, Genus of those forms with a determiner. */ private Set<String> getAgreementCategories(AnalyzedTokenReadings aToken, Set<GrammarCategory> omit, boolean skipSol) { Set<String> set = new HashSet<>(); List<AnalyzedToken> readings = aToken.getReadings(); for (AnalyzedToken tmpReading : readings) { if (skipSol && tmpReading.getPOSTag() != null && tmpReading.getPOSTag().endsWith(":SOL")) { // SOL = alleinstehend - needs to be skipped so we find errors like "An der roter Ampel." continue; } AnalyzedGermanToken reading = new AnalyzedGermanToken(tmpReading); if (reading.getCasus() == null && reading.getNumerus() == null && reading.getGenus() == null) { continue; } if (reading.getGenus() == GermanToken.Genus.ALLGEMEIN && tmpReading.getPOSTag() != null && !tmpReading.getPOSTag().endsWith(":STV") && // STV: stellvertretend (!= begleitend) !possessiveSpecialCase(aToken, tmpReading)) { // genus=ALG in the original data. Not sure if this is allowed, but expand this so // e.g. "Ich Arbeiter" doesn't get flagged as incorrect: if (reading.getDetermination() == null) { // Nouns don't have the determination property (definite/indefinite), and as we don't want to // introduce a special case for that, we just pretend they always fulfill both properties: set.add(makeString(reading.getCasus(), reading.getNumerus(), GermanToken.Genus.MASKULINUM, GermanToken.Determination.DEFINITE, omit)); set.add(makeString(reading.getCasus(), reading.getNumerus(), GermanToken.Genus.MASKULINUM, GermanToken.Determination.INDEFINITE, omit)); set.add(makeString(reading.getCasus(), reading.getNumerus(), GermanToken.Genus.FEMININUM, GermanToken.Determination.DEFINITE, omit)); set.add(makeString(reading.getCasus(), reading.getNumerus(), GermanToken.Genus.FEMININUM, GermanToken.Determination.INDEFINITE, omit)); set.add(makeString(reading.getCasus(), reading.getNumerus(), GermanToken.Genus.NEUTRUM, GermanToken.Determination.DEFINITE, omit)); set.add(makeString(reading.getCasus(), reading.getNumerus(), GermanToken.Genus.NEUTRUM, GermanToken.Determination.INDEFINITE, omit)); } else { set.add(makeString(reading.getCasus(), reading.getNumerus(), GermanToken.Genus.MASKULINUM, reading.getDetermination(), omit)); set.add(makeString(reading.getCasus(), reading.getNumerus(), GermanToken.Genus.FEMININUM, reading.getDetermination(), omit)); set.add(makeString(reading.getCasus(), reading.getNumerus(), GermanToken.Genus.NEUTRUM, reading.getDetermination(), omit)); } } else { if (reading.getDetermination() == null || "jed".equals(tmpReading.getLemma()) || "manch".equals(tmpReading.getLemma())) { // "jeder" etc. needs a special case to avoid false alarm set.add(makeString(reading.getCasus(), reading.getNumerus(), reading.getGenus(), GermanToken.Determination.DEFINITE, omit)); set.add(makeString(reading.getCasus(), reading.getNumerus(), reading.getGenus(), GermanToken.Determination.INDEFINITE, omit)); } else { set.add(makeString(reading.getCasus(), reading.getNumerus(), reading.getGenus(), reading.getDetermination(), omit)); } } } return set; } private boolean possessiveSpecialCase(AnalyzedTokenReadings aToken, AnalyzedToken tmpReading) { // would cause error misses as it contains 'ALG', e.g. in "Der Zustand meiner Gehirns." return aToken.hasPartialPosTag("PRO:POS") && ("ich".equals(tmpReading.getLemma()) || "sich".equals(tmpReading.getLemma())); } private String makeString(GermanToken.Kasus casus, GermanToken.Numerus num, GermanToken.Genus gen, GermanToken.Determination determination, Set<GrammarCategory> omit) { List<String> l = new ArrayList<>(); if (casus != null && !omit.contains(GrammarCategory.KASUS)) { l.add(casus.toString()); } if (num != null && !omit.contains(GrammarCategory.NUMERUS)) { l.add(num.toString()); } if (gen != null && !omit.contains(GrammarCategory.GENUS)) { l.add(gen.toString()); } if (determination != null) { l.add(determination.toString()); } return String.join("/", l); } }
package org.obolibrary.robot; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Convenience class to handle formatting error messages and returning links to user support. * * @author <a href="mailto:rctauber@gmail.com">Becky Tauber</a> */ public class ExceptionHelper { /** Logger. */ private static final Logger logger = LoggerFactory.getLogger(ExceptionHelper.class); /** * Prints the exception details as errors, including help URL (if the exception message contains a * valid exception ID). Expects the exception message to be formatted as: "{ID} :: {message}". If * message is not formatted, will just log the message. * * @param exception the exception */ public static void handleException(Exception exception) { String msg = trimExceptionClass(exception); if (msg != null) { String exceptionID = getExceptionID(msg); if (exceptionID != null) { System.out.println(trimExceptionID(msg)); System.out.println("For details see: http://robot.obolibrary.org/" + exceptionID); } } // Will only print with --very-very-verbose (DEBUG level) if (logger.isDebugEnabled()) { exception.printStackTrace(); } else { System.out.println("Use the -vvv option to show the stack trace."); System.out.println("Use the --help option to see usage information."); } } /** * Given an exception message, return the exception ID when formatted as "command#NAME OF ERROR * msg". Otherwise, return an empty string. * * @param msg exception message * @return exception ID or empty string */ private static String getExceptionID(String msg) { String exceptionID; try { exceptionID = msg.substring(0, msg.indexOf("ERROR") + 5).trim().toLowerCase().replace(" ", "-"); } catch (Exception e) { logger.debug("Malformed exception message: {}", msg); return null; } if (!exceptionID.contains(" logger.debug("Missing exception ID: {}", msg); return null; } return exceptionID; } /** * Given a full exception message, trim the Java exception class from the start. If there is no * class, just return the message. TODO: Support more throwable classes? * * @param exception the Exception * @return trimmed exception message String */ private static String trimExceptionClass(Exception exception) { String msg = exception.getMessage(); if (msg == null) { logger.debug("{} missing exception message.", exception); return null; } if (msg.startsWith("java.")) { return msg.substring(msg.indexOf(":") + 1).trim(); } else { return msg; } } /** * Given an exception message, remove the error namespace. If no namespace is provided, just * return the message. * * @param msg exception message * @return message without the command namespace */ private static String trimExceptionID(String msg) { if (msg.contains(" return msg.substring(msg.indexOf(" } else { return msg; } } }
package net.runelite.client.plugins; import com.google.common.util.concurrent.AbstractIdleService; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.concurrent.Executor; import net.runelite.client.ui.overlay.Overlay; public abstract class Plugin extends AbstractIdleService { public Overlay getOverlay() { return null; } public Collection<Overlay> getOverlays() { Overlay overlay = getOverlay(); return overlay != null ? Arrays.asList(overlay) : Collections.EMPTY_LIST; } /** * Override AbstractIdleService's default executor to instead execute in * the main thread. Prevents plugins from all being initialized from * different threads, which causes the plugin order on the navbar to be * undefined * @return */ @Override protected Executor executor() { return r -> r.run(); } }
package org.teiid.deployers; import static org.teiid.odbc.PGUtil.*; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Map; import java.util.Properties; import org.teiid.core.types.ArrayImpl; import org.teiid.core.types.DataTypeManager; import org.teiid.metadata.Column; import org.teiid.metadata.Datatype; import org.teiid.metadata.FunctionMethod; import org.teiid.metadata.MetadataFactory; import org.teiid.metadata.Table; import org.teiid.metadata.FunctionMethod.PushDown; import org.teiid.metadata.Table.Type; import org.teiid.odbc.ODBCServerRemoteImpl; import org.teiid.query.resolver.util.ResolverVisitor; import org.teiid.translator.TranslatorException; public class PgCatalogMetadataStore extends MetadataFactory { private static final long serialVersionUID = 2158418324376966987L; public PgCatalogMetadataStore(String modelName, Map<String, Datatype> dataTypes) throws TranslatorException { super(modelName, 1, modelName, dataTypes, new Properties(), null); add_pg_namespace(); add_pg_class(); add_pg_attribute(); add_pg_type(); add_pg_index(); add_pg_am(); add_pg_proc(); add_pg_trigger(); add_pg_attrdef(); add_pg_database(); add_pg_user(); add_matpg_relatt(); add_matpg_datatype(); addFunction("hasPerm", "has_function_privilege"); //$NON-NLS-1$ //$NON-NLS-2$ addFunction("getExpr2", "pg_get_expr"); //$NON-NLS-1$ //$NON-NLS-2$ addFunction("getExpr3", "pg_get_expr"); //$NON-NLS-1$ //$NON-NLS-2$ FunctionMethod func = addFunction("asPGVector", "asPGVector"); //$NON-NLS-1$ //$NON-NLS-2$ func.setProperty(ResolverVisitor.TEIID_PASS_THROUGH_TYPE, Boolean.TRUE.toString()); } private Table createView(String name) throws TranslatorException { Table t = addTable(name); t.setSystem(true); t.setSupportsUpdate(false); t.setVirtual(true); t.setTableType(Type.Table); return t; } //index access methods private Table add_pg_am() throws TranslatorException { Table t = createView("pg_am"); //$NON-NLS-1$ addColumn("oid", DataTypeManager.DefaultDataTypes.INTEGER, t); //$NON-NLS-1$ addColumn("amname", DataTypeManager.DefaultDataTypes.STRING, t); //$NON-NLS-1$ String transformation = "SELECT 0 as oid, 'btree' as amname"; //$NON-NLS-1$ t.setSelectTransformation(transformation); return t; } // column default values private Table add_pg_attrdef() throws TranslatorException { Table t = createView("pg_attrdef"); //$NON-NLS-1$ addColumn("adrelid", DataTypeManager.DefaultDataTypes.INTEGER, t); //$NON-NLS-1$ addColumn("adnum", DataTypeManager.DefaultDataTypes.SHORT, t); //$NON-NLS-1$ addColumn("adbin", DataTypeManager.DefaultDataTypes.STRING, t); //$NON-NLS-1$ addColumn("adsrc", DataTypeManager.DefaultDataTypes.STRING, t); //$NON-NLS-1$ String transformation = "SELECT st.oid as adrelid, convert(t1.Position, short) as adnum, " + //$NON-NLS-1$ "case when t1.IsAutoIncremented then 'nextval(' else t1.DefaultValue end as adbin, " + //$NON-NLS-1$ "case when t1.IsAutoIncremented then 'nextval(' else t1.DefaultValue end as adsrc " + //$NON-NLS-1$ "FROM SYS.Columns as t1 LEFT OUTER JOIN SYS.Tables st ON (st.Name = t1.TableName AND st.SchemaName = t1.SchemaName)"; //$NON-NLS-1$ t.setSelectTransformation(transformation); return t; } /** * table columns ("attributes") * see also {@link ODBCServerRemoteImpl} getPGColInfo for the mod calculation */ private Table add_pg_attribute() throws TranslatorException { Table t = createView("pg_attribute"); //$NON-NLS-1$ addColumn("oid", DataTypeManager.DefaultDataTypes.INTEGER, t); //$NON-NLS-1$ // OID, The table this column belongs to addColumn("attrelid", DataTypeManager.DefaultDataTypes.INTEGER, t); //$NON-NLS-1$ // The column name addColumn("attname", DataTypeManager.DefaultDataTypes.STRING, t); //$NON-NLS-1$ // OID, The data type of this column addColumn("atttypid", DataTypeManager.DefaultDataTypes.INTEGER, t); //$NON-NLS-1$ // A copy of pg_type.typlen of this column's type addColumn("attlen", DataTypeManager.DefaultDataTypes.SHORT, t); //$NON-NLS-1$ // The number of the column. Ordinary columns are numbered from 1 up. System columns, // such as oid, have (arbitrary) negative numbers addColumn("attnum", DataTypeManager.DefaultDataTypes.SHORT, t); //$NON-NLS-1$ // atttypmod records type-specific data supplied at table creation time (for example, // the maximum length of a varchar column). It is passed to type-specific input functions and // length coercion functions. The value will generally be -1 for types that do not need atttypmod addColumn("atttypmod", DataTypeManager.DefaultDataTypes.INTEGER, t); //$NON-NLS-1$ // This represents a not-null constraint. It is possible to change this column to enable or disable the constraint addColumn("attnotnull", DataTypeManager.DefaultDataTypes.BOOLEAN, t); //$NON-NLS-1$ // This column has been dropped and is no longer valid. A dropped column is still physically present in the table, // but is ignored by the parser and so cannot be accessed via SQL addColumn("attisdropped", DataTypeManager.DefaultDataTypes.BOOLEAN, t); //$NON-NLS-1$ // This column has a default value, in which case there will be a corresponding entry in the pg_attrdef // catalog that actually defines the value addColumn("atthasdef", DataTypeManager.DefaultDataTypes.BOOLEAN, t); //$NON-NLS-1$ addPrimaryKey("pk_pg_attr", Arrays.asList("oid"), t); //$NON-NLS-1$ //$NON-NLS-2$ String transformation = "SELECT t1.OID as oid, " + //$NON-NLS-1$ "st.oid as attrelid, " + //$NON-NLS-1$ "t1.Name as attname, " + //$NON-NLS-1$ "pt.oid as atttypid," + //$NON-NLS-1$ "pt.typlen as attlen, " + //$NON-NLS-1$ "convert(t1.Position, short) as attnum, " + //$NON-NLS-1$ "(CASE WHEN (t1.DataType = 'bigdecimal' OR t1.DataType = 'biginteger' OR t1.DataType = 'float' OR t1.DataType='double') THEN (4+(65536*t1.Precision)+t1.Scale) " + //$NON-NLS-1$ "ELSE (4+t1.Length) END) as atttypmod, " + //$NON-NLS-1$ "CASE WHEN (t1.NullType = 'No Nulls') THEN true ELSE false END as attnotnull, " + //$NON-NLS-1$ "false as attisdropped, " + //$NON-NLS-1$ "false as atthasdef " + //$NON-NLS-1$ "FROM SYS.Columns as t1 LEFT OUTER JOIN " + //$NON-NLS-1$ "SYS.Tables st ON (st.Name = t1.TableName AND st.SchemaName = t1.SchemaName) LEFT OUTER JOIN " + //$NON-NLS-1$ "pg_catalog.matpg_datatype pt ON t1.DataType = pt.Name " +//$NON-NLS-1$ "UNION ALL SELECT kc.OID + (SELECT MAX(oid) FROM SYS.Columns) as oid, " + //$NON-NLS-1$ "k.oid + (SELECT MAX(OID) FROM SYS.Tables) as attrelid, " + //$NON-NLS-1$ "t1.Name as attname, " + //$NON-NLS-1$ "pt.oid as atttypid," + //$NON-NLS-1$ "pt.typlen as attlen, " + //$NON-NLS-1$ "convert(kc.Position, short) as attnum, " + //$NON-NLS-1$ "(CASE WHEN (t1.DataType = 'bigdecimal' OR t1.DataType = 'biginteger' OR t1.DataType = 'float' OR t1.DataType='double') THEN (4+(65536*t1.Precision)+t1.Scale) " + //$NON-NLS-1$ "ELSE (4+t1.Length) END) as atttypmod, " + //$NON-NLS-1$ "CASE WHEN (t1.NullType = 'No Nulls') THEN true ELSE false END as attnotnull, " + //$NON-NLS-1$ "false as attisdropped, " + //$NON-NLS-1$ "false as atthasdef " + //$NON-NLS-1$ "FROM (SYS.Keys as k INNER JOIN SYS.KeyColumns as kc ON k.uid = kc.uid INNER JOIN SYS.Columns as t1 ON kc.SchemaName = t1.SchemaName AND kc.TableName = t1.TableName AND kc.Name = t1.Name INNER JOIN " + //$NON-NLS-1$ "SYS.Tables as st ON st.Name = t1.TableName AND st.SchemaName = t1.SchemaName) LEFT OUTER JOIN " + //$NON-NLS-1$ "pg_catalog.matpg_datatype pt ON t1.DataType = pt.Name WHERE k.type in ('Primary', 'Unique', 'Index')"; //$NON-NLS-1$ t.setSelectTransformation(transformation); t.setMaterialized(true); return t; } // tables, indexes, sequences ("relations") private Table add_pg_class() throws TranslatorException { Table t = createView("pg_class"); //$NON-NLS-1$ addColumn("oid", DataTypeManager.DefaultDataTypes.INTEGER, t); //$NON-NLS-1$ // Name of the table, index, view, etc addColumn("relname", DataTypeManager.DefaultDataTypes.STRING, t); //$NON-NLS-1$ // The OID of the namespace that contains this relation (pg_namespace.oid) addColumn("relnamespace", DataTypeManager.DefaultDataTypes.INTEGER, t); //$NON-NLS-1$ // r = ordinary table, i = index, S = sequence, v = view, c = composite type, t = TOAST table addColumn("relkind", DataTypeManager.DefaultDataTypes.CHAR, t); //$NON-NLS-1$ // If this is an index, the access method used (B-tree, hash, etc.) addColumn("relam", DataTypeManager.DefaultDataTypes.INTEGER, t); //$NON-NLS-1$ // Number of rows in the table. This is only an estimate used by the planner. It is updated // by VACUUM, ANALYZE, and a few DDL commands such as CREATE INDEX addColumn("reltuples", DataTypeManager.DefaultDataTypes.FLOAT, t); //$NON-NLS-1$ // Size of the on-disk representation of this table in pages (of size BLCKSZ). This is only an estimate // used by the planner. It is updated by VACUUM, ANALYZE, and a few DDL commands such as CREATE INDEX addColumn("relpages", DataTypeManager.DefaultDataTypes.INTEGER, t); //$NON-NLS-1$ // True if table has (or once had) rules; see pg_rewrite catalog addColumn("relhasrules", DataTypeManager.DefaultDataTypes.BOOLEAN, t); //$NON-NLS-1$ // True if we generate an OID for each row of the relation addColumn("relhasoids", DataTypeManager.DefaultDataTypes.BOOLEAN, t); //$NON-NLS-1$ addPrimaryKey("pk_pg_class", Arrays.asList("oid"), t); //$NON-NLS-1$ //$NON-NLS-2$ String transformation = "SELECT t1.OID as oid, t1.name as relname, " + //$NON-NLS-1$ "(SELECT OID FROM SYS.Schemas WHERE Name = t1.SchemaName) as relnamespace, " + //$NON-NLS-1$ "convert((CASE t1.isPhysical WHEN true THEN 'r' ELSE 'v' END), char) as relkind," + //$NON-NLS-1$ "0 as relam, " + //$NON-NLS-1$ "convert(0, float) as reltuples, " + //$NON-NLS-1$ "0 as relpages, " + //$NON-NLS-1$ "false as relhasrules, " + //$NON-NLS-1$ "false as relhasoids " + //$NON-NLS-1$ "FROM SYS.Tables t1 UNION ALL SELECT t1.OID + (SELECT MAX(oid) as max from sys.tables) as oid, t1.name as relname, " + //$NON-NLS-1$ "(SELECT OID FROM SYS.Schemas WHERE Name = t1.SchemaName) as relnamespace, " + //$NON-NLS-1$ "convert('i', char) as relkind," + //$NON-NLS-1$ "0 as relam, " + //$NON-NLS-1$ "convert(0, float) as reltuples, " + //$NON-NLS-1$ "0 as relpages, " + //$NON-NLS-1$ "false as relhasrules, " + //$NON-NLS-1$ "false as relhasoids " + //$NON-NLS-1$ "FROM SYS.Keys t1 WHERE t1.type in ('Primary', 'Unique', 'Index')"; //$NON-NLS-1$ t.setSelectTransformation(transformation); t.setMaterialized(true); return t; } // additional index information private Table add_pg_index() throws TranslatorException { Table t = createView("pg_index"); //$NON-NLS-1$ addColumn("oid", DataTypeManager.DefaultDataTypes.INTEGER, t); //$NON-NLS-1$ // The OID of the pg_class entry for this index addColumn("indexrelid", DataTypeManager.DefaultDataTypes.INTEGER, t); //$NON-NLS-1$ // The OID of the pg_class entry for the table this index is for addColumn("indrelid", DataTypeManager.DefaultDataTypes.INTEGER, t); //$NON-NLS-1$ addColumn("indnatts", DataTypeManager.DefaultDataTypes.SHORT, t); //$NON-NLS-1$ // If true, the table was last clustered on this index addColumn("indisclustered", DataTypeManager.DefaultDataTypes.BOOLEAN, t); //$NON-NLS-1$ // If true, this is a unique index addColumn("indisunique", DataTypeManager.DefaultDataTypes.BOOLEAN, t); //$NON-NLS-1$ // If true, this index represents the primary key of the table (indisunique should always be true when this is true) addColumn("indisprimary", DataTypeManager.DefaultDataTypes.BOOLEAN, t); //$NON-NLS-1$ // Expression trees (in nodeToString() representation) for index attributes that are not simple // column references. This is a list with one element for each zero entry in indkey. // NULL if all index attributes are simple references addColumn("indexprs", DataTypeManager.DefaultDataTypes.STRING, t); //$NON-NLS-1$ // This is an array of indnatts values that indicate which table columns this index indexes. Column c = addColumn("indkey", DataTypeManager.DefaultDataTypes.STRING, t); //$NON-NLS-1$ c.setRuntimeType(DataTypeManager.getDataTypeName(DataTypeManager.getArrayType(DataTypeManager.DefaultDataClasses.SHORT))); c.setProperty("pg_type:oid", String.valueOf(PG_TYPE_INT2VECTOR)); //$NON-NLS-1$ addPrimaryKey("pk_pg_index", Arrays.asList("oid"), t); //$NON-NLS-1$ //$NON-NLS-2$ String transformation = "SELECT k.oid as oid, " + //$NON-NLS-1$ "k.oid + (SELECT MAX(oid) as max from sys.tables) as indexrelid, " + //$NON-NLS-1$ "(SELECT OID FROM SYS.Tables WHERE SchemaName = t1.SchemaName AND Name = t1.TableName) as indrelid, " + //$NON-NLS-1$ "cast(count(t1.OID) as short) as indnatts, " + //$NON-NLS-1$ "false indisclustered, " + //$NON-NLS-1$ "(CASE WHEN t1.KeyType in ('Unique', 'Primary') THEN true ELSE false END) as indisunique, " + //$NON-NLS-1$ "(CASE t1.KeyType WHEN 'Primary' THEN true ELSE false END) as indisprimary, " + //$NON-NLS-1$ "'' as indexprs, asPGVector(" + //$NON-NLS-1$ arrayAgg("(select at.attnum FROM pg_attribute as at WHERE at.attname = t1.Name AND at.attrelid = (SELECT OID FROM SYS.Tables WHERE SchemaName = t1.SchemaName AND Name = t1.TableName))", "t1.position") +") as indkey " + //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ "FROM SYS.Keys as k, Sys.KeyColumns as t1 WHERE k.uid = t1.uid GROUP BY k.oid, t1.KeyType, t1.SchemaName, t1.TableName, t1.KeyName"; //$NON-NLS-1$ t.setSelectTransformation(transformation); t.setMaterialized(true); return t; } // schemas private Table add_pg_namespace() throws TranslatorException { Table t = createView("pg_namespace"); //$NON-NLS-1$ addColumn("oid", DataTypeManager.DefaultDataTypes.INTEGER, t); //$NON-NLS-1$ addColumn("nspname", DataTypeManager.DefaultDataTypes.STRING, t); //$NON-NLS-1$ String transformation = "SELECT t1.OID as oid, t1.Name as nspname " + //$NON-NLS-1$ "FROM SYS.Schemas as t1"; //$NON-NLS-1$ t.setSelectTransformation(transformation); return t; } // functions and procedures private Table add_pg_proc() throws TranslatorException { Table t = createView("pg_proc"); //$NON-NLS-1$ addColumn("oid", DataTypeManager.DefaultDataTypes.INTEGER, t); //$NON-NLS-1$ // Name of the function or procedure addColumn("proname", DataTypeManager.DefaultDataTypes.STRING, t); //$NON-NLS-1$ // Function returns a set (i.e., multiple values of the specified data type) addColumn("proretset", DataTypeManager.DefaultDataTypes.BOOLEAN, t); //$NON-NLS-1$ // OID of Data type of the return value addColumn("prorettype", DataTypeManager.DefaultDataTypes.INTEGER, t); //$NON-NLS-1$ // Number of input arguments addColumn("pronargs", DataTypeManager.DefaultDataTypes.SHORT, t); //$NON-NLS-1$ Column c = addColumn("proargtypes", DataTypeManager.DefaultDataTypes.OBJECT, t); //$NON-NLS-1$ c.setProperty("pg_type:oid", String.valueOf(PG_TYPE_OIDVECTOR)); //$NON-NLS-1$ c.setRuntimeType(DataTypeManager.getDataTypeName(DataTypeManager.getArrayType(DataTypeManager.DefaultDataClasses.INTEGER))); c = addColumn("proargnames", DataTypeManager.DefaultDataTypes.OBJECT, t); //$NON-NLS-1$ c.setProperty("pg_type:oid", String.valueOf(PG_TYPE_TEXTARRAY)); //$NON-NLS-1$ c.setRuntimeType(DataTypeManager.getDataTypeName(DataTypeManager.getArrayType(DataTypeManager.DefaultDataClasses.STRING))); c = addColumn("proargmodes", DataTypeManager.DefaultDataTypes.OBJECT, t); //$NON-NLS-1$ c.setProperty("pg_type:oid", String.valueOf(PG_TYPE_CHARARRAY)); //$NON-NLS-1$ //TODO: we don't yet understand that we can cast from string[] to char[] c.setRuntimeType(DataTypeManager.getDataTypeName(DataTypeManager.getArrayType(DataTypeManager.DefaultDataClasses.CHAR))); c = addColumn("proallargtypes", DataTypeManager.DefaultDataTypes.OBJECT, t); //$NON-NLS-1$ c.setProperty("pg_type:oid", String.valueOf(PG_TYPE_OIDARRAY)); //$NON-NLS-1$ c.setRuntimeType(DataTypeManager.getDataTypeName(DataTypeManager.getArrayType(DataTypeManager.DefaultDataClasses.INTEGER))); // The OID of the namespace that contains this function addColumn("pronamespace", DataTypeManager.DefaultDataTypes.INTEGER, t); //$NON-NLS-1$ addPrimaryKey("pk_pg_proc", Arrays.asList("oid"), t); //$NON-NLS-1$ //$NON-NLS-2$ String transformation = "SELECT t1.OID as oid, t1.Name as proname, (SELECT (CASE WHEN count(pp.Type)>0 THEN true else false END) as x FROM ProcedureParams pp WHERE pp.ProcedureName = t1.Name AND pp.SchemaName = t1.SchemaName and pp.Type='ResultSet') as proretset, " + //$NON-NLS-1$ "CASE WHEN (SELECT count(dt.oid) FROM ProcedureParams pp, matpg_datatype dt WHERE pp.ProcedureName = t1.Name AND pp.SchemaName = t1.SchemaName AND pp.Type IN ('ReturnValue', 'ResultSet') AND dt.Name = pp.DataType) IS NULL THEN (select oid from pg_type WHERE typname = 'void') WHEN (SELECT count(dt.oid) FROM ProcedureParams pp, matpg_datatype dt WHERE pp.ProcedureName = t1.Name AND pp.SchemaName = t1.SchemaName AND pp.Type = 'ResultSet' AND dt.Name = pp.DataType) IS NOT NULL THEN (select oid from pg_type WHERE typname = 'record') ELSE (SELECT dt.oid FROM ProcedureParams pp, matpg_datatype dt WHERE pp.ProcedureName = t1.Name AND pp.SchemaName = t1.SchemaName AND pp.Type = 'ReturnValue' AND dt.Name = pp.DataType) END as prorettype, " + //$NON-NLS-1$ "convert((SELECT count(*) FROM ProcedureParams pp WHERE pp.ProcedureName = t1.Name AND pp.SchemaName = t1.SchemaName AND pp.Type IN ('In', 'InOut')), short) as pronargs, " + //$NON-NLS-1$ "asPGVector((select "+arrayAgg("y.oid","y.type, y.position" )+" FROM ("+paramTable("'ResultSet','ReturnValue', 'Out'")+") as y)) as proargtypes, " +//$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ "(select "+arrayAgg("y.name", "y.type, y.position")+" FROM (SELECT pp.Name as name, pp.position as position, pp.Type as type FROM ProcedureParams pp WHERE pp.ProcedureName = t1.Name AND pp.SchemaName = t1.SchemaName AND pp.Type NOT IN ('ReturnValue' )) as y) as proargnames, " + //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ "(select case WHEN count(distinct(y.type)) = 1 THEN null ELSE "+arrayAgg("CASE WHEN (y.type ='In') THEN cast('i' as char) WHEN (y.type = 'Out') THEN cast('o' as char) WHEN (y.type = 'InOut') THEN cast('b' as char) WHEN (y.type = 'ResultSet') THEN cast('t' as char) END", "y.type,y.position")+" END FROM (SELECT pp.Type as type, pp.Position as position FROM ProcedureParams pp WHERE pp.ProcedureName = t1.Name AND pp.SchemaName = t1.SchemaName AND pp.Type NOT IN ('ReturnValue')) as y) as proargmodes, " + //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ "(select case WHEN count(distinct(y.oid)) = 1 THEN null ELSE "+arrayAgg("y.oid", "y.type, y.position")+" END FROM ("+paramTable("'ReturnValue'")+") as y) as proallargtypes, " + //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ "(SELECT OID FROM SYS.Schemas WHERE Name = t1.SchemaName) as pronamespace " + //$NON-NLS-1$ "FROM SYS.Procedures as t1";//$NON-NLS-1$ t.setSelectTransformation(transformation); t.setMaterialized(true); return t; } private String paramTable(String notIn) { return "SELECT case when pp.Type <> 'ResultSet' AND pp.DataType = 'object' then 2283 else dt.oid end as oid, pp.Position as position, pp.Type as type FROM ProcedureParams pp LEFT JOIN matpg_datatype dt ON pp.DataType=dt.Name " + //$NON-NLS-1$ "WHERE pp.ProcedureName = t1.Name AND pp.SchemaName = t1.SchemaName AND pp.Type NOT IN ("+notIn+")"; //$NON-NLS-1$ //$NON-NLS-2$ } private String arrayAgg(String select, String orderby) { return "array_agg("+select+" ORDER BY "+orderby+")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } // triggers private Table add_pg_trigger() throws TranslatorException { Table t = createView("pg_trigger"); //$NON-NLS-1$ addColumn("oid", DataTypeManager.DefaultDataTypes.INTEGER, t); //$NON-NLS-1$ addColumn("tgconstrrelid", DataTypeManager.DefaultDataTypes.INTEGER, t); //$NON-NLS-1$ addColumn("tgfoid", DataTypeManager.DefaultDataTypes.INTEGER, t); //$NON-NLS-1$ addColumn("tgargs", DataTypeManager.DefaultDataTypes.INTEGER, t); //$NON-NLS-1$ addColumn("tgnargs", DataTypeManager.DefaultDataTypes.INTEGER, t); //$NON-NLS-1$ addColumn("tgdeferrable", DataTypeManager.DefaultDataTypes.BOOLEAN, t); //$NON-NLS-1$ addColumn("tginitdeferred", DataTypeManager.DefaultDataTypes.BOOLEAN, t); //$NON-NLS-1$ addColumn("tgconstrname", DataTypeManager.DefaultDataTypes.STRING, t); //$NON-NLS-1$ addColumn("tgrelid", DataTypeManager.DefaultDataTypes.INTEGER, t); //$NON-NLS-1$ String transformation = "SELECT 1 as oid, 1 as tgconstrrelid, " +//$NON-NLS-1$ "1 as tgfoid, " +//$NON-NLS-1$ "1 as tgargs, " +//$NON-NLS-1$ "1 as tgnargs, " +//$NON-NLS-1$ "false as tgdeferrable, " +//$NON-NLS-1$ "false as tginitdeferred, " +//$NON-NLS-1$ "'dummy' as tgconstrname, " +//$NON-NLS-1$ "1 as tgrelid " +//$NON-NLS-1$ "FROM SYS.Tables WHERE 1=2"; //$NON-NLS-1$ t.setSelectTransformation(transformation); return t; } //data types private Table add_pg_type() throws TranslatorException { Table t = createView("pg_type"); //$NON-NLS-1$ // Data type name addColumn("oid", DataTypeManager.DefaultDataTypes.INTEGER, t); //$NON-NLS-1$ // Data type name addColumn("typname", DataTypeManager.DefaultDataTypes.STRING, t); //$NON-NLS-1$ // The OID of the namespace that contains this type addColumn("typnamespace", DataTypeManager.DefaultDataTypes.INTEGER, t); //$NON-NLS-1$ // For a fixed-size type, typlen is the number of bytes in the internal representation of the type. // But for a variable-length type, typlen is negative. -1 indicates a "varlena" type (one that // has a length word), -2 indicates a null-terminated C string. addColumn("typlen", DataTypeManager.DefaultDataTypes.SHORT, t); //$NON-NLS-1$ // typtype is b for a base type, c for a composite type (e.g., a table's row type), d for a domain, // e for an enum type, or p for a pseudo-type. See also typrelid and typbasetype addColumn("typtype", DataTypeManager.DefaultDataTypes.CHAR, t); //$NON-NLS-1$ // typnotnull represents a not-null constraint on a type. Used for domains only. addColumn("typnotnull", DataTypeManager.DefaultDataTypes.BOOLEAN, t); //$NON-NLS-1$ // if this is a domain (see typtype), then typbasetype identifies the type that this one is based on. // Zero if this type is not a domain addColumn("typbasetype", DataTypeManager.DefaultDataTypes.INTEGER, t); //$NON-NLS-1$ // Domains use typtypmod to record the typmod to be applied to their base type // (-1 if base type does not use a typmod). -1 if this type is not a domain addColumn("typtypmod", DataTypeManager.DefaultDataTypes.INTEGER, t); //$NON-NLS-1$ addColumn("typdelim", DataTypeManager.DefaultDataTypes.CHAR, t); //$NON-NLS-1$ addColumn("typrelid", DataTypeManager.DefaultDataTypes.INTEGER, t); //$NON-NLS-1$ addColumn("typelem", DataTypeManager.DefaultDataTypes.INTEGER, t); //$NON-NLS-1$ String transformation = "select oid, typname, (SELECT OID FROM SYS.Schemas where Name = 'SYS') as typnamespace, typlen, typtype, false as typnotnull, typbasetype, typtypmod, cast(',' as char) as typdelim, typrelid, typelem from texttable('" + //$NON-NLS-1$ "16,boolean,1,b,0,-1,0,0\n" + //$NON-NLS-1$ "1043,string,-1,b,0,-1,0,0\n" + //$NON-NLS-1$ "25,text,-1,b,0,-1,0,0\n" + //$NON-NLS-1$ "1042,char,1,b,0,-1,0,0\n" + //$NON-NLS-1$ "21,short,2,b,0,-1,0,0\n" + //$NON-NLS-1$ "20,long,8,b,0,-1,0,0\n" + //$NON-NLS-1$ "23,integer,4,b,0,-1,0,0\n" + //$NON-NLS-1$ "26,oid,4,b,0,-1,0,0\n" + //$NON-NLS-1$ "700,float,4,b,0,-1,0,0\n" + //$NON-NLS-1$ "701,double,8,b,0,-1,0,0\n" + //$NON-NLS-1$ "705,unknown,-2,b,0,-1,0,0\n" + //$NON-NLS-1$ "1082,date,4,b,0,-1,0,0\n" + //$NON-NLS-1$ "1083,datetime,8,b,0,-1,0,0\n" + //$NON-NLS-1$ "1114,timestamp,8,b,0,-1,0,0\n" + //$NON-NLS-1$ "1700,decimal,-1,b,0,-1,0,0\n" + //$NON-NLS-1$ "142,xml,-1,b,0,-1,0,0\n" + //$NON-NLS-1$ "14939,lo,-1,b,0,-1,0,0\n" + //$NON-NLS-1$ "2278,void,4,p,0,-1,0,0\n" + //$NON-NLS-1$ "2249,record,-1,p,0,-1,0,0\n" + //$NON-NLS-1$ "30,oidvector,-1,b,0,-1,0,26\n" + //$NON-NLS-1$ "1000,_bool,-1,b,0,-1,0,16\n" + //$NON-NLS-1$ "1002,_char,-1,b,0,-1,0,18\n" + //$NON-NLS-1$ "1005,_int2,-1,b,0,-1,0,21\n" + //$NON-NLS-1$ "1007,_int4,-1,b,0,-1,0,23\n" + //$NON-NLS-1$ "1009,_text,-1,b,0,-1,0,25\n" + //$NON-NLS-1$ "1028,_oid,-1,b,0,-1,0,26\n" + //$NON-NLS-1$ "1014,_bpchar,-1,b,0,-1,0,1042\n" + //$NON-NLS-1$ "1015,_varchar,-1,b,0,-1,0,1043\n" + //$NON-NLS-1$ "1016,_int8,-1,b,0,-1,0,20\n" + //$NON-NLS-1$ "1021,_float4,-1,b,0,-1,0,700\n" + //$NON-NLS-1$ "1022,_float8,-1,b,0,-1,0,701\n" + //$NON-NLS-1$ "1115,_timestamp,-1,b,0,-1,0,1114\n" + //$NON-NLS-1$ "1182,_date,-1,b,0,-1,0,1082\n" + //$NON-NLS-1$ "1183,_time,-1,b,0,-1,0,1083\n" + //$NON-NLS-1$ "2287,_record,-1,b,0,-1,0,2249\n" + //$NON-NLS-1$ "2283,anyelement,4,p,0,-1,0,0\n" + //$NON-NLS-1$ "22,int2vector,-1,b,0,-1,0,0" + //$NON-NLS-1$ "' columns oid integer, typname string, typlen short, typtype char, typbasetype integer, typtypmod integer, typrelid integer, typelem integer) AS t"; //$NON-NLS-1$ t.setSelectTransformation(transformation); t.setMaterialized(true); return t; } private Table add_pg_database() throws TranslatorException { Table t = createView("pg_database"); //$NON-NLS-1$ addColumn("oid", DataTypeManager.DefaultDataTypes.INTEGER, t); //$NON-NLS-1$ addColumn("datname", DataTypeManager.DefaultDataTypes.STRING, t); //$NON-NLS-1$ addColumn("encoding", DataTypeManager.DefaultDataTypes.INTEGER, t); //$NON-NLS-1$ addColumn("datlastsysoid", DataTypeManager.DefaultDataTypes.INTEGER, t); //$NON-NLS-1$ // this is is boolean type but the query coming in is in the form dataallowconn = 't' addColumn("datallowconn", DataTypeManager.DefaultDataTypes.CHAR, t); //$NON-NLS-1$ addColumn("datconfig", DataTypeManager.DefaultDataTypes.OBJECT, t); //$NON-NLS-1$ addColumn("datacl", DataTypeManager.DefaultDataTypes.OBJECT, t); //$NON-NLS-1$ addColumn("datdba", DataTypeManager.DefaultDataTypes.INTEGER, t); //$NON-NLS-1$ addColumn("dattablespace", DataTypeManager.DefaultDataTypes.INTEGER, t); //$NON-NLS-1$ String transformation = "SELECT 0 as oid, " + //$NON-NLS-1$ "'teiid' as datname, " + //$NON-NLS-1$ "6 as encoding, " + //$NON-NLS-1$ "100000 as datlastsysoid, " + //$NON-NLS-1$ "convert('t', char) as datallowconn, " + //$NON-NLS-1$ "null, " + //$NON-NLS-1$ "null, " + //$NON-NLS-1$ "0 as datdba, " + //$NON-NLS-1$ "0 as dattablespace" ; //$NON-NLS-1$ t.setSelectTransformation(transformation); return t; } private Table add_pg_user() throws TranslatorException { Table t = createView("pg_user"); //$NON-NLS-1$ addColumn("oid", DataTypeManager.DefaultDataTypes.INTEGER, t); //$NON-NLS-1$ addColumn("usename", DataTypeManager.DefaultDataTypes.STRING, t); //$NON-NLS-1$ addColumn("usecreatedb", DataTypeManager.DefaultDataTypes.BOOLEAN, t); //$NON-NLS-1$ addColumn("usesuper", DataTypeManager.DefaultDataTypes.BOOLEAN, t); //$NON-NLS-1$ String transformation = "SELECT 0 as oid, " + //$NON-NLS-1$ "null as usename, " + //$NON-NLS-1$ "false as usecreatedb, " + //$NON-NLS-1$ "false as usesuper "; //$NON-NLS-1$ t.setSelectTransformation(transformation); return t; } private Table add_matpg_relatt() throws TranslatorException { Table t = createView("matpg_relatt"); //$NON-NLS-1$ addColumn("attrelid", DataTypeManager.DefaultDataTypes.INTEGER, t); //$NON-NLS-1$ addColumn("attnum", DataTypeManager.DefaultDataTypes.SHORT, t); //$NON-NLS-1$ addColumn("attname", DataTypeManager.DefaultDataTypes.STRING, t); //$NON-NLS-1$ addColumn("relname", DataTypeManager.DefaultDataTypes.STRING, t); //$NON-NLS-1$ addColumn("nspname", DataTypeManager.DefaultDataTypes.STRING, t); //$NON-NLS-1$ addColumn("autoinc", DataTypeManager.DefaultDataTypes.BOOLEAN, t); //$NON-NLS-1$ addColumn("typoid", DataTypeManager.DefaultDataTypes.INTEGER, t); //$NON-NLS-1$ addPrimaryKey("pk_matpg_relatt_names", Arrays.asList("attname", "relname", "nspname"), t); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ addIndex("idx_matpg_relatt_ids", true, Arrays.asList("attrelid", "attnum"), t); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ String transformation = "select pg_class.oid as attrelid, attnum, attname, relname, nspname, IsAutoIncremented as autoinc, cast((select p.value from SYS.Properties p where p.name = 'pg_type:oid' and p.uid = SYS.Columns.uid) as integer) as typoid " + //$NON-NLS-1$ "from pg_attribute, pg_class, pg_namespace, SYS.Columns " + //$NON-NLS-1$ "where pg_attribute.attrelid = pg_class.oid and pg_namespace.oid = relnamespace" + //$NON-NLS-1$ " and SchemaName = nspname and TableName = relname and Name = attname"; //$NON-NLS-1$ t.setSelectTransformation(transformation); t.setMaterialized(true); return t; } private Table add_matpg_datatype() throws TranslatorException { Table t = createView("matpg_datatype"); //$NON-NLS-1$ addColumn("oid", DataTypeManager.DefaultDataTypes.INTEGER, t); //$NON-NLS-1$ addColumn("typname", DataTypeManager.DefaultDataTypes.STRING, t); //$NON-NLS-1$ addColumn("name", DataTypeManager.DefaultDataTypes.STRING, t); //$NON-NLS-1$ addColumn("uid", DataTypeManager.DefaultDataTypes.STRING, t); //$NON-NLS-1$ addColumn("typlen", DataTypeManager.DefaultDataTypes.SHORT, t); //$NON-NLS-1$ addPrimaryKey("matpg_datatype_names", Arrays.asList("oid", "name"), t); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ addIndex("matpg_datatype_ids", true, Arrays.asList("typname", "oid"), t); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ String transformation = "select pt.oid as oid, pt.typname as typname, t.Name name, t.UID, pt.typlen from pg_catalog.pg_type pt JOIN (select (CASE "+//$NON-NLS-1$ "WHEN (Name = 'clob' OR Name = 'blob') THEN 'lo' " +//$NON-NLS-1$ "WHEN (Name = 'byte' ) THEN 'short' " +//$NON-NLS-1$ "WHEN (Name = 'time' ) THEN 'datetime' " + //$NON-NLS-1$ "WHEN (Name = 'biginteger' ) THEN 'decimal' " +//$NON-NLS-1$ "WHEN (Name = 'bigdecimal' ) THEN 'decimal' " +//$NON-NLS-1$ "WHEN (Name = 'object' ) THEN 'unknown' " +//$NON-NLS-1$ "ELSE Name END) as pg_name, Name, UID from SYS.DataTypes) as t ON t.pg_name = pt.typname"; //$NON-NLS-1$ t.setSelectTransformation(transformation); t.setMaterialized(true); return t; } private FunctionMethod addFunction(String javaFunction, String name) { Method[] methods = FunctionMethods.class.getMethods(); for (Method method : methods) { if (!method.getName().equals(javaFunction)) { continue; } String returnType = DataTypeManager.getDataTypeName(method.getReturnType()); Class<?>[] params = method.getParameterTypes(); String[] paramTypes = new String[params.length]; for (int i = 0; i < params.length; i++) { paramTypes[i] = DataTypeManager.getDataTypeName(params[i]); } FunctionMethod func = FunctionMethod.createFunctionMethod(name, name, "pg", returnType, paramTypes); //$NON-NLS-1$ setUUID(func); getSchema().addFunction(func); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); func.setInvocationMethod(javaFunction); func.setPushdown(PushDown.CANNOT_PUSHDOWN); func.setClassloader(classLoader); func.setInvocationClass(FunctionMethods.class.getName()); return func; } throw new AssertionError("Could not find function"); //$NON-NLS-1$ } public static class FunctionMethods { public static Boolean hasPerm(@SuppressWarnings("unused") Integer oid, @SuppressWarnings("unused") String permission) { return true; } public static String getExpr2(String text, @SuppressWarnings("unused") Integer oid) { return text; } public static String getExpr3(String text, @SuppressWarnings("unused") Integer oid, @SuppressWarnings("unused") Boolean prettyPrint) { return text; } public static Object asPGVector(Object obj) { if (obj instanceof ArrayImpl) { ((ArrayImpl)obj).setZeroBased(true); } return obj; } } }
package org.saiku.repository; import org.apache.commons.lang.StringUtils; import org.apache.jackrabbit.commons.JcrUtils; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.type.TypeFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import javax.jcr.Node; import javax.jcr.PathNotFoundException; import javax.jcr.RepositoryException; public class Acl2 { private static final Logger log = LoggerFactory.getLogger(Acl2.class); private List<String> adminRoles; public void setAdminRoles( List<String> adminRoles ) { this.adminRoles = adminRoles; } private AclMethod rootMethod = AclMethod.WRITE; private Map<String, AclEntry> acl = new TreeMap<String, AclEntry>(); acl = mapper.readValue(node.getProperty("owner").getString(), TypeFactory .mapType(HashMap.class, String.class, AclEntry.class)); // mapper.readValue(acl, AclEntry.class); entry = acl.get(node.getPath()); ///entry = e.getValue(); } catch (PathNotFoundException e) { LOG.debug("Path(owner) not found: " + node.getPath(), e.getCause()); } catch (Exception e) { LOG.debug("Exception: " + node.getPath(), e.getCause()); } AclMethod method; public Acl2(Node root){ readAclTree(root); } /** * Returns the access method to the specified resource for the user or role * * @param node the resource to which you want to access * @param username the username of the user that's accessing * @param roles the role of the user that's accessing * @return */ public List<AclMethod> getMethods( Node node, String username, List<String> roles ) { try { ObjectMapper mapper = new ObjectMapper(); //log.debug("Set ACL to " + object + " : " + acl); //String acl = null; AclEntry entry = null; Map<String, AclEntry> acl = new TreeMap<String, AclEntry>(); try { acl = (Map<String, AclEntry>) mapper.readValue( node.getProperty("owner").getString(), TypeFactory .mapType(HashMap.class, String.class, AclEntry.class) ); // mapper.readValue(acl, AclEntry.class); Map.Entry<String, AclEntry> e = acl.entrySet().iterator().next(); entry = e.getValue(); } catch (PathNotFoundException e){ log.debug("Path(owner) not found: "+node.getPath(), e.getCause()); } catch (Exception e ){ log.debug("Exception: " + node.getPath(), e.getCause()); } AclMethod method; if ( node.getPath().startsWith("..") ) { return getAllAcls( AclMethod.NONE ); } if ( isAdminRole( roles ) ) { return getAllAcls( AclMethod.GRANT ); } if ( entry != null ) { switch( entry.getType() ) { case PRIVATE: if ( !entry.getOwner().equals( username ) ) { method = AclMethod.NONE; } else { method = AclMethod.GRANT; } break; case SECURED: List<AclMethod> allMethods = new ArrayList<AclMethod>(); if ( StringUtils.isNotBlank(entry.getOwner()) && entry.getOwner().equals( username ) ) { allMethods.add( AclMethod.GRANT ); } List<AclMethod> userMethods = entry.getUsers() != null && entry.getUsers().containsKey( username ) ? entry.getUsers().get( username ) : new ArrayList<AclMethod>(); List<AclMethod> roleMethods = new ArrayList<AclMethod>(); for ( String role : roles ) { List<AclMethod> r = entry.getRoles() != null && entry.getRoles().containsKey( role ) ? entry.getRoles().get( role ) : new ArrayList<AclMethod>(); roleMethods.addAll( r ); } allMethods.addAll( userMethods ); allMethods.addAll( roleMethods ); if ( allMethods.size() == 0 ) { // no role nor user acl method = AclMethod.NONE; } else { // return the strongest role method = AclMethod.max( allMethods ); } break; default: // PUBLIC ACCESS method = AclMethod.WRITE; break; } } else { if ( node.getParent() == null ) { method = AclMethod.NONE; } else if ( node.getParent().getName().equals("/") ) { return getAllAcls( rootMethod ); } else { Node parent = node.getParent(); List<AclMethod> parentMethods = getMethods( parent, username, roles ); method = AclMethod.max( parentMethods ); } } // String parentPath = repoRoot return getAllAcls( method ); } catch ( Exception e ) { log.debug("Error", e.getCause()); } List<AclMethod> noMethod = new ArrayList<AclMethod>(); noMethod.add( AclMethod.NONE ); return noMethod; } public void setRootAcl( String rootAcl ) { try { if ( StringUtils.isNotBlank( rootAcl ) ) { rootMethod = AclMethod.valueOf( rootAcl ); } } catch ( Exception e ) { } } private List<AclMethod> getAllAcls( AclMethod maxMethod ) { List<AclMethod> methods = new ArrayList<AclMethod>(); if ( maxMethod != null ) { for ( AclMethod m : AclMethod.values() ) { if ( m.ordinal() > 0 && m.ordinal() <= maxMethod.ordinal() ) { methods.add( m ); } } } return methods; } public boolean canGrant( Node node, String username, List<String> roles ) { List<AclMethod> acls = getMethods( node, username, roles ); return acls.contains( AclMethod.GRANT ); } public void addEntry(String path, AclEntry entry) { try { if (entry != null) { acl.put(path, entry); //writeAcl( path, entry ); } } catch (Exception e) { //logger.error( "Cannot add entry for resource: " + path, e ); } } public Node serialize(Node node) { try { ObjectMapper mapper = new ObjectMapper(); node.setProperty("owner", ""); node.setProperty("owner", mapper.writeValueAsString(acl)); return node; } catch (Exception e) { try { log.debug("Error while reading ACL files at path: " + node.getPath(), e.getCause()); } catch (RepositoryException e1) { log.debug("Repository Exception", e1.getCause()); } } return node; } private Map<String, AclEntry> deserialize(Node node) { ObjectMapper mapper = new ObjectMapper(); Map<String, AclEntry> acl = new TreeMap<String, AclEntry>(); try { if (node != null && node.getProperty("owner") != null) { acl = mapper.readValue(node.getProperty("owner").getString(), TypeFactory .mapType(HashMap.class, String.class, AclEntry.class)); } } catch (Exception e) { try { log.debug("Error while reading ACL files at path: " + node.getPath(), e.getCause()); } catch (RepositoryException e1) { log.debug("Repository Exception", e1.getCause()); } } return acl; } public AclEntry getEntry( String path ) { return ( acl.containsKey( path ) ? acl.get( path ) : null ); } public boolean canRead( Node path, String username, List<String> roles ) { if ( path == null ) { return false; } List<AclMethod> acls = getMethods( path, username, roles ); return acls.contains( AclMethod.READ ); } public boolean canWrite( Node path, String username, List<String> roles ) { if ( path == null ) { return false; } List<AclMethod> acls = getMethods( path, username, roles ); return acls.contains( AclMethod.WRITE ); } private void readAclTree( Node resource ) { try { String s = resource.getPrimaryNodeType().getName(); Node folder = resource; //resource.getPrimaryNodeType().getName().equals( "nt:folder" ) // ? resource : resource.getParent(); String jsonFile = folder.getProperty("owner").getString(); if ( jsonFile != null && jsonFile != "" ) { Map<String, AclEntry> folderAclMap = deserialize(folder); Map<String, AclEntry> aclMap = new TreeMap<String, AclEntry>(); for (String key : folderAclMap.keySet()) { if (key.equals(folder.getPath())) { AclEntry entry = folderAclMap.get(key); //FileName fn = folder.resolveFile( key ).getName(); //String childPath = repoRoot.getName().getRelativeName( fn ); aclMap.put(folder.getPath(), entry); } acl.putAll(aclMap); } for (Node file : JcrUtils.getChildNodes(folder)) { //if ( file.getPrimaryNodeType().equals( "nt:folder" ) ) { readAclTree(file); } } } catch ( Exception e ) { try { log.debug("Error while reading ACL files at path: "+resource.getPath(), e.getCause()); } catch (RepositoryException e1) { log.debug("Repository Exception", e1.getCause()); } } } /** * Returns the list of the administrator roles * * @return */ public List<String> getAdminRoles() { return adminRoles; } /** * Checks if a specific role is in the list of the admin roles * * @param role * @return */ private boolean isAdminRole( String role ) { return adminRoles.contains( role ); } /** * Checks if a list of roles contains an admin role * * @param roles * @return */ private boolean isAdminRole( List<String> roles ) { for ( String role : roles ) { if ( isAdminRole( role ) ) { return true; } } return false; } }
package cz.hobrasoft.pdfmu; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import cz.hobrasoft.pdfmu.operation.Operation; import cz.hobrasoft.pdfmu.operation.OperationAttach; import cz.hobrasoft.pdfmu.operation.OperationException; import cz.hobrasoft.pdfmu.operation.metadata.OperationMetadata; import cz.hobrasoft.pdfmu.operation.signature.OperationSignature; import cz.hobrasoft.pdfmu.operation.version.OperationVersion; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import java.util.logging.LogManager; import java.util.logging.Logger; import net.sourceforge.argparse4j.ArgumentParsers; import net.sourceforge.argparse4j.inf.ArgumentParser; import net.sourceforge.argparse4j.inf.ArgumentParserException; import net.sourceforge.argparse4j.inf.Namespace; import net.sourceforge.argparse4j.inf.Subparsers; /** * The main class of PDFMU * * @author <a href="mailto:filip.bartek@hobrasoft.cz">Filip Bartek</a> */ public class Main { private static void disableLoggers() { LogManager.getLogManager().reset(); // Remove default handler(s) } private static final Logger logger = Logger.getLogger(Main.class.getName()); /** * The main entry point of PDFMU * * @param args the command line arguments */ public static void main(String[] args) { System.setProperty("java.util.logging.SimpleFormatter.format", "%4$s: %5$s%n"); ArgumentParser parser = ArgumentParsers.newArgumentParser("pdfmu") .description("Manipulate a PDF document") .defaultHelp(true); parser.addArgument("-of", "--output_format") .choices("text", "json") .setDefault("text") .type(String.class) .nargs("?") .help("format of stdout output"); // TODO: Set pdfmu version in `parser`. For example: // parser.version("1.0"); // http://argparse4j.sourceforge.net/usage.html#argumentparser-version // Try to extract the version from `pom.xml`. // Once the version has been set, enable a CL argument: // parser.addArgument("-v", "--version") // .help("print version of pdfmu") // .action(Arguments.version()); Subparsers subparsers = parser.addSubparsers() .help("operation to execute") .metavar("OPERATION") .dest("operation"); SortedMap<String, Operation> operations = new TreeMap<>(); operations.put("version", OperationVersion.getInstance()); operations.put("signature", OperationSignature.getInstance()); operations.put("attach", OperationAttach.getInstance()); operations.put("metadata", OperationMetadata.getInstance()); for (Map.Entry<String, Operation> e : operations.entrySet()) { String name = e.getKey(); Operation operation = e.getValue(); operation.configureSubparser(subparsers.addParser(name)); } Namespace namespace = null; try { // If help is requested, // `parseArgs` prints help message and throws `ArgumentParserException` // (so `namespace` stays null). // If insufficient or invalid `args` are given, // `parseArgs` throws `ArgumentParserException`. namespace = parser.parseArgs(args); } catch (ArgumentParserException e) { // Prints information about the parsing error (missing argument etc.) parser.handleError(e); } if (namespace != null) { String operationName = namespace.getString("operation"); assert operationName != null; // Sub-command -> required Operation operation = operations.get(operationName); assert operation != null; String outputFormat = namespace.getString("output_format"); switch (outputFormat) { case "json": ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); // nice formatting WritingMapper wm = new WritingMapper(mapper, System.err); operation.setWritingMapper(wm); disableLoggers(); break; case "text": TextOutput to = new TextOutput(System.err); operation.setTextOutput(to); break; default: assert false; // Argument has limited choices } try { operation.execute(namespace); } catch (OperationException ex) { logger.severe(ex.getMessage()); Throwable cause = ex.getCause(); if (cause != null && cause.getMessage() != null) { logger.severe(cause.getMessage()); } } } } }
// -*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: // @homepage@ package example; import com.sun.java.swing.plaf.windows.WindowsComboBoxUI; import java.awt.*; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import javax.swing.*; import javax.swing.plaf.basic.BasicComboBoxUI; import javax.swing.plaf.basic.BasicComboPopup; import javax.swing.plaf.basic.ComboPopup; public final class MainPanel extends JPanel { private MainPanel() { super(new BorderLayout()); String[] model = {"aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg"}; JComboBox<String> combo = new JComboBox<String>(model) { @Override public void updateUI() { super.updateUI(); if (getUI() instanceof WindowsComboBoxUI) { setUI(new WindowsComboBoxUI() { @Override protected ComboPopup createPopup() { return new HeaderFooterComboPopup(comboBox); } }); } else { setUI(new BasicComboBoxUI() { @Override protected ComboPopup createPopup() { return new HeaderFooterComboPopup(comboBox); } }); } } }; combo.setMaximumRowCount(4); add(combo, BorderLayout.NORTH); setBorder(BorderFactory.createEmptyBorder(10, 10, 0, 10)); setPreferredSize(new Dimension(320, 240)); } public static void main(String[] args) { EventQueue.invokeLater(MainPanel::createAndShowGui); } private static void createAndShowGui() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); Toolkit.getDefaultToolkit().beep(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } class HeaderFooterComboPopup extends BasicComboPopup { protected transient JLabel header; protected transient JMenuItem footer; // Java 8: protected HeaderFooterComboPopup(JComboBox<?> combo) { // Java 9: protected HeaderFooterComboPopup(JComboBox<Object> combo) { @SuppressWarnings("unchecked") protected HeaderFooterComboPopup(JComboBox combo) { super(combo); } @Override protected void configurePopup() { // setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); // setBorderPainted(true); // setBorder(LIST_BORDER); // setOpaque(false); // add(scroller); // setDoubleBuffered(true); // setFocusable(false); super.configurePopup(); configureHeader(); configureFooter(); add(header, 0); add(footer); // setLayout(new BorderLayout()); // add(header, BorderLayout.NORTH); // add(scroller); // add(footer, BorderLayout.SOUTH); } protected void configureHeader() { header = new JLabel("History", SwingConstants.CENTER); header.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 0)); header.setMaximumSize(new Dimension(Short.MAX_VALUE, 24)); header.setAlignmentX(Component.CENTER_ALIGNMENT); } protected void configureFooter() { int modifiers = InputEvent.CTRL_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK; footer = new JMenuItem("Show All Bookmarks"); footer.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_B, modifiers)); footer.addActionListener(e -> { Window w = SwingUtilities.getWindowAncestor(getInvoker()); JOptionPane.showMessageDialog(w, "Bookmarks"); }); } }
package org.piwik.sdk; import android.content.Context; import android.content.SharedPreferences; import android.support.annotation.NonNull; import org.piwik.sdk.dispatcher.DispatcherFactory; import org.piwik.sdk.tools.Checksum; import org.piwik.sdk.tools.DeviceHelper; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Map; import timber.log.Timber; public class Piwik { public static final String LOGGER_PREFIX = "PIWIK:"; private static final String LOGGER_TAG = "PIWIK"; private static final String BASE_PREFERENCE_FILE = "org.piwik.sdk"; private final Map<Tracker, SharedPreferences> mPreferenceMap = new HashMap<>(); private final Context mContext; private static Piwik sInstance; private SharedPreferences mBasePreferences; public static synchronized Piwik getInstance(Context context) { if (sInstance == null) sInstance = new Piwik(context); return sInstance; } private Piwik(Context context) { mContext = context.getApplicationContext(); mBasePreferences = context.getSharedPreferences(BASE_PREFERENCE_FILE, Context.MODE_PRIVATE); } public Context getContext() { return mContext; } public synchronized Tracker newTracker(@NonNull String url, int siteId, String name) { URL trackerUrl; try { if (url.endsWith("piwik.php") || url.endsWith("piwik-proxy.php")) { trackerUrl = new URL(url); } else { if (!url.endsWith("/")) url += "/"; trackerUrl = new URL(url + "piwik.php"); } } catch (MalformedURLException e) { throw new RuntimeException(e); } return new Tracker(trackerUrl, siteId, this, name); } public String getApplicationDomain() { return getContext().getPackageName(); } /** * Base preferences, tracker idenpendent. */ public SharedPreferences getPiwikPreferences() { return mBasePreferences; } /** * @return Tracker specific settings object */ public SharedPreferences getTrackerPreferences(@NonNull Tracker tracker) { synchronized (mPreferenceMap) { SharedPreferences newPrefs = mPreferenceMap.get(tracker); if (newPrefs == null) { String prefName; try { prefName = "org.piwik.sdk_" + Checksum.getMD5Checksum(tracker.getName()); } catch (Exception e) { Timber.tag(LOGGER_TAG).e(e, null); prefName = "org.piwik.sdk_" + tracker.getName(); } newPrefs = getContext().getSharedPreferences(prefName, Context.MODE_PRIVATE); mPreferenceMap.put(tracker, newPrefs); } return newPrefs; } } protected DispatcherFactory getDispatcherFactory() { return new DispatcherFactory(); } DeviceHelper getDeviceHelper() { return new DeviceHelper(mContext); } }
package kilim.tools; import java.lang.reflect.Method; import kilim.WeavingClassLoader; /** * Invoke as java -Dkilim.class.path="classDir1:classDir2:jar1.jar:..." kilim.tools.Kilim class args... * * This class dynamically weaves kilim-related classes and runs "class". The classpath * specified must not be in the main classpath, otherwise the system class loader will * use the raw, unwoven classes. */ public class Kilim { public static void main(String[] args) throws Exception { if (args.length == 0) { usage(); } String className = args[0]; args = processArgs(args); WeavingClassLoader wcl = new WeavingClassLoader(Thread.currentThread().getContextClassLoader()); Class<?> mainClass = wcl.loadClass(className); Method mainMethod = mainClass.getMethod("main", new Class[]{String[].class}); mainMethod.invoke(null,new Object[] {args}); } private static void usage() { System.out.println("java -Dkilim.classpath kilim.tools.Kilim class [args ...]"); System.exit(1); } private static String[] processArgs(String[] args) { String[] ret = new String[args.length-1]; if (ret.length > 0) System.arraycopy(args, 1, ret, 0, ret.length); return ret; } }
package org.nutz.dao.test.normal; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import org.junit.Before; import org.junit.Test; import org.nutz.castor.Castors; import org.nutz.dao.Chain; import org.nutz.dao.Cnd; import org.nutz.dao.Condition; import org.nutz.dao.ConnCallback; import org.nutz.dao.DaoException; import org.nutz.dao.Sqls; import org.nutz.dao.entity.Entity; import org.nutz.dao.entity.Record; import org.nutz.dao.sql.Sql; import org.nutz.dao.test.DaoCase; import org.nutz.dao.test.meta.Abc; import org.nutz.dao.test.meta.Pet; import org.nutz.dao.test.meta.PetObj; import org.nutz.dao.test.meta.SimplePOJO; import org.nutz.lang.Lang; import org.nutz.trans.Molecule; import org.nutz.trans.Trans; public class SimpleDaoTest extends DaoCase { @Before public void before() { dao.create(Pet.class, true); } private void insertRecords(int len) { for (int i = 0; i < len; i++) { Pet pet = Pet.create("pet" + i); pet.setNickName("alias_" + i); dao.insert(pet); } } @Test public void test_simple_fetch_record() { Pet pet = Pet.create("abc"); long now = System.currentTimeMillis(); pet.setBirthday(Castors.me().castTo(now, Timestamp.class)); dao.insert(pet); List<Record> pets = dao.query("t_pet", null, null); assertEquals(1, pets.size()); assertEquals("abc", pets.get(0).getString("name")); assertEquals(now / 1000, pets.get(0).getTimestamp("birthday").getTime() / 1000); } @Test public void test_delete_list() { insertRecords(8); List<Pet> list = dao.query(Pet.class, null, null); List<Pet> pets = new ArrayList<Pet>(list.size()); pets.addAll(list); assertEquals(8, pets.size()); pets.addAll(list); dao.delete(pets); assertEquals(0, dao.count(Pet.class)); } @Test public void test_simple_update() { dao.fastInsert(Lang.array(Pet.create("A"), Pet.create("B"))); Pet a = dao.fetch(Pet.class, "A"); a.setName("C"); a.setAge(5); dao.update(a); Pet c = dao.fetch(Pet.class, "C"); assertEquals("C", c.getName()); assertEquals(5, c.getAge()); Pet b = dao.fetch(Pet.class, "B"); assertEquals("B", b.getName()); assertEquals(0, b.getAge()); } @Test public void test_fetch_by_condition_in_special_char() { dao.insert(Pet.create("a@b").setNickName("ABC")); Pet pet = dao.fetch(Pet.class, Cnd.where("name", "=", "a@b")); assertEquals("a@b", pet.getName()); assertEquals("ABC", pet.getNickName()); } @Test public void test_count_with_entity() { insertRecords(8); int re = dao.count(Pet.class, new Condition() { public String toSql(Entity<?> entity) { return entity.getField("nickName").getColumnName() + " IN ('alias_5','alias_6')"; } }); assertEquals(2, re); } @Test public void test_table_exists() { assertTrue(dao.exists(Pet.class)); } @Test public void test_count_by_condition() { insertRecords(4); assertEquals(4, dao.count(Pet.class)); assertEquals(2, dao.count(Pet.class, Cnd.wrap("name IN ('pet2','pet3') ORDER BY name ASC"))); } @Test public void run_2_sqls_with_error() { assertEquals(0, dao.count(Pet.class)); Sql sql1 = Sqls.create("INSERT INTO t_pet (name) VALUES ('A')"); Sql sql2 = Sqls.create("INSERT INTO t_pet (nocol) VALUES ('B')"); try { dao.execute(sql1, sql2); fail(); } catch (DaoException e) {} assertEquals(0, dao.count(Pet.class)); } @Test public void test_clear_two_records() { dao.insert(Pet.create("A")); dao.insert(Pet.create("B")); assertEquals(2, dao.clear(Pet.class, Cnd.where("id", ">", 0))); assertEquals(0, dao.clear(Pet.class, Cnd.where("id", ">", 0))); } @Test public void test_delete_records() { dao.insert(Pet.create("A")); dao.insert(Pet.create("B")); assertEquals(1, dao.delete(Pet.class, "A")); assertEquals(1, dao.delete(Pet.class, "B")); assertEquals(0, dao.delete(Pet.class, "A")); } @Test public void test_integer_object_column() { dao.insert(PetObj.create("X")); PetObj pet = dao.fetch(PetObj.class, "X"); assertEquals("X", pet.getName()); assertNull(pet.getAge()); dao.update(pet.setAge(20)); pet = dao.fetch(PetObj.class, "X"); assertEquals(20, pet.getAge().intValue()); dao.update(pet.setAge(null)); pet = dao.fetch(PetObj.class, "X"); assertNull(pet.getAge()); } @Test public void test_insert_readonly() { dao.create(SimplePOJO.class, true); SimplePOJO p = new SimplePOJO(); p.setSex(""); dao.insert(p); p.setSex(""); dao.update(p); } @Test public void test_order_by() { dao.create(Abc.class, true); Abc a = new Abc(); a.setName("ccc"); dao.insert(a); a.setName("abc"); dao.insert(a); dao.query(Abc.class, Cnd.where("id", ">", "-1").asc("name"), null); } @Test public void test_clear() { dao.create(Pet.class, true); dao.insert(Pet.create("Wendal")); dao.insert(Pet.create("Wendal2")); dao.insert(Pet.create("Wendal3")); dao.insert(Pet.create("Wendal4")); dao.insert(Pet.create("Wendal5")); assertEquals(5, dao.count(Pet.class)); assertEquals(5, dao.clear(Pet.class)); } @Test public void test_chain_insert() { dao.insert(Pet.class, Chain.make("name", "wendal").add("nickName", "asfads")); } //For github issue 131 @Test public void test_fastInsert_rollback() { dao.create(Pet.class, true); final List<Pet> pets = new ArrayList<Pet>(); for (int i = 0; i < 100; i++) { Pet u = new Pet(); u.setName("XXXX" + i); pets.add(u); } try { Trans.exec(new Molecule<Object>() { @Override public void run() { dao.fastInsert(pets); throw new RuntimeException(); } }); } catch (Throwable e) { e.printStackTrace(); } assertEquals(0, dao.count(Pet.class)); } //For github issue 131 @Test public void test_fastInsert_rollback_jdbc() { dao.create(Pet.class, true); try { Trans.exec(new Molecule<Object>() { @Override public void run() { dao.run(new ConnCallback() { @Override public void invoke(Connection conn) throws Exception { PreparedStatement ps = conn.prepareStatement("INSERT INTO t_pet(name) VALUES(?)"); for (int i = 0; i < 100; i++) { ps.setString(1, "XXXXX" + i); ps.addBatch(); } ps.execute(); } }); throw new RuntimeException(); } }); } catch (Throwable e) { e.printStackTrace(); } assertEquals(0, dao.count(Pet.class)); } }
package pl.pwr.hiervis.util; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import basic_hierarchy.common.Constants; import basic_hierarchy.common.HierarchyBuilder; import basic_hierarchy.common.NodeIdComparator; import basic_hierarchy.implementation.BasicHierarchy; import basic_hierarchy.implementation.BasicInstance; import basic_hierarchy.implementation.BasicNode; import basic_hierarchy.interfaces.Hierarchy; import basic_hierarchy.interfaces.Instance; import basic_hierarchy.interfaces.Node; public class HierarchyUtilsTest { /** Feature values' array is copied by reference when cloning Instances (memory optimization) */ private static final boolean _featureArrayOptimization = true; Hierarchy alpha = null; @Before public void setup() { alpha = generateHierarchy( 3000, 2, "gen.0", "gen.0.0", "gen.0.1", "gen.0.2", "gen.0.3", "gen.0.1.1" ); } @Test public void testClone() { Hierarchy test = HierarchyUtils.clone( alpha, false, null ); Assert.assertFalse( test == alpha ); compareHierarchies( alpha, test ); } @Test public void testSubHierarchy() { testSubHierarchy( alpha, "gen.0.2", Constants.ROOT_ID ); testSubHierarchy( alpha, "gen.0.1.1", Constants.ROOT_ID ); } @Test public void testMerge() { Hierarchy test = HierarchyUtils.subHierarchy( alpha, "gen.0.2", Constants.ROOT_ID ); testMerge( alpha, test, "gen.0.2" ); test = HierarchyUtils.subHierarchy( alpha, "gen.0.1.1", "gen.0.8.4.3" ); testMerge( alpha, test, "gen.0.1.1" ); } public static void testSubHierarchy( Hierarchy alphaH, String srcId, String destId ) { Hierarchy testH = HierarchyUtils.subHierarchy( alphaH, srcId, destId ); List<Node> alphaNs = new ArrayList<>( Arrays.asList( alphaH.getGroups() ) ); alphaNs.removeIf( n -> !n.getId().contains( srcId ) ); List<Node> testNs = Arrays.asList( testH.getGroups() ); Assert.assertEquals( alphaNs.size(), testNs.size() ); final int _endi = alphaNs.size(); for ( int i = 0; i < _endi; ++i ) { Node alphaN = alphaNs.get( i ); Node testN = testNs.get( i ); Assert.assertFalse( alphaN == testN ); String alphaId = alphaN.getId().replace( srcId, "" ); String testId = testN.getId().replace( destId, "" ); Assert.assertEquals( alphaId, testId ); List<Instance> alphaIs = alphaN.getNodeInstances(); List<Instance> testIs = testN.getNodeInstances(); Assert.assertEquals( alphaIs.size(), testIs.size() ); final int _endj = alphaIs.size(); for ( int j = 0; j < _endj; ++j ) { Instance alphaI = alphaIs.get( j ); Instance testI = testIs.get( j ); alphaId = alphaI.getNodeId().replace( srcId, "" ); testId = testI.getNodeId().replace( destId, "" ); Assert.assertEquals( alphaId, testId ); Assert.assertFalse( alphaI == testI ); Assert.assertEquals( alphaI.getTrueClass(), testI.getTrueClass() ); Assert.assertEquals( alphaI.getInstanceName(), testI.getInstanceName() ); if ( _featureArrayOptimization ) { Assert.assertEquals( alphaI.getData(), testI.getData() ); } else { Assert.assertFalse( alphaI.getData() == testI.getData() ); Assert.assertArrayEquals( alphaI.getData(), testI.getData(), 0 ); } } } } public static void testMerge( Hierarchy alphaH, Hierarchy testH, String mergeNodeId ) { testH = HierarchyUtils.merge( testH, alphaH, mergeNodeId ); compareHierarchies( alphaH, testH ); } /** * Compares the two hierarchies for deep equality, while also asserting that they don't contain * the same objects (by reference). * * @param a * the first hierarchy * @param b * the second hierarchy */ public static void compareHierarchies( Hierarchy a, Hierarchy b ) { Assert.assertFalse( a == b ); Assert.assertEquals( a.getRoot().getId(), b.getRoot().getId() ); Assert.assertEquals( a.getOverallNumberOfInstances(), b.getOverallNumberOfInstances() ); Assert.assertArrayEquals( a.getClasses(), b.getClasses() ); Assert.assertArrayEquals( a.getClassesCount(), b.getClassesCount() ); Assert.assertArrayEquals( a.getDataNames(), b.getDataNames() ); List<Node> aNodes = Arrays.asList( a.getGroups() ); List<Node> bNodes = Arrays.asList( b.getGroups() ); Assert.assertEquals( aNodes.size(), bNodes.size() ); final int _endi = aNodes.size(); for ( int i = 0; i < _endi; ++i ) { Node aN = aNodes.get( i ); Node bN = bNodes.get( i ); compareNodes( aN, bN ); } } public static void compareNodes( Node a, Node b ) { Assert.assertFalse( a == b ); Assert.assertEquals( a.getId(), b.getId() ); if ( a.getParent() != null ) { Assert.assertEquals( a.getParent().getId(), b.getParent().getId() ); } // Node representations are created artificially, therefore they can't // reference the same feature values array object. compareInstances( a.getNodeRepresentation(), b.getNodeRepresentation(), false ); List<Instance> aIs = a.getNodeInstances(); List<Instance> bIs = b.getNodeInstances(); Assert.assertEquals( aIs.size(), bIs.size() ); final int _endj = aIs.size(); for ( int j = 0; j < _endj; ++j ) { Instance aI = aIs.get( j ); Instance bI = bIs.get( j ); compareInstances( aI, bI, _featureArrayOptimization ); } } public static void compareInstances( Instance a, Instance b, boolean featureArrayOptimization ) { if ( a == null && b == null ) return; Assert.assertFalse( a == b ); Assert.assertEquals( a.getNodeId(), b.getNodeId() ); Assert.assertEquals( a.getTrueClass(), b.getTrueClass() ); Assert.assertEquals( a.getInstanceName(), b.getInstanceName() ); if ( featureArrayOptimization ) { Assert.assertEquals( a.getData(), b.getData() ); } else { Assert.assertFalse( a.getData() == b.getData() ); Assert.assertArrayEquals( a.getData(), b.getData(), 0 ); } } public BasicHierarchy generateHierarchy( int instanceCount, int dimCount, String... ids ) { Random r = new Random(); int nodeCount = ids.length; int currentInstanceCount = 0; final int avgInstancePerNode = instanceCount / nodeCount; List<BasicNode> nodes = new ArrayList<>(); for ( int i = 0; i < nodeCount; ++i ) { int nodeInstanceCount = Math.max( 1, (int)( avgInstancePerNode * ( r.nextGaussian() + 1 ) ) ); if ( i == nodeCount - 1 && currentInstanceCount + nodeInstanceCount < instanceCount ) { nodeInstanceCount = instanceCount - currentInstanceCount; } currentInstanceCount += nodeInstanceCount; nodes.add( generateNode( ids[i], nodeInstanceCount, dimCount ) ); } nodes.sort( new NodeIdComparator() ); BasicNode root = nodes.get( 0 ); if ( !root.getId().equals( Constants.ROOT_ID ) ) { root = null; } HierarchyBuilder hb = new HierarchyBuilder(); List<? extends Node> allNodes = hb.buildCompleteHierarchy( root, nodes, false, false ); return new BasicHierarchy( allNodes, null ); } public BasicNode generateNode( String id, int instanceCount, int dimCount ) { BasicNode node = new BasicNode( id, null, false ); for ( int i = 0; i < instanceCount; ++i ) { node.addInstance( generateInstance( id, dimCount ) ); } return node; } public BasicInstance generateInstance( String id, int dimCount ) { double[] data = new double[dimCount]; for ( int i = 0; i < dimCount; i++ ) { data[i] = Math.random() * 2 - 1; } return new BasicInstance( null, id, data ); } }
package liquibase.sqlgenerator.core; import liquibase.database.Database; import liquibase.database.core.OracleDatabase; import liquibase.database.typeconversion.TypeConverterFactory; import liquibase.exception.ValidationErrors; import liquibase.sql.Sql; import liquibase.sql.UnparsedSql; import liquibase.sqlgenerator.SqlGeneratorChain; import liquibase.statement.core.InsertOrUpdateStatement; import liquibase.statement.core.UpdateStatement; import java.util.Date; public class InsertOrUpdateGeneratorOracle extends InsertOrUpdateGenerator { @Override public boolean supports(InsertOrUpdateStatement statement, Database database) { return database instanceof OracleDatabase; } @Override protected String getRecordCheck(InsertOrUpdateStatement insertOrUpdateStatement, Database database, String whereClause) { StringBuffer recordCheckSql = new StringBuffer(); recordCheckSql.append("DECLARE\n"); recordCheckSql.append("\tv_reccount NUMBER := 0;\n"); recordCheckSql.append("BEGIN\n"); recordCheckSql.append("\tSELECT COUNT(*) INTO v_reccount FROM " + database.escapeTableName(insertOrUpdateStatement.getSchemaName(), insertOrUpdateStatement.getTableName()) + " WHERE "); recordCheckSql.append(whereClause); recordCheckSql.append(";\n"); recordCheckSql.append("\tIF v_reccount = 0 THEN\n"); return recordCheckSql.toString(); } @Override protected String getElse(Database database){ return "\tELSIF v_reccount = 1 THEN\n"; } @Override protected String getPostUpdateStatements(){ StringBuffer endStatements = new StringBuffer(); endStatements.append("END IF;\n"); endStatements.append("END;\n"); endStatements.append("/\n"); return endStatements.toString(); } }
package org.safehaus.subutai.shared.protocol; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.net.URLClassLoader; import java.util.logging.Logger; public class FileUtil { private static final Logger log = Logger.getLogger(FileUtil.class.getName()); private static URLClassLoader classLoader; public static File getFile(String fileName, Object object) { String currentPath = System.getProperty("user.dir") + "/res/" + fileName; File file = new File(currentPath); if (!file.exists()) { writeFile(fileName, object); file = new File(currentPath); } return file; } private static void writeFile(String fileName, Object object) { try { String currentPath = System.getProperty("user.dir") + "/res"; InputStream inputStream = getClassLoader(object).getResourceAsStream("img/" + fileName); File folder = new File(currentPath); if (!folder.exists()) { folder.mkdir(); } OutputStream outputStream = new FileOutputStream(new File(currentPath + "/" + fileName)); int read; byte[] bytes = new byte[1024]; while ((read = inputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, read); } inputStream.close(); outputStream.close(); } catch (Exception ex) { System.out.println(); System.out.println(fileName); ex.printStackTrace(); } } private static URLClassLoader getClassLoader(Object object) { if (classLoader != null) { return classLoader; } // Needed an instance to get URL, i.e. the static way doesn't work: FileUtil.class.getClass(). URL url = object.getClass().getProtectionDomain().getCodeSource().getLocation(); classLoader = new URLClassLoader(new URL[] {url}, Thread.currentThread().getContextClassLoader()); return classLoader; } }
package org.apache.maven.test; import org.codehaus.surefire.SurefireBooter; import org.apache.maven.plugin.AbstractPlugin; import org.apache.maven.plugin.PluginExecutionRequest; import org.apache.maven.plugin.PluginExecutionResponse; import java.io.File; import java.util.List; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.StringTokenizer; import java.lang.reflect.Array; /** * @goal test * * @description Run tests using surefire * * @prereq compiler:compile * @prereq compiler:testCompile * @prereq resources:resources * @prereq resources:testResources * * @parameter * name="mavenRepoLocal" * type="String" * required="true" * validator="validator" * expression="#maven.repo.local" * description="" * @parameter * name="basedir" * type="String" * required="true" * validator="validator" * expression="#basedir" * description="" * @parameter * name="classesDirectory" * type="String" * required="true" * validator="validator" * expression="#project.build.output" * description="" * @parameter * name="testClassesDirectory" * type="String" * required="true" * validator="validator" * expression="#project.build.testOutput" * description="" * @parameter * name="includes" * type="String" * required="true" * validator="" * expression="#project.build.unitTest.includes" * description="" * @parameter * name="excludes" * type="String" * required="true" * validator="" * expression="#project.build.unitTest.excludes" * description="" * @parameter * name="classpathElements" * type="String[]" * required="true" * validator="" * expression="#project.classpathElements" * description="" * @parameter * name="reportsDirectory" * type="String" * required="false" * validator="" * expression="#project.build.directory/surefire-reports" * description="Base directory where all reports are written to." * @parameter * name="test" * type="String" * required="false" * validator="" * expression="#test" * description="Specify this parameter if you want to use the test regex notation to select tests to run." * * @author <a href="mailto:jason@maven.org">Jason van Zyl</a> * @version $Id$ * * @todo make version of junit and surefire configurable * @todo make report to be produced configurable */ public class SurefirePlugin extends AbstractPlugin { public void execute( PluginExecutionRequest request, PluginExecutionResponse response ) throws Exception { String mavenRepoLocal = (String) request.getParameter( "mavenRepoLocal" ); String basedir = (String) request.getParameter( "basedir" ); String classesDirectory = (String) request.getParameter( "classesDirectory" ); String testClassesDirectory = (String) request.getParameter( "testClassesDirectory" ); String[] classpathElements = (String[]) request.getParameter( "classpathElements" ); String reportsDirectory = (String) request.getParameter( "reportsDirectory" ); String test = (String) request.getParameter( "test" ); // Setup the surefire booter SurefireBooter surefireBooter = new SurefireBooter(); surefireBooter.setReportsDirectory( reportsDirectory ); // Check to see if we are running a single test. The raw parameter will // come through if it has not been set. if ( test != null ) { // FooTest -> **/FooTest.java List includes = new ArrayList(); List excludes = new ArrayList(); String[] testRegexes = split( test, ",", -1 ); for ( int i = 0; i < testRegexes.length; i++ ) { includes.add( "**/" + testRegexes[i] + ".java" ); } surefireBooter.addBattery( "org.codehaus.surefire.battery.DirectoryBattery", new Object[]{basedir, includes, excludes} ); } else { List includes = (List) request.getParameter( "includes" ); List excludes = (List) request.getParameter( "excludes" ); surefireBooter.addBattery( "org.codehaus.surefire.battery.DirectoryBattery", new Object[]{basedir, includes, excludes} ); } System.setProperty( "basedir", basedir ); surefireBooter.addClassPathUrl( new File( mavenRepoLocal, "junit/jars/junit-3.8.1.jar" ).getPath() ); surefireBooter.addClassPathUrl( new File( mavenRepoLocal, "surefire/jars/surefire-1.2-SNAPSHOT.jar" ).getPath() ); surefireBooter.addClassPathUrl( new File( classesDirectory ).getPath() ); surefireBooter.addClassPathUrl( new File( testClassesDirectory ).getPath() ); for ( int i = 0; i < classpathElements.length; i++ ) { if(classpathElements[i] != null) { surefireBooter.addClassPathUrl( classpathElements[i] ); } } surefireBooter.addReport( "org.codehaus.surefire.report.ConsoleReporter" ); surefireBooter.addReport( "org.codehaus.surefire.report.FileReporter" ); boolean success = surefireBooter.run(); if ( !success ) { response.setExecutionFailure( true, new SurefireFailureResponse( null ) ); } } protected String[] split( String str, String separator, int max ) { StringTokenizer tok = null; if ( separator == null ) { // Null separator means we're using StringTokenizer's default // delimiter, which comprises all whitespace characters. tok = new StringTokenizer( str ); } else { tok = new StringTokenizer( str, separator ); } int listSize = tok.countTokens(); if ( max > 0 && listSize > max ) { listSize = max; } String[] list = new String[listSize]; int i = 0; int lastTokenBegin = 0; int lastTokenEnd = 0; while ( tok.hasMoreTokens() ) { if ( max > 0 && i == listSize - 1 ) { // In the situation where we hit the max yet have // tokens left over in our input, the last list // element gets all remaining text. String endToken = tok.nextToken(); lastTokenBegin = str.indexOf( endToken, lastTokenEnd ); list[i] = str.substring( lastTokenBegin ); break; } else { list[i] = tok.nextToken(); lastTokenBegin = str.indexOf( list[i], lastTokenEnd ); lastTokenEnd = lastTokenBegin + list[i].length(); } i++; } return list; } }
package org.geneontology.minerva.legacy; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.Pair; import org.geneontology.minerva.curie.CurieHandler; import org.geneontology.minerva.evidence.FindGoCodes; import org.geneontology.minerva.lookup.ExternalLookupService; import org.geneontology.minerva.lookup.ExternalLookupService.LookupEntry; import org.geneontology.minerva.taxon.FindTaxonTool; import org.obolibrary.obo2owl.Obo2Owl; import org.obolibrary.obo2owl.Owl2Obo; import org.obolibrary.oboformat.parser.OBOFormatConstants.OboFormatTag; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.owlapi.model.OWLAnnotation; import org.semanticweb.owlapi.model.OWLAnnotationAssertionAxiom; import org.semanticweb.owlapi.model.OWLAnnotationProperty; import org.semanticweb.owlapi.model.OWLAnnotationValueVisitorEx; import org.semanticweb.owlapi.model.OWLAnonymousIndividual; import org.semanticweb.owlapi.model.OWLClass; import org.semanticweb.owlapi.model.OWLClassExpression; import org.semanticweb.owlapi.model.OWLDataFactory; import org.semanticweb.owlapi.model.OWLLiteral; import org.semanticweb.owlapi.model.OWLNamedIndividual; import org.semanticweb.owlapi.model.OWLObjectProperty; import org.semanticweb.owlapi.model.OWLObjectPropertyExpression; import org.semanticweb.owlapi.model.OWLObjectSomeValuesFrom; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.reasoner.OWLReasoner; import owltools.gaf.Bioentity; import owltools.gaf.BioentityDocument; import owltools.gaf.ExtensionExpression; import owltools.gaf.GafDocument; import owltools.gaf.GeneAnnotation; import owltools.gaf.eco.SimpleEcoMapper; import owltools.graph.OWLGraphWrapper; import owltools.vocab.OBOUpperVocabulary; import uk.ac.manchester.cs.owl.owlapi.ImplUtils; abstract class AbstractLegoTranslator extends LegoModelWalker<AbstractLegoTranslator.Summary> { protected final OWLClass mf; protected final Set<OWLClass> mfSet; protected final OWLClass cc; protected final Set<OWLClass> ccSet; protected final OWLClass bp; protected final Set<OWLClass> bpSet; protected final FindGoCodes goCodes; protected final CurieHandler curieHandler; protected String assignedBy; protected AbstractLegoTranslator(OWLOntology model, CurieHandler curieHandler, SimpleEcoMapper mapper) { super(model.getOWLOntologyManager().getOWLDataFactory()); this.curieHandler = curieHandler; goCodes = new FindGoCodes(mapper, curieHandler); mf = OBOUpperVocabulary.GO_molecular_function.getOWLClass(f); cc = f.getOWLClass(curieHandler.getIRI("GO:0005575")); bp = OBOUpperVocabulary.GO_biological_process.getOWLClass(f); bpSet = new HashSet<>(); mfSet = new HashSet<>(); ccSet = new HashSet<>(); fillAspects(model, curieHandler, bpSet, mfSet, ccSet); assignedBy = "GO_Noctua"; } static void fillAspects(OWLOntology model, CurieHandler curieHandler, Set<OWLClass> bpSet, Set<OWLClass> mfSet, Set<OWLClass> ccSet) { final IRI namespaceIRI = Obo2Owl.trTagToIRI(OboFormatTag.TAG_NAMESPACE.getTag()); final OWLDataFactory df = model.getOWLOntologyManager().getOWLDataFactory(); final OWLAnnotationProperty namespaceProperty = df.getOWLAnnotationProperty(namespaceIRI); final Set<OWLOntology> ontologies = model.getImportsClosure(); for(OWLClass cls : model.getClassesInSignature(true)) { if (cls.isBuiltIn()) { continue; } String id = curieHandler.getCuri(cls); if (id.startsWith("GO:") == false) { continue; } for (OWLAnnotationAssertionAxiom ax : ImplUtils.getAnnotationAxioms(cls, ontologies)) { OWLAnnotation annotation = ax.getAnnotation(); if (annotation.getProperty().equals(namespaceProperty)) { String value = annotation.getValue().accept(new OWLAnnotationValueVisitorEx<String>() { @Override public String visit(IRI iri) { return null; } @Override public String visit(OWLAnonymousIndividual individual) { return null; } @Override public String visit(OWLLiteral literal) { return literal.getLiteral(); } }); if (value != null) { if ("molecular_function".equals(value)) { mfSet.add(cls); } else if ("biological_process".equals(value)) { bpSet.add(cls); } else if ("cellular_component".equals(value)) { ccSet.add(cls); } } } } } } protected static Set<OWLClass> getAllSubClasses(OWLClass cls, OWLReasoner r, boolean reflexive, String idSpace, CurieHandler curieHandler) { Set<OWLClass> allSubClasses = r.getSubClasses(cls, false).getFlattened(); Iterator<OWLClass> it = allSubClasses.iterator(); while (it.hasNext()) { OWLClass current = it.next(); if (current.isBuiltIn()) { it.remove(); continue; } String id = curieHandler.getCuri(current); if (id.startsWith(idSpace) == false) { it.remove(); continue; } } if (reflexive) { allSubClasses.add(cls); } return allSubClasses; } protected class Summary { Set<Entry<OWLClass>> activities = null; Set<Entry<OWLClass>> locations = null; Set<Entry<OWLClass>> processes = null; OWLClass entity = null; String entityType = null; String entityTaxon = null; boolean addMf(OWLClass cls, Metadata metadata, Set<OWLObjectSomeValuesFrom> expressions) { if (isMf(cls)) { activities = addAnnotation(cls, metadata, expressions, activities); return true; } return false; } boolean addBp(OWLClass cls, Metadata metadata, Set<OWLObjectSomeValuesFrom> expressions) { if (isBp(cls)) { processes = addAnnotation(cls, metadata, expressions, processes); return true; } return false; } boolean addCc(OWLClass cls, Metadata metadata, Set<OWLObjectSomeValuesFrom> expressions) { if (isCc(cls)) { locations = addAnnotation(cls, metadata, expressions, locations); return true; } return false; } private <T> Set<Entry<T>> addAnnotation(T cls, Metadata metadata, Set<OWLObjectSomeValuesFrom> expressions, Set<Entry<T>> set) { if (set == null) { set = new HashSet<Entry<T>>(); } Entry<T> entry = new Entry<T>(); entry.value = cls; entry.metadata = metadata.copy(); if (expressions != null) { entry.expressions = expressions; } set.add(entry); return set; } void addProcesses(Set<Entry<OWLClass>> processes, Metadata metadata) { if (processes != null) { if (this.processes == null) { this.processes = new HashSet<Entry<OWLClass>>(); } for(Entry<OWLClass> process : processes) { Entry<OWLClass> newEntry = new Entry<OWLClass>(); newEntry.value = process.value; newEntry.metadata = Metadata.combine(metadata, process.metadata); this.processes.add(newEntry); } } } void addLocations(Set<Entry<OWLClass>> locations) { if (locations != null) { if (this.locations == null) { this.locations = new HashSet<Entry<OWLClass>>(locations); } else { this.locations.addAll(locations); } } } } protected boolean isMf(OWLClass cls) { return mfSet.contains(cls); } protected boolean isBp(OWLClass cls) { return bpSet.contains(cls); } protected boolean isCc(OWLClass cls) { return ccSet.contains(cls); } public abstract void translate(OWLOntology modelAbox, ExternalLookupService lookup, GafDocument annotations, BioentityDocument entities, List<String> additionalRefs); /** * Get the type of an enabled by entity, e.g. gene, protein * * @param modelGraph * @param entity * @param individual * @param lookup * @return type */ protected String getEntityType(OWLClass entity, OWLNamedIndividual individual, OWLGraphWrapper modelGraph, ExternalLookupService lookup) { List<LookupEntry> result = lookup.lookup(entity.getIRI()); if (result.isEmpty() == false) { LookupEntry entry = result.get(0); if ("protein".equalsIgnoreCase(entry.type)) { return "protein"; } else if ("gene".equalsIgnoreCase(entry.type)) { return "gene"; } } return "gene"; } protected String getEntityTaxon(OWLClass entity, OWLOntology model) { if (entity == null) { return null; } FindTaxonTool tool = new FindTaxonTool(curieHandler, model.getOWLOntologyManager().getOWLDataFactory()); return tool.getEntityTaxon(curieHandler.getCuri(entity), model); } public Pair<GafDocument, BioentityDocument> translate(String id, OWLOntology modelAbox, ExternalLookupService lookup, List<String> additionalReferences) { final GafDocument annotations = new GafDocument(id, null); final BioentityDocument entities = new BioentityDocument(id); translate(modelAbox, lookup, annotations, entities, additionalReferences); return Pair.of(annotations, entities); } protected GeneAnnotation createAnnotation(Entry<OWLClass> e, Bioentity entity, String aspect, List<String> additionalReferences, OWLGraphWrapper g, Collection<OWLObjectSomeValuesFrom> c16) { GeneAnnotation annotation = new GeneAnnotation(); annotation.setBioentityObject(entity); annotation.setBioentity(entity.getId()); annotation.setAspect(aspect); annotation.setAssignedBy(assignedBy); annotation.setCls(curieHandler.getCuri(e.value)); if (e.metadata.evidence != null) { String ecoId = curieHandler.getCuri(e.metadata.evidence); if (ecoId != null) { String goCode = null; Pair<String, String> pair = goCodes.findShortEvidence(e.metadata.evidence, ecoId, g.getSourceOntology()); if (pair != null) { goCode = pair.getLeft(); String goRef = pair.getRight(); if (goRef != null) { if (additionalReferences == null) { additionalReferences = Collections.singletonList(goRef); } else { additionalReferences = new ArrayList<String>(additionalReferences); additionalReferences.add(goRef); } } } annotation.setEvidence(goCode, ecoId); } } if (e.metadata.date != null) { // assumes that the date is YYYY-MM-DD // gene annotations require YYYYMMDD StringBuilder sb = new StringBuilder(); for (int i = 0; i < e.metadata.date.length(); i++) { char c = e.metadata.date.charAt(i); if (Character.isDigit(c)) { sb.append(c); } } annotation.setLastUpdateDate(sb.toString()); } if (e.metadata.with != null) { List<String> withInfos = new ArrayList<>(e.metadata.with); annotation.setWithInfos(withInfos); } String relation = "enables"; if ("C".equals(aspect)) { relation = "part_of"; } else if ("P".equals(aspect)) { relation = "involved_in"; } annotation.setRelation(relation); if (e.metadata.sources != null) { annotation.addReferenceIds(e.metadata.sources); } if (additionalReferences != null) { for (String ref : additionalReferences) { annotation.addReferenceId(ref); } } if (c16 != null && !c16.isEmpty()) { List<ExtensionExpression> expressions = new ArrayList<ExtensionExpression>(); for (OWLObjectSomeValuesFrom svf : c16) { OWLObjectPropertyExpression property = svf.getProperty(); OWLClassExpression filler = svf.getFiller(); if (property instanceof OWLObjectProperty && filler instanceof OWLClass) { String rel = getRelId(property, g); String objectId = curieHandler.getCuri((OWLClass) filler); ExtensionExpression expr = new ExtensionExpression(rel, objectId); expressions.add(expr); } } annotation.setExtensionExpressions(Collections.singletonList(expressions)); } return annotation; } protected String getRelId(OWLObjectPropertyExpression p, OWLGraphWrapper graph) { String relId = null; for(OWLOntology ont : graph.getAllOntologies()) { relId = Owl2Obo.getIdentifierFromObject(p, ont, null); if (relId != null && relId.indexOf(':') < 0) { return relId; } } return relId; } protected Bioentity createBioentity(OWLClass entityCls, String entityType, String taxon, OWLGraphWrapper g, ExternalLookupService lookup) { Bioentity bioentity = new Bioentity(); BioentityStrings strings = getBioentityStrings(entityCls, entityType, taxon, g, lookup); String id = strings.id; bioentity.setId(id); if (strings.db != null) { bioentity.setDb(strings.db); } bioentity.setSymbol(strings.symbol); bioentity.setTypeCls(strings.type); if (taxon != null) { bioentity.setNcbiTaxonId(taxon); } return bioentity; } protected static class BioentityStrings { String id; String db; String symbol; String type; } protected BioentityStrings getBioentityStrings(OWLClass entityCls, String entityType, String taxon, OWLGraphWrapper g, ExternalLookupService lookup) { BioentityStrings strings = new BioentityStrings(); strings.id = curieHandler.getCuri(entityCls); strings.db = null; String[] split = StringUtils.split(strings.id, ":", 2); if (split.length == 2) { strings.db = split[0]; } strings.symbol = getLabelForBioentity(entityCls, entityType, taxon, g, lookup); strings.type = entityType; return strings; } private String getLabelForBioentity(OWLClass entityCls, String entityType, String taxon, OWLGraphWrapper g, ExternalLookupService lookup) { String lbl = g.getLabel(entityCls); if (lbl == null && lookup != null) { List<LookupEntry> result = lookup.lookup(entityCls.getIRI()); if (!result.isEmpty()) { LookupEntry entry = result.get(0); lbl = entry.label; } } return lbl; } protected void addAnnotations(OWLGraphWrapper modelGraph, ExternalLookupService lookup, Summary summary, List<String> additionalRefs, GafDocument annotations, BioentityDocument entities) { Bioentity entity = createBioentity(summary.entity, summary.entityType, summary.entityTaxon , modelGraph, lookup); entities.addBioentity(entity); annotations.addBioentity(entity); if (summary.activities != null) { for (Entry<OWLClass> e: summary.activities) { boolean renderActivity = true; if (mf.equals(e.value)) { // special handling for top level molecular functions // only add as annotation, if there is more than one annotation // otherwise they tend to be redundant with the bp or cc annotation if (e.expressions == null || e.expressions.isEmpty()) { renderActivity = false; } } if (renderActivity) { GeneAnnotation annotation = createAnnotation(e, entity, "F", additionalRefs, modelGraph, e.expressions); annotations.addGeneAnnotation(annotation); } } } if (summary.processes != null) { for (Entry<OWLClass> e : summary.processes) { GeneAnnotation annotation = createAnnotation(e, entity, "P", additionalRefs, modelGraph, e.expressions); annotations.addGeneAnnotation(annotation); } } if (summary.locations != null) { for (Entry<OWLClass> e : summary.locations) { if (isCc(e.value)) { GeneAnnotation annotation = createAnnotation(e, entity, "C", additionalRefs, modelGraph, e.expressions); annotations.addGeneAnnotation(annotation); } } } } }
package com.generic.support.netio.handler; import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE; import static io.netty.handler.codec.http.HttpHeaderNames.LOCATION; import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION; import static io.netty.handler.codec.http.HttpResponseStatus.FORBIDDEN; import static io.netty.handler.codec.http.HttpResponseStatus.FOUND; import static io.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND; import static io.netty.handler.codec.http.HttpResponseStatus.OK; import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; import java.io.File; import java.io.FileNotFoundException; import java.io.RandomAccessFile; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.regex.Pattern; import javax.activation.MimetypesFileTypeMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelProgressiveFuture; import io.netty.channel.ChannelProgressiveFutureListener; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.DefaultHttpResponse; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http.HttpHeaderValues; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpUtil; import io.netty.handler.codec.http.HttpVersion; import io.netty.handler.codec.http.LastHttpContent; import io.netty.handler.stream.ChunkedFile; import io.netty.util.CharsetUtil; public class NettyHttpFileServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> { private static final Logger log = LoggerFactory.getLogger(NettyHttpFileServerHandler.class); private static final Pattern INSECURE_URI = Pattern.compile(".*[<>&\"].*"); // private static final Pattern ALLOWED_FILE_NAME = // Pattern.compile("[A-Za-z0-9][-_A-Za-z0-9\\.]*"); private String pathContext = "/fs"; private String baseDir = "/home/gavin"; @Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { log.debug(String.format("channelRead0 %s", request.method())); if (!request.decoderResult().isSuccess()) { sendError(ctx, HttpResponseStatus.BAD_REQUEST); return; } if (request.method() != HttpMethod.GET) { sendError(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED); return; } String uri = request.uri(); String path = sanitize(uri); log.debug(String.format("uri:%s - path:%s", uri, path)); if (path == null) { sendError(ctx, FORBIDDEN); return; } File file = new File(path); if (file.isHidden() || !file.exists()) { sendError(ctx, NOT_FOUND); return; } if (file.isDirectory()) { if (uri.endsWith("/")) { sendList(ctx, file); } else { sendRedirect(ctx, uri + '/'); } return; } if (!file.isFile()) { sendError(ctx, FORBIDDEN); return; } RandomAccessFile randomAccessFile = null; try { randomAccessFile = new RandomAccessFile(file, "r"); } catch (FileNotFoundException fnfe) { sendError(ctx, NOT_FOUND); return; } long fileLength = randomAccessFile.length(); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); HttpUtil.setContentLength(response, fileLength); setContentTypeHeader(response, file); if (HttpUtil.isKeepAlive(request)) { response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE); } ctx.write(response); ChannelFuture sendFileFuture = ctx.write(new ChunkedFile(randomAccessFile, 0, fileLength, 8192), ctx.newProgressivePromise()); sendFileFuture.addListener(new ChannelProgressiveFutureListener() { @Override public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) { if (total < 0) { // total unknown System.err.println("Transfer progress: " + progress); } else { System.err.println("Transfer progress: " + progress + " / " + total); } } @Override public void operationComplete(ChannelProgressiveFuture future) throws Exception { System.out.println("Transfer complete."); } }); ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); if (!HttpUtil.isKeepAlive(request)) { lastContentFuture.addListener(ChannelFutureListener.CLOSE); } } private void sendRedirect(ChannelHandlerContext ctx, String newUri) { FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, FOUND); response.headers().set(LOCATION, newUri); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) { ByteBuf reasonPhrase = Unpooled.copiedBuffer("Failure: " + status.toString() + "\r\n", CharsetUtil.UTF_8); FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, reasonPhrase); response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8"); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } private String sanitize(String uri) { try { uri = URLDecoder.decode(uri, "UTF-8"); } catch (UnsupportedEncodingException e) { try { uri = URLDecoder.decode(uri, "ISO-8859-1"); } catch (UnsupportedEncodingException e1) { throw new Error(); } } if (!uri.startsWith(pathContext)) { return null; } if (!uri.startsWith("/")) { return null; } uri = uri.substring(pathContext.length()); uri = uri.replace('/', File.separatorChar); if (uri.contains(File.separator + '.') || uri.contains('.' + File.separator) || uri.startsWith(".") || uri.endsWith(".") || INSECURE_URI.matcher(uri).matches()) { return null; } if (baseDir != null && baseDir.length() > 0) { return baseDir + File.separator + uri; } else { return System.getProperty("user.dir") + File.separator + uri; } } private void sendList(ChannelHandlerContext ctx, File dir) { FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK); response.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8"); StringBuilder buf = new StringBuilder(); String dirPath = dir.getPath(); buf.append("<!DOCTYPE html>\r\n"); buf.append("<html><head><title>"); buf.append(dirPath); buf.append(" "); buf.append("</title></head><body>\r\n"); buf.append("<h3>"); buf.append(dirPath).append(" "); buf.append("</h3>\r\n"); buf.append("<ul>"); buf.append("<li><a href=\"../\">..</a></li>\r\n"); for (File f : dir.listFiles()) { if (f.isHidden() || !f.canRead()) { continue; } String name = f.getName(); // if (!ALLOWED_FILE_NAME.matcher(name).matches()) { // continue; buf.append("<li><a href=\""); buf.append(name); buf.append("\">"); buf.append(name); buf.append("</a></li>\r\n"); } buf.append("</ul></body></html>\r\n"); ByteBuf buffer = Unpooled.copiedBuffer(buf, CharsetUtil.UTF_8); response.content().writeBytes(buffer); buffer.release(); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } private void setContentTypeHeader(HttpResponse response, File file) { MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap(); response.headers().set(CONTENT_TYPE, mimeTypesMap.getContentType(file.getPath())); } }
package io.github.movementspeed.nhglib.graphics.shaders.tiledForward; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.*; import com.badlogic.gdx.graphics.g3d.Attributes; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Renderable; import com.badlogic.gdx.graphics.g3d.Shader; import com.badlogic.gdx.graphics.g3d.shaders.BaseShader; import com.badlogic.gdx.graphics.g3d.utils.RenderContext; import com.badlogic.gdx.graphics.glutils.ShaderProgram; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.GdxRuntimeException; import com.badlogic.gdx.utils.IntArray; import io.github.movementspeed.nhglib.core.ecs.systems.impl.RenderingSystem; import io.github.movementspeed.nhglib.enums.LightType; import io.github.movementspeed.nhglib.graphics.lights.NhgLight; import io.github.movementspeed.nhglib.graphics.lights.NhgLightsAttribute; import io.github.movementspeed.nhglib.graphics.shaders.attributes.IBLAttribute; import io.github.movementspeed.nhglib.graphics.shaders.attributes.PbrTextureAttribute; import io.github.movementspeed.nhglib.utils.graphics.ShaderUtils; public class PBRShader extends BaseShader { private int maxBonesLength = Integer.MIN_VALUE; private int bonesIID; private int bonesLoc; private float bones[]; private Vector3 vec1 = new Vector3(); private Matrix4 idtMatrix; private Color color; private Pixmap lightPixmap; private Pixmap lightInfoPixmap; private Texture lightTexture; private Texture lightInfoTexture; private Camera camera; private Params params; private Renderable renderable; private Environment environment; private LightGrid lightGrid; private ShaderProgram shaderProgram; private NhgLightsAttribute lightsAttribute; private Array<IntArray> lightsFrustum; private Array<NhgLight> lights; public PBRShader(Renderable renderable, Environment environment, Params params) { this.renderable = renderable; this.environment = environment; this.params = params; String prefix = createPrefix(renderable); String vert = prefix + Gdx.files.internal("shaders/tf_pbr_shader.vert").readString(); String frag = prefix + Gdx.files.internal("shaders/tf_pbr_shader.frag").readString(); ShaderProgram.pedantic = true; shaderProgram = new ShaderProgram(vert, frag); String shaderLog = shaderProgram.getLog(); if (!shaderProgram.isCompiled()) { throw new GdxRuntimeException(shaderLog); } lightsAttribute = (NhgLightsAttribute) environment.get(NhgLightsAttribute.Type); lights = lightsAttribute.lights; register("u_lights", new LocalSetter() { @Override public void set(BaseShader shader, int inputID, Renderable renderable, Attributes combinedAttributes) { shader.set(inputID, lightTexture); } }); register("u_lightInfo", new LocalSetter() { @Override public void set(BaseShader shader, int inputID, Renderable renderable, Attributes combinedAttributes) { shader.set(inputID, lightInfoTexture); } }); register("u_mvpMatrix", new LocalSetter() { @Override public void set(BaseShader shader, int inputID, Renderable renderable, Attributes combinedAttributes) { shader.set(inputID, shader.camera.combined); } }); register("u_viewMatrix", new LocalSetter() { @Override public void set(BaseShader shader, int inputID, Renderable renderable, Attributes combinedAttributes) { shader.set(inputID, shader.camera.view); } }); register("u_modelMatrix", new LocalSetter() { @Override public void set(BaseShader shader, int inputID, Renderable renderable, Attributes combinedAttributes) { shader.set(inputID, renderable.worldTransform); } }); register("u_graphicsWidth", new LocalSetter() { @Override public void set(BaseShader shader, int inputID, Renderable renderable, Attributes combinedAttributes) { shader.set(inputID, RenderingSystem.renderWidth); } }); register("u_graphicsHeight", new LocalSetter() { @Override public void set(BaseShader shader, int inputID, Renderable renderable, Attributes combinedAttributes) { shader.set(inputID, RenderingSystem.renderHeight); } }); register("u_albedo", new LocalSetter() { @Override public void set(BaseShader shader, int inputID, Renderable renderable, Attributes combinedAttributes) { PbrTextureAttribute textureAttribute = (PbrTextureAttribute) combinedAttributes.get(PbrTextureAttribute.Albedo); if (textureAttribute != null) { shader.set(inputID, textureAttribute.textureDescription.texture); } } }); register("u_metalness", new LocalSetter() { @Override public void set(BaseShader shader, int inputID, Renderable renderable, Attributes combinedAttributes) { PbrTextureAttribute textureAttribute = (PbrTextureAttribute) combinedAttributes.get(PbrTextureAttribute.Metalness); if (textureAttribute != null) { shader.set(inputID, textureAttribute.textureDescription.texture); } } }); register("u_roughness", new LocalSetter() { @Override public void set(BaseShader shader, int inputID, Renderable renderable, Attributes combinedAttributes) { PbrTextureAttribute textureAttribute = (PbrTextureAttribute) combinedAttributes.get(PbrTextureAttribute.Roughness); if (textureAttribute != null) { shader.set(inputID, textureAttribute.textureDescription.texture); } } }); register("u_normal", new LocalSetter() { @Override public void set(BaseShader shader, int inputID, Renderable renderable, Attributes combinedAttributes) { PbrTextureAttribute textureAttribute = (PbrTextureAttribute) combinedAttributes.get(PbrTextureAttribute.Normal); if (textureAttribute != null) { shader.set(inputID, textureAttribute.textureDescription.texture); } } }); register("u_ambientOcclusion", new LocalSetter() { @Override public void set(BaseShader shader, int inputID, Renderable renderable, Attributes combinedAttributes) { PbrTextureAttribute textureAttribute = (PbrTextureAttribute) combinedAttributes.get(PbrTextureAttribute.AmbientOcclusion); if (textureAttribute != null) { shader.set(inputID, textureAttribute.textureDescription.texture); } } }); register("u_irradiance", new LocalSetter() { @Override public void set(BaseShader shader, int inputID, Renderable renderable, Attributes combinedAttributes) { IBLAttribute attribute = (IBLAttribute) combinedAttributes.get(IBLAttribute.IrradianceType); if (attribute != null) { shader.set(inputID, attribute.textureDescription.texture); } } }); register("u_prefilter", new LocalSetter() { @Override public void set(BaseShader shader, int inputID, Renderable renderable, Attributes combinedAttributes) { IBLAttribute attribute = (IBLAttribute) combinedAttributes.get(IBLAttribute.PrefilterType); if (attribute != null) { shader.set(inputID, attribute.textureDescription.texture); } } }); register("u_brdf", new LocalSetter() { @Override public void set(BaseShader shader, int inputID, Renderable renderable, Attributes combinedAttributes) { IBLAttribute attribute = (IBLAttribute) combinedAttributes.get(IBLAttribute.BrdfType); if (attribute != null) { shader.set(inputID, attribute.textureDescription.texture); } } }); bonesIID = register("u_bones", new LocalSetter() { @Override public void set(BaseShader shader, int inputID, Renderable renderable, Attributes combinedAttributes) { if (renderable.bones != null) { int renderableBonesLength = renderable.bones.length * 16; if (renderableBonesLength > maxBonesLength) { maxBonesLength = renderableBonesLength; bones = new float[renderableBonesLength]; } for (int i = 0; i < renderableBonesLength; i++) { final int idx = i / 16; bones[i] = (idx >= renderable.bones.length || renderable.bones[idx] == null) ? idtMatrix.val[i % 16] : renderable.bones[idx].val[i % 16]; } shaderProgram.setUniformMatrix4fv(bonesLoc, bones, 0, renderableBonesLength); } } }); } @Override public void init() { super.init(shaderProgram, renderable); idtMatrix = new Matrix4(); bones = new float[0]; bonesLoc = loc(bonesIID); lightsFrustum = new Array<>(); for (int i = 0; i < 100; i++) { lightsFrustum.add(new IntArray()); } color = new Color(); lightTexture = new Texture(64, 128, Pixmap.Format.RGBA8888); lightTexture.setFilter(Texture.TextureFilter.Nearest, Texture.TextureFilter.Nearest); lightInfoTexture = new Texture(1, 128, Pixmap.Format.RGBA8888); lightInfoTexture.setFilter(Texture.TextureFilter.Nearest, Texture.TextureFilter.Nearest); lightPixmap = new Pixmap(64, 128, Pixmap.Format.RGBA8888); lightPixmap.setBlending(Pixmap.Blending.None); lightInfoPixmap = new Pixmap(1, 128, Pixmap.Format.RGBA8888); lightInfoPixmap.setBlending(Pixmap.Blending.None); lightGrid = new LightGrid(10, 10); } @Override public int compareTo(Shader other) { return 0; } @Override public boolean canRender(Renderable instance) { boolean diffuse = ShaderUtils.hasAlbedo(instance) == params.albedo; boolean metalness = ShaderUtils.hasMetalness(instance) == params.metalness; boolean roughness = ShaderUtils.hasRoughness(instance) == params.roughness; boolean normal = ShaderUtils.hasPbrNormal(instance) == params.normal; boolean ambientOcclusion = ShaderUtils.hasAmbientOcclusion(instance) == params.ambientOcclusion; boolean bones = ShaderUtils.useBones(instance) == params.useBones; boolean lit = ShaderUtils.hasLights(instance.environment) == params.lit; boolean gammaCorrection = ShaderUtils.useGammaCorrection(instance.environment) == params.gammaCorrection; boolean imageBasedLighting = ShaderUtils.useImageBasedLighting(instance.environment) == params.imageBasedLighting; return diffuse && metalness && roughness && normal && ambientOcclusion && bones && lit && gammaCorrection && imageBasedLighting; } @Override public void begin(Camera camera, RenderContext context) { this.camera = camera; lights = lightsAttribute.lights; float[] floatArray = new float[lights.size]; float[] float3Array = new float[lights.size * 3]; context.setCullFace(GL20.GL_BACK); context.setDepthTest(GL20.GL_LEQUAL); context.setDepthMask(true); lightGrid.setFrustums(((PerspectiveCamera) camera)); makeLightTexture(); super.begin(camera, context); if (shaderProgram.hasUniform("u_lightPositions[0]")) { shaderProgram.setUniform3fv("u_lightPositions", getLightPositions(float3Array), 0, lights.size * 3); } if (shaderProgram.hasUniform("u_lightDirections[0]")) { shaderProgram.setUniform3fv("u_lightDirections", getLightDirections(float3Array), 0, lights.size * 3); } if (shaderProgram.hasUniform("u_lightIntensities[0]")) { shaderProgram.setUniform1fv("u_lightIntensities", getLightIntensities(floatArray), 0, lights.size); } if (shaderProgram.hasUniform("u_lightInnerAngles[0]")) { shaderProgram.setUniform1fv("u_lightInnerAngles", getLightInnerAngles(floatArray), 0, lights.size); } if (shaderProgram.hasUniform("u_lightOuterAngles[0]")) { shaderProgram.setUniform1fv("u_lightOuterAngles", getLightOuterAngles(floatArray), 0, lights.size); } for (int i = 0; i < lights.size; i++) { NhgLight light = lights.get(i); String lightTypeUniform = "u_lightTypes[" + i + "]"; if (shaderProgram.hasUniform(lightTypeUniform)) { shaderProgram.setUniformi(lightTypeUniform, light.type.ordinal()); } } } @Override public void render(Renderable renderable) { super.render(renderable); } @Override public void end() { super.end(); } @Override public void dispose() { shaderProgram.dispose(); super.dispose(); } private void makeLightTexture() { for (int i = 0; i < 100; i++) { lightsFrustum.get(i).clear(); } for (int i = 0; i < lights.size; i++) { NhgLight l = lights.get(i); if (l.type != LightType.DIRECTIONAL_LIGHT) { lightGrid.checkFrustums(l.position, l.radius, lightsFrustum, i); } else { for (int j = 0; j < 100; j++) { lightsFrustum.get(j).add(i); } } } for (int i = 0; i < lights.size; i++) { NhgLight l = lights.get(i); float r = l.color.r; float g = l.color.g; float b = l.color.b; float a = l.radius / 255f; color.set(r, g, b, a); lightInfoPixmap.setColor(color); lightInfoPixmap.drawPixel(0, i); } lightInfoTexture.draw(lightInfoPixmap, 0, 0); for (int row = 0; row < 100; row++) { int col = 0; float r = lightsFrustum.get(row).size; float r255 = r / 255f; color.set(r255, 0, 0, 0); lightPixmap.setColor(color); lightPixmap.drawPixel(col, row); col++; for (int i = 0; i < lightsFrustum.get(row).size; i++) { int j = lightsFrustum.get(row).get(i); float j255 = ((float) j) / 255f; color.set(j255, 0, 0, 0); lightPixmap.setColor(color); lightPixmap.drawPixel(col, row); col++; } } lightTexture.draw(lightPixmap, 0, 0); } private String createPrefix(Renderable renderable) { String prefix = "#version 300 es\n"; if (params.useBones) { prefix += "#define numBones " + 12 + "\n"; final int n = renderable.meshPart.mesh.getVertexAttributes().size(); for (int i = 0; i < n; i++) { final VertexAttribute attr = renderable.meshPart.mesh.getVertexAttributes().get(i); if (attr.usage == VertexAttributes.Usage.BoneWeight) { prefix += "#define boneWeight" + attr.unit + "Flag\n"; } } } if (params.albedo) { prefix += "#define defAlbedo\n"; } if (params.metalness) { prefix += "#define defMetalness\n"; } if (params.roughness) { prefix += "#define defRoughness\n"; } if (params.normal) { prefix += "#define defNormal\n"; } if (params.ambientOcclusion) { prefix += "#define defAmbientOcclusion\n"; } if (params.gammaCorrection) { prefix += "#define defGammaCorrection\n"; } if (params.imageBasedLighting) { prefix += "#define defImageBasedLighting\n"; } if (params.lit) { NhgLightsAttribute lightsAttribute = (NhgLightsAttribute) environment.get(NhgLightsAttribute.Type); prefix += "#define lights " + lightsAttribute.lights.size + "\n"; } String renderer = Gdx.gl.glGetString(GL30.GL_RENDERER).toUpperCase(); if (renderer.contains("MALI")) { prefix += "#define GPU_MALI\n"; } else if (renderer.contains("ADRENO")) { prefix += "#define GPU_ADRENO\n"; } return prefix; } private float[] getLightPositions(float[] res) { int i = 0; for (int k = 0; k < lights.size; k++) { vec1.set(lights.get(k).position); vec1.mul(camera.view); res[i++] = vec1.x; res[i++] = vec1.y; res[i++] = vec1.z; } return res; } private float[] getLightDirections(float[] res) { int i = 0; for (int k = 0; k < lights.size; k++) { NhgLight light = lights.get(k); if (light.type != LightType.POINT_LIGHT) { vec1.set(light.direction) .rot(camera.view); res[i++] = vec1.x; res[i++] = vec1.y; res[i++] = vec1.z; } } return res; } private float[] getLightIntensities(float[] res) { for (int i = 0; i < lights.size; i++) { res[i] = lights.get(i).intensity; } return res; } private float[] getLightInnerAngles(float[] res) { for (int i = 0; i < lights.size; i++) { res[i] = lights.get(i).innerAngle; } return res; } private float[] getLightOuterAngles(float[] res) { for (int i = 0; i < lights.size; i++) { res[i] = lights.get(i).outerAngle; } return res; } public static class Params { boolean useBones; boolean albedo; boolean metalness; boolean roughness; boolean normal; boolean ambientOcclusion; boolean lit; boolean gammaCorrection; boolean imageBasedLighting; } }
package foundation.omni.netapi.omniwallet; import foundation.omni.CurrencyID; import foundation.omni.OmniDivisibleValue; import foundation.omni.OmniIndivisibleValue; import foundation.omni.OmniValue; import foundation.omni.PropertyType; import foundation.omni.json.pojo.OmniPropertyInfo; import foundation.omni.netapi.ConsensusService; import foundation.omni.netapi.OmniJBalances; import foundation.omni.netapi.WalletAddressBalance; import foundation.omni.netapi.omniwallet.json.AddressVerifyInfo; import foundation.omni.netapi.omniwallet.json.OmniwalletAddressBalance; import foundation.omni.netapi.omniwallet.json.OmniwalletAddressPropertyBalance; import foundation.omni.netapi.omniwallet.json.OmniwalletPropertiesListResponse; import foundation.omni.netapi.omniwallet.json.OmniwalletPropertyInfo; import foundation.omni.netapi.omniwallet.json.RevisionInfo; import foundation.omni.rpc.AddressBalanceEntry; import foundation.omni.rpc.BalanceEntry; import foundation.omni.rpc.ConsensusSnapshot; import foundation.omni.rpc.SmartPropertyListInfo; import io.reactivex.rxjava3.core.BackpressureStrategy; import io.reactivex.rxjava3.core.Flowable; import io.reactivex.rxjava3.core.Maybe; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.core.Single; import io.reactivex.rxjava3.disposables.Disposable; import io.reactivex.rxjava3.internal.operators.observable.ObservableInterval; import io.reactivex.rxjava3.processors.BehaviorProcessor; import io.reactivex.rxjava3.processors.FlowableProcessor; import org.bitcoinj.core.Address; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.core.Sha256Hash; import org.consensusj.bitcoin.json.pojo.ChainTip; import org.consensusj.bitcoin.rx.jsonrpc.PollingChainTipService; import org.consensusj.bitcoin.rx.jsonrpc.RxJsonChainTipClient; import org.consensusj.jsonrpc.AsyncSupport; import org.reactivestreams.Publisher; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOError; import java.io.IOException; import java.math.BigDecimal; import java.math.BigInteger; import java.net.URI; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; /** * Base class for Omniwallet Client implementations * TODO: We should probably use composition rather than inheritance and have * a RawOmniwallet interface and inject an implementation of * that into the constructor of an OmniwalletConsensusService type. */ public abstract class OmniwalletAbstractClient implements ConsensusService, RxOmniWalletClient { private static final Logger log = LoggerFactory.getLogger(OmniwalletAbstractClient.class); /** * This endpoint has an older (and now slightly incompatible) API */ @Deprecated public static final URI omniwalletBase = URI.create("https: public static final URI omniwalletApiBase = URI.create("https://api.omniwallet.org"); public static final URI omniExplorerApiBase = URI.create("https://api.omniexplorer.info"); public static final URI stagingBase = URI.create("https://staging.omniwallet.org"); static public final int BALANCES_FOR_ADDRESSES_MAX_ADDR = 20; static public final int CONNECT_TIMEOUT_MILLIS = 15 * 1000; // 15s static public final int READ_TIMEOUT_MILLIS = 120 * 1000; // 120s (long enough to load USDT rich list) protected final URI baseURI; private boolean debug; protected boolean strictMode; /** * netParams, if non-null, is used for validating addresses during deserialization */ protected final NetworkParameters netParams; private final Observable<Long> chainTipPollingInterval; private final Flowable<ChainTip> chainTipSource; private Disposable chainTipSubscription; private final FlowableProcessor<ChainTip> chainTipProcessor = BehaviorProcessor.create(); protected final Map<CurrencyID, PropertyType> cachedPropertyTypes = new ConcurrentHashMap<>(); public OmniwalletAbstractClient(URI baseURI, boolean debug, boolean strictMode) { this(baseURI, debug, strictMode, null); } public OmniwalletAbstractClient(URI baseURI, boolean debug, boolean strictMode, NetworkParameters netParams) { this.baseURI = baseURI; this.debug = debug; this.strictMode = strictMode; this.netParams = netParams; chainTipPollingInterval = ObservableInterval.interval(2,60, TimeUnit.SECONDS); chainTipSource = pollForDistinctChainTip(); } public synchronized void start() { if (chainTipSubscription == null) { chainTipSubscription = chainTipSource.subscribe(chainTipProcessor::onNext, chainTipProcessor::onError, chainTipProcessor::onComplete); } } @Override public CompletableFuture<Integer> currentBlockHeightAsync() { return revisionInfo().thenApply(RevisionInfo::getLastBlock); } abstract public CompletableFuture<RevisionInfo> revisionInfo(); protected abstract CompletableFuture<OmniwalletPropertiesListResponse> propertiesList(); @Override public CompletableFuture<List<OmniPropertyInfo>> listSmartProperties() { return propertiesList().thenApply(response -> response.getPropertyInfoList().stream() .map(OmniwalletAbstractClient::mapToOmniPropertyInfo) .collect(Collectors.toList())); } @Override public SortedMap<Address, BalanceEntry> getConsensusForCurrency(CurrencyID currencyID) throws InterruptedException, ExecutionException { return getConsensusForCurrencyAsync(currencyID).get(); } /** * Get a sorted map of consensus information for a currency. Internally we use an {@link CompletableFuture#thenCombine} * to make an async call to {@link OmniwalletAbstractClient#lookupPropertyType} which if it doesn't find the property type in * the cache may result in a network I/O to get the property list. * * @param currencyID the currency. * @return A future for a sorted map of address-balance consensus information */ @Override public CompletableFuture<SortedMap<Address, BalanceEntry>> getConsensusForCurrencyAsync(CurrencyID currencyID) { return verifyAddresses(currencyID) .thenCombine(lookupPropertyType(currencyID), (balances, ptype) -> balances.stream() .map(bal -> balanceMapper(bal, ptype)) .collect(Collectors.toMap( // Key is Address AddressBalanceEntry::getAddress, // Value is a BalanceEntry (with no Address field) address -> new BalanceEntry(address.getBalance(), address.getReserved(), address.getFrozen()), // If duplicate key keep existing value (there should be no duplicate keys) (existingValue, duplicateValue) -> existingValue, // Use a TreeMap so map is sorted by Address TreeMap::new) )); } @Override public OmniJBalances balancesForAddresses(List<Address> addresses) throws InterruptedException, IOException { try { return balancesForAddressesAsync(addresses).get(); } catch (ExecutionException e) { throw new IOException(e); } } @Override public CompletableFuture<OmniJBalances> balancesForAddressesAsync(List<Address> addresses) { if (addresses.size() > BALANCES_FOR_ADDRESSES_MAX_ADDR) { throw new IllegalArgumentException("Exceeded number of allowable addresses"); } return balanceMapForAddresses(addresses).thenApply(map -> { OmniJBalances balances = new OmniJBalances(); map.forEach((address, owb) -> balances.put(address, balanceEntryMapper(owb))); return balances; }); } @Override public WalletAddressBalance balancesForAddress(Address address) throws InterruptedException, IOException { try { return balancesForAddressAsync(address).get(); } catch (ExecutionException e) { throw new IOException(e); } } @Override public CompletableFuture<WalletAddressBalance> balancesForAddressAsync(Address address) { return balanceMapForAddress(address) .thenApply(map -> map.get(address)) .thenApply(this::balanceEntryMapper); } @Override public CompletableFuture<ChainTip> getActiveChainTip() { return revisionInfo() .thenApply(this::revisionInfoToChainTip); } @Override public ConsensusSnapshot createSnapshot(CurrencyID id, int blockHeight, SortedMap<Address, BalanceEntry> entries) { return new ConsensusSnapshot(id,blockHeight, "Omniwallet", baseURI, entries); } @Override public Publisher<ChainTip> chainTipPublisher() { return chainTipProcessor; } private ChainTip revisionInfoToChainTip(RevisionInfo info) { return new ChainTip(info.getLastBlock(), info.getBlockHash(), 0, "active"); } /** * Using a polling interval provided by {@link PollingChainTipService#getPollingInterval()} provide a * stream of distinct {@link ChainTip}s. * * @return A stream of distinct {@code ChainTip}s. */ private Flowable<ChainTip> pollForDistinctChainTip() { return chainTipPollingInterval .doOnNext(t -> log.debug("got interval")) .flatMapMaybe(t -> this.currentChainTipMaybe()) .doOnNext(tip -> log.debug("blockheight, blockhash = {}, {}", tip.getHeight(), tip.getHash())) //.distinctUntilChanged(ChainTip::getHash) // Omni Core looks for a hash change (because hash includes height) .distinctUntilChanged(ChainTip::getHeight) // Since hash isn't (YET!) included on Omniwallet, we'll just look for a new height .doOnNext(tip -> log.info("** NEW ** blockheight, blockhash = {}, {}", tip.getHeight(), tip.getHash())) // ERROR backpressure strategy is compatible with BehaviorProcessor since it subscribes to MAX items .toFlowable(BackpressureStrategy.ERROR); } @Override public void logSuccess(ChainTip result) { log.debug("RPC call returned: {}", result); } @Override public void logError(Throwable throwable) { log.error("Exception in RPCCall", throwable); } protected abstract CompletableFuture<Map<Address, OmniwalletAddressBalance>> balanceMapForAddress(Address address); protected abstract CompletableFuture<Map<Address, OmniwalletAddressBalance>> balanceMapForAddresses(List<Address> addresses); protected abstract CompletableFuture<List<AddressVerifyInfo>> verifyAddresses(CurrencyID currencyID); protected AddressBalanceEntry balanceMapper(AddressVerifyInfo item, PropertyType propertyType) { //log.info("Mapping AddressVerifyInfo to AddressBalanceEntry: {}, {}, {}, {}", item.getAddress(), item.getBalance(), item.getReservedBalance(), item.isFrozen()); Address address = item.getAddress(); OmniValue balance = toOmniValue(item.getBalance(), propertyType); OmniValue reserved = toOmniValue(item.getReservedBalance(), propertyType); OmniValue frozen = item.isFrozen() ? balance : OmniValue.of(0, propertyType); return new AddressBalanceEntry(address, balance, reserved, frozen); } protected static OmniValue stringToOmniValue(String valueString) { boolean divisible = valueString.contains("."); // Divisible amounts always contain a decimal point if (divisible) { return OmniValue.of(new BigDecimal(valueString), PropertyType.DIVISIBLE); } else { return OmniValue.of(Long.parseLong(valueString), PropertyType.INDIVISIBLE); } } protected SmartPropertyListInfo mapToSmartPropertyListInfo(OmniwalletPropertyInfo property) { return new SmartPropertyListInfo(property.getPropertyid(), property.getName(), property.getCategory(), property.getSubcategory(), property.getData(), property.getUrl(), property.isDivisible()); } static OmniPropertyInfo mapToOmniPropertyInfo(OmniwalletPropertyInfo property) { return new OmniPropertyInfo(property.getPropertyid(), property.getName(), property.getCategory(), property.getSubcategory(), property.getData(), property.getUrl(), property.isDivisible(), property.getIssuer(), property.getCreationTxId(), property.isFixedIssuance(), property.isManagedIssuance(), property.isFreezingEnabled(), property.getTotalTokens()); } /** * Get the property type for a propertyId. Is asynchronous using {@link CompletableFuture} because * if the value isn't in the cache, we'll need to fetch a list of properties from the server. * TODO: Should we consider making this method more general and returning OmniPropertyInfo? * * @param propertyID The propertyId to lookup * @return The property type. */ protected CompletableFuture<PropertyType> lookupPropertyType(CurrencyID propertyID) { CompletableFuture<PropertyType> future = new CompletableFuture<>(); if (!cachedPropertyTypes.containsKey(propertyID)) { listSmartProperties().whenComplete((infos,t) -> { if (infos != null) { infos.forEach(info -> { cachedPropertyTypes.put(info.getPropertyid(), divisibleToPropertyType(info.getDivisible())); }); PropertyType type = cachedPropertyTypes.get(propertyID); if (type != null) { future.complete(type); } else { future.completeExceptionally(new RuntimeException("Can't find PropertyType for id " + propertyID)); } } else { future.completeExceptionally(t); } }); } else { future.complete(cachedPropertyTypes.get(propertyID)); } return future; } protected WalletAddressBalance balanceEntryMapper(OmniwalletAddressBalance owb) { WalletAddressBalance wab = new WalletAddressBalance(); for (OmniwalletAddressPropertyBalance pb : owb.getBalance()) { CurrencyID id = pb.getId(); PropertyType type = pb.isDivisible() ? PropertyType.DIVISIBLE : PropertyType.INDIVISIBLE; OmniValue value = pb.getValue(); OmniValue zero = OmniValue.ofWilletts(0, type); if (!pb.isError()) { wab.put(id, new BalanceEntry(value, zero, zero)); } } return wab; } protected URI consensusURI(CurrencyID currencyID) { return baseURI.resolve("/v1/mastercoin_verify/addresses?currency_id=" + currencyID.getValue()); } protected OmniValue toOmniValue(String input, PropertyType type) { if (strictMode) { /* Validate string */ } return type.isDivisible() ? toOmniDivisibleValue(input) : toOmniIndivisibleValue(input); } protected OmniDivisibleValue toOmniDivisibleValue(String inputStr) { return toOmniDivisibleValue(new BigDecimal(inputStr)); } protected OmniDivisibleValue toOmniDivisibleValue(BigDecimal input) { if (input.compareTo(OmniDivisibleValue.MAX_VALUE) > 0) { if (strictMode) { throw new ArithmeticException("too big"); } return OmniDivisibleValue.MAX; } else if (input.compareTo(OmniDivisibleValue.MIN_VALUE) < 0) { if (strictMode) { throw new ArithmeticException("too small"); } return OmniDivisibleValue.MIN; } else { return OmniDivisibleValue.of(input); } } protected OmniIndivisibleValue toOmniIndivisibleValue(String input) { return toOmniIndivisibleValue(new BigInteger(input)); } protected OmniIndivisibleValue toOmniIndivisibleValue(BigInteger input) { if (input.compareTo(OmniIndivisibleValue.MAX_BIGINT) > 0) { if (strictMode) { throw new ArithmeticException("too big"); } return OmniIndivisibleValue.MAX; } else if (input.compareTo(OmniIndivisibleValue.MIN_BIGINT) < 0) { if (strictMode) { throw new ArithmeticException("too small"); } return OmniIndivisibleValue.MIN; } else { return OmniIndivisibleValue.of(input); } } protected PropertyType divisibleToPropertyType(boolean divisible) { return divisible ? PropertyType.DIVISIBLE : PropertyType.INDIVISIBLE; } }
package net.nemerosa.ontrack.model.buildfilter; import com.fasterxml.jackson.databind.JsonNode; import net.nemerosa.ontrack.model.structure.Build; import net.nemerosa.ontrack.model.structure.ID; import java.util.List; import java.util.Optional; public interface BuildFilterProvider<T> { /** * Display name */ String getName(); /** * If this method returns <code>true</code>, there is no need to configure the filter. */ boolean isPredefined(); /** * Gets the form for a new filter on the given branch */ BuildFilterForm newFilterForm(ID branchId); /** * Gets the form for a pre filled filter * * @param branchId Branch to filter * @param data Filter data * @return Form */ BuildFilterForm getFilterForm(ID branchId, T data); /** * Performs the filtering */ default List<Build> filterBranchBuilds(ID branchId, T data) { throw new UnsupportedOperationException("Filter branch builds must be implemented for " + this.getClass()); } /** * Builds an actual filter using the given set of parameters */ @Deprecated BuildFilter filter(ID branchId, T data); /** * Parses the filter data, provided as JSON, into an actual filter data object, when possible. * * @param data Filter data, as JSON * @return Filter data object, or empty when not possible to parse */ Optional<T> parse(JsonNode data); }
package org.eclipse.mylar.bugzilla.core.internal; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.List; import javax.security.auth.login.LoginException; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.mylar.bugzilla.core.Attribute; import org.eclipse.mylar.bugzilla.core.BugReport; import org.eclipse.mylar.bugzilla.core.BugzillaPlugin; import org.eclipse.mylar.bugzilla.core.BugzillaRepository; import org.eclipse.mylar.bugzilla.core.Comment; import org.eclipse.mylar.bugzilla.core.IBugzillaConstants; import org.eclipse.mylar.bugzilla.core.Operation; import org.eclipse.mylar.bugzilla.core.internal.HtmlStreamTokenizer.Token; /** * @author Shawn Minto * * This class parses bugs so that they can be displayed using the bug editor */ public class BugParser { /** Parser for dates in the report */ private static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm"); private static final String keywordsUrl = "describekeywords.cgi"; /** * Parse the case where we have found an attribute name * @param in The input stream for the bug * @return The name of the attribute that we are parsing * @throws IOException */ private static String parseAttributeName(HtmlStreamTokenizer tokenizer) throws IOException, ParseException { StringBuffer sb = new StringBuffer(); parseTableCell(tokenizer, sb); HtmlStreamTokenizer.unescape(sb); // remove the colon if there is one if (sb.length() > 0 && sb.charAt(sb.length() - 1) == ':') { sb.deleteCharAt(sb.length() - 1); } return sb.toString(); } /** * Parse the case where we have found attribute values * @param in The input stream of the bug * @param bug The bug report for the current bug * @param attribute The name of the attribute * @throws IOException */ private static void parseAttributeValue( BugReport bug, String attributeName, HtmlStreamTokenizer tokenizer, String userName, String password) throws IOException, ParseException { Token token = tokenizer.nextToken(); if (token.getType() == Token.TAG) { HtmlTag tag = (HtmlTag) token.getValue(); // make sure that we are on a tag that we care about, not a label // fix added so that we can parse the mozilla bug pages if(tag.getTagType() == HtmlTag.Type.LABEL) { token = tokenizer.nextToken(); if (token.getType() == Token.TAG) tag = (HtmlTag) token.getValue(); else { StringBuffer sb = new StringBuffer(); if (token.getType() == Token.TEXT) { sb.append((StringBuffer) token.getValue()); parseAttributeValueCell(bug, attributeName, tokenizer, sb); } } } if (tag.getTagType() == HtmlTag.Type.SELECT && !tag.isEndTag()) { String parameterName = tag.getAttribute("name"); parseSelect(bug, attributeName, parameterName, tokenizer); } else if (tag.getTagType() == HtmlTag.Type.INPUT && !tag.isEndTag()) { parseInput(bug, attributeName, tag, userName, password); } else if (!tag.isEndTag() || attributeName.equalsIgnoreCase("resolution")) { if(tag.isEndTag() && attributeName.equalsIgnoreCase("resolution")) { Attribute a = new Attribute(attributeName); a.setValue(""); bug.addAttribute(a); } parseAttributeValueCell(bug, attributeName, tokenizer); } } else { StringBuffer sb = new StringBuffer(); if (token.getType() == Token.TEXT) { sb.append((StringBuffer) token.getValue()); parseAttributeValueCell(bug, attributeName, tokenizer, sb); } } } /** * Parse the case where the attribute value is just text in a table cell * @param in The input stream of the bug * @param bug The bug report for the current bug * @param attributeName The name of the attribute that we are parsing * @throws IOException */ private static void parseAttributeValueCell( BugReport bug, String attributeName, HtmlStreamTokenizer tokenizer) throws IOException, ParseException { StringBuffer sb = new StringBuffer(); parseAttributeValueCell(bug, attributeName, tokenizer, sb); } private static void parseAttributeValueCell( BugReport bug, String attributeName, HtmlStreamTokenizer tokenizer, StringBuffer sb) throws IOException, ParseException { parseTableCell(tokenizer, sb); HtmlStreamTokenizer.unescape(sb); // create a new attribute and set its value to the value that we retrieved Attribute a = new Attribute(attributeName); a.setValue(sb.toString()); // if we found an attachment attribute, forget about it, else add the // attribute to the bug report if (attributeName.toLowerCase().startsWith("attachments")) { // do nothing } else { if(attributeName.equals("Bug a.setValue(a.getValue().replaceFirst("alias:", "")); bug.addAttribute(a); } } /** * Reads text into a StringBuffer until it encounters a close table cell tag (&lt;/TD&gt;) or start of another cell. * The text is appended to the existing value of the buffer. <b>NOTE:</b> Does not handle nested cells! * @param tokenizer * @param sb * @throws IOException * @throws ParseException */ private static void parseTableCell(HtmlStreamTokenizer tokenizer, StringBuffer sb) throws IOException, ParseException { boolean noWhitespace = false; for (Token token = tokenizer.nextToken(); token.getType() != Token.EOF; token = tokenizer.nextToken()) { if (token.getType() == Token.TAG) { HtmlTag tag = (HtmlTag) token.getValue(); if (tag.getTagType() == HtmlTag.Type.TD) { if (!tag.isEndTag()) { tokenizer.pushback(token); } break; } noWhitespace = token.getWhitespace().length() == 0; } else if (token.getType() == Token.TEXT) { // if there was no whitespace between the tag and the // preceding text, don't insert whitespace before this text // unless it is there in the source if (!noWhitespace && token.getWhitespace().length() > 0 && sb.length() > 0) { sb.append(' '); } sb.append((StringBuffer)token.getValue()); } } } /** * Parse the case where the attribute value is an option * @param in The input stream for the bug * @param bug The bug report for the current bug * @param attribute The name of the attribute that we are parsing * @param parameterName the SELECT tag's name * @throws IOException */ private static void parseSelect( BugReport bug, String attributeName, String parameterName, HtmlStreamTokenizer tokenizer) throws IOException, ParseException { boolean first = false; Attribute a = new Attribute(attributeName); a.setParameterName(parameterName); Token token = tokenizer.nextToken(); while ( token.getType() != Token.EOF) { if (token.getType() == Token.TAG) { HtmlTag tag = (HtmlTag) token.getValue(); if (tag.getTagType() == HtmlTag.Type.SELECT && tag.isEndTag()) break; if (tag.getTagType() == HtmlTag.Type.OPTION && !tag.isEndTag()) { String optionName = tag.getAttribute("value"); boolean selected = tag.hasAttribute("selected"); StringBuffer optionText = new StringBuffer(); for (token = tokenizer.nextToken(); token.getType() == Token.TEXT; token = tokenizer.nextToken()) { if (optionText.length() > 0) { optionText.append(' '); } optionText.append((StringBuffer) token.getValue()); } a.addOptionValue(optionText.toString(), optionName); if (selected || first) { a.setValue(optionText.toString()); first = false; } } else { token = tokenizer.nextToken(); } } else { token = tokenizer.nextToken(); } } // if we parsed the cc field add the e-mails to the bug report else add the attribute to the bug report if (attributeName.toLowerCase().startsWith("cc")) { for (Iterator<String> it = a.getOptionValues().keySet().iterator(); it.hasNext(); ) { String email = it.next(); bug.addCC(HtmlStreamTokenizer.unescape(email)); } } else { bug.addAttribute(a); } } /** * Parse the case where the attribute value is an input * @param bug The bug report for the current bug * @param attributeName The name of the attribute * @param tag The INPUT tag * @throws IOException */ private static void parseInput( BugReport bug, String attributeName, HtmlTag tag, String userName, String password) throws IOException { Attribute a = new Attribute(attributeName); a.setParameterName(tag.getAttribute("name")); String name = tag.getAttribute("name"); String value = tag.getAttribute("value"); if (value == null) value = ""; // if we found the summary, add it to the bug report if (name.equalsIgnoreCase("short_desc")) { bug.setSummary(value); } else if (name.equalsIgnoreCase("bug_file_loc")) { a.setValue(value); bug.addAttribute(a); } else if (name.equalsIgnoreCase("newcc")) { a.setValue(value); bug.addAttribute(a); } else { // otherwise just add the attribute a.setValue(value); bug.addAttribute(a); if (attributeName.equalsIgnoreCase("keywords") && BugzillaRepository.getURL() != null) { BufferedReader input = null; try { String urlText = ""; // if we have a user name, may as well log in just in case it is required if(userName != null && !userName.equals("") && password != null && !password.equals("")) { /* * The UnsupportedEncodingException exception for * URLEncoder.encode() should not be thrown, since every * implementation of the Java platform is required to support * the standard charset "UTF-8" */ urlText += "?GoAheadAndLogIn=1&Bugzilla_login=" + URLEncoder.encode(userName, "UTF-8") + "&Bugzilla_password=" + URLEncoder.encode(password, "UTF-8"); } // connect to the bugzilla server to get the keyword list URL url = new URL(BugzillaRepository.getURL() + "/" + keywordsUrl+urlText); URLConnection urlConnection = BugzillaPlugin.getDefault().getUrlConnection(url); input = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); // parse the valid keywords and add them to the bug List<String> keywords = new KeywordParser(input).getKeywords(); bug.setKeywords(keywords); } catch(Exception e) { // throw an exception if there is a problem reading the bug from the server throw new IOException("Exception while fetching the list of keywords from the server: " + e.getMessage()); } finally { try{ if(input != null) input.close(); }catch(IOException e) { BugzillaPlugin.log(new Status(IStatus.ERROR, IBugzillaConstants.PLUGIN_ID,IStatus.ERROR,"Problem closing the stream", e)); } } } } } /** * Parse the case where we are dealing with the description * @param bug The bug report for the bug * @throws IOException */ private static void parseDescription(BugReport bug, HtmlStreamTokenizer tokenizer) throws IOException, ParseException { StringBuffer sb = new StringBuffer(); for (Token token = tokenizer.nextToken(); token.getType() != Token.EOF; token = tokenizer.nextToken()) { if (token.getType() == Token.TAG) { HtmlTag tag = (HtmlTag) token.getValue(); if (tag.getTagType() == HtmlTag.Type.PRE && tag.isEndTag()) break; } else if (token.getType() == Token.TEXT) { if (sb.length() > 0) { sb.append(token.getWhitespace()); } sb.append((StringBuffer) token.getValue()); } } // set the bug to have the description we retrieved String text = HtmlStreamTokenizer.unescape(sb).toString(); bug.setDescription(text); } /** * Parse the case where we have found the start of a comment * @param in The input stream of the bug * @param bug The bug report for the current bug * @return The comment that we have created with the information * @throws IOException * @throws ParseException */ private static Comment parseCommentHead(BugReport bug, HtmlStreamTokenizer tokenizer) throws IOException, ParseException { int number = 0; Date date = null; String author = null; String authorName = null; // get the comment's number for (Token token = tokenizer.nextToken(); token.getType() != Token.EOF; token = tokenizer.nextToken()) { if (token.getType() == Token.TAG) { HtmlTag tag = (HtmlTag) token.getValue(); if (tag.getTagType() == HtmlTag.Type.A) { String href = tag.getAttribute("href"); if (href != null) { int index = href.toLowerCase().indexOf(" if (index == -1) continue; token = tokenizer.nextToken(); number = Integer.parseInt(((StringBuffer)token.getValue()).toString().substring(1)); break; } } } } for (Token token = tokenizer.nextToken(); token.getType() != Token.EOF; token = tokenizer.nextToken()) { if (token.getType() == Token.TAG) { HtmlTag tag = (HtmlTag) token.getValue(); if (tag.getTagType() == HtmlTag.Type.A) { String href = tag.getAttribute("href"); if (href != null) { int index = href.toLowerCase().indexOf("mailto"); if (index == -1) continue; author = href.substring(index + 7); break; } } } } // get the author's real name StringBuffer sb = new StringBuffer(); for (Token token = tokenizer.nextToken(); token.getType() != Token.EOF; token = tokenizer.nextToken()) { if (token.getType() == Token.TAG) { HtmlTag tag = (HtmlTag) token.getValue(); if (tag.getTagType() == HtmlTag.Type.A && tag.isEndTag()) break; } else if (token.getType() == Token.TEXT) { if (sb.length() > 0) { sb.append(' '); } sb.append((StringBuffer)token.getValue()); } } authorName = sb.toString(); // get the comment's date sb.setLength(0); for (Token token = tokenizer.nextToken(); token.getType() != Token.EOF; token = tokenizer.nextToken()) { if (token.getType() == Token.TAG) { HtmlTag tag = (HtmlTag) token.getValue(); if (tag.getTagType() == HtmlTag.Type.I && tag.isEndTag()) break; } else if (token.getType() == Token.TEXT) { if (sb.length() > 0) { sb.append(' '); } sb.append((StringBuffer)token.getValue()); } } if (sb.length() > 16) { date = df.parse(sb.substring(0, 16)); } else { date = Calendar.getInstance().getTime(); // XXX: failed to get date } return new Comment(bug, number, date, author, authorName); } /** * Parse the case where we have comment text * @param in The input stream for the bug * @param bug The bug report for the current bug * @param comment The comment to add the text to * @throws IOException */ private static void parseCommentText( BugReport bug, Comment comment, HtmlStreamTokenizer tokenizer) throws IOException, ParseException { StringBuffer sb = new StringBuffer(); for (Token token = tokenizer.nextToken(); token.getType() != Token.EOF; token = tokenizer.nextToken()) { if (token.getType() == Token.TAG) { HtmlTag tag = (HtmlTag) token.getValue(); if (sb.length() > 0) { // added to ensure whitespace is not lost if adding a tag within a tag sb.append(token.getWhitespace()); } if (tag.getTagType() == HtmlTag.Type.PRE && tag.isEndTag()) break; } else if (token.getType() == Token.TEXT) { if (sb.length() > 0) { sb.append(token.getWhitespace()); } sb.append((StringBuffer) token.getValue()); } } HtmlStreamTokenizer.unescape(sb); comment.setText(sb.toString()); bug.addComment(comment); } /** * Parse the full html version of the bug * @param in - the input stream for the bug * @param id - the id of the bug that is to be parsed * @return A bug report for the bug that was parsed * @throws IOException * @throws ParseException */ public static BugReport parseBug(Reader in, int id, String serverName, boolean is218, String userName, String password) throws IOException, ParseException, LoginException { // create a new bug report and set the parser state to the start state BugReport bug = new BugReport(id, serverName); ParserState state = ParserState.START; Comment comment = null; String attribute = null; HtmlStreamTokenizer tokenizer = new HtmlStreamTokenizer(in, null); boolean isTitle = false; boolean possibleBadLogin = false; boolean checkBody = false; String title = ""; StringBuffer body = new StringBuffer(); for (Token token = tokenizer.nextToken(); token.getType() != Token.EOF; token = tokenizer.nextToken()) { // make sure that bugzilla doesn't want us to login if(token.getType() == Token.TAG && ((HtmlTag)(token.getValue())).getTagType() == HtmlTag.Type.TITLE && !((HtmlTag)(token.getValue())).isEndTag()) { isTitle = true; continue; } if(isTitle) { // get all of the data in the title tag if(token.getType() != Token.TAG) { title += ((StringBuffer)token.getValue()).toString().toLowerCase() + " "; continue; } else if(token.getType() == Token.TAG && ((HtmlTag)token.getValue()).getTagType() == HtmlTag.Type.TITLE && ((HtmlTag)token.getValue()).isEndTag()) { // check and see if the title seems as though we have wrong login info if(title.indexOf("login") != -1 || (title.indexOf("invalid") != -1 && title.indexOf("password") != -1) || title.indexOf("check e-mail") != -1) possibleBadLogin = true; // we possibly have a bad login // if the title starts with error, we may have a login problem, or // there is a problem with the bug (doesn't exist), so we must do // some more checks if(title.startsWith("error")) checkBody = true; isTitle = false; title = ""; } continue; } // if we have to add all of the text so that we can check it later // for problems with the username and password if(checkBody && token.getType() == Token.TEXT) { body.append((StringBuffer)token.getValue()); body.append(" "); } // we have found the start of an attribute name if ((state == ParserState.ATT_NAME || state == ParserState.START) && token.getType() == Token.TAG ) { HtmlTag tag = (HtmlTag) token.getValue(); if (tag.getTagType() == HtmlTag.Type.TD && "right".equalsIgnoreCase(tag.getAttribute("align"))) { // parse the attribute's name attribute = parseAttributeName(tokenizer); if (attribute.toLowerCase().startsWith("opened")) { // find the colon so we can get the date int index = attribute.toLowerCase().indexOf(":"); String date; if (index != -1) date = attribute.substring(index + 1).trim(); else date = attribute.substring(6).trim(); // set the bugs opened date to be the date we parsed bug.setCreated(df.parse(date)); state = ParserState.ATT_NAME; continue; } // in 2.18, the last modified looks like the opened so we need to parse it differently if (attribute.toLowerCase().startsWith("last modified")&& is218) { // find the colon so we can get the date int index = attribute.toLowerCase().indexOf(":"); String date; if (index != -1) date = attribute.substring(index + 1).trim(); else date = attribute.substring(6).trim(); // create a new attribute and set the date Attribute t = new Attribute("Last Modified"); t.setValue(date); // add the attribute to the bug report bug.addAttribute(t); state = ParserState.ATT_NAME; continue; } state = ParserState.ATT_VALUE; continue; } else if (tag.getTagType() == HtmlTag.Type.INPUT && "radio".equalsIgnoreCase(tag.getAttribute("type")) && "knob".equalsIgnoreCase(tag.getAttribute("name"))) { // we found a radio button parseOperations(bug, tokenizer, tag, is218); } } // we have found the start of attribute values if (state == ParserState.ATT_VALUE && token.getType() == Token.TAG) { HtmlTag tag = (HtmlTag) token.getValue(); if (tag.getTagType() == HtmlTag.Type.TD) { // parse the attribute values parseAttributeValue(bug, attribute, tokenizer, userName, password); state = ParserState.ATT_NAME; attribute = null; continue; } } // we have found the start of a comment if (state == ParserState.DESC_START && token.getType() == Token.TAG) { HtmlTag tag = (HtmlTag) token.getValue(); if (tag.getTagType() == HtmlTag.Type.I) { // parse the comment's start comment = parseCommentHead(bug, tokenizer); state = ParserState.DESC_VALUE; continue; } } // we have found the start of the comment text if (state == ParserState.DESC_VALUE && token.getType() == Token.TAG) { HtmlTag tag = (HtmlTag) token.getValue(); if (tag.getTagType() == HtmlTag.Type.PRE) { // parse the text of the comment parseCommentText(bug, comment, tokenizer); comment = null; state = ParserState.DESC_START; continue; } } // we have found the description of the bug if ((state == ParserState.ATT_NAME || state == ParserState.START) && token.getType() == Token.TAG) { HtmlTag tag = (HtmlTag) token.getValue(); if (tag.getTagType() == HtmlTag.Type.PRE) { // parse the description for the bug parseDescription(bug, tokenizer); state = ParserState.DESC_START; continue; } } //parse hidden fields if((state == ParserState.ATT_NAME || state == ParserState.START) && token.getType() == Token.TAG) { HtmlTag tag = (HtmlTag)token.getValue(); if(tag.getTagType() == HtmlTag.Type.INPUT && tag.getAttribute("type") != null &&"hidden".equalsIgnoreCase(tag.getAttribute("type").trim())) { Attribute a = new Attribute(tag.getAttribute("name")); a.setParameterName(tag.getAttribute("name")); a.setValue(tag.getAttribute("value")); a.setHidden(true); bug.addAttribute(a); continue; } } } // if we are to check the body, make sure that there wasn't a bad login if(checkBody) { String b = body.toString(); if(b.indexOf("login") != -1 || ((b.indexOf("invalid") != -1 || b.indexOf("not valid") != -1) && b.indexOf("password") != -1) || b.indexOf("check e-mail") != -1) possibleBadLogin = true; // we possibly have a bad login } // fixed bug 59 // if there is no summary or created date, we expect that // the bug doesn't exist, so set it to null // if the bug seems like it doesn't exist, and we suspect a login problem, assume that there was a login problem if(bug.getCreated() == null && bug.getAttributes().isEmpty()) { if (possibleBadLogin) { throw new LoginException("Bugzilla login information incorrect"); } else { return null; } } // we are done...return the bug return bug; } /** * Parse the operations that are allowed on the bug (Assign, Re-open, fix) * @param bug The bug to add the operations to * @param tokenizer The stream tokenizer for the bug * @param tag The last tag that we were on */ private static void parseOperations(BugReport bug, HtmlStreamTokenizer tokenizer, HtmlTag tag, boolean is218) throws ParseException, IOException { String knobName = tag.getAttribute("value"); boolean isChecked = false; if(tag.getAttribute("checked") != null && tag.getAttribute("checked").equals("checked")) isChecked = true; StringBuffer sb = new StringBuffer(); Token lastTag = null; for (Token token = tokenizer.nextToken(); token.getType() != Token.EOF; token = tokenizer.nextToken()) { if(token.getType() == Token.TAG) { tag = (HtmlTag)token.getValue(); if(!(tag.getTagType() == HtmlTag.Type.A || tag.getTagType() == HtmlTag.Type.B || tag.getTagType() == HtmlTag.Type.STRONG || tag.getTagType() == HtmlTag.Type.LABEL)) { lastTag = token; break; } else{ if(is218 && tag.getTagType() == HtmlTag.Type.LABEL){ continue; } else if(tag.getTagType() == HtmlTag.Type.A || tag.getTagType() == HtmlTag.Type.B || tag.getTagType() == HtmlTag.Type.STRONG){ sb.append(tag.toString().trim() + " "); } else { break; } } } else if(token.getType() == Token.TEXT && !token.toString().trim().equals("\n")) sb.append(token.toString().trim() + " "); } String displayName = HtmlStreamTokenizer.unescape(sb).toString(); Operation o = new Operation(knobName, displayName); o.setChecked(isChecked); if(lastTag != null) { tag = (HtmlTag)lastTag.getValue(); if(tag.getTagType() != HtmlTag.Type.SELECT) { tokenizer.pushback(lastTag); if(tag.getTagType() == HtmlTag.Type.INPUT && !("radio".equalsIgnoreCase(tag.getAttribute("type")) && "knob".equalsIgnoreCase(tag.getAttribute("name")))) { o.setInputName(((HtmlTag)lastTag.getValue()).getAttribute("name")); o.setInputValue(((HtmlTag)lastTag.getValue()).getAttribute("value")); } } else { Token token = tokenizer.nextToken(); // parse the options tag = (HtmlTag)token.getValue(); o.setUpOptions(((HtmlTag)lastTag.getValue()).getAttribute("name")); while ( token.getType() != Token.EOF) { if (token.getType() == Token.TAG) { tag = (HtmlTag) token.getValue(); if (tag.getTagType() == HtmlTag.Type.SELECT && tag.isEndTag()) break; if (tag.getTagType() == HtmlTag.Type.OPTION && !tag.isEndTag()) { String optionName = tag.getAttribute("value"); StringBuffer optionText = new StringBuffer(); for (token = tokenizer.nextToken(); token.getType() == Token.TEXT; token = tokenizer.nextToken()) { if (optionText.length() > 0) { optionText.append(' '); } optionText.append((StringBuffer) token.getValue()); } o.addOption(optionText.toString(), optionName); } else { token = tokenizer.nextToken(); } } else { token = tokenizer.nextToken(); } } } } bug.addOperation(o); } /** * Enum class for describing current state of Bugzilla report parser. */ private static class ParserState { /** An instance of the start state */ protected static final ParserState START = new ParserState("start"); /** An instance of the state when the parser found an attribute name */ protected static final ParserState ATT_NAME = new ParserState("att_name"); /** An instance of the state when the parser found an attribute value */ protected static final ParserState ATT_VALUE = new ParserState("att_value"); /** An instance of the state when the parser found a description */ protected static final ParserState DESC_START = new ParserState("desc_start"); /** An instance of the state when the parser found a description value */ protected static final ParserState DESC_VALUE = new ParserState("desc_value"); /** State's human-readable name */ private String name; /** * Constructor * @param description - The states human readable name */ private ParserState(String description) { this.name = description; } @Override public String toString() { return name; } } }
package org.junit.platform.commons.support; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.platform.commons.support.PreconditionAssertions.assertPreconditionViolationException; import static org.junit.platform.commons.support.PreconditionAssertions.assertPreconditionViolationExceptionForString; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.net.URI; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; import org.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestFactory; import org.junit.platform.commons.util.PreconditionViolationException; import org.junit.platform.commons.util.ReflectionUtils; /** * @since 1.0 */ class ReflectionSupportTests { private static final Predicate<Class<?>> allTypes = type -> true; private static final Predicate<String> allNames = name -> true; private static final Predicate<Method> allMethods = name -> true; private static final Predicate<Field> allFields = name -> true; static final String staticField = "static"; final String instanceField = "instance"; @Test @SuppressWarnings("deprecation") void loadClassDelegates() { assertEquals(ReflectionUtils.loadClass("-"), ReflectionSupport.loadClass("-")); assertEquals(ReflectionUtils.loadClass("A"), ReflectionSupport.loadClass("A")); assertEquals(ReflectionUtils.loadClass("java.io.Bits"), ReflectionSupport.loadClass("java.io.Bits")); } @Test @SuppressWarnings("deprecation") void loadClassPreconditions() { assertPreconditionViolationExceptionForString("Class name", () -> ReflectionSupport.loadClass(null)); assertPreconditionViolationExceptionForString("Class name", () -> ReflectionSupport.loadClass("")); } @Test void tryToLoadClassDelegates() { assertEquals(ReflectionUtils.tryToLoadClass("-").toOptional(), ReflectionSupport.tryToLoadClass("-").toOptional()); assertEquals(ReflectionUtils.tryToLoadClass("A").toOptional(), ReflectionSupport.tryToLoadClass("A").toOptional()); assertEquals(ReflectionUtils.tryToLoadClass("java.io.Bits"), ReflectionSupport.tryToLoadClass("java.io.Bits")); } @Test void tryToLoadClassPreconditions() { assertPreconditionViolationExceptionForString("Class name", () -> ReflectionSupport.tryToLoadClass(null)); assertPreconditionViolationExceptionForString("Class name", () -> ReflectionSupport.tryToLoadClass("")); } @TestFactory List<DynamicTest> findAllClassesInClasspathRootDelegates() throws Throwable { List<DynamicTest> tests = new ArrayList<>(); List<Path> paths = new ArrayList<>(); paths.add(Path.of(".").toRealPath()); paths.addAll(ReflectionUtils.getAllClasspathRootDirectories()); for (Path path : paths) { URI root = path.toUri(); String displayName = root.getPath(); if (displayName.length() > 42) { displayName = "..." + displayName.substring(displayName.length() - 42); } tests.add(DynamicTest.dynamicTest(displayName, () -> assertEquals(ReflectionUtils.findAllClassesInClasspathRoot(root, allTypes, allNames), ReflectionSupport.findAllClassesInClasspathRoot(root, allTypes, allNames)))); } return tests; } @Test void findAllClassesInClasspathRootPreconditions() { URI path = Path.of(".").toUri(); assertPreconditionViolationException("root", () -> ReflectionSupport.findAllClassesInClasspathRoot(null, allTypes, allNames)); assertPreconditionViolationException("class predicate", () -> ReflectionSupport.findAllClassesInClasspathRoot(path, null, allNames)); assertPreconditionViolationException("name predicate", () -> ReflectionSupport.findAllClassesInClasspathRoot(path, allTypes, null)); } @Test void findAllClassesInPackageDelegates() { assertThrows(PreconditionViolationException.class, () -> ReflectionUtils.findAllClassesInPackage("void.return.null", allTypes, allNames)); assertThrows(PreconditionViolationException.class, () -> ReflectionSupport.findAllClassesInPackage("void.return.null", allTypes, allNames)); assertNotEquals(0, ReflectionSupport.findAllClassesInPackage("org.junit", allTypes, allNames).size()); assertEquals(ReflectionUtils.findAllClassesInPackage("org.junit", allTypes, allNames), ReflectionSupport.findAllClassesInPackage("org.junit", allTypes, allNames)); } @Test void findAllClassesInPackagePreconditions() { assertPreconditionViolationException("package name", () -> ReflectionSupport.findAllClassesInPackage(null, allTypes, allNames)); assertPreconditionViolationException("class predicate", () -> ReflectionSupport.findAllClassesInPackage("org.junit", null, allNames)); assertPreconditionViolationException("name predicate", () -> ReflectionSupport.findAllClassesInPackage("org.junit", allTypes, null)); } @Test void findAllClassesInModuleDelegates() { assertEquals(ReflectionUtils.findAllClassesInModule("org.junit.platform.commons", allTypes, allNames), ReflectionSupport.findAllClassesInModule("org.junit.platform.commons", allTypes, allNames)); } @Test void findAllClassesInModulePreconditions() { PreconditionViolationException exception = assertThrows(PreconditionViolationException.class, () -> ReflectionSupport.findAllClassesInModule(null, allTypes, allNames)); assertEquals("Module name must not be null or empty", exception.getMessage()); assertPreconditionViolationException("class predicate", () -> ReflectionSupport.findAllClassesInModule("org.junit.platform.commons", null, allNames)); assertPreconditionViolationException("name predicate", () -> ReflectionSupport.findAllClassesInModule("org.junit.platform.commons", allTypes, null)); } @Test void newInstanceDelegates() { assertEquals(ReflectionUtils.newInstance(String.class, "foo"), ReflectionSupport.newInstance(String.class, "foo")); } @Test void newInstancePreconditions() { assertPreconditionViolationException("Class", () -> ReflectionSupport.newInstance(null)); assertPreconditionViolationException("Argument array", () -> ReflectionSupport.newInstance(String.class, (Object[]) null)); assertPreconditionViolationException("Individual arguments", () -> ReflectionSupport.newInstance(String.class, new Object[] { null })); } @Test void findFieldsDelegates() { assertEquals( ReflectionUtils.findFields(ReflectionSupportTests.class, allFields, ReflectionUtils.HierarchyTraversalMode.BOTTOM_UP), ReflectionSupport.findFields(ReflectionSupportTests.class, allFields, HierarchyTraversalMode.BOTTOM_UP)); assertEquals( ReflectionUtils.findFields(ReflectionSupportTests.class, allFields, ReflectionUtils.HierarchyTraversalMode.TOP_DOWN), ReflectionSupport.findFields(ReflectionSupportTests.class, allFields, HierarchyTraversalMode.TOP_DOWN)); } @Test void findFieldsPreconditions() { assertPreconditionViolationException("Class", () -> ReflectionSupport.findFields(null, allFields, HierarchyTraversalMode.BOTTOM_UP)); assertPreconditionViolationException("Class", () -> ReflectionSupport.findFields(null, allFields, HierarchyTraversalMode.TOP_DOWN)); assertPreconditionViolationException("Predicate", () -> ReflectionSupport.findFields(ReflectionSupportTests.class, null, HierarchyTraversalMode.BOTTOM_UP)); assertPreconditionViolationException("Predicate", () -> ReflectionSupport.findFields(ReflectionSupportTests.class, null, HierarchyTraversalMode.TOP_DOWN)); assertPreconditionViolationException("HierarchyTraversalMode", () -> ReflectionSupport.findFields(ReflectionSupportTests.class, allFields, null)); } @Test void tryToReadFieldValueDelegates() throws Exception { Field staticField = getClass().getDeclaredField("staticField"); assertEquals(ReflectionUtils.tryToReadFieldValue(staticField, null), ReflectionSupport.tryToReadFieldValue(staticField, null)); Field instanceField = getClass().getDeclaredField("instanceField"); assertEquals(ReflectionUtils.tryToReadFieldValue(instanceField, this), ReflectionSupport.tryToReadFieldValue(instanceField, this)); } @Test void tryToReadFieldValuePreconditions() throws Exception { assertPreconditionViolationException("Field", () -> ReflectionSupport.tryToReadFieldValue(null, this)); Field instanceField = getClass().getDeclaredField("instanceField"); Exception exception = assertThrows(PreconditionViolationException.class, () -> ReflectionSupport.tryToReadFieldValue(instanceField, null)); assertThat(exception) .hasMessageStartingWith("Cannot read non-static field") .hasMessageEndingWith("on a null instance."); } @Test void findMethodsDelegates() { assertEquals( ReflectionUtils.findMethods(ReflectionSupportTests.class, allMethods, ReflectionUtils.HierarchyTraversalMode.BOTTOM_UP), ReflectionSupport.findMethods(ReflectionSupportTests.class, allMethods, HierarchyTraversalMode.BOTTOM_UP)); assertEquals( ReflectionUtils.findMethods(ReflectionSupportTests.class, allMethods, ReflectionUtils.HierarchyTraversalMode.TOP_DOWN), ReflectionSupport.findMethods(ReflectionSupportTests.class, allMethods, HierarchyTraversalMode.TOP_DOWN)); } @Test void findMethodsPreconditions() { assertPreconditionViolationException("Class", () -> ReflectionSupport.findMethods(null, allMethods, HierarchyTraversalMode.BOTTOM_UP)); assertPreconditionViolationException("Class", () -> ReflectionSupport.findMethods(null, allMethods, HierarchyTraversalMode.TOP_DOWN)); assertPreconditionViolationException("Predicate", () -> ReflectionSupport.findMethods(ReflectionSupportTests.class, null, HierarchyTraversalMode.BOTTOM_UP)); assertPreconditionViolationException("Predicate", () -> ReflectionSupport.findMethods(ReflectionSupportTests.class, null, HierarchyTraversalMode.TOP_DOWN)); assertPreconditionViolationException("HierarchyTraversalMode", () -> ReflectionSupport.findMethods(ReflectionSupportTests.class, allMethods, null)); } }
package org.motechproject.mds.web.controller; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.type.TypeReference; import org.motechproject.commons.api.CsvConverter; import org.motechproject.mds.dto.FieldInstanceDto; import org.motechproject.mds.dto.TypeDto; import org.motechproject.mds.ex.EntityNotFoundException; import org.motechproject.mds.filter.Filter; import org.motechproject.mds.query.QueryParams; import org.motechproject.mds.service.EntityService; import org.motechproject.mds.service.InstanceService; import org.motechproject.mds.util.Order; import org.motechproject.mds.web.domain.EntityRecord; import org.motechproject.mds.web.domain.FieldRecord; import org.motechproject.mds.web.domain.GridSettings; import org.motechproject.mds.web.domain.HistoryRecord; import org.motechproject.mds.web.domain.Records; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.apache.commons.lang.CharEncoding.UTF_8; import static org.motechproject.mds.util.Constants.Roles; /** * The <code>InstanceController</code> is the Spring Framework Controller used by view layer for * managing entity instances. * * @see org.motechproject.mds.dto.FieldDto * @see org.motechproject.mds.dto.EntityDto */ @Controller public class InstanceController extends MdsController { @Autowired private EntityService entityService; @Autowired private InstanceService instanceService; private ObjectMapper objectMapper = new ObjectMapper(); @RequestMapping(value = "/instances", method = RequestMethod.POST) @PreAuthorize(Roles.HAS_DATA_ACCESS) @ResponseStatus(HttpStatus.OK) public void saveInstance(@RequestBody EntityRecord record) { instanceService.saveInstance(decodeBlobFiles(record)); } @RequestMapping(value = "/instances/{instanceId}", method = RequestMethod.POST) @PreAuthorize(Roles.HAS_DATA_ACCESS) @ResponseStatus(HttpStatus.OK) public void updateInstance(@RequestBody EntityRecord record) { instanceService.saveInstance(decodeBlobFiles(record)); } @RequestMapping(value = "/instances/deleteBlob/{entityId}/{instanceId}/{fieldId}", method = RequestMethod.GET) @PreAuthorize(Roles.HAS_DATA_ACCESS) @ResponseStatus(HttpStatus.OK) public void deleteBlobContent(@PathVariable Long entityId, @PathVariable Long instanceId, @PathVariable Long fieldId) { EntityRecord record = instanceService.getEntityInstance(entityId, instanceId); instanceService.saveInstance(record, fieldId); } @RequestMapping(value = "/instances/{entityId}/new") @PreAuthorize(Roles.HAS_DATA_ACCESS) @ResponseBody public EntityRecord newInstance(@PathVariable Long entityId) { return instanceService.newInstance(entityId); } @RequestMapping(value = "/instances/{entityId}/{instanceId}/fields", method = RequestMethod.GET) @PreAuthorize(Roles.HAS_DATA_ACCESS) @ResponseBody public List<FieldInstanceDto> getInstanceFields(@PathVariable Long entityId, @PathVariable Long instanceId) { return instanceService.getInstanceFields(entityId, instanceId); } @RequestMapping(value = "/instances/{entityId}/{instanceId}/{fieldName}", method = RequestMethod.GET) @PreAuthorize(Roles.HAS_DATA_ACCESS) @ResponseBody public void getBlobField(@PathVariable Long entityId, @PathVariable Long instanceId, @PathVariable String fieldName, HttpServletResponse response) throws IOException { byte[] content = ArrayUtils.toPrimitive((Byte[]) instanceService.getInstanceField(entityId, instanceId, fieldName)); try (OutputStream outputStream = response.getOutputStream()) { response.setHeader("Accept-Ranges", "bytes"); if (content.length == 0) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); } else { response.setStatus(HttpServletResponse.SC_OK); } outputStream.write(content); } } @RequestMapping(value = "/instances/{entityId}/delete/{instanceId}", method = RequestMethod.DELETE) @PreAuthorize(Roles.HAS_DATA_ACCESS) @ResponseStatus(HttpStatus.OK) public void deleteInstance(@PathVariable Long entityId, @PathVariable Long instanceId) { instanceService.deleteInstance(entityId, instanceId); } @RequestMapping(value = "/instances/{entityId}/revertFromTrash/{instanceId}", method = RequestMethod.GET) @PreAuthorize(Roles.HAS_DATA_ACCESS) @ResponseStatus(HttpStatus.OK) public void revertInstanceFromTrash(@PathVariable Long entityId, @PathVariable Long instanceId) { instanceService.revertInstanceFromTrash(entityId, instanceId); } @RequestMapping(value = "/instances/{entityId}/{instanceId}/history", method = RequestMethod.GET) @PreAuthorize(Roles.HAS_DATA_ACCESS) @ResponseBody public Records<HistoryRecord> getHistory(@PathVariable Long entityId, @PathVariable Long instanceId, GridSettings settings) { Order order = null; if (settings.getSortColumn() != null && !settings.getSortColumn().isEmpty()) { order = new Order(settings.getSortColumn(), settings.getSortDirection()); } if (settings.getPage() == null) { settings.setPage(1); settings.setRows(10); } QueryParams queryParams = new QueryParams(settings.getPage(), settings.getRows(), order); List<HistoryRecord> historyRecordsList = instanceService.getInstanceHistory(entityId, instanceId, queryParams); long recordCount = instanceService.countHistoryRecords(entityId, instanceId); int rowCount = (int) Math.ceil(recordCount / (double) settings.getRows()); return new Records<>(settings.getPage(), rowCount, (int) recordCount, historyRecordsList); } @RequestMapping(value = "/instances/{entityId}/{instanceId}/previousVersion/{historyId}", method = RequestMethod.GET) @PreAuthorize(Roles.HAS_DATA_ACCESS) @ResponseBody public HistoryRecord getPreviousInstance(@PathVariable Long entityId, @PathVariable Long instanceId, @PathVariable Long historyId) { HistoryRecord historyRecord = instanceService.getHistoryRecord(entityId, instanceId, historyId); if (historyRecord == null) { throw new EntityNotFoundException(); } return historyRecord; } @RequestMapping(value = "/instances/{entityId}/{instanceId}/revert/{historyId}", method = RequestMethod.GET) @PreAuthorize(Roles.HAS_DATA_ACCESS) @ResponseBody public void revertPreviousVersion(@PathVariable Long entityId, @PathVariable Long instanceId, @PathVariable Long historyId) { instanceService.revertPreviousVersion(entityId, instanceId, historyId); } @RequestMapping(value = "/instances/{entityId}/instance/{instanceId}", method = RequestMethod.GET) @PreAuthorize(Roles.HAS_DATA_ACCESS) @ResponseBody public EntityRecord getInstance(@PathVariable Long entityId, @PathVariable Long instanceId) { return instanceService.getEntityInstance(entityId, instanceId); } @RequestMapping(value = "/entities/{entityId}/trash", method = RequestMethod.GET) @PreAuthorize(Roles.HAS_DATA_ACCESS) @ResponseBody public Records<EntityRecord> getTrash(@PathVariable Long entityId, GridSettings settings) { Order order = null; if (settings.getSortColumn() != null && !settings.getSortColumn().isEmpty()) { order = new Order(settings.getSortColumn(), settings.getSortDirection()); } QueryParams queryParams = new QueryParams(settings.getPage(), settings.getRows(), order); List<EntityRecord> trashRecordsList = instanceService.getTrashRecords(entityId, queryParams); long recordCount = instanceService.countTrashRecords(entityId); int rowCount = (int) Math.ceil(recordCount / (double) settings.getRows()); return new Records<>(settings.getPage(), rowCount, (int) recordCount, trashRecordsList); } @RequestMapping(value = "/entities/{entityId}/trash/{instanceId}", method = RequestMethod.GET) @PreAuthorize(Roles.HAS_DATA_ACCESS) @ResponseBody public EntityRecord getSingleTrashInstance(@PathVariable Long entityId, @PathVariable Long instanceId) { return instanceService.getSingleTrashRecord(entityId, instanceId); } @RequestMapping(value = "/entities/{entityId}/exportInstances", method = RequestMethod.GET) @PreAuthorize(Roles.HAS_DATA_ACCESS) public void exportEntityInstances(@PathVariable Long entityId, HttpServletResponse response) throws IOException { if (null == entityService.getEntity(entityId)) { throw new EntityNotFoundException(); } String fileName = "Entity_" + entityId + "_instances"; response.setContentType("text/csv"); response.setCharacterEncoding(UTF_8); response.setHeader( "Content-Disposition", "attachment; filename=" + fileName + ".csv"); response.getWriter().write(CsvConverter.convertToCSV(prepareForCsvConversion( instanceService.getEntityRecords(entityId)))); } @RequestMapping(value = "/entities/{entityId}/instances", method = RequestMethod.POST) @PreAuthorize(Roles.HAS_DATA_ACCESS) @ResponseBody public Records<?> getInstances(@PathVariable Long entityId, GridSettings settings) throws IOException { Order order = null; if (!settings.getSortColumn().isEmpty()) { order = new Order(settings.getSortColumn(), settings.getSortDirection()); } QueryParams queryParams = new QueryParams(settings.getPage(), settings.getRows(), order); String lookup = settings.getLookup(); String filterStr = settings.getFilter(); List<EntityRecord> entityRecords; long recordCount; if (StringUtils.isNotBlank(lookup)) { entityRecords = instanceService.getEntityRecordsFromLookup(entityId, lookup, getFields(settings), queryParams); recordCount = instanceService.countRecordsByLookup(entityId, lookup, getFields(settings)); } else if (filterSet(filterStr)) { Filter filter = objectMapper.readValue(filterStr, Filter.class); entityRecords = instanceService.getEntityRecordsWithFilter(entityId, filter, queryParams); recordCount = instanceService.countRecordsWithFilter(entityId, filter); } else { entityRecords = instanceService.getEntityRecords(entityId, queryParams); recordCount = instanceService.countRecords(entityId); } int rowCount = (int) Math.ceil(recordCount / (double) settings.getRows()); return new Records<>(settings.getPage(), rowCount, (int) recordCount, entityRecords); } private List<List<String>> prepareForCsvConversion(List<EntityRecord> entityList) { List<List<String>> list = new ArrayList<>(); if (entityList.size() != 0) { EntityRecord entity = entityList.get(0); List<String> fieldNames = new ArrayList<>(); for (FieldRecord fieldRecord : entity.getFields()) { fieldNames.add(fieldRecord.getDisplayName()); } list.add(fieldNames); } for (EntityRecord entityRecord : entityList) { List<String> fieldValues = new ArrayList<>(); for (FieldRecord fieldRecord : entityRecord.getFields()) { Object value = fieldRecord.getValue(); fieldValues.add(value == null ? "" : value.toString()); } list.add(fieldValues); } return list; } private Map<String, Object> getFields(GridSettings gridSettings) throws IOException { return objectMapper.readValue(gridSettings.getFields(), new TypeReference<HashMap>() { }); } private boolean filterSet(String filterStr) { return StringUtils.isNotBlank(filterStr) && !"{}".equals(filterStr); } private EntityRecord decodeBlobFiles(EntityRecord record) { for (FieldRecord field : record.getFields()) { if (TypeDto.BLOB.getTypeClass().equals(field.getType().getTypeClass())) { byte[] content = field.getValue() != null ? field.getValue().toString().getBytes() : ArrayUtils.EMPTY_BYTE_ARRAY; field.setValue(decodeBase64(content)); } } return record; } private Byte[] decodeBase64(byte[] content) { if (content == null || content.length == 0) { return null; } Base64 decoder = new Base64(); //We must remove "data:(content type);base64," prefix and then decode content int index = ArrayUtils.indexOf(content, (byte) ',') + 1; return ArrayUtils.toObject(decoder.decode(ArrayUtils.subarray(content, index, content.length))); } @Autowired public void setEntityService(EntityService entityService) { this.entityService = entityService; } @Autowired public void setInstanceService(InstanceService instanceService) { this.instanceService = instanceService; } }
package com.intellij.openapi.updateSettings.impl; import com.intellij.CommonBundle; import com.intellij.ide.IdeBundle; import com.intellij.ide.plugins.IdeaPluginDescriptor; import com.intellij.ide.plugins.PluginManagerConfigurable; import com.intellij.ide.plugins.PluginManagerCore; import com.intellij.ide.plugins.PluginManagerMain; import com.intellij.ide.plugins.newui.*; import com.intellij.notification.NotificationType; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.application.ex.ApplicationManagerEx; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.options.Configurable; import com.intellij.openapi.progress.PerformInBackgroundOption; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.Task; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.Divider; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.wm.impl.welcomeScreen.WelcomeFrame; import com.intellij.ui.OnePixelSplitter; import com.intellij.ui.components.labels.LinkListener; import com.intellij.ui.components.panels.OpaquePanel; import com.intellij.util.LineSeparator; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.JBDimension; import com.intellij.util.ui.JBUI; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.io.File; import java.io.IOException; import java.util.List; import java.util.*; /** * @author Alexander Lobas */ public class PluginUpdateDialog extends DialogWrapper { private final Collection<PluginDownloader> myDownloaders; private final MyPluginModel myPluginModel = new MyPluginModel() { @Override public void runRestartButton(@NotNull Component component) { doOKAction(); } }; private final PluginsGroupComponent myPluginsPanel; private final PluginsGroup myGroup; private final PluginDetailsPageComponent myDetailsPage; private final Action myIgnoreAction; public PluginUpdateDialog(@NotNull Collection<PluginDownloader> uploadedPlugins) { super(true); setTitle("Plugin Updates"); myDownloaders = uploadedPlugins; myIgnoreAction = new AbstractAction( IdeBundle.message(uploadedPlugins.size() == 1 ? "updates.ignore.update.button" : "updates.ignore.updates.button")) { @Override public void actionPerformed(ActionEvent e) { close(CANCEL_EXIT_CODE); ignorePlugins(ContainerUtil.map(myGroup.ui.plugins, component -> component.myUpdateDescriptor)); } }; myPluginModel.setTopController(new Configurable.TopComponentController() { @Override public void setLeftComponent(@Nullable Component component) { } @Override public void showProgress(boolean start) { } }); myPluginModel.setPluginUpdatesService(new PluginUpdatesService() { @Override public void finishUpdate(@NotNull IdeaPluginDescriptor descriptor) { updateButtons(); } @Override public void finishUpdate() { updateButtons(); } }); myDetailsPage = new PluginDetailsPageComponent(myPluginModel, emptyListener(), false) { @Override public void showProgress() { } }; myDetailsPage.setOnlyUpdateMode(); MultiSelectionEventHandler eventHandler = new MultiSelectionEventHandler(); myPluginsPanel = new PluginsGroupComponent(new PluginListLayout(), eventHandler, descriptor -> createListComponent(descriptor)); PluginManagerConfigurable.registerCopyProvider(myPluginsPanel); myPluginsPanel.setSelectionListener(__ -> { List<ListPluginComponent> selection = myPluginsPanel.getSelection(); int size = selection.size(); myDetailsPage.showPlugin(size == 1 ? selection.get(0) : null, size > 1); }); myGroup = new PluginsGroup("Plugin updates available"); for (PluginDownloader plugin : uploadedPlugins) { myGroup.descriptors.add(plugin.getDescriptor()); } myGroup.sortByName(); myPluginsPanel.addGroup(myGroup); setOKButtonText(false, false); setCancelButtonText(IdeBundle.message("updates.remind.later.button")); init(); JRootPane rootPane = getPeer().getRootPane(); if (rootPane != null) { rootPane.setPreferredSize(new JBDimension(800, 600)); } } private void updateButtons() { int count = myGroup.ui.plugins.size(); int restart = 0; int progress = 0; int updatedWithoutRestart = 0; for (ListPluginComponent plugin : myGroup.ui.plugins) { if (plugin.isRestartEnabled()) { restart++; } else if (plugin.underProgress()) { progress++; } else if (plugin.isUpdatedWithoutRestart()) { updatedWithoutRestart++; } } setOKButtonText(restart + progress > 0, updatedWithoutRestart == count); getCancelAction().setEnabled(restart + updatedWithoutRestart < count); myIgnoreAction.setEnabled(restart + progress + updatedWithoutRestart == 0); } private void setOKButtonText(boolean restart, boolean close) { if (close) { setOKButtonText("Close"); } else { String action = ApplicationManager.getApplication().isRestartCapable() ? "Restart" : "Shutdown"; setOKButtonText(restart ? action + " IDE" : "Update All and " + action); } } @Override protected void doOKAction() { super.doOKAction(); List<PluginDownloader> toDownloads = new ArrayList<>(); List<IdeaPluginDescriptor> toIgnore = new ArrayList<>(); int index = 0; boolean restart = false; for (PluginDownloader downloader : myDownloaders) { ListPluginComponent component = myGroup.ui.plugins.get(index++); if (component.isRestartEnabled() || component.underProgress()) { restart = true; } else if (!component.isUpdatedWithoutRestart()) { toDownloads.add(downloader); toIgnore.add(component.myUpdateDescriptor); } } boolean background = myPluginModel.toBackground(); if (toDownloads.size() != myDownloaders.size() || background) { if (!toIgnore.isEmpty()) { ignorePlugins(toIgnore); } if (!background && restart) { ApplicationManager.getApplication().invokeLater(() -> ApplicationManagerEx.getApplicationEx().restart(true)); } return; } new Task.Backgroundable(null, IdeBundle.message("update.notifications.title"), true, PerformInBackgroundOption.DEAF) { @Override public void run(@NotNull ProgressIndicator indicator) { final List<PluginDownloader> downloaders = UpdateInstaller.downloadPluginUpdates(toDownloads, indicator); if (!downloaders.isEmpty()) { ApplicationManager.getApplication().invokeLater(() -> { final PluginUpdateResult result = UpdateInstaller.installDownloadedPluginUpdates(downloaders, getContentPanel(), true); if (result.getPluginsInstalled().size() > 0) { if (result.getRestartRequired()) { if (WelcomeFrame.getInstance() == null) { PluginManagerMain.notifyPluginsUpdated(null); } else { PluginManagerConfigurable.shutdownOrRestartApp(); } } else { String message; if (result.getPluginsInstalled().size() == 1) { final IdeaPluginDescriptor installedPlugin = result.getPluginsInstalled().get(0); message = "Updated " + installedPlugin.getName() + " plugin to version " + installedPlugin.getVersion(); } else { message = "Updated " + result.getPluginsInstalled() + " plugins"; } UpdateChecker.NOTIFICATIONS.createNotification(message, NotificationType.INFORMATION).notify(myProject); } } }); } } }.queue(); } @Override public void doCancelAction() { close(CANCEL_EXIT_CODE); if (myPluginModel.toBackground()) { return; } for (ListPluginComponent plugin : myGroup.ui.plugins) { if (plugin.isRestartEnabled()) { ApplicationManager.getApplication().invokeLater(() -> PluginManagerConfigurable.shutdownOrRestartApp()); return; } } } @Override protected Action @NotNull [] createLeftSideActions() { return ContainerUtil.ar(myIgnoreAction); } @NotNull @Override protected DialogStyle getStyle() { return DialogStyle.COMPACT; } @Override protected String getDimensionServiceKey() { return "#com.intellij.openapi.updateSettings.impl.PluginUpdateInfoDialog"; } @NotNull private ListPluginComponent createListComponent(IdeaPluginDescriptor updateDescriptor) { IdeaPluginDescriptor descriptor = PluginManagerCore.getPlugin(updateDescriptor.getPluginId()); assert descriptor != null; ListPluginComponent component = new ListPluginComponent(myPluginModel, descriptor, emptyListener(), false) { @Override public void updateErrors() { } @Override public void showProgress() { super.showProgress(); updateButtons(); } }; component.setOnlyUpdateMode(updateDescriptor); return component; } @Nullable @Override protected JComponent createCenterPanel() { OnePixelSplitter splitter = new OnePixelSplitter(false, 0.45f) { @Override protected Divider createDivider() { Divider divider = super.createDivider(); divider.setBackground(PluginManagerConfigurable.SEARCH_FIELD_BORDER_COLOR); return divider; } }; JPanel leftPanel = new JPanel(new BorderLayout()); leftPanel.add(PluginManagerConfigurable.createScrollPane(myPluginsPanel, true)); OpaquePanel titlePanel = new OpaquePanel(new BorderLayout(), PluginManagerConfigurable.MAIN_BG_COLOR); titlePanel.setBorder(JBUI.Borders.empty(6, 10)); leftPanel.add(titlePanel, BorderLayout.SOUTH); JLabel titleComponent = new JLabel("Plugins can be updated later in " + CommonBundle.settingsTitle() + " | Plugins"); titleComponent.setForeground(PluginsGroupComponent.SECTION_HEADER_FOREGROUND); titlePanel.add(titleComponent); ((JComponent)myGroup.ui.panel).setBorder(JBUI.Borders.empty(6, 10)); splitter.setFirstComponent(leftPanel); splitter.setSecondComponent(myDetailsPage); return splitter; } private static Set<String> myIgnoredPluginsWithVersions; @NotNull private static File getDisabledUpdateFile() { return new File(PathManager.getConfigPath(), "plugin_disabled_updates.txt"); } @NotNull private static Set<String> getIgnoredPlugins() { if (myIgnoredPluginsWithVersions == null) { myIgnoredPluginsWithVersions = new HashSet<>(); if (!ApplicationManager.getApplication().isUnitTestMode()) { try { File file = getDisabledUpdateFile(); if (file.isFile()) { myIgnoredPluginsWithVersions.addAll(FileUtil.loadLines(file)); } } catch (IOException e) { Logger.getInstance(UpdateChecker.class).error(e); } } } return myIgnoredPluginsWithVersions; } static void ignorePlugins(@NotNull List<IdeaPluginDescriptor> descriptors) { Set<String> ignoredPlugins = getIgnoredPlugins(); for (IdeaPluginDescriptor descriptor : descriptors) { ignoredPlugins.add(getIdVersionValue(descriptor)); } try { FileUtil .writeToFile(getDisabledUpdateFile(), StringUtil.join(ignoredPlugins, LineSeparator.getSystemLineSeparator().getSeparatorString())); } catch (IOException e) { Logger.getInstance(UpdateChecker.class).error(e); } } public static boolean isIgnored(@NotNull IdeaPluginDescriptor descriptor) { Set<String> plugins = getIgnoredPlugins(); if (plugins.isEmpty()) { return false; } return plugins.contains(getIdVersionValue(descriptor)); } @NotNull private static String getIdVersionValue(@NotNull IdeaPluginDescriptor descriptor) { return descriptor.getPluginId().getIdString() + "+" + descriptor.getVersion(); } @NotNull private static <T> LinkListener<T> emptyListener() { return (__, ___) -> { }; } }
package com.intellij.openapi.vcs.changes.shelf; import com.intellij.diff.DiffContentFactoryEx; import com.intellij.diff.chains.DiffRequestProducerException; import com.intellij.diff.impl.CacheDiffRequestProcessor; import com.intellij.diff.requests.DiffRequest; import com.intellij.diff.requests.SimpleDiffRequest; import com.intellij.icons.AllIcons; import com.intellij.ide.DataManager; import com.intellij.ide.DeleteProvider; import com.intellij.ide.actions.EditSourceAction; import com.intellij.ide.dnd.*; import com.intellij.ide.dnd.aware.DnDAwareTree; import com.intellij.notification.Notification; import com.intellij.notification.NotificationAction; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.util.BackgroundTaskUtil; import com.intellij.openapi.project.DumbAwareRunnable; import com.intellij.openapi.project.Project; import com.intellij.openapi.startup.StartupManager; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.*; import com.intellij.openapi.vcs.changes.Change; import com.intellij.openapi.vcs.changes.DiffPreviewUpdateProcessor; import com.intellij.openapi.vcs.changes.DnDActivateOnHoldTargetContent; import com.intellij.openapi.vcs.changes.PreviewDiffSplitterComponent; import com.intellij.openapi.vcs.changes.actions.ShowDiffPreviewAction; import com.intellij.openapi.vcs.changes.patch.tool.PatchDiffRequest; import com.intellij.openapi.vcs.changes.ui.*; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.wm.ToolWindow; import com.intellij.openapi.wm.ToolWindowManager; import com.intellij.pom.Navigatable; import com.intellij.pom.NavigatableAdapter; import com.intellij.ui.*; import com.intellij.util.IconUtil; import com.intellij.util.IconUtil.IconSizeWrapper; import com.intellij.util.PathUtil; import com.intellij.util.messages.MessageBus; import com.intellij.util.text.DateFormatUtil; import com.intellij.util.ui.GraphicsUtil; import com.intellij.util.ui.tree.TreeUtil; import com.intellij.util.ui.update.MergingUpdateQueue; import com.intellij.util.ui.update.Update; import com.intellij.vcsUtil.VcsUtil; import one.util.streamex.StreamEx; import org.jetbrains.annotations.CalledInAwt; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.event.CellEditorListener; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.tree.*; import java.awt.*; import java.awt.event.MouseEvent; import java.beans.PropertyChangeListener; import java.io.IOException; import java.util.List; import java.util.*; import java.util.function.Predicate; import java.util.stream.Collectors; import static com.intellij.icons.AllIcons.Vcs.Patch_applied; import static com.intellij.openapi.actionSystem.Anchor.AFTER; import static com.intellij.openapi.vcs.changes.shelf.DiffShelvedChangesActionProvider.createAppliedTextPatch; import static com.intellij.openapi.vcs.changes.ui.ChangesGroupingSupport.REPOSITORY_GROUPING; import static com.intellij.util.FontUtil.spaceAndThinSpace; import static com.intellij.util.ObjectUtils.assertNotNull; import static com.intellij.util.containers.ContainerUtil.*; import static com.intellij.util.containers.UtilKt.isEmpty; import static java.util.Comparator.comparing; import static java.util.Objects.requireNonNull; public class ShelvedChangesViewManager implements Disposable { private static final Logger LOG = Logger.getInstance(ShelvedChangesViewManager.class); @NonNls static final String SHELF_CONTEXT_MENU = "Vcs.Shelf.ContextMenu"; private static final String SHELVE_PREVIEW_SPLITTER_PROPORTION = "ShelvedChangesViewManager.DETAILS_SPLITTER_PROPORTION"; private final ChangesViewContentManager myContentManager; private final ShelveChangesManager myShelveChangesManager; private final Project myProject; final ShelfTree myTree; @NotNull private final PropertyChangeListener myGroupingChangeListener; private MyShelfContent myContent = null; final DeleteProvider myDeleteProvider = new MyShelveDeleteProvider(); private final MergingUpdateQueue myUpdateQueue; private final VcsConfiguration myVcsConfiguration; private volatile List<ShelvedChangeList> myLoadedLists = emptyList(); private final List<Runnable> myPostUpdateEdtActivity = new ArrayList<>(); public static final DataKey<List<ShelvedChangeList>> SHELVED_CHANGELIST_KEY = DataKey.create("ShelveChangesManager.ShelvedChangeListData"); public static final DataKey<List<ShelvedChangeList>> SHELVED_RECYCLED_CHANGELIST_KEY = DataKey.create("ShelveChangesManager.ShelvedRecycledChangeListData"); public static final DataKey<List<ShelvedChangeList>> SHELVED_DELETED_CHANGELIST_KEY = DataKey.create("ShelveChangesManager.ShelvedDeletedChangeListData"); public static final DataKey<List<ShelvedChange>> SHELVED_CHANGE_KEY = DataKey.create("ShelveChangesManager.ShelvedChange"); public static final DataKey<List<ShelvedBinaryFile>> SHELVED_BINARY_FILE_KEY = DataKey.create("ShelveChangesManager.ShelvedBinaryFile"); private PreviewDiffSplitterComponent mySplitterComponent; public static ShelvedChangesViewManager getInstance(Project project) { return project.getComponent(ShelvedChangesViewManager.class); } public ShelvedChangesViewManager(Project project, ChangesViewContentManager contentManager, ShelveChangesManager shelveChangesManager, final MessageBus bus, StartupManager startupManager) { myProject = project; myContentManager = contentManager; myShelveChangesManager = shelveChangesManager; myUpdateQueue = new MergingUpdateQueue("Update Shelf Content", 200, true, null, myProject, null, true); myVcsConfiguration = VcsConfiguration.getInstance(myProject); bus.connect().subscribe(ShelveChangesManager.SHELF_TOPIC, new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { myUpdateQueue.queue(new MyContentUpdater()); } }); myTree = new ShelfTree(myProject); myTree.setEditable(true); myTree.setDragEnabled(true); myTree.getGroupingSupport().setGroupingKeysOrSkip(myShelveChangesManager.getGrouping()); myGroupingChangeListener = e -> { myShelveChangesManager.setGrouping(myTree.getGroupingSupport().getGroupingKeys()); myTree.rebuildTree(); }; myTree.addGroupingChangeListener(myGroupingChangeListener); DefaultTreeCellEditor treeCellEditor = new DefaultTreeCellEditor(myTree, null) { @Override public boolean isCellEditable(EventObject event) { return !(event instanceof MouseEvent) && super.isCellEditable(event); } }; myTree.setCellEditor(treeCellEditor); treeCellEditor.addCellEditorListener(new CellEditorListener() { @Override public void editingStopped(ChangeEvent e) { DefaultMutableTreeNode node = (DefaultMutableTreeNode)myTree.getLastSelectedPathComponent(); if (node instanceof ShelvedListNode && e.getSource() instanceof TreeCellEditor) { String editorValue = ((TreeCellEditor)e.getSource()).getCellEditorValue().toString(); ShelvedChangeList shelvedChangeList = ((ShelvedListNode)node).getList(); ShelveChangesManager.getInstance(project).renameChangeList(shelvedChangeList, editorValue); } } @Override public void editingCanceled(ChangeEvent e) { } }); final AnAction showDiffAction = ActionManager.getInstance().getAction(IdeActions.ACTION_SHOW_DIFF_COMMON); showDiffAction.registerCustomShortcutSet(showDiffAction.getShortcutSet(), myTree); final EditSourceAction editSourceAction = new EditSourceAction(); editSourceAction.registerCustomShortcutSet(editSourceAction.getShortcutSet(), myTree); PopupHandler.installPopupHandler(myTree, "ShelvedChangesPopupMenu", SHELF_CONTEXT_MENU); myTree.addSelectionListener(() -> mySplitterComponent.updatePreview(false)); if (startupManager == null) { LOG.error("Couldn't start loading shelved changes"); return; } startupManager.registerPostStartupActivity((DumbAwareRunnable)() -> myUpdateQueue.queue(new MyContentUpdater())); } private boolean hasExactlySelectedChanges() { return !isEmpty(VcsTreeModelData.exactlySelected(myTree).userObjectsStream(ShelvedWrapper.class)); } @CalledInAwt void updateViewContent() { if (myShelveChangesManager.getAllLists().isEmpty()) { if (myContent != null) { myContentManager.removeContent(myContent); myContentManager.selectContent(ChangesViewContentManager.LOCAL_CHANGES); VcsNotifier.getInstance(myProject).hideAllNotificationsByType(ShelfNotification.class); } myContent = null; } else { if (myContent == null) { myTree.updateUI(); JPanel rootPanel = createRootPanel(); myContent = new MyShelfContent(rootPanel, VcsBundle.message("shelf.tab"), false); myContent.setCloseable(false); myContentManager.addContent(myContent); DnDSupport.createBuilder(myTree) .setImageProvider(this::createDraggedImage) .setBeanProvider(this::createDragStartBean) .setTargetChecker(myContent) .setDropHandler(myContent) .setDisposableParent(myContent) .install(); } myTree.rebuildTree(); } } private ToolWindow getVcsToolWindow() { return ToolWindowManager.getInstance(myProject).getToolWindow(ChangesViewContentManager.TOOLWINDOW_ID); } @NotNull private JPanel createRootPanel() { JScrollPane pane = ScrollPaneFactory.createScrollPane(myTree, SideBorder.LEFT); DefaultActionGroup actionGroup = new DefaultActionGroup(); actionGroup.addAll((ActionGroup)ActionManager.getInstance().getAction("ShelvedChangesToolbar")); actionGroup.add(new MyToggleDetailsAction(), new Constraints(AFTER, "ShelvedChanges.ShowHideDeleted")); MyShelvedPreviewProcessor changeProcessor = new MyShelvedPreviewProcessor(myProject); mySplitterComponent = new PreviewDiffSplitterComponent(pane, changeProcessor, SHELVE_PREVIEW_SPLITTER_PROPORTION, myVcsConfiguration.SHELVE_DETAILS_PREVIEW_SHOWN); ActionToolbar toolbar = ActionManager.getInstance().createActionToolbar("ShelvedChanges", actionGroup, false); JPanel rootPanel = new JPanel(new BorderLayout()); rootPanel.add(toolbar.getComponent(), BorderLayout.WEST); rootPanel.add(mySplitterComponent, BorderLayout.CENTER); DataManager.registerDataProvider(rootPanel, myTree); return rootPanel; } private class MyShelvedTreeModelBuilder extends TreeModelBuilder { private MyShelvedTreeModelBuilder() { super(ShelvedChangesViewManager.this.myProject, myTree.getGrouping()); } public void setShelvedLists(@NotNull List<? extends ShelvedChangeList> shelvedLists) { createShelvedListsWithChangesNode(shelvedLists, myRoot); } public void setDeletedShelvedLists(@NotNull List<? extends ShelvedChangeList> shelvedLists) { createShelvedListsWithChangesNode(shelvedLists, createTagNode("Recently Deleted")); } private void createShelvedListsWithChangesNode(@NotNull List<? extends ShelvedChangeList> shelvedLists, @NotNull MutableTreeNode parentNode) { shelvedLists.forEach(changeList -> { List<ShelvedWrapper> shelvedChanges = new ArrayList<>(); requireNonNull(changeList.getChanges()).stream().map(ShelvedWrapper::new).forEach(shelvedChanges::add); changeList.getBinaryFiles().stream().map(ShelvedWrapper::new).forEach(shelvedChanges::add); shelvedChanges.sort(comparing(s -> s.getChange(myProject), CHANGE_COMPARATOR)); ShelvedListNode shelvedListNode = new ShelvedListNode(changeList); myModel.insertNodeInto(shelvedListNode, parentNode, parentNode.getChildCount()); for (ShelvedWrapper shelved : shelvedChanges) { Change change = shelved.getChange(myProject); insertChangeNode(change, shelvedListNode, new ShelvedChangeNode(shelved, change.getOriginText(myProject))); } }); } } @CalledInAwt private void updateTreeModel() { myTree.setPaintBusy(true); BackgroundTaskUtil.executeOnPooledThread(myProject, () -> { List<ShelvedChangeList> lists = myShelveChangesManager.getAllLists(); lists.forEach(l -> l.loadChangesIfNeeded(myProject)); myLoadedLists = sorted(lists, ChangelistComparator.getInstance()); ApplicationManager.getApplication().invokeLater(() -> { myTree.setPaintBusy(false); updateViewContent(); myPostUpdateEdtActivity.forEach(Runnable::run); myPostUpdateEdtActivity.clear(); }, ModalityState.NON_MODAL, myProject.getDisposed()); }); } @CalledInAwt public void startEditing(@NotNull ShelvedChangeList shelvedChangeList) { runAfterUpdate(() -> { selectShelvedList(shelvedChangeList); myTree.startEditingAtPath(myTree.getLeadSelectionPath()); }); } static class ChangelistComparator implements Comparator<ShelvedChangeList> { private final static ChangelistComparator ourInstance = new ChangelistComparator(); public static ChangelistComparator getInstance() { return ourInstance; } @Override public int compare(ShelvedChangeList o1, ShelvedChangeList o2) { return o2.DATE.compareTo(o1.DATE); } } public void activateView(@Nullable final ShelvedChangeList list) { runAfterUpdate(() -> { if (myContent == null) return; if (list != null) { selectShelvedList(list); } myContentManager.setSelectedContent(myContent); ToolWindow window = getVcsToolWindow(); if (window != null && !window.isVisible()) { window.activate(null); } }); } private void runAfterUpdate(@NotNull Runnable postUpdateRunnable) { GuiUtils.invokeLaterIfNeeded(() -> { myUpdateQueue.cancelAllUpdates(); myPostUpdateEdtActivity.add(postUpdateRunnable); updateTreeModel(); }, ModalityState.NON_MODAL); } @Override public void dispose() { myUpdateQueue.cancelAllUpdates(); myTree.removeGroupingChangeListener(myGroupingChangeListener); } public void updateOnVcsMappingsChanged() { ApplicationManager.getApplication().invokeLater(() -> { ChangesGroupingSupport treeGroupingSupport = myTree.getGroupingSupport(); if (treeGroupingSupport.isAvailable(REPOSITORY_GROUPING) && treeGroupingSupport.get(REPOSITORY_GROUPING)) { myTree.rebuildTree(); } }, myProject.getDisposed()); } public void selectShelvedList(@NotNull ShelvedChangeList list) { DefaultMutableTreeNode treeNode = TreeUtil.findNodeWithObject((DefaultMutableTreeNode)myTree.getModel().getRoot(), list); if (treeNode == null) { LOG.warn(String.format("Shelved changeList %s not found", list.DESCRIPTION)); return; } TreeUtil.selectNode(myTree, treeNode); } private class ShelfTree extends ChangesTree { private ShelfTree(@NotNull Project project) { super(project, false, false, true); setKeepTreeState(true); } @Override public boolean isPathEditable(TreePath path) { return isEditable() && myTree.getSelectionCount() == 1 && path.getLastPathComponent() instanceof ShelvedListNode; } @NotNull @Override protected ChangesGroupingSupport installGroupingSupport() { return new ChangesGroupingSupport(myProject, this, false); } @Override public int getToggleClickCount() { return 2; } @Override protected void installDoubleClickHandler() { new DoubleClickListener() { @Override protected boolean onDoubleClick(MouseEvent e) { if (!hasExactlySelectedChanges()) return false; DiffShelvedChangesActionProvider.showShelvedChangesDiff(DataManager.getInstance().getDataContext(myTree)); return true; } }.installOn(this); } @Override public void rebuildTree() { MyShelvedTreeModelBuilder modelBuilder = new MyShelvedTreeModelBuilder(); List<ShelvedChangeList> changeLists = new ArrayList<>(myLoadedLists); modelBuilder .setShelvedLists(filter(changeLists, l -> !l.isDeleted() && (myShelveChangesManager.isShowRecycled() || !l.isRecycled()))); modelBuilder.setDeletedShelvedLists(filter(changeLists, ShelvedChangeList::isDeleted)); updateTreeModel(modelBuilder.build()); } @Nullable @Override public Object getData(@NotNull @NonNls String dataId) { if (SHELVED_CHANGELIST_KEY.is(dataId)) { return new ArrayList<>((Collection<? extends ShelvedChangeList>)getSelectedLists(l -> !l.isRecycled() && !l.isDeleted())); } else if (SHELVED_RECYCLED_CHANGELIST_KEY.is(dataId)) { return new ArrayList<>((Collection<? extends ShelvedChangeList>)getSelectedLists(l -> l.isRecycled() && !l.isDeleted())); } else if (SHELVED_DELETED_CHANGELIST_KEY.is(dataId)) { return new ArrayList<>((Collection<? extends ShelvedChangeList>)getSelectedLists(l -> l.isDeleted())); } else if (SHELVED_CHANGE_KEY.is(dataId)) { return StreamEx.of(VcsTreeModelData.selected(myTree).userObjectsStream(ShelvedWrapper.class)).map(s -> s.getShelvedChange()) .nonNull().toList(); } else if (SHELVED_BINARY_FILE_KEY.is(dataId)) { return StreamEx.of(VcsTreeModelData.selected(myTree).userObjectsStream(ShelvedWrapper.class)).map(s -> s.getBinaryFile()) .nonNull().toList(); } else if (VcsDataKeys.HAVE_SELECTED_CHANGES.is(dataId)) { return getSelectionCount() > 0; } else if (VcsDataKeys.CHANGES.is(dataId)) { List<ShelvedWrapper> shelvedChanges = VcsTreeModelData.selected(myTree).userObjects(ShelvedWrapper.class); if (!shelvedChanges.isEmpty()) { return map2Array(shelvedChanges, Change.class, s -> s.getChange(myProject)); } } else if (PlatformDataKeys.DELETE_ELEMENT_PROVIDER.is(dataId)) { return myDeleteProvider; } else if (CommonDataKeys.NAVIGATABLE_ARRAY.is(dataId)) { List<ShelvedWrapper> shelvedChanges = VcsTreeModelData.selected(myTree).userObjects(ShelvedWrapper.class); final ArrayDeque<Navigatable> navigatables = new ArrayDeque<>(); for (final ShelvedWrapper shelvedChange : shelvedChanges) { if (shelvedChange.getBeforePath() != null && !FileStatus.ADDED.equals(shelvedChange.getFileStatus())) { final NavigatableAdapter navigatable = new NavigatableAdapter() { @Override public void navigate(boolean requestFocus) { final VirtualFile vf = shelvedChange.getBeforeVFUnderProject(myProject); if (vf != null) { navigate(myProject, vf, true); } } }; navigatables.add(navigatable); } } return navigatables.toArray(new Navigatable[0]); } return super.getData(dataId); } @NotNull private Set<ShelvedChangeList> getSelectedLists(@NotNull Predicate<? super ShelvedChangeList> condition) { TreePath[] selectionPaths = getSelectionPaths(); if (selectionPaths == null) return Collections.emptySet(); return StreamEx.of(selectionPaths) .map(path -> TreeUtil.findObjectInPath(path, ShelvedChangeList.class)) .filter(Objects::nonNull) .filter(condition) .collect(Collectors.toSet()); } } @NotNull public static List<ShelvedChangeList> getShelvedLists(@NotNull final DataContext dataContext) { List<ShelvedChangeList> shelvedChangeLists = new ArrayList<>(); addAll(shelvedChangeLists, notNullize(SHELVED_CHANGELIST_KEY.getData(dataContext))); addAll(shelvedChangeLists, notNullize(SHELVED_RECYCLED_CHANGELIST_KEY.getData(dataContext))); addAll(shelvedChangeLists, notNullize(SHELVED_DELETED_CHANGELIST_KEY.getData(dataContext))); return shelvedChangeLists; } @NotNull public static List<ShelvedChange> getShelveChanges(@NotNull final DataContext dataContext) { return notNullize(dataContext.getData(SHELVED_CHANGE_KEY)); } @NotNull public static List<ShelvedBinaryFile> getBinaryShelveChanges(@NotNull final DataContext dataContext) { return notNullize(dataContext.getData(SHELVED_BINARY_FILE_KEY)); } private class MyShelveDeleteProvider implements DeleteProvider { @Override public void deleteElement(@NotNull DataContext dataContext) { final Project project = CommonDataKeys.PROJECT.getData(dataContext); if (project == null) return; List<ShelvedChangeList> shelvedListsToDelete = TreeUtil.collectSelectedObjectsOfType(myTree, ShelvedChangeList.class); List<ShelvedChange> changesToDelete = getChangesNotInLists(shelvedListsToDelete, getShelveChanges(dataContext)); List<ShelvedBinaryFile> binariesToDelete = getBinariesNotInLists(shelvedListsToDelete, getBinaryShelveChanges(dataContext)); int fileListSize = binariesToDelete.size() + changesToDelete.size(); Map<ShelvedChangeList, Date> createdDeletedListsWithOriginalDates = myShelveChangesManager.deleteShelves(shelvedListsToDelete, getShelvedLists(dataContext), changesToDelete, binariesToDelete); if (!createdDeletedListsWithOriginalDates.isEmpty()) { showUndoDeleteNotification(shelvedListsToDelete, fileListSize, createdDeletedListsWithOriginalDates); } } private void showUndoDeleteNotification(@NotNull List<? extends ShelvedChangeList> shelvedListsToDelete, int fileListSize, @NotNull Map<ShelvedChangeList, Date> createdDeletedListsWithOriginalDate) { String message = constructDeleteSuccessfullyMessage(fileListSize, shelvedListsToDelete.size(), getFirstItem(shelvedListsToDelete)); Notification shelfDeletionNotification = new ShelfDeleteNotification(message); shelfDeletionNotification.addAction(new UndoShelfDeletionAction(createdDeletedListsWithOriginalDate)); shelfDeletionNotification.addAction(ActionManager.getInstance().getAction("ShelvedChanges.ShowRecentlyDeleted")); VcsNotifier.getInstance(myProject).showNotificationAndHideExisting(shelfDeletionNotification, ShelfDeleteNotification.class); } private class UndoShelfDeletionAction extends NotificationAction { @NotNull private final Map<ShelvedChangeList, Date> myListDateMap; private UndoShelfDeletionAction(@NotNull Map<ShelvedChangeList, Date> listDateMap) { super("Undo"); myListDateMap = listDateMap; } @Override public void actionPerformed(@NotNull AnActionEvent e, @NotNull Notification notification) { ShelveChangesManager manager = ShelveChangesManager.getInstance(myProject); List cantRestoreList = findAll(myListDateMap.keySet(), l -> !myShelveChangesManager.getDeletedLists().contains(l)); myListDateMap.forEach((l, d) -> manager.restoreList(l, d)); notification.expire(); if (!cantRestoreList.isEmpty()) { VcsNotifier.getInstance(myProject).notifyMinorWarning("Undo Shelf Deletion", VcsBundle .message("shelve.changes.restore.error", cantRestoreList.size(), StringUtil.pluralize("changelist", cantRestoreList.size()))); } } } private List<ShelvedBinaryFile> getBinariesNotInLists(@NotNull List<? extends ShelvedChangeList> listsToDelete, @NotNull List<? extends ShelvedBinaryFile> binaryFiles) { List<ShelvedBinaryFile> result = new ArrayList<>(binaryFiles); for (ShelvedChangeList list : listsToDelete) { result.removeAll(list.getBinaryFiles()); } return result; } @NotNull private List<ShelvedChange> getChangesNotInLists(@NotNull List<? extends ShelvedChangeList> listsToDelete, @NotNull List<? extends ShelvedChange> shelvedChanges) { List<ShelvedChange> result = new ArrayList<>(shelvedChanges); // all changes should be loaded because action performed from loaded shelf tab listsToDelete.stream().map(list -> requireNonNull(list.getChanges())).forEach(result::removeAll); return result; } @NotNull private String constructDeleteSuccessfullyMessage(int fileNum, int listNum, @Nullable ShelvedChangeList first) { StringBuilder stringBuilder = new StringBuilder(); String delimiter = ""; if (fileNum != 0) { stringBuilder.append(fileNum == 1 ? "one" : fileNum).append(StringUtil.pluralize(" file", fileNum)); delimiter = " and "; } if (listNum != 0) { stringBuilder.append(delimiter); if (listNum == 1 && first != null) { stringBuilder.append("one shelved changelist [<b>").append(first.DESCRIPTION).append("</b>]"); } else { stringBuilder.append(listNum).append(" shelved ").append(StringUtil.pluralize("changelist", listNum)); } } stringBuilder.append(" deleted successfully"); return StringUtil.capitalize(stringBuilder.toString()); } @Override public boolean canDeleteElement(@NotNull DataContext dataContext) { return !getShelvedLists(dataContext).isEmpty(); } } public class MyShelfContent extends DnDActivateOnHoldTargetContent { private MyShelfContent(JPanel panel, @NotNull String displayName, boolean isLockable) { super(myProject, panel, displayName, isLockable); } @Override public void drop(DnDEvent event) { super.drop(event); Object attachedObject = event.getAttachedObject(); if (attachedObject instanceof ChangeListDragBean) { FileDocumentManager.getInstance().saveAllDocuments(); List<Change> changes = Arrays.asList(((ChangeListDragBean)attachedObject).getChanges()); myShelveChangesManager.shelveSilentlyUnderProgress(changes); } } @Override public boolean isDropPossible(@NotNull DnDEvent event) { Object attachedObject = event.getAttachedObject(); return attachedObject instanceof ChangeListDragBean && ((ChangeListDragBean)attachedObject).getChanges().length > 0; } } @Nullable private DnDDragStartBean createDragStartBean(@NotNull DnDActionInfo info) { if (info.isMove()) { DataContext dc = DataManager.getInstance().getDataContext(myTree); return new DnDDragStartBean(new ShelvedChangeListDragBean(getShelveChanges(dc), getBinaryShelveChanges(dc), getShelvedLists(dc))); } return null; } @NotNull private DnDImage createDraggedImage(@NotNull DnDActionInfo info) { String imageText = "Unshelve changes"; Image image = DnDAwareTree.getDragImage(myTree, imageText, null).getFirst(); return new DnDImage(image, new Point(-image.getWidth(null), -image.getHeight(null))); } private class MyToggleDetailsAction extends ShowDiffPreviewAction { @Override public void setSelected(@NotNull AnActionEvent e, boolean state) { mySplitterComponent.setDetailsOn(state); myVcsConfiguration.SHELVE_DETAILS_PREVIEW_SHOWN = state; } @Override public boolean isSelected(@NotNull AnActionEvent e) { return myVcsConfiguration.SHELVE_DETAILS_PREVIEW_SHOWN; } } private class MyShelvedPreviewProcessor extends CacheDiffRequestProcessor<ShelvedWrapper> implements DiffPreviewUpdateProcessor { @NotNull private final DiffShelvedChangesActionProvider.PatchesPreloader myPreloader; @Nullable private ShelvedWrapper myCurrentShelvedElement; MyShelvedPreviewProcessor(@NotNull Project project) { super(project); myPreloader = new DiffShelvedChangesActionProvider.PatchesPreloader(project); Disposer.register(project, this); } @NotNull @Override protected String getRequestName(@NotNull ShelvedWrapper provider) { return provider.getRequestName(); } @Override protected ShelvedWrapper getCurrentRequestProvider() { return myCurrentShelvedElement; } @CalledInAwt @Override public void clear() { myCurrentShelvedElement = null; updateRequest(); dropCaches(); } @Override @CalledInAwt public void refresh(boolean fromModelRefresh) { DataContext dc = DataManager.getInstance().getDataContext(myTree); List<ShelvedChange> selectedChanges = getShelveChanges(dc); List<ShelvedBinaryFile> selectedBinaryChanges = getBinaryShelveChanges(dc); if (selectedChanges.isEmpty() && selectedBinaryChanges.isEmpty()) { clear(); return; } if (myCurrentShelvedElement != null) { if (keepBinarySelection(selectedBinaryChanges, myCurrentShelvedElement.getBinaryFile()) || keepShelvedSelection(selectedChanges, myCurrentShelvedElement.getShelvedChange())) { dropCachesIfNeededAndUpdate(myCurrentShelvedElement); return; } } //getFirstSelected myCurrentShelvedElement = !selectedChanges.isEmpty() ? new ShelvedWrapper(selectedChanges.get(0)) : new ShelvedWrapper(selectedBinaryChanges.get(0)); dropCachesIfNeededAndUpdate(myCurrentShelvedElement); } private void dropCachesIfNeededAndUpdate(@NotNull ShelvedWrapper currentShelvedElement) { ShelvedChange shelvedChange = currentShelvedElement.getShelvedChange(); boolean dropCaches = shelvedChange != null && myPreloader.isPatchFileChanged(shelvedChange.getPatchPath()); if (dropCaches) { dropCaches(); } updateRequest(dropCaches); } boolean keepShelvedSelection(@NotNull List<ShelvedChange> selectedChanges, @Nullable ShelvedChange currentShelvedChange) { return currentShelvedChange != null && selectedChanges.contains(currentShelvedChange); } boolean keepBinarySelection(@NotNull List<ShelvedBinaryFile> selectedBinaryChanges, @Nullable ShelvedBinaryFile currentBinary) { return currentBinary != null && selectedBinaryChanges.contains(currentBinary); } @NotNull @Override protected DiffRequest loadRequest(@NotNull ShelvedWrapper provider, @NotNull ProgressIndicator indicator) throws ProcessCanceledException, DiffRequestProducerException { try { ShelvedChange shelvedChange = provider.getShelvedChange(); if (shelvedChange != null) { return new PatchDiffRequest(createAppliedTextPatch(myPreloader.getPatch(shelvedChange, null))); } DiffContentFactoryEx factory = DiffContentFactoryEx.getInstanceEx(); ShelvedBinaryFile binaryFile = assertNotNull(provider.getBinaryFile()); if (binaryFile.AFTER_PATH == null) { throw new DiffRequestProducerException("Content for '" + getRequestName(provider) + "' was removed"); } byte[] binaryContent = binaryFile.createBinaryContentRevision(myProject).getBinaryContent(); FileType fileType = VcsUtil.getFilePath(binaryFile.SHELVED_PATH).getFileType(); return new SimpleDiffRequest(getRequestName(provider), factory.createEmpty(), factory.createBinary(myProject, binaryContent, fileType, getRequestName(provider)), null, null); } catch (VcsException | IOException e) { throw new DiffRequestProducerException("Can't show diff for '" + getRequestName(provider) + "'", e); } } } private static class ShelvedListNode extends ChangesBrowserNode<ShelvedChangeList> { private static final Icon PatchIcon = StdFileTypes.PATCH.getIcon(); private static final Icon AppliedPatchIcon = new IconSizeWrapper(Patch_applied, Patch_applied.getIconWidth(), Patch_applied.getIconHeight()) { @Override public void paintIcon(Component c, Graphics g, int x, int y) { GraphicsUtil.paintWithAlpha(g, 0.6f); super.paintIcon(c, g, x, y); } }; private static final Icon DisabledToDeleteIcon = IconUtil.desaturate(AllIcons.Actions.GC); @NotNull private final ShelvedChangeList myList; ShelvedListNode(@NotNull ShelvedChangeList list) { super(list); myList = list; } @NotNull public ShelvedChangeList getList() { return myList; } @Override public void render(@NotNull ChangesBrowserNodeRenderer renderer, boolean selected, boolean expanded, boolean hasFocus) { if (myList.isRecycled() || myList.isDeleted()) { renderer.appendTextWithIssueLinks(myList.DESCRIPTION, SimpleTextAttributes.GRAYED_BOLD_ATTRIBUTES); renderer.setIcon(myList.isMarkedToDelete() || myList.isDeleted() ? DisabledToDeleteIcon : AppliedPatchIcon); } else { renderer.appendTextWithIssueLinks(myList.DESCRIPTION, SimpleTextAttributes.REGULAR_ATTRIBUTES); renderer.setIcon(PatchIcon); } appendCount(renderer); String date = DateFormatUtil.formatPrettyDateTime(myList.DATE); renderer.append(", " + date, SimpleTextAttributes.GRAYED_ATTRIBUTES); } } private static class ShelvedChangeNode extends ChangesBrowserNode<ShelvedWrapper> { @NotNull private final ShelvedWrapper myShelvedChange; @Nullable private final String myAdditionalText; protected ShelvedChangeNode(@NotNull ShelvedWrapper shelvedChange, @Nullable String additionalText) { super(shelvedChange); myShelvedChange = shelvedChange; myAdditionalText = additionalText; } @Override public void render(@NotNull ChangesBrowserNodeRenderer renderer, boolean selected, boolean expanded, boolean hasFocus) { String path = myShelvedChange.getRequestName(); String directory = StringUtil.defaultIfEmpty(PathUtil.getParentPath(path), "<project root>"); String fileName = StringUtil.defaultIfEmpty(PathUtil.getFileName(path), path); renderer.append(fileName, new SimpleTextAttributes(SimpleTextAttributes.STYLE_PLAIN, myShelvedChange.getFileStatus().getColor())); if (myAdditionalText != null) { renderer.append(spaceAndThinSpace() + myAdditionalText, SimpleTextAttributes.REGULAR_ATTRIBUTES); } if (renderer.isShowFlatten()) { renderer.append(spaceAndThinSpace() + FileUtil.toSystemDependentName(directory), SimpleTextAttributes.GRAYED_ATTRIBUTES); } renderer.setIcon(FileTypeManager.getInstance().getFileTypeByFileName(fileName).getIcon()); } @Override public String getTextPresentation() { return PathUtil.getFileName(myShelvedChange.getRequestName()); } @Override protected boolean isFile() { return true; } } private class MyContentUpdater extends Update { MyContentUpdater() { super("ShelfContentUpdate"); } @Override public void run() { updateTreeModel(); } @Override public boolean canEat(Update update) { return true; } } }
package com.intellij.openapi.vcs.changes.shelf; import com.intellij.diff.DiffContentFactoryEx; import com.intellij.diff.chains.DiffRequestProducerException; import com.intellij.diff.impl.CacheDiffRequestProcessor; import com.intellij.diff.requests.DiffRequest; import com.intellij.diff.requests.SimpleDiffRequest; import com.intellij.icons.AllIcons; import com.intellij.ide.DataManager; import com.intellij.ide.DeleteProvider; import com.intellij.ide.actions.EditSourceAction; import com.intellij.ide.dnd.*; import com.intellij.ide.dnd.aware.DnDAwareTree; import com.intellij.notification.Notification; import com.intellij.notification.NotificationAction; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.util.BackgroundTaskUtil; import com.intellij.openapi.project.DumbAwareRunnable; import com.intellij.openapi.project.Project; import com.intellij.openapi.startup.StartupManager; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.*; import com.intellij.openapi.vcs.changes.*; import com.intellij.openapi.vcs.changes.actions.ShowDiffPreviewAction; import com.intellij.openapi.vcs.changes.patch.tool.PatchDiffRequest; import com.intellij.openapi.vcs.changes.ui.*; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.wm.ToolWindow; import com.intellij.openapi.wm.ToolWindowManager; import com.intellij.pom.Navigatable; import com.intellij.pom.NavigatableAdapter; import com.intellij.ui.*; import com.intellij.ui.content.Content; import com.intellij.ui.content.impl.ContentImpl; import com.intellij.util.IconUtil; import com.intellij.util.IconUtil.IconSizeWrapper; import com.intellij.util.PathUtil; import com.intellij.util.text.DateFormatUtil; import com.intellij.util.ui.GraphicsUtil; import com.intellij.util.ui.tree.TreeUtil; import com.intellij.util.ui.update.MergingUpdateQueue; import com.intellij.util.ui.update.Update; import com.intellij.vcsUtil.VcsUtil; import one.util.streamex.StreamEx; import org.jetbrains.annotations.CalledInAwt; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.event.CellEditorListener; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.tree.*; import java.awt.*; import java.awt.event.MouseEvent; import java.beans.PropertyChangeListener; import java.io.IOException; import java.util.List; import java.util.*; import java.util.function.Predicate; import java.util.stream.Collectors; import static com.intellij.icons.AllIcons.Vcs.Patch_applied; import static com.intellij.openapi.actionSystem.Anchor.AFTER; import static com.intellij.openapi.vcs.changes.shelf.DiffShelvedChangesActionProvider.createAppliedTextPatch; import static com.intellij.openapi.vcs.changes.ui.ChangesGroupingSupport.REPOSITORY_GROUPING; import static com.intellij.util.FontUtil.spaceAndThinSpace; import static com.intellij.util.ObjectUtils.assertNotNull; import static com.intellij.util.containers.ContainerUtil.*; import static com.intellij.util.containers.UtilKt.isEmpty; import static java.util.Comparator.comparing; import static java.util.Objects.requireNonNull; public class ShelvedChangesViewManager implements Disposable { private static final Logger LOG = Logger.getInstance(ShelvedChangesViewManager.class); @NonNls static final String SHELF_CONTEXT_MENU = "Vcs.Shelf.ContextMenu"; private static final String SHELVE_PREVIEW_SPLITTER_PROPORTION = "ShelvedChangesViewManager.DETAILS_SPLITTER_PROPORTION"; private final ShelveChangesManager myShelveChangesManager; private final Project myProject; final ShelfTree myTree; @NotNull private final PropertyChangeListener myGroupingChangeListener; private MyShelfContent myContent = null; final DeleteProvider myDeleteProvider = new MyShelveDeleteProvider(); private final MergingUpdateQueue myUpdateQueue; private final VcsConfiguration myVcsConfiguration; private volatile List<ShelvedChangeList> myLoadedLists = emptyList(); private final List<Runnable> myPostUpdateEdtActivity = new ArrayList<>(); public static final DataKey<List<ShelvedChangeList>> SHELVED_CHANGELIST_KEY = DataKey.create("ShelveChangesManager.ShelvedChangeListData"); public static final DataKey<List<ShelvedChangeList>> SHELVED_RECYCLED_CHANGELIST_KEY = DataKey.create("ShelveChangesManager.ShelvedRecycledChangeListData"); public static final DataKey<List<ShelvedChangeList>> SHELVED_DELETED_CHANGELIST_KEY = DataKey.create("ShelveChangesManager.ShelvedDeletedChangeListData"); public static final DataKey<List<ShelvedChange>> SHELVED_CHANGE_KEY = DataKey.create("ShelveChangesManager.ShelvedChange"); public static final DataKey<List<ShelvedBinaryFile>> SHELVED_BINARY_FILE_KEY = DataKey.create("ShelveChangesManager.ShelvedBinaryFile"); private PreviewDiffSplitterComponent mySplitterComponent; public static ShelvedChangesViewManager getInstance(Project project) { return project.getComponent(ShelvedChangesViewManager.class); } public ShelvedChangesViewManager(Project project) { myProject = project; myShelveChangesManager = ShelveChangesManager.getInstance(project); myUpdateQueue = new MergingUpdateQueue("Update Shelf Content", 200, true, null, myProject, null, true); myVcsConfiguration = VcsConfiguration.getInstance(myProject); project.getMessageBus().connect().subscribe(ShelveChangesManager.SHELF_TOPIC, new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { myUpdateQueue.queue(new MyContentUpdater()); } }); myTree = new ShelfTree(myProject); myTree.setEditable(true); myTree.setDragEnabled(true); myTree.getGroupingSupport().setGroupingKeysOrSkip(myShelveChangesManager.getGrouping()); myGroupingChangeListener = e -> { myShelveChangesManager.setGrouping(myTree.getGroupingSupport().getGroupingKeys()); myTree.rebuildTree(); }; myTree.addGroupingChangeListener(myGroupingChangeListener); DefaultTreeCellEditor treeCellEditor = new DefaultTreeCellEditor(myTree, null) { @Override public boolean isCellEditable(EventObject event) { return !(event instanceof MouseEvent) && super.isCellEditable(event); } }; myTree.setCellEditor(treeCellEditor); treeCellEditor.addCellEditorListener(new CellEditorListener() { @Override public void editingStopped(ChangeEvent e) { DefaultMutableTreeNode node = (DefaultMutableTreeNode)myTree.getLastSelectedPathComponent(); if (node instanceof ShelvedListNode && e.getSource() instanceof TreeCellEditor) { String editorValue = ((TreeCellEditor)e.getSource()).getCellEditorValue().toString(); ShelvedChangeList shelvedChangeList = ((ShelvedListNode)node).getList(); ShelveChangesManager.getInstance(project).renameChangeList(shelvedChangeList, editorValue); } } @Override public void editingCanceled(ChangeEvent e) { } }); final AnAction showDiffAction = ActionManager.getInstance().getAction(IdeActions.ACTION_SHOW_DIFF_COMMON); showDiffAction.registerCustomShortcutSet(showDiffAction.getShortcutSet(), myTree); final EditSourceAction editSourceAction = new EditSourceAction(); editSourceAction.registerCustomShortcutSet(editSourceAction.getShortcutSet(), myTree); PopupHandler.installPopupHandler(myTree, "ShelvedChangesPopupMenu", SHELF_CONTEXT_MENU); myTree.addSelectionListener(() -> mySplitterComponent.updatePreview(false)); StartupManager.getInstance(project).registerPostStartupActivity((DumbAwareRunnable)() -> myUpdateQueue.queue(new MyContentUpdater())); } private boolean hasExactlySelectedChanges() { return !isEmpty(VcsTreeModelData.exactlySelected(myTree).userObjectsStream(ShelvedWrapper.class)); } @CalledInAwt void updateViewContent() { if (myShelveChangesManager.getAllLists().isEmpty()) { if (myContent != null) { ChangesViewContentI contentManager = ChangesViewContentManager.getInstance(myProject); contentManager.removeContent(myContent); contentManager.selectContent(ChangesViewContentManager.LOCAL_CHANGES); VcsNotifier.getInstance(myProject).hideAllNotificationsByType(ShelfNotification.class); } myContent = null; } else { if (myContent == null) { myTree.updateUI(); JPanel rootPanel = createRootPanel(); myContent = new MyShelfContent(rootPanel, VcsBundle.message("shelf.tab"), false); myContent.setCloseable(false); ChangesViewContentI contentManager = ChangesViewContentManager.getInstance(myProject); contentManager.addContent(myContent); DnDSupport.createBuilder(myTree) .setImageProvider(this::createDraggedImage) .setBeanProvider(this::createDragStartBean) .setTargetChecker(myContent.myDnDTarget) .setDropHandler(myContent.myDnDTarget) .setDisposableParent(myContent) .install(); } myTree.rebuildTree(); } } private ToolWindow getVcsToolWindow() { return ToolWindowManager.getInstance(myProject).getToolWindow(ChangesViewContentManager.TOOLWINDOW_ID); } @NotNull private JPanel createRootPanel() { JScrollPane pane = ScrollPaneFactory.createScrollPane(myTree, SideBorder.LEFT); DefaultActionGroup actionGroup = new DefaultActionGroup(); actionGroup.addAll((ActionGroup)ActionManager.getInstance().getAction("ShelvedChangesToolbar")); actionGroup.add(new MyToggleDetailsAction(), new Constraints(AFTER, "ShelvedChanges.ShowHideDeleted")); MyShelvedPreviewProcessor changeProcessor = new MyShelvedPreviewProcessor(myProject); mySplitterComponent = new PreviewDiffSplitterComponent(pane, changeProcessor, SHELVE_PREVIEW_SPLITTER_PROPORTION, myVcsConfiguration.SHELVE_DETAILS_PREVIEW_SHOWN); ActionToolbar toolbar = ActionManager.getInstance().createActionToolbar("ShelvedChanges", actionGroup, false); JPanel rootPanel = new JPanel(new BorderLayout()); rootPanel.add(toolbar.getComponent(), BorderLayout.WEST); rootPanel.add(mySplitterComponent, BorderLayout.CENTER); DataManager.registerDataProvider(rootPanel, myTree); return rootPanel; } private class MyShelvedTreeModelBuilder extends TreeModelBuilder { private MyShelvedTreeModelBuilder() { super(ShelvedChangesViewManager.this.myProject, myTree.getGrouping()); } public void setShelvedLists(@NotNull List<? extends ShelvedChangeList> shelvedLists) { createShelvedListsWithChangesNode(shelvedLists, myRoot); } public void setDeletedShelvedLists(@NotNull List<? extends ShelvedChangeList> shelvedLists) { createShelvedListsWithChangesNode(shelvedLists, createTagNode("Recently Deleted")); } private void createShelvedListsWithChangesNode(@NotNull List<? extends ShelvedChangeList> shelvedLists, @NotNull MutableTreeNode parentNode) { shelvedLists.forEach(changeList -> { List<ShelvedWrapper> shelvedChanges = new ArrayList<>(); requireNonNull(changeList.getChanges()).stream().map(ShelvedWrapper::new).forEach(shelvedChanges::add); changeList.getBinaryFiles().stream().map(ShelvedWrapper::new).forEach(shelvedChanges::add); shelvedChanges.sort(comparing(s -> s.getChange(myProject), CHANGE_COMPARATOR)); ShelvedListNode shelvedListNode = new ShelvedListNode(changeList); myModel.insertNodeInto(shelvedListNode, parentNode, parentNode.getChildCount()); for (ShelvedWrapper shelved : shelvedChanges) { Change change = shelved.getChange(myProject); FilePath filePath = ChangesUtil.getFilePath(change); insertChangeNode(change, shelvedListNode, new ShelvedChangeNode(shelved, filePath, change.getOriginText(myProject))); } }); } } @CalledInAwt private void updateTreeModel() { myTree.setPaintBusy(true); BackgroundTaskUtil.executeOnPooledThread(myProject, () -> { List<ShelvedChangeList> lists = myShelveChangesManager.getAllLists(); lists.forEach(l -> l.loadChangesIfNeeded(myProject)); myLoadedLists = sorted(lists, ChangelistComparator.getInstance()); ApplicationManager.getApplication().invokeLater(() -> { myTree.setPaintBusy(false); updateViewContent(); myPostUpdateEdtActivity.forEach(Runnable::run); myPostUpdateEdtActivity.clear(); }, ModalityState.NON_MODAL, myProject.getDisposed()); }); } @CalledInAwt public void startEditing(@NotNull ShelvedChangeList shelvedChangeList) { runAfterUpdate(() -> { selectShelvedList(shelvedChangeList); myTree.startEditingAtPath(myTree.getLeadSelectionPath()); }); } static class ChangelistComparator implements Comparator<ShelvedChangeList> { private final static ChangelistComparator ourInstance = new ChangelistComparator(); public static ChangelistComparator getInstance() { return ourInstance; } @Override public int compare(ShelvedChangeList o1, ShelvedChangeList o2) { return o2.DATE.compareTo(o1.DATE); } } public void activateView(@Nullable final ShelvedChangeList list) { runAfterUpdate(() -> { if (myContent == null) return; if (list != null) { selectShelvedList(list); } ChangesViewContentI contentManager = ChangesViewContentManager.getInstance(myProject); contentManager.setSelectedContent(myContent); ToolWindow window = getVcsToolWindow(); if (window != null && !window.isVisible()) { window.activate(null); } }); } private void runAfterUpdate(@NotNull Runnable postUpdateRunnable) { GuiUtils.invokeLaterIfNeeded(() -> { myUpdateQueue.cancelAllUpdates(); myPostUpdateEdtActivity.add(postUpdateRunnable); updateTreeModel(); }, ModalityState.NON_MODAL, myProject.getDisposed()); } @Override public void dispose() { myUpdateQueue.cancelAllUpdates(); myTree.removeGroupingChangeListener(myGroupingChangeListener); } public void updateOnVcsMappingsChanged() { ApplicationManager.getApplication().invokeLater(() -> { ChangesGroupingSupport treeGroupingSupport = myTree.getGroupingSupport(); if (treeGroupingSupport.isAvailable(REPOSITORY_GROUPING) && treeGroupingSupport.get(REPOSITORY_GROUPING)) { myTree.rebuildTree(); } }, myProject.getDisposed()); } public void selectShelvedList(@NotNull ShelvedChangeList list) { DefaultMutableTreeNode treeNode = TreeUtil.findNodeWithObject((DefaultMutableTreeNode)myTree.getModel().getRoot(), list); if (treeNode == null) { LOG.warn(String.format("Shelved changeList %s not found", list.DESCRIPTION)); return; } TreeUtil.selectNode(myTree, treeNode); } private class ShelfTree extends ChangesTree { private ShelfTree(@NotNull Project project) { super(project, false, false, true); setKeepTreeState(true); } @Override public boolean isPathEditable(TreePath path) { return isEditable() && myTree.getSelectionCount() == 1 && path.getLastPathComponent() instanceof ShelvedListNode; } @NotNull @Override protected ChangesGroupingSupport installGroupingSupport() { return new ChangesGroupingSupport(myProject, this, false); } @Override public int getToggleClickCount() { return 2; } @Override protected void installDoubleClickHandler() { new DoubleClickListener() { @Override protected boolean onDoubleClick(MouseEvent e) { if (!hasExactlySelectedChanges()) return false; DiffShelvedChangesActionProvider.showShelvedChangesDiff(DataManager.getInstance().getDataContext(myTree)); return true; } }.installOn(this); } @Override public void rebuildTree() { MyShelvedTreeModelBuilder modelBuilder = new MyShelvedTreeModelBuilder(); List<ShelvedChangeList> changeLists = new ArrayList<>(myLoadedLists); modelBuilder .setShelvedLists(filter(changeLists, l -> !l.isDeleted() && (myShelveChangesManager.isShowRecycled() || !l.isRecycled()))); modelBuilder.setDeletedShelvedLists(filter(changeLists, ShelvedChangeList::isDeleted)); updateTreeModel(modelBuilder.build()); } @Nullable @Override public Object getData(@NotNull @NonNls String dataId) { if (SHELVED_CHANGELIST_KEY.is(dataId)) { return new ArrayList<>((Collection<? extends ShelvedChangeList>)getSelectedLists(l -> !l.isRecycled() && !l.isDeleted())); } else if (SHELVED_RECYCLED_CHANGELIST_KEY.is(dataId)) { return new ArrayList<>((Collection<? extends ShelvedChangeList>)getSelectedLists(l -> l.isRecycled() && !l.isDeleted())); } else if (SHELVED_DELETED_CHANGELIST_KEY.is(dataId)) { return new ArrayList<>((Collection<? extends ShelvedChangeList>)getSelectedLists(l -> l.isDeleted())); } else if (SHELVED_CHANGE_KEY.is(dataId)) { return StreamEx.of(VcsTreeModelData.selected(myTree).userObjectsStream(ShelvedWrapper.class)).map(s -> s.getShelvedChange()) .nonNull().toList(); } else if (SHELVED_BINARY_FILE_KEY.is(dataId)) { return StreamEx.of(VcsTreeModelData.selected(myTree).userObjectsStream(ShelvedWrapper.class)).map(s -> s.getBinaryFile()) .nonNull().toList(); } else if (VcsDataKeys.HAVE_SELECTED_CHANGES.is(dataId)) { return getSelectionCount() > 0; } else if (VcsDataKeys.CHANGES.is(dataId)) { List<ShelvedWrapper> shelvedChanges = VcsTreeModelData.selected(myTree).userObjects(ShelvedWrapper.class); if (!shelvedChanges.isEmpty()) { return map2Array(shelvedChanges, Change.class, s -> s.getChange(myProject)); } } else if (PlatformDataKeys.DELETE_ELEMENT_PROVIDER.is(dataId)) { return myDeleteProvider; } else if (CommonDataKeys.NAVIGATABLE_ARRAY.is(dataId)) { List<ShelvedWrapper> shelvedChanges = VcsTreeModelData.selected(myTree).userObjects(ShelvedWrapper.class); final ArrayDeque<Navigatable> navigatables = new ArrayDeque<>(); for (final ShelvedWrapper shelvedChange : shelvedChanges) { if (shelvedChange.getBeforePath() != null && !FileStatus.ADDED.equals(shelvedChange.getFileStatus())) { final NavigatableAdapter navigatable = new NavigatableAdapter() { @Override public void navigate(boolean requestFocus) { final VirtualFile vf = shelvedChange.getBeforeVFUnderProject(myProject); if (vf != null) { navigate(myProject, vf, true); } } }; navigatables.add(navigatable); } } return navigatables.toArray(new Navigatable[0]); } return super.getData(dataId); } @NotNull private Set<ShelvedChangeList> getSelectedLists(@NotNull Predicate<? super ShelvedChangeList> condition) { TreePath[] selectionPaths = getSelectionPaths(); if (selectionPaths == null) return Collections.emptySet(); return StreamEx.of(selectionPaths) .map(path -> TreeUtil.findObjectInPath(path, ShelvedChangeList.class)) .filter(Objects::nonNull) .filter(condition) .collect(Collectors.toSet()); } } @NotNull public static List<ShelvedChangeList> getShelvedLists(@NotNull final DataContext dataContext) { List<ShelvedChangeList> shelvedChangeLists = new ArrayList<>(); addAll(shelvedChangeLists, notNullize(SHELVED_CHANGELIST_KEY.getData(dataContext))); addAll(shelvedChangeLists, notNullize(SHELVED_RECYCLED_CHANGELIST_KEY.getData(dataContext))); addAll(shelvedChangeLists, notNullize(SHELVED_DELETED_CHANGELIST_KEY.getData(dataContext))); return shelvedChangeLists; } @NotNull public static List<ShelvedChange> getShelveChanges(@NotNull final DataContext dataContext) { return notNullize(dataContext.getData(SHELVED_CHANGE_KEY)); } @NotNull public static List<ShelvedBinaryFile> getBinaryShelveChanges(@NotNull final DataContext dataContext) { return notNullize(dataContext.getData(SHELVED_BINARY_FILE_KEY)); } private class MyShelveDeleteProvider implements DeleteProvider { @Override public void deleteElement(@NotNull DataContext dataContext) { final Project project = CommonDataKeys.PROJECT.getData(dataContext); if (project == null) return; List<ShelvedChangeList> shelvedListsToDelete = TreeUtil.collectSelectedObjectsOfType(myTree, ShelvedChangeList.class); List<ShelvedChange> changesToDelete = getChangesNotInLists(shelvedListsToDelete, getShelveChanges(dataContext)); List<ShelvedBinaryFile> binariesToDelete = getBinariesNotInLists(shelvedListsToDelete, getBinaryShelveChanges(dataContext)); int fileListSize = binariesToDelete.size() + changesToDelete.size(); Map<ShelvedChangeList, Date> createdDeletedListsWithOriginalDates = myShelveChangesManager.deleteShelves(shelvedListsToDelete, getShelvedLists(dataContext), changesToDelete, binariesToDelete); if (!createdDeletedListsWithOriginalDates.isEmpty()) { showUndoDeleteNotification(shelvedListsToDelete, fileListSize, createdDeletedListsWithOriginalDates); } } private void showUndoDeleteNotification(@NotNull List<? extends ShelvedChangeList> shelvedListsToDelete, int fileListSize, @NotNull Map<ShelvedChangeList, Date> createdDeletedListsWithOriginalDate) { String message = constructDeleteSuccessfullyMessage(fileListSize, shelvedListsToDelete.size(), getFirstItem(shelvedListsToDelete)); Notification shelfDeletionNotification = new ShelfDeleteNotification(message); shelfDeletionNotification.addAction(new UndoShelfDeletionAction(createdDeletedListsWithOriginalDate)); shelfDeletionNotification.addAction(ActionManager.getInstance().getAction("ShelvedChanges.ShowRecentlyDeleted")); VcsNotifier.getInstance(myProject).showNotificationAndHideExisting(shelfDeletionNotification, ShelfDeleteNotification.class); } private class UndoShelfDeletionAction extends NotificationAction { @NotNull private final Map<ShelvedChangeList, Date> myListDateMap; private UndoShelfDeletionAction(@NotNull Map<ShelvedChangeList, Date> listDateMap) { super("Undo"); myListDateMap = listDateMap; } @Override public void actionPerformed(@NotNull AnActionEvent e, @NotNull Notification notification) { ShelveChangesManager manager = ShelveChangesManager.getInstance(myProject); List<ShelvedChangeList> cantRestoreList = findAll(myListDateMap.keySet(), l -> !manager.getDeletedLists().contains(l)); myListDateMap.forEach((l, d) -> manager.restoreList(l, d)); notification.expire(); if (!cantRestoreList.isEmpty()) { VcsNotifier.getInstance(myProject).notifyMinorWarning("Undo Shelf Deletion", VcsBundle .message("shelve.changes.restore.error", cantRestoreList.size(), StringUtil.pluralize("changelist", cantRestoreList.size()))); } } } private List<ShelvedBinaryFile> getBinariesNotInLists(@NotNull List<? extends ShelvedChangeList> listsToDelete, @NotNull List<? extends ShelvedBinaryFile> binaryFiles) { List<ShelvedBinaryFile> result = new ArrayList<>(binaryFiles); for (ShelvedChangeList list : listsToDelete) { result.removeAll(list.getBinaryFiles()); } return result; } @NotNull private List<ShelvedChange> getChangesNotInLists(@NotNull List<? extends ShelvedChangeList> listsToDelete, @NotNull List<? extends ShelvedChange> shelvedChanges) { List<ShelvedChange> result = new ArrayList<>(shelvedChanges); // all changes should be loaded because action performed from loaded shelf tab listsToDelete.stream().map(list -> requireNonNull(list.getChanges())).forEach(result::removeAll); return result; } @NotNull private String constructDeleteSuccessfullyMessage(int fileNum, int listNum, @Nullable ShelvedChangeList first) { StringBuilder stringBuilder = new StringBuilder(); String delimiter = ""; if (fileNum != 0) { stringBuilder.append(fileNum == 1 ? "one" : fileNum).append(StringUtil.pluralize(" file", fileNum)); delimiter = " and "; } if (listNum != 0) { stringBuilder.append(delimiter); if (listNum == 1 && first != null) { stringBuilder.append("one shelved changelist [<b>").append(first.DESCRIPTION).append("</b>]"); } else { stringBuilder.append(listNum).append(" shelved ").append(StringUtil.pluralize("changelist", listNum)); } } stringBuilder.append(" deleted successfully"); return StringUtil.capitalize(stringBuilder.toString()); } @Override public boolean canDeleteElement(@NotNull DataContext dataContext) { return !getShelvedLists(dataContext).isEmpty(); } } public class MyShelfContent extends ContentImpl { private final MyDnDTarget myDnDTarget; private MyShelfContent(JPanel panel, @NotNull String displayName, boolean isLockable) { super(panel, displayName, isLockable); myDnDTarget = new MyDnDTarget(myProject, this); putUserData(Content.TAB_DND_TARGET_KEY, myDnDTarget); } private class MyDnDTarget extends VcsToolwindowDnDTarget { private MyDnDTarget(@NotNull Project project, @NotNull Content content) { super(project, content); } @Override public void drop(DnDEvent event) { super.drop(event); Object attachedObject = event.getAttachedObject(); if (attachedObject instanceof ChangeListDragBean) { FileDocumentManager.getInstance().saveAllDocuments(); List<Change> changes = Arrays.asList(((ChangeListDragBean)attachedObject).getChanges()); myShelveChangesManager.shelveSilentlyUnderProgress(changes); } } @Override public boolean isDropPossible(@NotNull DnDEvent event) { Object attachedObject = event.getAttachedObject(); return attachedObject instanceof ChangeListDragBean && ((ChangeListDragBean)attachedObject).getChanges().length > 0; } } } @Nullable private DnDDragStartBean createDragStartBean(@NotNull DnDActionInfo info) { if (info.isMove()) { DataContext dc = DataManager.getInstance().getDataContext(myTree); return new DnDDragStartBean(new ShelvedChangeListDragBean(getShelveChanges(dc), getBinaryShelveChanges(dc), getShelvedLists(dc))); } return null; } @NotNull private DnDImage createDraggedImage(@NotNull DnDActionInfo info) { String imageText = "Unshelve changes"; Image image = DnDAwareTree.getDragImage(myTree, imageText, null).getFirst(); return new DnDImage(image, new Point(-image.getWidth(null), -image.getHeight(null))); } private class MyToggleDetailsAction extends ShowDiffPreviewAction { @Override public void setSelected(@NotNull AnActionEvent e, boolean state) { mySplitterComponent.setDetailsOn(state); myVcsConfiguration.SHELVE_DETAILS_PREVIEW_SHOWN = state; } @Override public boolean isSelected(@NotNull AnActionEvent e) { return myVcsConfiguration.SHELVE_DETAILS_PREVIEW_SHOWN; } } private class MyShelvedPreviewProcessor extends CacheDiffRequestProcessor<ShelvedWrapper> implements DiffPreviewUpdateProcessor { @NotNull private final DiffShelvedChangesActionProvider.PatchesPreloader myPreloader; @Nullable private ShelvedWrapper myCurrentShelvedElement; MyShelvedPreviewProcessor(@NotNull Project project) { super(project); myPreloader = new DiffShelvedChangesActionProvider.PatchesPreloader(project); Disposer.register(project, this); } @NotNull @Override protected String getRequestName(@NotNull ShelvedWrapper provider) { return provider.getRequestName(); } @Override protected ShelvedWrapper getCurrentRequestProvider() { return myCurrentShelvedElement; } @CalledInAwt @Override public void clear() { myCurrentShelvedElement = null; updateRequest(); dropCaches(); } @Override @CalledInAwt public void refresh(boolean fromModelRefresh) { DataContext dc = DataManager.getInstance().getDataContext(myTree); List<ShelvedChange> selectedChanges = getShelveChanges(dc); List<ShelvedBinaryFile> selectedBinaryChanges = getBinaryShelveChanges(dc); if (selectedChanges.isEmpty() && selectedBinaryChanges.isEmpty()) { clear(); return; } if (myCurrentShelvedElement != null) { if (keepBinarySelection(selectedBinaryChanges, myCurrentShelvedElement.getBinaryFile()) || keepShelvedSelection(selectedChanges, myCurrentShelvedElement.getShelvedChange())) { dropCachesIfNeededAndUpdate(myCurrentShelvedElement); return; } } //getFirstSelected myCurrentShelvedElement = !selectedChanges.isEmpty() ? new ShelvedWrapper(selectedChanges.get(0)) : new ShelvedWrapper(selectedBinaryChanges.get(0)); dropCachesIfNeededAndUpdate(myCurrentShelvedElement); } private void dropCachesIfNeededAndUpdate(@NotNull ShelvedWrapper currentShelvedElement) { ShelvedChange shelvedChange = currentShelvedElement.getShelvedChange(); boolean dropCaches = shelvedChange != null && myPreloader.isPatchFileChanged(shelvedChange.getPatchPath()); if (dropCaches) { dropCaches(); } updateRequest(dropCaches); } boolean keepShelvedSelection(@NotNull List<ShelvedChange> selectedChanges, @Nullable ShelvedChange currentShelvedChange) { return currentShelvedChange != null && selectedChanges.contains(currentShelvedChange); } boolean keepBinarySelection(@NotNull List<ShelvedBinaryFile> selectedBinaryChanges, @Nullable ShelvedBinaryFile currentBinary) { return currentBinary != null && selectedBinaryChanges.contains(currentBinary); } @NotNull @Override protected DiffRequest loadRequest(@NotNull ShelvedWrapper provider, @NotNull ProgressIndicator indicator) throws ProcessCanceledException, DiffRequestProducerException { try { ShelvedChange shelvedChange = provider.getShelvedChange(); if (shelvedChange != null) { return new PatchDiffRequest(createAppliedTextPatch(myPreloader.getPatch(shelvedChange, null))); } DiffContentFactoryEx factory = DiffContentFactoryEx.getInstanceEx(); ShelvedBinaryFile binaryFile = assertNotNull(provider.getBinaryFile()); if (binaryFile.AFTER_PATH == null) { throw new DiffRequestProducerException("Content for '" + getRequestName(provider) + "' was removed"); } byte[] binaryContent = binaryFile.createBinaryContentRevision(myProject).getBinaryContent(); FileType fileType = VcsUtil.getFilePath(binaryFile.SHELVED_PATH).getFileType(); return new SimpleDiffRequest(getRequestName(provider), factory.createEmpty(), factory.createBinary(myProject, binaryContent, fileType, getRequestName(provider)), null, null); } catch (VcsException | IOException e) { throw new DiffRequestProducerException("Can't show diff for '" + getRequestName(provider) + "'", e); } } } private static class ShelvedListNode extends ChangesBrowserNode<ShelvedChangeList> { private static final Icon PatchIcon = StdFileTypes.PATCH.getIcon(); private static final Icon AppliedPatchIcon = new IconSizeWrapper(Patch_applied, Patch_applied.getIconWidth(), Patch_applied.getIconHeight()) { @Override public void paintIcon(Component c, Graphics g, int x, int y) { GraphicsUtil.paintWithAlpha(g, 0.6f); super.paintIcon(c, g, x, y); } }; private static final Icon DisabledToDeleteIcon = IconUtil.desaturate(AllIcons.Actions.GC); @NotNull private final ShelvedChangeList myList; ShelvedListNode(@NotNull ShelvedChangeList list) { super(list); myList = list; } @NotNull public ShelvedChangeList getList() { return myList; } @Override public void render(@NotNull ChangesBrowserNodeRenderer renderer, boolean selected, boolean expanded, boolean hasFocus) { if (myList.isRecycled() || myList.isDeleted()) { renderer.appendTextWithIssueLinks(myList.DESCRIPTION, SimpleTextAttributes.GRAYED_BOLD_ATTRIBUTES); renderer.setIcon(myList.isMarkedToDelete() || myList.isDeleted() ? DisabledToDeleteIcon : AppliedPatchIcon); } else { renderer.appendTextWithIssueLinks(myList.DESCRIPTION, SimpleTextAttributes.REGULAR_ATTRIBUTES); renderer.setIcon(PatchIcon); } appendCount(renderer); String date = DateFormatUtil.formatPrettyDateTime(myList.DATE); renderer.append(", " + date, SimpleTextAttributes.GRAYED_ATTRIBUTES); } } private static class ShelvedChangeNode extends ChangesBrowserNode<ShelvedWrapper> implements Comparable<ShelvedChangeNode> { @NotNull private final ShelvedWrapper myShelvedChange; @NotNull private final FilePath myFilePath; @Nullable private final String myAdditionalText; protected ShelvedChangeNode(@NotNull ShelvedWrapper shelvedChange, @NotNull FilePath filePath, @Nullable String additionalText) { super(shelvedChange); myShelvedChange = shelvedChange; myFilePath = filePath; myAdditionalText = additionalText; } @Override public void render(@NotNull ChangesBrowserNodeRenderer renderer, boolean selected, boolean expanded, boolean hasFocus) { String path = myShelvedChange.getRequestName(); String directory = StringUtil.defaultIfEmpty(PathUtil.getParentPath(path), "<project root>"); String fileName = StringUtil.defaultIfEmpty(PathUtil.getFileName(path), path); renderer.append(fileName, new SimpleTextAttributes(SimpleTextAttributes.STYLE_PLAIN, myShelvedChange.getFileStatus().getColor())); if (myAdditionalText != null) { renderer.append(spaceAndThinSpace() + myAdditionalText, SimpleTextAttributes.REGULAR_ATTRIBUTES); } if (renderer.isShowFlatten()) { renderer.append(spaceAndThinSpace() + FileUtil.toSystemDependentName(directory), SimpleTextAttributes.GRAYED_ATTRIBUTES); } renderer.setIcon(FileTypeManager.getInstance().getFileTypeByFileName(fileName).getIcon()); } @Override public String getTextPresentation() { return PathUtil.getFileName(myShelvedChange.getRequestName()); } @Override protected boolean isFile() { return true; } @Override public int compareTo(@NotNull ShelvedChangeNode o) { return compareFilePaths(myFilePath, o.myFilePath); } @Nullable @Override public Color getBackgroundColor(@NotNull Project project) { return getBackgroundColorFor(project, myFilePath); } } private class MyContentUpdater extends Update { MyContentUpdater() { super("ShelfContentUpdate"); } @Override public void run() { updateTreeModel(); } @Override public boolean canEat(Update update) { return true; } } }
package de.fernflower.struct.attr; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import de.fernflower.code.CodeConstants; import de.fernflower.modules.decompiler.exps.AnnotationExprent; import de.fernflower.modules.decompiler.exps.ConstExprent; import de.fernflower.modules.decompiler.exps.Exprent; import de.fernflower.modules.decompiler.exps.FieldExprent; import de.fernflower.modules.decompiler.exps.NewExprent; import de.fernflower.struct.consts.ConstantPool; import de.fernflower.struct.consts.PrimitiveConstant; import de.fernflower.struct.gen.FieldDescriptor; import de.fernflower.struct.gen.VarType; public class StructAnnotationAttribute extends StructGeneralAttribute { private List<AnnotationExprent> annotations; public void initContent(ConstantPool pool) { super.initContent(pool); annotations = new ArrayList<AnnotationExprent>(); DataInputStream data = new DataInputStream(new ByteArrayInputStream(info, 2, info.length)); int len = (((info[0] & 0xFF)<<8) | (info[1] & 0xFF)); for(int i=0;i<len;i++) { annotations.add(parseAnnotation(data, pool)); } } public static AnnotationExprent parseAnnotation(DataInputStream data, ConstantPool pool) { try { String classname = pool.getPrimitiveConstant(data.readUnsignedShort()).getString(); VarType cltype = new VarType(classname); int len = data.readUnsignedShort(); List<String> parnames = new ArrayList<String>(); List<Exprent> parvalues = new ArrayList<Exprent>(); for(int i=0;i<len;i++) { parnames.add(pool.getPrimitiveConstant(data.readUnsignedShort()).getString()); parvalues.add(parseAnnotationElement(data, pool)); } return new AnnotationExprent(cltype.value, parnames, parvalues); } catch(IOException ex) { throw new RuntimeException(ex); } } public static Exprent parseAnnotationElement(DataInputStream data, ConstantPool pool) { try { int tag = data.readUnsignedByte(); switch(tag) { case 'e': // enum constant String classname = pool.getPrimitiveConstant(data.readUnsignedShort()).getString(); String constname = pool.getPrimitiveConstant(data.readUnsignedShort()).getString(); FieldDescriptor descr = FieldDescriptor.parseDescriptor(classname); return new FieldExprent(constname, descr.type.value, true, null, descr); case 'c': // class String descriptor = pool.getPrimitiveConstant(data.readUnsignedShort()).getString(); VarType type = FieldDescriptor.parseDescriptor(descriptor).type; String value; switch(type.type) { case CodeConstants.TYPE_OBJECT: value = type.value; break; case CodeConstants.TYPE_BYTE: value = byte.class.getName(); break; case CodeConstants.TYPE_CHAR: value = char.class.getName(); break; case CodeConstants.TYPE_DOUBLE: value = double.class.getName(); break; case CodeConstants.TYPE_FLOAT: value = float.class.getName(); break; case CodeConstants.TYPE_INT: value = int.class.getName(); break; case CodeConstants.TYPE_LONG: value = long.class.getName(); break; case CodeConstants.TYPE_SHORT: value = short.class.getName(); break; case CodeConstants.TYPE_BOOLEAN: value = boolean.class.getName(); break; case CodeConstants.TYPE_VOID: value = void.class.getName(); break; default: throw new RuntimeException("invalid class type: " + type.type); } return new ConstExprent(VarType.VARTYPE_CLASS, value); case '[': // array int len = data.readUnsignedShort(); List<Exprent> lst = new ArrayList<Exprent>(); for(int i=0;i<len;i++) { lst.add(parseAnnotationElement(data, pool)); } VarType newtype; if(lst.isEmpty()) { newtype = new VarType(CodeConstants.TYPE_OBJECT, 1, "java/lang/Object"); } else { VarType eltype = lst.get(0).getExprType(); newtype = new VarType(eltype.type, 1, eltype.value); } NewExprent newexpr = new NewExprent(newtype, new ArrayList<Exprent>()); newexpr.setDirectArrayInit(true); newexpr.setLstArrayElements(lst); return newexpr; case '@': // annotation return parseAnnotation(data, pool); default: PrimitiveConstant cn = pool.getPrimitiveConstant(data.readUnsignedShort()); switch(tag) { case 'B': return new ConstExprent(VarType.VARTYPE_BYTE, cn.value); case 'C': return new ConstExprent(VarType.VARTYPE_CHAR, cn.value); case 'D': return new ConstExprent(VarType.VARTYPE_DOUBLE, cn.value); case 'F': return new ConstExprent(VarType.VARTYPE_FLOAT, cn.value); case 'I': return new ConstExprent(VarType.VARTYPE_INT, cn.value); case 'J': return new ConstExprent(VarType.VARTYPE_LONG, cn.value); case 'S': return new ConstExprent(VarType.VARTYPE_SHORT, cn.value); case 'Z': return new ConstExprent(VarType.VARTYPE_BOOLEAN, cn.value); case 's': return new ConstExprent(VarType.VARTYPE_STRING, cn.value); default: throw new RuntimeException("invalid element type!"); } } } catch(IOException ex) { throw new RuntimeException(ex); } } public List<AnnotationExprent> getAnnotations() { return annotations; } }
package org.jetbrains.idea.maven.project.action; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.startup.StartupManager; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.IconLoader; import com.intellij.openapi.util.Pair; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.projectImport.ProjectImportBuilder; import org.apache.maven.embedder.MavenEmbedder; import org.jetbrains.annotations.Nullable; import org.jetbrains.idea.maven.core.MavenCore; import org.jetbrains.idea.maven.core.MavenCoreSettings; import org.jetbrains.idea.maven.core.MavenFactory; import org.jetbrains.idea.maven.core.MavenLog; import org.jetbrains.idea.maven.core.util.FileFinder; import org.jetbrains.idea.maven.core.util.ProjectUtil; import org.jetbrains.idea.maven.project.*; import org.jetbrains.idea.maven.state.MavenProjectsManager; import javax.swing.*; import java.io.File; import java.util.*; /** * @author Vladislav.Kaznacheev */ public class MavenImportBuilder extends ProjectImportBuilder<MavenProjectModel.Node> implements MavenImportProcessorContext { private final static Icon ICON = IconLoader.getIcon("/images/mavenEmblem.png"); private Project projectToUpdate; private MavenCoreSettings myCoreSettings; private MavenImporterSettings myImporterSettings; private MavenArtifactSettings myArtifactSettings; private VirtualFile importRoot; private Collection<VirtualFile> myFiles; private Map<VirtualFile, Set<String>> myFilesWithProfiles = new HashMap<VirtualFile, Set<String>>(); private MavenImportProcessor myImportProcessor; private boolean openModulesConfigurator; private ArrayList<Pair<File, List<String>>> myResolutionProblems; public String getName() { return ProjectBundle.message("maven.name"); } public Icon getIcon() { return ICON; } public void cleanup() { super.cleanup(); myImportProcessor = null; importRoot = null; projectToUpdate = null; } @Override public boolean validate(Project current, Project dest) { try { myResolutionProblems = new ArrayList<Pair<File, List<String>>>(); myImportProcessor.resolve(dest, getAllProfiles(), myResolutionProblems); if (ApplicationManager.getApplication().isHeadlessEnvironment() && !myResolutionProblems.isEmpty()) { logResolutionProblems(); return false; } } catch (MavenException e) { Messages.showErrorDialog(dest, e.getMessage(), getTitle()); return false; } catch (CanceledException e) { return false; } return true; } private void logResolutionProblems() { String formatted = "There were resolution problems:"; for (Pair<File, List<String>> problems : myResolutionProblems) { formatted += "\n" + problems.first; for (String message : problems.second) { formatted += "\n\t" + message; } formatted += "\n"; } MavenLog.LOG.error(formatted); } public void commit(final Project project) { myImportProcessor.commit(project, getAllProfiles()); MavenProjectsManager.getInstance(project).setDoesNotRequireSynchronization(); MavenProjectsManager.getInstance(project).setMavenProject(); StartupManager.getInstance(project).registerPostStartupActivity(new Runnable() { public void run() { MavenImportToolWindow toolWindow = new MavenImportToolWindow(project, ProjectBundle.message("maven.import")); toolWindow.displayResolutionProblems(myResolutionProblems); } }); MavenProjectsManager manager = MavenProjectsManager.getInstance(project); manager.setOriginalFiles(myFiles); if (!myFilesWithProfiles.isEmpty()) { for (Map.Entry<VirtualFile,Set<String>> each : myFilesWithProfiles.entrySet()) { manager.setActiveProfiles(each.getKey(), each.getValue()); } } project.getComponent(MavenWorkspaceSettingsComponent.class).getState().myImporterSettings = getImporterPreferences(); project.getComponent(MavenWorkspaceSettingsComponent.class).getState().myArtifactSettings = getArtifactPreferences(); project.getComponent(MavenCore.class).loadState(myCoreSettings); } public Project getUpdatedProject() { return getProjectToUpdate(); } public VirtualFile getRootDirectory() { return getImportRoot(); } public boolean setRootDirectory(final String root) throws ConfigurationException { myFiles = null; myFilesWithProfiles.clear(); myImportProcessor = null; importRoot = FileFinder.refreshRecursively(root); if (getImportRoot() == null) return false; return runConfigurationProcess(ProjectBundle.message("maven.scanning.projects"), new Progress.Process() { public void run(Progress p) throws MavenException, CanceledException { p.setText(ProjectBundle.message("maven.locating.files")); myFiles = FileFinder.findPomFiles(getImportRoot().getChildren(), getImporterPreferences().isLookForNested(), p.getIndicator(), new ArrayList<VirtualFile>()); myFilesWithProfiles = collectProfiles(myFiles); if (myFilesWithProfiles.isEmpty()) { createImportProcessor(p); } p.setText2(""); } }); } private Map<VirtualFile, Set<String>> collectProfiles(Collection<VirtualFile> files) throws MavenException { Map<VirtualFile, Set<String>> result = new HashMap<VirtualFile, Set<String>>(); try { MavenEmbedder e = MavenFactory.createEmbedderForRead(getCoreState()); MavenProjectReader r = new MavenProjectReader(e); for (VirtualFile f : files) { Set<String> profiles = new LinkedHashSet<String>(); ProjectUtil.collectProfileIds(r.readModel(f.getPath()), profiles); if (!profiles.isEmpty()) result.put(f, profiles); } MavenFactory.releaseEmbedder(e); } catch (MavenException ignore) { } return result; } public List<String> getAllProfiles() { Set<String> result = new LinkedHashSet<String>(); for (Set<String> each : myFilesWithProfiles.values()) { result.addAll(each); } return new ArrayList<String>(result); } public boolean setSelectedProfiles(List<String> profiles) throws ConfigurationException { myImportProcessor = null; for (Map.Entry<VirtualFile,Set<String>> each : myFilesWithProfiles.entrySet()) { each.getValue().retainAll(profiles); } return runConfigurationProcess(ProjectBundle.message("maven.scanning.projects"), new Progress.Process() { public void run(Progress p) throws MavenException, CanceledException { createImportProcessor(p); p.setText2(""); } }); } private boolean runConfigurationProcess(String message, Progress.Process p) throws ConfigurationException { try { Progress.run(null, message, p); } catch (MavenException e) { throw new ConfigurationException(e.getMessage()); } catch (CanceledException e) { return false; } return true; } private void createImportProcessor(Progress p) throws MavenException, CanceledException { myImportProcessor = new MavenImportProcessor(getProject(), getCoreState(), getImporterPreferences(), getArtifactPreferences()); myImportProcessor.createMavenProjectModel(myFiles, new HashMap<VirtualFile, Module>(), getAllProfiles(), p); } public List<MavenProjectModel.Node> getList() { return myImportProcessor.getMavenProjectModel().getRootProjects(); } public boolean isMarked(final MavenProjectModel.Node element) { return true; } public void setList(List<MavenProjectModel.Node> nodes) throws ConfigurationException { for (MavenProjectModel.Node node : myImportProcessor.getMavenProjectModel().getRootProjects()) { node.setIncluded(nodes.contains(node)); } myImportProcessor.createMavenToIdeaMapping(); } public boolean isOpenProjectSettingsAfter() { return openModulesConfigurator; } public void setOpenProjectSettingsAfter(boolean on) { openModulesConfigurator = on; } public MavenCoreSettings getCoreState() { if (myCoreSettings == null) { myCoreSettings = getProject().getComponent(MavenCore.class).getState().clone(); } return myCoreSettings; } public MavenImporterSettings getImporterPreferences() { if (myImporterSettings == null) { myImporterSettings = getProject().getComponent(MavenWorkspaceSettingsComponent.class).getState() .myImporterSettings.clone(); } return myImporterSettings; } private MavenArtifactSettings getArtifactPreferences() { if (myArtifactSettings == null) { myArtifactSettings = getProject().getComponent(MavenWorkspaceSettingsComponent.class).getState() .myArtifactSettings.clone(); } return myArtifactSettings; } private Project getProject() { return isUpdate() ? getProjectToUpdate() : ProjectManager.getInstance().getDefaultProject(); } public void setFiles(final Collection<VirtualFile> files) { myFiles = files; } @Nullable public Project getProjectToUpdate() { if (projectToUpdate == null) { projectToUpdate = getCurrentProject(); } return projectToUpdate; } @Nullable public VirtualFile getImportRoot() { if (importRoot == null && isUpdate()) { final Project project = getProjectToUpdate(); assert project != null; importRoot = project.getBaseDir(); } return importRoot; } public String getSuggestedProjectName() { final List<MavenProjectModel.Node> list = myImportProcessor.getMavenProjectModel().getRootProjects(); if(list.size()==1){ return list.get(0).getMavenId().artifactId; } return null; } }
package org.eclipse.xtext.conversion.impl; import org.eclipse.emf.ecore.EDataType; import org.eclipse.xtext.conversion.IValueConverter; import org.eclipse.xtext.conversion.ValueConverterException; import org.eclipse.xtext.parsetree.AbstractNode; /** * A value converter that delegates to the {@link org.eclipse.emf.ecore.EFactory} of a {@link EDataType}. * * @author koehnlein - Initial contribution and API */ public class EFactoryValueConverter implements IValueConverter<Object> { private final EDataType dataType; public EFactoryValueConverter(EDataType dataType) { this.dataType = dataType; } public String toString(Object value) { return dataType.getEPackage().getEFactoryInstance().convertToString(dataType, value); } public Object toValue(String string, AbstractNode node) throws ValueConverterException { try { return dataType.getEPackage().getEFactoryInstance().createFromString(dataType, string); } catch (Exception exc) { throw new ValueConverterException("Error converting string to value", node, exc); } } }
package com.github.rubensousa.previewseekbar; import android.annotation.TargetApi; import android.content.Context; import android.content.res.ColorStateList; import android.graphics.drawable.Drawable; import android.os.Build; import android.support.annotation.ColorInt; import android.support.annotation.ColorRes; import android.support.v4.content.ContextCompat; import android.support.v4.graphics.drawable.DrawableCompat; import android.util.AttributeSet; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.RelativeLayout; public class PreviewSeekBarLayout extends RelativeLayout { private PreviewDelegate delegate; private PreviewSeekBar seekBar; private FrameLayout previewFrameLayout; private View morphView; private View frameView; private boolean firstLayout = true; private int tintColor; public PreviewSeekBarLayout(Context context) { super(context); init(context, null); } public PreviewSeekBarLayout(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs); } public PreviewSeekBarLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs); } private void init(Context context, AttributeSet attrs) { TypedValue outValue = new TypedValue(); getContext().getTheme().resolveAttribute(R.attr.colorAccent, outValue, true); tintColor = ContextCompat.getColor(context, outValue.resourceId); // Create morph view morphView = new View(getContext()); morphView.setBackgroundResource(R.drawable.previewseekbar_morph); // Create frame view for the circular reveal frameView = new View(getContext()); delegate = new PreviewDelegate(this); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); if (getWidth() == 0 || getHeight() == 0) { return; } else if (firstLayout) { // Check if we have the proper views if (!checkChilds()) { throw new IllegalStateException("You need to add a PreviewSeekBar" + "and a FrameLayout as direct childs"); } // Set proper seek bar margins setupSeekbarMargins(); // Setup colors for the morph view and frame view setupColors(); delegate.setup(); // Setup morph view ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(0, 0); layoutParams.width = getResources() .getDimensionPixelSize(R.dimen.previewseekbar_indicator_width); layoutParams.height = layoutParams.width; addView(morphView, layoutParams); // Add frame view to the preview layout FrameLayout.LayoutParams frameLayoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); frameLayoutParams.gravity = Gravity.CENTER; previewFrameLayout.addView(frameView, frameLayoutParams); firstLayout = false; } } public boolean isShowingPreview() { return delegate.isShowing(); } public void showPreview() { delegate.show(); } public void hidePreview() { delegate.hide(); } public FrameLayout getPreviewFrameLayout() { return previewFrameLayout; } public PreviewSeekBar getSeekBar() { return seekBar; } View getFrameView() { return frameView; } View getMorphView() { return morphView; } public void setTintColor(@ColorInt int color) { tintColor = color; Drawable drawable = DrawableCompat.wrap(morphView.getBackground()); DrawableCompat.setTint(drawable, color); morphView.setBackground(drawable); frameView.setBackgroundColor(color); } public void setTintColorResource(@ColorRes int color) { setTintColor(ContextCompat.getColor(getContext(), color)); } private void setupColors() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { ColorStateList list = seekBar.getThumbTintList(); if (list != null) { tintColor = list.getDefaultColor(); } } setTintColor(tintColor); } /** * Align seekbar thumb with the frame layout center */ private void setupSeekbarMargins() { LayoutParams layoutParams = (LayoutParams) seekBar.getLayoutParams(); layoutParams.rightMargin = (int) (previewFrameLayout.getWidth() / 2 - seekBar.getThumb().getIntrinsicWidth() * 0.9f); layoutParams.leftMargin = layoutParams.rightMargin; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { layoutParams.setMarginEnd(layoutParams.leftMargin); layoutParams.setMarginStart(layoutParams.leftMargin); } seekBar.setLayoutParams(layoutParams); requestLayout(); invalidate(); } private boolean checkChilds() { int childs = getChildCount(); if (childs < 2) { return false; } boolean hasSeekbar = false; boolean hasFrameLayout = false; for (int i = 0; i < getChildCount(); i++) { View child = getChildAt(i); if (child instanceof PreviewSeekBar) { hasSeekbar = true; seekBar = (PreviewSeekBar) child; } else if (child instanceof FrameLayout) { previewFrameLayout = (FrameLayout) child; hasFrameLayout = true; } if (hasSeekbar && hasFrameLayout) { return true; } } return hasSeekbar && hasFrameLayout; } }
package gov.nih.nci.cabig.caaers.domain; import gov.nih.nci.cabig.ctms.domain.AbstractMutableDomainObject; import gov.nih.nci.cabig.ctms.domain.DomainObjectTools; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.OrderBy; import org.hibernate.annotations.Parameter; import org.hibernate.annotations.Where; /** * @author Krikor Krumlian */ @Entity @Table(name = "participant_assignments") @GenericGenerator(name = "id-generator", strategy = "native", parameters = { @Parameter(name = "sequence", value = "seq_participant_assignments_id") }) @Where(clause = "load_status > 0") public class StudyParticipantAssignment extends AbstractMutableDomainObject { private Participant participant; private StudySite studySite; private Date dateOfEnrollment; private List<ExpeditedAdverseEventReport> aeReports; private List<RoutineAdverseEventReport> aeRoutineReports; private List<AdverseEventReportingPeriod> reportingPeriods; private List<LabViewerLab> labViewerLabs; private Integer loadStatus = LoadStatus.COMPLETE.getCode(); private String studySubjectIdentifier; private Date startDateOfFirstCourse; public StudyParticipantAssignment(Participant participant, StudySite studySite) { this.participant = participant; this.studySite = studySite; this.dateOfEnrollment = new Date(); } public StudyParticipantAssignment() { } // //// LOGIC public void addReport(ExpeditedAdverseEventReport report) { report.setAssignment(this); getAeReports().add(report); } public void addRoutineReport(RoutineAdverseEventReport routineReport) { routineReport.setAssignment(this); getAeRoutineReports().add(routineReport); } public void addReportingPeriod(AdverseEventReportingPeriod reportingPeriod) { //reportingPeriod.setAssignment(this); getReportingPeriods().add(reportingPeriod); } // //// BEAN PROPERTIES public void setStudySite(StudySite studySite) { this.studySite = studySite; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "study_site_id") @Cascade( { CascadeType.LOCK }) public StudySite getStudySite() { return studySite; } public void setParticipant(Participant participant) { this.participant = participant; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "participant_id") @Cascade( { CascadeType.LOCK }) public Participant getParticipant() { return participant; } public void setDateOfEnrollment(Date dateOfEnrollment) { this.dateOfEnrollment = dateOfEnrollment; } @Column(name = "date_of_enrollment") public Date getDateOfEnrollment() { return dateOfEnrollment; } @OneToMany(mappedBy = "assignment") public List<ExpeditedAdverseEventReport> getAeReports() { if (aeReports == null) aeReports = new ArrayList<ExpeditedAdverseEventReport>(); return aeReports; } public void setAeReports(List<ExpeditedAdverseEventReport> aeReports) { this.aeReports = aeReports; } @OneToMany(mappedBy = "assignment") public List<RoutineAdverseEventReport> getAeRoutineReports() { if (aeRoutineReports == null) aeRoutineReports = new ArrayList<RoutineAdverseEventReport>(); return aeRoutineReports; } public void setAeRoutineReports(List<RoutineAdverseEventReport> aeRoutineReports) { this.aeRoutineReports = aeRoutineReports; } @OneToMany(mappedBy = "assignment") @OrderBy(clause="startDate desc") public List<AdverseEventReportingPeriod> getReportingPeriods() { if(reportingPeriods == null) reportingPeriods = new ArrayList<AdverseEventReportingPeriod>(); return reportingPeriods; } public void setReportingPeriods(List<AdverseEventReportingPeriod> reportingPeriods) { this.reportingPeriods = reportingPeriods; } @OneToMany(mappedBy = "assignment") @OrderBy(clause="lab_date desc") public List<LabViewerLab> getLabViewerLabs() { if(labViewerLabs == null) labViewerLabs = new ArrayList<LabViewerLab>(); return labViewerLabs; } public void setLabViewerLabs(List<LabViewerLab> labViewerLabs) { this.labViewerLabs = labViewerLabs; } public Integer getLoadStatus() { return loadStatus; } public void setLoadStatus(Integer loadStatus) { this.loadStatus = loadStatus; } @Column(name="first_course_date") public Date getStartDateOfFirstCourse() { return startDateOfFirstCourse; } public void setStartDateOfFirstCourse(Date startDateOfFirstCourse) { this.startDateOfFirstCourse = startDateOfFirstCourse; } // //// OBJECT METHODS @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final StudyParticipantAssignment that = (StudyParticipantAssignment) o; if (dateOfEnrollment != null ? !dateOfEnrollment.equals(that.dateOfEnrollment) : that.dateOfEnrollment != null) return false; if (studySite != null ? !studySite.equals(that.studySite) : that.studySite != null) return false; // Participant#equals calls this method, so we can't use it here if (!DomainObjectTools.equalById(participant, that.participant)) return false; return true; } @Override public int hashCode() { int result; result = (studySite != null ? studySite.hashCode() : 0); result = 29 * result + (participant != null ? participant.hashCode() : 0); result = 29 * result + (dateOfEnrollment != null ? dateOfEnrollment.hashCode() : 0); return result; } public String getStudySubjectIdentifier() { return studySubjectIdentifier; } public void setStudySubjectIdentifier(final String studySubjectIdentifier) { this.studySubjectIdentifier = studySubjectIdentifier; } }
package org.protempa.query.handler.xml; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.protempa.FinderException; import org.protempa.KnowledgeSource; import org.protempa.ProtempaException; import org.protempa.proposition.Proposition; import org.protempa.proposition.UniqueIdentifier; import org.protempa.query.handler.QueryResultsHandler; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Text; public class XmlQueryResultsHandler implements QueryResultsHandler { private final Map<String, String> order; private KnowledgeSource knowledgeSource; private final String initialProposition; private final Writer out; public XmlQueryResultsHandler(Writer writer, Map<String, String> propOrder, String initialProp) { this.out = writer; this.order = propOrder; this.initialProposition = initialProp; } @Override public void finish() throws FinderException { try { this.out.write("</patients>"); this.out.flush(); } catch (IOException ioe) { throw new FinderException(ioe); } } @Override public void init(KnowledgeSource knowledgeSource) throws FinderException { this.knowledgeSource = knowledgeSource; try { this.out.write("<patients>"); this.out.flush(); } catch (IOException ioe) { throw new FinderException(ioe); } } private List<Proposition> createReferenceList(List<UniqueIdentifier> uids, Map<UniqueIdentifier, Proposition> references) { List<Proposition> propositions = new ArrayList<Proposition>(); if (uids != null) { for (UniqueIdentifier uid : uids) { Proposition refProp = references.get(uid); if (refProp != null) { propositions.add(refProp); } } } return propositions; } private List<Proposition> filterHandled(List<Proposition> propositions, Set<UniqueIdentifier> handled) { List<Proposition> filtered = new ArrayList<Proposition>(); if (propositions != null) { for (Proposition proposition : propositions) { if (!handled.contains(proposition.getUniqueIdentifier())) { filtered.add(proposition); } } } return filtered; } private Element handleProperties( Map<String, Map<String, String>> properties, Document document) { Element propertiesElem = document.createElement("properties"); for (String propertyName : properties.keySet()) { Map<String, String> m = properties.get(propertyName); Element propertyElem = document.createElement("property"); propertyElem.setAttribute("name", propertyName); for (String s : m.keySet()) { Element vElem = document.createElement(s); Text vText = document.createTextNode(m.get(s)); vElem.appendChild(vText); propertyElem.appendChild(vElem); } propertiesElem.appendChild(propertyElem); } return propertiesElem; } private List<Element> handleValues(Map<String, String> values, Document document) { List<Element> valueElems = new ArrayList<Element>(); for (String key : values.keySet()) { Element valElem = document.createElement(key); Text valTextElem = document.createTextNode(values.get(key)); valElem.appendChild(valTextElem); valueElems.add(valElem); } return valueElems; } private List<String> orderReferences(Proposition proposition) { List<String> orderedRefs = new ArrayList<String>(); String firstReference = this.order.get(proposition.getId()); for (String refName : proposition.getReferenceNames()) { if (refName.equals(firstReference)) { orderedRefs.add(0, refName); } else { orderedRefs.add(refName); } } return orderedRefs; } private Element handleReferences(Set<UniqueIdentifier> handled, Map<Proposition, List<Proposition>> derivations, Map<UniqueIdentifier, Proposition> references, Proposition proposition, XmlPropositionVisitor visitor, Document document) throws ProtempaException { Element referencesElem = document.createElement("references"); List<String> orderedReferences = orderReferences(proposition); Logger logger = Util.logger(); if (logger.isLoggable(Level.FINEST)) { logger.log(Level.FINEST, "Ordered References for proposition {0}: {1}", new Object[] { proposition.getId(), orderedReferences }); } if (orderedReferences != null) { for (String refName : orderedReferences) { logger.log(Level.FINEST, "Processing reference {0}", refName); List<UniqueIdentifier> uids = proposition .getReferences(refName); logger.log(Level.FINEST, "Total unique identifiers: {0}", uids.size()); logger.log(Level.FINEST, "UniqueIdentifiers: {0}", uids); List<Proposition> refProps = createReferenceList(uids, references); logger.log(Level.FINEST, "Total referred propositions: {0}", refProps.size()); if (!refProps.isEmpty()) { List<Proposition> filteredReferences = filterHandled( refProps, handled); logger.log(Level.FINEST, "Total filtered referred propositions: {0}", filteredReferences.size()); if (!filteredReferences.isEmpty()) { Element refElem = document.createElement("reference"); refElem.setAttribute("name", refName); for (Proposition refProp : filteredReferences) { Element e = handleProposition(handled, derivations, references, refProp, visitor, document); if (e != null) { refElem.appendChild(e); } } referencesElem.appendChild(refElem); } else { logger.log( Level.FINEST, "Skipping reference {0} because all propositions were handled", refName); } } } } return referencesElem; } private Element handleDerivations(Set<UniqueIdentifier> handled, Map<Proposition, List<Proposition>> derivations, Map<UniqueIdentifier, Proposition> references, Proposition proposition, XmlPropositionVisitor visitor, Document document) throws ProtempaException { Element derivationsElem = document.createElement("derivations"); List<Proposition> derivedPropositions = filterHandled( derivations.get(proposition), handled); if (derivedPropositions != null) { for (Proposition derivedProposition : derivedPropositions) { Element derivedElem = handleProposition(handled, derivations, references, derivedProposition, visitor, document); if (derivedElem != null) { derivationsElem.appendChild(derivedElem); } } } return derivationsElem; } private Element handleProposition(Set<UniqueIdentifier> handled, Map<Proposition, List<Proposition>> derivations, Map<UniqueIdentifier, Proposition> references, Proposition proposition, XmlPropositionVisitor visitor, Document document) throws ProtempaException { if (!handled.contains(proposition.getUniqueIdentifier())) { Util.logger().log( Level.FINEST, "Processing proposition {0} with unique id {1}", new Object[] { proposition.getId(), proposition.getUniqueIdentifier() }); // create a new set to pass down to the "children" (references and // derivations) of this proposition Set<UniqueIdentifier> tempHandled = new HashSet<UniqueIdentifier>( handled); tempHandled.add(proposition.getUniqueIdentifier()); Element propElem = document.createElement("proposition"); propElem.setAttribute("id", proposition.getId()); proposition.acceptChecked(visitor); for (Element elem : handleValues(visitor.getPropositionValues(), document)) { propElem.appendChild(elem); } propElem.appendChild(handleProperties( visitor.getPropositionProperties(), document)); visitor.clear(); propElem.appendChild(handleReferences(tempHandled, derivations, references, proposition, visitor, document)); propElem.appendChild(handleDerivations(tempHandled, derivations, references, proposition, visitor, document)); return propElem; } else { Util.logger().log(Level.FINEST, "Skipping proposition {0}", proposition.getId()); return null; } } private void printDocument(Document doc) throws IOException, TransformerException { TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty( "{http://xml.apache.org/xslt}indent-amount", "4"); transformer.transform(new DOMSource(doc), new StreamResult(this.out)); this.out.flush(); } private Proposition findInitialProposition(String propName, List<Proposition> props) { for (Proposition prop : props) { if (prop.getId().equals(propName)) { return prop; } } return null; } @Override public void handleQueryResult(String key, List<Proposition> propositions, Map<Proposition, List<Proposition>> derivations, Map<UniqueIdentifier, Proposition> references) throws FinderException { try { Set<UniqueIdentifier> handled = new HashSet<UniqueIdentifier>(); XmlPropositionVisitor visitor = new XmlPropositionVisitor( this.knowledgeSource); Document document = DocumentBuilderFactory.newInstance() .newDocumentBuilder().newDocument(); Element rootNode = document.createElement("patient"); rootNode.setAttribute("id", key); if (this.initialProposition != null) { Proposition firstProp = findInitialProposition( this.initialProposition, propositions); if (firstProp != null) { Element elem = handleProposition(handled, derivations, references, firstProp, visitor, document); if (null != elem) { rootNode.appendChild(elem); } } else { Util.logger() .log(Level.SEVERE, "Initial proposition {0} not found in proposition list", this.initialProposition); } } else { Util.logger() .log(Level.WARNING, "No initial proposition defined, printing all propositions"); for (Proposition proposition : propositions) { Element elem = handleProposition(handled, derivations, references, proposition, visitor, document); if (null != elem) { rootNode.appendChild(elem); } } } document.appendChild(rootNode); printDocument(document); } catch (IOException e) { Util.logger().log(Level.SEVERE, e.getMessage(), e); throw new FinderException(e); } catch (ProtempaException e) { Util.logger().log(Level.SEVERE, e.getMessage(), e); throw new FinderException(e); } catch (ParserConfigurationException e) { Util.logger().log(Level.SEVERE, e.getMessage(), e); throw new FinderException(e); } catch (TransformerException e) { Util.logger().log(Level.SEVERE, e.getMessage(), e); throw new FinderException(e); } } }
package de.volzo.miscreen; import de.volzo.miscreen.arbitraryBoundingBox.ArbitrarilyOrientedBoundingBox; import java.util.ArrayList; import java.util.List; import android.os.Handler; import org.ejml.simple.SimpleMatrix; import java.io.IOException; import java.util.Map; import java.util.Properties; import de.volzo.miscreen.arbitraryBoundingBox.MIPoint2D; import fi.iki.elonen.NanoHTTPD; public class Host { private static Host mHost = null; private Host() { } private Nano nano; public static Host getInstance() { if (mHost == null) { mHost = new Host(); } return mHost; } public static Boolean exists() { return mHost != null; } public static void destroy() { if (mHost != null) { mHost = null; } } // input: transformation matrices // matrices from ARToolkit are column-major (elements are listed column-wise) // --> use new SimpleMatrix(4, 4, false, <<arToolkitArray>>); private static ArbitrarilyOrientedBoundingBox getAOBB(float[] hostFArray, List<float[]> fList) { double[] hostFArrayDouble = floatArray2doubleArray(hostFArray); SimpleMatrix hostF = new SimpleMatrix(3, 3, false, hostFArrayDouble); // create projetion matrix to project from 4x4 (homogeneous 3D space) to 3x3 (homogeneous 2D space) SimpleMatrix p = new SimpleMatrix(4, 4, true, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1); SimpleMatrix originVector = new SimpleMatrix(3, 1, true, 0, 0, 0); List<MIPoint2D> cornerPoints = new ArrayList<>(); for (float[] clientFArray : fList) { double[] clientFArrayDouble = floatArray2doubleArray(clientFArray); SimpleMatrix clientF = new SimpleMatrix(3, 3, false, clientFArrayDouble); // TODO: calc 2D points from fMatrices SimpleMatrix relativeF = getRelativeTransformation(hostF, clientF); // project tranformation into xy-plane SimpleMatrix planarF = p.mult(relativeF); // transform point from origin SimpleMatrix planarPoint = planarF.mult(originVector); int pointX = (int) Math.round(planarF.get(0)); int pointY = (int) Math.round(planarF.get(1)); MIPoint2D point = new MIPoint2D(pointX, pointY); cornerPoints.add(point); } MIPoint2D[] cornerArray = cornerPoints.toArray(new MIPoint2D[cornerPoints.size()]); ArbitrarilyOrientedBoundingBox aobb = new ArbitrarilyOrientedBoundingBox(cornerArray); return aobb; } private static double[] floatArray2doubleArray(float[] clientFArray) { double[] resultArray = new double[clientFArray.length]; for (int i = 0; i < clientFArray.length; i++) { resultArray[i] = clientFArray[i]; } return resultArray; } private static SimpleMatrix getRelativeTransformation(SimpleMatrix fromT, SimpleMatrix toT) { SimpleMatrix relativeT = fromT.mult(toT.invert()); return relativeT; } public void init() throws Exception { nano = new Nano(); } private class Nano extends NanoHTTPD { private final static int PORT = 80; public Nano() throws IOException { super(PORT); //start(NanoHTTPD.SOCKET_READ_TIMEOUT, false); } public Response serve(String uri, String method, Properties header, Properties parms, Properties files) { final StringBuilder buf = new StringBuilder(); for (Map.Entry<Object, Object> kv : header.entrySet()) buf.append(kv.getKey() + " : " + kv.getValue() + "\n"); Handler handler = new Handler(); handler.post(new Runnable() { @Override public void run() { System.out.println(buf); } }); final String html = "<html><head><head><body><h1>Hello, World</h1></body></html>"; return new NanoHTTPD.Response(new Response.IStatus() { @Override public int getRequestStatus() { return 400; } @Override public String getDescription() { return null; } }, MIME_HTML, html); } } }
package uk.org.taverna.scufl2.api.core; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.TreeSet; import java.util.UUID; import uk.org.taverna.scufl2.api.common.AbstractNamedChild; import uk.org.taverna.scufl2.api.common.Child; import uk.org.taverna.scufl2.api.common.NamedSet; import uk.org.taverna.scufl2.api.common.Ported; import uk.org.taverna.scufl2.api.common.Visitor; import uk.org.taverna.scufl2.api.common.WorkflowBean; import uk.org.taverna.scufl2.api.container.WorkflowBundle; import uk.org.taverna.scufl2.api.port.InputWorkflowPort; import uk.org.taverna.scufl2.api.port.OutputWorkflowPort; /** * A <code>Workflow</code> is a set of {@link Processor}s and {@link DataLink}s between the * <code>Processor</code>s. <code>Workflow</code>s may also have input and output ports. * * @author Alan R Williams */ public class Workflow extends AbstractNamedChild implements Child<WorkflowBundle>, Ported { public static final URI WORKFLOW_ROOT = URI.create("http://ns.taverna.org.uk/2010/workflow/"); public static URI generateIdentifier() { return WORKFLOW_ROOT.resolve(UUID.randomUUID().toString() + "/"); } private final TreeSet<DataLink> dataLinks = new TreeSet<DataLink>(); private final TreeSet<ControlLink> controlLinks = new TreeSet<ControlLink>(); private final NamedSet<InputWorkflowPort> inputPorts = new NamedSet<InputWorkflowPort>(); private final NamedSet<OutputWorkflowPort> outputPorts = new NamedSet<OutputWorkflowPort>(); private final NamedSet<Processor> processors = new NamedSet<Processor>(); private URI workflowIdentifier; private WorkflowBundle parent; /** * Constructs a <code>Workflow</code> with a name based on a random UUID. */ public Workflow() { setWorkflowIdentifier(generateIdentifier()); String workflowId = WORKFLOW_ROOT.relativize(getWorkflowIdentifier()).toASCIIString(); setName("wf-" + workflowId); } @Override public boolean accept(Visitor visitor) { if (visitor.visitEnter(this)) { List<Iterable<? extends WorkflowBean>> children = new ArrayList<Iterable<? extends WorkflowBean>>(); children.add(getInputPorts()); children.add(getOutputPorts()); children.add(getProcessors()); children.add(getDataLinks()); children.add(getControlLinks()); outer: for (Iterable<? extends WorkflowBean> it : children) { for (WorkflowBean bean : it) { if (!bean.accept(visitor)) { break outer; } } } } return visitor.visitLeave(this); } /** * Returns the <code>ControlLink</code>s. * * If there are no <code>ControlLink</code>s an empty set is returned. * * @return the <code>ControlLink</code>s */ public Set<ControlLink> getControlLinks() { return controlLinks; } /** * Returns the <code>DataLink</code>s. * * If there are no <code>DataLink</code>s an empty set is returned. * * @return the <code>DataLink</code>s. */ public Set<DataLink> getDataLinks() { return dataLinks; } /** * Returns the <code>InputWorkflowPort</code>s. * * If there are no <code>InputWorkflowPort</code>s an empty set is returned. * * @return the <code>InputWorkflowPort</code>s. */ @Override public NamedSet<InputWorkflowPort> getInputPorts() { return inputPorts; } /** * Returns the <code>OutputWorkflowPort</code>s. * * If there are no <code>OutputWorkflowPort</code>s an empty set is returned. * * @return the <code>OutputWorkflowPort</code>s. */ @Override public NamedSet<OutputWorkflowPort> getOutputPorts() { return outputPorts; } @Override public WorkflowBundle getParent() { return parent; } /** * Returns the <code>Processor</code>s. * * If there are no <code>Processor</code>s an empty set is returned. * * @return the <code>Processor</code>s. */ public NamedSet<Processor> getProcessors() { return processors; } /** * Returns the workflow identifier. * <p> * The the default identifier is {@value #WORKFLOW_ROOT} plus a random UUID. * @see {@link #setWorkflowIdentifier(URI)} * * @return the workflow identifier */ public URI getWorkflowIdentifier() { return workflowIdentifier; } /** * Set the <code>ControlLink</code>s to be the contents of the specified set. * <p> * <code>ControlLink</code>s can be added by using {@link #getControlLinks()}.add(controlLink). * * @param controlLinks the <code>ControlLink</code>s. <strong>Must not</strong> be null */ public void setControlLinks(Set<ControlLink> controlLinks) { this.controlLinks.clear(); this.controlLinks.addAll(controlLinks); } /** * Set the <code>DataLink</code>s to be the contents of the specified set. * <p> * <code>DataLink</code>s can be added by using {@link #getDataLinks()}.add(dataLink). * * @param dataLinks the <code>DataLink</code>s. <strong>Must not</strong> be null */ public void setDataLinks(Set<DataLink> dataLinks) { dataLinks.clear(); dataLinks.addAll(dataLinks); } /** * Set the <code>InputWorkflowPort</code>s to be the contents of the specified set. * <p> * <code>InputWorkflowPort</code>s can be added by using {@link #getInputWorkflowPorts()}.add(inputPort). * * @param inputPorts the <code>InputWorkflowPort</code>s. <strong>Must not</strong> be null */ public void setInputPorts(Set<InputWorkflowPort> inputPorts) { this.inputPorts.clear(); for (InputWorkflowPort inputPort : inputPorts) { inputPort.setParent(this); } } /** * Set the <code>OutputWorkflowPort</code>s to be the contents of the specified set. * <p> * <code>OutputWorkflowPort</code>s can be added by using {@link #getOutputWorkflowPorts()}.add(outputPort). * * @param outputPorts the <code>OutputWorkflowPort</code>s. <strong>Must not</strong> be null */ public void setOutputPorts(Set<OutputWorkflowPort> outputPorts) { this.outputPorts.clear(); for (OutputWorkflowPort outputPort : outputPorts) { outputPort.setParent(this); } } @Override public void setParent(WorkflowBundle parent) { if (this.parent != null && this.parent != parent) { this.parent.getWorkflows().remove(this); } this.parent = parent; if (parent != null) { parent.getWorkflows().add(this); } } /** * Set the <code>Processor</code>s to be the contents of the specified set. * <p> * <code>Processor</code>s can be added by using {@link #getProcessors()}.add(processor). * * @param processors the <code>Processor</code>s. <strong>Must not</strong> be null */ public void setProcessors(Set<Processor> processors) { this.processors.clear(); for (Processor processor : processors) { processor.setParent(this); } } /** * Sets the workflow identifier. * * @param workflowIdentifier the workflow identifier */ public void setWorkflowIdentifier(URI workflowIdentifier) { this.workflowIdentifier = workflowIdentifier; } @Override public String toString() { final int maxLen = 6; return "Workflow [getName()=" + getName() + ", getDatalinks()=" + (getDataLinks() != null ? toString(getDataLinks(), maxLen) : null) + ", getInputPorts()=" + (getInputPorts() != null ? toString(getInputPorts(), maxLen) : null) + ", getOutputPorts()=" + (getOutputPorts() != null ? toString(getOutputPorts(), maxLen) : null) + ", getProcessors()=" + (getProcessors() != null ? toString(getProcessors(), maxLen) : null) + "]"; } private String toString(Collection<?> collection, int maxLen) { StringBuilder builder = new StringBuilder(); builder.append("["); int i = 0; for (Iterator<?> iterator = collection.iterator(); iterator.hasNext() && i < maxLen; i++) { if (i > 0) { builder.append(", "); } builder.append(iterator.next()); } builder.append("]"); return builder.toString(); } }
package org.project.openbaton.sdk.api.util; import com.google.gson.*; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.JsonNode; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.http.exceptions.UnirestException; import org.apache.commons.codec.binary.Base64; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.project.openbaton.sdk.api.exception.SDKException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.Serializable; import java.lang.reflect.Array; import java.lang.reflect.Type; import java.net.HttpURLConnection; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * OpenBaton api request request abstraction for all requester. Shares common data and methods. */ public abstract class RestRequest { private Logger log = LoggerFactory.getLogger(this.getClass()); protected final String baseUrl; // protected final String url; protected Gson mapper; private String username; private String password; private String authStr = "openbatonOSClient" + ":" + "secret"; private String encoding = Base64.encodeBase64String(authStr.getBytes()); private final String provider; private String token = null; private String bearerToken = null; /** * Create a request with a given url path */ public RestRequest(String username, String password, final String nfvoIp, String nfvoPort, String path, String version) { this.baseUrl = "http://" + nfvoIp + ":" + nfvoPort + "/api/v" + version + path; this.provider = "http://" + nfvoIp + ":" + nfvoPort + "/oauth/token"; this.username = username; this.password = password; GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { return new Date(json.getAsJsonPrimitive().getAsLong()); } }); this.mapper = builder.create(); } /** * * @param id: the id of the object * @return the created object * @throws SDKException */ public String requestPost(final String id) throws SDKException { HttpResponse<JsonNode> jsonResponse = null; try { log.debug("baseUrl: " + baseUrl); log.debug("id: " + baseUrl + id); checkToken(); // call the api here log.debug("Executing post on: " + this.baseUrl + id); if (token != null) jsonResponse = Unirest.post(this.baseUrl + id) .header("accept", "application/json") .header("Content-Type", "application/json") .header("Authorization", bearerToken.replaceAll("\"", "")) .asJson(); else jsonResponse = Unirest.post(this.baseUrl + id) .header("accept", "application/json") .header("Content-Type", "application/json") .asJson(); // check response status checkStatus(jsonResponse, HttpURLConnection.HTTP_CREATED); // return the response of the request String result = jsonResponse.getBody().toString(); log.debug("received: " + result); return result; } catch (IOException e) { // catch request exceptions here e.printStackTrace(); throw new SDKException("Could not http-post or open the object properly"); } catch (UnirestException e) { // catch request exceptions here e.printStackTrace(); throw new SDKException("Could not http-post or open the object properly"); } catch (net.minidev.json.parser.ParseException e) { e.printStackTrace(); throw new SDKException("Could not get token"); } catch (SDKException e) { if (jsonResponse.getStatus() == HttpStatus.SC_UNAUTHORIZED) { token = null; return requestPost(id); } else throw new SDKException("Status is " + jsonResponse.getStatus()); } } /** * Executes a http post with to a given url, while serializing the object content as json * and returning the response * * @param object the object content to be serialized as json * @return a string containing the response content */ public Serializable requestPost(final Serializable object) throws SDKException { return requestPost("",object); } public Serializable requestPost(final String id,final Serializable object) throws SDKException { HttpResponse<JsonNode> jsonResponse = null; try { log.debug("Object is: " + object); String fileJSONNode = mapper.toJson(object); log.debug("sending: " + fileJSONNode.toString()); log.debug("baseUrl: " + baseUrl + "/" +id); checkToken(); // call the api here log.debug("Executing post on: " + this.baseUrl + "/" +id); if (token != null) jsonResponse = Unirest.post(this.baseUrl + "/" +id) .header("accept", "application/json") .header("Content-Type", "application/json") .header("Authorization", bearerToken.replaceAll("\"", "")) .body(fileJSONNode) .asJson(); else jsonResponse = Unirest.post(this.baseUrl + "/" +id) .header("accept", "application/json") .header("Content-Type", "application/json") .body(fileJSONNode) .asJson(); // check response status checkStatus(jsonResponse, HttpURLConnection.HTTP_CREATED); // return the response of the request String result = jsonResponse.getBody().toString(); log.debug("received: " + result); log.debug("Casting it into: " + object.getClass()); // return mapper.readValue(jsonResponse.getBody().toString(), object.getClass()); return mapper.fromJson(result, object.getClass()); } catch (IOException e) { // catch request exceptions here e.printStackTrace(); throw new SDKException("Could not http-post or open the object properly"); } catch (UnirestException e) { // catch request exceptions here e.printStackTrace(); throw new SDKException("Could not http-post or open the object properly"); } catch (net.minidev.json.parser.ParseException e) { e.printStackTrace(); throw new SDKException("Could not get token"); } catch (SDKException e) { if (jsonResponse.getStatus() == HttpStatus.SC_UNAUTHORIZED) { token = null; return requestPost(object); } else throw new SDKException("Status is " + jsonResponse.getStatus()); } } private void checkToken() throws IOException, net.minidev.json.parser.ParseException { if (!(this.username == null || this.password == null)) if (token == null && (!this.username.equals("") || !this.password.equals(""))) { getAccessToken(); } } private JsonNode getJsonNode(Serializable object) throws IOException { return new JsonNode(mapper.toJson(object)); } /** * Executes a http delete with to a given id * * @param id the id path used for the api request */ public void requestDelete(final String id) throws SDKException { HttpResponse<JsonNode> jsonResponse = null; try { // call the api here checkToken(); log.trace("Executing delete on: " + this.baseUrl + "/" + id); if (token != null) jsonResponse = Unirest.delete(this.baseUrl + "/" + id) .header("Authorization", bearerToken.replaceAll("\"", "")) .asJson(); else jsonResponse = Unirest.delete(this.baseUrl + "/" + id).asJson(); // check response status checkStatus(jsonResponse, HttpURLConnection.HTTP_NO_CONTENT); } catch (UnirestException e) { // catch request exceptions here throw new SDKException("Could not http-delete or the api response was wrong"); } catch (SDKException e) { // catch request exceptions here if (jsonResponse.getStatus() == HttpStatus.SC_UNAUTHORIZED) { token = null; requestDelete(id); } throw new SDKException("Could not http-delete or the api response was wrong"); } catch (net.minidev.json.parser.ParseException e) { e.printStackTrace(); throw new SDKException("Could not get token"); } catch (IOException e) { e.printStackTrace(); throw new SDKException("Could not get token"); } } /** * Executes a http get with to a given id * * @param id the id path used for the api request * @return a string containing he response content */ public Object requestGet(final String id, Class type) throws SDKException { String url = this.baseUrl; if (id != null){ url += "/" + id; return requestGetWithStatus(url, null, type); } else return requestGetAll(url, type, null); } protected Object requestGetAll(String url, Class type) throws SDKException { return requestGetAll(url, type, null); } private Object requestGetAll(String url, Class type, final Integer httpStatus) throws SDKException { HttpResponse<JsonNode> jsonResponse = null; try { // call the api here try { checkToken(); } catch (IOException e) { e.printStackTrace(); throw new SDKException("Could not get token"); } catch (net.minidev.json.parser.ParseException e) { e.printStackTrace(); throw new SDKException("Could not get token"); } log.debug("Executing get on: " + url); if (token != null) jsonResponse = Unirest.get(url) .header("Authorization", bearerToken.replaceAll("\"", "")) .asJson(); else jsonResponse = Unirest.get(url).asJson(); // check response status if (httpStatus != null) { checkStatus(jsonResponse, httpStatus); } // return the response of the request log.debug("result is: " + jsonResponse.getBody().toString()); Class<?> aClass = Array.newInstance(type, 3).getClass(); log.debug("class is: " + aClass); Object o = mapper.fromJson(jsonResponse.getBody().toString(), aClass); log.debug("deserialized is: " + o); return o; } catch (UnirestException e) { // catch request exceptions here throw new SDKException("Could not http-get properly"); } catch (SDKException e) { if (jsonResponse.getStatus() == HttpStatus.SC_UNAUTHORIZED) { token = null; return requestGetAll(url, type, httpStatus); } else { e.printStackTrace(); throw new SDKException("Could not authorize"); } } } /** * Executes a http get with to a given id, and possible executed an http (accept) status check of the response if an httpStatus is delivered. * If httpStatus is null, no check will be executed. * * @param url the id path used for the api request * @param httpStatus the http status to be checked. * @param type * @return a string containing the response content */ private Object requestGetWithStatus(final String url, final Integer httpStatus, Class type) throws SDKException { HttpResponse<JsonNode> jsonResponse = null; try { // call the api here try { checkToken(); } catch (IOException e) { e.printStackTrace(); throw new SDKException("Could not get token"); } catch (net.minidev.json.parser.ParseException e) { e.printStackTrace(); throw new SDKException("Could not get token"); } log.debug("Executing get on: " +url); if (token != null) jsonResponse = Unirest.get(url) .header("Authorization", bearerToken.replaceAll("\"", "")) .asJson(); else jsonResponse = Unirest.get(url).asJson(); // check response status if (httpStatus != null) { checkStatus(jsonResponse, httpStatus); } // return the response of the request log.debug("result is: " + jsonResponse.getBody().toString()); Class<?> aClass = Array.newInstance(type, 1).getClass(); log.debug("class is: " + aClass); return mapper.fromJson(jsonResponse.getBody().toString(), type); } catch (UnirestException e) { // catch request exceptions here throw new SDKException("Could not http-get properly"); } catch (SDKException e) { if (jsonResponse.getStatus() == HttpStatus.SC_UNAUTHORIZED) { token = null; return requestGetWithStatus(url, httpStatus, type); } else { e.printStackTrace(); throw new SDKException("Could not authorize"); } } } /** * Executes a http get with to a given url, in contrast to the normal get it uses an http (accept) status check of the response * * @param url the url path used for the api request * @return a string containing the response content */ public Object requestGetWithStatusAccepted(String url, Class type) throws SDKException { url = this.baseUrl + url; return requestGetWithStatus(url, new Integer(HttpURLConnection.HTTP_ACCEPTED), type); } /** * Executes a http put with to a given id, while serializing the object content as json * and returning the response * * @param id the id path used for the api request * @param object the object content to be serialized as json * @return a string containing the response content */ public Serializable requestPut(final String id, final Serializable object) throws SDKException { HttpResponse<JsonNode> jsonResponse = null; try { JsonNode fileJSONNode = getJsonNode(object); try { checkToken(); } catch (net.minidev.json.parser.ParseException e) { e.printStackTrace(); throw new SDKException("Could not get token"); } // call the api here log.debug("Executing put on: " + this.baseUrl + "/" + id); if (token != null) jsonResponse = Unirest.put(this.baseUrl + "/" + id) .header("accept", "application/json") .header("Content-Type", "application/json") .header("Authorization", bearerToken.replaceAll("\"", "")) .body(fileJSONNode) .asJson(); else jsonResponse = Unirest.put(this.baseUrl + "/" + id) .header("accept", "application/json") .header("Content-Type", "application/json") .body(fileJSONNode) .asJson(); // check response status checkStatus(jsonResponse, HttpURLConnection.HTTP_ACCEPTED); // return the response of the request return mapper.fromJson(jsonResponse.getBody().toString(), object.getClass()); } catch (IOException e) { // catch request exceptions here throw new SDKException("Could not http-put or the api response was wrong or open the object properly"); } catch (UnirestException e) { // catch request exceptions here throw new SDKException("Could not http-put or the api response was wrong or open the object properly"); } catch (SDKException e) { // catch request exceptions here if (jsonResponse.getStatus() == HttpStatus.SC_UNAUTHORIZED) { token = null; return requestPut(id, object); } throw new SDKException("Could not http-put or the api response was wrong or open the object properly"); } } /** * Check wether a json repsonse has the right http status. If not, an SDKException is thrown. * * @param jsonResponse the http json response * @param httpStatus the (desired) http status of the repsonse */ private void checkStatus(HttpResponse<JsonNode> jsonResponse, final int httpStatus) throws SDKException { if (jsonResponse.getStatus() != httpStatus) { log.debug("Status expected: " + httpStatus + " obtained: " + jsonResponse.getStatus()); throw new SDKException("Received wrong API HTTPStatus"); } } private void getAccessToken() throws IOException { HttpClient httpClient = HttpClientBuilder.create().build(); HttpPost httpPost = new HttpPost(provider); httpPost.setHeader("Authorization", "Basic " + encoding); List<BasicNameValuePair> parametersBody = new ArrayList<>(); parametersBody.add(new BasicNameValuePair("grant_type", "password")); parametersBody.add(new BasicNameValuePair("username", this.username)); parametersBody.add(new BasicNameValuePair("password", this.password)); httpPost.setEntity(new UrlEncodedFormEntity(parametersBody, StandardCharsets.UTF_8)); org.apache.http.HttpResponse response = null; response = httpClient.execute(httpPost); String responseString = null; responseString = EntityUtils.toString(response.getEntity()); int statusCode = response.getStatusLine().getStatusCode(); log.debug(statusCode + ": " + responseString); if (statusCode != 200) { ParseComError error = new Gson().fromJson(responseString, ParseComError.class); log.error("Status Code [" + statusCode + "]: Error signing-in [" + error.error + "] - " + error.error_description); } JsonObject jobj = new Gson().fromJson(responseString, JsonObject.class); String token = jobj.get("access_token").toString(); log.trace(token); bearerToken = "Bearer " + token; this.token = token; } private class ParseComError implements Serializable { String error_description; String error; } }
package owltools.web; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletException; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.TimeZone; import org.apache.log4j.Logger; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.handler.AbstractHandler; import org.eclipse.jetty.util.URIUtil; import org.semanticweb.elk.owlapi.ElkReasonerFactory; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.model.OWLOntologyCreationException; import org.semanticweb.owlapi.model.OWLOntologyStorageException; import org.semanticweb.owlapi.reasoner.InferenceType; import org.semanticweb.owlapi.reasoner.OWLReasoner; import org.semanticweb.owlapi.reasoner.OWLReasonerFactory; import org.semanticweb.owlapi.reasoner.structural.StructuralReasonerFactory; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import de.tudresden.inf.lat.jcel.owlapi.main.JcelReasoner; import owltools.graph.OWLGraphWrapper; import owltools.sim2.OwlSim; import uk.ac.manchester.cs.factplusplus.owlapiv3.FaCTPlusPlusReasonerFactory; import uk.ac.manchester.cs.jfact.JFactFactory; public class OWLServer extends AbstractHandler { private static Logger LOG = Logger.getLogger(OWLServer.class); OWLGraphWrapper graph; Map<String,OWLReasoner> reasonerMap = new HashMap<String,OWLReasoner>(); OwlSim sos = null; public OWLServer(OWLGraphWrapper g) { super(); graph = g; } public OWLServer(OWLGraphWrapper g, OwlSim sos2) { super(); graph = g; sos = sos2; } public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String path = request.getPathInfo(); baseRequest.setHandled(true); // TODO/BUG: A real server interface that we can operate on. // Check the incoming args (if any) to see if we're going to use JSONP wrapping. String jsonp_callback = request.getParameter("json.wrf"); // Check to make sure that the jsonp callback argument is legit. if( jsonp_callback == null || jsonp_callback.isEmpty() ){ jsonp_callback = null; // a miss is as good as a mile } // About to sin... // TODO: We'd like to change the header to javascript here--no longer JSON. // TODO: We'll happily wrap non-JSON things here as well. // The closer is later on. if( jsonp_callback != null ){ response.getWriter().write(jsonp_callback + '('); } OWLHandler handler = new OWLHandler(this, graph, request, response); if (sos != null) handler.setOwlSim(sos); LOG.info("Request "+path); path = path.replace("/owlsim/", "/"); String[] toks = path.split("/"); String m; if (toks.length == 0) { m = "top"; } else { m = toks[1]; } if (m.contains(".")) { String[] mpa = m.split("\\.", 2); m = mpa[0]; handler.setFormat(mpa[1]); } if ("status".equals(m)) { // report status reportStatus(baseRequest, request, response); } else { handler.setCommandName(m); Class[] mArgs = new Class[0]; Method method = null; try { method = handler.getClass().getMethod(m + "Command", mArgs); } catch (SecurityException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (NoSuchMethodException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } if (method != null) { try { LOG.info("Method="+method); Object[] oArgs = new Object[0]; method.invoke(handler, oArgs); handler.printCachedObjects(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (OWLOntologyCreationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (OWLOntologyStorageException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } // TODO/BUG: Remove for a real system // Close in case of JSONP. See above. if( jsonp_callback != null ){ response.getWriter().write(')'); } } private void reportStatus(Request baseRequest, HttpServletRequest request, HttpServletResponse response) { Map<String, Object> jsonObj = new HashMap<String, Object>(); // name jsonObj.put("name", "owlserver"); // okay jsonObj.put("okay", Boolean.TRUE); // date in GMT Date localTime = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); sdf.setTimeZone(TimeZone.getTimeZone("GMT")); jsonObj.put("date", sdf.format(localTime)); // location // use the request URL, the server does not know its address jsonObj.put("location", getLocationInfo(request)); // offerings (optional list of values) // for now empty try { Gson gson = new GsonBuilder().create(); String js = gson.toJson(jsonObj); response.getWriter().write(js); } catch (IOException e) { int code = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; try { response.sendError(code , "Could not send status message due to an internal issue: "+e.getMessage()); } catch (IOException e1) { LOG.error("Could not send error message for original IOException: "+e.getMessage(), e1); } } } private CharSequence getLocationInfo(HttpServletRequest request) { StringBuilder sb = new StringBuilder(); String scheme = request.getScheme(); int port = request.getServerPort(); sb.append(scheme); sb.append(": sb.append(request.getServerName()); if (port>0 && ((scheme.equalsIgnoreCase(URIUtil.HTTP) && port != 80) || (scheme.equalsIgnoreCase(URIUtil.HTTPS) && port != 443))) { sb.append(':'); sb.append(port); } return sb; } public synchronized OWLReasoner getReasoner(String reasonerName) { // TODO - reasoner synchronization if (reasonerMap.containsKey(reasonerName)) return reasonerMap.get(reasonerName); OWLOntology ont = graph.getSourceOntology(); OWLReasonerFactory reasonerFactory = null; OWLReasoner reasoner = null; LOG.info("Creating reasoner:"+reasonerName); if (reasonerName == null || reasonerName.equals("default")) { if (graph.getReasoner() != null) return graph.getReasoner(); reasonerFactory = new ElkReasonerFactory(); } else if (reasonerName == null || reasonerName.equals("factpp")) reasonerFactory = new FaCTPlusPlusReasonerFactory(); else if (reasonerName.equals("hermit")) { reasonerFactory = new org.semanticweb.HermiT.Reasoner.ReasonerFactory(); } else if (reasonerName.equals("elk")) { reasonerFactory = new ElkReasonerFactory(); } else if (reasonerName.equals("jfact")) { reasonerFactory = new JFactFactory(); } else if (reasonerName.equals("jcel")) { reasoner = new JcelReasoner(ont); reasoner.precomputeInferences(InferenceType.CLASS_HIERARCHY); return reasoner; } else if (reasonerName.equals("structural")) { reasonerFactory = new StructuralReasonerFactory(); } else { // TODO System.out.println("no such reasoner: "+reasonerName); } if (reasoner == null) reasoner = reasonerFactory.createReasoner(ont); reasonerMap.put(reasonerName, reasoner); return reasoner; } /* (non-Javadoc) * @see org.eclipse.jetty.server.handler.AbstractHandler#destroy() */ @Override public void destroy() { // clean up reasoners Set<String> reasonerNames = reasonerMap.keySet(); Iterator<String> iterator = reasonerNames.iterator(); while (iterator.hasNext()) { String reasonerName = iterator.next(); OWLReasoner reasoner = reasonerMap.remove(reasonerName); if (reasoner != null) { reasoner.dispose(); } } super.destroy(); } }
package com.smartdevicelink.proxy; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.util.Hashtable; import java.util.List; import java.util.Vector; import java.util.concurrent.Callable; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.Executors; import java.util.concurrent.FutureTask; import java.util.concurrent.ScheduledExecutorService; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.annotation.TargetApi; import android.app.Service; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.os.Handler; import android.os.Looper; import android.os.SystemClock; import android.telephony.TelephonyManager; import android.util.DisplayMetrics; import android.util.Log; import android.util.SparseArray; import android.view.Display; import android.view.MotionEvent; import android.view.Surface; import com.smartdevicelink.Dispatcher.IDispatchingStrategy; import com.smartdevicelink.Dispatcher.ProxyMessageDispatcher; import com.smartdevicelink.SdlConnection.ISdlConnectionListener; import com.smartdevicelink.SdlConnection.SdlConnection; import com.smartdevicelink.SdlConnection.SdlSession; import com.smartdevicelink.encoder.VirtualDisplayEncoder; import com.smartdevicelink.exception.SdlException; import com.smartdevicelink.exception.SdlExceptionCause; import com.smartdevicelink.haptic.HapticInterfaceManager; import com.smartdevicelink.marshal.JsonRPCMarshaller; import com.smartdevicelink.protocol.ProtocolMessage; import com.smartdevicelink.protocol.enums.FunctionID; import com.smartdevicelink.protocol.enums.MessageType; import com.smartdevicelink.protocol.enums.SessionType; import com.smartdevicelink.protocol.heartbeat.HeartbeatMonitor; import com.smartdevicelink.proxy.LockScreenManager.OnLockScreenIconDownloadedListener; import com.smartdevicelink.proxy.callbacks.InternalProxyMessage; import com.smartdevicelink.proxy.callbacks.OnError; import com.smartdevicelink.proxy.callbacks.OnProxyClosed; import com.smartdevicelink.proxy.callbacks.OnServiceEnded; import com.smartdevicelink.proxy.callbacks.OnServiceNACKed; import com.smartdevicelink.proxy.interfaces.IAudioStreamListener; import com.smartdevicelink.proxy.interfaces.IProxyListenerBase; import com.smartdevicelink.proxy.interfaces.IPutFileResponseListener; import com.smartdevicelink.proxy.interfaces.ISdl; import com.smartdevicelink.proxy.interfaces.ISdlServiceListener; import com.smartdevicelink.proxy.interfaces.IVideoStreamListener; import com.smartdevicelink.proxy.interfaces.OnSystemCapabilityListener; import com.smartdevicelink.proxy.rpc.*; import com.smartdevicelink.proxy.rpc.enums.AppHMIType; import com.smartdevicelink.proxy.rpc.enums.AudioStreamingState; import com.smartdevicelink.proxy.rpc.enums.AudioType; import com.smartdevicelink.proxy.rpc.enums.BitsPerSample; import com.smartdevicelink.proxy.rpc.enums.ButtonName; import com.smartdevicelink.proxy.rpc.enums.DriverDistractionState; import com.smartdevicelink.proxy.rpc.enums.FileType; import com.smartdevicelink.proxy.rpc.enums.GlobalProperty; import com.smartdevicelink.proxy.rpc.enums.HMILevel; import com.smartdevicelink.proxy.rpc.enums.ImageType; import com.smartdevicelink.proxy.rpc.enums.InteractionMode; import com.smartdevicelink.proxy.rpc.enums.Language; import com.smartdevicelink.proxy.rpc.enums.PrerecordedSpeech; import com.smartdevicelink.proxy.rpc.enums.RequestType; import com.smartdevicelink.proxy.rpc.enums.Result; import com.smartdevicelink.proxy.rpc.enums.SamplingRate; import com.smartdevicelink.proxy.rpc.enums.SdlConnectionState; import com.smartdevicelink.proxy.rpc.enums.SdlDisconnectedReason; import com.smartdevicelink.proxy.rpc.enums.SdlInterfaceAvailability; import com.smartdevicelink.proxy.rpc.enums.SystemCapabilityType; import com.smartdevicelink.proxy.rpc.enums.TextAlignment; import com.smartdevicelink.proxy.rpc.enums.TouchType; import com.smartdevicelink.proxy.rpc.enums.UpdateMode; import com.smartdevicelink.proxy.rpc.listeners.OnPutFileUpdateListener; import com.smartdevicelink.proxy.rpc.listeners.OnRPCNotificationListener; import com.smartdevicelink.proxy.rpc.listeners.OnRPCResponseListener; import com.smartdevicelink.security.SdlSecurityBase; import com.smartdevicelink.streaming.audio.AudioStreamingCodec; import com.smartdevicelink.streaming.audio.AudioStreamingParams; import com.smartdevicelink.streaming.StreamRPCPacketizer; import com.smartdevicelink.streaming.video.SdlRemoteDisplay; import com.smartdevicelink.streaming.video.VideoStreamingParameters; import com.smartdevicelink.trace.SdlTrace; import com.smartdevicelink.trace.TraceDeviceInfo; import com.smartdevicelink.trace.enums.InterfaceActivityDirection; import com.smartdevicelink.transport.BaseTransportConfig; import com.smartdevicelink.transport.SiphonServer; import com.smartdevicelink.transport.enums.TransportType; import com.smartdevicelink.util.DebugTool; @SuppressWarnings({"WeakerAccess", "Convert2Diamond"}) public abstract class SdlProxyBase<proxyListenerType extends IProxyListenerBase> { // Used for calls to Android Log class. public static final String TAG = "SdlProxy"; private static final String SDL_LIB_TRACE_KEY = "42baba60-eb57-11df-98cf-0800200c9a66"; private static final int PROX_PROT_VER_ONE = 1; private static final int RESPONSE_WAIT_TIME = 2000; private SdlSession sdlSession = null; private proxyListenerType _proxyListener = null; protected Service _appService = null; private String sPoliciesURL = ""; //for testing only // Protected Correlation IDs private final int REGISTER_APP_INTERFACE_CORRELATION_ID = 65529, UNREGISTER_APP_INTERFACE_CORRELATION_ID = 65530, POLICIES_CORRELATION_ID = 65535; // Sdlhronization Objects private static final Object CONNECTION_REFERENCE_LOCK = new Object(), INCOMING_MESSAGE_QUEUE_THREAD_LOCK = new Object(), OUTGOING_MESSAGE_QUEUE_THREAD_LOCK = new Object(), INTERNAL_MESSAGE_QUEUE_THREAD_LOCK = new Object(), ON_UPDATE_LISTENER_LOCK = new Object(), ON_NOTIFICATION_LISTENER_LOCK = new Object(); private final Object APP_INTERFACE_REGISTERED_LOCK = new Object(); private int iFileCount = 0; private boolean navServiceStartResponseReceived = false; private boolean navServiceStartResponse = false; private List<String> navServiceStartRejectedParams = null; private boolean pcmServiceStartResponseReceived = false; private boolean pcmServiceStartResponse = false; @SuppressWarnings("FieldCanBeLocal") private List<String> pcmServiceStartRejectedParams = null; private boolean navServiceEndResponseReceived = false; private boolean navServiceEndResponse = false; private boolean pcmServiceEndResponseReceived = false; private boolean pcmServiceEndResponse = false; private boolean rpcProtectedResponseReceived = false; private boolean rpcProtectedStartResponse = false; // Device Info for logging private TraceDeviceInfo _traceDeviceInterrogator = null; // Declare Queuing Threads private ProxyMessageDispatcher<ProtocolMessage> _incomingProxyMessageDispatcher; private ProxyMessageDispatcher<ProtocolMessage> _outgoingProxyMessageDispatcher; private ProxyMessageDispatcher<InternalProxyMessage> _internalProxyMessageDispatcher; // Flag indicating if callbacks should be called from UIThread private Boolean _callbackToUIThread = false; // UI Handler private Handler _mainUIHandler = null; final int HEARTBEAT_CORRELATION_ID = 65531; // SdlProxy Advanced Lifecycle Management protected Boolean _advancedLifecycleManagementEnabled = false; // Parameters passed to the constructor from the app to register an app interface private String _applicationName = null; private final long instanceDateTime = System.currentTimeMillis(); private String sConnectionDetails = "N/A"; private Vector<TTSChunk> _ttsName = null; private String _ngnMediaScreenAppName = null; private Boolean _isMediaApp = null; private Language _sdlLanguageDesired = null; private Language _hmiDisplayLanguageDesired = null; private Vector<AppHMIType> _appType = null; private String _appID = null; @SuppressWarnings({"FieldCanBeLocal", "unused"}) //Need to understand what this is used for private String _autoActivateIdDesired = null; private String _lastHashID = null; private SdlMsgVersion _sdlMsgVersionRequest = null; private Vector<String> _vrSynonyms = null; private boolean _bAppResumeEnabled = false; private OnSystemRequest lockScreenIconRequest = null; private TelephonyManager telephonyManager = null; private DeviceInfo deviceInfo = null; /** * Contains current configuration for the transport that was selected during * construction of this object */ private BaseTransportConfig _transportConfig = null; // Proxy State Variables protected Boolean _appInterfaceRegisterd = false; protected Boolean _preRegisterd = false; @SuppressWarnings({"unused", "FieldCanBeLocal"}) private Boolean _haveReceivedFirstNonNoneHMILevel = false; protected Boolean _haveReceivedFirstFocusLevel = false; protected Boolean _haveReceivedFirstFocusLevelFull = false; protected Boolean _proxyDisposed = false; protected SdlConnectionState _sdlConnectionState = null; protected SdlInterfaceAvailability _sdlIntefaceAvailablity = null; protected HMILevel _hmiLevel = null; protected AudioStreamingState _audioStreamingState = null; // Variables set by RegisterAppInterfaceResponse protected SdlMsgVersion _sdlMsgVersion = null; protected String _autoActivateIdReturned = null; protected Language _sdlLanguage = null; protected Language _hmiDisplayLanguage = null; protected List<PrerecordedSpeech> _prerecordedSpeech = null; protected VehicleType _vehicleType = null; protected String _systemSoftwareVersion = null; protected List<Integer> _diagModes = null; protected Boolean firstTimeFull = true; protected String _proxyVersionInfo = null; protected Boolean _bResumeSuccess = false; protected List<Class<? extends SdlSecurityBase>> _secList = null; protected SystemCapabilityManager _systemCapabilityManager; private final CopyOnWriteArrayList<IPutFileResponseListener> _putFileListenerList = new CopyOnWriteArrayList<IPutFileResponseListener>(); protected byte _wiproVersion = 1; protected SparseArray<OnRPCResponseListener> rpcResponseListeners = null; protected SparseArray<CopyOnWriteArrayList<OnRPCNotificationListener>> rpcNotificationListeners = null; protected VideoStreamingManager manager; //Will move to SdlSession once the class becomes public // Interface broker private SdlInterfaceBroker _interfaceBroker = null; //We create an easily passable anonymous class of the interface so that we don't expose the internal interface to developers private ISdl _internalInterface = new ISdl() { @Override public void start() { try{ initializeProxy(); }catch (SdlException e){ e.printStackTrace(); } } @Override public void stop() { try{ dispose(); }catch (SdlException e){ e.printStackTrace(); } } @Override public boolean isConnected() { return getIsConnected(); } @Override public void addServiceListener(SessionType serviceType, ISdlServiceListener sdlServiceListener) { SdlProxyBase.this.addServiceListener(serviceType,sdlServiceListener); } @Override public void removeServiceListener(SessionType serviceType, ISdlServiceListener sdlServiceListener) { SdlProxyBase.this.removeServiceListener(serviceType,sdlServiceListener); } @Override public void startVideoService(VideoStreamingParameters parameters, boolean encrypted) { if(isConnected()){ sdlSession.setDesiredVideoParams(parameters); sdlSession.startService(SessionType.NAV,sdlSession.getSessionId(),encrypted); } } @Override public void stopVideoService() { if(isConnected()){ sdlSession.endService(SessionType.NAV,sdlSession.getSessionId()); } } @Override public void startAudioService(boolean encrypted) { if(isConnected()){ sdlSession.startService(SessionType.PCM,sdlSession.getSessionId(),encrypted); } } @Override public void stopAudioService() { if(isConnected()){ sdlSession.endService(SessionType.PCM,sdlSession.getSessionId()); } } @Override public void sendRPCRequest(RPCRequest message){ try { SdlProxyBase.this.sendRPCRequest(message); } catch (SdlException e) { e.printStackTrace(); } } @Override public void addOnRPCNotificationListener(FunctionID notificationId, OnRPCNotificationListener listener) { SdlProxyBase.this.addOnRPCNotificationListener(notificationId,listener); } @Override public boolean removeOnRPCNotificationListener(FunctionID notificationId, OnRPCNotificationListener listener) { return SdlProxyBase.this.removeOnRPCNotificationListener(notificationId,listener); } }; private void notifyPutFileStreamError(Exception e, String info) { for (IPutFileResponseListener _putFileListener : _putFileListenerList) { _putFileListener.onPutFileStreamError(e, info); } } private void notifyPutFileStreamResponse(PutFileResponse msg) { for (IPutFileResponseListener _putFileListener : _putFileListenerList) { _putFileListener.onPutFileResponse(msg); } } public void addPutFileResponseListener(IPutFileResponseListener _putFileListener) { _putFileListenerList.addIfAbsent(_putFileListener); } public void remPutFileResponseListener(IPutFileResponseListener _putFileListener) { _putFileListenerList.remove(_putFileListener); } // Private Class to Interface with SdlConnection private class SdlInterfaceBroker implements ISdlConnectionListener { @Override public void onTransportDisconnected(String info) { // proxyOnTransportDisconnect is called to alert the proxy that a requested // disconnect has completed notifyPutFileStreamError(null, info); if (!_advancedLifecycleManagementEnabled) { // If original model, notify app the proxy is closed so it will delete and reinstanciate notifyProxyClosed(info, new SdlException("Transport disconnected.", SdlExceptionCause.SDL_UNAVAILABLE), SdlDisconnectedReason.TRANSPORT_DISCONNECT); }// else If ALM, nothing is required to be done here } @Override public void onTransportError(String info, Exception e) { DebugTool.logError("Transport failure: " + info, e); notifyPutFileStreamError(e, info); if (_advancedLifecycleManagementEnabled) { // Cycle the proxy if(SdlConnection.isLegacyModeEnabled()){ cycleProxy(SdlDisconnectedReason.LEGACY_BLUETOOTH_MODE_ENABLED); }else{ cycleProxy(SdlDisconnectedReason.TRANSPORT_ERROR); } } else { notifyProxyClosed(info, e, SdlDisconnectedReason.TRANSPORT_ERROR); } } @Override public void onProtocolMessageReceived(ProtocolMessage msg) { // AudioPathThrough is coming WITH BulkData but WITHOUT JSON Data // Policy Snapshot is coming WITH BulkData and WITH JSON Data if ((msg.getData() != null && msg.getData().length > 0) || (msg.getBulkData() != null && msg.getBulkData().length > 0)) { queueIncomingMessage(msg); } } @Override public void onProtocolSessionStarted(SessionType sessionType, byte sessionID, byte version, String correlationID, int hashID, boolean isEncrypted) { Intent sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "FUNCTION_NAME", "onProtocolSessionStarted"); updateBroadcastIntent(sendIntent, "COMMENT1", "SessionID: " + sessionID); updateBroadcastIntent(sendIntent, "COMMENT2", " ServiceType: " + sessionType.getName()); updateBroadcastIntent(sendIntent, "COMMENT3", " Encrypted: " + isEncrypted); sendBroadcastIntent(sendIntent); setWiProVersion(version); if (sessionType.eq(SessionType.RPC)) { if (!isEncrypted) { if ( (_transportConfig.getHeartBeatTimeout() != Integer.MAX_VALUE) && (version > 2)) { HeartbeatMonitor outgoingHeartbeatMonitor = new HeartbeatMonitor(); outgoingHeartbeatMonitor.setInterval(_transportConfig.getHeartBeatTimeout()); sdlSession.setOutgoingHeartbeatMonitor(outgoingHeartbeatMonitor); HeartbeatMonitor incomingHeartbeatMonitor = new HeartbeatMonitor(); incomingHeartbeatMonitor.setInterval(_transportConfig.getHeartBeatTimeout()); sdlSession.setIncomingHeartbeatMonitor(incomingHeartbeatMonitor); } startRPCProtocolSession(); } else { RPCProtectedServiceStarted(); } } else if (sessionType.eq(SessionType.NAV)) { NavServiceStarted(); } else if (sessionType.eq(SessionType.PCM)) { AudioServiceStarted(); } else if (sessionType.eq(SessionType.RPC)){ cycleProxy(SdlDisconnectedReason.RPC_SESSION_ENDED); } else if (_wiproVersion > 1) { //If version is 2 or above then don't need to specify a Session Type startRPCProtocolSession(); } //else{} Handle other protocol session types here } @Override public void onProtocolSessionStartedNACKed(SessionType sessionType, byte sessionID, byte version, String correlationID, List<String> rejectedParams) { OnServiceNACKed message = new OnServiceNACKed(sessionType); queueInternalMessage(message); if (sessionType.eq(SessionType.NAV)) { Intent sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "FUNCTION_NAME", "onProtocolSessionStartedNACKed"); updateBroadcastIntent(sendIntent, "COMMENT1", "SessionID: " + sessionID); updateBroadcastIntent(sendIntent, "COMMENT2", " NACK ServiceType: " + sessionType.getName()); sendBroadcastIntent(sendIntent); NavServiceStartedNACK(rejectedParams); } else if (sessionType.eq(SessionType.PCM)) { Intent sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "FUNCTION_NAME", "onProtocolSessionStartedNACKed"); updateBroadcastIntent(sendIntent, "COMMENT1", "SessionID: " + sessionID); updateBroadcastIntent(sendIntent, "COMMENT2", " NACK ServiceType: " + sessionType.getName()); sendBroadcastIntent(sendIntent); AudioServiceStartedNACK(rejectedParams); } } @Override public void onProtocolSessionEnded(SessionType sessionType, byte sessionID, String correlationID) { OnServiceEnded message = new OnServiceEnded(sessionType); queueInternalMessage(message); if (sessionType.eq(SessionType.NAV)) { Intent sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "FUNCTION_NAME", "onProtocolSessionEnded"); updateBroadcastIntent(sendIntent, "COMMENT1", "SessionID: " + sessionID); updateBroadcastIntent(sendIntent, "COMMENT2", " End ServiceType: " + sessionType.getName()); sendBroadcastIntent(sendIntent); NavServiceEnded(); } else if (sessionType.eq(SessionType.PCM)) { Intent sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "FUNCTION_NAME", "onProtocolSessionEnded"); updateBroadcastIntent(sendIntent, "COMMENT1", "SessionID: " + sessionID); updateBroadcastIntent(sendIntent, "COMMENT2", " End ServiceType: " + sessionType.getName()); sendBroadcastIntent(sendIntent); AudioServiceEnded(); } } @Override public void onProtocolError(String info, Exception e) { notifyPutFileStreamError(e, info); passErrorToProxyListener(info, e); } @Override public void onHeartbeatTimedOut(byte sessionID) { final String msg = "Heartbeat timeout"; DebugTool.logInfo(msg); Intent sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "FUNCTION_NAME", "onHeartbeatTimedOut"); updateBroadcastIntent(sendIntent, "COMMENT1", "Heartbeat timeout for SessionID: " + sessionID); sendBroadcastIntent(sendIntent); notifyProxyClosed(msg, new SdlException(msg, SdlExceptionCause.HEARTBEAT_PAST_DUE), SdlDisconnectedReason.HB_TIMEOUT); } @Override public void onProtocolSessionEndedNACKed(SessionType sessionType, byte sessionID, String correlationID) { if (sessionType.eq(SessionType.NAV)) { Intent sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "FUNCTION_NAME", "onProtocolSessionEndedNACKed"); updateBroadcastIntent(sendIntent, "COMMENT1", "SessionID: " + sessionID); updateBroadcastIntent(sendIntent, "COMMENT2", " End NACK ServiceType: " + sessionType.getName()); sendBroadcastIntent(sendIntent); NavServiceEndedNACK(); } else if (sessionType.eq(SessionType.PCM)) { Intent sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "FUNCTION_NAME", "onProtocolSessionEndedNACKed"); updateBroadcastIntent(sendIntent, "COMMENT1", "SessionID: " + sessionID); updateBroadcastIntent(sendIntent, "COMMENT2", " End NACK ServiceType: " + sessionType.getName()); sendBroadcastIntent(sendIntent); AudioServiceEndedNACK(); } } public void onProtocolServiceDataACK(SessionType sessionType, final int dataSize, byte sessionID) { if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onServiceDataACK(dataSize); } }); } else { _proxyListener.onServiceDataACK(dataSize); } } } /** * Constructor. * * @param listener Type of listener for this proxy base. * @param sdlProxyConfigurationResources Configuration resources for this proxy. * @param enableAdvancedLifecycleManagement Flag that ALM should be enabled or not. * @param appName Client application name. * @param ttsName TTS name. * @param ngnMediaScreenAppName Media Screen Application name. * @param vrSynonyms List of synonyms. * @param isMediaApp Flag that indicates that client application if media application or not. * @param sdlMsgVersion Version of Sdl Message. * @param languageDesired Desired language. * @param hmiDisplayLanguageDesired Desired language for HMI. * @param appType Type of application. * @param appID Application identifier. * @param autoActivateID Auto activation identifier. * @param callbackToUIThread Flag that indicates that this proxy should send callback to UI thread or not. * @param transportConfig Configuration of transport to be used by underlying connection. * @throws SdlException if there is an unrecoverable error class might throw an exception. */ protected SdlProxyBase(proxyListenerType listener, SdlProxyConfigurationResources sdlProxyConfigurationResources, boolean enableAdvancedLifecycleManagement, String appName, Vector<TTSChunk> ttsName, String ngnMediaScreenAppName, Vector<String> vrSynonyms, Boolean isMediaApp, SdlMsgVersion sdlMsgVersion, Language languageDesired, Language hmiDisplayLanguageDesired, Vector<AppHMIType> appType, String appID, String autoActivateID, boolean callbackToUIThread, BaseTransportConfig transportConfig) throws SdlException { performBaseCommon(listener, sdlProxyConfigurationResources, enableAdvancedLifecycleManagement, appName, ttsName, ngnMediaScreenAppName, vrSynonyms, isMediaApp, sdlMsgVersion, languageDesired, hmiDisplayLanguageDesired, appType, appID, autoActivateID, callbackToUIThread, null, null, null, transportConfig); } @SuppressWarnings("ConstantConditions") private void performBaseCommon(proxyListenerType listener, SdlProxyConfigurationResources sdlProxyConfigurationResources, boolean enableAdvancedLifecycleManagement, String appName, Vector<TTSChunk> ttsName, String ngnMediaScreenAppName, Vector<String> vrSynonyms, Boolean isMediaApp, SdlMsgVersion sdlMsgVersion, Language languageDesired, Language hmiDisplayLanguageDesired, Vector<AppHMIType> appType, String appID, String autoActivateID, boolean callbackToUIThread, Boolean preRegister, String sHashID, Boolean bAppResumeEnab, BaseTransportConfig transportConfig) throws SdlException { setWiProVersion((byte)PROX_PROT_VER_ONE); if (preRegister != null && preRegister) { _appInterfaceRegisterd = preRegister; _preRegisterd = preRegister; } if (bAppResumeEnab != null && bAppResumeEnab) { _bAppResumeEnabled = true; _lastHashID = sHashID; } _interfaceBroker = new SdlInterfaceBroker(); _callbackToUIThread = callbackToUIThread; if (_callbackToUIThread) { _mainUIHandler = new Handler(Looper.getMainLooper()); } // Set variables for Advanced Lifecycle Management _advancedLifecycleManagementEnabled = enableAdvancedLifecycleManagement; _applicationName = appName; _ttsName = ttsName; _ngnMediaScreenAppName = ngnMediaScreenAppName; _isMediaApp = isMediaApp; _sdlMsgVersionRequest = sdlMsgVersion; _vrSynonyms = vrSynonyms; _sdlLanguageDesired = languageDesired; _hmiDisplayLanguageDesired = hmiDisplayLanguageDesired; _appType = appType; _appID = appID; _autoActivateIdDesired = autoActivateID; _transportConfig = transportConfig; // Test conditions to invalidate the proxy if (listener == null) { throw new IllegalArgumentException("IProxyListener listener must be provided to instantiate SdlProxy object."); } if (_advancedLifecycleManagementEnabled) { if (_isMediaApp == null) { throw new IllegalArgumentException("isMediaApp must not be null when using SdlProxyALM."); } } _proxyListener = listener; // Get information from sdlProxyConfigurationResources if (sdlProxyConfigurationResources != null) { telephonyManager = sdlProxyConfigurationResources.getTelephonyManager(); } // Use the telephonyManager to get and log phone info if (telephonyManager != null) { // Following is not quite thread-safe (because m_traceLogger could test null twice), // so we need to fix this, but vulnerability (i.e. two instances of listener) is // likely harmless. if (_traceDeviceInterrogator == null) { _traceDeviceInterrogator = new TraceDeviceInfo(telephonyManager); } // end-if } // end-if // Setup Internal ProxyMessage Dispatcher synchronized(INTERNAL_MESSAGE_QUEUE_THREAD_LOCK) { // Ensure internalProxyMessageDispatcher is null if (_internalProxyMessageDispatcher != null) { _internalProxyMessageDispatcher.dispose(); _internalProxyMessageDispatcher = null; } _internalProxyMessageDispatcher = new ProxyMessageDispatcher<InternalProxyMessage>("INTERNAL_MESSAGE_DISPATCHER", new IDispatchingStrategy<InternalProxyMessage>() { @Override public void dispatch(InternalProxyMessage message) { dispatchInternalMessage(message); } @Override public void handleDispatchingError(String info, Exception ex) { handleErrorsFromInternalMessageDispatcher(info, ex); } @Override public void handleQueueingError(String info, Exception ex) { handleErrorsFromInternalMessageDispatcher(info, ex); } }); } // Setup Incoming ProxyMessage Dispatcher synchronized(INCOMING_MESSAGE_QUEUE_THREAD_LOCK) { // Ensure incomingProxyMessageDispatcher is null if (_incomingProxyMessageDispatcher != null) { _incomingProxyMessageDispatcher.dispose(); _incomingProxyMessageDispatcher = null; } _incomingProxyMessageDispatcher = new ProxyMessageDispatcher<ProtocolMessage>("INCOMING_MESSAGE_DISPATCHER",new IDispatchingStrategy<ProtocolMessage>() { @Override public void dispatch(ProtocolMessage message) { dispatchIncomingMessage(message); } @Override public void handleDispatchingError(String info, Exception ex) { handleErrorsFromIncomingMessageDispatcher(info, ex); } @Override public void handleQueueingError(String info, Exception ex) { handleErrorsFromIncomingMessageDispatcher(info, ex); } }); } // Setup Outgoing ProxyMessage Dispatcher synchronized(OUTGOING_MESSAGE_QUEUE_THREAD_LOCK) { // Ensure outgoingProxyMessageDispatcher is null if (_outgoingProxyMessageDispatcher != null) { _outgoingProxyMessageDispatcher.dispose(); _outgoingProxyMessageDispatcher = null; } _outgoingProxyMessageDispatcher = new ProxyMessageDispatcher<ProtocolMessage>("OUTGOING_MESSAGE_DISPATCHER",new IDispatchingStrategy<ProtocolMessage>() { @Override public void dispatch(ProtocolMessage message) { dispatchOutgoingMessage(message); } @Override public void handleDispatchingError(String info, Exception ex) { handleErrorsFromOutgoingMessageDispatcher(info, ex); } @Override public void handleQueueingError(String info, Exception ex) { handleErrorsFromOutgoingMessageDispatcher(info, ex); } }); } rpcResponseListeners = new SparseArray<OnRPCResponseListener>(); rpcNotificationListeners = new SparseArray<CopyOnWriteArrayList<OnRPCNotificationListener>>(); // Initialize the proxy try { initializeProxy(); } catch (SdlException e) { // Couldn't initialize the proxy // Dispose threads and then rethrow exception if (_internalProxyMessageDispatcher != null) { _internalProxyMessageDispatcher.dispose(); _internalProxyMessageDispatcher = null; } if (_incomingProxyMessageDispatcher != null) { _incomingProxyMessageDispatcher.dispose(); _incomingProxyMessageDispatcher = null; } if (_outgoingProxyMessageDispatcher != null) { _outgoingProxyMessageDispatcher.dispose(); _outgoingProxyMessageDispatcher = null; } throw e; } // Trace that ctor has fired SdlTrace.logProxyEvent("SdlProxy Created, instanceID=" + this.toString(), SDL_LIB_TRACE_KEY); } protected SdlProxyBase(proxyListenerType listener, SdlProxyConfigurationResources sdlProxyConfigurationResources, boolean enableAdvancedLifecycleManagement, String appName, Vector<TTSChunk> ttsName, String ngnMediaScreenAppName, Vector<String> vrSynonyms, Boolean isMediaApp, SdlMsgVersion sdlMsgVersion, Language languageDesired, Language hmiDisplayLanguageDesired, Vector<AppHMIType> appType, String appID, String autoActivateID, boolean callbackToUIThread, boolean preRegister, String sHashID, Boolean bEnableResume, BaseTransportConfig transportConfig) throws SdlException { performBaseCommon(listener, sdlProxyConfigurationResources, enableAdvancedLifecycleManagement, appName, ttsName, ngnMediaScreenAppName, vrSynonyms, isMediaApp, sdlMsgVersion, languageDesired, hmiDisplayLanguageDesired, appType, appID, autoActivateID, callbackToUIThread, preRegister, sHashID, bEnableResume, transportConfig); } /** * Constructor. * * @param listener Type of listener for this proxy base. * @param sdlProxyConfigurationResources Configuration resources for this proxy. * @param enableAdvancedLifecycleManagement Flag that ALM should be enabled or not. * @param appName Client application name. * @param ttsName TTS name. * @param ngnMediaScreenAppName Media Screen Application name. * @param vrSynonyms List of synonyms. * @param isMediaApp Flag that indicates that client application if media application or not. * @param sdlMsgVersion Version of Sdl Message. * @param languageDesired Desired language. * @param hmiDisplayLanguageDesired Desired language for HMI. * @param appType Type of application. * @param appID Application identifier. * @param autoActivateID Auto activation identifier. * @param callbackToUIThread Flag that indicates that this proxy should send callback to UI thread or not. * @param preRegister Flag that indicates that this proxy should be pre-registerd or not. * @param transportConfig Configuration of transport to be used by underlying connection. * @throws SdlException if there is an unrecoverable error class might throw an exception. */ protected SdlProxyBase(proxyListenerType listener, SdlProxyConfigurationResources sdlProxyConfigurationResources, boolean enableAdvancedLifecycleManagement, String appName, Vector<TTSChunk> ttsName, String ngnMediaScreenAppName, Vector<String> vrSynonyms, Boolean isMediaApp, SdlMsgVersion sdlMsgVersion, Language languageDesired, Language hmiDisplayLanguageDesired, Vector<AppHMIType> appType, String appID, String autoActivateID, boolean callbackToUIThread, boolean preRegister, BaseTransportConfig transportConfig) throws SdlException { performBaseCommon(listener, sdlProxyConfigurationResources, enableAdvancedLifecycleManagement, appName, ttsName, ngnMediaScreenAppName, vrSynonyms, isMediaApp, sdlMsgVersion, languageDesired, hmiDisplayLanguageDesired, appType, appID, autoActivateID, callbackToUIThread, preRegister, null, null, transportConfig); } private Intent createBroadcastIntent() { Intent sendIntent = new Intent(); sendIntent.setAction("com.smartdevicelink.broadcast"); sendIntent.putExtra("APP_NAME", this._applicationName); sendIntent.putExtra("APP_ID", this._appID); sendIntent.putExtra("RPC_NAME", ""); sendIntent.putExtra("TYPE", ""); sendIntent.putExtra("SUCCESS", true); sendIntent.putExtra("CORRID", 0); sendIntent.putExtra("FUNCTION_NAME", ""); sendIntent.putExtra("COMMENT1", ""); sendIntent.putExtra("COMMENT2", ""); sendIntent.putExtra("COMMENT3", ""); sendIntent.putExtra("COMMENT4", ""); sendIntent.putExtra("COMMENT5", ""); sendIntent.putExtra("COMMENT6", ""); sendIntent.putExtra("COMMENT7", ""); sendIntent.putExtra("COMMENT8", ""); sendIntent.putExtra("COMMENT9", ""); sendIntent.putExtra("COMMENT10", ""); sendIntent.putExtra("DATA", ""); sendIntent.putExtra("SHOW_ON_UI", true); return sendIntent; } private void updateBroadcastIntent(Intent sendIntent, String sKey, String sValue) { if (sValue == null) sValue = ""; sendIntent.putExtra(sKey, sValue); } private void updateBroadcastIntent(Intent sendIntent, String sKey, boolean bValue) { sendIntent.putExtra(sKey, bValue); } private void updateBroadcastIntent(Intent sendIntent, String sKey, int iValue) { sendIntent.putExtra(sKey, iValue); } private Service getService() { Service myService = null; if (_proxyListener != null && _proxyListener instanceof Service) { myService = (Service) _proxyListener; } else if (_appService != null) { myService = _appService; } if (myService != null) { try { return myService; } catch(Exception ex) { return null; } } return null; } private void sendBroadcastIntent(Intent sendIntent) { Service myService; if (_proxyListener != null && _proxyListener instanceof Service) { myService = (Service) _proxyListener; } else if (_appService != null) { myService = _appService; } else { return; } try { Context myContext = myService.getApplicationContext(); if (myContext != null) myContext.sendBroadcast(sendIntent); } catch(Exception ex) { //If the service or context has become unavailable unexpectedly, catch the exception and move on -- no broadcast log will occur. } } private HttpURLConnection getURLConnection(Headers myHeader, String sURLString, int Timeout, int iContentLen) { String sContentType = "application/json"; int CONNECTION_TIMEOUT = Timeout * 1000; int READ_TIMEOUT = Timeout * 1000; boolean bDoOutput = true; boolean bDoInput = true; boolean bUsesCaches = false; String sRequestMeth = "POST"; boolean bInstFolRed = false; String sCharSet = "utf-8"; int iContentLength = iContentLen; URL url; HttpURLConnection urlConnection; Intent sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "FUNCTION_NAME", "getURLConnection"); updateBroadcastIntent(sendIntent, "COMMENT1", "Actual Content Length: " + iContentLen); if (myHeader != null) { //if the header isn't null, use it and replace the hardcoded params int iTimeout; int iReadTimeout; sContentType = myHeader.getContentType(); iTimeout = myHeader.getConnectTimeout(); bDoOutput = myHeader.getDoOutput(); bDoInput = myHeader.getDoInput(); bUsesCaches = myHeader.getUseCaches(); sRequestMeth = myHeader.getRequestMethod(); iReadTimeout = myHeader.getReadTimeout(); bInstFolRed = myHeader.getInstanceFollowRedirects(); sCharSet = myHeader.getCharset(); iContentLength = myHeader.getContentLength(); CONNECTION_TIMEOUT = iTimeout*1000; READ_TIMEOUT = iReadTimeout*1000; updateBroadcastIntent(sendIntent, "COMMENT2", "\nHeader Defined Content Length: " + iContentLength); } try { url = new URL(sURLString); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setConnectTimeout(CONNECTION_TIMEOUT); urlConnection.setDoOutput(bDoOutput); urlConnection.setDoInput(bDoInput); urlConnection.setRequestMethod(sRequestMeth); urlConnection.setReadTimeout(READ_TIMEOUT); urlConnection.setInstanceFollowRedirects(bInstFolRed); urlConnection.setRequestProperty("Content-Type", sContentType); urlConnection.setRequestProperty("charset", sCharSet); urlConnection.setRequestProperty("Content-Length", "" + Integer.toString(iContentLength)); urlConnection.setUseCaches(bUsesCaches); return urlConnection; } catch (Exception e) { return null; } finally { sendBroadcastIntent(sendIntent); } } private void sendOnSystemRequestToUrl(OnSystemRequest msg) { Intent sendIntent = createBroadcastIntent(); Intent sendIntent2 = createBroadcastIntent(); HttpURLConnection urlConnection = null; boolean bLegacy = false; String sURLString; if (!getPoliciesURL().equals("")) sURLString = sPoliciesURL; else sURLString = msg.getUrl(); Integer iTimeout = msg.getTimeout(); if (iTimeout == null) iTimeout = 2000; Headers myHeader = msg.getHeader(); updateBroadcastIntent(sendIntent, "FUNCTION_NAME", "sendOnSystemRequestToUrl"); updateBroadcastIntent(sendIntent, "COMMENT5", "\r\nCloud URL: " + sURLString); try { if (myHeader == null) updateBroadcastIntent(sendIntent, "COMMENT7", "\r\nHTTPRequest Header is null"); String sBodyString = msg.getBody(); JSONObject jsonObjectToSendToServer; String valid_json = ""; int length; if (sBodyString == null) { if(RequestType.HTTP.equals(msg.getRequestType())){ length = msg.getBulkData().length; Intent sendIntent3 = createBroadcastIntent(); updateBroadcastIntent(sendIntent3, "FUNCTION_NAME", "replace"); updateBroadcastIntent(sendIntent3, "COMMENT1", "Valid Json length before replace: " + length); sendBroadcastIntent(sendIntent3); }else{ List<String> legacyData = msg.getLegacyData(); JSONArray jsonArrayOfSdlPPackets = new JSONArray(legacyData); jsonObjectToSendToServer = new JSONObject(); jsonObjectToSendToServer.put("data", jsonArrayOfSdlPPackets); bLegacy = true; updateBroadcastIntent(sendIntent, "COMMENT6", "\r\nLegacy SystemRequest: true"); valid_json = jsonObjectToSendToServer.toString().replace("\\", ""); length = valid_json.getBytes("UTF-8").length; } } else { Intent sendIntent3 = createBroadcastIntent(); updateBroadcastIntent(sendIntent3, "FUNCTION_NAME", "replace"); updateBroadcastIntent(sendIntent3, "COMMENT1", "Valid Json length before replace: " + sBodyString.getBytes("UTF-8").length); sendBroadcastIntent(sendIntent3); valid_json = sBodyString.replace("\\", ""); length = valid_json.getBytes("UTF-8").length; } urlConnection = getURLConnection(myHeader, sURLString, iTimeout, length); if (urlConnection == null) { Log.i(TAG, "urlConnection is null, check RPC input parameters"); updateBroadcastIntent(sendIntent, "COMMENT2", "urlConnection is null, check RPC input parameters"); return; } DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream()); if(RequestType.HTTP.equals(msg.getRequestType())){ wr.write(msg.getBulkData()); }else{ wr.writeBytes(valid_json); } wr.flush(); wr.close(); long BeforeTime = System.currentTimeMillis(); long AfterTime = System.currentTimeMillis(); final long roundtriptime = AfterTime - BeforeTime; updateBroadcastIntent(sendIntent, "COMMENT4", " Round trip time: " + roundtriptime); updateBroadcastIntent(sendIntent, "COMMENT1", "Received response from cloud, response code=" + urlConnection.getResponseCode() + " "); int iResponseCode = urlConnection.getResponseCode(); if (iResponseCode != HttpURLConnection.HTTP_OK) { Log.i(TAG, "Response code not HTTP_OK, returning from sendOnSystemRequestToUrl."); updateBroadcastIntent(sendIntent, "COMMENT2", "Response code not HTTP_OK, aborting request. "); return; } InputStream is = urlConnection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuilder response = new StringBuilder(); while((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); //We've read the body if(RequestType.HTTP.equals(msg.getRequestType())){ // Create the SystemRequest RPC to send to module. PutFile putFile = new PutFile(); putFile.setFileType(FileType.JSON); putFile.setCorrelationID(POLICIES_CORRELATION_ID); putFile.setSdlFileName("response_data"); putFile.setFileData(response.toString().getBytes("UTF-8")); updateBroadcastIntent(sendIntent, "DATA", "Data from cloud response: " + response.toString()); sendRPCRequestPrivate(putFile); Log.i("sendSystemRequestToUrl", "sent to sdl"); updateBroadcastIntent(sendIntent2, "RPC_NAME", FunctionID.PUT_FILE.toString()); updateBroadcastIntent(sendIntent2, "TYPE", RPCMessage.KEY_REQUEST); updateBroadcastIntent(sendIntent2, "CORRID", putFile.getCorrelationID()); }else{ Vector<String> cloudDataReceived = new Vector<String>(); final String dataKey = "data"; // Convert the response to JSON JSONObject jsonResponse = new JSONObject(response.toString()); if(jsonResponse.has(dataKey)){ if (jsonResponse.get(dataKey) instanceof JSONArray) { JSONArray jsonArray = jsonResponse.getJSONArray(dataKey); for (int i=0; i<jsonArray.length(); i++) { if (jsonArray.get(i) instanceof String) { cloudDataReceived.add(jsonArray.getString(i)); //Log.i("sendSystemRequestToUrl", "jsonArray.getString(i): " + jsonArray.getString(i)); } } } else if (jsonResponse.get(dataKey) instanceof String) { cloudDataReceived.add(jsonResponse.getString(dataKey)); //Log.i("sendSystemRequestToUrl", "jsonResponse.getString(data): " + jsonResponse.getString("data")); } } else { DebugTool.logError("sendSystemRequestToUrl: Data in JSON Object neither an array nor a string."); //Log.i("sendSystemRequestToUrl", "sendSystemRequestToUrl: Data in JSON Object neither an array nor a string."); return; } String sResponse = cloudDataReceived.toString(); if (sResponse.length() > 512) { sResponse = sResponse.substring(0, 511); } updateBroadcastIntent(sendIntent, "DATA", "Data from cloud response: " + sResponse); // Send new SystemRequest to SDL SystemRequest mySystemRequest; if (bLegacy){ mySystemRequest = RPCRequestFactory.buildSystemRequestLegacy(cloudDataReceived, getPoliciesReservedCorrelationID()); }else{ mySystemRequest = RPCRequestFactory.buildSystemRequest(response.toString(), getPoliciesReservedCorrelationID()); } if (getIsConnected()) { sendRPCRequestPrivate(mySystemRequest); Log.i("sendSystemRequestToUrl", "sent to sdl"); updateBroadcastIntent(sendIntent2, "RPC_NAME", FunctionID.SYSTEM_REQUEST.toString()); updateBroadcastIntent(sendIntent2, "TYPE", RPCMessage.KEY_REQUEST); updateBroadcastIntent(sendIntent2, "CORRID", mySystemRequest.getCorrelationID()); } } } catch (SdlException e) { DebugTool.logError("sendSystemRequestToUrl: Could not get data from JSONObject received.", e); updateBroadcastIntent(sendIntent, "COMMENT3", " SdlException encountered sendOnSystemRequestToUrl: "+ e); //Log.i("pt", "sendSystemRequestToUrl: Could not get data from JSONObject received."+ e); } catch (JSONException e) { DebugTool.logError("sendSystemRequestToUrl: JSONException: ", e); updateBroadcastIntent(sendIntent, "COMMENT3", " JSONException encountered sendOnSystemRequestToUrl: "+ e); //Log.i("pt", "sendSystemRequestToUrl: JSONException: "+ e); } catch (UnsupportedEncodingException e) { DebugTool.logError("sendSystemRequestToUrl: Could not encode string.", e); updateBroadcastIntent(sendIntent, "COMMENT3", " UnsupportedEncodingException encountered sendOnSystemRequestToUrl: "+ e); //Log.i("pt", "sendSystemRequestToUrl: Could not encode string."+ e); } catch (ProtocolException e) { DebugTool.logError("sendSystemRequestToUrl: Could not set request method to post.", e); updateBroadcastIntent(sendIntent, "COMMENT3", " ProtocolException encountered sendOnSystemRequestToUrl: "+ e); //Log.i("pt", "sendSystemRequestToUrl: Could not set request method to post."+ e); } catch (MalformedURLException e) { DebugTool.logError("sendSystemRequestToUrl: URL Exception when sending SystemRequest to an external server.", e); updateBroadcastIntent(sendIntent, "COMMENT3", " MalformedURLException encountered sendOnSystemRequestToUrl: "+ e); //Log.i("pt", "sendSystemRequestToUrl: URL Exception when sending SystemRequest to an external server."+ e); } catch (IOException e) { DebugTool.logError("sendSystemRequestToUrl: IOException: ", e); updateBroadcastIntent(sendIntent, "COMMENT3", " IOException while sending to cloud: IOException: "+ e); //Log.i("pt", "sendSystemRequestToUrl: IOException: "+ e); } catch (Exception e) { DebugTool.logError("sendSystemRequestToUrl: Unexpected Exception: ", e); updateBroadcastIntent(sendIntent, "COMMENT3", " Exception encountered sendOnSystemRequestToUrl: "+ e); //Log.i("pt", "sendSystemRequestToUrl: Unexpected Exception: " + e); } finally { sendBroadcastIntent(sendIntent); sendBroadcastIntent(sendIntent2); if (iFileCount < 10) iFileCount++; else iFileCount = 0; if(urlConnection != null) { urlConnection.disconnect(); } } } private int getPoliciesReservedCorrelationID() { return POLICIES_CORRELATION_ID; } // Test correlationID private boolean isCorrelationIDProtected(Integer correlationID) { return correlationID != null && (HEARTBEAT_CORRELATION_ID == correlationID || REGISTER_APP_INTERFACE_CORRELATION_ID == correlationID || UNREGISTER_APP_INTERFACE_CORRELATION_ID == correlationID || POLICIES_CORRELATION_ID == correlationID); } // Protected isConnected method to allow legacy proxy to poll isConnected state public Boolean getIsConnected() { return sdlSession != null && sdlSession.getIsConnected(); } /** * Returns whether the application is registered in SDL. Note: for testing * purposes, it's possible that the connection is established, but the * application is not registered. * * @return true if the application is registered in SDL */ public Boolean getAppInterfaceRegistered() { return _appInterfaceRegisterd; } // Function to initialize new proxy connection private void initializeProxy() throws SdlException { // Reset all of the flags and state variables _haveReceivedFirstNonNoneHMILevel = false; _haveReceivedFirstFocusLevel = false; _haveReceivedFirstFocusLevelFull = false; _appInterfaceRegisterd = _preRegisterd; _putFileListenerList.clear(); _sdlIntefaceAvailablity = SdlInterfaceAvailability.SDL_INTERFACE_UNAVAILABLE; //Initialize _systemCapabilityManager here. _systemCapabilityManager = new SystemCapabilityManager(_internalInterface); // Setup SdlConnection synchronized(CONNECTION_REFERENCE_LOCK) { this.sdlSession = SdlSession.createSession(_wiproVersion,_interfaceBroker, _transportConfig); } synchronized(CONNECTION_REFERENCE_LOCK) { this.sdlSession.startSession(); sendTransportBroadcast(); } } /** * This method will fake the multiplex connection event */ @SuppressWarnings("unused") public void forceOnConnected(){ synchronized(CONNECTION_REFERENCE_LOCK) { if (sdlSession != null) { if(sdlSession.getSdlConnection()==null){ //There is an issue when switching from v1 to v2+ where the connection is closed. So we restart the session during this call. try { sdlSession.startSession(); } catch (SdlException e) { e.printStackTrace(); } } sdlSession.getSdlConnection().forceHardwareConnectEvent(TransportType.BLUETOOTH); } } } public void sendTransportBroadcast() { if (sdlSession == null || _transportConfig == null) return; String sTransComment = sdlSession.getBroadcastComment(_transportConfig); if (sTransComment == null || sTransComment.equals("")) return; Intent sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "FUNCTION_NAME", "initializeProxy"); updateBroadcastIntent(sendIntent, "COMMENT1", sTransComment); sendBroadcastIntent(sendIntent); } /** * Public method to enable the siphon transport */ @SuppressWarnings("unused") public void enableSiphonDebug() { short enabledPortNumber = SiphonServer.enableSiphonServer(); String sSiphonPortNumber = "Enabled Siphon Port Number: " + enabledPortNumber; Intent sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "FUNCTION_NAME", "enableSiphonDebug"); updateBroadcastIntent(sendIntent, "COMMENT1", sSiphonPortNumber); sendBroadcastIntent(sendIntent); } /** * Public method to disable the Siphon Trace Server */ @SuppressWarnings("unused") public void disableSiphonDebug() { short disabledPortNumber = SiphonServer.disableSiphonServer(); if (disabledPortNumber != -1) { String sSiphonPortNumber = "Disabled Siphon Port Number: " + disabledPortNumber; Intent sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "FUNCTION_NAME", "disableSiphonDebug"); updateBroadcastIntent(sendIntent, "COMMENT1", sSiphonPortNumber); sendBroadcastIntent(sendIntent); } } /** * Public method to enable the Debug Tool */ public static void enableDebugTool() { DebugTool.enableDebugTool(); } /** * Public method to disable the Debug Tool */ public static void disableDebugTool() { DebugTool.disableDebugTool(); } /** * Public method to determine Debug Tool enabled */ @SuppressWarnings("BooleanMethodIsAlwaysInverted") public static boolean isDebugEnabled() { return DebugTool.isDebugEnabled(); } @SuppressWarnings("unused") @Deprecated public void close() throws SdlException { dispose(); } @SuppressWarnings("UnusedParameters") private void cleanProxy(SdlDisconnectedReason disconnectedReason) throws SdlException { try { // ALM Specific Cleanup if (_advancedLifecycleManagementEnabled) { _sdlConnectionState = SdlConnectionState.SDL_DISCONNECTED; firstTimeFull = true; // Should we wait for the interface to be unregistered? Boolean waitForInterfaceUnregistered = false; // Unregister app interface synchronized(CONNECTION_REFERENCE_LOCK) { if (getIsConnected() && getAppInterfaceRegistered()) { waitForInterfaceUnregistered = true; unregisterAppInterfacePrivate(UNREGISTER_APP_INTERFACE_CORRELATION_ID); } } // Wait for the app interface to be unregistered if (waitForInterfaceUnregistered) { synchronized(APP_INTERFACE_REGISTERED_LOCK) { try { APP_INTERFACE_REGISTERED_LOCK.wait(3000); } catch (InterruptedException e) { // Do nothing } } } } if(rpcResponseListeners != null){ rpcResponseListeners.clear(); } if(rpcNotificationListeners != null){ rpcNotificationListeners.clear(); } // Clean up SDL Connection synchronized(CONNECTION_REFERENCE_LOCK) { if (sdlSession != null) sdlSession.close(); } } finally { SdlTrace.logProxyEvent("SdlProxy cleaned.", SDL_LIB_TRACE_KEY); } } /** * Terminates the App's Interface Registration, closes the transport connection, ends the protocol session, and frees any resources used by the proxy. */ public void dispose() throws SdlException { if (_proxyDisposed) { throw new SdlException("This object has been disposed, it is no long capable of executing methods.", SdlExceptionCause.SDL_PROXY_DISPOSED); } _proxyDisposed = true; SdlTrace.logProxyEvent("Application called dispose() method.", SDL_LIB_TRACE_KEY); try{ // Clean the proxy cleanProxy(SdlDisconnectedReason.APPLICATION_REQUESTED_DISCONNECT); // Close IncomingProxyMessageDispatcher thread synchronized(INCOMING_MESSAGE_QUEUE_THREAD_LOCK) { if (_incomingProxyMessageDispatcher != null) { _incomingProxyMessageDispatcher.dispose(); _incomingProxyMessageDispatcher = null; } } // Close OutgoingProxyMessageDispatcher thread synchronized(OUTGOING_MESSAGE_QUEUE_THREAD_LOCK) { if (_outgoingProxyMessageDispatcher != null) { _outgoingProxyMessageDispatcher.dispose(); _outgoingProxyMessageDispatcher = null; } } // Close InternalProxyMessageDispatcher thread synchronized(INTERNAL_MESSAGE_QUEUE_THREAD_LOCK) { if (_internalProxyMessageDispatcher != null) { _internalProxyMessageDispatcher.dispose(); _internalProxyMessageDispatcher = null; } } _traceDeviceInterrogator = null; rpcResponseListeners = null; } finally { SdlTrace.logProxyEvent("SdlProxy disposed.", SDL_LIB_TRACE_KEY); } } // end-method private final static Object CYCLE_LOCK = new Object(); private boolean _cycling = false; // Method to cycle the proxy, only called in ALM protected void cycleProxy(SdlDisconnectedReason disconnectedReason) { if (_cycling) return; synchronized(CYCLE_LOCK) { try{ _cycling = true; cleanProxy(disconnectedReason); initializeProxy(); if(!SdlDisconnectedReason.LEGACY_BLUETOOTH_MODE_ENABLED.equals(disconnectedReason)){//We don't want to alert higher if we are just cycling for legacy bluetooth notifyProxyClosed("Sdl Proxy Cycled", new SdlException("Sdl Proxy Cycled", SdlExceptionCause.SDL_PROXY_CYCLED), disconnectedReason); } } catch (SdlException e) { Intent sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "FUNCTION_NAME", "cycleProxy"); updateBroadcastIntent(sendIntent, "COMMENT1", "Proxy cycled, exception cause: " + e.getSdlExceptionCause()); sendBroadcastIntent(sendIntent); switch(e.getSdlExceptionCause()) { case BLUETOOTH_DISABLED: notifyProxyClosed("Bluetooth is disabled. Bluetooth must be enabled to connect to SDL. Reattempt a connection once Bluetooth is enabled.", new SdlException("Bluetooth is disabled. Bluetooth must be enabled to connect to SDL. Reattempt a connection once Bluetooth is enabled.", SdlExceptionCause.BLUETOOTH_DISABLED), SdlDisconnectedReason.BLUETOOTH_DISABLED); break; case BLUETOOTH_ADAPTER_NULL: notifyProxyClosed("Cannot locate a Bluetooth adapater. A SDL connection is impossible on this device until a Bluetooth adapter is added.", new SdlException("Cannot locate a Bluetooth adapater. A SDL connection is impossible on this device until a Bluetooth adapter is added.", SdlExceptionCause.BLUETOOTH_ADAPTER_NULL), SdlDisconnectedReason.BLUETOOTH_ADAPTER_ERROR); break; default : notifyProxyClosed("Cycling the proxy failed.", e, SdlDisconnectedReason.GENERIC_ERROR); break; } } catch (Exception e) { notifyProxyClosed("Cycling the proxy failed.", e, SdlDisconnectedReason.GENERIC_ERROR); } _cycling = false; } } private void dispatchIncomingMessage(ProtocolMessage message) { try{ // Dispatching logic if (message.getSessionType().equals(SessionType.RPC) ||message.getSessionType().equals(SessionType.BULK_DATA) ) { try { if (_wiproVersion == 1) { if (message.getVersion() > 1) setWiProVersion(message.getVersion()); } Hashtable<String, Object> hash = new Hashtable<String, Object>(); if (_wiproVersion > 1) { Hashtable<String, Object> hashTemp = new Hashtable<String, Object>(); hashTemp.put(RPCMessage.KEY_CORRELATION_ID, message.getCorrID()); if (message.getJsonSize() > 0) { final Hashtable<String, Object> mhash = JsonRPCMarshaller.unmarshall(message.getData()); //hashTemp.put(Names.parameters, mhash.get(Names.parameters)); if (mhash != null) { hashTemp.put(RPCMessage.KEY_PARAMETERS, mhash); } } String functionName = FunctionID.getFunctionName(message.getFunctionID()); if (functionName != null) { hashTemp.put(RPCMessage.KEY_FUNCTION_NAME, functionName); } else { DebugTool.logWarning("Dispatch Incoming Message - function name is null unknown RPC. FunctionId: " + message.getFunctionID()); return; } if (message.getRPCType() == 0x00) { hash.put(RPCMessage.KEY_REQUEST, hashTemp); } else if (message.getRPCType() == 0x01) { hash.put(RPCMessage.KEY_RESPONSE, hashTemp); } else if (message.getRPCType() == 0x02) { hash.put(RPCMessage.KEY_NOTIFICATION, hashTemp); } if (message.getBulkData() != null) hash.put(RPCStruct.KEY_BULK_DATA, message.getBulkData()); if (message.getPayloadProtected()) hash.put(RPCStruct.KEY_PROTECTED, true); } else { hash = JsonRPCMarshaller.unmarshall(message.getData()); } handleRPCMessage(hash); } catch (final Exception excp) { DebugTool.logError("Failure handling protocol message: " + excp.toString(), excp); passErrorToProxyListener("Error handing incoming protocol message.", excp); } // end-catch } //else { Handle other protocol message types here} } catch (final Exception e) { // Pass error to application through listener DebugTool.logError("Error handing proxy event.", e); passErrorToProxyListener("Error handing incoming protocol message.", e); } } private byte getWiProVersion() { return this._wiproVersion; } private void setWiProVersion(byte version) { this._wiproVersion = version; } public String serializeJSON(RPCMessage msg) { String sReturn; try { sReturn = msg.serializeJSON(getWiProVersion()).toString(2); } catch (final Exception e) { DebugTool.logError("Error handing proxy event.", e); passErrorToProxyListener("Error serializing message.", e); return null; } return sReturn; } private void handleErrorsFromIncomingMessageDispatcher(String info, Exception e) { passErrorToProxyListener(info, e); } private void dispatchOutgoingMessage(ProtocolMessage message) { synchronized(CONNECTION_REFERENCE_LOCK) { if (sdlSession != null) { sdlSession.sendMessage(message); } } SdlTrace.logProxyEvent("SdlProxy sending Protocol Message: " + message.toString(), SDL_LIB_TRACE_KEY); } private void handleErrorsFromOutgoingMessageDispatcher(String info, Exception e) { passErrorToProxyListener(info, e); } void dispatchInternalMessage(final InternalProxyMessage message) { try{ switch (message.getFunctionName()) { case InternalProxyMessage.OnProxyError: { final OnError msg = (OnError) message; if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onError(msg.getInfo(), msg.getException()); } }); } else { _proxyListener.onError(msg.getInfo(), msg.getException()); } break; } case InternalProxyMessage.OnServiceEnded: { final OnServiceEnded msg = (OnServiceEnded) message; if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onServiceEnded(msg); } }); } else { _proxyListener.onServiceEnded(msg); } break; } case InternalProxyMessage.OnServiceNACKed: { final OnServiceNACKed msg = (OnServiceNACKed) message; if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onServiceNACKed(msg); } }); } else { _proxyListener.onServiceNACKed(msg); } break; } case InternalProxyMessage.OnProxyOpened: if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { ((IProxyListener) _proxyListener).onProxyOpened(); } }); } else { ((IProxyListener) _proxyListener).onProxyOpened(); } break; case InternalProxyMessage.OnProxyClosed: { final OnProxyClosed msg = (OnProxyClosed) message; if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onProxyClosed(msg.getInfo(), msg.getException(), msg.getReason()); } }); } else { _proxyListener.onProxyClosed(msg.getInfo(), msg.getException(), msg.getReason()); } break; } default: // Diagnostics SdlTrace.logProxyEvent("Unknown RPC Message encountered. Check for an updated version of the SDL Proxy.", SDL_LIB_TRACE_KEY); DebugTool.logError("Unknown RPC Message encountered. Check for an updated version of the SDL Proxy."); break; } SdlTrace.logProxyEvent("Proxy fired callback: " + message.getFunctionName(), SDL_LIB_TRACE_KEY); } catch(final Exception e) { // Pass error to application through listener DebugTool.logError("Error handing proxy event.", e); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onError("Error handing proxy event.", e); } }); } else { _proxyListener.onError("Error handing proxy event.", e); } } } private void handleErrorsFromInternalMessageDispatcher(String info, Exception e) { DebugTool.logError(info, e); // This error cannot be passed to the user, as it indicates an error // in the communication between the proxy and the application. DebugTool.logError("InternalMessageDispatcher failed.", e); // Note, this is the only place where the _proxyListener should be referenced asdlhronously, // with an error on the internalMessageDispatcher, we have no other reliable way of // communicating with the application. notifyProxyClosed("Proxy callback dispatcher is down. Proxy instance is invalid.", e, SdlDisconnectedReason.GENERIC_ERROR); _proxyListener.onError("Proxy callback dispatcher is down. Proxy instance is invalid.", e); } // Private sendPRCRequest method. All RPCRequests are funneled through this method after // error checking. private void sendRPCRequestPrivate(RPCRequest request) throws SdlException { try { SdlTrace.logRPCEvent(InterfaceActivityDirection.Transmit, request, SDL_LIB_TRACE_KEY); byte[] msgBytes = JsonRPCMarshaller.marshall(request, _wiproVersion); ProtocolMessage pm = new ProtocolMessage(); pm.setData(msgBytes); if (sdlSession != null) pm.setSessionID(sdlSession.getSessionId()); pm.setMessageType(MessageType.RPC); pm.setSessionType(SessionType.RPC); pm.setFunctionID(FunctionID.getFunctionId(request.getFunctionName())); pm.setPayloadProtected(request.isPayloadProtected()); if (request.getCorrelationID() == null) { //Log error here throw new SdlException("CorrelationID cannot be null. RPC: " + request.getFunctionName(), SdlExceptionCause.INVALID_ARGUMENT); } pm.setCorrID(request.getCorrelationID()); if (request.getBulkData() != null){ pm.setBulkData(request.getBulkData()); } if(request.getFunctionName().equalsIgnoreCase(FunctionID.PUT_FILE.name())){ pm.setPriorityCoefficient(1); } // Queue this outgoing message synchronized(OUTGOING_MESSAGE_QUEUE_THREAD_LOCK) { if (_outgoingProxyMessageDispatcher != null) { _outgoingProxyMessageDispatcher.queueMessage(pm); //Since the message is queued we can add it's listener to our list OnRPCResponseListener listener = request.getOnRPCResponseListener(); if(request.getMessageType().equals(RPCMessage.KEY_REQUEST)){//We might want to include other message types in the future addOnRPCResponseListener(listener, request.getCorrelationID(), msgBytes.length); } } } } catch (OutOfMemoryError e) { SdlTrace.logProxyEvent("OutOfMemory exception while sending request " + request.getFunctionName(), SDL_LIB_TRACE_KEY); throw new SdlException("OutOfMemory exception while sending request " + request.getFunctionName(), e, SdlExceptionCause.INVALID_ARGUMENT); } } /** * Only call this method for a PutFile response. It will cause a class cast exception if not. * @param correlationId correlation id of the packet being updated * @param bytesWritten how many bytes were written * @param totalSize the total size in bytes */ @SuppressWarnings("unused") public void onPacketProgress(int correlationId, long bytesWritten, long totalSize){ synchronized(ON_UPDATE_LISTENER_LOCK){ if(rpcResponseListeners !=null && rpcResponseListeners.indexOfKey(correlationId)>=0){ ((OnPutFileUpdateListener)rpcResponseListeners.get(correlationId)).onUpdate(correlationId, bytesWritten, totalSize); } } } /** * Will provide callback to the listener either onFinish or onError depending on the RPCResponses result code, * <p>Will automatically remove the listener for the list of listeners on completion. * @param msg The RPCResponse message that was received * @return if a listener was called or not */ @SuppressWarnings("UnusedReturnValue") private boolean onRPCResponseReceived(RPCResponse msg){ synchronized(ON_UPDATE_LISTENER_LOCK){ int correlationId = msg.getCorrelationID(); if(rpcResponseListeners !=null && rpcResponseListeners.indexOfKey(correlationId)>=0){ OnRPCResponseListener listener = rpcResponseListeners.get(correlationId); if(msg.getSuccess()){ listener.onResponse(correlationId, msg); }else{ listener.onError(correlationId, msg.getResultCode(), msg.getInfo()); } rpcResponseListeners.remove(correlationId); return true; } return false; } } /** * Add a listener that will receive the response to the specific RPCRequest sent with the corresponding correlation id * @param listener that will get called back when a response is received * @param correlationId of the RPCRequest that was sent * @param totalSize only include if this is an OnPutFileUpdateListener. Otherwise it will be ignored. */ public void addOnRPCResponseListener(OnRPCResponseListener listener,int correlationId, int totalSize){ synchronized(ON_UPDATE_LISTENER_LOCK){ if(rpcResponseListeners!=null && listener !=null){ if(listener.getListenerType() == OnRPCResponseListener.UPDATE_LISTENER_TYPE_PUT_FILE){ ((OnPutFileUpdateListener)listener).setTotalSize(totalSize); } listener.onStart(correlationId); rpcResponseListeners.put(correlationId, listener); } } } @SuppressWarnings("unused") public SparseArray<OnRPCResponseListener> getResponseListeners(){ synchronized(ON_UPDATE_LISTENER_LOCK){ return this.rpcResponseListeners; } } @SuppressWarnings("UnusedReturnValue") public boolean onRPCNotificationReceived(RPCNotification notification){ synchronized(ON_NOTIFICATION_LISTENER_LOCK){ CopyOnWriteArrayList<OnRPCNotificationListener> listeners = rpcNotificationListeners.get(FunctionID.getFunctionId(notification.getFunctionName())); if(listeners!=null && listeners.size()>0) { for (OnRPCNotificationListener listener : listeners) { listener.onNotified(notification); } return true; } return false; } } /** * This will ad a listener for the specific type of notification. As of now it will only allow * a single listener per notification function id * @param notificationId The notification type that this listener is designated for * @param listener The listener that will be called when a notification of the provided type is received */ @SuppressWarnings("unused") public void addOnRPCNotificationListener(FunctionID notificationId, OnRPCNotificationListener listener){ synchronized(ON_NOTIFICATION_LISTENER_LOCK){ if(notificationId != null && listener != null){ if(rpcNotificationListeners.indexOfKey(notificationId.getId()) < 0 ){ rpcNotificationListeners.put(notificationId.getId(),new CopyOnWriteArrayList<OnRPCNotificationListener>()); } rpcNotificationListeners.get(notificationId.getId()).add(listener); } } } /** * This method is no longer valid and will not remove the listener for the supplied notificaiton id * @param notificationId n/a * @see #removeOnRPCNotificationListener(FunctionID, OnRPCNotificationListener) */ @SuppressWarnings("unused") @Deprecated public void removeOnRPCNotificationListener(FunctionID notificationId){ synchronized(ON_NOTIFICATION_LISTENER_LOCK){ //rpcNotificationListeners.delete(notificationId.getId()); } } public boolean removeOnRPCNotificationListener(FunctionID notificationId, OnRPCNotificationListener listener){ synchronized(ON_NOTIFICATION_LISTENER_LOCK){ if(rpcNotificationListeners!= null && notificationId != null && listener != null && rpcNotificationListeners.indexOfKey(notificationId.getId()) >= 0){ return rpcNotificationListeners.get(notificationId.getId()).remove(listener); } } return false; } private void processRaiResponse(RegisterAppInterfaceResponse rai) { if (rai == null) return; VehicleType vt = rai.getVehicleType(); if (vt == null) return; String make = vt.getMake(); if (make == null) return; if (_secList == null) return; SdlSecurityBase sec; Service svc = getService(); SdlSecurityBase.setAppService(svc); for (Class<? extends SdlSecurityBase> cls : _secList) { try { sec = cls.newInstance(); } catch (Exception e) { continue; } if ( (sec != null) && (sec.getMakeList() != null) ) { if (sec.getMakeList().contains(make)) { setSdlSecurity(sec); sec.setAppId(_appID); if (sdlSession != null) sec.handleSdlSession(sdlSession); return; } } } } private void handleRPCMessage(Hashtable<String, Object> hash) { RPCMessage rpcMsg = new RPCMessage(hash); String functionName = rpcMsg.getFunctionName(); String messageType = rpcMsg.getMessageType(); if (messageType.equals(RPCMessage.KEY_RESPONSE)) { SdlTrace.logRPCEvent(InterfaceActivityDirection.Receive, new RPCResponse(rpcMsg), SDL_LIB_TRACE_KEY); // Check to ensure response is not from an internal message (reserved correlation ID) if (isCorrelationIDProtected((new RPCResponse(hash)).getCorrelationID())) { // This is a response generated from an internal message, it can be trapped here // The app should not receive a response for a request it did not send if ((new RPCResponse(hash)).getCorrelationID() == REGISTER_APP_INTERFACE_CORRELATION_ID && _advancedLifecycleManagementEnabled && functionName.equals(FunctionID.REGISTER_APP_INTERFACE.toString())) { final RegisterAppInterfaceResponse msg = new RegisterAppInterfaceResponse(hash); if (msg.getSuccess()) { _appInterfaceRegisterd = true; } processRaiResponse(msg); //Populate the system capability manager with the RAI response _systemCapabilityManager.parseRAIResponse(msg); Intent sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "RPC_NAME", FunctionID.REGISTER_APP_INTERFACE.toString()); updateBroadcastIntent(sendIntent, "TYPE", RPCMessage.KEY_RESPONSE); updateBroadcastIntent(sendIntent, "SUCCESS", msg.getSuccess()); updateBroadcastIntent(sendIntent, "COMMENT1", msg.getInfo()); updateBroadcastIntent(sendIntent, "COMMENT2", msg.getResultCode().toString()); updateBroadcastIntent(sendIntent, "DATA",serializeJSON(msg)); updateBroadcastIntent(sendIntent, "CORRID", msg.getCorrelationID()); sendBroadcastIntent(sendIntent); //_autoActivateIdReturned = msg.getAutoActivateID(); /*Place holder for legacy support*/ _autoActivateIdReturned = "8675309"; _prerecordedSpeech = msg.getPrerecordedSpeech(); _sdlLanguage = msg.getLanguage(); _hmiDisplayLanguage = msg.getHmiDisplayLanguage(); _sdlMsgVersion = msg.getSdlMsgVersion(); _vehicleType = msg.getVehicleType(); _systemSoftwareVersion = msg.getSystemSoftwareVersion(); _proxyVersionInfo = msg.getProxyVersionInfo(); if (_bAppResumeEnabled) { if ( (_sdlMsgVersion.getMajorVersion() > 2) && (_lastHashID != null) && (msg.getSuccess()) && (msg.getResultCode() != Result.RESUME_FAILED) ) _bResumeSuccess = true; else { _bResumeSuccess = false; _lastHashID = null; } } _diagModes = msg.getSupportedDiagModes(); String sVersionInfo = "SDL Proxy Version: " + _proxyVersionInfo; if (!isDebugEnabled()) { enableDebugTool(); DebugTool.logInfo(sVersionInfo, false); disableDebugTool(); } else DebugTool.logInfo(sVersionInfo, false); sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "FUNCTION_NAME", "RAI_RESPONSE"); updateBroadcastIntent(sendIntent, "COMMENT1", sVersionInfo); sendBroadcastIntent(sendIntent); // Send onSdlConnected message in ALM _sdlConnectionState = SdlConnectionState.SDL_CONNECTED; // If registerAppInterface failed, exit with OnProxyUnusable if (!msg.getSuccess()) { notifyProxyClosed("Unable to register app interface. Review values passed to the SdlProxy constructor. RegisterAppInterface result code: ", new SdlException("Unable to register app interface. Review values passed to the SdlProxy constructor. RegisterAppInterface result code: " + msg.getResultCode(), SdlExceptionCause.SDL_REGISTRATION_ERROR), SdlDisconnectedReason.SDL_REGISTRATION_ERROR); } if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { if (_proxyListener instanceof IProxyListener) { ((IProxyListener)_proxyListener).onRegisterAppInterfaceResponse(msg); } onRPCResponseReceived(msg); } }); } else { if (_proxyListener instanceof IProxyListener) { ((IProxyListener)_proxyListener).onRegisterAppInterfaceResponse(msg); } onRPCResponseReceived(msg); } } else if ((new RPCResponse(hash)).getCorrelationID() == POLICIES_CORRELATION_ID && functionName.equals(FunctionID.ON_ENCODED_SYNC_P_DATA.toString())) { Log.i("pt", "POLICIES_CORRELATION_ID SystemRequest Notification (Legacy)"); final OnSystemRequest msg = new OnSystemRequest(hash); // If url is not null, then send to URL if ( (msg.getUrl() != null) ) { // URL has data, attempt to post request to external server Thread handleOffboardTransmissionThread = new Thread() { @Override public void run() { sendOnSystemRequestToUrl(msg); } }; handleOffboardTransmissionThread.start(); } } else if ((new RPCResponse(hash)).getCorrelationID() == POLICIES_CORRELATION_ID && functionName.equals(FunctionID.ENCODED_SYNC_P_DATA.toString())) { Log.i("pt", "POLICIES_CORRELATION_ID SystemRequest Response (Legacy)"); final SystemRequestResponse msg = new SystemRequestResponse(hash); Intent sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "RPC_NAME", FunctionID.SYSTEM_REQUEST.toString()); updateBroadcastIntent(sendIntent, "TYPE", RPCMessage.KEY_RESPONSE); updateBroadcastIntent(sendIntent, "SUCCESS", msg.getSuccess()); updateBroadcastIntent(sendIntent, "COMMENT1", msg.getInfo()); updateBroadcastIntent(sendIntent, "COMMENT2", msg.getResultCode().toString()); updateBroadcastIntent(sendIntent, "CORRID", msg.getCorrelationID()); sendBroadcastIntent(sendIntent); } else if ((new RPCResponse(hash)).getCorrelationID() == POLICIES_CORRELATION_ID && functionName.equals(FunctionID.SYSTEM_REQUEST.toString())) { final SystemRequestResponse msg = new SystemRequestResponse(hash); Intent sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "RPC_NAME", FunctionID.SYSTEM_REQUEST.toString()); updateBroadcastIntent(sendIntent, "TYPE", RPCMessage.KEY_RESPONSE); updateBroadcastIntent(sendIntent, "SUCCESS", msg.getSuccess()); updateBroadcastIntent(sendIntent, "COMMENT1", msg.getInfo()); updateBroadcastIntent(sendIntent, "COMMENT2", msg.getResultCode().toString()); updateBroadcastIntent(sendIntent, "CORRID", msg.getCorrelationID()); updateBroadcastIntent(sendIntent, "DATA", serializeJSON(msg)); sendBroadcastIntent(sendIntent); } else if (functionName.equals(FunctionID.UNREGISTER_APP_INTERFACE.toString())) { // UnregisterAppInterface _appInterfaceRegisterd = false; synchronized(APP_INTERFACE_REGISTERED_LOCK) { APP_INTERFACE_REGISTERED_LOCK.notify(); } final UnregisterAppInterfaceResponse msg = new UnregisterAppInterfaceResponse(hash); Intent sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "RPC_NAME", FunctionID.UNREGISTER_APP_INTERFACE.toString()); updateBroadcastIntent(sendIntent, "TYPE", RPCMessage.KEY_RESPONSE); updateBroadcastIntent(sendIntent, "SUCCESS", msg.getSuccess()); updateBroadcastIntent(sendIntent, "COMMENT1", msg.getInfo()); updateBroadcastIntent(sendIntent, "COMMENT2", msg.getResultCode().toString()); updateBroadcastIntent(sendIntent, "DATA",serializeJSON(msg)); updateBroadcastIntent(sendIntent, "CORRID", msg.getCorrelationID()); sendBroadcastIntent(sendIntent); } return; } if (functionName.equals(FunctionID.REGISTER_APP_INTERFACE.toString())) { final RegisterAppInterfaceResponse msg = new RegisterAppInterfaceResponse(hash); if (msg.getSuccess()) { _appInterfaceRegisterd = true; } processRaiResponse(msg); //Populate the system capability manager with the RAI response _systemCapabilityManager.parseRAIResponse(msg); //_autoActivateIdReturned = msg.getAutoActivateID(); /*Place holder for legacy support*/ _autoActivateIdReturned = "8675309"; _prerecordedSpeech = msg.getPrerecordedSpeech(); _sdlLanguage = msg.getLanguage(); _hmiDisplayLanguage = msg.getHmiDisplayLanguage(); _sdlMsgVersion = msg.getSdlMsgVersion(); _vehicleType = msg.getVehicleType(); _systemSoftwareVersion = msg.getSystemSoftwareVersion(); _proxyVersionInfo = msg.getProxyVersionInfo(); if (_bAppResumeEnabled) { if ( (_sdlMsgVersion.getMajorVersion() > 2) && (_lastHashID != null) && (msg.getSuccess()) && (msg.getResultCode() != Result.RESUME_FAILED) ) _bResumeSuccess = true; else { _bResumeSuccess = false; _lastHashID = null; } } _diagModes = msg.getSupportedDiagModes(); if (!isDebugEnabled()) { enableDebugTool(); DebugTool.logInfo("SDL Proxy Version: " + _proxyVersionInfo); disableDebugTool(); } else DebugTool.logInfo("SDL Proxy Version: " + _proxyVersionInfo); // RegisterAppInterface if (_advancedLifecycleManagementEnabled) { // Send onSdlConnected message in ALM _sdlConnectionState = SdlConnectionState.SDL_CONNECTED; // If registerAppInterface failed, exit with OnProxyUnusable if (!msg.getSuccess()) { notifyProxyClosed("Unable to register app interface. Review values passed to the SdlProxy constructor. RegisterAppInterface result code: ", new SdlException("Unable to register app interface. Review values passed to the SdlProxy constructor. RegisterAppInterface result code: " + msg.getResultCode(), SdlExceptionCause.SDL_REGISTRATION_ERROR), SdlDisconnectedReason.SDL_REGISTRATION_ERROR); } } else { if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { if (_proxyListener instanceof IProxyListener) { ((IProxyListener)_proxyListener).onRegisterAppInterfaceResponse(msg); } onRPCResponseReceived(msg); } }); } else { if (_proxyListener instanceof IProxyListener) { ((IProxyListener)_proxyListener).onRegisterAppInterfaceResponse(msg); } onRPCResponseReceived(msg); } } } else if (functionName.equals(FunctionID.SPEAK.toString())) { // SpeakResponse final SpeakResponse msg = new SpeakResponse(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onSpeakResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onSpeakResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.ALERT.toString())) { // AlertResponse final AlertResponse msg = new AlertResponse(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onAlertResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onAlertResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.SHOW.toString())) { // ShowResponse final ShowResponse msg = new ShowResponse(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onShowResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onShowResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.ADD_COMMAND.toString())) { // AddCommand final AddCommandResponse msg = new AddCommandResponse(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onAddCommandResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onAddCommandResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.DELETE_COMMAND.toString())) { // DeleteCommandResponse final DeleteCommandResponse msg = new DeleteCommandResponse(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onDeleteCommandResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onDeleteCommandResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.ADD_SUB_MENU.toString())) { // AddSubMenu final AddSubMenuResponse msg = new AddSubMenuResponse(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onAddSubMenuResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onAddSubMenuResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.DELETE_SUB_MENU.toString())) { // DeleteSubMenu final DeleteSubMenuResponse msg = new DeleteSubMenuResponse(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onDeleteSubMenuResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onDeleteSubMenuResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.SUBSCRIBE_BUTTON.toString())) { // SubscribeButton final SubscribeButtonResponse msg = new SubscribeButtonResponse(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onSubscribeButtonResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onSubscribeButtonResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.UNSUBSCRIBE_BUTTON.toString())) { // UnsubscribeButton final UnsubscribeButtonResponse msg = new UnsubscribeButtonResponse(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onUnsubscribeButtonResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onUnsubscribeButtonResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.SET_MEDIA_CLOCK_TIMER.toString())) { // SetMediaClockTimer final SetMediaClockTimerResponse msg = new SetMediaClockTimerResponse(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onSetMediaClockTimerResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onSetMediaClockTimerResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.ENCODED_SYNC_P_DATA.toString())) { final SystemRequestResponse msg = new SystemRequestResponse(hash); Intent sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "RPC_NAME", FunctionID.SYSTEM_REQUEST.toString()); updateBroadcastIntent(sendIntent, "TYPE", RPCMessage.KEY_RESPONSE); updateBroadcastIntent(sendIntent, "SUCCESS", msg.getSuccess()); updateBroadcastIntent(sendIntent, "COMMENT1", msg.getInfo()); updateBroadcastIntent(sendIntent, "COMMENT2", msg.getResultCode().toString()); updateBroadcastIntent(sendIntent, "CORRID", msg.getCorrelationID()); sendBroadcastIntent(sendIntent); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onSystemRequestResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onSystemRequestResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.CREATE_INTERACTION_CHOICE_SET.toString())) { // CreateInteractionChoiceSet final CreateInteractionChoiceSetResponse msg = new CreateInteractionChoiceSetResponse(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onCreateInteractionChoiceSetResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onCreateInteractionChoiceSetResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.DELETE_INTERACTION_CHOICE_SET.toString())) { // DeleteInteractionChoiceSet final DeleteInteractionChoiceSetResponse msg = new DeleteInteractionChoiceSetResponse(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onDeleteInteractionChoiceSetResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onDeleteInteractionChoiceSetResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.PERFORM_INTERACTION.toString())) { // PerformInteraction final PerformInteractionResponse msg = new PerformInteractionResponse(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onPerformInteractionResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onPerformInteractionResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.SET_GLOBAL_PROPERTIES.toString())) { // SetGlobalPropertiesResponse final SetGlobalPropertiesResponse msg = new SetGlobalPropertiesResponse(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onSetGlobalPropertiesResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onSetGlobalPropertiesResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.RESET_GLOBAL_PROPERTIES.toString())) { // ResetGlobalProperties final ResetGlobalPropertiesResponse msg = new ResetGlobalPropertiesResponse(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onResetGlobalPropertiesResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onResetGlobalPropertiesResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.UNREGISTER_APP_INTERFACE.toString())) { // UnregisterAppInterface _appInterfaceRegisterd = false; synchronized(APP_INTERFACE_REGISTERED_LOCK) { APP_INTERFACE_REGISTERED_LOCK.notify(); } final UnregisterAppInterfaceResponse msg = new UnregisterAppInterfaceResponse(hash); Intent sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "RPC_NAME", FunctionID.UNREGISTER_APP_INTERFACE.toString()); updateBroadcastIntent(sendIntent, "TYPE", RPCMessage.KEY_RESPONSE); updateBroadcastIntent(sendIntent, "SUCCESS", msg.getSuccess()); updateBroadcastIntent(sendIntent, "COMMENT1", msg.getInfo()); updateBroadcastIntent(sendIntent, "COMMENT2", msg.getResultCode().toString()); updateBroadcastIntent(sendIntent, "DATA",serializeJSON(msg)); updateBroadcastIntent(sendIntent, "CORRID", msg.getCorrelationID()); sendBroadcastIntent(sendIntent); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { if (_proxyListener instanceof IProxyListener) { ((IProxyListener)_proxyListener).onUnregisterAppInterfaceResponse(msg); } onRPCResponseReceived(msg); } }); } else { if (_proxyListener instanceof IProxyListener) { ((IProxyListener)_proxyListener).onUnregisterAppInterfaceResponse(msg); } onRPCResponseReceived(msg); } notifyProxyClosed("UnregisterAppInterfaceResponse", null, SdlDisconnectedReason.APP_INTERFACE_UNREG); } else if (functionName.equals(FunctionID.GENERIC_RESPONSE.toString())) { // GenericResponse (Usually and error) final GenericResponse msg = new GenericResponse(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onGenericResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onGenericResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.SLIDER.toString())) { // Slider final SliderResponse msg = new SliderResponse(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onSliderResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onSliderResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.PUT_FILE.toString())) { // PutFile final PutFileResponse msg = new PutFileResponse(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onPutFileResponse(msg); onRPCResponseReceived(msg); notifyPutFileStreamResponse(msg); } }); } else { _proxyListener.onPutFileResponse(msg); onRPCResponseReceived(msg); notifyPutFileStreamResponse(msg); } } else if (functionName.equals(FunctionID.DELETE_FILE.toString())) { // DeleteFile final DeleteFileResponse msg = new DeleteFileResponse(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onDeleteFileResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onDeleteFileResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.LIST_FILES.toString())) { // ListFiles final ListFilesResponse msg = new ListFilesResponse(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onListFilesResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onListFilesResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.SET_APP_ICON.toString())) { // SetAppIcon final SetAppIconResponse msg = new SetAppIconResponse(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onSetAppIconResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onSetAppIconResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.SCROLLABLE_MESSAGE.toString())) { // ScrollableMessage final ScrollableMessageResponse msg = new ScrollableMessageResponse(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onScrollableMessageResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onScrollableMessageResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.CHANGE_REGISTRATION.toString())) { // ChangeLanguageRegistration final ChangeRegistrationResponse msg = new ChangeRegistrationResponse(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onChangeRegistrationResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onChangeRegistrationResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.SET_DISPLAY_LAYOUT.toString())) { // SetDisplayLayout final SetDisplayLayoutResponse msg = new SetDisplayLayoutResponse(hash); // successfully changed display layout - update layout capabilities if(msg.getSuccess() && _systemCapabilityManager!=null){ _systemCapabilityManager.setCapability(SystemCapabilityType.DISPLAY, msg.getDisplayCapabilities()); _systemCapabilityManager.setCapability(SystemCapabilityType.BUTTON, msg.getButtonCapabilities()); _systemCapabilityManager.setCapability(SystemCapabilityType.PRESET_BANK, msg.getPresetBankCapabilities()); _systemCapabilityManager.setCapability(SystemCapabilityType.SOFTBUTTON, msg.getSoftButtonCapabilities()); } if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onSetDisplayLayoutResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onSetDisplayLayoutResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.PERFORM_AUDIO_PASS_THRU.toString())) { // PerformAudioPassThru final PerformAudioPassThruResponse msg = new PerformAudioPassThruResponse(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onPerformAudioPassThruResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onPerformAudioPassThruResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.END_AUDIO_PASS_THRU.toString())) { // EndAudioPassThru final EndAudioPassThruResponse msg = new EndAudioPassThruResponse(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onEndAudioPassThruResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onEndAudioPassThruResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.SUBSCRIBE_VEHICLE_DATA.toString())) { // SubscribeVehicleData final SubscribeVehicleDataResponse msg = new SubscribeVehicleDataResponse(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onSubscribeVehicleDataResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onSubscribeVehicleDataResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.UNSUBSCRIBE_VEHICLE_DATA.toString())) { // UnsubscribeVehicleData final UnsubscribeVehicleDataResponse msg = new UnsubscribeVehicleDataResponse(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onUnsubscribeVehicleDataResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onUnsubscribeVehicleDataResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.GET_VEHICLE_DATA.toString())) { // GetVehicleData final GetVehicleDataResponse msg = new GetVehicleDataResponse(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onGetVehicleDataResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onGetVehicleDataResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.SUBSCRIBE_WAY_POINTS.toString())) { // SubscribeWayPoints final SubscribeWayPointsResponse msg = new SubscribeWayPointsResponse(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onSubscribeWayPointsResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onSubscribeWayPointsResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.UNSUBSCRIBE_WAY_POINTS.toString())) { // UnsubscribeWayPoints final UnsubscribeWayPointsResponse msg = new UnsubscribeWayPointsResponse(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onUnsubscribeWayPointsResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onUnsubscribeWayPointsResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.GET_WAY_POINTS.toString())) { // GetWayPoints final GetWayPointsResponse msg = new GetWayPointsResponse(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onGetWayPointsResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onGetWayPointsResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.READ_DID.toString())) { final ReadDIDResponse msg = new ReadDIDResponse(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onReadDIDResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onReadDIDResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.GET_DTCS.toString())) { final GetDTCsResponse msg = new GetDTCsResponse(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onGetDTCsResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onGetDTCsResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.DIAGNOSTIC_MESSAGE.toString())) { final DiagnosticMessageResponse msg = new DiagnosticMessageResponse(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onDiagnosticMessageResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onDiagnosticMessageResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.SYSTEM_REQUEST.toString())) { final SystemRequestResponse msg = new SystemRequestResponse(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onSystemRequestResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onSystemRequestResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.SEND_LOCATION.toString())) { final SendLocationResponse msg = new SendLocationResponse(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onSendLocationResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onSendLocationResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.DIAL_NUMBER.toString())) { final DialNumberResponse msg = new DialNumberResponse(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onDialNumberResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onDialNumberResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.SHOW_CONSTANT_TBT.toString())) { final ShowConstantTbtResponse msg = new ShowConstantTbtResponse(hash); if (_callbackToUIThread) { _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onShowConstantTbtResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onShowConstantTbtResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.ALERT_MANEUVER.toString())) { final AlertManeuverResponse msg = new AlertManeuverResponse(hash); if (_callbackToUIThread) { _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onAlertManeuverResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onAlertManeuverResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.UPDATE_TURN_LIST.toString())) { final UpdateTurnListResponse msg = new UpdateTurnListResponse(hash); if (_callbackToUIThread) { _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onUpdateTurnListResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onUpdateTurnListResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.SET_INTERIOR_VEHICLE_DATA.toString())) { final SetInteriorVehicleDataResponse msg = new SetInteriorVehicleDataResponse(hash); if (_callbackToUIThread) { _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onSetInteriorVehicleDataResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onSetInteriorVehicleDataResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.GET_INTERIOR_VEHICLE_DATA.toString())) { final GetInteriorVehicleDataResponse msg = new GetInteriorVehicleDataResponse(hash); if (_callbackToUIThread) { _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onGetInteriorVehicleDataResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onGetInteriorVehicleDataResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.GET_SYSTEM_CAPABILITY.toString())) { // GetSystemCapabilityResponse final GetSystemCapabilityResponse msg = new GetSystemCapabilityResponse(hash); if (_callbackToUIThread) { _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onGetSystemCapabilityResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onGetSystemCapabilityResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.BUTTON_PRESS.toString())) { final ButtonPressResponse msg = new ButtonPressResponse(hash); if (_callbackToUIThread) { _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onButtonPressResponse(msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onButtonPressResponse(msg); onRPCResponseReceived(msg); } } else if (functionName.equals(FunctionID.SEND_HAPTIC_DATA.toString())) { final SendHapticDataResponse msg = new SendHapticDataResponse(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onSendHapticDataResponse( msg); onRPCResponseReceived(msg); } }); } else { _proxyListener.onSendHapticDataResponse( msg); onRPCResponseReceived(msg); } } else { if (_sdlMsgVersion != null) { DebugTool.logError("Unrecognized response Message: " + functionName + " SDL Message Version = " + _sdlMsgVersion); } else { DebugTool.logError("Unrecognized response Message: " + functionName); } } // end-if } else if (messageType.equals(RPCMessage.KEY_NOTIFICATION)) { SdlTrace.logRPCEvent(InterfaceActivityDirection.Receive, new RPCNotification(rpcMsg), SDL_LIB_TRACE_KEY); if (functionName.equals(FunctionID.ON_HMI_STATUS.toString())) { // OnHMIStatus final OnHMIStatus msg = new OnHMIStatus(hash); //setup lockscreeninfo if (sdlSession != null) { sdlSession.getLockScreenMan().setHMILevel(msg.getHmiLevel()); } msg.setFirstRun(firstTimeFull); if (msg.getHmiLevel() == HMILevel.HMI_FULL) firstTimeFull = false; _hmiLevel = msg.getHmiLevel(); _audioStreamingState = msg.getAudioStreamingState(); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onOnHMIStatus(msg); _proxyListener.onOnLockScreenNotification(sdlSession.getLockScreenMan().getLockObj()); onRPCNotificationReceived(msg); } }); } else { _proxyListener.onOnHMIStatus(msg); _proxyListener.onOnLockScreenNotification(sdlSession.getLockScreenMan().getLockObj()); onRPCNotificationReceived(msg); } } else if (functionName.equals(FunctionID.ON_COMMAND.toString())) { // OnCommand final OnCommand msg = new OnCommand(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onOnCommand(msg); onRPCNotificationReceived(msg); } }); } else { _proxyListener.onOnCommand(msg); onRPCNotificationReceived(msg); } } else if (functionName.equals(FunctionID.ON_DRIVER_DISTRACTION.toString())) { // OnDriverDistration final OnDriverDistraction msg = new OnDriverDistraction(hash); //setup lockscreeninfo if (sdlSession != null) { DriverDistractionState drDist = msg.getState(); sdlSession.getLockScreenMan().setDriverDistStatus(drDist == DriverDistractionState.DD_ON); } if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onOnDriverDistraction(msg); _proxyListener.onOnLockScreenNotification(sdlSession.getLockScreenMan().getLockObj()); onRPCNotificationReceived(msg); } }); } else { _proxyListener.onOnDriverDistraction(msg); _proxyListener.onOnLockScreenNotification(sdlSession.getLockScreenMan().getLockObj()); onRPCNotificationReceived(msg); } } else if (functionName.equals(FunctionID.ON_ENCODED_SYNC_P_DATA.toString())) { final OnSystemRequest msg = new OnSystemRequest(hash); Intent sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "RPC_NAME", FunctionID.ON_SYSTEM_REQUEST.toString()); updateBroadcastIntent(sendIntent, "TYPE", RPCMessage.KEY_NOTIFICATION); // If url is null, then send notification to the app, otherwise, send to URL if (msg.getUrl() == null) { updateBroadcastIntent(sendIntent, "COMMENT1", "URL is a null value (received)"); sendBroadcastIntent(sendIntent); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onOnSystemRequest(msg); onRPCNotificationReceived(msg); } }); } else { _proxyListener.onOnSystemRequest(msg); onRPCNotificationReceived(msg); } } else { updateBroadcastIntent(sendIntent, "COMMENT1", "Sending to cloud: " + msg.getUrl()); sendBroadcastIntent(sendIntent); Log.i("pt", "send to url"); if ( (msg.getUrl() != null) ) { Thread handleOffboardTransmissionThread = new Thread() { @Override public void run() { sendOnSystemRequestToUrl(msg); } }; handleOffboardTransmissionThread.start(); } } } else if (functionName.equals(FunctionID.ON_PERMISSIONS_CHANGE.toString())) { final OnPermissionsChange msg = new OnPermissionsChange(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onOnPermissionsChange(msg); onRPCNotificationReceived(msg); } }); } else { _proxyListener.onOnPermissionsChange(msg); onRPCNotificationReceived(msg); } } else if (functionName.equals(FunctionID.ON_TBT_CLIENT_STATE.toString())) { // OnTBTClientState final OnTBTClientState msg = new OnTBTClientState(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onOnTBTClientState(msg); onRPCNotificationReceived(msg); } }); } else { _proxyListener.onOnTBTClientState(msg); onRPCNotificationReceived(msg); } } else if (functionName.equals(FunctionID.ON_BUTTON_PRESS.toString())) { // OnButtonPress final OnButtonPress msg = new OnButtonPress(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onOnButtonPress(msg); onRPCNotificationReceived(msg); } }); } else { _proxyListener.onOnButtonPress(msg); onRPCNotificationReceived(msg); } } else if (functionName.equals(FunctionID.ON_BUTTON_EVENT.toString())) { // OnButtonEvent final OnButtonEvent msg = new OnButtonEvent(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onOnButtonEvent(msg); onRPCNotificationReceived(msg); } }); } else { _proxyListener.onOnButtonEvent(msg); onRPCNotificationReceived(msg); } } else if (functionName.equals(FunctionID.ON_LANGUAGE_CHANGE.toString())) { // OnLanguageChange final OnLanguageChange msg = new OnLanguageChange(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onOnLanguageChange(msg); onRPCNotificationReceived(msg); } }); } else { _proxyListener.onOnLanguageChange(msg); onRPCNotificationReceived(msg); } } else if (functionName.equals(FunctionID.ON_HASH_CHANGE.toString())) { // OnLanguageChange final OnHashChange msg = new OnHashChange(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onOnHashChange(msg); onRPCNotificationReceived(msg); if (_bAppResumeEnabled) { _lastHashID = msg.getHashID(); } } }); } else { _proxyListener.onOnHashChange(msg); onRPCNotificationReceived(msg); if (_bAppResumeEnabled) { _lastHashID = msg.getHashID(); } } } else if (functionName.equals(FunctionID.ON_SYSTEM_REQUEST.toString())) { // OnSystemRequest final OnSystemRequest msg = new OnSystemRequest(hash); if ((msg.getUrl() != null) && (((msg.getRequestType() == RequestType.PROPRIETARY) && (msg.getFileType() == FileType.JSON)) || ((msg.getRequestType() == RequestType.HTTP) && (msg.getFileType() == FileType.BINARY)))){ Thread handleOffboardTransmissionThread = new Thread() { @Override public void run() { sendOnSystemRequestToUrl(msg); } }; handleOffboardTransmissionThread.start(); } if(msg.getRequestType() == RequestType.LOCK_SCREEN_ICON_URL && msg.getUrl() != null){ lockScreenIconRequest = msg; } if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onOnSystemRequest(msg); onRPCNotificationReceived(msg); } }); } else { _proxyListener.onOnSystemRequest(msg); onRPCNotificationReceived(msg); } } else if (functionName.equals(FunctionID.ON_AUDIO_PASS_THRU.toString())) { // OnAudioPassThru final OnAudioPassThru msg = new OnAudioPassThru(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onOnAudioPassThru(msg); onRPCNotificationReceived(msg); } }); } else { _proxyListener.onOnAudioPassThru(msg); onRPCNotificationReceived(msg); } } else if (functionName.equals(FunctionID.ON_VEHICLE_DATA.toString())) { // OnVehicleData final OnVehicleData msg = new OnVehicleData(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onOnVehicleData(msg); onRPCNotificationReceived(msg); } }); } else { _proxyListener.onOnVehicleData(msg); onRPCNotificationReceived(msg); } } else if (functionName.equals(FunctionID.ON_APP_INTERFACE_UNREGISTERED.toString())) { // OnAppInterfaceUnregistered _appInterfaceRegisterd = false; synchronized(APP_INTERFACE_REGISTERED_LOCK) { APP_INTERFACE_REGISTERED_LOCK.notify(); } final OnAppInterfaceUnregistered msg = new OnAppInterfaceUnregistered(hash); Intent sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "RPC_NAME", FunctionID.ON_APP_INTERFACE_UNREGISTERED.toString()); updateBroadcastIntent(sendIntent, "TYPE", RPCMessage.KEY_NOTIFICATION); updateBroadcastIntent(sendIntent, "DATA",serializeJSON(msg)); sendBroadcastIntent(sendIntent); if (_advancedLifecycleManagementEnabled) { // This requires the proxy to be cycled cycleProxy(SdlDisconnectedReason.convertAppInterfaceUnregisteredReason(msg.getReason())); } else { if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { ((IProxyListener)_proxyListener).onOnAppInterfaceUnregistered(msg); onRPCNotificationReceived(msg); } }); } else { ((IProxyListener)_proxyListener).onOnAppInterfaceUnregistered(msg); onRPCNotificationReceived(msg); } notifyProxyClosed("OnAppInterfaceUnregistered", null, SdlDisconnectedReason.APP_INTERFACE_UNREG); } } else if (functionName.equals(FunctionID.ON_KEYBOARD_INPUT.toString())) { final OnKeyboardInput msg = new OnKeyboardInput(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onOnKeyboardInput(msg); onRPCNotificationReceived(msg); } }); } else { _proxyListener.onOnKeyboardInput(msg); onRPCNotificationReceived(msg); } } else if (functionName.equals(FunctionID.ON_TOUCH_EVENT.toString())) { final OnTouchEvent msg = new OnTouchEvent(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onOnTouchEvent(msg); onRPCNotificationReceived(msg); } }); } else { _proxyListener.onOnTouchEvent(msg); onRPCNotificationReceived(msg); } } else if (functionName.equals(FunctionID.ON_WAY_POINT_CHANGE.toString())) { final OnWayPointChange msg = new OnWayPointChange(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onOnWayPointChange(msg); onRPCNotificationReceived(msg); } }); } else { _proxyListener.onOnWayPointChange(msg); onRPCNotificationReceived(msg); } } else if (functionName.equals(FunctionID.ON_INTERIOR_VEHICLE_DATA.toString())) { final OnInteriorVehicleData msg = new OnInteriorVehicleData(hash); if (_callbackToUIThread) { // Run in UI thread _mainUIHandler.post(new Runnable() { @Override public void run() { _proxyListener.onOnInteriorVehicleData(msg); onRPCNotificationReceived(msg); } }); } else { _proxyListener.onOnInteriorVehicleData(msg); onRPCNotificationReceived(msg); } } else { if (_sdlMsgVersion != null) { DebugTool.logInfo("Unrecognized notification Message: " + functionName + " connected to SDL using message version: " + _sdlMsgVersion.getMajorVersion() + "." + _sdlMsgVersion.getMinorVersion()); } else { DebugTool.logInfo("Unrecognized notification Message: " + functionName); } } // end-if } // end-if notification SdlTrace.logProxyEvent("Proxy received RPC Message: " + functionName, SDL_LIB_TRACE_KEY); } /** * Takes an RPCRequest and sends it to SDL. Responses are captured through callback on IProxyListener. * * @param request is the RPCRequest being sent * @throws SdlException if an unrecoverable error is encountered if an unrecoverable error is encountered */ public void sendRPCRequest(RPCRequest request) throws SdlException { if (_proxyDisposed) { throw new SdlException("This object has been disposed, it is no long capable of executing methods.", SdlExceptionCause.SDL_PROXY_DISPOSED); } // Test if request is null if (request == null) { SdlTrace.logProxyEvent("Application called sendRPCRequest method with a null RPCRequest.", SDL_LIB_TRACE_KEY); throw new IllegalArgumentException("sendRPCRequest cannot be called with a null request."); } SdlTrace.logProxyEvent("Application called sendRPCRequest method for RPCRequest: ." + request.getFunctionName(), SDL_LIB_TRACE_KEY); // Test if SdlConnection is null synchronized(CONNECTION_REFERENCE_LOCK) { if (!getIsConnected()) { SdlTrace.logProxyEvent("Application attempted to send and RPCRequest without a connected transport.", SDL_LIB_TRACE_KEY); throw new SdlException("There is no valid connection to SDL. sendRPCRequest cannot be called until SDL has been connected.", SdlExceptionCause.SDL_UNAVAILABLE); } } if (isCorrelationIDProtected(request.getCorrelationID())) { SdlTrace.logProxyEvent("Application attempted to use the reserved correlation ID, " + request.getCorrelationID(), SDL_LIB_TRACE_KEY); throw new SdlException("Invalid correlation ID. The correlation ID, " + request.getCorrelationID() + " , is a reserved correlation ID.", SdlExceptionCause.RESERVED_CORRELATION_ID); } // Throw exception if RPCRequest is sent when SDL is unavailable if (!_appInterfaceRegisterd && !request.getFunctionName().equals(FunctionID.REGISTER_APP_INTERFACE.toString())) { SdlTrace.logProxyEvent("Application attempted to send an RPCRequest (non-registerAppInterface), before the interface was registerd.", SDL_LIB_TRACE_KEY); throw new SdlException("SDL is currently unavailable. RPC Requests cannot be sent.", SdlExceptionCause.SDL_UNAVAILABLE); } if (_advancedLifecycleManagementEnabled) { if (request.getFunctionName().equals(FunctionID.REGISTER_APP_INTERFACE.toString()) || request.getFunctionName().equals(FunctionID.UNREGISTER_APP_INTERFACE.toString())) { SdlTrace.logProxyEvent("Application attempted to send a RegisterAppInterface or UnregisterAppInterface while using ALM.", SDL_LIB_TRACE_KEY); throw new SdlException("The RPCRequest, " + request.getFunctionName() + ", is unallowed using the Advanced Lifecycle Management Model.", SdlExceptionCause.INCORRECT_LIFECYCLE_MODEL); } } sendRPCRequestPrivate(request); } // end-method protected void notifyProxyClosed(final String info, final Exception e, final SdlDisconnectedReason reason) { SdlTrace.logProxyEvent("NotifyProxyClose", SDL_LIB_TRACE_KEY); OnProxyClosed message = new OnProxyClosed(info, e, reason); queueInternalMessage(message); } private void passErrorToProxyListener(final String info, final Exception e) { OnError message = new OnError(info, e); queueInternalMessage(message); } private void startRPCProtocolSession() { // Set Proxy Lifecyclek Available if (_advancedLifecycleManagementEnabled) { try { registerAppInterfacePrivate( _sdlMsgVersionRequest, _applicationName, _ttsName, _ngnMediaScreenAppName, _vrSynonyms, _isMediaApp, _sdlLanguageDesired, _hmiDisplayLanguageDesired, _appType, _appID, REGISTER_APP_INTERFACE_CORRELATION_ID); } catch (Exception e) { notifyProxyClosed("Failed to register application interface with SDL. Check parameter values given to SdlProxy constructor.", e, SdlDisconnectedReason.SDL_REGISTRATION_ERROR); } } else { InternalProxyMessage message = new InternalProxyMessage(InternalProxyMessage.OnProxyOpened); queueInternalMessage(message); } } // Queue internal callback message private void queueInternalMessage(InternalProxyMessage message) { synchronized(INTERNAL_MESSAGE_QUEUE_THREAD_LOCK) { if (_internalProxyMessageDispatcher != null) { _internalProxyMessageDispatcher.queueMessage(message); } } } // Queue incoming ProtocolMessage private void queueIncomingMessage(ProtocolMessage message) { synchronized(INCOMING_MESSAGE_QUEUE_THREAD_LOCK) { if (_incomingProxyMessageDispatcher != null) { _incomingProxyMessageDispatcher.queueMessage(message); } } } private FileInputStream getFileInputStream(String sLocalFile) { FileInputStream is = null; try { is = new FileInputStream(sLocalFile); } catch (IOException e1) { e1.printStackTrace(); } return is; } private Long getFileInputStreamSize(FileInputStream is) { Long lSize = null; try { lSize = is.getChannel().size(); } catch (IOException e) { e.printStackTrace(); } return lSize; } private void closeFileInputStream(FileInputStream is) { try { is.close(); } catch (Exception e) { e.printStackTrace(); } } @SuppressWarnings("unchecked") private RPCStreamController startRPCStream(String sLocalFile, PutFile request, SessionType sType, byte rpcSessionID, byte wiproVersion) { if (sdlSession == null) return null; FileInputStream is = getFileInputStream(sLocalFile); if (is == null) return null; Long lSize = getFileInputStreamSize(is); if (lSize == null) { closeFileInputStream(is); return null; } try { StreamRPCPacketizer rpcPacketizer = new StreamRPCPacketizer((SdlProxyBase<IProxyListenerBase>) this, sdlSession, is, request, sType, rpcSessionID, wiproVersion, lSize, sdlSession); rpcPacketizer.start(); return new RPCStreamController(rpcPacketizer, request.getCorrelationID()); } catch (Exception e) { Log.e("SyncConnection", "Unable to start streaming:" + e.toString()); return null; } } @SuppressWarnings({"unchecked", "UnusedReturnValue"}) private RPCStreamController startRPCStream(InputStream is, PutFile request, SessionType sType, byte rpcSessionID, byte wiproVersion) { if (sdlSession == null) return null; Long lSize = request.getLength(); if (lSize == null) { return null; } try { StreamRPCPacketizer rpcPacketizer = new StreamRPCPacketizer((SdlProxyBase<IProxyListenerBase>) this, sdlSession, is, request, sType, rpcSessionID, wiproVersion, lSize, sdlSession); rpcPacketizer.start(); return new RPCStreamController(rpcPacketizer, request.getCorrelationID()); } catch (Exception e) { Log.e("SyncConnection", "Unable to start streaming:" + e.toString()); return null; } } private RPCStreamController startPutFileStream(String sPath, PutFile msg) { if (sdlSession == null) return null; return startRPCStream(sPath, msg, SessionType.RPC, sdlSession.getSessionId(), _wiproVersion); } private RPCStreamController startPutFileStream(InputStream is, PutFile msg) { if (sdlSession == null) return null; if (is == null) return null; return startRPCStream(is, msg, SessionType.RPC, sdlSession.getSessionId(), _wiproVersion); } @SuppressWarnings("UnusedReturnValue") public boolean startRPCStream(InputStream is, RPCRequest msg) { if (sdlSession == null) return false; sdlSession.startRPCStream(is, msg, SessionType.RPC, sdlSession.getSessionId(), _wiproVersion); return true; } public OutputStream startRPCStream(RPCRequest msg) { if (sdlSession == null) return null; return sdlSession.startRPCStream(msg, SessionType.RPC, sdlSession.getSessionId(), _wiproVersion); } public void endRPCStream() { if (sdlSession == null) return; sdlSession.stopRPCStream(); } private class CallableMethod implements Callable<Void> { private final long waitTime; public CallableMethod(int timeInMillis){ this.waitTime=timeInMillis; } @Override public Void call() { try { Thread.sleep(waitTime); } catch (InterruptedException e) { e.printStackTrace(); } return null; } } public FutureTask<Void> createFutureTask(CallableMethod callMethod){ return new FutureTask<Void>(callMethod); } public ScheduledExecutorService createScheduler(){ return Executors.newSingleThreadScheduledExecutor(); } @SuppressWarnings("unused") public void startService(SessionType serviceType, boolean isEncrypted){ sdlSession.startService(serviceType, sdlSession.getSessionId(), isEncrypted); } @SuppressWarnings("unused") public void endService(SessionType serviceType){ sdlSession.endService(serviceType, sdlSession.getSessionId()); } /** * @deprecated *Opens the video service (serviceType 11) and subsequently streams raw H264 video from an InputStream provided by the app *@return true if service is opened successfully and stream is started, return false otherwise * @see #startRemoteDisplayStream(Context, Class, VideoStreamingParameters, boolean) startRemoteDisplayStream * @see #startVideoStream(boolean, VideoStreamingParameters) startVideoStream * @see #createOpenGLInputSurface(int, int, int, int, int, boolean) createOpenGLInputSurface */ @SuppressWarnings("unused") @Deprecated public boolean startH264(InputStream is, boolean isEncrypted) { if (sdlSession == null) return false; navServiceStartResponseReceived = false; navServiceStartResponse = false; navServiceStartRejectedParams = null; // When startH264() API is used, we will not send video format / width / height information // with StartService. (Reasons: InputStream does not provide timestamp information so RTP // cannot be used. startH264() does not provide with/height information.) VideoStreamingParameters emptyParam = new VideoStreamingParameters(); emptyParam.setResolution(null); emptyParam.setFormat(null); sdlSession.setDesiredVideoParams(emptyParam); sdlSession.startService(SessionType.NAV, sdlSession.getSessionId(), isEncrypted); FutureTask<Void> fTask = createFutureTask(new CallableMethod(RESPONSE_WAIT_TIME)); ScheduledExecutorService scheduler = createScheduler(); scheduler.execute(fTask); //noinspection StatementWithEmptyBody while (!navServiceStartResponseReceived && !fTask.isDone()); scheduler.shutdown(); if (navServiceStartResponse) { try { sdlSession.startStream(is, SessionType.NAV, sdlSession.getSessionId()); return true; } catch (Exception e) { return false; } } else { return false; } } /** * @deprecated *Opens the video service (serviceType 11) and subsequently provides an OutputStream to the app to use for a raw H264 video stream *@return OutputStream if service is opened successfully and stream is started, return null otherwise * @see #startRemoteDisplayStream(Context, Class, VideoStreamingParameters, boolean) startRemoteDisplayStream * @see #startVideoStream(boolean, VideoStreamingParameters) startVideoStream * @see #createOpenGLInputSurface(int, int, int, int, int, boolean) createOpenGLInputSurface */ @SuppressWarnings("unused") @Deprecated public OutputStream startH264(boolean isEncrypted) { if (sdlSession == null) return null; navServiceStartResponseReceived = false; navServiceStartResponse = false; navServiceStartRejectedParams = null; // When startH264() API is used, we will not send video format / width / height information // with StartService. (Reasons: OutputStream does not provide timestamp information so RTP // cannot be used. startH264() does not provide with/height information.) VideoStreamingParameters emptyParam = new VideoStreamingParameters(); emptyParam.setResolution(null); emptyParam.setFormat(null); sdlSession.setDesiredVideoParams(emptyParam); sdlSession.startService(SessionType.NAV, sdlSession.getSessionId(), isEncrypted); FutureTask<Void> fTask = createFutureTask(new CallableMethod(RESPONSE_WAIT_TIME)); ScheduledExecutorService scheduler = createScheduler(); scheduler.execute(fTask); //noinspection StatementWithEmptyBody while (!navServiceStartResponseReceived && !fTask.isDone()); scheduler.shutdown(); if (navServiceStartResponse) { try { return sdlSession.startStream(SessionType.NAV, sdlSession.getSessionId()); } catch (Exception e) { return null; } } else { return null; } } /** *Closes the opened video service (serviceType 11) *@return true if the video service is closed successfully, return false otherwise */ @SuppressWarnings("unused") @Deprecated public boolean endH264() { return endVideoStream(); } /** *Pauses the stream for the opened audio service (serviceType 10) *@return true if the audio service stream is paused successfully, return false otherwise */ @SuppressWarnings("unused") @Deprecated public boolean pausePCM() { return pauseAudioStream(); } /** *Pauses the stream for the opened video service (serviceType 11) *@return true if the video service stream is paused successfully, return false otherwise */ @SuppressWarnings("unused") @Deprecated public boolean pauseH264() { return pauseVideoStream(); } /** *Resumes the stream for the opened audio service (serviceType 10) *@return true if the audio service stream is resumed successfully, return false otherwise */ @SuppressWarnings("unused") @Deprecated public boolean resumePCM() { return resumeAudioStream(); } /** *Resumes the stream for the opened video service (serviceType 11) *@return true if the video service is resumed successfully, return false otherwise */ @SuppressWarnings("unused") @Deprecated public boolean resumeH264() { return resumeVideoStream(); } /** *Opens the audio service (serviceType 10) and subsequently streams raw PCM audio from an InputStream provided by the app *@return true if service is opened successfully and stream is started, return false otherwise */ @SuppressWarnings("unused") @Deprecated public boolean startPCM(InputStream is, boolean isEncrypted) { if (sdlSession == null) return false; pcmServiceStartResponseReceived = false; pcmServiceStartResponse = false; sdlSession.startService(SessionType.PCM, sdlSession.getSessionId(), isEncrypted); FutureTask<Void> fTask = createFutureTask(new CallableMethod(RESPONSE_WAIT_TIME)); ScheduledExecutorService scheduler = createScheduler(); scheduler.execute(fTask); //noinspection StatementWithEmptyBody while (!pcmServiceStartResponseReceived && !fTask.isDone()); scheduler.shutdown(); if (pcmServiceStartResponse) { try { sdlSession.startStream(is, SessionType.PCM, sdlSession.getSessionId()); return true; } catch (Exception e) { return false; } } else { return false; } } /** *Opens the audio service (serviceType 10) and subsequently provides an OutputStream to the app *@return OutputStream if service is opened successfully and stream is started, return null otherwise */ @SuppressWarnings("unused") @Deprecated public OutputStream startPCM(boolean isEncrypted) { if (sdlSession == null) return null; pcmServiceStartResponseReceived = false; pcmServiceStartResponse = false; sdlSession.startService(SessionType.PCM, sdlSession.getSessionId(), isEncrypted); FutureTask<Void> fTask = createFutureTask(new CallableMethod(RESPONSE_WAIT_TIME)); ScheduledExecutorService scheduler = createScheduler(); scheduler.execute(fTask); //noinspection StatementWithEmptyBody while (!pcmServiceStartResponseReceived && !fTask.isDone()); scheduler.shutdown(); if (pcmServiceStartResponse) { try { return sdlSession.startStream(SessionType.PCM, sdlSession.getSessionId()); } catch (Exception e) { return null; } } else { if (pcmServiceStartRejectedParams != null) { StringBuilder builder = new StringBuilder(); for (String paramName : pcmServiceStartRejectedParams) { if (builder.length() > 0) { builder.append(", "); } builder.append(paramName); } DebugTool.logWarning("StartService for nav failed. Rejected params: " + builder.toString()); } else { DebugTool.logWarning("StartService for nav failed (rejected params not supplied)"); } return null; } } /** *Closes the opened audio service (serviceType 10) *@return true if the audio service is closed successfully, return false otherwise */ @SuppressWarnings("unused") @Deprecated public boolean endPCM() { return endAudioStream(); } /** * Opens a video service (service type 11) and subsequently provides an IVideoStreamListener * to the app to send video data. The supplied VideoStreamingParameters will be set as desired paramaters * that will be used to negotiate * * @param isEncrypted Specify true if packets on this service have to be encrypted * @param parameters Video streaming parameters including: codec which will be used for streaming (currently, only * VideoStreamingCodec.H264 is accepted), height and width of the video in pixels. * * @return IVideoStreamListener interface if service is opened successfully and streaming is * started, null otherwise */ @SuppressWarnings("unused") public IVideoStreamListener startVideoStream(boolean isEncrypted, VideoStreamingParameters parameters) { if (sdlSession == null) { DebugTool.logWarning("SdlSession is not created yet."); return null; } if (sdlSession.getSdlConnection() == null) { DebugTool.logWarning("SdlConnection is not available."); return null; } sdlSession.setDesiredVideoParams(parameters); VideoStreamingParameters acceptedParams = tryStartVideoStream(isEncrypted, parameters); if (acceptedParams != null) { return sdlSession.startVideoStream(); } else { return null; } } /** *Closes the opened video service (serviceType 11) *@return true if the video service is closed successfully, return false otherwise */ @SuppressWarnings("unused") public boolean endVideoStream() { if (sdlSession == null){ return false; } navServiceEndResponseReceived = false; navServiceEndResponse = false; sdlSession.stopVideoStream(); FutureTask<Void> fTask = createFutureTask(new CallableMethod(RESPONSE_WAIT_TIME)); ScheduledExecutorService scheduler = createScheduler(); scheduler.execute(fTask); //noinspection StatementWithEmptyBody while (!navServiceEndResponseReceived && !fTask.isDone()); scheduler.shutdown(); return navServiceEndResponse; } /** *Pauses the stream for the opened video service (serviceType 11) *@return true if the video service stream is paused successfully, return false otherwise */ @SuppressWarnings("unused") public boolean pauseVideoStream() { return sdlSession != null && sdlSession.pauseVideoStream(); } /** *Resumes the stream for the opened video service (serviceType 11) *@return true if the video service is resumed successfully, return false otherwise */ @SuppressWarnings("unused") public boolean resumeVideoStream() { return sdlSession != null && sdlSession.resumeVideoStream(); } /** * Opens the video service (serviceType 11) and creates a Surface (used for streaming video) with input parameters provided by the app * @param frameRate - specified rate of frames to utilize for creation of Surface * @param iFrameInterval - specified interval to utilize for creation of Surface * @param width - specified width to utilize for creation of Surface * @param height - specified height to utilize for creation of Surface * @param bitrate - specified bitrate to utilize for creation of Surface *@return Surface if service is opened successfully and stream is started, return null otherwise */ @SuppressWarnings("unused") public Surface createOpenGLInputSurface(int frameRate, int iFrameInterval, int width, int height, int bitrate, boolean isEncrypted) { if (sdlSession == null || sdlSession.getSdlConnection() == null){ return null; } VideoStreamingParameters desired = new VideoStreamingParameters(); desired.setFrameRate(frameRate); desired.setInterval(iFrameInterval); ImageResolution resolution = new ImageResolution(); resolution.setResolutionWidth(width); resolution.setResolutionHeight(height); desired.setResolution(resolution); desired.setBitrate(bitrate); VideoStreamingParameters acceptedParams = tryStartVideoStream(isEncrypted, desired); if (acceptedParams != null) { return sdlSession.createOpenGLInputSurface(frameRate, iFrameInterval, width, height, bitrate, SessionType.NAV, sdlSession.getSessionId()); } else { return null; } } /** * Starts streaming a remote display to the module if there is a connected session. This method of streaming requires the device to be on API level 19 or higher * @param context a context that can be used to create the remote display * @param remoteDisplay class object of the remote display. This class will be used to create an instance of the remote display and will be projected to the module * @param parameters streaming parameters to be used when streaming. If null is sent in, the default/optimized options will be used. * If you are unsure about what parameters to be used it is best to just send null and let the system determine what * works best for the currently connected module. * * @param encrypted a flag of if the stream should be encrypted. Only set if you have a supplied encryption library that the module can understand. */ @TargetApi(19) public void startRemoteDisplayStream(Context context, final Class<? extends SdlRemoteDisplay> remoteDisplay, final VideoStreamingParameters parameters, final boolean encrypted){ if(getWiProVersion() >= 5 && !_systemCapabilityManager.isCapabilitySupported(SystemCapabilityType.VIDEO_STREAMING)){ Log.e(TAG, "Video streaming not supported on this module"); return; } //Create streaming manager if(manager == null){ manager = new VideoStreamingManager(context,this._internalInterface); } if(parameters == null){ if(getWiProVersion() >= 5) { _systemCapabilityManager.getCapability(SystemCapabilityType.VIDEO_STREAMING, new OnSystemCapabilityListener() { @Override public void onCapabilityRetrieved(Object capability) { VideoStreamingParameters params = new VideoStreamingParameters(); params.update((VideoStreamingCapability)capability); //Streaming parameters are ready time to stream sdlSession.setDesiredVideoParams(params); manager.startVideoStreaming(remoteDisplay, params, encrypted); } @Override public void onError(String info) { Log.e(TAG, "Error retrieving video streaming capability: " + info); } }); }else{ //We just use default video streaming params VideoStreamingParameters params = new VideoStreamingParameters(); DisplayCapabilities dispCap = (DisplayCapabilities)_systemCapabilityManager.getCapability(SystemCapabilityType.DISPLAY); if(dispCap !=null){ params.setResolution(dispCap.getScreenParams().getImageResolution()); } sdlSession.setDesiredVideoParams(params); manager.startVideoStreaming(remoteDisplay,params, encrypted); } }else{ sdlSession.setDesiredVideoParams(parameters); manager.startVideoStreaming(remoteDisplay,parameters, encrypted); } } /** * Stops the remote display stream if one has been started */ public void stopRemoteDisplayStream(){ if(manager!=null){ manager.dispose(); } manager = null; } /** * Try to open a video service by using the video streaming parameters supplied. * * Only information from codecs, width and height are used during video format negotiation. * * @param isEncrypted Specify true if packets on this service have to be encrypted * @param parameters VideoStreamingParameters that are desired. Does not guarantee this is what will be accepted. * * @return If the service is opened successfully, an instance of VideoStreamingParams is * returned which contains accepted video format. If the service is opened with legacy * mode (i.e. without any negotiation) then an instance of VideoStreamingParams is * returned. If the service was not opened then null is returned. */ @SuppressWarnings("unused") private VideoStreamingParameters tryStartVideoStream(boolean isEncrypted, VideoStreamingParameters parameters) { if (sdlSession == null) { DebugTool.logWarning("SdlSession is not created yet."); return null; } if(getWiProVersion() >= 5 && !_systemCapabilityManager.isCapabilitySupported(SystemCapabilityType.VIDEO_STREAMING)){ DebugTool.logWarning("Module doesn't support video streaming."); return null; } if (parameters == null) { DebugTool.logWarning("Video parameters were not supplied."); return null; } sdlSession.setDesiredVideoParams(parameters); navServiceStartResponseReceived = false; navServiceStartResponse = false; navServiceStartRejectedParams = null; sdlSession.startService(SessionType.NAV, sdlSession.getSessionId(), isEncrypted); FutureTask<Void> fTask = createFutureTask(new CallableMethod(RESPONSE_WAIT_TIME)); ScheduledExecutorService scheduler = createScheduler(); scheduler.execute(fTask); //noinspection StatementWithEmptyBody while (!navServiceStartResponseReceived && !fTask.isDone()); scheduler.shutdown(); if (navServiceStartResponse) { if(getWiProVersion() < 5){ //Versions 1-4 do not support streaming parameter negotiations sdlSession.setAcceptedVideoParams(parameters); } return sdlSession.getAcceptedVideoParams(); } if (navServiceStartRejectedParams != null) { StringBuilder builder = new StringBuilder(); for (String paramName : navServiceStartRejectedParams) { if (builder.length() > 0) { builder.append(", "); } builder.append(paramName); } DebugTool.logWarning("StartService for nav failed. Rejected params: " + builder.toString()); } else { DebugTool.logWarning("StartService for nav failed (rejected params not supplied)"); } return null; } /** *Starts the MediaCodec encoder utilized in conjunction with the Surface returned via the createOpenGLInputSurface method */ @SuppressWarnings("unused") public void startEncoder () { if (sdlSession == null) return; SdlConnection sdlConn = sdlSession.getSdlConnection(); if (sdlConn == null) return; sdlSession.startEncoder(); } /** *Releases the MediaCodec encoder utilized in conjunction with the Surface returned via the createOpenGLInputSurface method */ @SuppressWarnings("unused") public void releaseEncoder() { if (sdlSession == null) return; SdlConnection sdlConn = sdlSession.getSdlConnection(); if (sdlConn == null) return; sdlSession.releaseEncoder(); } /** *Releases the MediaCodec encoder utilized in conjunction with the Surface returned via the createOpenGLInputSurface method */ @SuppressWarnings("unused") public void drainEncoder(boolean endOfStream) { if (sdlSession == null) return; SdlConnection sdlConn = sdlSession.getSdlConnection(); if (sdlConn == null) return; sdlSession.drainEncoder(endOfStream); } /** * Opens a audio service (service type 10) and subsequently provides an IAudioStreamListener * to the app to send audio data. * * Currently information passed by "params" are ignored, since Audio Streaming feature lacks * capability negotiation mechanism. App should configure audio stream data to align with * head unit's capability by checking (upcoming) pcmCapabilities. The default format is in * 16kHz and 16 bits. * * @param isEncrypted Specify true if packets on this service have to be encrypted * @param codec Audio codec which will be used for streaming. Currently, only * AudioStreamingCodec.LPCM is accepted. * @param params (Reserved for future use) Additional configuration information for each * codec. If "codec" is AudioStreamingCodec.LPCM, "params" must be an * instance of LPCMParams class. * * @return IAudioStreamListener interface if service is opened successfully and streaming is * started, null otherwise */ @SuppressWarnings("unused") public IAudioStreamListener startAudioStream(boolean isEncrypted, AudioStreamingCodec codec, AudioStreamingParams params) { if (sdlSession == null) { DebugTool.logWarning("SdlSession is not created yet."); return null; } if (sdlSession.getSdlConnection() == null) { DebugTool.logWarning("SdlConnection is not available."); return null; } if (codec != AudioStreamingCodec.LPCM) { DebugTool.logWarning("Audio codec " + codec + " is not supported."); return null; } pcmServiceStartResponseReceived = false; pcmServiceStartResponse = false; sdlSession.startService(SessionType.PCM, sdlSession.getSessionId(), isEncrypted); FutureTask<Void> fTask = createFutureTask(new CallableMethod(RESPONSE_WAIT_TIME)); ScheduledExecutorService scheduler = createScheduler(); scheduler.execute(fTask); //noinspection StatementWithEmptyBody while (!pcmServiceStartResponseReceived && !fTask.isDone()); scheduler.shutdown(); if (pcmServiceStartResponse) { DebugTool.logInfo("StartService for audio succeeded"); return sdlSession.startAudioStream(); } else { if (pcmServiceStartRejectedParams != null) { StringBuilder builder = new StringBuilder(); for (String paramName : pcmServiceStartRejectedParams) { if (builder.length() > 0) { builder.append(", "); } builder.append(paramName); } DebugTool.logWarning("StartService for audio failed. Rejected params: " + builder.toString()); } else { DebugTool.logWarning("StartService for audio failed (rejected params not supplied)"); } return null; } } /** *Closes the opened audio service (serviceType 10) *@return true if the audio service is closed successfully, return false otherwise */ @SuppressWarnings("unused") public boolean endAudioStream() { if (sdlSession == null) return false; SdlConnection sdlConn = sdlSession.getSdlConnection(); if (sdlConn == null) return false; pcmServiceEndResponseReceived = false; pcmServiceEndResponse = false; sdlSession.stopAudioStream(); FutureTask<Void> fTask = createFutureTask(new CallableMethod(RESPONSE_WAIT_TIME)); ScheduledExecutorService scheduler = createScheduler(); scheduler.execute(fTask); //noinspection StatementWithEmptyBody while (!pcmServiceEndResponseReceived && !fTask.isDone()); scheduler.shutdown(); return pcmServiceEndResponse; } /** *Pauses the stream for the opened audio service (serviceType 10) *@return true if the audio service stream is paused successfully, return false otherwise */ @SuppressWarnings("unused") public boolean pauseAudioStream() { return sdlSession != null && sdlSession.pauseAudioStream(); } /** *Resumes the stream for the opened audio service (serviceType 10) *@return true if the audio service stream is resumed successfully, return false otherwise */ @SuppressWarnings("unused") public boolean resumeAudioStream() { return sdlSession != null && sdlSession.resumeAudioStream(); } private void NavServiceStarted() { navServiceStartResponseReceived = true; navServiceStartResponse = true; } private void NavServiceStartedNACK(List<String> rejectedParams) { navServiceStartResponseReceived = true; navServiceStartResponse = false; navServiceStartRejectedParams = rejectedParams; } private void AudioServiceStarted() { pcmServiceStartResponseReceived = true; pcmServiceStartResponse = true; } private void RPCProtectedServiceStarted() { rpcProtectedResponseReceived = true; rpcProtectedStartResponse = true; } private void AudioServiceStartedNACK(List<String> rejectedParams) { pcmServiceStartResponseReceived = true; pcmServiceStartResponse = false; pcmServiceStartRejectedParams = rejectedParams; } private void NavServiceEnded() { navServiceEndResponseReceived = true; navServiceEndResponse = true; } private void NavServiceEndedNACK() { navServiceEndResponseReceived = true; navServiceEndResponse = false; } private void AudioServiceEnded() { pcmServiceEndResponseReceived = true; pcmServiceEndResponse = true; } private void AudioServiceEndedNACK() { pcmServiceEndResponseReceived = true; pcmServiceEndResponse = false; } public void setAppService(Service mService) { _appService = mService; } @SuppressWarnings("unused") public boolean startProtectedRPCService() { rpcProtectedResponseReceived = false; rpcProtectedStartResponse = false; sdlSession.startService(SessionType.RPC, sdlSession.getSessionId(), true); FutureTask<Void> fTask = createFutureTask(new CallableMethod(RESPONSE_WAIT_TIME)); ScheduledExecutorService scheduler = createScheduler(); scheduler.execute(fTask); //noinspection StatementWithEmptyBody while (!rpcProtectedResponseReceived && !fTask.isDone()); scheduler.shutdown(); return rpcProtectedStartResponse; } @SuppressWarnings("unused") public void getLockScreenIcon(final OnLockScreenIconDownloadedListener l){ if(lockScreenIconRequest == null){ l.onLockScreenIconDownloadError(new SdlException("This version of SDL core may not support lock screen icons.", SdlExceptionCause.LOCK_SCREEN_ICON_NOT_SUPPORTED)); return; } LockScreenManager lockMan = sdlSession.getLockScreenMan(); Bitmap bitmap = lockMan.getLockScreenIcon(); // read bitmap if it was already downloaded so we don't have to download it every time if(bitmap != null){ l.onLockScreenIconDownloaded(bitmap); } else{ String url = lockScreenIconRequest.getUrl(); sdlSession.getLockScreenMan().downloadLockScreenIcon(url, l); } } /*Begin V1 Enhanced helper*/ /** *Sends an AddCommand RPCRequest to SDL. Responses are captured through callback on IProxyListener. * *@param commandID -Unique command ID of the command to add. *@param menuText -Menu text for optional sub value containing menu parameters. *@param parentID -Menu parent ID for optional sub value containing menu parameters. *@param position -Menu position for optional sub value containing menu parameters. *@param vrCommands -VR synonyms for this AddCommand. *@param IconValue -A static hex icon value or the binary image file name identifier (sent by the PutFile RPC). *@param IconType -Describes whether the image is static or dynamic *@param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("SameParameterValue") public void addCommand(Integer commandID, String menuText, Integer parentID, Integer position, Vector<String> vrCommands, String IconValue, ImageType IconType, Integer correlationID) throws SdlException { AddCommand msg = RPCRequestFactory.buildAddCommand(commandID, menuText, parentID, position, vrCommands, IconValue, IconType, correlationID); sendRPCRequest(msg); } /** *Sends an AddCommand RPCRequest to SDL. Responses are captured through callback on IProxyListener. * *@param commandID -Unique command ID of the command to add. *@param menuText -Menu text for optional sub value containing menu parameters. *@param position -Menu position for optional sub value containing menu parameters. *@param vrCommands -VR synonyms for this AddCommand. *@param IconValue -A static hex icon value or the binary image file name identifier (sent by the PutFile RPC). *@param IconType -Describes whether the image is static or dynamic *@param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void addCommand(Integer commandID, String menuText, Integer position, Vector<String> vrCommands, String IconValue, ImageType IconType, Integer correlationID) throws SdlException { addCommand(commandID, menuText, null, position, vrCommands, IconValue, IconType, correlationID); } /** *Sends an AddCommand RPCRequest to SDL. Responses are captured through callback on IProxyListener. * *@param commandID -Unique command ID of the command to add. *@param menuText -Menu text for optional sub value containing menu parameters. *@param position -Menu position for optional sub value containing menu parameters. *@param IconValue -A static hex icon value or the binary image file name identifier (sent by the PutFile RPC). *@param IconType -Describes whether the image is static or dynamic *@param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void addCommand(Integer commandID, String menuText, Integer position, String IconValue, ImageType IconType, Integer correlationID) throws SdlException { addCommand(commandID, menuText, null, position, null, IconValue, IconType, correlationID); } /** *Sends an AddCommand RPCRequest to SDL. Responses are captured through callback on IProxyListener. * *@param commandID -Unique command ID of the command to add. *@param menuText -Menu text for optional sub value containing menu parameters. *@param IconValue -A static hex icon value or the binary image file name identifier (sent by the PutFile RPC). *@param IconType -Describes whether the image is static or dynamic *@param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void addCommand(Integer commandID, String menuText, String IconValue, ImageType IconType, Integer correlationID) throws SdlException { addCommand(commandID, menuText, null, null, null, IconValue, IconType, correlationID); } /** * Sends an AddCommand RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param commandID -Unique command ID of the command to add. * @param menuText -Menu text for optional sub value containing menu parameters. * @param vrCommands -VR synonyms for this AddCommand. * @param IconValue -A static hex icon value or the binary image file name identifier (sent by the PutFile RPC). * @param IconType -Describes whether the image is static or dynamic * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void addCommand(Integer commandID, String menuText, Vector<String> vrCommands, String IconValue, ImageType IconType, Integer correlationID) throws SdlException { addCommand(commandID, menuText, null, null, vrCommands, IconValue, IconType, correlationID); } /** * Sends an AddCommand RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param commandID -Unique command ID of the command to add. * @param vrCommands -VR synonyms for this AddCommand. * @param IconValue -A static hex icon value or the binary image file name identifier (sent by the PutFile RPC). * @param IconType -Describes whether the image is static or dynamic * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void addCommand(Integer commandID, Vector<String> vrCommands, String IconValue, ImageType IconType, Integer correlationID) throws SdlException { addCommand(commandID, null, null, null, vrCommands, IconValue, IconType, correlationID); } /*End V1 Enhanced helper*/ /** *Sends an AddCommand RPCRequest to SDL. Responses are captured through callback on IProxyListener. * *@param commandID -Unique command ID of the command to add. *@param menuText -Menu text for optional sub value containing menu parameters. *@param parentID -Menu parent ID for optional sub value containing menu parameters. *@param position -Menu position for optional sub value containing menu parameters. *@param vrCommands -VR synonyms for this AddCommand. *@param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("SameParameterValue") public void addCommand(Integer commandID, String menuText, Integer parentID, Integer position, Vector<String> vrCommands, Integer correlationID) throws SdlException { AddCommand msg = RPCRequestFactory.buildAddCommand(commandID, menuText, parentID, position, vrCommands, correlationID); sendRPCRequest(msg); } /** *Sends an AddCommand RPCRequest to SDL. Responses are captured through callback on IProxyListener. * *@param commandID -Unique command ID of the command to add. *@param menuText -Menu text for optional sub value containing menu parameters. *@param position -Menu position for optional sub value containing menu parameters. *@param vrCommands -VR synonyms for this AddCommand. *@param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void addCommand(Integer commandID, String menuText, Integer position, Vector<String> vrCommands, Integer correlationID) throws SdlException { addCommand(commandID, menuText, null, position, vrCommands, correlationID); } /** *Sends an AddCommand RPCRequest to SDL. Responses are captured through callback on IProxyListener. * *@param commandID -Unique command ID of the command to add. *@param menuText -Menu text for optional sub value containing menu parameters. *@param position -Menu position for optional sub value containing menu parameters. *@param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void addCommand(Integer commandID, String menuText, Integer position, Integer correlationID) throws SdlException { addCommand(commandID, menuText, null, position, null, correlationID); } /** *Sends an AddCommand RPCRequest to SDL. Responses are captured through callback on IProxyListener. * *@param commandID -Unique command ID of the command to add. *@param menuText -Menu text for optional sub value containing menu parameters. *@param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void addCommand(Integer commandID, String menuText, Integer correlationID) throws SdlException { addCommand(commandID, menuText, null, null, (Vector<String>)null, correlationID); } /** * Sends an AddCommand RPCRequest to SDL. Responses are captured through callback on IProxyListener. * *@param commandID -Unique command ID of the command to add. *@param menuText -Menu text for optional sub value containing menu parameters. *@param vrCommands -VR synonyms for this AddCommand. *@param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void addCommand(Integer commandID, String menuText, Vector<String> vrCommands, Integer correlationID) throws SdlException { addCommand(commandID, menuText, null, null, vrCommands, correlationID); } /** * Sends an AddCommand RPCRequest to SDL. Responses are captured through callback on IProxyListener. * *@param commandID -Unique command ID of the command to add. *@param vrCommands -VR synonyms for this AddCommand. *@param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void addCommand(Integer commandID, Vector<String> vrCommands, Integer correlationID) throws SdlException { addCommand(commandID, null, null, null, vrCommands, correlationID); } /** * Sends an AddSubMenu RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param menuID -Unique ID of the sub menu to add. * @param menuName -Text to show in the menu for this sub menu. * @param position -Position within the items that are are at top level of the in application menu. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("SameParameterValue") public void addSubMenu(Integer menuID, String menuName, Integer position, Integer correlationID) throws SdlException { AddSubMenu msg = RPCRequestFactory.buildAddSubMenu(menuID, menuName, position, correlationID); sendRPCRequest(msg); } /** * Sends an AddSubMenu RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param menuID -Unique ID of the sub menu to add. * @param menuName -Text to show in the menu for this sub menu. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void addSubMenu(Integer menuID, String menuName, Integer correlationID) throws SdlException { addSubMenu(menuID, menuName, null, correlationID); } /*Begin V1 Enhanced helper*/ /** * Sends an Alert RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param ttsText -The text to speech message in the form of a string. * @param alertText1 -The first line of the alert text field. * @param alertText2 -The second line of the alert text field. * @param alertText3 -The optional third line of the alert text field. * @param playTone -Defines if tone should be played. * @param duration -Timeout in milliseconds. * @param softButtons -A list of App defined SoftButtons. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("SameParameterValue") public void alert(String ttsText, String alertText1, String alertText2, String alertText3, Boolean playTone, Integer duration, Vector<SoftButton> softButtons, Integer correlationID) throws SdlException { Alert msg = RPCRequestFactory.buildAlert(ttsText, alertText1, alertText2, alertText3, playTone, duration, softButtons, correlationID); sendRPCRequest(msg); } /** * Sends an Alert RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param ttsChunks -Text/phonemes to speak in the form of ttsChunks. * @param alertText1 -The first line of the alert text field. * @param alertText2 -The second line of the alert text field. * @param alertText3 -The optional third line of the alert text field. * @param playTone -Defines if tone should be played. * @param duration -Timeout in milliseconds. * @param softButtons -A list of App defined SoftButtons. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ public void alert(Vector<TTSChunk> ttsChunks, String alertText1, String alertText2, String alertText3, Boolean playTone, Integer duration, Vector<SoftButton> softButtons, Integer correlationID) throws SdlException { Alert msg = RPCRequestFactory.buildAlert(ttsChunks, alertText1, alertText2, alertText3, playTone, duration, softButtons, correlationID); sendRPCRequest(msg); } /** * Sends an Alert RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param ttsText -The text to speech message in the form of a string. * @param playTone -Defines if tone should be played. * @param softButtons -A list of App defined SoftButtons. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void alert(String ttsText, Boolean playTone, Vector<SoftButton> softButtons, Integer correlationID) throws SdlException { alert(ttsText, null, null, null, playTone, null, softButtons, correlationID); } /** * Sends an Alert RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param chunks -A list of text/phonemes to speak in the form of ttsChunks. * @param playTone -Defines if tone should be played. * @param softButtons -A list of App defined SoftButtons. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void alert(Vector<TTSChunk> chunks, Boolean playTone, Vector<SoftButton> softButtons, Integer correlationID) throws SdlException { alert(chunks, null, null, null, playTone, null, softButtons, correlationID); } /** * Sends an Alert RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param alertText1 -The first line of the alert text field. * @param alertText2 -The second line of the alert text field. * @param alertText3 -The optional third line of the alert text field. * @param playTone -Defines if tone should be played. * @param duration -Timeout in milliseconds. * @param softButtons -A list of App defined SoftButtons. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void alert(String alertText1, String alertText2, String alertText3, Boolean playTone, Integer duration, Vector<SoftButton> softButtons, Integer correlationID) throws SdlException { alert((Vector<TTSChunk>)null, alertText1, alertText2, alertText3, playTone, duration, softButtons, correlationID); } /*End V1 Enhanced helper*/ /** * Sends an Alert RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param ttsText -The text to speech message in the form of a string. * @param alertText1 -The first line of the alert text field. * @param alertText2 -The second line of the alert text field. * @param playTone -Defines if tone should be played. * @param duration -Timeout in milliseconds. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("SameParameterValue") public void alert(String ttsText, String alertText1, String alertText2, Boolean playTone, Integer duration, Integer correlationID) throws SdlException { Alert msg = RPCRequestFactory.buildAlert(ttsText, alertText1, alertText2, playTone, duration, correlationID); sendRPCRequest(msg); } /** * Sends an Alert RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param ttsChunks -A list of text/phonemes to speak in the form of ttsChunks. * @param alertText1 -The first line of the alert text field. * @param alertText2 -The second line of the alert text field. * @param playTone -Defines if tone should be played. * @param duration -Timeout in milliseconds. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ public void alert(Vector<TTSChunk> ttsChunks, String alertText1, String alertText2, Boolean playTone, Integer duration, Integer correlationID) throws SdlException { Alert msg = RPCRequestFactory.buildAlert(ttsChunks, alertText1, alertText2, playTone, duration, correlationID); sendRPCRequest(msg); } /** * Sends an Alert RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param ttsText -The text to speech message in the form of a string. * @param playTone -Defines if tone should be played. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void alert(String ttsText, Boolean playTone, Integer correlationID) throws SdlException { alert(ttsText, null, null, playTone, null, correlationID); } /** * Sends an Alert RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param chunks -A list of text/phonemes to speak in the form of ttsChunks. * @param playTone -Defines if tone should be played. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void alert(Vector<TTSChunk> chunks, Boolean playTone, Integer correlationID) throws SdlException { alert(chunks, null, null, playTone, null, correlationID); } /** * Sends an Alert RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param alertText1 -The first line of the alert text field. * @param alertText2 -The second line of the alert text field. * @param playTone -Defines if tone should be played. * @param duration -Timeout in milliseconds. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void alert(String alertText1, String alertText2, Boolean playTone, Integer duration, Integer correlationID) throws SdlException { alert((Vector<TTSChunk>)null, alertText1, alertText2, playTone, duration, correlationID); } /** * Sends a CreateInteractionChoiceSet RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param choiceSet to be sent to the module * @param interactionChoiceSetID to be used in reference to the supplied choiceSet * @param correlationID to be set to the RPCRequest * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void createInteractionChoiceSet( Vector<Choice> choiceSet, Integer interactionChoiceSetID, Integer correlationID) throws SdlException { CreateInteractionChoiceSet msg = RPCRequestFactory.buildCreateInteractionChoiceSet( choiceSet, interactionChoiceSetID, correlationID); sendRPCRequest(msg); } /** * Sends a DeleteCommand RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param commandID -ID of the command(s) to delete. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void deleteCommand(Integer commandID, Integer correlationID) throws SdlException { DeleteCommand msg = RPCRequestFactory.buildDeleteCommand(commandID, correlationID); sendRPCRequest(msg); } /** * Sends a DeleteInteractionChoiceSet RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param interactionChoiceSetID -ID of the interaction choice set to delete. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void deleteInteractionChoiceSet( Integer interactionChoiceSetID, Integer correlationID) throws SdlException { DeleteInteractionChoiceSet msg = RPCRequestFactory.buildDeleteInteractionChoiceSet( interactionChoiceSetID, correlationID); sendRPCRequest(msg); } /** * Sends a DeleteSubMenu RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param menuID -The menuID of the submenu to delete. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void deleteSubMenu(Integer menuID, Integer correlationID) throws SdlException { DeleteSubMenu msg = RPCRequestFactory.buildDeleteSubMenu(menuID, correlationID); sendRPCRequest(msg); } /*Begin V1 Enhanced helper*/ /** * Sends a PerformInteraction RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param initPrompt -Intial prompt spoken to the user at the start of an interaction. * @param displayText -Text to be displayed first. * @param interactionChoiceSetID -Interaction choice set IDs to use with an interaction. * @param vrHelp -Suggested VR Help Items to display on-screen during Perform Interaction. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void performInteraction(String initPrompt, String displayText, Integer interactionChoiceSetID, Vector<VrHelpItem> vrHelp, Integer correlationID) throws SdlException { PerformInteraction msg = RPCRequestFactory.buildPerformInteraction(initPrompt, displayText, interactionChoiceSetID, vrHelp, correlationID); sendRPCRequest(msg); } /** * Sends a PerformInteraction RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param initPrompt -Intial prompt spoken to the user at the start of an interaction. * @param displayText -Text to be displayed first. * @param interactionChoiceSetID -Interaction choice set IDs to use with an interaction. * @param helpPrompt -Help text that is spoken when a user speaks "help" during the interaction. * @param timeoutPrompt -Timeout text that is spoken when a VR interaction times out. * @param interactionMode - The method in which the user is notified and uses the interaction (Manual,VR,Both). * @param timeout -Timeout in milliseconds. * @param vrHelp -Suggested VR Help Items to display on-screen during Perform Interaction. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void performInteraction(String initPrompt, String displayText, Integer interactionChoiceSetID, String helpPrompt, String timeoutPrompt, InteractionMode interactionMode, Integer timeout, Vector<VrHelpItem> vrHelp, Integer correlationID) throws SdlException { PerformInteraction msg = RPCRequestFactory.buildPerformInteraction( initPrompt, displayText, interactionChoiceSetID, helpPrompt, timeoutPrompt, interactionMode, timeout, vrHelp, correlationID); sendRPCRequest(msg); } /** * Sends a PerformInteraction RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param initPrompt -Intial prompt spoken to the user at the start of an interaction. * @param displayText -Text to be displayed first. * @param interactionChoiceSetIDList -A list of interaction choice set IDs to use with an interaction. * @param helpPrompt -Help text that is spoken when a user speaks "help" during the interaction. * @param timeoutPrompt -Timeout text that is spoken when a VR interaction times out. * @param interactionMode - The method in which the user is notified and uses the interaction (Manual,VR,Both). * @param timeout -Timeout in milliseconds. * @param vrHelp -Suggested VR Help Items to display on-screen during Perform Interaction. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void performInteraction(String initPrompt, String displayText, Vector<Integer> interactionChoiceSetIDList, String helpPrompt, String timeoutPrompt, InteractionMode interactionMode, Integer timeout, Vector<VrHelpItem> vrHelp, Integer correlationID) throws SdlException { PerformInteraction msg = RPCRequestFactory.buildPerformInteraction(initPrompt, displayText, interactionChoiceSetIDList, helpPrompt, timeoutPrompt, interactionMode, timeout, vrHelp, correlationID); sendRPCRequest(msg); } /** * Sends a PerformInteraction RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param initChunks -A list of text/phonemes to speak for the initial prompt in the form of ttsChunks. * @param displayText -Text to be displayed first. * @param interactionChoiceSetIDList -A list of interaction choice set IDs to use with an interaction. * @param helpChunks -A list of text/phonemes to speak for the help text that is spoken when a user speaks "help" during the interaction. * @param timeoutChunks A list of text/phonems to speak for the timeout text that is spoken when a VR interaction times out. * @param interactionMode - The method in which the user is notified and uses the interaction (Manual,VR,Both). * @param timeout -Timeout in milliseconds. * @param vrHelp -Suggested VR Help Items to display on-screen during Perform Interaction. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void performInteraction( Vector<TTSChunk> initChunks, String displayText, Vector<Integer> interactionChoiceSetIDList, Vector<TTSChunk> helpChunks, Vector<TTSChunk> timeoutChunks, InteractionMode interactionMode, Integer timeout, Vector<VrHelpItem> vrHelp, Integer correlationID) throws SdlException { PerformInteraction msg = RPCRequestFactory.buildPerformInteraction( initChunks, displayText, interactionChoiceSetIDList, helpChunks, timeoutChunks, interactionMode, timeout,vrHelp, correlationID); sendRPCRequest(msg); } /*End V1 Enhanced*/ /** * Sends a PerformInteraction RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param initPrompt -Intial prompt spoken to the user at the start of an interaction. * @param displayText -Text to be displayed first. * @param interactionChoiceSetID -Interaction choice set IDs to use with an interaction. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void performInteraction(String initPrompt, String displayText, Integer interactionChoiceSetID, Integer correlationID) throws SdlException { PerformInteraction msg = RPCRequestFactory.buildPerformInteraction(initPrompt, displayText, interactionChoiceSetID, correlationID); sendRPCRequest(msg); } /** * Sends a PerformInteraction RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param initPrompt -Intial prompt spoken to the user at the start of an interaction. * @param displayText -Text to be displayed first. * @param interactionChoiceSetID -Interaction choice set IDs to use with an interaction. * @param helpPrompt -Help text that is spoken when a user speaks "help" during the interaction. * @param timeoutPrompt -Timeout text that is spoken when a VR interaction times out. * @param interactionMode - The method in which the user is notified and uses the interaction (Manual,VR,Both). * @param timeout -Timeout in milliseconds. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void performInteraction(String initPrompt, String displayText, Integer interactionChoiceSetID, String helpPrompt, String timeoutPrompt, InteractionMode interactionMode, Integer timeout, Integer correlationID) throws SdlException { PerformInteraction msg = RPCRequestFactory.buildPerformInteraction( initPrompt, displayText, interactionChoiceSetID, helpPrompt, timeoutPrompt, interactionMode, timeout, correlationID); sendRPCRequest(msg); } /** * Sends a PerformInteraction RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param initPrompt -Intial prompt spoken to the user at the start of an interaction. * @param displayText -Text to be displayed first. * @param interactionChoiceSetIDList -A list of interaction choice set IDs to use with an interaction. * @param helpPrompt -Help text that is spoken when a user speaks "help" during the interaction. * @param timeoutPrompt -Timeout text that is spoken when a VR interaction times out. * @param interactionMode - The method in which the user is notified and uses the interaction (Manual,VR,Both). * @param timeout -Timeout in milliseconds. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void performInteraction(String initPrompt, String displayText, Vector<Integer> interactionChoiceSetIDList, String helpPrompt, String timeoutPrompt, InteractionMode interactionMode, Integer timeout, Integer correlationID) throws SdlException { PerformInteraction msg = RPCRequestFactory.buildPerformInteraction(initPrompt, displayText, interactionChoiceSetIDList, helpPrompt, timeoutPrompt, interactionMode, timeout, correlationID); sendRPCRequest(msg); } /** * Sends a PerformInteraction RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param initChunks -A list of text/phonemes to speak for the initial prompt in the form of ttsChunks. * @param displayText -Text to be displayed first. * @param interactionChoiceSetIDList -A list of interaction choice set IDs to use with an interaction. * @param helpChunks -A list of text/phonemes to speak for the help text that is spoken when a user speaks "help" during the interaction. * @param timeoutChunks A list of text/phonems to speak for the timeout text that is spoken when a VR interaction times out. * @param interactionMode - The method in which the user is notified and uses the interaction (Manual,VR,Both). * @param timeout -Timeout in milliseconds. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void performInteraction( Vector<TTSChunk> initChunks, String displayText, Vector<Integer> interactionChoiceSetIDList, Vector<TTSChunk> helpChunks, Vector<TTSChunk> timeoutChunks, InteractionMode interactionMode, Integer timeout, Integer correlationID) throws SdlException { PerformInteraction msg = RPCRequestFactory.buildPerformInteraction( initChunks, displayText, interactionChoiceSetIDList, helpChunks, timeoutChunks, interactionMode, timeout, correlationID); sendRPCRequest(msg); } // Protected registerAppInterface used to ensure only non-ALM applications call // reqisterAppInterface protected void registerAppInterfacePrivate( SdlMsgVersion sdlMsgVersion, String appName, Vector<TTSChunk> ttsName, String ngnMediaScreenAppName, Vector<String> vrSynonyms, Boolean isMediaApp, Language languageDesired, Language hmiDisplayLanguageDesired, Vector<AppHMIType> appType, String appID, Integer correlationID) throws SdlException { String carrierName = null; if(telephonyManager != null){ carrierName = telephonyManager.getNetworkOperatorName(); } deviceInfo = RPCRequestFactory.BuildDeviceInfo(carrierName); RegisterAppInterface msg = RPCRequestFactory.buildRegisterAppInterface( sdlMsgVersion, appName, ttsName, ngnMediaScreenAppName, vrSynonyms, isMediaApp, languageDesired, hmiDisplayLanguageDesired, appType, appID, correlationID, deviceInfo); if (_bAppResumeEnabled) { if (_lastHashID != null) msg.setHashID(_lastHashID); } Intent sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "RPC_NAME", FunctionID.REGISTER_APP_INTERFACE.toString()); updateBroadcastIntent(sendIntent, "TYPE", RPCMessage.KEY_REQUEST); updateBroadcastIntent(sendIntent, "CORRID", msg.getCorrelationID()); updateBroadcastIntent(sendIntent, "DATA",serializeJSON(msg)); sendBroadcastIntent(sendIntent); sendRPCRequestPrivate(msg); } /*Begin V1 Enhanced helper function*/ /** * Sends a SetGlobalProperties RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param helpPrompt that will be used for the VR screen * @param timeoutPrompt string to be displayed after timeout * @param vrHelpTitle string that may be displayed on VR prompt dialog * @param vrHelp a list of VR synonyms that may be displayed to user * @param correlationID to be attached to the request * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void setGlobalProperties( String helpPrompt, String timeoutPrompt, String vrHelpTitle, Vector<VrHelpItem> vrHelp, Integer correlationID) throws SdlException { SetGlobalProperties req = RPCRequestFactory.buildSetGlobalProperties(helpPrompt, timeoutPrompt, vrHelpTitle, vrHelp, correlationID); sendRPCRequest(req); } /** * Sends a SetGlobalProperties RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param helpChunks tts chunks that should be used when prompting the user * @param timeoutChunks tts chunks that will be used when a timeout occurs * @param vrHelpTitle string that may be displayed on VR prompt dialog * @param vrHelp a list of VR synonyms that may be displayed to user * @param correlationID ID to be attached to the RPCRequest that correlates the RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void setGlobalProperties( Vector<TTSChunk> helpChunks, Vector<TTSChunk> timeoutChunks, String vrHelpTitle, Vector<VrHelpItem> vrHelp, Integer correlationID) throws SdlException { SetGlobalProperties req = RPCRequestFactory.buildSetGlobalProperties( helpChunks, timeoutChunks, vrHelpTitle, vrHelp, correlationID); sendRPCRequest(req); } /*End V1 Enhanced helper function*/ /** * Sends a SetGlobalProperties RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param helpPrompt that will be used for the VR screen * @param timeoutPrompt string to be displayed after timeout * @param correlationID ID to be attached to the RPCRequest that correlates the RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void setGlobalProperties( String helpPrompt, String timeoutPrompt, Integer correlationID) throws SdlException { SetGlobalProperties req = RPCRequestFactory.buildSetGlobalProperties(helpPrompt, timeoutPrompt, correlationID); sendRPCRequest(req); } /** * Sends a SetGlobalProperties RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param helpChunks tts chunks that should be used when prompting the user * @param timeoutChunks tts chunks that will be used when a timeout occurs * @param correlationID ID to be attached to the RPCRequest that correlates the RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void setGlobalProperties( Vector<TTSChunk> helpChunks, Vector<TTSChunk> timeoutChunks, Integer correlationID) throws SdlException { SetGlobalProperties req = RPCRequestFactory.buildSetGlobalProperties( helpChunks, timeoutChunks, correlationID); sendRPCRequest(req); } @SuppressWarnings("unused") public void resetGlobalProperties(Vector<GlobalProperty> properties, Integer correlationID) throws SdlException { ResetGlobalProperties req = new ResetGlobalProperties(); req.setCorrelationID(correlationID); req.setProperties(properties); sendRPCRequest(req); } /** * Sends a SetMediaClockTimer RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param hours integer for hours * @param minutes integer for minutes * @param seconds integer for seconds * @param updateMode mode in which the media clock timer should be updated * @param correlationID ID to be attached to the RPCRequest that correlates the RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void setMediaClockTimer(Integer hours, Integer minutes, Integer seconds, UpdateMode updateMode, Integer correlationID) throws SdlException { SetMediaClockTimer msg = RPCRequestFactory.buildSetMediaClockTimer(hours, minutes, seconds, updateMode, correlationID); sendRPCRequest(msg); } /** * Pauses the media clock. Responses are captured through callback on IProxyListener. * * @param correlationID ID to be attached to the RPCRequest that correlates the RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void pauseMediaClockTimer(Integer correlationID) throws SdlException { SetMediaClockTimer msg = RPCRequestFactory.buildSetMediaClockTimer(0, 0, 0, UpdateMode.PAUSE, correlationID); sendRPCRequest(msg); } /** * Resumes the media clock. Responses are captured through callback on IProxyListener. * * @param correlationID ID to be attached to the RPCRequest that correlates the RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void resumeMediaClockTimer(Integer correlationID) throws SdlException { SetMediaClockTimer msg = RPCRequestFactory.buildSetMediaClockTimer(0, 0, 0, UpdateMode.RESUME, correlationID); sendRPCRequest(msg); } /** * Clears the media clock. Responses are captured through callback on IProxyListener. * * @param correlationID ID to be attached to the RPCRequest that correlates the RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void clearMediaClockTimer(Integer correlationID) throws SdlException { Show msg = RPCRequestFactory.buildShow(null, null, null, " ", null, null, correlationID); sendRPCRequest(msg); } /*Begin V1 Enhanced helper*/ /** * Sends a Show RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param mainText1 text displayed in a single or upper display line. * @param mainText2 text displayed on the second display line. * @param mainText3 text displayed on the second "page" first display line. * @param mainText4 text displayed on the second "page" second display line. * @param statusBar text is placed in the status bar area (Only valid for NAVIGATION apps) * @param mediaClock text value for MediaClock field. * @param mediaTrack text displayed in the track field. * @param graphic image struct determining whether static or dynamic image to display in app. * @param softButtons app defined SoftButtons. * @param customPresets app labeled on-screen presets. * @param alignment specifies how mainText1 and mainText2s texts should be aligned on display. * @param correlationID ID to be attached to the RPCRequest that correlates the RPCResponse -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("SameParameterValue") public void show(String mainText1, String mainText2, String mainText3, String mainText4, String statusBar, String mediaClock, String mediaTrack, Image graphic, Vector<SoftButton> softButtons, Vector <String> customPresets, TextAlignment alignment, Integer correlationID) throws SdlException { Show msg = RPCRequestFactory.buildShow(mainText1, mainText2, mainText3, mainText4, statusBar, mediaClock, mediaTrack, graphic, softButtons, customPresets, alignment, correlationID); sendRPCRequest(msg); } /** * Sends a Show RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param mainText1 -Text displayed in a single or upper display line. * @param mainText2 -Text displayed on the second display line. * @param mainText3 -Text displayed on the second "page" first display line. * @param mainText4 -Text displayed on the second "page" second display line. * @param graphic -Image struct determining whether static or dynamic image to display in app. * @param softButtons -App defined SoftButtons. * @param customPresets -App labeled on-screen presets. * @param alignment -Specifies how mainText1 and mainText2s texts should be aligned on display. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void show(String mainText1, String mainText2, String mainText3, String mainText4, Image graphic, Vector<SoftButton> softButtons, Vector <String> customPresets, TextAlignment alignment, Integer correlationID) throws SdlException { show(mainText1, mainText2, mainText3, mainText4, null, null, null, graphic, softButtons, customPresets, alignment, correlationID); } /*End V1 Enhanced helper*/ /** * Sends a Show RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param mainText1 text displayed in a single or upper display line. * @param mainText2 text displayed on the second display line. * @param statusBar text is placed in the status bar area (Only valid for NAVIGATION apps) * @param mediaClock text value for MediaClock field. * @param mediaTrack text displayed in the track field. * @param alignment specifies how mainText1 and mainText2s texts should be aligned on display. * @param correlationID unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("SameParameterValue") public void show(String mainText1, String mainText2, String statusBar, String mediaClock, String mediaTrack, TextAlignment alignment, Integer correlationID) throws SdlException { Show msg = RPCRequestFactory.buildShow(mainText1, mainText2, statusBar, mediaClock, mediaTrack, alignment, correlationID); sendRPCRequest(msg); } /** * Sends a Show RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param mainText1 -Text displayed in a single or upper display line. * @param mainText2 -Text displayed on the second display line. * @param alignment -Specifies how mainText1 and mainText2s texts should be aligned on display. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void show(String mainText1, String mainText2, TextAlignment alignment, Integer correlationID) throws SdlException { show(mainText1, mainText2, null, null, null, alignment, correlationID); } /** * Sends a Speak RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param ttsText -The text to speech message in the form of a string. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void speak(String ttsText, Integer correlationID) throws SdlException { Speak msg = RPCRequestFactory.buildSpeak(TTSChunkFactory.createSimpleTTSChunks(ttsText), correlationID); sendRPCRequest(msg); } /** * Sends a Speak RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param ttsChunks -Text/phonemes to speak in the form of ttsChunks. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void speak(Vector<TTSChunk> ttsChunks, Integer correlationID) throws SdlException { Speak msg = RPCRequestFactory.buildSpeak(ttsChunks, correlationID); sendRPCRequest(msg); } /** * Sends a SubscribeButton RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param buttonName -Name of the button to subscribe. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void subscribeButton(ButtonName buttonName, Integer correlationID) throws SdlException { SubscribeButton msg = RPCRequestFactory.buildSubscribeButton(buttonName, correlationID); sendRPCRequest(msg); } // Protected unregisterAppInterface used to ensure no non-ALM app calls // unregisterAppInterface. protected void unregisterAppInterfacePrivate(Integer correlationID) throws SdlException { UnregisterAppInterface msg = RPCRequestFactory.buildUnregisterAppInterface(correlationID); Intent sendIntent = createBroadcastIntent(); updateBroadcastIntent(sendIntent, "RPC_NAME", FunctionID.UNREGISTER_APP_INTERFACE.toString()); updateBroadcastIntent(sendIntent, "TYPE", RPCMessage.KEY_REQUEST); updateBroadcastIntent(sendIntent, "CORRID", msg.getCorrelationID()); updateBroadcastIntent(sendIntent, "DATA",serializeJSON(msg)); sendBroadcastIntent(sendIntent); sendRPCRequestPrivate(msg); } /** * Sends an UnsubscribeButton RPCRequest to SDL. Responses are captured through callback on IProxyListener. * * @param buttonName -Name of the button to unsubscribe. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void unsubscribeButton(ButtonName buttonName, Integer correlationID) throws SdlException { UnsubscribeButton msg = RPCRequestFactory.buildUnsubscribeButton( buttonName, correlationID); sendRPCRequest(msg); } /** * Creates a choice to be added to a choiceset. Choice has both a voice and a visual menu component. * * @param choiceID -Unique ID used to identify this choice (returned in callback). * @param choiceMenuName -Text name displayed for this choice. * @param choiceVrCommands -Vector of vrCommands used to select this choice by voice. Must contain * at least one non-empty element. * @return Choice created. */ @SuppressWarnings("unused") public Choice createChoiceSetChoice(Integer choiceID, String choiceMenuName, Vector<String> choiceVrCommands) { Choice returnChoice = new Choice(); returnChoice.setChoiceID(choiceID); returnChoice.setMenuName(choiceMenuName); returnChoice.setVrCommands(choiceVrCommands); return returnChoice; } /** * Starts audio pass thru session. Responses are captured through callback on IProxyListener. * * @param initialPrompt -SDL will speak this prompt before opening the audio pass thru session. * @param audioPassThruDisplayText1 -First line of text displayed during audio capture. * @param audioPassThruDisplayText2 -Second line of text displayed during audio capture. * @param samplingRate -Allowable values of 8 khz or 16 or 22 or 44 khz. * @param maxDuration -The maximum duration of audio recording in milliseconds. * @param bitsPerSample -Specifies the quality the audio is recorded. Currently 8 bit or 16 bit. * @param audioType -Specifies the type of audio data being requested. * @param muteAudio -Defines if the current audio source should be muted during the APT session. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void performaudiopassthru(String initialPrompt, String audioPassThruDisplayText1, String audioPassThruDisplayText2, SamplingRate samplingRate, Integer maxDuration, BitsPerSample bitsPerSample, AudioType audioType, Boolean muteAudio, Integer correlationID) throws SdlException { PerformAudioPassThru msg = RPCRequestFactory.BuildPerformAudioPassThru(initialPrompt, audioPassThruDisplayText1, audioPassThruDisplayText2, samplingRate, maxDuration, bitsPerSample, audioType, muteAudio, correlationID); sendRPCRequest(msg); } /** * Ends audio pass thru session. Responses are captured through callback on IProxyListener. * * @param correlationID ID to be attached to the RPCRequest that correlates the RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void endaudiopassthru(Integer correlationID) throws SdlException { EndAudioPassThru msg = RPCRequestFactory.BuildEndAudioPassThru(correlationID); sendRPCRequest(msg); } /** * Subscribes for specific published data items. The data will be only sent if it has changed. * Responses are captured through callback on IProxyListener. * * @param gps -Subscribes to GPS data. * @param speed -Subscribes to vehicle speed data in kilometers per hour. * @param rpm -Subscribes to number of revolutions per minute of the engine. * @param fuelLevel -Subscribes to fuel level in the tank (percentage). * @param fuelLevel_State -Subscribes to fuel level state. * @param instantFuelConsumption -Subscribes to instantaneous fuel consumption in microlitres. * @param externalTemperature -Subscribes to the external temperature in degrees celsius. * @param prndl -Subscribes to PRNDL data that houses the selected gear. * @param tirePressure -Subscribes to the TireStatus data containing status and pressure of tires. * @param odometer -Subscribes to Odometer data in km. * @param beltStatus -Subscribes to status of the seat belts. * @param bodyInformation -Subscribes to body information including power modes. * @param deviceStatus -Subscribes to device status including signal and battery strength. * @param driverBraking -Subscribes to the status of the brake pedal. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void subscribevehicledata(boolean gps, boolean speed, boolean rpm, boolean fuelLevel, boolean fuelLevel_State, boolean instantFuelConsumption, boolean externalTemperature, boolean prndl, boolean tirePressure, boolean odometer, boolean beltStatus, boolean bodyInformation, boolean deviceStatus, boolean driverBraking, Integer correlationID) throws SdlException { SubscribeVehicleData msg = RPCRequestFactory.BuildSubscribeVehicleData(gps, speed, rpm, fuelLevel, fuelLevel_State, instantFuelConsumption, externalTemperature, prndl, tirePressure, odometer, beltStatus, bodyInformation, deviceStatus, driverBraking, correlationID); sendRPCRequest(msg); } /** * Unsubscribes for specific published data items. * Responses are captured through callback on IProxyListener. * * @param gps -Unsubscribes to GPS data. * @param speed -Unsubscribes to vehicle speed data in kilometers per hour. * @param rpm -Unsubscribes to number of revolutions per minute of the engine. * @param fuelLevel -Unsubscribes to fuel level in the tank (percentage). * @param fuelLevel_State -Unsubscribes to fuel level state. * @param instantFuelConsumption -Unsubscribes to instantaneous fuel consumption in microlitres. * @param externalTemperature -Unsubscribes to the external temperature in degrees celsius. * @param prndl -Unsubscribes to PRNDL data that houses the selected gear. * @param tirePressure -Unsubscribes to the TireStatus data containing status and pressure of tires. * @param odometer -Unsubscribes to Odometer data in km. * @param beltStatus -Unsubscribes to status of the seat belts. * @param bodyInformation -Unsubscribes to body information including power modes. * @param deviceStatus -Unsubscribes to device status including signal and battery strength. * @param driverBraking -Unsubscribes to the status of the brake pedal. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void unsubscribevehicledata(boolean gps, boolean speed, boolean rpm, boolean fuelLevel, boolean fuelLevel_State, boolean instantFuelConsumption, boolean externalTemperature, boolean prndl, boolean tirePressure, boolean odometer, boolean beltStatus, boolean bodyInformation, boolean deviceStatus, boolean driverBraking, Integer correlationID) throws SdlException { UnsubscribeVehicleData msg = RPCRequestFactory.BuildUnsubscribeVehicleData(gps, speed, rpm, fuelLevel, fuelLevel_State, instantFuelConsumption, externalTemperature, prndl, tirePressure, odometer, beltStatus, bodyInformation, deviceStatus, driverBraking, correlationID); sendRPCRequest(msg); } /** * Performs a Non periodic vehicle data read request. * Responses are captured through callback on IProxyListener. * * @param gps -Performs an ad-hoc request for GPS data. * @param speed -Performs an ad-hoc request for vehicle speed data in kilometers per hour. * @param rpm -Performs an ad-hoc request for number of revolutions per minute of the engine. * @param fuelLevel -Performs an ad-hoc request for fuel level in the tank (percentage). * @param fuelLevel_State -Performs an ad-hoc request for fuel level state. * @param instantFuelConsumption -Performs an ad-hoc request for instantaneous fuel consumption in microlitres. * @param externalTemperature -Performs an ad-hoc request for the external temperature in degrees celsius. * @param vin -Performs an ad-hoc request for the Vehicle identification number * @param prndl -Performs an ad-hoc request for PRNDL data that houses the selected gear. * @param tirePressure -Performs an ad-hoc request for the TireStatus data containing status and pressure of tires. * @param odometer -Performs an ad-hoc request for Odometer data in km. * @param beltStatus -Performs an ad-hoc request for status of the seat belts. * @param bodyInformation -Performs an ad-hoc request for body information including power modes. * @param deviceStatus -Performs an ad-hoc request for device status including signal and battery strength. * @param driverBraking -Performs an ad-hoc request for the status of the brake pedal. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void getvehicledata(boolean gps, boolean speed, boolean rpm, boolean fuelLevel, boolean fuelLevel_State, boolean instantFuelConsumption, boolean externalTemperature, boolean vin, boolean prndl, boolean tirePressure, boolean odometer, boolean beltStatus, boolean bodyInformation, boolean deviceStatus, boolean driverBraking, Integer correlationID) throws SdlException { GetVehicleData msg = RPCRequestFactory.BuildGetVehicleData(gps, speed, rpm, fuelLevel, fuelLevel_State, instantFuelConsumption, externalTemperature, vin, prndl, tirePressure, odometer, beltStatus, bodyInformation, deviceStatus, driverBraking, correlationID); sendRPCRequest(msg); } /** * Creates a full screen overlay containing a large block of formatted text that can be scrolled with up to 8 SoftButtons defined. * Responses are captured through callback on IProxyListener. * * @param scrollableMessageBody -Body of text that can include newlines and tabs. * @param timeout -App defined timeout. Indicates how long of a timeout from the last action. * @param softButtons -App defined SoftButtons. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void scrollablemessage(String scrollableMessageBody, Integer timeout, Vector<SoftButton> softButtons, Integer correlationID) throws SdlException { ScrollableMessage msg = RPCRequestFactory.BuildScrollableMessage(scrollableMessageBody, timeout, softButtons, correlationID); sendRPCRequest(msg); } /** * Creates a full screen or pop-up overlay (depending on platform) with a single user controlled slider. * Responses are captured through callback on IProxyListener. * * @param numTicks -Number of selectable items on a horizontal axis. * @param position -Initial position of slider control (cannot exceed numTicks). * @param sliderHeader -Text header to display. * @param sliderFooter - Text footer to display (meant to display min/max threshold descriptors). * @param timeout -App defined timeout. Indicates how long of a timeout from the last action. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void slider(Integer numTicks, Integer position, String sliderHeader, Vector<String> sliderFooter, Integer timeout, Integer correlationID) throws SdlException { Slider msg = RPCRequestFactory.BuildSlider(numTicks, position, sliderHeader, sliderFooter, timeout, correlationID); sendRPCRequest(msg); } /** * Responses are captured through callback on IProxyListener. * * @param language requested SDL voice engine (VR+TTS) language registration * @param hmiDisplayLanguage request display language registration. * @param correlationID ID to be attached to the RPCRequest that correlates the RPCResponse * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void changeregistration(Language language, Language hmiDisplayLanguage, Integer correlationID) throws SdlException { ChangeRegistration msg = RPCRequestFactory.BuildChangeRegistration(language, hmiDisplayLanguage, correlationID); sendRPCRequest(msg); } /** * Used to push a binary stream of file data onto the module from a mobile device. * Responses are captured through callback on IProxyListener. * * @param is - The input stream of byte data that putFileStream will read from * @param sdlFileName - The file reference name used by the putFile RPC. * @param iOffset - The data offset in bytes, a value of zero is used to indicate data starting from the beginging of the file. * A value greater than zero is used for resuming partial data chunks. * @param iLength - The total length of the file being sent. * @throws SdlException if an unrecoverable error is encountered * @see #putFileStream(InputStream, String, Long, Long) */ @SuppressWarnings("unused") @Deprecated public void putFileStream(InputStream is, String sdlFileName, Integer iOffset, Integer iLength) throws SdlException { @SuppressWarnings("deprecation") PutFile msg = RPCRequestFactory.buildPutFile(sdlFileName, iOffset, iLength); startRPCStream(is, msg); } /** * Used to push a binary stream of file data onto the module from a mobile * device. Responses are captured through callback on IProxyListener. * * @param inputStream The input stream of byte data that will be read from. * @param fileName The SDL file reference name used by the RPC. * @param offset The data offset in bytes. A value of zero is used to * indicate data starting from the beginning of the file and a value greater * than zero is used for resuming partial data chunks. * @param length The total length of the file being sent. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void putFileStream(InputStream inputStream, String fileName, Long offset, Long length) throws SdlException { PutFile msg = RPCRequestFactory.buildPutFile(fileName, offset, length); startRPCStream(inputStream, msg); } /** * Used to push a binary stream of file data onto the module from a mobile device. * Responses are captured through callback on IProxyListener. * * @param sdlFileName - The file reference name used by the putFile RPC. * @param iOffset - The data offset in bytes, a value of zero is used to indicate data starting from the beginging of a file. * A value greater than zero is used for resuming partial data chunks. * @param iLength - The total length of the file being sent. * * @return OutputStream - The output stream of byte data that is written to by the app developer * @throws SdlException if an unrecoverable error is encountered * @see #putFileStream(String, Long, Long) */ @SuppressWarnings("unused") @Deprecated public OutputStream putFileStream(String sdlFileName, Integer iOffset, Integer iLength) throws SdlException { @SuppressWarnings("deprecation") PutFile msg = RPCRequestFactory.buildPutFile(sdlFileName, iOffset, iLength); return startRPCStream(msg); } /** * Used to push a binary stream of file data onto the module from a mobile * device. Responses are captured through callback on IProxyListener. * * @param fileName The SDL file reference name used by the RPC. * @param offset The data offset in bytes. A value of zero is used to * indicate data starting from the beginning of the file and a value greater * than zero is used for resuming partial data chunks. * @param length The total length of the file being sent. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public OutputStream putFileStream(String fileName, Long offset, Long length) throws SdlException { PutFile msg = RPCRequestFactory.buildPutFile(fileName, offset, length); return startRPCStream(msg); } /** * Used to push a binary stream of file data onto the module from a mobile device. * Responses are captured through callback on IProxyListener. * * @param is - The input stream of byte data that PutFileStream will read from * @param sdlFileName - The file reference name used by the putFile RPC. * @param iOffset - The data offset in bytes, a value of zero is used to indicate data starting from the beginging of the file. * A value greater than zero is used for resuming partial data chunks. * @param iLength - The total length of the file being sent. * @param fileType - The selected file type -- see the FileType enumeration for details * @param bPersistentFile - Indicates if the file is meant to persist between sessions / ignition cycles. * @param bSystemFile - Indicates if the file is meant to be passed thru core to elsewhere on the system. * @throws SdlException if an unrecoverable error is encountered * @see #putFileStream(InputStream, String, Long, Long, FileType, Boolean, Boolean, OnPutFileUpdateListener) */ @SuppressWarnings("unused") @Deprecated public void putFileStream(InputStream is, String sdlFileName, Integer iOffset, Integer iLength, FileType fileType, Boolean bPersistentFile, Boolean bSystemFile) throws SdlException { @SuppressWarnings("deprecation") PutFile msg = RPCRequestFactory.buildPutFile(sdlFileName, iOffset, iLength, fileType, bPersistentFile, bSystemFile); startRPCStream(is, msg); } /** * Used to push a binary stream of file data onto the module from a mobile * device. Responses are captured through callback on IProxyListener. * * @param inputStream The input stream of byte data that will be read from. * @param fileName The SDL file reference name used by the RPC. * @param offset The data offset in bytes. A value of zero is used to * indicate data starting from the beginning of the file and a value greater * than zero is used for resuming partial data chunks. * @param length The total length of the file being sent. * @param fileType The selected file type. See the {@link FileType} enum for * details. * @param isPersistentFile Indicates if the file is meant to persist between * sessions / ignition cycles. * @param isSystemFile Indicates if the file is meant to be passed through * core to elsewhere in the system. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void putFileStream(InputStream inputStream, String fileName, Long offset, Long length, FileType fileType, Boolean isPersistentFile, Boolean isSystemFile, OnPutFileUpdateListener cb) throws SdlException { PutFile msg = RPCRequestFactory.buildPutFile(fileName, offset, length); msg.setOnPutFileUpdateListener(cb); startRPCStream(inputStream, msg); } /** * Used to push a binary stream of file data onto the module from a mobile device. * Responses are captured through callback on IProxyListener. * * @param sdlFileName - The file reference name used by the putFile RPC. * @param iOffset - The data offset in bytes, a value of zero is used to indicate data starting from the beginging of a file. * A value greater than zero is used for resuming partial data chunks. * @param iLength - The total length of the file being sent. * @param fileType - The selected file type -- see the FileType enumeration for details * @param bPersistentFile - Indicates if the file is meant to persist between sessions / ignition cycles. * @param bSystemFile - Indicates if the file is meant to be passed thru core to elsewhere on the system. * @return OutputStream - The output stream of byte data that is written to by the app developer * @throws SdlException if an unrecoverable error is encountered * @see #putFileStream(String, Long, Long, FileType, Boolean, Boolean, OnPutFileUpdateListener) */ @SuppressWarnings("unused") @Deprecated public OutputStream putFileStream(String sdlFileName, Integer iOffset, Integer iLength, FileType fileType, Boolean bPersistentFile, Boolean bSystemFile) throws SdlException { @SuppressWarnings("deprecation") PutFile msg = RPCRequestFactory.buildPutFile(sdlFileName, iOffset, iLength, fileType, bPersistentFile, bSystemFile); return startRPCStream(msg); } /** * Used to push a binary stream of file data onto the module from a mobile * device. Responses are captured through callback on IProxyListener. * * @param fileName The SDL file reference name used by the RPC. * @param offset The data offset in bytes. A value of zero is used to * indicate data starting from the beginning of the file and a value greater * than zero is used for resuming partial data chunks. * @param length The total length of the file being sent. * @param fileType The selected file type. See the {@link FileType} enum for * details. * @param isPersistentFile Indicates if the file is meant to persist between * sessions / ignition cycles. * @param isSystemFile Indicates if the file is meant to be passed through * core to elsewhere in the system. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public OutputStream putFileStream(String fileName, Long offset, Long length, FileType fileType, Boolean isPersistentFile, Boolean isSystemFile, OnPutFileUpdateListener cb) throws SdlException { PutFile msg = RPCRequestFactory.buildPutFile(fileName, offset, length); msg.setOnPutFileUpdateListener(cb); return startRPCStream(msg); } /** * Used to push a stream of putfile RPC's containing binary data from a mobile device to the module. * Responses are captured through callback on IProxyListener. * * @param sPath - The physical file path on the mobile device. * @param sdlFileName - The file reference name used by the putFile RPC. * @param iOffset - The data offset in bytes, a value of zero is used to indicate data starting from the beginging of a file. * A value greater than zero is used for resuming partial data chunks. * @param fileType - The selected file type -- see the FileType enumeration for details * @param bPersistentFile - Indicates if the file is meant to persist between sessions / ignition cycles. * @param bSystemFile - Indicates if the file is meant to be passed thru core to elsewhere on the system. * @param iCorrelationID - A unique ID that correlates each RPCRequest and RPCResponse. * @return RPCStreamController - If the putFileStream was not started successfully null is returned, otherwise a valid object reference is returned * @throws SdlException if an unrecoverable error is encountered * @see #putFileStream(String, String, Long, FileType, Boolean, Boolean, Boolean, Integer, OnPutFileUpdateListener) */ @SuppressWarnings("unused") @Deprecated public RPCStreamController putFileStream(String sPath, String sdlFileName, Integer iOffset, FileType fileType, Boolean bPersistentFile, Boolean bSystemFile, Integer iCorrelationID) throws SdlException { @SuppressWarnings("deprecation") PutFile msg = RPCRequestFactory.buildPutFile(sdlFileName, iOffset, 0, fileType, bPersistentFile, bSystemFile, iCorrelationID); return startPutFileStream(sPath, msg); } /** * Used to push a binary stream of file data onto the module from a mobile * device. Responses are captured through callback on IProxyListener. * * @param path The physical file path on the mobile device. * @param fileName The SDL file reference name used by the RPC. * @param offset The data offset in bytes. A value of zero is used to * indicate data starting from the beginning of the file and a value greater * than zero is used for resuming partial data chunks. * @param fileType The selected file type. See the {@link FileType} enum for * details. * @param isPersistentFile Indicates if the file is meant to persist between * sessions / ignition cycles. * @param isSystemFile Indicates if the file is meant to be passed through * core to elsewhere in the system. * @param correlationId A unique id that correlates each RPCRequest and * RPCResponse. * @return RPCStreamController If the putFileStream was not started * successfully null is returned, otherwise a valid object reference is * returned . * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public RPCStreamController putFileStream(String path, String fileName, Long offset, FileType fileType, Boolean isPersistentFile, Boolean isSystemFile, Boolean isPayloadProtected, Integer correlationId, OnPutFileUpdateListener cb ) throws SdlException { PutFile msg = RPCRequestFactory.buildPutFile(fileName, offset, 0L, fileType, isPersistentFile, isSystemFile, isPayloadProtected, correlationId); msg.setOnPutFileUpdateListener(cb); return startPutFileStream(path,msg); } /** * Used to push a stream of putfile RPC's containing binary data from a mobile device to the module. * Responses are captured through callback on IProxyListener. * * @param is - The input stream of byte data that putFileStream will read from. * @param sdlFileName - The file reference name used by the putFile RPC. * @param iOffset - The data offset in bytes, a value of zero is used to indicate data starting from the beginging of a file. * A value greater than zero is used for resuming partial data chunks. * @param fileType - The selected file type -- see the FileType enumeration for details * @param bPersistentFile - Indicates if the file is meant to persist between sessions / ignition cycles. * @param bSystemFile - Indicates if the file is meant to be passed thru core to elsewhere on the system. * @param iCorrelationID - A unique ID that correlates each RPCRequest and RPCResponse. * @return RPCStreamController - If the putFileStream was not started successfully null is returned, otherwise a valid object reference is returned * @throws SdlException if an unrecoverable error is encountered * @see #putFileStream(InputStream, String, Long, Long, FileType, Boolean, Boolean, Boolean, Integer) */ @SuppressWarnings("unused") @Deprecated public RPCStreamController putFileStream(InputStream is, String sdlFileName, Integer iOffset, Integer iLength, FileType fileType, Boolean bPersistentFile, Boolean bSystemFile, Integer iCorrelationID) throws SdlException { @SuppressWarnings("deprecation") PutFile msg = RPCRequestFactory.buildPutFile(sdlFileName, iOffset, iLength, fileType, bPersistentFile, bSystemFile, iCorrelationID); return startPutFileStream(is, msg); } /** * Used to push a binary stream of file data onto the module from a mobile * device. Responses are captured through callback on IProxyListener. * * @param inputStream The input stream of byte data that will be read from. * @param fileName The SDL file reference name used by the RPC. * @param offset The data offset in bytes. A value of zero is used to * indicate data starting from the beginning of the file and a value greater * than zero is used for resuming partial data chunks. * @param length The total length of the file being sent. * @param fileType The selected file type. See the {@link FileType} enum for * details. * @param isPersistentFile Indicates if the file is meant to persist between * sessions / ignition cycles. * @param isSystemFile Indicates if the file is meant to be passed through * core to elsewhere in the system. * @param correlationId A unique id that correlates each RPCRequest and * RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public RPCStreamController putFileStream(InputStream inputStream, String fileName, Long offset, Long length, FileType fileType, Boolean isPersistentFile, Boolean isSystemFile, Boolean isPayloadProtected, Integer correlationId) throws SdlException { PutFile msg = RPCRequestFactory.buildPutFile(fileName, offset, length, fileType, isPersistentFile, isSystemFile, isPayloadProtected, correlationId); return startPutFileStream(inputStream, msg); } /** * * Used to end an existing putFileStream that was previously initiated with any putFileStream method. * */ @SuppressWarnings("unused") public void endPutFileStream() { endRPCStream(); } /** * Used to push a binary data onto the SDL module from a mobile device, such as icons and album art. Not supported on first generation SDL vehicles. * Responses are captured through callback on IProxyListener. * * @param sdlFileName -File reference name. * @param fileType -Selected file type. * @param persistentFile -Indicates if the file is meant to persist between sessions / ignition cycles. * @param fileData byte array of data of the file that is to be sent * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void putfile(String sdlFileName, FileType fileType, Boolean persistentFile, byte[] fileData, Integer correlationID) throws SdlException { PutFile msg = RPCRequestFactory.buildPutFile(sdlFileName, fileType, persistentFile, fileData, correlationID); sendRPCRequest(msg); } /** * Used to delete a file resident on the SDL module in the app's local cache. Not supported on first generation SDL vehicles. * Responses are captured through callback on IProxyListener. * * @param sdlFileName -File reference name. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void deletefile(String sdlFileName, Integer correlationID) throws SdlException { DeleteFile msg = RPCRequestFactory.buildDeleteFile(sdlFileName, correlationID); sendRPCRequest(msg); } /** * Requests the current list of resident filenames for the registered app. Not supported on first generation SDL vehicles. * Responses are captured through callback on IProxyListener. * * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void listfiles(Integer correlationID) throws SdlException { ListFiles msg = RPCRequestFactory.buildListFiles(correlationID); sendRPCRequest(msg); } /** * Used to set existing local file on SDL as the app's icon. Not supported on first generation SDL vehicles. * Responses are captured through callback on IProxyListener. * * @param sdlFileName -File reference name. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void setappicon(String sdlFileName, Integer correlationID) throws SdlException { SetAppIcon msg = RPCRequestFactory.buildSetAppIcon(sdlFileName, correlationID); sendRPCRequest(msg); } /** * Set an alternate display layout. If not sent, default screen for given platform will be shown. * Responses are captured through callback on IProxyListener. * * @param displayLayout -Predefined or dynamically created screen layout. * @param correlationID -A unique ID that correlates each RPCRequest and RPCResponse. * @throws SdlException if an unrecoverable error is encountered */ @SuppressWarnings("unused") public void setdisplaylayout(String displayLayout, Integer correlationID) throws SdlException { SetDisplayLayout msg = RPCRequestFactory.BuildSetDisplayLayout(displayLayout, correlationID); sendRPCRequest(msg); } @SuppressWarnings("unused") public boolean isCapabilitySupported(SystemCapabilityType systemCapabilityType) { return _systemCapabilityManager != null && _systemCapabilityManager.isCapabilitySupported(systemCapabilityType); } @SuppressWarnings("unused") public void getCapability(SystemCapabilityType systemCapabilityType, OnSystemCapabilityListener scListener){ if(_systemCapabilityManager != null){ _systemCapabilityManager.getCapability(systemCapabilityType, scListener); } } @SuppressWarnings("unused") public Object getCapability(SystemCapabilityType systemCapabilityType){ if(_systemCapabilityManager != null ){ return _systemCapabilityManager.getCapability(systemCapabilityType); }else{ return null; } } /** * Gets type of transport currently used by this SdlProxy. * * @return One of TransportType enumeration values. * * @see TransportType */ @SuppressWarnings("unused") public TransportType getCurrentTransportType() throws IllegalStateException { if (sdlSession == null) { throw new IllegalStateException("Incorrect state of SdlProxyBase: Calling for getCurrentTransportType() while connection is not initialized"); } return sdlSession.getCurrentTransportType(); } public void setSdlSecurityClassList(List<Class<? extends SdlSecurityBase>> list) { _secList = list; } private void setSdlSecurity(SdlSecurityBase sec) { if (sdlSession != null) { sdlSession.setSdlSecurity(sec); } } @SuppressWarnings("unused") public boolean isServiceTypeProtected(SessionType sType) { return sdlSession != null && sdlSession.isServiceProtected(sType); } public void addServiceListener(SessionType serviceType, ISdlServiceListener sdlServiceListener){ if(serviceType != null && sdlSession != null && sdlServiceListener != null){ sdlSession.addServiceListener(serviceType, sdlServiceListener); } } public void removeServiceListener(SessionType serviceType, ISdlServiceListener sdlServiceListener){ if(serviceType != null && sdlSession != null && sdlServiceListener != null){ sdlSession.removeServiceListener(serviceType, sdlServiceListener); } } @SuppressWarnings("unused") public VideoStreamingParameters getAcceptedVideoParams(){ return sdlSession.getAcceptedVideoParams(); } public IProxyListenerBase getProxyListener() { return _proxyListener; } @SuppressWarnings("unused") public String getAppName() { return _applicationName; } @SuppressWarnings("unused") public String getNgnAppName() { return _ngnMediaScreenAppName; } @SuppressWarnings("unused") public String getAppID() { return _appID; } @SuppressWarnings("unused") public DeviceInfo getDeviceInfo() { return deviceInfo; } @SuppressWarnings("unused") public long getInstanceDT() { return instanceDateTime; } @SuppressWarnings("unused") public void setConnectionDetails(String sDetails) { sConnectionDetails = sDetails; } @SuppressWarnings("unused") public String getConnectionDetails() { return sConnectionDetails; } //for testing only @SuppressWarnings("unused") public void setPoliciesURL(String sText) { sPoliciesURL = sText; } //for testing only public String getPoliciesURL() { return sPoliciesURL; } /** * VideoStreamingManager houses all the elements needed to create a scoped, streaming manager for video projection. It is only a private, instance * dependant class at the moment until it can become public. Once the class is public and API defined, it will be moved into the SdlSession class */ @TargetApi(19) private class VideoStreamingManager implements ISdlServiceListener{ Context context; ISdl internalInterface; volatile VirtualDisplayEncoder encoder; private Class<? extends SdlRemoteDisplay> remoteDisplayClass = null; SdlRemoteDisplay remoteDisplay; IVideoStreamListener streamListener; float[] touchScalar = {1.0f,1.0f}; //x, y private HapticInterfaceManager hapticManager; public VideoStreamingManager(Context context,ISdl iSdl){ this.context = context; this.internalInterface = iSdl; encoder = new VirtualDisplayEncoder(); internalInterface.addServiceListener(SessionType.NAV,this); //Take care of the touch events internalInterface.addOnRPCNotificationListener(FunctionID.ON_TOUCH_EVENT, new OnRPCNotificationListener() { @Override public void onNotified(RPCNotification notification) { if(notification !=null && remoteDisplay != null){ MotionEvent event = convertTouchEvent((OnTouchEvent)notification); if(event!=null){ remoteDisplay.handleMotionEvent(event); } } } }); } public void startVideoStreaming(Class<? extends SdlRemoteDisplay> remoteDisplayClass, VideoStreamingParameters parameters, boolean encrypted){ streamListener = startVideoStream(encrypted,parameters); if(streamListener == null){ Log.e(TAG, "Error starting video service"); return; } VideoStreamingCapability capability = (VideoStreamingCapability)_systemCapabilityManager.getCapability(SystemCapabilityType.VIDEO_STREAMING); if(capability != null && capability.getIsHapticSpatialDataSupported()){ hapticManager = new HapticInterfaceManager(internalInterface); } this.remoteDisplayClass = remoteDisplayClass; try { encoder.init(context,streamListener,parameters); //We are all set so we can start streaming at at this point encoder.start(); //Encoder should be up and running createRemoteDisplay(encoder.getVirtualDisplay()); } catch (Exception e) { e.printStackTrace(); } Log.d(TAG, parameters.toString()); } public void stopStreaming(){ if(remoteDisplay!=null){ remoteDisplay.stop(); remoteDisplay = null; } if(encoder!=null){ encoder.shutDown(); } if(internalInterface!=null){ internalInterface.stopVideoService(); } } public void dispose(){ stopStreaming(); internalInterface.removeServiceListener(SessionType.NAV,this); } private void createRemoteDisplay(final Display disp){ try{ if (disp == null){ return; } // Dismiss the current presentation if the display has changed. if (remoteDisplay != null && remoteDisplay.getDisplay() != disp) { remoteDisplay.dismissPresentation(); } FutureTask<Boolean> fTask = new FutureTask<Boolean>( new SdlRemoteDisplay.Creator(context, disp, remoteDisplay, remoteDisplayClass, new SdlRemoteDisplay.Callback(){ @Override public void onCreated(final SdlRemoteDisplay remoteDisplay) { //Remote display has been created. //Now is a good time to do parsing for spatial data VideoStreamingManager.this.remoteDisplay = remoteDisplay; if(hapticManager != null) { remoteDisplay.getMainView().post(new Runnable() { @Override public void run() { hapticManager.refreshHapticData(remoteDisplay.getMainView()); } }); } //Get touch scalars ImageResolution resolution = null; if(getWiProVersion()>=5){ //At this point we should already have the capability VideoStreamingCapability capability = (VideoStreamingCapability)_systemCapabilityManager.getCapability(SystemCapabilityType.VIDEO_STREAMING); resolution = capability.getPreferredResolution(); }else { DisplayCapabilities dispCap = (DisplayCapabilities) _systemCapabilityManager.getCapability(SystemCapabilityType.DISPLAY); if (dispCap != null) { resolution = (dispCap.getScreenParams().getImageResolution()); } } if(resolution != null){ DisplayMetrics displayMetrics = new DisplayMetrics(); disp.getMetrics(displayMetrics); touchScalar[0] = ((float)displayMetrics.widthPixels) / resolution.getResolutionWidth(); touchScalar[1] = ((float)displayMetrics.heightPixels) / resolution.getResolutionHeight(); } } @Override public void onInvalidated(final SdlRemoteDisplay remoteDisplay) { //Our view has been invalidated //A good time to refresh spatial data if(hapticManager != null) { remoteDisplay.getMainView().post(new Runnable() { @Override public void run() { hapticManager.refreshHapticData(remoteDisplay.getMainView()); } }); } } } )); Thread showPresentation = new Thread(fTask); showPresentation.start(); } catch (Exception ex) { Log.e(TAG, "Unable to create Virtual Display."); } } @Override public void onServiceStarted(SdlSession session, SessionType type, boolean isEncrypted) { } @Override public void onServiceEnded(SdlSession session, SessionType type) { if(SessionType.NAV.equals(type)){ if(remoteDisplay!=null){ stopStreaming(); } } } @Override public void onServiceError(SdlSession session, SessionType type, String reason) { } private MotionEvent convertTouchEvent(OnTouchEvent touchEvent){ List<TouchEvent> eventList = touchEvent.getEvent(); if (eventList == null || eventList.size() == 0) return null; TouchType touchType = touchEvent.getType(); if (touchType == null){ return null;} float x; float y; TouchEvent event = eventList.get(eventList.size() - 1); List<TouchCoord> coordList = event.getTouchCoordinates(); if (coordList == null || coordList.size() == 0){ return null;} TouchCoord coord = coordList.get(coordList.size() - 1); if (coord == null){ return null;} x = (coord.getX() * touchScalar[0]); y = (coord.getY() * touchScalar[1]); if (x == 0 && y == 0){ return null;} int eventAction = MotionEvent.ACTION_DOWN; long downTime = 0; if (touchType == TouchType.BEGIN) { downTime = SystemClock.uptimeMillis(); eventAction = MotionEvent.ACTION_DOWN; } long eventTime = SystemClock.uptimeMillis(); if (downTime == 0){ downTime = eventTime - 100;} if (touchType == TouchType.MOVE) { eventAction = MotionEvent.ACTION_MOVE; } if (touchType == TouchType.END) { eventAction = MotionEvent.ACTION_UP; } return MotionEvent.obtain(downTime, eventTime, eventAction, x, y, 0); } } } // end-class
package ch.openech.client; import java.awt.Color; import java.awt.event.ActionEvent; import java.util.List; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.Action; import ch.openech.client.ewk.event.PersonEventEditor; import ch.openech.client.preferences.OpenEchPreferences; import ch.openech.client.xmlpreview.XmlPreview; import ch.openech.mj.edit.Editor; import ch.openech.mj.edit.validation.Indicator; import ch.openech.mj.edit.validation.ValidationMessage; import ch.openech.mj.page.PageContext; import ch.openech.mj.page.PageContextHelper; import ch.openech.server.EchServer; import ch.openech.server.ServerCallResult; import ch.openech.xml.write.EchSchema; public abstract class XmlEditor<T> extends Editor<T> { public static final Logger logger = Logger.getLogger(PersonEventEditor.class.getName()); protected final EchSchema echSchema; protected final OpenEchPreferences preferences; private final XmlAction xmlAction; public XmlEditor(EchSchema echSchema, OpenEchPreferences preferences) { this.echSchema = echSchema; this.preferences = preferences; this.xmlAction = new XmlAction(); setIndicator(xmlAction); } protected int getFormColumns() { return 1; } public abstract List<String> getXml(T object) throws Exception; public void generateSedexOutput(T object) throws Exception { // to overwrite } @Override public Action[] getActions() { if (preferences.devMode()) { return new Action[]{demoAction(), xmlAction, cancelAction(), saveAction()}; } else { return new Action[]{cancelAction(), saveAction()}; } } @Override public boolean save(T object) throws Exception { List<String> xmls = getXml(object); send(xmls); return true; } public static boolean send(final List<String> xmls) { for (String xml : xmls) { if (!send(xml)) { return false; } } // TODO // if (SedexOutputGenerator.sedexOutputDirectoryAvailable()) { // try { // generateSedexOutput(); // } catch (Exception e) { // throw new RuntimeException("Fehler bei Sedex Meldung erstellen", e); return true; } public static boolean send(final String xml) { ServerCallResult result = EchServer.getInstance().process(xml); if (result.exception != null) { throw new RuntimeException("Speichern Fehlgeschlagen: " + result.exception.getMessage(), result.exception); } return true; } private class XmlAction extends AbstractAction implements Indicator { public XmlAction() { super("Vorschau XML"); } @Override public void actionPerformed(ActionEvent e) { try { List<String> xmls = getXml(getObject()); PageContext context = PageContextHelper.findContext(e.getSource()); XmlPreview.viewXml(context, xmls); } catch (Exception x) { throw new RuntimeException("XML Preview fehlgeschlagen", x); } } @Override public void setValidationMessages(List<ValidationMessage> validationMessages) { xmlAction.setEnabled(validationMessages.isEmpty()); updateXmlStatus(); } private void updateXmlStatus() { if (!isEnabled()) return; try { List<String> xmls = getXml(getObject()); boolean ok = true; String result = "ok"; for (String string : xmls) { result = EchServer.validate(string); if (!"ok".equals(result)) { ok = false; break; } } putValue("foreground", (ok ? Color.BLACK : Color.RED)); putValue(AbstractAction.SHORT_DESCRIPTION, result); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); putValue("foreground",Color.BLUE); putValue(AbstractAction.SHORT_DESCRIPTION, e1.getMessage()); } } } }
package net.hillsdon.svnwiki.vc; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.ListIterator; import java.util.Set; import org.tmatesoft.svn.core.SVNAuthenticationException; import org.tmatesoft.svn.core.SVNDirEntry; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNLogEntry; import org.tmatesoft.svn.core.SVNNodeKind; import org.tmatesoft.svn.core.SVNProperty; import org.tmatesoft.svn.core.io.ISVNEditor; import org.tmatesoft.svn.core.io.SVNRepository; import org.tmatesoft.svn.core.io.diff.SVNDeltaGenerator; import org.tmatesoft.svn.core.wc.SVNRevision; /** * Stores pages in an SVN repository. * * @author mth */ public class SVNPageStore implements PageStore { /** * The assumed encoding of files from the repository. */ private static final String UTF8 = "UTF8"; private final SVNRepository _repository; /** * Note the repository URL can be deep, it need not refer to * the root of the repository itself. We put pages in the root * of what we're given. */ public SVNPageStore(final SVNRepository repository) { _repository = repository; } @Override @SuppressWarnings("unchecked") public String[] recentChanges() throws PageStoreException { try { List<SVNLogEntry> entries = new ArrayList<SVNLogEntry>(); _repository.log(new String[] {""}, entries, 0, -1, true, true); Set<String> results = new LinkedHashSet<String>(entries.size()); String rootPath = _repository.getRepositoryPath(""); for (ListIterator<SVNLogEntry> iter = entries.listIterator(entries.size()); iter.hasPrevious();) { SVNLogEntry entry = iter.previous(); for (String path : (Collection<String>) entry.getChangedPaths().keySet()) { if (path.length() > rootPath.length()) { results.add(path.substring(rootPath.length() + 1)); } } } return results.toArray(new String[results.size()]); } catch (SVNException ex) { throw new PageStoreException(ex); } } @Override public String[] list() throws PageStoreException { try { List<SVNDirEntry> entries = new ArrayList<SVNDirEntry>(); _repository.getDir("", -1, false, entries); List<String> results = new ArrayList<String>(entries.size()); for (SVNDirEntry e : entries) { if (SVNNodeKind.FILE.equals(e.getKind())) { results.add(e.getName()); } } return results.toArray(new String[results.size()]); } catch (SVNException ex) { throw new PageStoreException(ex); } } public PageInfo get(final String path) throws PageStoreException { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); HashMap<String, String> properties = new HashMap<String, String>(); // We really want (kind, revision) back to avoid a race here... SVNNodeKind kind = _repository.checkPath(path, SVNRevision.HEAD.getNumber()); if (SVNNodeKind.FILE.equals(kind)) { _repository.getFile(path, SVNRevision.HEAD.getNumber(), properties, baos); long revision = Long.parseLong(properties.get(SVNProperty.REVISION)); return new PageInfo(path, toUTF8(baos.toByteArray()), revision); } else if (SVNNodeKind.NONE.equals(kind)) { return new PageInfo(path, "", PageInfo.UNCOMMITTED); } else { throw new PageStoreException(String.format("Unexpected node kind '%s' at '%s'", kind, path)); } } catch (SVNAuthenticationException ex) { throw new PageStoreAuthenticationException(ex); } catch (SVNException ex) { throw new PageStoreException(ex); } } public void set(final String path, final long baseRevision, final String content) throws PageStoreException { try { ISVNEditor commitEditor = _repository.getCommitEditor("[automated commit]", null); if (baseRevision == PageInfo.UNCOMMITTED) { createFile(commitEditor, path, fromUTF8(content)); } else { editFile(commitEditor, path, baseRevision, fromUTF8(content)); } commitEditor.closeEdit(); } catch (SVNAuthenticationException ex) { throw new PageStoreAuthenticationException(ex); } catch (SVNException ex) { if (SVNErrorCode.FS_CONFLICT.equals(ex.getErrorMessage().getErrorCode())) { // What to do! throw new InterveningCommitException(ex); } throw new PageStoreException(ex); } } private void createFile(ISVNEditor commitEditor, String filePath, byte[] data) throws SVNException { commitEditor.openRoot(-1); commitEditor.addFile(filePath, null, -1); commitEditor.applyTextDelta(filePath, null); SVNDeltaGenerator deltaGenerator = new SVNDeltaGenerator(); String checksum = deltaGenerator.sendDelta(filePath, new ByteArrayInputStream(data), commitEditor, true); commitEditor.closeFile(filePath, checksum); commitEditor.closeDir(); } private void editFile(final ISVNEditor commitEditor, final String filePath, final long baseRevision, final byte[] newData) throws SVNException { commitEditor.openRoot(-1); commitEditor.openFile(filePath, baseRevision); commitEditor.applyTextDelta(filePath, null); SVNDeltaGenerator deltaGenerator = new SVNDeltaGenerator(); // We don't keep the base around so we can't provide it here. String checksum = deltaGenerator.sendDelta(filePath, new ByteArrayInputStream(newData), commitEditor, true); commitEditor.closeFile(filePath, checksum); commitEditor.closeDir(); } private static String toUTF8(byte[] bytes) { try { return new String(bytes, UTF8); } catch (UnsupportedEncodingException e) { throw new AssertionError("Java supports UTF8."); } } private static byte[] fromUTF8(String string) { try { return string.getBytes(UTF8); } catch (UnsupportedEncodingException e) { throw new AssertionError("Java supports UTF8."); } } }
package com.greatmancode.legendarybot; import com.greatmancode.legendarybot.api.LegendaryBot; import com.greatmancode.legendarybot.api.commands.CommandHandler; import com.greatmancode.legendarybot.api.plugin.LegendaryBotPluginManager; import com.greatmancode.legendarybot.api.server.GuildSettings; import com.greatmancode.legendarybot.api.utils.StacktraceHandler; import com.greatmancode.legendarybot.commands.LoadCommand; import com.greatmancode.legendarybot.commands.ReloadPluginsCommand; import com.greatmancode.legendarybot.commands.UnloadCommand; import com.greatmancode.legendarybot.server.IGuildSettings; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import net.dv8tion.jda.core.AccountType; import net.dv8tion.jda.core.JDA; import net.dv8tion.jda.core.JDABuilder; import net.dv8tion.jda.core.entities.Guild; import net.dv8tion.jda.core.exceptions.RateLimitedException; import net.dv8tion.jda.core.utils.SimpleLog; import org.apache.commons.io.FileUtils; import org.apache.http.HttpHost; import org.elasticsearch.client.RestClient; import ro.fortsoft.pf4j.PluginManager; import ro.fortsoft.pf4j.PluginWrapper; import javax.security.auth.login.LoginException; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Properties; /** * Implementation of a {@link LegendaryBot} bot. */ public class ILegendaryBot extends LegendaryBot { /** * The Plugin Manager */ private PluginManager pluginManager = new LegendaryBotPluginManager(this); /** * The Command handler */ private CommandHandler commandHandler = new CommandHandler(this); /** * The instance of JDA being linked to this Bot. */ private JDA jda; /** * The settings of every guilds that this bot is connected to */ private Map<String, GuildSettings> guildSettings = new HashMap<>(); /** * The Database data source */ private HikariDataSource dataSource; /** * Bot-related statistics handler */ //TODO: Move it into the BotGeneral plugin private StatsHandler statsHandler; /** * The instance of the Stacktrace Handler. */ private IStacktraceHandler stacktraceHandler; private RestClient restClient; /** * The app.properties file. */ private static Properties props; /** * Start all the feature of the LegendaryBot * @param jda the JDA instance * @param sentryKey The key for Sentry.io * @param battlenetKey The Battle.Net API key. */ //TODO: Remove sentryKey parameter public ILegendaryBot(JDA jda, String sentryKey, String battlenetKey) { super(battlenetKey); this.jda = jda; this.stacktraceHandler = new IStacktraceHandler(sentryKey); //Load the database HikariConfig config = new HikariConfig(); config.setDataSourceClassName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource"); config.addDataSourceProperty("serverName", System.getenv("MYSQL_ADDRESS") != null ? System.getenv("MYSQL_ADDRESS") : props.getProperty("mysql.address")); config.addDataSourceProperty("port", System.getenv("MYSQL_PORT") != null ? System.getenv("MYSQL_PORT") : props.getProperty("mysql.port")); config.addDataSourceProperty("databaseName", System.getenv("MYSQL_DATABASE") != null ? System.getenv("MYSQL_DATABASE") : props.getProperty("mysql.database")); config.addDataSourceProperty("user", System.getenv("MYSQL_USER") != null ? System.getenv("MYSQL_USER") : props.getProperty("mysql.user")); config.addDataSourceProperty("password", System.getenv("MYSQL_PASSWORD") != null ? System.getenv("MYSQL_PASSWORD") : props.getProperty("mysql.password")); config.setConnectionTimeout(5000); dataSource = new HikariDataSource(config); //We configure our Stacktrace catchers Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(stacktraceHandler)); SimpleLog.getLog("JDA").addListener(new LogListener(stacktraceHandler)); //Register the server specific commands commandHandler.addCommand("reloadplugins", new ReloadPluginsCommand(this)); commandHandler.addCommand("load", new LoadCommand(this)); commandHandler.addCommand("unload", new UnloadCommand(this)); //We register the message listener jda.addEventListener(new MessageListener(this)); //We create the Config table String SERVER_CONFIG_TABLE = "CREATE TABLE IF NOT EXISTS `guild_config` (\n" + " `guildId` VARCHAR(64) NOT NULL,\n" + " `configName` VARCHAR(255) NOT NULL,\n" + " `configValue` MEDIUMTEXT NOT NULL,\n" + " PRIMARY KEY (`guildId`, `configName`));\n"; try { Connection conn = getDatabase().getConnection(); PreparedStatement statement = conn.prepareStatement(SERVER_CONFIG_TABLE); statement.executeUpdate(); statement.close(); } catch (SQLException e) { e.printStackTrace(); } //Load the settings for each guild jda.getGuilds().forEach(guild -> guildSettings.put(guild.getId(), new IGuildSettings(guild, this))); //We load all plugins pluginManager.loadPlugins(); pluginManager.startPlugins(); if (Boolean.parseBoolean(props.getProperty("stats.enable"))) { statsHandler = new StatsHandler(props, jda); } Runtime.getRuntime().addShutdownHook(new Thread(() -> { for (PluginWrapper wrapper : getPluginManager().getPlugins()) { getPluginManager().unloadPlugin(wrapper.getPluginId()); } jda.shutdown(); File plugins = new File("plugins"); Arrays.stream(plugins.listFiles(File::isDirectory)).forEach(file -> { try { FileUtils.deleteDirectory(file); } catch (IOException e) { e.printStackTrace(); } }); if (statsHandler != null) { statsHandler.stop(); } try { restClient.close(); } catch (IOException e) { e.printStackTrace(); } System.out.println("Legendarybot shutdown."); })); } /** * Launch the Bot * @param args Command line arguments (unused) * @throws IOException * @throws LoginException * @throws InterruptedException * @throws RateLimitedException */ public static void main(String[] args) throws IOException, LoginException, InterruptedException, RateLimitedException { //Load the configuration props = new Properties(); props.load(new FileInputStream("app.properties")); //Connect the bot to Discord JDA jda = new JDABuilder(AccountType.BOT).setToken(System.getenv("BOT_TOKEN") != null ? System.getenv("BOT_TOKEN") : props.getProperty("bot.token")).buildBlocking(); //We launch the bot new ILegendaryBot(jda, props.getProperty("sentry.key"), props.getProperty("battlenet.key")); } @Override public CommandHandler getCommandHandler() { return commandHandler; } @Override public GuildSettings getGuildSettings(Guild guild) { return guildSettings.get(guild.getId()); } @Override public PluginManager getPluginManager() { return pluginManager; } @Override public HikariDataSource getDatabase() { return dataSource; } @Override public void addGuild(Guild guild) { guildSettings.put(guild.getId(), new IGuildSettings(guild, this)); } @Override public StacktraceHandler getStacktraceHandler() { return stacktraceHandler; } @Override public RestClient getElasticSearch() { if (restClient == null) { restClient = RestClient.builder( new HttpHost(props.getProperty("elasticsearch.address"), Integer.parseInt(props.getProperty("elasticsearch.port")), props.getProperty("elasticsearch.scheme"))).build(); } return restClient; } @Override public JDA getJDA() { return jda; } }
package gov.nih.nlm.ncbi.seqr; import org.apache.solr.common.SolrDocument; import java.io.IOException; import java.io.Writer; import java.util.List; import java.util.StringJoiner; import java.lang.*; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; public class Output { public static final int PAIRWISE = 0; public static final int QUERY_ANCHORED_SHOWING_IDENTITIES = 1; public static final int QUERY_ANCHORED_NO_IDENTITIES = 2; public static final int FLAT_QUERY_ANCHORED_SHOW_IDENTITIES = 3; public static final int FLAT_QUERY_ANCHORED_NO_IDENTITIES = 4; public static final int XML_BLAST_OUTPUT = 5; public static final int TABULAR = 6; public static final int TABULAR_WITH_COMMENT_LINES = 7; public static final int TEXT_ASN_1 = 8; public static final int BINARY_ASN_1 = 9; public static final int COMMA_SEPARATED_VALUES = 10; public static final int BLAST_ARCHIVE_FORMAT_ASN_1 = 11; public static final int JSON_SEQALIGN_OUTPUT = 12; public static final int JSON_BLAST_OUTPUT = 13; public static final int XML2_BLAST_OUTPUT = 14; public static final int SAM_BLAST_OUTPUT = 15; private static final String NEW_LINE = System.getProperty("line.separator"); private static final String COMMA_DELIMITER = ","; private static final String COMMA_SPACE_DELIMITER = ", "; private static final String TAB_DELIMITER = "\t"; private Writer writer; private int style = COMMA_SEPARATED_VALUES; private List<String> fields; private boolean wroteHeader = false; public void setStyle (int style) { this.style = style; } public int getStyle () { return style; } public void setFields(List<String> fields) { this.fields = fields; } public List<String> getFields() { return fields; } private void checkFields(SolrDocument sd) { if(fields == null) { setFields((List<String>) sd.getFieldNames()); } } private void writeOut(String out) throws IOException { writer.write(out); } private void writeCsv(SolrDocument sd) throws IOException { checkFields(sd); StringJoiner joiner = new StringJoiner(COMMA_DELIMITER); for(String field : getFields()) { joiner.add(sd.getFieldValue(field).toString()); } writeOut(joiner.toString()); writeOut(NEW_LINE); } private void writeTab(SolrDocument sd) throws IOException { checkFields(sd); StringJoiner joiner = new StringJoiner(TAB_DELIMITER); for(String field : getFields()) { joiner.add(sd.getFieldValue(field).toString()); } writeOut(joiner.toString()); writeOut(NEW_LINE); } private void writeJson(SolrDocument sd) throws IOException { checkFields(sd); JSONObject obj = new JSONObject(); for(String field : getFields()) { obj.put(field, sd.getFieldValue(field).toString()); } writeOut(obj.toJSONString()); } private void writeXml(SolrDocument sd) throws ParserConfigurationException, TransformerException { checkFields(sd); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("seqr"); doc.appendChild(rootElement); for(String field : getFields()) { Element fieldElement = doc.createElement(field); fieldElement.appendChild(doc.createTextNode(sd.getFieldValue(field).toString())); rootElement.appendChild(fieldElement); } TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(writer); transformer.transform(source, result); } public void writeHeader(SolrDocument sd) throws IOException { checkFields(sd); String versionSeqr = "1.0"; String versionSolr = "4.10.4"; String queryName = "gi|584277003|ref|NP_001276862.1| ZO-2 associated speckle protein [Homo sapiens]"; String databaseName = "refseq_protein.00"; int hits = 6; writeHeader(versionSeqr, versionSolr, queryName, databaseName, getFields(), hits); } public void writeHeader(String versionSeqr, String versionSolr, String queryName, String databaseName, List<String> fields, int hits) throws IOException { if(wroteHeader) { return; } setFields(fields); StringJoiner joiner = new StringJoiner(COMMA_SPACE_DELIMITER); for(String s : getFields()) { joiner.add(s); } String fieldNames = joiner.toString(); writeOut("# SEQR " + versionSeqr + NEW_LINE + "# SOLR " + versionSolr + NEW_LINE + "# Query: " + queryName + NEW_LINE + "# Database: " + databaseName + NEW_LINE + "# Fields: " + fieldNames + NEW_LINE + "# " + Integer.toString(hits) + " hits found" + NEW_LINE); wroteHeader = !wroteHeader; } public void write (SolrDocument sd) throws IOException, ParserConfigurationException, TransformerException { switch (getStyle()) { case PAIRWISE: throw new UnsupportedOperationException("Pairwise is unimplemented"); case QUERY_ANCHORED_SHOWING_IDENTITIES: throw new UnsupportedOperationException("Query anchored showing identities is unimplemented"); case QUERY_ANCHORED_NO_IDENTITIES: throw new UnsupportedOperationException("Query anchored, no identities is unimplemented"); case FLAT_QUERY_ANCHORED_SHOW_IDENTITIES: throw new UnsupportedOperationException("Flat query anchored showing identities is unimplemented"); case FLAT_QUERY_ANCHORED_NO_IDENTITIES: throw new UnsupportedOperationException("Flat query anchored, no identities is unimplemented"); case XML_BLAST_OUTPUT: writeXml(sd); break; case TABULAR: writeTab(sd); break; case TABULAR_WITH_COMMENT_LINES: writeHeader(sd); writeTab(sd); break; case TEXT_ASN_1: throw new UnsupportedOperationException("Text ASN.1 is unimplemented"); case BINARY_ASN_1: throw new UnsupportedOperationException("Binary ASN.1 is unimplemented"); case COMMA_SEPARATED_VALUES: writeCsv(sd); break; case BLAST_ARCHIVE_FORMAT_ASN_1: throw new UnsupportedOperationException("Blast archive format ASN.1 is unimplemented"); case JSON_SEQALIGN_OUTPUT: writeJson(sd); break; case JSON_BLAST_OUTPUT: writeJson(sd); break; case XML2_BLAST_OUTPUT: writeXml(sd); break; case SAM_BLAST_OUTPUT: throw new UnsupportedOperationException("SAM output is unimplemented"); default: writeCsv(sd); break; } } public Output(Writer writer, int style, List<String> fields) { this.writer = writer; this.style = style; this.fields = fields; } public Output(Writer writer, List<String> fields) { this.writer = writer; this.fields = fields; } public Output(Writer writer, int style) { this.writer = writer; this.style = style; } public Output(Writer writer) { this.writer = writer; } }
package io.spine.server.entity; import io.spine.server.entity.model.EntityClass; import java.util.Objects; import static io.spine.server.entity.model.EntityClass.asEntityClass; /** * Default factory that creates entities by invoking constructor that * accepts a single ID parameter. * * @param <I> the type of entity identifiers * @param <E> the type of entities to create */ final class DefaultEntityFactory<I, E extends AbstractEntity<I, ?>> implements EntityFactory<I, E> { private static final long serialVersionUID = 0L; private final EntityClass<E> entityClass; DefaultEntityFactory(Class<E> entityClass) { this.entityClass = asEntityClass(entityClass); } @Override public E create(I id) { return entityClass.createEntity(id); } @Override public int hashCode() { return Objects.hash(entityClass); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof DefaultEntityFactory)) { return false; } DefaultEntityFactory other = (DefaultEntityFactory) obj; return Objects.equals(this.entityClass, other.entityClass); } }
package cz.net21.ttulka.thistledb.server; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.net.SocketException; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.IntStream; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import static junit.framework.TestCase.fail; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.startsWith; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsNull.nullValue; public class ServerTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); @Test public void startServerTest() throws Exception { Server server = new Server(temp.newFolder().toPath()); assertThat("Server shouldn't listen before been started.", server.listening(), is(false)); server.startAndWait(500); assertThat("Server should listen after been started.", server.listening(), is(true)); server.stopAndWait(500); assertThat("Server shouldn't listen after been stopped.", server.listening(), is(false)); } @Test public void basicTest() throws Exception { try (Server server = new Server(temp.newFolder().toPath())) { server.startAndWait(5000); try (Socket socket = new Socket("localhost", Server.DEFAULT_PORT); PrintWriter out = new PrintWriter(socket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) { socket.setSoTimeout(1000); out.println("SELECT name FROM dual"); assertThat("First connection should be accepted.", in.readLine(), is("ACCEPTED")); assertThat("First result shouldn't be null.", in.readLine(), is("{\"name\":\"DUAL\"}")); assertThat("First connection should be finished.", in.readLine(), is("FINISHED")); } } } @Test public void moreQueriesTest() throws Exception { try (Server server = new Server(temp.newFolder().toPath())) { server.startAndWait(5000); try (Socket socket = new Socket("localhost", Server.DEFAULT_PORT); PrintWriter out = new PrintWriter(socket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) { socket.setSoTimeout(1000); out.println("SELECT name FROM dual"); assertThat("First connection should be accepted.", in.readLine(), is("ACCEPTED")); assertThat("First result shouldn't be null.", in.readLine(), is("{\"name\":\"DUAL\"}")); assertThat("First connection should be finished.", in.readLine(), is("FINISHED")); out.println("SELECT name FROM dual"); assertThat("Second connection should be accepted.", in.readLine(), startsWith("ACCEPTED")); assertThat("Second result shouldn't be null.", in.readLine(), is("{\"name\":\"DUAL\"}")); assertThat("Second connection should be finished.", in.readLine(), is("FINISHED")); Thread.sleep(1000); out.println("SELECT name FROM dual"); assertThat("Second connection should be accepted.", in.readLine(), startsWith("ACCEPTED")); assertThat("Second result shouldn't be null.", in.readLine(), is("{\"name\":\"DUAL\"}")); assertThat("Second connection should be finished.", in.readLine(), is("FINISHED")); } } } @Test(expected = SocketException.class) public void checkConnectionPoolMaxConnectionsTest() throws Exception { try (Server server = new Server(temp.newFolder().toPath())) { server.startAndWait(500); server.setMaxClientConnections(2); // only two connections in time are accepted try (Socket socket1 = new Socket("localhost", Server.DEFAULT_PORT); PrintWriter out1 = new PrintWriter(socket1.getOutputStream(), true); BufferedReader in1 = new BufferedReader(new InputStreamReader(socket1.getInputStream()))) { socket1.setSoTimeout(1000); try (Socket socket2 = new Socket("localhost", Server.DEFAULT_PORT); PrintWriter out2 = new PrintWriter(socket2.getOutputStream(), true); BufferedReader in2 = new BufferedReader(new InputStreamReader(socket2.getInputStream()))) { socket2.setSoTimeout(1000); try (Socket socket3 = new Socket("localhost", Server.DEFAULT_PORT); PrintWriter out3 = new PrintWriter(socket3.getOutputStream(), true); BufferedReader in3 = new BufferedReader(new InputStreamReader(socket3.getInputStream()))) { socket3.setSoTimeout(1000); // okay out1.println("SELECT 1 FROM dual"); assertThat("First connection should be accepted.", in1.readLine(), is("ACCEPTED")); assertThat("First result shouldn't be null.", in1.readLine(), is("{\"value\":1}")); assertThat("First connection should be finished.", in1.readLine(), is("FINISHED")); // okay out2.println("SELECT 2 FROM dual"); assertThat("Second connection should be accepted.", in2.readLine(), is("ACCEPTED")); assertThat("Second result shouldn't be null.", in2.readLine(), is("{\"value\":2}")); assertThat("Second connection should be finished.", in2.readLine(), is("FINISHED")); // refused out3.println("SELECT 3 FROM dual"); assertThat("Third connection should be refused.", in3.readLine(), startsWith("REFUSED")); assertThat("Third result should be null.", in3.readLine(), nullValue()); out3.println("SELECT 4 FROM dual"); fail("After the connection was refused any attempt to query the server will fail."); } } } } } @Test public void checkConnectionPoolMaxConnectionsAfterPreviousConnectionsWereClosedTest() throws Exception { try (Server server = new Server(temp.newFolder().toPath())) { server.startAndWait(500); server.setMaxClientConnections(1); // only one connection in time is accepted try (Socket socket = new Socket("localhost", Server.DEFAULT_PORT); PrintWriter out = new PrintWriter(socket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) { socket.setSoTimeout(1000); out.println("SELECT name FROM dual"); assertThat("First connection should be accepted.", in.readLine(), is("ACCEPTED")); assertThat("First result shouldn't be null.", in.readLine(), is("{\"name\":\"DUAL\"}")); assertThat("First connection should be finished.", in.readLine(), is("FINISHED")); } Thread.sleep(500); try (Socket socket = new Socket("localhost", Server.DEFAULT_PORT); PrintWriter out = new PrintWriter(socket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) { socket.setSoTimeout(1000); out.println("SELECT name FROM dual"); assertThat("Second connection should be accepted.", in.readLine(), startsWith("ACCEPTED")); assertThat("Second result shouldn't be null.", in.readLine(), is("{\"name\":\"DUAL\"}")); assertThat("Second connection should be finished.", in.readLine(), is("FINISHED")); } } } @Test public void multipleConcurrentConnectionsTest() throws Exception { int numberOfClients = 100; try (Server server = new Server(temp.newFolder().toPath())) { server.startAndWait(500); server.setMaxClientConnections(numberOfClients); AtomicInteger sucessConnections = new AtomicInteger(); List<String> errors = new CopyOnWriteArrayList<>(); IntStream.range(0, numberOfClients).forEach(i -> new Thread(() -> { try (Socket socket = new Socket("localhost", Server.DEFAULT_PORT); PrintWriter out = new PrintWriter(socket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) { socket.setSoTimeout(1000); out.println("SELECT " + i + " FROM dual"); Thread.sleep(100); assertThat("First connection should be accepted.", in.readLine(), is("ACCEPTED")); Thread.sleep(100); assertThat("First result shouldn't be null.", in.readLine(), is("{\"value\":" + i + "}")); Thread.sleep(100); assertThat("First connection should be finished.", in.readLine(), is("FINISHED")); sucessConnections.incrementAndGet(); } catch (Exception e) { e.printStackTrace(); errors.add("Client connection " + i + " failed: " + e.getMessage()); } }).start() ); Thread.sleep(numberOfClients + 3000); errors.forEach(error -> fail(error)); assertThat("Count of successful connections must be " + numberOfClients + ".", sucessConnections.get(), is(numberOfClients)); } } }
package org.spine3.server; import com.google.protobuf.Message; import io.grpc.stub.StreamObserver; import org.junit.Test; import org.spine3.base.Queries; import org.spine3.base.Response; import org.spine3.client.Subscription; import org.spine3.client.SubscriptionUpdate; import org.spine3.client.Target; import org.spine3.client.Topic; import org.spine3.protobuf.AnyPacker; import org.spine3.server.stand.Stand; import org.spine3.test.aggregate.Project; import org.spine3.test.aggregate.ProjectId; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.spine3.test.Verify.assertSize; import static org.spine3.testdata.TestBoundedContextFactory.newBoundedContext; /** * @author Dmytro Dashenkov */ public class SubscriptionServiceShould { @Test public void initialize_properly_with_one_bounded_context() { final BoundedContext singleBoundedContext = newBoundedContext("Single", newSimpleStand()); final SubscriptionService.Builder builder = SubscriptionService.newBuilder() .addBoundedContext(singleBoundedContext); final SubscriptionService subscriptionService = builder.build(); assertNotNull(subscriptionService); final List<BoundedContext> boundedContexs = builder.getBoundedContexts(); assertSize(1, boundedContexs); assertTrue(boundedContexs.contains(singleBoundedContext)); } @Test public void initialize_properly_with_several_bounded_contexts() { final BoundedContext firstBoundedContext = newBoundedContext("First", newSimpleStand()); final BoundedContext secondBoundedContext = newBoundedContext("Second", newSimpleStand()); final BoundedContext thirdBoundedContext = newBoundedContext("Third", newSimpleStand()); final SubscriptionService.Builder builder = SubscriptionService.newBuilder() .addBoundedContext(firstBoundedContext) .addBoundedContext(secondBoundedContext) .addBoundedContext(thirdBoundedContext); final SubscriptionService service = builder.build(); assertNotNull(service); final List<BoundedContext> boundedContexts = builder.getBoundedContexts(); assertSize(3, boundedContexts); assertTrue(boundedContexts.contains(firstBoundedContext)); assertTrue(boundedContexts.contains(secondBoundedContext)); assertTrue(boundedContexts.contains(thirdBoundedContext)); } @Test public void be_able_to_remove_bounded_context_from_builder() { final BoundedContext firstBoundedContext = newBoundedContext("Removed", newSimpleStand()); final BoundedContext secondBoundedContext = newBoundedContext("Also removed", newSimpleStand()); final BoundedContext thirdBoundedContext = newBoundedContext("The one to stay", newSimpleStand()); final SubscriptionService.Builder builder = SubscriptionService.newBuilder() .addBoundedContext(firstBoundedContext) .addBoundedContext(secondBoundedContext) .addBoundedContext(thirdBoundedContext) .removeBoundedContext(secondBoundedContext) .removeBoundedContext(firstBoundedContext); final SubscriptionService subscriptionService = builder.build(); assertNotNull(subscriptionService); final List<BoundedContext> boundedContexts = builder.getBoundedContexts(); assertSize(1, boundedContexts); assertFalse(boundedContexts.contains(firstBoundedContext)); assertFalse(boundedContexts.contains(secondBoundedContext)); assertTrue(boundedContexts.contains(thirdBoundedContext)); } @Test(expected = IllegalStateException.class) public void fail_to_initialize_from_empty_builder() { SubscriptionService.newBuilder() .build(); } @Test public void subscribe_to_topic() { final BoundedContext boundedContext = setupBoundedContextForAggregateRepo(); final SubscriptionService subscriptionService = SubscriptionService.newBuilder() .addBoundedContext(boundedContext) .build(); final String type = boundedContext.getStand() .getExposedTypes() .iterator() .next() .getTypeName(); final Target target = getProjectQueryTarget(); assertEquals(type, target.getType()); final Topic topic = Topic.newBuilder() .setTarget(target) .build(); final MemoizeStreamObserver<Subscription> observer = new MemoizeStreamObserver<>(); subscriptionService.subscribe(topic, observer); assertNotNull(observer.streamFlowValue); assertTrue(observer.streamFlowValue.isInitialized()); assertEquals(observer.streamFlowValue.getType(), type); assertNull(observer.throwable); assertTrue(observer.isCompleted); } @Test public void activate_subscription() { final BoundedContext boundedContext = setupBoundedContextForAggregateRepo(); final SubscriptionService subscriptionService = SubscriptionService.newBuilder() .addBoundedContext(boundedContext) .build(); final Target target = getProjectQueryTarget(); final Topic topic = Topic.newBuilder() .setTarget(target) .build(); // Subscribe on the topic final MemoizeStreamObserver<Subscription> subscriptionObserver = new MemoizeStreamObserver<>(); subscriptionService.subscribe(topic, subscriptionObserver); subscriptionObserver.verifyState(); // Activate subscription final MemoizeStreamObserver<SubscriptionUpdate> activationObserver = new MemoizeStreamObserver<>(); subscriptionService.activate(subscriptionObserver.streamFlowValue, activationObserver); // Post update to Stand directly final ProjectId projectId = ProjectId.newBuilder() .setId("some-id") .build(); final Message projectState = Project.newBuilder() .setId(projectId) .build(); boundedContext.getStand() .update(projectId, AnyPacker.pack(projectState)); // isCompleted set to false since we don't expect activationObserver::onCompleted to be called. activationObserver.verifyState(false); } @Test public void cancel_subscription_on_topic() { final BoundedContext boundedContext = setupBoundedContextForAggregateRepo(); final SubscriptionService subscriptionService = SubscriptionService.newBuilder() .addBoundedContext(boundedContext) .build(); final Target target = getProjectQueryTarget(); final Topic topic = Topic.newBuilder() .setTarget(target) .build(); // Subscribe final MemoizeStreamObserver<Subscription> subscribeObserver = new MemoizeStreamObserver<>(); subscriptionService.subscribe(topic, subscribeObserver); // Activate subscription final MemoizeStreamObserver<SubscriptionUpdate> activateSubscription = spy(new MemoizeStreamObserver<SubscriptionUpdate>()); subscriptionService.activate(subscribeObserver.streamFlowValue, activateSubscription); // Cancel subscription subscriptionService.cancel(subscribeObserver.streamFlowValue, new MemoizeStreamObserver<Response>()); // Post update to Stand final ProjectId projectId = ProjectId.newBuilder() .setId("some-other-id") .build(); final Message projectState = Project.newBuilder() .setId(projectId) .build(); boundedContext.getStand() .update(projectId, AnyPacker.pack(projectState)); // The update must not be handled by the observer verify(activateSubscription, never()).onNext(any(SubscriptionUpdate.class)); verify(activateSubscription, never()).onCompleted(); } private static BoundedContext setupBoundedContextForAggregateRepo() { final Stand stand = Stand.newBuilder() .build(); final BoundedContext boundedContext = newBoundedContext(stand); stand.registerTypeSupplier(new Given.ProjectAggregateRepository(boundedContext)); return boundedContext; } private static Target getProjectQueryTarget() { return Queries.Targets.allOf(Project.class); } private static Stand newSimpleStand() { return Stand.newBuilder() .build(); } private static class MemoizeStreamObserver<T> implements StreamObserver<T> { private T streamFlowValue; private Throwable throwable; private boolean isCompleted; @Override public void onNext(T value) { this.streamFlowValue = value; } @Override public void onError(Throwable t) { this.throwable = t; } @Override public void onCompleted() { this.isCompleted = true; } private void verifyState() { verifyState(true); } private void verifyState(boolean isCompleted) { assertNotNull(streamFlowValue); assertNull(throwable); assertEquals(this.isCompleted, isCompleted); } } }
package com.commercetools.util; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.junit.Test; import java.io.IOException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; import static com.commercetools.util.HttpRequestUtil.*; import static java.lang.String.format; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; public class HttpRequestUtilTest { // try to make 200 simultaneous requests in 200 threads private final int nThreads = CONNECTION_MAX_TOTAL; private final int requests = CONNECTION_MAX_TOTAL; @Test public void executeGetRequest_shouldBeParalleled() throws Exception { makeParallelRequests(nThreads, requests, () -> { try { final HttpResponse httpResponse = executeGetRequest("http://httpbin.org/get"); assertThat(httpResponse.getStatusLine().getStatusCode()).isEqualTo(HttpStatus.SC_OK); return 1; } catch (IOException e) { throw new RuntimeException("Request exception", e); } }); } @Test public void executePostRequest_shouldBeParalleled() throws Exception { makeParallelRequests(nThreads, requests, () -> { try { final HttpResponse httpResponse = executePostRequest("http://httpbin.org/post", asList( nameValue("xxx", "yyy"), nameValue("zzz", 11223344))); assertThat(httpResponse.getStatusLine().getStatusCode()).isEqualTo(HttpStatus.SC_OK); assertThat(responseToString(httpResponse)).contains("xxx", "yyy", "zzz", "11223344"); return 1; } catch (IOException e) { throw new RuntimeException("Request exception", e); } }); } @Test public void executeGetRequestToString_returnsString() throws Exception { assertThat(executeGetRequestToString("http: } @Test public void executePostRequestToString_returnsStringContainingRequestArguments() throws Exception { assertThat(executePostRequestToString("http://httpbin.org/post", asList( nameValue("aaa", "bbb"), nameValue("ccc", 89456677823452345L)))) .contains("http://httpbin.org/post", "aaa", "bbb", "ccc", "89456677823452345"); } private void makeParallelRequests(final int nThreads, final int requests, final Supplier<Integer> request) throws Exception { final ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(nThreads); final AtomicInteger counter = new AtomicInteger(0); for (int i = 0; i < requests; i++) { newFixedThreadPool.execute(() -> counter.addAndGet(request.get())); } newFixedThreadPool.shutdown(); // length of the longest pipe in the multi thread pipeline, // literally it is an maximum integer number of sequential requests in one pipe (thread) final int criticalPathLength = (int) Math.ceil((double) requests / nThreads); // longest expected time of one successful request (even if retried), // which may have +RETRY_TIMES attempts additionally to the first (failed) attempt final int longestRequestTimeMsec = REQUEST_TIMEOUT * (1 + RETRY_TIMES); // await not more than (longestRequestTimeMsec * criticalPathLength) msec with // coefficient 1.5 is added to avoid test fails on some lags and threads switching timeouts. final long maxCriticalPathDurationMsec = (int) (1.5 * longestRequestTimeMsec * criticalPathLength); boolean interrupted = newFixedThreadPool.awaitTermination(maxCriticalPathDurationMsec, TimeUnit.MILLISECONDS); assertThat(interrupted) .withFailMessage(format("The execution thread pool was not able to shutdown in time %s msec", maxCriticalPathDurationMsec)) .isTrue(); assertThat(counter.get()).isEqualTo(requests); } }
package net.mchs_u.mc.aiwolf.nlp.blade; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.aiwolf.client.lib.Content; import org.aiwolf.client.lib.Topic; import org.aiwolf.common.data.Agent; import org.aiwolf.common.data.Role; import org.aiwolf.common.data.Species; import org.aiwolf.common.data.Talk; import org.aiwolf.common.net.GameInfo; import net.mchs_u.mc.aiwolf.common.AgentTargetResult; import net.mchs_u.mc.aiwolf.dokin.Estimate; import net.mchs_u.mc.aiwolf.dokin.McrePlayer; import net.mchs_u.mc.aiwolf.nlp.common.Transrater; public class Mouth { private static final double EPS = 0.00001d; private Set<String> talkedSet = null; private McrePlayer player = null; private Map<String, String> characterMap = null; private boolean firstVoted = false; private Agent targetOfVotingDeclarationToday = null; public Mouth(McrePlayer player) { this.player = player; } public void initialize(GameInfo gameInfo) { talkedSet = new HashSet<>(); characterMap = Character.getCharacterMap(gameInfo.getAgent().getAgentIdx()); firstVoted = false; } public void dayStart() { targetOfVotingDeclarationToday = null; } public String toNaturalLanguageForTalk(GameInfo gameInfo, String protocol, Collection<String> answers) { if(!Content.validate(protocol)) { System.err.println("Mouth: -> " + protocol); return Talk.SKIP; } Content content = new Content(protocol); if(gameInfo.getDay() == 0) { if(!talkedSet.contains("0")){ talkedSet.add("0"); return r("<>"); } return Talk.OVER; } Agent t = content.getTarget(); switch (content.getTopic()) { case OVER: return Talk.OVER; case SKIP: return skipTalk(gameInfo, answers); case COMINGOUT: if(!content.getTarget().equals(gameInfo.getAgent())) return Talk.SKIP; if(content.getRole() == Role.WEREWOLF) { if(getEstimate().isPowerPlay()) return r("<><>"); else return r("<><><><>"); } if(content.getRole() == Role.POSSESSED) { return r("<><>"); } return r("<>" + Transrater.roleToString(content.getRole()) + "<>"); case DIVINED: String r = Transrater.speciesToString(content.getResult()); t = content.getTarget(); switch ((int)(Math.random() * 5)) { case 0: return r(t + "<>" + r + "<>"); case 1: return r(t + "<>" + r + "<>"); case 2: return r(t + "<>" + r + "<>"); case 3: return r(t + "<>" + r + "<>"); case 4: return r("<>" + t + "<>" + r + "<>"); } case IDENTIFIED: return r(content.getTarget() + "<>" + Transrater.speciesToString(content.getResult()) + "<>"); case OPERATOR: Content c = content.getContentList().get(0); if(c.getTopic() != Topic.VOTE) return Talk.SKIP; return r(c.getTarget() + "<><>"); case VOTE: if(getEstimate().isPowerPlay()) { if((gameInfo.getRole() == Role.WEREWOLF || gameInfo.getRole() == Role.POSSESSED)) return r(t + "<><>"); else return Talk.SKIP; } if(firstVoted) { Agent bak = targetOfVotingDeclarationToday; targetOfVotingDeclarationToday = t; if(bak == null || bak == t) { switch ((int)(Math.random() * 2)) { case 0: return r(t + "<><>"); case 1: return r(t + "<><>"); } } else { switch ((int)(Math.random() * 2)) { case 0: return r("" + t + "<><>"); case 1: return r("" + t + "<><>"); } } } firstVoted = true; default: return Talk.SKIP; } } private static String agentsToTalk(GameInfo gameInfo, Collection<Agent> agents, char conj) { String ret = ""; for(Agent agent: agents) ret += agent.toString() + "<>" + conj; return ret.substring(0, ret.length() - 1).replace(gameInfo.getAgent() + "<>", "<>"); } private static String resultsToTalk(GameInfo gameInfo, Collection<AgentTargetResult> results, Set<Agent> seers) { String ret = ""; for(AgentTargetResult r: results) { if(!seers.contains(r.getAgent())) continue; ret += r.getAgent() + "<>" + r.getTarget() + "<>"; if(r.getResult() == Species.WEREWOLF) ret += ""; else ret += ""; } if(ret.length() > 1) return ret.substring(0, ret.length() - 1).replace(gameInfo.getAgent() + "<>", "<>"); return null; } private String makeStatusTalk(GameInfo gameInfo) { String s = ""; Set<Agent> seers = getEstimate().getCoSet(Role.SEER); List<AgentTargetResult> divs = getEstimate().getDivinedHistory(); List<Agent> attackeds = getEstimate().getAttackedAgents(); if(seers.contains(gameInfo.getAgent())) s += "<>"; seers.remove(gameInfo.getAgent()); if(!seers.isEmpty()) s += agentsToTalk(gameInfo, seers, '') + ""; if(!divs.isEmpty()) { String d = resultsToTalk(gameInfo, divs, seers); if(d != null) s += resultsToTalk(gameInfo, divs, seers) + ""; } if(!attackeds.isEmpty()) s += agentsToTalk(gameInfo, attackeds, '') + ""; if(s.length() < 1) return null; if(s.charAt(s.length() - 2) == '') return s.substring(0, s.length() - 2) + ""; return s.substring(0, s.length() - 2) + ""; } private static List<Agent> max(Collection<Agent> candidate, Map<Agent, Double> likeness) { List<Agent> ret = new ArrayList<>(); if(likeness == null) return ret; double max = Collections.max(likeness.values()); for(Agent agent: candidate) if(Math.abs(max - likeness.get(agent)) < EPS) ret.add(agent); return ret; } private static Map<Agent, Double> toPossessedLikeness(Map<Agent, Double> werewolfLikeness, Map<Agent, Double> villagerTeamLikeness) { Map<Agent, Double> ret = new HashMap<>(); for(Agent agent: werewolfLikeness.keySet()) ret.put(agent, 1d - werewolfLikeness.get(agent) - villagerTeamLikeness.get(agent)); return ret; } private String skipTalk(GameInfo gameInfo, Collection<String> answers) { if(getEstimate().isPowerPlay()) { if(!talkedSet.contains("")){ talkedSet.add(""); if(gameInfo.getRole() == Role.WEREWOLF) { return r("<>"); } else if(gameInfo.getRole() == Role.POSSESSED) { return ""; } else { return ""; } } return Talk.SKIP; } if(gameInfo.getLastDeadAgentList().size() > 0 && gameInfo.getDay() == 2) { if(!talkedSet.contains("")){ talkedSet.add(""); switch ((int)(Math.random() * 5)) { case 0: return ""; case 1: return r(gameInfo.getLastDeadAgentList().get(0) + "<><>"); } } } if(getEstimate().getCoMap().get(gameInfo.getAgent()) == Role.SEER) { if(getEstimate().getCoSet(Role.SEER).size() == 2) { if(!talkedSet.contains("")){ talkedSet.add(""); Set<Agent> coSeers = getEstimate().getCoSet(Role.SEER); coSeers.remove(gameInfo.getAgent()); Agent t = (Agent)coSeers.toArray()[0]; switch ((int)(Math.random() * 6)) { case 0: return r(t + "<><><><>"); case 1: return r(t + "<><><><>"); case 2: return r(">>" + t + " " + t + "<><><>"); case 3: return r(">>" + t + " " + t + "<><><>"); } } } } else { if(getEstimate().getCoSet(Role.SEER).size() == 2) { if(!talkedSet.contains("")){ talkedSet.add(""); switch ((int)(Math.random() * 5)) { case 0: return ""; } } } } for(String answer: answers) { //EarAnswer if(!talkedSet.contains("answer:" + answer)){ talkedSet.add("answer:" + answer); Agent voteTarget = player.getVoteTarget(); if(voteTarget != null) { if(answer.startsWith(">>" + voteTarget + " ")) return r(answer.replace(" else return r(answer.replace("#", voteTarget.toString())); } } } List<Agent> candidate = gameInfo.getAgentList(); candidate.remove(gameInfo.getAgent()); String st = makeStatusTalk(gameInfo); if(!talkedSet.contains("" + gameInfo.getDay()) && st != null){ switch ((int)(Math.random() * 10)) { case 0: List<Agent> wolves = max(candidate, getEstimate().getWerewolfLikeness()); if(!wolves.isEmpty() && wolves.size() <= 2) { talkedSet.add("" + gameInfo.getDay()); return r(st + agentsToTalk(gameInfo, wolves, '') + "<>"); } break; case 1: Estimate es = getEstimate(); List<Agent> possesseds = max(candidate, toPossessedLikeness(es.getWerewolfLikeness(), es.getVillagerTeamLikeness())); if(!possesseds.isEmpty() && possesseds.size() <= 2) { talkedSet.add("" + gameInfo.getDay()); return r(st + agentsToTalk(gameInfo, possesseds, '') + "<>"); } break; } } return Talk.SKIP; } private String r(String s) { // replace String ret = s; for(String key: characterMap.keySet()) ret = ret.replace("<" + key + ">", characterMap.get(key)); return ret; } public String toNaturalLanguageForWhisper(GameInfo gameInfo, String protocol) { if(!Content.validate(protocol)) { System.err.println("Mouth: -> " + protocol); return Talk.SKIP; } Content content = new Content(protocol); switch (content.getTopic()) { case OVER: return Talk.OVER; case SKIP: return Talk.SKIP; case COMINGOUT: if(content.getTarget().equals(gameInfo.getAgent()) && content.getRole() == Role.VILLAGER) return r("<><>"); return Talk.SKIP; case ATTACK: return r(content.getTarget() + "<>"); default: return Talk.SKIP; } } private Estimate getEstimate() { return (Estimate)player.getPretendVillagerEstimate(); } }
package nu.validator.io; /** * @version $Id$ * @author hsivonen */ public class StreamBoundException extends SystemIdIOException { public StreamBoundException() { super(); } /** * @param message */ public StreamBoundException(String message) { super(null, message); } public StreamBoundException(String message, String systemId) { super(systemId, message); } }
package opendap.coreServlet; import opendap.bes.dap4Responders.MediaType; import opendap.http.mediaTypes.*; import opendap.io.HyraxStringEncoding; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; import org.owasp.encoder.Encode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URLDecoder; import java.util.concurrent.ConcurrentHashMap; /** * Wraps the Exception class so that it can be serialized as a DAP2 error object. * Includes methods for assigning DAP2 Error codes to the error. * <p/> * * @author ndp */ public class OPeNDAPException extends Exception { Logger _log; public static final String ERROR_RESPONSE_MEDIA_TYPE_KEY = "ErrorResponseMediaType"; private static ConcurrentHashMap<Thread, String> _errorMessageCache; static { _errorMessageCache = new ConcurrentHashMap<>(); } /** * Undefined error. */ public static final int UNDEFINED_ERROR = -1; /** * The error message. * * @serial */ private String _errorMessage; private int _httpStatusCode; private MediaType _responseMediaType; public void setResponseMediaType(MediaType mt){ _responseMediaType = mt; } public MediaType getResponseMediaType(){ return _responseMediaType; } protected String _systemPath; public void setSystemPath(String sysPath){ _systemPath = sysPath; } /** * Construct an empty <code>OPeNDAPException</code>. */ protected OPeNDAPException() { // this should never be seen, since this class overrides getMessage() // to display its own error message. super("OPeNDAPException"); _responseMediaType = new TextPlain(); _httpStatusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; _systemPath=null; _log = LoggerFactory.getLogger(this.getClass()); } /** * Construct a <code>OPeNDAPException</code>. * @param msg A message describing the error. * @param cause The cause (which is saved for later retrieval by the * Throwable.getCause() method). (A null value is permitted, and indicates * that the cause is nonexistent or unknown.) */ public OPeNDAPException(int httpStatus, String msg, Throwable cause) { super(msg, cause); _responseMediaType = new TextPlain(); _httpStatusCode = httpStatus; _errorMessage = msg; _systemPath=null; _log = LoggerFactory.getLogger(this.getClass()); } /** * Construct a <code>OPeNDAPException</code>. * @param cause The cause (which is saved for later retrieval by the * Throwable.getCause() method). (A null value is permitted, and indicates * that the cause is nonexistent or unknown.) */ public OPeNDAPException(int httpStatus,Throwable cause) { super(cause); _responseMediaType = new TextPlain(); _httpStatusCode = httpStatus; _errorMessage = cause.getMessage(); _systemPath=null; _log = LoggerFactory.getLogger(this.getClass()); } /** * Construct a <code>OPeNDAPException</code> with the given message. * * @param code the error core * @param msg the error message */ public OPeNDAPException(int code, String msg) { super(msg); _responseMediaType = new TextPlain(); _httpStatusCode = code; _errorMessage = msg; _systemPath=null; _log = LoggerFactory.getLogger(this.getClass()); } /** * Returns the detail message of this throwable object. * * @return the detail message of this throwable object. */ public String getMessage() { return _errorMessage; } /** * Sets the error message. * * @param msg the error message. */ public final void setErrorMessage(String msg) { _errorMessage = msg; } public static int anyExceptionHandler(Throwable t, HttpServlet servlet, HttpServletResponse response) { Logger log = org.slf4j.LoggerFactory.getLogger(OPeNDAPException.class); try { log.error("anyExceptionHandler(): " + t); ByteArrayOutputStream baos =new ByteArrayOutputStream(); PrintStream ps = new PrintStream( baos, true, HyraxStringEncoding.getCharset().name()); t.printStackTrace(ps); log.debug(baos.toString(HyraxStringEncoding.getCharset().name())); OPeNDAPException oe; if (t instanceof OPeNDAPException) oe = (OPeNDAPException) t; else { String msg = t.getClass().getName()+": "; msg += t.getMessage(); msg += " [" + t.getStackTrace()[0].getFileName() + " - line " + t.getStackTrace()[0].getLineNumber() + "]"; msg = msg.replace('\"', '\''); oe = new OPeNDAPException(UNDEFINED_ERROR, msg); oe.setHttpStatusCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } if(!response.isCommitted()){ response.reset(); oe.setSystemPath(ServletUtil.getSystemPath(servlet,"")); try { oe.sendHttpErrorResponse(response); } catch(IOException ioe){ log.error("Failed to transmit http error response to " + "requesting client. Caught {} Message: {}", ioe.getClass().getName(),ioe.getMessage()); } } else { try { oe.sendAsDap2Error(response); } catch(IOException ioe){ log.error("Failed to transmit DAP2 error object to " + "requesting client. Caught {} Message: {}", ioe.getClass().getName(),ioe.getMessage()); } } return oe.getHttpStatusCode(); } catch (Throwable moreT) { log.error("The Bad Things have happened! A new {} was thrown while " + "processing a prior exception. message: {}" , moreT.getClass().getName(), moreT.getMessage()); } return -1; } public void sendHttpErrorResponse(HttpServletResponse response) throws Exception { MediaType errorResponseMediaType = (MediaType) RequestCache.get(ERROR_RESPONSE_MEDIA_TYPE_KEY); if(errorResponseMediaType==null) errorResponseMediaType = new TextHtml(); if(errorResponseMediaType.getPrimaryType().equalsIgnoreCase("text")) { if (errorResponseMediaType.getSubType().equalsIgnoreCase(TextHtml.SUB_TYPE)) { sendAsHtmlErrorPage(response); return; } if (errorResponseMediaType.getSubType().equalsIgnoreCase(TextPlain.SUB_TYPE)) { sendAsDap2Error(response); return; } if (errorResponseMediaType.getSubType().equalsIgnoreCase(TextXml.SUB_TYPE)) { sendAsDap4Error(response); return; } if (errorResponseMediaType.getSubType().equalsIgnoreCase(TextCsv.SUB_TYPE)) { sendAsCsvError(response); return; } } if(errorResponseMediaType.getPrimaryType().equalsIgnoreCase("application")) { if (errorResponseMediaType.getSubType().equalsIgnoreCase(Json.SUB_TYPE)) { sendAsJsonError(response); return; } if (errorResponseMediaType.getSubType().equalsIgnoreCase(DMR.SUB_TYPE)) { sendAsDap4Error(response); return; } if (errorResponseMediaType.getSubType().equalsIgnoreCase(Dap4Data.SUB_TYPE)) { sendAsDap4Error(response); return; } if (errorResponseMediaType.getSubType().equalsIgnoreCase(Dap2Data.SUB_TYPE)) { sendAsDap2Error(response); return; } if (errorResponseMediaType.getSubType().equalsIgnoreCase(RDF.SUB_TYPE)) { sendAsDap4Error(response); return; } } sendAsHtmlErrorPage(response); } public void setHttpStatusCode(int code){ //@TODO Make this thing look at the code and QC it's HTTP codyness. _httpStatusCode = code; } /** * * @return The HTTP status code associated with the error. */ public int getHttpStatusCode(){ return _httpStatusCode; } /** * Transmits a DAP2 encoding of the error object. * Error { * code = 1005; * message = "libdap error transmitting DDS: Constraint expression parse error: No such identifier in dataset: foo"; * }; * * * @param response The response object to load up with the error response. * @throws IOException */ public void sendAsDap2Error(HttpServletResponse response) throws IOException { _log.debug("sendAsDap2Error(): Sending DAP2 Error Object."); MediaType mt = new TextPlain(); response.setContentType(mt.getMimeType()); response.setHeader("Content-Description", "DAP2 Error Object"); response.setStatus(getHttpStatusCode()); ServletOutputStream sos = response.getOutputStream(); sos.println("Error { "); sos.print(" code = "); sos.print(getHttpStatusCode()); sos.println(";"); sos.print(" message = \""); sos.print(getMessage()); sos.println("\";"); sos.println("}"); sos.flush(); } /** * Transmits a DAP4 encoding of the error object. * * @param response The response object to load up with the error response. * @throws IOException */ public void sendAsDap4Error(HttpServletResponse response) throws IOException{ opendap.dap4.Dap4Error d4e = new opendap.dap4.Dap4Error(); d4e.setHttpStatusCode(getHttpStatusCode()); d4e.setMessage(Encode.forXmlContent(getMessage())); response.setContentType(d4e.getMediaType().getMimeType()); response.setHeader("Content-Description", "DAP4 Error Object"); response.setStatus(getHttpStatusCode()); ServletOutputStream sos = response.getOutputStream(); XMLOutputter xmlo = new XMLOutputter(Format.getPrettyFormat()); xmlo.output(d4e.getErrorDocument(),sos); sos.flush(); } /** * Transmits a CSV encoding of a DAP error object. * * @param response The response object to load up with the error response. * @throws IOException */ public void sendAsCsvError(HttpServletResponse response) throws IOException { TextCsv csvMediaType = new TextCsv(); response.setContentType(csvMediaType.getMimeType()); response.setHeader("Content-Description", "Error Object"); response.setStatus(getHttpStatusCode()); ServletOutputStream sos = response.getOutputStream(); sos.println("Dataset: ERROR"); sos.println("status, " + getHttpStatusCode()); sos.println("message, \""+getMessage()+"\""); } /** * { * "name": "ERROR", * "type": "String", * "data": "Message" * } * * @param response The response object to load up with the error response. * @throws IOException */ public void sendAsJsonError(HttpServletResponse response) throws IOException { _log.debug("sendAsJsonError(): Sending JSON Error Object."); Json jsonMediaType = new Json(); response.setContentType(jsonMediaType.getMimeType()); // response.setContentType("text/plain"); response.setHeader("Content-Description", "Error Object"); response.setStatus(getHttpStatusCode()); ServletOutputStream sos = response.getOutputStream(); sos.println("{"); sos.println(" \"name\": = \"ERROR\","); sos.println(" \"type\": = \"node\","); sos.println(" \"attributes\": = \"[]\","); sos.println(" \"leaves\": = [\""); sos.println(" {"); sos.println(" \"name\": = \"Message\","); sos.println(" \"type\": = \"String\","); sos.println(" \"attributes\": = \"[]\","); sos.print(" \"data\": = \""); sos.print(Encode.forJavaScriptBlock(getMessage())); sos.println("\""); sos.println(" },"); sos.println(" \"name\": = \"HttpStatus\","); sos.println(" \"type\": = \"Int32\","); sos.println(" \"attributes\": = \"[]\","); sos.print(" \"data\": = "); sos.print(getHttpStatusCode()); sos.println(""); sos.println(" }"); sos.println("}"); sos.flush(); } /** * * @param response The response object to load up with the error response. * @throws Exception */ public void sendAsHtmlErrorPage(HttpServletResponse response) throws Exception { int httpStatus = getHttpStatusCode(); // Because the error messages are utilized by the associated JSP page they must be made available // for the JSP to retrieve. The RequestCache for this thread gets destroyed when the doGet/doPost // methods exit which is normal and expected behavior, but the JSP page is invoked afterward so we // need a rendezvous for the message. We utilize this errorMessage cache for this purpose. The only // public method for retrieving the message is tied to the thread of execution and it removes the // message from the cache (clears the cache for the thread) once it is retrieved. _errorMessageCache.put(Thread.currentThread(), getMessage()); // Invokes the appropriate JSP page. response.sendError(httpStatus); } /** * * @return The error message cached by the current thread. This message is * not encoded for inclusion in a particular message type (such as HTML) * encoding is left to the receiver. */ public static String getAndClearCachedErrorMessage(){ return _errorMessageCache.remove(Thread.currentThread()); } /** * Adds the passed string to the error message cache for the current thread. * @param errMsg The error message. */ public static void setCachedErrorMessage(String errMsg){ _errorMessageCache.put(Thread.currentThread(),errMsg); } /** * Builds the mailto link to be utilized in various form , error, and directory pages * @param request * @param http_status * @param errorMessage * @param adminEmail * @return The support mailto link, encoded forHtmlAttribute */ public static String getSupportMailtoLink(HttpServletRequest request, int http_status, String errorMessage, String adminEmail) throws UnsupportedEncodingException { StringBuilder sb = new StringBuilder(); if(http_status!=200){ sb.append("mailto:").append(adminEmail).append("?subject=Hyrax Error ").append(http_status); } else { sb.append("mailto:").append(adminEmail).append("?subject=Hyrax Usage Question"); } sb.append("&body="); sb.append("%0A"); sb.append("%0A"); sb.append("%0A"); sb.append("%0A"); sb.append("%0A"); sb.append(" sb.append(" sb.append("# We're sorry you had a problem using the server.%0A"); sb.append("# Please use the space above to describe what you%0A"); sb.append("# were trying to do and we will try to assist you.%0A"); sb.append("# Thanks,%0A"); sb.append("# OPeNDAP Support.%0A"); sb.append(" if(http_status !=200) { sb.append("# -- -- -- hyrax error info, please include -- -- --%0A"); } else { sb.append("# -- -- -- hyrax location info, please include -- -- --%0A"); } sb.append(" sb.append("# request_url: "); sb.append(request.getRequestURL().toString()).append("%0A"); sb.append("# protocol: ").append(request.getProtocol()).append("%0A"); sb.append("# server: ").append(request.getServerName()).append("%0A"); sb.append("# port: ").append(request.getServerPort()).append("%0A"); String cleanUri = (String) request.getAttribute("javax.servlet.forward.request_uri"); if(cleanUri!=null){ cleanUri = URLDecoder.decode(cleanUri, HyraxStringEncoding.getCharset().name()); cleanUri = Scrub.urlContent(cleanUri); } else { cleanUri = "null"; } sb.append("# javax.servlet.forward.request_uri: "); sb.append(cleanUri); sb.append("%0A"); sb.append("# query_string: "); String queryString = request.getQueryString(); if(queryString!=null && !queryString.isEmpty()){ sb.append(Scrub.simpleQueryString(queryString)).append("%0A"); } else { sb.append("n/a%0A"); } sb.append("# status: ").append(http_status).append("%0A"); if(http_status !=200) { sb.append("# message: "); if(errorMessage!=null) sb.append(errorMessage).append("%0A"); else sb.append("no_error_message_found").append("%0A"); } sb.append(" sb.append(" return Encode.forHtmlAttribute(sb.toString()); } }
package orbitSimulator; import java.awt.Font; import java.awt.List; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.sql.Array; import java.util.ArrayList; import java.util.EventObject; import java.util.HashMap; import java.util.Map; import javax.swing.JLabel; import javax.swing.JPanel; import net.miginfocom.swing.MigLayout; import javax.swing.BorderFactory; import javax.swing.JOptionPane; import javax.swing.JTextField; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.border.BevelBorder; import javax.swing.border.Border; import javax.swing.border.CompoundBorder; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.Document; import java.awt.Color; import javax.swing.border.EmptyBorder; import javax.swing.JCheckBox; public class EllipticalOrbitInputs extends JPanel implements ActionListener { // input text fields - NB need to add each new tf to getUserInputs() and a private parameter below private JTextField tfArgOfPeri; private JTextField tfPeriapsis; private static JTextField tfApoapsis; private JTextField tfSemimajorAxis; private JTextField tfEccentricity; private JTextField tfPeriod; private JTextField tfRAAN; private JTextField tfSME; private JTextField tfRadiusForVelocity; private JTextField tfVelocityAtRadius; private JTextField tfVelocityAtApoapsis; private JTextField tfVelocityAtPeriapsis; private JTextField tfInclination; private Double ArgOfPeri = null; private Double Periapsis = null; private Double Apoapsis = null; private Double SemimajorAxis = null; private Double Eccentricity = null; private Double OrbitalPeriod = null; private Double RAAN = null; private Double Period = null; private Double SME = null; private Double RadiusForVelocity = null; private Double VelocityAtRadius = null; private Double VelocityAtApoapsis = null; private Double VelocityAtPeriapsis = null; private Double Inclination = null; private boolean ArgOfPeriAdded; private boolean PeriapsisAdded; private boolean ApoapsisAdded; private boolean SemimajorAxisAdded; private boolean EccentricityAdded; private boolean OrbitalPeriodAdded; private boolean RAANAdded; private boolean PeriodAdded; private boolean SMEAdded; private boolean VelocityAtRadiusAdded; private boolean RadiusForVelocityAdded; private boolean VelocityAtApoapsisAdded; private boolean VelocityAtPeriapsisAdded; private boolean InclinationAdded; private double mu; private double pi = Math.PI; private JButton btnCalculateEllipticalOrbit; private MainFrameListenerElliptical newGraphicsListener; private DocumentListener tfListener; private JLabel lblEllipticalInputWarning; JCheckBox chckbxNewVelocityAtRadius; Color defaultBackground = Color.WHITE; Color warningBackground = Color.decode("#FF9A9A"); private JLabel lblUnitsApoPeriRadius; private JLabel lblUnitsSemimajorAxis; private JLabel lblUnitDegrees; private JLabel lblUnitDegree1; private JLabel lblUnitHr; private JLabel lblUnitVelocutyAtRadiusKm; private JLabel lblUnitVelocityAtRadius1; private JLabel lblUnitSME; private JLabel lblub; private JLabel lblKm; private JLabel lblKm_1; EllipticalOrbitInputs() { setBorder(new EmptyBorder(0, 0, 0, 0)); setLayout(new MigLayout("", "[22.00][18.00][29.00][74.00,grow][60.00][37.00,grow][79.00][44.00]", "[][][][12.00][][14.00][][center][][][][][][]")); JLabel lblEllipticalOrbitInputs = new JLabel("Elliptical Orbit Inputs"); lblEllipticalOrbitInputs.setFont(new Font("Lucida Grande", Font.BOLD, 13)); add(lblEllipticalOrbitInputs, "cell 0 0 4 1"); lblEllipticalInputWarning = new JLabel("numbers only (3.4, +3.4, -3.4)"); lblEllipticalInputWarning.setForeground(Color.decode("#FF9A9A")); lblEllipticalInputWarning.setVisible(false); add(lblEllipticalInputWarning, "cell 4 0 4 1"); JLabel lblArgumentOfPeriapsis = new JLabel("Arg of Periapsis"); lblArgumentOfPeriapsis.setFont(new Font("Lucida Grande", Font.PLAIN, 11)); add(lblArgumentOfPeriapsis, "cell 1 1 2 1"); tfArgOfPeri = new JTextField(); tfArgOfPeri.setBackground(Color.WHITE); tfArgOfPeri.setFont(new Font("Lucida Grande", Font.PLAIN, 11)); add(tfArgOfPeri, "cell 3 1,growx"); tfArgOfPeri.setColumns(10); lblub = new JLabel("\u00B0"); add(lblub, "cell 4 1"); JLabel lblRadius = new JLabel("Radius"); lblRadius.setFont(new Font("Lucida Grande", Font.PLAIN, 11)); add(lblRadius, "cell 1 2 2 1"); JLabel lblPeriapsis = new JLabel("Periapsis"); lblPeriapsis.setFont(new Font("Lucida Grande", Font.PLAIN, 11)); add(lblPeriapsis, "cell 2 3,alignx left"); tfPeriapsis = new JTextField(); tfPeriapsis.setFont(new Font("Lucida Grande", Font.PLAIN, 11)); add(tfPeriapsis, "cell 3 3,growx"); tfPeriapsis.setColumns(10); lblKm_1 = new JLabel("Km "); lblKm_1.setFont(new Font("Lucida Grande", Font.PLAIN, 11)); add(lblKm_1, "cell 4 3"); JLabel lblApoapsis = new JLabel("Apoapsis"); lblApoapsis.setFont(new Font("Lucida Grande", Font.PLAIN, 11)); add(lblApoapsis, "cell 5 3,alignx right"); tfApoapsis = new JTextField(); tfApoapsis.setFont(new Font("Lucida Grande", Font.PLAIN, 11)); add(tfApoapsis, "cell 6 3,growx"); tfApoapsis.setColumns(10); tfApoapsis.getDocument().putProperty("owner", tfApoapsis); tfApoapsis.setName("apoapsis"); lblUnitsApoPeriRadius = new JLabel("Km"); lblUnitsApoPeriRadius.setFont(new Font("Lucida Grande", Font.PLAIN, 11)); add(lblUnitsApoPeriRadius, "cell 7 3"); JLabel lblSemimajorAxis = new JLabel("Semimajor Axis"); lblSemimajorAxis.setFont(new Font("Lucida Grande", Font.PLAIN, 11)); add(lblSemimajorAxis, "cell 1 4 2 1"); tfSemimajorAxis = new JTextField(); tfSemimajorAxis.setFont(new Font("Lucida Grande", Font.PLAIN, 11)); add(tfSemimajorAxis, "cell 3 4,growx"); tfSemimajorAxis.setColumns(10); lblUnitsSemimajorAxis = new JLabel("Km"); lblUnitsSemimajorAxis.setFont(new Font("Lucida Grande", Font.PLAIN, 11)); add(lblUnitsSemimajorAxis, "cell 4 4"); JLabel lblEccentricity = new JLabel("Eccentricity"); lblEccentricity.setFont(new Font("Lucida Grande", Font.PLAIN, 11)); add(lblEccentricity, "cell 1 5 2 1"); tfEccentricity = new JTextField(); tfEccentricity.setFont(new Font("Lucida Grande", Font.PLAIN, 11)); add(tfEccentricity, "cell 3 5,growx"); tfEccentricity.setColumns(10); JLabel lblInclination = new JLabel("Inclination"); lblInclination.setFont(new Font("Lucida Grande", Font.PLAIN, 11)); add(lblInclination, "cell 1 6 2 1,alignx left"); tfInclination = new JTextField(); tfInclination.setFont(new Font("Lucida Grande", Font.PLAIN, 11)); add(tfInclination, "cell 3 6,growx,aligny top"); tfInclination.setColumns(10); lblUnitDegrees = new JLabel(" \u00B0"); lblUnitDegrees.setFont(new Font("Lucida Grande", Font.PLAIN, 11)); add(lblUnitDegrees, "cell 4 6"); JLabel lblVelecity = new JLabel("Velocity at:"); lblVelecity.setFont(new Font("Lucida Grande", Font.PLAIN, 11)); add(lblVelecity, "flowx,cell 1 7 2 1,alignx left"); final JLabel lblUnitRadiusForVelocity = new JLabel("Radius ="); lblUnitRadiusForVelocity.setForeground(Color.LIGHT_GRAY); lblUnitRadiusForVelocity.setFont(new Font("Lucida Grande", Font.PLAIN, 11)); add(lblUnitRadiusForVelocity, "cell 3 7,alignx right"); tfRadiusForVelocity = new JTextField(); tfRadiusForVelocity.setEditable(false); tfRadiusForVelocity.setFont(new Font("Lucida Grande", Font.PLAIN, 11)); add(tfRadiusForVelocity, "cell 4 7,growx"); tfRadiusForVelocity.setColumns(10); final JLabel lblUnitkmAndArrow = new JLabel("Km \u21D2"); lblUnitkmAndArrow.setForeground(Color.LIGHT_GRAY); lblUnitkmAndArrow.setFont(new Font("Lucida Grande", Font.PLAIN, 11)); add(lblUnitkmAndArrow, "flowx,cell 5 7"); tfVelocityAtRadius = new JTextField(); tfVelocityAtRadius.setEditable(false); tfVelocityAtRadius.setFont(new Font("Lucida Grande", Font.PLAIN, 11)); add(tfVelocityAtRadius, "cell 6 7"); tfVelocityAtRadius.setColumns(10); tfVelocityAtRadius.getDocument().putProperty("owner", tfVelocityAtRadius); tfVelocityAtRadius.setName("velocityatradius"); lblUnitVelocityAtRadius1 = new JLabel("Km/s"); lblUnitVelocityAtRadius1.setForeground(Color.LIGHT_GRAY); lblUnitVelocityAtRadius1.setFont(new Font("Lucida Grande", Font.PLAIN, 11)); add(lblUnitVelocityAtRadius1, "cell 7 7"); JLabel lblVelocityAtRP = new JLabel("Periapsis"); lblVelocityAtRP.setFont(new Font("Lucida Grande", Font.PLAIN, 11)); add(lblVelocityAtRP, "cell 2 8,alignx trailing"); tfVelocityAtPeriapsis = new JTextField(); tfVelocityAtPeriapsis.setFont(new Font("Lucida Grande", Font.PLAIN, 11)); add(tfVelocityAtPeriapsis, "cell 3 8,growx"); tfVelocityAtPeriapsis.setColumns(10); lblKm = new JLabel("Km/s"); lblKm.setFont(new Font("Lucida Grande", Font.PLAIN, 11)); add(lblKm, "cell 4 8"); JLabel lblVelocityAtApoapsis = new JLabel("Apoapsis"); lblVelocityAtApoapsis.setFont(new Font("Lucida Grande", Font.PLAIN, 11)); add(lblVelocityAtApoapsis, "cell 5 8,alignx trailing"); tfVelocityAtApoapsis = new JTextField(); tfVelocityAtApoapsis.setFont(new Font("Lucida Grande", Font.PLAIN, 11)); add(tfVelocityAtApoapsis, "cell 6 8,growx"); tfVelocityAtApoapsis.setColumns(10); tfVelocityAtApoapsis.getDocument().putProperty("owner", tfVelocityAtApoapsis); tfVelocityAtApoapsis.setName("velocityatapoapsis"); lblUnitVelocutyAtRadiusKm = new JLabel("Km/s"); lblUnitVelocutyAtRadiusKm.setFont(new Font("Lucida Grande", Font.PLAIN, 11)); add(lblUnitVelocutyAtRadiusKm, "cell 7 8"); JLabel lblSME = new JLabel("SME"); lblSME.setFont(new Font("Lucida Grande", Font.PLAIN, 11)); add(lblSME, "cell 1 9 2 1"); tfSME = new JTextField(); tfSME.setFont(new Font("Lucida Grande", Font.PLAIN, 11)); add(tfSME, "cell 3 9,growx"); tfSME.setColumns(10); lblUnitSME = new JLabel("KmKg/s"); lblUnitSME.setFont(new Font("Lucida Grande", Font.PLAIN, 11)); add(lblUnitSME, "cell 4 9"); JLabel lblRaan = new JLabel("RAAN"); lblRaan.setFont(new Font("Lucida Grande", Font.PLAIN, 11)); add(lblRaan, "cell 1 10 2 1"); tfRAAN = new JTextField(); tfRAAN.setFont(new Font("Lucida Grande", Font.PLAIN, 11)); add(tfRAAN, "cell 3 10,growx"); tfRAAN.setColumns(10); lblUnitDegree1 = new JLabel(" \u00B0"); lblUnitDegree1.setFont(new Font("Lucida Grande", Font.PLAIN, 11)); add(lblUnitDegree1, "cell 4 10"); tfPeriod = new JTextField(); tfPeriod.setFont(new Font("Lucida Grande", Font.PLAIN, 11)); add(tfPeriod, "cell 3 11,growx"); tfPeriod.setColumns(10); // Listen for changes to textFields tfArgOfPeri.getDocument().putProperty("owner", tfArgOfPeri); tfArgOfPeri.setName("argofperi"); tfPeriapsis.getDocument().putProperty("owner", tfPeriapsis); tfPeriapsis.setName("periapsis"); tfSemimajorAxis.getDocument().putProperty("owner", tfSemimajorAxis); tfSemimajorAxis.setName("semimajoraxis"); tfEccentricity.getDocument().putProperty("owner", tfEccentricity); tfEccentricity.setName("eccentricity"); tfInclination.getDocument().putProperty("owner", tfInclination); tfInclination.setName("inclination"); tfSME.getDocument().putProperty("owner", tfSME); tfSME.setName("sme"); tfRAAN.getDocument().putProperty("owner", tfRAAN); tfRAAN.setName("raan"); tfPeriod.getDocument().putProperty("owner", tfPeriod); tfPeriod.setName("period"); tfRadiusForVelocity.getDocument().putProperty("owner", tfRadiusForVelocity); tfRadiusForVelocity.setName("radiusforvelocity"); tfVelocityAtPeriapsis.getDocument().putProperty("owner", tfVelocityAtPeriapsis); tfVelocityAtPeriapsis.setName("velocityatperiapsis"); btnCalculateEllipticalOrbit = new JButton("Calculate Orbit"); btnCalculateEllipticalOrbit.addActionListener(this); lblUnitHr = new JLabel("hr"); lblUnitHr.setFont(new Font("Lucida Grande", Font.PLAIN, 11)); add(lblUnitHr, "cell 4 11"); add(btnCalculateEllipticalOrbit, "cell 4 12 4 2"); JLabel lblOrbitalPeriod = new JLabel("Orbital Period"); lblOrbitalPeriod.setFont(new Font("Lucida Grande", Font.PLAIN, 11)); add(lblOrbitalPeriod, "cell 1 11 2 1,alignx left"); chckbxNewVelocityAtRadius = new JCheckBox(""); chckbxNewVelocityAtRadius.setFont(new Font("Lucida Grande", Font.PLAIN, 11)); add(chckbxNewVelocityAtRadius, "cell 2 7,alignx right"); chckbxNewVelocityAtRadius.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { tfRadiusForVelocity.setEditable(true); tfVelocityAtRadius.setEditable(true); lblUnitRadiusForVelocity.setForeground(Color.BLACK); lblUnitkmAndArrow.setForeground(Color.BLACK); lblUnitVelocityAtRadius1.setForeground(Color.BLACK); } else if (e.getStateChange() == ItemEvent.DESELECTED) { tfRadiusForVelocity.setEditable(false); tfVelocityAtRadius.setEditable(false); lblUnitRadiusForVelocity.setForeground(Color.LIGHT_GRAY); lblUnitkmAndArrow.setForeground(Color.LIGHT_GRAY); lblUnitVelocityAtRadius1.setForeground(Color.LIGHT_GRAY); } } }); DocumentListener docListener = new DocumentListener() { @Override public void removeUpdate(DocumentEvent e) { event(e); } @Override public void insertUpdate(DocumentEvent e) { event(e); } @Override public void changedUpdate(DocumentEvent e) { event(e); } private void event(DocumentEvent e) { Object owner = e.getDocument().getProperty("owner"); String tfName = ((JTextField) owner).getName(); System.out.println("the textfield that changed is: " + tfName); // READ BEFORE STARTING - will be best to put these methods at bottom in helper method section including the switch above // General logic String tfVal = "unassigned"; switch(tfName) { case "argofperi": tfVal = tfArgOfPeri.getText(); break; case "periapsis": tfVal = tfPeriapsis.getText(); break; case "apoapsis": tfVal = tfApoapsis.getText(); break; case "semimajoraxis": tfVal = tfSemimajorAxis.getText(); break; case "eccentricity": tfVal = tfEccentricity.getText(); break; case "inclination": tfVal = tfInclination.getText(); break; case "radiusforvelocity": tfVal = tfRadiusForVelocity.getText(); break; case "velocityatradius": tfVal = tfVelocityAtRadius.getText(); break; case "velocityatapoapsis": tfVal = tfVelocityAtApoapsis.getText(); break; case "velocityatperiapsis": tfVal = tfVelocityAtPeriapsis.getText(); break; case "sme": tfVal = tfSME.getText(); break; case "period": tfVal = tfPeriod.getText(); break; case "raan": tfVal = tfRAAN.getText(); break; } // check for sign // char sign = getSign(tfVal); // check val is numeric String currentTextFieldIsEmpty = "unassigned"; // can be "unassigned" "empty" or "populated" - for error checking methods Color background = Color.WHITE; if (isNumeric(tfVal) == true || tfVal.isEmpty() == true) { background = defaultBackground; // make label warning invisible lblEllipticalInputWarning.setVisible(false); currentTextFieldIsEmpty = "empty"; } else if (isNumeric(tfVal) == false) { // make warning sign visible lblEllipticalInputWarning.setVisible(true); // make background of current tf red background = warningBackground; // need to know the field is populated for setTextFieldCombinations() below currentTextFieldIsEmpty = "populated"; } switch(tfName) { case "argofperi": tfArgOfPeri.setBackground(background); break; case "periapsis": tfPeriapsis.setBackground(background); break; case "apoapsis": tfApoapsis.setBackground(background); break; case "semimajoraxis": tfSemimajorAxis.setBackground(background); break; case "eccentricity": tfEccentricity.setBackground(background); break; case "inclination": tfInclination.setBackground(background); break; case "radiusforvelocity": tfRadiusForVelocity.setBackground(background); break; case "velocityatradius": tfVelocityAtRadius.setBackground(background); break; case "velocityatapoapsis": tfVelocityAtApoapsis.setBackground(background); break; case "velocityatperiapsis": tfVelocityAtPeriapsis.setBackground(background); break; case "sme": tfSME.setBackground(background); break; case "period": tfPeriod.setBackground(background); break; case "raan": tfRAAN.setBackground(background); break; } // call relevant method to make sure the relevant textfields are changed so the user cant edit them // setTextFieldCombinations(tfName, currentTextFieldIsEmpty); } }; tfArgOfPeri.getDocument().addDocumentListener(docListener); tfPeriapsis.getDocument().addDocumentListener(docListener); tfSemimajorAxis.getDocument().addDocumentListener(docListener); tfEccentricity.getDocument().addDocumentListener(docListener); tfInclination.getDocument().addDocumentListener(docListener); tfSME.getDocument().addDocumentListener(docListener); tfRAAN.getDocument().addDocumentListener(docListener); tfPeriod.getDocument().addDocumentListener(docListener); tfRadiusForVelocity.getDocument().addDocumentListener(docListener); tfVelocityAtPeriapsis.getDocument().addDocumentListener(docListener); tfVelocityAtApoapsis.getDocument().addDocumentListener(docListener); tfVelocityAtRadius.getDocument().addDocumentListener(docListener); tfApoapsis.getDocument().addDocumentListener(docListener); // kept this to remind me how to make a listener for individual tf's /*tfArgOfPeri.getDocument().addDocumentListener(new DocumentListener() { public void changedUpdate(DocumentEvent e) { warn(); } public void removeUpdate(DocumentEvent e) { warn(); } public void insertUpdate(DocumentEvent e) { warn(); } public void warn() { System.out.println("tf edited"); } }); */ Border defaultBorder = tfSME.getBorder(); } // listener model view controller architecture public void setNewGraphics(MainFrameListenerElliptical listener) { System.out.println("setNewGraphics()"); this.newGraphicsListener = listener; } /*@Override - I'm not sure why this isnt required as it is in CircularOrbitInputs using the same architecture. The only possibility I can think of is that circularPanel has a button which may mean that it needs overriding.*/ @Override public void actionPerformed(ActionEvent e) { System.out.println("in actionPerformed(ActionEvent e)"); //getOrbitRenderScale(); mu = OrbitMainFrame.getOrbitingBodyData("mu"); calculateEllipticalOrbit(); newGraphicsListener.setNewGraphics(); } // FUNCTION METHODS private void getOrbitRenderScale() { // TODO Auto-generated method stub } private void calculateEllipticalOrbit() { System.out.println("in calculateEllipticalOrbit()"); // get all the inputs and set them to private parameters getUserInputs(); // calculations (multiple methods) int loopCounter = 1; boolean finished = false; do { boolean calculationRan = false; System.out.println("========= TEST FOR LOOP " + loopCounter + " ==========="); System.out.println("Apoapsis = " + (Apoapsis == null) + " = " + Apoapsis); System.out.println("Periapsis = " + (Periapsis == null) + " = " + Periapsis); System.out.println("a = " + (SemimajorAxis == null) + " = " + SemimajorAxis); System.out.println("e = " + (Eccentricity == null) + " = " + Eccentricity); System.out.println("i = " + (Inclination == null) + " = " + Inclination); System.out.println("V at R = " + (VelocityAtRadius == null) + " = " + VelocityAtRadius); System.out.println("R for V = " + (RadiusForVelocity == null) + " = " + RadiusForVelocity); System.out.println("V at A = " + (VelocityAtApoapsis == null) + " = " + VelocityAtApoapsis); System.out.println("V at P = " + (VelocityAtPeriapsis == null) + " = " + VelocityAtPeriapsis); System.out.println("SME = " + (SME == null) + " = " + SME); System.out.println("T = " + (Period == null) + " = " + Period); System.out.println("============================================="); // if both rp and ra is defined/calculated if (Periapsis != null && Apoapsis != null) { // calculate a System.out.println("in peri true & apo true"); if (SemimajorAxis == null ) { System.out.println("call ()"); calcSimimajorAxisWithPeriapsisAndApoasis(Apoapsis, Periapsis); calculationRan = true; } // calculate e System.out.println("got to the ECCENTRICITY IF IN RP AND RA == TRUE"); if (Eccentricity == null) { System.out.println("call calcEccentricityWithPeriAndApo()"); calcEccentricityWithPeriapsisAndApoasis(Apoapsis, Periapsis); System.out.println("e = " + Eccentricity); calculationRan = true; } } // if a and rp are defined/calculated if (Apoapsis != null && SemimajorAxis != null) { // calc rp if (Periapsis == null) { System.out.println("call ()"); calcPeriapsisWithApoapsisAndSemimajorAxis(SemimajorAxis, Apoapsis); calculationRan= true; } } // if a and ra are defined/calculated if (Periapsis != null && SemimajorAxis != null) { // calc ra if (Apoapsis == null) { System.out.println("call ()"); calcApoapsisWithPeriapsisAndSemimajorAxis(SemimajorAxis, Periapsis); calculationRan = true; } } // if a is defined/calculated if (SemimajorAxis != null) { // calc epsilon if (SME == null) { calcEpsilonWithSemimajorAxis(SemimajorAxis); calculationRan = true; } // calc period if (Period == null) { calcPeriodWithSemimajorAxis(SemimajorAxis); calculationRan = true; } } // if e and ra are defined/ calculated // if e and rp are defined/ calculated // if e a and ra are defined/ calculated // if e a and rp are defined/ calculated // if SME (epsilon) is provided by the user if (SME != null) { // calculate a System.out.println("call calcSemimajorAxisWithEpsilon()"); if (SemimajorAxis == null) { calcSemimajorAxisWithEpsilon(SME); calculationRan = true; } } // if period is provided by the user if (Period != null) { // calculate a if (SemimajorAxis == null) { calcSemimajorAxisWithPeriod(Period); calculationRan = true; } } // VELOCITY // standard vp and va if (Periapsis != null) { if (SME != null && VelocityAtPeriapsis == null) { VelocityAtPeriapsis = EllipticalOrbitVelocityAtRadius(Periapsis); calculationRan = true; } } else { if (SME != null && VelocityAtPeriapsis != null && Periapsis == null) { Periapsis = EllipticalOrbitRadiusAtVelocity(VelocityAtPeriapsis); calculationRan = true; } } if (Apoapsis != null && VelocityAtApoapsis == null) { if (SME != null) { VelocityAtApoapsis = EllipticalOrbitVelocityAtRadius(Apoapsis); calculationRan = true; } } else { if (SME != null && VelocityAtApoapsis != null && Apoapsis == null) { Apoapsis = EllipticalOrbitRadiusAtVelocity(VelocityAtApoapsis); calculationRan = true; } } // user specific v at r OR r at v if (chckbxNewVelocityAtRadius.isSelected() == true) { if (SME != null) { if (RadiusForVelocity != null && VelocityAtRadius == null) { VelocityAtRadius = EllipticalOrbitVelocityAtRadius(RadiusForVelocity); calculationRan = true; } if (VelocityAtRadius != null && RadiusForVelocity == null) { RadiusForVelocity = EllipticalOrbitRadiusAtVelocity(VelocityAtRadius); calculationRan = true; } } } loopCounter++; System.out.println("loopCounter = " + loopCounter); // if there is nothing more that can be done then the loop is finished if (calculationRan == true) { // let it loop again System.out.println("calculationRan = true"); } else if (calculationRan == false){ finished = true; System.out.println("calculationRan = false"); } if (loopCounter == 100) { finished = true; System.out.println("STOPPED BY loopCounter"); } } while (finished == false); // write calculated values to relevant text fields setCalculationsToRelevantTextFields(); } private void getUserInputs() { if (isNumeric(tfArgOfPeri.getText()) == true) { ArgOfPeri = Double.parseDouble(tfArgOfPeri.getText()); ArgOfPeriAdded = true; } else { ArgOfPeriAdded = false; } //System.out.println("ArgOfPeri = " + ArgOfPeri); if (isNumeric(tfPeriapsis.getText()) == true) { Periapsis = Double.parseDouble(tfPeriapsis.getText()); PeriapsisAdded = true; } else { PeriapsisAdded = false; } //System.out.println("Periapsis = " + Periapsis); if (isNumeric(tfApoapsis.getText()) == true) { Apoapsis = Double.parseDouble(tfApoapsis.getText()); ApoapsisAdded = true; } else { ApoapsisAdded = false; } //System.out.println("Apoapsis = " + Apoapsis); if (isNumeric(tfSemimajorAxis.getText()) == true) { SemimajorAxis = Double.parseDouble(tfSemimajorAxis.getText()); SemimajorAxisAdded = true; } else { SemimajorAxisAdded = false; } //System.out.println("SemimajorAxis = " + SemimajorAxis); if (isNumeric(tfEccentricity.getText()) == true) { Eccentricity = Double.parseDouble(tfEccentricity.getText()); EccentricityAdded = true; } else { EccentricityAdded = false; } if (isNumeric(tfInclination.getText()) == true) { Inclination = Double.parseDouble(tfInclination.getText()); InclinationAdded = true; } else { InclinationAdded = false; } if (isNumeric(tfVelocityAtRadius.getText()) == true) { VelocityAtRadius = Double.parseDouble(tfVelocityAtRadius.getText()); VelocityAtRadiusAdded = true; } else { VelocityAtRadiusAdded = false; } if (isNumeric(tfRadiusForVelocity.getText()) == true) { RadiusForVelocity = Double.parseDouble(tfRadiusForVelocity.getText()); RadiusForVelocityAdded = true; } else { RadiusForVelocityAdded = false; } if (isNumeric(tfVelocityAtApoapsis.getText()) == true) { VelocityAtApoapsis = Double.parseDouble(tfVelocityAtApoapsis.getText()); VelocityAtApoapsisAdded = true; } else { VelocityAtApoapsisAdded = false; } if (isNumeric(tfVelocityAtPeriapsis.getText()) == true) { VelocityAtPeriapsis = Double.parseDouble(tfVelocityAtPeriapsis.getText()); VelocityAtPeriapsisAdded = true; } else { VelocityAtPeriapsisAdded = false; } //System.out.println("OrbitalPeriod = " + OrbitalPeriod); if (isNumeric(tfRAAN.getText()) == true) { RAAN = Double.parseDouble(tfRAAN.getText()); RAANAdded = true; } else { RAANAdded = false; } //System.out.println("RANN = " + RAAN); if (isNumeric(tfPeriod.getText()) == true) { Period = Double.parseDouble(tfPeriod.getText()); PeriodAdded = true; } else { PeriodAdded = false; } //System.out.println("Period = " + Period); } public static void resetEllipticalPanel() { } private void setCalculationsToRelevantTextFields() { // System.out.println(" IN TRY BLOCK"); // System.out.println("rp = " + Periapsis); // System.out.println("ra = " + Apoapsis) ; // System.out.println("a = " + SemimajorAxis); // System.out.println("e = " + Eccentricity); // System.out.println("R for V = " + RadiusForVelocity); // System.out.println("V at R = " + VelocityAtRadius); // System.out.println("V at A = " + VelocityAtApoapsis); // System.out.println("V at P = " + VelocityAtPeriapsis); // System.out.println("SME = " + SME); // System.out.println("T = " + Period); //tfArgOfPeri.setText(); //tfInclination.setText(Inclination.toString()); //tfRAAN.setText(RAAN.toString()); tfPeriapsis.setText(String.format("%.1f", Periapsis)); tfApoapsis.setText(String.format("%.1f", Apoapsis)); tfSemimajorAxis.setText(String.format("%.1f", SemimajorAxis)); tfEccentricity.setText(String.format("%.5f", Eccentricity)); // the following 2 text fields may not be in use. the if checks so as not to throw a null pointer exception if (chckbxNewVelocityAtRadius.isSelected() == true) { tfRadiusForVelocity.setText(String.format("%.1f", RadiusForVelocity)); tfVelocityAtRadius.setText(String.format("%.5f", VelocityAtRadius)); } tfVelocityAtApoapsis.setText(String.format("%.5f", VelocityAtApoapsis)); tfVelocityAtPeriapsis.setText(String.format("%.5f", VelocityAtPeriapsis)); tfSME.setText(String.format("%.5f", SME)); tfPeriod.setText(String.format("%.5f", Period/60/60)); } // MAIN MATHS METHODS private void calcSemimajorAxisWithPeriod(double T) { SemimajorAxis = Math.cbrt((Math.pow((T / (2*pi)), 2) * mu)); System.out.println("a = " + SemimajorAxis + " with T = " + T); } private void calcSemimajorAxisWithEpsilon(double epsilon) { SemimajorAxis = - mu / (2 * epsilon); System.out.println("a = " + SemimajorAxis + " with epsilon = " + epsilon); } private void calcPeriodWithSemimajorAxis(double a) { Period = 2 * pi * Math.sqrt(a*a*a / mu); System.out.println("T = " + Period + " with a = " + a); } private void calcEpsilonWithSemimajorAxis(double a) { SME = - mu / (2 * a); System.out.println("SME = " + SME + " with a = " + a); } private void calcApoapsisWithPeriapsisAndSemimajorAxis(double a, double rp) { Apoapsis = (2 * a) - rp; System.out.println("ra = " + Apoapsis + " with rp = " + rp + " and a = " + a); } private void calcPeriapsisWithApoapsisAndSemimajorAxis(double a, double ra ) { Periapsis = (2 * a) - ra; System.out.println("rp = " + Periapsis + " with ra = " + ra + " and a = " + a); } private void calcEccentricityWithPeriapsisAndApoasis(double ra, double rp ) { Eccentricity = (ra - rp) / (ra + rp); System.out.println("e = " + Eccentricity + " with ra = " + ra + " and rp = " + rp); } private void calcSimimajorAxisWithPeriapsisAndApoasis(double ra, double rp) { SemimajorAxis = (ra + rp) / 2; System.out.println("a = " + SemimajorAxis + " with ra = " + ra + " and rp = " + rp); } private Double EllipticalOrbitVelocityAtRadius(Double r) { Double v = Math.sqrt(2 * ((mu / r) + SME)); return v; } private Double EllipticalOrbitRadiusAtVelocity(Double r) { r = mu / (((r * r) / 2) - SME); return r; } // HELPER METHODS public static boolean isNumeric(String str) { try { double d = Double.parseDouble(str); } catch(NumberFormatException nfe) { return false; } return true; } public static char getSign(String var) { char possSignVal = var.charAt(0); char sign = '0'; if (possSignVal == '-') { sign = '-'; } else /*possSignVal therefore = '+' || a number which means it is +ve */ { sign = '+'; } return sign; } // ERROR CHECKING public static void setTextFieldCombinations(String tfName, String currentTextFieldIsEmpty) { switch(tfName) { case "argofperi": // NOT REQUIRED if (currentTextFieldIsEmpty == "populated") /* make it so relevant tf's can't be edited */ { } else if (currentTextFieldIsEmpty == "empty") /* make all relevant fields editable */ { } break; case "periapsis": if (currentTextFieldIsEmpty == "populated") /* make it so relevant tf's can't be edited */ { } else if (currentTextFieldIsEmpty == "empty") /* make all relevant fields editable */ { } break; case "apoapsis": if (currentTextFieldIsEmpty == "populated") /* make it so relevant tf's can't be edited */ { } else if (currentTextFieldIsEmpty == "empty") /* make all relevant fields editable */ { } break; case "semimajoraxis": if (currentTextFieldIsEmpty == "populated") /* make it so relevant tf's can't be edited */ { } else if (currentTextFieldIsEmpty == "empty") /* make all relevant fields editable */ { } break; case "eccentricity": if (currentTextFieldIsEmpty == "populated") /* make it so relevant tf's can't be edited */ { } else if (currentTextFieldIsEmpty == "empty") /* make all relevant fields editable */ { } break; case "inclination": if (currentTextFieldIsEmpty == "populated") /* make it so relevant tf's can't be edited */ { } else if (currentTextFieldIsEmpty == "empty") /* make all relevant fields editable */ { } break; case "velocity": if (currentTextFieldIsEmpty == "populated") /* make it so relevant tf's can't be edited */ { } else if (currentTextFieldIsEmpty == "empty") /* make all relevant fields editable */ { } break; case "sme": if (currentTextFieldIsEmpty == "populated") /* make it so relevant tf's can't be edited */ { } else if (currentTextFieldIsEmpty == "empty") /* make all relevant fields editable */ { } break; case "period": if (currentTextFieldIsEmpty == "populated") /* make it so relevant tf's can't be edited */ { } else if (currentTextFieldIsEmpty == "empty") /* make all relevant fields editable */ { } break; case "raan": if (currentTextFieldIsEmpty == "populated") /* make it so relevant tf's can't be edited */ { } else if (currentTextFieldIsEmpty == "empty") /* make all relevant fields editable */ { } break; } } }
package org.anathan.zf2modulecreator; import com.intellij.lang.ASTNode; import com.intellij.lang.Language; import com.intellij.navigation.ItemPresentation; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.editor.Document; import com.intellij.openapi.fileTypes.FileTypes; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Iconable; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.io.StreamUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.codeStyle.CodeStyleManager; import com.intellij.psi.scope.PsiScopeProcessor; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.PsiElementProcessor; import com.intellij.psi.search.SearchScope; import com.intellij.util.IncorrectOperationException; import com.jetbrains.php.lang.lexer.PhpTokenTypes; import com.jetbrains.php.lang.parser.PhpElementTypes; import com.jetbrains.php.lang.psi.PhpPsiElementFactory; import com.jetbrains.php.lang.psi.elements.*; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ZF2Util { public static boolean isZF2Project(@NotNull Project project) { VirtualFile baseDir = project.getBaseDir(); VirtualFile zfDir = baseDir.findFileByRelativePath("vendor/zendframework"); if (zfDir == null || !zfDir.isDirectory()) { return false; } VirtualFile moduleDir = baseDir.findFileByRelativePath("module"); if (moduleDir == null || !moduleDir.isDirectory()) { return false; } VirtualFile appConfigFile = baseDir.findFileByRelativePath("config/application.config.php"); if (appConfigFile == null || appConfigFile.isDirectory()) { return false; } return true; } public static void addArrayValueToArrayCreation(@NotNull ArrayCreationExpression arrayCreation, @NotNull String valueText) { final Project project = arrayCreation.getProject(); final PsiFile psiFile = arrayCreation.getContainingFile(); final ArrayCreationExpression arrayCreationExpression = arrayCreation; final String newValueText = valueText; final Document doc = PsiDocumentManager.getInstance(project).getDocument(psiFile); if (doc == null) { return; } CommandProcessor.getInstance().executeCommand(project, new Runnable() { @Override public void run() { PsiElement[] arrayChildren = arrayCreationExpression.getChildren(); // all are Array Values if (arrayChildren.length >= 1) { PsiElement lastArrayValue = arrayChildren[arrayChildren.length - 1]; PsiElement whitespace = lastArrayValue.getPrevSibling(); // this is the white space before last PhpPsiElement PsiElement newWhiteSpace = null; if (whitespace instanceof PsiWhiteSpace) { newWhiteSpace = PsiElementFactory.SERVICE.getInstance(project).createDummyHolder(whitespace.getText(), PhpTokenTypes.WHITE_SPACE, null); } if (lastArrayValue.getNextSibling().getText().equals(",")) { PsiElement comma = lastArrayValue.getNextSibling(); PsiElement newPsi = PsiElementFactory.SERVICE.getInstance(project).createDummyHolder(newValueText, PhpElementTypes.ARRAY_VALUE, null); arrayCreationExpression.addAfter(newPsi, comma); if (newWhiteSpace != null) { arrayCreationExpression.addAfter(newWhiteSpace, comma); } } else { PsiElement newComma = PhpPsiElementFactory.createComma(project); PsiElement newPsi = PsiElementFactory.SERVICE.getInstance(project).createDummyHolder(newValueText, PhpElementTypes.ARRAY_VALUE, null); arrayCreationExpression.addAfter(newPsi, lastArrayValue); if (newWhiteSpace != null) { arrayCreationExpression.addAfter(newWhiteSpace, lastArrayValue); } arrayCreationExpression.addAfter(newComma, lastArrayValue); } } else { PsiElement lastChild = arrayCreationExpression.getLastChild(); // this is either ')' or ']' PsiElement secondLastChild = lastChild.getPrevSibling(); // this is either '('/'[' or whitespace PsiElement newWhiteSpace = null; PsiElement openingBrace = null; // this is '('/'[' if (secondLastChild instanceof PsiWhiteSpace) { String newSpaceText = secondLastChild.getText(); if (!newSpaceText.contains(" ") && !newSpaceText.contains("\t") && newSpaceText.contains("\n")) { newSpaceText += '\t'; } newWhiteSpace = PsiElementFactory.SERVICE.getInstance(project).createDummyHolder(newSpaceText, PhpTokenTypes.WHITE_SPACE, null); openingBrace = secondLastChild.getPrevSibling(); } else { openingBrace = secondLastChild; } PsiElement newPsi = PsiElementFactory.SERVICE.getInstance(project).createDummyHolder(newValueText, PhpElementTypes.ARRAY_VALUE, null); if (newWhiteSpace != null) { arrayCreationExpression.addAfter(newPsi, openingBrace); arrayCreationExpression.addAfter(newWhiteSpace, openingBrace); // this doesn't work, because white space will merge, then secondLastChild no longer valid // arrayCreationExpression.addAfter(newWhiteSpace, secondLastChild); // arrayCreationExpression.addAfter(newPsi, secondLastChild); } else { arrayCreationExpression.addAfter(newPsi, secondLastChild); } } List<VirtualFile> files = new ArrayList<VirtualFile>(); VirtualFile vFile = psiFile.getVirtualFile(); files.add(vFile); PsiDocumentManager.getInstance(project).reparseFiles(files, false); // this does work, but style isn't what I want, array values are in same line // PsiFile myPsiFile = PsiManager.getInstance(project).findFile(vFile); // if (myPsiFile != null) { // //must not change document outside command // CodeStyleManager.getInstance(project).reformat(myPsiFile); // int i = 0; } }, null, null, doc); } public static void addModuleToAppConfig(@NotNull Project project, @NotNull String moduleName) { VirtualFile baseDir = project.getBaseDir(); VirtualFile appConfigFile = baseDir.findFileByRelativePath("config/application.config.php"); if (appConfigFile == null || appConfigFile.isDirectory()) { return; } PsiFile appConfigPsiFile = PsiManager.getInstance(project).findFile(appConfigFile); if (appConfigPsiFile == null) { return; } PsiElement[] children = appConfigPsiFile.getChildren(); for (PsiElement child : children) { if (child instanceof GroupStatement) { GroupStatement groupStatement = (GroupStatement)child; for (PsiElement statementChild : groupStatement.getStatements()) { if (statementChild instanceof PhpReturn) { PhpReturn phpReturn = (PhpReturn)statementChild; if (phpReturn.getArgument() instanceof ArrayCreationExpression) { ArrayCreationExpression topArrayCreation = (ArrayCreationExpression)phpReturn.getArgument(); ArrayHashElement modulesHash = findArrayHashWithKey(topArrayCreation, "modules"); if (modulesHash != null && modulesHash.getValue() != null && modulesHash.getValue() instanceof ArrayCreationExpression) { ArrayCreationExpression modulesArray = (ArrayCreationExpression)modulesHash.getValue(); addArrayValueToArrayCreation(modulesArray, "\'" + moduleName + "\'"); return; } } break; } } } } } private static ArrayHashElement findArrayHashWithKey(@NotNull ArrayCreationExpression array, @NotNull String key) { for (ArrayHashElement arrayHash : array.getHashElements()) { if (arrayHash.getKey() != null && arrayHash.getKey()instanceof StringLiteralExpression) { StringLiteralExpression keyLiteral = (StringLiteralExpression)arrayHash.getKey(); if (keyLiteral.getContents().equals(key)) { return arrayHash; } } } return null; } public static boolean isValidModuleName(@NotNull String moduleName) { if (Pattern.matches("^[_a-zA-Z][_a-zA-Z0-9]*$", moduleName)) { return true; } else { return false; } } public static VirtualFile createDirectory(@NotNull Project project, @NotNull VirtualFile baseDir, @NotNull String dirName) { try { return baseDir.createChildDirectory(project, dirName); } catch (IOException e1) { } return null; } public static PsiFile createFile(@NotNull Project project, @NotNull VirtualFile baseDir, @NotNull String fileName, @NotNull String fileContent) { PsiDirectory basePsiDir = PsiManager.getInstance(project).findDirectory(baseDir); if (basePsiDir != null) { PsiFile psiFile = PsiFileFactory.getInstance(project).createFileFromText(fileName, FileTypes.PLAIN_TEXT, fileContent); basePsiDir.add(psiFile); return psiFile; } return null; } public static String readResourceFileText(@NotNull String resourcePath) { String content; try { content = StreamUtil.convertSeparators(StreamUtil.readText(ZF2Util.class.getResourceAsStream(resourcePath), "UTF-8")); } catch (IOException e) { e.printStackTrace(); return null; } return content; } }
package org.biojava.utils.xml; import org.xml.sax.*; import org.xml.sax.helpers.*; import java.util.*; /** * SAX DocumentHandler which uses an XMLPeerFactory to construct * Java objects reflecting an XML document. The XMLPeerBuilder * system takes a depth-first approach to constructing the Object * tree. This means that, before attempting to construct an * Object to represent a particular element, it first constructs * Objects for all child elelments. * * <P> * Currently, Text nodes are automatically converted to Java strings * and treated as normal children. Treatment of Text may be * configurable in a future release. * </P> * * @author Thomas Down */ public class XMLPeerBuilder implements DocumentHandler { private static AttributeList emptyAttributes = new AttributeListImpl(); private XMLPeerFactory peerFactory; private boolean isComplete = true; private List stack; private StackEntry stackTop = null; private Object topLevel = null; /** * Construct a new XMLPeerBuilder, using the specified XMLPeerFactory * */ public XMLPeerBuilder(XMLPeerFactory f) { peerFactory = f; stack = new LinkedList(); } /** * Once the XMLPeerBuilder has been used, return an Object * which represents the whole document. * * @return an Object reflecting the document, or <code>null</code> * if none is available. */ public Object getTopLevelObject() { if (isComplete) return topLevel; return null; } public void characters(char[] ch, int start, int len) { String child = new String(ch, start, len); stackTop.objs.add(child); } public void ignorableWhitespace(char[] ch, int start, int len) { } public void startDocument() { isComplete = false; topLevel = new LinkedList(); } public void setDocumentLocator(Locator l) { } public void endDocument() { isComplete = true; } public void processingInstruction(String target, String data) { } public void startElement(String name, AttributeList al) { stack.add(0, stackTop); stackTop = new StackEntry(); if (al.getLength() == 0) stackTop.al = emptyAttributes; else stackTop.al = new AttributeListImpl(al); stackTop.objs = null; } public void endElement(String name) { Object o = peerFactory.getXMLPeer(name, stackTop.objs != null ? stackTop.objs : Collections.EMPTY_LIST, stackTop.al); stackTop = (StackEntry) stack.remove(0); if (o != null) { if (stackTop == null) { topLevel = o; } else { if (stackTop.objs == null) stackTop.objs = new LinkedList(); stackTop.objs.add(o); } } } class StackEntry { List objs; AttributeList al; } }
package org.dcache.xdr.gss; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Logger; import javax.security.auth.Subject; import javax.security.auth.kerberos.KerberosPrincipal; import org.dcache.xdr.RpcLoginService; import org.dcache.utils.Opaque; import org.ietf.jgss.GSSContext; import org.ietf.jgss.GSSCredential; import org.ietf.jgss.GSSException; import org.ietf.jgss.GSSManager; import org.ietf.jgss.GSSName; import org.ietf.jgss.Oid; public class GssSessionManager { private static final Logger _log = Logger.getLogger(GssSessionManager.class.getName()); private final GSSManager gManager = GSSManager.getInstance(); private final GSSCredential _serviceCredential; private final RpcLoginService _loginService; public GssSessionManager(RpcLoginService loginService) throws GSSException { System.setProperty("javax.security.auth.useSubjectCredsOnly", "false"); Oid krb5Mechanism = new Oid("1.2.840.113554.1.2.2"); _serviceCredential = gManager.createCredential(null, GSSCredential.INDEFINITE_LIFETIME, krb5Mechanism, GSSCredential.ACCEPT_ONLY); _loginService = loginService; } private final Map<Opaque, GSSContext> sessions = new ConcurrentHashMap<Opaque, GSSContext>(); public GSSContext createContext(byte[] handle) throws GSSException { GSSContext context = gManager.createContext(_serviceCredential); sessions.put(new Opaque(handle), context); return context; } public GSSContext getContext(byte[] handle) throws GSSException { GSSContext context = sessions.get(new Opaque(handle)); if(context == null) { throw new GSSException(GSSException.NO_CONTEXT); } return context; } public GSSContext getEstablishedContext(byte[] handle) throws GSSException { GSSContext context = getContext(handle); if (!context.isEstablished()) { throw new GSSException(GSSException.NO_CONTEXT); } return context; } public GSSContext destroyContext(byte[] handle) throws GSSException { GSSContext context = sessions.remove(new Opaque(handle)); if(context == null || !context.isEstablished()) { throw new GSSException(GSSException.NO_CONTEXT); } return context; } public Subject subjectOf(GSSName name) { return _loginService.login( new KerberosPrincipal(name.toString())); } }