answer
stringlengths
17
10.2M
package com.github.sormuras.bach; import com.github.sormuras.bach.internal.ArgVester; import com.github.sormuras.bach.internal.ModuleDescriptorSupport; import com.github.sormuras.bach.internal.ModuleLayerSupport; import com.github.sormuras.bach.project.DeclaredModule; import com.github.sormuras.bach.project.DeclaredModules; import java.lang.module.ModuleFinder; import java.nio.file.Files; import java.nio.file.Path; import java.util.EnumSet; import java.util.ServiceLoader; import java.util.concurrent.atomic.AtomicReference; import java.util.spi.ToolProvider; import java.util.stream.Stream; record MainBachBuilder(Printer printer, ArgVester<CommandLineInterface> parser) { MainBachBuilder(Printer printer) { this(printer, ArgVester.create(CommandLineInterface.class)); } Bach build(String... args) { return build(parser.parse(args)); } Bach build(CommandLineInterface commandLineArguments) { var flags = EnumSet.noneOf(Flag.class); commandLineArguments.verbose().ifPresent(__ -> flags.add(Flag.VERBOSE)); commandLineArguments.dry_run().ifPresent(__ -> flags.add(Flag.DRY_RUN)); var root = Path.of(commandLineArguments.root_directory().orElse("")); var paths = new Paths( root, commandLineArguments .output_directory() .map(Path::of) .orElse(root.resolve(".bach/out"))); var fileArguments = loadFileArguments(paths, "project-info.args"); var projectInfoLayer = loadModuleLayer(paths, "project-info"); var configurator = loadConfigurator(projectInfoLayer); var configuration = Configuration.ofDefaults() .with(printer) .with(paths) .with(new Flags(flags)) .with(configurator.configureToolFinder(paths)); var pattern = commandLineArguments .module_info_find_pattern() .or(fileArguments::module_info_find_pattern) .orElse("glob:**/module-info.java"); var project = Project.ofDefaults(); project = withWalkingDirectory(project, paths.root(), pattern); project = withApplyingArguments(project, fileArguments); project = withApplyingConfigurator(project, configurator); project = withApplyingArguments(project, commandLineArguments); return new Bach(configuration, project); } Configurator loadConfigurator(ModuleLayer layer) { var configurators = ServiceLoader.load(layer, Configurator.class).stream() .map(ServiceLoader.Provider::get) .toList(); if (configurators.size() >= 2) throw new RuntimeException("Too many configurators: " + configurators); return configurators.isEmpty() ? Configurator.identity() : configurators.get(0); } CommandLineInterface loadFileArguments(Paths paths, String name) { var files = Stream.of(paths.root(name), paths.root(".bach", name)) .filter(Files::isRegularFile) .toList(); if (files.isEmpty()) return parser.parse(); if (files.size() > 1) throw new RuntimeException("Expected single file:" + files); var file = files.get(0); try { var lines = Files.readAllLines(file).stream() .map(String::strip) .filter(line -> !line.startsWith(" return parser.parse(lines.toArray(String[]::new)); } catch (Exception exception) { throw new RuntimeException("Read all lines from file failed: " + file, exception); } } ModuleLayer loadModuleLayer(Paths paths, String name) { var info = Path.of(name); var directories = Stream.of("", ".bach") .map(base -> paths.root(base).resolve(info)) .map(Path::normalize) .filter(Files::isDirectory) .filter(directory -> Files.isRegularFile(directory.resolve("module-info.java"))) .toList(); if (directories.isEmpty()) return ModuleLayer.empty(); if (directories.size() > 1) throw new RuntimeException("Expected single folder:" + directories); var directory = directories.get(0); try { var module = ModuleDescriptorSupport.parse(directory.resolve("module-info.java")); var javac = ToolProvider.findFirst("javac").orElseThrow(); var location = Bach.class.getProtectionDomain().getCodeSource().getLocation().toURI(); var target = paths.out(info.getFileName().toString()); javac.run( printer.out(), printer.err(), "--module=" + module.name(), "--module-source-path=" + module.name() + '=' + directory, "--module-path=" + Path.of(location), "-d", target.toString()); return ModuleLayerSupport.layer(ModuleFinder.of(target), false); } catch (Exception exception) { throw new RuntimeException(exception); } } static Project withApplyingConfigurator(Project project, Configurator configurator) { return configurator.configureProject(project); } static Project withApplyingArguments(Project project, CommandLineInterface cli) { var it = new AtomicReference<>(project); cli.project_name().ifPresent(name -> it.set(it.get().withName(name))); cli.project_version().ifPresent(version -> it.set(it.get().withVersion(version))); cli.project_version_date().ifPresent(date -> it.set(it.get().withVersionDate(date))); cli.project_targets_java().ifPresent(java -> it.set(it.get().withTargetsJava(java))); cli.project_launcher().ifPresent(launcher -> it.set(it.get().withLauncher(launcher))); return it.get(); } /** * {@return new project instance configured by finding {@code module-info.java} files matching the * given {@link java.nio.file.FileSystem#getPathMatcher(String) syntaxAndPattern} below the * specified root directory} */ static Project withWalkingDirectory(Project project, Path directory, String syntaxAndPattern) { var name = directory.normalize().toAbsolutePath().getFileName(); if (name != null) project = project.withName(name.toString()); var matcher = directory.getFileSystem().getPathMatcher(syntaxAndPattern); try (var stream = Files.find(directory, 9, (p, a) -> matcher.matches(p))) { var inits = DeclaredModules.of(); var mains = DeclaredModules.of(); var tests = DeclaredModules.of(); for (var path : stream.toList()) { var uri = path.toUri().toString(); if (uri.contains("/.bach/")) continue; var module = DeclaredModule.of(path); if (uri.contains("/init/")) { inits = inits.with(module); continue; } if (uri.contains("/test/")) { tests = tests.with(module); continue; } mains = mains.with(module); } project = project.with(project.spaces().init().withModules(inits)); project = project.with(project.spaces().main().withModules(mains)); project = project.with(project.spaces().test().withModules(tests)); } catch (Exception exception) { throw new RuntimeException("Find with %s failed".formatted(syntaxAndPattern), exception); } return project; } }
package org.jfree.chart.axis; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Shape; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.jfree.chart.entity.CategoryLabelEntity; import org.jfree.chart.entity.EntityCollection; import org.jfree.chart.event.AxisChangeEvent; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.Plot; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.util.ParamChecks; import org.jfree.data.category.CategoryDataset; import org.jfree.io.SerialUtilities; import org.jfree.text.G2TextMeasurer; import org.jfree.text.TextBlock; import org.jfree.text.TextUtilities; import org.jfree.ui.RectangleAnchor; import org.jfree.ui.RectangleEdge; import org.jfree.ui.RectangleInsets; import org.jfree.ui.Size2D; import org.jfree.util.ObjectUtilities; import org.jfree.util.PaintUtilities; import org.jfree.util.ShapeUtilities; /** * An axis that displays categories. */ public class CategoryAxis extends Axis implements Cloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = 5886554608114265863L; /** * The default margin for the axis (used for both lower and upper margins). */ public static final double DEFAULT_AXIS_MARGIN = 0.05; /** * The default margin between categories (a percentage of the overall axis * length). */ public static final double DEFAULT_CATEGORY_MARGIN = 0.20; /** The amount of space reserved at the start of the axis. */ private double lowerMargin; /** The amount of space reserved at the end of the axis. */ private double upperMargin; /** The amount of space reserved between categories. */ private double categoryMargin; /** The maximum number of lines for category labels. */ private int maximumCategoryLabelLines; /** * A ratio that is multiplied by the width of one category to determine the * maximum label width. */ private float maximumCategoryLabelWidthRatio; /** The category label offset. */ private int categoryLabelPositionOffset; /** * A structure defining the category label positions for each axis * location. */ private CategoryLabelPositions categoryLabelPositions; /** Storage for tick label font overrides (if any). */ private Map tickLabelFontMap; /** Storage for tick label paint overrides (if any). */ private transient Map tickLabelPaintMap; /** Storage for the category label tooltips (if any). */ private Map categoryLabelToolTips; /** Storage for the category label URLs (if any). */ private Map categoryLabelURLs; /** * Creates a new category axis with no label. */ public CategoryAxis() { this(null); } /** * Constructs a category axis, using default values where necessary. * * @param label the axis label (<code>null</code> permitted). */ public CategoryAxis(String label) { super(label); this.lowerMargin = DEFAULT_AXIS_MARGIN; this.upperMargin = DEFAULT_AXIS_MARGIN; this.categoryMargin = DEFAULT_CATEGORY_MARGIN; this.maximumCategoryLabelLines = 1; this.maximumCategoryLabelWidthRatio = 0.0f; this.categoryLabelPositionOffset = 4; this.categoryLabelPositions = CategoryLabelPositions.STANDARD; this.tickLabelFontMap = new HashMap(); this.tickLabelPaintMap = new HashMap(); this.categoryLabelToolTips = new HashMap(); this.categoryLabelURLs = new HashMap(); } /** * Returns the lower margin for the axis. * * @return The margin. * * @see #getUpperMargin() * @see #setLowerMargin(double) */ public double getLowerMargin() { return this.lowerMargin; } /** * Sets the lower margin for the axis and sends an {@link AxisChangeEvent} * to all registered listeners. * * @param margin the margin as a percentage of the axis length (for * example, 0.05 is five percent). * * @see #getLowerMargin() */ public void setLowerMargin(double margin) { this.lowerMargin = margin; fireChangeEvent(); } /** * Returns the upper margin for the axis. * * @return The margin. * * @see #getLowerMargin() * @see #setUpperMargin(double) */ public double getUpperMargin() { return this.upperMargin; } /** * Sets the upper margin for the axis and sends an {@link AxisChangeEvent} * to all registered listeners. * * @param margin the margin as a percentage of the axis length (for * example, 0.05 is five percent). * * @see #getUpperMargin() */ public void setUpperMargin(double margin) { this.upperMargin = margin; fireChangeEvent(); } /** * Returns the category margin. * * @return The margin. * * @see #setCategoryMargin(double) */ public double getCategoryMargin() { return this.categoryMargin; } /** * Sets the category margin and sends an {@link AxisChangeEvent} to all * registered listeners. The overall category margin is distributed over * N-1 gaps, where N is the number of categories on the axis. * * @param margin the margin as a percentage of the axis length (for * example, 0.05 is five percent). * * @see #getCategoryMargin() */ public void setCategoryMargin(double margin) { this.categoryMargin = margin; fireChangeEvent(); } /** * Returns the maximum number of lines to use for each category label. * * @return The maximum number of lines. * * @see #setMaximumCategoryLabelLines(int) */ public int getMaximumCategoryLabelLines() { return this.maximumCategoryLabelLines; } /** * Sets the maximum number of lines to use for each category label and * sends an {@link AxisChangeEvent} to all registered listeners. * * @param lines the maximum number of lines. * * @see #getMaximumCategoryLabelLines() */ public void setMaximumCategoryLabelLines(int lines) { this.maximumCategoryLabelLines = lines; fireChangeEvent(); } /** * Returns the category label width ratio. * * @return The ratio. * * @see #setMaximumCategoryLabelWidthRatio(float) */ public float getMaximumCategoryLabelWidthRatio() { return this.maximumCategoryLabelWidthRatio; } /** * Sets the maximum category label width ratio and sends an * {@link AxisChangeEvent} to all registered listeners. * * @param ratio the ratio. * * @see #getMaximumCategoryLabelWidthRatio() */ public void setMaximumCategoryLabelWidthRatio(float ratio) { this.maximumCategoryLabelWidthRatio = ratio; fireChangeEvent(); } /** * Returns the offset between the axis and the category labels (before * label positioning is taken into account). * * @return The offset (in Java2D units). * * @see #setCategoryLabelPositionOffset(int) */ public int getCategoryLabelPositionOffset() { return this.categoryLabelPositionOffset; } /** * Sets the offset between the axis and the category labels (before label * positioning is taken into account) and sends a change event to all * registered listeners. * * @param offset the offset (in Java2D units). * * @see #getCategoryLabelPositionOffset() */ public void setCategoryLabelPositionOffset(int offset) { this.categoryLabelPositionOffset = offset; fireChangeEvent(); } /** * Returns the category label position specification (this contains label * positioning info for all four possible axis locations). * * @return The positions (never <code>null</code>). * * @see #setCategoryLabelPositions(CategoryLabelPositions) */ public CategoryLabelPositions getCategoryLabelPositions() { return this.categoryLabelPositions; } /** * Sets the category label position specification for the axis and sends an * {@link AxisChangeEvent} to all registered listeners. * * @param positions the positions (<code>null</code> not permitted). * * @see #getCategoryLabelPositions() */ public void setCategoryLabelPositions(CategoryLabelPositions positions) { ParamChecks.nullNotPermitted(positions, "positions"); this.categoryLabelPositions = positions; fireChangeEvent(); } /** * Returns the font for the tick label for the given category. * * @param category the category (<code>null</code> not permitted). * * @return The font (never <code>null</code>). * * @see #setTickLabelFont(Comparable, Font) */ public Font getTickLabelFont(Comparable category) { ParamChecks.nullNotPermitted(category, "category"); Font result = (Font) this.tickLabelFontMap.get(category); // if there is no specific font, use the general one... if (result == null) { result = getTickLabelFont(); } return result; } /** * Sets the font for the tick label for the specified category and sends * an {@link AxisChangeEvent} to all registered listeners. * * @param category the category (<code>null</code> not permitted). * @param font the font (<code>null</code> permitted). * * @see #getTickLabelFont(Comparable) */ public void setTickLabelFont(Comparable category, Font font) { ParamChecks.nullNotPermitted(category, "category"); if (font == null) { this.tickLabelFontMap.remove(category); } else { this.tickLabelFontMap.put(category, font); } fireChangeEvent(); } /** * Returns the paint for the tick label for the given category. * * @param category the category (<code>null</code> not permitted). * * @return The paint (never <code>null</code>). * * @see #setTickLabelPaint(Paint) */ public Paint getTickLabelPaint(Comparable category) { ParamChecks.nullNotPermitted(category, "category"); Paint result = (Paint) this.tickLabelPaintMap.get(category); // if there is no specific paint, use the general one... if (result == null) { result = getTickLabelPaint(); } return result; } /** * Sets the paint for the tick label for the specified category and sends * an {@link AxisChangeEvent} to all registered listeners. * * @param category the category (<code>null</code> not permitted). * @param paint the paint (<code>null</code> permitted). * * @see #getTickLabelPaint(Comparable) */ public void setTickLabelPaint(Comparable category, Paint paint) { ParamChecks.nullNotPermitted(category, "category"); if (paint == null) { this.tickLabelPaintMap.remove(category); } else { this.tickLabelPaintMap.put(category, paint); } fireChangeEvent(); } /** * Adds a tooltip to the specified category and sends an * {@link AxisChangeEvent} to all registered listeners. * * @param category the category (<code>null</code> not permitted). * @param tooltip the tooltip text (<code>null</code> permitted). * * @see #removeCategoryLabelToolTip(Comparable) */ public void addCategoryLabelToolTip(Comparable category, String tooltip) { ParamChecks.nullNotPermitted(category, "category"); this.categoryLabelToolTips.put(category, tooltip); fireChangeEvent(); } /** * Returns the tool tip text for the label belonging to the specified * category. * * @param category the category (<code>null</code> not permitted). * * @return The tool tip text (possibly <code>null</code>). * * @see #addCategoryLabelToolTip(Comparable, String) * @see #removeCategoryLabelToolTip(Comparable) */ public String getCategoryLabelToolTip(Comparable category) { ParamChecks.nullNotPermitted(category, "category"); return (String) this.categoryLabelToolTips.get(category); } /** * Removes the tooltip for the specified category and, if there was a value * associated with that category, sends an {@link AxisChangeEvent} to all * registered listeners. * * @param category the category (<code>null</code> not permitted). * * @see #addCategoryLabelToolTip(Comparable, String) * @see #clearCategoryLabelToolTips() */ public void removeCategoryLabelToolTip(Comparable category) { ParamChecks.nullNotPermitted(category, "category"); if (this.categoryLabelToolTips.remove(category) != null) { fireChangeEvent(); } } /** * Clears the category label tooltips and sends an {@link AxisChangeEvent} * to all registered listeners. * * @see #addCategoryLabelToolTip(Comparable, String) * @see #removeCategoryLabelToolTip(Comparable) */ public void clearCategoryLabelToolTips() { this.categoryLabelToolTips.clear(); fireChangeEvent(); } /** * Adds a URL (to be used in image maps) to the specified category and * sends an {@link AxisChangeEvent} to all registered listeners. * * @param category the category (<code>null</code> not permitted). * @param url the URL text (<code>null</code> permitted). * * @see #removeCategoryLabelURL(Comparable) * * @since 1.0.16 */ public void addCategoryLabelURL(Comparable category, String url) { ParamChecks.nullNotPermitted(category, "category"); this.categoryLabelURLs.put(category, url); fireChangeEvent(); } /** * Returns the URL for the label belonging to the specified category. * * @param category the category (<code>null</code> not permitted). * * @return The URL text (possibly <code>null</code>). * * @see #addCategoryLabelURL(Comparable, String) * @see #removeCategoryLabelURL(Comparable) * * @since 1.0.16 */ public String getCategoryLabelURL(Comparable category) { ParamChecks.nullNotPermitted(category, "category"); return (String) this.categoryLabelURLs.get(category); } /** * Removes the URL for the specified category and, if there was a URL * associated with that category, sends an {@link AxisChangeEvent} to all * registered listeners. * * @param category the category (<code>null</code> not permitted). * * @see #addCategoryLabelURL(Comparable, String) * @see #clearCategoryLabelURLs() * * @since 1.0.16 */ public void removeCategoryLabelURL(Comparable category) { ParamChecks.nullNotPermitted(category, "category"); if (this.categoryLabelURLs.remove(category) != null) { fireChangeEvent(); } } /** * Clears the category label URLs and sends an {@link AxisChangeEvent} * to all registered listeners. * * @see #addCategoryLabelURL(Comparable, String) * @see #removeCategoryLabelURL(Comparable) * * @since 1.0.16 */ public void clearCategoryLabelURLs() { this.categoryLabelURLs.clear(); fireChangeEvent(); } /** * Returns the Java 2D coordinate for a category. * * @param anchor the anchor point. * @param category the category index. * @param categoryCount the category count. * @param area the data area. * @param edge the location of the axis. * * @return The coordinate. */ public double getCategoryJava2DCoordinate(CategoryAnchor anchor, int category, int categoryCount, Rectangle2D area, RectangleEdge edge) { double result = 0.0; if (anchor == CategoryAnchor.START) { result = getCategoryStart(category, categoryCount, area, edge); } else if (anchor == CategoryAnchor.MIDDLE) { result = getCategoryMiddle(category, categoryCount, area, edge); } else if (anchor == CategoryAnchor.END) { result = getCategoryEnd(category, categoryCount, area, edge); } return result; } /** * Returns the starting coordinate for the specified category. * * @param category the category. * @param categoryCount the number of categories. * @param area the data area. * @param edge the axis location. * * @return The coordinate. * * @see #getCategoryMiddle(int, int, Rectangle2D, RectangleEdge) * @see #getCategoryEnd(int, int, Rectangle2D, RectangleEdge) */ public double getCategoryStart(int category, int categoryCount, Rectangle2D area, RectangleEdge edge) { double result = 0.0; if ((edge == RectangleEdge.TOP) || (edge == RectangleEdge.BOTTOM)) { result = area.getX() + area.getWidth() * getLowerMargin(); } else if ((edge == RectangleEdge.LEFT) || (edge == RectangleEdge.RIGHT)) { result = area.getMinY() + area.getHeight() * getLowerMargin(); } double categorySize = calculateCategorySize(categoryCount, area, edge); double categoryGapWidth = calculateCategoryGapSize(categoryCount, area, edge); result = result + category * (categorySize + categoryGapWidth); return result; } /** * Returns the middle coordinate for the specified category. * * @param category the category. * @param categoryCount the number of categories. * @param area the data area. * @param edge the axis location. * * @return The coordinate. * * @see #getCategoryStart(int, int, Rectangle2D, RectangleEdge) * @see #getCategoryEnd(int, int, Rectangle2D, RectangleEdge) */ public double getCategoryMiddle(int category, int categoryCount, Rectangle2D area, RectangleEdge edge) { if (category < 0 || category >= categoryCount) { throw new IllegalArgumentException("Invalid category index: " + category); } return getCategoryStart(category, categoryCount, area, edge) + calculateCategorySize(categoryCount, area, edge) / 2; } /** * Returns the end coordinate for the specified category. * * @param category the category. * @param categoryCount the number of categories. * @param area the data area. * @param edge the axis location. * * @return The coordinate. * * @see #getCategoryStart(int, int, Rectangle2D, RectangleEdge) * @see #getCategoryMiddle(int, int, Rectangle2D, RectangleEdge) */ public double getCategoryEnd(int category, int categoryCount, Rectangle2D area, RectangleEdge edge) { return getCategoryStart(category, categoryCount, area, edge) + calculateCategorySize(categoryCount, area, edge); } /** * A convenience method that returns the axis coordinate for the centre of * a category. * * @param category the category key (<code>null</code> not permitted). * @param categories the categories (<code>null</code> not permitted). * @param area the data area (<code>null</code> not permitted). * @param edge the edge along which the axis lies (<code>null</code> not * permitted). * * @return The centre coordinate. * * @since 1.0.11 * * @see #getCategorySeriesMiddle(Comparable, Comparable, CategoryDataset, * double, Rectangle2D, RectangleEdge) */ public double getCategoryMiddle(Comparable category, List categories, Rectangle2D area, RectangleEdge edge) { ParamChecks.nullNotPermitted(categories, "categories"); int categoryIndex = categories.indexOf(category); int categoryCount = categories.size(); return getCategoryMiddle(categoryIndex, categoryCount, area, edge); } /** * Returns the middle coordinate (in Java2D space) for a series within a * category. * * @param category the category (<code>null</code> not permitted). * @param seriesKey the series key (<code>null</code> not permitted). * @param dataset the dataset (<code>null</code> not permitted). * @param itemMargin the item margin (0.0 &lt;= itemMargin &lt; 1.0); * @param area the area (<code>null</code> not permitted). * @param edge the edge (<code>null</code> not permitted). * * @return The coordinate in Java2D space. * * @since 1.0.7 */ public double getCategorySeriesMiddle(Comparable category, Comparable seriesKey, CategoryDataset dataset, double itemMargin, Rectangle2D area, RectangleEdge edge) { int categoryIndex = dataset.getColumnIndex(category); int categoryCount = dataset.getColumnCount(); int seriesIndex = dataset.getRowIndex(seriesKey); int seriesCount = dataset.getRowCount(); double start = getCategoryStart(categoryIndex, categoryCount, area, edge); double end = getCategoryEnd(categoryIndex, categoryCount, area, edge); double width = end - start; if (seriesCount == 1) { return start + width / 2.0; } else { double gap = (width * itemMargin) / (seriesCount - 1); double ww = (width * (1 - itemMargin)) / seriesCount; return start + (seriesIndex * (ww + gap)) + ww / 2.0; } } /** * Returns the middle coordinate (in Java2D space) for a series within a * category. * * @param categoryIndex the category index. * @param categoryCount the category count. * @param seriesIndex the series index. * @param seriesCount the series count. * @param itemMargin the item margin (0.0 &lt;= itemMargin &lt; 1.0); * @param area the area (<code>null</code> not permitted). * @param edge the edge (<code>null</code> not permitted). * * @return The coordinate in Java2D space. * * @since 1.0.13 */ public double getCategorySeriesMiddle(int categoryIndex, int categoryCount, int seriesIndex, int seriesCount, double itemMargin, Rectangle2D area, RectangleEdge edge) { double start = getCategoryStart(categoryIndex, categoryCount, area, edge); double end = getCategoryEnd(categoryIndex, categoryCount, area, edge); double width = end - start; if (seriesCount == 1) { return start + width / 2.0; } else { double gap = (width * itemMargin) / (seriesCount - 1); double ww = (width * (1 - itemMargin)) / seriesCount; return start + (seriesIndex * (ww + gap)) + ww / 2.0; } } /** * Calculates the size (width or height, depending on the location of the * axis) of a category. * * @param categoryCount the number of categories. * @param area the area within which the categories will be drawn. * @param edge the axis location. * * @return The category size. */ protected double calculateCategorySize(int categoryCount, Rectangle2D area, RectangleEdge edge) { double result; double available = 0.0; if ((edge == RectangleEdge.TOP) || (edge == RectangleEdge.BOTTOM)) { available = area.getWidth(); } else if ((edge == RectangleEdge.LEFT) || (edge == RectangleEdge.RIGHT)) { available = area.getHeight(); } if (categoryCount > 1) { result = available * (1 - getLowerMargin() - getUpperMargin() - getCategoryMargin()); result = result / categoryCount; } else { result = available * (1 - getLowerMargin() - getUpperMargin()); } return result; } /** * Calculates the size (width or height, depending on the location of the * axis) of a category gap. * * @param categoryCount the number of categories. * @param area the area within which the categories will be drawn. * @param edge the axis location. * * @return The category gap width. */ protected double calculateCategoryGapSize(int categoryCount, Rectangle2D area, RectangleEdge edge) { double result = 0.0; double available = 0.0; if ((edge == RectangleEdge.TOP) || (edge == RectangleEdge.BOTTOM)) { available = area.getWidth(); } else if ((edge == RectangleEdge.LEFT) || (edge == RectangleEdge.RIGHT)) { available = area.getHeight(); } if (categoryCount > 1) { result = available * getCategoryMargin() / (categoryCount - 1); } return result; } /** * Estimates the space required for the axis, given a specific drawing area. * * @param g2 the graphics device (used to obtain font information). * @param plot the plot that the axis belongs to. * @param plotArea the area within which the axis should be drawn. * @param edge the axis location (top or bottom). * @param space the space already reserved. * * @return The space required to draw the axis. */ @Override public AxisSpace reserveSpace(Graphics2D g2, Plot plot, Rectangle2D plotArea, RectangleEdge edge, AxisSpace space) { // create a new space object if one wasn't supplied... if (space == null) { space = new AxisSpace(); } // if the axis is not visible, no additional space is required... if (!isVisible()) { return space; } // calculate the max size of the tick labels (if visible)... double tickLabelHeight = 0.0; double tickLabelWidth = 0.0; if (isTickLabelsVisible()) { g2.setFont(getTickLabelFont()); AxisState state = new AxisState(); // we call refresh ticks just to get the maximum width or height refreshTicks(g2, state, plotArea, edge); if (edge == RectangleEdge.TOP) { tickLabelHeight = state.getMax(); } else if (edge == RectangleEdge.BOTTOM) { tickLabelHeight = state.getMax(); } else if (edge == RectangleEdge.LEFT) { tickLabelWidth = state.getMax(); } else if (edge == RectangleEdge.RIGHT) { tickLabelWidth = state.getMax(); } } // get the axis label size and update the space object... Rectangle2D labelEnclosure = getLabelEnclosure(g2, edge); double labelHeight, labelWidth; if (RectangleEdge.isTopOrBottom(edge)) { labelHeight = labelEnclosure.getHeight(); space.add(labelHeight + tickLabelHeight + this.categoryLabelPositionOffset, edge); } else if (RectangleEdge.isLeftOrRight(edge)) { labelWidth = labelEnclosure.getWidth(); space.add(labelWidth + tickLabelWidth + this.categoryLabelPositionOffset, edge); } return space; } /** * Configures the axis against the current plot. */ @Override public void configure() { // nothing required } /** * Draws the axis on a Java 2D graphics device (such as the screen or a * printer). * * @param g2 the graphics device (<code>null</code> not permitted). * @param cursor the cursor location. * @param plotArea the area within which the axis should be drawn * (<code>null</code> not permitted). * @param dataArea the area within which the plot is being drawn * (<code>null</code> not permitted). * @param edge the location of the axis (<code>null</code> not permitted). * @param plotState collects information about the plot * (<code>null</code> permitted). * * @return The axis state (never <code>null</code>). */ @Override public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea, Rectangle2D dataArea, RectangleEdge edge, PlotRenderingInfo plotState) { // if the axis is not visible, don't draw it... if (!isVisible()) { return new AxisState(cursor); } if (isAxisLineVisible()) { drawAxisLine(g2, cursor, dataArea, edge); } AxisState state = new AxisState(cursor); if (isTickMarksVisible()) { drawTickMarks(g2, cursor, dataArea, edge, state); } createAndAddEntity(cursor, state, dataArea, edge, plotState); // draw the category labels and axis label state = drawCategoryLabels(g2, plotArea, dataArea, edge, state, plotState); if (getAttributedLabel() != null) { state = drawAttributedLabel(getAttributedLabel(), g2, plotArea, dataArea, edge, state); } else { state = drawLabel(getLabel(), g2, plotArea, dataArea, edge, state); } return state; } /** * Draws the category labels and returns the updated axis state. * * @param g2 the graphics device (<code>null</code> not permitted). * @param plotArea the plot area (<code>null</code> not permitted). * @param dataArea the area inside the axes (<code>null</code> not * permitted). * @param edge the axis location (<code>null</code> not permitted). * @param state the axis state (<code>null</code> not permitted). * @param plotState collects information about the plot (<code>null</code> * permitted). * * @return The updated axis state (never <code>null</code>). */ protected AxisState drawCategoryLabels(Graphics2D g2, Rectangle2D plotArea, Rectangle2D dataArea, RectangleEdge edge, AxisState state, PlotRenderingInfo plotState) { ParamChecks.nullNotPermitted(state, "state"); if (!isTickLabelsVisible()) { return state; } List ticks = refreshTicks(g2, state, plotArea, edge); state.setTicks(ticks); int categoryIndex = 0; Iterator iterator = ticks.iterator(); while (iterator.hasNext()) { CategoryTick tick = (CategoryTick) iterator.next(); g2.setFont(getTickLabelFont(tick.getCategory())); g2.setPaint(getTickLabelPaint(tick.getCategory())); CategoryLabelPosition position = this.categoryLabelPositions.getLabelPosition(edge); double x0 = 0.0; double x1 = 0.0; double y0 = 0.0; double y1 = 0.0; if (edge == RectangleEdge.TOP) { x0 = getCategoryStart(categoryIndex, ticks.size(), dataArea, edge); x1 = getCategoryEnd(categoryIndex, ticks.size(), dataArea, edge); y1 = state.getCursor() - this.categoryLabelPositionOffset; y0 = y1 - state.getMax(); } else if (edge == RectangleEdge.BOTTOM) { x0 = getCategoryStart(categoryIndex, ticks.size(), dataArea, edge); x1 = getCategoryEnd(categoryIndex, ticks.size(), dataArea, edge); y0 = state.getCursor() + this.categoryLabelPositionOffset; y1 = y0 + state.getMax(); } else if (edge == RectangleEdge.LEFT) { y0 = getCategoryStart(categoryIndex, ticks.size(), dataArea, edge); y1 = getCategoryEnd(categoryIndex, ticks.size(), dataArea, edge); x1 = state.getCursor() - this.categoryLabelPositionOffset; x0 = x1 - state.getMax(); } else if (edge == RectangleEdge.RIGHT) { y0 = getCategoryStart(categoryIndex, ticks.size(), dataArea, edge); y1 = getCategoryEnd(categoryIndex, ticks.size(), dataArea, edge); x0 = state.getCursor() + this.categoryLabelPositionOffset; x1 = x0 - state.getMax(); } Rectangle2D area = new Rectangle2D.Double(x0, y0, (x1 - x0), (y1 - y0)); Point2D anchorPoint = RectangleAnchor.coordinates(area, position.getCategoryAnchor()); TextBlock block = tick.getLabel(); block.draw(g2, (float) anchorPoint.getX(), (float) anchorPoint.getY(), position.getLabelAnchor(), (float) anchorPoint.getX(), (float) anchorPoint.getY(), position.getAngle()); Shape bounds = block.calculateBounds(g2, (float) anchorPoint.getX(), (float) anchorPoint.getY(), position.getLabelAnchor(), (float) anchorPoint.getX(), (float) anchorPoint.getY(), position.getAngle()); if (plotState != null && plotState.getOwner() != null) { EntityCollection entities = plotState.getOwner() .getEntityCollection(); if (entities != null) { String tooltip = getCategoryLabelToolTip( tick.getCategory()); String url = getCategoryLabelURL(tick.getCategory()); entities.add(new CategoryLabelEntity(tick.getCategory(), bounds, tooltip, url)); } } categoryIndex++; } if (edge.equals(RectangleEdge.TOP)) { double h = state.getMax() + this.categoryLabelPositionOffset; state.cursorUp(h); } else if (edge.equals(RectangleEdge.BOTTOM)) { double h = state.getMax() + this.categoryLabelPositionOffset; state.cursorDown(h); } else if (edge == RectangleEdge.LEFT) { double w = state.getMax() + this.categoryLabelPositionOffset; state.cursorLeft(w); } else if (edge == RectangleEdge.RIGHT) { double w = state.getMax() + this.categoryLabelPositionOffset; state.cursorRight(w); } return state; } /** * Creates a temporary list of ticks that can be used when drawing the axis. * * @param g2 the graphics device (used to get font measurements). * @param state the axis state. * @param dataArea the area inside the axes. * @param edge the location of the axis. * * @return A list of ticks. */ @Override public List refreshTicks(Graphics2D g2, AxisState state, Rectangle2D dataArea, RectangleEdge edge) { List ticks = new java.util.ArrayList(); // sanity check for data area... if (dataArea.getHeight() <= 0.0 || dataArea.getWidth() < 0.0) { return ticks; } CategoryPlot plot = (CategoryPlot) getPlot(); List categories = plot.getCategoriesForAxis(this); double max = 0.0; if (categories != null) { CategoryLabelPosition position = this.categoryLabelPositions.getLabelPosition(edge); float r = this.maximumCategoryLabelWidthRatio; if (r <= 0.0) { r = position.getWidthRatio(); } float l; if (position.getWidthType() == CategoryLabelWidthType.CATEGORY) { l = (float) calculateCategorySize(categories.size(), dataArea, edge); } else { if (RectangleEdge.isLeftOrRight(edge)) { l = (float) dataArea.getWidth(); } else { l = (float) dataArea.getHeight(); } } int categoryIndex = 0; Iterator iterator = categories.iterator(); while (iterator.hasNext()) { Comparable category = (Comparable) iterator.next(); g2.setFont(getTickLabelFont(category)); TextBlock label = createLabel(category, l * r, edge, g2); if (edge == RectangleEdge.TOP || edge == RectangleEdge.BOTTOM) { max = Math.max(max, calculateTextBlockHeight(label, position, g2)); } else if (edge == RectangleEdge.LEFT || edge == RectangleEdge.RIGHT) { max = Math.max(max, calculateTextBlockWidth(label, position, g2)); } Tick tick = new CategoryTick(category, label, position.getLabelAnchor(), position.getRotationAnchor(), position.getAngle()); ticks.add(tick); categoryIndex = categoryIndex + 1; } } state.setMax(max); return ticks; } /** * Draws the tick marks. * * @param g2 the graphics target. * @param cursor the cursor position (an offset when drawing multiple axes) * @param dataArea the area for plotting the data. * @param edge the location of the axis. * @param state the axis state. * * @since 1.0.13 */ public void drawTickMarks(Graphics2D g2, double cursor, Rectangle2D dataArea, RectangleEdge edge, AxisState state) { Plot p = getPlot(); if (p == null) { return; } CategoryPlot plot = (CategoryPlot) p; double il = getTickMarkInsideLength(); double ol = getTickMarkOutsideLength(); Line2D line = new Line2D.Double(); List categories = plot.getCategoriesForAxis(this); g2.setPaint(getTickMarkPaint()); g2.setStroke(getTickMarkStroke()); if (edge.equals(RectangleEdge.TOP)) { Iterator iterator = categories.iterator(); while (iterator.hasNext()) { Comparable key = (Comparable) iterator.next(); double x = getCategoryMiddle(key, categories, dataArea, edge); line.setLine(x, cursor, x, cursor + il); g2.draw(line); line.setLine(x, cursor, x, cursor - ol); g2.draw(line); } state.cursorUp(ol); } else if (edge.equals(RectangleEdge.BOTTOM)) { Iterator iterator = categories.iterator(); while (iterator.hasNext()) { Comparable key = (Comparable) iterator.next(); double x = getCategoryMiddle(key, categories, dataArea, edge); line.setLine(x, cursor, x, cursor - il); g2.draw(line); line.setLine(x, cursor, x, cursor + ol); g2.draw(line); } state.cursorDown(ol); } else if (edge.equals(RectangleEdge.LEFT)) { Iterator iterator = categories.iterator(); while (iterator.hasNext()) { Comparable key = (Comparable) iterator.next(); double y = getCategoryMiddle(key, categories, dataArea, edge); line.setLine(cursor, y, cursor + il, y); g2.draw(line); line.setLine(cursor, y, cursor - ol, y); g2.draw(line); } state.cursorLeft(ol); } else if (edge.equals(RectangleEdge.RIGHT)) { Iterator iterator = categories.iterator(); while (iterator.hasNext()) { Comparable key = (Comparable) iterator.next(); double y = getCategoryMiddle(key, categories, dataArea, edge); line.setLine(cursor, y, cursor - il, y); g2.draw(line); line.setLine(cursor, y, cursor + ol, y); g2.draw(line); } state.cursorRight(ol); } } /** * Creates a label. * * @param category the category. * @param width the available width. * @param edge the edge on which the axis appears. * @param g2 the graphics device. * * @return A label. */ protected TextBlock createLabel(Comparable category, float width, RectangleEdge edge, Graphics2D g2) { TextBlock label = TextUtilities.createTextBlock(category.toString(), getTickLabelFont(category), getTickLabelPaint(category), width, this.maximumCategoryLabelLines, new G2TextMeasurer(g2)); return label; } /** * A utility method for determining the width of a text block. * * @param block the text block. * @param position the position. * @param g2 the graphics device. * * @return The width. */ protected double calculateTextBlockWidth(TextBlock block, CategoryLabelPosition position, Graphics2D g2) { RectangleInsets insets = getTickLabelInsets(); Size2D size = block.calculateDimensions(g2); Rectangle2D box = new Rectangle2D.Double(0.0, 0.0, size.getWidth(), size.getHeight()); Shape rotatedBox = ShapeUtilities.rotateShape(box, position.getAngle(), 0.0f, 0.0f); double w = rotatedBox.getBounds2D().getWidth() + insets.getLeft() + insets.getRight(); return w; } /** * A utility method for determining the height of a text block. * * @param block the text block. * @param position the label position. * @param g2 the graphics device. * * @return The height. */ protected double calculateTextBlockHeight(TextBlock block, CategoryLabelPosition position, Graphics2D g2) { RectangleInsets insets = getTickLabelInsets(); Size2D size = block.calculateDimensions(g2); Rectangle2D box = new Rectangle2D.Double(0.0, 0.0, size.getWidth(), size.getHeight()); Shape rotatedBox = ShapeUtilities.rotateShape(box, position.getAngle(), 0.0f, 0.0f); double h = rotatedBox.getBounds2D().getHeight() + insets.getTop() + insets.getBottom(); return h; } /** * Creates a clone of the axis. * * @return A clone. * * @throws CloneNotSupportedException if some component of the axis does * not support cloning. */ @Override public Object clone() throws CloneNotSupportedException { CategoryAxis clone = (CategoryAxis) super.clone(); clone.tickLabelFontMap = new HashMap(this.tickLabelFontMap); clone.tickLabelPaintMap = new HashMap(this.tickLabelPaintMap); clone.categoryLabelToolTips = new HashMap(this.categoryLabelToolTips); clone.categoryLabelURLs = new HashMap(this.categoryLabelToolTips); return clone; } /** * Tests this axis for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof CategoryAxis)) { return false; } if (!super.equals(obj)) { return false; } CategoryAxis that = (CategoryAxis) obj; if (that.lowerMargin != this.lowerMargin) { return false; } if (that.upperMargin != this.upperMargin) { return false; } if (that.categoryMargin != this.categoryMargin) { return false; } if (that.maximumCategoryLabelWidthRatio != this.maximumCategoryLabelWidthRatio) { return false; } if (that.categoryLabelPositionOffset != this.categoryLabelPositionOffset) { return false; } if (!ObjectUtilities.equal(that.categoryLabelPositions, this.categoryLabelPositions)) { return false; } if (!ObjectUtilities.equal(that.categoryLabelToolTips, this.categoryLabelToolTips)) { return false; } if (!ObjectUtilities.equal(this.categoryLabelURLs, that.categoryLabelURLs)) { return false; } if (!ObjectUtilities.equal(this.tickLabelFontMap, that.tickLabelFontMap)) { return false; } if (!equalPaintMaps(this.tickLabelPaintMap, that.tickLabelPaintMap)) { return false; } return true; } /** * Returns a hash code for this object. * * @return A hash code. */ @Override public int hashCode() { return super.hashCode(); } /** * 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(); writePaintMap(this.tickLabelPaintMap, 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.tickLabelPaintMap = readPaintMap(stream); } /** * Reads a <code>Map</code> of (<code>Comparable</code>, <code>Paint</code>) * elements from a stream. * * @param in the input stream. * * @return The map. * * @throws IOException * @throws ClassNotFoundException * * @see #writePaintMap(Map, ObjectOutputStream) */ private Map readPaintMap(ObjectInputStream in) throws IOException, ClassNotFoundException { boolean isNull = in.readBoolean(); if (isNull) { return null; } Map result = new HashMap(); int count = in.readInt(); for (int i = 0; i < count; i++) { Comparable category = (Comparable) in.readObject(); Paint paint = SerialUtilities.readPaint(in); result.put(category, paint); } return result; } /** * Writes a map of (<code>Comparable</code>, <code>Paint</code>) * elements to a stream. * * @param map the map (<code>null</code> permitted). * * @param out * @throws IOException * * @see #readPaintMap(ObjectInputStream) */ private void writePaintMap(Map map, ObjectOutputStream out) throws IOException { if (map == null) { out.writeBoolean(true); } else { out.writeBoolean(false); Set keys = map.keySet(); int count = keys.size(); out.writeInt(count); Iterator iterator = keys.iterator(); while (iterator.hasNext()) { Comparable key = (Comparable) iterator.next(); out.writeObject(key); SerialUtilities.writePaint((Paint) map.get(key), out); } } } /** * Tests two maps containing (<code>Comparable</code>, <code>Paint</code>) * elements for equality. * * @param map1 the first map (<code>null</code> not permitted). * @param map2 the second map (<code>null</code> not permitted). * * @return A boolean. */ private boolean equalPaintMaps(Map map1, Map map2) { if (map1.size() != map2.size()) { return false; } Set entries = map1.entrySet(); Iterator iterator = entries.iterator(); while (iterator.hasNext()) { Map.Entry entry = (Map.Entry) iterator.next(); Paint p1 = (Paint) entry.getValue(); Paint p2 = (Paint) map2.get(entry.getKey()); if (!PaintUtilities.equal(p1, p2)) { return false; } } return true; } /** * Draws the category labels and returns the updated axis state. * * @param g2 the graphics device (<code>null</code> not permitted). * @param dataArea the area inside the axes (<code>null</code> not * permitted). * @param edge the axis location (<code>null</code> not permitted). * @param state the axis state (<code>null</code> not permitted). * @param plotState collects information about the plot (<code>null</code> * permitted). * * @return The updated axis state (never <code>null</code>). * * @deprecated Use {@link #drawCategoryLabels(Graphics2D, Rectangle2D, * Rectangle2D, RectangleEdge, AxisState, PlotRenderingInfo)}. */ protected AxisState drawCategoryLabels(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge, AxisState state, PlotRenderingInfo plotState) { // this method is deprecated because we really need the plotArea // when drawing the labels - see bug 1277726 return drawCategoryLabels(g2, dataArea, dataArea, edge, state, plotState); } }
package mho.qbar.objects; import mho.qbar.iterableProviders.QBarExhaustiveProvider; import mho.qbar.iterableProviders.QBarIterableProvider; import mho.qbar.iterableProviders.QBarRandomProvider; import mho.wheels.iterables.RandomProvider; import mho.wheels.ordering.Ordering; import mho.wheels.structures.Pair; import java.math.BigInteger; import java.util.List; import java.util.Random; import static mho.qbar.objects.Polynomial.*; import static mho.wheels.iterables.IterableUtils.*; @SuppressWarnings({"ConstantConditions", "UnusedDeclaration"}) public class PolynomialDemos { private static final boolean USE_RANDOM = false; private static final String POLYNOMIAL_CHARS = "*+-0123456789^x"; private static int LIMIT; private static QBarIterableProvider P; private static void initialize() { if (USE_RANDOM) { P = new QBarRandomProvider(new Random(0x6af477d9a7e54fcaL)); LIMIT = 1000; } else { P = QBarExhaustiveProvider.INSTANCE; LIMIT = 10000; } } public static void demoIterator() { initialize(); for (Polynomial p : take(LIMIT, P.polynomials())) { System.out.println("toList(" + p + ") = " + toList(p)); } } public static void demoApply_BigInteger() { initialize(); for (Pair<Polynomial, BigInteger> p : take(LIMIT, P.pairs(P.polynomials(), P.bigIntegers()))) { System.out.println(p.a + " at " + p.b + " = " + p.a.apply(p.b)); } } public static void demoApply_Rational() { initialize(); for (Pair<Polynomial, Rational> p : take(LIMIT, P.pairs(P.polynomials(), P.rationals()))) { System.out.println(p.a + " at " + p.b + " = " + p.a.apply(p.b)); } } public static void demoToRationalPolynomial() { initialize(); for (Polynomial p : take(LIMIT, P.polynomials())) { System.out.println("toRationalPolynomial(" + p + ") = " + p.toRationalPolynomial()); } } public static void demoCoefficient() { initialize(); Iterable<Pair<Polynomial, Integer>> ps; if (P instanceof QBarExhaustiveProvider) { ps = ((QBarExhaustiveProvider) P).pairsLogarithmicOrder(P.polynomials(), P.naturalIntegers()); } else { ps = P.pairs(P.polynomials(), ((RandomProvider) P).naturalIntegersGeometric(10)); } for (Pair<Polynomial, Integer> p : take(LIMIT, ps)) { System.out.println("coefficient(" + p.a + ", " + p.b + ") = " + p.a.coefficient(p.b)); } } public static void demoOf_List_BigInteger() { initialize(); for (List<BigInteger> is : take(LIMIT, P.lists(P.bigIntegers()))) { String listString = tail(init(is.toString())); System.out.println("of(" + listString + ") = " + of(is)); } } public static void demoOf_BigInteger() { initialize(); for (BigInteger i : take(LIMIT, P.bigIntegers())) { System.out.println("of(" + i + ") = " + of(i)); } } public static void demoOf_BigInteger_int() { initialize(); Iterable<Pair<BigInteger, Integer>> ps; if (P instanceof QBarExhaustiveProvider) { ps = ((QBarExhaustiveProvider) P).pairsLogarithmicOrder(P.bigIntegers(), P.naturalIntegers()); } else { ps = P.pairs(P.bigIntegers(), ((RandomProvider) P).naturalIntegersGeometric(20)); } for (Pair<BigInteger, Integer> p : take(LIMIT, ps)) { System.out.println("of(" + p.a + ", " + p.b + ") = " + of(p.a, p.b)); } } public static void demoDegree() { initialize(); for (Polynomial p : take(LIMIT, P.polynomials())) { System.out.println("degree(" + p + ") = " + p.degree()); } } public static void demoLeading() { initialize(); for (Polynomial p : take(LIMIT, P.polynomials())) { System.out.println("leading(" + p + ") = " + p.leading()); } } public static void demoAdd() { initialize(); for (Pair<Polynomial, Polynomial> p : take(LIMIT, P.pairs(P.polynomials()))) { System.out.println("(" + p.a + ") + (" + p.b + ") = " + p.a.add(p.b)); } } public static void demoNegate() { initialize(); for (Polynomial p : take(LIMIT, P.polynomials())) { System.out.println("-(" + p + ") = " + p.negate()); } } public static void demoAbs() { initialize(); for (Polynomial p : take(LIMIT, P.polynomials())) { System.out.println("|" + p + "| = " + p.abs()); } } public static void demoSignum() { initialize(); for (Polynomial p : take(LIMIT, P.polynomials())) { System.out.println("sgn(" + p + ") = " + p.signum()); } } public static void demoSubtract() { initialize(); for (Pair<Polynomial, Polynomial> p : take(LIMIT, P.pairs(P.polynomials()))) { System.out.println("(" + p.a + ") - (" + p.b + ") = " + p.a.subtract(p.b)); } } public static void demoMultiply_Polynomial() { initialize(); for (Pair<Polynomial, Polynomial> p : take(LIMIT, P.pairs(P.polynomials()))) { System.out.println("(" + p.a + ") * (" + p.b + ") = " + p.a.multiply(p.b)); } } public static void demoMultiply_BigInteger() { initialize(); for (Pair<Polynomial, BigInteger> p : take(LIMIT, P.pairs(P.polynomials(), P.bigIntegers()))) { System.out.println("(" + p.a + ") * " + p.b + " = " + p.a.multiply(p.b)); } } public static void demoMultiply_int() { initialize(); for (Pair<Polynomial, Integer> p : take(LIMIT, P.pairs(P.polynomials(), P.integers()))) { System.out.println("(" + p.a + ") * " + p.b + " = " + p.a.multiply(p.b)); } } public static void demoShiftLeft() { initialize(); Iterable<Integer> is; if (P instanceof QBarExhaustiveProvider) { is = P.naturalIntegers(); } else { is = ((QBarRandomProvider) P).naturalIntegersGeometric(50); } for (Pair<Polynomial, Integer> p : take(LIMIT, P.pairs(P.polynomials(), is))) { System.out.println(p.a + " << " + p.b + " = " + p.a.shiftLeft(p.b)); } } public static void demoEquals_Polynomial() { initialize(); for (Pair<Polynomial, Polynomial> p : take(LIMIT, P.pairs(P.polynomials()))) { System.out.println(p.a + (p.a.equals(p.b) ? " = " : " ≠ ") + p.b); } } public static void demoEquals_null() { initialize(); for (Polynomial p : take(LIMIT, P.polynomials())) { //noinspection ObjectEqualsNull System.out.println(p + (p.equals(null) ? " = " : " ≠ ") + null); } } public static void demoHashCode() { initialize(); for (Polynomial p : take(LIMIT, P.polynomials())) { System.out.println("hashCode(" + p + ") = " + p.hashCode()); } } public static void demoCompareTo() { initialize(); for (Pair<Polynomial, Polynomial> p : take(LIMIT, P.pairs(P.polynomials()))) { System.out.println(p.a + " " + Ordering.compare(p.a, p.b).toChar() + " " + p.b); } } public static void demoRead() { initialize(); for (String s : take(LIMIT, P.strings())) { System.out.println("read(" + s + ") = " + read(s)); } } public static void demoRead_targeted() { initialize(); Iterable<Character> cs; if (P instanceof QBarExhaustiveProvider) { cs = fromString(POLYNOMIAL_CHARS); } else { cs = ((QBarRandomProvider) P).uniformSample(POLYNOMIAL_CHARS); } for (String s : take(LIMIT, P.strings(cs))) { System.out.println("read(" + s + ") = " + read(s)); } } private static void demoFindIn() { initialize(); for (String s : take(LIMIT, P.strings())) { System.out.println("findIn(" + s + ") = " + findIn(s)); } } public static void demoFindIn_targeted() { initialize(); Iterable<Character> cs; if (P instanceof QBarExhaustiveProvider) { cs = fromString(POLYNOMIAL_CHARS); } else { cs = ((RandomProvider) P).uniformSample(POLYNOMIAL_CHARS); } for (String s : take(LIMIT, P.strings(cs))) { System.out.println("findIn(" + s + ") = " + findIn(s)); } } public static void demoToString() { initialize(); for (Polynomial p : take(LIMIT, P.polynomials())) { System.out.println(p); } } }
package com.continuuity.common.twill; /** * InMemory Reactor Service Management class. */ public class InMemoryReactorServiceManager implements ReactorServiceManager { @Override public int getRequestedInstances() { return 1; } @Override public int getProvisionedInstances() { return 1; } @Override public boolean setInstances(int instanceCount) { return false; } @Override public int getMinInstances() { return 1; } @Override public int getMaxInstances() { return 1; } @Override public boolean isLogAvailable() { return true; } @Override public boolean canCheckStatus() { return true; } @Override public boolean isServiceAvailable() { return true; } @Override public boolean isServiceEnabled() { return true; } }
package org.amc.game.chess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.*; import org.amc.game.chess.AbstractChessGame.GameState; import org.junit.*; import java.util.List; public class ChessGameTest { private ChessGameFixture chessGameFixture; private ChessBoardUtilities cbUtils; private String endLocation; private String startLocation; private ChessGamePlayer whitePlayer; private ChessGamePlayer blackPlayer; @Before public void setUp() throws Exception { chessGameFixture = new ChessGameFixture(); whitePlayer = chessGameFixture.getWhitePlayer(); blackPlayer = chessGameFixture.getBlackPlayer(); chessGameFixture.putPieceOnBoardAt(KingPiece.getKingPiece(Colour.WHITE), StartingSquare.WHITE_KING.getLocation()); chessGameFixture.putPieceOnBoardAt(KingPiece.getKingPiece(Colour.BLACK), StartingSquare.BLACK_KING.getLocation()); startLocation = "A8"; endLocation = "B7"; cbUtils = new ChessBoardUtilities(chessGameFixture.getBoard()); } @Test public void testChangePlayer() { assertEquals(whitePlayer, chessGameFixture.getCurrentPlayer()); chessGameFixture.changePlayer(); assertEquals(blackPlayer, chessGameFixture.getCurrentPlayer()); chessGameFixture.changePlayer(); assertEquals(whitePlayer, chessGameFixture.getCurrentPlayer()); } @Test(expected = IllegalMoveException.class) public void testMoveWithAnEmptySquare() throws IllegalMoveException { chessGameFixture.move(whitePlayer, cbUtils.createMove(startLocation, endLocation)); } @Test(expected = IllegalMoveException.class) public void testPlayerCantMoveOtherPlayersPiece() throws IllegalMoveException { BishopPiece bishop = BishopPiece.getBishopPiece(Colour.WHITE); cbUtils.addChessPieceToBoard(bishop, startLocation); chessGameFixture.move(blackPlayer, cbUtils.createMove(startLocation, "B7")); } @Test public void testPlayerCanMoveTheirOwnPiece() throws IllegalMoveException { BishopPiece bishop = BishopPiece.getBishopPiece(Colour.WHITE); cbUtils.addChessPieceToBoard(bishop, startLocation); chessGameFixture.move(whitePlayer, cbUtils.createMove(startLocation, endLocation)); assertEquals(bishop.moved(), cbUtils.getPieceOnBoard(endLocation)); assertNull(cbUtils.getPieceOnBoard(startLocation)); } @Test public void doesGameRuleApply() { RookPiece rook = RookPiece.getRookPiece(Colour.WHITE); final String rookStartPosition = "H1"; Move move = cbUtils.createMove(StartingSquare.WHITE_KING.getLocation().asString(), "G1"); cbUtils.addChessPieceToBoard(rook, rookStartPosition); assertTrue(chessGameFixture.doesAGameRuleApply(chessGameFixture, move)); } @Test public void doesNotGameRuleApply() { RookPiece rook = RookPiece.getRookPiece(Colour.WHITE); final String rookStartPosition = "H1"; Move move = cbUtils.createMove(StartingSquare.WHITE_KING.getLocation().asString(), "F1"); cbUtils.addChessPieceToBoard(rook, rookStartPosition); assertFalse(chessGameFixture.doesAGameRuleApply(chessGameFixture, move)); } @Test public void gameRuleApplied() throws IllegalMoveException { RookPiece rook = RookPiece.getRookPiece(Colour.WHITE); String rookStartPosition = "H1"; Move move = cbUtils.createMove(StartingSquare.WHITE_KING.getLocation().asString(), "F1"); cbUtils.addChessPieceToBoard(rook, rookStartPosition); chessGameFixture.move(whitePlayer, move); } @Test public void testMovesAreSaved() throws IllegalMoveException { BishopPiece bishop = BishopPiece.getBishopPiece(Colour.BLACK); cbUtils.addChessPieceToBoard(bishop, startLocation); chessGameFixture.changePlayer(); chessGameFixture.move(blackPlayer, cbUtils.createMove(startLocation, endLocation)); Move lastMove = chessGameFixture.getTheLastMove(); assertEquals(lastMove.getStart().asString(), startLocation); assertEquals(lastMove.getEnd().asString(), endLocation); } @Test public void getEmptyMove() { Move move = chessGameFixture.getTheLastMove(); assertTrue(move instanceof EmptyMove); } @Test public void cloneConstuctorMoveListCopyTest() { chessGameFixture.initialise(); ChessGame clone = new ChessGame(chessGameFixture.getChessGame()); assertTrue(chessGameFixture.getTheLastMove().equals(clone.getTheLastMove())); assertEquals(GameState.RUNNING, clone.getGameState()); } @Test public void cloneConstuctorRuleListCopyTest() { chessGameFixture.initialise(); ChessGame clone = new ChessGame(chessGameFixture.getChessGame()); clone.addChessMoveRule(EnPassantRule.getInstance()); assertEquals(3, chessGameFixture.getChessGame().getChessMoveRules().size()); assertEquals(4, clone.getChessMoveRules().size()); assertTrue(clone.getChessMoveRules().contains(EnPassantRule.getInstance())); } @Test public void testCopyConstructorForEmptyConstructor() { ChessGame game = new ChessGame(); game.addChessMoveRule(EnPassantRule.getInstance()); ChessGame copy = new ChessGame(game); testForChessRules(copy); assertEquals(game.getBlackPlayer(), copy.getBlackPlayer()); assertEquals(game.getWhitePlayer(), copy.getWhitePlayer()); assertNotNull(copy.getChessBoard()); assertFalse(game.getChessBoard() == copy.getChessBoard()); ChessBoardUtilities.compareBoards(game.getChessBoard(), copy.getChessBoard()); assertEquals(GameState.NEW, copy.getGameState()); } private void testForChessRules(ChessGame game) { List<ChessMoveRule> rules = game.getChessMoveRules(); assertFalse(rules.isEmpty()); assertEquals(1, rules.size()); assertTrue(rules.contains(EnPassantRule.getInstance())); } @Test(expected = IllegalMoveException.class) public void notPlayersTurn() throws IllegalMoveException { Move move = new Move(StartingSquare.BLACK_KING.getLocation(), new Location("E7")); chessGameFixture.move(blackPlayer, move); assertEquals(whitePlayer, chessGameFixture.getCurrentPlayer()); } }
package org.owasp.esapi.codecs; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; public class CodecTest extends TestCase { private static final char[] EMPTY_CHAR_ARRAY = new char[0]; private static final Character LESS_THAN = Character.valueOf('<'); private static final Character SINGLE_QUOTE = Character.valueOf('\''); private HTMLEntityCodec htmlCodec = new HTMLEntityCodec(); private PercentCodec percentCodec = new PercentCodec(); private JavaScriptCodec javaScriptCodec = new JavaScriptCodec(); private VBScriptCodec vbScriptCodec = new VBScriptCodec(); private CSSCodec cssCodec = new CSSCodec(); private MySQLCodec mySQLCodecANSI = new MySQLCodec( MySQLCodec.ANSI_MODE ); private MySQLCodec mySQLCodecStandard = new MySQLCodec( MySQLCodec.MYSQL_MODE ); private OracleCodec oracleCodec = new OracleCodec(); private UnixCodec unixCodec = new UnixCodec(); private WindowsCodec windowsCodec = new WindowsCodec(); /** * Instantiates a new access reference map test. * * @param testName * the test name */ public CodecTest(String testName) { super(testName); } /** * {@inheritDoc} * @throws Exception */ protected void setUp() throws Exception { // none } /** * {@inheritDoc} * @throws Exception */ protected void tearDown() throws Exception { // none } /** * Suite. * * @return the test */ public static Test suite() { TestSuite suite = new TestSuite(CodecTest.class); return suite; } public void testHtmlEncode() { assertEquals( "test", htmlCodec.encode( EMPTY_CHAR_ARRAY, "test") ); } public void testPercentEncode() { assertEquals( "%3c", percentCodec.encode(EMPTY_CHAR_ARRAY, "<") ); } public void testJavaScriptEncode() { assertEquals( "\\x3C", javaScriptCodec.encode(EMPTY_CHAR_ARRAY, "<") ); } public void testVBScriptEncode() { assertEquals( "chrw(60)", vbScriptCodec.encode(EMPTY_CHAR_ARRAY, "<") ); } public void testCSSEncode() { assertEquals( "\\3c ", cssCodec.encode(EMPTY_CHAR_ARRAY, "<") ); } public void testMySQLANSCIEncode() { assertEquals( "\'\'", mySQLCodecANSI.encode(EMPTY_CHAR_ARRAY, "\'") ); } public void testMySQLStandardEncode() { assertEquals( "\\<", mySQLCodecStandard.encode(EMPTY_CHAR_ARRAY, "<") ); } public void testOracleEncode() { assertEquals( "\'\'", oracleCodec.encode(EMPTY_CHAR_ARRAY, "\'") ); } public void testUnixEncode() { assertEquals( "\\<", unixCodec.encode(EMPTY_CHAR_ARRAY, "<") ); } public void testWindowsEncode() { assertEquals( "^<", windowsCodec.encode(EMPTY_CHAR_ARRAY, "<") ); } public void testHtmlEncodeChar() { assertEquals( "&lt;", htmlCodec.encodeCharacter(EMPTY_CHAR_ARRAY, LESS_THAN) ); } public void testHtmlEncodeChar0x100() { char in = 0x100; String inStr = Character.toString(in); String expected = "&#x100;"; String result; result = htmlCodec.encodeCharacter(EMPTY_CHAR_ARRAY, in); // this should be escaped assertFalse(inStr.equals(result)); // UTF-8 encoded and then percent escaped assertEquals(expected, result); } public void testHtmlEncodeStr0x100() { char in = 0x100; String inStr = Character.toString(in); String expected = "&#x100;"; String result; result = htmlCodec.encode(EMPTY_CHAR_ARRAY, inStr); // this should be escaped assertFalse(inStr.equals(result)); // UTF-8 encoded and then percent escaped assertEquals(expected, result); } public void testPercentEncodeChar() { assertEquals( "%3c", percentCodec.encodeCharacter(EMPTY_CHAR_ARRAY, LESS_THAN) ); } public void testPercentEncodeChar0x100() { char in = 0x100; String inStr = Character.toString(in); String expected = "%C4%80"; String result; result = percentCodec.encodeCharacter(EMPTY_CHAR_ARRAY, in); // this should be escaped assertFalse(inStr.equals(result)); // UTF-8 encoded and then percent escaped assertEquals(expected, result); } public void testPercentEncodeStr0x100() { char in = 0x100; String inStr = Character.toString(in); String expected = "%C4%80"; String result; result = percentCodec.encode(EMPTY_CHAR_ARRAY, inStr); // this should be escaped assertFalse(inStr.equals(result)); // UTF-8 encoded and then percent escaped assertEquals(expected, result); } public void testJavaScriptEncodeChar() { assertEquals( "\\x3C", javaScriptCodec.encodeCharacter(EMPTY_CHAR_ARRAY, LESS_THAN) ); } public void testJavaScriptEncodeChar0x100() { char in = 0x100; String inStr = Character.toString(in); String expected = "\\u0100"; String result; result = javaScriptCodec.encodeCharacter(EMPTY_CHAR_ARRAY, in); // this should be escaped assertFalse(inStr.equals(result)); assertEquals(expected,result); } public void testJavaScriptEncodeStr0x100() { char in = 0x100; String inStr = Character.toString(in); String expected = "\\u0100"; String result; result = javaScriptCodec.encode(EMPTY_CHAR_ARRAY, inStr); // this should be escaped assertFalse(inStr.equals(result)); assertEquals(expected,result); } public void testVBScriptEncodeChar() { assertEquals( "chrw(60)", vbScriptCodec.encodeCharacter(EMPTY_CHAR_ARRAY, LESS_THAN) ); } public void testVBScriptEncodeChar0x100() { char in = 0x100; String inStr = Character.toString(in); // FIXME I don't know vb... // String expected = "\\u0100"; String result; result = vbScriptCodec.encodeCharacter(EMPTY_CHAR_ARRAY, in); // this should be escaped assertFalse(inStr.equals(result)); //assertEquals(expected,result); } public void testVBScriptEncodeStr0x100() { char in = 0x100; String inStr = Character.toString(in); // FIXME I don't know vb... // String expected = "chrw(0x100)"; String result; result = vbScriptCodec.encode(EMPTY_CHAR_ARRAY, inStr); // this should be escaped assertFalse(inStr.equals(result)); // assertEquals(expected,result); } public void testCSSEncodeChar() { assertEquals( "\\3c ", cssCodec.encodeCharacter(EMPTY_CHAR_ARRAY, LESS_THAN) ); } public void testCSSEncodeChar0x100() { char in = 0x100; String inStr = Character.toString(in); String expected = "\\u100"; String result; result = cssCodec.encodeCharacter(EMPTY_CHAR_ARRAY, in); // this should be escaped assertFalse(inStr.equals(result)); assertEquals(expected,result); } public void testCSSEncodeStr0x100() { char in = 0x100; String inStr = Character.toString(in); String expected = "\\u100"; String result; result = cssCodec.encode(EMPTY_CHAR_ARRAY, inStr); // this should be escaped assertFalse(inStr.equals(result)); assertEquals(expected,result); } public void testMySQLANSIEncodeChar() { assertEquals( "\'\'", mySQLCodecANSI.encodeCharacter(EMPTY_CHAR_ARRAY, SINGLE_QUOTE)); } public void testMySQLStandardEncodeChar0x100() { char in = 0x100; String inStr = Character.toString(in); String expected = "\\" + in; String result; result = mySQLCodecStandard.encodeCharacter(EMPTY_CHAR_ARRAY, in); // this should be escaped assertFalse(inStr.equals(result)); assertEquals(expected,result); } public void testMySQLStandardEncodeStr0x100() { char in = 0x100; String inStr = Character.toString(in); String expected = "\\" + in; String result; result = mySQLCodecStandard.encode(EMPTY_CHAR_ARRAY, inStr); // this should be escaped assertFalse(inStr.equals(result)); assertEquals(expected,result); } public void testMySQLStandardEncodeChar() { assertEquals( "\\<", mySQLCodecStandard.encodeCharacter(EMPTY_CHAR_ARRAY, LESS_THAN) ); } public void testOracleEncodeChar() { assertEquals( "\'\'", oracleCodec.encodeCharacter(EMPTY_CHAR_ARRAY, SINGLE_QUOTE) ); } public void testUnixEncodeChar() { assertEquals( "\\<", unixCodec.encodeCharacter(EMPTY_CHAR_ARRAY, LESS_THAN) ); } public void testUnixEncodeChar0x100() { char in = 0x100; String inStr = Character.toString(in); String expected = "\\" + in; String result; result = unixCodec.encodeCharacter(EMPTY_CHAR_ARRAY, in); // this should be escaped assertFalse(inStr.equals(result)); assertEquals(expected,result); } public void testUnixEncodeStr0x100() { char in = 0x100; String inStr = Character.toString(in); String expected = "\\" + in; String result; result = unixCodec.encode(EMPTY_CHAR_ARRAY, inStr); // this should be escaped assertFalse(inStr.equals(result)); assertEquals(expected,result); } public void testWindowsEncodeChar() { assertEquals( "^<", windowsCodec.encodeCharacter(EMPTY_CHAR_ARRAY, LESS_THAN) ); } public void testWindowsEncodeChar0x100() { char in = 0x100; String inStr = Character.toString(in); String expected = "^" + in; String result; result = windowsCodec.encodeCharacter(EMPTY_CHAR_ARRAY, in); // this should be escaped assertFalse(inStr.equals(result)); assertEquals(expected,result); } public void testWindowsEncodeStr0x100() { char in = 0x100; String inStr = Character.toString(in); String expected = "^" + in; String result; result = windowsCodec.encode(EMPTY_CHAR_ARRAY, inStr); // this should be escaped assertFalse(inStr.equals(result)); assertEquals(expected,result); } public void testHtmlDecodeDecimalEntities() { assertEquals( "test!", htmlCodec.decode("&#116;&#101;&#115;&#116;!") ); } public void testHtmlDecodeHexEntitites() { assertEquals( "test!", htmlCodec.decode("&#x74;&#x65;&#x73;&#x74;!") ); } public void testHtmlDecodeInvalidAttribute() { assertEquals( "&jeff;", htmlCodec.decode("&jeff;") ); } public void testHtmlDecodeAmp() { assertEquals("&", htmlCodec.decode("&amp;")); assertEquals("&X", htmlCodec.decode("&amp;X")); assertEquals("&", htmlCodec.decode("&amp")); assertEquals("&X", htmlCodec.decode("&ampX")); } public void testHtmlDecodeLt() { assertEquals("<", htmlCodec.decode("&lt;")); assertEquals("<X", htmlCodec.decode("&lt;X")); assertEquals("<", htmlCodec.decode("&lt")); assertEquals("<X", htmlCodec.decode("&ltX")); } public void testHtmlDecodeSup1() { assertEquals("\u00B9", htmlCodec.decode("&sup1;")); assertEquals("\u00B9X", htmlCodec.decode("&sup1;X")); assertEquals("\u00B9", htmlCodec.decode("&sup1")); assertEquals("\u00B9X", htmlCodec.decode("&sup1X")); } public void testHtmlDecodeSup2() { assertEquals("\u00B2", htmlCodec.decode("&sup2;")); assertEquals("\u00B2X", htmlCodec.decode("&sup2;X")); assertEquals("\u00B2", htmlCodec.decode("&sup2")); assertEquals("\u00B2X", htmlCodec.decode("&sup2X")); } public void testHtmlDecodeSup3() { assertEquals("\u00B3", htmlCodec.decode("&sup3;")); assertEquals("\u00B3X", htmlCodec.decode("&sup3;X")); assertEquals("\u00B3", htmlCodec.decode("&sup3")); assertEquals("\u00B3X", htmlCodec.decode("&sup3X")); } public void testHtmlDecodeSup() { assertEquals("\u2283", htmlCodec.decode("&sup;")); assertEquals("\u2283X", htmlCodec.decode("&sup;X")); assertEquals("\u2283", htmlCodec.decode("&sup")); assertEquals("\u2283X", htmlCodec.decode("&supX")); } public void testHtmlDecodeSupe() { assertEquals("\u2287", htmlCodec.decode("&supe;")); assertEquals("\u2287X", htmlCodec.decode("&supe;X")); assertEquals("\u2287", htmlCodec.decode("&supe")); assertEquals("\u2287X", htmlCodec.decode("&supeX")); } public void testHtmlDecodePi() { assertEquals("\u03C0", htmlCodec.decode("&pi;")); assertEquals("\u03C0X", htmlCodec.decode("&pi;X")); assertEquals("\u03C0", htmlCodec.decode("&pi")); assertEquals("\u03C0X", htmlCodec.decode("&piX")); } public void testHtmlDecodePiv() { assertEquals("\u03D6", htmlCodec.decode("&piv;")); assertEquals("\u03D6X", htmlCodec.decode("&piv;X")); assertEquals("\u03D6", htmlCodec.decode("&piv")); assertEquals("\u03D6X", htmlCodec.decode("&pivX")); } public void testHtmlDecodeTheta() { assertEquals("\u03B8", htmlCodec.decode("&theta;")); assertEquals("\u03B8X", htmlCodec.decode("&theta;X")); assertEquals("\u03B8", htmlCodec.decode("&theta")); assertEquals("\u03B8X", htmlCodec.decode("&thetaX")); } public void testHtmlDecodeThetasym() { assertEquals("\u03D1", htmlCodec.decode("&thetasym;")); assertEquals("\u03D1X", htmlCodec.decode("&thetasym;X")); assertEquals("\u03D1", htmlCodec.decode("&thetasym")); assertEquals("\u03D1X", htmlCodec.decode("&thetasymX")); } public void testPercentDecode() { assertEquals( "<", percentCodec.decode("%3c") ); } public void testJavaScriptDecodeBackSlashHex() { assertEquals( "<", javaScriptCodec.decode("\\x3c") ); } public void testVBScriptDecode() { assertEquals( "<", vbScriptCodec.decode("\"<") ); } public void testCSSDecode() { assertEquals( "<", cssCodec.decode("\\<") ); } public void testMySQLANSIDecode() { assertEquals( "\'", mySQLCodecANSI.decode("\'\'") ); } public void testMySQLStandardDecode() { assertEquals( "<", mySQLCodecStandard.decode("\\<") ); } public void testOracleDecode() { assertEquals( "\'", oracleCodec.decode("\'\'") ); } public void testUnixDecode() { assertEquals( "<", unixCodec.decode("\\<") ); } public void testWindowsDecode() { assertEquals( "<", windowsCodec.decode("^<") ); } public void testHtmlDecodeCharLessThan() { assertEquals( LESS_THAN, htmlCodec.decodeCharacter(new PushbackString("&lt;")) ); } public void testPercentDecodeChar() { assertEquals( LESS_THAN, percentCodec.decodeCharacter(new PushbackString("%3c") )); } public void testJavaScriptDecodeCharBackSlashHex() { assertEquals( LESS_THAN, javaScriptCodec.decodeCharacter(new PushbackString("\\x3c") )); } public void testVBScriptDecodeChar() { assertEquals( LESS_THAN, vbScriptCodec.decodeCharacter(new PushbackString("\"<") )); } public void testCSSDecodeCharBackSlashHex() { assertEquals( LESS_THAN, cssCodec.decodeCharacter(new PushbackString("\\3c") )); } public void testMySQLANSIDecodCharQuoteQuote() { assertEquals( SINGLE_QUOTE, mySQLCodecANSI.decodeCharacter(new PushbackString("\'\'") )); } public void testMySQLStandardDecodeCharBackSlashLessThan() { assertEquals( LESS_THAN, mySQLCodecStandard.decodeCharacter(new PushbackString("\\<") )); } public void testOracleDecodeCharBackSlashLessThan() { assertEquals( SINGLE_QUOTE, oracleCodec.decodeCharacter(new PushbackString("\'\'") )); } public void testUnixDecodeCharBackSlashLessThan() { assertEquals( LESS_THAN, unixCodec.decodeCharacter(new PushbackString("\\<") )); } public void testWindowsDecodeCharCarrotLessThan() { assertEquals( LESS_THAN, windowsCodec.decodeCharacter(new PushbackString("^<") )); } }
package org.unidle.feature.step; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import org.openqa.selenium.By; import org.openqa.selenium.Cookie; import org.openqa.selenium.WebDriver; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.web.WebAppConfiguration; import org.unidle.feature.config.FeatureConfig; import java.net.URL; import static org.fest.assertions.Assertions.assertThat; @ContextConfiguration(classes = FeatureConfig.class) @WebAppConfiguration public class StepDefs { @Autowired private URL baseUrl; @Autowired private WebDriver webDriver; @Given("^a user from \"([^\"]*)\" with the IP \"([^\"]*)\"$") public void a_user_from_with_the_IP(final String location, final String address) throws Throwable { webDriver.manage().addCookie(new Cookie("location", location)); webDriver.manage().addCookie(new Cookie("address", address)); } @Then("^the \"([^\"]*)\" element should contain the text \"([^\"]*)\"$") public void the_element_should_contain_the_text(final String element, final String text) throws Throwable { final String elementText = webDriver.findElement(By.id(element)).getText(); assertThat(elementText).contains(text); } @When("^they access the \"([^\"]*)\" page$") public void they_access_the_page(final String path) throws Throwable { webDriver.navigate().to(baseUrl + path); } }
package ui.issuepanel.comments; import java.lang.ref.WeakReference; import ui.StatusBar; import util.DialogMessage; import handler.IssueDetailsContentHandler; import model.TurboIssue; import javafx.application.Platform; import javafx.concurrent.Task; import javafx.concurrent.WorkerStateEvent; import javafx.event.EventHandler; import javafx.scene.control.ProgressIndicator; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.layout.Priority; import javafx.scene.layout.VBox; public class IssueDetailsDisplay extends VBox { public enum DisplayType{ COMMENTS, LOG } private TabPane detailsTab; private IssueDetailsContentHandler contentHandler; private TurboIssue issue; private int loadFailCount = 0; DetailsPanel commentsDisplay; DetailsPanel issueLogDisplay; Thread backgroundThread; public IssueDetailsDisplay(TurboIssue issue){ this.issue = issue; setupDetailsContents(); setupDisplay(); } private void setupDetailsContents(){ contentHandler = new IssueDetailsContentHandler(issue); } private void setupDetailsTab(){ this.detailsTab = new TabPane(); Tab commentsTab = createCommentsTab(); Tab logTab = createChangeLogTab(); detailsTab.getTabs().addAll(commentsTab, logTab); } private void setupDisplay(){ setupDetailsTab(); this.getChildren().add(detailsTab); } public void show(){ if(issue == null || issue.getId() <= 0){ return; } Task<Boolean> bgTask = new Task<Boolean>(){ @Override protected Boolean call() throws Exception { contentHandler.startContentUpdate(); return true; } }; WeakReference<IssueDetailsDisplay> selfRef = new WeakReference<>(this); bgTask.setOnSucceeded(new EventHandler<WorkerStateEvent>() { @Override public void handle(WorkerStateEvent t) { IssueDetailsDisplay self = selfRef.get(); if(self != null){ self.scrollDisplayToBottom(); self.loadFailCount = 0; } } }); bgTask.setOnFailed(new EventHandler<WorkerStateEvent>() { @Override public void handle(WorkerStateEvent t) { IssueDetailsDisplay self = selfRef.get(); if(self != null){ self.loadFailCount += 1; if(loadFailCount <= 3){ self.show(); }else{ //Notify user of load failure and reset count loadFailCount = 0; StatusBar.displayMessage("An error occured while loading the issue's comments. Comments partially loaded"); } } } }); DialogMessage.showProgressDialog(bgTask, "Loading Issue Comments..."); backgroundThread = new Thread(bgTask); backgroundThread.start(); } private void scrollDisplayToBottom(){ Platform.runLater(new Runnable() { @Override public void run() { commentsDisplay.scrollToBottom(); issueLogDisplay.scrollToBottom(); } }); } public void hide(){ contentHandler.stopContentUpdate(); } public void cleanup(){ contentHandler.stopContentUpdate(); } private DetailsPanel createTabContentsDisplay(DisplayType type){ return new DetailsPanel(issue, contentHandler, type); } private Tab createCommentsTab(){ Tab comments = new Tab(); comments.setText("C"); comments.setClosable(false); commentsDisplay = createTabContentsDisplay(DisplayType.COMMENTS); VBox.setVgrow(commentsDisplay, Priority.ALWAYS); comments.setContent(commentsDisplay); return comments; } private Tab createChangeLogTab(){ Tab log = new Tab(); log.setText("Log"); log.setClosable(false); issueLogDisplay = createTabContentsDisplay(DisplayType.LOG); log.setContent(issueLogDisplay); return log; } }
package uk.ac.brighton.ci360.bigarrow.places; import java.io.Serializable; import java.util.LinkedHashMap; import uk.ac.brighton.ci360.bigarrow.classes.Utils; import com.google.android.gms.maps.model.LatLng; import com.google.api.client.util.Key; /** * Implement this class from "Serializable" So that you can pass this class * Object to another using Intents Otherwise you can't pass to another actitivy * */ public class Place implements Serializable { private static final long serialVersionUID = -1518642766553991067L; public final static String NO_RESULT = "NO_RESULT"; /** * Details about this place we're interested in to show * on place detail activity. The code is dynamic, only * need to add link between enum and actual field in the * getDetails() method */ public enum Detail { NAME, ADDRESS, PHONE, LOCATION, RATING, OPENING_HOURS }; /** * Careful if accessing fields directly * Any of the keys below can be null * It is advised that you use getDetails() instead */ @Key public String id; @Key public String name; @Key public String reference; @Key public String icon; @Key public String vicinity; @Key public Photo[] photos; @Key public Geometry geometry; @Key public double rating; @Key public OpeningHours opening_hours; @Key public String formatted_address; @Key public String formatted_phone_number; /** * The returned hashmap contains all details * we need to display on the place detail activity * The key is stringified Detail enum, value is string representation of this detail * It is advised to declare the map as "final" where you plan to use it * as it is only a very convenient data wrapper * Since it's linked, using keySet() will return keys in the order they were put * The map is safe to use as all of the values ARE NOT null, * so there is no need to check for null * Whenever you need more details, simply expand the map * @return details of this place */ public LinkedHashMap<String, String> getDetails() { LinkedHashMap<String, String> details = new LinkedHashMap<String, String>(); details.put(Utils.format(Detail.NAME), name); //put name details.put(Utils.format(Detail.ADDRESS), formatted_address); //put address details.put(Utils.format(Detail.PHONE), formatted_phone_number); //put phone details.put(Utils.format(Detail.LOCATION), getLatLng().toString()); //put location details.put(Utils.format(Detail.RATING), Utils.format(rating)); //put rating details.put(Utils.format(Detail.OPENING_HOURS), opening_hours == null ? Utils.NO_DATA : (opening_hours.open_now ? "open now" : "closed")); return details; } /** * Assuming that geometry != null since google maps could find it * using some sort of coordintates * @return a pair of latitude and longitude coordinates of this place */ public LatLng getLatLng() { return new LatLng(geometry.location.lat, geometry.location.lng); } /** * Since we have defined our on location I had to use * android.location.Location. Once I really get into it * I will probably replace the inner class with something different * to demystify the code * @param location - location to which you need to know the distance * @return a distance in meters to the given location */ public float distanceTo(android.location.Location location) { android.location.Location thisPlaceLocation = new android.location.Location(""); thisPlaceLocation.setLatitude(geometry.location.lat); thisPlaceLocation.setLongitude(geometry.location.lng); return thisPlaceLocation.distanceTo(location); } @Override public String toString() { return name + " - " + id + " - " + reference; } @SuppressWarnings("serial") public static class Geometry implements Serializable { @Key public Location location; } @SuppressWarnings("serial") public static class OpeningHours implements Serializable { @Key public boolean open_now; } @SuppressWarnings("serial") public static class Photo implements Serializable { @Key public int height; @Key public String[] html_attributions; @Key public String photo_reference; @Key public int width; } @SuppressWarnings("serial") public static class Location implements Serializable { @Key public double lat; @Key public double lng; } }
package org.perl6.nqp.io; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.channels.FileChannel; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CharsetEncoder; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import org.perl6.nqp.runtime.ExceptionHandling; import org.perl6.nqp.runtime.ThreadContext; public class FileHandle implements IIOClosable, IIOSeekable, IIOEncodable, IIOSyncReadable, IIOSyncWritable { private FileChannel chan; private CharsetEncoder enc; private CharsetDecoder dec; private boolean eof = false; private ByteBuffer readBuffer; public FileHandle(ThreadContext tc, String filename, String mode) { try { Path p = new File(filename).toPath(); if (mode.equals("r")) { chan = FileChannel.open(p, StandardOpenOption.READ); } else if (mode.equals("w")) { chan = FileChannel.open(p, StandardOpenOption.WRITE, StandardOpenOption.CREATE); } else if (mode.equals("wa")) { chan = FileChannel.open(p, StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.APPEND); } else { ExceptionHandling.dieInternal(tc, "Unhandled file open mode '" + mode + "'"); } setEncoding(tc, Charset.forName("UTF-8")); } catch (IOException e) { throw ExceptionHandling.dieInternal(tc, e); } } public void close(ThreadContext tc) { try { chan.close(); } catch (IOException e) { throw ExceptionHandling.dieInternal(tc, e); } } public void seek(ThreadContext tc, long offset, long whence) { try { switch ((int)whence) { case 0: chan.position(offset); break; case 1: chan.position(chan.position() + offset); break; case 2: chan.position(chan.size()); break; default: throw ExceptionHandling.dieInternal(tc, "Invalid seek mode"); } } catch (IOException e) { throw ExceptionHandling.dieInternal(tc, e); } } public long tell(ThreadContext tc) { try { return chan.position(); } catch (IOException e) { throw ExceptionHandling.dieInternal(tc, e); } } public void setEncoding(ThreadContext tc, Charset cs) { enc = cs.newEncoder(); dec = cs.newDecoder(); } public synchronized String slurp(ThreadContext tc) { try { // Read in file. ArrayList<ByteBuffer> buffers = new ArrayList<ByteBuffer>(); ByteBuffer curBuffer = ByteBuffer.allocate(32768); int total = 0; int read; if (readBuffer != null) { buffers.add(ByteBuffer.wrap(readBuffer.array(), readBuffer.position(), readBuffer.limit() - readBuffer.position())); readBuffer = null; } while ((read = chan.read(curBuffer)) != -1) { curBuffer.flip(); buffers.add(curBuffer); curBuffer = ByteBuffer.allocate(32768); total += read; } eof = true; return decodeBuffers(buffers, total); } catch (IOException e) { throw ExceptionHandling.dieInternal(tc, e); } } public synchronized String readline(ThreadContext tc) { try { boolean foundLine = false; ArrayList<ByteBuffer> lineChunks = new ArrayList<ByteBuffer>(); int total = 0; while (!foundLine) { /* Ensure we have a buffer available. */ if (readBuffer == null) { readBuffer = ByteBuffer.allocate(32768); if (chan.read(readBuffer) == -1) { /* End of file, so what we have is fine. */ eof = true; foundLine = true; break; } readBuffer.flip(); } /* Look for a line end. */ int start = readBuffer.position(); int end = start; while (!foundLine && end < readBuffer.limit()) { if (readBuffer.get(end) == '\n') foundLine = true; end++; } /* Copy what we found into the results. */ byte[] lineBytes = new byte[end - start]; readBuffer.get(lineBytes); lineChunks.add(ByteBuffer.wrap(lineBytes)); total += lineBytes.length; /* If we didn't find a line, will cross chunk boundary. */ if (!foundLine) readBuffer = null; } if (lineChunks.size() == 1) return dec.decode(lineChunks.get(0)).toString(); else return decodeBuffers(lineChunks, total); } catch (IOException e) { throw ExceptionHandling.dieInternal(tc, e); } } private String decodeBuffers(ArrayList<ByteBuffer> buffers, int total) throws IOException { // Copy to a single buffer and decode (could be smarter, but need // to be wary as UTF-8 chars may span a buffer boundary). ByteBuffer allBytes = ByteBuffer.allocate(total); for (ByteBuffer bb : buffers) allBytes.put(bb.array(), 0, bb.limit()); allBytes.rewind(); return dec.decode(allBytes).toString(); } public boolean eof(ThreadContext tc) { return eof; } public void print(ThreadContext tc, String s) { try { ByteBuffer buffer = enc.encode(CharBuffer.wrap(s)); while (buffer.position() > 0) { buffer.flip(); chan.write(buffer); buffer.compact(); } } catch (IOException e) { throw ExceptionHandling.dieInternal(tc, e); } } public void say(ThreadContext tc, String s) { print(tc, s); print(tc, System.lineSeparator()); } }
/* * $Id: TestOpenUrlResolver.java,v 1.24 2012-09-06 03:14:22 pgust Exp $ */ package org.lockss.daemon; import java.io.*; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.*; import org.lockss.config.*; import org.lockss.daemon.OpenUrlResolver.OpenUrlInfo; import org.lockss.db.DbManager; import org.lockss.extractor.ArticleMetadata; import org.lockss.extractor.ArticleMetadataExtractor; import org.lockss.extractor.MetadataField; import org.lockss.extractor.MetadataTarget; import org.lockss.plugin.ArchivalUnit; import org.lockss.plugin.ArticleFiles; import org.lockss.plugin.ArticleIteratorFactory; import org.lockss.plugin.PluginManager; import org.lockss.plugin.PluginTestUtil; import org.lockss.plugin.SubTreeArticleIterator; import org.lockss.plugin.simulated.*; import org.lockss.util.*; import org.lockss.test.*; //import TestBePressMetadataExtractor.MySimulatedPlugin; /** * Test class for org.lockss.daemon.MetadataManager * * @author Philip Gust * @version 1.0 */ public class TestOpenUrlResolver extends LockssTestCase { static Logger log = Logger.getLogger("TestOpenUrlResolver"); private SimulatedArchivalUnit sau0, sau1, sau2, sau3; private MockLockssDaemon theDaemon; private MetadataManager metadataManager; private PluginManager pluginManager; private OpenUrlResolver openUrlResolver; private boolean disableMetadataManager = false; private DbManager dbManager; /** set of AUs reindexed by the MetadataManager */ Set<String> ausReindexed = new HashSet<String>(); public void setUp() throws Exception { super.setUp(); String paramIndexingEnabled = Boolean.toString(!disableMetadataManager && true); final String tempDirPath = getTempDir().getAbsolutePath(); ConfigurationUtil.setFromArgs(MetadataManager.PARAM_INDEXING_ENABLED, paramIndexingEnabled, ConfigManager.PARAM_PLATFORM_DISK_SPACE_LIST, new File(tempDirPath, "disk").toString()); // set derby database log System.setProperty("derby.stream.error.file", new File(tempDirPath,"derby.log").getAbsolutePath()); theDaemon = getMockLockssDaemon(); theDaemon.getAlertManager(); pluginManager = theDaemon.getPluginManager(); pluginManager.setLoadablePluginsReady(true); theDaemon.setDaemonInited(true); pluginManager.startService(); theDaemon.getCrawlManager(); // Make a copy of current config so can add tdb Configuration config = ConfigManager.getCurrentConfig().copy(); Tdb tdb = new Tdb(); // create Tdb for testing purposes Properties tdbProps = new Properties(); tdbProps = new Properties(); tdbProps.setProperty("title", "Title[10.0135/12345678]"); tdbProps.setProperty("attributes.isbn", "976-1-58562-317-7"); tdbProps.setProperty("journalTitle", "Journal[10.0135/12345678]"); tdbProps.setProperty("attributes.publisher", "Publisher[10.0135/12345678]"); tdbProps.setProperty("plugin", "org.lockss.daemon.TestOpenUrlResolver$MySimulatedPlugin3"); tdbProps.setProperty("param.1.key", "base_url"); tdbProps.setProperty("param.1.value", "http: tdb.addTdbAuFromProperties(tdbProps); tdbProps = new Properties(); tdbProps.setProperty("title", "Title[Manual of Clinical Psychopharmacology]"); tdbProps.setProperty("attributes.isbn", "978-1-58562-317-4"); tdbProps.setProperty("journalTitle", "Manual of Clinical Psychopharmacology"); tdbProps.setProperty("attributes.publisher", "Publisher[Manual of Clinical Psychopharmacology]"); tdbProps.setProperty("plugin", "org.lockss.daemon.TestOpenUrlResolver$MySimulatedPlugin2"); tdbProps.setProperty("param.1.key", "base_url"); tdbProps.setProperty("param.1.value", "http: tdbProps.setProperty("attributes.year", "1993"); tdb.addTdbAuFromProperties(tdbProps); tdbProps = new Properties(); tdbProps.setProperty("title", "Title[10.2468/24681357]"); tdbProps.setProperty("issn", "1144-875X"); tdbProps.setProperty("eissn", "7744-6521"); tdbProps.setProperty("attributes.volume", "42"); tdbProps.setProperty("attributes."+OpenUrlResolver.AU_FEATURE_KEY, "key1"); tdbProps.setProperty("journalTitle", "Journal[10.2468/24681357]"); tdbProps.setProperty("attributes.publisher", "Publisher[10.2468/24681357]"); tdbProps.setProperty("plugin", "org.lockss.daemon.TestOpenUrlResolver$MySimulatedPlugin1"); tdbProps.setProperty("param.1.key", "base_url"); tdbProps.setProperty("param.1.value", "http: tdb.addTdbAuFromProperties(tdbProps); tdbProps = new Properties(); tdbProps.setProperty("title", "Title[10.1234/12345678]"); tdbProps.setProperty("issn", "0740-2783"); tdbProps.setProperty("attributes.volume", "XI"); tdbProps.setProperty("journalTitle", "Journal[10.1234/12345678]"); tdbProps.setProperty("attributes.publisher", "Publisher[10.1234/12345678]"); tdbProps.setProperty("plugin", "org.lockss.daemon.TestOpenUrlResolver$MySimulatedPlugin0"); tdbProps.setProperty("param.1.key", "base_url"); tdbProps.setProperty("param.1.value", "http: tdb.addTdbAuFromProperties(tdbProps); config.setTdb(tdb); ConfigurationUtil.installConfig(config); config = simAuConfig(tempDirPath + "/0"); config.put("volume", "XI"); config.put("base_url", "http: sau0 = PluginTestUtil.createAndStartSimAu(MySimulatedPlugin0.class, config); config = simAuConfig(tempDirPath + "/1"); config.put("base_url", "http: sau1 = PluginTestUtil.createAndStartSimAu(MySimulatedPlugin1.class, config); config = simAuConfig(tempDirPath + "/2"); config.put("base_url", "http: sau2 = PluginTestUtil.createAndStartSimAu(MySimulatedPlugin2.class, config); config = simAuConfig(tempDirPath + "/3"); config.put("base_url", "http: sau3 = PluginTestUtil.createAndStartSimAu(MySimulatedPlugin3.class, config); PluginTestUtil.crawlSimAu(sau0); PluginTestUtil.crawlSimAu(sau1); PluginTestUtil.crawlSimAu(sau2); PluginTestUtil.crawlSimAu(sau3); ausReindexed.clear(); dbManager = new DbManager() { public Connection getConnection() throws SQLException { return super.getConnection(); } }; theDaemon.setDbManager(dbManager); dbManager.initService(theDaemon); try { dbManager.startService(); } catch (IllegalArgumentException ex) { // ignored } metadataManager = new MetadataManager() { /** * Notify listeners that an AU is being reindexed. * * @param au */ protected void notifyStartReindexingAu(ArchivalUnit au) { log.debug("Start reindexing au " + au); } /** * Notify listeners that an AU is finshed being reindexed. * * @param au */ protected void notifyFinishReindexingAu(ArchivalUnit au, ReindexingStatus status) { log.debug("Finished reindexing au (" + status + ") " + au); if (status != ReindexingStatus.rescheduled) { synchronized (ausReindexed) { ausReindexed.add(au.getAuId()); ausReindexed.notifyAll(); } } } }; theDaemon.setMetadataManager(metadataManager); metadataManager.initService(theDaemon); try { metadataManager.startService(); } catch (IllegalArgumentException ex) { // ignored } theDaemon.setAusStarted(true); if ("true".equals(paramIndexingEnabled)) { int expectedAuCount = 4; assertEquals(expectedAuCount, pluginManager.getAllAus().size()); long maxWaitTime = expectedAuCount * 20000; // 20 sec. per au int ausCount = waitForReindexing(expectedAuCount, maxWaitTime); assertEquals(expectedAuCount, ausCount); } // override to eliminate URL resolution for testing openUrlResolver = new OpenUrlResolver(theDaemon) { @Override public String resolveUrl(String url, String auProxySpec) { return url; } }; } Configuration simAuConfig(String rootPath) { Configuration conf = ConfigManager.newConfiguration(); conf.put("root", rootPath); conf.put("depth", "2"); conf.put("branch", "1"); conf.put("numFiles", "3"); conf.put("fileTypes", "" + (SimulatedContentGenerator.FILE_TYPE_PDF + SimulatedContentGenerator.FILE_TYPE_HTML)); conf.put("binFileSize", "7"); return conf; } public void tearDown() throws Exception { sau0.deleteContentTree(); sau1.deleteContentTree(); sau2.deleteContentTree(); theDaemon.stopDaemon(); super.tearDown(); } public void createMetadata() throws Exception { dbManager.startService(); // reset set of reindexed aus ausReindexed.clear(); metadataManager.restartService(); theDaemon.setAusStarted(true); int expectedAuCount = 4; assertEquals(expectedAuCount, pluginManager.getAllAus().size()); Connection con = dbManager.getConnection(); long maxWaitTime = expectedAuCount * 20000; // 20 sec. per au int ausCount = waitForReindexing(expectedAuCount, maxWaitTime); assertEquals(expectedAuCount, ausCount); assertEquals(0, metadataManager.activeReindexingTasks.size()); assertEquals(0, metadataManager.getAuIdsToReindex(con, Integer.MAX_VALUE).size()); String query = "select access_url from " + MetadataManager.METADATA_TABLE; Statement stmt = con.createStatement(); ResultSet resultSet = stmt.executeQuery(query); if (!resultSet.next()) { fail("No entries in metadata table"); } String url = resultSet.getString(1); log.debug("url from metadata table: " + url); con.rollback(); con.commit(); } /** * Waits a specified period for a specified number of AUs to finish * being reindexed. Returns the actual number of AUs reindexed. * * @param auCount the expected AU count * @param maxWaitTime the maximum time to wait * @return the number of AUs reindexed */ private int waitForReindexing(int auCount, long maxWaitTime) { long startTime = System.currentTimeMillis(); synchronized (ausReindexed) { while ( (System.currentTimeMillis()-startTime < maxWaitTime) && (ausReindexed.size() < auCount)) { try { ausReindexed.wait(maxWaitTime); } catch (InterruptedException ex) { } } } return ausReindexed.size(); } public static class MySubTreeArticleIteratorFactory implements ArticleIteratorFactory { String pat; public MySubTreeArticleIteratorFactory(String pat) { this.pat = pat; } /** * Create an Iterator that iterates through the AU's articles, pointing * to the appropriate CachedUrl of type mimeType for each, or to the * plugin's choice of CachedUrl if mimeType is null * @param au the ArchivalUnit to iterate through * @return the ArticleIterator */ @Override public Iterator<ArticleFiles> createArticleIterator(ArchivalUnit au, MetadataTarget target) throws PluginException { Iterator<ArticleFiles> ret; SubTreeArticleIterator.Spec spec = new SubTreeArticleIterator.Spec().setTarget(target); if (pat != null) { spec.setPattern(pat); } ret = new SubTreeArticleIterator(au, spec); log.debug( "creating article iterator for au " + au.getName() + " hasNext: " + ret.hasNext()); return ret; } } public static class MySimulatedPlugin extends SimulatedPlugin { ArticleMetadataExtractor simulatedArticleMetadataExtractor = null; /** * Returns the article iterator factory for the mime type, if any * @param contentType the content type * @return the ArticleIteratorFactory */ @Override public ArticleIteratorFactory getArticleIteratorFactory() { MySubTreeArticleIteratorFactory ret = new MySubTreeArticleIteratorFactory(null); //"branch1/branch1"); return ret; } @Override public ArticleMetadataExtractor getArticleMetadataExtractor(MetadataTarget target, ArchivalUnit au) { return simulatedArticleMetadataExtractor; } } public static class MySimulatedPlugin0 extends MySimulatedPlugin { public MySimulatedPlugin0() { simulatedArticleMetadataExtractor = new ArticleMetadataExtractor() { int articleNumber = 0; public void extract(MetadataTarget target, ArticleFiles af, Emitter emitter) throws IOException, PluginException { ArticleMetadata md = new ArticleMetadata(); articleNumber++; md.put(MetadataField.FIELD_ISSN,"0740-2783"); md.put(MetadataField.FIELD_VOLUME,"XI"); if (articleNumber < 10) { md.put(MetadataField.FIELD_ISSUE,"1st Quarter"); md.put(MetadataField.FIELD_DATE,"2010-Q1"); md.put(MetadataField.FIELD_START_PAGE,"" + articleNumber); } else { md.put(MetadataField.FIELD_ISSUE,"2nd Quarter"); md.put(MetadataField.FIELD_DATE,"2010-Q2"); md.put(MetadataField.FIELD_START_PAGE,"" + (articleNumber-9)); } String doiPrefix = "10.1234/12345678"; String doi = doiPrefix + "." + md.get(MetadataField.FIELD_DATE) + "." + md.get(MetadataField.FIELD_START_PAGE); md.put(MetadataField.FIELD_DOI, doi); md.put(MetadataField.FIELD_JOURNAL_TITLE,"Journal[" + doiPrefix + "]"); md.put(MetadataField.FIELD_ARTICLE_TITLE,"Title[" + doi + "]"); md.put(MetadataField.FIELD_AUTHOR,"Author[" + doi + "]"); md.put(MetadataField.FIELD_ACCESS_URL, "http: + md.get(MetadataField.FIELD_ISSUE) +"/p" + md.get(MetadataField.FIELD_START_PAGE)); emitter.emitMetadata(af, md); } }; } public ExternalizableMap getDefinitionMap() { ExternalizableMap map = new ExternalizableMap(); map.putString("au_start_url", "\"%splugin0/%s\", base_url, volume"); map.putString("au_volume_url", "\"%splugin0/%s/toc\", base_url, volume"); map.putString("au_issue_url", "\"%splugin0/%s/%s/toc\", base_url, volume, issue"); map.putString("au_title_url", "\"%splugin0/toc\", base_url"); return map; } } public static class MySimulatedPlugin1 extends MySimulatedPlugin { public MySimulatedPlugin1() { simulatedArticleMetadataExtractor = new ArticleMetadataExtractor() { int articleNumber = 0; public void extract(MetadataTarget target, ArticleFiles af, Emitter emitter) throws IOException, PluginException { articleNumber++; ArticleMetadata md = new ArticleMetadata(); md.put(MetadataField.FIELD_ISSN,"1144-875X"); md.put(MetadataField.FIELD_EISSN, "7744-6521"); md.put(MetadataField.FIELD_VOLUME,"42"); if (articleNumber < 10) { md.put(MetadataField.FIELD_ISSUE,"Summer"); md.put(MetadataField.FIELD_DATE,"2010-S2"); md.put(MetadataField.FIELD_START_PAGE,"" + articleNumber); } else { md.put(MetadataField.FIELD_ISSUE,"Fall"); md.put(MetadataField.FIELD_DATE,"2010-S3"); md.put(MetadataField.FIELD_START_PAGE, "" + (articleNumber-9)); } String doiPrefix = "10.2468/28681357"; String doi = doiPrefix + "." + md.get(MetadataField.FIELD_DATE) + "." + md.get(MetadataField.FIELD_START_PAGE); md.put(MetadataField.FIELD_DOI, doi); md.put(MetadataField.FIELD_JOURNAL_TITLE, "Journal[" + doiPrefix + "]"); md.put(MetadataField.FIELD_ARTICLE_TITLE, "Title[" + doi + "]"); md.put(MetadataField.FIELD_AUTHOR, "Author1[" + doi + "]"); md.put(MetadataField.FIELD_ACCESS_URL, "http: + "i_" + md.get(MetadataField.FIELD_ISSUE) +"/p_" + md.get(MetadataField.FIELD_START_PAGE)); emitter.emitMetadata(af, md); } }; } public ExternalizableMap getDefinitionMap() { ExternalizableMap map = new ExternalizableMap(); map.putString("au_start_url", "\"%splugin1/v_%s/toc\", base_url, volume"); Map<String,Object> map1 = new HashMap<String,Object>(); map.putMap("au_feature_urls", map1); Map<String,String> map2 = new HashMap<String,String>(); map1.put("au_title", "\"%splugin1/toc\", base_url"); map1.put("au_issue", map2); map2.put("key1", "\"%splugin1/v_%s/i_%s/key1/toc\", base_url, volume, issue"); map2.put("key2;*", "\"%splugin1/v_%s/i_%s/key2/toc\", base_url, volume, issue"); return map; } } public static class MySimulatedPlugin2 extends MySimulatedPlugin { public MySimulatedPlugin2() { simulatedArticleMetadataExtractor = new ArticleMetadataExtractor() { int articleNumber = 0; public void extract(MetadataTarget target, ArticleFiles af, Emitter emitter) throws IOException, PluginException { org.lockss.extractor.ArticleMetadata md = new ArticleMetadata(); articleNumber++; String doi = "10.1357/9781585623174." + articleNumber; md.put(MetadataField.FIELD_DOI,doi); md.put(MetadataField.FIELD_ISBN,"978-1-58562-317-4"); md.put(MetadataField.FIELD_DATE,"1993"); md.put(MetadataField.FIELD_START_PAGE,"" + articleNumber); md.put(MetadataField.FIELD_JOURNAL_TITLE,"Manual of Clinical Psychopharmacology"); md.put(MetadataField.FIELD_ARTICLE_TITLE,"Title[" + doi + "]"); md.put(MetadataField.FIELD_AUTHOR,"Author1[" + doi + "]"); md.put(MetadataField.FIELD_AUTHOR,"Author2[" + doi + "]"); md.put(MetadataField.FIELD_AUTHOR,"Author3[" + doi + "]"); md.put(MetadataField.FIELD_ACCESS_URL, "http: emitter.emitMetadata(af, md); } }; } public ExternalizableMap getDefinitionMap() { ExternalizableMap map = new ExternalizableMap(); map.putString("au_start_url", "\"%splugin2/%s\", base_url, year"); return map; } } public static class MySimulatedPlugin3 extends MySimulatedPlugin { public MySimulatedPlugin3() { simulatedArticleMetadataExtractor = new ArticleMetadataExtractor() { int articleNumber = 0; public void extract(MetadataTarget target, ArticleFiles af, Emitter emitter) throws IOException, PluginException { org.lockss.extractor.ArticleMetadata md = new ArticleMetadata(); articleNumber++; String doiPrefix = "10.0135/12345678.1999-11.12"; String doi = doiPrefix + "." + articleNumber; md.put(MetadataField.FIELD_DOI,doi); md.put(MetadataField.FIELD_ISBN,"976-1-58562-317-7"); md.put(MetadataField.FIELD_DATE,"1999"); md.put(MetadataField.FIELD_START_PAGE,"" + articleNumber); md.put(MetadataField.FIELD_JOURNAL_TITLE,"Journal[" + doiPrefix + "]"); md.put(MetadataField.FIELD_ARTICLE_TITLE,"Title[" + doi + "]"); md.put(MetadataField.FIELD_AUTHOR,"Author1[" + doi + "]"); md.put(MetadataField.FIELD_ACCESS_URL, "http: emitter.emitMetadata(af, md); } }; } public ExternalizableMap getDefinitionMap() { ExternalizableMap map = new ExternalizableMap(); map.putString("au_start_url", "\"%splugin3/%s\", base_url, year"); return map; } } /* * Test resolving a journal article using the DOI of the article. */ public void testResolveFromRftIdDoi() { // from SimulatedPlugin0 // expect url for article with specified DOI Map<String,String> params = new HashMap<String,String>(); if (disableMetadataManager) { // use real DOI so test doesn't take so long to time out params.put("rft_id", "info:doi/" + "10.3789/isqv22n3.2010.04"); OpenUrlInfo resolver = openUrlResolver.resolveOpenUrl(params); assertEquals(OpenUrlInfo.ResolvedTo.OTHER, resolver.getResolvedTo()); assertEquals("http://dx.doi.org/10.3789/isqv22n3.2010.04", resolver.getResolvedUrl()); } else { params.put("rft_id", "info:doi/" + "10.1234/12345678.2010-Q1.1"); OpenUrlInfo resolver = openUrlResolver.resolveOpenUrl(params); assertEquals(OpenUrlInfo.ResolvedTo.ARTICLE, resolver.getResolvedTo()); assertEquals("http: resolver.getResolvedUrl()); } } /** * Test resolving a book chapter using an ISBN plus either * the page, the article number, the author, or the article title. */ public void testResolveFromIsbn() { OpenUrlInfo resolved;; Map<String,String> params = new HashMap<String,String>(); // from SimulatedPlugin2 with ISBN and start page // expect url for specified chapter of the book params.clear(); params.put("rft.isbn", "978-1-58562-317-4"); params.put("rft.spage", "4"); resolved = openUrlResolver.resolveOpenUrl(params); if (disableMetadataManager) { assertEquals(OpenUrlInfo.ResolvedTo.PUBLISHER, resolved.getResolvedTo()); assertEquals("http: } else { assertEquals(OpenUrlInfo.ResolvedTo.CHAPTER, resolved.getResolvedTo()); assertEquals("http: } // from SimulatedPlugin2 with ISBN and bad start page // expect landing page since the page number is bad params.clear(); params.put("rft.isbn", "978-1-58562-317-4"); params.put("rft.spage", "bad"); resolved = openUrlResolver.resolveOpenUrl(params); assertEquals(OpenUrlInfo.ResolvedTo.PUBLISHER, resolved.getResolvedTo()); assertEquals("http: // from SimulatedPlugin2 with ISBN and article number // expect url for specified chapter params.clear(); params.put("rft.isbn", "978-1-58562-317-4"); params.put("rft.artnum", "2"); resolved = openUrlResolver.resolveOpenUrl(params); if (disableMetadataManager) { assertEquals(OpenUrlInfo.ResolvedTo.PUBLISHER, resolved.getResolvedTo()); assertEquals("http: } else { assertEquals(OpenUrlInfo.ResolvedTo.CHAPTER, resolved.getResolvedTo()); assertEquals("http: } // from SimulatedPlugin2 with ISBN and author // expect url for author's chapter of the book params.clear(); params.put("rft.isbn", "978-1-58562-317-4"); params.put("rft.au", "Author2[10.1357/9781585623174.1]"); resolved = openUrlResolver.resolveOpenUrl(params); if (disableMetadataManager) { assertEquals(OpenUrlInfo.ResolvedTo.PUBLISHER, resolved.getResolvedTo()); assertEquals("http: } else { assertEquals(OpenUrlInfo.ResolvedTo.CHAPTER, resolved.getResolvedTo()); assertEquals("http: } // from SimulatedPlugin2 with ISBN only // expect url for specified article of the book params.clear(); params.put("rft.isbn", "978-1-58562-317-4"); params.put("rft.atitle", "Title[10.1357/9781585623174.1]"); resolved = openUrlResolver.resolveOpenUrl(params); if (disableMetadataManager) { assertEquals(OpenUrlInfo.ResolvedTo.PUBLISHER, resolved.getResolvedTo()); assertEquals("http: } else { assertEquals(OpenUrlInfo.ResolvedTo.CHAPTER, resolved.getResolvedTo()); assertEquals("http: } // from SimulatedPlugin2 with ISBN, start page, author, and title // expect url for specified article for author and page number params.clear(); params.put("rft.isbn", "978-1-58562-317-4"); params.put("rft.atitle", "Title[10.1357/9781585623174.1]"); params.put("rft.au", "Author2[10.1357/9781585623174.1]"); params.put("rft.spage", "1"); resolved = openUrlResolver.resolveOpenUrl(params); if (disableMetadataManager) { assertEquals(OpenUrlInfo.ResolvedTo.PUBLISHER, resolved.getResolvedTo()); assertEquals("http: } else { assertEquals(OpenUrlInfo.ResolvedTo.CHAPTER, resolved.getResolvedTo()); assertEquals("http: } // from SimulatedPlugin2 with ISBN, start page, author, and title // expect url for specified article for author and page number params.clear(); params.put("rft.isbn", "978-1-58562-317-4"); params.put("rft.date", "1993"); resolved = openUrlResolver.resolveOpenUrl(params); if (disableMetadataManager) { assertEquals(OpenUrlInfo.ResolvedTo.VOLUME, resolved.getResolvedTo()); assertEquals("http: } else { assertEquals(OpenUrlInfo.ResolvedTo.VOLUME, resolved.getResolvedTo()); assertEquals("http: } } /** * Test resolving a book chapter using the publisher and book title. */ public void testResolveFromBookTitle() { // these tests require a TDB if (ConfigManager.getCurrentConfig().getTdb() == null) { return; } Map<String,String> params; OpenUrlInfo resolved; // from SimulatedPlugin2 with book publisher, title with start page // expect url for chapter on specified page params = new HashMap<String,String>(); params.put("rft.pub", "Publisher[Manual of Clinical Psychopharmacology]"); params.put("rft.btitle", "Title[Manual of Clinical Psychopharmacology]"); params.put("rft.spage", "1"); resolved = openUrlResolver.resolveOpenUrl(params); if (disableMetadataManager) { assertEquals(OpenUrlInfo.ResolvedTo.PUBLISHER, resolved.getResolvedTo()); assertEquals("http: } else { assertEquals(OpenUrlInfo.ResolvedTo.CHAPTER, resolved.getResolvedTo()); assertEquals("http: } // from SimulatedPlugin2 book title and page only, without publisher // expect url for chapter on specified page params.clear(); params.put("rft.btitle", "Title[Manual of Clinical Psychopharmacology]"); params.put("rft.spage", "1"); resolved = openUrlResolver.resolveOpenUrl(params); if (disableMetadataManager) { assertEquals(OpenUrlInfo.ResolvedTo.PUBLISHER, resolved.getResolvedTo()); assertEquals("http: } else { assertEquals(OpenUrlInfo.ResolvedTo.CHAPTER, resolved.getResolvedTo()); assertEquals("http: } // from SimulatedPlugin2 book title and page only, without publisher // expect url for specified article params.clear(); params.put("rft.btitle", "Title[Manual of Clinical Psychopharmacology]"); params.put("rft.atitle", "Title[10.1357/9781585623174.1]"); resolved = openUrlResolver.resolveOpenUrl(params); if (disableMetadataManager) { assertEquals(OpenUrlInfo.ResolvedTo.PUBLISHER, resolved.getResolvedTo()); assertEquals("http: } else { assertEquals(OpenUrlInfo.ResolvedTo.CHAPTER, resolved.getResolvedTo()); assertEquals("http: } // from SimulatedPlugin2 book title only // expect url of book landing page params.clear(); params.put("rft.btitle", "Title[Manual of Clinical Psychopharmacology]"); resolved = openUrlResolver.resolveOpenUrl(params); assertEquals(OpenUrlInfo.ResolvedTo.PUBLISHER, resolved.getResolvedTo()); assertEquals("http: // from SimulatedPlugin2 book title and year // expect url of book landing page params.clear(); params.put("rft.btitle", "Title[Manual of Clinical Psychopharmacology]"); params.put("rft.date", "1993"); resolved = openUrlResolver.resolveOpenUrl(params); assertEquals(OpenUrlInfo.ResolvedTo.VOLUME, resolved.getResolvedTo()); assertEquals("http: } /** * Test resolving a book chapter using an ISBN plus either * the page, the article number, the author, or the article title. */ public void testResolveFromIssn() { OpenUrlInfo resolved; Map<String,String> params = new HashMap<String,String>(); // from SimulatedPlugin1, journal ISSN only // expect base_url params.put("rft.issn", "1144-875X"); resolved = openUrlResolver.resolveOpenUrl(params); assertEquals(OpenUrlInfo.ResolvedTo.TITLE, resolved.getResolvedTo()); assertEquals("http: // from SimulatedPlugin1, journal EISSN only // expect base_url (eventually title TOC) params.clear(); params.put("rft.eissn", "7744-6521"); resolved = openUrlResolver.resolveOpenUrl(params); assertEquals(OpenUrlInfo.ResolvedTo.TITLE, resolved.getResolvedTo()); assertEquals("http: // from SimulatedPlugin1, journal ISSN and article number only // expect base_url (eventually title TOC) since article number is not unique params.clear(); params.put("rft.issn", "1144-875X"); params.put("rft.artnum", "1"); resolved = openUrlResolver.resolveOpenUrl(params); assertEquals(OpenUrlInfo.ResolvedTo.TITLE, resolved.getResolvedTo()); assertEquals("http: // from SimulatedPlugin1, journal ISSN, volume, issue, and article title // expect article URL params.clear(); params.put("rft.issn", "1144-875X"); params.put("rft.volume", "42"); params.put("rft.issue", "Summer"); params.put("rft.atitle", "Title[10.2468/28681357.2010-S2.1]"); resolved = openUrlResolver.resolveOpenUrl(params); if (disableMetadataManager) { assertEquals(OpenUrlInfo.ResolvedTo.ISSUE, resolved.getResolvedTo()); assertEquals("http: resolved.getResolvedUrl()); } else { assertEquals(OpenUrlInfo.ResolvedTo.ARTICLE, resolved.getResolvedTo()); assertEquals("http: resolved.getResolvedUrl()); } // from SimulatedPlugin1, journal ISSN, volume, issue, and article author // expect article URL params.clear(); params.put("rft.issn", "1144-875X"); params.put("rft.volume", "42"); params.put("rft.issue", "Summer"); params.put("rft.au", "Author1[10.2468/28681357.2010-S2.1]"); resolved = openUrlResolver.resolveOpenUrl(params); if (disableMetadataManager) { assertEquals(OpenUrlInfo.ResolvedTo.ISSUE, resolved.getResolvedTo()); assertEquals("http: resolved.getResolvedUrl()); } else { assertEquals(OpenUrlInfo.ResolvedTo.ARTICLE, resolved.getResolvedTo()); assertEquals("http: resolved.getResolvedUrl()); } // from SimulatedPlugin1, journal ISSN, volume, issue, and start page // expect article URL params.clear(); params.put("rft.issn", "1144-875X"); params.put("rft.volume", "42"); params.put("rft.issue", "Summer"); params.put("rft.spage", "1"); resolved = openUrlResolver.resolveOpenUrl(params); if (disableMetadataManager) { assertEquals(OpenUrlInfo.ResolvedTo.ISSUE, resolved.getResolvedTo()); assertEquals("http: resolved.getResolvedUrl()); } else { assertEquals(OpenUrlInfo.ResolvedTo.ARTICLE, resolved.getResolvedTo()); assertEquals("http: resolved.getResolvedUrl()); } // from SimulatedPlugin1, journal ISSN, and article title only // expect article URL because article title is unique across the journal params.clear(); params.put("rft.issn", "1144-875X"); params.put("rft.atitle", "Title[10.2468/28681357.2010-S2.1]"); resolved = openUrlResolver.resolveOpenUrl(params); if (disableMetadataManager) { assertEquals(OpenUrlInfo.ResolvedTo.TITLE, resolved.getResolvedTo()); assertEquals("http: } else { assertEquals(OpenUrlInfo.ResolvedTo.ARTICLE, resolved.getResolvedTo()); assertEquals("http: resolved.getResolvedUrl()); } // from SimulatedPlugin1, journal ISSN, and article article author only // expect article_url because author only wrote one article for this journal params.clear(); params.put("rft.issn", "1144-875X"); params.put("rft.au", "Author1[10.2468/28681357.2010-S2.1]"); resolved = openUrlResolver.resolveOpenUrl(params); if (disableMetadataManager) { assertEquals(OpenUrlInfo.ResolvedTo.TITLE, resolved.getResolvedTo()); assertEquals("http: } else { assertEquals(OpenUrlInfo.ResolvedTo.ARTICLE, resolved.getResolvedTo()); assertEquals("http: resolved.getResolvedUrl()); } } /** * Test resolving a book chapter using the publisher and book title. */ public void testResolveFromJournalTitle() { // these tests require a TDB if (ConfigManager.getCurrentConfig().getTdb() == null) { return; } OpenUrlInfo resolved; // from SimulatedPlugin1 // journal title with publisher and page // expect base_url because start page not unique across issues Map<String,String> params = new HashMap<String,String>(); params.put("rft.pub", "Publisher[10.2468/24681357]"); params.put("rft.jtitle", "Journal[10.2468/24681357]"); params.put("rft.spage", "1"); resolved = openUrlResolver.resolveOpenUrl(params); assertEquals(OpenUrlInfo.ResolvedTo.TITLE, resolved.getResolvedTo()); assertEquals("http: // from SimulatedPlugin1 // journal title and page only, without publisher // expect base_url because start page not unique across issues params.clear(); params.put("rft.jtitle", "Journal[10.2468/24681357]"); params.put("rft.spage", "1"); resolved = openUrlResolver.resolveOpenUrl(params); assertEquals(OpenUrlInfo.ResolvedTo.TITLE, resolved.getResolvedTo()); assertEquals("http: // from SimulatedPlugin1 // journal title and invalid page only, without publisher // expect base_url because start page not unique across issue params.clear(); params.put("rft.jtitle", "Journal[10.2468/24681357]"); params.put("rft.spage", "1"); resolved = openUrlResolver.resolveOpenUrl(params); assertEquals(OpenUrlInfo.ResolvedTo.TITLE, resolved.getResolvedTo()); assertEquals("http: // from SimulatedPlugin1 // journal title and invalid page only, without publisher // expect volume url params.clear(); params.put("rft.jtitle", "Journal[10.2468/24681357]"); params.put("rft.volume", "42"); resolved = openUrlResolver.resolveOpenUrl(params); // ensure this is a volume URL assertEquals(OpenUrlInfo.ResolvedTo.VOLUME, resolved.getResolvedTo()); assertEquals("http: // from SimulatedPlugin3 // book title and page only, without publisher // expect article url because start page is unique within the book params.clear(); params.put("rft.btitle", "Title[10.0135/12345678]"); params.put("rft.spage", "1"); resolved = openUrlResolver.resolveOpenUrl(params); if (disableMetadataManager) { assertEquals(OpenUrlInfo.ResolvedTo.PUBLISHER, resolved.getResolvedTo()); assertEquals("http: } else { assertEquals(OpenUrlInfo.ResolvedTo.CHAPTER, resolved.getResolvedTo()); assertEquals("http: } // from SimulatedPlugin3 // book title only, without publisher // expect au url for book params.clear(); params.put("rft.jtitle", "Journal[10.0135/12345678]"); resolved = openUrlResolver.resolveOpenUrl(params); assertEquals(OpenUrlInfo.ResolvedTo.PUBLISHER, resolved.getResolvedTo()); assertEquals("http: } }
package com.fueled.flowr; import android.content.Intent; import android.content.pm.ActivityInfo; import android.net.Uri; import android.os.Bundle; import android.support.annotation.AnimRes; import android.support.annotation.IdRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.text.TextUtils; import android.util.Log; import android.view.View; import com.fueled.flowr.internal.FlowrDeepLinkHandler; import com.fueled.flowr.internal.FlowrDeepLinkInfo; import com.fueled.flowr.internal.TransactionData; import java.util.ArrayList; import java.util.Collections; import java.util.List; @SuppressWarnings({"WeakerAccess", "UnusedDeclaration"}) // Public API. public class Flowr implements FragmentManager.OnBackStackChangedListener, View.OnClickListener { /** * To be used as Bundle key for deep links. */ public final static String DEEP_LINK_URL = "DEEP_LINK_URL"; private final static String KEY_REQUEST_BUNDLE = "KEY_REQUEST_BUNDLE"; private final static String KEY_FRAGMENT_ID = "KEY_FRAGMENT_ID"; private final static String KEY_REQUEST_CODE = "KEY_REQUEST_CODE"; private final static String TAG = Flowr.class.getSimpleName(); private final FragmentsResultPublisher resultPublisher; private final int mainContainerId; @Nullable private FlowrScreen screen; @Nullable private ToolbarHandler toolbarHandler; @Nullable private DrawerHandler drawerHandler; @Nullable private Fragment currentFragment; private boolean overrideBack; private String tagPrefix; private List<FlowrDeepLinkHandler> deepLinkHandlers; /** * Constructor to use when creating a new router for an activity * that has no toolbar. * * @param mainContainerId the id of the container where the fragments should be displayed * @param screen the fragment's parent screen */ public Flowr(@IdRes int mainContainerId, @Nullable FlowrScreen screen, FragmentsResultPublisher resultPublisher) { this(mainContainerId, screen, null, null, resultPublisher); } /** * Constructor to use when creating a new router for an activity * that has no toolbar. * * @param mainContainerId the id of the container where the fragments should be displayed * @param screen the fragment's parent screen * @param tagPrefix a custom prefix for the tags to be used for fragments that will be added to * the backstack. * @param resultPublisher the result publish to be used to publish results from fragments * that where opened for results. */ public Flowr(@IdRes int mainContainerId, @Nullable FlowrScreen screen, @NonNull String tagPrefix, FragmentsResultPublisher resultPublisher) { this(mainContainerId, screen, null, null, tagPrefix, resultPublisher); } /** * Constructor to use when creating a new router for an activity * that has toolbar and a drawer. * * @param mainContainerId the id of the container where the fragments should be displayed * @param screen the fragment's parent screen * @param toolbarHandler the {@link ToolbarHandler} to be used to sync toolbar state * @param drawerHandler the {@link DrawerHandler} to be used to sync drawer state * @param resultPublisher the result publish to be used to publish results from fragments * that where opened for results. */ public Flowr(@IdRes int mainContainerId, @Nullable FlowrScreen screen, @Nullable ToolbarHandler toolbarHandler, @Nullable DrawerHandler drawerHandler, FragmentsResultPublisher resultPublisher) { this(mainContainerId, screen, toolbarHandler, drawerHandler, "#id-", resultPublisher); } /** * Constructor to use when creating a new router for an activity * that has toolbar and a drawer. * * @param mainContainerId the id of the container where the fragments should be displayed * @param screen the fragment's parent screen * @param toolbarHandler the {@link ToolbarHandler} to be used to sync toolbar state * @param drawerHandler the {@link DrawerHandler} to be used to sync drawer state * @param tagPrefix a custom prefix for the tags to be used for fragments that will be added to * the backstack. * @param resultPublisher the result publish to be used to publish results from fragments * that where opened for results. */ public Flowr(@IdRes int mainContainerId, @Nullable FlowrScreen screen, @Nullable ToolbarHandler toolbarHandler, @Nullable DrawerHandler drawerHandler, @NonNull String tagPrefix, FragmentsResultPublisher resultPublisher) { this.resultPublisher = resultPublisher; this.mainContainerId = mainContainerId; this.tagPrefix = tagPrefix; this.overrideBack = false; setRouterScreen(screen); setToolbarHandler(toolbarHandler); setDrawerHandler(drawerHandler); deepLinkHandlers = new ArrayList<>(); syncScreenState(); } /** * Build and return a new ResultResponse instant using the arguments passed in. * * @param arguments Used to retrieve the ID and request code for the fragment * requesting the results. * @param resultCode The results code to be returned. * @param data Used to return extra data that might be required. * @return a new {@link ResultResponse} instance */ public static ResultResponse getResultsResponse(Bundle arguments, int resultCode, Bundle data) { if (arguments == null || !arguments.containsKey(KEY_REQUEST_BUNDLE)) { return null; } ResultResponse resultResponse = new ResultResponse(); resultResponse.resultCode = resultCode; resultResponse.data = data; Bundle requestBundle = arguments.getBundle(KEY_REQUEST_BUNDLE); if (requestBundle != null) { resultResponse.fragmentId = requestBundle.getString(KEY_FRAGMENT_ID); resultResponse.requestCode = requestBundle.getInt(KEY_REQUEST_CODE); } return resultResponse; } /** * Returns the {@link FlowrScreen} used for this router. * * @return the router screen for this router */ @Nullable protected FlowrScreen getRouterScreen() { return screen; } /** * Sets the {@link FlowrScreen} to be used for this router. * * @param flowrScreen the router screen to be used */ public void setRouterScreen(@Nullable FlowrScreen flowrScreen) { removeCurrentRouterScreen(); if (flowrScreen != null) { this.screen = flowrScreen; if (flowrScreen.getScreenFragmentManager() != null) { screen.getScreenFragmentManager().addOnBackStackChangedListener(this); setCurrentFragment(retrieveCurrentFragment()); } } } private void removeCurrentRouterScreen() { if (screen != null) { screen.getScreenFragmentManager().removeOnBackStackChangedListener(this); screen = null; currentFragment = null; } } /** * Sets the {@link ToolbarHandler} to be used to sync toolbar state. * * @param toolbarHandler the toolbar handler to be used. */ public void setToolbarHandler(@Nullable ToolbarHandler toolbarHandler) { removeCurrentToolbarHandler(); if (toolbarHandler != null) { this.toolbarHandler = toolbarHandler; toolbarHandler.setToolbarNavigationButtonListener(this); } } private void removeCurrentToolbarHandler() { if (toolbarHandler != null) { toolbarHandler.setToolbarNavigationButtonListener(null); toolbarHandler = null; } } /** * Sets the {@link DrawerHandler} to be used to sync drawer state. * * @param drawerHandler the drawer handler to be used. */ public void setDrawerHandler(@Nullable DrawerHandler drawerHandler) { this.drawerHandler = drawerHandler; } /** * Specify a collection of {@link FlowrDeepLinkHandler} to be used when routing deep link * intents replacing all previously set handlers. * * @param handlers the collection of handlers to be used. */ public void setDeepLinkHandlers(FlowrDeepLinkHandler... handlers) { this.deepLinkHandlers.clear(); if (handlers != null) { Collections.addAll(deepLinkHandlers, handlers); } } /** * Returns the prefix used for the backstack fragments tag * * @return the prefix used for the backstack fragments tag */ @NonNull protected final String getTagPrefix() { return tagPrefix; } protected <T extends Fragment & FlowrFragment> void displayFragment(TransactionData<T> data) { try { if (screen == null) { return; } injectDeepLinkInfo(data); if (data.isClearBackStack()) { clearBackStack(); } currentFragment = retrieveCurrentFragment(); Fragment fragment = data.getFragmentClass().newInstance(); fragment.setArguments(data.getArgs()); FragmentTransaction transaction = screen.getScreenFragmentManager().beginTransaction(); if (!data.isSkipBackStack()) { String id = tagPrefix + screen.getScreenFragmentManager().getBackStackEntryCount(); transaction.addToBackStack(id); } setCustomAnimations(transaction, data.getEnterAnim(), data.getExitAnim(), data.getPopEnterAnim(), data.getPopExitAnim()); if (data.isReplaceCurrentFragment()) { transaction.replace(mainContainerId, fragment); } else { transaction.add(mainContainerId, fragment); } transaction.commit(); if (data.isSkipBackStack()) { setCurrentFragment(fragment); } } catch (Exception e) { Log.e(TAG, "Error while displaying fragment.", e); } } /** * Parse the intent set by {@link TransactionData#deepLinkIntent} and if this intent contains * Deep Link info, update the {@link #currentFragment} and the Transaction data. * * @param data The Transaction data to extend if Deep link info are found in * the {@link TransactionData#deepLinkIntent}. * @param <T> The generic type for a valid Fragment. */ @SuppressWarnings("unchecked") private <T extends Fragment & FlowrFragment> void injectDeepLinkInfo(TransactionData<T> data) { Intent deepLinkIntent = data.getDeepLinkIntent(); if (deepLinkIntent != null) { for (FlowrDeepLinkHandler handler : deepLinkHandlers) { FlowrDeepLinkInfo info = handler.getDeepLinkInfoForIntent(deepLinkIntent); if (info != null) { data.setFragmentClass(info.fragment); Bundle dataArgs = data.getArgs(); if (dataArgs != null) { data.getArgs().putAll(info.data); } else { data.setArgs(info.data); } break; } } } } /** * Set a Custom Animation to a Fragment transaction * * @param transaction The transaction that will * @param enterAnim The animation resource to be used when the next fragment enters. * @param exitAnim The animation resource to be used when the current fragment exits. * @param popEnterAnim The animation resource to be used when the previous fragment enters on back pressed. * @param popExitAnim The animation resource to be used when the current fragment exits on back pressed.. */ private void setCustomAnimations(FragmentTransaction transaction, @AnimRes int enterAnim, @AnimRes int exitAnim, @AnimRes int popEnterAnim, @AnimRes int popExitAnim) { transaction.setCustomAnimations( enterAnim, exitAnim, popEnterAnim, popExitAnim ); } @Nullable private Fragment retrieveCurrentFragment() { Fragment fragment = null; if (screen != null) { fragment = screen.getScreenFragmentManager() .findFragmentById(mainContainerId); } return fragment; } @Override public void onBackStackChanged() { setCurrentFragment(retrieveCurrentFragment()); } private void updateVisibilityState(Fragment fragment, boolean shown) { if (fragment instanceof FlowrFragment) { if (shown) { ((FlowrFragment) fragment).onShown(); } else { ((FlowrFragment) fragment).onHidden(); } } } /** * Closes the current activity if the fragments back stack is empty, * otherwise pop the top fragment from the stack. */ public void close() { overrideBack = true; if (screen != null) { screen.invokeOnBackPressed(); } } /** * Closes the current activity if the fragments back stack is empty, * otherwise pop the top n fragments from the stack. * * @param n the number of fragments to remove from the back stack */ public void close(int n) { if (screen == null) { return; } int count = screen.getScreenFragmentManager().getBackStackEntryCount(); if (count > 1) { String id = tagPrefix + (screen.getScreenFragmentManager().getBackStackEntryCount() - n); screen.getScreenFragmentManager() .popBackStackImmediate(id, FragmentManager.POP_BACK_STACK_INCLUSIVE); } else { close(); } } /** * Closes the current activity if the fragments back stack is empty, * otherwise pop the top fragment from the stack and publish the results response. * * @param resultResponse the results response to be published */ public void closeWithResults(ResultResponse resultResponse) { closeWithResults(resultResponse, 1); } /** * Closes the current activity if the fragments back stack is empty, * otherwise pop the top n fragments from the stack and publish the results response. * * @param resultResponse the results response to be published * @param n the number of fragments to remove from the back stack */ public void closeWithResults(ResultResponse resultResponse, int n) { close(n); if (resultResponse != null) { resultPublisher.publishResult(resultResponse); } } /** * Clears the fragments back stack. */ public void clearBackStack() { if (screen != null) { screen.getScreenFragmentManager() .popBackStack(tagPrefix + "0", FragmentManager.POP_BACK_STACK_INCLUSIVE); currentFragment = null; } } /** * Notify the current fragment of the back press event * and see if the fragment will handle it. * * @return true if the event was handled by the fragment */ public boolean onBackPressed() { if (!overrideBack && currentFragment instanceof FlowrFragment && ((FlowrFragment) currentFragment).onBackPressed()) { return true; } overrideBack = false; return false; } public void onNavigationIconClicked() { if (!(currentFragment instanceof FlowrFragment && ((FlowrFragment) currentFragment).onNavigationIconClick())) { close(); } } /** * Checks if the current fragment is the home fragment. * * @return true if the current fragment is the home fragment */ public boolean isHomeFragment() { return screen == null || screen.getScreenFragmentManager().getBackStackEntryCount() == 0; } /** * Returns the fragment currently being displayed for this screen, * * @return the fragment currently being displayed */ @Nullable public Fragment getCurrentFragment() { return currentFragment; } private void setCurrentFragment(@Nullable Fragment newFragment) { if (currentFragment != newFragment) { updateVisibilityState(currentFragment, false); currentFragment = newFragment; updateVisibilityState(currentFragment, true); syncScreenState(); } } /** * Called by the {@link android.app.Activity#onPostCreate(Bundle)} to update * the state of the container screen. */ public void syncScreenState() { int screenOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED; int navigationBarColor = -1; if (currentFragment instanceof FlowrFragment) { screenOrientation = ((FlowrFragment) currentFragment).getScreenOrientation(); navigationBarColor = ((FlowrFragment) currentFragment).getNavigationBarColor(); } if (screen != null) { screen.onCurrentFragmentChanged(getCurrentFragment()); screen.setScreenOrientation(screenOrientation); screen.setNavigationBarColor(navigationBarColor); } syncToolbarState(); syncDrawerState(); } private void syncToolbarState() { if (toolbarHandler == null) { return; } NavigationIconType iconType = NavigationIconType.HIDDEN; String title = null; if (currentFragment instanceof FlowrFragment) { iconType = ((FlowrFragment) currentFragment).getNavigationIconType(); title = ((FlowrFragment) currentFragment).getTitle(); } if (iconType == NavigationIconType.CUSTOM) { toolbarHandler.setCustomNavigationIcon(((FlowrFragment) currentFragment).getNavigationIcon()); } else { toolbarHandler.setNavigationIcon(iconType); } toolbarHandler.setToolbarVisible(!(currentFragment instanceof FlowrFragment) || ((FlowrFragment) currentFragment).isToolbarVisible()); toolbarHandler.setToolbarTitle(title != null ? title : ""); } private void syncDrawerState() { if (drawerHandler == null) { return; } drawerHandler.setDrawerEnabled(!(currentFragment instanceof FlowrFragment) || ((FlowrFragment) currentFragment).isDrawerEnabled()); } /** * Creates a new {@link Builder} instance to be used to display a fragment * * @param fragmentClass the class for the fragment to be displayed * @return a new {@link Builder} instance */ public <T extends Fragment & FlowrFragment> Builder open(Class<? extends T> fragmentClass) { return new Builder<>(fragmentClass); } /** * Creates a new {@link Builder} instance to be used to display a fragment * * @param deepLinkIntent An Intent to parse and open the appropriate Fragment. * @return a new {@link Builder} instance */ public Builder open(Intent deepLinkIntent) { return new Builder<>(deepLinkIntent); } /** * Creates a new {@link Builder} instance to be used to display a fragment. * * @param intent An intent that contains a possible Deep link. * @param fragmentClass The fragment to use if the intent doesn't contain a Deep Link. * @param <T> The proper Fragment type. * @return a new {@link Builder} instance */ public <T extends Fragment & FlowrFragment> Builder open(Intent intent, Class<? extends T> fragmentClass) { return new Builder<>(intent, fragmentClass); } /** * Creates a new {@link Builder} instance to be used to display a fragment * * @param path the path of a Fragment annotated with {@link com.fueled.flowr.annotations.DeepLink} * @return a new {@link Builder} instance */ public Builder open(String path) { Uri uri = Uri.parse(path); Intent intent = new Intent(); intent.setData(uri); return open(intent); } /** * The default enter animation to be used for fragment transactions * * @return the default fragment enter animation */ protected int getDefaultEnterAnimation() { return FragmentTransaction.TRANSIT_NONE; } /** * The default exit animation to be used for fragment transactions * * @return the default fragment exit animation */ protected int getDefaultExitAnimation() { return FragmentTransaction.TRANSIT_NONE; } /** * The default pop enter animation to be used for fragment transactions * * @return the default fragment pop enter animation */ protected int getDefaultPopEnterAnimation() { return FragmentTransaction.TRANSIT_NONE; } /** * The default pop exit animation to be used for fragment transactions * * @return the default fragment pop exit animation */ protected int getDefaultPopExitAnimation() { return FragmentTransaction.TRANSIT_NONE; } @Override public void onClick(View view) { onNavigationIconClicked(); } public void onDestroy() { setRouterScreen(null); setToolbarHandler(null); setDrawerHandler(null); } /** * This builder class is used to show a new fragment inside the current activity */ public class Builder<T extends Fragment & FlowrFragment> { private TransactionData<T> data; public Builder(Class<? extends T> fragmentClass) { data = new TransactionData<>(fragmentClass, getDefaultEnterAnimation(), getDefaultExitAnimation(), getDefaultPopEnterAnimation(), getDefaultPopExitAnimation()); } public Builder(Intent intent) { data = new TransactionData<>(null, getDefaultEnterAnimation(), getDefaultExitAnimation(), getDefaultPopEnterAnimation(), getDefaultPopExitAnimation()); data.setDeepLinkIntent(intent); } public Builder(Intent intent, Class<? extends T> fragmentClass) { data = new TransactionData<>(fragmentClass, getDefaultEnterAnimation(), getDefaultExitAnimation(), getDefaultPopEnterAnimation(), getDefaultPopExitAnimation()); data.setDeepLinkIntent(intent); } /** * Sets the construction arguments for fragment to be displayed. * * @param args the construction arguments for this fragment. */ public Builder setData(Bundle args) { data.setArgs(args); return this; } /** * Specifies if this fragment should not be added to the back stack. */ public Builder skipBackStack(boolean skipBackStack) { data.setSkipBackStack(skipBackStack); return this; } /** * Specifies if the fragment manager back stack should be cleared. */ public Builder clearBackStack(boolean clearBackStack) { data.setClearBackStack(clearBackStack); return this; } /** * Specifies if this fragment should replace the current fragment. */ public Builder replaceCurrentFragment(boolean replaceCurrentFragment) { data.setReplaceCurrentFragment(replaceCurrentFragment); return this; } /** * Specifies the animations to be used for this transaction. * * @param enterAnim the fragment enter animation. * @param exitAnim the fragment exit animation. */ public Builder setCustomTransactionAnimation(@AnimRes int enterAnim, @AnimRes int exitAnim) { return setCustomTransactionAnimation(enterAnim, FragmentTransaction.TRANSIT_NONE, FragmentTransaction.TRANSIT_NONE, exitAnim); } /** * Set a Custom Animation to a Fragment transaction. * * @param enterAnim The animation resource to be used when the next fragment enters. * @param exitAnim The animation resource to be used when the current fragment exits. * @param popEnterAnim The animation resource to be used when the previous fragment enters on back pressed. * @param popExitAnim The animation resource to be used when the current fragment exits on back pressed.. */ public Builder setCustomTransactionAnimation(@AnimRes int enterAnim, @AnimRes int exitAnim, @AnimRes int popEnterAnim, @AnimRes int popExitAnim) { data.setEnterAnim(enterAnim); data.setExitAnim(exitAnim); data.setPopEnterAnim(popEnterAnim); data.setPopExitAnim(popExitAnim); return this; } /** * Don't use any animations for this transaction */ public Builder noTransactionAnimation() { return setCustomTransactionAnimation(FragmentTransaction.TRANSIT_NONE, FragmentTransaction.TRANSIT_NONE); } /** * Displays the fragment using this builder configurations. */ public void displayFragment() { Flowr.this.displayFragment(data); } /** * Displays the fragment for results using this builder configurations. * * @param fragmentId a unique ID that the fragment requesting the results can be identified by, * it will be later used to deliver the results to the correct fragment instance. * @param requestCode this code will be returned in {@link ResultResponse} when the fragment is closed, * and it can be used to identify the request from which the results were returned. */ public void displayFragmentForResults(String fragmentId, int requestCode) { if (!TextUtils.isEmpty(fragmentId)) { if (data.getArgs() == null) { data.setArgs(new Bundle()); } data.getArgs().putBundle(KEY_REQUEST_BUNDLE, getResultRequestBundle(fragmentId, requestCode)); } Flowr.this.displayFragment(data); } private Bundle getResultRequestBundle(String fragmentId, int requestCode) { Bundle request = new Bundle(); request.putString(KEY_FRAGMENT_ID, fragmentId); request.putInt(KEY_REQUEST_CODE, requestCode); return request; } } }
// Triple Play - utilities for use in PlayN-based games package tripleplay.ui; import pythagoras.f.Dimension; import pythagoras.f.IDimension; import pythagoras.f.IPoint; import pythagoras.f.IRectangle; import pythagoras.f.MathUtil; import pythagoras.f.Point; import pythagoras.f.Rectangle; import react.Signal; import react.SignalView; import react.Slot; import react.UnitSlot; import playn.core.GroupLayer; import playn.core.Layer; import playn.core.PlayN; import tripleplay.util.Ref; /** * The root of the interface element hierarchy. See {@link Widget} for the root of all interactive * elements, and {@link Elements} for the root of all grouping elements. * * @param T used as a "self" type; when subclassing {@code Element}, T must be the type of the * subclass. */ public abstract class Element<T extends Element<T>> { /** The layer associated with this element. */ public final GroupLayer layer = createLayer(); protected Element () { // optimize hit testing by checking our bounds first layer.setHitTester(new Layer.HitTester() { public Layer hitTest (Layer layer, Point p) { Layer hit = null; if (isVisible() && contains(p.x, p.y)) { if (isSet(Flag.HIT_DESCEND)) hit = layer.hitTestDefault(p); if (hit == null && isSet(Flag.HIT_ABSORB)) hit = layer; } return hit; } @Override public String toString () { return "HitTester for " + Element.this; } }); // descend by default set(Flag.HIT_DESCEND, true); } /** * Returns this element's x offset relative to its parent. */ public float x () { return layer.tx(); } /** * Returns this element's y offset relative to its parent. */ public float y () { return layer.ty(); } /** * Returns the width and height of this element's bounds. */ public IDimension size () { return _size; } /** * Writes the location of this element (relative to its parent) into the supplied point. * @return {@code loc} for convenience. */ public IPoint location (Point loc) { return loc.set(x(), y()); } /** * Writes the current bounds of this element into the supplied bounds. * @return {@code bounds} for convenience. */ public IRectangle bounds (Rectangle bounds) { bounds.setBounds(x(), y(), _size.width, _size.height); return bounds; } /** * Returns the parent of this element, or null. */ public Elements<?> parent () { return _parent; } /** * Returns a signal that will dispatch when this element is added or removed from the * hierarchy. The emitted value is true if the element was just added to the hierarchy, false * if removed. */ public SignalView<Boolean> hierarchyChanged () { if (_hierarchyChanged == null) _hierarchyChanged = Signal.create(); return _hierarchyChanged; } /** * Returns the styles configured on this element. */ public Styles styles () { return _styles; } /** * Configures the styles for this element. Any previously configured styles are overwritten. * @return this element for convenient call chaining. */ public T setStyles (Styles styles) { _styles = styles; clearLayoutData(); invalidate(); return asT(); } /** * Configures styles for this element (in the DEFAULT mode). Any previously configured styles * are overwritten. * @return this element for convenient call chaining. */ public T setStyles (Style.Binding<?>... styles) { return setStyles(Styles.make(styles)); } /** * Adds the supplied styles to this element. Where the new styles overlap with existing styles, * the new styles are preferred, but non-overlapping old styles are preserved. * @return this element for convenient call chaining. */ public T addStyles (Styles styles) { _styles = _styles.merge(styles); clearLayoutData(); invalidate(); return asT(); } /** * Adds the supplied styles to this element (in the DEFAULT mode). Where the new styles overlap * with existing styles, the new styles are preferred, but non-overlapping old styles are * preserved. * @return this element for convenient call chaining. */ public T addStyles (Style.Binding<?>... styles) { return addStyles(Styles.make(styles)); } /** * Returns <code>this</code> cast to <code>T</code>. */ @SuppressWarnings({"unchecked", "cast"}) protected T asT () { return (T)this; } /** * Returns whether this element is enabled. */ public boolean isEnabled () { return isSet(Flag.ENABLED); } /** * Enables or disables this element. Disabled elements are not interactive and are usually * rendered so as to communicate this state to the user. */ public T setEnabled (boolean enabled) { if (enabled != isEnabled()) { set(Flag.ENABLED, enabled); clearLayoutData(); invalidate(); } return asT(); } /** * Returns a slot which can be used to wire the enabled status of this element to a {@link * react.Signal} or {@link react.Value}. */ public Slot<Boolean> enabledSlot () { return new Slot<Boolean>() { public void onEmit (Boolean value) { setEnabled(value); } }; } /** * Returns whether this element is visible. */ public boolean isVisible () { return isSet(Flag.VISIBLE); } /** * Configures whether this element is visible. An invisible element is not rendered and * consumes no space in a group. */ public T setVisible (boolean visible) { if (visible != isVisible()) { set(Flag.VISIBLE, visible); layer.setVisible(visible); invalidate(); } return asT(); } /** * Returns a slot which can be used to wire the visible status of this element to a {@link * react.Signal} or {@link react.Value}. */ public Slot<Boolean> visibleSlot () { return new Slot<Boolean>() { public void onEmit (Boolean value) { setVisible(value); } }; } /** * Returns true only if this element and all its parents' {@link #isVisible()} return true. */ public boolean isShowing () { Elements<?> parent; return isVisible() && ((parent = parent()) != null) && parent.isShowing(); } /** * Returns the layout constraint configured on this element, or null. */ public Layout.Constraint constraint () { return _constraint; } /** * Configures the layout constraint on this element. * @return this element for call chaining. */ public T setConstraint (Layout.Constraint constraint) { if (constraint != null) constraint.setElement(this); _constraint = constraint; invalidate(); return asT(); } /** * Returns true if this element is part of an interface heirarchy. */ public boolean isAdded () { return root() != null; } /** * Returns the class of this element for use in computing its style. By default this is the * actual class, but you may wish to, for example, extend {@link Label} with some customization * and override this method to return {@code Label.class} so that your extension has the same * styles as Label applied to it. * * Concrete Element implementations should return the actual class instance instead of * getClass(). Returning getClass() means that further subclasses will lose all styles applied * to this implementation, probably unintentionally. */ protected abstract Class<?> getStyleClass (); /** * Called when this element is added to a parent element. If the parent element is already * added to a hierarchy with a {@link Root}, this will immediately be followed by a call to * {@link #wasAdded}, otherwise the {@link #wasAdded} call will come later when the parent is * added to a root. */ protected void wasParented (Elements<?> parent) { _parent = parent; } /** * Called when this element is removed from its direct parent. If the element was removed from * a parent that was connected to a {@link Root}, a call to {@link #wasRemoved} will * immediately follow. Otherwise no call to {@link #wasRemoved} will be made. */ protected void wasUnparented () { _parent = null; } /** * Called when this element (or its parent element) was added to an interface hierarchy * connected to a {@link Root}. The element will subsequently be validated and displayed * (assuming it's visible). */ protected void wasAdded () { if (_hierarchyChanged != null) _hierarchyChanged.emit(Boolean.TRUE); invalidate(); set(Flag.IS_ADDING, false); } /** * Called when this element (or its parent element) was removed from the interface hierarchy. * Also, if the element was removed directly from its parent, then the layer is orphaned prior * to this call. Furthermore, if the element is being destroyed (see {@link Elements#destroy} * and other methods), the destruction of the layer will occur <b>after</b> this method * returns and the {@link #willDestroy()} method returns true. This allows subclasses to * manage resources as needed. <p><b>NOTE</b>: the base class method must <b>always</b> be * called for correct operation.</p> */ protected void wasRemoved () { _bginst.clear(); if (_hierarchyChanged != null) _hierarchyChanged.emit(Boolean.FALSE); set(Flag.IS_REMOVING, false); } /** * Returns true if the supplied, element-relative, coordinates are inside our bounds. */ protected boolean contains (float x, float y) { return !(x < 0 || x > _size.width || y < 0 || y > _size.height); } /** * Returns whether this element is selected. This is only applicable for elements that maintain * a selected state, but is used when computing styles for all elements (it is assumed that an * element that maintains no selected state will always return false from this method). * Elements that do maintain a selected state should override this method and expose it as * public. */ protected boolean isSelected () { return isSet(Flag.SELECTED); } /** * An element should call this method when it knows that it has changed in such a way that * requires it to recreate its visualization. */ protected void invalidate () { // note that our preferred size and background are no longer valid _preferredSize = null; if (isSet(Flag.VALID)) { set(Flag.VALID, false); // invalidate our parent if we've got one if (_parent != null) { _parent.invalidate(); } } } /** * Gets a new slot which will invoke {@link #invalidate()} when emitted. */ protected UnitSlot invalidateSlot () { return invalidateSlot(false); } /** * Gets a new slot which will invoke {@link #invalidate()}. * @param styles if set, the slot will also call {@link #clearLayoutData()} when emitted */ protected UnitSlot invalidateSlot (final boolean styles) { return new UnitSlot() { @Override public void onEmit () { invalidate(); if (styles) clearLayoutData(); } }; } /** * Does whatever this element needs to validate itself. This may involve recomputing * visualizations, or laying out children, or anything else. */ protected void validate () { if (!isSet(Flag.VALID)) { layout(); set(Flag.VALID, true); } } /** * Returns the root of this element's hierarchy, or null if the element is not currently added * to a hierarchy. */ protected Root root () { return (_parent == null) ? null : _parent.root(); } /** * Returns whether the specified flag is set. */ protected boolean isSet (Flag flag) { return (flag.mask & _flags) != 0; } /** * Sets or clears the specified flag. */ protected void set (Flag flag, boolean on) { if (on) { _flags |= flag.mask; } else { _flags &= ~flag.mask; } } /** * Returns this element's preferred size, potentially recomputing it if needed. * * @param hintX if non-zero, an indication that the element will be constrained in the x * direction to the specified width. * @param hintY if non-zero, an indication that the element will be constrained in the y * direction to the specified height. */ protected IDimension preferredSize (float hintX, float hintY) { if (_preferredSize == null) { Dimension psize = computeSize(hintX, hintY); if (_constraint != null) _constraint.adjustPreferredSize(psize, hintX, hintY); // round our preferred size up to the nearest whole number; if we allow it to remain // fractional, we can run into annoying layout problems where floating point rounding // error causes a tiny fraction of a pixel to be shaved off of the preferred size of a // text widget, causing it to wrap its text differently and hosing the layout psize.width = MathUtil.iceil(psize.width); psize.height = MathUtil.iceil(psize.height); _preferredSize = psize; } return _preferredSize; } /** * Configures the location of this element, relative to its parent. */ protected void setLocation (float x, float y) { layer.setTranslation(MathUtil.ifloor(x), MathUtil.ifloor(y)); } /** * Configures the size of this widget. */ protected T setSize (float width, float height) { boolean changed = _size.width != width || _size.height != height; _size.setSize(width, height); // if we have a cached preferred size and this size differs from it, we need to clear our // layout data as it may contain computations specific to our preferred size if (_preferredSize != null && !_size.equals(_preferredSize)) clearLayoutData(); if (changed) invalidate(); return asT(); } /** * Resolves the value for the supplied style. See {@link Styles#resolveStyle} for the gritty * details. */ protected <V> V resolveStyle (Style<V> style) { return Styles.resolveStyle(this, style); } /** * Recomputes this element's preferred size. * * @param hintX if non-zero, an indication that the element will be constrained in the x * direction to the specified width. * @param hintY if non-zero, an indication that the element will be constrained in the y * direction to the specified height. */ protected Dimension computeSize (float hintX, float hintY) { LayoutData ldata = _ldata = createLayoutData(hintX, hintY); Dimension size = ldata.computeSize(hintX - ldata.bg.width(), hintY - ldata.bg.height()); return ldata.bg.addInsets(size); } /** * Handles common element layout (background), then calls {@link LayoutData#layout} to do the * actual layout. */ protected void layout () { if (!isVisible()) return; float width = _size.width, height = _size.height; LayoutData ldata = (_ldata != null) ? _ldata : createLayoutData(width, height); // if we have a non-matching background, destroy it (note that if we don't want a bg, any // existing bg will necessarily be invalid) Background.Instance bginst = _bginst.get(); boolean bgok = (bginst != null && bginst.owner() == ldata.bg && bginst.size.equals(_size)); if (!bgok) _bginst.clear(); // if we want a background and don't already have one, create it if (width > 0 && height > 0 && !bgok) { bginst = _bginst.set(ldata.bg.instantiate(_size)); bginst.addTo(layer, 0, 0, 0); } // do our actual layout ldata.layout(ldata.bg.left, ldata.bg.top, width - ldata.bg.width(), height - ldata.bg.height()); // finally clear our cached layout data clearLayoutData(); } /** * Creates the layout data record used by this element. This record temporarily holds resolved * style information between the time that an element has its preferred size computed, and the * time that the element is subsequently laid out. Note: {@code hintX} and {@code hintY} <em>do * not</em> yet have the background insets subtracted from them, because the creation of the * LayoutData is what resolves the background in the first place. */ protected abstract LayoutData createLayoutData (float hintX, float hintY); /** * Clears out cached layout data. This can be called by methods that change the configuration * of the element when they know it will render pre-computed layout info invalid. */ protected void clearLayoutData () { _ldata = null; } /** * Creates the layer to be used by this element. Subclasses may override to use a clipped one. */ protected GroupLayer createLayer () { return PlayN.graphics().createGroupLayer(); } /** * Tests if this element is about to be destroyed. Elements are destroyed via a call to one of * the "destroy" methods such as {@link Elements#destroy(Element)}. This allows subclasses * to manage resources appropriately during their implementation of {@link #wasRemoved}, for * example clearing a child cache. <p>NOTE: at the expense of slight semantic dissonance, * the flag is not cleared after destruction</p> */ protected boolean willDestroy () { return isSet(Flag.WILL_DESTROY); } /** * Tests if this element is scheduled to be removed from a root hierarchy. */ protected final boolean willRemove () { return isSet(Flag.IS_REMOVING) || (_parent != null && _parent.willRemove()); } /** * Tests if this element is scheduled to be added to a root hierarchy. */ protected final boolean willAdd () { return isSet(Flag.IS_ADDING) || (_parent != null && _parent.willAdd()); } protected abstract class BaseLayoutData { /** * Rebuilds this element's visualization. Called when this element's size has changed. In * the case of groups, this will relayout its children, in the case of widgets, this will * rerender the widget. */ public void layout (float left, float top, float width, float height) { // noop! } } protected abstract class LayoutData extends BaseLayoutData { public final Background bg = resolveStyle(Style.BACKGROUND); /** * Computes this element's preferred size, given the supplied hints. The background insets * will be automatically added to the returned size. */ public abstract Dimension computeSize (float hintX, float hintY); } /** Ways in which a preferred and an original dimension can be "taken" to produce a result. * The name is supposed to be readable in context and compact, for example * <code>new SizableLayoutData(...).forWidth(Take.MAX).forHeight(Take.MIN, 200)</code>. */ protected enum Take { /** Uses the maximum of the preferred size and original. */ MAX { @Override public float apply (float preferred, float original) { return Math.max(preferred, original); } }, /** Uses the minimum of the preferred size and original. */ MIN { @Override public float apply (float preferred, float original) { return Math.min(preferred, original); } }, /** Uses the preferred size if non-zero, otherwise the original. This is the default. */ PREFERRED_IF_SET { @Override public float apply (float preferred, float original) { return preferred == 0 ? original : preferred; } }; public abstract float apply (float preferred, float original); } /** * A layout data that will delegate to another layout data instance, but alter the size * computation to optionally use fixed values. */ protected class SizableLayoutData extends LayoutData { /** * Creates a new layout with the given delegates and size. * @param layoutDelegate the delegate to use during layout. May be null if the element * has no layout * @param sizeDelegate the delegate to use during size computation. May be null if the * size will be completely specified by <code>prefSize</code> * @param prefSize overrides the size computation. The width and/or height may be zero, * which indicates the <code>sizeDelegate</code>'s result should be used for that axis. * Passing <code>null</code> is equivalent to passing a 0x0 dimension */ public SizableLayoutData (BaseLayoutData layoutDelegate, LayoutData sizeDelegate, IDimension prefSize) { this.layoutDelegate = layoutDelegate; this.sizeDelegate = sizeDelegate; if (prefSize != null) { prefWidth = prefSize.width(); prefHeight = prefSize.height(); } else { prefWidth = prefHeight = 0; } } /** * Creates a new layout that will defer to the given delegate for layout and size. This * is equivalent to <code>SizableLayoutData(delegate, delegate, prefSize)</code>. * @see #SizableLayoutData(BaseLayoutData, LayoutData, IDimension) */ public SizableLayoutData (LayoutData delegate, IDimension prefSize) { this.layoutDelegate = delegate; this.sizeDelegate = delegate; if (prefSize != null) { prefWidth = prefSize.width(); prefHeight = prefSize.height(); } else { prefWidth = prefHeight = 0; } } /** * Sets the way in which widths are combined to calculate the resulting preferred size. * For example, <code>new SizeableLayoutData(...).forWidth(Take.MAX)</code>. */ public SizableLayoutData forWidth (Take fn) { widthFn = fn; return this; } /** * Sets the preferred width and how it should be combined with the delegate's preferred * width. For example, <code>new SizeableLayoutData(...).forWidth(Take.MAX, 250)</code>. */ public SizableLayoutData forWidth (Take fn, float pref) { widthFn = fn; prefWidth = pref; return this; } /** * Sets the way in which heights are combined to calculate the resulting preferred size. * For example, <code>new SizeableLayoutData(...).forHeight(Take.MAX)</code>. */ public SizableLayoutData forHeight (Take fn) { heightFn = fn; return this; } /** * Sets the preferred height and how it should be combined with the delegate's preferred * height. For example, <code>new SizeableLayoutData(...).forHeight(Take.MAX, 250)</code>. */ public SizableLayoutData forHeight (Take fn, float pref) { heightFn = fn; prefHeight = pref; return this; } @Override public Dimension computeSize (float hintX, float hintY) { // hint the delegate with our preferred width or height or both hintX = select(prefWidth, hintX); hintY = select(prefHeight, hintY); // get the usual size Dimension dim = sizeDelegate == null ? new Dimension(prefWidth, prefHeight) : sizeDelegate.computeSize(hintX, hintY); // swap in our preferred width or height or both dim.width = widthFn.apply(prefWidth, dim.width); dim.height = heightFn.apply(prefHeight, dim.height); return dim; } @Override public void layout (float left, float top, float width, float height) { if (layoutDelegate != null) layoutDelegate.layout(left, top, width, height); } protected float select (float pref, float base) { return pref == 0 ? base : pref; } protected final BaseLayoutData layoutDelegate; protected final LayoutData sizeDelegate; protected float prefWidth, prefHeight; protected Take widthFn = Take.PREFERRED_IF_SET, heightFn = Take.PREFERRED_IF_SET; } protected int _flags = Flag.VISIBLE.mask | Flag.ENABLED.mask; protected Elements<?> _parent; protected Dimension _preferredSize; protected Dimension _size = new Dimension(); protected Styles _styles = Styles.none(); protected Layout.Constraint _constraint; protected Signal<Boolean> _hierarchyChanged; protected LayoutData _ldata; protected final Ref<Background.Instance> _bginst = Ref.<Background.Instance>create(null); protected static enum Flag { VALID(1 << 0), ENABLED(1 << 1), VISIBLE(1 << 2), SELECTED(1 << 3), WILL_DESTROY(1 << 4), HIT_DESCEND(1 << 5), HIT_ABSORB(1 << 6), IS_REMOVING(1 << 7), IS_ADDING(1 << 8); public final int mask; Flag (int mask) { this.mask = mask; } }; }
package xal.model.probe.traj; import xal.tools.RealNumericIndexer; import xal.tools.data.DataAdaptor; import xal.tools.data.DataFormatException; import xal.tools.data.IArchive; import xal.model.probe.Probe; import xal.model.xml.ParsingException; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.Date; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeMap; /** * Manages the history for a probe. Saves <code>ProbeState</code> objects, * each of which reflects the state of the <code>Probe</code> at a particular * point in time. * * @author Craig McChesney * @author Christopher K. Allen * (cosmetic enhancements) * @version $id: * */ public class Trajectory<S extends ProbeState<S>> implements IArchive, Iterable<S> { /* * Global Constants */ /** XML element tag for trajectory */ public final static String TRAJ_LABEL = "trajectory"; /** XML element tag for trajectory concrete type */ private final static String TYPE_LABEL = "type"; /** XML element tag for time stamp data */ private static final String TIMESTAMP_LABEL = "timestamp"; /** XML element tag for user comment data */ private static final String DESCRIPTION_LABEL = "description"; /* * Local Types */ /** * <p> * Maintains a list of probe states for every each element class. Each element * class is refined as the collection is built. States are placed into the map * using the modeling element ID as the key. If it is found that that element ID * is similar to an existing element ID, than the state is entered into the element * ID class. By similar, we mean that one ID string can be contained within another * ID (or is equal to). * </p> * <p> * The idea is that each element ID class is then representative of probe states associated * with a single hardware node. See {@link IdentifierEquivClass} for another explanation. * </p> * <p> * <h4>NOTES:</h4> * &middot; I am not sure if we have to explicitly consider the empty identifier string. * This empty ID is a substring of all IDs. * <br/> * &middot; But we use the * <code>{@link TreeMap#ceilingEntry(Object)}</code> for access so that may * circumvent things. * <br/> * &middot; The easy thing to do might be just to reject empty strings in * <code>{@link #putState(String, ProbeState)}</code> * </p> * * @author Christopher K. Allen * @since Aug 14, 2014 */ private class NodeIdToElemStates { /** Comparator defining the order of String ID keys in the tree map */ private final Comparator<String> cmpKeyOrder; /** Map of SMF node identifiers to probe states within all modeling elements */ private final TreeMap<String, RealNumericIndexer<S>> mapNodeToStates; /** The last map entry to be accessed when adding a new probe state */ private Map.Entry<String, RealNumericIndexer<S>> entryLast; /* * Initialization */ /** * Creates a new uninitialized instance of <code>ElementStateMap</code>. * * @author Christopher K. Allen * @since Jun 5, 2013 */ public NodeIdToElemStates() { // Create the comparator for ordering the tree map nodes according to node IDs // Then create the map itself this.cmpKeyOrder = new Comparator<String>() { @Override public int compare(String strId1, String strId2) { if ( strId1.contentEquals(strId2) ) return 0; else if (strId2.contains(strId1) ) return 0; else if (strId1.contains(strId2)) return 0; else return strId1.compareTo(strId2); } }; this.mapNodeToStates = new TreeMap<String, RealNumericIndexer<S>>(cmpKeyOrder); // Create a blank last map entry String ideEmpty = new String("XXX - Root Node"); RealNumericIndexer<S> setIdEmpty = new RealNumericIndexer<S>(); // this.mapNodeToStates.put(ideEmpty, setIdEmpty); this.entryLast = new AbstractMap.SimpleEntry<String, RealNumericIndexer<S>>(ideEmpty, setIdEmpty); } /* * Operations */ /** * <p> * Enters the given probe state into the map using the element's * hardware node ID as the * key. Note that this key can be changed internally (clobbered) if the * element ID belongs to an hardware ID class already identified. * </p> * <p> * To improve efficiency the method checks if the state's hardware node ID * (of the state's associated element) is the same * (i.e., same equivalence class) as the last one provided in the previous call * to this method. A reference to the list of states for that ID is kept * on hand so a full map search is not used. * </p> * * @param strSmfNodeId hardware node ID of the modeling element associated with the given probe state * @param state probe state to be entered into the map * * @author Christopher K. Allen * @since Aug 14, 2014 */ public void putState(String strSmfNodeId, S state) { // We're going to reject the empty ID if (strSmfNodeId.equals("")) return; // Get the Node ID class for last node accessed (needed for mapping elements) // and get the position of the state within the sequence // (needed for indexing states within elements) double dblPos = state.getPosition(); String strIdLast = this.entryLast.getKey(); // The state is a member of the last equivalence class accessed // if ( this.entryLast.getKey().equals(strNodeId) ) { // if ( strNodeId.startsWith(strIdLast) ) { if ( this.cmpKeyOrder.compare(strIdLast, strSmfNodeId) == 0 ) { RealNumericIndexer<S> setStates = this.entryLast.getValue(); setStates.add(dblPos, state); return; } // This is a new equivalence class - that is, different then the last accessed // Get the list of states corresponding to the ID class RealNumericIndexer<S> setStates = this.mapNodeToStates.get(strSmfNodeId); // If there is no element list for this ID class, create one and add it to the map if (setStates == null) { this.createNewEquivClass(strSmfNodeId, state); return; } setStates.add(dblPos, state); // This will have the same equiv. class ID this.updateLastEntry(strSmfNodeId, setStates); } /** * Returns a set of position ordered probe states corresponding to * the given hardware node ID. * * @param strSmfNodeId model element identifier * * @return all the probe states which are associated with the given * hardware node ID, or <code>null</code> if there are none * * @author Christopher K. Allen * @since Aug 14, 2014 */ public List<S> getStates(String strSmfNodeId) { // Specific case; We get lucky, the given node ID is in the last equivalence class accessed String strIdLast = this.entryLast.getKey(); if ( this.cmpKeyOrder.compare(strSmfNodeId, strIdLast) == 0) { RealNumericIndexer<S> setStates = this.entryLast.getValue(); return setStates.toList(); } // The general case: We must get the list of states corresponding to the ID class RealNumericIndexer<S> setStates = this.mapNodeToStates.get(strSmfNodeId); if (setStates == null) return null; List<S> lstStates = setStates.toList(); return lstStates; } /** * Return all the states managed by this map as a list. * * @return all probe states managed by this element state map * * @author Christopher K. Allen * @since Aug 26, 2014 */ public List<S> getAllStates() { List<S> lstStates = new LinkedList<S>(); Collection< RealNumericIndexer<S> > setLists = this.mapNodeToStates.values(); for (RealNumericIndexer<S> rni : setLists) { Iterator<S> iter = rni.iterator(); while (iter.hasNext()) { S state = iter.next(); lstStates.add(state); } } return lstStates; } /* * Support Methods */ /** * Creates a new set of probe states to go into the * (NodeID,{probe states}) mapping. The given probe state is * used as the first element in the new set and the given * equivalence class identifier is used to key the map. The set * is created and put into the map. * * @param strClsId ID of the equivalence class of probe states * (usually a hardware node prefix) * @param stateFirst The first (and only) state in the new state set * * @author Christopher K. Allen * @since Aug 14, 2014 */ private void createNewEquivClass(String strClsId, S stateFirst) { // Create the set of probe states (indexed by position) // and add the given state to this new set RealNumericIndexer<S> setStates = new RealNumericIndexer<S>(); double dblPos = stateFirst.getPosition(); setStates.add(dblPos, stateFirst); // Now put the equivalence class ID - probe state pair into the map this.mapNodeToStates.put(strClsId, setStates); // Save the last list to be accessed this.updateLastEntry(strClsId, setStates); } /** * Convenience method for reseting the last entry maintained by this class. * Saves the space of having to write out all the nested types and * generic information. * * @param strClsId ID of the equivalence class of probe states * (usually a hardware node prefix) * @param setStates The set of probe states belonging to the given class ID * * @author Christopher K. Allen * @since Aug 14, 2014 */ private void updateLastEntry(String strClsId, RealNumericIndexer<S> setStates) { this.entryLast = new AbstractMap.SimpleEntry<String, RealNumericIndexer<S>>(strClsId, setStates); } } // /** // * <p> // * Maintains a list of probe states for every each element class. Each element // * class is refined as the collection is built. States are placed into the map // * using the modeling element ID as the key. If it is found that that element ID // * is similar to an existing element ID, than the state is entered into the element // * ID class. By similar, we mean that one ID string can be contained within another // * ID (or is equal to). // * </p> // * <p> // * The idea is that each element ID class is then representative of probe states associated // * with a single hardware node. See {@link IdentifierEquivClass} for another explanation. // * </p> // * // * @param <S> probe state type for particular probe trajectory // * // * @author Christopher K. Allen // * @since Jun 5, 2013 // */ // private static class ElementStateMap<S extends ProbeState<S>> { // /* // * Local Attributes // */ // /** map from element prefix to element states */ // private final Map<String, RealNumericIndexer<S>> mapStateList; // /** the last map entry to be accessed (added to) */ // private Map.Entry<String, RealNumericIndexer<S>> entryLast; // /* // * Initialization // */ // /** // * Creates a new uninitialized instance of <code>ElementStateMap</code>. // * // * @author Christopher K. Allen // * @since Jun 5, 2013 // */ // public ElementStateMap() { // // Create the comparator for ordering the tree map nodes // // Then create the map itself // Comparator<String> cmpIdClsOrder = new Comparator<String>() { // @Override // public int compare(String id1, String id2) { // return id1.compareTo(id2); // this.mapStateList = new TreeMap<String, RealNumericIndexer<S>>(cmpIdClsOrder); // // Create a blank last map entry // String ideEmpty = new String(""); // RealNumericIndexer<S> setIdEmpty = new RealNumericIndexer<S>(); // this.mapStateList.put(ideEmpty, setIdEmpty); // this.entryLast = new AbstractMap.SimpleEntry<String, RealNumericIndexer<S>>(ideEmpty, setIdEmpty); // /* // * Operations // */ // /** // * <p> // * Enters the given probe state into the map using the element ID as the // * initial key. Note that this key can be changed internally if the // * element ID belongs to an element ID class already identified. // * </p> // * <p> // * To improve efficiency the method checks if the given element ID is the same // * (same equivalence class, that is) as the last one provided in the previous call // * to this method. A reference to the list of elements for that ID is kept // * on hand so a full map search is not used. // * </p> // * // * @param strElemId string identifier of the modeling element associated with the probe state // * @param state probe state to be entered into the map // * // * @author Christopher K. Allen // * @since Jun 5, 2013 // */ // public void putState(String strElemId, S state) { // // Create the ID class for the element ID (needed for indexing elements) // // and get the position of the state within the sequence (needed for indexing states within elements) // String idElem = strElemId; // double dblPos = state.getPosition(); // // The state is a member of the last equivalence class accessed // if ( this.entryLast.getKey().equals(idElem) ) { // RealNumericIndexer<S> setStates = this.entryLast.getValue(); // setStates.add(dblPos, state); // return; // // This is a new equivalence class - that is, different then the last accessed // // Get the list of states corresponding to the ID class // RealNumericIndexer<S> setStates = this.mapStateList.get(idElem); // // If there is no list for this ID class, create one and add it to the map // if (setStates == null) { // setStates = new RealNumericIndexer<S>(); // this.mapStateList.put(idElem, setStates); // // Add the given state to the list // setStates.add(dblPos, state); // // Save the last list to be accessed // this.entryLast = new AbstractMap.SimpleEntry<String, RealNumericIndexer<S>>(idElem, setStates); // /** // * Returns a list of probe states corresponding to the identifier // * class containing the given modeling element ID. // * // * @param strElemId model element identifier // * // * @return all the probe states which are associated with the given element ID and its class, // * or <code>null</code> if there are none // * // * @author Christopher K. Allen // * @since Jun 5, 2013 // */ // public RealNumericIndexer<S> getStates(String strElemId) { // RealNumericIndexer<S> lstStates = this.mapStateList.get(strElemId); // return lstStates; // /** // * Return all the states managed by this map as a list. // * // * @return all probe states managed by this element state map // * // * @author Christopher K. Allen // * @since Aug 26, 2014 // */ // public List<S> getAllStates() { // List<S> lstStates = new LinkedList<S>(); // Collection< RealNumericIndexer<S> > setLists = this.mapStateList.values(); // for (RealNumericIndexer<S> rni : setLists) { // Iterator<S> iter = rni.iterator(); // while (iter.hasNext()) { // S state = iter.next(); // lstStates.add(state); // return lstStates; /* * Local Attributes */ /** any user comments regard the trajectory */ private String description = ""; /** the history of probe states along the trajectory */ private RealNumericIndexer<S> _history; /** Probe states by element name */ // private final ElementStateMap<S> mapIdToStates; private final NodeIdToElemStates mapIdToStates; /** Type class of the underlying state objects */ private final Class<S> clsStates; /** time stamp of trajectory */ private Date timestamp = new Date(); // I think this will have to be rewritten once the other trajectory classes // are gone since there will be no way to instantiate [newInstance()] /** * Read the contents of the supplied <code>DataAdaptor</code> and return * an instance of the appropriate Trajectory species. * * @param container <code>DataAdaptor</code> to read a Trajectory from * @return a Trajectory for the contents of the DataAdaptor * @throws ParsingException error encountered reading the DataAdaptor */ @SuppressWarnings("unchecked") public static Trajectory<? extends ProbeState<?>> readFrom(DataAdaptor container) throws ParsingException { DataAdaptor daptTraj = container.childAdaptor(Trajectory.TRAJ_LABEL); if (daptTraj == null) throw new ParsingException("Trajectory#readFrom() - DataAdaptor contains no trajectory node"); String type = container.stringValue(Trajectory.TYPE_LABEL); Trajectory<? extends ProbeState<?>> trajectory; try { Class<?> trajectoryClass = Class.forName(type); trajectory = (Trajectory<? extends ProbeState<?>>) trajectoryClass.newInstance(); } catch (Exception e) { e.printStackTrace(); throw new ParsingException(e.getMessage()); } trajectory.load(daptTraj); return trajectory; } /** * Override this method in subclasses to add subclass-specific properties to * the output. Subclass implementations should call super.addPropertiesTo * so that superclass implementations are executed. * * @param container the <code>DataAdaptor</code> to add properties to */ protected void addPropertiesTo(DataAdaptor container) {} /** * Allow subclasses to read subclass-specific properties from the <code> * DataAdaptor</code>. Implementations should call super.readPropertiesFrom * to ensure that superclass implementations are executed. * * @param container <code>DataAdaptor</code> to read properties from */ protected void readPropertiesFrom(DataAdaptor container) throws ParsingException {} // /** // * Create a new, empty <code>Trajectory</code> object. // */ // public Trajectory() { // this._history = new RealNumericIndexer<S>(); // this.mapStates = new ElementStateMap<S>(); // this.clsStates = null; /** * Creates a new <code>Trajectory</code> given the <code>Class&lt;S&gt;</code> * object of the underlying <code>ProbeState</code> type, <code><b>S</b></code>. * * * @param clsStates - the <code>Class&lt;S&gt;</code> object of the underlying * <code>ProbeState</code> type * * @since Jul 1, 2014 */ public Trajectory(final Class<S> clsStates) { this._history = new RealNumericIndexer<S>(); // this.mapStates = new ElementStateMap<S>(); this.mapIdToStates = new NodeIdToElemStates(); this.clsStates = clsStates; } /** * Set the user comment string * * @param strDescr user comment string */ public void setDescription(String strDescr) { description = strDescr; }; /** * Set the time stamp of the trajectory. * * @param lngTimeStamp number of milliseconds since January 1, 1970 GMT */ public void setTimestamp(long lngTimeStamp) { timestamp = new Date(lngTimeStamp); } /** * Gets the <code>Class&lt;S&gt;</code> object of the generic type <b><code>S</code></b>. * * @return a <code>Class&lt;S&gt;</code> object for the class <b><code>S</code></b> * * @author Jonathan M. Freed */ public Class<S> getStateClass() { return this.clsStates; } /** * Captures the specified probe's current state to a <code>ProbeState</code> object * then saves it to the trajectory. State goes at the tail of the trajectory list. * * @param probe target probe object */ public void update(Probe<S> probe) { S state = probe.cloneCurrentProbeState(); saveState(state); } /** * Save the <code>ProbeState</code> object directly to the trajectory at the tail. * @param state new addition to trajectory */ public void saveState( final S state ) { double dblPos = state.getPosition(); _history.add( dblPos, state ); // String strElemId = state.getElementId(); String strSmfNodeId = state.getHardwareNodeId(); this.mapIdToStates.putState(strSmfNodeId, state); } /** * Remove the last state from the trajectory and return it. * * @return the most recent <code>ProbeState</code> in the history */ public S popLastState() { return _history.remove( _history.size() - 1 ); } /** * Return the user comment associated with this trajectory. * * @return user comment (meta-data) */ public String getDescription() {return description; } /** * Return the time stamp of the trajectory object * * @return trajectory time stamp */ public Date getTimestamp() { return timestamp; } /** * Return an Iterator over the iterator's states. */ public Iterator<S> stateIterator() { return _history.iterator(); } /** * Return the number of states in the trajectory. * * @return the number of states */ public int numStates() { return _history.size(); } /** * Returns the probe's initial state or null if there is none. * * @return the probe's initial state or null */ public S initialState() { return stateWithIndex(0); } /** * Returns the probe's final state or null if there is none. * * @return the probe's final state or null */ public S finalState() { return stateWithIndex(numStates()-1); } /** * Get the list of all states in this trajectory managed by the * state map. * * @return a new list of this trajectory's states */ public List<S> getStatesViaStateMap() { return this.mapIdToStates.getAllStates(); } /** * Returns a list of all the states in this trajectory managed by * the state numeric (position) indexer. * * @return * * @author Christopher K. Allen * @since Aug 26, 2014 */ public List<S> getStatesViaIndexer() { return this._history.toList(); } /** * Creates and returns a "sub-trajectory" object built from the contiguous * state objects of this trajectory between the start node <code>strSmfNodeId1</code> * and the stop node <code>strSmfNodeId2</code>. The returned trajectory contains * references to the same states contained in this trajectory, <i>they are not * duplicates</i>. So any modifications made on the returned object will * be reflected here. Also, it is important to note that the returned sub-trajectory * <i>excludes</i> all states belonging to the stop hardware node * <code>strSmfNodeId2</code>. That is, the returned value contains states from, * and including, node 1 up to, but not including, state 2. If you wish to include * the states of both hardware nodes see * <code>{@link #subTrajectoryInclusive(String, String)}</code>. * * @param strSmfNodeId1 hardware node ID defining the first state object in sub-trajectory * @param strSmfNodeId2 hardware node ID defining the last state object in sub-trajectory * * @return sub-trajectory of this trajectory defined by the above hardware nodes * * @author Christopher K. Allen * @since Nov 14, 2014 * * @see #subTrajectoryInclusive(String, String) */ public Trajectory<S> subTrajectory(String strSmfNodeId1, String strSmfNodeId2) { boolean bolStart1 = false; // The returned sub-trajectory Trajectory<S> trjSub = new Trajectory<S>(this.clsStates); // For every state in this trajectory... for (S state : this) { String strStateId = state.getHardwareNodeId(); // Look for the first state, set the "start state found" flag if so if ( strStateId.equals(strSmfNodeId1) ) { bolStart1 = true; } // We have not encountered the first state, skip to loop beginning if ( bolStart1==false ) { continue; } // Check for the stop state. // If found, set the "stop state found" flag and save the current // state to the sub trajectory (if the sub-trajectory contains states // all the way through the last hardware node). // If no longer at stop state we pass through and the // "stop state found" flag is left at true. if ( strStateId.equals(strSmfNodeId2) ) { break; } trjSub.saveState(state); } return trjSub; } /** * Creates and returns a "sub-trajectory" object built from the contiguous * state objects of this trajectory between the start node <code>strSmfNodeId1</code> * and the stop node <code>strSmfNodeId2</code>. The returned trajectory contains * references to the same states contained in this trajectory, <i>they are not * duplicates</i>. So any modifications made on the returned object will * be reflected here. Also, it is important to note that the returned sub-trajectory * <i>includes</i> all states belonging to the stop hardware node * <code>strSmfNodeId2</code>. That is, the returned value contains states from, * and including, node 1 up to and including state 2. If you wish to exclude * the states of both hardware nodes see * <code>{@link #subTrajectory(String, String)}</code>. * * @param strSmfNodeId1 hardware node ID defining the first state object in sub-trajectory * @param strSmfNodeId2 hardware node ID defining the last state object in sub-trajectory * * @return sub-trajectory of this trajectory defined by the above hardware nodes * * @author Christopher K. Allen * @since Nov 14, 2014 * * @see #subTrajectory(String, String) */ public Trajectory<S> subTrajectoryInclusive(String strSmfNodeId1, String strSmfNodeId2) { boolean bolStart1 = false; boolean bolStop2 = false; // The returned sub-trajectory Trajectory<S> trjSub = new Trajectory<S>(this.clsStates); // For every state in this trajectory... for (S state : this) { String strStateId = state.getHardwareNodeId(); // Look for the first state, set the "start state found" flag if so if ( strStateId.equals(strSmfNodeId1) ) { bolStart1 = true; } // We have not encountered the first state, skip to loop beginning if ( bolStart1==false ) { continue; } // Check for the stop state. // If found, set the "stop state found" flag and save the current // state to the sub trajectory (if the subtrajectory contains states // all the way through the last hardware node). // If no longer at stop state we pass through and the // "stop state found" flag is left at true. if ( strStateId.equals(strSmfNodeId2) ) { bolStop2 = true; trjSub.saveState(state); continue; } // If we have made it this far we have // bolStart1 = true // and bolStop2 depends upon whether or not the above // if conditional set it. If not, than we have not hit // the last element yet. if ( bolStop2 == false ) { trjSub.saveState(state); } // We have // bolStart1 = true // bolStop2 = true; // We have started and stopped. All the states of the // subtrajectory have been collected and we are done. if ( bolStop2 == true) { break; } } return trjSub; } /** * Returns the probe state at the specified position. Returns null if there * is no state for the specified position. */ public S stateAtPosition(double pos) { for(S state : _history) { if (state.getPosition() == pos) return state; } return null; } /** * Get the state that is closest to the specified position * @param position the position for which to find a state * @return the state nearest the specified position */ public S stateNearestPosition( final double position ) { final int index = _history.getClosestIndex( position ); return _history.size() > 0 ? _history.get( index ) : null; } // Does the return type need to be an array? Otherwise an ArrayList would // support generics /** * Returns the states that fall within the specified position range, inclusive. * @param low lower bound on position range * @param high upper bound on position range * @return an array of <code>ProbeState</code> objects whose position falls * within the specified range */ public List<S> statesInPositionRange( final double low, final double high ) { final int[] range = _history.getIndicesWithinLocationRange( low, high ); if ( range != null ) { final List<S> result = new ArrayList<S>( range[1] - range[0] + 1 ); for ( int index = range[0] ; index <= range[1] ; index++ ) { result.add( _history.get( index ) ); } // final ProbeState[] resultArray = new ProbeState[result.size()]; // return result.toArray( resultArray ); return result; } else { // return new ProbeState[0]; return new LinkedList<S>(); } } /** * <p> * The old comment read * <br/> * <br/> * &nbsp; &nbsp; "Get the probe state for the specified element ID." * <br/> * <br/> * which is now inaccurate. The returned state is actual the first * state for the given identifier which is treated as that for an * SMF hardware node. The "first state" is the state with the smallest * upstream position, that which the probe encounters first in an * forward propagation. * * @param strSmfNodeId hardware node ID of the desired state * * @return The first probe state for the given hardware node. */ public S stateForElement( final String strSmfNodeId ) { List<S> lstStates = this.statesForElement(strSmfNodeId); if (lstStates == null) return null; return lstStates.get(0); } /** * Returns the states associated with the specified element. * @param strElemId the name of the element to search for * @return an array of <code>ProbeState</code> objects for that element * @deprecated */ @SuppressWarnings("rawtypes") @Deprecated public ProbeState[] statesForElement_OLD(String strElemId) { List<ProbeState> result = new ArrayList<ProbeState>(); Iterator<S> it = stateIterator(); while (it.hasNext()) { ProbeState state = it.next(); if ((state.getElementId().equals(strElemId)) ||(state.getElementId().equals(strElemId+"y"))) { result.add(state); } } ProbeState[] resultArray = new ProbeState[result.size()]; return result.toArray(resultArray); } /** * <p> * Revised version of state lookup method for an element ID * class, which now corresponds to a hardware node * ID lookup. Since the lattice * generator creates element IDs by prefixing and suffixing * hardware node IDs, the actual hardware node ID must be used * to get all the states corresponding to a given hardware node. * <p> * The revised part comes from the fact that the states are now stored and retrieved by * hashing or a tree lookup, rather that by a linear search. * Specifically, a map of probe * states for every hardware node ID is maintained, along with an ordered * list of states arranged according to their position along the * beamline (for iterations, e.g., see <code>{@link#iterator()}</code>). * </p> * * @param strSmfNodeId identifier for the SMF hardware node * * @return all the probe states associated with the element ID class containing * the given element ID * * @author Christopher K. Allen * @since Jun 5, 2013 */ public List<S> statesForElement(String strSmfNodeId) { // RealNumericIndexer<S> setStates = this.mapStates.getStates(strElemId); List<S> lstStates = this.mapIdToStates.getStates(strSmfNodeId); if (lstStates == null) return null; return lstStates; // ProbeState[] arrStates = new ProbeState[lstStates.size()]; // return lstStates.toArray(arrStates); // List<S> lstStates = setStates.toList(); // return lstStates; } /** * Returns an array of the state indices corresponding to the specified element. * @param element name of element to search for * @return an array of integer indices corresponding to that element */ public int[] indicesForElement(String element) { List<Integer> indices = new ArrayList<Integer>(); int c1 = 0; Iterator<S> it = stateIterator(); while (it.hasNext()) { S state = it.next(); if ((state.getElementId().equals(element) || state.getElementId().equals(element+"y"))) { indices.add(c1); } c1++; } int[] resultArray = new int[indices.size()]; int c2 = 0; for (Iterator<Integer> indIt = indices.iterator(); indIt.hasNext(); c2++) { resultArray[c2] = indIt.next(); } return resultArray; } /** * Returns the state corresponding to the specified index, or null if there is none. * @param i index of state to return * @return state corresponding to specified index */ public S stateWithIndex(int i) { try { return _history.get(i); } catch (IndexOutOfBoundsException e) { return null; } } /* * Iterable Interface */ /** * Returns an iterator over all the probe states in the trajectory. This is * the single method in the <code>Iterable<T></code> interface which facilitates * the "for each" statement. States are traversed in their order along the * beamline. * * @return iterator for use in a <code>(T X : Container&lt;T&gt;)</code> statement * * @author Christopher K. Allen * @since Oct 28, 2013 */ public Iterator<S> iterator() { return this._history.iterator(); } /* * Object Overrides */ /** * Store a textual representation of the trajectory to a string * @return trajectory contents in string form */ @Override public String toString() { StringBuffer buf = new StringBuffer(); buf.append("Trajectory: " + getClass().getName() + "\n"); buf.append("Time: " + getTimestamp() + "\n"); buf.append("Description: " + getDescription() + "\n"); buf.append("States: " + _history.size() + "\n"); Iterator<S> it = stateIterator(); while (it.hasNext()) { buf.append(it.next().toString() + "\n"); } return buf.toString(); } /* * IArchive Interface */ /** * Adds a representation of this Trajectory and its state history to the supplied <code>DataAdaptor</code>. * @param container <code>DataAdaptor</code> in which to add <code>Trajectory</code> data */ public void save(DataAdaptor container) { DataAdaptor trajNode = container.createChild(TRAJ_LABEL); trajNode.setValue(TYPE_LABEL, getClass().getName()); trajNode.setValue(TIMESTAMP_LABEL, new Double(getTimestamp().getTime())); if (getDescription().length() > 0) trajNode.setValue(DESCRIPTION_LABEL, getDescription()); addPropertiesTo(trajNode); addStatesTo(trajNode); } /** * Load the current <code>Trajectory</code> object with the state history * information in the <code>DataAdaptor</code> object. * * @param container <code>DataAdaptor</code> from which state history is extracted * * @exception DataFormatException malformated data in <code>DataAdaptor</code> */ public void load(DataAdaptor container) throws DataFormatException { // DataAdaptor daptTraj = container.childAdaptor(Trajectory.TRAJ_LABEL); // if (daptTraj == null) // throw new DataFormatException("Trajectory#load() - DataAdaptor contains no trajectory node"); DataAdaptor daptTraj = container; long time = new Double(daptTraj.doubleValue(TIMESTAMP_LABEL)).longValue(); setTimestamp(time); setDescription(daptTraj.stringValue(DESCRIPTION_LABEL)); try { readPropertiesFrom(daptTraj); readStatesFrom(daptTraj); } catch (ParsingException e) { e.printStackTrace(); throw new DataFormatException( "Exception loading from adaptor: " + e.getMessage()); } } /** * Iterates over child nodes, asking the concrete Trajectory subclass to * create a <code>ProbeState</code> of the appropriate species, initialized * from the contents of the supplied <code>DataAdaptor</code> * * @param container <code>DataAdaptor</code> containing the child state nodes */ @SuppressWarnings("unchecked") private void readStatesFrom(DataAdaptor container) throws ParsingException { Iterator<? extends DataAdaptor> childNodes = container.childAdaptors().iterator(); while (childNodes.hasNext()) { DataAdaptor childNode = childNodes.next(); if (!childNode.name().equals(ProbeState.STATE_LABEL)) { throw new ParsingException( "Expected state element, got: " + childNode.name()); } /** * Save the current trajectory information in the proper trajectory format to the target <code>DataAdaptor</code> object. * @param container <code>DataAdaptor</code> to receive trajectory history */ private void addStatesTo(DataAdaptor container) { Iterator<S> it = stateIterator(); while (it.hasNext()) { S ps = it.next(); ps.save(container); } } } /** * This class realized equivalences classes of hardware identifier * strings. Since modeling elements for hardware devices could have * many difference names, it is necessary to identify all these names * into a single equivalence class for the hardware ID. * * @author Christopher K. Allen * @since Nov 13, 2014 * * @deprecated This class is no longer needed since the probe state * implementation now incorporates a hardware ID attribute. */ @Deprecated class IdEquivClass implements Comparator<IdEquivClass> { /* * Local Attributes */ /** Size of the string regular expression */ private final int cntChars; /** The root Id */ private String strIdRoot; /* * Initialization */ public IdEquivClass(String strIdRoot) { this.strIdRoot = strIdRoot; this.cntChars = strIdRoot.length(); } public IdEquivClass(int cntSzRoot, String strMemberId) { this.cntChars = cntSzRoot; this.strIdRoot = strMemberId.substring(0, cntSzRoot); } public boolean isMember(String strId) { boolean bolResult = strId.matches(this.strIdRoot); return bolResult; } /* * Comparator Interface */ /** * * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) * * @author Christopher K. Allen * @since Aug 28, 2014 */ @Override public int compare(IdEquivClass id1, IdEquivClass id2) { return 0; } }
package com.jetbrains.ther.lexer; import com.intellij.lexer.Lexer; import com.intellij.testFramework.PlatformLiteFixture; public class TheRLexerTest extends PlatformLiteFixture { public void testLogicTrue() { doTest("TRUE", "TheR:TRUE_KEYWORD"); } public void testLogicFalse() { doTest("FALSE", "TheR:FALSE_KEYWORD"); } public void testNumeric1() { doTest("1", "TheR:NUMERIC_LITERAL"); } public void testNumeric10() { doTest("10", "TheR:NUMERIC_LITERAL"); } public void testNumericFloat() { doTest("0.1", "TheR:NUMERIC_LITERAL"); } public void testNumericFloat2() { doTest(".2", "TheR:NUMERIC_LITERAL"); } public void testNumericExponent() { doTest("1e-7", "TheR:NUMERIC_LITERAL"); } public void testNumericFloatExponent() { doTest("1.2e+7", "TheR:NUMERIC_LITERAL"); } public void testNumericHexExponent() { doTest("0x1.1p-2", "TheR:NUMERIC_LITERAL"); } public void testNumericBinaryExponent() { doTest("0x123p456", "TheR:NUMERIC_LITERAL"); } public void testNumericHex() { doTest("0x1", "TheR:NUMERIC_LITERAL"); } public void testInteger1() { doTest("1L", "TheR:INTEGER_LITERAL"); } public void testIntegerHex() { doTest("0x10L", "TheR:INTEGER_LITERAL"); } public void testIntegerLong() { doTest("1000000L", "TheR:INTEGER_LITERAL"); } public void testIntegerExponent() { doTest("1e6L", "TheR:INTEGER_LITERAL"); } public void testNumericWithWarn() { // TODO: inspection. Actually, it's numeric one doTest("1.1L", "TheR:INTEGER_LITERAL"); } public void testNumericWithWarnExp() { // TODO: inspection. Actually, it's numeric one doTest("1e-3L", "TheR:INTEGER_LITERAL"); } public void testSyntaxError() { doTest("12iL", "TheR:COMPLEX_LITERAL", "TheR:IDENTIFIER"); } public void testUnnecessaryDecimalPoint() { // TODO: inspection. Unnecessary Decimal Point warning runtime doTest("1.L", "TheR:INTEGER_LITERAL"); } public void testComplex() { doTest("1i", "TheR:COMPLEX_LITERAL"); } public void testFloatComplex() { doTest("4.1i", "TheR:COMPLEX_LITERAL"); } public void testExponentComplex() { doTest("1e-2i", "TheR:COMPLEX_LITERAL"); } public void testHexLong() { doTest("0xFL", "TheR:INTEGER_LITERAL"); } private static void doTest(String text, String... expectedTokens) { doLexerTest(text, new TheRLexer(), expectedTokens); } public static void doLexerTest(String text, Lexer lexer, String... expectedTokens) { doLexerTest(text, lexer, false, expectedTokens); } public static void doLexerTest(String text, Lexer lexer, boolean checkTokenText, String... expectedTokens) { lexer.start(text); int idx = 0; int tokenPos = 0; while (lexer.getTokenType() != null) { if (idx >= expectedTokens.length) { StringBuilder remainingTokens = new StringBuilder("\"" + lexer.getTokenType().toString() + "\""); lexer.advance(); while (lexer.getTokenType() != null) { remainingTokens.append(","); remainingTokens.append(" \"").append(checkTokenText ? lexer.getTokenText() : lexer.getTokenType().toString()).append("\""); lexer.advance(); } fail("Too many tokens. Following tokens: " + remainingTokens.toString()); } assertEquals("Token offset mismatch at position " + idx, tokenPos, lexer.getTokenStart()); String tokenName = checkTokenText ? lexer.getTokenText() : lexer.getTokenType().toString(); assertEquals("Token mismatch at position " + idx, expectedTokens[idx], tokenName); idx++; tokenPos = lexer.getTokenEnd(); lexer.advance(); } if (idx < expectedTokens.length) fail("Not enough tokens"); } }
/* * Decompiled with CFR 0_132. */ package main; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferedImage; import java.awt.image.RenderedImage; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.Map; import java.util.Scanner; import java.util.TreeMap; import java.util.TreeSet; import javax.imageio.ImageIO; import javax.swing.BorderFactory; import javax.swing.DefaultComboBoxModel; import javax.swing.GroupLayout; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JRadioButton; import javax.swing.JRadioButtonMenuItem; import javax.swing.JScrollBar; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.JToggleButton; import javax.swing.KeyStroke; import javax.swing.LayoutStyle; import javax.swing.ProgressMonitor; import javax.swing.Timer; import javax.swing.UIManager; import javax.swing.border.Border; import javax.swing.border.LineBorder; import javax.swing.border.TitledBorder; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.filechooser.FileFilter; import lib.Manager; import lib.anim.AnimFrame; import lib.anim.Animation; import lib.anim.Character; import lib.anim.HitFrame; import lib.anim.WeaponFrame; import lib.map.Palette; import lib.map.Piece; import lib.map.Sprite; import lib.map.SpritePiece; import lib.map.Tile; public class Gui extends JFrame implements ActionListener, TheListener { private static final String VERSION = " v1.6b"; private static final String TITLE = "Pancake 2 v1.6b"; private static final int INVALID_INT = Integer.MIN_VALUE; private static final long INVALID_LONG = Long.MIN_VALUE; private String romName; private String currentDirectory; private JFileChooser romChooser; private JFileChooser guideChooser; public JFileChooser imageChooser; private JFileChooser imageSaver; private JFileChooser resizerChooser; private ImagePanel imagePanel; private Manager manager; private Guide guide; private JPanel[] colorPanels; private Border selectionBorder; private Timer timer; private int frameDelayCount; private int currAnimation; private int currFrame; private HashSet<JTextField> inUse; private int selectedColor; private long copiedMap; private long copiedArt; private boolean copiedHasHit; private boolean copiedKnockDown; private boolean copiedHasWeapon; private boolean copiedWpShowBehind; private int copiedHitX; private int copiedHitY; private int copiedHitSound; private int copiedHitDamage; private int copiedWpX; private int copiedWpY; private int copiedWpRotation; private int lastcX; private int lastcY; private boolean wasFrameReplaced; // Variables declaration - do not modify//GEN-BEGIN:variables private JTextField angleField; private JComboBox animationCombo; private JPanel animationPanel; private JTextField artField; private JButton backBut; private JCheckBox behindCheck; private JRadioButtonMenuItem brushMenu; private JRadioButton brushRadio; private JRadioButtonMenuItem bucketMenu; private JRadioButton bucketRadio; private JComboBox characterCombo; private JPanel characterPanel; private JPanel characterPanel1; private JMenuItem closeMenu; private JPanel colorPanel1; private JPanel colorPanel10; private JPanel colorPanel11; private JPanel colorPanel12; private JPanel colorPanel13; private JPanel colorPanel14; private JPanel colorPanel15; private JPanel colorPanel16; private JPanel colorPanel2; private JPanel colorPanel3; private JPanel colorPanel4; private JPanel colorPanel5; private JPanel colorPanel6; private JPanel colorPanel7; private JPanel colorPanel8; private JPanel colorPanel9; private JPanel colorsPanel1; private JLabel compressedLabel; private JMenuItem copyMenu; private JTextField damageField; private JTextField delayField; private JRadioButtonMenuItem dragImageMenu; private JRadioButton dragImageRadio; private JRadioButtonMenuItem dragSpriteMenu; private JRadioButton dragSpriteRadio; private JMenu exportMenu; private JPanel framePanel; private JButton frontBut; private JTextField genAddressField; private JTextField genPaletteField; private JPanel generatePanel; private JButton hardReplaceButton; private JRadioButtonMenuItem hexIdsMenu; private JCheckBox hitCheck; private JPanel hitPanel; private JMenu inportMenu; private JButton jButton2; private JButton jButton3; private JLabel jLabel1; private JLabel jLabel10; private JLabel jLabel11; private JLabel jLabel12; private JLabel jLabel13; private JLabel jLabel14; private JLabel jLabel15; private JLabel jLabel16; private JLabel jLabel17; private JLabel jLabel2; private JLabel jLabel3; private JLabel jLabel5; private JLabel jLabel6; private JLabel jLabel7; private JLabel jLabel8; private JLabel jLabel9; private JMenu jMenu1; private JMenu jMenu2; private JMenu jMenu3; private JMenu jMenu4; private JMenu jMenu5; private JMenu jMenu6; private JMenuBar jMenuBar1; private JMenuItem jMenuItem1; private JMenuItem jMenuItem10; private JMenuItem jMenuItem11; private JMenuItem jMenuItem2; private JMenuItem jMenuItem3; private JMenuItem jMenuItem4; private JMenuItem jMenuItem5; private JMenuItem jMenuItem6; private JMenuItem jMenuItem7; private JMenuItem jMenuItem9; private JPopupMenu.Separator jSeparator1; private JPopupMenu.Separator jSeparator2; private JPopupMenu.Separator jSeparator3; private JPopupMenu.Separator jSeparator4; private JPopupMenu.Separator jSeparator5; private JPopupMenu.Separator jSeparator6; private JCheckBox koCheck; private JPanel mainPanel; private JTextField mapField; private JMenuItem nameMenu; private JButton nextBut; private JRadioButtonMenuItem noneMenu; private JRadioButton noneRadio; private JMenuItem openRomMenu; private JPanel overridePanel; private JMenuItem pasteMenu; private JMenuItem pasteMenu1; private JRadioButtonMenuItem pencilMenu; private JRadioButton pencilRadio; private JToggleButton playToggle; private JPanel playerPanel; private JPanel previewPanel; private JButton previousBut; private JMenuItem resizeAnimsMenu; private JScrollPane scrollPanel; private JCheckBox showCenterCheck; private JCheckBox showFacedRightCheck; private JCheckBox showHitsCheck; private JCheckBox showTileCheck; private JCheckBox showWeaponCheck; private JTextField sizeField; private JRadioButtonMenuItem sizeRadioMenu1; private JRadioButtonMenuItem sizeRadioMenu2; private JRadioButtonMenuItem sizeRadioMenu3; private JButton softReplaceButton; private JTextField soundField; private JMenuItem spriteSheetMenu; private JMenuItem spriteSheetMenu1; private JPanel toolsPanel; private JTextField wXField; private JTextField wYField; private JCheckBox weaponCheck; private JComboBox weaponCombo; private JPanel weaponPanel; private JTextField xField; private JTextField yField; // End of variables declaration//GEN-END:variables private void setupAnimationCombo() { int charId = this.guide.getFakeCharId(this.manager.getCurrentCharacterId()); int count = this.guide.getAnimsCount(charId); this.animationCombo.removeAllItems(); if (this.areIdsHex()) { for (int i = 0; i < count; ++i) { this.animationCombo.addItem(Integer.toHexString(i * 2) + " - " + this.guide.getAnimName(charId, i)); } } else { for (int i = 0; i < count; ++i) { this.animationCombo.addItem("" + (i + 1) + " - " + this.guide.getAnimName(charId, i)); } } } private boolean areIdsHex() { return this.hexIdsMenu.isSelected(); } private void setupCharacterCombo() { int count = this.guide.getNumChars(); this.characterCombo.removeAllItems(); if (this.areIdsHex()) { for (int i = 0; i < count; ++i) { this.characterCombo.addItem(Integer.toHexString(i * 2) + " - " + this.guide.getCharName(i)); } } else { for (int i = 0; i < count; ++i) { this.characterCombo.addItem("" + (i + 1) + " - " + this.guide.getCharName(i)); } } } private void updateTitle() { Character ch = this.manager.getCharacter(); if (ch.wasModified()) { this.setTitle("Pancake 2 v1.6b - " + new File(this.romName).getName() + "*"); } else { this.setTitle("Pancake 2 v1.6b - " + new File(this.romName).getName()); } } private void verifyModifications() { if (this.manager == null) { return; } if (this.imagePanel.wasImageModified()) { BufferedImage img = this.imagePanel.getImage(); Animation anim = this.manager.getCharacter().getAnimation(this.currAnimation); anim.setImage(this.currFrame, img); this.manager.getCharacter().setModified(true); this.manager.getCharacter().setSpritesModified(true); anim.setSpritesModified(this.currFrame, true); this.dragImageRadio.setEnabled(false); } } private void changeFrame(int frameId) { this.verifyModifications(); if (this.manager != null && this.manager.getCharacter() != null) { if (this.manager.getCharacter().wasModified()) { this.saveRom(); } this.setFrame(frameId); } } private void changeAnimation(int animId) { this.verifyModifications(); this.setAnimation(animId); } private void changeCharacter(int charId) throws IOException { this.verifyModifications(); this.setCharacter(charId); } private void setFrame(int frameId) { if (this.currFrame != frameId) { this.wasFrameReplaced = false; this.imagePanel.updateGhost(); } this.currFrame = frameId; Character ch = this.manager.getCharacter(); AnimFrame animFrame = ch.getAnimFrame(this.currAnimation, this.currFrame); HitFrame hitFrame = ch.getHitFrame(this.currAnimation, this.currFrame); WeaponFrame weaponFrame = ch.getWeaponFrame(this.currAnimation, this.currFrame); TitledBorder border = (TitledBorder)this.framePanel.getBorder(); border.setTitle("Frame " + Integer.toString(this.currFrame + 1)); this.framePanel.repaint(); this.setField(this.delayField, animFrame.delay); this.setFieldAsHex(this.mapField, animFrame.mapAddress); this.setFieldAsHex(this.artField, animFrame.artAddress); if (hitFrame != null) { this.setField(this.xField, hitFrame.x); this.setField(this.yField, hitFrame.y); this.setField(this.damageField, hitFrame.damage); this.setField(this.soundField, hitFrame.sound); this.setCheck(this.koCheck, hitFrame.knockDown); this.setCheck(this.hitCheck, hitFrame.isEnabled()); if (hitFrame.isEnabled()) { this.imagePanel.setHit(hitFrame.x, hitFrame.y, hitFrame.knockDown); } else { this.imagePanel.removeHit(); } } else { this.setCheck(this.hitCheck, false); this.imagePanel.removeHit(); } this.updateHitFrameEnabling(); if (weaponFrame != null) { this.setField(this.wXField, weaponFrame.x); this.setField(this.wYField, - weaponFrame.y); this.setField(this.angleField, weaponFrame.angle); this.setCheck(this.behindCheck, weaponFrame.showBehind); this.setCheck(this.weaponCheck, weaponFrame.isEnabled()); if (weaponFrame.isEnabled()) { this.imagePanel.setWeapon(weaponFrame.x, weaponFrame.y, weaponFrame.angle, weaponFrame.showBehind); } else { this.imagePanel.removeWeapon(); } } else { this.imagePanel.removeWeapon(); } this.updateWeaponFrameEnabling(); this.frameDelayCount = 0; this.setImage(this.manager.getImage(this.currAnimation, this.currFrame), this.manager.getShadow(this.currAnimation, this.currFrame)); this.updateTitle(); this.copyMenu.setEnabled(true); this.pasteMenu.setEnabled(this.copiedMap != 0L); } private void setAnimation(int animId) { if (this.currAnimation != animId) { this.imagePanel.updateGhost(); } this.currAnimation = animId; try { this.manager.bufferAnimation(this.currAnimation); } catch (IOException ex) { ex.printStackTrace(); this.showError("Unable to read animation graphics"); return; } this.setComboSelection(this.animationCombo, this.currAnimation); Character ch = this.manager.getCharacter(); int animSize = ch.getAnimation(this.currAnimation).getNumFrames(); this.setField(this.sizeField, animSize); boolean isCompressed = ch.getAnimation(this.currAnimation).isCompressed(); this.artField.setEnabled(!isCompressed); Gui.setEnable(this.toolsPanel, !isCompressed); Gui.setEnable(this.overridePanel, !isCompressed); Gui.setEnable(this.generatePanel, !isCompressed); this.inportMenu.setEnabled(!isCompressed); this.resizeAnimsMenu.setEnabled(!isCompressed); if (isCompressed) { this.imagePanel.setMode(Mode.none); } this.setFrame(0); } private void setCharacter(int charId) throws IOException { this.changeFrame(this.currFrame); if (this.manager == null) { return; } Character ch = this.manager.getCharacter(); if (ch != null && ch.wasModified()) { this.saveRom(); } int backupCurrAnim = this.currAnimation; int fakeId = this.guide.getFakeCharId(charId); int type = this.guide.getType(fakeId); if (type == 1) { AnimFrame.providedArtAddress = this.guide.getCompressedArtAddress(charId); } this.manager.setCharacter(charId, this.guide.getAnimsCount(fakeId), type); this.compressedLabel.setVisible(type == 1); this.setComboSelection(this.characterCombo, fakeId); this.setupAnimationCombo(); int numAnimations = this.manager.getCharacter().getNumAnimations(); this.updatePalettePanels(); if (backupCurrAnim == -1) { this.setAnimation(0); } else if (backupCurrAnim >= numAnimations) { this.setAnimation(numAnimations - 1); } else { this.setAnimation(backupCurrAnim); } this.updateGenAddress(); this.nameMenu.setEnabled(charId < this.guide.getPlayableChars()); } private void guideChanged() { this.setupCharacterCombo(); } private boolean openCustomGuide() { int returnVal = this.guideChooser.showOpenDialog(this); if (returnVal == 0) { File file = this.guideChooser.getSelectedFile(); try { this.guide = new Guide(file.getAbsolutePath()); this.guideChanged(); return true; } catch (FileNotFoundException ex) { ex.printStackTrace(); this.showError("Guide file '" + file.getName() + "' not found"); } catch (Exception ex) { ex.printStackTrace(); this.showError("Unable to open guide '" + file.getName() + "'"); } } return false; } private boolean openDefaultGuide() { try { this.guide = new Guide(Guide.GUIDES_DIR + "default.txt"); this.guideChanged(); } catch (Exception e) { return false; } return true; } private boolean setupManager(String romName) { Manager oldManager = this.manager; try { this.manager = new Manager(romName, this.guide); this.changeCharacter(0); } catch (FileNotFoundException ex) { ex.printStackTrace(); this.showError("File '" + romName + "' not found"); this.manager = oldManager; return false; } catch (IOException ex) { ex.printStackTrace(); this.showError("File '" + romName + "' is not a valid Streets of Rage 2 ROM"); this.manager = oldManager; return false; } Manager newManager = this.manager; this.manager = oldManager; this.closeRom(); this.manager = newManager; return true; } private boolean openRom() { if (!this.askSaveRom()) { return false; } int returnVal = this.romChooser.showOpenDialog(this); if (returnVal == 0) { File file = this.romChooser.getSelectedFile(); this.romName = file.getAbsolutePath(); if (this.setupManager(this.romName)) { this.setTitle("Pancake 2 v1.6b - " + file.getName()); this.updateEnablings(); } } try { this.setCharacter(0); } catch (IOException ex) { ex.printStackTrace(); this.showError("Unable to read first character"); return false; } return true; } private void closeRom() { if (this.askSaveRom()) { this.manager = null; this.copyMenu.setEnabled(false); this.pasteMenu.setEnabled(false); this.nameMenu.setEnabled(false); this.pasteMenu1.setEnabled(false); this.resizeAnimsMenu.setEnabled(false); this.imagePanel.setImage(null, null); this.imagePanel.setReplaceImage(null); this.imagePanel.removeHit(); this.imagePanel.removeWeapon(); this.updateEnablings(); } } private boolean saveRom() { try { this.manager.save(); this.updateTitle(); return true; } catch (IOException ex) { ex.printStackTrace(); this.showError("Unable to save rom"); return false; } } private boolean askSaveRom() { if (this.guide == null || this.manager == null) { return true; } Character ch = this.manager.getCharacter(); if (!ch.wasModified()) { return true; } int option = JOptionPane.showConfirmDialog(this, this.guide.getCharName(this.guide.getFakeCharId(this.manager.getCurrentCharacterId())) + " was modified.\n" + "Save changes?", "Character modified", 1); if (option == 0) { return this.saveRom(); } if (option != 1) { return false; } return true; } private void setRadiosOff() { this.pencilRadio.setSelected(false); this.brushRadio.setSelected(false); this.bucketRadio.setSelected(false); this.dragSpriteRadio.setSelected(false); this.dragImageRadio.setSelected(false); this.noneRadio.setSelected(false); this.pencilMenu.setSelected(false); this.brushMenu.setSelected(false); this.bucketMenu.setSelected(false); this.dragSpriteMenu.setSelected(false); this.dragImageMenu.setSelected(false); this.noneMenu.setSelected(false); } private static void setEnable(JComponent component, boolean enabled) { if (component.isEnabled() == enabled) { return; } component.setEnabled(enabled); Component[] com = component.getComponents(); for (int a = 0; a < com.length; ++a) { if (com[a] instanceof JComponent) { Gui.setEnable((JComponent)com[a], enabled); continue; } com[a].setEnabled(enabled); } } private void updateHitFrameEnabling() { Character ch = this.manager.getCharacter(); HitFrame hitFrame = ch.getHitFrame(this.currAnimation, this.currFrame); boolean enabled = hitFrame != null && hitFrame.isEnabled(); Gui.setEnable(this.hitPanel, enabled); this.hitCheck.setSelected(enabled); this.hitCheck.setEnabled(hitFrame != null); } private void updateWeaponFrameEnabling() { Character ch = this.manager.getCharacter(); WeaponFrame weaponFrame = ch.getWeaponFrame(this.currAnimation, this.currFrame); boolean enabled = weaponFrame != null && weaponFrame.isEnabled(); Gui.setEnable(this.weaponPanel, enabled); this.weaponCheck.setSelected(enabled); this.weaponCheck.setEnabled(weaponFrame != null); } private void updateEnablings() { Gui.setEnable(this.mainPanel, this.manager != null && this.guide != null); this.closeMenu.setEnabled(this.manager != null); this.inportMenu.setEnabled(this.manager != null); this.exportMenu.setEnabled(this.manager != null); this.resizeAnimsMenu.setEnabled(this.manager != null); this.copyMenu.setEnabled(this.manager != null); this.pasteMenu.setEnabled(this.manager != null && this.copiedMap != 0L); this.pasteMenu1.setEnabled(this.manager != null); if (this.manager != null) { this.updateHitFrameEnabling(); this.updateWeaponFrameEnabling(); } } private void sizeChanged() { if (this.inUse.contains(this.sizeField)) { return; } this.inUse.add(this.sizeField); Character ch = this.manager.getCharacter(); Animation anim = ch.getAnimation(this.currAnimation); int maxSize = anim.getMaxNumFrames(); int newSize = this.getIntFromField(this.sizeField, 1, maxSize); if (newSize == Integer.MIN_VALUE) { this.sizeField.setBackground(Color.red); } else { this.sizeField.setBackground(Color.white); if (newSize != anim.getNumFrames()) { anim.setNumFrames(newSize); ch.setModified(true); this.changeAnimation(this.currAnimation); } } this.inUse.remove(this.sizeField); } private void delayChanged() { if (this.inUse.contains(this.delayField)) { return; } this.inUse.add(this.delayField); Character ch = this.manager.getCharacter(); Animation anim = ch.getAnimation(this.currAnimation); AnimFrame frame = anim.getFrame(this.currFrame); int newDelay = this.getIntFromField(this.delayField, 1, 255); if (newDelay == Integer.MIN_VALUE) { this.delayField.setBackground(Color.red); } else { this.delayField.setBackground(Color.white); if (newDelay != frame.delay) { frame.delay = newDelay; ch.setModified(true); this.refresh(); } } this.inUse.remove(this.delayField); } private void hitXChanged() { if (this.inUse.contains(this.xField)) { return; } this.inUse.add(this.xField); Character ch = this.manager.getCharacter(); HitFrame frame = ch.getHitFrame(this.currAnimation, this.currFrame); int newX = this.getIntFromField(this.xField, -127, 127); if (newX == Integer.MIN_VALUE) { this.xField.setBackground(Color.red); } else { this.xField.setBackground(Color.white); if (newX != frame.x) { frame.x = newX; ch.setModified(true); this.refresh(); } } this.inUse.remove(this.xField); } private void hitYChanged() { if (this.inUse.contains(this.yField)) { return; } this.inUse.add(this.yField); Character ch = this.manager.getCharacter(); HitFrame frame = ch.getHitFrame(this.currAnimation, this.currFrame); int newY = this.getIntFromField(this.yField, -127, 127); if (newY == Integer.MIN_VALUE) { this.yField.setBackground(Color.red); } else { this.yField.setBackground(Color.white); if (newY != frame.y) { frame.y = newY; ch.setModified(true); this.refresh(); } } this.inUse.remove(this.yField); } private void hitSoundChanged() { if (this.inUse.contains(this.soundField)) { return; } this.inUse.add(this.soundField); Character ch = this.manager.getCharacter(); HitFrame frame = ch.getHitFrame(this.currAnimation, this.currFrame); int newSound = this.getIntFromField(this.soundField, 0, 255); if (newSound == Integer.MIN_VALUE) { this.soundField.setBackground(Color.red); } else { this.soundField.setBackground(Color.white); if (newSound != frame.sound) { frame.sound = newSound; ch.setModified(true); this.refresh(); } } this.inUse.remove(this.soundField); } private void hitDamageChanged() { if (this.inUse.contains(this.damageField)) { return; } this.inUse.add(this.damageField); Character ch = this.manager.getCharacter(); HitFrame frame = ch.getHitFrame(this.currAnimation, this.currFrame); int newDamage = this.getIntFromField(this.damageField, -127, 127); if (newDamage == Integer.MIN_VALUE) { this.damageField.setBackground(Color.red); } else { this.damageField.setBackground(Color.white); if (newDamage != frame.damage) { frame.damage = newDamage; ch.setModified(true); this.refresh(); } } this.inUse.remove(this.damageField); } private void weaponXChanged() { if (this.inUse.contains(this.wXField)) { return; } this.inUse.add(this.wXField); Character ch = this.manager.getCharacter(); WeaponFrame frame = ch.getWeaponFrame(this.currAnimation, this.currFrame); int newX = this.getIntFromField(this.wXField, -127, 127); if (newX == Integer.MIN_VALUE) { this.wXField.setBackground(Color.red); } else { this.wXField.setBackground(Color.white); if (newX != frame.x) { frame.x = newX; ch.setModified(true); this.refresh(); } } this.inUse.remove(this.wXField); } private void weaponYChanged() { if (this.inUse.contains(this.wYField)) { return; } this.inUse.add(this.wYField); Character ch = this.manager.getCharacter(); WeaponFrame frame = ch.getWeaponFrame(this.currAnimation, this.currFrame); int newY = this.getIntFromField(this.wYField, -127, 127); if (newY == Integer.MIN_VALUE) { this.wYField.setBackground(Color.red); } else { newY = - newY; this.wYField.setBackground(Color.white); if (newY != frame.y) { frame.y = newY; ch.setModified(true); this.refresh(); } } this.inUse.remove(this.wYField); } private void weaponAngleChanged() { if (this.inUse.contains(this.angleField)) { return; } this.inUse.add(this.angleField); Character ch = this.manager.getCharacter(); WeaponFrame frame = ch.getWeaponFrame(this.currAnimation, this.currFrame); int newAngle = this.getIntFromField(this.angleField, -127, 127); if (newAngle == Integer.MIN_VALUE || newAngle < 0 || newAngle > 7) { if (frame.isEnabled()) { this.angleField.setBackground(Color.red); } } else { this.angleField.setBackground(Color.white); if (newAngle != frame.angle) { frame.angle = newAngle; ch.setModified(true); this.refresh(); } } this.inUse.remove(this.angleField); } private void mapAddressChanged() { if (this.inUse.contains(this.mapField)) { return; } this.inUse.add(this.mapField); Character ch = this.manager.getCharacter(); Animation anim = ch.getAnimation(this.currAnimation); AnimFrame frame = anim.getFrame(this.currFrame); long newMap = this.getHexFromField(this.mapField); if (newMap == Long.MIN_VALUE) { this.mapField.setBackground(Color.red); } else { this.mapField.setBackground(Color.white); if (newMap != frame.mapAddress) { long oldMap = frame.mapAddress; frame.mapAddress = newMap; try { this.manager.bufferAnimFrame(this.currAnimation, this.currFrame); ch.setModified(true); this.refresh(); } catch (IOException ex) { frame.mapAddress = oldMap; this.mapField.setBackground(Color.red); } } } this.inUse.remove(this.mapField); } private void artAddressChanged() { if (this.inUse.contains(this.artField)) { return; } this.inUse.add(this.artField); Character ch = this.manager.getCharacter(); Animation anim = ch.getAnimation(this.currAnimation); AnimFrame frame = anim.getFrame(this.currFrame); long newArt = this.getHexFromField(this.artField); if (newArt == Long.MIN_VALUE) { this.artField.setBackground(Color.red); } else { this.artField.setBackground(Color.white); if (newArt != frame.artAddress) { long oldArt = frame.artAddress; frame.artAddress = newArt; try { this.manager.bufferAnimFrame(this.currAnimation, this.currFrame); ch.setModified(true); this.refresh(); } catch (IOException ex) { frame.artAddress = oldArt; this.artField.setBackground(Color.red); } } } this.inUse.remove(this.artField); } private void setupFields() { this.sizeField.getDocument().addDocumentListener(new DocumentListener(){ @Override public void changedUpdate(DocumentEvent e) { Gui.this.sizeChanged(); } @Override public void removeUpdate(DocumentEvent e) { Gui.this.sizeChanged(); } @Override public void insertUpdate(DocumentEvent e) { Gui.this.sizeChanged(); } }); this.delayField.getDocument().addDocumentListener(new DocumentListener(){ @Override public void changedUpdate(DocumentEvent e) { Gui.this.delayChanged(); } @Override public void removeUpdate(DocumentEvent e) { Gui.this.delayChanged(); } @Override public void insertUpdate(DocumentEvent e) { Gui.this.delayChanged(); } }); this.xField.getDocument().addDocumentListener(new DocumentListener(){ @Override public void changedUpdate(DocumentEvent e) { Gui.this.hitXChanged(); } @Override public void removeUpdate(DocumentEvent e) { Gui.this.hitXChanged(); } @Override public void insertUpdate(DocumentEvent e) { Gui.this.hitXChanged(); } }); this.yField.getDocument().addDocumentListener(new DocumentListener(){ @Override public void changedUpdate(DocumentEvent e) { Gui.this.hitYChanged(); } @Override public void removeUpdate(DocumentEvent e) { Gui.this.hitYChanged(); } @Override public void insertUpdate(DocumentEvent e) { Gui.this.hitYChanged(); } }); this.soundField.getDocument().addDocumentListener(new DocumentListener(){ @Override public void changedUpdate(DocumentEvent e) { Gui.this.hitSoundChanged(); } @Override public void removeUpdate(DocumentEvent e) { Gui.this.hitSoundChanged(); } @Override public void insertUpdate(DocumentEvent e) { Gui.this.hitSoundChanged(); } }); this.damageField.getDocument().addDocumentListener(new DocumentListener(){ @Override public void changedUpdate(DocumentEvent e) { Gui.this.hitDamageChanged(); } @Override public void removeUpdate(DocumentEvent e) { Gui.this.hitDamageChanged(); } @Override public void insertUpdate(DocumentEvent e) { Gui.this.hitDamageChanged(); } }); this.wXField.getDocument().addDocumentListener(new DocumentListener(){ @Override public void changedUpdate(DocumentEvent e) { Gui.this.weaponXChanged(); } @Override public void removeUpdate(DocumentEvent e) { Gui.this.weaponXChanged(); } @Override public void insertUpdate(DocumentEvent e) { Gui.this.weaponXChanged(); } }); this.wYField.getDocument().addDocumentListener(new DocumentListener(){ @Override public void changedUpdate(DocumentEvent e) { Gui.this.weaponYChanged(); } @Override public void removeUpdate(DocumentEvent e) { Gui.this.weaponYChanged(); } @Override public void insertUpdate(DocumentEvent e) { Gui.this.weaponYChanged(); } }); this.angleField.getDocument().addDocumentListener(new DocumentListener(){ @Override public void changedUpdate(DocumentEvent e) { Gui.this.weaponAngleChanged(); } @Override public void removeUpdate(DocumentEvent e) { Gui.this.weaponAngleChanged(); } @Override public void insertUpdate(DocumentEvent e) { Gui.this.weaponAngleChanged(); } }); this.mapField.getDocument().addDocumentListener(new DocumentListener(){ @Override public void changedUpdate(DocumentEvent e) { Gui.this.mapAddressChanged(); } @Override public void removeUpdate(DocumentEvent e) { Gui.this.mapAddressChanged(); } @Override public void insertUpdate(DocumentEvent e) { Gui.this.mapAddressChanged(); } }); this.artField.getDocument().addDocumentListener(new DocumentListener(){ @Override public void changedUpdate(DocumentEvent e) { Gui.this.artAddressChanged(); } @Override public void removeUpdate(DocumentEvent e) { Gui.this.artAddressChanged(); } @Override public void insertUpdate(DocumentEvent e) { Gui.this.artAddressChanged(); } }); } private void setupFileChoosers() { this.romChooser.addChoosableFileFilter(new FileFilter(){ @Override public boolean accept(File file) { if (file.isDirectory()) { return true; } String filename = file.getName(); return filename.endsWith(".bin"); } @Override public String getDescription() { return "*.bin"; } }); this.guideChooser.addChoosableFileFilter(new FileFilter(){ @Override public boolean accept(File file) { if (file.isDirectory()) { return true; } String filename = file.getName(); return filename.endsWith(".txt"); } @Override public String getDescription() { return "*.txt"; } }); this.resizerChooser.addChoosableFileFilter(new FileFilter(){ @Override public boolean accept(File file) { if (file.isDirectory()) { return true; } String filename = file.getName(); return filename.endsWith(".txt"); } @Override public String getDescription() { return "*.txt"; } }); this.imageChooser.addChoosableFileFilter(new FileFilter(){ @Override public boolean accept(File file) { if (file.isDirectory()) { return true; } String filename = file.getName(); return filename.endsWith(".png") || filename.endsWith(".gif") || filename.endsWith(".jpg") || filename.endsWith(".bmp"); } @Override public String getDescription() { return "Image (*.png, *.gif, *.jpg, *.bmp)"; } }); this.imageSaver.addChoosableFileFilter(new FileFilter(){ @Override public boolean accept(File file) { if (file.isDirectory()) { return true; } String filename = file.getName(); return filename.endsWith(".png"); } @Override public String getDescription() { return "*.png"; } }); } private void initColorPanels() { this.colorPanels = new JPanel[16]; this.colorPanels[0] = this.colorPanel1; this.colorPanels[1] = this.colorPanel2; this.colorPanels[2] = this.colorPanel3; this.colorPanels[3] = this.colorPanel4; this.colorPanels[4] = this.colorPanel5; this.colorPanels[5] = this.colorPanel6; this.colorPanels[6] = this.colorPanel7; this.colorPanels[7] = this.colorPanel8; this.colorPanels[8] = this.colorPanel9; this.colorPanels[9] = this.colorPanel10; this.colorPanels[10] = this.colorPanel11; this.colorPanels[11] = this.colorPanel12; this.colorPanels[12] = this.colorPanel13; this.colorPanels[13] = this.colorPanel14; this.colorPanels[14] = this.colorPanel15; this.colorPanels[15] = this.colorPanel16; this.selectionBorder = BorderFactory.createCompoundBorder(new LineBorder(Color.white, 2), new LineBorder(Color.black)); this.selectionBorder = BorderFactory.createCompoundBorder(new LineBorder(Color.black), this.selectionBorder); this.colorPanel1.setBorder(this.selectionBorder); } private void preInitComponents() { this.lastcY = -1; this.lastcX = -1; this.inUse = new HashSet(); this.imagePanel = new ImagePanel(this); this.currentDirectory = new File(".").getAbsolutePath(); this.romChooser = new JFileChooser(this.currentDirectory); this.romChooser.setDialogTitle("Open the 'Streets of Rage 2' ROM to edit"); this.guideChooser = new JFileChooser(this.currentDirectory + "/" + Guide.GUIDES_DIR); this.guideChooser.setDialogTitle("Open characters guide"); this.imageChooser = new JFileChooser(this.currentDirectory); this.imageChooser.setDialogTitle("Open image"); this.imageSaver = new JFileChooser(this.currentDirectory); this.imageSaver.setDialogTitle("Save image"); this.resizerChooser = new JFileChooser(this.currentDirectory); this.resizerChooser.setDialogTitle("Open resizing script"); try { BufferedImage icon = ImageIO.read(new File("images/icon.png")); this.setIconImage(icon); } catch (IOException ex) { // empty catch block } this.timer = new Timer(1, this); } private void postInitComponents() { this.compressedLabel.setVisible(false); this.setupFields(); this.setupFileChoosers(); this.scrollPanel.setWheelScrollingEnabled(false); this.scrollPanel.setAutoscrolls(true); this.initColorPanels(); this.updateEnablings(); } public Gui() { this.preInitComponents(); this.initComponents(); this.setVisible(true); this.postInitComponents(); } private void setImagePanelScale(float newScale) { float oldScale = this.imagePanel.getScale(); Rectangle oldView = this.scrollPanel.getViewport().getViewRect(); this.imagePanel.setScale(newScale); Point newViewPos = new Point(); newViewPos.x = (int)Math.max(0.0f, (float)(oldView.x + oldView.width / 2) * newScale / oldScale - (float)(oldView.width / 2)); newViewPos.y = (int)Math.max(0.0f, (float)(oldView.y + oldView.height / 2) * newScale / oldScale - (float)(oldView.height / 2)); this.scrollPanel.getViewport().setViewPosition(newViewPos); } private void scaleImagePanel(float zoom) { this.setImagePanelScale(this.imagePanel.getScale() + zoom); } public void showError(String text) { String title = "Wops!"; JOptionPane.showMessageDialog(this, text, title, 0); } public int getIntFromField(JTextField field, int lowerLim, int upperLim) { String text = field.getText(); if (text.isEmpty()) { return Integer.MIN_VALUE; } try { int res = Integer.parseInt(text); if (res < lowerLim || res > upperLim) { return Integer.MIN_VALUE; } return res; } catch (Exception e) { return Integer.MIN_VALUE; } } public int getPositiveIntFromField(JTextField field) { return this.getIntFromField(field, 0, Integer.MAX_VALUE); } public int getIntFromField(JTextField field) { String text = field.getText(); if (text.isEmpty()) { return Integer.MIN_VALUE; } try { return Integer.parseInt(text); } catch (Exception e) { return Integer.MIN_VALUE; } } public long getHexFromField(JTextField field) { String text = field.getText(); if (text.isEmpty()) { return Long.MIN_VALUE; } try { return Long.parseLong(text, 16); } catch (Exception e) { return Long.MIN_VALUE; } } private void setField(JTextField field, String value) { if (this.inUse.contains(field)) { return; } if (!field.getText().equals(value)) { this.inUse.add(field); field.setBackground(Color.white); field.setText(value); this.inUse.remove(field); } } private void setField(JTextField field, int value) { this.setField(field, Integer.toString(value)); } private void setField(JTextField field, long value) { this.setField(field, Long.toString(value)); } private void setFieldAsHex(JTextField field, long value) { this.setField(field, Long.toString(value, 16)); } private void setCheck(JCheckBox check, boolean value) { if (check.isSelected() != value) { check.setSelected(value); } } private void setComboSelection(JComboBox combo, int newIndex) { if (combo.getSelectedIndex() != newIndex) { combo.setSelectedIndex(newIndex); } } private void setImage(BufferedImage image, BufferedImage shadow) { JScrollBar horizontalScrollBar = this.scrollPanel.getHorizontalScrollBar(); JScrollBar verticalScrollBar = this.scrollPanel.getVerticalScrollBar(); int x = horizontalScrollBar.getValue(); int y = verticalScrollBar.getValue(); this.imagePanel.setImage(image, shadow); horizontalScrollBar.setValue(x + 1); horizontalScrollBar.setValue(x); verticalScrollBar.setValue(y + 1); verticalScrollBar.setValue(y); this.dragImageRadio.setEnabled(false); } private void setNextAnimation() { int nextAnimation = this.currAnimation + 1; if (nextAnimation >= this.manager.getCharacter().getNumAnimations()) { nextAnimation = 0; } this.changeAnimation(nextAnimation); } private void setPreviousAnimation() { int previousAnimation = this.currAnimation - 1; if (previousAnimation < 0) { previousAnimation = this.manager.getCharacter().getNumAnimations() - 1; } this.changeAnimation(previousAnimation); } private void setNextFrame() { int nextFrame = this.currFrame + 1; if (nextFrame >= this.manager.getCharacter().getAnimation(this.currAnimation).getNumFrames()) { nextFrame = 0; } this.changeFrame(nextFrame); } private void setPreviousFrame() { int previousFrame = this.currFrame + -1; if (previousFrame < 0) { previousFrame = this.manager.getCharacter().getAnimation(this.currAnimation).getNumFrames() - 1; } this.changeFrame(previousFrame); } private void updatePalettePanels() { Palette palette = this.manager.getPalette(); if (palette == null) { palette = new Palette(); } for (int i = 0; i < 16; ++i) { this.colorPanels[i].setBackground(new Color(palette.getColor(i))); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { this.mainPanel = new JPanel(); this.characterPanel = new JPanel(); this.jLabel1 = new JLabel(); this.characterCombo = new JComboBox(); this.animationPanel = new JPanel(); this.jLabel5 = new JLabel(); this.animationCombo = new JComboBox(); this.jLabel6 = new JLabel(); this.sizeField = new JTextField(); this.framePanel = new JPanel(); this.jLabel7 = new JLabel(); this.delayField = new JTextField(); this.hitPanel = new JPanel(); this.jLabel8 = new JLabel(); this.xField = new JTextField(); this.jLabel9 = new JLabel(); this.yField = new JTextField(); this.jLabel10 = new JLabel(); this.soundField = new JTextField(); this.jLabel11 = new JLabel(); this.damageField = new JTextField(); this.koCheck = new JCheckBox(); this.hitCheck = new JCheckBox(); this.jLabel12 = new JLabel(); this.mapField = new JTextField(); this.jLabel3 = new JLabel(); this.artField = new JTextField(); this.jButton2 = new JButton(); this.jButton3 = new JButton(); this.weaponPanel = new JPanel(); this.jLabel15 = new JLabel(); this.wXField = new JTextField(); this.jLabel16 = new JLabel(); this.wYField = new JTextField(); this.jLabel17 = new JLabel(); this.angleField = new JTextField(); this.behindCheck = new JCheckBox(); this.weaponCheck = new JCheckBox(); this.compressedLabel = new JLabel(); this.previewPanel = new JPanel(); this.scrollPanel = new JScrollPane(this.imagePanel); this.playerPanel = new JPanel(); this.backBut = new JButton(); this.previousBut = new JButton(); this.nextBut = new JButton(); this.frontBut = new JButton(); this.playToggle = new JToggleButton(); this.colorsPanel1 = new JPanel(); this.colorPanel2 = new JPanel(); this.colorPanel3 = new JPanel(); this.colorPanel4 = new JPanel(); this.colorPanel5 = new JPanel(); this.colorPanel6 = new JPanel(); this.colorPanel7 = new JPanel(); this.colorPanel8 = new JPanel(); this.colorPanel9 = new JPanel(); this.colorPanel10 = new JPanel(); this.colorPanel11 = new JPanel(); this.colorPanel12 = new JPanel(); this.colorPanel13 = new JPanel(); this.colorPanel14 = new JPanel(); this.colorPanel15 = new JPanel(); this.colorPanel16 = new JPanel(); this.colorPanel1 = new JPanel(); this.characterPanel1 = new JPanel(); this.showHitsCheck = new JCheckBox(); this.showWeaponCheck = new JCheckBox(); this.weaponCombo = new JComboBox(); this.showFacedRightCheck = new JCheckBox(); this.showTileCheck = new JCheckBox(); this.showCenterCheck = new JCheckBox(); this.toolsPanel = new JPanel(); this.pencilRadio = new JRadioButton(); this.brushRadio = new JRadioButton(); this.bucketRadio = new JRadioButton(); this.dragSpriteRadio = new JRadioButton(); this.dragImageRadio = new JRadioButton(); this.noneRadio = new JRadioButton(); this.overridePanel = new JPanel(); this.softReplaceButton = new JButton(); this.jLabel2 = new JLabel(); this.generatePanel = new JPanel(); this.hardReplaceButton = new JButton(); this.jLabel13 = new JLabel(); this.genAddressField = new JTextField(); this.jLabel14 = new JLabel(); this.genPaletteField = new JTextField(); this.jMenuBar1 = new JMenuBar(); this.jMenu1 = new JMenu(); this.openRomMenu = new JMenuItem(); this.jMenuItem4 = new JMenuItem(); this.closeMenu = new JMenuItem(); this.jSeparator2 = new JPopupMenu.Separator(); this.inportMenu = new JMenu(); this.jMenuItem1 = new JMenuItem(); this.jMenuItem2 = new JMenuItem(); this.jSeparator6 = new JPopupMenu.Separator(); this.jMenuItem3 = new JMenuItem(); this.exportMenu = new JMenu(); this.spriteSheetMenu1 = new JMenuItem(); this.spriteSheetMenu = new JMenuItem(); this.jSeparator1 = new JPopupMenu.Separator(); this.jMenuItem5 = new JMenuItem(); this.jMenu2 = new JMenu(); this.jMenu6 = new JMenu(); this.pencilMenu = new JRadioButtonMenuItem(); this.brushMenu = new JRadioButtonMenuItem(); this.bucketMenu = new JRadioButtonMenuItem(); this.dragSpriteMenu = new JRadioButtonMenuItem(); this.dragImageMenu = new JRadioButtonMenuItem(); this.noneMenu = new JRadioButtonMenuItem(); this.jMenu5 = new JMenu(); this.sizeRadioMenu1 = new JRadioButtonMenuItem(); this.sizeRadioMenu2 = new JRadioButtonMenuItem(); this.sizeRadioMenu3 = new JRadioButtonMenuItem(); this.jMenu4 = new JMenu(); this.jMenuItem11 = new JMenuItem(); this.jMenuItem7 = new JMenuItem(); this.jMenuItem9 = new JMenuItem(); this.jMenuItem10 = new JMenuItem(); this.hexIdsMenu = new JRadioButtonMenuItem(); this.jSeparator3 = new JPopupMenu.Separator(); this.resizeAnimsMenu = new JMenuItem(); this.nameMenu = new JMenuItem(); this.jSeparator4 = new JPopupMenu.Separator(); this.copyMenu = new JMenuItem(); this.pasteMenu = new JMenuItem(); this.jSeparator5 = new JPopupMenu.Separator(); this.pasteMenu1 = new JMenuItem(); this.jMenu3 = new JMenu(); this.jMenuItem6 = new JMenuItem(); this.setDefaultCloseOperation(0); this.setTitle(TITLE); this.setLocationByPlatform(true); this.addMouseWheelListener(new MouseWheelListener(){ @Override public void mouseWheelMoved(MouseWheelEvent evt) { Gui.this.formMouseWheelMoved(evt); } }); this.addWindowListener(new WindowAdapter(){ @Override public void windowClosing(WindowEvent evt) { Gui.this.formWindowClosing(evt); } }); this.characterPanel.setBackground(new Color(229, 235, 235)); this.characterPanel.setBorder(BorderFactory.createTitledBorder("")); this.jLabel1.setFont(new Font("Tahoma", 1, 14)); this.jLabel1.setHorizontalAlignment(4); this.jLabel1.setText("Character:"); this.characterCombo.setFont(new Font("Tahoma", 0, 14)); this.characterCombo.setMaximumRowCount(16); this.characterCombo.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.characterComboActionPerformed(evt); } }); this.characterCombo.addKeyListener(new KeyAdapter(){ @Override public void keyPressed(KeyEvent evt) { Gui.this.characterComboKeyPressed(evt); } }); this.animationPanel.setBackground(new Color(241, 241, 171)); this.animationPanel.setBorder(BorderFactory.createTitledBorder("")); this.jLabel5.setFont(new Font("Tahoma", 1, 12)); this.jLabel5.setHorizontalAlignment(4); this.jLabel5.setText("Animation:"); this.animationCombo.setFont(new Font("Tahoma", 0, 14)); this.animationCombo.setMaximumRowCount(16); this.animationCombo.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.animationComboActionPerformed(evt); } }); this.animationCombo.addKeyListener(new KeyAdapter(){ @Override public void keyPressed(KeyEvent evt) { Gui.this.animationComboKeyPressed(evt); } }); this.jLabel6.setFont(new Font("Tahoma", 0, 14)); this.jLabel6.setHorizontalAlignment(4); this.jLabel6.setText("Size:"); this.sizeField.setEditable(false); this.sizeField.setFont(new Font("Courier New", 0, 14)); this.sizeField.setHorizontalAlignment(4); this.sizeField.setText("0"); this.framePanel.setBackground(new Color(240, 226, 157)); this.framePanel.setBorder(BorderFactory.createTitledBorder(null, "Frame #", 0, 0, new Font("Tahoma", 0, 14), new Color(0, 0, 0))); this.jLabel7.setFont(new Font("Tahoma", 0, 14)); this.jLabel7.setHorizontalAlignment(4); this.jLabel7.setText("Delay:"); this.delayField.setFont(new Font("Courier New", 0, 14)); this.delayField.setHorizontalAlignment(4); this.delayField.setText("0"); this.hitPanel.setBackground(new Color(236, 209, 127)); this.hitPanel.setBorder(BorderFactory.createTitledBorder(null, "Hit", 0, 0, new Font("Tahoma", 0, 11), new Color(0, 0, 0))); this.jLabel8.setFont(new Font("Tahoma", 0, 14)); this.jLabel8.setHorizontalAlignment(4); this.jLabel8.setText("x:"); this.xField.setFont(new Font("Courier New", 0, 14)); this.xField.setHorizontalAlignment(4); this.xField.setText("0"); this.jLabel9.setFont(new Font("Tahoma", 0, 14)); this.jLabel9.setHorizontalAlignment(4); this.jLabel9.setText("y:"); this.yField.setFont(new Font("Courier New", 0, 14)); this.yField.setHorizontalAlignment(4); this.yField.setText("0"); this.jLabel10.setFont(new Font("Tahoma", 0, 14)); this.jLabel10.setHorizontalAlignment(4); this.jLabel10.setText("sound:"); this.soundField.setFont(new Font("Courier New", 0, 14)); this.soundField.setHorizontalAlignment(4); this.soundField.setText("0"); this.jLabel11.setFont(new Font("Tahoma", 0, 14)); this.jLabel11.setHorizontalAlignment(4); this.jLabel11.setText("damage:"); this.damageField.setFont(new Font("Courier New", 0, 14)); this.damageField.setHorizontalAlignment(4); this.damageField.setText("0"); this.koCheck.setBackground(new Color(236, 209, 127)); this.koCheck.setFont(new Font("Tahoma", 0, 14)); this.koCheck.setText("Knock Down"); this.koCheck.setContentAreaFilled(false); this.koCheck.setFocusable(false); this.koCheck.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.koCheckActionPerformed(evt); } }); GroupLayout hitPanelLayout = new GroupLayout(this.hitPanel); this.hitPanel.setLayout(hitPanelLayout); hitPanelLayout.setHorizontalGroup(hitPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(hitPanelLayout.createSequentialGroup().addGroup(hitPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(hitPanelLayout.createSequentialGroup().addGap(16, 16, 16).addComponent(this.jLabel8, -2, 22, -2).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(this.xField, -2, 33, -2).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(this.jLabel9, -2, 22, -2).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(this.yField, -2, 33, -2)).addGroup(GroupLayout.Alignment.TRAILING, hitPanelLayout.createSequentialGroup().addContainerGap().addComponent(this.jLabel11, -2, 63, -2).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(this.damageField, -2, 33, -2))).addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED).addGroup(hitPanelLayout.createParallelGroup(GroupLayout.Alignment.TRAILING).addComponent(this.koCheck).addGroup(hitPanelLayout.createSequentialGroup().addComponent(this.jLabel10, -2, 57, -2).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(this.soundField, -2, 33, -2))).addContainerGap(-1, 32767))); hitPanelLayout.setVerticalGroup(hitPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(hitPanelLayout.createSequentialGroup().addGroup(hitPanelLayout.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(this.jLabel8).addComponent(this.xField, -2, -1, -2).addComponent(this.jLabel9).addComponent(this.yField, -2, -1, -2).addComponent(this.jLabel10).addComponent(this.soundField, -2, -1, -2)).addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED).addGroup(hitPanelLayout.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(this.jLabel11).addComponent(this.damageField, -2, -1, -2).addComponent(this.koCheck)).addGap(0, 9, 32767))); this.hitCheck.setBackground(new Color(240, 226, 157)); this.hitCheck.setFont(new Font("Tahoma", 0, 14)); this.hitCheck.setText("Hit frame"); this.hitCheck.setContentAreaFilled(false); this.hitCheck.setFocusable(false); this.hitCheck.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.hitCheckActionPerformed(evt); } }); this.jLabel12.setFont(new Font("Tahoma", 0, 14)); this.jLabel12.setHorizontalAlignment(4); this.jLabel12.setText("SpriteMap:"); this.mapField.setFont(new Font("Courier New", 0, 14)); this.mapField.setHorizontalAlignment(4); this.mapField.setText("200"); this.jLabel3.setFont(new Font("Tahoma", 0, 14)); this.jLabel3.setHorizontalAlignment(4); this.jLabel3.setText("Art Address:"); this.artField.setFont(new Font("Courier New", 0, 14)); this.artField.setHorizontalAlignment(4); this.artField.setText("200"); this.jButton2.setText("<"); this.jButton2.setFocusable(false); this.jButton2.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.jButton2ActionPerformed(evt); } }); this.jButton3.setText(">"); this.jButton3.setFocusable(false); this.jButton3.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.jButton3ActionPerformed(evt); } }); this.weaponPanel.setBackground(new Color(217, 227, 154)); this.weaponPanel.setBorder(BorderFactory.createTitledBorder(null, "Weapon Point", 0, 0, new Font("Tahoma", 0, 11), new Color(0, 0, 0))); this.jLabel15.setFont(new Font("Tahoma", 0, 14)); this.jLabel15.setHorizontalAlignment(4); this.jLabel15.setText("x:"); this.wXField.setFont(new Font("Courier New", 0, 14)); this.wXField.setHorizontalAlignment(4); this.wXField.setText("0"); this.jLabel16.setFont(new Font("Tahoma", 0, 14)); this.jLabel16.setHorizontalAlignment(4); this.jLabel16.setText("y:"); this.wYField.setFont(new Font("Courier New", 0, 14)); this.wYField.setHorizontalAlignment(4); this.wYField.setText("0"); this.jLabel17.setFont(new Font("Tahoma", 0, 14)); this.jLabel17.setHorizontalAlignment(4); this.jLabel17.setText("rotation"); this.angleField.setFont(new Font("Courier New", 0, 14)); this.angleField.setHorizontalAlignment(4); this.angleField.setText("0"); this.behindCheck.setFont(new Font("Tahoma", 0, 14)); this.behindCheck.setText("Show behind"); this.behindCheck.setContentAreaFilled(false); this.behindCheck.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.behindCheckActionPerformed(evt); } }); GroupLayout weaponPanelLayout = new GroupLayout(this.weaponPanel); this.weaponPanel.setLayout(weaponPanelLayout); weaponPanelLayout.setHorizontalGroup(weaponPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(weaponPanelLayout.createSequentialGroup().addComponent(this.jLabel15, -2, 22, -2).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(this.wXField, -2, 33, -2).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(this.jLabel16, -2, 22, -2).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(this.wYField, -2, 33, -2).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(this.jLabel17, -2, 51, -2).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(this.angleField, -2, 19, -2).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, -1, 32767).addComponent(this.behindCheck))); weaponPanelLayout.setVerticalGroup(weaponPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(weaponPanelLayout.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(this.jLabel15).addComponent(this.wXField, -2, -1, -2).addComponent(this.jLabel16).addComponent(this.wYField, -2, -1, -2).addComponent(this.jLabel17).addComponent(this.angleField, -2, -1, -2).addComponent(this.behindCheck))); this.weaponCheck.setBackground(new Color(240, 226, 157)); this.weaponCheck.setFont(new Font("Tahoma", 0, 14)); this.weaponCheck.setText("Weapon Point"); this.weaponCheck.setContentAreaFilled(false); this.weaponCheck.setFocusable(false); this.weaponCheck.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.weaponCheckActionPerformed(evt); } }); GroupLayout framePanelLayout = new GroupLayout(this.framePanel); this.framePanel.setLayout(framePanelLayout); framePanelLayout.setHorizontalGroup(framePanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(framePanelLayout.createSequentialGroup().addComponent(this.jLabel12, -2, 79, -2).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(this.mapField, -2, 62, -2).addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED).addComponent(this.jLabel3, -2, 79, -2).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(this.artField, -2, 62, -2).addContainerGap()).addGroup(framePanelLayout.createSequentialGroup().addGroup(framePanelLayout.createParallelGroup(GroupLayout.Alignment.TRAILING).addGroup(framePanelLayout.createSequentialGroup().addComponent(this.jLabel7).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(this.delayField, -2, 33, -2)).addComponent(this.hitCheck)).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, -1, 32767).addComponent(this.jButton2).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(this.jButton3)).addGroup(framePanelLayout.createSequentialGroup().addComponent(this.weaponCheck).addGap(0, 0, 32767)).addComponent(this.hitPanel, -1, -1, 32767).addComponent(this.weaponPanel, -1, -1, 32767)); framePanelLayout.setVerticalGroup(framePanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(framePanelLayout.createSequentialGroup().addGroup(framePanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(framePanelLayout.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(this.jButton2).addComponent(this.jButton3)).addGroup(framePanelLayout.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(this.jLabel7).addComponent(this.delayField, -2, -1, -2))).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(this.hitCheck).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(this.hitPanel, -2, -1, -2).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, 8, 32767).addComponent(this.weaponCheck).addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED).addComponent(this.weaponPanel, -2, -1, -2).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addGroup(framePanelLayout.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(this.jLabel12).addComponent(this.mapField, -2, -1, -2).addComponent(this.jLabel3).addComponent(this.artField, -2, -1, -2)))); GroupLayout animationPanelLayout = new GroupLayout(this.animationPanel); this.animationPanel.setLayout(animationPanelLayout); animationPanelLayout.setHorizontalGroup(animationPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(animationPanelLayout.createSequentialGroup().addComponent(this.jLabel5).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(this.animationCombo, -2, 202, -2).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(this.jLabel6).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, -1, 32767).addComponent(this.sizeField, -2, 33, -2).addGap(6, 6, 6)).addComponent(this.framePanel, -1, -1, 32767)); animationPanelLayout.setVerticalGroup(animationPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(animationPanelLayout.createSequentialGroup().addGroup(animationPanelLayout.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(this.jLabel5).addComponent(this.animationCombo, -2, -1, -2).addComponent(this.sizeField, -2, -1, -2).addComponent(this.jLabel6)).addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED).addComponent(this.framePanel, -1, -1, 32767))); this.compressedLabel.setFont(new Font("Tahoma", 1, 12)); this.compressedLabel.setForeground(new Color(199, 18, 18)); this.compressedLabel.setText("Compressed!"); GroupLayout characterPanelLayout = new GroupLayout(this.characterPanel); this.characterPanel.setLayout(characterPanelLayout); characterPanelLayout.setHorizontalGroup(characterPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(characterPanelLayout.createSequentialGroup().addGroup(characterPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(characterPanelLayout.createSequentialGroup().addComponent(this.jLabel1, -2, 73, -2).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(this.characterCombo, -2, 205, -2).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(this.compressedLabel)).addComponent(this.animationPanel, -2, -1, -2)).addContainerGap(-1, 32767))); characterPanelLayout.setVerticalGroup(characterPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(characterPanelLayout.createSequentialGroup().addGroup(characterPanelLayout.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(this.jLabel1).addComponent(this.characterCombo, -2, -1, -2).addComponent(this.compressedLabel)).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(this.animationPanel, -1, -1, 32767))); this.scrollPanel.setBackground(new Color(0, 0, 0)); this.scrollPanel.setFocusable(false); this.backBut.setBackground(new Color(241, 241, 171)); this.backBut.setText("|<<"); this.backBut.setFocusable(false); this.backBut.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.backButActionPerformed(evt); } }); this.previousBut.setBackground(new Color(240, 226, 157)); this.previousBut.setText("<<"); this.previousBut.setFocusable(false); this.previousBut.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.previousButActionPerformed(evt); } }); this.nextBut.setBackground(new Color(240, 226, 157)); this.nextBut.setText(">>"); this.nextBut.setFocusable(false); this.nextBut.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.nextButActionPerformed(evt); } }); this.frontBut.setBackground(new Color(241, 241, 171)); this.frontBut.setText(">>|"); this.frontBut.setFocusable(false); this.frontBut.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.frontButActionPerformed(evt); } }); this.playToggle.setBackground(new Color(236, 209, 127)); this.playToggle.setText(">"); this.playToggle.setFocusable(false); this.playToggle.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.playToggleActionPerformed(evt); } }); GroupLayout playerPanelLayout = new GroupLayout(this.playerPanel); this.playerPanel.setLayout(playerPanelLayout); playerPanelLayout.setHorizontalGroup(playerPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(GroupLayout.Alignment.TRAILING, playerPanelLayout.createSequentialGroup().addComponent(this.backBut, -1, -1, 32767).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(this.previousBut, -1, -1, 32767).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(this.playToggle, -2, 105, -2).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(this.nextBut, -1, -1, 32767).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(this.frontBut, -1, -1, 32767))); playerPanelLayout.setVerticalGroup(playerPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(playerPanelLayout.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(this.backBut).addComponent(this.previousBut).addComponent(this.nextBut).addComponent(this.frontBut).addComponent(this.playToggle))); this.colorsPanel1.setBorder(BorderFactory.createTitledBorder(null, "Palette", 0, 0, new Font("Tahoma", 0, 11), new Color(0, 0, 0))); this.colorsPanel1.setPreferredSize(new Dimension(256, 64)); this.colorPanel2.setBackground(new Color(255, 255, 255)); this.colorPanel2.setCursor(new Cursor(0)); this.colorPanel2.setPreferredSize(new Dimension(32, 32)); this.colorPanel2.addMouseListener(new MouseAdapter(){ @Override public void mousePressed(MouseEvent evt) { Gui.this.colorPanel2MousePressed(evt); } }); GroupLayout colorPanel2Layout = new GroupLayout(this.colorPanel2); this.colorPanel2.setLayout(colorPanel2Layout); colorPanel2Layout.setHorizontalGroup(colorPanel2Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0, 0, 32767)); colorPanel2Layout.setVerticalGroup(colorPanel2Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0, 32, 32767)); this.colorPanel3.setBackground(new Color(255, 255, 255)); this.colorPanel3.setCursor(new Cursor(0)); this.colorPanel3.setPreferredSize(new Dimension(32, 32)); this.colorPanel3.addMouseListener(new MouseAdapter(){ @Override public void mousePressed(MouseEvent evt) { Gui.this.colorPanel3MousePressed(evt); } }); GroupLayout colorPanel3Layout = new GroupLayout(this.colorPanel3); this.colorPanel3.setLayout(colorPanel3Layout); colorPanel3Layout.setHorizontalGroup(colorPanel3Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0, 0, 32767)); colorPanel3Layout.setVerticalGroup(colorPanel3Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0, 32, 32767)); this.colorPanel4.setBackground(new Color(255, 255, 255)); this.colorPanel4.setCursor(new Cursor(0)); this.colorPanel4.setPreferredSize(new Dimension(32, 32)); this.colorPanel4.addMouseListener(new MouseAdapter(){ @Override public void mousePressed(MouseEvent evt) { Gui.this.colorPanel4MousePressed(evt); } }); GroupLayout colorPanel4Layout = new GroupLayout(this.colorPanel4); this.colorPanel4.setLayout(colorPanel4Layout); colorPanel4Layout.setHorizontalGroup(colorPanel4Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0, 0, 32767)); colorPanel4Layout.setVerticalGroup(colorPanel4Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0, 32, 32767)); this.colorPanel5.setBackground(new Color(255, 255, 255)); this.colorPanel5.setCursor(new Cursor(0)); this.colorPanel5.setPreferredSize(new Dimension(32, 32)); this.colorPanel5.addMouseListener(new MouseAdapter(){ @Override public void mousePressed(MouseEvent evt) { Gui.this.colorPanel5MousePressed(evt); } }); GroupLayout colorPanel5Layout = new GroupLayout(this.colorPanel5); this.colorPanel5.setLayout(colorPanel5Layout); colorPanel5Layout.setHorizontalGroup(colorPanel5Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0, 0, 32767)); colorPanel5Layout.setVerticalGroup(colorPanel5Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0, 32, 32767)); this.colorPanel6.setBackground(new Color(255, 255, 255)); this.colorPanel6.setCursor(new Cursor(0)); this.colorPanel6.setPreferredSize(new Dimension(32, 32)); this.colorPanel6.addMouseListener(new MouseAdapter(){ @Override public void mousePressed(MouseEvent evt) { Gui.this.colorPanel6MousePressed(evt); } }); GroupLayout colorPanel6Layout = new GroupLayout(this.colorPanel6); this.colorPanel6.setLayout(colorPanel6Layout); colorPanel6Layout.setHorizontalGroup(colorPanel6Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0, 0, 32767)); colorPanel6Layout.setVerticalGroup(colorPanel6Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0, 32, 32767)); this.colorPanel7.setBackground(new Color(255, 255, 255)); this.colorPanel7.setCursor(new Cursor(0)); this.colorPanel7.setPreferredSize(new Dimension(32, 32)); this.colorPanel7.addMouseListener(new MouseAdapter(){ @Override public void mousePressed(MouseEvent evt) { Gui.this.colorPanel7MousePressed(evt); } }); GroupLayout colorPanel7Layout = new GroupLayout(this.colorPanel7); this.colorPanel7.setLayout(colorPanel7Layout); colorPanel7Layout.setHorizontalGroup(colorPanel7Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0, 0, 32767)); colorPanel7Layout.setVerticalGroup(colorPanel7Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0, 32, 32767)); this.colorPanel8.setBackground(new Color(255, 255, 255)); this.colorPanel8.setCursor(new Cursor(0)); this.colorPanel8.setPreferredSize(new Dimension(32, 32)); this.colorPanel8.addMouseListener(new MouseAdapter(){ @Override public void mousePressed(MouseEvent evt) { Gui.this.colorPanel8MousePressed(evt); } }); GroupLayout colorPanel8Layout = new GroupLayout(this.colorPanel8); this.colorPanel8.setLayout(colorPanel8Layout); colorPanel8Layout.setHorizontalGroup(colorPanel8Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0, 0, 32767)); colorPanel8Layout.setVerticalGroup(colorPanel8Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0, 32, 32767)); this.colorPanel9.setBackground(new Color(255, 255, 255)); this.colorPanel9.setCursor(new Cursor(0)); this.colorPanel9.setPreferredSize(new Dimension(32, 32)); this.colorPanel9.addMouseListener(new MouseAdapter(){ @Override public void mousePressed(MouseEvent evt) { Gui.this.colorPanel9MousePressed(evt); } }); GroupLayout colorPanel9Layout = new GroupLayout(this.colorPanel9); this.colorPanel9.setLayout(colorPanel9Layout); colorPanel9Layout.setHorizontalGroup(colorPanel9Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0, 0, 32767)); colorPanel9Layout.setVerticalGroup(colorPanel9Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0, 32, 32767)); this.colorPanel10.setBackground(new Color(255, 255, 255)); this.colorPanel10.setCursor(new Cursor(0)); this.colorPanel10.setPreferredSize(new Dimension(32, 32)); this.colorPanel10.addMouseListener(new MouseAdapter(){ @Override public void mousePressed(MouseEvent evt) { Gui.this.colorPanel10MousePressed(evt); } }); GroupLayout colorPanel10Layout = new GroupLayout(this.colorPanel10); this.colorPanel10.setLayout(colorPanel10Layout); colorPanel10Layout.setHorizontalGroup(colorPanel10Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0, 0, 32767)); colorPanel10Layout.setVerticalGroup(colorPanel10Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0, 32, 32767)); this.colorPanel11.setBackground(new Color(255, 255, 255)); this.colorPanel11.setCursor(new Cursor(0)); this.colorPanel11.setPreferredSize(new Dimension(32, 32)); this.colorPanel11.addMouseListener(new MouseAdapter(){ @Override public void mousePressed(MouseEvent evt) { Gui.this.colorPanel11MousePressed(evt); } }); GroupLayout colorPanel11Layout = new GroupLayout(this.colorPanel11); this.colorPanel11.setLayout(colorPanel11Layout); colorPanel11Layout.setHorizontalGroup(colorPanel11Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0, 0, 32767)); colorPanel11Layout.setVerticalGroup(colorPanel11Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0, 32, 32767)); this.colorPanel12.setBackground(new Color(255, 255, 255)); this.colorPanel12.setCursor(new Cursor(0)); this.colorPanel12.setPreferredSize(new Dimension(32, 32)); this.colorPanel12.addMouseListener(new MouseAdapter(){ @Override public void mousePressed(MouseEvent evt) { Gui.this.colorPanel12MousePressed(evt); } }); GroupLayout colorPanel12Layout = new GroupLayout(this.colorPanel12); this.colorPanel12.setLayout(colorPanel12Layout); colorPanel12Layout.setHorizontalGroup(colorPanel12Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0, 0, 32767)); colorPanel12Layout.setVerticalGroup(colorPanel12Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0, 32, 32767)); this.colorPanel13.setBackground(new Color(255, 255, 255)); this.colorPanel13.setCursor(new Cursor(0)); this.colorPanel13.setPreferredSize(new Dimension(32, 32)); this.colorPanel13.addMouseListener(new MouseAdapter(){ @Override public void mousePressed(MouseEvent evt) { Gui.this.colorPanel13MousePressed(evt); } }); GroupLayout colorPanel13Layout = new GroupLayout(this.colorPanel13); this.colorPanel13.setLayout(colorPanel13Layout); colorPanel13Layout.setHorizontalGroup(colorPanel13Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0, 0, 32767)); colorPanel13Layout.setVerticalGroup(colorPanel13Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0, 32, 32767)); this.colorPanel14.setBackground(new Color(255, 255, 255)); this.colorPanel14.setCursor(new Cursor(0)); this.colorPanel14.setPreferredSize(new Dimension(32, 32)); this.colorPanel14.addMouseListener(new MouseAdapter(){ @Override public void mousePressed(MouseEvent evt) { Gui.this.colorPanel14MousePressed(evt); } }); GroupLayout colorPanel14Layout = new GroupLayout(this.colorPanel14); this.colorPanel14.setLayout(colorPanel14Layout); colorPanel14Layout.setHorizontalGroup(colorPanel14Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0, 0, 32767)); colorPanel14Layout.setVerticalGroup(colorPanel14Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0, 32, 32767)); this.colorPanel15.setBackground(new Color(255, 255, 255)); this.colorPanel15.setCursor(new Cursor(0)); this.colorPanel15.setPreferredSize(new Dimension(32, 32)); this.colorPanel15.addMouseListener(new MouseAdapter(){ @Override public void mousePressed(MouseEvent evt) { Gui.this.colorPanel15MousePressed(evt); } }); GroupLayout colorPanel15Layout = new GroupLayout(this.colorPanel15); this.colorPanel15.setLayout(colorPanel15Layout); colorPanel15Layout.setHorizontalGroup(colorPanel15Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0, 0, 32767)); colorPanel15Layout.setVerticalGroup(colorPanel15Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0, 32, 32767)); this.colorPanel16.setBackground(new Color(255, 255, 255)); this.colorPanel16.setCursor(new Cursor(0)); this.colorPanel16.setPreferredSize(new Dimension(32, 32)); this.colorPanel16.addMouseListener(new MouseAdapter(){ @Override public void mousePressed(MouseEvent evt) { Gui.this.colorPanel16MousePressed(evt); } }); GroupLayout colorPanel16Layout = new GroupLayout(this.colorPanel16); this.colorPanel16.setLayout(colorPanel16Layout); colorPanel16Layout.setHorizontalGroup(colorPanel16Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0, 0, 32767)); colorPanel16Layout.setVerticalGroup(colorPanel16Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0, 32, 32767)); this.colorPanel1.setBackground(new Color(255, 255, 255)); this.colorPanel1.setCursor(new Cursor(0)); this.colorPanel1.setPreferredSize(new Dimension(32, 32)); this.colorPanel1.addMouseListener(new MouseAdapter(){ @Override public void mousePressed(MouseEvent evt) { Gui.this.colorPanel1MousePressed(evt); } }); GroupLayout colorPanel1Layout = new GroupLayout(this.colorPanel1); this.colorPanel1.setLayout(colorPanel1Layout); colorPanel1Layout.setHorizontalGroup(colorPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0, 0, 32767)); colorPanel1Layout.setVerticalGroup(colorPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0, 32, 32767)); GroupLayout colorsPanel1Layout = new GroupLayout(this.colorsPanel1); this.colorsPanel1.setLayout(colorsPanel1Layout); colorsPanel1Layout.setHorizontalGroup(colorsPanel1Layout.createParallelGroup(GroupLayout.Alignment.TRAILING).addGroup(colorsPanel1Layout.createSequentialGroup().addGap(0, 0, 0).addGroup(colorsPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(this.colorPanel1, -1, 33, 32767).addComponent(this.colorPanel9, -1, 33, 32767)).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addGroup(colorsPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(this.colorPanel2, -1, 33, 32767).addComponent(this.colorPanel10, -1, 33, 32767)).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addGroup(colorsPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(this.colorPanel3, -1, 33, 32767).addComponent(this.colorPanel11, -1, 33, 32767)).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addGroup(colorsPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(this.colorPanel4, -1, 35, 32767).addComponent(this.colorPanel12, -1, 35, 32767)).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addGroup(colorsPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(this.colorPanel5, -1, 37, 32767).addComponent(this.colorPanel13, -1, 37, 32767)).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addGroup(colorsPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(this.colorPanel6, -1, 35, 32767).addComponent(this.colorPanel14, -1, 35, 32767)).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addGroup(colorsPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(this.colorPanel7, -1, 35, 32767).addComponent(this.colorPanel15, -1, 35, 32767)).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addGroup(colorsPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(this.colorPanel8, -1, 34, 32767).addComponent(this.colorPanel16, -1, 34, 32767)))); colorsPanel1Layout.setVerticalGroup(colorsPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(colorsPanel1Layout.createSequentialGroup().addGroup(colorsPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(this.colorPanel2, -2, -1, -2).addComponent(this.colorPanel3, -2, -1, -2).addComponent(this.colorPanel4, -2, -1, -2).addComponent(this.colorPanel5, -2, -1, -2).addComponent(this.colorPanel6, -2, -1, -2).addComponent(this.colorPanel7, -2, -1, -2).addComponent(this.colorPanel8, -2, -1, -2).addComponent(this.colorPanel1, -2, -1, -2)).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, -1, 32767).addGroup(colorsPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(this.colorPanel10, GroupLayout.Alignment.TRAILING, -2, -1, -2).addComponent(this.colorPanel11, GroupLayout.Alignment.TRAILING, -2, -1, -2).addComponent(this.colorPanel12, GroupLayout.Alignment.TRAILING, -2, -1, -2).addComponent(this.colorPanel13, GroupLayout.Alignment.TRAILING, -2, -1, -2).addComponent(this.colorPanel14, GroupLayout.Alignment.TRAILING, -2, -1, -2).addComponent(this.colorPanel15, GroupLayout.Alignment.TRAILING, -2, -1, -2).addComponent(this.colorPanel16, GroupLayout.Alignment.TRAILING, -2, -1, -2).addComponent(this.colorPanel9, GroupLayout.Alignment.TRAILING, -2, -1, -2)))); GroupLayout previewPanelLayout = new GroupLayout(this.previewPanel); this.previewPanel.setLayout(previewPanelLayout); previewPanelLayout.setHorizontalGroup(previewPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(this.playerPanel, GroupLayout.Alignment.TRAILING, -1, -1, 32767).addComponent(this.scrollPanel, GroupLayout.Alignment.TRAILING).addComponent(this.colorsPanel1, -1, 333, 32767)); previewPanelLayout.setVerticalGroup(previewPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(previewPanelLayout.createSequentialGroup().addComponent(this.scrollPanel).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(this.playerPanel, -2, -1, -2).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(this.colorsPanel1, -2, 100, -2))); this.characterPanel1.setBackground(new Color(228, 236, 191)); this.characterPanel1.setBorder(BorderFactory.createTitledBorder(null, "View", 0, 0, new Font("Tahoma", 0, 14), new Color(0, 0, 0))); this.showHitsCheck.setBackground(new Color(228, 236, 191)); this.showHitsCheck.setSelected(true); this.showHitsCheck.setText("Hit Point"); this.showHitsCheck.setContentAreaFilled(false); this.showHitsCheck.setFocusable(false); this.showHitsCheck.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.showHitsCheckActionPerformed(evt); } }); this.showWeaponCheck.setBackground(new Color(228, 236, 191)); this.showWeaponCheck.setSelected(true); this.showWeaponCheck.setText("Weapon:"); this.showWeaponCheck.setContentAreaFilled(false); this.showWeaponCheck.setFocusable(false); this.showWeaponCheck.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.showWeaponCheckActionPerformed(evt); } }); this.weaponCombo.setModel(new DefaultComboBoxModel<String>(new String[]{"Knife", "Pipe"})); this.weaponCombo.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.weaponComboActionPerformed(evt); } }); this.showFacedRightCheck.setBackground(new Color(228, 236, 191)); this.showFacedRightCheck.setSelected(true); this.showFacedRightCheck.setText("Faced Right"); this.showFacedRightCheck.setContentAreaFilled(false); this.showFacedRightCheck.setFocusable(false); this.showFacedRightCheck.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.showFacedRightCheckActionPerformed(evt); } }); this.showTileCheck.setBackground(new Color(228, 236, 191)); this.showTileCheck.setSelected(true); this.showTileCheck.setText("Tile Space"); this.showTileCheck.setContentAreaFilled(false); this.showTileCheck.setFocusable(false); this.showTileCheck.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.showTileCheckActionPerformed(evt); } }); this.showCenterCheck.setBackground(new Color(228, 236, 191)); this.showCenterCheck.setText("Ghost"); this.showCenterCheck.setContentAreaFilled(false); this.showCenterCheck.setFocusable(false); this.showCenterCheck.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.showCenterCheckActionPerformed(evt); } }); GroupLayout characterPanel1Layout = new GroupLayout(this.characterPanel1); this.characterPanel1.setLayout(characterPanel1Layout); characterPanel1Layout.setHorizontalGroup(characterPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(characterPanel1Layout.createSequentialGroup().addGroup(characterPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(this.showWeaponCheck).addComponent(this.showCenterCheck).addComponent(this.showHitsCheck)).addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED).addGroup(characterPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(this.weaponCombo, -2, 83, -2).addComponent(this.showFacedRightCheck).addComponent(this.showTileCheck)).addContainerGap(-1, 32767))); characterPanel1Layout.setVerticalGroup(characterPanel1Layout.createParallelGroup(GroupLayout.Alignment.TRAILING).addGroup(characterPanel1Layout.createSequentialGroup().addGap(1, 1, 1).addGroup(characterPanel1Layout.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(this.showFacedRightCheck).addComponent(this.showCenterCheck)).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addGroup(characterPanel1Layout.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(this.showTileCheck).addComponent(this.showHitsCheck)).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, 3, 32767).addGroup(characterPanel1Layout.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(this.weaponCombo, -2, -1, -2).addComponent(this.showWeaponCheck)))); this.toolsPanel.setBackground(new Color(230, 230, 235)); this.toolsPanel.setBorder(BorderFactory.createTitledBorder(null, "Tools", 0, 0, new Font("Tahoma", 0, 14), new Color(0, 0, 0))); this.pencilRadio.setBackground(new Color(230, 226, 235)); this.pencilRadio.setText("Pencil"); this.pencilRadio.setContentAreaFilled(false); this.pencilRadio.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.pencilRadioActionPerformed(evt); } }); this.brushRadio.setBackground(new Color(230, 226, 235)); this.brushRadio.setText("Brush"); this.brushRadio.setContentAreaFilled(false); this.brushRadio.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.brushRadioActionPerformed(evt); } }); this.bucketRadio.setBackground(new Color(230, 226, 235)); this.bucketRadio.setText("Paint Bucket"); this.bucketRadio.setContentAreaFilled(false); this.bucketRadio.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.bucketRadioActionPerformed(evt); } }); this.dragSpriteRadio.setBackground(new Color(230, 226, 235)); this.dragSpriteRadio.setText("Drag Sprite"); this.dragSpriteRadio.setContentAreaFilled(false); this.dragSpriteRadio.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.dragSpriteRadioActionPerformed(evt); } }); this.dragImageRadio.setBackground(new Color(230, 226, 235)); this.dragImageRadio.setText("Drag Image"); this.dragImageRadio.setContentAreaFilled(false); this.dragImageRadio.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.dragImageRadioActionPerformed(evt); } }); this.noneRadio.setBackground(new Color(230, 226, 235)); this.noneRadio.setSelected(true); this.noneRadio.setText("None"); this.noneRadio.setContentAreaFilled(false); this.noneRadio.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.noneRadioActionPerformed(evt); } }); GroupLayout toolsPanelLayout = new GroupLayout(this.toolsPanel); this.toolsPanel.setLayout(toolsPanelLayout); toolsPanelLayout.setHorizontalGroup(toolsPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(toolsPanelLayout.createSequentialGroup().addContainerGap().addGroup(toolsPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(this.pencilRadio).addComponent(this.brushRadio).addComponent(this.bucketRadio)).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, -1, 32767).addGroup(toolsPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(toolsPanelLayout.createSequentialGroup().addGap(2, 2, 2).addComponent(this.dragSpriteRadio)).addGroup(GroupLayout.Alignment.TRAILING, toolsPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING, false).addComponent(this.dragImageRadio, -1, -1, 32767).addComponent(this.noneRadio, -2, 81, -2))))); toolsPanelLayout.setVerticalGroup(toolsPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(toolsPanelLayout.createSequentialGroup().addGroup(toolsPanelLayout.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(this.pencilRadio).addComponent(this.dragSpriteRadio)).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addGroup(toolsPanelLayout.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(this.brushRadio).addComponent(this.dragImageRadio)).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, -1, 32767).addGroup(toolsPanelLayout.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(this.bucketRadio).addComponent(this.noneRadio)))); this.overridePanel.setBackground(new Color(240, 233, 221)); this.overridePanel.setBorder(BorderFactory.createTitledBorder(null, "Override Art", 0, 0, new Font("Tahoma", 0, 14), new Color(0, 0, 0))); this.softReplaceButton.setText("Replace from Image"); this.softReplaceButton.setFocusable(false); this.softReplaceButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.softReplaceButtonActionPerformed(evt); } }); this.jLabel2.setText("Replace art using same tiles"); GroupLayout overridePanelLayout = new GroupLayout(this.overridePanel); this.overridePanel.setLayout(overridePanelLayout); overridePanelLayout.setHorizontalGroup(overridePanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(overridePanelLayout.createSequentialGroup().addContainerGap(-1, 32767).addGroup(overridePanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(GroupLayout.Alignment.TRAILING, overridePanelLayout.createSequentialGroup().addComponent(this.softReplaceButton).addGap(18, 18, 18)).addGroup(GroupLayout.Alignment.TRAILING, overridePanelLayout.createSequentialGroup().addComponent(this.jLabel2).addContainerGap())))); overridePanelLayout.setVerticalGroup(overridePanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(GroupLayout.Alignment.TRAILING, overridePanelLayout.createSequentialGroup().addGap(19, 19, 19).addComponent(this.jLabel2).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, 27, 32767).addComponent(this.softReplaceButton))); this.generatePanel.setBackground(new Color(240, 221, 221)); this.generatePanel.setBorder(BorderFactory.createTitledBorder(null, "Generate Sprite", 0, 0, new Font("Tahoma", 0, 14), new Color(0, 0, 0))); this.hardReplaceButton.setText("Generate From Image"); this.hardReplaceButton.setFocusable(false); this.hardReplaceButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.hardReplaceButtonActionPerformed(evt); } }); this.jLabel13.setFont(new Font("Tahoma", 0, 14)); this.jLabel13.setHorizontalAlignment(4); this.jLabel13.setText("Address:"); this.genAddressField.setFont(new Font("Courier New", 0, 14)); this.genAddressField.setHorizontalAlignment(4); this.genAddressField.setText("200"); this.jLabel14.setFont(new Font("Tahoma", 0, 14)); this.jLabel14.setHorizontalAlignment(4); this.jLabel14.setText("Palette Line:"); this.genPaletteField.setFont(new Font("Courier New", 0, 14)); this.genPaletteField.setHorizontalAlignment(4); this.genPaletteField.setText("0"); GroupLayout generatePanelLayout = new GroupLayout(this.generatePanel); this.generatePanel.setLayout(generatePanelLayout); generatePanelLayout.setHorizontalGroup(generatePanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(generatePanelLayout.createSequentialGroup().addGroup(generatePanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(generatePanelLayout.createSequentialGroup().addGap(18, 18, 18).addGroup(generatePanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING, false).addGroup(generatePanelLayout.createSequentialGroup().addComponent(this.jLabel13, -2, 61, -2).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(this.genAddressField)).addGroup(generatePanelLayout.createSequentialGroup().addComponent(this.jLabel14, -2, 79, -2).addGap(18, 18, 18).addComponent(this.genPaletteField, -2, 24, -2)))).addGroup(generatePanelLayout.createSequentialGroup().addContainerGap().addComponent(this.hardReplaceButton))).addGap(0, 25, 32767))); generatePanelLayout.setVerticalGroup(generatePanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(GroupLayout.Alignment.TRAILING, generatePanelLayout.createSequentialGroup().addGroup(generatePanelLayout.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(this.jLabel13).addComponent(this.genAddressField, -2, -1, -2)).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, -1, 32767).addGroup(generatePanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(this.jLabel14, GroupLayout.Alignment.TRAILING).addComponent(this.genPaletteField, GroupLayout.Alignment.TRAILING, -2, -1, -2)).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(this.hardReplaceButton))); GroupLayout mainPanelLayout = new GroupLayout(this.mainPanel); this.mainPanel.setLayout(mainPanelLayout); mainPanelLayout.setHorizontalGroup(mainPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(mainPanelLayout.createSequentialGroup().addGroup(mainPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING, false).addGroup(mainPanelLayout.createSequentialGroup().addGroup(mainPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(this.characterPanel1, -1, 0, 32767).addComponent(this.overridePanel, -1, -1, 32767)).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addGroup(mainPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(this.toolsPanel, GroupLayout.Alignment.TRAILING, -2, -1, -2).addComponent(this.generatePanel, GroupLayout.Alignment.TRAILING, -2, -1, -2))).addComponent(this.characterPanel, -2, 376, -2)).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(this.previewPanel, -1, -1, 32767))); mainPanelLayout.setVerticalGroup(mainPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(mainPanelLayout.createSequentialGroup().addComponent(this.characterPanel, -2, -1, -2).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addGroup(mainPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(this.characterPanel1, -2, -1, -2).addComponent(this.toolsPanel, -2, -1, -2)).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addGroup(mainPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(this.overridePanel, -2, -1, -2).addComponent(this.generatePanel, -2, -1, -2))).addComponent(this.previewPanel, -1, -1, 32767)); this.jMenu1.setText("File"); this.openRomMenu.setAccelerator(KeyStroke.getKeyStroke(82, 2)); this.openRomMenu.setText("Open Rom"); this.openRomMenu.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.openRomMenuActionPerformed(evt); } }); this.jMenu1.add(this.openRomMenu); this.jMenuItem4.setText("Open with Specific Guide"); this.jMenuItem4.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.jMenuItem4ActionPerformed(evt); } }); this.jMenu1.add(this.jMenuItem4); this.closeMenu.setText("Close"); this.closeMenu.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.closeMenuActionPerformed(evt); } }); this.jMenu1.add(this.closeMenu); this.jMenu1.add(this.jSeparator2); this.inportMenu.setText("Inport Character..."); this.jMenuItem1.setText("Replace from Spritesheet"); this.jMenuItem1.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.jMenuItem1ActionPerformed(evt); } }); this.inportMenu.add(this.jMenuItem1); this.jMenuItem2.setText("Generate from Spritesheet"); this.jMenuItem2.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.jMenuItem2ActionPerformed(evt); } }); this.inportMenu.add(this.jMenuItem2); this.inportMenu.add(this.jSeparator6); this.jMenuItem3.setText("Import from other ROM"); this.jMenuItem3.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.jMenuItem3ActionPerformed(evt); } }); this.inportMenu.add(this.jMenuItem3); this.jMenu1.add(this.inportMenu); this.exportMenu.setText("Export Character..."); this.spriteSheetMenu1.setText("Individual Frames"); this.spriteSheetMenu1.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.spriteSheetMenu1ActionPerformed(evt); } }); this.exportMenu.add(this.spriteSheetMenu1); this.spriteSheetMenu.setText("Spritesheet"); this.spriteSheetMenu.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.spriteSheetMenuActionPerformed(evt); } }); this.exportMenu.add(this.spriteSheetMenu); this.jMenu1.add(this.exportMenu); this.jMenu1.add(this.jSeparator1); this.jMenuItem5.setAccelerator(KeyStroke.getKeyStroke(115, 8)); this.jMenuItem5.setText("Exit"); this.jMenuItem5.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.jMenuItem5ActionPerformed(evt); } }); this.jMenu1.add(this.jMenuItem5); this.jMenuBar1.add(this.jMenu1); this.jMenu2.setText("Edit"); this.jMenu6.setText("Tool"); this.pencilMenu.setAccelerator(KeyStroke.getKeyStroke(49, 8)); this.pencilMenu.setText("Pencil"); this.pencilMenu.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.pencilMenuActionPerformed(evt); } }); this.jMenu6.add(this.pencilMenu); this.brushMenu.setAccelerator(KeyStroke.getKeyStroke(50, 8)); this.brushMenu.setText("Brush"); this.brushMenu.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.brushMenuActionPerformed(evt); } }); this.jMenu6.add(this.brushMenu); this.bucketMenu.setAccelerator(KeyStroke.getKeyStroke(51, 8)); this.bucketMenu.setText("Paint Bucket"); this.bucketMenu.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.bucketMenuActionPerformed(evt); } }); this.jMenu6.add(this.bucketMenu); this.dragSpriteMenu.setAccelerator(KeyStroke.getKeyStroke(52, 8)); this.dragSpriteMenu.setText("Drag Sprite"); this.dragSpriteMenu.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.dragSpriteMenuActionPerformed(evt); } }); this.jMenu6.add(this.dragSpriteMenu); this.dragImageMenu.setAccelerator(KeyStroke.getKeyStroke(53, 8)); this.dragImageMenu.setText("Drag Image"); this.dragImageMenu.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.dragImageMenuActionPerformed(evt); } }); this.jMenu6.add(this.dragImageMenu); this.noneMenu.setAccelerator(KeyStroke.getKeyStroke(54, 8)); this.noneMenu.setSelected(true); this.noneMenu.setText("None"); this.noneMenu.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.noneMenuActionPerformed(evt); } }); this.jMenu6.add(this.noneMenu); this.jMenu2.add(this.jMenu6); this.jMenu5.setText("Brush Size"); this.sizeRadioMenu1.setAccelerator(KeyStroke.getKeyStroke(49, 1)); this.sizeRadioMenu1.setSelected(true); this.sizeRadioMenu1.setText("3 pixels"); this.sizeRadioMenu1.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.sizeRadioMenu1ActionPerformed(evt); } }); this.jMenu5.add(this.sizeRadioMenu1); this.sizeRadioMenu2.setAccelerator(KeyStroke.getKeyStroke(50, 1)); this.sizeRadioMenu2.setText("5 pixels"); this.sizeRadioMenu2.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.sizeRadioMenu2ActionPerformed(evt); } }); this.jMenu5.add(this.sizeRadioMenu2); this.sizeRadioMenu3.setAccelerator(KeyStroke.getKeyStroke(51, 1)); this.sizeRadioMenu3.setText("10 pixels"); this.sizeRadioMenu3.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.sizeRadioMenu3ActionPerformed(evt); } }); this.jMenu5.add(this.sizeRadioMenu3); this.jMenu2.add(this.jMenu5); this.jMenu4.setText("Scale"); this.jMenuItem11.setAccelerator(KeyStroke.getKeyStroke(49, 2)); this.jMenuItem11.setText("Reset Scale"); this.jMenuItem11.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.jMenuItem11ActionPerformed(evt); } }); this.jMenu4.add(this.jMenuItem11); this.jMenuItem7.setAccelerator(KeyStroke.getKeyStroke(50, 2)); this.jMenuItem7.setText("2x Scale"); this.jMenuItem7.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.jMenuItem7ActionPerformed(evt); } }); this.jMenu4.add(this.jMenuItem7); this.jMenuItem9.setAccelerator(KeyStroke.getKeyStroke(51, 2)); this.jMenuItem9.setText("6x Scale"); this.jMenuItem9.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.jMenuItem9ActionPerformed(evt); } }); this.jMenu4.add(this.jMenuItem9); this.jMenuItem10.setAccelerator(KeyStroke.getKeyStroke(52, 2)); this.jMenuItem10.setText("12x Scale"); this.jMenuItem10.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.jMenuItem10ActionPerformed(evt); } }); this.jMenu4.add(this.jMenuItem10); this.jMenu2.add(this.jMenu4); this.hexIdsMenu.setText("See IDs as hex"); this.hexIdsMenu.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.hexIdsMenuActionPerformed(evt); } }); this.jMenu2.add(this.hexIdsMenu); this.jMenu2.add(this.jSeparator3); this.resizeAnimsMenu.setText("Resize Animations"); this.resizeAnimsMenu.setEnabled(false); this.resizeAnimsMenu.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.resizeAnimsMenuActionPerformed(evt); } }); this.jMenu2.add(this.resizeAnimsMenu); this.nameMenu.setText("Properties"); this.nameMenu.setEnabled(false); this.nameMenu.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.nameMenuActionPerformed(evt); } }); this.jMenu2.add(this.nameMenu); this.jMenu2.add(this.jSeparator4); this.copyMenu.setAccelerator(KeyStroke.getKeyStroke(116, 0)); this.copyMenu.setText("Copy Frame"); this.copyMenu.setEnabled(false); this.copyMenu.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.copyMenuActionPerformed(evt); } }); this.jMenu2.add(this.copyMenu); this.pasteMenu.setAccelerator(KeyStroke.getKeyStroke(117, 0)); this.pasteMenu.setText("Paste Frame"); this.pasteMenu.setEnabled(false); this.pasteMenu.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.pasteMenuActionPerformed(evt); } }); this.jMenu2.add(this.pasteMenu); this.jMenu2.add(this.jSeparator5); this.pasteMenu1.setText("Decompress Art"); this.pasteMenu1.setEnabled(false); this.pasteMenu1.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.pasteMenu1ActionPerformed(evt); } }); this.jMenu2.add(this.pasteMenu1); this.jMenuBar1.add(this.jMenu2); this.jMenu3.setText("Help"); this.jMenuItem6.setText("About"); this.jMenuItem6.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent evt) { Gui.this.jMenuItem6ActionPerformed(evt); } }); this.jMenu3.add(this.jMenuItem6); this.jMenuBar1.add(this.jMenu3); this.setJMenuBar(this.jMenuBar1); GroupLayout layout = new GroupLayout(this.getContentPane()); this.getContentPane().setLayout(layout); layout.setHorizontalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(this.mainPanel, -1, -1, 32767)); layout.setVerticalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(this.mainPanel, -1, -1, 32767)); this.pack(); }// </editor-fold>//GEN-END:initComponents private void colorPanel2MousePressed(MouseEvent evt) {//GEN-FIRST:event_colorPanel2MousePressed this.colorPanelPressed(1); }//GEN-LAST:event_colorPanel2MousePressed private void colorPanel3MousePressed(MouseEvent evt) {//GEN-FIRST:event_colorPanel3MousePressed this.colorPanelPressed(2); }//GEN-LAST:event_colorPanel3MousePressed private void colorPanel4MousePressed(MouseEvent evt) {//GEN-FIRST:event_colorPanel4MousePressed this.colorPanelPressed(3); }//GEN-LAST:event_colorPanel4MousePressed private void colorPanel5MousePressed(MouseEvent evt) {//GEN-FIRST:event_colorPanel5MousePressed this.colorPanelPressed(4); }//GEN-LAST:event_colorPanel5MousePressed private void colorPanel6MousePressed(MouseEvent evt) {//GEN-FIRST:event_colorPanel6MousePressed this.colorPanelPressed(5); }//GEN-LAST:event_colorPanel6MousePressed private void colorPanel7MousePressed(MouseEvent evt) {//GEN-FIRST:event_colorPanel7MousePressed this.colorPanelPressed(6); }//GEN-LAST:event_colorPanel7MousePressed private void colorPanel8MousePressed(MouseEvent evt) {//GEN-FIRST:event_colorPanel8MousePressed this.colorPanelPressed(7); }//GEN-LAST:event_colorPanel8MousePressed private void colorPanel9MousePressed(MouseEvent evt) {//GEN-FIRST:event_colorPanel9MousePressed this.colorPanelPressed(8); }//GEN-LAST:event_colorPanel9MousePressed private void colorPanel10MousePressed(MouseEvent evt) {//GEN-FIRST:event_colorPanel10MousePressed this.colorPanelPressed(9); }//GEN-LAST:event_colorPanel10MousePressed private void colorPanel11MousePressed(MouseEvent evt) {//GEN-FIRST:event_colorPanel11MousePressed this.colorPanelPressed(10); }//GEN-LAST:event_colorPanel11MousePressed private void colorPanel12MousePressed(MouseEvent evt) {//GEN-FIRST:event_colorPanel12MousePressed this.colorPanelPressed(11); }//GEN-LAST:event_colorPanel12MousePressed private void colorPanel13MousePressed(MouseEvent evt) {//GEN-FIRST:event_colorPanel13MousePressed this.colorPanelPressed(12); }//GEN-LAST:event_colorPanel13MousePressed private void colorPanel14MousePressed(MouseEvent evt) {//GEN-FIRST:event_colorPanel14MousePressed this.colorPanelPressed(13); }//GEN-LAST:event_colorPanel14MousePressed private void colorPanel15MousePressed(MouseEvent evt) {//GEN-FIRST:event_colorPanel15MousePressed this.colorPanelPressed(14); }//GEN-LAST:event_colorPanel15MousePressed private void colorPanel16MousePressed(MouseEvent evt) {//GEN-FIRST:event_colorPanel16MousePressed this.colorPanelPressed(15); }//GEN-LAST:event_colorPanel16MousePressed private void colorPanel1MousePressed(MouseEvent evt) {//GEN-FIRST:event_colorPanel1MousePressed this.colorPanelPressed(0); }//GEN-LAST:event_colorPanel1MousePressed private void formMouseWheelMoved(MouseWheelEvent evt) {//GEN-FIRST:event_formMouseWheelMoved this.scaleImagePanel(-0.2f * (float)evt.getWheelRotation()); }//GEN-LAST:event_formMouseWheelMoved private void jMenuItem11ActionPerformed(ActionEvent evt) {//GEN-FIRST:event_jMenuItem11ActionPerformed this.setImagePanelScale(1.0f); }//GEN-LAST:event_jMenuItem11ActionPerformed private void jMenuItem7ActionPerformed(ActionEvent evt) {//GEN-FIRST:event_jMenuItem7ActionPerformed this.setImagePanelScale(2.0f); }//GEN-LAST:event_jMenuItem7ActionPerformed private void jMenuItem9ActionPerformed(ActionEvent evt) {//GEN-FIRST:event_jMenuItem9ActionPerformed this.setImagePanelScale(6.0f); }//GEN-LAST:event_jMenuItem9ActionPerformed private void jMenuItem10ActionPerformed(ActionEvent evt) {//GEN-FIRST:event_jMenuItem10ActionPerformed this.setImagePanelScale(12.0f); }//GEN-LAST:event_jMenuItem10ActionPerformed private void openRomMenuActionPerformed(ActionEvent evt) {//GEN-FIRST:event_openRomMenuActionPerformed Guide oldGuide = this.guide; if (this.openDefaultGuide() || this.openCustomGuide()) { if (!this.openRom()) { this.guide = oldGuide; } } else { this.guide = oldGuide; } }//GEN-LAST:event_openRomMenuActionPerformed private void closeMenuActionPerformed(ActionEvent evt) {//GEN-FIRST:event_closeMenuActionPerformed this.closeRom(); }//GEN-LAST:event_closeMenuActionPerformed private void jMenuItem4ActionPerformed(ActionEvent evt) {//GEN-FIRST:event_jMenuItem4ActionPerformed Guide oldGuide = this.guide; if (this.openCustomGuide()) { if (!this.openRom()) { this.guide = oldGuide; } } else { this.guide = oldGuide; } }//GEN-LAST:event_jMenuItem4ActionPerformed private void jMenuItem5ActionPerformed(ActionEvent evt) {//GEN-FIRST:event_jMenuItem5ActionPerformed if (this.askSaveRom()) { this.closeRom(); System.exit(0); } }//GEN-LAST:event_jMenuItem5ActionPerformed private void jButton3ActionPerformed(ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed this.setNextFrame(); }//GEN-LAST:event_jButton3ActionPerformed private void jButton2ActionPerformed(ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed this.setPreviousFrame(); }//GEN-LAST:event_jButton2ActionPerformed private void nextButActionPerformed(ActionEvent evt) {//GEN-FIRST:event_nextButActionPerformed this.setNextFrame(); }//GEN-LAST:event_nextButActionPerformed private void previousButActionPerformed(ActionEvent evt) {//GEN-FIRST:event_previousButActionPerformed this.setPreviousFrame(); }//GEN-LAST:event_previousButActionPerformed private void animationComboActionPerformed(ActionEvent evt) {//GEN-FIRST:event_animationComboActionPerformed int newAnim = this.animationCombo.getSelectedIndex(); if (newAnim != this.currAnimation && newAnim >= 0) { this.changeAnimation(newAnim); } }//GEN-LAST:event_animationComboActionPerformed private void frontButActionPerformed(ActionEvent evt) {//GEN-FIRST:event_frontButActionPerformed this.setNextAnimation(); }//GEN-LAST:event_frontButActionPerformed private void backButActionPerformed(ActionEvent evt) {//GEN-FIRST:event_backButActionPerformed this.setPreviousAnimation(); }//GEN-LAST:event_backButActionPerformed private void animationComboKeyPressed(KeyEvent evt) {//GEN-FIRST:event_animationComboKeyPressed switch (evt.getKeyCode()) { case 39: { this.setNextFrame(); break; } case 37: { this.setPreviousFrame(); } } }//GEN-LAST:event_animationComboKeyPressed private void characterComboActionPerformed(ActionEvent evt) {//GEN-FIRST:event_characterComboActionPerformed if (this.manager == null || this.guide == null) { return; } int newChar = this.guide.getRealCharId(this.characterCombo.getSelectedIndex()); if (newChar != this.manager.getCurrentCharacterId() && newChar >= 0) { try { this.changeCharacter(newChar); } catch (IOException ex) { ex.printStackTrace(); this.showError("Unable to read '" + this.characterCombo.getSelectedItem() + "' character"); } } }//GEN-LAST:event_characterComboActionPerformed private void playToggleActionPerformed(ActionEvent evt) {//GEN-FIRST:event_playToggleActionPerformed if (this.playToggle.isSelected()) { this.timer.start(); this.playToggle.setText("[]"); } else { this.timer.stop(); this.playToggle.setText(">"); } }//GEN-LAST:event_playToggleActionPerformed private void showHitsCheckActionPerformed(ActionEvent evt) {//GEN-FIRST:event_showHitsCheckActionPerformed this.imagePanel.showHit(this.showHitsCheck.isSelected()); }//GEN-LAST:event_showHitsCheckActionPerformed private void showCenterCheckActionPerformed(ActionEvent evt) {//GEN-FIRST:event_showCenterCheckActionPerformed this.imagePanel.showGhost(this.showCenterCheck.isSelected()); }//GEN-LAST:event_showCenterCheckActionPerformed private void showTileCheckActionPerformed(ActionEvent evt) {//GEN-FIRST:event_showTileCheckActionPerformed this.imagePanel.showShadow(this.showTileCheck.isSelected()); }//GEN-LAST:event_showTileCheckActionPerformed private void hitCheckActionPerformed(ActionEvent evt) {//GEN-FIRST:event_hitCheckActionPerformed Character ch = this.manager.getCharacter(); HitFrame hitFrame = ch.getHitFrame(this.currAnimation, this.currFrame); boolean selected = this.hitCheck.isSelected(); if (hitFrame.isEnabled() != selected) { hitFrame.setEnabled(selected); ch.setModified(true); this.refresh(); } }//GEN-LAST:event_hitCheckActionPerformed private void koCheckActionPerformed(ActionEvent evt) {//GEN-FIRST:event_koCheckActionPerformed Character ch = this.manager.getCharacter(); HitFrame hitFrame = ch.getHitFrame(this.currAnimation, this.currFrame); boolean selected = this.koCheck.isSelected(); if (hitFrame.knockDown != selected) { hitFrame.knockDown = selected; ch.setModified(true); this.refresh(); } }//GEN-LAST:event_koCheckActionPerformed private void formWindowClosing(WindowEvent evt) {//GEN-FIRST:event_formWindowClosing if (this.askSaveRom()) { this.closeRom(); System.exit(0); } }//GEN-LAST:event_formWindowClosing private void softReplaceButtonActionPerformed(ActionEvent evt) {//GEN-FIRST:event_softReplaceButtonActionPerformed int returnVal = this.imageChooser.showOpenDialog(this); if (returnVal == 0) { File file = this.imageChooser.getSelectedFile(); try { BufferedImage replaceImg = ImageIO.read(file); replaceImg = this.processReplaceImg(replaceImg); this.dragImageRadio.setEnabled(true); this.imagePanel.setReplaceImage(replaceImg); } catch (IOException ex) { ex.printStackTrace(); this.showError("Unable to read image file: " + file.getName()); this.imagePanel.setReplaceImage(null); this.dragImageRadio.setEnabled(false); } this.manager.getCharacter().getAnimation(this.currAnimation).setSpritesModified(this.currFrame, true); this.manager.getCharacter().setSpritesModified(true); this.manager.getCharacter().setModified(true); } }//GEN-LAST:event_softReplaceButtonActionPerformed private void hardReplaceButtonActionPerformed(ActionEvent evt) {//GEN-FIRST:event_hardReplaceButtonActionPerformed int returnVal = this.imageChooser.showOpenDialog(this); if (returnVal == 0) { File file = this.imageChooser.getSelectedFile(); try { this.manager.getCharacter().setModified(true); this.manager.getCharacter().setSpritesModified(true); this.manager.getCharacter().getAnimation(this.currAnimation).setSpritesModified(this.currFrame, true); BufferedImage replaceImg = ImageIO.read(file); if (this.imagePanel.isFacedRight()) { replaceImg = ImagePanel.flipImage(replaceImg); } replaceImg = this.processReplaceImg(replaceImg); if (this.lastcX == -1) { this.lastcX = (int)((double)replaceImg.getWidth() * 0.5); this.lastcY = (int)((double)replaceImg.getHeight() * 0.95); } int cx = this.lastcX; int cy = this.lastcY; this.replaceSprite(replaceImg, this.currAnimation, this.currFrame, cx, cy); this.wasFrameReplaced = true; try { this.manager.bufferAnimFrame(this.currAnimation, this.currFrame); } catch (IOException ex) { ex.printStackTrace(); this.showError("Unable to save the generated sprite"); } this.dragImageRadio.setEnabled(false); this.hardRefresh(); } catch (IOException ex) { ex.printStackTrace(); this.showError("Unable to read image file: " + file.getName()); } } }//GEN-LAST:event_hardReplaceButtonActionPerformed private void pencilRadioActionPerformed(ActionEvent evt) {//GEN-FIRST:event_pencilRadioActionPerformed this.setRadiosOff(); this.pencilRadio.setSelected(true); this.imagePanel.setMode(Mode.pencil); }//GEN-LAST:event_pencilRadioActionPerformed private void brushRadioActionPerformed(ActionEvent evt) {//GEN-FIRST:event_brushRadioActionPerformed this.setRadiosOff(); this.brushRadio.setSelected(true); this.imagePanel.setMode(Mode.brush); }//GEN-LAST:event_brushRadioActionPerformed private void bucketRadioActionPerformed(ActionEvent evt) {//GEN-FIRST:event_bucketRadioActionPerformed this.setRadiosOff(); this.bucketRadio.setSelected(true); this.imagePanel.setMode(Mode.bucket); }//GEN-LAST:event_bucketRadioActionPerformed private void dragSpriteRadioActionPerformed(ActionEvent evt) {//GEN-FIRST:event_dragSpriteRadioActionPerformed this.setRadiosOff(); this.dragSpriteRadio.setSelected(true); this.imagePanel.setMode(Mode.dragSprite); }//GEN-LAST:event_dragSpriteRadioActionPerformed private void dragImageRadioActionPerformed(ActionEvent evt) {//GEN-FIRST:event_dragImageRadioActionPerformed this.setRadiosOff(); this.dragImageRadio.setSelected(true); this.imagePanel.setMode(Mode.dragImage); }//GEN-LAST:event_dragImageRadioActionPerformed private void noneRadioActionPerformed(ActionEvent evt) {//GEN-FIRST:event_noneRadioActionPerformed this.setRadiosOff(); this.noneRadio.setSelected(true); this.imagePanel.setMode(Mode.none); }//GEN-LAST:event_noneRadioActionPerformed private void sizeRadioMenu1ActionPerformed(ActionEvent evt) {//GEN-FIRST:event_sizeRadioMenu1ActionPerformed this.setSizeRadioMenusOff(); this.sizeRadioMenu1.setSelected(true); this.imagePanel.setBrushSize(3); }//GEN-LAST:event_sizeRadioMenu1ActionPerformed private void sizeRadioMenu2ActionPerformed(ActionEvent evt) {//GEN-FIRST:event_sizeRadioMenu2ActionPerformed this.setSizeRadioMenusOff(); this.sizeRadioMenu2.setSelected(true); this.imagePanel.setBrushSize(5); }//GEN-LAST:event_sizeRadioMenu2ActionPerformed private void sizeRadioMenu3ActionPerformed(ActionEvent evt) {//GEN-FIRST:event_sizeRadioMenu3ActionPerformed this.setSizeRadioMenusOff(); this.sizeRadioMenu3.setSelected(true); this.imagePanel.setBrushSize(10); }//GEN-LAST:event_sizeRadioMenu3ActionPerformed private void bucketMenuActionPerformed(ActionEvent evt) {//GEN-FIRST:event_bucketMenuActionPerformed this.bucketRadioActionPerformed(null); }//GEN-LAST:event_bucketMenuActionPerformed private void pencilMenuActionPerformed(ActionEvent evt) {//GEN-FIRST:event_pencilMenuActionPerformed this.pencilRadioActionPerformed(null); }//GEN-LAST:event_pencilMenuActionPerformed private void brushMenuActionPerformed(ActionEvent evt) {//GEN-FIRST:event_brushMenuActionPerformed this.brushRadioActionPerformed(null); }//GEN-LAST:event_brushMenuActionPerformed private void dragSpriteMenuActionPerformed(ActionEvent evt) {//GEN-FIRST:event_dragSpriteMenuActionPerformed this.dragSpriteRadioActionPerformed(null); }//GEN-LAST:event_dragSpriteMenuActionPerformed private void dragImageMenuActionPerformed(ActionEvent evt) {//GEN-FIRST:event_dragImageMenuActionPerformed this.dragImageRadioActionPerformed(null); }//GEN-LAST:event_dragImageMenuActionPerformed private void noneMenuActionPerformed(ActionEvent evt) {//GEN-FIRST:event_noneMenuActionPerformed this.noneRadioActionPerformed(null); }//GEN-LAST:event_noneMenuActionPerformed private void showWeaponCheckActionPerformed(ActionEvent evt) {//GEN-FIRST:event_showWeaponCheckActionPerformed this.weaponCombo.setEnabled(this.showWeaponCheck.isSelected()); this.imagePanel.showWeapon(this.showWeaponCheck.isSelected()); }//GEN-LAST:event_showWeaponCheckActionPerformed private void weaponCheckActionPerformed(ActionEvent evt) {//GEN-FIRST:event_weaponCheckActionPerformed Character ch = this.manager.getCharacter(); WeaponFrame frame = ch.getWeaponFrame(this.currAnimation, this.currFrame); boolean selected = this.weaponCheck.isSelected(); if (frame.isEnabled() != selected) { frame.setEnabled(selected); ch.setModified(true); this.refresh(); } }//GEN-LAST:event_weaponCheckActionPerformed private void weaponComboActionPerformed(ActionEvent evt) {//GEN-FIRST:event_weaponComboActionPerformed this.imagePanel.setWeaponPreview(this.weaponCombo.getSelectedIndex()); }//GEN-LAST:event_weaponComboActionPerformed private void behindCheckActionPerformed(ActionEvent evt) {//GEN-FIRST:event_behindCheckActionPerformed Character ch = this.manager.getCharacter(); WeaponFrame frame = ch.getWeaponFrame(this.currAnimation, this.currFrame); boolean selected = this.behindCheck.isSelected(); if (frame.showBehind != selected) { frame.showBehind = selected; ch.setModified(true); this.refresh(); } }//GEN-LAST:event_behindCheckActionPerformed private void jMenuItem6ActionPerformed(ActionEvent evt) {//GEN-FIRST:event_jMenuItem6ActionPerformed JOptionPane.showMessageDialog(this, "Pancake 2 v1.6b\n\u00a9 Gil Costa 2012\n\nAcknowledgment on derived work\nwould be appreciated but is not required\n\nPk2 is free software. The author can not be held responsible\nfor any illicit use of this program.\n", "About", 1); }//GEN-LAST:event_jMenuItem6ActionPerformed private void spriteSheetMenuActionPerformed(ActionEvent evt) {//GEN-FIRST:event_spriteSheetMenuActionPerformed this.exportSpriteSheet(); }//GEN-LAST:event_spriteSheetMenuActionPerformed private void showFacedRightCheckActionPerformed(ActionEvent evt) {//GEN-FIRST:event_showFacedRightCheckActionPerformed this.imagePanel.setFacedRight(this.showFacedRightCheck.isSelected()); }//GEN-LAST:event_showFacedRightCheckActionPerformed private void jMenuItem1ActionPerformed(ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed BufferedImage replaceImg; int charId = this.manager.getCurrentCharacterId(); String charName = this.guide.getCharName(this.guide.getFakeCharId(charId)); int returnVal = this.imageChooser.showOpenDialog(this); if (returnVal == 0) { File file = this.imageChooser.getSelectedFile(); try { replaceImg = ImageIO.read(file); replaceImg = this.processReplaceImg(replaceImg); } catch (IOException e) { e.printStackTrace(); this.showError("Unable to read image " + file.getName()); return; } } else { return; } JTextField columnsField = new JTextField(); JTextField rowsField = new JTextField(); JTextField cxField = new JTextField(); JTextField cyField = new JTextField(); JComponent[] inputs = new JComponent[]{new JLabel("Number of columns:"), columnsField, new JLabel("Number of rows:"), rowsField, new JLabel("Sprite center X:"), cxField, new JLabel("Sprite center Y:"), cyField}; int res = JOptionPane.showConfirmDialog(null, inputs, charName + "art replacer", 2); if (res != 0) { return; } int columns = this.getIntFromField(columnsField, 1, 9999); int rows = this.getIntFromField(rowsField, 1, 9999); int cx = this.getIntFromField(cxField, 0, 256); int cy = this.getIntFromField(cyField, 0, 256); if (columns == Integer.MIN_VALUE || rows == Integer.MIN_VALUE || cx == Integer.MIN_VALUE || cy == Integer.MIN_VALUE) { this.showError("Invalid columns/rows/center"); return; } if (this.timer.isRunning()) { this.playToggleActionPerformed(null); } this.importSpriteReplacer(replaceImg, columns, rows, cx, cy); }//GEN-LAST:event_jMenuItem1ActionPerformed private void jMenuItem2ActionPerformed(ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed BufferedImage replaceImg; int charId = this.manager.getCurrentCharacterId(); String charName = this.guide.getCharName(this.guide.getFakeCharId(charId)); int returnVal = this.imageChooser.showOpenDialog(this); if (returnVal == 0) { File file = this.imageChooser.getSelectedFile(); try { replaceImg = ImageIO.read(file); replaceImg = this.processReplaceImg(replaceImg); } catch (IOException e) { e.printStackTrace(); this.showError("Unable to read image " + file.getName()); return; } } else { return; } JTextField columnsField = new JTextField(); JTextField rowsField = new JTextField(); JTextField cxField = new JTextField(); JTextField cyField = new JTextField(); JComponent[] inputs = new JComponent[]{new JLabel("Number of columns:"), columnsField, new JLabel("Number of rows:"), rowsField, new JLabel("Sprite center X:"), cxField, new JLabel("Sprite center Y:"), cyField}; int res = JOptionPane.showConfirmDialog(null, inputs, charName + "art replacer", 2); if (res != 0) { return; } int columns = this.getIntFromField(columnsField, 1, 9999); int rows = this.getIntFromField(rowsField, 1, 9999); int cx = this.getIntFromField(cxField, 0, 256); int cy = this.getIntFromField(cyField, 0, 256); if (columns == Integer.MIN_VALUE || rows == Integer.MIN_VALUE || cx == Integer.MIN_VALUE || cy == Integer.MIN_VALUE) { this.showError("Invalid columns/rows/center"); return; } if (this.timer.isRunning()) { this.playToggleActionPerformed(null); } this.importSpriteGenerator(replaceImg, columns, rows, cx, cy); }//GEN-LAST:event_jMenuItem2ActionPerformed private void nameMenuActionPerformed(ActionEvent evt) {//GEN-FIRST:event_nameMenuActionPerformed new PropertiesDialog(this, this.manager).setVisible(true); }//GEN-LAST:event_nameMenuActionPerformed public BufferedImage openImageForPortrait() { int returnVal = this.imageChooser.showOpenDialog(this); if (returnVal == 0) { BufferedImage img; File file = this.imageChooser.getSelectedFile(); try { img = ImageIO.read(file); img = this.processReplaceImg(img, false); } catch (IOException ex) { ex.printStackTrace(); this.showError("Unable to read image file: " + file.getName()); return null; } if (img.getWidth() < 16 || img.getHeight() < 16) { this.showError("Image too small"); return null; } return img; } return null; } private void copyMenuActionPerformed(ActionEvent evt) {//GEN-FIRST:event_copyMenuActionPerformed this.copiedMap = this.getHexFromField(this.mapField); this.copiedArt = this.getHexFromField(this.artField); this.copiedHasHit = this.hitCheck.isSelected(); this.copiedKnockDown = this.koCheck.isSelected(); this.copiedHasWeapon = this.weaponCheck.isSelected(); this.copiedWpShowBehind = this.behindCheck.isSelected(); this.copiedHitX = this.getIntFromField(this.xField); this.copiedHitY = this.getIntFromField(this.yField); this.copiedHitSound = this.getIntFromField(this.soundField); this.copiedHitDamage = this.getIntFromField(this.damageField); this.copiedWpX = this.getIntFromField(this.wXField); this.copiedWpY = this.getIntFromField(this.wYField); this.copiedWpRotation = this.getIntFromField(this.angleField); this.pasteMenu.setEnabled(true); }//GEN-LAST:event_copyMenuActionPerformed private void pasteMenuActionPerformed(ActionEvent evt) {//GEN-FIRST:event_pasteMenuActionPerformed this.setFieldAsHex(this.mapField, this.copiedMap); this.mapAddressChanged(); this.setFieldAsHex(this.artField, this.copiedArt); this.artAddressChanged(); if (this.hitCheck.isEnabled()) { this.hitCheck.setSelected(this.copiedHasHit); this.hitCheckActionPerformed(null); this.koCheck.setSelected(this.copiedKnockDown); this.koCheckActionPerformed(null); this.setField(this.xField, this.copiedHitX); this.hitXChanged(); this.setField(this.yField, this.copiedHitY); this.hitYChanged(); this.setField(this.soundField, this.copiedHitSound); this.hitSoundChanged(); this.setField(this.damageField, this.copiedHitDamage); this.hitDamageChanged(); } if (this.weaponCheck.isEnabled()) { this.weaponCheck.setSelected(this.copiedHasWeapon); this.weaponCheckActionPerformed(null); this.behindCheck.setSelected(this.copiedWpShowBehind); this.behindCheckActionPerformed(null); this.setField(this.wXField, this.copiedWpX); this.weaponXChanged(); this.setField(this.wYField, this.copiedWpY); this.weaponYChanged(); this.setField(this.angleField, this.copiedWpRotation); this.weaponAngleChanged(); } }//GEN-LAST:event_pasteMenuActionPerformed private void spriteSheetMenu1ActionPerformed(ActionEvent evt) {//GEN-FIRST:event_spriteSheetMenu1ActionPerformed this.exportIndividualFrames(); }//GEN-LAST:event_spriteSheetMenu1ActionPerformed private void resizeAnimsMenuActionPerformed(ActionEvent evt) {//GEN-FIRST:event_resizeAnimsMenuActionPerformed Scanner sc; int charId = this.manager.getCurrentCharacterId(); Character c = this.manager.getCharacter(); HashSet<Animation> processed = new HashSet<Animation>(); int totalFrames = 0; for (int i = 0; i < c.getNumAnimations(); ++i) { Animation anim = c.getAnimation(i); if (processed.contains(anim)) continue; totalFrames += anim.getMaxNumFrames(); processed.add(anim); } int returnVal = this.resizerChooser.showOpenDialog(this); if (returnVal != 0) { return; } File file = this.resizerChooser.getSelectedFile(); try { sc = new Scanner(file); } catch (Exception e) { e.printStackTrace(); this.showError("Unable to open file " + file.getName()); return; } ArrayList<Integer> sizes = new ArrayList<Integer>(c.getNumAnimations()); ArrayList<Integer> wps = new ArrayList<Integer>(c.getNumAnimations()); ArrayList<Boolean> hit = new ArrayList<Boolean>(c.getNumAnimations() - 24); int totalProvided = 0; int totalHits = 0; int totalWps = 0; while (sc.hasNext()) { try { int s = sc.nextInt(); sizes.add(s); int hasWp = sc.nextInt(); wps.add(hasWp); boolean hasHit = false; if (sizes.size() - 1 >= 24) { if (hasWp < 2) { hasHit = sc.nextInt() != 0; } hit.add(hasHit); } if (s > 0) { totalProvided += s; if (hasWp == 1) { totalWps += s; } if (!hasHit) continue; totalHits += s; continue; } if (s >= 0) continue; } catch (Exception e) { this.showError("Invalid size values"); e.printStackTrace(); return; } } int numAnims = c.getNumAnimations(); int numHits = c.getHitsSize(); int numWeapons = c.getWeaponsSize(); System.out.println("" + totalProvided + "-" + totalFrames + ", " + totalHits + "-" + numHits + ", " + totalWps + "-" + numWeapons); boolean hasGlobalColl = this.manager.hasGlobalCollision(); boolean hasGlobalWeap = this.manager.hasGlobalWeapons(); if (sizes.isEmpty()) { this.showError("Empty input"); return; } if (sizes.size() != numAnims) { this.showError("Number of animations mismatch, \nGot " + sizes.size() + ", expected " + numAnims); return; } if (totalProvided > totalFrames && !hasGlobalColl && !hasGlobalWeap) { this.showError("Total number of frames exceeds the available space\nGot " + totalProvided + ", max allowed " + totalFrames); return; } if (totalHits > numHits && !hasGlobalColl) { this.showError("Total number of frames with collision exceeds the available space\nGot " + totalHits + ", max allowed " + numHits); return; } if (totalWps > numWeapons && !hasGlobalWeap) { this.showError("Total number of frames with weapons exceeds the available space\nGot " + totalWps + ", max allowed " + numWeapons); return; } if (this.timer.isRunning()) { this.playToggleActionPerformed(null); } this.resizeAnimations(sizes, wps, hit, totalProvided > totalFrames, totalHits > numHits, totalWps > numWeapons); }//GEN-LAST:event_resizeAnimsMenuActionPerformed private void characterComboKeyPressed(KeyEvent evt) {//GEN-FIRST:event_characterComboKeyPressed switch (evt.getKeyCode()) { case 81: { this.setPreviousAnimation(); break; } case 65: { this.setNextAnimation(); } } }//GEN-LAST:event_characterComboKeyPressed private void pasteMenu1ActionPerformed(ActionEvent evt) {//GEN-FIRST:event_pasteMenu1ActionPerformed JTextField field = new JTextField(); field.setText("0"); JTextField nameField = new JTextField(); nameField.setText("decompressed.bin"); JComponent[] inputs = new JComponent[]{new JLabel("Compressed art address:"), field, new JLabel("Output filename:"), nameField}; int res = JOptionPane.showConfirmDialog(null, inputs, "Decompress SOR2 art", 2); if (res == 0) { long address = this.getHexFromField(field); if (address == Long.MIN_VALUE) { this.showError("Invalid address"); return; } String fileName = nameField.getText(); try { FileOutputStream fos = new FileOutputStream(fileName); } catch (Exception e) { this.showError("Unable to save to file \"" + fileName + "\""); return; } try { this.manager.decompressArt(fileName, address); } catch (IOException e) { e.printStackTrace(); this.showError("Invalid data"); return; } Toolkit.getDefaultToolkit().beep(); } }//GEN-LAST:event_pasteMenu1ActionPerformed private void jMenuItem3ActionPerformed(ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed this.portRom(); this.hardRefresh(); JOptionPane.showMessageDialog(this, "Character sucessfully imported", "Done!", 1); }//GEN-LAST:event_jMenuItem3ActionPerformed private void hexIdsMenuActionPerformed(ActionEvent evt) {//GEN-FIRST:event_hexIdsMenuActionPerformed this.setupCharacterCombo(); this.setupAnimationCombo(); }//GEN-LAST:event_hexIdsMenuActionPerformed private void setSizeRadioMenusOff() { this.sizeRadioMenu1.setSelected(false); this.sizeRadioMenu2.setSelected(false); this.sizeRadioMenu3.setSelected(false); } public static void main(String[] args) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { // empty catch block } EventQueue.invokeLater(new Runnable(){ @Override public void run() { new Gui(); } }); } @Override public void actionPerformed(ActionEvent e) { if (this.guide == null || this.manager == null || this.currAnimation < 0) { return; } Character ch = this.manager.getCharacter(); AnimFrame animFrame = ch.getAnimFrame(this.currAnimation, this.currFrame); if (this.frameDelayCount++ >= animFrame.delay) { this.frameDelayCount = 0; this.setNextFrame(); } } @Override public void hitPositionChanged(int newX, int newY) { if (this.imagePanel.isFacedRight()) { newX *= -1; } if (newX < -127) { newX = -127; } if (newX > 127) { newX = 127; } if (newY < -127) { newY = -127; } if (newY > 127) { newY = 127; } this.setField(this.xField, newX); this.hitXChanged(); this.setField(this.yField, newY); this.hitYChanged(); } private void colorPanelPressed(int id) { JPanel panel = this.colorPanels[id]; if (id == 0) { this.imagePanel.setColor(null); } else { this.imagePanel.setColor(panel.getBackground()); } this.colorPanels[this.selectedColor].setBorder(null); this.selectedColor = id; this.colorPanels[this.selectedColor].setBorder(this.selectionBorder); } @Override public void artChanged() { this.manager.getCharacter().setModified(true); this.updateTitle(); } private int findTransparency(BufferedImage img) { Integer count; int y; int val; int x; TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>(); for (x = 0; x < img.getWidth(); ++x) { val = img.getRGB(x, 0); if ((val >> 24 & 255) == 0) { return val; } count = (Integer)map.get(val); if (count == null) { count = 0; } map.put(val, count + 1); } for (x = 0; x < img.getWidth(); ++x) { val = img.getRGB(x, img.getHeight() - 1); if ((val >> 24 & 255) == 0) { return val; } count = (Integer)map.get(val); if (count == null) { count = 0; } map.put(val, count + 1); } for (y = 0; y < img.getHeight(); ++y) { val = img.getRGB(0, y); if ((val >> 24 & 255) == 0) { return val; } count = (Integer)map.get(val); if (count == null) { count = 0; } map.put(val, count + 1); } for (y = 0; y < img.getHeight(); ++y) { val = img.getRGB(img.getWidth() - 1, y); if ((val >> 24 & 255) == 0) { return val; } count = (Integer)map.get(val); if (count == null) { count = 0; } map.put(val, count + 1); } int maxCount = 0; int moda = 0; for (Map.Entry entry : map.entrySet()) { if ((Integer)entry.getValue() <= maxCount) continue; moda = (Integer)entry.getKey(); maxCount = (Integer)entry.getValue(); } return moda; } private BufferedImage processReplaceImg(BufferedImage replaceImg) { return this.processReplaceImg(replaceImg, true); } private BufferedImage processReplaceImg(BufferedImage replaceImg, boolean transp) { Palette palette = this.manager.getPalette(); BufferedImage res = new BufferedImage(replaceImg.getWidth(), replaceImg.getHeight(), 2); int transparency = 0; if (transp) { transparency = this.findTransparency(replaceImg); } for (int x = 0; x < replaceImg.getWidth(); ++x) { for (int y = 0; y < replaceImg.getHeight(); ++y) { int val = replaceImg.getRGB(x, y); Color c = new Color(val); if (val == transparency || (val >> 24 & 255) == 0) continue; float[] hsb = Color.RGBtoHSB(c.getRed(), c.getGreen(), c.getBlue(), null); c = this.nearestColor(hsb, palette); res.setRGB(x, y, c.getRGB()); } } return res; } private Color nearestColor(float[] hsb, Palette palette) { float hx = 0.4f; float sx = 0.3f; float bx = 0.3f; float bestDist = Float.MAX_VALUE; int index = 0; for (int i = 15; i > 0; --i) { Color p = new Color(palette.getColor(i)); float[] phsb = Color.RGBtoHSB(p.getRed(), p.getGreen(), p.getBlue(), null); float dist = (float)Math.sqrt(Math.pow(hsb[0] - phsb[0], 2.0) + Math.pow(hsb[1] - phsb[1], 2.0) + Math.pow(hsb[2] - phsb[2], 2.0)); if (dist >= bestDist) continue; index = i; bestDist = dist; } return new Color(palette.getColor(index)); } private boolean isTile(BufferedImage img, int xi, int yi) { xi *= 8; yi *= 8; for (int i = 0; i < 8; ++i) { int y; int x = xi + i; if (x >= img.getWidth()) continue; for (int j = 0; j < 8 && (y = yi + j) < img.getHeight(); ++j) { int val = img.getRGB(x, y); if ((val >> 24 & 255) == 0) continue; return true; } } return false; } private void updateGenAddress() { try { long mapAddress = this.manager.romSize(); this.setFieldAsHex(this.genAddressField, mapAddress); } catch (IOException ex) { ex.printStackTrace(); } } private Piece optimizedPiece1(boolean[][] mx, boolean[][] done, int xi, int yi) { int j; int x; if (done[xi][yi]) { return null; } int sum = 0; int lx = 0; int ly = 0; int maxX = Math.min(4, 32 - xi); int maxY = Math.min(4, 32 - yi); block0 : for (int i = 0; i < maxX && mx[x = xi + i][0] && !done[x][0]; ++i) { for (j = 0; j < maxY; ++j) { int y = yi + j; if (!mx[x][y] || done[x][y]) { maxY = j; continue block0; } int locSum = i * j; if (locSum <= sum) continue; sum = locSum; lx = i; ly = j; } } Piece piece = new Piece(lx + 1, ly + 1); for (int i = 0; i < lx + 1; ++i) { for (j = 0; j < lx + 1; ++j) { done[xi + i][yi + j] = true; piece.setTile(i, j, new Tile()); } } return piece; } private boolean check(boolean[][] mx, int x, int y, int width, int height) { if (x + width > 32) { return false; } if (y + height > 32) { return false; } for (int i = 0; i < width; ++i) { for (int j = 0; j < height; ++j) { if (mx[x + i][y + j]) continue; return false; } } return true; } private boolean optimizePieces(boolean[][] mx, Piece[][] res) { int bestX = 0; int bestY = 0; int bestWidth = 0; int bestHeight = 0; int size = 0; for (int x = 0; x < 32; ++x) { for (int y = 0; y < 32; ++y) { if (!this.check(mx, x, y, 1, 1)) continue; if (this.check(mx, x, y, 4, 4)) { bestX = x; bestY = y; bestWidth = 4; bestHeight = 4; size = bestWidth * bestHeight; break; } if (size >= 12) break; if (this.check(mx, x, y, 4, 3)) { bestX = x; bestY = y; bestWidth = 4; bestHeight = 3; size = bestWidth * bestHeight; continue; } if (this.check(mx, x, y, 3, 4)) { bestX = x; bestY = y; bestWidth = 3; bestHeight = 4; size = bestWidth * bestHeight; continue; } if (size >= 9) break; if (this.check(mx, x, y, 3, 3)) { bestX = x; bestY = y; bestWidth = 3; bestHeight = 3; size = bestWidth * bestHeight; continue; } if (size >= 8) break; if (this.check(mx, x, y, 4, 2)) { bestX = x; bestY = y; bestWidth = 4; bestHeight = 2; size = bestWidth * bestHeight; continue; } if (this.check(mx, x, y, 2, 4)) { bestX = x; bestY = y; bestWidth = 2; bestHeight = 4; size = bestWidth * bestHeight; continue; } if (size >= 6) break; if (this.check(mx, x, y, 3, 2)) { bestX = x; bestY = y; bestWidth = 3; bestHeight = 2; size = bestWidth * bestHeight; continue; } if (this.check(mx, x, y, 2, 3)) { bestX = x; bestY = y; bestWidth = 2; bestHeight = 3; size = bestWidth * bestHeight; continue; } if (size >= 4) break; if (this.check(mx, x, y, 4, 1)) { bestX = x; bestY = y; bestWidth = 4; bestHeight = 1; size = bestWidth * bestHeight; continue; } if (this.check(mx, x, y, 1, 4)) { bestX = x; bestY = y; bestWidth = 1; bestHeight = 4; size = bestWidth * bestHeight; continue; } if (this.check(mx, x, y, 2, 2)) { bestX = x; bestY = y; bestWidth = 2; bestHeight = 2; size = bestWidth * bestHeight; continue; } if (size >= 3) break; if (this.check(mx, x, y, 3, 1)) { bestX = x; bestY = y; bestWidth = 3; bestHeight = 1; size = bestWidth * bestHeight; continue; } if (this.check(mx, x, y, 1, 3)) { bestX = x; bestY = y; bestWidth = 1; bestHeight = 3; size = bestWidth * bestHeight; continue; } if (size >= 2) break; if (this.check(mx, x, y, 2, 1)) { bestX = x; bestY = y; bestWidth = 2; bestHeight = 1; size = bestWidth * bestHeight; continue; } if (this.check(mx, x, y, 1, 2)) { bestX = x; bestY = y; bestWidth = 1; bestHeight = 2; size = bestWidth * bestHeight; continue; } if (size >= 1) break; bestX = x; bestY = y; bestWidth = 1; bestHeight = 1; size = bestWidth * bestHeight; } if (size == 16) break; } if (size == 0) { return false; } Piece piece = new Piece(bestWidth, bestHeight); for (int i = 0; i < bestWidth; ++i) { for (int j = 0; j < bestHeight; ++j) { piece.setTile(i, j, new Tile()); mx[bestX + i][bestY + j] = false; } } res[bestX][bestY] = piece; return true; } private Piece[][] genPieces(boolean[][] mx) { Piece[][] res = new Piece[32][32]; while (this.optimizePieces(mx, res)) { } return res; } private int trunkLeft(BufferedImage img) { for (int x = 0; x < img.getWidth(); ++x) { for (int y = 0; y < img.getHeight(); ++y) { int rgbVal = img.getRGB(x, y); if ((rgbVal >> 24 & 255) == 0) continue; return x; } } return img.getWidth() - 1; } private int trunkRight(BufferedImage img) { for (int x = img.getWidth() - 1; x >= 0; --x) { for (int y = 0; y < img.getHeight(); ++y) { int rgbVal = img.getRGB(x, y); if ((rgbVal >> 24 & 255) == 0) continue; return x + 1; } } return 0; } private int trunkTop(BufferedImage img) { for (int y = 0; y < img.getHeight(); ++y) { for (int x = 0; x < img.getWidth(); ++x) { int rgbVal = img.getRGB(x, y); if ((rgbVal >> 24 & 255) == 0) continue; return y; } } return 0; } private int trunkBottom(BufferedImage img) { for (int y = img.getHeight() - 1; y >= 0; --y) { for (int x = 0; x < img.getWidth(); ++x) { int rgbVal = img.getRGB(x, y); if ((rgbVal >> 24 & 255) == 0) continue; return y + 1; } } return 0; } private long replaceSprite(BufferedImage img, int animId, int frameId, int cx, int cy) { int width = img.getWidth(); int height = img.getHeight(); AnimFrame frame = this.manager.getCharacter().getAnimFrame(animId, frameId); if (frame.type == 3) { return frame.mapAddress; } long mapAddress = this.getHexFromField(this.genAddressField); int paletteLine = this.getIntFromField(this.genPaletteField); if (paletteLine == Integer.MIN_VALUE || paletteLine < 0 || paletteLine > 3) { this.showError("Invalid palette line"); return Long.MIN_VALUE; } if (mapAddress == Long.MIN_VALUE || mapAddress < 0L) { this.showError("Invalid address"); this.updateGenAddress(); return Long.MIN_VALUE; } Sprite sprite = new Sprite(); int numTiles = 0; width = width % 8 == 0 ? (width /= 8) : width / 8 + 1; height = height % 8 == 0 ? (height /= 8) : height / 8 + 1; boolean[][] mx = new boolean[32][32]; for (int x = 0; x < width; ++x) { for (int y = 0; y < height; ++y) { if (!this.isTile(img, x, y)) continue; mx[x][y] = true; ++numTiles; } } sprite.setNumTiles(numTiles); Piece[][] pieces = this.genPieces(mx); int nextIndex = 0; for (int x = 0; x < 32; ++x) { for (int y = 0; y < 32; ++y) { Piece p = pieces[x][y]; if (pieces[x][y] == null) continue; SpritePiece sp = new SpritePiece(); sp.width = p.getWidth() - 1; sp.height = p.getHeight() - 1; sp.paletteLine = paletteLine; sp.priorityFlag = false; sp.yFliped = false; sp.xFliped = false; sp.spriteIndex = nextIndex; sp.y = y * 8 - cy; sp.xL = x * 8 - cx; sp.xR = - sp.xL - p.getWidth() * 8; nextIndex += p.getWidth() * p.getHeight(); sprite.addPiece(sp, p); } } long artAddress = mapAddress + 6L + sprite.getNumPieces() * 6L; frame.mapAddress = mapAddress; frame.artAddress = artAddress; try { this.manager.writeSprite(sprite, mapAddress, artAddress); } catch (IOException ex) { ex.printStackTrace(); this.showError("Unable to create the new sprite"); return Long.MIN_VALUE; } this.updateGenAddress(); BufferedImage extended = this.expandImage(img, cx, cy); Animation anim = this.manager.getCharacter().getAnimation(animId); anim.setImage(frameId, extended); try { this.manager.save(); } catch (IOException e) { e.printStackTrace(); this.showError("Unable to render the new sprite"); return Long.MIN_VALUE; } return mapAddress; } @Override public void modeChanged(Mode mode) { this.setRadiosOff(); switch (mode) { case pencil: { this.pencilRadio.setSelected(true); break; } case brush: { this.brushRadio.setSelected(true); break; } case bucket: { this.bucketRadio.setSelected(true); break; } case dragSprite: { this.dragSpriteRadio.setSelected(true); break; } case dragImage: { this.dragImageRadio.setSelected(true); break; } case none: { this.noneRadio.setSelected(true); } } } @Override public void spriteDragged(int deltaX, int deltaY) { if (this.imagePanel.isFacedRight()) { deltaX *= -1; } if (this.wasFrameReplaced) { this.lastcX -= deltaX; this.lastcY -= deltaY; } try { Sprite sprite = this.manager.readSprite(this.currAnimation, this.currFrame); AnimFrame frame = this.manager.getCharacter().getAnimFrame(this.currAnimation, this.currFrame); sprite.applyOffset(deltaX, deltaY); HitFrame hitFrame = this.manager.getCharacter().getHitFrame(this.currAnimation, this.currFrame); WeaponFrame weaponFrame = this.manager.getCharacter().getWeaponFrame(this.currAnimation, this.currFrame); if (hitFrame != null) { hitFrame.x -= deltaX / 2; hitFrame.y -= deltaY; } if (weaponFrame != null) { weaponFrame.x += deltaX; weaponFrame.y += deltaY; } this.manager.writeSpriteOnly(sprite, frame.mapAddress); this.manager.save(); this.manager.bufferAnimFrame(this.currAnimation, this.currFrame); } catch (IOException ex) { ex.printStackTrace(); this.showError("Unable to apply offset"); } this.setFrame(this.currFrame); } private void refresh() { this.verifyModifications(); this.setFrame(this.currFrame); } private void hardRefresh() { int frame = this.currFrame; try { this.setCharacter(this.manager.getCurrentCharacterId()); } catch (IOException ex) { ex.printStackTrace(); this.showError("Error loading character"); } this.setFrame(frame); } @Override public void weaponPositionChanged(int newX, int newY) { if (this.imagePanel.isFacedRight()) { newX *= -1; } if (newX < -127) { newX = -127; } if (newX > 127) { newX = 127; } if (newY < -127) { newY = -127; } if (newY > 127) { newY = 127; } this.setField(this.wXField, newX); this.weaponXChanged(); this.setField(this.wYField, newY); this.weaponYChanged(); } private BufferedImage expandImage(BufferedImage img, int cx, int cy) { BufferedImage extended = new BufferedImage(256, 256, 2); for (int i = 0; i < img.getWidth(); ++i) { for (int j = 0; j < img.getHeight(); ++j) { int x = i + 128 - cx; int y = j + 128 - cy; int rgbVal = img.getRGB(i, j); if ((rgbVal >> 24 & 255) == 0 || x <= 0 || x >= 256 || y <= 0 || y >= 256) continue; extended.setRGB(x, y, rgbVal); } } return extended; } private void importSpriteReplacer(final BufferedImage sheet, final int columns, int rows, final int cx, final int cy) { final Character ch = this.manager.getCharacter(); final int numAnims = ch.getNumAnimations(); final ProgressMonitor progressMonitor = new ProgressMonitor(this, "Importing spritesheet", "", 0, numAnims); progressMonitor.setMillisToDecideToPopup(50); progressMonitor.setMillisToPopup(100); final int frameWidth = sheet.getWidth() / columns; final int frameHeight = sheet.getHeight() / rows; final int maxId = columns * rows; new Thread(new Runnable(){ private void finish() { ch.setModified(true); ch.setSpritesModified(true); try { Gui.this.manager.save(); Gui.this.setCharacter(Gui.this.manager.getCurrentCharacterId()); } catch (IOException ex) { ex.printStackTrace(); Gui.this.showError("Unable to save the sprites"); } progressMonitor.setProgress(999999); Gui.this.setEnabled(true); Gui.this.requestFocus(); } @Override public void run() { Gui.this.setEnabled(false); int index = 0; TreeSet<Long> maps = new TreeSet<Long>(); HashSet<Animation> processed = new HashSet<Animation>(); for (int i = 0; i < numAnims; ++i) { Animation anim = ch.getAnimation(i); if (!processed.contains(anim)) { processed.add(anim); int animSize = anim.getNumFrames(); for (int j = 0; j < animSize; ++j) { long mapAddress = ch.getAnimFrame((int)i, (int)j).mapAddress; if (maps.contains(mapAddress)) continue; maps.add(mapAddress); int x = index % columns * frameWidth; int y = index / columns * frameHeight; BufferedImage img = sheet.getSubimage(x, y, frameWidth, frameHeight); if (Gui.this.imagePanel.isFacedRight()) { img = ImagePanel.flipImage(img); } img = Gui.this.expandImage(img, cx, cy); anim.setImage(j, img); anim.setSpritesModified(j, true); if (++index != maxId) continue; this.finish(); Toolkit.getDefaultToolkit().beep(); return; } } progressMonitor.setNote("processing animations: " + (int)((double)i * 1.0 / (double)numAnims * 100.0) + "%"); progressMonitor.setProgress(i); if (!progressMonitor.isCanceled()) continue; this.finish(); return; } this.finish(); Toolkit.getDefaultToolkit().beep(); } }).start(); } private void portRom() { int returnVal = this.guideChooser.showOpenDialog(this); Guide guide = null; if (returnVal == 0) { File file = this.guideChooser.getSelectedFile(); try { guide = new Guide(file.getAbsolutePath()); } catch (FileNotFoundException ex) { ex.printStackTrace(); this.showError("Guide file '" + file.getName() + "' not found"); } catch (Exception ex) { ex.printStackTrace(); this.showError("Unable to open guide '" + file.getName() + "'"); } } if (guide == null) { return; } String romName = null; Manager manager = null; returnVal = this.romChooser.showOpenDialog(this); if (returnVal == 0) { File file = this.romChooser.getSelectedFile(); romName = file.getAbsolutePath(); try { manager = new Manager(romName, guide); } catch (FileNotFoundException ex) { ex.printStackTrace(); this.showError("File '" + romName + "' not found"); } catch (IOException ex) { ex.printStackTrace(); this.showError("File '" + romName + "' is not a valid Streets of Rage 2 ROM"); } } if (manager == null) { return; } int charId = this.manager.getCurrentCharacterId(); int fakeId = guide.getFakeCharId(charId); try { manager.setCharacter(charId, guide.getAnimsCount(fakeId), guide.getType(fakeId)); } catch (IOException ex) { ex.printStackTrace(); this.showError("Unable to read character #" + charId); } try { this.manager.replaceCharacterFromManager(manager); } catch (IOException ex) { ex.printStackTrace(); this.showError("Unable to port character #" + charId); } } private void importSpriteGenerator(final BufferedImage sheet, final int columns, int rows, final int cx, final int cy) { final Character ch = this.manager.getCharacter(); final int numAnims = ch.getNumAnimations(); final ProgressMonitor progressMonitor = new ProgressMonitor(this, "Importing spritesheet", "", 0, numAnims); progressMonitor.setMillisToDecideToPopup(50); progressMonitor.setMillisToPopup(100); final int frameWidth = sheet.getWidth() / columns; final int frameHeight = sheet.getHeight() / rows; final int maxId = columns * rows; new Thread(new Runnable(){ private void finish() { ch.setModified(true); ch.setSpritesModified(true); Gui.this.hardRefresh(); progressMonitor.setProgress(999999); Gui.this.setEnabled(true); Gui.this.requestFocus(); } @Override public void run() { Gui.this.setEnabled(false); int index = 0; TreeMap<Long, AddressesPair> maps = new TreeMap<Long, AddressesPair>(); HashSet<Animation> processed = new HashSet<Animation>(); for (int i = 0; i < numAnims; ++i) { Animation anim = ch.getAnimation(i); if (!processed.contains(anim)) { processed.add(anim); int animSize = anim.getNumFrames(); for (int j = 0; j < animSize; ++j) { long newAddress; anim.setSpritesModified(j, true); long mapAddress = anim.getFrame((int)j).mapAddress; if (maps.containsKey(mapAddress)) { AddressesPair p = (AddressesPair)maps.get(mapAddress); anim.getFrame((int)j).mapAddress = p.a; anim.getFrame((int)j).artAddress = p.b; anim.setImage(j, p.img); continue; } int x = index % columns * frameWidth; int y = index / columns * frameHeight; BufferedImage img = sheet.getSubimage(x, y, frameWidth, frameHeight); if (Gui.this.imagePanel.isFacedRight()) { img = ImagePanel.flipImage(img); } if ((newAddress = Gui.this.replaceSprite(img, i, j, cx, cy)) == Long.MIN_VALUE) { this.finish(); Gui.this.showError("Unable to replace sprites"); return; } maps.put(mapAddress, new AddressesPair(anim.getFrame((int)j).mapAddress, anim.getFrame((int)j).artAddress, anim.getImage(j))); if (++index != maxId) continue; this.finish(); Toolkit.getDefaultToolkit().beep(); return; } } progressMonitor.setNote("processing animations: " + (int)((double)i * 1.0 / (double)numAnims * 100.0) + "%"); progressMonitor.setProgress(i); if (!progressMonitor.isCanceled()) continue; this.finish(); return; } this.finish(); Toolkit.getDefaultToolkit().beep(); } }).start(); } private void exportSpriteSheet() { this.exportSpriteSheet(false); } private void exportSpriteSheet(final boolean single) { final String charName = this.guide.getCharName(this.guide.getFakeCharId(this.manager.getCurrentCharacterId())); File tmpFile = null; if (!single) { this.imageSaver.setSelectedFile(new File(charName + ".png")); int returnOption = this.imageSaver.showSaveDialog(this); if (returnOption != 0) { return; } tmpFile = this.imageSaver.getSelectedFile(); if (tmpFile == null) { return; } } final File outputFile = tmpFile; final Character ch = this.manager.getCharacter(); final int numAnims = ch.getNumAnimations(); final ProgressMonitor progressMonitor = new ProgressMonitor(this, single ? "Exporting sprites" : "Exporting spritesheet", "", 0, numAnims * 2); progressMonitor.setMillisToDecideToPopup(50); progressMonitor.setMillisToPopup(100); new Thread(new Runnable(){ @Override public void run() { Gui.this.setEnabled(false); int left = Integer.MAX_VALUE; int right = Integer.MIN_VALUE; int top = Integer.MAX_VALUE; int bottom = Integer.MIN_VALUE; TreeSet<Long> maps = new TreeSet<Long>(); HashSet<Animation> processed = new HashSet<Animation>(); for (int i = 0; i < ch.getNumAnimations(); ++i) { Animation anim = ch.getAnimation(i); if (!processed.contains(anim)) { processed.add(anim); int animSize = anim.getNumFrames(); for (int j = 0; j < animSize; ++j) { Sprite sp; maps.add(manager.getCharacter().getAnimFrame((int)i, (int)j).mapAddress); try { sp = Gui.this.manager.readSprite(i, j); } catch (IOException ex) { ex.printStackTrace(); Gui.this.showError("Unable to access sprites"); progressMonitor.setProgress(999999); Gui.this.setEnabled(true); Gui.this.requestFocus(); return; } Rectangle rect = sp.getBounds(); if (rect.x < left) { left = rect.x; } if (rect.y < top) { top = rect.y; } int r = rect.x + rect.width; int b = rect.y + rect.height; if (r > right) { right = r; } if (b <= bottom) continue; bottom = b; } } if (progressMonitor.isCanceled()) { Gui.this.setEnabled(true); Gui.this.requestFocus(); return; } progressMonitor.setNote("Computing space: " + (int)((float)i * 1.0f / (float)numAnims * 100.0f) + "%"); progressMonitor.setProgress(i); } int numMaps = maps.size() + 1; int width = right - left; int height = bottom - top; int columns = (int)Math.sqrt(numMaps); int rows = numMaps / columns; if (numMaps % columns != 0) { ++rows; } BufferedImage res = null; Graphics2D g2d = null; if (!single) { res = new BufferedImage(columns * width, rows * height, 2); g2d = res.createGraphics(); } maps.clear(); processed.clear(); int index = 0; for (int i = 0; i < ch.getNumAnimations(); ++i) { Animation anim = ch.getAnimation(i); if (!processed.contains(anim)) { processed.add(anim); int animSize = anim.getNumFrames(); for (int j = 0; j < animSize; ++j) { long address = manager.getCharacter().getAnimFrame((int)i, (int)j).mapAddress; try { Gui.this.manager.bufferAnimation(i); } catch (IOException ex) { ex.printStackTrace(); Gui.this.showError("Unable to access sprites"); progressMonitor.setProgress(999999); Gui.this.setEnabled(true); Gui.this.requestFocus(); return; } if (maps.contains(address)) continue; maps.add(address); BufferedImage img = Gui.this.manager.getImage(i, j).getSubimage(left, top, width, height); if (single) { try { File outputFile2 = new File(Gui.this.currentDirectory + "/" + charName + " " + i + "." + j + ".png"); if (Gui.this.imagePanel.isFacedRight()) { img = ImagePanel.flipImage(img); } ImageIO.write((RenderedImage)img, "png", outputFile2); } catch (IOException ex) { ex.printStackTrace(); Gui.this.showError("Unable to save image"); progressMonitor.setProgress(999999); Gui.this.setEnabled(true); Gui.this.requestFocus(); return; } } else { int x = index % columns * width; int y = index / columns * height; if (Gui.this.imagePanel.isFacedRight()) { int w = img.getWidth(); int h = img.getHeight(); g2d.drawImage(img, x, y, x + w, y + h, w, 0, 0, h, null); } else { g2d.drawImage(img, x, y, null); } } ++index; } } progressMonitor.setNote("Rendering sprites: " + (int)((float)i * 1.0f / (float)numAnims * 100.0f) + "%"); progressMonitor.setProgress(numAnims + i); if (!progressMonitor.isCanceled()) continue; Gui.this.setEnabled(true); Gui.this.requestFocus(); return; } if (!single) { int x = index % columns * width; int y = index / columns * height; String cs = (columns / 10 == 0 ? " " : "") + (columns / 100 == 0 ? " " : ""); String watermark0a = "Columns: " + cs + columns; cs = (rows / 10 == 0 ? " " : "") + (rows / 100 == 0 ? " " : ""); String watermark0b = "Rows: " + cs + rows; cs = ((128 - left) / 10 == 0 ? " " : "") + ((128 - left) / 100 == 0 ? " " : ""); String watermark0c = "Center X: " + cs + (128 - left); cs = ((128 - top) / 10 == 0 ? " " : "") + ((128 - top) / 100 == 0 ? " " : ""); String watermark0d = "Center Y: " + cs + (128 - top); String watermark1 = "Generated by"; String watermark2 = Gui.TITLE; g2d.setColor(Color.red); g2d.setFont(new Font("Courier New", 0, 12)); g2d.drawChars(watermark0a.toCharArray(), 0, watermark0a.length(), x + 4, y + 0); g2d.drawChars(watermark0b.toCharArray(), 0, watermark0b.length(), x + 4, y + 10); g2d.drawChars(watermark0c.toCharArray(), 0, watermark0c.length(), x + 4, y + 20); g2d.drawChars(watermark0d.toCharArray(), 0, watermark0d.length(), x + 4, y + 30); g2d.drawChars(watermark1.toCharArray(), 0, watermark1.length(), x + 4, y + 45); g2d.drawChars(watermark2.toCharArray(), 0, watermark2.length(), x + 4, y + 55); Palette pal = Gui.this.manager.getPalette(); int rc = 12; for (int i = 0; i < 16; ++i) { int c = pal.getColor(i); g2d.setColor(new Color(c)); g2d.fillRect(x + 4 + i % 8 * rc, y + 60 + i / 8 * rc, rc, rc); } g2d.dispose(); try { ImageIO.write((RenderedImage)res, "png", outputFile); } catch (IOException ex) { ex.printStackTrace(); Gui.this.showError("Unable to save spritesheet"); progressMonitor.setProgress(999999); Gui.this.setEnabled(true); Gui.this.requestFocus(); return; } } progressMonitor.setProgress(999999); Gui.this.setEnabled(true); Gui.this.requestFocus(); Toolkit.getDefaultToolkit().beep(); } }).start(); } private void exportIndividualFrames() { this.exportSpriteSheet(true); } private void resizeAnimations(final ArrayList<Integer> sizes, final ArrayList<Integer> wps, final ArrayList<Boolean> hits, final boolean newArea, final boolean newHits, final boolean newWeapons) { final Character ch = this.manager.getCharacter(); final int numAnims = sizes.size(); final ProgressMonitor progressMonitor = new ProgressMonitor(this, "Generating resized animations", "", 0, numAnims + 1); progressMonitor.setMillisToDecideToPopup(50); progressMonitor.setMillisToPopup(100); new Thread(new Runnable(){ private void finish() { ch.setModified(true); Gui.this.hardRefresh(); progressMonitor.setProgress(999999); Gui.this.setEnabled(true); Gui.this.requestFocus(); } @Override public void run() { Gui.this.setEnabled(false); HashSet<Animation> processedAnims = new HashSet<Animation>(); for (int i = 0; i < numAnims; ++i) { int size = (Integer)sizes.get(i); int wp = (Integer)wps.get(i); boolean hit = false; if (i >= 24) { hit = (Boolean)hits.get(i - 24); } if (wp != 2) { if (size < 0) { ch.setAnim(i, - size - 1, wp == 1, hit); processedAnims.add(ch.getAnimation(i)); } else if (size > 0) { Animation anim = ch.getAnimation(i); if (processedAnims.contains(anim)) { ch.doubleAnim(i); } ch.resizeAnim(i, size, wp == 1, hit); } else { processedAnims.add(ch.getAnimation(i)); } } else { processedAnims.add(ch.getAnimation(i)); } processedAnims.add(ch.getAnimation(i)); progressMonitor.setNote("Resizing animations: " + (int)((double)i * 1.0 / (double)numAnims * 100.0) + "%"); progressMonitor.setProgress(i); if (!progressMonitor.isCanceled()) continue; this.finish(); return; } progressMonitor.setNote("Generating new scripts"); progressMonitor.setProgress(numAnims); long newAnimsAddress = 0L; if (newArea) { newAnimsAddress = Gui.this.getHexFromField(Gui.this.genAddressField); } try { Gui.this.manager.writeNewScripts(newAnimsAddress, newHits, newWeapons); } catch (IOException e) { this.finish(); e.printStackTrace(); Gui.this.showError("Failed to convert the animations script"); return; } Gui.this.updateGenAddress(); Gui.this.hardRefresh(); this.finish(); Toolkit.getDefaultToolkit().beep(); } }).start(); } private void uncompressChar(final int type) { final Character ch = this.manager.getCharacter(); final int numAnims = ch.getNumAnimations(); final ProgressMonitor progressMonitor = new ProgressMonitor(this, "Uncompressing Character", "", 0, numAnims + 1); progressMonitor.setMillisToDecideToPopup(50); progressMonitor.setMillisToPopup(100); new Thread(new Runnable(){ private void finish() { ch.setModified(true); ch.setSpritesModified(true); Gui.this.hardRefresh(); progressMonitor.setProgress(999999); Gui.this.setEnabled(true); Gui.this.requestFocus(); } @Override public void run() { Gui.this.setEnabled(false); int index = 0; long newAnimsAddress = Gui.this.getHexFromField(Gui.this.genAddressField); int animsSyzeInBytes = ch.getAnimsSize(type); Gui.this.setFieldAsHex(Gui.this.genAddressField, newAnimsAddress + (long)animsSyzeInBytes); TreeMap<Long, AddressesPair> maps = new TreeMap<Long, AddressesPair>(); for (int i = 0; i < numAnims; ++i) { Animation anim = ch.getAnimation(i); try { Gui.this.manager.bufferAnimation(i); } catch (IOException e) { this.finish(); e.printStackTrace(); Gui.this.showError("Failed to buffer animations"); return; } int animSize = anim.getNumFrames(); for (int j = 0; j < animSize; ++j) { anim.setSpritesModified(j, true); ch.setModified(true); ch.setSpritesModified(true); long mapAddress = anim.getFrame((int)j).mapAddress; if (maps.containsKey(mapAddress)) { AddressesPair p = (AddressesPair)maps.get(mapAddress); anim.getFrame((int)j).mapAddress = p.a; anim.getFrame((int)j).artAddress = p.b; anim.setImage(j, p.img); anim.setAnimType(type); continue; } BufferedImage img = anim.getImage(j); anim.setAnimType(type); long newAddress = Gui.this.replaceSprite(img, i, j, 128, 128); if (newAddress == Long.MIN_VALUE) { this.finish(); Gui.this.showError("Unable to replace the compressed sprites"); return; } maps.put(mapAddress, new AddressesPair(anim.getFrame((int)j).mapAddress, anim.getFrame((int)j).artAddress, anim.getImage(j))); ++index; } progressMonitor.setNote("Converting sprites: " + (int)((double)i * 1.0 / (double)numAnims * 100.0) + "%"); progressMonitor.setProgress(i); if (!progressMonitor.isCanceled()) continue; this.finish(); return; } progressMonitor.setNote("Converting animations script"); progressMonitor.setProgress(numAnims); try { Gui.this.manager.writeNewAnimations(newAnimsAddress); } catch (IOException e) { this.finish(); e.printStackTrace(); Gui.this.showError("Failed to convert the animations script"); return; } Gui.this.updateGenAddress(); Gui.this.guide.setAnimType(Gui.this.guide.getFakeCharId(Gui.this.manager.getCurrentCharacterId()), type); Gui.this.hardRefresh(); this.finish(); Toolkit.getDefaultToolkit().beep(); } }).start(); } class AddressesPair { public BufferedImage img; public long a; public long b; public AddressesPair(long a, long b, BufferedImage img) { this.a = a; this.b = b; this.img = img; } } }
package zorbage.type.data; import zorbage.type.algebra.Conjugate; import zorbage.type.algebra.Constants; import zorbage.type.algebra.Infinite; import zorbage.type.algebra.Norm; import zorbage.type.algebra.Rounding; import zorbage.type.algebra.SkewField; /** * * @author Barry DeZonia * */ //TODO: is it really a skewfield or something else? Multiplication is not associative public class OctonionFloat64SkewField implements SkewField<OctonionFloat64SkewField, OctonionFloat64Member>, Conjugate<OctonionFloat64Member>, Norm<OctonionFloat64Member,Float64Member>, Infinite<OctonionFloat64Member>, Rounding<OctonionFloat64Member>, Constants<OctonionFloat64Member> { private static final OctonionFloat64Member ZERO = new OctonionFloat64Member(0, 0, 0, 0, 0, 0, 0, 0); private static final OctonionFloat64Member ONE = new OctonionFloat64Member(1, 0, 0, 0, 0, 0, 0, 0); private static final OctonionFloat64Member PI = new OctonionFloat64Member(Math.PI, 0, 0, 0, 0, 0, 0, 0); private static final OctonionFloat64Member E = new OctonionFloat64Member(Math.E, 0, 0, 0, 0, 0, 0, 0); @Override public void unity(OctonionFloat64Member a) { assign(ONE, a); } @Override public void multiply(OctonionFloat64Member a, OctonionFloat64Member b, OctonionFloat64Member c) { OctonionFloat64Member tmp = new OctonionFloat64Member(ZERO); // r * r = r tmp.setR(a.r() * b.r()); // r * i = i tmp.setI(a.r() * b.i()); // r * j = j tmp.setJ(a.r() * b.j()); // r * k = k tmp.setK(a.r() * b.k()); // r * l = l tmp.setL(a.r() * b.l()); // r * i0 = i0 tmp.setI0(a.r() * b.i0()); // r * j0 = j0 tmp.setJ0(a.r() * b.j0()); // r * k0 = k0 tmp.setK0(a.r() * b.k0()); // i * r = i tmp.setI(tmp.i() + a.i() * b.r()); tmp.setR(tmp.r() - a.i() * b.i()); // i * j = k tmp.setK(tmp.k() + a.i() * b.j()); tmp.setJ(tmp.j() - a.i() * b.k()); // i * l = i0 tmp.setI0(tmp.i0() + a.i() * b.l()); tmp.setL(tmp.l() - a.i() * b.i0()); tmp.setK0(tmp.k0() - a.i() * b.j0()); // i * k0 = j0 tmp.setJ0(tmp.j0() + a.i() * b.k0()); // j * r = j tmp.setJ(tmp.j() + a.j() * b.r()); tmp.setK(tmp.k() - a.j() * b.i()); tmp.setR(tmp.r() - a.j() * b.j()); // j * k = i tmp.setI(tmp.i() + a.j() * b.k()); // j * l = j0 tmp.setJ0(tmp.j0() + a.j() * b.l()); // j * i0 = k0 tmp.setK0(tmp.k0() + a.j() * b.i0()); tmp.setL(tmp.l() - a.j() * b.j0()); // j * k0 = -i0 tmp.setI0(tmp.i0() - a.j() * b.k0()); // k * r = k tmp.setK(tmp.k() + a.k() * b.r()); // k * i = j tmp.setJ(tmp.j() + a.k() * b.i()); tmp.setI(tmp.i() - a.k() * b.j()); tmp.setR(tmp.r() - a.k() * b.k()); // k * l = k0 tmp.setK0(tmp.k0() + a.k() * b.l()); tmp.setJ0(tmp.j0() - a.k() * b.i0()); // k * j0 = i0 tmp.setI0(tmp.i0() + a.k() * b.j0()); tmp.setL(tmp.l() - a.k() * b.k0()); // l * r = l tmp.setL(tmp.l() + a.l() * b.r()); tmp.setI0(tmp.i0() - a.l() * b.i()); tmp.setJ0(tmp.j0() - a.l() * b.j()); tmp.setK0(tmp.k0() - a.l() * b.k()); tmp.setR(tmp.r() - a.l() * b.l()); // l * i0 = i tmp.setI(tmp.i() + a.l() * b.i0()); // l * j0 = j tmp.setJ(tmp.j() + a.l() * b.j0()); // l * k0 = k tmp.setK(tmp.k() + a.l() * b.k0()); // i0 * r = i0 tmp.setI0(tmp.i0() + a.i0() * b.r()); // i0 * i = l tmp.setL(tmp.l() + a.i0() * b.i()); tmp.setK0(tmp.k0() - a.i0() * b.j()); // i0 * k = j0 tmp.setJ0(tmp.j0() + a.i0() * b.k()); tmp.setI(tmp.i() - a.i0() * b.l()); tmp.setR(tmp.r() - a.i0() * b.i0()); tmp.setK(tmp.k() - a.i0() * b.j0()); // i0 * k0 = j tmp.setJ(tmp.j() + a.i0() * b.k0()); // j0 * r = j0 tmp.setJ0(tmp.j0() + a.j0() * b.r()); // j0 * i = k0 tmp.setK0(tmp.k0() + a.j0() * b.i()); // j0 * j = l tmp.setL(tmp.l() + a.j0() * b.j()); tmp.setI0(tmp.i0() - a.j0() * b.k()); tmp.setJ(tmp.j() - a.j0() * b.l()); // j0 * i0 = k tmp.setK(tmp.k() + a.j0() * b.i0()); tmp.setR(tmp.r() - a.j0() * b.j0()); tmp.setI(tmp.i() - a.j0() * b.k0()); // k0 * r = k0 tmp.setK0(tmp.k0() + a.k0() * b.r()); tmp.setJ0(tmp.j0() - a.k0() * b.i()); // k0 * j = i0 tmp.setI0(tmp.i0() + a.k0() * b.j()); // k0 * k = l tmp.setL(tmp.l() + a.k0() * b.k()); tmp.setK(tmp.k() - a.k0() * b.l()); tmp.setJ(tmp.j() - a.k0() * b.i0()); // k0 * j0 = i tmp.setI(tmp.i() + a.k0() * b.j0()); tmp.setR(tmp.r() - a.k0() * b.k0()); assign(tmp, c); } @Override public void power(int power, OctonionFloat64Member a, OctonionFloat64Member b) { // okay for power to be negative OctonionFloat64Member tmp = new OctonionFloat64Member(); assign(ONE,tmp); if (power > 0) { for (int i = 1; i <= power; i++) multiply(tmp,a,tmp); } else if (power < 0) { power = -power; for (int i = 1; i <= power; i++) divide(tmp,a,tmp); } assign(tmp, b); } @Override public void zero(OctonionFloat64Member a) { assign(ZERO, a); } // TODO: scale coeffs by -1 or multiply by (-1,0,0,0,0,0,0,0)? Same with Quats and Complexes. @Override public void negate(OctonionFloat64Member a, OctonionFloat64Member b) { subtract(ZERO, a, b); } @Override public void add(OctonionFloat64Member a, OctonionFloat64Member b, OctonionFloat64Member c) { c.setR( a.r() + b.r() ); c.setI( a.i() + b.i() ); c.setJ( a.j() + b.j() ); c.setK( a.k() + b.k() ); c.setL( a.l() + b.l() ); c.setI0( a.i0() + b.i0() ); c.setJ0( a.j0() + b.j0() ); c.setK0( a.k0() + b.k0() ); } @Override public void subtract(OctonionFloat64Member a, OctonionFloat64Member b, OctonionFloat64Member c) { c.setR( a.r() - b.r() ); c.setI( a.i() - b.i() ); c.setJ( a.j() - b.j() ); c.setK( a.k() - b.k() ); c.setL( a.l() - b.l() ); c.setI0( a.i0() - b.i0() ); c.setJ0( a.j0() - b.j0() ); c.setK0( a.k0() - b.k0() ); } @Override public boolean isEqual(OctonionFloat64Member a, OctonionFloat64Member b) { return a.r() == b.r() && a.i() == b.i() && a.j() == b.j() && a.k() == b.k() && a.l() == b.l() && a.i0() == b.i0() && a.j0() == b.j0() && a.k0() == b.k0(); } @Override public boolean isNotEqual(OctonionFloat64Member a, OctonionFloat64Member b) { return !isEqual(a,b); } @Override public OctonionFloat64Member construct() { return new OctonionFloat64Member(); } @Override public OctonionFloat64Member construct(OctonionFloat64Member other) { return new OctonionFloat64Member(other); } @Override public OctonionFloat64Member construct(String s) { return new OctonionFloat64Member(s); } @Override public void assign(OctonionFloat64Member from, OctonionFloat64Member to) { to.setR( from.r() ); to.setI( from.i() ); to.setJ( from.j() ); to.setK( from.k() ); to.setL( from.l() ); to.setI0( from.i0() ); to.setJ0( from.j0() ); to.setK0( from.k0() ); } @Override public void invert(OctonionFloat64Member a, OctonionFloat64Member b) { double norm2 = norm2(a); conjugate(a, b); b.setR( b.r() / norm2 ); b.setI( b.i() / norm2 ); b.setJ( b.j() / norm2 ); b.setK( b.k() / norm2 ); b.setL( b.l() / norm2 ); b.setI0( b.i0() / norm2 ); b.setJ0( b.j0() / norm2 ); b.setK0( b.k0() / norm2 ); } @Override public void divide(OctonionFloat64Member a, OctonionFloat64Member b, OctonionFloat64Member c) { OctonionFloat64Member tmp = new OctonionFloat64Member(); invert(b, tmp); multiply(a, tmp, c); } @Override public void roundTowardsZero(OctonionFloat64Member a, OctonionFloat64Member b) { if (a.r() < 0) b.setR( Math.ceil(a.r()) ); else b.setR( Math.floor(a.r()) ); if (a.i() < 0) b.setI( Math.ceil(a.i()) ); else b.setI( Math.floor(a.i()) ); if (a.j() < 0) b.setJ( Math.ceil(a.j()) ); else b.setJ( Math.floor(a.j()) ); if (a.k() < 0) b.setK( Math.ceil(a.k()) ); else b.setK( Math.floor(a.k()) ); if (a.l() < 0) b.setL( Math.ceil(a.l()) ); else b.setL( Math.floor(a.l()) ); if (a.i0() < 0) b.setI0( Math.ceil(a.i0()) ); else b.setI0( Math.floor(a.i0()) ); if (a.j0() < 0) b.setJ0( Math.ceil(a.j0()) ); else b.setJ0( Math.floor(a.j0()) ); if (a.k0() < 0) b.setK0( Math.ceil(a.k0()) ); else b.setK0( Math.floor(a.k0()) ); } @Override public void roundAwayFromZero(OctonionFloat64Member a, OctonionFloat64Member b) { if (a.r() > 0) b.setR( Math.ceil(a.r()) ); else b.setR( Math.floor(a.r()) ); if (a.i() > 0) b.setI( Math.ceil(a.i()) ); else b.setI( Math.floor(a.i()) ); if (a.j() > 0) b.setJ( Math.ceil(a.j()) ); else b.setJ( Math.floor(a.j()) ); if (a.k() > 0) b.setK( Math.ceil(a.k()) ); else b.setK( Math.floor(a.k()) ); if (a.l() > 0) b.setL( Math.ceil(a.l()) ); else b.setL( Math.floor(a.l()) ); if (a.i0() > 0) b.setI0( Math.ceil(a.i0()) ); else b.setI0( Math.floor(a.i0()) ); if (a.j0() > 0) b.setJ0( Math.ceil(a.j0()) ); else b.setJ0( Math.floor(a.j0()) ); if (a.k0() > 0) b.setK0( Math.ceil(a.k0()) ); else b.setK0( Math.floor(a.k0()) ); } @Override public void roundPositive(OctonionFloat64Member a, OctonionFloat64Member b) { b.setR( Math.ceil(a.r()) ); b.setI( Math.ceil(a.i()) ); b.setJ( Math.ceil(a.j()) ); b.setK( Math.ceil(a.k()) ); b.setL( Math.ceil(a.l()) ); b.setI0( Math.ceil(a.i0()) ); b.setJ0( Math.ceil(a.j0()) ); b.setK0( Math.ceil(a.k0()) ); } @Override public void roundNegative(OctonionFloat64Member a, OctonionFloat64Member b) { b.setR( Math.floor(a.r()) ); b.setI( Math.floor(a.i()) ); b.setJ( Math.floor(a.j()) ); b.setK( Math.floor(a.k()) ); b.setL( Math.floor(a.l()) ); b.setI0( Math.floor(a.i0()) ); b.setJ0( Math.floor(a.j0()) ); b.setK0( Math.floor(a.k0()) ); } @Override public void roundNearest(OctonionFloat64Member a, OctonionFloat64Member b) { b.setR( Math.rint(a.r()) ); b.setI( Math.rint(a.i()) ); b.setJ( Math.rint(a.j()) ); b.setK( Math.rint(a.k()) ); b.setL( Math.rint(a.l()) ); b.setI0( Math.rint(a.i0()) ); b.setJ0( Math.rint(a.j0()) ); b.setK0( Math.rint(a.k0()) ); } @Override public boolean isNaN(OctonionFloat64Member a) { return Double.isNaN(a.r()) || Double.isNaN(a.i()) || Double.isNaN(a.j()) || Double.isNaN(a.k()) || Double.isNaN(a.l()) || Double.isNaN(a.i0()) || Double.isNaN(a.j0()) || Double.isNaN(a.k0()); } @Override public boolean isInfinite(OctonionFloat64Member a) { return !isNaN(a) && ( Double.isInfinite(a.r()) || Double.isInfinite(a.i()) || Double.isInfinite(a.j()) || Double.isInfinite(a.k()) || Double.isInfinite(a.l()) || Double.isInfinite(a.i0()) || Double.isInfinite(a.j0()) || Double.isInfinite(a.k0()) ); } // TODO need generalized and accurate hypot() method for quats and octs @Override public void norm(OctonionFloat64Member a, Float64Member b) { b.setV( norm2(a) ); } private double norm2(OctonionFloat64Member a) { return a.r()*a.r() + a.i()*a.i() + a.j()*a.j() + a.k()*a.k() + a.l()*a.l() + a.i0()*a.i0() + a.j0()*a.j0() + a.k0()*a.k0(); } @Override public void conjugate(OctonionFloat64Member a, OctonionFloat64Member b) { b.setR(a.r()); b.setI(-a.i()); b.setJ(-a.j()); b.setK(-a.k()); b.setL(-a.l()); b.setI0(-a.i0()); b.setJ0(-a.j0()); b.setK0(-a.k0()); } @Override public void PI(OctonionFloat64Member a) { assign(PI, a); } @Override public void E(OctonionFloat64Member a) { assign(E, a); } }
package mondrian.test; import mondrian.rolap.BatchTestCase; import mondrian.spi.Dialect.DatabaseProduct; /** * Test native evaluation of supported set operations. */ public class NativeSetEvaluationTest extends BatchTestCase { /** * we'll reuse this in a few variations */ private static final class NativeTopCountWithAgg { final static String mysql = "select\n" + " `product_class`.`product_family` as `c0`,\n" + " `product_class`.`product_department` as `c1`,\n" + " `product_class`.`product_category` as `c2`,\n" + " `product_class`.`product_subcategory` as `c3`,\n" + " `product`.`brand_name` as `c4`,\n" + " `product`.`product_name` as `c5`,\n" + " sum(`sales_fact_1997`.`store_sales`) as `c6`\n" + "from\n" + " `product` as `product`,\n" + " `product_class` as `product_class`,\n" + " `sales_fact_1997` as `sales_fact_1997`,\n" + " `time_by_day` as `time_by_day`\n" + "where\n" + " `product`.`product_class_id` = `product_class`.`product_class_id`\n" + "and\n" + " `sales_fact_1997`.`product_id` = `product`.`product_id`\n" + "and\n" + " `sales_fact_1997`.`time_id` = `time_by_day`.`time_id`\n" //aggregate set + "and\n" + " (`time_by_day`.`quarter`, `time_by_day`.`the_year`) in (('Q1', 1997), ('Q2', 1997), ('Q3', 1997))\n" + "group by\n" + " `product_class`.`product_family`,\n" + " `product_class`.`product_department`,\n" + " `product_class`.`product_category`,\n" + " `product_class`.`product_subcategory`,\n" + " `product`.`brand_name`,\n" + " `product`.`product_name`\n" + "order by\n" //top count Measures.[Store Sales] + " `c6` DESC,\n" + " ISNULL(`product_class`.`product_family`) ASC, `product_class`.`product_family` ASC,\n" + " ISNULL(`product_class`.`product_department`) ASC, `product_class`.`product_department` ASC,\n" + " ISNULL(`product_class`.`product_category`) ASC, `product_class`.`product_category` ASC,\n" + " ISNULL(`product_class`.`product_subcategory`) ASC, `product_class`.`product_subcategory` ASC,\n" + " ISNULL(`product`.`brand_name`) ASC, `product`.`brand_name` ASC,\n" + " ISNULL(`product`.`product_name`) ASC, `product`.`product_name` ASC"; final static String result = "Axis + "{[Time].[x]}\n" + "Axis + "{[Measures].[Store Sales]}\n" + "{[Measures].[x1]}\n" + "{[Measures].[x2]}\n" + "{[Measures].[x3]}\n" + "Axis + "{[Product].[Food].[Produce].[Vegetables].[Fresh Vegetables].[Hermanos].[Hermanos Green Pepper]}\n" + "{[Product].[Non-Consumable].[Health and Hygiene].[Bathroom Products].[Mouthwash].[Hilltop].[Hilltop Mint Mouthwash]}\n" + "Row #0: 733.40\n" + "Row #0: 281.78\n" + "Row #0: 165.98\n" + "Row #0: 285.64\n" + "Row #1: 647.98\n" + "Row #1: 264.26\n" + "Row #1: 173.76\n" + "Row #1: 209.96\n"; } /** * Simple enumerated aggregate. */ public void testNativeTopCountWithAggFlatSet() { final String mdx = "with\n" + "member Time.x as Aggregate({[Time].[1997].[Q1] , [Time].[1997].[Q2], [Time].[1997].[Q3]}, [Measures].[Store Sales])\n" + "member Measures.x1 as ([Time].[1997].[Q1], [Measures].[Store Sales])\n" + "member Measures.x2 as ([Time].[1997].[Q2], [Measures].[Store Sales])\n" + "member Measures.x3 as ([Time].[1997].[Q3], [Measures].[Store Sales])\n" + " set products as TopCount(Product.[Product Name].Members, 2, Measures.[Store Sales])\n" + " SELECT NON EMPTY products ON 1,\n" + "NON EMPTY {[Measures].[Store Sales], Measures.x1, Measures.x2} ON 0\n" + "FROM [Sales] where Time.x"; propSaver.set(propSaver.properties.GenerateFormattedSql, true); SqlPattern mysqlPattern = new SqlPattern( DatabaseProduct.MYSQL, NativeTopCountWithAgg.mysql, NativeTopCountWithAgg.mysql.indexOf("from")); assertQuerySql(mdx, new SqlPattern[]{mysqlPattern}); assertQueryReturns(mdx, NativeTopCountWithAgg.result); } /** * Same as above, but using a named set */ public void testNativeTopCountWithAggMemberEnumSet() { final String mdx = "with set TO_AGGREGATE as '{[Time].[1997].[Q1] , [Time].[1997].[Q2], [Time].[1997].[Q3]}'\n" + "member Time.x as Aggregate(TO_AGGREGATE, [Measures].[Store Sales])\n" + "member Measures.x1 as ([Time].[1997].[Q1], [Measures].[Store Sales])\n" + "member Measures.x2 as ([Time].[1997].[Q2], [Measures].[Store Sales])\n" + "member Measures.x3 as ([Time].[1997].[Q3], [Measures].[Store Sales])\n" + " set products as TopCount(Product.[Product Name].Members, 2, Measures.[Store Sales])\n" + " SELECT NON EMPTY products ON 1,\n" + "NON EMPTY {[Measures].[Store Sales], Measures.x1, Measures.x2} ON 0\n" + "FROM [Sales] where Time.x"; propSaver.set(propSaver.properties.GenerateFormattedSql, true); SqlPattern mysqlPattern = new SqlPattern( DatabaseProduct.MYSQL, NativeTopCountWithAgg.mysql, NativeTopCountWithAgg.mysql.indexOf("from")); assertQuerySql(mdx, new SqlPattern[]{mysqlPattern}); assertQueryReturns(mdx, NativeTopCountWithAgg.result); } /** * Same as above, defined as a range. */ public void testNativeTopCountWithAggMemberCMRange() { final String mdx = "with set TO_AGGREGATE as '([Time].[1997].[Q1] : [Time].[1997].[Q3])'\n" + "member Time.x as Aggregate(TO_AGGREGATE, [Measures].[Store Sales])\n" + "member Measures.x1 as ([Time].[1997].[Q1], [Measures].[Store Sales])\n" + "member Measures.x2 as ([Time].[1997].[Q2], [Measures].[Store Sales])\n" + "member Measures.x3 as ([Time].[1997].[Q3], [Measures].[Store Sales])\n" + " set products as TopCount(Product.[Product Name].Members, 2, Measures.[Store Sales])\n" + " SELECT NON EMPTY products ON 1,\n" + "NON EMPTY {[Measures].[Store Sales], Measures.x1, Measures.x2} ON 0\n" + " FROM [Sales] where Time.x"; propSaver.set(propSaver.properties.GenerateFormattedSql, true); SqlPattern mysqlPattern = new SqlPattern( DatabaseProduct.MYSQL, NativeTopCountWithAgg.mysql, NativeTopCountWithAgg.mysql.indexOf("from")); assertQuerySql(mdx, new SqlPattern[]{mysqlPattern}); assertQueryReturns(mdx, NativeTopCountWithAgg.result); } public void testNativeFilterWithAggDescendants() { final String mdx = "with\n" + " set QUARTERS as Descendants([Time].[1997], [Time].[Time].[Quarter])\n" + " member Time.x as Aggregate(QUARTERS, [Measures].[Store Sales])\n" + " set products as Filter([Product].[Food].[Produce].[Vegetables].[Fresh Vegetables].[Hermanos].Children, [Measures].[Store Sales] > 700)\n" + " SELECT NON EMPTY products ON 1,\n" + " NON EMPTY {[Measures].[Store Sales]} ON 0\n" + " FROM [Sales] where Time.x"; final String mysqlQuery = "select\n" + " `product_class`.`product_family` as `c0`,\n" + " `product_class`.`product_department` as `c1`,\n" + " `product_class`.`product_category` as `c2`,\n" + " `product_class`.`product_subcategory` as `c3`,\n" + " `product`.`brand_name` as `c4`,\n" + " `product`.`product_name` as `c5`\n" + "from\n" + " `product` as `product`,\n" + " `product_class` as `product_class`,\n" + " `sales_fact_1997` as `sales_fact_1997`,\n" + " `time_by_day` as `time_by_day`\n" + "where\n" + " `product`.`product_class_id` = `product_class`.`product_class_id`\n" + "and\n" + " `sales_fact_1997`.`product_id` = `product`.`product_id`\n" + "and\n" + " `sales_fact_1997`.`time_id` = `time_by_day`.`time_id`\n" + "and\n" + " (`time_by_day`.`quarter`, `time_by_day`.`the_year`) in (('Q4', 1997), ('Q3', 1997), ('Q1', 1997), ('Q2', 1997))\n"//slicer + "and\n" + " (`product`.`brand_name` = 'Hermanos' and `product_class`.`product_subcategory` = 'Fresh Vegetables' and `product_class`.`product_category` = 'Vegetables' and `product_class`.`product_department` = 'Produce' and `product_class`.`product_family` = 'Food')\n" + "group by\n" + " `product_class`.`product_family`,\n" + " `product_class`.`product_department`,\n" + " `product_class`.`product_category`,\n" + " `product_class`.`product_subcategory`,\n" + " `product`.`brand_name`,\n" + " `product`.`product_name`\n" + "having\n" + " (sum(`sales_fact_1997`.`store_sales`) > 700)\n"//filter exp + "order by\n" + " ISNULL(`product_class`.`product_family`) ASC, `product_class`.`product_family` ASC,\n" + " ISNULL(`product_class`.`product_department`) ASC, `product_class`.`product_department` ASC,\n" + " ISNULL(`product_class`.`product_category`) ASC, `product_class`.`product_category` ASC,\n" + " ISNULL(`product_class`.`product_subcategory`) ASC, `product_class`.`product_subcategory` ASC,\n" + " ISNULL(`product`.`brand_name`) ASC, `product`.`brand_name` ASC,\n" + " ISNULL(`product`.`product_name`) ASC, `product`.`product_name` ASC"; propSaver.set(propSaver.properties.GenerateFormattedSql, true); SqlPattern mysqlPattern = new SqlPattern( DatabaseProduct.MYSQL, mysqlQuery, mysqlQuery.indexOf("from")); assertQuerySql(mdx, new SqlPattern[]{mysqlPattern}); assertQueryReturns(mdx, "Axis + "{[Time].[x]}\n" + "Axis + "{[Measures].[Store Sales]}\n" + "Axis + "{[Product].[Food].[Produce].[Vegetables].[Fresh Vegetables].[Hermanos].[Hermanos Broccoli]}\n" + "{[Product].[Food].[Produce].[Vegetables].[Fresh Vegetables].[Hermanos].[Hermanos Green Pepper]}\n" + "{[Product].[Food].[Produce].[Vegetables].[Fresh Vegetables].[Hermanos].[Hermanos New Potatos]}\n" + "{[Product].[Food].[Produce].[Vegetables].[Fresh Vegetables].[Hermanos].[Hermanos Prepared Salad]}\n" + "Row #0: 742.73\n" + "Row #1: 922.54\n" + "Row #2: 703.80\n" + "Row #3: 718.08\n"); } /** * Check if getSlicerMembers in native evaluation context * doesn't break the results as in MONDRIAN-1187 */ public void testSlicerTuplesPartialCrossJoin() { final String mdx = "with\n" + "set TSET as {NonEmptyCrossJoin({[Time].[1997].[Q1], [Time].[1997].[Q2]}, {[Store Type].[Supermarket]}),\n" + " NonEmptyCrossJoin({[Time].[1997].[Q1]}, {[Store Type].[Deluxe Supermarket], [Store Type].[Gourmet Supermarket]}) }\n" + " set products as TopCount(Product.[Product Name].Members, 2, Measures.[Store Sales])\n" + " SELECT NON EMPTY products ON 1,\n" + "NON EMPTY {[Measures].[Store Sales]} ON 0\n" + " FROM [Sales]\n" + "where TSET"; final String result = "Axis + "{[Time].[1997].[Q1], [Store Type].[Supermarket]}\n" + "{[Time].[1997].[Q2], [Store Type].[Supermarket]}\n" + "{[Time].[1997].[Q1], [Store Type].[Deluxe Supermarket]}\n" + "{[Time].[1997].[Q1], [Store Type].[Gourmet Supermarket]}\n" + "Axis + "{[Measures].[Store Sales]}\n" + "Axis + "{[Product].[Food].[Eggs].[Eggs].[Eggs].[Urban].[Urban Small Eggs]}\n" + "{[Product].[Food].[Produce].[Vegetables].[Fresh Vegetables].[Hermanos].[Hermanos Green Pepper]}\n" + "Row #0: 332.86\n" + "Row #1: 343.54\n"; assertQueryReturns(mdx, result ); } /** * Same as before but without combinations missing in the crossjoin */ public void testSlicerTuplesFullCrossJoin() { final String mdx = "with\n" + "set TSET as NonEmptyCrossJoin({[Time].[1997].[Q1], [Time].[1997].[Q2]}, {[Store Type].[Supermarket], [Store Type].[Deluxe Supermarket], [Store Type].[Gourmet Supermarket]})\n" + " set products as TopCount(Product.[Product Name].Members, 2, Measures.[Store Sales])\n" + " SELECT NON EMPTY products ON 1,\n" + "NON EMPTY {[Measures].[Store Sales]} ON 0\n" + " FROM [Sales]\n" + "where TSET"; String result = "Axis + "{[Time].[1997].[Q1], [Store Type].[Deluxe Supermarket]}\n" + "{[Time].[1997].[Q1], [Store Type].[Gourmet Supermarket]}\n" + "{[Time].[1997].[Q1], [Store Type].[Supermarket]}\n" + "{[Time].[1997].[Q2], [Store Type].[Deluxe Supermarket]}\n" + "{[Time].[1997].[Q2], [Store Type].[Gourmet Supermarket]}\n" + "{[Time].[1997].[Q2], [Store Type].[Supermarket]}\n" + "Axis + "{[Measures].[Store Sales]}\n" + "Axis + "{[Product].[Food].[Eggs].[Eggs].[Eggs].[Urban].[Urban Small Eggs]}\n" + "{[Product].[Food].[Produce].[Vegetables].[Fresh Vegetables].[Hermanos].[Hermanos Green Pepper]}\n" + "Row #0: 460.02\n" + "Row #1: 420.74\n"; assertQueryReturns(mdx, result ); } }
package org.voltdb; import org.voltdb.VoltDB.Configuration; import org.voltdb.client.ClientResponse; import org.voltdb.client.ProcCallException; import org.voltdb.compiler.VoltProjectBuilder; import org.voltdb.utils.MiscUtils; public class TestAdhocCreateTable extends AdhocDDLTestBase { public void testBasicCreateTable() throws Exception { String pathToCatalog = Configuration.getPathToCatalogForTest("adhocddl.jar"); String pathToDeployment = Configuration.getPathToCatalogForTest("adhocddl.xml"); VoltProjectBuilder builder = new VoltProjectBuilder(); builder.addLiteralSchema("--dont care"); boolean success = builder.compile(pathToCatalog, 2, 1, 0); assertTrue("Schema compilation failed", success); MiscUtils.copyFile(builder.getPathToDeployment(), pathToDeployment); VoltDB.Configuration config = new VoltDB.Configuration(); config.m_pathToCatalog = pathToCatalog; config.m_pathToDeployment = pathToDeployment; try { startSystem(config); assertFalse(findTableInSystemCatalogResults("FOO")); try { m_client.callProcedure("@AdHoc", "create table FOO (ID int default 0, VAL varchar(64 bytes));"); } catch (ProcCallException pce) { fail("create table should have succeeded"); } assertTrue(findTableInSystemCatalogResults("FOO")); // make sure we can't create the same table twice boolean threw = false; try { m_client.callProcedure("@AdHoc", "create table FOO (ID int default 0, VAL varchar(64 bytes));"); } catch (ProcCallException pce) { threw = true; } assertTrue("Shouldn't have been able to create table FOO twice.", threw); } finally { teardownSystem(); } } // Test creating a table when we feed a statement containing newlines. // I honestly didn't expect this to work yet --izzy public void testMultiLineCreateTable() throws Exception { String pathToCatalog = Configuration.getPathToCatalogForTest("adhocddl.jar"); String pathToDeployment = Configuration.getPathToCatalogForTest("adhocddl.xml"); VoltProjectBuilder builder = new VoltProjectBuilder(); builder.addLiteralSchema("--dont care"); boolean success = builder.compile(pathToCatalog, 2, 1, 0); assertTrue("Schema compilation failed", success); MiscUtils.copyFile(builder.getPathToDeployment(), pathToDeployment); VoltDB.Configuration config = new VoltDB.Configuration(); config.m_pathToCatalog = pathToCatalog; config.m_pathToDeployment = pathToDeployment; try { startSystem(config); // Check basic drop of partitioned table that should work. ClientResponse resp = m_client.callProcedure("@SystemCatalog", "TABLES"); assertFalse(findTableInSystemCatalogResults("FOO")); System.out.println(resp.getResults()[0]); try { m_client.callProcedure("@AdHoc", "create table FOO (\n" + "ID int default 0 not null,\n" + "VAL varchar(32 bytes)\n" + ");"); } catch (ProcCallException pce) { fail("create table should have succeeded"); } resp = m_client.callProcedure("@SystemCatalog", "TABLES"); System.out.println(resp.getResults()[0]); assertTrue(findTableInSystemCatalogResults("FOO")); } finally { teardownSystem(); } } }
package org.swows.mouse; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.TimerTask; import org.apache.log4j.Logger; import org.swows.graph.events.DynamicGraph; import org.swows.graph.events.DynamicGraphFromGraph; import org.swows.runnable.LocalTimer; import org.swows.runnable.RunnableContextFactory; import org.swows.util.GraphUtils; import org.swows.vocabulary.DOMEvents; import org.swows.xmlinrdf.DomEventListener; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.events.Event; import org.w3c.dom.events.MouseEvent; import com.hp.hpl.jena.graph.GraphMaker; import com.hp.hpl.jena.graph.Node; import com.hp.hpl.jena.graph.Triple; import com.hp.hpl.jena.graph.impl.SimpleGraphMaker; import com.hp.hpl.jena.vocabulary.RDF; public class MouseInput implements DomEventListener { private static GraphMaker graphMaker = new SimpleGraphMaker(); private DynamicGraphFromGraph mouseEventGraph; // private boolean isReceiving = false; // private Logger logger = Logger.getLogger(getClass()); // private RunnableContext runnableContext = null; private Map<MouseEvent,Set<Node>> event2domNodes = new HashMap<MouseEvent, Set<Node>>(); private Logger logger = Logger.getRootLogger(); // private TimerTask localTimerTask = new TimerTask() { // @Override // public void run() { // logger.debug("Sending update events ... "); // mouseEventGraph.sendUpdateEvents(); // logger.debug("Update events sent!"); // private void startReceiving() { // isReceiving = true; // private void stopReceiving() { // if (isReceiving) { // RunnableContextFactory.getDefaultRunnableContext().run(localTimerTask); //// if (runnableContext != null) //// runnableContext.run(localTimerTask); //// else //// LocalTimer.get().schedule(localTimerTask, 0); // isReceiving = false; public void buildGraph() { if (mouseEventGraph == null) { mouseEventGraph = new DynamicGraphFromGraph( graphMaker.createGraph() ); } } public synchronized DynamicGraph getGraph() { buildGraph(); return mouseEventGraph; } @Override public synchronized void handleEvent(Event event, Node graphNode) { // logger.debug("In " + this + " received event " + event); MouseEvent mouseEvent = (MouseEvent) event; Set<Node> domNodes = event2domNodes.get(mouseEvent); // logger.debug("domNodes: " + domNodes); if (event.getCurrentTarget() instanceof Element) { if (domNodes == null) { domNodes = new HashSet<Node>(); event2domNodes.put(mouseEvent, domNodes); } domNodes.add(graphNode); } else if (event.getCurrentTarget() instanceof Document && domNodes != null) { buildGraph(); Node eventNode = Node.createURI(DOMEvents.getInstanceURI() + "event_" + event.hashCode()); mouseEventGraph.add( new Triple( eventNode, RDF.type.asNode(), DOMEvents.Event.asNode() ) ); mouseEventGraph.add( new Triple( eventNode, RDF.type.asNode(), DOMEvents.UIEvent.asNode() ) ); mouseEventGraph.add( new Triple( eventNode, RDF.type.asNode(), DOMEvents.MouseEvent.asNode() ) ); for (Node targetNode : domNodes) mouseEventGraph.add( new Triple( eventNode, DOMEvents.target.asNode(), targetNode )); GraphUtils.addIntegerProperty( mouseEventGraph, eventNode, DOMEvents.timeStamp.asNode(), event.getTimeStamp()); GraphUtils.addIntegerProperty( mouseEventGraph, eventNode, DOMEvents.detail.asNode(), mouseEvent.getDetail()); // public static final Property target = property( "target" ); // public static final Property currentTarget = property( "currentTarget" ); // public static final Property button = property( "button" ); // public static final Property relatedTarget = property( "relatedTarget" ); GraphUtils.addDecimalProperty( mouseEventGraph, eventNode, DOMEvents.screenX.asNode(), mouseEvent.getScreenX()); GraphUtils.addDecimalProperty( mouseEventGraph, eventNode, DOMEvents.screenY.asNode(), mouseEvent.getScreenY()); GraphUtils.addDecimalProperty( mouseEventGraph, eventNode, DOMEvents.clientX.asNode(), mouseEvent.getClientX()); GraphUtils.addDecimalProperty( mouseEventGraph, eventNode, DOMEvents.clientY.asNode(), mouseEvent.getClientY()); GraphUtils.addBooleanProperty( mouseEventGraph, eventNode, DOMEvents.ctrlKey.asNode(), mouseEvent.getCtrlKey()); GraphUtils.addBooleanProperty( mouseEventGraph, eventNode, DOMEvents.shiftKey.asNode(), mouseEvent.getShiftKey()); GraphUtils.addBooleanProperty( mouseEventGraph, eventNode, DOMEvents.altKey.asNode(), mouseEvent.getAltKey()); GraphUtils.addBooleanProperty( mouseEventGraph, eventNode, DOMEvents.metaKey.asNode(), mouseEvent.getMetaKey()); GraphUtils.addIntegerProperty( mouseEventGraph, eventNode, DOMEvents.button.asNode(), mouseEvent.getButton()); logger.debug("Launching update thread... "); LocalTimer.get().schedule( new TimerTask() { @Override public void run() { RunnableContextFactory.getDefaultRunnableContext().run( new Runnable() { @Override public void run() { logger.debug("Sending update events ... "); mouseEventGraph.sendUpdateEvents(); logger.debug("Update events sent!"); } } ); } }, 0 ); logger.debug("Update thread launched!"); } } }
package <%=packageName%>.grpc; import <%=packageName%>.service.AuditEventService; import com.fasterxml.jackson.core.JsonProcessingException; import com.google.protobuf.Int64Value; import io.grpc.Status; import io.reactivex.Flowable; import io.reactivex.Single; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.time.Instant; import java.time.ZoneId; public class AuditGrpcService extends RxAuditServiceGrpc.AuditServiceImplBase { private final Logger log = LoggerFactory.getLogger(AuditGrpcService.class); private final AuditEventService auditEventService; public AuditGrpcService(AuditEventService auditEventService) { this.auditEventService = auditEventService; } @Override public Flowable<AuditEvent> getAuditEvents(Single<AuditRequest> request) { return request .map( auditRequest -> { if (auditRequest.hasFromDate() || auditRequest.hasToDate()) { Instant fromDate = auditRequest.hasFromDate() ? ProtobufMappers .dateProtoToLocalDate(auditRequest.getFromDate()) .atStartOfDay(ZoneId.systemDefault()) .toInstant() : null; Instant toDate = auditRequest.hasToDate() ? ProtobufMappers .dateProtoToLocalDate(auditRequest.getToDate()) .atStartOfDay(ZoneId.systemDefault()) .plusDays(1) .toInstant() : null; return auditEventService.findByDates(fromDate, toDate, ProtobufMappers.pageRequestProtoToPageRequest(auditRequest.getPaginationParams())); } else { return auditEventService.findAll(ProtobufMappers.pageRequestProtoToPageRequest(auditRequest.getPaginationParams())); } }) .flatMapPublisher(Flowable::fromIterable) .map(auditEvent -> { try { return ProtobufMappers.auditEventToAuditEventProto(auditEvent); } catch (JsonProcessingException e) { log.error("Couldn't parse audit event", e); throw Status.INTERNAL.withCause(e).asRuntimeException(); } }); } @Override public Single<AuditEvent> getAuditEvent(Single<<%= idProtoWrappedType %>> request) { return request .map(Int64Value::getValue) .map(id -> auditEventService.find(id).orElseThrow(Status.NOT_FOUND::asException)) .map(auditEvent -> { try { return ProtobufMappers.auditEventToAuditEventProto(auditEvent); } catch (JsonProcessingException e) { throw Status.INTERNAL.withCause(e).asRuntimeException(); } }); } }
package fi.henu.gdxextras; public class IVector2 { public int x, y; public IVector2() { x = 0; y = 0; } public IVector2(int x, int y) { this.x = x; this.y = y; } public IVector2(IVector2 v) { x = v.x; y = v.y; } public void set(IVector2 pos) { x = pos.x; y = pos.y; } public String toString() { return "(" + x + ", " + y + ")"; } public boolean equals(IVector2 v) { return v.x == x && v.y == y; } public float distanceTo(IVector2 pos) { return (float)Math.sqrt(distanceTo2(pos)); } public long distanceTo2(IVector2 pos) { long xdiff = pos.x - x; long ydiff = pos.y - y; return xdiff * xdiff + ydiff * ydiff; } public int chebyshevDistanceTo(IVector2 pos) { return Math.max(Math.abs(pos.x - x), Math.abs(pos.y - y)); } public IVector2 cpy() { return new IVector2(x, y); } public void scl(int i) { x *= i; y *= i; } public void sub(IVector2 pos) { sub(pos.x, pos.y); } private void sub(int x, int y) { this.x -= x; this.y -= y; } }
package ciissit.maraton; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFileChooser; public abstract class Template { private static final Logger l = Logger.getLogger(Template.class.getName()); protected void init(String[] args) { try { BufferedReader jin; PrintStream jout; String inFileName = null; String outFileName = null; if (args.length == 2) { l.log(Level.INFO, "Entrada y salida correctamente declaradas!"); inFileName = args[0]; outFileName = args[1]; } else { l.log(Level.WARNING, "Estableciendo entrada y salida!"); // Modo Testing JFileChooser fs = new JFileChooser(); int resp = fs.showOpenDialog(null); if (resp == JFileChooser.APPROVE_OPTION) { inFileName = fs.getSelectedFile().getPath(); outFileName = inFileName.replaceAll("\\..*$", ".out"); l.log(Level.INFO, "Salida: {0}", outFileName); } } if (inFileName != null && outFileName != null) { jin = new BufferedReader(new InputStreamReader( new FileInputStream(inFileName))); jout = new PrintStream(outFileName, "UTF-8"); } else { l.log(Level.WARNING, "Usando entrada y salida estándar."); jin = new BufferedReader(new InputStreamReader(System.in)); jout = System.out; } start(jin, jout); jin.close(); jout.close(); } catch (FileNotFoundException ex) { l.log(Level.SEVERE, null, ex); } catch (IOException ex) { l.log(Level.SEVERE, null, ex); } } public abstract void start(BufferedReader jin, PrintStream jout) throws IOException; }
package imj3.draft; import static imj3.draft.Register.add; import static imj3.draft.Register.lerp; import static imj3.draft.Register.newPatchOffsets; import static java.lang.Integer.decode; import static java.lang.Math.*; import static java.util.Arrays.stream; import static net.sourceforge.aprog.swing.SwingTools.show; import static net.sourceforge.aprog.tools.Tools.*; import imj3.core.Channels; import imj3.core.Image2D; import imj3.core.Image2D.Pixel2DProcessor; import imj3.draft.Register.WarpField; import imj3.tools.DoubleImage2D; import imj3.tools.IMJTools; import imj3.tools.Image2DComponent; import imj3.tools.Image2DComponent.TileOverlay; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Polygon; import java.awt.Rectangle; import java.awt.Shape; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.geom.Path2D; import java.awt.geom.Point2D; import java.awt.image.BufferedImage; import java.io.Serializable; import java.util.Arrays; import java.util.concurrent.atomic.AtomicBoolean; import net.sourceforge.aprog.tools.CommandLineArgumentsParser; import net.sourceforge.aprog.tools.ConsoleMonitor; import net.sourceforge.aprog.tools.IllegalInstantiationException; import net.sourceforge.aprog.tools.Factory.DefaultFactory; import net.sourceforge.aprog.tools.MathTools.VectorStatistics; import net.sourceforge.aprog.tools.Tools; /** * @author codistmonk (creation 2015-04-27) */ public final class Register2 { private Register2() { throw new IllegalInstantiationException(); } static final Point2D ZERO = new Point2D.Double(); /** * @param commandLineArguments * <br>Must not be null */ public static final void main(final String[] commandLineArguments) { final CommandLineArgumentsParser arguments = new CommandLineArgumentsParser(commandLineArguments); final int lod = arguments.get("lod", 5)[0]; final Image2D source = IMJTools.read(arguments.get("source", ""), lod); final int iterations = arguments.get("iterations", 200)[0]; final int patchSize0 = arguments.get("patchSize", 25)[0]; final int regularization = arguments.get("regularization", 20)[0]; final String outputPrefix = arguments.get("outputPrefix", baseName(source.getId())); final boolean show = arguments.get("show", 0)[0] != 0; debugPrint("sourceId:", source.getId()); debugPrint("sourceWidth:", source.getWidth(), "sourceHeight:", source.getHeight(), "sourceChannels:", source.getChannels()); final Image2D target = IMJTools.read(arguments.get("target", ""), lod); debugPrint("targetId:", target.getId()); debugPrint("targetWidth:", target.getWidth(), "targetHeight:", target.getHeight(), "targetChannels:", target.getChannels()); final WarpField warpField = new WarpField(target.getWidth() / 2, target.getHeight() / 2); final Warping warping = new Warping(16, 16); debugPrint("score:", warpField.score(source, target)); if (true) { final Image2DComponent sourceComponent = new Image2DComponent(scalarize(source)); final Image2DComponent targetComponent = new Image2DComponent(scalarize(target)); focus(warping.getTargetGrid(), target, 200, 16, 5); copyTo(warping.getSourceGrid(), warping.getTargetGrid()); focus(warping.getSourceGrid(), source, 400, 16, 5); overlay(warping.getSourceGrid(), sourceComponent); overlay(warping.getTargetGrid(), targetComponent); show(sourceComponent, "scalarized source", false); show(targetComponent, "scalarized target", false); return; } } public static final void copyTo(final ParticleGrid destination, final ParticleGrid source) { final int w = destination.getWidth(); final int h = destination.getHeight(); if (w != source.getWidth() || h != source.getHeight()) { throw new IllegalArgumentException(); } destination.forEach((x, y) -> { destination.get(x, y).setLocation(source.get(x, y)); return true; }); } public static final void focusAndRegularize(final ParticleGrid grid, final Image2D image, final int iterations, final int windowSize, final int patchSize, final int regularization) { final ConsoleMonitor monitor = new ConsoleMonitor(10_000L); for (int i = 0; i < iterations; ++i) { monitor.ping(i + "/" + iterations + "\r"); focus(grid, image, windowSize - i * (windowSize - 1) / iterations, patchSize); for (int j = 0; j < regularization; ++j) { regularize(grid); } } monitor.pause(); } public static final void focus(final ParticleGrid grid, final Image2D image, final int iterations, final int windowSize, final int patchSize) { final ConsoleMonitor monitor = new ConsoleMonitor(10_000L); for (int i = 0; i < iterations; ++i) { debugPrint(i); monitor.ping(i + "/" + iterations + "\r"); try { focus(grid, image, windowSize - i * (windowSize - 1) / iterations, patchSize); } catch (final RuntimeException exception) { final String[] xy = exception.getMessage().split(","); final Point2D point = grid.get(decode(xy[0]), decode(xy[1])); final int w = 600; final int h = w; showGrid(grid, w, h, "grid " + i).setRGB((int) (point.getX() * w), (int) (point.getY() * h), 0xFFFF0000); exception.printStackTrace(); break; } } monitor.pause(); } public static final BufferedImage showGrid(final ParticleGrid grid, final int width, final int height, final String title) { final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); final Graphics2D graphics = image.createGraphics(); final Polygon polygon = new Polygon(new int[4], new int[4], 4); grid.forEach((x, y) -> { if (0 < x && 0 < y) { setPoint(polygon, 0, grid.get(x - 1, y - 1), width, height); setPoint(polygon, 1, grid.get(x - 1, y), width, height); setPoint(polygon, 2, grid.get(x, y), width, height); setPoint(polygon, 3, grid.get(x, y - 1), width, height); } graphics.draw(polygon); return true; }); graphics.dispose(); show(image, title, false); return image; } public static final void setPoint(final Polygon polygon, final int index, final Point2D normalizedPoint, final int width, final int height) { polygon.xpoints[index] = (int) (normalizedPoint.getX() * width); polygon.ypoints[index] = (int) (normalizedPoint.getY() * height); } public static final void overlay(final ParticleGrid grid, final Image2DComponent component) { final AtomicBoolean showParticles = new AtomicBoolean(true); component.setTileOverlay(new TileOverlay() { @Override public final void update(final Graphics2D graphics, final Point tileXY, final Rectangle region) { if (!showParticles.get()) { return; } final int tileX = tileXY.x; final int tileY = tileXY.y; final Image2D image = component.getImage(); final int tileWidth = image.getTileWidth(tileX); final int tileHeight = image.getTileHeight(tileY); final int w = grid.getWidth(); final int h = grid.getHeight(); final int r = 2; final int imageWidth = image.getWidth(); final int imageHeight = image.getHeight(); for (int i = 0; i < h; ++i) { for (int j = 0; j < w; ++j) { final Point2D normalizedPoint = grid.get(j, i); final int x0 = j * imageWidth / w; final int y0 = i * imageHeight / h; final int x1 = (int) (normalizedPoint.getX() * imageWidth); final int y1 = (int) (normalizedPoint.getY() * imageHeight); if (tileX <= x1 && x1 < tileX + tileWidth && tileY <= y1 && y1 < tileY + tileHeight) { final int rx0 = (int) lerp(region.x, region.x + region.width, (double) (x0 - tileX) / tileWidth); final int ry0 = (int) lerp(region.y, region.y + region.height, (double) (y0 - tileY) / tileHeight); final int rx1 = (int) lerp(region.x, region.x + region.width, (double) (x1 - tileX) / tileWidth); final int ry1 = (int) lerp(region.y, region.y + region.height, (double) (y1 - tileY) / tileHeight); graphics.setColor(Color.GREEN); graphics.drawLine(rx0, ry0, rx1, ry1); graphics.setColor(Color.RED); graphics.drawOval(rx1 - r, ry1 - r, 2 * r, 2 * r); } } } } private static final long serialVersionUID = -993700290668202661L; }); component.addKeyListener(new KeyAdapter() { @Override public final void keyPressed(final KeyEvent event) { if (event.getKeyCode() == KeyEvent.VK_F) { showParticles.set(!showParticles.get()); component.repaint(); } } }); } public static final void regularize(final ParticleGrid grid) { final WarpField tmp = new WarpField(grid.getWidth(), grid.getHeight()); final int fieldWidth = grid.getWidth(); final int fieldHeight = grid.getHeight(); for (int i = 0; i < fieldHeight; ++i) { for (int j = 0; j < fieldWidth; ++j) { final Point2D normalizedDelta = grid.get(j, i); final Point2D sum = new Point2D.Double(); int n = 0; if (0 < j && j + 1 < fieldWidth) { add(grid.get(j - 1, i), sum); add(grid.get(j + 1, i), sum); n += 2; } if (0 < i && i + 1 < fieldHeight) { add(grid.get(j, i - 1), sum); add(grid.get(j, i + 1), sum); n += 2; } if (i == 0) { if (j == 0) { add(grid.get(j + 1, i), sum); add(grid.get(j, i + 1), sum); n += 2; } else if (j + 1 == fieldWidth) { add(grid.get(j - 1, i), sum); add(grid.get(j, i + 1), sum); n += 2; } } else if (i + 1 == fieldHeight) { if (j == 0) { add(grid.get(j, i - 1), sum); add(grid.get(j + 1, i), sum); n += 2; } else if (j + 1 == fieldWidth) { add(grid.get(j, i - 1), sum); add(grid.get(j - 1, i), sum); n += 2; } } if (0 < n) { final double k = 0.5; tmp.get(j, i).setLocation(lerp(normalizedDelta.getX(), sum.getX() / n, k), lerp(normalizedDelta.getY(), sum.getY() / n, k)); } else { tmp.get(j, i).setLocation(normalizedDelta); } } } for (int i = 0; i < fieldHeight; ++i) { for (int j = 0; j < fieldWidth; ++j) { grid.get(j, i).setLocation(tmp.get(j, i)); } } } public static final void focus(final ParticleGrid grid, final Image2D image, final int windowSize, final int patchSize) { final int imageWidth = image.getWidth(); final int imageHeight = image.getHeight(); final Point2D[] patchOffsets = newPatchOffsets(windowSize); // final Polygon polygon = new Polygon(new int[4], new int[4], 4); final Polygon polygon = new Polygon(new int[8], new int[8], 8); grid.forEach((x, y) -> { final Point2D normalizedPixel = grid.get(x, y); double bestSaliency = 0.0; Point2D bestOffset = null; for (final Point2D offset : patchOffsets) { final double saliency = saliency(image, (int) (normalizedPixel.getX() * imageWidth + offset.getX()), (int) (normalizedPixel.getY() * imageHeight + offset.getY()), patchSize); if (bestSaliency < saliency) { bestSaliency = saliency; bestOffset = offset; } } if (bestOffset != null) { updateSurroundingPolygon8(grid, x, y, imageWidth, imageHeight, polygon); final Shape shape = new Path2D.Double(polygon); if (!shape.contains(normalizedPixel.getX() * imageWidth, normalizedPixel.getY() * imageHeight)) { debugError(x, y); debugError(Arrays.toString(polygon.xpoints)); debugError(Arrays.toString(polygon.ypoints)); debugError((int) (normalizedPixel.getX() * imageWidth), (int) (normalizedPixel.getY() * imageHeight)); throw new RuntimeException(x + "," + y); } for (final int s : new int[] { 4, 8, 16, 32, -32 }) { if (shape.contains(normalizedPixel.getX() * imageWidth + bestOffset.getX() / s / 2.0, normalizedPixel.getY() * imageHeight + bestOffset.getY() / s / 2.0)) { normalizedPixel.setLocation(normalizedPixel.getX() + bestOffset.getX() / s / 2.0 / imageWidth, normalizedPixel.getY() + bestOffset.getY() / s / 2.0 / imageHeight); break; } } } return true; }); } public static final void updateSurroundingPolygon4(final ParticleGrid grid, final int x, final int y, final int imageWidth, final int imageHeight, final Polygon result) { final Point2D point = grid.get(x, y); if (0 < y) { final Point2D neighbor = grid.get(x, y - 1); result.xpoints[0] = (int) (neighbor.getX() * imageWidth); result.ypoints[0] = (int) (neighbor.getY() * imageHeight); } else { final Point2D neighbor = grid.get(x, y + 1); result.xpoints[0] = (int) ((2.0 * point.getX() - neighbor.getX()) * imageWidth); result.ypoints[0] = (int) ((2.0 * point.getY() - neighbor.getY()) * imageHeight); } if (0 < x) { final Point2D neighbor = grid.get(x - 1, y); result.xpoints[1] = (int) (neighbor.getX() * imageWidth); result.ypoints[1] = (int) (neighbor.getY() * imageHeight); } else { final Point2D neighbor = grid.get(x + 1, y); result.xpoints[1] = (int) ((2.0 * point.getX() - neighbor.getX()) * imageWidth); result.ypoints[1] = (int) ((2.0 * point.getY() - neighbor.getY()) * imageHeight); } if (y + 1 < grid.getHeight()) { final Point2D neighbor = grid.get(x, y + 1); result.xpoints[2] = (int) (neighbor.getX() * imageWidth); result.ypoints[2] = (int) (neighbor.getY() * imageHeight); } else { final Point2D neighbor = grid.get(x, y - 1); result.xpoints[2] = (int) ((2.0 * point.getX() - neighbor.getX()) * imageWidth); result.ypoints[2] = (int) ((2.0 * point.getY() - neighbor.getY()) * imageHeight); } if (x + 1 < grid.getWidth()) { final Point2D neighbor = grid.get(x + 1, y); result.xpoints[3] = (int) (neighbor.getX() * imageWidth); result.ypoints[3] = (int) (neighbor.getY() * imageHeight); } else { final Point2D neighbor = grid.get(x - 1, y); result.xpoints[3] = (int) ((2.0 * point.getX() - neighbor.getX()) * imageWidth); result.ypoints[3] = (int) ((2.0 * point.getY() - neighbor.getY()) * imageHeight); } } public static final void updateSurroundingPolygon8(final ParticleGrid grid, final int x, final int y, final int imageWidth, final int imageHeight, final Polygon result) { final int gridWidth = grid.getWidth(); final int gridHeight = grid.getHeight(); final Point2D point = grid.get(x, y); int i = 0; if (0 < y) { final Point2D neighbor = grid.get(x, y - 1); result.xpoints[i] = (int) (neighbor.getX() * imageWidth); result.ypoints[i] = (int) (neighbor.getY() * imageHeight); } else { final Point2D neighbor = grid.get(x, y + 1); result.xpoints[i] = (int) ((2.0 * point.getX() - neighbor.getX()) * imageWidth); result.ypoints[i] = (int) ((2.0 * point.getY() - neighbor.getY()) * imageHeight); } ++i; if (0 < y && 0 < x) { final Point2D neighbor = grid.get(x - 1, y - 1); result.xpoints[i] = (int) (neighbor.getX() * imageWidth); result.ypoints[i] = (int) (neighbor.getY() * imageHeight); } else { final Point2D neighbor = grid.get(x + 1, y + 1); result.xpoints[i] = (int) ((2.0 * point.getX() - neighbor.getX()) * imageWidth); result.ypoints[i] = (int) ((2.0 * point.getY() - neighbor.getY()) * imageHeight); } ++i; if (0 < x) { final Point2D neighbor = grid.get(x - 1, y); result.xpoints[i] = (int) (neighbor.getX() * imageWidth); result.ypoints[i] = (int) (neighbor.getY() * imageHeight); } else { final Point2D neighbor = grid.get(x + 1, y); result.xpoints[i] = (int) ((2.0 * point.getX() - neighbor.getX()) * imageWidth); result.ypoints[i] = (int) ((2.0 * point.getY() - neighbor.getY()) * imageHeight); } ++i; if (y + 1 < gridHeight && 0 < x) { final Point2D neighbor = grid.get(x - 1, y + 1); result.xpoints[i] = (int) (neighbor.getX() * imageWidth); result.ypoints[i] = (int) (neighbor.getY() * imageHeight); } else { final Point2D neighbor = grid.get(x + 1, y - 1); result.xpoints[i] = (int) ((2.0 * point.getX() - neighbor.getX()) * imageWidth); result.ypoints[i] = (int) ((2.0 * point.getY() - neighbor.getY()) * imageHeight); } ++i; if (y + 1 < gridHeight) { final Point2D neighbor = grid.get(x, y + 1); result.xpoints[i] = (int) (neighbor.getX() * imageWidth); result.ypoints[i] = (int) (neighbor.getY() * imageHeight); } else { final Point2D neighbor = grid.get(x, y - 1); result.xpoints[i] = (int) ((2.0 * point.getX() - neighbor.getX()) * imageWidth); result.ypoints[i] = (int) ((2.0 * point.getY() - neighbor.getY()) * imageHeight); } ++i; if (y + 1 < gridHeight && x + 1 < gridWidth) { final Point2D neighbor = grid.get(x + 1, y + 1); result.xpoints[i] = (int) (neighbor.getX() * imageWidth); result.ypoints[i] = (int) (neighbor.getY() * imageHeight); } else { final Point2D neighbor = grid.get(x - 1, y - 1); result.xpoints[i] = (int) ((2.0 * point.getX() - neighbor.getX()) * imageWidth); result.ypoints[i] = (int) ((2.0 * point.getY() - neighbor.getY()) * imageHeight); } ++i; if (x + 1 < gridWidth) { final Point2D neighbor = grid.get(x + 1, y); result.xpoints[i] = (int) (neighbor.getX() * imageWidth); result.ypoints[i] = (int) (neighbor.getY() * imageHeight); } else { final Point2D neighbor = grid.get(x - 1, y); result.xpoints[i] = (int) ((2.0 * point.getX() - neighbor.getX()) * imageWidth); result.ypoints[i] = (int) ((2.0 * point.getY() - neighbor.getY()) * imageHeight); } ++i; if (0 < y && x + 1 < gridWidth) { final Point2D neighbor = grid.get(x + 1, y - 1); result.xpoints[i] = (int) (neighbor.getX() * imageWidth); result.ypoints[i] = (int) (neighbor.getY() * imageHeight); } else { final Point2D neighbor = grid.get(x - 1, y + 1); result.xpoints[i] = (int) ((2.0 * point.getX() - neighbor.getX()) * imageWidth); result.ypoints[i] = (int) ((2.0 * point.getY() - neighbor.getY()) * imageHeight); } } public static final void move(final ParticleGrid grid, final int x, final int y, final Point2D offset, final int imageWidth, final int imageHeight) { if (offset != null) { final double d = offset.distance(ZERO); if (0.0 < d) { final Point2D normalizedOffset = new Point2D.Double(offset.getX() / imageWidth, offset.getY() / imageHeight); final Point2D normalizedPixel = grid.get(x, y); final Point2D tmp = new Point2D.Double(); double smallestK = 1.0; { for (int i = 0; i <= 3; ++i) { final Point2D opposition = getInternalDirection(grid, x, y, i, tmp); if (opposition != null) { final double dotNormalizedOffsetOpposition = dot(normalizedOffset, opposition); if (dotNormalizedOffsetOpposition < 0.0) { final Point2D neighbor = getNeighbor(grid, x, y, i); // (normalizedPixel + k * normalizedOffset) . opposition == neighbor . opposition // <- normalizedPixel . opposition + k * normalizedOffset . opposition == neighbor . opposition // <- k * normalizedOffset . opposition == neighbor . opposition - normalizedPixel . opposition // <- k = (neighbor . opposition - normalizedPixel . opposition) / normalizedOffset . opposition final double k = (dot(neighbor, opposition) - dot(normalizedPixel, opposition)) / dotNormalizedOffsetOpposition; if (k < smallestK) { smallestK = k; } } } } } final double k = smallestK / 2.0; if (k < -1.0) { debugError(k); debugError(normalizedPixel, normalizedOffset); throw new RuntimeException(); } normalizedPixel.setLocation( normalizedPixel.getX() + k * normalizedOffset.getX(), normalizedPixel.getY() + k * normalizedOffset.getY()); } } } private static final Point[] neighborOffsets = { new Point(0, -1), new Point(-1, 0), new Point(0, 1), new Point(1, 0) }; public static final double dot(final Point2D p1, final Point2D p2) { return p1.getX() * p2.getX() + p1.getY() * p2.getY(); } public static final Point2D getNeighbor(final ParticleGrid grid, final int x, final int y, final int neighborIndex) { final Point neighborOffset = neighborOffsets[neighborIndex]; return grid.get(x + neighborOffset.x, y + neighborOffset.y); } public static final Point2D getInternalDirection(final ParticleGrid grid, final int x, final int y, final int neighborIndex, final Point2D result) { final int gridWidth = grid.getWidth(); final int gridHeight = grid.getHeight(); final Point neighbor0Offset = neighborOffsets[neighborIndex]; final int neighbor0X = x + neighbor0Offset.x; final int neighbor0Y = y + neighbor0Offset.y; if (neighbor0X < 0 || gridWidth <= neighbor0X || neighbor0Y < 0 || gridHeight <= neighbor0Y) { return null; } final Point neighbor1Offset = neighborOffsets[(neighborIndex + 1) % neighborOffsets.length]; final int neighbor1X = x + neighbor1Offset.x; final int neighbor1Y = y + neighbor1Offset.y; if (neighbor1X < 0 || gridWidth <= neighbor1X || neighbor1Y < 0 || gridHeight <= neighbor1Y) { return null; } final Point2D neighbor0 = grid.get(neighbor0X, neighbor0Y); final Point2D neighbor1 = grid.get(neighbor1X, neighbor1Y); // left-handed coordinates result.setLocation(neighbor1.getY() - neighbor0.getY(), -(neighbor1.getX() - neighbor0.getX())); return result; } public static void checkInducedTopology(final ParticleGrid grid, final int x, final int y, final int imageWidth, final int imageHeight) { final Point2D normalizedPixel = grid.get(x, y); for (int i = 0; i <= 3; ++i) { final Point neighborOffset = neighborOffsets[i]; final Point2D neighbor = grid.get(x + neighborOffset.x, y + neighborOffset.y); xs[i] = (int) (neighbor.getX() * imageWidth); ys[i] = (int) (neighbor.getY() * imageHeight); } final Polygon polygon = new Polygon(xs, ys, xs.length); if (!polygon.contains((int) (normalizedPixel.getX() * imageWidth), (int) (normalizedPixel.getY() * imageHeight))) { // debugError(); // debugError(Arrays.toString(xs)); // debugError(Arrays.toString(ys)); // debugError(normalizedPixel, (int) (normalizedPixel.getX() * imageWidth), (int) (normalizedPixel.getY() * imageHeight)); } } static final int[] xs = new int[4]; static final int[] ys = new int[4]; public static final double saliency(final Image2D image, final int x, final int y, final int patchSize) { final Channels channels = image.getChannels(); final int n = channels.getChannelCount(); final VectorStatistics statistics = new VectorStatistics(n); final int left = max(0, x - patchSize / 2); final int right = min(left + patchSize, image.getWidth()); final int top = max(0, y - patchSize / 2); final int bottom = min(top + patchSize, image.getHeight()); final double[] pixelValue = new double[n]; for (int yy = top; yy < bottom; ++yy) { for (int xx = left; xx < right; ++xx) { statistics.addValues(image.getPixelValue(xx, yy, pixelValue)); } } return stream(statistics.getVariances()).sum(); } public static final DoubleImage2D scalarize(final Image2D image) { final DoubleImage2D result = new DoubleImage2D(image.getId() + "_scalarized", image.getWidth(), image.getHeight(), 1); final int n = image.getChannels().getChannelCount(); final int patchSize = 5; result.forEachPixel(new Pixel2DProcessor() { private final VectorStatistics statistics = new VectorStatistics(n); private final double[] inputValue = new double[n]; private final double[] outputValue = new double[1]; @Override public final boolean pixel(final int x, final int y) { this.statistics.reset(); final int imageWidth = image.getWidth(); final int imageHeight = image.getHeight(); final int left = max(0, x - patchSize / 2); final int right = min(left + patchSize, imageWidth); final int top = max(0, y - patchSize / 2); final int bottom = min(top + patchSize, imageHeight); for (int yy = top; yy < bottom; ++yy) { for (int xx = left; xx < right; ++xx) { this.statistics.addValues(image.getPixelValue(xx, yy, this.inputValue)); } } this.outputValue[0] = Arrays.stream(this.statistics.getVariances()).sum(); result.setPixelValue(x, y, this.outputValue); return true; } private static final long serialVersionUID = 3324647706518224181L; }); return result; } /** * @author codistmonk (creation 2015-04-27) */ public static final class ParticleGrid implements Serializable { private final int width; private final int height; private final Point2D[] grid; public ParticleGrid(final int width, final int height) { this.width = width; this.height = height; this.grid = instances(width * height, new DefaultFactory<>(Point2D.Double.class)); this.forEach((x, y) -> { this.get(x, y).setLocation((double) x / width, (double) y / height); return true; }); } public final int getWidth() { return this.width; } public final int getHeight() { return this.height; } public final void forEach(final Pixel2DProcessor process) { final int w = this.getWidth(); final int h = this.getHeight(); for (int i = 0; i < h; ++i) { for (int j = 0; j < w; ++j) { if (!process.pixel(j, i)) { return; } } } } public final Point2D get(final int x, final int y) { return this.grid[max(0, min(y, this.getHeight() - 1)) * this.getWidth() + max(0, min(x, this.getWidth() - 1))]; } public final Point2D get(final double x, final double y) { final int left = (int) x; final int top = (int) y; final int right = left + 1; final int bottom = top + 1; final double rx = x - left; final double ry = y - top; final Point2D topLeft = this.get(left, top); if (rx == 0.0 && ry == 0.0) { return topLeft; } final double topLeftWeight = (1.0 - rx) * (1.0 - ry); final double topRightWeight = rx * (1.0 - ry); final double bottomLeftWeight = (1.0 - rx) * ry; final double bottomRightWeight = rx * ry; final Point2D topRight = topRightWeight == 0.0 ? topLeft : this.get(right, top); final Point2D bottomLeft = bottomLeftWeight == 0.0 ? topLeft : this.get(left, bottom); final Point2D bottomRight = bottomRightWeight == 0.0 ? topLeft : this.get(right, bottom); return new Point2D.Double( topLeft.getX() * topLeftWeight + topRight.getX() * topRightWeight + bottomLeft.getX() * bottomLeftWeight + bottomRight.getX() * bottomRightWeight, topLeft.getY() * topLeftWeight + topRight.getY() * topRightWeight + bottomLeft.getY() * bottomLeftWeight + bottomRight.getY() * bottomRightWeight); } private static final long serialVersionUID = -1320819035669324144L; } /** * @author codistmonk (creation 2015-04-27) */ public static final class Warping implements Serializable { private final ParticleGrid sourceGrid; private final ParticleGrid targetGrid; public Warping(final int wwidth, final int height) { this.sourceGrid = new ParticleGrid(wwidth, height); this.targetGrid = new ParticleGrid(wwidth, height); } public final ParticleGrid getSourceGrid() { return this.sourceGrid; } public final ParticleGrid getTargetGrid() { return this.targetGrid; } private static final long serialVersionUID = 7301482635789363102L; } }
package io.spine.type; import com.google.common.collect.ImmutableList; import com.google.protobuf.DescriptorProtos; import com.google.protobuf.DescriptorProtos.DescriptorProto; import com.google.protobuf.DescriptorProtos.FileDescriptorProto; import com.google.protobuf.Descriptors.Descriptor; import com.google.protobuf.Descriptors.FileDescriptor; import com.google.protobuf.Message; import io.spine.base.UuidValue; import io.spine.code.java.ClassName; import io.spine.code.java.SimpleClassName; import io.spine.code.java.VBuilderClassName; import io.spine.code.proto.FieldDeclaration; import io.spine.code.proto.FileDescriptors; import io.spine.code.proto.LocationPath; import io.spine.code.proto.OneofDeclaration; import io.spine.code.proto.TypeSet; import io.spine.logging.Logging; import io.spine.option.OptionsProto; import java.util.Deque; import java.util.Optional; import java.util.function.Predicate; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.Lists.newLinkedList; import static io.spine.code.proto.FileDescriptors.sameFiles; /** * A message type as declared in a proto file. */ public class MessageType extends Type<Descriptor, DescriptorProto> implements Logging { /** * Standard suffix for a Validating Builder class name. */ public static final String VBUILDER_SUFFIX = "VBuilder"; /** * Creates a new instance by the given message descriptor. */ public MessageType(Descriptor descriptor) { super(descriptor, true); } /** * Collects all message types, including nested, declared in the passed file. */ public static TypeSet allFrom(FileDescriptor file) { checkNotNull(file); TypeSet.Builder result = TypeSet.newBuilder(); for (Descriptor messageType : file.getMessageTypes()) { addType(messageType, result); } return result.build(); } private static void addType(Descriptor type, TypeSet.Builder set) { if (type.getOptions() .getMapEntry()) { return; } MessageType messageType = new MessageType(type); set.add(messageType); for (Descriptor nestedType : type.getNestedTypes()) { addType(nestedType, set); } } @Override public final DescriptorProto toProto() { return descriptor().toProto(); } @Override public final TypeUrl url() { return TypeUrl.from(descriptor()); } @Override public final ClassName javaClassName() { return ClassName.from(descriptor()); } @Override @SuppressWarnings("unchecked") // It is safe since we work with a message descriptors public Class<? extends Message> javaClass() { return (Class<? extends Message>) super.javaClass(); } /** * Tells if this message is under the "google" package. */ public boolean isGoogle() { FileDescriptor file = descriptor().getFile(); boolean result = FileDescriptors.isGoogle(file); return result; } /** * Tells if this message type is not from "google" package, and is not an extension * defined in "options.proto". */ public boolean isCustom() { if (isGoogle()) { return false; } FileDescriptor optionsProto = OptionsProto.getDescriptor(); FileDescriptor file = descriptor().getFile(); return !sameFiles(optionsProto, file); } /** * Tells if this message is top-level in its file. */ public boolean isTopLevel() { Descriptor descriptor = descriptor(); return isTopLevel(descriptor); } /** * Verifies if the message is top-level (rather than nested). */ public static boolean isTopLevel(Descriptor descriptor) { Descriptor parent = descriptor.getContainingType(); return parent == null; } /** * Tells if this message is nested inside another message declaration. */ public boolean isNested() { return !isTopLevel(); } /** * Tells if this message is a rejection. */ public boolean isRejection() { boolean result = isTopLevel() && declaringFileName().isRejections(); return result; } /** * Tells if this message is a command. */ public boolean isCommand() { boolean result = isTopLevel() && declaringFileName().isCommands(); return result; } /** * Tells if this message is an event. * * <p>Returns {@code false} if this type is a {@linkplain #isRejection() rejection}. */ public boolean isEvent() { boolean result = isTopLevel() && declaringFileName().isEvents(); return result; } /** * Tells if this message has a {@link io.spine.validate.ValidatingBuilder Validating Builder}. */ public boolean hasVBuilder(){ boolean result = isCustom() && !isRejection(); return result; } public SimpleClassName validatingBuilderClass() { checkState(hasVBuilder(), "No validating builder class available for the type `%s`.", this); SimpleClassName result = VBuilderClassName.of(this); return result; } /** * Obtains all nested declarations that match the passed predicate. */ public ImmutableList<MessageType> nestedTypesThat(Predicate<DescriptorProto> predicate) { ImmutableList.Builder<MessageType> result = ImmutableList.builder(); Iterable<MessageType> nestedDeclarations = immediateNested(); Deque<MessageType> deque = newLinkedList(nestedDeclarations); while (!deque.isEmpty()) { MessageType nestedDeclaration = deque.pollFirst(); assert nestedDeclaration != null; // Cannot be null since the queue is not empty. DescriptorProto nestedDescriptor = nestedDeclaration.descriptor() .toProto(); if (predicate.test(nestedDescriptor)) { result.add(nestedDeclaration); } deque.addAll(nestedDeclaration.immediateNested()); } return result.build(); } /** * Obtains immediate declarations of nested types of this declaration, or * empty list if no nested types are declared. */ private ImmutableList<MessageType> immediateNested() { ImmutableList<MessageType> result = descriptor().getNestedTypes() .stream() .map(MessageType::new) .collect(toImmutableList()); return result; } /** * Obtains fields declared in the message type. */ public ImmutableList<FieldDeclaration> fields() { ImmutableList<FieldDeclaration> result = descriptor().getFields() .stream() .map(field -> new FieldDeclaration(field, this)) .collect(toImmutableList()); return result; } public ImmutableList<OneofDeclaration> oneofs() { ImmutableList<OneofDeclaration> result = descriptor().getOneofs() .stream() .map(OneofDeclaration::new) .collect(toImmutableList()); return result; } /** * Returns the message location path for a top-level message definition. * * @return the message location path */ public LocationPath path() { LocationPath result = LocationPath.fromMessage(descriptor()); return result; } public Optional<String> leadingComments() { LocationPath messagePath = path(); return leadingComments(messagePath); } /** * Obtains a leading comments by the {@link LocationPath}. * * @param locationPath * the location path to get leading comments * @return the leading comments or empty {@code Optional} if there are no such comments or * a descriptor was generated without source code information */ public Optional<String> leadingComments(LocationPath locationPath) { FileDescriptorProto file = descriptor() .getFile() .toProto(); if (!file.hasSourceCodeInfo()) { _warn("Unable to obtain proto source code info. " + "Please configure the Gradle Protobuf plugin as follows:%n%s", "`task.descriptorSetOptions.includeSourceInfo = true`."); return Optional.empty(); } DescriptorProtos.SourceCodeInfo.Location location = locationPath.toLocation(file); return location.hasLeadingComments() ? Optional.of(location.getLeadingComments()) : Optional.empty(); } /** * Determines if the message type represents a {@link UuidValue}. */ public boolean isUuidValue() { return UuidValue.classifier() .test(this); } }
//FILE: PositionList.java //PROJECT: Micro-Manager //SUBSYSTEM: mmstudio // DESCRIPTION: Container for the scanning pattern // This file is distributed in the hope that it will be useful, // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES. // CVS: $Id: PositionList.java 10970 2013-05-08 16:58:06Z nico $ package org.micromanager.api; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.micromanager.utils.MMException; import org.micromanager.utils.MMSerializationException; /** * Navigation list of positions for the XYStage. * Used for multi site acquisition support. */ public class PositionList implements Serializable { private ArrayList<MultiStagePosition> positions_; private final static String ID = "Micro-Manager XY-position list"; private final static String ID_KEY = "ID"; private final static int VERSION = 3; private final static String VERSION_KEY = "VERSION"; private final static String LABEL_KEY = "LABEL"; private final static String DEVICE_KEY = "DEVICE"; private final static String X_KEY = "X"; private final static String Y_KEY = "Y"; private final static String Z_KEY = "Z"; private final static String NUMAXES_KEY = "AXES"; private final static String POSARRAY_KEY = "POSITIONS"; private final static String DEVARRAY_KEY = "DEVICES"; private final static String GRID_ROW_KEY = "GRID_ROW"; private final static String GRID_COL_KEY = "GRID_COL"; private final static String PROPERTIES_KEY = "PROPERTIES"; private final static String DEFAULT_XY_STAGE = "DEFAULT_XY_STAGE"; private final static String DEFAULT_Z_STAGE = "DEFAULT_Z_STAGE"; public final static String AF_KEY = "AUTOFOCUS"; public final static String AF_VALUE_FULL = "full"; public final static String AF_VALUE_INCREMENTAL = "incremental"; public final static String AF_VALUE_NONE = "none"; private HashSet<ChangeListener> listeners_ = new HashSet<ChangeListener>(); public PositionList() { positions_ = new ArrayList<MultiStagePosition>(); } public static PositionList newInstance(PositionList aPl) { PositionList pl = new PositionList(); Iterator<MultiStagePosition> it = aPl.positions_.iterator(); while (it.hasNext()) pl.addPosition(MultiStagePosition.newInstance(it.next())); return pl; } public void addChangeListener(ChangeListener listener) { listeners_.add(listener); } public void removeChangeListener(ChangeListener listener) { listeners_.remove(listener); } public void notifyChangeListeners() { for (ChangeListener listener:listeners_) { listener.stateChanged(new ChangeEvent(this)); } } /** * Returns multi-stage position associated with the position index. * @param idx - position index * @return multi-stage position */ public MultiStagePosition getPosition(int idx) { if (idx < 0 || idx >= positions_.size()) return null; return positions_.get(idx); } /** * Returns a copy of the multi-stage position associated with the position index. * @param idx - position index * @return multi-stage position */ public MultiStagePosition getPositionCopy(int idx) { if (idx < 0 || idx >= positions_.size()) return null; return MultiStagePosition.newInstance(positions_.get(idx)); } /** * Returns position index associated with the position name. * @param posLabel - label (name) of the position * @return index */ public int getPositionIndex(String posLabel) { for (int i=0; i<positions_.size(); i++) { if (positions_.get(i).getLabel().compareTo(posLabel) == 0) return i; } return -1; } /** * Adds a new position to the list. * @param pos - multi-stage position */ public void addPosition(MultiStagePosition pos) { String label = pos.getLabel(); if (!isLabelUnique(label)) { pos.setLabel(generateLabel(label)); } positions_.add(pos); notifyChangeListeners(); } /** * Insert a position into the list. * @param pos - multi-stage position */ public void addPosition(int in0, MultiStagePosition pos) { String label = pos.getLabel(); if (!isLabelUnique(label)) { pos.setLabel(generateLabel(label)); } positions_.add(in0, pos); notifyChangeListeners(); } /** * Replaces position in the list with the new position * @param pos - multi-stage position */ public void replacePosition(int index, MultiStagePosition pos) { if (index >= 0 && index < positions_.size()) { positions_.set(index, pos); notifyChangeListeners(); } } /** * Returns the number of positions contained within the list */ public int getNumberOfPositions() { return positions_.size(); } /** * Empties the list. */ public void clearAllPositions() { positions_.clear(); notifyChangeListeners(); } /** * Removes a specific position based on the index * @param idx - position index */ public void removePosition(int idx) { if (idx >= 0 && idx < positions_.size()) positions_.remove(idx); notifyChangeListeners(); } /** * Initialize the entire array by passing an array of multi-stage positions * @param posArray - array of multi-stage positions */ public void setPositions(MultiStagePosition[] posArray) { positions_.clear(); for (int i=0; i<posArray.length; i++) { positions_.add(posArray[i]); } notifyChangeListeners(); } /** * Returns an array of positions contained in the list. * @return position array */ public MultiStagePosition[] getPositions() { MultiStagePosition[] list = new MultiStagePosition[positions_.size()]; for (int i=0; i<positions_.size(); i++) { list[i] = positions_.get(i); } return list; } /** * Assigns a label to the position index * @param idx - position index * @param label - new label (name) */ public void setLabel(int idx, String label) { if (idx < 0 || idx >= positions_.size()) return; positions_.get(idx).setLabel(label); notifyChangeListeners(); } /** * Serialize object into the JSON encoded stream. * @throws MMSerializationException */ public String serialize() throws MMSerializationException { JSONObject meta = new JSONObject(); try { meta.put(ID_KEY, ID); meta.put(VERSION_KEY, VERSION); JSONArray listOfPositions = new JSONArray(); // iterate on positions for (int i=0; i<positions_.size(); i++) { MultiStagePosition msp = positions_.get(i); JSONObject mspData = new JSONObject(); // annotate position with label mspData.put(LABEL_KEY, positions_.get(i).getLabel()); mspData.put(GRID_ROW_KEY, msp.getGridRow()); mspData.put(GRID_COL_KEY, msp.getGridColumn()); mspData.put(DEFAULT_XY_STAGE, msp.getDefaultXYStage()); mspData.put(DEFAULT_Z_STAGE, msp.getDefaultZStage()); JSONArray devicePosData = new JSONArray(); // iterate on devices for (int j=0; j<msp.size(); j++) { StagePosition sp = msp.get(j); JSONObject stage = new JSONObject(); stage.put(X_KEY, sp.x); stage.put(Y_KEY, sp.y); stage.put(Z_KEY, sp.z); stage.put(NUMAXES_KEY, sp.numAxes); stage.put(DEVICE_KEY, sp.stageName); devicePosData.put(j, stage); } mspData.put(DEVARRAY_KEY, devicePosData); // insert properties JSONObject props = new JSONObject(); String keys[] = msp.getPropertyNames(); for (int k=0; k<keys.length; k++) { String val = msp.getProperty(keys[k]); props.put(keys[k], val); } mspData.put(PROPERTIES_KEY, props); listOfPositions.put(i, mspData); } meta.put(POSARRAY_KEY, listOfPositions); return meta.toString(3); } catch (JSONException e) { throw new MMSerializationException("Unable to serialize XY positition data into formatted string."); } } /** * Restore object data from the JSON encoded stream. * @param stream * @throws MMSerializationException */ public void restore(String stream) throws MMSerializationException { try { JSONObject meta = new JSONObject(stream); JSONArray posArray = meta.getJSONArray(POSARRAY_KEY); int version = meta.getInt(VERSION_KEY); positions_.clear(); for (int i=0; i<posArray.length(); i++) { JSONObject mspData = posArray.getJSONObject(i); MultiStagePosition msp = new MultiStagePosition(); msp.setLabel(mspData.getString(LABEL_KEY)); if (version >= 2) msp.setGridCoordinates(mspData.getInt(GRID_ROW_KEY), mspData.getInt(GRID_COL_KEY)); if (version >= 3) { msp.setDefaultXYStage(mspData.getString(DEFAULT_XY_STAGE)); msp.setDefaultZStage(mspData.getString(DEFAULT_Z_STAGE)); } JSONArray devicePosData = mspData.getJSONArray(DEVARRAY_KEY); for (int j=0; j < devicePosData.length(); j++) { JSONObject stage = devicePosData.getJSONObject(j); StagePosition pos = new StagePosition(); pos.x = stage.getDouble(X_KEY); pos.y = stage.getDouble(Y_KEY); pos.z = stage.getDouble(Z_KEY); pos.stageName = stage.getString(DEVICE_KEY); pos.numAxes = stage.getInt(NUMAXES_KEY); msp.add(pos); } // get properties JSONObject props = mspData.getJSONObject(PROPERTIES_KEY); for (Iterator<String> it = props.keys(); it.hasNext();) { String key = it.next(); msp.setProperty(key, props.getString(key)); } positions_.add(msp); } } catch (JSONException e) { throw new MMSerializationException("Invalid or corrupted serialization data."); } notifyChangeListeners(); } /** * Helper method to generate unique label when inserting a new position. * Not recommended for use - planned to become obsolete. * @return Unique label */ public String generateLabel() { return generateLabel("Pos"); } public String generateLabel(String proposal) { String label = proposal + positions_.size(); // verify the uniqueness int i = 1; while (!isLabelUnique(label)) { label = proposal + (positions_.size() + i++); } return label; } /** * Verify that the new label is unique * @param label - proposed label * @return true if label does not exist */ public boolean isLabelUnique(String label) { for (int i=0; i<positions_.size(); i++) { if (positions_.get(i).getLabel().compareTo(label) == 0) return false; } return true; } /** * Save list to a file. * @param path * @throws MMException */ public void save(String path) throws MMException { File f = new File(path); try { String serList = serialize(); FileWriter fw = new FileWriter(f); fw.write(serList); fw.close(); } catch (Exception e) { throw new MMException(e.getMessage()); } } /** * Load position list from a file. * @param path * @throws MMException */ public void load(String path) throws MMException { File f = new File(path); try { StringBuffer contents = new StringBuffer(); BufferedReader input = new BufferedReader(new FileReader(f)); String line = null; while (( line = input.readLine()) != null){ contents.append(line); contents.append(System.getProperty("line.separator")); } restore(contents.toString()); } catch (Exception e) { throw new MMException(e.getMessage()); } notifyChangeListeners(); } }
package org.micromanager.utils; import ij.ImagePlus; import ij.process.ByteProcessor; import ij.process.ColorProcessor; import ij.process.ImageProcessor; import ij.process.ShortProcessor; import java.awt.Point; import mmcorej.CMMCore; public class ImageUtils { public static int BppToImageType(long Bpp) { int BppInt = (int) Bpp; switch (BppInt) { case 1: return ImagePlus.GRAY8; case 2: return ImagePlus.GRAY16; case 4: return ImagePlus.COLOR_RGB; } return 0; } public static int getImageProcessorType(ImageProcessor proc) { if (proc instanceof ByteProcessor) { return ImagePlus.GRAY8; } if (proc instanceof ShortProcessor) { return ImagePlus.GRAY16; } if (proc instanceof ColorProcessor) { return ImagePlus.COLOR_RGB; } return -1; } public static ImageProcessor makeProcessor(CMMCore core) { return makeProcessor(core, null); } public static ImageProcessor makeProcessor(CMMCore core, Object imgArray) { int w = (int) core.getImageWidth(); int h = (int) core.getImageHeight(); int Bpp = (int) core.getBytesPerPixel(); int type; switch (Bpp) { case 1: type = ImagePlus.GRAY8; break; case 2: type = ImagePlus.GRAY16; break; case 4: type = ImagePlus.COLOR_RGB; break; default: type = 0; } return makeProcessor(type, w, h, imgArray); } public static ImageProcessor makeProcessor(int type, int w, int h, Object imgArray) { if (imgArray == null) { return makeProcessor(type, w, h); } else { switch (type) { case ImagePlus.GRAY8: return new ByteProcessor(w, h, (byte[]) imgArray, null); case ImagePlus.GRAY16: return new ShortProcessor(w, h, (short[]) imgArray, null); case ImagePlus.COLOR_RGB: return new ColorProcessor(w, h, (int[]) imgArray); default: return null; } } } public static ImageProcessor makeProcessor(int type, int w, int h) { if (type == ImagePlus.GRAY8) { return new ByteProcessor(w, h); } else if (type == ImagePlus.GRAY16) { return new ShortProcessor(w, h); } else if (type == ImagePlus.COLOR_RGB) { return new ColorProcessor(w, h); } else { return null; } } /* * Finds the position of the maximum pixel value. */ public static Point findMaxPixel(ImagePlus img) { ImageProcessor proc = img.getProcessor(); float[] pix = (float[]) proc.getPixels(); int width = img.getWidth(); double max = 0; int imax = -1; for (int i = 0; i < pix.length; i++) { if (pix[i] > max) { max = pix[i]; imax = i; } } int y = imax / width; int x = imax % width; return new Point(x, y); } public static Point findMaxPixel(ImageProcessor proc) { int width = proc.getWidth(); int imax = findArrayMax(proc.getPixels()); int y = imax / width; int x = imax % width; return new Point(x, y); } public static byte[] get8BitData(Object bytesAsObject) { return (byte[]) bytesAsObject; } public static short[] get16BitData(Object shortsAsObject) { return (short[]) shortsAsObject; } public static int[] get32BitData(Object intsAsObject) { return (int[]) intsAsObject; } public static int findArrayMax(Object pix) { if (pix instanceof byte []) return findArrayMax((byte []) pix); if (pix instanceof int []) return findArrayMax((int []) pix); if (pix instanceof short []) return findArrayMax((short []) pix); if (pix instanceof float []) return findArrayMax((float []) pix); else return -1; } public static int findArrayMax(float[] pix) { float pixel; int imax = -1; float max = Float.MIN_VALUE; for (int i = 0; i < pix.length; ++i) { pixel = pix[i]; if (pixel > max) { max = pixel; imax = i; } } return imax; } public static int findArrayMax(short[] pix) { short pixel; int imax = -1; short max = Short.MIN_VALUE; for (int i = 0; i < pix.length; ++i) { pixel = pix[i]; if (pixel > max) { max = pixel; imax = i; } } return imax; } public static int findArrayMax(byte[] pix) { byte pixel; int imax = -1; byte max = Byte.MIN_VALUE; for (int i = 0; i < pix.length; ++i) { pixel = pix[i]; if (pixel > max) { max = pixel; imax = i; } } return imax; } public static int findArrayMax(int[] pix) { int pixel; int imax = -1; int max = Integer.MIN_VALUE; for (int i = 0; i < pix.length; ++i) { pixel = pix[i]; if (pixel > max) { max = pixel; imax = i; } } return imax; } /* * channel should be 0, 1 or 2. */ public static byte[] singleChannelFromRGB32(int[] pixels, int channel) { byte[] newPixels = new byte[pixels.length]; int bitShift = 8*channel; for (int i=0;i<pixels.length;++i) { newPixels[i] = (byte) (0xff & (pixels[i] >> bitShift)); } return newPixels; } /* * channel should be 0, 1 or 2. */ public static short[] singleChannelFromRGB64(int[] pixels, int channel) { short [] newPixels = new short[pixels.length/2]; int i=0; if (channel == 0) { // even pixels, first half for (int j=0; j<newPixels.length; j+=2) { newPixels[i++] = (short) (pixels[j] & 0xffff); } } else if (channel == 1) { // even pixels, second half for (int j=0; j<newPixels.length; j+=2) { newPixels[i++] = (short) (pixels[j] >> 16); } } else if (channel == 2) { // odd pixels, first half for (int j=1; j<newPixels.length; j+=2) { newPixels[i++] = (short) (pixels[j] & 0xffff); } } else { newPixels = null; } return newPixels; } }
package moa.classifiers.bayes; import eu.amidst.core.datastream.*; import arffWekaReader.DataRowWeka; import eu.amidst.core.datastream.filereaders.DataInstanceImpl; import eu.amidst.core.distribution.Multinomial; import eu.amidst.core.distribution.Normal; import eu.amidst.core.inference.InferenceEngineForBN; import eu.amidst.core.learning.TransitionMethod; import eu.amidst.core.models.BayesianNetwork; import eu.amidst.core.utils.Utils; import eu.amidst.core.variables.StateSpaceType; import eu.amidst.core.variables.StaticVariables; import eu.amidst.core.variables.Variable; import eu.amidst.core.variables.stateSpaceTypes.FiniteStateSpace; import eu.amidst.core.variables.stateSpaceTypes.RealStateSpace; import eu.amidst.ida2015.NaiveBayesGaussianHiddenConceptDrift; import moa.classifiers.AbstractClassifier; import moa.classifiers.SemiSupervisedLearner; import moa.core.InstancesHeader; import moa.core.Measurement; import moa.options.FloatOption; import moa.options.IntOption; import moa.options.MultiChoiceOption; import weka.core.Instance; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; public class amidstModels extends AbstractClassifier implements SemiSupervisedLearner{ private static final long serialVersionUID = 1L; double acc=0; int nbatch=0; /** * Parameters of the amidst model */ String[] driftModes = new String[]{ "GLOBAL", "LOCAL", "GLOBAL_LOCAL"}; public MultiChoiceOption driftDetectorOption = new MultiChoiceOption( "driftDetector", 'd', "Drift detector type.", new String[]{ "GLOBAL", "LOCAL", "GLOBAL_LOCAL"}, new String[]{ "GLOBAL", "LOCAL", "GLOBAL_LOCAL"}, 0); public IntOption windowSizeOption = new IntOption("windowSize", 'w', "Size of the window in which to apply variational Bayes", 100); protected int windowSize_ = 100; public FloatOption transitionVarianceOption = new FloatOption("transitionVariance", 'v', "Transition variance for the global hidden variable.", 0.1); protected double transitionVariance_ = 0.1; public FloatOption fadingOption = new FloatOption("fading", 'f', "Fading.", 1); protected double fading_ = 1; public IntOption asNBOption = new IntOption("asNB", 'n', "If 1 then build plain NB (without hidden)", 0); protected int asNB_ = 0; /* public FloatOption MARclassOption = new FloatOption("MARclass", 'm', "MARclass.", 1); protected double MARclass_ = 1;*/ /* public MultiChoiceOption semiSupervisedLearnerOption = new MultiChoiceOption( "semiSupervisedLearning", 'd', "Perform semi-supervised learning.", new String[]{ "TRUE", "FALSE"}, new String[]{ "TRUE", "FALSE", 0);*/ /** * Private fields */ //private StreamingVariationalBayesVMP svb_ = null; NaiveBayesGaussianHiddenConceptDrift nb_ = null; private Variable classVar_ = null; private Attributes attributes_ = null; private Attribute TIME_ID = null; private Attribute SEQUENCE_ID = null; private BayesianNetwork learntBN_ = null; DataOnMemoryListContainer<DataInstance> batch_ = null; private int count_ = 0; private int currentTimeID = 0; private DataInstance firstInstanceForBatch = null; private boolean dynamicFlag = false; /** * SETTERS AND GETTERS */ public int getWindowSize_() { return windowSize_; } public void setWindowSize_(int windowSize_) { this.windowSize_ = windowSize_; } public double getTransitionVariance_() { return transitionVariance_; } public void setTransitionVariance_(double transitionVariance_) { this.transitionVariance_ = transitionVariance_; } public double getFading_() { return fading_; } public void setFading_(double fading_) { this.fading_ = fading_; } public int getAsNB_() { return asNB_; } public void setAsNB_(int asNB_) { this.asNB_ = asNB_; } /* public double getMARclass_() { return MARclass_; } public void setMARclass_(double MARclass_) { this.MARclass_ = MARclass_; }*/ @Override public String getPurposeString() { return "Amidst concept-drift classifier: performs concept-drift detection with a BN model plus one or several hidden variables."; } @Override public void resetLearningImpl() { } @Override public void setModelContext(InstancesHeader ih) { super.setModelContext(ih); nb_ = new NaiveBayesGaussianHiddenConceptDrift(); convertAttributes(); batch_ = new DataOnMemoryListContainer(attributes_); nb_.setData(batch_); nb_.setSeed(randomSeed);//Note that the default value is 1 nb_.setClassIndex(-1); setWindowSize_(windowSizeOption.getValue()); nb_.setWindowsSize(windowSize_); setTransitionVariance_(transitionVarianceOption.getValue()); nb_.setTransitionVariance(transitionVariance_); nb_.setConceptDriftDetector(NaiveBayesGaussianHiddenConceptDrift.DriftDetector.valueOf(this.driftModes[driftDetectorOption.getChosenIndex()])); setFading_(fadingOption.getValue()); nb_.setFading(fading_); setAsNB_(asNBOption.getValue()); if(asNB_ == 1) nb_.setGlobalHidden(false); else nb_.setGlobalHidden(true); nb_.learnDAG(); List<Attribute> attributesExtendedList = new ArrayList<>(attributes_.getList()); if(TIME_ID != null && SEQUENCE_ID != null) { attributesExtendedList.add(TIME_ID); attributesExtendedList.add(SEQUENCE_ID); dynamicFlag = true; } attributes_ = new Attributes(attributesExtendedList); batch_ = new DataOnMemoryListContainer(attributes_); //System.out.println(nb_.getLearntBayesianNetwork().getDAG().toString()); } private void convertAttributes(){ weka.core.Attribute attrWeka; Enumeration attributesWeka = modelContext.enumerateAttributes(); List<Attribute> attrList = new ArrayList<>(); /* Predictive attributes */ while (attributesWeka.hasMoreElements()) { attrWeka = (weka.core.Attribute) attributesWeka.nextElement(); convertAttribute(attrWeka,attrList); } /* Class attribute */ convertAttribute(modelContext.classAttribute(), attrList); attributes_ = new Attributes(attrList); StaticVariables variables = new StaticVariables(attributes_); String className = modelContext.classAttribute().name(); classVar_ = variables.getVariableByName(className); } private void convertAttribute(weka.core.Attribute attrWeka, List<Attribute> attrList){ StateSpaceType stateSpaceTypeAtt; if(attrWeka.isNominal()){ String[] vals = new String[attrWeka.numValues()]; for (int i=0; i<attrWeka.numValues(); i++) { vals[i] = attrWeka.value(i); } stateSpaceTypeAtt = new FiniteStateSpace(attrWeka.numValues()); }else{ stateSpaceTypeAtt = new RealStateSpace(); } Attribute att = new Attribute(attrWeka.index(),attrWeka.name(), stateSpaceTypeAtt); if(att.getName().equalsIgnoreCase("TIME_ID")) TIME_ID = att; else if(att.getName().equalsIgnoreCase("SEQUENCE_ID")) SEQUENCE_ID = att; else attrList.add(att); } @Override public void trainOnInstance(Instance inst) { boolean isTraining = (inst.weight() > 0.0); if (this instanceof SemiSupervisedLearner == false && inst.classIsMissing() == true){ isTraining = false; } if (isTraining) { this.trainingWeightSeenByModel += inst.weight(); trainOnInstanceImpl(inst); } } @Override public void trainOnInstanceImpl(Instance inst) { if (dynamicFlag) trainOnInstanceImplDynamic(inst); else trainOnInstanceImplStatic(inst); } public void trainOnInstanceImplStatic(Instance inst) { if(firstInstanceForBatch != null) { batch_.add(firstInstanceForBatch); count_++; firstInstanceForBatch = null; } DataInstance dataInstance = new DataInstanceImpl(new DataRowWeka(inst)); if(count_ < windowSize_){ if(TIME_ID==null || (int)dataInstance.getValue(TIME_ID) == currentTimeID) { batch_.add(dataInstance); count_++; } }else{ count_ = 0; TransitionMethod transitionMethod = nb_.getSvb().getTransitionMethod(); if(TIME_ID!=null && (int)dataInstance.getValue(TIME_ID) == currentTimeID) nb_.getSvb().setTransitionMethod(null); firstInstanceForBatch = dataInstance; if(TIME_ID!=null) currentTimeID = (int)dataInstance.getValue(TIME_ID); double batchAccuracy=nb_.computeAccuracy(nb_.getLearntBayesianNetwork(), batch_); nbatch+=windowSize_; //System.out.println(acc/nbatch); nb_.updateModel(batch_); nb_.getSvb().setTransitionMethod(transitionMethod); batch_ = new DataOnMemoryListContainer(attributes_); learntBN_ = nb_.getLearntBayesianNetwork(); //System.out.println(learntBN_.toString()); System.out.print(nbatch); for (Variable hiddenVar : nb_.getHiddenVars()) { Normal normal = nb_.getSvb().getPlateuStructure().getEFVariablePosterior(hiddenVar, 0).toUnivariateDistribution(); System.out.print("\t" + normal.getMean()); } System.out.print("\t" + batchAccuracy); System.out.println(); } } public void trainOnInstanceImplDynamic(Instance inst) { if(firstInstanceForBatch != null) { batch_.add(firstInstanceForBatch); count_++; firstInstanceForBatch = null; } DataInstance dataInstance = new DataInstanceImpl(new DataRowWeka(inst)); if(count_ < windowSize_){ if(TIME_ID==null || (int)dataInstance.getValue(TIME_ID) == currentTimeID) { batch_.add(dataInstance); count_++; } }else{ count_ = 0; TransitionMethod transitionMethod = nb_.getSvb().getTransitionMethod(); if(TIME_ID!=null && (int)dataInstance.getValue(TIME_ID) == currentTimeID) nb_.getSvb().setTransitionMethod(null); firstInstanceForBatch = dataInstance; if(TIME_ID!=null) currentTimeID = (int)dataInstance.getValue(TIME_ID); double batchAccuracy=nb_.computeAccuracy(nb_.getLearntBayesianNetwork(), batch_); nbatch+=windowSize_; //System.out.println(acc/nbatch); nb_.updateModel(batch_); nb_.getSvb().setTransitionMethod(transitionMethod); batch_ = new DataOnMemoryListContainer(attributes_); learntBN_ = nb_.getLearntBayesianNetwork(); //System.out.println(learntBN_.toString()); System.out.print(nbatch); for (Variable hiddenVar : nb_.getHiddenVars()) { Normal normal = nb_.getSvb().getPlateuStructure().getEFVariablePosterior(hiddenVar, 0).toUnivariateDistribution(); System.out.print("\t" + normal.getMean()); } System.out.print("\t" + batchAccuracy); System.out.println(); } } @Override public double[] getVotesForInstance(Instance inst) { if(learntBN_ == null) { double[] votes = new double[classVar_.getNumberOfStates()]; for (int i = 0; i < votes.length; i++) { votes[i] = 1.0/votes.length; } return votes; } InferenceEngineForBN.setModel(learntBN_); DataInstance dataInstance = new DataInstanceImpl(new DataRowWeka(inst)); double realValue = dataInstance.getValue(classVar_); dataInstance.setValue(classVar_, Utils.missingValue()); InferenceEngineForBN.setEvidence(dataInstance); InferenceEngineForBN.runInference(); Multinomial posterior = InferenceEngineForBN.getPosterior(classVar_); dataInstance.setValue(classVar_, realValue); return posterior.getProbabilities(); } @Override public void getModelDescription(StringBuilder out, int indent) { } @Override protected Measurement[] getModelMeasurementsImpl() { return null; } @Override public boolean isRandomizable() { return true; } public static void main(String[] args){ } }
package wycs.testing.tests; import org.junit.Ignore; import org.junit.Test; import wycs.testing.TestHarness; public class ValidTests extends TestHarness { public ValidTests() { super("tests/valid"); } @Test public void Test_Arith_1() { verifyPassTest("test_arith_01"); } @Test public void Test_Arith_2() { verifyPassTest("test_arith_02"); } @Test public void Test_Arith_3() { verifyPassTest("test_arith_03"); } @Test public void Test_Arith_4() { verifyPassTest("test_arith_04"); } @Test public void Test_Arith_5() { verifyPassTest("test_arith_05"); } @Test public void Test_Arith_6() { verifyPassTest("test_arith_06"); } @Ignore("Known Issue") @Test public void Test_Arith_7() { verifyPassTest("test_arith_07"); } @Test public void Test_Arith_8() { verifyPassTest("test_arith_08"); } @Test public void Test_Arith_9() { verifyPassTest("test_arith_09"); } @Test public void Test_Arith_10() { verifyPassTest("test_arith_10"); } @Test public void Test_Arith_11() { verifyPassTest("test_arith_11"); } @Ignore("Known Issue") @Test public void Test_Arith_12() { verifyPassTest("test_arith_12"); } @Test public void Test_Arith_13() { verifyPassTest("test_arith_13"); } @Test public void Test_Arith_14() { verifyPassTest("test_arith_14"); } @Ignore("Known Issue") @Test public void Test_Arith_15() { verifyPassTest("test_arith_15"); } @Test public void Test_Arith_16() { verifyPassTest("test_arith_16"); } @Test public void Test_Arith_17() { verifyPassTest("test_arith_17"); } @Ignore("Known Issue") @Test public void Test_Arith_18() { verifyPassTest("test_arith_18"); } @Test public void Test_Arith_19() { verifyPassTest("test_arith_19"); } @Test public void Test_Arith_20() { verifyPassTest("test_arith_20"); } @Test public void Test_Arith_21() { verifyPassTest("test_arith_21"); } @Ignore("Set <=> Length") @Test public void Test_Arith_22() { verifyPassTest("test_arith_22"); } @Test public void Test_Arith_23() { verifyPassTest("test_arith_23"); } @Test public void Test_Arith_24() { verifyPassTest("test_arith_24"); } @Test public void Test_Arith_25() { verifyPassTest("test_arith_25"); } @Test public void Test_Arith_26() { verifyPassTest("test_arith_26"); } @Test public void Test_Arith_27() { verifyPassTest("test_arith_27"); } @Ignore("Known Issue") @Test public void Test_Arith_28() { verifyPassTest("test_arith_28"); } @Test public void Test_Macro_1() { verifyPassTest("test_macro_01"); } @Test public void Test_Macro_2() { verifyPassTest("test_macro_02"); } @Test public void Test_Bool_1() { verifyPassTest("test_bool_01"); } @Test public void Test_Fun_1() { verifyPassTest("test_fun_01"); } @Test public void Test_Set_1() { verifyPassTest("test_set_01"); } @Test public void Test_Set_2() { verifyPassTest("test_set_02"); } @Test public void Test_Set_3() { verifyPassTest("test_set_03"); } @Test public void Test_Set_4() { verifyPassTest("test_set_04"); } @Test public void Test_Set_5() { verifyPassTest("test_set_05"); } @Test public void Test_Set_6() { verifyPassTest("test_set_06"); } @Test public void Test_Set_7() { verifyPassTest("test_set_07"); } @Test public void Test_Set_8() { verifyPassTest("test_set_08"); } @Test public void Test_Set_9() { verifyPassTest("test_set_09"); } @Ignore("SubsetEq <=> Length") @Test public void Test_Valid_058() { verifyPassTest("test_058"); } @Test public void Test_Valid_059() { verifyPassTest("test_059"); } @Test public void Test_Valid_060() { verifyPassTest("test_060"); } @Test public void Test_Valid_061() { verifyPassTest("test_061"); } @Ignore("SubsetEq <=> Length") @Test public void Test_Valid_062() { verifyPassTest("test_062"); } @Test public void Test_Valid_063() { verifyPassTest("test_063"); } @Test public void Test_Valid_064() { verifyPassTest("test_064"); } @Test public void Test_Valid_065() { verifyPassTest("test_065"); } @Ignore("Nat <=> Length") @Test public void Test_Valid_066() { verifyPassTest("test_066"); } @Ignore("Nat <=> Length") @Test public void Test_Valid_067() { verifyPassTest("test_067"); } @Test public void Test_Valid_068() { verifyPassTest("test_068"); } @Ignore("SubsetEq <=> Length") @Test public void Test_Valid_069() { verifyPassTest("test_069"); } @Ignore("SubsetEq <=> Length") @Test public void Test_Valid_070() { verifyPassTest("test_070"); } @Ignore("SubsetEq to Equals") @Test public void Test_Valid_071() { verifyPassTest("test_071"); } @Test public void Test_Valid_072() { verifyPassTest("test_072"); } @Test public void Test_Valid_073() { verifyPassTest("test_073"); } @Ignore("ListLength") @Test public void Test_Valid_074() { verifyPassTest("test_074"); } @Test public void Test_Valid_075() { verifyPassTest("test_075"); } @Ignore("ListAppend") @Test public void Test_Valid_076() { verifyPassTest("test_076"); } @Ignore("ListAppend") @Test public void Test_Valid_077() { verifyPassTest("test_077"); } @Test public void Test_Valid_078() { verifyPassTest("test_078"); } @Test public void Test_Valid_079() { verifyPassTest("test_079"); } @Test public void Test_Valid_100() { verifyPassTest("test_100"); } @Ignore("MaxSteps") @Test public void Test_Valid_101() { verifyPassTest("test_101"); } @Test public void Test_Valid_102() { verifyPassTest("test_102"); } @Ignore("Known Issue") @Test public void Test_Valid_103() { verifyPassTest("test_103"); } @Ignore("Infinite Loop?") @Test public void Test_Valid_104() { verifyPassTest("test_104"); } @Test public void Test_Valid_105() { verifyPassTest("test_105"); } @Ignore("Known Issue") @Test public void Test_Valid_106() { verifyPassTest("test_106"); } @Ignore("Known Issue") @Test public void Test_Valid_107() { verifyPassTest("test_107"); } @Test public void Test_Valid_108() { verifyPassTest("test_108"); } @Test public void Test_Valid_109() { verifyPassTest("test_109"); } @Ignore("Known Issue") @Test public void Test_Valid_110() { verifyPassTest("test_110"); } @Test public void Test_Valid_111() { verifyPassTest("test_111"); } @Test public void Test_Valid_112() { verifyPassTest("test_112"); } @Test public void Test_Valid_113() { verifyPassTest("test_113"); } @Test public void Test_Valid_114() { verifyPassTest("test_114"); } @Ignore("Too Slow") @Test public void Test_Valid_115() { verifyPassTest("test_115"); } @Test public void Test_Valid_116() { verifyPassTest("test_116"); } @Test public void Test_Valid_117() { verifyPassTest("test_117"); } @Test public void Test_Valid_118() { verifyPassTest("test_118"); } @Test public void Test_Valid_119() { verifyPassTest("test_119"); } @Test public void Test_Valid_120() { verifyPassTest("test_120"); } }
package com.me.mylolgame; import edu.lehigh.cse.lol.ChooserConfiguration; public class ChooserConfig implements ChooserConfiguration { /** * Each chooser screen will have a bunch of buttons for playing specific * levels. This defines the number of rows of buttons on each screen. */ @Override public int getRows() { return 2; } /** * Each chooser screen will have a bunch of buttons for playing specific * levels. This defines the number of columns of buttons on each screen. */ @Override public int getColumns() { return 5; } /** * This is the space, in pixels, between the top of the screen and the first * row of buttons * * @return */ @Override public int getTopMargin() { return 130; } /** * This is the space, in pixels, between the left of the screen and the * first column of buttons */ @Override public int getLeftMargin() { return 85; } /** * This is the horizontal space between buttons */ @Override public int getHPadding() { return 15; } /** * This is the vertical space between buttons */ @Override public int getBPadding() { return 15; } /** * This is the name of the image that is displayed for each "level" button, * behind the text for that button */ @Override public String getLevelButtonName() { return "leveltile.png"; } /** * This is the width of each level button's image */ @Override public int getLevelButtonWidth() { return 50; } /** * This is the height of each level button's image */ @Override public int getLevelButtonHeight() { return 50; } /** * This is the name of the font to use when making the "level" buttons */ @Override public String getLevelFont() { return "arial.ttf"; } /** * This is the font size for the "level" buttons */ @Override public int getLevelFontSize() { return 28; } /** * This is the red component of the font for level buttons */ @Override public int getLevelFontRed() { return 255; } /** * This is the green component of the font for level buttons */ @Override public int getLevelFontGreen() { return 255; } /** * This is the blue component of the font for level buttons */ @Override public int getLevelFontBlue() { return 255; } /** * This is the text to display on locked levels */ @Override public String getLevelLockText() { return "X"; } /** * This is the name of the music file to play for the Chooser scenes */ @Override public String getMusicName() { return "tune.ogg"; } /** * This is the name of the background image to display on the Chooser scenes */ @Override public String getBackgroundName() { return "chooser.png"; } /** * The image to display as the "back to splash" button */ @Override public String getBackButtonName() { return "backarrow.png"; } /** * The X coordinate of the bottom left corner of the "back to splash" button */ @Override public int getBackButtonX() { return 0; } /** * The Y coordinate of the bottom left corner of the "back to splash" button */ @Override public int getBackButtonY() { return 0; } /** * The width of the "back to splash" button */ @Override public int getBackButtonWidth() { return 25; } /** * The height of the "back to splash" button */ @Override public int getBackButtonHeight() { return 25; } /** * The image to display as the "previous chooser screen" button */ @Override public String getPrevButtonName() { return "leftarrow.png"; } /** * The X coordinate of bottom left corner of the "previous chooser screen" * button */ @Override public int getPrevButtonX() { return 0; } /** * The Y coordinate of bottom left corner of the "previous chooser screen" * button */ @Override public int getPrevButtonY() { return 110; } /** * The width of the "previous chooser screen" button */ @Override public int getPrevButtonWidth() { return 40; } /** * The width of the "previous chooser screen" button */ @Override public int getPrevButtonHeight() { return 40; } /** * The image to display as the "next chooser screen" button */ @Override public String getNextButtonName() { return "rightarrow.png"; } /** * The X coordinate of the bottom left corner of the "next chooser screen" * button */ @Override public int getNextButtonX() { return 440; } /** * The Y coordinate of the bottom left corner of the "next chooser screen" * button */ @Override public int getNextButtonY() { return 110; } /** * The width of the "next chooser screen" button */ @Override public int getNextButtonWidth() { return 40; } /** * The height of the "next chooser screen" button */ @Override public int getNextButtonHeight() { return 40; } /** * Return true if pressing 'play' should result in the level-chooser screen * showing; return false if pressing 'play' should immediately start level * one. */ @Override public boolean showChooser() { return true; } }
import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.io.File; public class MyWindow implements ActionListener { private JFrame mainFrame; private JFrame alertFrame; private JLabel statusLabel; private JPanel controlPanel; private JPanel outputPanel; private JPanel inputPanel; private JButton runButton, rfpsFileChooseButton, signalProChooseButton, chooseOutputButton; private JLabel rfpsInputLabel, signalProInputLabel, directoryOutputLabel, outputLocationLabel; private JFileChooser fileChooser, outputDirChooser, inputFileChooser; private UserInput userInput; public MyWindow(){ mainFrame = new JFrame("GPS Coordinate Comparison Program"); mainFrame.setSize(1200,1200); mainFrame.setLayout(new GridBagLayout()); mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); userInput = new UserInput(); fileChooser = new JFileChooser(); outputDirChooser = new JFileChooser(); outputDirChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); inputFileChooser = new JFileChooser(); setupInputOptions(); setupOutputOptions(); setupRunControls(); setupResultsDisplay(); mainFrame.setVisible(true); } private void setupInputOptions(){ GridBagConstraints constraints = new GridBagConstraints(); constraints.anchor = GridBagConstraints.LINE_START; rfpsFileChooseButton = new JButton("Input RFPS file"); //KML button rfpsFileChooseButton.addActionListener(this); constraints.gridx = 0; constraints.gridy = 0; mainFrame.add(rfpsFileChooseButton, constraints); rfpsInputLabel = new JLabel("No file chosen"); constraints.gridx = 1; constraints.gridy = 0; mainFrame.add(rfpsInputLabel, constraints); signalProChooseButton = new JButton("Input SignalPro file"); //KMZ button signalProChooseButton.addActionListener(this); constraints.gridx = 0; constraints.gridy = 1; mainFrame.add(signalProChooseButton, constraints); signalProInputLabel = new JLabel("No file chosen"); constraints.gridx = 1; constraints.gridy = 1; mainFrame.add(signalProInputLabel, constraints); }//end showInputButton() function private void setupOutputOptions() { GridBagConstraints constraints = new GridBagConstraints(); constraints.anchor = GridBagConstraints.LINE_START; chooseOutputButton = new JButton("Choose Output Directory"); chooseOutputButton.addActionListener(this); constraints.gridx = 0; constraints.gridy = 2; mainFrame.add(chooseOutputButton, constraints); directoryOutputLabel = new JLabel("No directory chosen"); constraints.gridx = 1; constraints.gridy = 2; mainFrame.add(directoryOutputLabel, constraints); } private void setupRunControls() { GridBagConstraints constraints = new GridBagConstraints(); constraints.anchor = GridBagConstraints.LINE_START; constraints.gridx = 0; constraints.gridy = 3; runButton = new JButton("RUN"); runButton.addActionListener(this); mainFrame.add(runButton, constraints); } private void setupResultsDisplay() { GridBagConstraints constraints = new GridBagConstraints(); constraints.anchor = GridBagConstraints.LINE_START; constraints.gridx = 0; constraints.gridy = 4; constraints.gridwidth = 2; outputLocationLabel = new JLabel("Select an RFPS file, SignalPro file, and output directory."); mainFrame.add(outputLocationLabel, constraints); } public void actionPerformed(ActionEvent e) { //Handle open button action. if (e.getSource() == chooseOutputButton) { int returnVal = outputDirChooser.showOpenDialog(mainFrame); if (returnVal == JFileChooser.APPROVE_OPTION) { File directory = outputDirChooser.getSelectedFile(); userInput.setOutputDirectory(directory); directoryOutputLabel.setText(directory.getAbsolutePath()); } } else if (e.getSource() == rfpsFileChooseButton) { try{ inputFileChooser.showOpenDialog(mainFrame); userInput.setRfpsFile(inputFileChooser.getSelectedFile()); String RFPSName = inputFileChooser.getSelectedFile().getName(); rfpsInputLabel.setText(RFPSName); } catch(Exception E){ } } else if (e.getSource() == signalProChooseButton) { try{ inputFileChooser.showOpenDialog(mainFrame); userInput.setSignalproFile(inputFileChooser.getSelectedFile()); String SignalProName = inputFileChooser.getSelectedFile().getName(); signalProInputLabel.setText(SignalProName); } catch(Exception E){ } } else if (e.getSource() == runButton) { if (validUserInput()) { Comparison comparison = new Comparison(); boolean success = comparison.createKmlOutputFile(userInput.getOutputDirectory()); String outputLocationLabelText; if (success) { outputLocationLabelText = "File output to " + userInput.getOutputDirectory().getAbsolutePath(); } else { outputLocationLabelText = "Select an RFPS file, SignalPro file, and output directory."; } outputLocationLabel.setText(outputLocationLabelText); } } } boolean validUserInput() { if (userInput.getRfpsFile() == null) return false; if (userInput.getSignalproFile() == null) return false; if (userInput.getOutputDirectory() == null) return false; return true; } public static void main(String[] args){ MyWindow demo = new MyWindow( ); } }
package gov.va.isaac.gui.conceptview.data; import gov.va.isaac.util.Utility; import gov.vha.isaac.metadata.coordinates.StampCoordinates; import gov.vha.isaac.metadata.source.IsaacMetadataAuxiliaryBinding; import gov.vha.isaac.ochre.api.Get; import gov.vha.isaac.ochre.api.chronicle.LatestVersion; import gov.vha.isaac.ochre.api.component.sememe.SememeChronology; import gov.vha.isaac.ochre.api.component.sememe.version.DescriptionSememe; import gov.vha.isaac.ochre.impl.lang.LanguageCode; import gov.vha.isaac.ochre.impl.utility.Frills; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; import java.util.function.Function; import javafx.application.Platform; import javafx.beans.property.SimpleStringProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ConceptDescription extends StampedItem { private static final Logger LOG = LoggerFactory.getLogger(ConceptDescription.class); private DescriptionSememe<?> _description; private final SimpleStringProperty typeSSP = new SimpleStringProperty("-"); private final SimpleStringProperty valueSSP = new SimpleStringProperty("-"); private final SimpleStringProperty languageSSP = new SimpleStringProperty("-"); private final SimpleStringProperty acceptabilitySSP = new SimpleStringProperty("-"); private final SimpleStringProperty significanceSSP = new SimpleStringProperty("-"); @SuppressWarnings("rawtypes") public static DescriptionSememe extractDescription(SememeChronology<? extends DescriptionSememe> sememeChronology) { DescriptionSememe description = null; SememeChronology sc = (SememeChronology) sememeChronology; Optional optDS = sc.getLatestVersion(DescriptionSememe.class, Get.configurationService().getDefaultStampCoordinate()); if (optDS.isPresent()) { LatestVersion<DescriptionSememe> lv = (LatestVersion) optDS.get(); description = (DescriptionSememe) lv.value(); } return description; } public static ObservableList<ConceptDescription> makeDescriptionList(List<? extends SememeChronology<? extends DescriptionSememe<?>>> sememeChronologyList, boolean activeOnly) { ObservableList<ConceptDescription> descriptionList = FXCollections.observableArrayList(); for (SememeChronology<? extends DescriptionSememe<?>> sememeChronology : sememeChronologyList) { if (activeOnly && ! sememeChronology.isLatestVersionActive(Get.configurationService().getDefaultStampCoordinate())) { // Ignore inactive descriptions when activeOnly true continue; } else { DescriptionSememe<?> descSememe = extractDescription(sememeChronology); if (descSememe != null) { ConceptDescription description = new ConceptDescription(descSememe); descriptionList.add(description); } } } return descriptionList; } public ConceptDescription(DescriptionSememe<?> description) { readDescription(description); } private void readDescription(DescriptionSememe<?> description) { _description = description; if (description != null) { readStampDetails(description); Utility.execute(() -> { String typeName = Get.conceptDescriptionText(_description.getDescriptionTypeConceptSequence()); String valueName = _description.getText(); String languageName = Get.conceptDescriptionText(getLanguageSequence()); String acceptabilityName = getAcceptabilities(_description, CUSTOM_DIALECT_SEQUENCE_RENDERER, CUSTOM_ACCEPTABILITY_NID_RENDERER); String significanceName = Get.conceptDescriptionText(getSignificanceSequence()); final String finalValueName = valueName; Platform.runLater(() -> { typeSSP.set(typeName); valueSSP.set(finalValueName); languageSSP.set(languageName); acceptabilitySSP.set(acceptabilityName); significanceSSP.set(significanceName); }); }); } } public int getSequence() { return _description.getSememeSequence(); } public int getTypeSequence() { return _description.getDescriptionTypeConceptSequence(); } public int getLanguageSequence() { return _description.getLanguageConceptSequence(); } public int getAcceptabilitySequence() { return 0; } public int getSignificanceSequence() { return _description.getCaseSignificanceConceptSequence(); } public SimpleStringProperty getTypeProperty() { return typeSSP; } public SimpleStringProperty getValueProperty() { return valueSSP; } public SimpleStringProperty getLanguageProperty() { return languageSSP; } public SimpleStringProperty getAcceptabilityProperty() { return acceptabilitySSP; } public SimpleStringProperty getSignificanceProperty() { return significanceSSP; } public String getType() { return typeSSP.get(); } public String getValue() { return valueSSP.get(); } public String getLanguage() { return languageSSP.get(); } public String getAcceptability() { return acceptabilitySSP.get(); } public String getSignificance() { return significanceSSP.get(); } public static final Comparator<ConceptDescription> typeComparator = new Comparator<ConceptDescription>() { @Override public int compare(ConceptDescription o1, ConceptDescription o2) { return Utility.compareStringsIgnoreCase(o1.getType(), o2.getType()); } }; public static final Comparator<ConceptDescription> valueComparator = new Comparator<ConceptDescription>() { @Override public int compare(ConceptDescription o1, ConceptDescription o2) { return Utility.compareStringsIgnoreCase(o1.getValue(), o2.getValue()); } }; public static final Comparator<ConceptDescription> languageComparator = new Comparator<ConceptDescription>() { @Override public int compare(ConceptDescription o1, ConceptDescription o2) { return Utility.compareStringsIgnoreCase(o1.getLanguage(), o2.getLanguage()); } }; public static final Comparator<ConceptDescription> acceptabilityComparator = new Comparator<ConceptDescription>() { @Override public int compare(ConceptDescription o1, ConceptDescription o2) { return Utility.compareStringsIgnoreCase(o1.getAcceptability(), o2.getAcceptability()); } }; public static final Comparator<ConceptDescription> significanceComparator = new Comparator<ConceptDescription>() { @Override public int compare(ConceptDescription o1, ConceptDescription o2) { return Utility.compareStringsIgnoreCase(o1.getSignificance(), o2.getSignificance()); } }; private static String getAcceptabilities(DescriptionSememe<?> description) { return getAcceptabilities(description, null, null); } private final static Function<Integer, String> DEFAULT_DIALECT_SEQUENCE_RENDERER = new Function<Integer, String>() { @Override public String apply(Integer t) { return Get.conceptDescriptionText(t); } }; private final static Function<Integer, String> CUSTOM_DIALECT_SEQUENCE_RENDERER = new Function<Integer, String>() { @Override public String apply(Integer t) { String dialectDesc = null; Optional<UUID> uuidForDialectSequence = Get.identifierService().getUuidPrimordialFromConceptSequence(t); if (uuidForDialectSequence.isPresent()) { LanguageCode code = LanguageCode.safeValueOf(uuidForDialectSequence.get()); if (code != null) { dialectDesc = code.getFormatedLanguageCode(); } } if (dialectDesc == null) { dialectDesc = Get.conceptDescriptionText(t); } return dialectDesc; } }; private final static Function<Integer, String> DEFAULT_ACCEPTABILITY_NID_RENDERER = new Function<Integer, String>() { @Override public String apply(Integer t) { return Get.conceptDescriptionText(t); } }; private final static Function<Integer, String> CUSTOM_ACCEPTABILITY_NID_RENDERER = new Function<Integer, String>() { @Override public String apply(Integer t) { if (t == IsaacMetadataAuxiliaryBinding.PREFERRED.getNid()) { return "PT"; } else if (t == IsaacMetadataAuxiliaryBinding.ACCEPTABLE.getNid()) { return "AC"; } else { String error = "Unexpected acceptability NID " + t + "(" + Get.conceptDescriptionText(t) + ")"; LOG.error(error); throw new RuntimeException(error); } } }; private static String getAcceptabilities(DescriptionSememe<?> description, Function<Integer, String> passedDialectSequenceRenderer, Function<Integer, String> passedAcceptabilityRenderer) { final Function<Integer, String> acceptabilityRenderer = passedAcceptabilityRenderer != null ? passedAcceptabilityRenderer : DEFAULT_ACCEPTABILITY_NID_RENDERER; final Function<Integer, String> dialectSequenceRenderer = passedDialectSequenceRenderer != null ? passedDialectSequenceRenderer : DEFAULT_DIALECT_SEQUENCE_RENDERER; Map<Integer, Integer> dialectSequenceToAcceptabilityNidMap = Frills.getAcceptabilities(description.getNid(), StampCoordinates.getDevelopmentLatest()); StringBuilder builder = new StringBuilder(); for (Map.Entry<Integer, Integer> entry : dialectSequenceToAcceptabilityNidMap.entrySet()) { if (entry.getKey() != null && entry.getValue() != null) { if (builder.toString().length() > 0) { builder.append(", "); } builder.append(passedDialectSequenceRenderer.apply(entry.getKey()) + ":" + acceptabilityRenderer.apply(entry.getValue())); } } return builder.toString(); } }
package com.yahoo.prelude.fastsearch; import com.yahoo.slime.BinaryFormat; import com.yahoo.slime.Slime; import com.yahoo.data.access.slime.SlimeAdapter; import com.yahoo.prelude.ConfigurationException; import com.yahoo.container.search.LegacyEmulationConfig; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.logging.Logger; public final class DocsumDefinitionSet { public static final int SLIME_MAGIC_ID = 0x55555555; private final static Logger log = Logger.getLogger(DocsumDefinitionSet.class.getName()); private final HashMap<Long, DocsumDefinition> definitions = new HashMap<>(); private final HashMap<String, DocsumDefinition> definitionsByName = new HashMap<>(); private final LegacyEmulationConfig emulationConfig; public DocsumDefinitionSet(DocumentdbInfoConfig.Documentdb config) { this.emulationConfig = new LegacyEmulationConfig(new LegacyEmulationConfig.Builder()); configure(config); } public DocsumDefinitionSet(DocumentdbInfoConfig.Documentdb config, LegacyEmulationConfig emulConfig) { this.emulationConfig = emulConfig; configure(config); } /** Returns a docsum definition by id * @param id document summary class id * @return a DocsumDefinition for the id, if found. */ public final DocsumDefinition getDocsumDefinition(long id) { return definitions.get(new Long(id)); } /** * Returns a docsum definition by name, or null if not found * * @param name the name of the summary class to use, or null to use the name "default" * @return the summary class found, or null if none */ public final DocsumDefinition getDocsumDefinition(String name) { if (name == null) name="default"; return definitionsByName.get(name); } /** * Makes data available for decoding for the given hit. * * @param summaryClass the requested summary class * @param data docsum data from backend * @param hit the Hit corresponding to this document summary * @throws ConfigurationException if the summary class of this hit is missing */ public final void lazyDecode(String summaryClass, byte[] data, FastHit hit) { ByteBuffer buffer = ByteBuffer.wrap(data); buffer.order(ByteOrder.LITTLE_ENDIAN); long docsumClassId = buffer.getInt(); if (docsumClassId != SLIME_MAGIC_ID) { throw new IllegalArgumentException("Only expecting SchemaLess docsums - summary class:" + summaryClass + " hit:" + hit); } DocsumDefinition docsumDefinition = lookupDocsum(summaryClass); Slime value = BinaryFormat.decode(buffer.array(), buffer.arrayOffset()+buffer.position(), buffer.remaining()); hit.addSummary(docsumDefinition, new SlimeAdapter(value.get())); } private DocsumDefinition lookupDocsum(String summaryClass) { DocsumDefinition ds = definitionsByName.get(summaryClass); if (ds == null) { ds = definitionsByName.get("default"); } if (ds == null) { throw new ConfigurationException("Fetched hit with summary class " + summaryClass + ", but this summary class is not in current summary config (" + toString() + ")" + " (that is, you asked for something unknown, and no default was found)"); } return ds; } public String toString() { StringBuilder sb = new StringBuilder(); Set<Map.Entry<Long, DocsumDefinition>> entrySet = definitions.entrySet(); boolean first = true; for (Iterator<Map.Entry<Long, DocsumDefinition>> itr = entrySet.iterator(); itr.hasNext(); ) { if (!first) { sb.append(","); } else { first = false; } Map.Entry<Long, DocsumDefinition> entry = itr.next(); sb.append("[").append(entry.getKey()).append(",").append(entry.getValue().getName()).append("]"); } return sb.toString(); } public int size() { return definitions.size(); } private void configure(DocumentdbInfoConfig.Documentdb config) { for (int i = 0; i < config.summaryclass().size(); ++i) { DocumentdbInfoConfig.Documentdb.Summaryclass sc = config.summaryclass(i); DocsumDefinition docSumDef = new DocsumDefinition(sc, emulationConfig); definitions.put((long) sc.id(), docSumDef); definitionsByName.put(sc.name(), docSumDef); } if (definitions.size() == 0) { log.warning("No summary classes found in DocumentdbInfoConfig.Documentdb"); } } }
package org.hisp.dhis.android.core.arch.handlers; import org.hisp.dhis.android.core.common.HandleAction; import org.hisp.dhis.android.core.common.ModelBuilder; import java.util.Collection; abstract class SyncHandlerBaseImpl<O> implements SyncHandlerWithTransformer<O> { @Override public final void handle(O o) { if (o == null) { return; } HandleAction action = deleteOrPersist(o); afterObjectHandled(o, action); } @Override public final void handle(O o, ModelBuilder<O, O> modelBuilder) { if (o == null) { return; } O oTransformed = modelBuilder.buildModel(o); HandleAction action = deleteOrPersist(oTransformed); afterObjectHandled(oTransformed, action); } @Override public final void handleMany(Collection<O> oCollection) { if (oCollection != null) { for(O o : oCollection) { handle(o); } afterCollectionHandled(oCollection); } } @Override public final void handleMany(Collection<O> oCollection, ModelBuilder<O, O> modelBuilder) { if (oCollection != null) { for(O o : oCollection) { handle(o, modelBuilder); } afterCollectionHandled(oCollection); } } protected abstract HandleAction deleteOrPersist(O o); @SuppressWarnings("PMD.EmptyMethodInAbstractClassShouldBeAbstract") protected void afterObjectHandled(O o, HandleAction action) { /* Method is not abstract since empty action is the default action and we don't want it to * be unnecessarily written in every child. */ } @SuppressWarnings("PMD.EmptyMethodInAbstractClassShouldBeAbstract") protected void afterCollectionHandled(Collection<O> oCollection) { /* Method is not abstract since empty action is the default action and we don't want it to * be unnecessarily written in every child. */ } }
package org.jasig.cas.web.flow; import org.springframework.webflow.test.MockRequestContext; import junit.framework.TestCase; /** * @author Scott Battaglia * @version $Revision$ $Date$ * @since 3.0.4 */ public class TicketGrantingTicketExistsActionTests extends TestCase { private TicketGrantingTicketExistsAction action = new TicketGrantingTicketExistsAction(); public void testTicketExists() { assertEquals("ticketGrantingTicketExists", this.action .doExecuteInternal(new MockRequestContext(), "test", "service", true, true, true).getId()); } public void testTicketDoesntExists() { assertEquals("noTicketGrantingTicketExists", this.action .doExecuteInternal(new MockRequestContext(), null, "service", true, true, true).getId()); } }
package org.postgresql.jdbc2; import java.math.BigDecimal; import java.io.*; import java.sql.*; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; import org.postgresql.Driver; import org.postgresql.Field; import org.postgresql.core.Encoding; import org.postgresql.largeobject.*; import org.postgresql.util.PGbytea; import org.postgresql.util.PSQLException; /* $Header$ * This class defines methods of the jdbc2 specification. This class extends * org.postgresql.jdbc1.AbstractJdbc1ResultSet which provides the jdbc1 * methods. The real Statement class (for jdbc2) is org.postgresql.jdbc2.Jdbc2ResultSet */ public abstract class AbstractJdbc2ResultSet extends org.postgresql.jdbc1.AbstractJdbc1ResultSet { //needed for updateable result set support protected boolean updateable = false; protected boolean doingUpdates = false; protected boolean onInsertRow = false; protected Hashtable updateValues = new Hashtable(); private boolean usingOID = false; // are we using the OID for the primary key? private Vector primaryKeys; // list of primary keys private int numKeys = 0; private boolean singleTable = false; protected String tableName = null; protected PreparedStatement updateStatement = null; protected PreparedStatement insertStatement = null; protected PreparedStatement deleteStatement = null; private PreparedStatement selectStatement = null; public AbstractJdbc2ResultSet(org.postgresql.PGConnection conn, Statement statement, Field[] fields, Vector tuples, String status, int updateCount, long insertOID, boolean binaryCursor) { super (conn, statement, fields, tuples, status, updateCount, insertOID, binaryCursor); } public java.net.URL getURL(int columnIndex) throws SQLException { return null; } public java.net.URL getURL(String columnName) throws SQLException { return null; } /* * Get the value of a column in the current row as a Java object * * <p>This method will return the value of the given column as a * Java object. The type of the Java object will be the default * Java Object type corresponding to the column's SQL type, following * the mapping specified in the JDBC specification. * * <p>This method may also be used to read database specific abstract * data types. * * @param columnIndex the first column is 1, the second is 2... * @return a Object holding the column value * @exception SQLException if a database access error occurs */ public Object getObject(int columnIndex) throws SQLException { Field field; checkResultSet( columnIndex ); wasNullFlag = (this_row[columnIndex - 1] == null); if (wasNullFlag) return null; field = fields[columnIndex - 1]; // some fields can be null, mainly from those returned by MetaData methods if (field == null) { wasNullFlag = true; return null; } switch (field.getSQLType()) { case Types.BIT: return getBoolean(columnIndex) ? Boolean.TRUE : Boolean.FALSE; case Types.SMALLINT: return new Short(getShort(columnIndex)); case Types.INTEGER: return new Integer(getInt(columnIndex)); case Types.BIGINT: return new Long(getLong(columnIndex)); case Types.NUMERIC: return getBigDecimal (columnIndex, (field.getMod() == -1) ? -1 : ((field.getMod() - 4) & 0xffff)); case Types.REAL: return new Float(getFloat(columnIndex)); case Types.DOUBLE: return new Double(getDouble(columnIndex)); case Types.CHAR: case Types.VARCHAR: return getString(columnIndex); case Types.DATE: return getDate(columnIndex); case Types.TIME: return getTime(columnIndex); case Types.TIMESTAMP: return getTimestamp(columnIndex); case Types.BINARY: case Types.VARBINARY: return getBytes(columnIndex); case Types.ARRAY: return getArray(columnIndex); default: String type = field.getPGType(); // if the backend doesn't know the type then coerce to String if (type.equals("unknown")) { return getString(columnIndex); } else { return connection.getObject(field.getPGType(), getString(columnIndex)); } } } public boolean absolute(int index) throws SQLException { // index is 1-based, but internally we use 0-based indices int internalIndex; if (index == 0) throw new SQLException("Cannot move to index of 0"); final int rows_size = rows.size(); //if index<0, count from the end of the result set, but check //to be sure that it is not beyond the first index if (index < 0) { if (index >= -rows_size) internalIndex = rows_size + index; else { beforeFirst(); return false; } } else { //must be the case that index>0, //find the correct place, assuming that //the index is not too large if (index <= rows_size) internalIndex = index - 1; else { afterLast(); return false; } } current_row = internalIndex; this_row = (byte[][]) rows.elementAt(internalIndex); return true; } public void afterLast() throws SQLException { final int rows_size = rows.size(); if (rows_size > 0) current_row = rows_size; } public void beforeFirst() throws SQLException { if (rows.size() > 0) current_row = -1; } public boolean first() throws SQLException { if (rows.size() <= 0) return false; onInsertRow = false; current_row = 0; this_row = (byte[][]) rows.elementAt(current_row); rowBuffer = new byte[this_row.length][]; System.arraycopy(this_row, 0, rowBuffer, 0, this_row.length); return true; } public java.sql.Array getArray(String colName) throws SQLException { return getArray(findColumn(colName)); } public java.sql.Array getArray(int i) throws SQLException { wasNullFlag = (this_row[i - 1] == null); if (wasNullFlag) return null; if (i < 1 || i > fields.length) throw new PSQLException("postgresql.res.colrange"); return (java.sql.Array) new org.postgresql.jdbc2.Array( connection, i, fields[i - 1], (java.sql.ResultSet) this ); } public java.math.BigDecimal getBigDecimal(int columnIndex) throws SQLException { return getBigDecimal(columnIndex, -1); } public java.math.BigDecimal getBigDecimal(String columnName) throws SQLException { return getBigDecimal(findColumn(columnName)); } public Blob getBlob(String columnName) throws SQLException { return getBlob(findColumn(columnName)); } public abstract Blob getBlob(int i) throws SQLException; public java.io.Reader getCharacterStream(String columnName) throws SQLException { return getCharacterStream(findColumn(columnName)); } public java.io.Reader getCharacterStream(int i) throws SQLException { checkResultSet( i ); wasNullFlag = (this_row[i - 1] == null); if (wasNullFlag) return null; if (((AbstractJdbc2Connection) connection).haveMinimumCompatibleVersion("7.2")) { //Version 7.2 supports AsciiStream for all the PG text types //As the spec/javadoc for this method indicate this is to be used for //large text values (i.e. LONGVARCHAR) PG doesn't have a separate //long string datatype, but with toast the text datatype is capable of //handling very large values. Thus the implementation ends up calling //getString() since there is no current way to stream the value from the server return new CharArrayReader(getString(i).toCharArray()); } else { // In 7.1 Handle as BLOBS so return the LargeObject input stream Encoding encoding = connection.getEncoding(); InputStream input = getBinaryStream(i); return encoding.getDecodingReader(input); } } public Clob getClob(String columnName) throws SQLException { return getClob(findColumn(columnName)); } public abstract Clob getClob(int i) throws SQLException; public int getConcurrency() throws SQLException { if (statement == null) return java.sql.ResultSet.CONCUR_READ_ONLY; return statement.getResultSetConcurrency(); } public java.sql.Date getDate(int i, java.util.Calendar cal) throws SQLException { // If I read the specs, this should use cal only if we don't // store the timezone, and if we do, then act just like getDate()? // for now... return getDate(i); } public Time getTime(int i, java.util.Calendar cal) throws SQLException { // If I read the specs, this should use cal only if we don't // store the timezone, and if we do, then act just like getTime()? // for now... return getTime(i); } public Timestamp getTimestamp(int i, java.util.Calendar cal) throws SQLException { // If I read the specs, this should use cal only if we don't // store the timezone, and if we do, then act just like getDate()? // for now... return getTimestamp(i); } public java.sql.Date getDate(String c, java.util.Calendar cal) throws SQLException { return getDate(findColumn(c), cal); } public Time getTime(String c, java.util.Calendar cal) throws SQLException { return getTime(findColumn(c), cal); } public Timestamp getTimestamp(String c, java.util.Calendar cal) throws SQLException { return getTimestamp(findColumn(c), cal); } public int getFetchDirection() throws SQLException { //PostgreSQL normally sends rows first->last return java.sql.ResultSet.FETCH_FORWARD; } public int getFetchSize() throws SQLException { // In this implementation we return the entire result set, so // here return the number of rows we have. Sub-classes can return a proper // value return rows.size(); } public Object getObject(String columnName, java.util.Map map) throws SQLException { return getObject(findColumn(columnName), map); } /* * This checks against map for the type of column i, and if found returns * an object based on that mapping. The class must implement the SQLData * interface. */ public Object getObject(int i, java.util.Map map) throws SQLException { throw org.postgresql.Driver.notImplemented(); } public Ref getRef(String columnName) throws SQLException { return getRef(findColumn(columnName)); } public Ref getRef(int i) throws SQLException { //The backend doesn't yet have SQL3 REF types throw new PSQLException("postgresql.psqlnotimp"); } public int getRow() throws SQLException { final int rows_size = rows.size(); if (current_row < 0 || current_row >= rows_size) return 0; return current_row + 1; } // This one needs some thought, as not all ResultSets come from a statement public Statement getStatement() throws SQLException { return statement; } public int getType() throws SQLException { // This implementation allows scrolling but is not able to // see any changes. Sub-classes may overide this to return a more // meaningful result. return java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE; } public boolean isAfterLast() throws SQLException { final int rows_size = rows.size(); return (current_row >= rows_size && rows_size > 0); } public boolean isBeforeFirst() throws SQLException { return (current_row < 0 && rows.size() > 0); } public boolean isFirst() throws SQLException { return (current_row == 0 && rows.size() >= 0); } public boolean isLast() throws SQLException { final int rows_size = rows.size(); return (current_row == rows_size - 1 && rows_size > 0); } public boolean last() throws SQLException { final int rows_size = rows.size(); if (rows_size <= 0) return false; current_row = rows_size - 1; this_row = (byte[][]) rows.elementAt(current_row); rowBuffer = new byte[this_row.length][]; System.arraycopy(this_row, 0, rowBuffer, 0, this_row.length); return true; } public boolean previous() throws SQLException { if (--current_row < 0) return false; this_row = (byte[][]) rows.elementAt(current_row); System.arraycopy(this_row, 0, rowBuffer, 0, this_row.length); return true; } public boolean relative(int rows) throws SQLException { //have to add 1 since absolute expects a 1-based index return absolute(current_row + 1 + rows); } public void setFetchDirection(int direction) throws SQLException { throw new PSQLException("postgresql.psqlnotimp"); } public void setFetchSize(int rows) throws SQLException { // Sub-classes should implement this as part of their cursor support throw org.postgresql.Driver.notImplemented(); } public synchronized void cancelRowUpdates() throws SQLException { if (doingUpdates) { doingUpdates = false; clearRowBuffer(); } } public synchronized void deleteRow() throws SQLException { if ( !isUpdateable() ) { throw new PSQLException( "postgresql.updateable.notupdateable" ); } if (onInsertRow) { throw new PSQLException( "postgresql.updateable.oninsertrow" ); } if (rows.size() == 0) { throw new PSQLException( "postgresql.updateable.emptydelete" ); } if (isBeforeFirst()) { throw new PSQLException( "postgresql.updateable.beforestartdelete" ); } if (isAfterLast()) { throw new PSQLException( "postgresql.updateable.afterlastdelete" ); } int numKeys = primaryKeys.size(); if ( deleteStatement == null ) { StringBuffer deleteSQL = new StringBuffer("DELETE FROM " ).append(tableName).append(" where " ); for ( int i = 0; i < numKeys; i++ ) { deleteSQL.append( ((PrimaryKey) primaryKeys.get(i)).name ).append( " = ? " ); if ( i < numKeys - 1 ) { deleteSQL.append( " and " ); } } deleteStatement = ((java.sql.Connection) connection).prepareStatement(deleteSQL.toString()); } deleteStatement.clearParameters(); for ( int i = 0; i < numKeys; i++ ) { deleteStatement.setObject(i + 1, ((PrimaryKey) primaryKeys.get(i)).getValue()); } deleteStatement.executeUpdate(); rows.removeElementAt(current_row); } public synchronized void insertRow() throws SQLException { if ( !isUpdateable() ) { throw new PSQLException( "postgresql.updateable.notupdateable" ); } if (!onInsertRow) { throw new PSQLException( "postgresql.updateable.notoninsertrow" ); } else { // loop through the keys in the insertTable and create the sql statement // we have to create the sql every time since the user could insert different // columns each time StringBuffer insertSQL = new StringBuffer("INSERT INTO ").append(tableName).append(" ("); StringBuffer paramSQL = new StringBuffer(") values (" ); Enumeration columnNames = updateValues.keys(); int numColumns = updateValues.size(); for ( int i = 0; columnNames.hasMoreElements(); i++ ) { String columnName = (String) columnNames.nextElement(); insertSQL.append( columnName ); if ( i < numColumns - 1 ) { insertSQL.append(", "); paramSQL.append("?,"); } else { paramSQL.append("?)"); } } insertSQL.append(paramSQL.toString()); insertStatement = ((java.sql.Connection) connection).prepareStatement(insertSQL.toString()); Enumeration keys = updateValues.keys(); for ( int i = 1; keys.hasMoreElements(); i++) { String key = (String) keys.nextElement(); insertStatement.setObject(i, updateValues.get( key ) ); } insertStatement.executeUpdate(); if ( usingOID ) { // we have to get the last inserted OID and put it in the resultset long insertedOID = ((AbstractJdbc2Statement) insertStatement).getLastOID(); updateValues.put("oid", new Long(insertedOID) ); } // update the underlying row to the new inserted data updateRowBuffer(); rows.addElement(rowBuffer); // we should now reflect the current data in this_row // that way getXXX will get the newly inserted data this_row = rowBuffer; // need to clear this in case of another insert clearRowBuffer(); } } public synchronized void moveToCurrentRow() throws SQLException { if (!updateable) { throw new PSQLException( "postgresql.updateable.notupdateable" ); } this_row = (byte[][]) rows.elementAt(current_row); rowBuffer = new byte[this_row.length][]; System.arraycopy(this_row, 0, rowBuffer, 0, this_row.length); onInsertRow = false; doingUpdates = false; } public synchronized void moveToInsertRow() throws SQLException { if ( !isUpdateable() ) { throw new PSQLException( "postgresql.updateable.notupdateable" ); } if (insertStatement != null) { insertStatement = null; } // make sure the underlying data is null clearRowBuffer(); onInsertRow = true; doingUpdates = false; } private synchronized void clearRowBuffer() throws SQLException { // rowBuffer is the temporary storage for the row rowBuffer = new byte[fields.length][]; // clear the updateValues hashTable for the next set of updates updateValues.clear(); } public boolean rowDeleted() throws SQLException { // only sub-classes implement CONCURuPDATEABLE throw Driver.notImplemented(); } public boolean rowInserted() throws SQLException { // only sub-classes implement CONCURuPDATEABLE throw Driver.notImplemented(); } public boolean rowUpdated() throws SQLException { // only sub-classes implement CONCURuPDATEABLE throw Driver.notImplemented(); } public synchronized void updateAsciiStream(int columnIndex, java.io.InputStream x, int length ) throws SQLException { if ( !isUpdateable() ) { throw new PSQLException( "postgresql.updateable.notupdateable" ); } byte[] theData = null; try { x.read(theData, 0, length); } catch (NullPointerException ex ) { throw new PSQLException("postgresql.updateable.inputstream"); } catch (IOException ie) { throw new PSQLException("postgresql.updateable.ioerror" + ie); } doingUpdates = !onInsertRow; updateValues.put( fields[columnIndex - 1].getName(), theData ); } public synchronized void updateBigDecimal(int columnIndex, java.math.BigDecimal x ) throws SQLException { if ( !isUpdateable() ) { throw new PSQLException( "postgresql.updateable.notupdateable" ); } doingUpdates = !onInsertRow; updateValues.put( fields[columnIndex - 1].getName(), x ); } public synchronized void updateBinaryStream(int columnIndex, java.io.InputStream x, int length ) throws SQLException { if ( !isUpdateable() ) { throw new PSQLException( "postgresql.updateable.notupdateable" ); } byte[] theData = null; try { x.read(theData, 0, length); } catch ( NullPointerException ex ) { throw new PSQLException("postgresql.updateable.inputstream"); } catch (IOException ie) { throw new PSQLException("postgresql.updateable.ioerror" + ie); } doingUpdates = !onInsertRow; updateValues.put( fields[columnIndex - 1].getName(), theData ); } public synchronized void updateBoolean(int columnIndex, boolean x) throws SQLException { if ( !isUpdateable() ) { throw new PSQLException( "postgresql.updateable.notupdateable" ); } if ( Driver.logDebug ) Driver.debug("updating boolean " + fields[columnIndex - 1].getName() + "=" + x); doingUpdates = !onInsertRow; updateValues.put( fields[columnIndex - 1].getName(), new Boolean(x) ); } public synchronized void updateByte(int columnIndex, byte x) throws SQLException { if ( !isUpdateable() ) { throw new PSQLException( "postgresql.updateable.notupdateable" ); } doingUpdates = true; updateValues.put( fields[columnIndex - 1].getName(), String.valueOf(x) ); } public synchronized void updateBytes(int columnIndex, byte[] x) throws SQLException { if ( !isUpdateable() ) { throw new PSQLException( "postgresql.updateable.notupdateable" ); } doingUpdates = !onInsertRow; updateValues.put( fields[columnIndex - 1].getName(), x ); } public synchronized void updateCharacterStream(int columnIndex, java.io.Reader x, int length ) throws SQLException { if ( !isUpdateable() ) { throw new PSQLException( "postgresql.updateable.notupdateable" ); } char[] theData = null; try { x.read(theData, 0, length); } catch (NullPointerException ex) { throw new PSQLException("postgresql.updateable.inputstream"); } catch (IOException ie) { throw new PSQLException("postgresql.updateable.ioerror" + ie); } doingUpdates = !onInsertRow; updateValues.put( fields[columnIndex - 1].getName(), theData); } public synchronized void updateDate(int columnIndex, java.sql.Date x) throws SQLException { if ( !isUpdateable() ) { throw new PSQLException( "postgresql.updateable.notupdateable" ); } doingUpdates = !onInsertRow; updateValues.put( fields[columnIndex - 1].getName(), x ); } public synchronized void updateDouble(int columnIndex, double x) throws SQLException { if ( !isUpdateable() ) { throw new PSQLException( "postgresql.updateable.notupdateable" ); } if ( Driver.logDebug ) Driver.debug("updating double " + fields[columnIndex - 1].getName() + "=" + x); doingUpdates = !onInsertRow; updateValues.put( fields[columnIndex - 1].getName(), new Double(x) ); } public synchronized void updateFloat(int columnIndex, float x) throws SQLException { if ( !isUpdateable() ) { throw new PSQLException( "postgresql.updateable.notupdateable" ); } if ( Driver.logDebug ) Driver.debug("updating float " + fields[columnIndex - 1].getName() + "=" + x); doingUpdates = !onInsertRow; updateValues.put( fields[columnIndex - 1].getName(), new Float(x) ); } public synchronized void updateInt(int columnIndex, int x) throws SQLException { if ( !isUpdateable() ) { throw new PSQLException( "postgresql.updateable.notupdateable" ); } if ( Driver.logDebug ) Driver.debug("updating int " + fields[columnIndex - 1].getName() + "=" + x); doingUpdates = !onInsertRow; updateValues.put( fields[columnIndex - 1].getName(), new Integer(x) ); } public synchronized void updateLong(int columnIndex, long x) throws SQLException { if ( !isUpdateable() ) { throw new PSQLException( "postgresql.updateable.notupdateable" ); } if ( Driver.logDebug ) Driver.debug("updating long " + fields[columnIndex - 1].getName() + "=" + x); doingUpdates = !onInsertRow; updateValues.put( fields[columnIndex - 1].getName(), new Long(x) ); } public synchronized void updateNull(int columnIndex) throws SQLException { if ( !isUpdateable() ) { throw new PSQLException( "postgresql.updateable.notupdateable" ); } doingUpdates = !onInsertRow; updateValues.put( fields[columnIndex - 1].getName(), null); } public synchronized void updateObject(int columnIndex, Object x) throws SQLException { if ( !isUpdateable() ) { throw new PSQLException( "postgresql.updateable.notupdateable" ); } if ( Driver.logDebug ) Driver.debug("updating object " + fields[columnIndex - 1].getName() + " = " + x); doingUpdates = !onInsertRow; updateValues.put( fields[columnIndex - 1].getName(), x ); } public synchronized void updateObject(int columnIndex, Object x, int scale) throws SQLException { if ( !isUpdateable() ) { throw new PSQLException( "postgresql.updateable.notupdateable" ); } this.updateObject(columnIndex, x); } public void refreshRow() throws SQLException { if ( !isUpdateable() ) { throw new PSQLException( "postgresql.updateable.notupdateable" ); } try { StringBuffer selectSQL = new StringBuffer( "select "); final int numColumns = java.lang.reflect.Array.getLength(fields); for (int i = 0; i < numColumns; i++ ) { selectSQL.append( fields[i].getName() ); if ( i < numColumns - 1 ) { selectSQL.append(", "); } } selectSQL.append(" from " ).append(tableName).append(" where "); int numKeys = primaryKeys.size(); for ( int i = 0; i < numKeys; i++ ) { PrimaryKey primaryKey = ((PrimaryKey) primaryKeys.get(i)); selectSQL.append(primaryKey.name).append("= ?"); if ( i < numKeys - 1 ) { selectSQL.append(" and "); } } if ( Driver.logDebug ) Driver.debug("selecting " + selectSQL.toString()); selectStatement = ((java.sql.Connection) connection).prepareStatement(selectSQL.toString()); for ( int j = 0, i = 1; j < numKeys; j++, i++) { selectStatement.setObject( i, ((PrimaryKey) primaryKeys.get(j)).getValue() ); } AbstractJdbc2ResultSet rs = (AbstractJdbc2ResultSet) selectStatement.executeQuery(); if ( rs.first() ) { rowBuffer = rs.rowBuffer; } rows.setElementAt( rowBuffer, current_row ); if ( Driver.logDebug ) Driver.debug("done updates"); rs.close(); selectStatement.close(); selectStatement = null; } catch (Exception e) { if ( Driver.logDebug ) Driver.debug(e.getClass().getName() + e); throw new SQLException( e.getMessage() ); } } public synchronized void updateRow() throws SQLException { if ( !isUpdateable() ) { throw new PSQLException( "postgresql.updateable.notupdateable" ); } if (doingUpdates) { try { StringBuffer updateSQL = new StringBuffer("UPDATE " + tableName + " SET "); int numColumns = updateValues.size(); Enumeration columns = updateValues.keys(); for (int i = 0; columns.hasMoreElements(); i++ ) { String column = (String) columns.nextElement(); updateSQL.append( column + "= ?"); if ( i < numColumns - 1 ) { updateSQL.append(", "); } } updateSQL.append( " WHERE " ); int numKeys = primaryKeys.size(); for ( int i = 0; i < numKeys; i++ ) { PrimaryKey primaryKey = ((PrimaryKey) primaryKeys.get(i)); updateSQL.append(primaryKey.name).append("= ?"); if ( i < numKeys - 1 ) { updateSQL.append(" and "); } } if ( Driver.logDebug ) Driver.debug("updating " + updateSQL.toString()); updateStatement = ((java.sql.Connection) connection).prepareStatement(updateSQL.toString()); int i = 0; Iterator iterator = updateValues.values().iterator(); for (; iterator.hasNext(); i++) { updateStatement.setObject( i + 1, iterator.next() ); } for ( int j = 0; j < numKeys; j++, i++) { updateStatement.setObject( i + 1, ((PrimaryKey) primaryKeys.get(j)).getValue() ); } updateStatement.executeUpdate(); updateStatement.close(); updateStatement = null; updateRowBuffer(); if ( Driver.logDebug ) Driver.debug("copying data"); System.arraycopy(rowBuffer, 0, this_row, 0, rowBuffer.length); rows.setElementAt( rowBuffer, current_row ); if ( Driver.logDebug ) Driver.debug("done updates"); doingUpdates = false; } catch (Exception e) { if ( Driver.logDebug ) Driver.debug(e.getClass().getName() + e); throw new SQLException( e.getMessage() ); } } } public synchronized void updateShort(int columnIndex, short x) throws SQLException { if ( Driver.logDebug ) Driver.debug("in update Short " + fields[columnIndex - 1].getName() + " = " + x); doingUpdates = !onInsertRow; updateValues.put( fields[columnIndex - 1].getName(), new Short(x) ); } public synchronized void updateString(int columnIndex, String x) throws SQLException { if ( Driver.logDebug ) Driver.debug("in update String " + fields[columnIndex - 1].getName() + " = " + x); doingUpdates = !onInsertRow; updateValues.put( fields[columnIndex - 1].getName(), x ); } public synchronized void updateTime(int columnIndex, Time x) throws SQLException { if ( Driver.logDebug ) Driver.debug("in update Time " + fields[columnIndex - 1].getName() + " = " + x); doingUpdates = !onInsertRow; updateValues.put( fields[columnIndex - 1].getName(), x ); } public synchronized void updateTimestamp(int columnIndex, Timestamp x) throws SQLException { if ( Driver.logDebug ) Driver.debug("updating Timestamp " + fields[columnIndex - 1].getName() + " = " + x); doingUpdates = !onInsertRow; updateValues.put( fields[columnIndex - 1].getName(), x ); } public synchronized void updateNull(String columnName) throws SQLException { updateNull(findColumn(columnName)); } public synchronized void updateBoolean(String columnName, boolean x) throws SQLException { updateBoolean(findColumn(columnName), x); } public synchronized void updateByte(String columnName, byte x) throws SQLException { updateByte(findColumn(columnName), x); } public synchronized void updateShort(String columnName, short x) throws SQLException { updateShort(findColumn(columnName), x); } public synchronized void updateInt(String columnName, int x) throws SQLException { updateInt(findColumn(columnName), x); } public synchronized void updateLong(String columnName, long x) throws SQLException { updateLong(findColumn(columnName), x); } public synchronized void updateFloat(String columnName, float x) throws SQLException { updateFloat(findColumn(columnName), x); } public synchronized void updateDouble(String columnName, double x) throws SQLException { updateDouble(findColumn(columnName), x); } public synchronized void updateBigDecimal(String columnName, BigDecimal x) throws SQLException { updateBigDecimal(findColumn(columnName), x); } public synchronized void updateString(String columnName, String x) throws SQLException { updateString(findColumn(columnName), x); } public synchronized void updateBytes(String columnName, byte x[]) throws SQLException { updateBytes(findColumn(columnName), x); } public synchronized void updateDate(String columnName, java.sql.Date x) throws SQLException { updateDate(findColumn(columnName), x); } public synchronized void updateTime(String columnName, java.sql.Time x) throws SQLException { updateTime(findColumn(columnName), x); } public synchronized void updateTimestamp(String columnName, java.sql.Timestamp x) throws SQLException { updateTimestamp(findColumn(columnName), x); } public synchronized void updateAsciiStream( String columnName, java.io.InputStream x, int length) throws SQLException { updateAsciiStream(findColumn(columnName), x, length); } public synchronized void updateBinaryStream( String columnName, java.io.InputStream x, int length) throws SQLException { updateBinaryStream(findColumn(columnName), x, length); } public synchronized void updateCharacterStream( String columnName, java.io.Reader reader, int length) throws SQLException { updateCharacterStream(findColumn(columnName), reader, length); } public synchronized void updateObject(String columnName, Object x, int scale) throws SQLException { updateObject(findColumn(columnName), x); } public synchronized void updateObject(String columnName, Object x) throws SQLException { updateObject(findColumn(columnName), x); } private int _findColumn( String columnName ) { int i; final int flen = fields.length; for (i = 0; i < flen; ++i) { if (fields[i].getName().equalsIgnoreCase(columnName)) { return (i + 1); } } return -1; } /** * Is this ResultSet updateable? */ boolean isUpdateable() throws SQLException { if (updateable) return true; if ( Driver.logDebug ) Driver.debug("checking if rs is updateable"); parseQuery(); if ( singleTable == false ) { if ( Driver.logDebug ) Driver.debug("not a single table"); return false; } if ( Driver.logDebug ) Driver.debug("getting primary keys"); // Contains the primary key? primaryKeys = new Vector(); // this is not stricty jdbc spec, but it will make things much faster if used // the user has to select oid, * from table and then we will just use oid usingOID = false; int oidIndex = _findColumn( "oid" ); int i = 0; // if we find the oid then just use it if ( oidIndex > 0 ) { i++; primaryKeys.add( new PrimaryKey( oidIndex, "oid" ) ); usingOID = true; } else { // otherwise go and get the primary keys and create a hashtable of keys java.sql.ResultSet rs = ((java.sql.Connection) connection).getMetaData().getPrimaryKeys("", "", tableName); for (; rs.next(); i++ ) { String columnName = rs.getString(4); // get the columnName int index = findColumn( columnName ); if ( index > 0 ) { primaryKeys.add( new PrimaryKey(index, columnName ) ); // get the primary key information } } rs.close(); } numKeys = primaryKeys.size(); if ( Driver.logDebug ) Driver.debug( "no of keys=" + i ); if ( i < 1 ) { throw new SQLException("No Primary Keys"); } updateable = primaryKeys.size() > 0; if ( Driver.logDebug ) Driver.debug( "checking primary key " + updateable ); return updateable; } public void parseQuery() { String[] l_sqlFragments = ((AbstractJdbc2Statement)statement).getSqlFragments(); String l_sql = l_sqlFragments[0]; StringTokenizer st = new StringTokenizer(l_sql, " \r\t"); boolean tableFound = false, tablesChecked = false; String name = ""; singleTable = true; while ( !tableFound && !tablesChecked && st.hasMoreTokens() ) { name = st.nextToken(); if ( !tableFound ) { if (name.toLowerCase().equals("from")) { tableName = st.nextToken(); tableFound = true; } } else { tablesChecked = true; // if the very next token is , then there are multiple tables singleTable = !name.equalsIgnoreCase(","); } } } private void updateRowBuffer() throws SQLException { Enumeration columns = updateValues.keys(); while ( columns.hasMoreElements() ) { String columnName = (String) columns.nextElement(); int columnIndex = _findColumn( columnName ) - 1; switch ( connection.getSQLType( fields[columnIndex].getPGType() ) ) { case Types.DECIMAL: case Types.BIGINT: case Types.DOUBLE: case Types.BIT: case Types.VARCHAR: case Types.DATE: case Types.TIME: case Types.TIMESTAMP: case Types.SMALLINT: case Types.FLOAT: case Types.INTEGER: case Types.CHAR: case Types.NUMERIC: case Types.REAL: case Types.TINYINT: try { rowBuffer[columnIndex] = String.valueOf( updateValues.get( columnName ) ).getBytes(connection.getEncoding().name() ); } catch ( UnsupportedEncodingException ex) { throw new SQLException("Unsupported Encoding " + connection.getEncoding().name()); } case Types.NULL: continue; default: rowBuffer[columnIndex] = (byte[]) updateValues.get( columnName ); } } } public void setStatement(Statement statement) { this.statement = statement; } private class PrimaryKey { int index; // where in the result set is this primaryKey String name; // what is the columnName of this primary Key PrimaryKey( int index, String name) { this.index = index; this.name = name; } Object getValue() throws SQLException { return getObject(index); } }; }
package com.powerdata.openpa.pwrflow; import java.io.File; import java.util.AbstractList; import java.util.Arrays; import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.Set; import com.powerdata.openpa.ACBranch; import com.powerdata.openpa.ACBranchListIfc; import com.powerdata.openpa.CloneModelBuilder; import com.powerdata.openpa.ColumnMeta; import com.powerdata.openpa.Gen; import com.powerdata.openpa.LineList; import com.powerdata.openpa.PAModel; import com.powerdata.openpa.PAModelException; import com.powerdata.openpa.PflowModelBuilder; import com.powerdata.openpa.impl.GenListI; import com.powerdata.openpa.impl.LoadListI; /** * Remedial adaptive topology control (RATC) * * Evaluate power system to recommend switching actions that will alleviate flow * on specified branch by calculating a set of Line Outage Distribution Factors (LODF) * and applying them to the solved flows * * * * The algorithm works as follows: * * <ol> * <li>Fabricate and place 100MW flow across selected branch</li> * <li>Solve flows for fabricated case</li> * <li>Calculate fraction of flow in target branch</li> * <li>Assign remaining fracction to network, NF</li> * <li>LODF for each Line (branch, actually), = flow / 100 / NF</li> * </ol> * * @author chris@powerdata.com * */ public class RATCWorker { protected PAModel _model; protected ACBranch _targ; protected BusRefIndex _bri; protected BusTypeUtil _btu; protected boolean _swapgenside = false; @SuppressWarnings("deprecation") public RATCWorker(PAModel model, ACBranch target) throws PAModelException { System.out.format("Target: %s\n", target.getName()); _model = model; _targ = target; if (_targ.getFromP() < 0f) _swapgenside = true; _bri = BusRefIndex.CreateFromSingleBus(model); FDPowerFlow pf = new FDPowerFlow(model, _bri); pf.runPF(); pf.updateResults(); // try // new ListDumper().dump(_model, new File("/run/shm/actest")); // catch (IOException | ReflectiveOperationException | RuntimeException e) // // TODO Auto-generated catch block // e.printStackTrace(); //TODO: make the bus type util creation external to the ac power flow _btu = pf.getBusTypes(); } float[] _lodf, _ratc; ACBranchListIfc<? extends ACBranch> _branches; public void runRATC() throws PAModelException { RATCModelBuilder rmb = new RATCModelBuilder(_model); PAModel dcmodel = rmb.load(); DCPowerFlow dcpf = new DCPowerFlow(dcmodel, _bri, _btu); dcpf.runPF().updateResults(); // try // new ListDumper().dump(dcmodel, new File("/run/shm/dctest")); // catch (IOException | ReflectiveOperationException | RuntimeException e) // // TODO Auto-generated catch block // e.printStackTrace(); int nlodf = _model.getLines().size(); _lodf = new float[nlodf]; _ratc = new float[nlodf]; // TODO: Update to support all AC branches LineList dclineflow = dcmodel.getLines(), aclineflow = _model.getLines(); _branches = aclineflow; ACBranch dctarg = dclineflow.get(_targ.getIndex()); /** fraction of artificial 100MW flow across target */ float lnfact = Math.abs(dctarg.getFromP())/100f; _lodf[_targ.getIndex()] = lnfact; float netfrac = 1f-lnfact; float div = 1f/(100f*netfrac); for(int i=0; i < nlodf; ++i) { if (i != _targ.getIndex()) { ACBranch dc = dclineflow.get(i), ac = aclineflow.get(i); _lodf[i] = dc.getFromP() * div; _ratc[i] = _lodf[i] * ac.getFromP(); } } // try // File dir = new File("/run/shm"); // PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(new File(dir, "lodf-palco.csv")))); // pw.println("LineName,X,ACFlow(MW),LODF,RATC Order"); // for(int i=0; i < nlodf; ++i) // ACBranch ac = aclineflow.get(i); // pw.format("\"%s\",%f,%f,%f,%f\n", // ac.getName(), ac.getX(), ac.getFromP(), _lodf[i], _ratc[i]); // pw.close(); // catch(Exception x) // x.printStackTrace(); } public class Result implements Comparable<Result> { int _ndx; Result(int ndx) {_ndx = ndx;} public ACBranch getBranch() {return _branches.get(_ndx);} public float getLODF() {return _lodf[_ndx];} public float getOrder() {return _ratc[_ndx];} @Override public int compareTo(Result o) { return Float.compare(getOrder(), o.getOrder()); } } public List<Result> getResults() { List<Result> rv = new AbstractList<Result>() { @Override public Result get(int index) {return new Result(index);} @Override public int size() {return _branches.size();} }; return rv; } /** * Create a model builder that can provide a model configured with only a * single generate and load on either side of the target branch * * @author chris@powerdata.com * */ class RATCModelBuilder extends CloneModelBuilder { @Override protected void loadPrep() { super.loadPrep(); /* replace entries to return our fabricated data */ DataLoader<String[]> gname = () -> new String[] {"RATC_SRC"}; DataLoader<float[]> fzero = () -> new float[] {0f}; DataLoader<float[]> f200 = () -> new float[] {200f}; DataLoader<int[]> fbus = () -> new int[] {_targ.getFromBus().getIndex()}; DataLoader<int[]> tbus = () -> new int[] {_targ.getToBus().getIndex()}; DataLoader<boolean[]> oos = () -> new boolean[] {false}; DataLoader<int[]> genbus=fbus, loadbus=tbus; if (_swapgenside) { genbus = tbus; loadbus = fbus; } _col.put(ColumnMeta.GenID, gname); _col.put(ColumnMeta.GenNAME, gname); _col.put(ColumnMeta.GenBUS, genbus); _col.put(ColumnMeta.GenP, fzero); _col.put(ColumnMeta.GenQ, fzero); _col.put(ColumnMeta.GenOOS, oos); _col.put(ColumnMeta.GenTYPE, () -> new Gen.Type[] {Gen.Type.Thermal}); _col.put(ColumnMeta.GenMODE, () -> new Gen.Mode[] {Gen.Mode.MAN}); _col.put(ColumnMeta.GenOPMINP, fzero); _col.put(ColumnMeta.GenOPMAXP, f200); _col.put(ColumnMeta.GenMINQ, () -> new float[] {-100f}); _col.put(ColumnMeta.GenMAXQ, f200); _col.put(ColumnMeta.GenPS, () -> new float[] {100f}); _col.put(ColumnMeta.GenQS, fzero); _col.put(ColumnMeta.GenAVR, () -> new boolean[] {true}); _col.put(ColumnMeta.GenVS, () -> new float[] {1f}); _col.put(ColumnMeta.GenREGBUS, genbus); DataLoader<String[]> lname = () -> new String[] {"RATC_LOAD"}; DataLoader<float[]> pld = () -> new float[]{-100f}; DataLoader<float[]> qld = () -> new float[]{-10f}; _col.put(ColumnMeta.LoadID, lname); _col.put(ColumnMeta.LoadNAME, lname); _col.put(ColumnMeta.LoadBUS, loadbus); _col.put(ColumnMeta.LoadP, pld); _col.put(ColumnMeta.LoadQ, qld); _col.put(ColumnMeta.LoadOOS, oos); _col.put(ColumnMeta.LoadPMAX, pld); _col.put(ColumnMeta.LoadQMAX, qld); } @Override protected LoadListI loadLoads() throws PAModelException { return new LoadListI(_m, 1); } @Override protected GenListI loadGens() throws PAModelException { return new GenListI(_m, 1); } public RATCModelBuilder(PAModel srcmdl) { super(srcmdl, _localCols); // TODO Auto-generated constructor stub } } static Set<ColumnMeta> _localCols = EnumSet.copyOf(Arrays.asList(new ColumnMeta[] { ColumnMeta.BusVM, ColumnMeta.BusVA, ColumnMeta.ShcapQ, ColumnMeta.ShreacQ, ColumnMeta.SvcQ, ColumnMeta.LinePFROM, ColumnMeta.LinePTO, ColumnMeta.LineQFROM, ColumnMeta.LineQTO, ColumnMeta.SercapPFROM, ColumnMeta.SercapPTO, ColumnMeta.SercapQFROM, ColumnMeta.SercapQTO, ColumnMeta.SerreacPFROM, ColumnMeta.SerreacPTO, ColumnMeta.SerreacQFROM, ColumnMeta.SerreacQTO, ColumnMeta.PhashPFROM, ColumnMeta.PhashPTO, ColumnMeta.PhashQFROM, ColumnMeta.PhashQTO, ColumnMeta.TfmrPFROM, ColumnMeta.TfmrPTO, ColumnMeta.TfmrQFROM, ColumnMeta.TfmrQTO, })); public static void main(String[] args) throws Exception { String uri = null; File poutdir = new File(System.getProperty("user.dir")); for(int i=0; i < args.length;) { String s = args[i++].toLowerCase(); int ssx = 1; if (s.startsWith("--")) ++ssx; switch(s.substring(ssx)) { case "uri": uri = args[i++]; break; case "outdir": poutdir = new File(args[i++]); break; } } if (uri == null) { System.err.format("Usage: -uri model_uri " + "[ --outdir output_directory (deft to $CWD ]\n"); System.exit(1); } final File outdir = poutdir; if (!outdir.exists()) outdir.mkdirs(); PflowModelBuilder bldr = PflowModelBuilder.Create(uri); bldr.enableFlatVoltage(true); bldr.setLeastX(0.0001f); PAModel base = bldr.load(); RATCWorker rw = new RATCWorker(base, base.getLines().getByKey(6512)); rw.runRATC(); // new ListDumper().dump(rmb.load(), outdir); } }
/* * $Id: TestPublicationDate.java,v 1.11 2012-07-27 13:21:13 pgust Exp $ */ package org.lockss.daemon; import java.util.*; import org.lockss.test.*; /** * Test class for org.lockss.util.ArrayIterator */ public class TestPublicationDate extends LockssTestCase { /** * Test big-endian date formats that put year first, month second, and day last. */ public void testBigEndian() { assertEquals("2010-03-13", PublicationDate.parse("2010.3.13",Locale.US).toString()); assertEquals("2010-03", PublicationDate.parse("2010.3",Locale.US).toString()); assertEquals("2010-03-13", PublicationDate.parse("2010.3.13",Locale.US).toString()); assertEquals("2010-03-13", PublicationDate.parse("2010-3-13",Locale.US).toString()); assertEquals("2010-03", PublicationDate.parse("2010-3",Locale.US).toString()); assertEquals("2010-03-13", PublicationDate.parse("2010 March 13",Locale.US).toString()); assertEquals("2010-03-13", PublicationDate.parse("2010. March, 13",Locale.US).toString()); assertEquals("2010-03-13", PublicationDate.parse("2010 March 13th",Locale.US).toString()); assertEquals("2010-03-13", PublicationDate.parse("2010 13 marzo",Locale.ITALY).toString()); assertEquals("2010-03-13", PublicationDate.parse("2010/3/13",Locale.US).toString()); assertEquals("2010-03-13", PublicationDate.parse("2010/3/13",Locale.UK).toString()); assertEquals("2010-03-13", PublicationDate.parse("2010/March/13",Locale.US).toString()); assertEquals("2010-03-13", PublicationDate.parse("2010/M\u00e4rz/13",Locale.GERMANY).toString()); // a-umlaut assertEquals("2010-03-13", PublicationDate.parse("2010/Mar./13",Locale.US).toString()); assertEquals("2010-03-13", PublicationDate.parse("2010/Mar./13",Locale.US).toString()); assertEquals("2010-03", PublicationDate.parse("2010/3",Locale.US).toString()); assertEquals("2010-03", PublicationDate.parse("2010/Mar",Locale.US).toString()); assertEquals("2010-03-13", PublicationDate.parse("2010-Mar-13, Sunday",Locale.US).toString()); assertEquals("2010-Q1", PublicationDate.parse("2010-Q1",Locale.US).toString()); } /** * Test little-endian date formats that put day first, month second, and year last. */ public void testLittleEndian() { assertEquals("2010-03", PublicationDate.parse("Mar 2010",Locale.US).toString()); assertEquals("2010-03", PublicationDate.parse("Mar., 2010",Locale.US).toString()); // "May-June 2010", // -> 2010-05 ?? // "May/Jun 2010", // -> 2010-05 ?? assertEquals("2010-03-13", PublicationDate.parse("13 Mar 2010",Locale.US).toString()); assertEquals("2010-03-13", PublicationDate.parse("13th March 2010",Locale.US).toString()); assertEquals("2010-S2", PublicationDate.parse("Summer Quarter, 2010",Locale.US).toString()); assertEquals("2010-S2", PublicationDate.parse("Summer 2010",Locale.US).toString()); // assertEquals("2010-S1", PublicationDate.parse("Fr\u00fchling, 2010",Locale.GERMANY).toString()); // u-mlaut // assertEquals("2010-Q2", PublicationDate.parse("2 \u00ba trimestre, 2010",Locale.ITALY).toString()); // ordinal indicator // "Summer-Fall 2010", // 2010 2X (non-standard) ?? // "Summer/Fall 2010", // 2010 2X (non-standard) ?? assertEquals("2010-Q1", PublicationDate.parse("First Quarter 2010",Locale.US).toString()); assertEquals("2010-Q1", PublicationDate.parse("First Quarter, 2010",Locale.US).toString()); assertEquals("2010-Q1", PublicationDate.parse("ersten Quartal 2010",Locale.GERMANY).toString()); assertEquals("2010-Q1", PublicationDate.parse("1st Quarter 2010",Locale.US).toString()); assertEquals("2010-Q1", PublicationDate.parse("Quarter 1 2010",Locale.US).toString()); assertEquals("2010-Q1", PublicationDate.parse("Quarter 1, 2010",Locale.US).toString()); assertEquals("2010-Q1", PublicationDate.parse("Quarter One 2010",Locale.US).toString()); assertEquals("2010-Q1", PublicationDate.parse("1Q 2010",Locale.US).toString()); assertEquals("2010-Q1", PublicationDate.parse("Q1 2010",Locale.US).toString()); assertEquals("2010-Q1", PublicationDate.parse("Q1/2010",Locale.US).toString()); } /** * Test middle-endian date formats that put month first, day second, and year third. * This form is peculiar to the US English locale. */ public void testMiddleEndian() { assertEquals("2010-03-13", PublicationDate.parse("March 13, 2010",Locale.US).toString()); assertEquals("2010-03-13", PublicationDate.parse("Mar. 13, 2010",Locale.US).toString()); assertEquals("2010-03-13", PublicationDate.parse("13 Mar. 2010",Locale.US).toString()); assertEquals("2010-03-13", PublicationDate.parse("13 Mar., 2010",Locale.US).toString()); assertEquals("2010-03-13", PublicationDate.parse("Mar 13th, 2010",Locale.US).toString()); assertEquals("2010-03-13", PublicationDate.parse("Mar 13th, 2010",Locale.UK).toString()); assertEquals("2010-03-13", PublicationDate.parse("3/13/2010",Locale.US).toString()); assertEquals("2010-03-13", PublicationDate.parse("Mar/13/2010",Locale.US).toString()); assertEquals("2010-03-13", PublicationDate.parse("Mar./13/2010",Locale.US).toString()); assertEquals("2010-03-13", PublicationDate.parse("Mar.13.2010",Locale.US).toString()); assertEquals("2010-03-13", PublicationDate.parse("Mar.13.2010",Locale.UK).toString()); assertEquals("2010-03-13", PublicationDate.parse("Mar.13.2010",Locale.UK).toString()); assertEquals("2010-03-13", PublicationDate.parse("3.13.2010",Locale.US).toString()); assertEquals("2010-03-13", PublicationDate.parse("March.13.2010",Locale.US).toString()); } /** * Test bad date formats */ public void testBad() { assertEquals("0", PublicationDate.parse("20111226").toString()); assertEquals("0", PublicationDate.parse("funky.chicken").toString()); assertEquals("0", PublicationDate.parse("MCM").toString()); } }
package org.spongycastle.bcpg; import java.io.ByteArrayOutputStream; import java.io.IOException; /** * basic packet for a PGP secret key */ public class SecretKeyPacket extends ContainedPacket implements PublicKeyAlgorithmTags { public static final int USAGE_NONE = 0x00; public static final int USAGE_CHECKSUM = 0xff; public static final int USAGE_SHA1 = 0xfe; private PublicKeyPacket pubKeyPacket; private byte[] secKeyData; private int s2kUsage; private int encAlgorithm; private S2K s2k; private byte[] iv; /** * * @param in * @throws IOException */ SecretKeyPacket( BCPGInputStream in) throws IOException { if (this instanceof SecretSubkeyPacket) { pubKeyPacket = new PublicSubkeyPacket(in); } else { pubKeyPacket = new PublicKeyPacket(in); } s2kUsage = in.read(); if (s2kUsage == USAGE_CHECKSUM || s2kUsage == USAGE_SHA1) { encAlgorithm = in.read(); s2k = new S2K(in); } else { encAlgorithm = s2kUsage; } // For the GNU divert-to-card type, the serial number of the card is stored in the IV if (s2k != null && s2k.getType() == S2K.GNU_DUMMY_S2K && s2k.getProtectionMode() == 0x02) { int len = in.read(); iv = new byte[len]; in.readFully(iv); } else if (!(s2k != null && s2k.getType() == S2K.GNU_DUMMY_S2K && s2k.getProtectionMode() == 0x01)) { if (s2kUsage != 0) { if (encAlgorithm < 7) { iv = new byte[8]; } else { iv = new byte[16]; } in.readFully(iv, 0, iv.length); } } this.secKeyData = in.readAll(); } /** * * @param pubKeyPacket * @param encAlgorithm * @param s2k * @param iv * @param secKeyData */ public SecretKeyPacket( PublicKeyPacket pubKeyPacket, int encAlgorithm, S2K s2k, byte[] iv, byte[] secKeyData) { this.pubKeyPacket = pubKeyPacket; this.encAlgorithm = encAlgorithm; if (encAlgorithm != SymmetricKeyAlgorithmTags.NULL) { this.s2kUsage = USAGE_CHECKSUM; } else { this.s2kUsage = USAGE_NONE; } this.s2k = s2k; this.iv = iv; this.secKeyData = secKeyData; } public SecretKeyPacket( PublicKeyPacket pubKeyPacket, int encAlgorithm, int s2kUsage, S2K s2k, byte[] iv, byte[] secKeyData) { this.pubKeyPacket = pubKeyPacket; this.encAlgorithm = encAlgorithm; this.s2kUsage = s2kUsage; this.s2k = s2k; this.iv = iv; this.secKeyData = secKeyData; } public int getEncAlgorithm() { return encAlgorithm; } public int getS2KUsage() { return s2kUsage; } public byte[] getIV() { return iv; } public S2K getS2K() { return s2k; } public PublicKeyPacket getPublicKeyPacket() { return pubKeyPacket; } public byte[] getSecretKeyData() { return secKeyData; } public byte[] getEncodedContents() throws IOException { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); BCPGOutputStream pOut = new BCPGOutputStream(bOut); pOut.write(pubKeyPacket.getEncodedContents()); pOut.write(s2kUsage); if (s2kUsage == USAGE_CHECKSUM || s2kUsage == USAGE_SHA1) { pOut.write(encAlgorithm); pOut.writeObject(s2k); } if (iv != null) { // If this is a divert-to-card, write the length of the serial number at the start of the iv if (s2k != null && s2k.getType() == S2K.GNU_DUMMY_S2K && s2k.getProtectionMode() == S2K.GNU_PROTECTION_MODE_DIVERT_TO_CARD) { pOut.write(iv.length); } pOut.write(iv); } if (secKeyData != null && secKeyData.length > 0) { pOut.write(secKeyData); } return bOut.toByteArray(); } public void encode( BCPGOutputStream out) throws IOException { out.writePacket(SECRET_KEY, getEncodedContents(), true); } }
package com.intellij.util; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.ThrowableComputable; import com.intellij.openapi.util.registry.Registry; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import java.util.HashSet; import java.util.Set; public final class SlowOperations { private static final Logger LOG = Logger.getInstance(SlowOperations.class); private static final Set<String> ourReportedTraces = new HashSet<>(); private static final String[] misbehavingFrames = { "org.jetbrains.kotlin.idea.refactoring.introduce.introduceVariable.KotlinIntroduceVariableHandler", "org.jetbrains.kotlin.idea.actions.KotlinAddImportAction", "org.jetbrains.kotlin.idea.codeInsight.KotlinCopyPasteReferenceProcessor", "com.intellij.apiwatcher.plugin.presentation.bytecode.UsageHighlighter", }; private static boolean ourAllowedFlag = System.getenv("TEAMCITY_VERSION") != null; private SlowOperations() {} /** * If you get an exception from this method, then you need to move the computation to the background * while also trying to avoid blocking the UI thread as well. It's okay if the API changes in the process, * e.g. instead of wrapping implementation of some extension into {@link #allowSlowOperations}, * it's better to admit that the EP semantic as a whole requires index access, * and then move the iteration over all extensions to the background on the platform-side. * <p/> * In cases when it's impossible to do so, the computation should be wrapped into {@code allowSlowOperations} explicitly. * This way it's possible to find all such operations by searching usages of {@code allowSlowOperations}. * * @see com.intellij.openapi.application.NonBlockingReadAction * @see com.intellij.openapi.application.CoroutinesKt#readAction * @see com.intellij.openapi.actionSystem.ex.ActionUtil#underModalProgress */ public static void assertSlowOperationsAreAllowed() { if (ourAllowedFlag) { return; } if (Registry.is("ide.enable.slow.operations.in.edt")) { return; } Application application = ApplicationManager.getApplication(); if (application.isUnitTestMode() || !application.isDispatchThread() || application.isWriteAccessAllowed()) { return; } String stackTrace = ExceptionUtil.currentStackTrace(); if (ContainerUtil.or(misbehavingFrames, stackTrace::contains) || !ourReportedTraces.add(stackTrace)) { return; } LOG.error("Slow operations are prohibited in the EDT"); } public static <T, E extends Throwable> T allowSlowOperations(@NotNull ThrowableComputable<T, E> computable) throws E { if (ourAllowedFlag || !ApplicationManager.getApplication().isDispatchThread()) { return computable.compute(); } ourAllowedFlag = true; try { return computable.compute(); } finally { ourAllowedFlag = false; } } public static <E extends Throwable> void allowSlowOperations(@NotNull ThrowableRunnable<E> runnable) throws E { allowSlowOperations(() -> { runnable.run(); return null; }); } }
package com.intellij.ui; import com.intellij.icons.AllIcons; import com.intellij.openapi.util.Key; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import javax.swing.CellRendererPane; import javax.swing.Icon; import javax.swing.Timer; import java.awt.AlphaComposite; import java.awt.Component; import java.awt.Composite; import java.awt.Graphics; import java.awt.Graphics2D; import java.util.List; import static com.intellij.openapi.util.IconLoader.getDisabledIcon; import static com.intellij.util.ObjectUtils.notNull; import static java.util.Arrays.asList; /** * @author Sergey.Malenkov */ public class AnimatedIcon implements Icon { /** * This key is used to allow animated icons in lists, tables and trees. * If the corresponding client property is set to {@code true} the corresponding component * will be automatically repainted to update an animated icon painted by the renderer of the component. * Note, that animation may cause a performance problems and should not be used everywhere. * * @see UIUtil#putClientProperty */ @ApiStatus.Experimental public static final Key<Boolean> ANIMATION_IN_RENDERER_ALLOWED = Key.create("ANIMATION_IN_RENDERER_ALLOWED"); public interface Frame { @NotNull Icon getIcon(); int getDelay(); } public static class Default extends AnimatedIcon { public Default() { super(DELAY, ICONS.toArray(new Icon[0])); } public static final int DELAY = 130; public static final List<Icon> ICONS = asList( AllIcons.Process.Step_1, AllIcons.Process.Step_2, AllIcons.Process.Step_3, AllIcons.Process.Step_4, AllIcons.Process.Step_5, AllIcons.Process.Step_6, AllIcons.Process.Step_7, AllIcons.Process.Step_8); } public static class Big extends AnimatedIcon { public Big() { super(DELAY, ICONS.toArray(new Icon[0])); } public static final int DELAY = 130; public static final List<Icon> ICONS = asList( AllIcons.Process.Big.Step_1, AllIcons.Process.Big.Step_2, AllIcons.Process.Big.Step_3, AllIcons.Process.Big.Step_4, AllIcons.Process.Big.Step_5, AllIcons.Process.Big.Step_6, AllIcons.Process.Big.Step_7, AllIcons.Process.Big.Step_8); } public static class Recording extends AnimatedIcon { public Recording() { super(DELAY, ICONS.toArray(new Icon[0])); } public static final int DELAY = 250; public static final List<Icon> ICONS = asList( AllIcons.Ide.Macro.Recording_1, AllIcons.Ide.Macro.Recording_2, AllIcons.Ide.Macro.Recording_3, AllIcons.Ide.Macro.Recording_4); } @Deprecated public static class Grey extends AnimatedIcon { public Grey() { super(DELAY, ICONS.toArray(new Icon[0])); } public static final int DELAY = 130; public static final List<Icon> ICONS = asList( AllIcons.Process.State.GreyProgr_1, AllIcons.Process.State.GreyProgr_2, AllIcons.Process.State.GreyProgr_3, AllIcons.Process.State.GreyProgr_4, AllIcons.Process.State.GreyProgr_5, AllIcons.Process.State.GreyProgr_6, AllIcons.Process.State.GreyProgr_7, AllIcons.Process.State.GreyProgr_8); } @ApiStatus.Experimental public static class FS extends AnimatedIcon { public FS() { super(DELAY, ICONS.toArray(new Icon[0])); } public static final int DELAY = 50; public static final List<Icon> ICONS = asList( AllIcons.Process.FS.Step_1, AllIcons.Process.FS.Step_2, AllIcons.Process.FS.Step_3, AllIcons.Process.FS.Step_4, AllIcons.Process.FS.Step_5, AllIcons.Process.FS.Step_6, AllIcons.Process.FS.Step_7, AllIcons.Process.FS.Step_8, AllIcons.Process.FS.Step_9, AllIcons.Process.FS.Step_10, AllIcons.Process.FS.Step_11, AllIcons.Process.FS.Step_12, AllIcons.Process.FS.Step_13, AllIcons.Process.FS.Step_14, AllIcons.Process.FS.Step_15, AllIcons.Process.FS.Step_16, AllIcons.Process.FS.Step_17, AllIcons.Process.FS.Step_18); } @ApiStatus.Experimental public static class Blinking extends AnimatedIcon { public Blinking(@NotNull Icon icon) { this(1000, icon); } public Blinking(int delay, @NotNull Icon icon) { super(delay, icon, notNull(getDisabledIcon(icon), icon)); } } @ApiStatus.Experimental public static class Fading extends AnimatedIcon { public Fading(@NotNull Icon icon) { this(1000, icon); } public Fading(int period, @NotNull Icon icon) { super(50, new Icon() { private final long time = System.currentTimeMillis(); @Override public int getIconWidth() { return icon.getIconWidth(); } @Override public int getIconHeight() { return icon.getIconHeight(); } @Override public void paintIcon(Component c, Graphics g, int x, int y) { assert period > 0 : "unexpected"; long time = (System.currentTimeMillis() - this.time) % period; float alpha = (float)((Math.cos(2 * Math.PI * time / period) + 1) / 2); if (alpha > 0) { Runnable restore = null; if (alpha < 1 && g instanceof Graphics2D) { Graphics2D g2d = (Graphics2D)g; Composite old = g2d.getComposite(); restore = () -> g2d.setComposite(old); g2d.setComposite(AlphaComposite.SrcAtop.derive(alpha)); } icon.paintIcon(c, g, x, y); if (restore != null) restore.run(); } } }); } } private final Frame[] frames; private boolean requested; private long time; private int index; public AnimatedIcon(int delay, @NotNull Icon... icons) { this(getFrames(delay, icons)); } public AnimatedIcon(@NotNull Frame... frames) { this.frames = frames; assert frames.length > 0 : "empty array"; for (Frame frame : frames) assert frame != null : "null animation frame"; time = System.currentTimeMillis(); } private static Frame[] getFrames(int delay, @NotNull Icon... icons) { int length = icons.length; assert length > 0 : "empty array"; Frame[] frames = new Frame[length]; for (int i = 0; i < length; i++) { Icon icon = icons[i]; assert icon != null : "null icon"; frames[i] = new Frame() { @NotNull @Override public Icon getIcon() { return icon; } @Override public int getDelay() { return delay; } }; } return frames; } private void updateFrameAt(long current) { int next = index + 1; index = next < frames.length ? next : 0; time = current; } @NotNull private Icon getUpdatedIcon() { int index = getCurrentIndex(); return frames[index].getIcon(); } private int getCurrentIndex() { long current = System.currentTimeMillis(); Frame frame = frames[index]; if (frame.getDelay() <= (current - time)) updateFrameAt(current); return index; } private void requestRefresh(Component c) { if (!requested && canRefresh(c)) { Frame frame = frames[index]; int delay = frame.getDelay(); if (delay > 0) { requested = true; Timer timer = new Timer(delay, event -> { requested = false; if (canRefresh(c)) { doRefresh(c); } }); timer.setRepeats(false); timer.start(); } else { doRefresh(c); } } } @Override public final void paintIcon(Component c, Graphics g, int x, int y) { Icon icon = getUpdatedIcon(); CellRendererPane pane = UIUtil.getParentOfType(CellRendererPane.class, c); requestRefresh(pane == null ? c : getRendererOwner(pane.getParent())); icon.paintIcon(c, g, x, y); } @Override public final int getIconWidth() { return getUpdatedIcon().getIconWidth(); } @Override public final int getIconHeight() { return getUpdatedIcon().getIconHeight(); } protected boolean canRefresh(Component component) { return component != null && component.isShowing(); } protected void doRefresh(Component component) { if (component != null) component.repaint(); } protected Component getRendererOwner(Component component) { return UIUtil.isClientPropertyTrue(component, ANIMATION_IN_RENDERER_ALLOWED) ? component : null; } }
package com.intellij.openapi.util; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.IconLoader.CachedImageIcon.HandleNotFound; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.reference.SoftReference; import com.intellij.ui.RetrievableIcon; import com.intellij.ui.paint.PaintUtil.RoundingMode; import com.intellij.util.*; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.FixedHashMap; import com.intellij.util.ui.ImageUtil; import com.intellij.util.ui.JBImageIcon; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.JBUI.BaseScaleContext.UpdateListener; import com.intellij.util.ui.JBUI.RasterJBIcon; import com.intellij.util.ui.JBUI.ScaleContext; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.*; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.awt.image.ImageFilter; import java.awt.image.RGBImageFilter; import java.lang.ref.Reference; import java.lang.reflect.Field; import java.net.URL; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicReference; import static com.intellij.util.ui.JBUI.ScaleType.*; public final class IconLoader { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.util.IconLoader"); private static final String LAF_PREFIX = "/com/intellij/ide/ui/laf/icons/"; private static final String ICON_CACHE_URL_KEY = "ICON_CACHE_URL_KEY"; // the key: Pair(ICON_CACHE_URL_KEY, url) or Pair(path, classLoader) private static final ConcurrentMap<Pair<String, Object>, CachedImageIcon> ourIconsCache = ContainerUtil.newConcurrentMap(100, 0.9f, 2); /** * This cache contains mapping between icons and disabled icons. */ private static final Map<Icon, Icon> ourIcon2DisabledIcon = ContainerUtil.createWeakMap(200); private static volatile boolean STRICT_GLOBAL; private static final ThreadLocal<Boolean> STRICT_LOCAL = new ThreadLocal<Boolean>() { @Override protected Boolean initialValue() { return false; } @Override public Boolean get() { if (STRICT_GLOBAL) return true; return super.get(); } }; private static final AtomicReference<IconTransform> ourTransform = new AtomicReference<IconTransform>(IconTransform.getDefault()); static { installPathPatcher(new DeprecatedDuplicatesIconPathPatcher()); } private static final ImageIcon EMPTY_ICON = new ImageIcon(UIUtil.createImage(1, 1, BufferedImage.TYPE_3BYTE_BGR)) { @NonNls public String toString() { return "Empty icon " + super.toString(); } }; private static boolean ourIsActivated; private IconLoader() { } public static <T, E extends Throwable> T performStrictly(ThrowableComputable<T, E> computable) throws E { STRICT_LOCAL.set(true); try { return computable.compute(); } finally { STRICT_LOCAL.set(false); } } public static void setStrictGlobally(boolean strict) { STRICT_GLOBAL = strict; } private static void updateTransform(Function<IconTransform, IconTransform> updater) { IconTransform prev, next; do { prev = ourTransform.get(); next = updater.fun(prev); } while (!ourTransform.compareAndSet(prev, next)); if (prev != next) { ourIconsCache.clear(); ourIcon2DisabledIcon.clear(); ImageLoader.clearCache(); //clears svg cache } } public static void installPathPatcher(@NotNull final IconPathPatcher patcher) { updateTransform(new Function<IconTransform, IconTransform>() { @Override public IconTransform fun(IconTransform transform) { return transform.withPathPatcher(patcher); } }); } public static void removePathPatcher(@NotNull final IconPathPatcher patcher) { updateTransform(new Function<IconTransform, IconTransform>() { @Override public IconTransform fun(IconTransform transform) { return transform.withoutPathPatcher(patcher); } }); } @Deprecated @NotNull public static Icon getIcon(@NotNull final Image image) { return new JBImageIcon(image); } public static void setUseDarkIcons(final boolean useDarkIcons) { updateTransform(new Function<IconTransform, IconTransform>() { @Override public IconTransform fun(IconTransform transform) { return transform.withDark(useDarkIcons); } }); } public static void setFilter(final ImageFilter filter) { updateTransform(new Function<IconTransform, IconTransform>() { @Override public IconTransform fun(IconTransform transform) { return transform.withFilter(filter); } }); } public static void clearCache() { updateTransform(new Function<IconTransform, IconTransform>() { @Override public IconTransform fun(IconTransform transform) { // Copy the transform to trigger update of cached icons return transform.copy(); } }); } //TODO[kb] support iconsets //public static Icon getIcon(@NotNull final String path, @NotNull final String darkVariantPath) { // return new InvariantIcon(getIcon(path), getIcon(darkVariantPath)); @NotNull public static Icon getIcon(@NonNls @NotNull final String path) { Class callerClass = ReflectionUtil.getGrandCallerClass(); assert callerClass != null : path; return getIcon(path, callerClass); } @Nullable private static Icon getReflectiveIcon(@NotNull String path, ClassLoader classLoader) { try { @NonNls String pckg = path.startsWith("AllIcons.") ? "com.intellij.icons." : "icons."; Class cur = Class.forName(pckg + path.substring(0, path.lastIndexOf('.')).replace('.', '$'), true, classLoader); Field field = cur.getField(path.substring(path.lastIndexOf('.') + 1)); return (Icon)field.get(null); } catch (Exception e) { return null; } } /** * Might return null if icon was not found. * Use only if you expected null return value, otherwise see {@link IconLoader#getIcon(String)} */ @Nullable public static Icon findIcon(@NonNls @NotNull String path) { Class callerClass = ReflectionUtil.getGrandCallerClass(); if (callerClass == null) return null; return findIcon(path, callerClass); } @Nullable public static Icon findIcon(@NonNls @NotNull String path, boolean strict) { Class callerClass = ReflectionUtil.getGrandCallerClass(); if (callerClass == null) return null; return findIcon(path, callerClass, false, strict); } @NotNull public static Icon getIcon(@NotNull String path, @NotNull final Class aClass) { Icon icon = findIcon(path, null, aClass, aClass.getClassLoader(), HandleNotFound.strict(STRICT_LOCAL.get()), true, true); if (icon == null) { LOG.error("Icon cannot be found in '" + path + "', aClass='" + aClass + "'"); } return icon; // [tav] todo: can't fix it } public static void activate() { ourIsActivated = true; } private static boolean isLoaderDisabled() { return !ourIsActivated; } @Nullable public static Icon findLafIcon(@NotNull String key, @NotNull Class aClass) { return findLafIcon(key, aClass, STRICT_LOCAL.get()); } @Nullable public static Icon findLafIcon(@NotNull String key, @NotNull Class aClass, boolean strict) { return findIcon(LAF_PREFIX + key + ".png", aClass, true, strict); } /** * Might return null if icon was not found. * Use only if you expected null return value, otherwise see {@link IconLoader#getIcon(String, Class)} */ @Nullable public static Icon findIcon(@NotNull final String path, @NotNull final Class aClass) { return findIcon(path, aClass, false); } @Nullable public static Icon findIcon(@NotNull String path, @NotNull final Class aClass, boolean computeNow) { return findIcon(path, aClass, computeNow, STRICT_LOCAL.get()); } @Nullable public static Icon findIcon(@NotNull String path, @NotNull Class aClass, @SuppressWarnings("unused") boolean computeNow, boolean strict) { return findIcon(path, null, aClass, aClass.getClassLoader(), HandleNotFound.strict(strict), false, true); } private static boolean findReflectiveIcon(@NotNull String path, @Nullable ClassLoader classLoader, /*OUT*/ @NotNull Ref<Icon> reflectiveIconResult) { Pair<String, ClassLoader> patchedPath = ourTransform.get().patchPath(path, classLoader); path = patchedPath.first; if (patchedPath.second != null) { classLoader = patchedPath.second; } if (isReflectivePath(path)) { reflectiveIconResult.set(getReflectiveIcon(path, classLoader)); return true; } else { reflectiveIconResult.set(null); return false; } } private static boolean isReflectivePath(@NotNull String path) { List<String> paths = StringUtil.split(path, "."); return paths.size() > 1 && paths.get(0).endsWith("Icons"); } @Nullable private static URL findURL(@NotNull String path, @Nullable Object context) { URL url; if (context instanceof Class) { url = ((Class)context).getResource(path); } else if (context instanceof ClassLoader) { // Paths in ClassLoader getResource shouldn't start with "/" url = ((ClassLoader)context).getResource(path.startsWith("/") ? path.substring(1) : path); } else { LOG.warn("unexpected: " + context); return null; } // Find either PNG or SVG icon. The icon will then be wrapped into CachedImageIcon // which will load proper icon version depending on the context - UI theme, DPI. // SVG version, when present, has more priority than PNG. // See for details: com.intellij.util.ImageLoader.ImageDescList#create if (url != null || !path.endsWith(".png")) return url; url = findURL(path.substring(0, path.length() - 4) + ".svg", context); if (url != null && !path.startsWith(LAF_PREFIX)) LOG.info("replace '" + path + "' with '" + url + "'"); return url; } @Nullable public static Icon findIcon(URL url) { return findIcon(url, true); } @Nullable public static Icon findIcon(URL url, boolean useCache) { if (url == null) { return null; } Pair<String, Object> key = Pair.create(ICON_CACHE_URL_KEY, (Object)url); CachedImageIcon icon = ourIconsCache.get(key); if (icon == null) { icon = new CachedImageIcon(url, useCache); if (useCache) { icon = ConcurrencyUtil.cacheOrGet(ourIconsCache, key, icon); } } return icon; } @Nullable private static Icon findIcon(@NotNull String originalPath, @Nullable String pathToResolve, @Nullable Class clazz, @NotNull ClassLoader classLoader, HandleNotFound handleNotFound, boolean deferResolve, boolean findReflectiveIcon) { if (findReflectiveIcon) { Ref<Icon> reflectiveIcon = new Ref<Icon>(null); if (findReflectiveIcon(originalPath, classLoader, reflectiveIcon)) { return reflectiveIcon.get(); // @Nullable } } Pair<String, Object> key = Pair.create(originalPath, (Object)classLoader); CachedImageIcon cachedIcon = ourIconsCache.get(key); if (cachedIcon == null) { cachedIcon = CachedImageIcon.create(originalPath, pathToResolve, classLoader, clazz, handleNotFound, deferResolve); if (cachedIcon == null) { return null; } cachedIcon = ConcurrencyUtil.cacheOrGet(ourIconsCache, key, cachedIcon); } return cachedIcon; } @Nullable public static Icon findIcon(@NotNull String path, @NotNull ClassLoader classLoader) { Ref<Icon> reflectiveIcon = new Ref<Icon>(null); if (findReflectiveIcon(path, classLoader, reflectiveIcon)) { return reflectiveIcon.get(); // @Nullable } if (!StringUtil.startsWithChar(path, '/')) return null; return findIcon(path, path.substring(1), null, classLoader, HandleNotFound.strict(false), false, false); } @Nullable public static Image toImage(@NotNull Icon icon) { return toImage(icon, null); } @Nullable public static Image toImage(@NotNull Icon icon, @Nullable ScaleContext ctx) { if (icon instanceof RetrievableIcon) { icon = ((RetrievableIcon)icon).retrieveIcon(); } if (icon instanceof CachedImageIcon) { icon = ((CachedImageIcon)icon).getRealIcon(ctx); } if (icon == null) return null; if (icon instanceof ImageIcon) { return ((ImageIcon)icon).getImage(); } else { BufferedImage image; if (GraphicsEnvironment.isHeadless()) { // for testing purpose image = UIUtil.createImage(ctx, icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB, RoundingMode.FLOOR); } else { // [tav] todo: match the screen with the provided ctx image = GraphicsEnvironment.getLocalGraphicsEnvironment() .getDefaultScreenDevice().getDefaultConfiguration() .createCompatibleImage(icon.getIconWidth(), icon.getIconHeight(), Transparency.TRANSLUCENT); } Graphics2D g = image.createGraphics(); try { icon.paintIcon(null, g, 0, 0); } finally { g.dispose(); } return image; } } @Contract("null, _->null; !null, _->!null") public static Icon copy(@Nullable Icon icon, @Nullable Component ancestor) { if (icon == null) return null; if (icon instanceof CopyableIcon) { return ((CopyableIcon)icon).copy(); } BufferedImage image = UIUtil.createImage(ancestor, icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB); Graphics2D g = image.createGraphics(); try { icon.paintIcon(ancestor, g, 0, 0); } finally { g.dispose(); } return new JBImageIcon(image); } @Nullable private static ImageIcon checkIcon(final @Nullable Image image, @NotNull CachedImageIcon cii) { if (image == null || image.getHeight(null) < 1) { // image wasn't loaded or broken return null; } final ImageIcon icon = new JBImageIcon(image); if (!isGoodSize(icon)) { LOG.error("Invalid icon: " + cii); // # 22481 return EMPTY_ICON; } return icon; } public static boolean isGoodSize(@NotNull final Icon icon) { return icon.getIconWidth() > 0 && icon.getIconHeight() > 0; } /** * Gets (creates if necessary) disabled icon based on the passed one. * * @return {@code ImageIcon} constructed from disabled image of passed icon. */ @Nullable public static Icon getDisabledIcon(Icon icon) { if (icon instanceof LazyIcon) icon = ((LazyIcon)icon).getOrComputeIcon(); if (icon == null) return null; Icon disabledIcon = ourIcon2DisabledIcon.get(icon); if (disabledIcon == null) { disabledIcon = filterIcon(icon, UIUtil.getGrayFilter(), null); // [tav] todo: lack ancestor ourIcon2DisabledIcon.put(icon, disabledIcon); } return disabledIcon; } /** * Creates new icon with the filter applied. */ @Nullable public static Icon filterIcon(@NotNull Icon icon, RGBImageFilter filter, @Nullable Component ancestor) { if (icon instanceof LazyIcon) icon = ((LazyIcon)icon).getOrComputeIcon(); if (icon == null) return null; if (!isGoodSize(icon)) { LOG.error(icon); // # 22481 return EMPTY_ICON; } if (icon instanceof CachedImageIcon) { icon = ((CachedImageIcon)icon).createWithFilter(filter); } else { final float scale; if (icon instanceof JBUI.ScaleContextAware) { scale = (float)((JBUI.ScaleContextAware)icon).getScale(SYS_SCALE); } else { scale = UIUtil.isJreHiDPI() ? JBUI.sysScale(ancestor) : 1f; } @SuppressWarnings("UndesirableClassUsage") BufferedImage image = new BufferedImage((int)(scale * icon.getIconWidth()), (int)(scale * icon.getIconHeight()), BufferedImage.TYPE_INT_ARGB); final Graphics2D graphics = image.createGraphics(); graphics.setColor(UIUtil.TRANSPARENT_COLOR); graphics.fillRect(0, 0, icon.getIconWidth(), icon.getIconHeight()); graphics.scale(scale, scale); icon.paintIcon(LabelHolder.ourFakeComponent, graphics, 0, 0); graphics.dispose(); Image img = ImageUtil.filter(image, filter); if (UIUtil.isJreHiDPI(ancestor)) img = RetinaImage.createFrom(img, scale, null); icon = new JBImageIcon(img); } return icon; } @NotNull public static Icon getTransparentIcon(@NotNull final Icon icon) { return getTransparentIcon(icon, 0.5f); } @NotNull public static Icon getTransparentIcon(@NotNull final Icon icon, final float alpha) { return new RetrievableIcon() { @Override public Icon retrieveIcon() { return icon; } @Override public int getIconHeight() { return icon.getIconHeight(); } @Override public int getIconWidth() { return icon.getIconWidth(); } @Override public void paintIcon(final Component c, final Graphics g, final int x, final int y) { final Graphics2D g2 = (Graphics2D)g; final Composite saveComposite = g2.getComposite(); g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha)); icon.paintIcon(c, g2, x, y); g2.setComposite(saveComposite); } }; } /** * Gets a snapshot of the icon, immune to changes made by these calls: * {@link #setFilter(ImageFilter)}, {@link #setUseDarkIcons(boolean)} * * @param icon the source icon * @return the icon snapshot */ @NotNull public static Icon getIconSnapshot(@NotNull Icon icon) { if (icon instanceof CachedImageIcon) { return ((CachedImageIcon)icon).getRealIcon(); } return icon; } /** * For internal usage. Converts the icon to 1x scale when applicable. */ public static Icon getMenuBarIcon(Icon icon, boolean dark) { if (icon instanceof RetrievableIcon) { icon = ((RetrievableIcon)icon).retrieveIcon(); } if (icon instanceof MenuBarIconProvider) { return ((MenuBarIconProvider)icon).getMenuBarIcon(dark); } return icon; } /** * Returns a copy of the provided {@code icon} with darkness set to {@code dark}. * The method takes effect on a {@link CachedImageIcon} (or its wrapper) only. */ public static Icon getDarkIcon(Icon icon, boolean dark) { if (icon instanceof RetrievableIcon) { icon = getOrigin((RetrievableIcon)icon); } if (icon instanceof DarkIconProvider) { return ((DarkIconProvider)icon).getDarkIcon(dark); } return icon; } public static final class CachedImageIcon extends com.intellij.util.ui.JBUI.RasterJBIcon implements ScalableIcon, DarkIconProvider, MenuBarIconProvider { private final Object myLock = new Object(); @Nullable private volatile Object myRealIcon; @Nullable private final String myOriginalPath; @NotNull private volatile MyUrlResolver myResolver; @Nullable("when not overridden") private final Boolean myDarkOverridden; @NotNull private volatile IconTransform myTransform; private final boolean myUseCacheOnLoad; @Nullable private final ImageFilter myLocalFilter; private final MyScaledIconsCache myScaledIconsCache = new MyScaledIconsCache(); public CachedImageIcon(@NotNull URL url) { this(url, true); } CachedImageIcon(@Nullable URL url, boolean useCacheOnLoad) { this(new MyUrlResolver(url, null), null, useCacheOnLoad); } private CachedImageIcon(@NotNull MyUrlResolver urlResolver, @Nullable String originalPath, boolean useCacheOnLoad) { this(originalPath, urlResolver, null, useCacheOnLoad, ourTransform.get(), null); } private CachedImageIcon(@Nullable String originalPath, @NotNull MyUrlResolver resolver, @Nullable Boolean darkOverridden, boolean useCacheOnLoad, @NotNull IconTransform transform, @Nullable ImageFilter localFilter) { myOriginalPath = originalPath; myResolver = resolver; myDarkOverridden = darkOverridden; myUseCacheOnLoad = useCacheOnLoad; myTransform = transform; myLocalFilter = localFilter; // For instance, ShadowPainter updates the context from outside. getScaleContext().addUpdateListener(new UpdateListener() { @Override public void contextUpdated() { myRealIcon = null; } }); } @Contract("_, _, _, _, _, true -> !null") static CachedImageIcon create(@NotNull String originalPath, @Nullable String pathToResolve, @NotNull ClassLoader classLoader, @Nullable Class clazz, HandleNotFound handleNotFound, boolean deferResolve) { MyUrlResolver resolver = new MyUrlResolver(pathToResolve == null ? originalPath : pathToResolve, clazz, classLoader, handleNotFound); CachedImageIcon icon = new CachedImageIcon(resolver, originalPath, true); if (!deferResolve && icon.getURL() == null) return null; return icon; } @Nullable public String getOriginalPath() { return myOriginalPath; } @NotNull private ImageIcon getRealIcon() { return getRealIcon(null); } @Nullable @TestOnly public ImageIcon doGetRealIcon() { return unwrapIcon(myRealIcon); } @NotNull private ImageIcon getRealIcon(@Nullable ScaleContext ctx) { if (!isValid()) { if (isLoaderDisabled()) return EMPTY_ICON; synchronized (myLock) { if (!isValid()) { myTransform = ourTransform.get(); myResolver.resolve(); myRealIcon = null; myScaledIconsCache.clear(); if (myOriginalPath != null) { myResolver = myResolver.patch(myOriginalPath, myTransform); } } } } Object realIcon = myRealIcon; synchronized (myLock) { if (!updateScaleContext(ctx) && realIcon != null) { // try returning the current icon as the context is up-to-date ImageIcon icon = unwrapIcon(realIcon); if (icon != null) return icon; } ImageIcon icon = myScaledIconsCache.getOrScaleIcon(1f); if (icon != null) { myRealIcon = icon.getIconWidth() < 50 && icon.getIconHeight() < 50 ? icon : new SoftReference<ImageIcon>(icon); return icon; } } return EMPTY_ICON; } @Nullable private static ImageIcon unwrapIcon(Object realIcon) { Object icon = realIcon; if (icon instanceof Reference) { //noinspection unchecked icon = ((Reference<ImageIcon>)icon).get(); } return icon instanceof ImageIcon ? (ImageIcon)icon : null; } private boolean isValid() { return myTransform == ourTransform.get() && myResolver.isResolved(); } @Override public void paintIcon(Component c, Graphics g, int x, int y) { Graphics2D g2d = g instanceof Graphics2D ? (Graphics2D)g : null; getRealIcon(ScaleContext.create(c, g2d)).paintIcon(c, g, x, y); } @Override public int getIconWidth() { return getRealIcon().getIconWidth(); } @Override public int getIconHeight() { return getRealIcon().getIconHeight(); } @Override public String toString() { if (myResolver.isResolved()) { URL url = myResolver.getURL(); if (url != null) return url.toString(); } return myOriginalPath != null ? myOriginalPath : "unknown path"; } @Override public float getScale() { return 1f; } @NotNull @Override public Icon scale(float scale) { if (scale == 1f) return this; getRealIcon(); // force state update & cache reset Icon icon = myScaledIconsCache.getOrScaleIcon(scale); if (icon != null) { return icon; } return this; } @Override public Icon getDarkIcon(boolean isDark) { return new CachedImageIcon(myOriginalPath, myResolver, isDark, myUseCacheOnLoad, myTransform, myLocalFilter); } @Override public Icon getMenuBarIcon(boolean isDark) { Image img = loadFromUrl(ScaleContext.createIdentity(), isDark); if (img != null) { return new ImageIcon(img); } return this; } @NotNull @Override public CachedImageIcon copy() { return new CachedImageIcon(myOriginalPath, myResolver, myDarkOverridden, myUseCacheOnLoad, myTransform, myLocalFilter); } @NotNull private Icon createWithFilter(@NotNull RGBImageFilter filter) { return new CachedImageIcon(myOriginalPath, myResolver, myDarkOverridden, myUseCacheOnLoad, myTransform, filter); } private boolean isDark() { return myDarkOverridden == null ? myTransform.isDark() : myDarkOverridden; } @Nullable private ImageFilter[] getFilters() { ImageFilter global = myTransform.getFilter(); ImageFilter local = myLocalFilter; if (global != null && local != null) { return new ImageFilter[] {global, local}; } else if (global != null) { return new ImageFilter[] {global}; } else if (local != null) { return new ImageFilter[] {local}; } return null; } @Nullable public URL getURL() { return myResolver.getURL(); } @Nullable private Image loadFromUrl(@NotNull ScaleContext ctx, boolean dark) { URL url = getURL(); if (url == null) return null; return ImageLoader.loadFromUrl(url, true, myUseCacheOnLoad, dark, getFilters(), ctx); } private class MyScaledIconsCache { private static final int SCALED_ICONS_CACHE_LIMIT = 5; private final Map<Couple<Double>, SoftReference<ImageIcon>> scaledIconsCache = Collections.synchronizedMap(new FixedHashMap<Couple<Double>, SoftReference<ImageIcon>>(SCALED_ICONS_CACHE_LIMIT)); private Couple<Double> key(@NotNull ScaleContext ctx) { return new Couple<Double>(ctx.getScale(USR_SCALE) * ctx.getScale(OBJ_SCALE), ctx.getScale(SYS_SCALE)); } /** * Retrieves the orig icon scaled by the provided scale. */ ImageIcon getOrScaleIcon(final float scale) { ScaleContext ctx = getScaleContext(); if (scale != 1) { ctx = ctx.copy(); ctx.update(OBJ_SCALE.of(scale)); } ImageIcon icon = SoftReference.dereference(scaledIconsCache.get(key(ctx))); if (icon != null) { return icon; } Image image = loadFromUrl(ctx, isDark()); icon = checkIcon(image, CachedImageIcon.this); if (icon != null && icon.getIconWidth() * icon.getIconHeight() * 4 < ImageLoader.CACHED_IMAGE_MAX_SIZE) { scaledIconsCache.put(key(ctx), new SoftReference<ImageIcon>(icon)); } return icon; } public void clear() { scaledIconsCache.clear(); } } enum HandleNotFound { THROW_EXCEPTION { @Override void handle(String msg) { throw new RuntimeException(msg); } }, LOG_ERROR { @Override void handle(String msg) { LOG.error(msg); } }, IGNORE; void handle(String msg) throws RuntimeException {} static HandleNotFound strict(boolean strict) { return strict ? THROW_EXCEPTION : IGNORE; } } /** * Used to defer URL resolve. */ private static class MyUrlResolver { @Nullable private final Class myClass; @Nullable private final ClassLoader myClassLoader; @Nullable private final String myOverriddenPath; @NotNull private final HandleNotFound myHandleNotFound; // Every myUrl write is performed before isResolved write (see resolve()) // and every myUrl read is performed after isResolved read (see getUrl()), thus // no necessary to declare myUrl as volatile: happens-before is established via isResolved. @Nullable private URL myUrl; private volatile boolean isResolved; MyUrlResolver(@Nullable URL url, @Nullable ClassLoader classLoader) { myClass = null; myOverriddenPath = null; myClassLoader = classLoader; myUrl = url; myHandleNotFound = HandleNotFound.IGNORE; isResolved = true; } MyUrlResolver(@NotNull String path, @Nullable Class clazz, @Nullable ClassLoader classLoader, @NotNull HandleNotFound handleNotFound) { myOverriddenPath = path; myClass = clazz; myClassLoader = classLoader; myHandleNotFound = handleNotFound; if (!Registry.is("ide.icons.deferUrlResolve")) resolve(); } boolean isResolved() { return isResolved; } /** * Resolves the URL if it's not yet resolved. */ MyUrlResolver resolve() throws RuntimeException { if (isResolved) return this; try { URL url = null; String path = myOverriddenPath; if (path != null) { url = findURL(path, myClassLoader); if (url == null && myClass != null) { // Some plugins use findIcon("icon.png",IconContainer.class) url = findURL(path, myClass); } } if (url == null) { myHandleNotFound.handle("Can't find icon in '" + path + "' near " + myClassLoader); } myUrl = url; } finally { isResolved = true; } return this; } @Nullable URL getURL() { if (!isResolved()) { return resolve().myUrl; } return myUrl; } MyUrlResolver patch(String originalPath, IconTransform transform) { Pair<String, ClassLoader> patchedPath = transform.patchPath(originalPath, myClassLoader); ClassLoader classLoader = patchedPath.second != null ? patchedPath.second : myClassLoader; String path = patchedPath.first; if (classLoader != null && path != null && path.startsWith("/")) { return new MyUrlResolver(path.substring(1), null, classLoader, myHandleNotFound).resolve(); } return this; } } } public abstract static class LazyIcon extends RasterJBIcon implements RetrievableIcon { private boolean myWasComputed; private volatile Icon myIcon; private IconTransform myTransform = ourTransform.get(); @Override public void paintIcon(Component c, Graphics g, int x, int y) { if (updateScaleContext(ScaleContext.create((Graphics2D)g))) { myIcon = null; } final Icon icon = getOrComputeIcon(); if (icon != null) { icon.paintIcon(c, g, x, y); } } @Override public int getIconWidth() { final Icon icon = getOrComputeIcon(); return icon != null ? icon.getIconWidth() : 0; } @Override public int getIconHeight() { final Icon icon = getOrComputeIcon(); return icon != null ? icon.getIconHeight() : 0; } protected final synchronized Icon getOrComputeIcon() { IconTransform currentTransform = ourTransform.get(); if (!myWasComputed || myTransform != currentTransform || myIcon == null) { myTransform = currentTransform; myWasComputed = true; myIcon = compute(); } return myIcon; } public final void load() { getIconWidth(); } protected abstract Icon compute(); @Nullable @Override public Icon retrieveIcon() { return getOrComputeIcon(); } @NotNull @Override public Icon copy() { return IconLoader.copy(getOrComputeIcon(), null); } } // todo: remove and use DarkIconProvider when JBSDK supports scalable icons in menu public interface MenuBarIconProvider { Icon getMenuBarIcon(boolean isDark); } public interface DarkIconProvider { Icon getDarkIcon(boolean isDark); } private static Icon getOrigin(RetrievableIcon icon) { final int maxDeep = 10; Icon origin = icon.retrieveIcon(); int level = 0; while (origin instanceof RetrievableIcon && level < maxDeep) { ++level; origin = ((RetrievableIcon)origin).retrieveIcon(); } if (origin instanceof RetrievableIcon) LOG.error("can't calculate origin icon (too deep in hierarchy), src: " + icon); return origin; } private static class LabelHolder { /** * To get disabled icon with paint it into the image. Some icons require * not null component to paint. */ private static final JComponent ourFakeComponent = new JLabel(); } /** * Immutable representation of a global transformation applied to all icons */ private static final class IconTransform { private final boolean myDark; private final @NotNull IconPathPatcher[] myPatchers; private final @Nullable ImageFilter myFilter; private IconTransform(boolean dark, @NotNull IconPathPatcher[] patchers, @Nullable ImageFilter filter) { myDark = dark; myPatchers = patchers; myFilter = filter; } public boolean isDark() { return myDark; } @Nullable public ImageFilter getFilter() { return myFilter; } public IconTransform withPathPatcher(IconPathPatcher patcher) { return new IconTransform(myDark, ArrayUtil.append(myPatchers, patcher), myFilter); } public IconTransform withoutPathPatcher(IconPathPatcher patcher) { IconPathPatcher[] newPatchers = ArrayUtil.remove(myPatchers, patcher); return newPatchers == myPatchers ? this : new IconTransform(myDark, newPatchers, myFilter); } public IconTransform withFilter(ImageFilter filter) { return filter == myFilter ? this : new IconTransform(myDark, myPatchers, filter); } public IconTransform withDark(boolean dark) { return dark == myDark ? this : new IconTransform(dark, myPatchers, myFilter); } public Pair<String, ClassLoader> patchPath(@NotNull String path, ClassLoader classLoader) { for (IconPathPatcher patcher : myPatchers) { String newPath = patcher.patchPath(path, classLoader); if (newPath == null) { newPath = patcher.patchPath(path, null); } if (newPath != null) { LOG.info("replace '" + path + "' with '" + newPath + "'"); ClassLoader contextClassLoader = patcher.getContextClassLoader(path, classLoader); if (contextClassLoader == null) { //noinspection deprecation Class contextClass = patcher.getContextClass(path); if (contextClass != null) { contextClassLoader = contextClass.getClassLoader(); } } return Pair.create(newPath, contextClassLoader); } } return Pair.create(path, null); } public IconTransform copy() { return new IconTransform(myDark, myPatchers, myFilter); } public static IconTransform getDefault() { return new IconTransform(UIUtil.isUnderDarcula(), new IconPathPatcher[0], null); } } }
package org.hsqldb_voltpatches; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLDecoder; import java.util.ArrayList; import org.apache.commons.lang3.tuple.Pair; import org.hsqldb_voltpatches.HSQLInterface.HSQLParseException; import org.voltdb.planner.ParameterizationInfo; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import junit.framework.TestCase; public class TestHSQLDB extends TestCase { class VoltErrorHandler implements ErrorHandler { @Override public void error(SAXParseException exception) throws SAXException { throw exception; } @Override public void fatalError(SAXParseException exception) throws SAXException { } @Override public void warning(SAXParseException exception) throws SAXException { throw exception; } } public class StringInputStream extends InputStream { StringReader sr; public StringInputStream(String value) { sr = new StringReader(value); } @Override public int read() throws IOException { return sr.read(); } } public void testCatalogRead() { HSQLInterface hsql = HSQLInterface.loadHsqldb(ParameterizationInfo.getParamStateManager()); try { hsql.runDDLCommand("create table test (cash integer default 23);"); } catch (HSQLParseException e1) { e1.printStackTrace(); fail(); } VoltXMLElement xml; try { xml = hsql.getXMLFromCatalog(); assertNotNull(xml); } catch (HSQLParseException e1) { // TODO Auto-generated catch block e1.printStackTrace(); fail(); } try { xml = hsql.getXMLCompiledStatement("select * from test;"); assertNotNull(xml); } catch (HSQLParseException e) { e.printStackTrace(); fail(); } //* enable to debug */ System.out.println(xml); } public HSQLInterface setupTPCCDDL() { HSQLInterface hsql = HSQLInterface.loadHsqldb(ParameterizationInfo.getParamStateManager()); URL url = getClass().getResource("hsqltest-ddl.sql"); try { hsql.runDDLFile(URLDecoder.decode(url.getPath(), "UTF-8")); } catch (HSQLParseException e) { e.printStackTrace(); fail(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); fail(); } return hsql; } //* enable to debug *-/ System.out.println(xml); StringInputStream xmlStream = new StringInputStream(xml); Document doc = null; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(true); try { DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(new VoltErrorHandler()); doc = builder.parse(xmlStream); } catch (Exception e) { e.printStackTrace(); fail(); } assertNotNull(doc); } }*/ private static void expectFailStmt(HSQLInterface hsql, String stmt, String errorPart) { try { VoltXMLElement xml = hsql.getXMLCompiledStatement(stmt); System.out.println(xml.toString()); fail(); } catch (Exception e) { assertTrue(e.getMessage().contains(errorPart)); } } public void testSqlInToXML() throws HSQLParseException { HSQLInterface hsql = setupTPCCDDL(); VoltXMLElement stmt; // The next few statements should work, also with a trivial test stmt = hsql.getXMLCompiledStatement("select * from new_order"); assertTrue(stmt.toString().contains("NO_W_ID")); stmt = hsql.getXMLCompiledStatement("select * from new_order where no_w_id = 5"); assertTrue(stmt.toString().contains("equal")); stmt = hsql.getXMLCompiledStatement("select * from new_order where no_w_id in (5,7);"); assertTrue(stmt.toString().contains("vector")); stmt = hsql.getXMLCompiledStatement("select * from new_order where no_w_id in (?);"); assertTrue(stmt.toString().contains("vector")); stmt = hsql.getXMLCompiledStatement("select * from new_order where no_w_id in (?,5,3,?);"); assertTrue(stmt.toString().contains("vector")); stmt = hsql.getXMLCompiledStatement("select * from new_order where no_w_id not in (?,5,3,?);"); assertTrue(stmt.toString().contains("vector")); stmt = hsql.getXMLCompiledStatement("select * from warehouse where w_name not in (?, 'foo');"); assertTrue(stmt.toString().contains("vector")); stmt = hsql.getXMLCompiledStatement("select * from new_order where no_w_id in (no_d_id, no_o_id, ?, 7);"); assertTrue(stmt.toString().contains("vector")); stmt = hsql.getXMLCompiledStatement("select * from new_order where no_w_id in (abs(-1), ?, 17761776);"); assertTrue(stmt.toString().contains("vector")); stmt = hsql.getXMLCompiledStatement("select * from new_order where no_w_id in (abs(17761776), ?, 17761776) and no_d_id in (abs(-1), ?, 17761776);"); assertTrue(stmt.toString().contains("vector")); stmt = hsql.getXMLCompiledStatement("select * from new_order where no_w_id in ?;"); assertTrue(stmt.toString().contains("vector")); stmt = hsql.getXMLCompiledStatement("select * from new_order where no_w_id in (select w_id from warehouse);"); assertTrue(stmt.toString().contains("tablesubquery")); stmt = hsql.getXMLCompiledStatement("select * from new_order where exists (select w_id from warehouse);"); assertTrue(stmt.toString().contains("tablesubquery")); stmt = hsql.getXMLCompiledStatement("select * from new_order where not exists (select w_id from warehouse);"); assertTrue(stmt.toString().contains("tablesubquery")); // The ones below here should continue to give sensible errors expectFailStmt(hsql, "select * from new_order where no_w_id <> (5, 7, 8);", "row column count mismatch"); // Fixed as ENG-9869 bogus plan when ORDER BY of self-join uses wrong table alias for GROUP BY key expectFailStmt(hsql, "select x.no_w_id from new_order x, new_order y group by x.no_w_id order by y.no_w_id;", "expression not in aggregate or GROUP BY columns"); } public void testVarbinary() { HSQLInterface hsql = HSQLInterface.loadHsqldb(ParameterizationInfo.getParamStateManager()); URL url = getClass().getResource("hsqltest-varbinaryddl.sql"); try { hsql.runDDLFile(URLDecoder.decode(url.getPath(), "UTF-8")); } catch (Exception e) { e.printStackTrace(); fail(); } String sql = "SELECT * FROM BT;"; VoltXMLElement xml = null; try { xml = hsql.getXMLCompiledStatement(sql); assertNotNull(xml); } catch (HSQLParseException e1) { e1.printStackTrace(); fail(); } //* enable to debug */ System.out.println(xml); sql = "INSERT INTO BT VALUES (?, ?, ?);"; xml = null; try { xml = hsql.getXMLCompiledStatement(sql); assertNotNull(xml); } catch (HSQLParseException e1) { e1.printStackTrace(); fail(); } //* enable to debug */ System.out.println(xml); } public void testInsertIntoSelectFrom() { HSQLInterface hsql = setupTPCCDDL(); String sql = "INSERT INTO new_order (NO_O_ID, NO_D_ID, NO_W_ID) SELECT O_ID, O_D_ID+1, CAST(? AS INTEGER) FROM ORDERS;"; VoltXMLElement xml = null; try { xml = hsql.getXMLCompiledStatement(sql); assertNotNull(xml); } catch (HSQLParseException e1) { e1.printStackTrace(); fail(); } } public void testSumStarFails() { HSQLInterface hsql = HSQLInterface.loadHsqldb(ParameterizationInfo.getParamStateManager()); assertNotNull(hsql); // The elements of this ArrayList tells us the statement to // execute, and whether we expect an exception when we execute // the statement. If the first element of the pair begins // with the string "Expected", we expect an error. If // the First begins with something else, we don't expect errors. // In either case and the string tells what to complain about. ArrayList<Pair<String, String>> allddl = new ArrayList<Pair<String, String>>(); allddl.add(Pair.of("Unexpected Table Creation Failure.", "CREATE TABLE t (i INTEGER, j INTEGER);")); allddl.add(Pair.of("Unexpected count(*) call failure.", "CREATE VIEW vw1 (sm) as SELECT count(*) from t group by i;")); allddl.add(Pair.of("Expected sum(*) call failure.", "CREATE VIEW vw (sm) AS SELECT sum(*) from t group by i;")); for (Pair<String, String> ddl : allddl) { boolean sawException = false; try { hsql.runDDLCommand(ddl.getRight()); } catch (HSQLParseException e1) { sawException = true; } assertEquals(ddl.getLeft(), ddl.getLeft().startsWith("Expected", 0), sawException); } } public void testDeleteTableAliasPass() { HSQLInterface hsql = setupTPCCDDL(); // Parsed result without a table alias String no_alias = ""; // Parsed result with a table alias String alias_ref = ""; // No aliasing String sql = "DELETE FROM ORDERS WHERE O_W_ID = ?;"; VoltXMLElement xml = null; try { xml = hsql.getXMLCompiledStatement(sql); assertNotNull(xml); no_alias = xml.toString(); } catch (HSQLParseException e1) { e1.printStackTrace(); fail(); } // Aliasing in FROM without AS, refer to a column in WHERE without the alias sql = "DELETE FROM ORDERS O WHERE O_W_ID = ?;"; xml = null; try { xml = hsql.getXMLCompiledStatement(sql); assertNotNull(xml); alias_ref = xml.toString(); // Check the parsed result for the correct table alias assertTrue(alias_ref.contains("tablealias=\"O\"")); // Create a new string that have tablealias entries replaced by whitespaces String alias_modified = alias_ref.replace("tablealias=\"O\"", " "); // The parsed results with and without a table alias should only be different by the tablealias field. // i.e. For this particular statement, the parsed result without table alias should be "...table=\"ORDERS\"..." // the parsed result with table alias should be "...table=\"ORDERS\"...tablealias=\"O\"..." assertTrue(no_alias.replaceAll("[\\s+\n+]", "").equals(alias_modified.replaceAll("[\\s+\\n+]", ""))); } catch (HSQLParseException e1) { e1.printStackTrace(); fail(); } // Aliasing in FROM with AS, refer to a column in WHERE with the alias sql = "DELETE FROM ORDERS AS O WHERE O.O_W_ID = ?;"; xml = null; try { xml = hsql.getXMLCompiledStatement(sql); assertNotNull(xml); // All statements that have a table alias should be parsed into the same result assertTrue(xml.toString().equals(alias_ref)); } catch (HSQLParseException e1) { e1.printStackTrace(); fail(); } // Aliasing in FROM without AS, refer to a column in WHERE without the alias sql = "DELETE FROM ORDERS O WHERE O_W_ID = ?;"; xml = null; try { xml = hsql.getXMLCompiledStatement(sql); assertNotNull(xml); // All statements that have a table alias should be parsed into the same result assertTrue(xml.toString().equals(alias_ref)); } catch (HSQLParseException e1) { e1.printStackTrace(); fail(); } // Aliasing in FROM with AS, refer to a column in WHERE with the alias sql = "DELETE FROM ORDERS AS O WHERE O.O_W_ID = ?;"; xml = null; try { xml = hsql.getXMLCompiledStatement(sql); assertNotNull(xml); // All statements that have a table alias should be parsed into the same result assertTrue(xml.toString().equals(alias_ref)); } catch (HSQLParseException e1) { e1.printStackTrace(); fail(); } } public void testDeleteTableAliasFail() { HSQLInterface hsql = setupTPCCDDL(); // Aliasing in FROM without AS, refer to a column in WHERE with the original table expectFailStmt(hsql, "DELETE FROM ORDERS O WHERE ORDERS.O_W_ID = ?;", "object not found: ORDERS.O_W_ID"); // Aliasing in FROM with AS, refer to a column in WHERE with the original table expectFailStmt(hsql, "DELETE FROM ORDERS AS O WHERE ORDERS.O_W_ID = ?;", "object not found: ORDERS.O_W_ID"); } //* enable to debug *-/ System.out.println(xml); StringInputStream xmlStream = new StringInputStream(xml); Document doc = null; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(true); try { DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(new VoltErrorHandler()); doc = builder.parse(xmlStream); assertNotNull(doc); } catch (Exception e) { e.printStackTrace(); fail(); } }*/ //* enable to debug *-/ System.out.println(xml); }*/ public static void main(String args[]) { //new TestHSQLDB().testWithTPCCDDL(); } }
package edu.georgetown.library.fileAnalyzer.filetest; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Map; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVPrinter; import org.apache.commons.csv.CSVRecord; import edu.georgetown.library.fileAnalyzer.filetest.SwapDelimitedColumns.Generator.ColStats; import gov.nara.nwts.ftapp.FTDriver; import gov.nara.nwts.ftapp.filetest.DefaultFileTest; import gov.nara.nwts.ftapp.filter.CSVFilter; import gov.nara.nwts.ftapp.ftprop.FTPropEnum; import gov.nara.nwts.ftapp.ftprop.FTPropString; import gov.nara.nwts.ftapp.ftprop.InitializationStatus; import gov.nara.nwts.ftapp.stats.Stats; import gov.nara.nwts.ftapp.stats.StatsGenerator; import gov.nara.nwts.ftapp.stats.StatsItem; import gov.nara.nwts.ftapp.stats.StatsItemConfig; import gov.nara.nwts.ftapp.stats.StatsItemEnum; /* * This code is included for illustrative purposes. It is not currently active in the application. * More robust file overwriting controls are needed. */ public class SwapDelimitedColumns extends DefaultFileTest { static final String DELIM = "delim"; static final String COLA = "ColA"; static final String COLB = "ColB"; String cNameA = ""; String cNameB = ""; public static enum Sep{CSV, TSV;} public static enum Status{Updated, Failed, ColNotFound;} private static enum ColStatsItems implements StatsItemEnum { Key(StatsItem.makeStringStatsItem("File", 200)), Status(StatsItem.makeEnumStatsItem(Status.class, "Status")), Note(StatsItem.makeStringStatsItem("Message", 200)), ; StatsItem si; ColStatsItems(StatsItem si) {this.si=si;} public StatsItem si() {return si;} } public static enum Generator implements StatsGenerator { INSTANCE; class ColStats extends Stats { public ColStats(String key) { super(details, key); } } public ColStats create(String key) {return new ColStats(key);} } public static StatsItemConfig details = StatsItemConfig.create(ColStatsItems.class); public SwapDelimitedColumns(FTDriver dt) { super(dt); this.ftprops.add(new FTPropEnum(dt, this.getClass().getName(), DELIM, DELIM, "Delimiter character separating fields", Sep.values(), Sep.CSV)); ftprops.add(new FTPropString(dt, this.getClass().getSimpleName(), COLA, COLA, "Column A to Swap", "")); ftprops.add(new FTPropString(dt, this.getClass().getSimpleName(), COLB, COLB, "Column B to Swap", "")); } @Override public InitializationStatus init() { InitializationStatus is = super.init(); cNameA = getProperty(COLA, "").toString(); cNameB = getProperty(COLB, "").toString(); if (cNameA.isEmpty() || cNameB.isEmpty()) { is.addFailMessage("ColA and ColB cannot be blank"); return is; } if (cNameA.equals(cNameB)) { is.addFailMessage("ColA and ColB should not be equal"); } return is; } @Override public String getDescription() { return "Swap Delimited File Columns\n\nTHIS RULE WILL OVERWRITE FILES. MAKE A BACKUP."; } @Override public String toString() { return "Swap CSV Columns"; } @Override public Object fileTest(File f) { Stats stats = getStats(f); Sep sep = (Sep)getProperty(DELIM); CSVFormat csvf = (sep == Sep.TSV) ? CSVFormat.TDF : CSVFormat.DEFAULT; try(FileReader fr = new FileReader(f)) { CSVParser cp = CSVParser.parse(f, Charset.forName("UTF-8"), csvf.withHeader()); Map<String,Integer> headers = cp.getHeaderMap(); Integer cola = headers.get(cNameA); if (cola == null) { stats.setVal(ColStatsItems.Status, Status.ColNotFound); stats.setVal(ColStatsItems.Note, String.format("Col [%s] not found", cNameA)); return Status.ColNotFound; } Integer colb = headers.get(cNameB); if (colb == null) { stats.setVal(ColStatsItems.Status, Status.ColNotFound); stats.setVal(ColStatsItems.Note, String.format("Col [%s] not found", cNameB)); return Status.ColNotFound; } cp = CSVParser.parse(f, Charset.forName("UTF-8"), csvf); ArrayList<ArrayList<String>> data = new ArrayList<>(); ArrayList<String> row = new ArrayList<>(); for(CSVRecord rec: cp.getRecords()) { row = new ArrayList<>(); data.add(row); for(int i=0; i<rec.size(); i++) { int col = i; if (col == cola) { col = colb; } else if (col == colb) { col = cola; } row.add(rec.get(col)); } } try( FileWriter fw = new FileWriter(f); CSVPrinter cprint = new CSVPrinter(fw, csvf); ) { cprint.printRecords(data); } stats.setVal(ColStatsItems.Status, Status.Updated); stats.setVal(ColStatsItems.Note, String.format("Record Count [%06d]", data.size())); } catch (IOException e) { stats.setVal(ColStatsItems.Status, Status.Failed); stats.setVal(ColStatsItems.Note, e.getMessage()); } return Status.Updated; } @Override public ColStats createStats(String key){ return Generator.INSTANCE.create(key); } @Override public StatsItemConfig getStatsDetails() { return details; } @Override public String getShortName() { return "SwapCol"; } public void initFilters() { filters.add(new CSVFilter()); } @Override public String getKey(File f) { return f.getPath(); } }
package org.camunda.bpm.engine.test.jobexecutor; import org.apache.ibatis.session.SqlSession; import org.camunda.bpm.engine.impl.Page; import org.camunda.bpm.engine.impl.interceptor.Command; import org.camunda.bpm.engine.impl.interceptor.CommandContext; import org.camunda.bpm.engine.impl.interceptor.CommandExecutor; import org.camunda.bpm.engine.impl.persistence.entity.JobEntity; import org.camunda.bpm.engine.impl.persistence.entity.JobManager; import org.camunda.bpm.engine.impl.persistence.entity.TimerEntity; import org.camunda.bpm.engine.impl.test.PluggableProcessEngineTestCase; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.List; /** * <p>This testcase verifies that jobs without suspension state are correctly picked up by the job acquisition</p> * * @author Christian Lipphardt * */ public class JobAcquisitionTest extends PluggableProcessEngineTestCase { public void testJobAcquisitionForJobsWithoutSuspensionStateSet() { final String processInstanceId = "1"; final String myCustomTimerEntity = "myCustomTimerEntity"; final TimerEntity timer = new TimerEntity(); timer.setRetries(3); timer.setDuedate(null); timer.setLockOwner(null); timer.setLockExpirationTime(null); timer.setJobHandlerConfiguration(myCustomTimerEntity); timer.setProcessInstanceId(processInstanceId); CommandExecutor commandExecutor = processEngineConfiguration.getCommandExecutorTxRequired(); // we create a timer entity commandExecutor.execute(new Command<Void>() { public Void execute(CommandContext commandContext) { commandContext.getJobManager().insert(timer); return null; } }); // we change the suspension state to null commandExecutor.execute(new Command<Void>() { public Void execute(CommandContext commandContext) { try { SqlSession sqlSession = commandContext.getDbSqlSession().getSqlSession(); PreparedStatement preparedStatement = sqlSession.getConnection() .prepareStatement("UPDATE ACT_RU_JOB SET SUSPENSION_STATE_ = NULL"); assertEquals(1, preparedStatement.executeUpdate()); } catch (SQLException e) { throw new RuntimeException(e); } return null; } }); // it is picked up by the acquisition queries commandExecutor.execute(new Command<Void>() { public Void execute(CommandContext commandContext) { JobManager jobManager = commandContext.getJobManager(); List<JobEntity> executableJobs = jobManager.findNextJobsToExecute(new Page(0, 1)); assertEquals(1, executableJobs.size()); assertEquals(myCustomTimerEntity, executableJobs.get(0).getJobHandlerConfiguration()); executableJobs = jobManager.findExclusiveJobsToExecute(processInstanceId); assertEquals(1, executableJobs.size()); assertEquals(myCustomTimerEntity, executableJobs.get(0).getJobHandlerConfiguration()); return null; } }); // cleanup commandExecutor.execute(new Command<Void>() { public Void execute(CommandContext commandContext) { commandContext.getJobManager().delete(timer); return null; } }); } }
package org.apache.felix.ipojo.everest.servlet; import com.google.common.collect.ImmutableMap; import org.apache.felix.ipojo.everest.impl.DefaultResource; import org.apache.felix.ipojo.everest.impl.ImmutableResourceMetadata; import org.apache.felix.ipojo.everest.services.IllegalResourceException; import org.apache.felix.ipojo.everest.services.Resource; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.io.StringWriter; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.List; import static org.fest.assertions.Assertions.assertThat; /** * Test the behavior of the toJson methods */ public class ToJsonTest { private EverestServlet servlet; @Before public void setUp() { servlet = new EverestServlet(); } @Test public void serializationOfString() throws IllegalResourceException, IOException { StringWriter writer = new StringWriter(); String s = "this is a string"; Resource resource = new DefaultResource.Builder() .fromPath("/foo") .with(new ImmutableResourceMetadata.Builder().set("data", s).build()) .build(); servlet.toJSON(resource, writer); assertThat(writer.toString()).isEqualToIgnoringCase("{\"data\":\"" + s + "\"}"); } @Test public void serializationOfNull() throws IllegalResourceException, IOException { StringWriter writer = new StringWriter(); Resource resource = new DefaultResource.Builder() .fromPath("/foo") .with(new ImmutableResourceMetadata.Builder().set("data", null).build()) .build(); servlet.toJSON(resource, writer); assertThat(writer.toString()).isEqualToIgnoringCase("{\"data\":null}"); } @Test public void serializationOfNumbers() throws IllegalResourceException, IOException { StringWriter writer = new StringWriter(); Resource resource = new DefaultResource.Builder() .fromPath("/foo") .with(new ImmutableResourceMetadata.Builder() .set("int", 1) .set("double", 1d) .build()) .build(); servlet.toJSON(resource, writer); assertThat(writer.toString()).contains("\"int\":" + 1); assertThat(writer.toString()).contains("\"double\":" + 1.0); } @Test public void serializationOfBooleans() throws IllegalResourceException, IOException { StringWriter writer = new StringWriter(); Resource resource = new DefaultResource.Builder() .fromPath("/foo") .with(new ImmutableResourceMetadata.Builder() .set("right", true) .set("wrong", false) .build()) .build(); servlet.toJSON(resource, writer); assertThat(writer.toString()).contains("\"right\":" + true); assertThat(writer.toString()).contains("\"wrong\":" + false); } @Test public void serializationOfSimpleLists() throws IllegalResourceException, IOException { StringWriter writer = new StringWriter(); List<String> l1 = Arrays.asList("a", "b", "c"); List<Integer> l2 = Arrays.asList(1, 2, 3); Resource resource = new DefaultResource.Builder() .fromPath("/foo") .with(new ImmutableResourceMetadata.Builder() .set("l1", l1) .set("l2", l2) .build()) .build(); servlet.toJSON(resource, writer); assertThat(writer.toString()).contains("\"l1\":[\"a\",\"b\",\"c\"]"); assertThat(writer.toString()).contains("\"l2\":[1,2,3]"); } @Test public void serializationOfArrays() throws IllegalResourceException, IOException { StringWriter writer = new StringWriter(); String[] a1 = new String[]{"a", "b", "c"}; int[] a2 = new int[]{1, 2, 3}; Resource resource = new DefaultResource.Builder() .fromPath("/foo") .with(new ImmutableResourceMetadata.Builder() .set("l1", a1) .set("l2", a2) .build()) .build(); servlet.toJSON(resource, writer); assertThat(writer.toString()).contains("\"l1\":[\"a\",\"b\",\"c\"]"); assertThat(writer.toString()).contains("\"l2\":[1,2,3]"); } @Test public void serializationOfSimpleSets() throws IllegalResourceException, IOException { StringWriter writer = new StringWriter(); List<String> l1 = Arrays.asList("a", "b", "c"); List<Integer> l2 = Arrays.asList(1, 2, 3); Resource resource = new DefaultResource.Builder() .fromPath("/foo") .with(new ImmutableResourceMetadata.Builder() .set("l1", new LinkedHashSet(l1)) .set("l2", new LinkedHashSet(l2)) .build()) .build(); servlet.toJSON(resource, writer); assertThat(writer.toString()).contains("\"l1\":[\"a\",\"b\",\"c\"]"); assertThat(writer.toString()).contains("\"l2\":[1,2,3]"); } @Test public void serializationOfMaps() throws IllegalResourceException, IOException { StringWriter writer = new StringWriter(); ImmutableMap<String, String> mapOfString = new ImmutableMap.Builder<String, String>() .put("one", "1") .put("two", "2") .build(); ImmutableMap<String, Integer> mapOfInt = new ImmutableMap.Builder<String, Integer>() .put("one", 1) .put("two", 2) .build(); Resource resource = new DefaultResource.Builder() .fromPath("/foo") .with(new ImmutableResourceMetadata.Builder() .set("m1", mapOfString) .set("m2", mapOfInt) .build()) .build(); servlet.toJSON(resource, writer); assertThat(writer.toString()).contains("\"m1\":{\"one\":\"1\",\"two\":\"2\"}"); assertThat(writer.toString()).contains("\"m2\":{\"one\":1,\"two\":2}"); } @Test public void serializationOfComplexList() throws IllegalResourceException, IOException { StringWriter writer = new StringWriter(); List<ImmutableMap<String, List<Integer>>> l1 = Arrays.asList( new ImmutableMap.Builder<String, List<Integer>>() .put("a1", Arrays.asList(1, 2, 3)) .put("a2", Arrays.asList(4, 5, 6)).build(), new ImmutableMap.Builder<String, List<Integer>>() .put("b1", Arrays.asList(9, 8, 7)) .put("b2", Arrays.asList(6, 5, 4)).build() ); Resource resource = new DefaultResource.Builder() .fromPath("/foo") .with(new ImmutableResourceMetadata.Builder() .set("object", l1) .build()) .build(); servlet.toJSON(resource, writer); assertThat(writer.toString()).isEqualToIgnoringCase( "{\"object\":[" + "{\"a1\":[1,2,3],\"a2\":[4,5,6]}," + "{\"b1\":[9,8,7],\"b2\":[6,5,4]}" + "]}"); } }
package com.matthewtamlin.mixtape.example.activities; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import com.matthewtamlin.mixtape.example.R; import com.matthewtamlin.mixtape.example.data.Mp3Album; import com.matthewtamlin.mixtape.example.data.Mp3AlbumDataSource; import com.matthewtamlin.mixtape.library.caching.LibraryItemCache; import com.matthewtamlin.mixtape.library.caching.LruLibraryItemCache; import com.matthewtamlin.mixtape.library.data.DisplayableDefaults; import com.matthewtamlin.mixtape.library.data.ImmutableDisplayableDefaults; import com.matthewtamlin.mixtape.library.databinders.ArtworkBinder; import com.matthewtamlin.mixtape.library.databinders.SubtitleBinder; import com.matthewtamlin.mixtape.library.databinders.TitleBinder; import com.matthewtamlin.mixtape.library.mixtape_body.GridBody; import com.matthewtamlin.mixtape.library.mixtape_body.RecyclerViewBodyPresenter; import com.matthewtamlin.mixtape.library.mixtape_coordinator.CoordinatedMixtapeContainer; public class GridActivity extends AppCompatActivity { private GridBody body; private LibraryItemCache cache; private Mp3AlbumDataSource dataSource; private RecyclerViewBodyPresenter<Mp3Album, Mp3AlbumDataSource> presenter; @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle("Albums"); setupView(); setupDataSource(); setupPresenter(); presenter.setView(body); presenter.setDataSource(dataSource); presenter.present(true); } private void setupView() { setContentView(R.layout.example_layout); final CoordinatedMixtapeContainer container = (CoordinatedMixtapeContainer) findViewById (R.id.example_layout_coordinator); body = new GridBody(this); container.setBody(body); } private void setupDataSource() { dataSource = new Mp3AlbumDataSource(); } private void setupPresenter() { final Bitmap defaultArtwork = BitmapFactory.decodeResource(getResources(), R.raw .default_artwork); final DisplayableDefaults defaults = new ImmutableDisplayableDefaults( "Unknown title", "Unknown subtitle", defaultArtwork); cache = new LruLibraryItemCache(10000, 10000, 10000000); final TitleBinder titleBinder = new TitleBinder(cache, defaults); final SubtitleBinder subtitleBinder = new SubtitleBinder(cache, defaults); final ArtworkBinder artworkBinder = new ArtworkBinder(cache, defaults, 300); presenter = new RecyclerViewBodyPresenter<>(titleBinder, subtitleBinder, artworkBinder); } }
package arez.processor; import com.google.auto.common.AnnotationMirrors; import com.google.common.collect.ImmutableMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.lang.model.AnnotatedConstruct; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.ExecutableElement; import javax.lang.model.type.TypeMirror; @SuppressWarnings( { "SameParameterValue", "WeakerAccess", "unused", "RedundantSuppression" } ) final class AnnotationsUtil { private AnnotationsUtil() { } @SuppressWarnings( "unchecked" ) @Nonnull static List<TypeMirror> getTypeMirrorsAnnotationParameter( @Nonnull final AnnotatedConstruct annotated, @Nonnull final String annotationClassName, @Nonnull final String parameterName ) { final AnnotationValue annotationValue = getAnnotationValue( annotated, annotationClassName, parameterName ); return ( (List<AnnotationValue>) annotationValue.getValue() ) .stream() .map( v -> (TypeMirror) v.getValue() ).collect( Collectors.toList() ); } @Nonnull static AnnotationValue getAnnotationValue( @Nonnull final AnnotatedConstruct annotated, @Nonnull final String annotationClassName, @Nonnull final String parameterName ) { final AnnotationValue value = findAnnotationValue( annotated, annotationClassName, parameterName ); assert null != value; return value; } @Nullable private static AnnotationValue findAnnotationValue( @Nonnull final AnnotatedConstruct annotated, @Nonnull final String annotationClassName, @Nonnull final String parameterName ) { final AnnotationMirror mirror = findAnnotationByType( annotated, annotationClassName ); return null == mirror ? null : findAnnotationValue( mirror, parameterName ); } @Nullable private static AnnotationValue findAnnotationValue( @Nonnull final AnnotationMirror annotation, @Nonnull final String parameterName ) { final ImmutableMap<ExecutableElement, AnnotationValue> values = AnnotationMirrors.getAnnotationValuesWithDefaults( annotation ); final ExecutableElement annotationKey = values.keySet().stream(). filter( k -> parameterName.equals( k.getSimpleName().toString() ) ).findFirst().orElse( null ); return values.get( annotationKey ); } @Nullable static AnnotationValue findAnnotationValueNoDefaults( @Nonnull final AnnotationMirror annotation, @Nonnull final String parameterName ) { final Map<? extends ExecutableElement, ? extends AnnotationValue> values = annotation.getElementValues(); final ExecutableElement annotationKey = values.keySet().stream(). filter( k -> parameterName.equals( k.getSimpleName().toString() ) ).findFirst().orElse( null ); return values.get( annotationKey ); } @SuppressWarnings( "unchecked" ) @Nonnull static <T> T getAnnotationValue( @Nonnull final AnnotationMirror annotation, @Nonnull final String parameterName ) { final AnnotationValue value = findAnnotationValue( annotation, parameterName ); assert null != value; return (T) value.getValue(); } @Nonnull static AnnotationMirror getAnnotationByType( @Nonnull final AnnotatedConstruct annotated, @Nonnull final String annotationClassName ) { AnnotationMirror mirror = findAnnotationByType( annotated, annotationClassName ); assert null != mirror; return mirror; } @Nullable static AnnotationMirror findAnnotationByType( @Nonnull final AnnotatedConstruct annotated, @Nonnull final String annotationClassName ) { return annotated.getAnnotationMirrors().stream(). filter( a -> a.getAnnotationType().toString().equals( annotationClassName ) ).findFirst().orElse( null ); } static boolean hasAnnotationOfType( @Nonnull final AnnotatedConstruct annotated, @Nonnull final String annotationClassName ) { return null != findAnnotationByType( annotated, annotationClassName ); } }
package de.jpaw.fixedpoint.tests; import java.util.Arrays; import org.testng.Assert; import org.testng.annotations.Test; import de.jpaw.fixedpoint.types.Units; @Test public class TestRoundingDistribution { private void runTestScaleDown(long [] unscaled, long [] scaled, int scale) { // validate test case long sum = 0; for (int i = 1; i < unscaled.length; ++i) sum += unscaled[i]; Assert.assertEquals(sum, unscaled[0]); long [] actuals = Units.ZERO.roundWithErrorDistribution(unscaled, 2); assert(Arrays.equals(actuals, scaled)); } public void testPositiveVector() throws Exception { final long [] h = { 297, 148, 149 }; final long [] i = { 3, 1, 2 }; runTestScaleDown(h, i, 2); } public void testMixedSignVector() throws Exception { final long [] h = { 8, -144, 152 }; final long [] i = { 0, -1, 1 }; runTestScaleDown(h, i, 2); } public void testMiniAmountsVector() throws Exception { final long [] h = { 339, 49, 48, 49, 47, 48, 51, 47 }; final long [] i = { 3, 1, 0, 1, 0, 0, 1, 0 }; runTestScaleDown(h, i, 2); } }
package org.zkoss.ganttz.data.criticalpath; 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.joda.time.Days; import org.joda.time.LocalDate; import org.zkoss.ganttz.data.DependencyType; import org.zkoss.ganttz.data.GanttDate; import org.zkoss.ganttz.data.IDependency; import org.zkoss.ganttz.data.constraint.Constraint; /** * Class that calculates the critical path of a Gantt diagram graph. * * @author Manuel Rego Casasnovas <mrego@igalia.com> */ public class CriticalPathCalculator<T, D extends IDependency<T>> { public static <T, D extends IDependency<T>> CriticalPathCalculator<T, D> create() { return new CriticalPathCalculator<T, D>(); } private ICriticalPathCalculable<T> graph; private LocalDate initDate; private Map<T, Node<T, D>> nodes; private InitialNode<T, D> bop; private LastNode<T, D> eop; public List<T> calculateCriticalPath(ICriticalPathCalculable<T> graph) { this.graph = graph; initDate = calculateInitDate(); bop = createBeginningOfProjectNode(); eop = createEndOfProjectNode(); nodes = createGraphNodes(); forward(bop, null); eop.updateLatestValues(); backward(eop, null); return getTasksOnCriticalPath(); } private LocalDate calculateInitDate() { List<T> initialTasks = graph.getInitialTasks(); if (initialTasks.isEmpty()) { return null; } GanttDate ganttDate = Collections.min(getStartDates()); return LocalDate.fromDateFields(ganttDate.toDayRoundedDate()); } private List<GanttDate> getStartDates() { List<GanttDate> result = new ArrayList<GanttDate>(); for (T task : graph.getInitialTasks()) { result.add(graph.getStartDate(task)); } return result; } private Collection<T> removeContainers(Collection<T> tasks) { if (tasks == null) { return Collections.emptyList(); } List<T> noConatinersTasks = new ArrayList<T>(); for (T t : tasks) { if (graph.isContainer(t)) { List<T> children = graph.getChildren(t); noConatinersTasks.addAll(removeContainers(children)); } else { noConatinersTasks.add(t); } } return noConatinersTasks; } private InitialNode<T, D> createBeginningOfProjectNode() { return new InitialNode<T, D>(new HashSet<T>(removeContainers(graph .getInitialTasks()))); } private LastNode<T, D> createEndOfProjectNode() { return new LastNode<T, D>(new HashSet<T>(removeContainers(graph .getLatestTasks()))); } private Map<T, Node<T, D>> createGraphNodes() { Map<T, Node<T, D>> result = new HashMap<T, Node<T, D>>(); for (T task : graph.getTasks()) { if (!graph.isContainer(task)) { Set<T> in = getRelatedTasksFor(task, true); Set<T> out = getRelatedTasksFor(task, false); Node<T, D> node = new Node<T, D>(task, in, out, graph .getStartDate(task), graph.getEndDateFor(task)); result.put(task, node); } } return result; } private Set<T> getRelatedTasksFor(T task, boolean incoming) { Set<T> result = new HashSet<T>(); Set<T> relatedTasks; if (incoming) { relatedTasks = graph.getIncomingTasksFor(task); } else { relatedTasks = graph.getOutgoingTasksFor(task); } for (T t : relatedTasks) { if (graph.isContainer(t) && graph.contains(t, task)) { Set<T> related; if (incoming) { related = graph.getIncomingTasksFor(t); } else { related = graph.getOutgoingTasksFor(t); } result.addAll(removeChildrenAndParents(t, related)); } else { result.add(t); } } return new HashSet<T>(removeContainers(result)); } private Collection<? extends T> removeChildrenAndParents(T task, Set<T> tasks) { Set<T> result = new HashSet<T>(); for (T t : tasks) { if (!graph.contains(task, t)) { if (!graph.isContainer(t) || !graph.contains(t, task)) { result.add(t); } } } return result; } private DependencyType getDependencyTypeEndStartByDefault(T from, T to) { if ((from != null) && (to != null)) { IDependency<T> dependency = graph.getDependencyFrom(from, to); if (dependency != null) { return dependency.getType(); } } return DependencyType.END_START; } private void forward(Node<T, D> currentNode, T previousTask) { T currentTask = currentNode.getTask(); int earliestStart = currentNode.getEarliestStart(); int earliestFinish = currentNode.getEarliestFinish(); Set<T> nextTasks = currentNode.getNextTasks(); if (nextTasks.isEmpty()) { eop.setEarliestStart(earliestFinish); } else { int countStartStart = 0; for (T task : nextTasks) { if (graph.isContainer(currentTask)) { if (graph.contains(currentTask, previousTask)) { if (graph.contains(currentTask, task)) { continue; } } } Node<T, D> node = nodes.get(task); DependencyType dependencyType = getDependencyTypeEndStartByDefault( currentTask, task); Constraint<GanttDate> constraint = getDateConstraint(task); switch (dependencyType) { case START_START: setEarliestStart(node, earliestStart, constraint); countStartStart++; break; case END_END: setEarliestStart(node, earliestFinish - node.getDuration(), constraint); break; case END_START: default: setEarliestStart(node, earliestFinish, constraint); break; } forward(node, currentTask); } if (nextTasks.size() == countStartStart) { eop.setEarliestStart(earliestFinish); } } } private void setEarliestStart(Node<T, D> node, int earliestStart, Constraint<GanttDate> constraint) { if (constraint != null) { GanttDate date = GanttDate.createFrom(initDate .plusDays(earliestStart)); date = constraint.applyTo(date); earliestStart = Days.daysBetween(initDate, LocalDate.fromDateFields(date.toDayRoundedDate())) .getDays(); } node.setEarliestStart(earliestStart); } private Constraint<GanttDate> getDateConstraint(T task) { if (task == null) { return null; } List<Constraint<GanttDate>> constraints = graph .getStartConstraintsFor(task); if (constraints == null) { return null; } return Constraint.coalesce(constraints); } private void backward(Node<T, D> currentNode, T nextTask) { T currentTask = currentNode.getTask(); int latestStart = currentNode.getLatestStart(); int latestFinish = currentNode.getLatestFinish(); Set<T> previousTasks = currentNode.getPreviousTasks(); if (previousTasks.isEmpty()) { bop.setLatestFinish(latestStart); } else { int countEndEnd = 0; for (T task : previousTasks) { if (graph.isContainer(currentTask)) { if (graph.contains(currentTask, nextTask)) { if (graph.contains(currentTask, task)) { continue; } } } Node<T, D> node = nodes.get(task); DependencyType dependencyType = getDependencyTypeEndStartByDefault( task, currentTask); Constraint<GanttDate> constraint = getDateConstraint(task); switch (dependencyType) { case START_START: setLatestFinish(node, latestStart + node.getDuration(), constraint); break; case END_END: setLatestFinish(node, latestFinish, constraint); countEndEnd++; break; case END_START: default: setLatestFinish(node, latestStart, constraint); break; } backward(node, currentTask); } if (previousTasks.size() == countEndEnd) { bop.setLatestFinish(latestStart); } } } private void setLatestFinish(Node<T, D> node, int latestFinish, Constraint<GanttDate> constraint) { if (constraint != null) { int duration = node.getDuration(); GanttDate date = GanttDate.createFrom(initDate.plusDays(latestFinish - duration)); date = constraint.applyTo(date); int daysBetween = Days.daysBetween(initDate, LocalDate.fromDateFields(date.toDayRoundedDate())) .getDays(); latestFinish = daysBetween + duration; } node.setLatestFinish(latestFinish); } private List<T> getTasksOnCriticalPath() { List<T> result = new ArrayList<T>(); for (Node<T, D> node : nodes.values()) { if (node.getLatestStart() == node.getEarliestStart()) { result.add(node.getTask()); } } return result; } }
package org.jnosql.artemis.graph; import org.apache.tinkerpop.gremlin.structure.Vertex; /** * This interface represent the manager of events. When an entity be either saved or updated an event will be fired. This order gonna be: * 1) firePreEntity * 2) firePreGraphEntity * 3) firePreGraph * 4) firePostGraph * 5) firePostEntity * 6) firePostGraphEntity * * @see GraphWorkflow */ public interface GraphEventPersistManager { /** * Fire an event after the conversion of the entity to communication API model. * * @param entity the entity */ void firePreGraph(Vertex entity); /** * Fire an event after the response from communication layer * * @param entity the entity */ void firePostGraph(Vertex entity); /** * Fire an event once the method is called * * @param entity the entity * @param <T> the entity type */ <T> void firePreEntity(T entity); /** * Fire an event after convert the {@link Vertex}, * from database response, to Entity. * * @param entity the entity * @param <T> the entity kind */ <T> void firePostEntity(T entity); /** * Fire an event once the method is called after firePreEntity * * @param entity the entity * @param <T> the entity type */ <T> void firePreGraphEntity(T entity); /** * Fire an event after firePostEntity * * @param entity the entity * @param <T> the entity kind */ <T> void firePostGraphEntity(T entity); }
package arez; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Objects; import java.util.stream.Stream; import javax.annotation.Nonnull; import javax.annotation.Nullable; import static org.realityforge.braincheck.Guards.*; /** * Basic implementation of task queue that supports priority based queuing of tasks. */ final class MultiPriorityTaskQueue implements TaskQueue { /** * The default number of priorities. */ static final int DEFAULT_PRIORITY_COUNT = 5; /** * The default of slots in each priority buffer. */ static final int DEFAULT_BUFFER_SIZE = 100; /** * A buffer per priority containing tasks that have been scheduled but are not executing. */ @Nonnull private final CircularBuffer<Task>[] _taskQueues; /** * Construct the queue with priority count specified by {@link #DEFAULT_PRIORITY_COUNT} where each priority is backed by a buffer with default size specified by {@link #DEFAULT_BUFFER_SIZE}. */ MultiPriorityTaskQueue() { this( DEFAULT_PRIORITY_COUNT, DEFAULT_BUFFER_SIZE ); } /** * Construct queue with specified priority count where each priority is backed by a buffer with specified size. * * @param priorityCount the number of priorities supported. * @param bufferSize the initial size of buffer for each priority. */ @SuppressWarnings( "unchecked" ) MultiPriorityTaskQueue( final int priorityCount, final int bufferSize ) { assert priorityCount > 0; assert bufferSize > 0; _taskQueues = (CircularBuffer<Task>[]) new CircularBuffer[ priorityCount ]; for ( int i = 0; i < priorityCount; i++ ) { _taskQueues[ i ] = new CircularBuffer<>( bufferSize ); } } /** * Return the number of priorities handled by the queue. * * @return the number of priorities handled by the queue. */ int getPriorityCount() { return _taskQueues.length; } /** * {@inheritDoc} */ @Override public int getQueueSize() { int count = 0; //noinspection ForLoopReplaceableByForEach for ( int i = 0; i < _taskQueues.length; i++ ) { count += _taskQueues[ i ].size(); } return count; } /** * {@inheritDoc} */ @Override public boolean hasTasks() { //noinspection ForLoopReplaceableByForEach for ( int i = 0; i < _taskQueues.length; i++ ) { if ( !_taskQueues[ i ].isEmpty() ) { return true; } } return false; } /** * Add the specified task to the queue. * The task must not already be in the queue. * * @param priority the task priority. * @param task the task. */ public void queueTask( final int priority, @Nonnull final Task task ) { if ( Arez.shouldCheckInvariants() ) { invariant( () -> Arrays.stream( _taskQueues ).noneMatch( b -> b.contains( task ) ), () -> "Arez-0099: Attempting to schedule task named '" + task.getName() + "' when task is already in queues." ); //TODO: Turn this into invariant assert priority >= 0 && priority < _taskQueues.length; } _taskQueues[ priority ].add( Objects.requireNonNull( task ) ); } /** * {@inheritDoc} */ @Nullable @Override public Task dequeueTask() { // Return the highest priority taskQueue that has tasks in it and return task. //noinspection ForLoopReplaceableByForEach for ( int i = 0; i < _taskQueues.length; i++ ) { final CircularBuffer<Task> taskQueue = _taskQueues[ i ]; if ( !taskQueue.isEmpty() ) { final Task task = taskQueue.pop(); assert null != task; return task; } } return null; } /** * {@inheritDoc} */ @Override public Collection<Task> clear() { final ArrayList<Task> tasks = new ArrayList<>(); //noinspection ForLoopReplaceableByForEach for ( int i = 0; i < _taskQueues.length; i++ ) { final CircularBuffer<Task> taskQueue = _taskQueues[ i ]; taskQueue.stream().forEach( tasks::add ); taskQueue.clear(); } return tasks; } /** * {@inheritDoc} */ @Nonnull @Override public Stream<Task> getOrderedTasks() { assert Arez.shouldCheckInvariants() || Arez.shouldCheckApiInvariants(); return Stream.of( _taskQueues ).flatMap( CircularBuffer::stream ); } @Nonnull CircularBuffer<Task> getTasksByPriority( final int priority ) { return _taskQueues[ priority ]; } }
package jenkins.install; import static java.util.logging.Level.SEVERE; import static java.util.logging.Level.WARNING; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Logger; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import org.apache.commons.io.FileUtils; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; import com.thoughtworks.xstream.XStream; import hudson.Functions; import hudson.model.UpdateCenter.DownloadJob.InstallationStatus; import hudson.model.UpdateCenter.DownloadJob.Installing; import hudson.model.UpdateCenter.InstallationJob; import hudson.model.UpdateCenter.UpdateCenterJob; import hudson.util.VersionNumber; import jenkins.model.Jenkins; import jenkins.util.xml.XMLUtils; /** * Jenkins install utilities. * * @author <a href="mailto:tom.fennelly@gmail.com">tom.fennelly@gmail.com</a> */ @Restricted(NoExternalUse.class) public class InstallUtil { private static final Logger LOGGER = Logger.getLogger(InstallUtil.class.getName()); // must use something less than 1.0, as Jenkins may // report back 1.0 if the system config page has never been saved, // which erroneously leads to installer running private static final VersionNumber NEW_INSTALL_VERSION = new VersionNumber("0.0.0"); /** * Get the current installation state. * @return The type of "startup" currently under way in Jenkins. */ public static InstallState getInstallState() { // install wizard will always run if environment specified if (!Boolean.getBoolean("jenkins.install.runSetupWizard")) { if (Functions.getIsUnitTest()) { return InstallState.TEST; } if (Boolean.getBoolean("hudson.Main.development")) { return InstallState.DEVELOPMENT; } } VersionNumber lastRunVersion = new VersionNumber(getLastExecVersion()); // Neither the top level config or the lastExecVersionFile have a version // stored in them, which means it's a new install. if (lastRunVersion.compareTo(NEW_INSTALL_VERSION) == 0) { return InstallState.NEW; } // We have a last version. VersionNumber currentRunVersion = new VersionNumber(getCurrentExecVersion()); if (lastRunVersion.isOlderThan(currentRunVersion)) { return InstallState.UPGRADE; } else if (lastRunVersion.isNewerThan(currentRunVersion)) { return InstallState.DOWNGRADE; } else { // Last running version was the same as "this" running version. return InstallState.RESTART; } } /** * Save the current Jenkins instance version as the last executed version. * <p> * This state information is required in order to determine whether or not the Jenkins instance * is just restarting, or is being upgraded from an earlier version. */ public static void saveLastExecVersion() { if (Jenkins.VERSION.equals(Jenkins.UNCOMPUTED_VERSION)) { // This should never happen!! Only adding this check in case someone moves the call to this method to the wrong place. throw new IllegalStateException("Unexpected call to InstallUtil.saveLastExecVersion(). Jenkins.VERSION has not been initialized. Call computeVersion() first."); } saveLastExecVersion(Jenkins.VERSION); } /** * Get the last saved Jenkins instance version. * @return The last saved Jenkins instance version. * @see #saveLastExecVersion() */ public static @Nonnull String getLastExecVersion() { File lastExecVersionFile = getLastExecVersionFile(); if (lastExecVersionFile.exists()) { try { return FileUtils.readFileToString(lastExecVersionFile); } catch (IOException e) { LOGGER.log(SEVERE, "Unexpected Error. Unable to read " + lastExecVersionFile.getAbsolutePath(), e); LOGGER.log(WARNING, "Unable to determine the last running version (see error above). Treating this as a restart. No plugins will be updated."); return getCurrentExecVersion(); } } else { // Backward compatibility. Use the last version stored in the top level config.xml. // Going to read the value directly from the config.xml file Vs hoping that the // Jenkins startup sequence has moved far enough along that it has loaded the // global config. It can't load the global config until well into the startup // sequence because the unmarshal requires numerous objects to be created e.g. // it requires the Plugin Manager. It happens too late and it's too risky to // change how it currently works. File configFile = getConfigFile(); if (configFile.exists()) { try { String lastVersion = XMLUtils.getValue("/hudson/version", configFile); if (lastVersion.length() > 0) { return lastVersion; } } catch (Exception e) { LOGGER.log(SEVERE, "Unexpected error reading global config.xml", e); } } return NEW_INSTALL_VERSION.toString(); } } /** * Save a specific version as the last execute version. * @param version The version to save. */ static void saveLastExecVersion(@Nonnull String version) { File lastExecVersionFile = getLastExecVersionFile(); try { FileUtils.write(lastExecVersionFile, version); } catch (IOException e) { LOGGER.log(SEVERE, "Failed to save " + lastExecVersionFile.getAbsolutePath(), e); } } static File getConfigFile() { return new File(Jenkins.getActiveInstance().getRootDir(), "config.xml"); } static File getLastExecVersionFile() { return new File(Jenkins.getActiveInstance().getRootDir(), ".last_exec_version"); } static File getInstallingPluginsFile() { return new File(Jenkins.getActiveInstance().getRootDir(), ".installing_plugins"); } private static String getCurrentExecVersion() { if (Jenkins.VERSION.equals(Jenkins.UNCOMPUTED_VERSION)) { // This should never happen!! Only adding this check in case someone moves the call to this method to the wrong place. throw new IllegalStateException("Unexpected call to InstallUtil.getCurrentExecVersion(). Jenkins.VERSION has not been initialized. Call computeVersion() first."); } return Jenkins.VERSION; } /** * Returns a list of any plugins that are persisted in the installing list */ @SuppressWarnings("unchecked") public static synchronized @CheckForNull Map<String,String> getPersistedInstallStatus() { File installingPluginsFile = getInstallingPluginsFile(); if(installingPluginsFile == null || !installingPluginsFile.exists()) { return null; } return (Map<String,String>)new XStream().fromXML(installingPluginsFile); } /** * Persists a list of installing plugins; this is used in the case Jenkins fails mid-installation and needs to be restarted * @param installingPlugins */ public static synchronized void persistInstallStatus(List<UpdateCenterJob> installingPlugins) { File installingPluginsFile = getInstallingPluginsFile(); if(installingPlugins == null || installingPlugins.isEmpty()) { installingPluginsFile.delete(); return; } LOGGER.fine("Writing install state to: " + installingPluginsFile.getAbsolutePath()); Map<String,String> statuses = new HashMap<String,String>(); for(UpdateCenterJob j : installingPlugins) { if(j instanceof InstallationJob && j.getCorrelationId() != null) { // only include install jobs with a correlation id (directly selected) InstallationJob ij = (InstallationJob)j; InstallationStatus status = ij.status; String statusText = status.getType(); if(status instanceof Installing) { // flag currently installing plugins as pending statusText = "Pending"; } statuses.put(ij.plugin.name, statusText); } } try { String installingPluginXml = new XStream().toXML(statuses); FileUtils.write(installingPluginsFile, installingPluginXml); } catch (IOException e) { LOGGER.log(SEVERE, "Failed to save " + installingPluginsFile.getAbsolutePath(), e); } } /** * Call to remove any active install status */ public static void clearInstallStatus() { persistInstallStatus(null); } }
package org.cache2k.impl; /** * Straight forward CLOCK implementation. This is probably the simplest * eviction algorithm around. Interestingly it produces good results. * * @author Jens Wilke; created: 2013-12-01 */ public class ClockCache<K, T> extends LockFreeCache<ClockCache.Entry, K, T> { long hits; int runCnt; int scan24hCnt; int scanCnt; int size; Entry hand; @Override public long getHitCnt() { return hits + sumUpListHits(hand); } private int sumUpListHits(Entry e) { if (e == null) { return 0; } int cnt = 0; Entry _head = e; do { cnt += e.hitCnt; e = (Entry) e.prev; } while (e != _head); return cnt; } @Override protected void initializeHeapCache() { super.initializeHeapCache(); size = 0; hand = null; } @Override protected void removeEntryFromReplacementList(Entry e) { hand = removeFromCyclicList(hand, e); size } private int getListSize() { return size; } @Override protected void recordHit(Entry e) { e.hitCnt++; } @Override protected void insertIntoReplacementList(Entry e) { size++; hand = insertIntoTailCyclicList(hand, e); } @Override protected Entry newEntry() { return new Entry(); } /** * Run to evict an entry. */ @Override protected Entry findEvictionCandidate() { runCnt++; int _scanCnt = 0; while (hand.hitCnt > 0) { _scanCnt++; hits += hand.hitCnt; hand.hitCnt = 0; hand = (Entry) hand.next; } if (_scanCnt > size) { scan24hCnt++; } scanCnt += _scanCnt; return hand; } @Override protected IntegrityState getIntegrityState() { synchronized (lock) { return super.getIntegrityState() .checkEquals("getListSize() + evictedButInHashCnt == getSize()", getListSize() + evictedButInHashCnt, getLocalSize()) .check("checkCyclicListIntegrity(hand)", checkCyclicListIntegrity(hand)) .checkEquals("getCyclicListEntryCount(hand) == size", getCyclicListEntryCount(hand), size); } } @Override protected String getExtraStatistics() { return ", clockRunCnt=" + runCnt + ", scanCnt=" + scanCnt + ", scan24hCnt=" + scan24hCnt; } static class Entry<K, T> extends org.cache2k.impl.Entry<Entry, K, T> { int hitCnt; } }
package main.swapship.systems; import main.swapship.SwapShipGame; import main.swapship.common.Constants; import main.swapship.components.SpatialComp; import main.swapship.components.VelocityComp; import main.swapship.components.player.ShipColorsComp; import main.swapship.components.player.ShipSpritesComp; import main.swapship.util.AssetUtil; import main.swapship.util.VectorUtil; import com.artemis.ComponentMapper; import com.artemis.Entity; import com.artemis.Filter; import com.artemis.systems.EntityProcessingSystem; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.g2d.TextureRegion; public class PlayerRenderSys extends EntityProcessingSystem { // The game, used to get the camera and sritebatch private final SwapShipGame game; private final OrthographicCamera camera; private ComponentMapper<SpatialComp> scm; private ComponentMapper<VelocityComp> vcm; private ComponentMapper<ShipColorsComp> sccm; private ComponentMapper<ShipSpritesComp> sscm; public PlayerRenderSys(final SwapShipGame game, OrthographicCamera camera) { super(Filter.allComponents(SpatialComp.class, VelocityComp.class, ShipColorsComp.class, ShipSpritesComp.class)); this.game = game; this.camera = camera; } @Override public void initialize() { scm = world.getMapper(SpatialComp.class); sccm = world.getMapper(ShipColorsComp.class); sscm = world.getMapper(ShipSpritesComp.class); vcm = world.getMapper(VelocityComp.class); } @Override protected void process(Entity e) { SpatialComp sc = scm.get(e); VelocityComp vc = vcm.get(e); ShipColorsComp scc = sccm.get(e); ShipSpritesComp ssc = sscm.get(e); // Textures to draw with TextureRegion topTr = AssetUtil.getInstance().getTexture(ssc.topName); TextureRegion midTr = AssetUtil.getInstance().getTexture(ssc.midName); TextureRegion botTr = AssetUtil.getInstance().getTexture(ssc.botName); game.batch.setProjectionMatrix(camera.combined); float rotation = VectorUtil.calcRotation(vc.xVel, vc.yVel); // TODO figure out how to do this properly? float y = sc.y; // Draw the parts! // Start at the bottom because y goes upward game.batch.setColor(scc.botColor); game.batch.draw(botTr, sc.x, y, sc.width / 2, sc.height / 2, sc.width, Constants.Player.SHIP_PART_HEIGHT, 1f, 1f, 0); y += Constants.Player.SHIP_PART_HEIGHT; game.batch.setColor(scc.midColor); game.batch.draw(midTr, sc.x, y, sc.width / 2, sc.height / 2, sc.width, Constants.Player.SHIP_PART_HEIGHT, 1f, 1f, 0); y += Constants.Player.SHIP_PART_HEIGHT; game.batch.setColor(scc.topColor); game.batch.draw(topTr, sc.x, y, sc.width / 2, sc.height / 2, sc.width, Constants.Player.SHIP_PART_HEIGHT, 1f, 1f, 0); } }
package com.siberia.plugin; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CallbackContext; import org.apache.cordova.PluginResult; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.os.Handler; import android.os.Message; import android.util.Log; import android.net.nsd.NsdServiceInfo; import com.siberia.plugin.NsdHelper; public class Discovery extends CordovaPlugin { NsdHelper mNsdHelper; private Handler mHandler; // ChatConnection mConnection; // CallbackContextHandler ccHandler; @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { if (action.equals("initChat")) { this.initChat(callbackContext); } else if (action.equals("advertizeChat")) { this.advertizeChat(callbackContext); } else if (action.equals("identify")) { this.discoverServices(callbackContext); } else if (action.equals("connectChat")) { this.connectChat(callbackContext); } else if (action.equals("sendChatMessage")) { String messageString = args.getString(0); this.sendChatMessage(callbackContext, messageString); } else { callbackContext.error(String.format("Discovery - invalid action:", action)); return false; } // PluginResult.Status status = PluginResult.Status.NO_RESULT; // PluginResult pluginResult = new PluginResult(status); // pluginResult.setKeepCallback(true); // callbackContext.sendPluginResult(pluginResult); return true; } // private void initChat(CallbackContext callbackContext) { // final CallbackContext cbc = callbackContext; // try { // mHandler = new Handler() { // @Override // public void handleMessage(Message msg) { // String type = msg.getData().getString("type"); // String message = msg.getData().getString("msg"); // JSONObject data = new JSONObject(); // try { // data.put("type", new String(type)); // data.put("data", new String(message)); // } catch(JSONException e) { // PluginResult result = new PluginResult(PluginResult.Status.OK, data); // result.setKeepCallback(true); // cbc.sendPluginResult(result); // // mConnection = new ChatConnection(ccHandler); // mConnection = new ChatConnection(mHandler); // // mNsdHelper = new NsdHelper(cordova.getActivity(), ccHandler); // mNsdHelper = new NsdHelper(cordova.getActivity(), mHandler); // mNsdHelper.initializeNsd(); // } catch(Exception e) { // callbackContext.error("Error " + e); // private void advertizeChat(CallbackContext callbackContext) { // final CallbackContext cbc = callbackContext; // if(mConnection.getLocalPort() > -1) { // mNsdHelper.registerService(mConnection.getLocalPort()); // } else { // cbc.error("ServerSocket isn't bound."); private void identify(CallbackContext callbackContext) { final CallbackContext cbc = callbackContext; mNsdHelper.discoverServices(); } // private void connectChat(CallbackContext callbackContext) { // final CallbackContext cbc = callbackContext; // NsdServiceInfo service = mNsdHelper.getChosenServiceInfo(); // if (service != null) { // mConnection.connectToServer(service.getHost(), // service.getPort()); // } else { // cbc.error("No service to connect to!"); // private void sendChatMessage(CallbackContext callbackContext, String messageString) { // mConnection.sendMessage(messageString); }
package info.limpet.stackedcharts.ui.view; import info.limpet.stackedcharts.model.AbstractAnnotation; import info.limpet.stackedcharts.model.AngleAxis; import info.limpet.stackedcharts.model.AxisDirection; import info.limpet.stackedcharts.model.AxisType; import info.limpet.stackedcharts.model.Chart; import info.limpet.stackedcharts.model.ChartSet; import info.limpet.stackedcharts.model.DataItem; import info.limpet.stackedcharts.model.Dataset; import info.limpet.stackedcharts.model.Datum; import info.limpet.stackedcharts.model.DependentAxis; import info.limpet.stackedcharts.model.IndependentAxis; import info.limpet.stackedcharts.model.LineType; import info.limpet.stackedcharts.model.MarkerStyle; import info.limpet.stackedcharts.model.Orientation; import info.limpet.stackedcharts.model.PlainStyling; import info.limpet.stackedcharts.model.SelectiveAnnotation; import info.limpet.stackedcharts.model.Styling; import info.limpet.stackedcharts.ui.view.StackedChartsView.ControllableDate; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Stroke; import java.awt.geom.Ellipse2D; import java.awt.geom.Rectangle2D; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.eclipse.emf.common.notify.Adapter; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.impl.AdapterImpl; import org.eclipse.emf.common.util.EList; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.AxisLocation; import org.jfree.chart.axis.DateAxis; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.axis.NumberTickUnit; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.plot.CombinedDomainXYPlot; import org.jfree.chart.plot.IntervalMarker; import org.jfree.chart.plot.Marker; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.ValueMarker; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; import org.jfree.data.general.Series; import org.jfree.data.time.Millisecond; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesCollection; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import org.jfree.ui.Layer; import org.jfree.ui.RectangleAnchor; import org.jfree.ui.RectangleInsets; import org.jfree.ui.TextAnchor; import org.jfree.util.ShapeUtilities; public class ChartBuilder { /** * helper class that can handle either temporal or non-temporal datasets * * @author ian * */ private static interface ChartHelper { /** * add this item to this series * * @param series * @param item */ void addItem(Series series, DataItem item); /** * clear the contents of the series * */ void clear(Series series); /** * create the correct type of axis * * @param name * @return */ ValueAxis createAxis(String name); /** * create a new collection of datasets (seroes) * * @return */ XYDataset createCollection(); /** * create a series with the specified name * * @param name * @return */ Series createSeries(String name); /** * put the series into the collection * * @param collection * @param series */ void storeSeries(XYDataset collection, Series series); } /** * support generation of a stacked chart with a shared time axis * * @author ian * */ private static class DateHelper implements ChartHelper { @Override public void addItem(final Series series, final DataItem item) { final TimeSeries ns = (TimeSeries) series; final long time = (long) item.getIndependentVal(); final Millisecond milli = new Millisecond(new Date(time)); ns.add(milli, item.getDependentVal()); } @Override public void clear(final Series series) { final TimeSeries ns = (TimeSeries) series; ns.clear(); } @Override public ValueAxis createAxis(final String name) { return new DateAxis(name); } @Override public XYDataset createCollection() { return new TimeSeriesCollection(); } @Override public Series createSeries(final String name) { return new TimeSeries(name); } @Override public void storeSeries(final XYDataset collection, final Series series) { final TimeSeriesCollection cc = (TimeSeriesCollection) collection; cc.addSeries((TimeSeries) series); } } /** * support generation of a stacked chart with a shared number axis * * @author ian * */ private static class NumberHelper implements ChartHelper { @Override public void addItem(final Series series, final DataItem item) { final XYSeries ns = (XYSeries) series; ns.add(item.getIndependentVal(), item.getDependentVal()); } @Override public void clear(final Series series) { final XYSeries ns = (XYSeries) series; ns.clear(); } @Override public ValueAxis createAxis(final String name) { return new NumberAxis(name); } @Override public XYDataset createCollection() { return new XYSeriesCollection(); } @Override public Series createSeries(final String name) { return new XYSeries(name); } @Override public void storeSeries(final XYDataset collection, final Series series) { final XYSeriesCollection cc = (XYSeriesCollection) collection; cc.addSeries((XYSeries) series); } } /** * * @param subplot * target plot for annotation * @param annotations * annotation list to be added to plot eg: Marker,Zone * @param isRangeAnnotation * is annotation added to Range or Domain */ private static void addAnnotationToPlot(final XYPlot subplot, final List<AbstractAnnotation> annotations, final boolean isRangeAnnotation) { for (final AbstractAnnotation annotation : annotations) { final Color color = annotation.getColor(); if (annotation instanceof info.limpet.stackedcharts.model.Marker) { // build value Marker final info.limpet.stackedcharts.model.Marker marker = (info.limpet.stackedcharts.model.Marker) annotation; final Marker mrk = new ValueMarker(marker.getValue()); mrk.setLabel(annotation.getName()); mrk.setPaint(color == null ? Color.GRAY : color); // move Text Anchor mrk.setLabelTextAnchor(TextAnchor.TOP_RIGHT); mrk.setLabelAnchor(RectangleAnchor.TOP); mrk.setLabelOffset(new RectangleInsets(2, 2, 2, 2)); if (isRangeAnnotation) { subplot.addRangeMarker(mrk, Layer.FOREGROUND); } else { subplot.addDomainMarker(mrk, Layer.FOREGROUND); } } else if (annotation instanceof info.limpet.stackedcharts.model.Zone) { // build Zone final info.limpet.stackedcharts.model.Zone zone = (info.limpet.stackedcharts.model.Zone) annotation; final Marker mrk = new IntervalMarker(zone.getStart(), zone.getEnd()); mrk.setLabel(annotation.getName()); if (color != null) { mrk.setPaint(color); } // move Text & Label Anchor mrk.setLabelTextAnchor(TextAnchor.CENTER); mrk.setLabelAnchor(RectangleAnchor.CENTER); mrk.setLabelOffset(new RectangleInsets(2, 2, 2, 2)); if (isRangeAnnotation) { subplot.addRangeMarker(mrk, Layer.FOREGROUND); } else { subplot.addDomainMarker(mrk, Layer.FOREGROUND); } } else if (annotation instanceof info.limpet.stackedcharts.model.ScatterSet) { // build ScatterSet final info.limpet.stackedcharts.model.ScatterSet marker = (info.limpet.stackedcharts.model.ScatterSet) annotation; final EList<Datum> datums = marker.getDatums(); boolean addLabel = true; for (final Datum datum : datums) { final Marker mrk = new ValueMarker(datum.getVal()); // only add label for first Marker if (addLabel) { mrk.setLabel(annotation.getName()); addLabel = false; } final Color thisColor = datum.getColor(); final Color colorToUse = thisColor == null ? color : thisColor; // apply some transparency to the color if (colorToUse != null) { final Color transColor = new Color(colorToUse.getRed(), colorToUse.getGreen(), colorToUse.getBlue(), 120); mrk.setPaint(transColor); } // move Text Anchor mrk.setLabelTextAnchor(TextAnchor.TOP_RIGHT); mrk.setLabelAnchor(RectangleAnchor.TOP); mrk.setLabelOffset(new RectangleInsets(2, 2, 2, 2)); if (isRangeAnnotation) { subplot.addRangeMarker(mrk, Layer.FOREGROUND); } else { subplot.addDomainMarker(mrk, Layer.FOREGROUND); } } } } } /** * * @param helper * Helper object to map between axis types * @param datasets * list of datasets to add to this axis * @param collection * XYDataset need to be fill with Series * @param renderer * axis renderer * @param seriesIndex * counter for current series being assigned * * build axis dataset via adding series to Series & config renderer for styles */ private static void addDatasetToAxis(final ChartHelper helper, final EList<Dataset> datasets, final XYDataset collection, final XYLineAndShapeRenderer renderer, int seriesIndex) { for (final Dataset dataset : datasets) { final Series series = helper.createSeries(dataset.getName()); final Styling styling = dataset.getStyling(); if (styling != null) { if (styling instanceof PlainStyling) { final PlainStyling ps = (PlainStyling) styling; renderer.setSeriesPaint(seriesIndex, ps.getColor()); } else { System.err.println("Linear colors not implemented"); } // legend visibility final boolean isInLegend = styling.isIncludeInLegend(); renderer.setSeriesVisibleInLegend(seriesIndex, isInLegend); // line thickness // line style final LineType lineType = styling.getLineStyle(); if (lineType != null) { final float thickness = (float) styling.getLineThickness(); Stroke stroke; float[] pattern; switch (lineType) { case NONE: renderer.setSeriesLinesVisible(seriesIndex, false); break; case SOLID: renderer.setSeriesLinesVisible(seriesIndex, true); stroke = new BasicStroke(thickness); renderer.setSeriesStroke(seriesIndex, stroke); break; case DOTTED: renderer.setSeriesLinesVisible(seriesIndex, true); pattern = new float[] {3f, 3f}; stroke = new BasicStroke(thickness, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, pattern, 0); renderer.setSeriesStroke(seriesIndex, stroke); break; case DASHED: renderer.setSeriesLinesVisible(seriesIndex, true); pattern = new float[] {8.0f, 4.0f}; stroke = new BasicStroke(thickness, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, pattern, 0); renderer.setSeriesStroke(seriesIndex, stroke); break; } } // marker size double size = styling.getMarkerSize(); if (size == 0) { size = 2;// default } // marker style final MarkerStyle marker = styling.getMarkerStyle(); if (marker != null) { switch (marker) { case NONE: renderer.setSeriesShapesVisible(seriesIndex, false); break; case SQUARE: renderer.setSeriesShape(seriesIndex, new Rectangle2D.Double(0, 0, size, size)); break; case CIRCLE: renderer.setSeriesShape(seriesIndex, new Ellipse2D.Double(0, 0, size, size)); break; case TRIANGLE: renderer.setSeriesShape(seriesIndex, ShapeUtilities .createUpTriangle((float) size)); break; case CROSS: renderer.setSeriesShape(seriesIndex, ShapeUtilities .createRegularCross((float) size, (float) size)); break; case DIAMOND: renderer.setSeriesShape(seriesIndex, ShapeUtilities .createDiamond((float) size)); break; default: renderer.setSeriesShapesVisible(seriesIndex, false); } } seriesIndex++; } helper.storeSeries(collection, series); // store the data in the collection populateCollection(helper, dataset, series); // also register as a listener final Adapter adapter = new AdapterImpl() { @Override public void notifyChanged(final Notification notification) { populateCollection(helper, dataset, series); } }; dataset.eAdapters().add(adapter); } } /** * create a chart from chart object for preview * * @param chart * * @return */ public static JFreeChart build(final Chart chart) { final IndependentAxis sharedAxisModel = chart.getParent().getSharedAxis(); final ChartHelper helper; final ValueAxis sharedAxis; if (sharedAxisModel == null) { sharedAxis = new DateAxis("Time"); helper = new NumberHelper(); } else { final AxisType axisType = sharedAxisModel.getAxisType(); if (axisType instanceof info.limpet.stackedcharts.model.NumberAxis) { helper = new NumberHelper(); } else if (axisType instanceof info.limpet.stackedcharts.model.AngleAxis) { helper = new NumberHelper(); } else if (axisType instanceof info.limpet.stackedcharts.model.DateAxis) { helper = new DateHelper(); } else { System.err.println("UNEXPECTED AXIS TYPE RECEIVED"); helper = new NumberHelper(); } sharedAxis = helper.createAxis(sharedAxisModel.getName()); if (sharedAxisModel.getDirection() == AxisDirection.DESCENDING) { sharedAxis.setInverted(true); } } sharedAxis.setVisible(false); final CombinedDomainXYPlot plot = new TimeBarPlot(sharedAxis); // create this chart final XYPlot subplot = createChart(sharedAxisModel, chart, helper); // add chart to stack plot.add(subplot); final JFreeChart jFreeChart = new JFreeChart(plot); jFreeChart.getLegend().setVisible(false); return jFreeChart; } /** * create a chart from our dataset * * @param chartsSet * @param controllableDate * * @return */ public static JFreeChart build(final ChartSet chartsSet, ControllableDate controllableDate) { final IndependentAxis sharedAxisModel = chartsSet.getSharedAxis(); final ChartHelper helper; final ValueAxis sharedAxis; if (sharedAxisModel == null) { sharedAxis = new DateAxis("Time"); helper = new NumberHelper(); } else { final AxisType axisType = sharedAxisModel.getAxisType(); if (axisType instanceof info.limpet.stackedcharts.model.NumberAxis) { helper = new NumberHelper(); } else if (axisType instanceof info.limpet.stackedcharts.model.AngleAxis) { helper = new NumberHelper(); } else if (axisType instanceof info.limpet.stackedcharts.model.DateAxis) { helper = new DateHelper(); } else { System.err.println("UNEXPECTED AXIS TYPE RECEIVED"); helper = new NumberHelper(); } sharedAxis = helper.createAxis(sharedAxisModel.getName()); if (sharedAxisModel.getDirection() == AxisDirection.DESCENDING) { sharedAxis.setInverted(true); } } final TimeBarPlot plot = new TimeBarPlot(sharedAxis); // now loop through the charts final EList<Chart> charts = chartsSet.getCharts(); for (final Chart chart : charts) { // create this chart final XYPlot subplot = createChart(sharedAxisModel, chart, helper); // add chart to stack plot.add(subplot); } // do we know a date? if (controllableDate != null) { // ok, initialise it Date theTime = controllableDate.getDate(); if (theTime != null) { plot.setTime(theTime); } } plot.setGap(5.0); plot.setOrientation(chartsSet.getOrientation() == Orientation.VERTICAL ? PlotOrientation.VERTICAL : PlotOrientation.HORIZONTAL); return new JFreeChart(plot); } protected static XYPlot createChart(final IndependentAxis sharedAxisModel, final Chart chart, ChartHelper helper) { final XYPlot subplot = new XYPlot(null, null, null, null); // keep track of how many axes we create int indexAxis = 0; // min axis create on bottom or left final EList<DependentAxis> minAxes = chart.getMinAxes(); for (final DependentAxis axis : minAxes) { createDependentAxis(subplot, indexAxis, axis, helper); subplot.setRangeAxisLocation(indexAxis, AxisLocation.BOTTOM_OR_LEFT); indexAxis++; } // max axis create on top or right final EList<DependentAxis> maxAxes = chart.getMaxAxes(); for (final DependentAxis axis : maxAxes) { createDependentAxis(subplot, indexAxis, axis, helper); subplot.setRangeAxisLocation(indexAxis, AxisLocation.TOP_OR_RIGHT); indexAxis++; } if (sharedAxisModel != null) { // build selective annotations to plot final EList<SelectiveAnnotation> selectiveAnnotations = sharedAxisModel.getAnnotations(); final List<AbstractAnnotation> annotations = new ArrayList<>(); for (final SelectiveAnnotation selectiveAnnotation : selectiveAnnotations) { final EList<Chart> appearsIn = selectiveAnnotation.getAppearsIn(); // check selective option to see is this applicable to current chart if (appearsIn == null || appearsIn.isEmpty() || appearsIn.contains(chart)) { annotations.add(selectiveAnnotation.getAnnotation()); } } addAnnotationToPlot(subplot, annotations, false); } // TODO: sort out how to position this title // XYTitleAnnotation title = new XYTitleAnnotation(0, 0, new TextTitle(chart.getName())); // subplot.addAnnotation(title); return subplot; } /** * * @param subplot * target plot for index * @param indexAxis * index of new axis * @param dependentAxis * model object of DependentAxis */ private static void createDependentAxis(final XYPlot subplot, final int indexAxis, final DependentAxis dependentAxis, ChartHelper axeshelper) { final XYLineAndShapeRenderer renderer; // is this a special axis type final AxisType axisType = dependentAxis.getAxisType(); // sort out the name final String axisName; if (axisType instanceof info.limpet.stackedcharts.model.NumberAxis) { info.limpet.stackedcharts.model.NumberAxis number = (info.limpet.stackedcharts.model.NumberAxis) axisType; if (number.getUnits() != null) { axisName = dependentAxis.getName() + " (" + number.getUnits() + ")"; } else { axisName = dependentAxis.getName(); } } else { axisName = dependentAxis.getName(); } final ValueAxis chartAxis; if (axisType instanceof AngleAxis) { AngleAxis angle = (AngleAxis) axisType; // use the renderer that "jumps" across zero/360 barrier renderer = new WrappingRenderer(angle.getMinVal(), angle.getMaxVal()); // use the angular axis chartAxis = new AnglularUnitAxis(axisName); } else { renderer = new XYLineAndShapeRenderer(); chartAxis = new NumberAxis(axisName); } renderer.setDrawSeriesLineAsPath(true); final int indexSeries = 0; final XYDataset collection = axeshelper.createCollection(); if (dependentAxis.getDirection() == AxisDirection.DESCENDING) { chartAxis.setInverted(true); } addDatasetToAxis(axeshelper, dependentAxis.getDatasets(), collection, renderer, indexSeries); final EList<AbstractAnnotation> annotations = dependentAxis.getAnnotations(); addAnnotationToPlot(subplot, annotations, true); subplot.setDataset(indexAxis, collection); subplot.setRangeAxis(indexAxis, chartAxis); subplot.setRenderer(indexAxis, renderer); subplot.mapDatasetToRangeAxis(indexAxis, indexAxis); } protected static void populateCollection(final ChartHelper helper, final Dataset dataset, final Series series) { helper.clear(series); final EList<DataItem> measurements = dataset.getMeasurements(); for (final DataItem dataItem : measurements) { helper.addItem(series, dataItem); } } /** modified version of angle axis that prefers to use * angular metric units. * @author ian * */ private static class AnglularUnitAxis extends NumberAxis { private static final long serialVersionUID = 1L; public AnglularUnitAxis(final String axisName) { super(axisName); } @Override public NumberTickUnit getTickUnit() { final NumberTickUnit tickUnit = super.getTickUnit(); if (tickUnit.getSize() < 15) { return tickUnit; } else if (tickUnit.getSize() < 45) { return new NumberTickUnit(45); } else if (tickUnit.getSize() < 90) { return new NumberTickUnit(90); } else if (tickUnit.getSize() < 180) { return new NumberTickUnit(180); } else { return new NumberTickUnit(360); } } } private ChartBuilder() { } }
package com.intellij.codeInspection.dataFlow; import com.intellij.codeInspection.dataFlow.instructions.EndOfInitializerInstruction; import com.intellij.codeInspection.dataFlow.rangeSet.LongRangeSet; import com.intellij.codeInspection.dataFlow.value.DfaConstValue; import com.intellij.codeInspection.dataFlow.value.DfaFactMapValue; import com.intellij.codeInspection.dataFlow.value.DfaValue; import com.intellij.codeInspection.dataFlow.value.DfaVariableValue; import com.intellij.diagnostic.ThreadDumper; import com.intellij.openapi.diagnostic.Attachment; import com.intellij.openapi.diagnostic.RuntimeExceptionWithAttachments; import com.intellij.openapi.util.TextRange; import com.intellij.psi.*; import com.intellij.psi.util.*; import com.intellij.util.JavaPsiConstructorUtil; import com.siyeh.ig.psiutils.ExpressionUtils; import one.util.streamex.StreamEx; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.RejectedExecutionException; import static com.intellij.codeInspection.dataFlow.DfaUtil.hasImplicitImpureSuperCall; public class CommonDataflow { private static class DataflowPoint { // null = top; empty = bottom @Nullable DfaFactMap myFacts = null; // empty = top; null = bottom @Nullable Set<Object> myPossibleValues = Collections.emptySet(); // null = top; empty = bottom @Nullable Set<Object> myNotValues = null; boolean myMayFailByContract = false; DataflowPoint() {} DataflowPoint(DataflowPoint other) { myFacts = other.myFacts; myPossibleValues = other.myPossibleValues; myNotValues = other.myNotValues == null || other.myNotValues.isEmpty() ? other.myNotValues : new HashSet<>(other.myNotValues); myMayFailByContract = other.myMayFailByContract; } void addNotValues(DfaMemoryStateImpl memState, DfaValue value) { // We do not store not-values for integral numbers as this functionality is covered by range fact if (value instanceof DfaVariableValue && !TypeConversionUtil.isIntegralNumberType(value.getType())) { Set<Object> notValues = myNotValues; if (notValues == null) { Set<Object> constants = memState.getNonEqualConstants((DfaVariableValue)value); myNotValues = constants.isEmpty() ? Collections.emptySet() : constants; } else if (!notValues.isEmpty()) { notValues.retainAll(memState.getNonEqualConstants((DfaVariableValue)value)); if (notValues.isEmpty()) { myNotValues = Collections.emptySet(); } } } } void addValue(DfaMemoryStateImpl memState, DfaValue value) { if (myPossibleValues == null) return; DfaConstValue constantValue = memState.getConstantValue(value); if (constantValue == null) { myPossibleValues = null; return; } Object newValue = constantValue.getValue(); if (myPossibleValues.contains(newValue)) return; myNotValues = null; if (myPossibleValues.isEmpty()) { myPossibleValues = Collections.singleton(newValue); } else { myPossibleValues = new HashSet<>(myPossibleValues); myPossibleValues.add(newValue); } } void addFacts(DfaMemoryStateImpl memState, DfaValue value) { if (myFacts == DfaFactMap.EMPTY) return; DfaFactMap newMap = DataflowResult.getFactMap(memState, value); if (value instanceof DfaVariableValue) { SpecialField field = SpecialField.fromQualifierType(value.getType()); if (field != null) { DfaValue specialField = field.createValue(value.getFactory(), value); if (specialField instanceof DfaVariableValue) { DfaConstValue constantValue = memState.getConstantValue(specialField); specialField = constantValue != null ? constantValue : specialField.getFactory().getFactFactory().createValue(DataflowResult.getFactMap(memState, specialField)); } if (specialField instanceof DfaConstValue || specialField instanceof DfaFactMapValue) { newMap = newMap.with(DfaFactType.SPECIAL_FIELD_VALUE, field.withValue(specialField)); } } } myFacts = myFacts == null ? newMap : myFacts.unite(newMap); } } /** * Represents the result of dataflow applied to some code fragment (usually a method) */ public static final class DataflowResult { private final Map<PsiExpression, DataflowPoint> myData = new HashMap<>(); private final RunnerResult myResult; public DataflowResult(RunnerResult result) { myResult = result; } @NotNull DataflowResult copy() { DataflowResult copy = new DataflowResult(myResult); myData.forEach((expression, point) -> copy.myData.put(expression, new DataflowPoint(point))); return copy; } void add(PsiExpression expression, DfaMemoryStateImpl memState, DfaValue value) { DataflowPoint point = myData.computeIfAbsent(expression, e -> new DataflowPoint()); if (DfaConstValue.isContractFail(value)) { point.myMayFailByContract = true; return; } if (point.myFacts != DfaFactMap.EMPTY) { PsiElement parent = PsiUtil.skipParenthesizedExprUp(expression.getParent()); if (parent instanceof PsiConditionalExpression && !PsiTreeUtil.isAncestor(((PsiConditionalExpression)parent).getCondition(), expression, false)) { add((PsiExpression)parent, memState, value); } } point.addFacts(memState, value); point.addValue(memState, value); point.addNotValues(memState, value); } @NotNull private static DfaFactMap getFactMap(DfaMemoryStateImpl memState, DfaValue value) { DfaFactMap newMap = memState.getFactMap(value); DfaNullability nullability = newMap.get(DfaFactType.NULLABILITY); if (nullability != DfaNullability.NOT_NULL && memState.isNotNull(value)) { newMap = newMap.with(DfaFactType.NULLABILITY, DfaNullability.NOT_NULL); } return newMap; } /** * Returns true if given expression was visited by dataflow. Note that dataflow usually tracks deparenthesized expressions only, * so you should deparenthesize it in advance if necessary. * * @param expression expression to check, not parenthesized * @return true if given expression was visited by dataflow. * If false is returned, it's possible that the expression exists in unreachable branch or this expression is not tracked due to * the dataflow implementation details. */ public boolean expressionWasAnalyzed(PsiExpression expression) { if (expression instanceof PsiParenthesizedExpression) { throw new IllegalArgumentException("Should not pass parenthesized expression"); } return myData.containsKey(expression); } /** * Returns true if given call cannot fail according to its contracts * (e.g. {@code Optional.get()} executed under {@code Optional.isPresent()}). * * @param call call to check * @return true if it cannot fail by contract; false if unknown or can fail */ public boolean cannotFailByContract(PsiCallExpression call) { DataflowPoint point = myData.get(call); return point != null && !point.myMayFailByContract; } /** * Returns a fact of specific type which is known for given expression or null if fact is not known * * @param expression expression to get the fact * @param type a fact type * @param <T> resulting type * @return a fact value or null if fact of given type is not known for given expression */ @Nullable public <T> T getExpressionFact(PsiExpression expression, DfaFactType<T> type) { DataflowPoint point = myData.get(expression); return point == null || point.myFacts == null ? null : point.myFacts.get(type); } /** * Returns a set of expression values if known. If non-empty set is returned, then given expression * is guaranteed to have one of returned values. * * @param expression an expression to get its value * @return a set of possible values or empty set if not known */ @NotNull public Set<Object> getExpressionValues(@Nullable PsiExpression expression) { DataflowPoint point = myData.get(expression); if (point == null) return Collections.emptySet(); Set<Object> values = point.myPossibleValues; return values == null ? Collections.emptySet() : Collections.unmodifiableSet(values); } /** * Returns a set of values which are known to be not equal to given expression. * An empty list is returned if nothing is known. * * <p> * This method may return nothing if {@link #getExpressionValues(PsiExpression)} * returns some values (if expression values are known, it's not equal to any other value), * or if expression type is an integral type (in this case use * {@code getExpressionFact(expression, DfaFactType.RANGE)} which would provide more information anyway). * * @param expression an expression to get values not equal to. * @return a set of values; empty set if nothing is known or this expression was not tracked. */ @NotNull public Set<Object> getValuesNotEqualToExpression(@Nullable PsiExpression expression) { DataflowPoint point = myData.get(expression); if (point == null) return Collections.emptySet(); Set<Object> values = point.myNotValues; return values == null ? Collections.emptySet() : Collections.unmodifiableSet(values); } /** * Returns the fact map which represents all the facts known for given expression * * @param expression an expression to check * @return the fact map which represents all the facts known for given expression; empty map if the expression was * analyzed, but no particular facts were inferred; null if the expression was not analyzed. */ @Nullable public DfaFactMap getAllFacts(PsiExpression expression) { DataflowPoint point = myData.get(expression); return point == null ? null : point.myFacts; } } @NotNull private static DataflowResult runDFA(@Nullable PsiElement block) { if (block == null) return new DataflowResult(RunnerResult.NOT_APPLICABLE); DataFlowRunner runner = new DataFlowRunner(false, block); CommonDataflowVisitor visitor = new CommonDataflowVisitor(); RunnerResult result = runner.analyzeMethodRecursively(block, visitor, false); if (result != RunnerResult.OK) return new DataflowResult(result); if (!(block instanceof PsiClass)) return visitor.myResult; DataflowResult dfr = visitor.myResult.copy(); List<DfaMemoryState> states = visitor.myEndOfInitializerStates; for (PsiMethod method : ((PsiClass)block).getConstructors()) { List<DfaMemoryState> initialStates; PsiCodeBlock body = method.getBody(); if (body == null) continue; PsiMethodCallExpression call = JavaPsiConstructorUtil.findThisOrSuperCallInConstructor(method); if (JavaPsiConstructorUtil.isChainedConstructorCall(call) || (call == null && hasImplicitImpureSuperCall((PsiClass)block, method))) { initialStates = Collections.singletonList(runner.createMemoryState()); } else { initialStates = StreamEx.of(states).map(DfaMemoryState::createCopy).toList(); } if(runner.analyzeBlockRecursively(body, initialStates, visitor, false) == RunnerResult.OK) { dfr = visitor.myResult.copy(); } else { visitor.myResult = dfr; } } return dfr; } /** * Returns the dataflow result for code fragment which contains given context * @param context a context to get the dataflow result * @return the dataflow result or null if dataflow cannot be launched for this context (e.g. we are inside too complex method) */ @Nullable public static DataflowResult getDataflowResult(PsiExpression context) { PsiElement body = DfaUtil.getDataflowContext(context); if (body == null) return null; ConcurrentHashMap<PsiElement, DataflowResult> fileMap = CachedValuesManager.getCachedValue(body.getContainingFile(), () -> CachedValueProvider.Result.create(new ConcurrentHashMap<>(), PsiModificationTracker.MODIFICATION_COUNT)); class ManagedCompute implements ForkJoinPool.ManagedBlocker { DataflowResult myResult; @Override public boolean block() { myResult = fileMap.computeIfAbsent(body, CommonDataflow::runDFA); return true; } @Override public boolean isReleasable() { myResult = fileMap.get(body); return myResult != null; } DataflowResult getResult() { return myResult == null || myResult.myResult != RunnerResult.OK ? null : myResult; } } ManagedCompute managedCompute = new ManagedCompute(); try { ForkJoinPool.managedBlock(managedCompute); } catch (RejectedExecutionException ex) { Attachment attachment = new Attachment("dumps.txt", ThreadDumper.dumpThreadsToString()); attachment.setIncluded(true); throw new RuntimeExceptionWithAttachments("Rejected execution!", attachment); } catch (InterruptedException ignored) { // Should not happen throw new AssertionError(); } return managedCompute.getResult(); } /** * Returns a fact of specific type which is known for given expression or null if fact is not known * * @param expression expression to get the fact * @param type a fact type * @param <T> resulting type * @return a fact value or null if fact of given type is not known for given expression */ public static <T> T getExpressionFact(PsiExpression expression, DfaFactType<T> type) { DataflowResult result = getDataflowResult(expression); if (result == null) return null; return result.getExpressionFact(PsiUtil.skipParenthesizedExprDown(expression), type); } /** * Returns long range set for expression or null if range is unknown. * This method first tries to compute expression using {@link com.intellij.psi.impl.ConstantExpressionEvaluator} * and only then calls {@link #getExpressionFact(PsiExpression, DfaFactType)}. * * @param expression expression to get its range * @return long range set */ @Contract("null -> null") @Nullable public static LongRangeSet getExpressionRange(@Nullable PsiExpression expression) { if (expression == null) return null; Object value = ExpressionUtils.computeConstantExpression(expression); LongRangeSet rangeSet = LongRangeSet.fromConstant(value); if (rangeSet != null) return rangeSet; return getExpressionFact(expression, DfaFactType.RANGE); } private static class CommonDataflowVisitor extends StandardInstructionVisitor { private DataflowResult myResult = new DataflowResult(RunnerResult.OK); private final List<DfaMemoryState> myEndOfInitializerStates = new ArrayList<>(); @Override public DfaInstructionState[] visitEndOfInitializer(EndOfInitializerInstruction instruction, DataFlowRunner runner, DfaMemoryState state) { if (!instruction.isStatic()) { myEndOfInitializerStates.add(state.createCopy()); } return super.visitEndOfInitializer(instruction, runner, state); } @Override protected void beforeExpressionPush(@NotNull DfaValue value, @NotNull PsiExpression expression, @Nullable TextRange range, @NotNull DfaMemoryState state) { if (range == null) { // Do not track instructions which cover part of expression myResult.add(expression, (DfaMemoryStateImpl)state, value); } } } }
package org.eclipse.jetty.client; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.client.api.Connection; import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.jetty.client.api.Request; import org.eclipse.jetty.client.api.Response; import org.eclipse.jetty.client.api.Result; import org.eclipse.jetty.client.util.ByteBufferContentProvider; import org.eclipse.jetty.http.HttpHeader; import org.eclipse.jetty.server.handler.AbstractHandler; import org.eclipse.jetty.toolchain.test.annotation.Slow; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.log.StdErrLog; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.junit.Assert; import org.junit.Test; public class HttpConnectionLifecycleTest extends AbstractHttpClientServerTest { public HttpConnectionLifecycleTest(SslContextFactory sslContextFactory) { super(sslContextFactory); } @Test public void test_SuccessfulRequest_ReturnsConnection() throws Exception { start(new EmptyServerHandler()); String host = "localhost"; int port = connector.getLocalPort(); HttpDestination destination = (HttpDestination)client.getDestination(scheme, host, port); final BlockingQueue<Connection> idleConnections = destination.getIdleConnections(); Assert.assertEquals(0, idleConnections.size()); final BlockingQueue<Connection> activeConnections = destination.getActiveConnections(); Assert.assertEquals(0, activeConnections.size()); final CountDownLatch headersLatch = new CountDownLatch(1); final CountDownLatch successLatch = new CountDownLatch(3); client.newRequest(host, port) .scheme(scheme) .onRequestSuccess(new Request.SuccessListener() { @Override public void onSuccess(Request request) { successLatch.countDown(); } }) .onResponseHeaders(new Response.HeadersListener() { @Override public void onHeaders(Response response) { Assert.assertEquals(0, idleConnections.size()); Assert.assertEquals(1, activeConnections.size()); headersLatch.countDown(); } }) .send(new Response.Listener.Empty() { @Override public void onSuccess(Response response) { successLatch.countDown(); } @Override public void onComplete(Result result) { Assert.assertFalse(result.isFailed()); successLatch.countDown(); } }); Assert.assertTrue(headersLatch.await(5, TimeUnit.SECONDS)); Assert.assertTrue(successLatch.await(5, TimeUnit.SECONDS)); Assert.assertEquals(1, idleConnections.size()); Assert.assertEquals(0, activeConnections.size()); } @Test public void test_FailedRequest_RemovesConnection() throws Exception { start(new EmptyServerHandler()); String host = "localhost"; int port = connector.getLocalPort(); HttpDestination destination = (HttpDestination)client.getDestination(scheme, host, port); final BlockingQueue<Connection> idleConnections = destination.getIdleConnections(); Assert.assertEquals(0, idleConnections.size()); final BlockingQueue<Connection> activeConnections = destination.getActiveConnections(); Assert.assertEquals(0, activeConnections.size()); final CountDownLatch beginLatch = new CountDownLatch(1); final CountDownLatch failureLatch = new CountDownLatch(2); client.newRequest(host, port).scheme(scheme).listener(new Request.Listener.Empty() { @Override public void onBegin(Request request) { activeConnections.peek().close(); beginLatch.countDown(); } @Override public void onFailure(Request request, Throwable failure) { failureLatch.countDown(); } }).send(new Response.Listener.Empty() { @Override public void onComplete(Result result) { Assert.assertTrue(result.isFailed()); Assert.assertEquals(0, idleConnections.size()); Assert.assertEquals(0, activeConnections.size()); failureLatch.countDown(); } }); Assert.assertTrue(beginLatch.await(5, TimeUnit.SECONDS)); Assert.assertTrue(failureLatch.await(5, TimeUnit.SECONDS)); Assert.assertEquals(0, idleConnections.size()); Assert.assertEquals(0, activeConnections.size()); } @Test public void test_BadRequest_RemovesConnection() throws Exception { start(new EmptyServerHandler()); String host = "localhost"; int port = connector.getLocalPort(); HttpDestination destination = (HttpDestination)client.getDestination(scheme, host, port); final BlockingQueue<Connection> idleConnections = destination.getIdleConnections(); Assert.assertEquals(0, idleConnections.size()); final BlockingQueue<Connection> activeConnections = destination.getActiveConnections(); Assert.assertEquals(0, activeConnections.size()); final CountDownLatch successLatch = new CountDownLatch(3); client.newRequest(host, port) .scheme(scheme) .listener(new Request.Listener.Empty() { @Override public void onBegin(Request request) { // Remove the host header, this will make the request invalid request.header(HttpHeader.HOST, null); } @Override public void onSuccess(Request request) { successLatch.countDown(); } }) .send(new Response.Listener.Empty() { @Override public void onSuccess(Response response) { Assert.assertEquals(400, response.getStatus()); // 400 response also come with a Connection: close, // so the connection is closed and removed successLatch.countDown(); } @Override public void onComplete(Result result) { Assert.assertFalse(result.isFailed()); successLatch.countDown(); } }); Assert.assertTrue(successLatch.await(5, TimeUnit.SECONDS)); Assert.assertEquals(0, idleConnections.size()); Assert.assertEquals(0, activeConnections.size()); } @Slow @Test public void test_BadRequest_WithSlowRequest_RemovesConnection() throws Exception { start(new EmptyServerHandler()); String host = "localhost"; int port = connector.getLocalPort(); HttpDestination destination = (HttpDestination)client.getDestination(scheme, host, port); final BlockingQueue<Connection> idleConnections = destination.getIdleConnections(); Assert.assertEquals(0, idleConnections.size()); final BlockingQueue<Connection> activeConnections = destination.getActiveConnections(); Assert.assertEquals(0, activeConnections.size()); final long delay = 1000; final CountDownLatch successLatch = new CountDownLatch(3); client.newRequest(host, port) .scheme(scheme) .listener(new Request.Listener.Empty() { @Override public void onBegin(Request request) { // Remove the host header, this will make the request invalid request.header(HttpHeader.HOST, null); } @Override public void onHeaders(Request request) { try { TimeUnit.MILLISECONDS.sleep(delay); } catch (InterruptedException e) { e.printStackTrace(); } } @Override public void onSuccess(Request request) { successLatch.countDown(); } }) .send(new Response.Listener.Empty() { @Override public void onSuccess(Response response) { Assert.assertEquals(400, response.getStatus()); // 400 response also come with a Connection: close, // so the connection is closed and removed successLatch.countDown(); } @Override public void onComplete(Result result) { Assert.assertFalse(result.isFailed()); successLatch.countDown(); } }); Assert.assertTrue(successLatch.await(delay * 5, TimeUnit.MILLISECONDS)); Assert.assertEquals(0, idleConnections.size()); Assert.assertEquals(0, activeConnections.size()); } @Test public void test_ConnectionFailure_RemovesConnection() throws Exception { start(new EmptyServerHandler()); String host = "localhost"; int port = connector.getLocalPort(); HttpDestination destination = (HttpDestination)client.getDestination(scheme, host, port); final BlockingQueue<Connection> idleConnections = destination.getIdleConnections(); Assert.assertEquals(0, idleConnections.size()); final BlockingQueue<Connection> activeConnections = destination.getActiveConnections(); Assert.assertEquals(0, activeConnections.size()); server.stop(); final CountDownLatch failureLatch = new CountDownLatch(2); client.newRequest(host, port) .scheme(scheme) .onRequestFailure(new Request.FailureListener() { @Override public void onFailure(Request request, Throwable failure) { failureLatch.countDown(); } }) .send(new Response.Listener.Empty() { @Override public void onComplete(Result result) { Assert.assertTrue(result.isFailed()); failureLatch.countDown(); } }); Assert.assertTrue(failureLatch.await(5, TimeUnit.SECONDS)); Assert.assertEquals(0, idleConnections.size()); Assert.assertEquals(0, activeConnections.size()); } @Test public void test_ResponseWithConnectionCloseHeader_RemovesConnection() throws Exception { start(new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setHeader("Connection", "close"); baseRequest.setHandled(true); } }); String host = "localhost"; int port = connector.getLocalPort(); HttpDestination destination = (HttpDestination)client.getDestination(scheme, host, port); final BlockingQueue<Connection> idleConnections = destination.getIdleConnections(); Assert.assertEquals(0, idleConnections.size()); final BlockingQueue<Connection> activeConnections = destination.getActiveConnections(); Assert.assertEquals(0, activeConnections.size()); final CountDownLatch latch = new CountDownLatch(1); client.newRequest(host, port) .scheme(scheme) .send(new Response.Listener.Empty() { @Override public void onComplete(Result result) { Assert.assertFalse(result.isFailed()); Assert.assertEquals(0, idleConnections.size()); Assert.assertEquals(0, activeConnections.size()); latch.countDown(); } }); Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); Assert.assertEquals(0, idleConnections.size()); Assert.assertEquals(0, activeConnections.size()); } @Test public void test_BigRequestContent_ResponseWithConnectionCloseHeader_RemovesConnection() throws Exception { StdErrLog logger = StdErrLog.getLogger(org.eclipse.jetty.server.HttpConnection.class); logger.setHideStacks(true); try { start(new AbstractHandler() { @Override public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setHeader("Connection", "close"); baseRequest.setHandled(true); // Don't read request content; this causes the server parser to be closed } }); String host = "localhost"; int port = connector.getLocalPort(); HttpDestination destination = (HttpDestination)client.getDestination(scheme, host, port); final BlockingQueue<Connection> idleConnections = destination.getIdleConnections(); Assert.assertEquals(0, idleConnections.size()); final BlockingQueue<Connection> activeConnections = destination.getActiveConnections(); Assert.assertEquals(0, activeConnections.size()); Log.getLogger(HttpConnection.class).info("Expecting java.lang.IllegalStateException: HttpParser{s=CLOSED,..."); final CountDownLatch latch = new CountDownLatch(1); ByteBuffer buffer = ByteBuffer.allocate(16 * 1024 * 1024); Arrays.fill(buffer.array(),(byte)'x'); client.newRequest(host, port) .scheme(scheme) .content(new ByteBufferContentProvider(buffer)) .send(new Response.Listener.Empty() { @Override public void onComplete(Result result) { Assert.assertEquals(0, idleConnections.size()); Assert.assertEquals(0, activeConnections.size()); latch.countDown(); } }); Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); Assert.assertEquals(0, idleConnections.size()); Assert.assertEquals(0, activeConnections.size()); server.stop(); } finally { logger.setHideStacks(false); } } @Slow @Test public void test_IdleConnection_IsClosed_OnRemoteClose() throws Exception { start(new EmptyServerHandler()); String host = "localhost"; int port = connector.getLocalPort(); HttpDestination destination = (HttpDestination)client.getDestination(scheme, host, port); final BlockingQueue<Connection> idleConnections = destination.getIdleConnections(); Assert.assertEquals(0, idleConnections.size()); final BlockingQueue<Connection> activeConnections = destination.getActiveConnections(); Assert.assertEquals(0, activeConnections.size()); ContentResponse response = client.newRequest(host, port) .scheme(scheme) .timeout(5, TimeUnit.SECONDS) .send(); Assert.assertEquals(200, response.getStatus()); connector.stop(); // Give the connection some time to process the remote close TimeUnit.SECONDS.sleep(1); Assert.assertEquals(0, idleConnections.size()); Assert.assertEquals(0, activeConnections.size()); } }
package org.eclipse.jetty.webapp; import java.io.File; import java.net.URI; import java.util.Collection; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.webapp.verifier.RuleSet; import org.eclipse.jetty.webapp.verifier.Severity; import org.eclipse.jetty.webapp.verifier.Violation; import org.eclipse.jetty.webapp.verifier.WebappVerifier; /** * WebappVerifierConfiguration */ public class WebappVerifierConfiguration implements Configuration { /** * @see org.eclipse.jetty.webapp.Configuration#configure(org.eclipse.jetty.webapp.WebAppContext) */ public void configure(WebAppContext context) throws Exception { } /** * @see org.eclipse.jetty.webapp.Configuration#deconfigure(org.eclipse.jetty.webapp.WebAppContext) */ public void deconfigure(WebAppContext context) throws Exception { } /** * @see org.eclipse.jetty.webapp.Configuration#postConfigure(org.eclipse.jetty.webapp.WebAppContext) */ public void postConfigure(WebAppContext context) throws Exception { } /** * @see org.eclipse.jetty.webapp.Configuration#preConfigure(org.eclipse.jetty.webapp.WebAppContext) */ public void preConfigure(WebAppContext context) throws Exception { if(Log.isDebugEnabled()) { Log.debug("Configuring webapp verifier"); } URI configurationUri = new File( System.getProperty( "jetty.home" )).toURI().resolve( "etc/default-webapp-verifier.xml" ); RuleSet suite = RuleSet.load( configurationUri.toURL() ); String warLocation = context.getWar(); if ( !warLocation.startsWith("file:" ) ) { warLocation = "file:" + warLocation; } WebappVerifier verifier = suite.createWebappVerifier( new URI( warLocation ) ); verifier.visitAll(); Collection<Violation> violations = verifier.getViolations(); boolean haltWebapp = false; Log.info( " Webapp Verifier Report: " + violations.size() + " violations" ); for (Violation violation : violations) { if ( violation.getSeverity() == Severity.ERROR ) { haltWebapp = true; } Log.info( violation.toString() ); } if ( haltWebapp ) { throw new InstantiationException( "Configuration exception: webapp failed webapp verification" ); } } }
package org.motechproject.nms.kilkari.service.impl; import org.motechproject.alerts.contract.AlertService; import org.motechproject.alerts.domain.AlertStatus; import org.motechproject.alerts.domain.AlertType; import org.motechproject.event.MotechEvent; import org.motechproject.event.listener.annotations.MotechListener; import org.motechproject.nms.kilkari.domain.CallRetry; import org.motechproject.nms.kilkari.domain.CallStage; import org.motechproject.nms.kilkari.domain.CallSummaryRecord; import org.motechproject.nms.kilkari.domain.DeactivationReason; import org.motechproject.nms.kilkari.domain.Subscriber; import org.motechproject.nms.kilkari.domain.Subscription; import org.motechproject.nms.kilkari.domain.SubscriptionOrigin; import org.motechproject.nms.kilkari.domain.SubscriptionPackMessage; import org.motechproject.nms.kilkari.domain.SubscriptionStatus; import org.motechproject.nms.kilkari.dto.CallSummaryRecordDto; import org.motechproject.nms.kilkari.repository.CallRetryDataService; import org.motechproject.nms.kilkari.repository.CallSummaryRecordDataService; import org.motechproject.nms.kilkari.repository.SubscriberDataService; import org.motechproject.nms.kilkari.repository.SubscriptionDataService; import org.motechproject.nms.kilkari.repository.SubscriptionPackMessageDataService; import org.motechproject.nms.kilkari.service.CsrService; import org.motechproject.nms.props.domain.DayOfTheWeek; import org.motechproject.nms.props.domain.FinalCallStatus; import org.motechproject.nms.props.domain.StatusCode; import org.motechproject.nms.region.domain.Circle; import org.motechproject.nms.region.domain.Language; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.Map; @Service("csrService") public class CsrServiceImpl implements CsrService { private static final String PROCESS_SUMMARY_RECORD_SUBJECT = "nms.imi.kk.process_summary_record"; private static final String CSR_PARAM_KEY = "csr"; private static final int ONE_HUNDRED = 100; private static final Logger LOGGER = LoggerFactory.getLogger(CsrServiceImpl.class); private CallSummaryRecordDataService csrDataService; private SubscriptionDataService subscriptionDataService; private CallRetryDataService callRetryDataService; private SubscriberDataService subscriberDataService; private AlertService alertService; private SubscriptionPackMessageDataService subscriptionPackMessageDataService; private Map<String, Integer> messageDuration; @Autowired public CsrServiceImpl(CallSummaryRecordDataService csrDataService, SubscriptionDataService subscriptionDataService, CallRetryDataService callRetryDataService, SubscriberDataService subscriberDataService, AlertService alertService, SubscriptionPackMessageDataService subscriptionPackMessageDataService) { this.csrDataService = csrDataService; this.subscriptionDataService = subscriptionDataService; this.callRetryDataService = callRetryDataService; this.subscriberDataService = subscriberDataService; this.alertService = alertService; this.subscriptionPackMessageDataService = subscriptionPackMessageDataService; buildMessageDurationCache(); } public final void buildMessageDurationCache() { messageDuration = new HashMap<>(); for (SubscriptionPackMessage msg : subscriptionPackMessageDataService.retrieveAll()) { messageDuration.put(msg.getMessageFileName(), msg.getDuration()); } } //todo: IT private int calculatePercentPlayed(String contentFileName, int duration) { //refresh Cache if empty if (messageDuration.size() == 0) { buildMessageDurationCache(); } if (messageDuration.containsKey(contentFileName)) { int totalDuration = messageDuration.get(contentFileName); return duration / totalDuration * ONE_HUNDRED; } throw new IllegalArgumentException(String.format("Invalid contentFileName: %s", contentFileName)); } private String getLanguageCode(Subscription subscription) { //todo: don't understand why subscriber.getLanguage() doesn't work here... Subscriber subscriber = subscription.getSubscriber(); Language language; language = (Language) subscriberDataService.getDetachedField(subscriber, "language"); return language.getCode(); } private String getCircleName(Subscription subscription) { Subscriber subscriber = subscription.getSubscriber(); Circle circle = (Circle) subscriberDataService.getDetachedField(subscriber, "circle"); return circle.getName(); } private void completeSubscriptionIfNeeded(Subscription subscription, CallSummaryRecord record, CallRetry callRetry) { if (!subscription.isLastPackMessage(record.getContentFileName())) { // This subscription has not completed, do nothing return; } // Mark the subscription completed subscription.setStatus(SubscriptionStatus.COMPLETED); subscriptionDataService.update(subscription); // Delete the callRetry entry, if any if (callRetry != null) { callRetryDataService.delete(callRetry); } } // Check if this call has been failing with OBD_FAILED_INVALIDNUMBER for all the retries. // See issue private boolean isMsisdnInvalid(CallSummaryRecord record) { if (record.getStatusStats().keySet().size() > 1) { return false; } return record.getStatusStats().containsKey(StatusCode.OBD_FAILED_INVALIDNUMBER.getValue()); } private void rescheduleCall(Subscription subscription, CallSummaryRecord record, CallRetry callRetry) { Long msisdn = subscription.getSubscriber().getCallingNumber(); if (callRetry == null) { // This message was never retried before, so this is a first retry DayOfTheWeek nextDay = DayOfTheWeek.fromInt(subscription.getStartDate().dayOfWeek().get()).nextDay(); CallRetry newCallRetry = new CallRetry( subscription.getSubscriptionId(), msisdn, nextDay, CallStage.RETRY_1, record.getContentFileName(), record.getWeekId(), getLanguageCode(subscription), getCircleName(subscription), subscription.getOrigin() ); callRetryDataService.create(newCallRetry); return; } // We've already rescheduled this call, let's see if it needs to be re-rescheduled if ((subscription.getSubscriptionPack().retryCount() == 1) || (callRetry.getCallStage() == CallStage.RETRY_LAST)) { // Nope, this call should not be retried // Deactivate subscription for persistent invalid numbers if (isMsisdnInvalid(record)) { subscription.setStatus(SubscriptionStatus.DEACTIVATED); subscription.setDeactivationReason(DeactivationReason.INVALID_NUMBER); subscriptionDataService.update(subscription); } callRetryDataService.delete(callRetry); // Does subscription need to be marked complete, even if we failed to send the last message? completeSubscriptionIfNeeded(subscription, record, callRetry); return; } // Re-reschedule the call callRetry.setCallStage(callRetry.getCallStage().nextStage()); callRetry.setDayOfTheWeek(callRetry.getDayOfTheWeek().nextDay()); callRetryDataService.update(callRetry); } private void deactivateSubscription(Subscription subscription, CallRetry callRetry) { if (subscription.getOrigin() == SubscriptionOrigin.IVR) { String error = String.format("Subscription %s was rejected (DND) but its origin is IVR, not MCTS!", subscription.getSubscriptionId()); LOGGER.error(error); alertService.create(subscription.getSubscriptionId(), "subscription", error, AlertType.CRITICAL, AlertStatus.NEW, 0, null); return; } // Delete the callRetry entry, if any if (callRetry != null) { callRetryDataService.delete(callRetry); } //Deactivate the subscription subscription.setStatus(SubscriptionStatus.DEACTIVATED); subscription.setDeactivationReason(DeactivationReason.DO_NOT_DISTURB); subscriptionDataService.update(subscription); } private void aggregateStats(Map<Integer, Integer> src, Map<Integer, Integer> dst) { for (Map.Entry<Integer, Integer> entry : src.entrySet()) { if (dst.containsKey(entry.getKey())) { dst.put(entry.getKey(), dst.get(entry.getKey()) + entry.getValue()); } else { dst.put(entry.getKey(), entry.getValue()); } } } private CallSummaryRecord aggregateSummaryRecord(CallSummaryRecordDto csr) { CallSummaryRecord record = csrDataService.findByRequestId(csr.getRequestId().toString()); if (record == null) { record = csrDataService.create(new CallSummaryRecord( csr.getRequestId().toString(), csr.getMsisdn(), csr.getContentFileName(), csr.getWeekId(), csr.getLanguageLocationCode(), csr.getCircle(), csr.getFinalStatus(), csr.getStatusStats(), calculatePercentPlayed(csr.getContentFileName(), csr.getSecondsPlayed()), csr.getCallAttempts(), 1)); } else { aggregateStats(csr.getStatusStats(), record.getStatusStats()); record.setCallAttempts(record.getCallAttempts() + csr.getCallAttempts()); record.setAttemptedDayCount(record.getAttemptedDayCount() + 1); record.setFinalStatus(csr.getFinalStatus()); int percentPlayed = calculatePercentPlayed(csr.getContentFileName(), csr.getSecondsPlayed()); if (percentPlayed > record.getPercentPlayed()) { record.setPercentPlayed(percentPlayed); } csrDataService.update(record); } return record; } @MotechListener(subjects = { PROCESS_SUMMARY_RECORD_SUBJECT }) public void processCallSummaryRecord(MotechEvent event) { CallSummaryRecordDto csr = (CallSummaryRecordDto) event.getParameters().get(CSR_PARAM_KEY); String subscriptionId = csr.getRequestId().getSubscriptionId(); CallSummaryRecord record = aggregateSummaryRecord(csr); CallRetry callRetry = callRetryDataService.findBySubscriptionId(subscriptionId); Subscription subscription = subscriptionDataService.findBySubscriptionId(subscriptionId); if (csr.getFinalStatus() == FinalCallStatus.SUCCESS) { completeSubscriptionIfNeeded(subscription, record, callRetry); } if (csr.getFinalStatus() == FinalCallStatus.FAILED) { rescheduleCall(subscription, record, callRetry); } if (csr.getFinalStatus() == FinalCallStatus.REJECTED) { deactivateSubscription(subscription, callRetry); } } }
package org.languagetool.rules.patterns; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.junit.Test; import org.languagetool.AnalyzedSentence; import org.languagetool.AnalyzedTokenReadings; import org.languagetool.FakeLanguage; import org.languagetool.JLanguageTool; import org.languagetool.Language; import org.languagetool.Languages; import org.languagetool.MultiThreadedJLanguageTool; import org.languagetool.TestTools; import org.languagetool.XMLValidator; import org.languagetool.rules.Category; import org.languagetool.rules.CorrectExample; import org.languagetool.rules.ErrorTriggeringExample; import org.languagetool.rules.IncorrectExample; import org.languagetool.rules.Rule; import org.languagetool.rules.RuleMatch; import org.languagetool.rules.spelling.SpellingCheckRule; import org.languagetool.tagging.disambiguation.rules.DisambiguationPatternRule; /** * @author Daniel Naber */ public class PatternRuleTest extends AbstractPatternRuleTest { // A test sentence should only be a single sentence - if that's not the case it can // happen that rules are checked as being correct that in reality will never match. // This check prints a warning for affected rules, but it's disabled by default because // it makes the tests very slow: private static final boolean CHECK_WITH_SENTENCE_SPLITTING = false; private static final Pattern PATTERN_MARKER_START = Pattern.compile(".*<pattern[^>]*>\\s*<marker>.*", Pattern.DOTALL); private static final Pattern PATTERN_MARKER_END = Pattern.compile(".*</marker>\\s*</pattern>.*", Pattern.DOTALL); private static final Comparator<Match> MATCH_COMPARATOR = (m1, m2) -> Integer.compare( m1.getTokenRef(), m2.getTokenRef()); public void testFake() { // there's no test here - the languages are supposed to extend this class and call runGrammarRulesFromXmlTest() } @Test public void testSupportsLanguage() { FakeLanguage fakeLanguage1 = new FakeLanguage("yy"); FakeLanguage fakeLanguage2 = new FakeLanguage("zz"); PatternRule patternRule1 = new PatternRule("ID", fakeLanguage1, Collections.<PatternToken>emptyList(), "", "", ""); assertTrue(patternRule1.supportsLanguage(fakeLanguage1)); assertFalse(patternRule1.supportsLanguage(fakeLanguage2)); FakeLanguage fakeLanguage1WithVariant1 = new FakeLanguage("zz", "VAR1"); FakeLanguage fakeLanguage1WithVariant2 = new FakeLanguage("zz", "VAR2"); PatternRule patternRuleVariant1 = new PatternRule("ID", fakeLanguage1WithVariant1, Collections.<PatternToken>emptyList(), "", "", ""); assertTrue(patternRuleVariant1.supportsLanguage(fakeLanguage1WithVariant1)); assertFalse(patternRuleVariant1.supportsLanguage(fakeLanguage1)); assertFalse(patternRuleVariant1.supportsLanguage(fakeLanguage2)); assertFalse(patternRuleVariant1.supportsLanguage(fakeLanguage1WithVariant2)); } /** * To be called from language modules. Languages.get() knows only the languages that's in the classpath. * @param ignoredLanguage ignore this language - useful to speed up tests from languages that * have another language as a dependency */ protected void runGrammarRulesFromXmlTest(Language ignoredLanguage) throws IOException { int count = 0; for (Language lang : Languages.get()) { if (ignoredLanguage.getShortCodeWithCountryAndVariant().equals(lang.getShortCodeWithCountryAndVariant())) { continue; } runGrammarRuleForLanguage(lang); count++; } if (count == 0) { System.err.println("Warning: no languages found in classpath - cannot run any grammar rule tests"); } } /** * To be called from language modules. Languages.get() only knows the languages that are in the classpath, * and that's only the demo language for languagetool-core. */ protected void runGrammarRulesFromXmlTest() throws IOException { for (Language lang : Languages.get()) { runGrammarRuleForLanguage(lang); } if (Languages.get().isEmpty()) { System.err.println("Warning: no languages found in classpath - cannot run any grammar rule tests"); } } protected void runGrammarRuleForLanguage(Language lang) throws IOException { if (skipCountryVariant(lang)) { System.out.println("Skipping " + lang + " because there are no specific rules for that variant"); return; } runTestForLanguage(lang); } private void runGrammarRulesFromXmlTestIgnoringLanguages(Set<Language> ignoredLanguages) throws IOException { System.out.println("Known languages: " + Languages.getWithDemoLanguage()); for (Language lang : Languages.getWithDemoLanguage()) { if (ignoredLanguages != null && ignoredLanguages.contains(lang)) { continue; } runTestForLanguage(lang); } } public void runTestForLanguage(Language lang) throws IOException { validatePatternFile(lang); System.out.println("Running pattern rule tests for " + lang.getName() + "... "); MultiThreadedJLanguageTool lt = new MultiThreadedJLanguageTool(lang); if (CHECK_WITH_SENTENCE_SPLITTING) { disableSpellingRules(lt); } MultiThreadedJLanguageTool allRulesLt = new MultiThreadedJLanguageTool(lang); validateRuleIds(lang, allRulesLt); validateSentenceStartNotInMarker(allRulesLt); List<AbstractPatternRule> rules = getAllPatternRules(lang, lt); testRegexSyntax(lang, rules); testExamplesExist(lang, rules); testGrammarRulesFromXML(rules, lt, allRulesLt, lang); System.out.println(rules.size() + " rules tested."); allRulesLt.shutdown(); lt.shutdown(); } private void validatePatternFile(Language lang) throws IOException { validatePatternFile(getGrammarFileNames(lang)); } protected void validatePatternFile(List<String> grammarFiles) throws IOException { XMLValidator validator = new XMLValidator(); for (String grammarFile : grammarFiles) { System.out.println("Running XML validation for " + grammarFile + "..."); String rulesDir = JLanguageTool.getDataBroker().getRulesDir(); String ruleFilePath = rulesDir + "/" + grammarFile; try (InputStream xmlStream = this.getClass().getResourceAsStream(ruleFilePath)) { if (xmlStream == null) { if (!ruleFilePath.equals("/org/languagetool/rules/en/en-US/grammar-l2-de.xml") && !ruleFilePath.equals("/org/languagetool/rules/en/en-US/grammar-l2-fr.xml")) { System.out.println("No rule file found at " + ruleFilePath + " in classpath. THIS SHOULD BE FIXED!"); } continue; } // if there are multiple xml grammar files we'll prepend all unification elements // from the first file to the rest of them if (grammarFiles.size() > 1 && !grammarFiles.get(0).equals(grammarFile)) { validator.validateWithXmlSchema(rulesDir + "/" + grammarFiles.get(0), ruleFilePath, rulesDir + "/rules.xsd"); } else { validator.validateWithXmlSchema(ruleFilePath, rulesDir + "/rules.xsd"); } } } } private void validateRuleIds(Language lang, JLanguageTool lt) { List<Rule> allRules = lt.getAllRules(); Set<String> categoryIds = new HashSet<>(); new RuleIdValidator(lang).validateUniqueness(); for (Rule rule : allRules) { if (rule.getId().equalsIgnoreCase("ID")) { System.err.println("WARNING: " + lang.getShortCodeWithCountryAndVariant() + " has a rule with id 'ID', this should probably be changed"); } Category category = rule.getCategory(); if (category != null && category.getId() != null) { String catId = category.getId().toString(); if (!catId.matches("[A-Z0-9_-]+") && !categoryIds.contains(catId)) { System.err.println("WARNING: category id '" + catId + "' doesn't match expected regexp [A-Z0-9_-]+"); categoryIds.add(catId); } } } } /* * A <marker> that covers the SENT_START can lead to obscure offset issues, so warn about that. */ private void validateSentenceStartNotInMarker(JLanguageTool lt) { System.out.println("Check that sentence start tag is not included in <marker>...."); List<Rule> rules = lt.getAllRules(); for (Rule rule : rules) { if (rule instanceof AbstractPatternRule) { List<PatternToken> patternTokens = ((AbstractPatternRule) rule).getPatternTokens(); if (patternTokens != null) { boolean hasExplicitMarker = patternTokens.stream().anyMatch(PatternToken::isInsideMarker); for (PatternToken patternToken : patternTokens) { if ((patternToken.isInsideMarker() || !hasExplicitMarker) && patternToken.isSentenceStart()) { System.err.println("WARNING: Sentence start in <marker>: " + ((AbstractPatternRule) rule).getFullId() + " (hasExplicitMarker: " + hasExplicitMarker + ") - please move the <marker> so the SENT_START is not covered"); } } } } } } private void disableSpellingRules(JLanguageTool lt) { List<Rule> allRules = lt.getAllRules(); for (Rule rule : allRules) { if (rule instanceof SpellingCheckRule) { lt.disableRule(rule.getId()); } } } private void testRegexSyntax(Language lang, List<AbstractPatternRule> rules) { System.out.println("Checking regexp syntax of " + rules.size() + " rules for " + lang + "..."); for (AbstractPatternRule rule : rules) { // Test the rule pattern. /* check for useless 'marker' elements commented out - too slow to always run: PatternRuleXmlCreator creator = new PatternRuleXmlCreator(); String xml = creator.toXML(rule.getPatternRuleId(), lang); if (PATTERN_MARKER_START.matcher(xml).matches() && PATTERN_MARKER_END.matcher(xml).matches()) { System.err.println("WARNING " + lang + ": useless <marker>: " + rule.getFullId()); }*/ // too aggressive for now: //PatternTestTools.failIfWhitespaceInToken(rule.getPatternTokens(), rule, lang); PatternTestTools.warnIfRegexpSyntaxNotKosher(rule.getPatternTokens(), rule.getId(), rule.getSubId(), lang); // Test the rule antipatterns. List<DisambiguationPatternRule> antiPatterns = rule.getAntiPatterns(); for (DisambiguationPatternRule antiPattern : antiPatterns) { PatternTestTools.warnIfRegexpSyntaxNotKosher(antiPattern.getPatternTokens(), antiPattern.getId(), antiPattern.getSubId(), lang); } } } private void testExamplesExist(Language lang, List<AbstractPatternRule> rules) { for (AbstractPatternRule rule : rules) { if (rule.getCorrectExamples().isEmpty()) { boolean correctionExists = false; for (IncorrectExample incorrectExample : rule.getIncorrectExamples()) { if (incorrectExample.getCorrections().size() > 0) { correctionExists = true; break; } } if (!correctionExists) { fail("Rule " + rule.getFullId() + " in language " + lang + " needs at least one <example> with a 'correction' attribute" + " or one <example> of type='correct'."); } } } } public void testGrammarRulesFromXML(List<AbstractPatternRule> rules, JLanguageTool lt, JLanguageTool allRulesLt, Language lang) throws IOException { System.out.println("Checking example sentences of " + rules.size() + " rules for " + lang + "..."); Map<String, AbstractPatternRule> complexRules = new HashMap<>(); int skipCount = 0; int i = 0; for (AbstractPatternRule rule : rules) { String sourceFile = rule.getSourceFile(); if (lang.isVariant() && sourceFile != null && sourceFile.matches("/org/languagetool/rules/" + lang.getShortCode() + "/grammar.*\\.xml") && !sourceFile.contains("-l2-")) { //System.out.println("Skipping " + rule.getFullId() + " in " + sourceFile + " because we're checking a variant"); skipCount++; continue; } testCorrectSentences(lt, allRulesLt, lang, rule); testBadSentences(lt, allRulesLt, lang, complexRules, rule); testErrorTriggeringSentences(lt, lang, rule); if (++i % 100 == 0) { System.out.println("Testing rule " + i + "..."); } } System.out.println("Skipped " + skipCount + " rules for variant language to avoid checking rules more than once"); if (!complexRules.isEmpty()) { Set<String> set = complexRules.keySet(); List<AbstractPatternRule> badRules = new ArrayList<>(); for (String aSet : set) { AbstractPatternRule badRule = complexRules.get(aSet); if (badRule instanceof PatternRule) { ((PatternRule)badRule).notComplexPhrase(); badRule.setMessage("The rule contains a phrase that never matched any incorrect example.\n" + ((PatternRule) badRule).toPatternString()); badRules.add(badRule); } } if (!badRules.isEmpty()) { testGrammarRulesFromXML(badRules, lt, allRulesLt, lang); } } } private void testBadSentences(JLanguageTool lt, JLanguageTool allRulesLt, Language lang, Map<String, AbstractPatternRule> complexRules, AbstractPatternRule rule) throws IOException { List<IncorrectExample> badSentences = rule.getIncorrectExamples(); if (badSentences.isEmpty()) { fail("No incorrect examples found for rule " + rule.getFullId()); } // necessary for XML Pattern rules containing <or> List<AbstractPatternRule> rules = allRulesLt.getPatternRulesByIdAndSubId(rule.getId(), rule.getSubId()); for (IncorrectExample origBadExample : badSentences) { // enable indentation use String origBadSentence = origBadExample.getExample().replaceAll("[\\n\\t]+", ""); List<String> expectedCorrections = origBadExample.getCorrections(); int expectedMatchStart = origBadSentence.indexOf("<marker>"); int expectedMatchEnd = origBadSentence.indexOf("</marker>") - "<marker>".length(); if (expectedMatchStart == -1 || expectedMatchEnd == -1) { fail(lang + ": No error position markup ('<marker>...</marker>') in bad example in rule " + rule.getFullId()); } String badSentence = cleanMarkersInExample(origBadSentence); assertTrue(badSentence.trim().length() > 0); // necessary for XML Pattern rules containing <or> List<RuleMatch> matches = new ArrayList<>(); for (Rule auxRule : rules) { matches.addAll(getMatchesForSingleSentence(auxRule, badSentence, lt)); } if (rule instanceof RegexPatternRule || rule instanceof PatternRule && !((PatternRule)rule).isWithComplexPhrase()) { if (matches.size() != 1) { AnalyzedSentence analyzedSentence = lt.getAnalyzedSentence(badSentence); StringBuilder sb = new StringBuilder("Analyzed token readings:"); for (AnalyzedTokenReadings atr : analyzedSentence.getTokens()) { sb.append(" ").append(atr); } String info = ""; if (rule instanceof RegexPatternRule) { info = "\nRegexp: " + ((RegexPatternRule) rule).getPattern().toString(); } fail(lang + " rule " + rule.getFullId() + ":\n\"" + badSentence + "\"\n" + "Errors expected: 1\n" + "Errors found : " + matches.size() + "\n" + "Message: " + rule.getMessage() + "\n" + sb + "\nMatches: " + matches + info); } int maxReference = 0; if (rule.getSuggestionMatches() != null) { Optional<Match> opt = rule.getSuggestionMatches().stream().max(MATCH_COMPARATOR); maxReference = opt.isPresent() ? opt.get().getTokenRef() : 0; } maxReference = Math.max( rule.getMessage() != null ? findLargestReference(rule.getMessage()) : 0, maxReference); if (rule.getPatternTokens() != null && maxReference > rule.getPatternTokens().size()) { System.err.println("Warning: Rule "+rule.getFullId()+" refers to token \\"+(maxReference)+" but has only "+rule.getPatternTokens().size()+" tokens."); } assertEquals(lang + ": Incorrect match position markup (start) for rule " + rule.getFullId() + ", sentence: " + badSentence, expectedMatchStart, matches.get(0).getFromPos()); assertEquals(lang + ": Incorrect match position markup (end) for rule " + rule.getFullId() + ", sentence: " + badSentence, expectedMatchEnd, matches.get(0).getToPos()); // make sure suggestion is what we expect it to be assertSuggestions(badSentence, lang, expectedCorrections, rule, matches); // make sure the suggested correction doesn't produce an error: if (matches.get(0).getSuggestedReplacements().size() > 0) { int fromPos = matches.get(0).getFromPos(); int toPos = matches.get(0).getToPos(); for (String replacement : matches.get(0).getSuggestedReplacements()) { String fixedSentence = badSentence.substring(0, fromPos) + replacement + badSentence.substring(toPos); matches = getMatchesForSingleSentence(rule, fixedSentence, lt); if (matches.size() > 0) { fail("Incorrect input:\n" + " " + badSentence + "\nCorrected sentence:\n" + " " + fixedSentence + "\nBy Rule:\n" + " " + rule.getFullId() + "\nThe correction triggered an error itself:\n" + " " + matches.get(0) + "\n"); } } } } else { // for multiple rules created with complex phrases matches = getMatchesForSingleSentence(rule, badSentence, lt); if (matches.isEmpty() && !complexRules.containsKey(rule.getId() + badSentence)) { complexRules.put(rule.getId() + badSentence, rule); } if (matches.size() != 0) { complexRules.put(rule.getId() + badSentence, null); assertTrue(lang + ": Did expect one error in: \"" + badSentence + "\" (Rule: " + rule.getFullId() + "), got " + matches.size(), matches.size() == 1); assertEquals(lang + ": Incorrect match position markup (start) for rule " + rule.getFullId(), expectedMatchStart, matches.get(0).getFromPos()); assertEquals(lang + ": Incorrect match position markup (end) for rule " + rule.getFullId(), expectedMatchEnd, matches.get(0).getToPos()); assertSuggestions(badSentence, lang, expectedCorrections, rule, matches); assertSuggestionsDoNotCreateErrors(badSentence, lt, rule, matches); } } // check for overlapping rules /*matches = getMatches(rule, badSentence, lt); List<RuleMatch> matchesAllRules = allRulesLt.check(badSentence); for (RuleMatch match : matchesAllRules) { if (!match.getRule().getId().equals(rule.getId()) && !matches.isEmpty() && rangeIsOverlapping(matches.get(0).getFromPos(), matches.get(0).getToPos(), match.getFromPos(), match.getToPos())) System.err.println("WARNING: " + lang.getShortCode() + ": '" + badSentence + "' in " + rule.getId() + " also matched " + match.getRule().getId()); }*/ } } private int findLargestReference (String message) { Pattern pattern = Pattern.compile("\\\\[0-9]+"); Matcher matcher = pattern.matcher(message); int max = 0; while (matcher.find()) { max = Math.max(max, Integer.parseInt(matcher.group().replace("\\", ""))); } return max; } private void testErrorTriggeringSentences(JLanguageTool lt, Language lang, AbstractPatternRule rule) throws IOException { for (ErrorTriggeringExample example : rule.getErrorTriggeringExamples()) { String sentence = cleanXML(example.getExample()); List<RuleMatch> matches = getMatchesForText(rule, sentence, lt); if (matches.isEmpty()) { fail(lang + ": " + rule.getFullId() + ": Example sentence marked with 'triggers_error' didn't actually trigger an error: '" + sentence + "'"); } } } /** * returns true if [a, b] has at least one number in common with [x, y] */ private boolean rangeIsOverlapping(int a, int b, int x, int y) { if (a < x) { return x <= b; } else { return a <= y; } } private void assertSuggestions(String sentence, Language lang, List<String> expectedCorrections, AbstractPatternRule rule, List<RuleMatch> matches) { if (!expectedCorrections.isEmpty()) { boolean expectedNonEmptyCorrection = expectedCorrections.get(0).length() > 0; if (expectedNonEmptyCorrection) { assertTrue("You specified a correction but your message has no suggestions in rule " + rule.getFullId(), rule.getMessage().contains("<suggestion>") || rule.getSuggestionsOutMsg().contains("<suggestion>")); } List<String> realSuggestions = matches.get(0).getSuggestedReplacements(); if (realSuggestions.isEmpty()) { boolean expectedEmptyCorrection = expectedCorrections.size() == 1 && expectedCorrections.get(0).length() == 0; assertTrue(lang + ": Incorrect suggestions: " + expectedCorrections + " != " + " <no suggestion> for rule " + rule.getFullId() + " on input: " + sentence, expectedEmptyCorrection); } else { assertEquals(lang + ": Incorrect suggestions: " + expectedCorrections + " != " + realSuggestions + " for rule " + rule.getFullId() + " on input: " + sentence, expectedCorrections, realSuggestions); } } } private void assertSuggestionsDoNotCreateErrors(String badSentence, JLanguageTool lt, AbstractPatternRule rule, List<RuleMatch> matches) throws IOException { if (matches.get(0).getSuggestedReplacements().size() > 0) { int fromPos = matches.get(0).getFromPos(); int toPos = matches.get(0).getToPos(); for (String replacement : matches.get(0).getSuggestedReplacements()) { String fixedSentence = badSentence.substring(0, fromPos) + replacement + badSentence.substring(toPos); List<RuleMatch> tempMatches = getMatchesForSingleSentence(rule, fixedSentence, lt); assertEquals("Corrected sentence for rule " + rule.getFullId() + " triggered error: " + fixedSentence, 0, tempMatches.size()); } } } private void testCorrectSentences(JLanguageTool lt, JLanguageTool allRulesLt, Language lang, AbstractPatternRule rule) throws IOException { List<CorrectExample> goodSentences = rule.getCorrectExamples(); // necessary for XML Pattern rules containing <or> List<AbstractPatternRule> rules = allRulesLt.getPatternRulesByIdAndSubId(rule.getId(), rule.getSubId()); for (CorrectExample goodSentenceObj : goodSentences) { // enable indentation use String goodSentence = goodSentenceObj.getExample().replaceAll("[\\n\\t]+", ""); goodSentence = cleanXML(goodSentence); assertTrue(lang + ": Empty correct example in rule " + rule.getFullId(), goodSentence.trim().length() > 0); boolean isMatched = false; // necessary for XML Pattern rules containing <or> for (Rule auxRule : rules) { isMatched = isMatched || match(auxRule, goodSentence, lt); } if (isMatched) { AnalyzedSentence analyzedSentence = lt.getAnalyzedSentence(goodSentence); StringBuilder sb = new StringBuilder("Analyzed token readings:"); for (AnalyzedTokenReadings atr : analyzedSentence.getTokens()) { sb.append(" ").append(atr); } fail(lang + ": Did not expect error in:\n" + " " + goodSentence + "\n" + " " + sb + "\n" + "Matching Rule: " + rule.getFullId() + " from " + rule.getSourceFile()); } // avoid matches with all the *other* rules: /* List<RuleMatch> matches = allRulesLt.check(goodSentence); for (RuleMatch match : matches) { System.err.println("WARNING: " + lang.getShortCode() + ": '" + goodSentence + "' did not match " + rule.getId() + " but matched " + match.getRule().getId()); } */ } } protected String cleanXML(String str) { return str.replaceAll("<([^<].*?)>", ""); } protected String cleanMarkersInExample(String str) { return str.replace("<marker>", "").replace("</marker>", ""); } private boolean match(Rule rule, String sentence, JLanguageTool lt) throws IOException { List<AnalyzedSentence> analyzedSentences = lt.analyzeText(sentence); int matchCount = 0; for (AnalyzedSentence analyzedSentence : analyzedSentences) { RuleMatch[] matches = rule.match(analyzedSentence); matchCount += matches.length; } return matchCount > 0; } // Unlike getMatchesForSingleSentence() this splits the text at sentence boundaries private List<RuleMatch> getMatchesForText(Rule rule, String sentence, JLanguageTool lt) throws IOException { List<AnalyzedSentence> analyzedSentences = lt.analyzeText(sentence); List<RuleMatch> matches = new ArrayList<>(); for (AnalyzedSentence analyzedSentence : analyzedSentences) { matches.addAll(Arrays.asList(rule.match(analyzedSentence))); } return matches; } private List<RuleMatch> getMatchesForSingleSentence(Rule rule, String sentence, JLanguageTool lt) throws IOException { AnalyzedSentence analyzedSentence = lt.getAnalyzedSentence(sentence); RuleMatch[] matches = rule.match(analyzedSentence); if (CHECK_WITH_SENTENCE_SPLITTING) { // "real check" with sentence splitting: for (Rule r : lt.getAllActiveRules()) { lt.disableRule(r.getId()); } lt.enableRule(rule.getId()); List<RuleMatch> realMatches = lt.check(sentence); List<String> realMatchRuleIds = new ArrayList<>(); for (RuleMatch realMatch : realMatches) { realMatchRuleIds.add(realMatch.getRule().getId()); } for (RuleMatch match : matches) { String ruleId = match.getRule().getId(); if (!match.getRule().isDefaultOff() && !realMatchRuleIds.contains(ruleId)) { System.err.println("WARNING: " + lt.getLanguage().getName() + ": missing rule match " + ruleId + " when splitting sentences for test sentence '" + sentence + "'"); } } } return Arrays.asList(matches); } protected PatternRule makePatternRule(String s, boolean caseSensitive, boolean regex) { List<PatternToken> patternTokens = new ArrayList<>(); String[] parts = s.split(" "); boolean pos = false; PatternToken pToken; for (String element : parts) { if (element.equals(JLanguageTool.SENTENCE_START_TAGNAME)) { pos = true; } if (!pos) { pToken = new PatternToken(element, caseSensitive, regex, false); } else { pToken = new PatternToken("", caseSensitive, regex, false); } if (pos) { pToken.setPosToken(new PatternToken.PosToken(element, false, false)); } patternTokens.add(pToken); pos = false; } PatternRule rule = new PatternRule("ID1", TestTools.getDemoLanguage(), patternTokens, "test rule", "user visible message", "short comment"); return rule; } /** * Test XML patterns, as a help for people developing rules that are not * programmers. */ public static void main(String[] args) throws IOException { PatternRuleTest test = new PatternRuleTest(); System.out.println("Running XML pattern tests..."); if (args.length == 0) { test.runGrammarRulesFromXmlTestIgnoringLanguages(null); } else { Set<Language> ignoredLanguages = TestTools.getLanguagesExcept(args); test.runGrammarRulesFromXmlTestIgnoringLanguages(ignoredLanguages); } System.out.println("Tests finished!"); } }
package com.rho.camera; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.sql.Date; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import android.annotation.SuppressLint; import android.app.Activity; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.hardware.Camera; import android.media.MediaPlayer; import android.net.Uri; import android.os.Environment; import android.provider.MediaStore; import android.view.SurfaceHolder; import com.rhomobile.rhodes.Base64; import com.rhomobile.rhodes.Logger; import com.rhomobile.rhodes.RhodesActivity; import com.rhomobile.rhodes.api.IMethodResult; import com.rhomobile.rhodes.extmanager.RhoExtManager; import com.rhomobile.rhodes.file.RhoFileApi; import com.rhomobile.rhodes.util.ContextFactory; public class CameraObject extends CameraBase implements ICameraObject { private static final String TAG = CameraObject.class.getSimpleName(); public static boolean deprecated_take_pic; private Map<String, String> mActualPropertyMap; SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_hhmmss"); void setActualPropertyMap(Map<String, String> props) { mActualPropertyMap = props; } Map<String, String> getActualPropertyMap() { return mActualPropertyMap; } private Camera mCamera; private int mCameraUsers; private Uri fileUri; String mCurrentPhotoPath = null; private ContentValues values = null; int getCameraIndex() { return CameraSingletonObject.getCameraIndex(getId()); } @Override public void setProperties(Map<String, String> propertyMap, IMethodResult result) { // TODO Auto-generated method stub Map<String, String> temp=getPropertiesMap(); temp.putAll(propertyMap); result.set(true); } @Override public void getProperties(List<String> arrayofNames, IMethodResult result) { //super.getProperties(arrayofNames, result); Map<String, Object> props = new HashMap<String, Object>(); for (String name: arrayofNames) { props.put(name, cameraPropGet(name)); } result.set(props); } private String cameraPropGet(String name) { String propValue=""; Map<String, String> temp=getPropertiesMap(); if(temp.containsKey(name)) { try{ propValue=String.valueOf(temp.get(name)); } catch(Exception ex) { } } return propValue; } static class CameraSize implements ICameraObject.ISize { private Camera.Size mSize; CameraSize(Camera.Size size) { mSize = size; } @Override public int getWidth() { return mSize.width; } @Override public int getHeight() { return mSize.height; } @Override public int D2() { return mSize.width * mSize.width + mSize.height * mSize.height; } @Override public String toString() { return "" + mSize.width + "X" + mSize.height; } } static class RawSize implements ICameraObject.ISize { private int width; private int height; RawSize(int width, int height) { this.width = width; this.height = height; } @Override public int getWidth() { return this.width; } @Override public int getHeight() { return this.height; } @Override public int D2() { return width * width + height * height; } @Override public String toString() { return "" + width + "X" + height; } } protected class TakePictureCallback implements Camera.PictureCallback { private Activity mPreviewActivity; MediaPlayer mp; TakePictureCallback(Activity previewActivity) { mPreviewActivity = previewActivity; } @Override public void onPictureTaken(byte[] data, Camera camera) { Intent intent = new Intent(); OutputStream stream = null; Bitmap bitmap = null; try { final Map<String, String> propertyMap = getActualPropertyMap(); if (propertyMap == null) { throw new RuntimeException("Camera property map is undefined"); } String outputFormat = propertyMap.get("outputFormat"); if(propertyMap.get("deprecated") == null || propertyMap.get("deprecated").equalsIgnoreCase("false")){ propertyMap.put("deprecated", "false"); deprecated_take_pic = false; } else deprecated_take_pic = true; if(propertyMap.containsKey("captureSound")){ Runnable music= new Runnable(){ public void run() { playMusic(propertyMap.get("captureSound")); } }; ExecutorService exec = Executors.newSingleThreadExecutor(); exec.submit(music); } String filePath = null; SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_hhmmss"); if(!propertyMap.containsKey("fileName")){ filePath = "/sdcard/DCIM/Camera/IMG_"+ dateFormat.format(new Date(System.currentTimeMillis())); } else{ filePath = propertyMap.get("fileName"); if(filePath.contains("\\")){ intent.putExtra("error", "Invalid file path"); } } Uri resultUri = null; BitmapFactory.Options options=new BitmapFactory.Options(); options.inPurgeable = true; bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options); if (outputFormat.equalsIgnoreCase("dataUri")) { Logger.T(TAG, "outputFormat: " + outputFormat); filePath = getTemporaryPath(filePath)+ ".jpg"; if (Boolean.parseBoolean(propertyMap.get("saveToDeviceGallery"))) { ContentResolver contentResolver = ContextFactory.getContext().getContentResolver(); Logger.T(TAG, "Image size: " + bitmap.getWidth() + "X" + bitmap.getHeight()); propertyMap.put("DeviceGallery_Key", "DeviceGallery_Value"); String strUri = null; if (!propertyMap.containsKey("fileName")) { strUri = MediaStore.Images.Media.insertImage(contentResolver, bitmap, "IMG_"+ dateFormat.format(new Date(System.currentTimeMillis())), "Camera"); } else{ strUri = MediaStore.Images.Media.insertImage(contentResolver, bitmap, new File(propertyMap.get("fileName")).getName(), "Camera"); } if (strUri != null) { resultUri = Uri.parse(strUri); } else { throw new RuntimeException("Failed to save camera image to Gallery"); } } else { stream = new FileOutputStream(filePath); resultUri = Uri.fromFile(new File(filePath)); stream.write(data); stream.flush(); stream.close(); } StringBuilder dataBuilder = new StringBuilder(); dataBuilder.append("data:image/jpeg;base64,"); dataBuilder.append(Base64.encodeToString(data, false)); propertyMap.put("captureUri", dataBuilder.toString()); propertyMap.put("dataURI", "datauri_value"); Logger.T(TAG, dataBuilder.toString()); intent.putExtra("IMAGE_WIDTH", bitmap.getWidth()); intent.putExtra("IMAGE_HEIGHT", bitmap.getHeight()); mPreviewActivity.setResult(Activity.RESULT_OK, intent); } else if (outputFormat.equalsIgnoreCase("image")) { filePath = getTemporaryPath(filePath)+ ".jpg"; Logger.T(TAG, "outputFormat: " + outputFormat + ", path: " + filePath); if (Boolean.parseBoolean(propertyMap.get("saveToDeviceGallery"))) { ContentResolver contentResolver = ContextFactory.getContext().getContentResolver(); Logger.T(TAG, "Image size: " + bitmap.getWidth() + "X" + bitmap.getHeight()); propertyMap.put("DeviceGallery_Key", "DeviceGallery_Value"); String strUri = null; if (!propertyMap.containsKey("fileName")) strUri = MediaStore.Images.Media.insertImage(contentResolver, bitmap, "IMG_"+ dateFormat.format(new Date(System.currentTimeMillis())), "Camera"); else strUri = MediaStore.Images.Media.insertImage(contentResolver, bitmap, new File(propertyMap.get("fileName")).getName(), "Camera"); if (strUri != null) { resultUri = Uri.parse(strUri); } else { throw new RuntimeException("Failed to save camera image to Gallery"); } } else { stream = new FileOutputStream(filePath); resultUri = Uri.fromFile(new File(filePath)); stream.write(data); stream.flush(); stream.close(); } intent.putExtra(MediaStore.EXTRA_OUTPUT, resultUri); intent.putExtra("IMAGE_WIDTH", bitmap.getWidth()); intent.putExtra("IMAGE_HEIGHT", bitmap.getHeight()); mPreviewActivity.setResult(Activity.RESULT_OK, intent); } } catch (Throwable e) { Logger.E(TAG, e); if (stream != null) { try { stream.close(); } catch (Throwable e1) { //Do nothing } } intent.putExtra("error", e.getMessage()); mPreviewActivity.setResult(Activity.RESULT_CANCELED, intent); } if(bitmap != null){ bitmap.recycle(); bitmap = null; System.gc(); } mPreviewActivity.finish(); } private void playMusic(String musicPath) { mp = new MediaPlayer(); try { mp.setDataSource(RhoFileApi.openFd(musicPath)); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { mp.prepare(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } mp.start(); try { Thread.sleep(3000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } mp.stop(); clearMediaPlayerResources(); } private void clearMediaPlayerResources() { // TODO Auto-generated method stub if(mp != null){ mp.release(); mp = null; } } } protected Camera getCamera() { return mCamera; } protected void setCamera(Camera camera) { mCamera = camera; } synchronized protected void openCamera() { if (mCameraUsers == 0) { setCamera(android.hardware.Camera.open()); } mCameraUsers++; } synchronized protected void closeCamera() { mCameraUsers if (mCameraUsers == 0) { getCamera().release(); } } CameraObject(String id) { super(id); getPropertiesMap().put("ChoosePicture_Key", ""); getPropertiesMap().put("cameraType", "back"); getPropertiesMap().put("compressionFormat", "jpg"); getPropertiesMap().put("outputFormat", "image"); getPropertiesMap().put("colorModel", "rgb"); getPropertiesMap().put("useSystemViewfinder", "false"); getPropertiesMap().put("saveToDeviceGallery", "false"); openCamera(); Camera.Parameters params = getCamera().getParameters(); closeCamera(); getPropertiesMap().put("maxWidth", String.valueOf(params.getPictureSize().width)); getPropertiesMap().put("maxHeight", String.valueOf(params.getPictureSize().height)); getPropertiesMap().put("desiredWidth", "640"); getPropertiesMap().put("desiredHeight", "480"); } @Override public void startPreview(SurfaceHolder surfaceHolder) { try { openCamera(); getCamera().setPreviewDisplay(surfaceHolder); getCamera().startPreview(); } catch (Throwable e) { Logger.E(TAG, e); return; } } @Override public void stopPreview() { // Surface will be destroyed when we return, so stop the preview. if (getCamera() != null) { try { getCamera().stopPreview(); getCamera().setPreviewDisplay(null); closeCamera(); } catch (Throwable e) { Logger.E(TAG, e); return; } } } @SuppressWarnings("deprecation") @SuppressLint("NewApi") @Override public ISize setPreviewSize(int width, int height) { Camera camera = getCamera(); Camera.Parameters parameters = camera.getParameters(); List<android.hardware.Camera.Size> sizes = camera.getParameters().getSupportedPictureSizes(); android.hardware.Camera.Size maxSize=sizes.get(0); if(getActualPropertyMap().containsKey("desiredWidth") || getActualPropertyMap().containsKey("desiredHeight")){ int desired_width = Integer.parseInt(getActualPropertyMap().get("desiredWidth")); int desired_height = Integer.parseInt(getActualPropertyMap().get("desiredHeight")); if(desired_width > 0 && desired_width <= maxSize.width && desired_height > 0 && desired_height <= maxSize.height){ Camera.Size previewSize = getOptimalPreviewSize(parameters.getSupportedPictureSizes(), desired_width, desired_height); Logger.T(TAG, "Selected size: " + previewSize.width + "x" + previewSize.height); parameters.setPreviewSize(previewSize.width, previewSize.height); } else if(desired_width > maxSize.width || desired_height > maxSize.height){ parameters.setPreviewSize(maxSize.width , maxSize.height); } else{ parameters.setPreviewSize(320, 240); } } else{ Camera.Size previewSize = getOptimalPreviewSize(parameters.getSupportedPictureSizes(), width, height); Logger.T(TAG, "Selected size: " + previewSize.width + "x" + previewSize.height); parameters.setPreviewSize(previewSize.width, previewSize.height); } camera.stopPreview(); try{ camera.setParameters(parameters); } catch(RuntimeException e){ e.printStackTrace(); } camera.startPreview(); return new CameraSize(camera.getParameters().getPreviewSize()); } private Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes, int w, int h) { final double ASPECT_TOLERANCE = 0.2; final double SCALE_TOLERANCE = 0.2; double targetRatio = (double) w / h; if (sizes == null) return null; Camera.Size optimalSize = null; double minDiff = Double.MAX_VALUE; int targetHeight = h; // Try to find an size match aspect ratio and size for (Camera.Size size : sizes) { Logger.T(TAG, "Size: " + size.width + "x" + size.height); double scale = (double) size.width / w; double ratio = (double) size.width / size.height; Logger.T(TAG, "Target ratio: " + targetRatio + ", ratio: " + ratio + ", scale: " + scale); if (size.width > w || size.height > h) continue; if (Math.abs(1 - scale) > SCALE_TOLERANCE) continue; if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue; Logger.T(TAG, "Try size: " + size.width + "x" + size.height); if (Math.abs(size.height - targetHeight) < minDiff) { optimalSize = size; minDiff = Math.abs(size.height - targetHeight); } } // Cannot find the one match the aspect ratio, ignore the requirement if (optimalSize == null) { Logger.T(TAG, "There is no match for preview size!"); minDiff = Double.MAX_VALUE; for (Camera.Size size : sizes) { if (size.width > w || size.height > h) continue; Logger.T(TAG, "Try size: " + size.width + "x" + size.height); if (Math.abs(size.height - targetHeight) < minDiff) { optimalSize = size; minDiff = Math.abs(size.height - targetHeight); } } } if(optimalSize == null) return getCamera().getParameters().getPictureSize(); return optimalSize; } @Override public void setCompressionFormat(String compressionFormat, IMethodResult result) { if (!compressionFormat.equalsIgnoreCase("jpg")) { Logger.E(TAG, "Android does not support the compression format: " + compressionFormat); result.setError("Android does not support the compression format: " + compressionFormat); } } @Override public void getPreviewLeft(IMethodResult result) { //WM only } @Override public void setPreviewLeft(int previewLeft, IMethodResult result) { //WM only } @Override public void getPreviewTop(IMethodResult result) { //WM only } @Override public void setPreviewTop(int previewTop, IMethodResult result) { //WM only } @Override public void takePicture(Map<String, String> propertyMap, IMethodResult result) { Logger.T(TAG, "takePicture"); CameraActivity.click_rotation = false; try { Map<String, String> actualPropertyMap = new HashMap<String, String>(); actualPropertyMap.putAll(getPropertiesMap()); actualPropertyMap.putAll(propertyMap); setActualPropertyMap(actualPropertyMap); String outputFormat = actualPropertyMap.get("outputFormat"); String filePath = null; if(!actualPropertyMap.containsKey("fileName")){ filePath = "/sdcard/DCIM/Camera/IMG_"+ dateFormat.format(new Date(System.currentTimeMillis())) + ".jpg"; } else{ filePath = actualPropertyMap.get("fileName"); } if (outputFormat.equalsIgnoreCase("image")) { filePath = actualPropertyMap.get("fileName") + ".jpg"; Logger.T(TAG, "outputFormat: " + outputFormat + ", path: " + filePath); } else if (outputFormat.equalsIgnoreCase("dataUri")) { Logger.T(TAG, "outputFormat: " + outputFormat); } else { throw new RuntimeException("Unknown 'outputFormat' value: " + outputFormat); } Intent intent = null; if (Boolean.parseBoolean(actualPropertyMap.get("useSystemViewfinder"))) { if (outputFormat.equalsIgnoreCase("image")) { values = new ContentValues(); fileUri = RhodesActivity.getContext().getContentResolver().insert( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); actualPropertyMap.put("captureUri", fileUri.toString()); propertyMap.put("dataURI", ""); // intent is null with MediaStore.EXTRA_OUTPUT so adding fileuri to map and get it with same key // if instead of MediaStore.EXTRA_OUTPUT any other key is used then the bitmap is null though the file is getting created intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); } else if (outputFormat.equalsIgnoreCase("dataUri")) { } } else { intent = new Intent(ContextFactory.getUiContext(), CameraActivity.class); intent.putExtra(CameraExtension.INTENT_EXTRA_PREFIX + "CAMERA_ID", getId()); } ((CameraFactory)CameraFactorySingleton.getInstance()).getRhoListener().setMethodResult(result); ((CameraFactory)CameraFactorySingleton.getInstance()).getRhoListener().setActualPropertyMap(actualPropertyMap); RhodesActivity.safeGetInstance().startActivityForResult(intent, RhoExtManager.getInstance().getActivityResultNextRequestCode(CameraRhoListener.getInstance())); } catch (RuntimeException e) { Logger.E(TAG, e); result.setError(e.getMessage()); } } protected String getTemporaryPath(String targetPath) { if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { File externalRoot = Environment.getExternalStorageDirectory(); if (! externalRoot.exists()){ if (! externalRoot.mkdirs()){ Logger.E(TAG, "Failed to create directory: " + externalRoot); return null; } } String filename = new File(targetPath).getName(); return new File(externalRoot, filename).getAbsolutePath(); } else { return null; } } @Override public void getSupportedSizeList(IMethodResult result) { } @SuppressLint("NewApi") @Override public void doTakePicture(Activity previewActivity, int rotation) { Logger.T(TAG, "doTakePicture: rotation: " + rotation); openCamera(); Camera.Parameters params = getCamera().getParameters(); params.setRotation((90 + rotation) % 360); getCamera().setParameters(params); getCamera().takePicture(null, null, new TakePictureCallback(previewActivity)); closeCamera(); } public void finalize() { if (getCamera() != null) { getCamera().release(); } } @Override public void showPreview(Map<String, String> propertyMap, IMethodResult result) { // TODO Auto-generated method stub } @Override public void hidePreview(IMethodResult result) { // TODO Auto-generated method stub } @Override public void capture(IMethodResult result) { // TODO Auto-generated method stub } @Override public void setDisplayOrientation(int rotate) { Camera camera = getCamera(); camera.setDisplayOrientation(rotate); } }
/** * This file is automatically generated by wheat-build. * Do not modify this file -- YOUR CHANGES WILL BE ERASED! */ package x7c1.linen.res.layout; import android.content.Context; import android.view.LayoutInflater; import android.view.ViewGroup; import android.view.View; import x7c1.wheat.ancient.resource.ViewHolderProvider; import x7c1.wheat.ancient.resource.ViewHolderProviderFactory; import x7c1.linen.R; import x7c1.linen.glue.res.layout.SourceSearchRowFooter; public class SourceSearchRowFooterProvider implements ViewHolderProvider<SourceSearchRowFooter> { private final LayoutInflater inflater; public SourceSearchRowFooterProvider(Context context){ this.inflater = LayoutInflater.from(context); } public SourceSearchRowFooterProvider(LayoutInflater inflater){ this.inflater = inflater; } @Override public int layoutId(){ return R.layout.source_search_row__footer; } @Override public SourceSearchRowFooter inflateOn(ViewGroup parent){ return inflate(parent, false); } @Override public SourceSearchRowFooter inflate(ViewGroup parent, boolean attachToRoot){ View view = inflater.inflate(R.layout.source_search_row__footer, parent, attachToRoot); return factory().createViewHolder(view); } @Override public SourceSearchRowFooter inflate(){ return inflate(null, false); } public static ViewHolderProviderFactory<SourceSearchRowFooter> factory(){ return new ViewHolderProviderFactory<SourceSearchRowFooter>() { @Override public ViewHolderProvider<SourceSearchRowFooter> create(LayoutInflater inflater){ return new SourceSearchRowFooterProvider(inflater); } @Override public ViewHolderProvider<SourceSearchRowFooter> create(Context context){ return new SourceSearchRowFooterProvider(context); } @Override public SourceSearchRowFooter createViewHolder(View view){ return new SourceSearchRowFooter( view ); } }; } }
package liquibase.sqlgenerator.core; import liquibase.database.Database; import liquibase.database.core.*; import liquibase.exception.ValidationErrors; import liquibase.sql.Sql; import liquibase.sql.UnparsedSql; import liquibase.sqlgenerator.SqlGenerator; import liquibase.sqlgenerator.SqlGeneratorChain; import liquibase.statement.core.AlterSequenceStatement; import liquibase.structure.core.Sequence; public class AlterSequenceGenerator extends AbstractSqlGenerator<AlterSequenceStatement> { @Override public boolean supports(AlterSequenceStatement statement, Database database) { return database.supportsSequences(); } @Override public ValidationErrors validate(AlterSequenceStatement alterSequenceStatement, Database database, SqlGeneratorChain sqlGeneratorChain) { ValidationErrors validationErrors = new ValidationErrors(); validationErrors.checkDisallowedField("incrementBy", alterSequenceStatement.getIncrementBy(), database, HsqlDatabase.class, H2Database.class); validationErrors.checkDisallowedField("maxValue", alterSequenceStatement.getMaxValue(), database, HsqlDatabase.class, H2Database.class); validationErrors.checkDisallowedField("minValue", alterSequenceStatement.getMinValue(), database, H2Database.class); validationErrors.checkDisallowedField("ordered", alterSequenceStatement.getOrdered(), database, HsqlDatabase.class, DB2Database.class); validationErrors.checkRequiredField("sequenceName", alterSequenceStatement.getSequenceName()); return validationErrors; } @Override public Sql[] generateSql(AlterSequenceStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("ALTER SEQUENCE "); buffer.append(database.escapeSequenceName(statement.getCatalogName(), statement.getSchemaName(), statement.getSequenceName())); if (statement.getIncrementBy() != null) { buffer.append(" INCREMENT BY ").append(statement.getIncrementBy()); } if (statement.getMinValue() != null) { if (database instanceof FirebirdDatabase || database instanceof HsqlDatabase || database instanceof H2Database) { buffer.append(" RESTART WITH ").append(statement.getMinValue()); } else { buffer.append(" MINVALUE ").append(statement.getMinValue()); } } if (statement.getMaxValue() != null) { buffer.append(" MAXVALUE ").append(statement.getMaxValue()); } if (statement.getCacheSize() != null) { buffer.append(" CACHE ").append(statement.getCacheSize()); } if (statement.getOrdered() != null) { if (statement.getOrdered()) { buffer.append(" ORDER"); } } return new Sql[]{ new UnparsedSql(buffer.toString(), getAffectedSequence(statement)) }; } protected Sequence getAffectedSequence(AlterSequenceStatement statement) { return new Sequence().setName(statement.getSequenceName()).setSchema(statement.getCatalogName(), statement.getSchemaName()); } }
package com.altamiracorp.lumify.core.model.ontology; public enum LabelName { HAS_PROPERTY("hasProperty"), HAS_EDGE("hasEdge"), IS_A("isA"), ENTITY_HAS_IMAGE_RAW("entityHasImageRaw"), RAW_HAS_ENTITY("rawHasEntity"), RAW_CONTAINS_IMAGE_OF_ENTITY("rawContainsImageOfEntity"); private final String text; LabelName(String text) { this.text = text; } @Override public String toString() { return this.text; } }
package com.bloatit.framework.webserver.components.form; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; import com.bloatit.framework.webserver.components.HtmlGenericElement; import com.bloatit.framework.webserver.components.meta.HtmlBranch; /** * Class to create Html drop down ({@code<select>} tag) */ public class HtmlDropDown extends HtmlStringFormField { private final Map<String, HtmlGenericElement> elements = new HashMap<String, HtmlGenericElement>(); public HtmlDropDown(final String name) { super(InputBlock.create(new HtmlGenericElement("select")), name); } public HtmlDropDown(final String name, final String label) { super(InputBlock.create(new HtmlGenericElement("select")), name, label); } public void addDropDownElement(final String value, final String displayName) { final HtmlGenericElement opt = new HtmlGenericElement("option"); opt.addText(displayName); opt.addAttribute("value", value); ((HtmlBranch) inputBlock.getInputElement()).add(opt); elements.put(value, opt); } /** * Adds elements based on an enum * * @param <T> the type of the elements of the set * @param elements the enum set */ public <T extends Enum<T> & Displayable> void addDropDownElements(final EnumSet<T> elements) { for (final T enumValue : elements) { addDropDownElement(enumValue.name(), enumValue.getDisplayName()); } } /** * Sets the default value of the drop down menu * <p> * The default value is set based on the <i>value</i> field of the * {@link #addDropDownElement(String, String)} method (the code which is not * visible from the user). * </p> * * @param value the code of the default element */ @Override protected void doSetDefaultValue(final String value) { final HtmlGenericElement checkedElement = elements.get(value); if (checkedElement != null) { checkedElement.addAttribute("selected", "selected"); } } }
package org.mifosplatform.portfolio.client.domain; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; import javax.persistence.UniqueConstraint; import org.apache.commons.lang.StringUtils; import org.hibernate.annotations.LazyCollection; import org.hibernate.annotations.LazyCollectionOption; import org.joda.time.LocalDate; import org.joda.time.format.DateTimeFormatter; import org.mifosplatform.infrastructure.codes.domain.CodeValue; import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.data.ApiParameterError; import org.mifosplatform.infrastructure.core.data.DataValidatorBuilder; import org.mifosplatform.infrastructure.core.exception.PlatformApiDataValidationException; import org.mifosplatform.infrastructure.core.service.DateUtils; import org.mifosplatform.infrastructure.documentmanagement.domain.Image; import org.mifosplatform.infrastructure.security.service.RandomPasswordGenerator; import org.mifosplatform.organisation.office.domain.Office; import org.mifosplatform.organisation.staff.domain.Staff; import org.mifosplatform.portfolio.client.api.ClientApiConstants; import org.mifosplatform.portfolio.group.domain.Group; import org.springframework.data.jpa.domain.AbstractPersistable; @Entity @Table(name = "m_client", uniqueConstraints = { @UniqueConstraint(columnNames = { "account_no" }, name = "account_no_UNIQUE"), @UniqueConstraint(columnNames = { "mobile_no" }, name = "mobile_no_UNIQUE") }) public final class Client extends AbstractPersistable<Long> { @Column(name = "account_no", length = 20, unique = true, nullable = false) private String accountNumber; @ManyToOne @JoinColumn(name = "office_id", nullable = false) private Office office; @ManyToOne @JoinColumn(name = "transfer_to_office_id", nullable = true) private Office transferToOffice; @OneToOne(optional = true) @JoinColumn(name = "image_id", nullable = true) private Image image; /** * A value from {@link ClientStatus}. */ @Column(name = "status_enum", nullable = false) private Integer status; @Column(name = "activation_date", nullable = true) @Temporal(TemporalType.DATE) private Date activationDate; @Column(name = "office_joining_date", nullable = true) @Temporal(TemporalType.DATE) private Date officeJoiningDate; @Column(name = "firstname", length = 50) private String firstname; @Column(name = "middlename", length = 50) private String middlename; @Column(name = "lastname", length = 50) private String lastname; @Column(name = "fullname", length = 100) private String fullname; @Column(name = "display_name", length = 100, nullable = false) private String displayName; @Column(name = "mobile_no", length = 50, nullable = false, unique = true) private String mobileNo; @Column(name = "external_id", length = 100, nullable = true, unique = true) private String externalId; @ManyToOne @JoinColumn(name = "staff_id") private Staff staff; @LazyCollection(LazyCollectionOption.FALSE) @ManyToMany @JoinTable(name = "m_group_client", joinColumns = @JoinColumn(name = "client_id"), inverseJoinColumns = @JoinColumn(name = "group_id")) private Set<Group> groups; @Transient private boolean accountNumberRequiresAutoGeneration = false; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "closure_reason_cv_id", nullable = true) private CodeValue closureReason; @Column(name = "closedon_date", nullable = true) @Temporal(TemporalType.DATE) private Date closureDate; public static Client createNew(final Office clientOffice, final Group clientParentGroup, final Staff staff, final JsonCommand command) { final String accountNo = command.stringValueOfParameterNamed(ClientApiConstants.accountNoParamName); final String externalId = command.stringValueOfParameterNamed(ClientApiConstants.externalIdParamName); final String mobileNo = command.stringValueOfParameterNamed(ClientApiConstants.mobileNoParamName); final String firstname = command.stringValueOfParameterNamed(ClientApiConstants.firstnameParamName); final String middlename = command.stringValueOfParameterNamed(ClientApiConstants.middlenameParamName); final String lastname = command.stringValueOfParameterNamed(ClientApiConstants.lastnameParamName); final String fullname = command.stringValueOfParameterNamed(ClientApiConstants.fullnameParamName); ClientStatus status = ClientStatus.PENDING; boolean active = false; if (command.hasParameter("active")) { active = command.booleanPrimitiveValueOfParameterNamed(ClientApiConstants.activeParamName); } LocalDate activationDate = null; LocalDate officeJoiningDate = null; if (active) { status = ClientStatus.ACTIVE; activationDate = command.localDateValueOfParameterNamed(ClientApiConstants.activationDateParamName); officeJoiningDate = activationDate; if (activationDate.isAfter(DateUtils.getLocalDateOfTenant())) { final String defaultUserMessage = "Activation date cannot be in the future."; final ApiParameterError error = ApiParameterError.parameterError("error.msg.clients.activationDate.in.the.future", defaultUserMessage, ClientApiConstants.activationDateParamName, activationDate); final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>(); dataValidationErrors.add(error); throw new PlatformApiDataValidationException(dataValidationErrors); } } return new Client(status, clientOffice, clientParentGroup, accountNo, firstname, middlename, lastname, fullname, activationDate, officeJoiningDate, externalId, mobileNo, staff); } protected Client() { } private Client(final ClientStatus status, final Office office, final Group clientParentGroup, final String accountNo, final String firstname, final String middlename, final String lastname, final String fullname, final LocalDate activationDate, final LocalDate officeJoiningDate, final String externalId, final String mobileNo, final Staff staff) { if (StringUtils.isBlank(accountNo)) { this.accountNumber = new RandomPasswordGenerator(19).generate(); this.accountNumberRequiresAutoGeneration = true; } else { this.accountNumber = accountNo; } this.status = status.getValue(); this.office = office; if (StringUtils.isNotBlank(externalId)) { this.externalId = externalId.trim(); } else { this.externalId = null; } if (StringUtils.isNotBlank(mobileNo)) { this.mobileNo = mobileNo.trim(); } else { this.mobileNo = null; } if (activationDate != null) { this.activationDate = activationDate.toDateMidnight().toDate(); } if (officeJoiningDate != null) { this.officeJoiningDate = officeJoiningDate.toDateMidnight().toDate(); } if (StringUtils.isNotBlank(firstname)) { this.firstname = firstname.trim(); } else { this.firstname = null; } if (StringUtils.isNotBlank(middlename)) { this.middlename = middlename.trim(); } else { this.middlename = null; } if (StringUtils.isNotBlank(lastname)) { this.lastname = lastname.trim(); } else { this.lastname = null; } if (StringUtils.isNotBlank(fullname)) { this.fullname = fullname.trim(); } else { this.fullname = null; } if (clientParentGroup != null) { this.groups = new HashSet<Group>(); this.groups.add(clientParentGroup); } this.staff = staff; deriveDisplayName(); validate(); } private void validate() { final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>(); validateNameParts(dataValidationErrors); validateActivationDate(dataValidationErrors); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } public boolean isAccountNumberRequiresAutoGeneration() { return this.accountNumberRequiresAutoGeneration; } public void setAccountNumberRequiresAutoGeneration(final boolean accountNumberRequiresAutoGeneration) { this.accountNumberRequiresAutoGeneration = accountNumberRequiresAutoGeneration; } public boolean identifiedBy(final String identifier) { return identifier.equalsIgnoreCase(this.externalId); } public boolean identifiedBy(final Long clientId) { return getId().equals(clientId); } public void updateAccountNo(final String accountIdentifier) { this.accountNumber = accountIdentifier; this.accountNumberRequiresAutoGeneration = false; } public void activate(final DateTimeFormatter formatter, final LocalDate activationLocalDate) { if (isActive()) { final String defaultUserMessage = "Cannot activate client. Client is already active."; final ApiParameterError error = ApiParameterError.parameterError("error.msg.clients.already.active", defaultUserMessage, ClientApiConstants.activationDateParamName, activationLocalDate.toString(formatter)); final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>(); dataValidationErrors.add(error); throw new PlatformApiDataValidationException(dataValidationErrors); } if (isDateInTheFuture(activationLocalDate)) { final String defaultUserMessage = "Activation date cannot be in the future."; final ApiParameterError error = ApiParameterError.parameterError("error.msg.clients.activationDate.in.the.future", defaultUserMessage, ClientApiConstants.activationDateParamName, activationLocalDate); final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>(); dataValidationErrors.add(error); throw new PlatformApiDataValidationException(dataValidationErrors); } this.activationDate = activationLocalDate.toDate(); this.officeJoiningDate = this.activationDate; this.status = ClientStatus.ACTIVE.getValue(); validate(); } public boolean isNotActive() { return !isActive(); } public boolean isActive() { return ClientStatus.fromInt(this.status).isActive(); } public boolean isClosed() { return ClientStatus.fromInt(this.status).isClosed(); } public boolean isTransferInProgress() { return ClientStatus.fromInt(this.status).isTransferInProgress(); } public boolean isTransferOnHold() { return ClientStatus.fromInt(this.status).isTransferOnHold(); } public boolean isTransferInProgressOrOnHold() { return isTransferInProgress() || isTransferOnHold(); } public boolean isNotPending() { return !isPending(); } public boolean isPending() { return ClientStatus.fromInt(this.status).isPending(); } private boolean isDateInTheFuture(final LocalDate localDate) { return localDate.isAfter(DateUtils.getLocalDateOfTenant()); } public Map<String, Object> update(final JsonCommand command) { final Map<String, Object> actualChanges = new LinkedHashMap<String, Object>(9); if (command.isChangeInIntegerParameterNamed(ClientApiConstants.statusParamName, this.status)) { final Integer newValue = command.integerValueOfParameterNamed(ClientApiConstants.statusParamName); actualChanges.put(ClientApiConstants.statusParamName, ClientEnumerations.status(newValue)); this.status = ClientStatus.fromInt(newValue).getValue(); } if (command.isChangeInStringParameterNamed(ClientApiConstants.accountNoParamName, this.accountNumber)) { final String newValue = command.stringValueOfParameterNamed(ClientApiConstants.accountNoParamName); actualChanges.put(ClientApiConstants.accountNoParamName, newValue); this.accountNumber = StringUtils.defaultIfEmpty(newValue, null); } if (command.isChangeInStringParameterNamed(ClientApiConstants.externalIdParamName, this.externalId)) { final String newValue = command.stringValueOfParameterNamed(ClientApiConstants.externalIdParamName); actualChanges.put(ClientApiConstants.externalIdParamName, newValue); this.externalId = StringUtils.defaultIfEmpty(newValue, null); } if (command.isChangeInStringParameterNamed(ClientApiConstants.mobileNoParamName, this.mobileNo)) { final String newValue = command.stringValueOfParameterNamed(ClientApiConstants.mobileNoParamName); actualChanges.put(ClientApiConstants.mobileNoParamName, newValue); this.mobileNo = StringUtils.defaultIfEmpty(newValue, null); } if (command.isChangeInStringParameterNamed(ClientApiConstants.firstnameParamName, this.firstname)) { final String newValue = command.stringValueOfParameterNamed(ClientApiConstants.firstnameParamName); actualChanges.put(ClientApiConstants.firstnameParamName, newValue); this.firstname = StringUtils.defaultIfEmpty(newValue, null); } if (command.isChangeInStringParameterNamed(ClientApiConstants.middlenameParamName, this.middlename)) { final String newValue = command.stringValueOfParameterNamed(ClientApiConstants.middlenameParamName); actualChanges.put(ClientApiConstants.middlenameParamName, newValue); this.middlename = StringUtils.defaultIfEmpty(newValue, null); } if (command.isChangeInStringParameterNamed(ClientApiConstants.lastnameParamName, this.lastname)) { final String newValue = command.stringValueOfParameterNamed(ClientApiConstants.lastnameParamName); actualChanges.put(ClientApiConstants.lastnameParamName, newValue); this.lastname = StringUtils.defaultIfEmpty(newValue, null); } if (command.isChangeInStringParameterNamed(ClientApiConstants.fullnameParamName, this.fullname)) { final String newValue = command.stringValueOfParameterNamed(ClientApiConstants.fullnameParamName); actualChanges.put(ClientApiConstants.fullnameParamName, newValue); this.fullname = newValue; } if (command.isChangeInLongParameterNamed(ClientApiConstants.staffIdParamName, staffId())) { final Long newValue = command.longValueOfParameterNamed(ClientApiConstants.staffIdParamName); actualChanges.put(ClientApiConstants.staffIdParamName, newValue); } final String dateFormatAsInput = command.dateFormat(); final String localeAsInput = command.locale(); if (command.isChangeInLocalDateParameterNamed(ClientApiConstants.activationDateParamName, getActivationLocalDate())) { final String valueAsInput = command.stringValueOfParameterNamed(ClientApiConstants.activationDateParamName); actualChanges.put(ClientApiConstants.activationDateParamName, valueAsInput); actualChanges.put(ClientApiConstants.dateFormatParamName, dateFormatAsInput); actualChanges.put(ClientApiConstants.localeParamName, localeAsInput); final LocalDate newValue = command.localDateValueOfParameterNamed(ClientApiConstants.activationDateParamName); this.activationDate = newValue.toDate(); this.officeJoiningDate = this.activationDate; } validate(); deriveDisplayName(); return actualChanges; } private void validateNameParts(final List<ApiParameterError> dataValidationErrors) { final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("client"); if (StringUtils.isNotBlank(this.fullname)) { baseDataValidator.reset().parameter(ClientApiConstants.firstnameParamName).value(this.firstname) .mustBeBlankWhenParameterProvided(ClientApiConstants.fullnameParamName, this.fullname); baseDataValidator.reset().parameter(ClientApiConstants.middlenameParamName).value(this.middlename) .mustBeBlankWhenParameterProvided(ClientApiConstants.fullnameParamName, this.fullname); baseDataValidator.reset().parameter(ClientApiConstants.lastnameParamName).value(this.lastname) .mustBeBlankWhenParameterProvided(ClientApiConstants.fullnameParamName, this.fullname); } else { baseDataValidator.reset().parameter(ClientApiConstants.firstnameParamName).value(this.firstname).notBlank() .notExceedingLengthOf(50); baseDataValidator.reset().parameter(ClientApiConstants.middlenameParamName).value(this.middlename).ignoreIfNull() .notExceedingLengthOf(50); baseDataValidator.reset().parameter(ClientApiConstants.lastnameParamName).value(this.lastname).notBlank() .notExceedingLengthOf(50); } } private void validateActivationDate(final List<ApiParameterError> dataValidationErrors) { if (this.activationDate != null) { if (this.office.isOpeningDateAfter(getActivationLocalDate())) { final String defaultUserMessage = "Client activation date cannot be a date before the office opening date."; final ApiParameterError error = ApiParameterError.parameterError( "error.msg.clients.activationDate.cannot.be.before.office.activation.date", defaultUserMessage, ClientApiConstants.activationDateParamName, getActivationLocalDate()); dataValidationErrors.add(error); } } } private void deriveDisplayName() { StringBuilder nameBuilder = new StringBuilder(); if (StringUtils.isNotBlank(this.firstname)) { nameBuilder.append(this.firstname).append(' '); } if (StringUtils.isNotBlank(this.middlename)) { nameBuilder.append(this.middlename).append(' '); } if (StringUtils.isNotBlank(this.lastname)) { nameBuilder.append(this.lastname); } if (StringUtils.isNotBlank(this.fullname)) { nameBuilder = new StringBuilder(this.fullname); } this.displayName = nameBuilder.toString(); } public LocalDate getActivationLocalDate() { LocalDate activationLocalDate = null; if (this.activationDate != null) { activationLocalDate = LocalDate.fromDateFields(this.activationDate); } return activationLocalDate; } public LocalDate getOfficeJoiningLocalDate() { LocalDate officeJoiningLocalDate = null; if (this.officeJoiningDate != null) { officeJoiningLocalDate = LocalDate.fromDateFields(this.officeJoiningDate); } return officeJoiningLocalDate; } public boolean isOfficeIdentifiedBy(final Long officeId) { return this.office.identifiedBy(officeId); } public Long officeId() { return this.office.getId(); } public void setImage(final Image image) { this.image = image; } public Image getImage() { return this.image; } public String mobileNo() { return this.mobileNo; } public void setMobileNo(final String mobileNo) { this.mobileNo = mobileNo; } public String getDisplayName() { return this.displayName; } public void setDisplayName(final String displayName) { this.displayName = displayName; } public Office getOffice() { return this.office; } public Office getTransferToOffice() { return this.transferToOffice; } public void updateOffice(final Office office) { this.office = office; } public void updateTransferToOffice(final Office office) { this.transferToOffice = office; } public void updateOfficeJoiningDate(final Date date) { this.officeJoiningDate = date; } private Long staffId() { Long staffId = null; if (this.staff != null) { staffId = this.staff.getId(); } return staffId; } public void updateStaff(final Staff staff) { this.staff = staff; } public Staff getStaff() { return this.staff; } public void unassignStaff() { this.staff = null; } public void assignStaff(final Staff staff) { this.staff = staff; } public Set<Group> getGroups() { return this.groups; } public void close(final CodeValue closureReason, final Date closureDate) { this.closureReason = closureReason; this.closureDate = closureDate; this.status = ClientStatus.CLOSED.getValue(); } public Integer getStatus() { return this.status; } public void setStatus(final Integer status) { this.status = status; } public boolean isActivatedAfter(final LocalDate submittedOn) { return getActivationLocalDate().isAfter(submittedOn); } public boolean isChildOfGroup(final Long groupId) { if (groupId != null && this.groups != null && !this.groups.isEmpty()) { for (final Group group : this.groups) { if (group.getId().equals(groupId)) { return true; } } } return false; } }
package net.anotheria.moskito.aop.aspect; import net.anotheria.moskito.aop.aspect.specialtreater.HttpFilterHandler; import net.anotheria.moskito.aop.aspect.specialtreater.SpecialCaseHandler; import net.anotheria.moskito.core.calltrace.CurrentlyTracedCall; import net.anotheria.moskito.core.calltrace.RunningTraceContainer; import net.anotheria.moskito.core.calltrace.TraceStep; import net.anotheria.moskito.core.calltrace.TracedCall; import net.anotheria.moskito.core.calltrace.TracingUtil; import net.anotheria.moskito.core.config.MoskitoConfiguration; import net.anotheria.moskito.core.config.MoskitoConfigurationHolder; import net.anotheria.moskito.core.context.CurrentMeasurement; import net.anotheria.moskito.core.context.MoSKitoContext; import net.anotheria.moskito.core.dynamic.OnDemandStatsProducer; import net.anotheria.moskito.core.journey.Journey; import net.anotheria.moskito.core.journey.JourneyManagerFactory; import net.anotheria.moskito.core.predefined.ServiceStats; import net.anotheria.moskito.core.predefined.ServiceStatsFactory; import net.anotheria.moskito.core.tracer.Trace; import net.anotheria.moskito.core.tracer.TracerRepository; import net.anotheria.moskito.core.tracer.Tracers; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.reflect.MethodSignature; import java.lang.reflect.InvocationTargetException; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * @author Roman Stetsiuk. */ public class MonitoringBaseAspect extends AbstractMoskitoAspect<ServiceStats>{ /** * Factory constant is needed to prevent continuous reinstantiation of ServiceStatsFactory objects. */ protected static final ServiceStatsFactory FACTORY = new ServiceStatsFactory(); /** * Remember previous producer to avoid time cumulation of recursive calls. * TODO: maybe we can remove this and rely on the one in the context now. */ protected static final ThreadLocal<String> lastProducerId = new ThreadLocal<>(); /** * Global configuration. */ protected MoskitoConfiguration moskitoConfiguration = MoskitoConfigurationHolder.getConfiguration(); protected Object doProfiling(ProceedingJoinPoint pjp, String aProducerId, String aSubsystem, String aCategory) throws Throwable { //check if kill switch is active, return if so. if (moskitoConfiguration.getKillSwitch().disableMetricCollection()) return pjp.proceed(); //check if this a synthetic method like a switch or lambda method. if (((MethodSignature)pjp.getSignature()).getMethod().isSynthetic()) return pjp.proceed(); MoSKitoContext moSKitoContext = MoSKitoContext.get(); OnDemandStatsProducer<ServiceStats> producer = getProducer(pjp, aProducerId, aCategory, aSubsystem, false, FACTORY, true); String producerId = producer.getProducerId(); String prevProducerId = lastProducerId.get(); lastProducerId.set(producerId); //in most cases this is the same as lastProducerId. However lastProducerId is restored after the call //and previousProducerName is not. //we are using previous producer name for source monitoring. String previousProducerName = null; if (moSKitoContext.getLastProducer()!=null){ previousProducerName = moSKitoContext.getLastProducer().getProducerId(); } boolean sourceMonitoringActive = !producerId.equals(previousProducerName) && producer.sourceMonitoringEnabled(); OnDemandStatsProducer<ServiceStats> sourceMonitoringProducer = null; if (sourceMonitoringActive){ sourceMonitoringProducer = getSourceMonitoringProducer(producerId, previousProducerName, aCategory, aSubsystem, FACTORY, pjp.getSignature().getDeclaringType()); } //calculate cumulated stats (default stats). //we only do this if previous producer wasn't same as current -> meaning if we call a second method in the same producer we don't count it as new call. boolean calculateCumulatedStats = !producerId.equals(prevProducerId); //check if we are the first producer CurrentMeasurement cm = moSKitoContext.notifyProducerEntry(producer); String methodName = getMethodStatName(pjp.getSignature()); ServiceStats defaultStats = producer.getDefaultStats(); ServiceStats methodStats = producer.getStats(methodName); //source monitoring ServiceStats smDefaultStats = null, smMethodStats = null; if (sourceMonitoringActive){ smDefaultStats = sourceMonitoringProducer.getDefaultStats(); smMethodStats = sourceMonitoringProducer.getStats(methodName); } final Object[] args = pjp.getArgs(); if (calculateCumulatedStats) { defaultStats.addRequest(); if (sourceMonitoringActive) smDefaultStats.addRequest(); } if (methodStats != null) { methodStats.addRequest(); if (sourceMonitoringActive) smMethodStats.addRequest(); } TracedCall aRunningTrace = RunningTraceContainer.getCurrentlyTracedCall(); TraceStep currentStep = null; CurrentlyTracedCall currentTrace = aRunningTrace.callTraced() ? (CurrentlyTracedCall) aRunningTrace : null; boolean isLoggingEnabled = producer.isLoggingEnabled(); TracerRepository tracerRepository = TracerRepository.getInstance(); //only trace this producer if no tracers have been fired yet. boolean tracePassingOfThisProducer = !moSKitoContext.hasTracerFired() && tracerRepository.isTracingEnabledForProducer(producerId); Trace trace = null; boolean journeyStartedByMe = false; //we create trace here already, because we want to reserve a new trace id. if (tracePassingOfThisProducer){ trace = new Trace(); moSKitoContext.setTracerFired(); } if (currentTrace == null && tracePassingOfThisProducer){ //ok, we will create a new journey on the fly. String journeyCallName = Tracers.getCallName(trace); RunningTraceContainer.startTracedCall(journeyCallName); journeyStartedByMe = true; currentTrace = (CurrentlyTracedCall) RunningTraceContainer.getCurrentlyTracedCall(); } StringBuilder call = null; if (currentTrace != null || tracePassingOfThisProducer || isLoggingEnabled || cm.isFirst()) { if (isSpecial(methodName)){ call = getSpecialTreatmentForCall(methodName, pjp.getTarget(), args); } if (call==null) call = TracingUtil.buildCall(producerId, methodName, args, tracePassingOfThisProducer ? Tracers.getCallName(trace) : null); } if (currentTrace != null) { currentStep = currentTrace.startStep(call.toString(), producer, methodName); } if (cm.isFirst()){ cm.setCallDescription(call.toString()); } long startTime = System.nanoTime(); Object ret = null; try { ret = pjp.proceed(); return ret; } catch (InvocationTargetException e) { if (calculateCumulatedStats) { defaultStats.notifyError(e.getTargetException()); if (sourceMonitoringActive) smDefaultStats.notifyError(); } if (methodStats != null) { methodStats.notifyError(); if (sourceMonitoringActive) smMethodStats.notifyError(); } if (currentStep != null) { currentStep.setAborted(); } throw e.getCause(); } catch (Throwable t) { if (calculateCumulatedStats) { defaultStats.notifyError(t); if (sourceMonitoringActive) smDefaultStats.notifyError(); } if (methodStats != null) { methodStats.notifyError(); if (sourceMonitoringActive) smMethodStats.notifyError(); } if (currentStep != null) { currentStep.setAborted(); } if (tracePassingOfThisProducer) { call.append(" ERR ").append(t.getMessage()); } throw t; } finally { long exTime = System.nanoTime() - startTime; if (calculateCumulatedStats) { defaultStats.addExecutionTime(exTime); if (sourceMonitoringActive) smDefaultStats.addExecutionTime(exTime); } if (methodStats != null) { methodStats.addExecutionTime(exTime); if (sourceMonitoringActive) smMethodStats.addExecutionTime(exTime); } lastProducerId.set(prevProducerId); moSKitoContext.notifyProducerExit(producer); if (calculateCumulatedStats) { defaultStats.notifyRequestFinished(); if (sourceMonitoringActive) smDefaultStats.notifyRequestFinished(); } if (methodStats != null) { methodStats.notifyRequestFinished(); if (sourceMonitoringActive) smMethodStats.notifyRequestFinished(); } if (currentStep != null) { currentStep.setDuration(exTime); try { currentStep.appendToCall(" = " + TracingUtil.parameter2string(ret)); } catch (Throwable t) { currentStep.appendToCall(" = ERR: " + t.getMessage() + " (" + t.getClass() + ')'); } } if (currentTrace != null) { currentTrace.endStep(); } if (tracePassingOfThisProducer) { call.append(" = ").append(TracingUtil.parameter2string(ret)); trace.setCall(call.toString()); trace.setDuration(exTime); trace.setElements(Thread.currentThread().getStackTrace()); if (journeyStartedByMe) { //now finish the journey. Journey myJourney = JourneyManagerFactory.getJourneyManager().getOrCreateJourney(Tracers.getJourneyNameForTracers(producerId)); myJourney.addUseCase((CurrentlyTracedCall) RunningTraceContainer.endTrace()); RunningTraceContainer.cleanup(); } tracerRepository.addTracedExecution(producerId, trace); } //TODO added this temporarly to 2.9.2 -> will be developed further in 2.10.0 if (isLoggingEnabled){ call.append(" = ").append(TracingUtil.parameter2string(ret)); System.out.println(call.toString()); } if (cm.isFirst()){ cm.notifyProducerFinished(); } } } /** * Checks if the method is notified as special case, used to add additional info to known, often used methods, * which do not have publicly available arguments with toString methods, for example javax.servlet.Filter. * @param methodName * @return */ private boolean isSpecial(String methodName) { return specialCases.containsKey(methodName); } private StringBuilder getSpecialTreatmentForCall(String methodName, Object target, Object[] args){ StringBuilder ret = new StringBuilder(); SpecialCase sc = specialCases.get(methodName); if (sc==null) throw new IllegalStateException("Special case is not found even it must have been found before for method '"+methodName+"'"); Class clazz = null; try{ clazz = Class.forName(sc.className, false, getClass().getClassLoader()); }catch(ClassNotFoundException e){ e.printStackTrace(); return null; } if (clazz.isInstance(target)){ //special treatment for httpfilter. return sc.treater.getCallDescription(clazz, methodName, target, args); } return null; } /** * Map with special case definition. */ private static final ConcurrentMap<String, SpecialCase> specialCases = new ConcurrentHashMap<>(); static{ specialCases.put("doFilter", new SpecialCase("doFilter", "javax.servlet.Filter", new HttpFilterHandler())); } /** * Definition of a special case. We probably should cache the clazz at some point to reduce load, but since the clazz is only loaded if the * method name matches, we shouldn't be in much trouble for now. */ static class SpecialCase{ /** * Name of the method. i.e. doFilter in ServletFilter. */ private final String methodName; /** * Full name of the class to be matched after method name. */ private final String className; /** * The special handler for this type of call. */ private final SpecialCaseHandler treater; SpecialCase(String aMethodName, String aClassName, SpecialCaseHandler aTreater){ methodName = aMethodName; className = aClassName; treater = aTreater; } } }
package org.motechproject.model; import java.util.Collections; import java.util.HashMap; import java.util.Map; public final class MotechScheduledEvent { public static final String EVENT_TYPE_KEY_NAME = "eventType"; private String jobId; private String eventType; private HashMap<String, Object> parameters; public MotechScheduledEvent(String jobId, String eventType, HashMap<String, Object> parameters) { if (jobId == null) { throw new IllegalArgumentException("jobId can not be null"); } if (eventType == null) { throw new IllegalArgumentException("eventType can not be null"); } this.jobId = jobId; this.eventType = eventType; this.parameters = parameters; } public String getJobId() { return jobId; } public String getEventType() { return eventType; } public Map<String, Object> getParameters() { if (parameters == null ) { return Collections.emptyMap(); } return Collections.unmodifiableMap(parameters); } }
package com.gofish.sentiment.newscrawler; import io.vertx.core.Future; import io.vertx.core.eventbus.MessageConsumer; import io.vertx.core.json.JsonObject; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import io.vertx.rx.java.ObservableFuture; import io.vertx.rx.java.RxHelper; import io.vertx.rxjava.core.AbstractVerticle; import io.vertx.rxjava.servicediscovery.ServiceDiscovery; import io.vertx.rxjava.servicediscovery.types.EventBusService; import io.vertx.servicediscovery.Record; import io.vertx.serviceproxy.ProxyHelper; import java.util.Optional; /** * @author Luke Herron */ public class NewsCrawlerVerticle extends AbstractVerticle { private static final Logger LOG = LoggerFactory.getLogger(NewsCrawlerVerticle.class); private MessageConsumer<JsonObject> messageConsumer; private ServiceDiscovery serviceDiscovery; private Record record; @Override public void start(Future<Void> startFuture) throws Exception { LOG.info("Bringing up NewsCrawlerVerticle"); JsonObject config = Optional.ofNullable(config()) .orElseThrow(() -> new RuntimeException("Could not load crawler configuration")); com.gofish.sentiment.newscrawler.rxjava.NewsCrawlerService newsCrawlerService = com.gofish.sentiment.newscrawler.rxjava.NewsCrawlerService.create(vertx, config); messageConsumer = ProxyHelper.registerService(NewsCrawlerService.class, vertx.getDelegate(), newsCrawlerService.getDelegate(), NewsCrawlerService.ADDRESS); serviceDiscovery = ServiceDiscovery.create(vertx, serviceDiscovery -> { LOG.info("Service Discovery initialised"); record = EventBusService.createRecord(NewsCrawlerService.NAME, NewsCrawlerService.ADDRESS, NewsCrawlerService.class.getName()); serviceDiscovery.rxPublish(record) .subscribe(r -> startFuture.complete(), startFuture::fail); }); } @Override public void stop(Future<Void> stopFuture) throws Exception { ObservableFuture<Void> messageConsumerObservable = new ObservableFuture<>(); serviceDiscovery.rxUnpublish(record.getRegistration()) .flatMapObservable(v -> { messageConsumer.unregister(messageConsumerObservable.toHandler()); return messageConsumerObservable; }) .doOnNext(v -> serviceDiscovery.close()) .subscribe(RxHelper.toSubscriber(stopFuture)); } }
import java.util.Random; import java.util.Scanner; public class FriendlySoccerMatch implements FriendlyMatch { private String nameHomeTeam; private String nameGuestTeam; private int pointsHome; private int pointsGuest; public String[] commentArray = { " Catches the ball", " Deflects the ball with his fist", " Nods the ball away" }; public String[] arr = {"","",""}; Scanner user_input = new Scanner(System.in); boolean changePlayer = false; // Constructor public FriendlySoccerMatch(){ pointsHome = 0; pointsGuest = 0; } @Override public String getHomeTeam() { return nameHomeTeam; } @Override public String getGuestTeam() { return nameGuestTeam; } @Override public int getHomePoints() { return pointsHome; } @Override public int getGuestPoints() { return pointsGuest; } @Override public String getResultText() { return "The friendly game ends with \n\n"+nameHomeTeam+" - "+nameGuestTeam +" "+pointsHome+":"+pointsGuest+"."; } public void startGame(Team t1, Team t2){ nameHomeTeam = t1.getName(); nameGuestTeam = t2.getName(); pointsHome = 0; pointsGuest = 0; // now the game can begin; we have to create for the // 90 minutes + extra time the different actions Random r = new Random(); boolean gameruns = true; int gameduration = 90 + r.nextInt(5); int time = 1; int nextAction = 0; // while the game runs, goals can be scored while (gameruns){ nextAction = r.nextInt(15)+1; // Is the game over? if ((time + nextAction > gameduration) || (time > gameduration)){ gameruns = false; break; } if ((time + nextAction > 45) && !changePlayer){ changePlayer = true; String player_name; String player_motivation; String player_strength; String player_shots; String player_age; String playerChosen; String substituteChosen; // Random ran = new Random(); // int ranNum = ran.nextInt(10); // System.out.println(t1.getPlayers()[ranNum]); System.out.println(); System.out.println(" System.out.println("Change player for " + t1.getName()); System.out.println("select a player (1-10)"); playerChosen = user_input.next(); Player pOut = t1.getPlayers()[Integer.parseInt(playerChosen)]; System.out.println(pOut.getName()); System.out.println("Select a substitute player (1-3)"); substituteChosen = user_input.next(); Substitute sIn = t1.getSubstitute()[Integer.parseInt(substituteChosen)]; System.out.println(sIn.getName()); swapPlayers(t1, Integer.parseInt(playerChosen), Integer.parseInt(substituteChosen)); System.out.println(pOut.getName() + " has been changed with "+ sIn.getName()); System.out.println(t1.getPlayers()[Integer.parseInt(playerChosen)].getName()); System.out.println(); System.out.println(" // Player p3 = new Player(player_name, Integer.parseInt(player_age), Integer.parseInt(player_strength), Integer.parseInt(player_shots), Integer.parseInt(player_motivation)); System.out.println(" System.out.println(" System.out.println("Change player for team 2"); System.out.println("Enter player name: "); player_name = user_input.next(); System.out.println("Enter player motivation: "); player_motivation = user_input.next(); System.out.println("Enter player strength: "); player_strength = user_input.next(); System.out.println("Enter player age: "); player_age = user_input.next(); System.out.println("Enter player shots: "); player_shots = user_input.next(); System.out.println(); System.out.println(" // Player p4 = new Player(player_name, Integer.parseInt(player_age), Integer.parseInt(player_strength), Integer.parseInt(player_shots), Integer.parseInt(player_motivation)); System.out.println(" }
package org.gbif.occurrence.search; import org.gbif.api.model.checklistbank.NameUsageMatch; import org.gbif.api.model.checklistbank.NameUsageMatch.MatchType; import org.gbif.api.model.common.paging.Pageable; import org.gbif.api.model.common.search.SearchResponse; import org.gbif.api.model.occurrence.Occurrence; import org.gbif.api.model.occurrence.search.OccurrenceSearchParameter; import org.gbif.api.model.occurrence.search.OccurrenceSearchRequest; import org.gbif.api.service.checklistbank.NameUsageMatchingService; import org.gbif.api.service.occurrence.OccurrenceSearchService; import org.gbif.api.service.occurrence.OccurrenceService; import org.gbif.common.search.builder.SolrQueryUtils; import org.gbif.common.search.builder.SpellCheckResponseBuilder; import org.gbif.common.search.exception.SearchException; import org.gbif.common.search.util.QueryUtils; import org.gbif.occurrence.search.solr.OccurrenceSolrField; import java.io.IOException; import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.annotation.Nullable; import com.google.common.base.Objects; import com.google.common.collect.Lists; import com.google.inject.Inject; import com.google.inject.name.Named; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.client.solrj.response.TermsResponse; import org.apache.solr.client.solrj.response.TermsResponse.Term; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.gbif.api.model.common.search.SearchConstants.DEFAULT_SUGGEST_LIMIT; import static org.gbif.common.search.util.QueryUtils.buildTermQuery; import static org.gbif.common.search.util.SolrConstants.SOLR_REQUEST_HANDLER; import static org.gbif.occurrence.search.OccurrenceSearchRequestBuilder.QUERY_FIELD_MAPPING; /** * Occurrence search service. * Executes {@link OccurrenceSearchRequest} by transforming the request into {@link SolrQuery}. */ public class OccurrenceSearchImpl implements OccurrenceSearchService { /** * Default limit value for auto-suggest services. */ private static final Logger LOG = LoggerFactory.getLogger(OccurrenceSearchImpl.class); private static final Map<String, OccurrenceSearchParameter> FIELD_PARAMETER_MAPPING = new HashMap<String, OccurrenceSearchParameter>(QUERY_FIELD_MAPPING.size()); static { for (Map.Entry<OccurrenceSearchParameter, OccurrenceSolrField> paramField : QUERY_FIELD_MAPPING.entrySet()) { FIELD_PARAMETER_MAPPING.put(paramField.getValue().getFieldName(), paramField.getKey()); } } // Default order of results private static final Map<String, SolrQuery.ORDER> SORT_ORDER = new LinkedHashMap<String, SolrQuery.ORDER>(2); private final OccurrenceService occurrenceService; static { SORT_ORDER.put(OccurrenceSolrField.YEAR.getFieldName(), SolrQuery.ORDER.desc); SORT_ORDER.put(OccurrenceSolrField.MONTH.getFieldName(), SolrQuery.ORDER.asc); } private final SolrClient solrClient; private final OccurrenceSearchRequestBuilder occurrenceSearchRequestBuilder; private final NameUsageMatchingService nameUsageMatchingService; @Inject public OccurrenceSearchImpl(SolrClient solrClient, @Named(SOLR_REQUEST_HANDLER) String requestHandler, OccurrenceService occurrenceService, NameUsageMatchingService nameUsageMatchingService, @Named("max.offset") int maxOffset, @Named("max.limit") int maxLimit, @Named("facets.enable") boolean facetsEnable) { this.solrClient = solrClient; occurrenceSearchRequestBuilder = new OccurrenceSearchRequestBuilder(requestHandler, SORT_ORDER, maxOffset, maxLimit, facetsEnable); this.occurrenceService = occurrenceService; this.nameUsageMatchingService = nameUsageMatchingService; } /** * Builds a SearchResponse instance using the current builder state. * * @return a new instance of a SearchResponse. */ public SearchResponse<Occurrence, OccurrenceSearchParameter> buildResponse(QueryResponse queryResponse, Pageable request) { // Create response SearchResponse<Occurrence, OccurrenceSearchParameter> response = new SearchResponse<Occurrence, OccurrenceSearchParameter>(request); SolrDocumentList results = queryResponse.getResults(); // set total count response.setCount(results.getNumFound()); // Populates the results List<Occurrence> occurrences = Lists.newArrayListWithCapacity(results.size()); for (SolrDocument doc : results) { // Only field key is returned in the result Integer occKey = (Integer) doc.getFieldValue(OccurrenceSolrField.KEY.getFieldName()); Occurrence occ = occurrenceService.get(occKey); if (occ == null || occ.getKey() == null) { LOG.warn("Occurrence {} not found in store, but present in solr", occKey); } else { occurrences.add(occ); } } if (request.getLimit() > OccurrenceSearchRequestBuilder.MAX_PAGE_SIZE) { response.setLimit(OccurrenceSearchRequestBuilder.MAX_PAGE_SIZE); } if (queryResponse.getSpellCheckResponse() != null) { response.setSpellCheckResponse(SpellCheckResponseBuilder.build(queryResponse.getSpellCheckResponse())); } response.setResults(occurrences); if (occurrenceSearchRequestBuilder.isFacetsEnable()) { response.setFacets(SolrQueryUtils.getFacetsFromResponse(queryResponse, FIELD_PARAMETER_MAPPING)); } return response; } @Override public SearchResponse<Occurrence, OccurrenceSearchParameter> search(@Nullable OccurrenceSearchRequest request) { try { if (hasReplaceableScientificNames(request)) { SolrQuery solrQuery = occurrenceSearchRequestBuilder.build(request); QueryResponse queryResponse = solrClient.query(solrQuery); return buildResponse(queryResponse, request); } else { return new SearchResponse<Occurrence, OccurrenceSearchParameter>(request); } } catch (SolrServerException | IOException e) { LOG.error("Error executing the search operation", e); throw new SearchException(e); } } @Override public List<String> suggestCatalogNumbers(String prefix, @Nullable Integer limit) { return suggestTermByField(prefix, OccurrenceSearchParameter.CATALOG_NUMBER, limit); } @Override public List<String> suggestCollectionCodes(String prefix, @Nullable Integer limit) { return suggestTermByField(prefix, OccurrenceSearchParameter.COLLECTION_CODE, limit); } @Override public List<String> suggestRecordedBy(String prefix, @Nullable Integer limit) { return suggestTermByField(prefix, OccurrenceSearchParameter.RECORDED_BY, limit); } @Override public List<String> suggestInstitutionCodes(String prefix, @Nullable Integer limit) { return suggestTermByField(prefix, OccurrenceSearchParameter.INSTITUTION_CODE, limit); } @Override public List<String> suggestRecordNumbers(String prefix, @Nullable Integer limit) { return suggestTermByField(prefix, OccurrenceSearchParameter.RECORD_NUMBER, limit); } @Override public List<String> suggestOccurrenceIds(String prefix, @Nullable Integer limit) { return suggestTermByField(prefix, OccurrenceSearchParameter.OCCURRENCE_ID, limit); } /** * Searches a indexed terms of a field that matched against the prefix parameter. * * @param prefix search term * @param parameter mapped field to be searched * @param limit of maximum matches * @return a list of elements that matched against the prefix */ public List<String> suggestTermByField(String prefix, OccurrenceSearchParameter parameter, Integer limit) { try { String solrField = QUERY_FIELD_MAPPING.get(parameter).getFieldName(); SolrQuery solrQuery = buildTermQuery(QueryUtils.parseQueryValue(prefix), solrField, Objects.firstNonNull(limit, DEFAULT_SUGGEST_LIMIT)); QueryResponse queryResponse = solrClient.query(solrQuery); TermsResponse termsResponse = queryResponse.getTermsResponse(); List<Term> terms = termsResponse.getTerms(solrField); List<String> suggestions = Lists.newArrayListWithCapacity(terms.size()); for (Term term : terms) { suggestions.add(term.getTerm()); } return suggestions; } catch (SolrServerException | IOException e) { LOG.error("Error executing/building the request", e); throw new SearchException(e); } } /** * Tries to get the corresponding name usage keys from the scientific_name parameter values. * * @return true: if the request doesn't contain any scientific_name parameter or if any scientific name was found * false: if none scientific name was found */ private boolean hasReplaceableScientificNames(OccurrenceSearchRequest request) { boolean hasValidReplaces = true; if (request.getParameters().containsKey(OccurrenceSearchParameter.SCIENTIFIC_NAME)) { hasValidReplaces = false; Collection<String> values = request.getParameters().get(OccurrenceSearchParameter.SCIENTIFIC_NAME); for (String value : values) { NameUsageMatch nameUsageMatch = nameUsageMatchingService.match(value, null, null, true, false); if (nameUsageMatch.getMatchType() == MatchType.EXACT) { hasValidReplaces = true; values.remove(value); request.addParameter(OccurrenceSearchParameter.TAXON_KEY, nameUsageMatch.getUsageKey()); } } } return hasValidReplaces; } }
package org.openmrs.module.ohdsi.web; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.sql.*; import java.text.SimpleDateFormat; import java.util.*; import java.util.Date; public class DownloadInsertStatementsServlet extends HttpServlet { private Log log = LogFactory.getLog(this.getClass()); /** * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String s = new SimpleDateFormat("dMy_Hm").format(new Date()); response.setHeader("Content-Type", "text/sql;charset=UTF-8"); response.setHeader("Content-Disposition", "attachment; filename=ohdsiInserts" + s + ".sql"); //String headerLine = "Concept Id,Name,Description,Synonyms,Answers,Set Members,Class,Datatype,Changed By,Creator\n"; //response.getWriter().write(headerLine); // JDBC driver name and database URL String JDBC_DRIVER = "com.mysql.jdbc.Driver"; String DB_URL = "jdbc:mysql://localhost/openmrs"; // Database credentials final String USER = "root"; final String PASS = "root"; Connection conn = null; Statement stmt = null; Statement stmt2 = null; try{ //STEP 2: Register JDBC driver Class.forName("com.mysql.jdbc.Driver"); //STEP 3: Open a connection System.out.println("Connecting to a selected database..."); conn = DriverManager.getConnection(DB_URL, USER, PASS); System.out.println("Connected database successfully..."); //STEP 4: Execute a query System.out.println("Creating statement..."); stmt = conn.createStatement(); stmt2 = conn.createStatement(); String sql = "SELECT * FROM openmrs.person;"; ResultSet rs = stmt.executeQuery(sql); //STEP 5: Extract data from result set int maleGenderConceptID=8507; int femaleGenderConceptID=8532; String completeString=""; while(rs.next()) { //Retrieve by column name completeString="\nINSERT INTO person (person_id, gender_concept_id, year_of_birth,month_of_birth,day_of_birth,time_of_birth,race_concept_id,ethnicity_concept_id,location_id,provider_id,care_site_id,person_source_value, gender_source_value,gender_source_concept_id,race_source_value,race_source_concept_id,ethnicity_source_value,ethnicity_source_concept_id)" + "VALUES ("+rs.getInt("person_id")+","; //gender conditioning if (rs.getString("gender").equalsIgnoreCase("M")) completeString=completeString+maleGenderConceptID; else if (rs.getString("gender").equalsIgnoreCase("F")) completeString=completeString+femaleGenderConceptID; else completeString=completeString+0; //birth date conditioning if(rs.getDate("birthdate")!=null){ Calendar cal = Calendar.getInstance(); cal.setTime(rs.getDate("birthdate")); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int day = cal.get(Calendar.DAY_OF_MONTH); completeString=completeString+","+year+","+month+","+day; } else continue; //time completeString=completeString+",null"; //race completeString=completeString+",2060-2"; //ethnicity completeString=completeString+",0"; //location_id,provider_id,care_site_id, completeString=completeString+",null,null,null"; //person source value String patientidentifiersql = "SELECT * FROM openmrs.patient_identifier where patient_id="+rs.getInt("person_id")+";"; ResultSet patientidentifierresutset = stmt2.executeQuery(patientidentifiersql); String identifier=""; while(patientidentifierresutset.next()) { identifier = patientidentifierresutset.getString("identifier"); } completeString=completeString+",'"+rs.getInt("person_id")+identifier+"'"; //gendersource if(rs.getString("gender")!=null) completeString=completeString+",'"+rs.getString("gender")+"'"; else completeString=completeString+",null"; //gender_source_concept_id,race_source_value,race_source_concept_id,ethnicity_source_value,ethnicity_source_concept_id completeString=completeString+",null,null,null,null,null"; completeString=completeString+");"; response.getWriter().write(completeString); //System.out.println(completeString); } rs.close(); //obs table population sql = "SELECT DISTINCT person_id from openmrs.obs;"; rs = stmt.executeQuery(sql); int counter=0; while(rs.next()) { counter++; completeString="\nINSERT INTO observation_period (observation_period_id,person_id,observation_period_start_date,observation_period_end_date,period_type_concept_id)" + "VALUES ("+counter+","+rs.getInt("person_id"); String obsStartDatesql = "select min(obs_datetime) from obs where person_id="+rs.getInt("person_id")+";"; ResultSet obsStartDateresutset = stmt2.executeQuery(obsStartDatesql); Date obsStartDate=null; while(obsStartDateresutset.next()) { obsStartDate = obsStartDateresutset.getDate("min(obs_datetime)"); } completeString=completeString+",'"+obsStartDate+"'"; String obsEndDatesql = "select max(obs_datetime) from obs where person_id="+rs.getInt("person_id")+";"; ResultSet obsEndDateresutset = stmt2.executeQuery(obsEndDatesql); Date obsEndDate=null; while(obsEndDateresutset.next()) { obsEndDate = obsEndDateresutset.getDate("max(obs_datetime)"); } completeString=completeString+",'"+obsEndDate+"'"; completeString=completeString+",0"; completeString=completeString+");"; response.getWriter().write(completeString); } rs.close(); //condition_occurrence table population int[] valueCodedDoNotIncludeArray={1252,1262,1266,1269,5303,6097}; //List<Integer> valueCodedDoNotIncludeArrayList = new ArrayList<Integer>(); // valueCodedDoNotIncludeArrayList.addAll(valueCodedDoNotIncludeArray.); sql = "SELECT DISTINCT * from openmrs.obs;"; rs = stmt.executeQuery(sql); counter=0; while(rs.next()) { //also considering 0 as null if(rs.getInt("value_coded")==0) continue; String valueCodedConceptsql = "select * from concept where concept_id="+rs.getInt("value_coded")+";"; ResultSet valueCodedConceptresutset = stmt2.executeQuery(valueCodedConceptsql); int valueCodedClassCheck=0; boolean isUnwantedConcept = false; while(valueCodedConceptresutset.next()) { valueCodedClassCheck=valueCodedConceptresutset.getInt("class_id"); } //check for diagnosis if(valueCodedClassCheck!=4 && valueCodedClassCheck!=12 && valueCodedClassCheck!=13) continue; int valueCodedConcept=rs.getInt("concept_id"); for(int i: valueCodedDoNotIncludeArray){ if( valueCodedConcept==i) { isUnwantedConcept = true; } } //remove unwanted concepts if(isUnwantedConcept) continue; counter++; completeString="\nINSERT INTO condition_occurrence (condition_occurrence_id,person_id,condition_concept_id,condition_start_date,condition_end_date,condition_type_concept_id,stop_reason,provider_id,visit_occurrence_id,condition_source_value,condition_source_concept_id)" + "VALUES ("+counter+","+rs.getInt("person_id"); completeString=completeString+",'"+rs.getInt("concept_id")+rs.getInt("value_coded")+"'"; completeString=completeString + ",'" + rs.getDate("obs_datetime")+"'"; //conditiontype not null - taking it as 0 for now completeString=completeString+",null,0,null"; completeString=completeString+","+rs.getInt("encounter_id")+","+rs.getInt("encounter_id"); completeString=completeString+","+rs.getInt("value_coded")+","+rs.getInt("value_coded"); completeString=completeString+");"; response.getWriter().write(completeString); } rs.close(); }catch(SQLException se){ //Handle errors for JDBC se.printStackTrace(); }catch(Exception e){ //Handle errors for Class.forName e.printStackTrace(); }finally{ //finally block used to close resources try{ if(stmt!=null) conn.close(); }catch(SQLException se){ }// do nothing try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); }//end finally try }//end try } catch (Exception e) { log.error("Error while downloading concepts.", e); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
package uk.ac.ebi.quickgo.ontology.controller; import io.swagger.annotations.ApiOperation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.InputStreamResource; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import uk.ac.ebi.quickgo.common.SearchableField; import uk.ac.ebi.quickgo.graphics.model.GraphImageLayout; import uk.ac.ebi.quickgo.graphics.ontology.RenderingGraphException; import uk.ac.ebi.quickgo.graphics.service.GraphImageService; import uk.ac.ebi.quickgo.ontology.OntologyRestConfig; import uk.ac.ebi.quickgo.ontology.OntologyRestProperties; import uk.ac.ebi.quickgo.ontology.common.OntologyFields; import uk.ac.ebi.quickgo.ontology.common.OntologyType; import uk.ac.ebi.quickgo.ontology.controller.validation.OBOControllerValidationHelper; import uk.ac.ebi.quickgo.ontology.model.OBOTerm; import uk.ac.ebi.quickgo.ontology.model.OntologyRelationType; import uk.ac.ebi.quickgo.ontology.model.OntologyRelationship; import uk.ac.ebi.quickgo.ontology.service.OntologyService; import uk.ac.ebi.quickgo.ontology.service.search.SearchServiceConfig; import uk.ac.ebi.quickgo.rest.ResponseExceptionHandler; import uk.ac.ebi.quickgo.rest.search.RetrievalException; import uk.ac.ebi.quickgo.rest.search.SearchDispatcher; import uk.ac.ebi.quickgo.rest.search.SearchService; import uk.ac.ebi.quickgo.rest.search.StringToQuickGOQueryConverter; import uk.ac.ebi.quickgo.rest.search.query.QueryRequest; import uk.ac.ebi.quickgo.rest.search.query.QuickGOQuery; import uk.ac.ebi.quickgo.rest.search.query.RegularPage; import uk.ac.ebi.quickgo.rest.search.results.QueryResult; import javax.imageio.ImageIO; import java.awt.image.RenderedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.time.Duration; import java.time.LocalTime; import java.util.*; import java.util.stream.Collectors; import static com.google.common.base.Preconditions.checkArgument; import static uk.ac.ebi.quickgo.ontology.model.OntologyRelationType.DEFAULT_TRAVERSAL_TYPES_CSV; import static uk.ac.ebi.quickgo.rest.search.query.QuickGOQuery.and; /** * Abstract controller defining common end-points of an OBO related * REST API. * * Created 27/11/15 * @author Edd */ public abstract class OBOController<T extends OBOTerm> { static final String TERMS_RESOURCE = "terms"; static final String SEARCH_RESOUCE = "search"; static final String COMPLETE_SUB_RESOURCE = "complete"; static final String HISTORY_SUB_RESOURCE = "history"; static final String XREFS_SUB_RESOURCE = "xrefs"; static final String CONSTRAINTS_SUB_RESOURCE = "constraints"; static final String XRELATIONS_SUB_RESOURCE = "xontologyrelations"; static final String GUIDELINES_SUB_RESOURCE = "guidelines"; static final String ANCESTORS_SUB_RESOURCE = "ancestors"; static final String DESCENDANTS_SUB_RESOURCE = "descendants"; static final String PATHS_SUB_RESOURCE = "paths"; static final String CHART_SUB_RESOURCE = "chart"; static final String CHART_COORDINATES_SUB_RESOURCE = CHART_SUB_RESOURCE + "/coords"; private static final Logger LOGGER = LoggerFactory.getLogger(OBOController.class); private static final String COLON = ":"; private static final String DEFAULT_ENTRIES_PER_PAGE = "25"; private static final String DEFAULT_PAGE_NUMBER = "1"; private static final String MAX_AGE_HTTP_HEADER = "max-age=%s"; private final OntologyService<T> ontologyService; private final SearchService<OBOTerm> ontologySearchService; private final StringToQuickGOQueryConverter ontologyQueryConverter; private final SearchServiceConfig.OntologyCompositeRetrievalConfig ontologyRetrievalConfig; private final OBOControllerValidationHelper validationHelper; private final GraphImageService graphImageService; private final OntologyRestConfig.OntologyPagingConfig ontologyPagingConfig; private final OntologyType ontologyType; private final OntologyRestProperties restProperties; public OBOController(OntologyService<T> ontologyService, SearchService<OBOTerm> ontologySearchService, SearchableField searchableField, SearchServiceConfig.OntologyCompositeRetrievalConfig ontologyRetrievalConfig, GraphImageService graphImageService, OBOControllerValidationHelper oboControllerValidationHelper, OntologyRestConfig.OntologyPagingConfig ontologyPagingConfig, OntologyType ontologyType, OntologyRestProperties restProperties) { checkArgument(ontologyService != null, "Ontology service cannot be null"); checkArgument(ontologySearchService != null, "Ontology search service cannot be null"); checkArgument(searchableField != null, "Ontology searchable field cannot be null"); checkArgument(ontologyRetrievalConfig != null, "Ontology retrieval configuration cannot be null"); checkArgument(graphImageService != null, "Graph image service cannot be null"); checkArgument(oboControllerValidationHelper != null, "OBO validation helper cannot be null"); checkArgument(ontologyPagingConfig != null, "Paging config cannot be null"); checkArgument(ontologyType != null, "Ontology type config cannot be null"); checkArgument(restProperties != null, "Rest properties cannot be null"); this.ontologyService = ontologyService; this.ontologySearchService = ontologySearchService; this.ontologyQueryConverter = new StringToQuickGOQueryConverter(searchableField); this.ontologyRetrievalConfig = ontologyRetrievalConfig; this.validationHelper = oboControllerValidationHelper; this.graphImageService = graphImageService; this.ontologyPagingConfig = ontologyPagingConfig; this.ontologyType = ontologyType; this.restProperties = restProperties; } /** * Wrap a collection as a {@link Set} * * @param items the items to wrap as a {@link Set} * @param <ItemType> the type of the {@link Collection}, i.e., this method works for any type * @return a {@link Set} wrapping the items in a {@link Collection} */ private static <ItemType> Set<ItemType> asSet(Collection<ItemType> items) { return items.stream().collect(Collectors.toSet()); } /** * Converts a {@link Collection} of {@link OntologyRelationType}s to a corresponding array of * {@link OntologyRelationType}s * * @param relations the {@link OntologyRelationType}s * @return an array of {@link OntologyRelationType}s */ private static OntologyRelationType[] asOntologyRelationTypeArray(Collection<OntologyRelationType> relations) { return relations.stream().toArray(OntologyRelationType[]::new); } /** * An empty or unknown path should result in a bad request * * @return a 400 response */ @ApiOperation(value = "Catches any bad requests and returns an error response with a 400 status") /** * Get all information about all terms and page through the results. * * @param page the page number of results to retrieve * @return the specified page of results as a {@link QueryResult} instance or a 400 response * if the page number is invalid */ @ApiOperation(value = "Get all information on all terms and page through the results") @RequestMapping(value = "/" + TERMS_RESOURCE, method = {RequestMethod.GET}, produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity<QueryResult<T>> baseUrl( @RequestParam(value = "page", defaultValue = DEFAULT_PAGE_NUMBER) int page) { return new ResponseEntity<>(ontologyService.findAllByOntologyType (this.ontologyType, new RegularPage(page, ontologyPagingConfig.defaultPageSize())), httpHeaders(), HttpStatus.OK); } /** * Get core information about a list of terms in comma-separated-value (CSV) format * * @param ids ontology identifiers in CSV format * @return * <ul> * <li>all ids are valid: response consists of a 200 with the chosen information about the ontology terms</li> * <li>any id is not found: response returns 200 with an empty result set.</li> * <li>any id is of the an invalid format: response returns 400</li> * </ul> */ @ApiOperation(value = "Get core information about a (CSV) list of terms based on their ids", notes = "If possible, response fields include: id, isObsolete, name, definition, ancestors, synonyms, " + "aspect and usage.") @RequestMapping(value = TERMS_RESOURCE + "/{ids}", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity<QueryResult<T>> findTermsCoreAttr(@PathVariable(value = "ids") String ids) { return getResultsResponse(ontologyService.findCoreInfoByOntologyId(validationHelper.validateCSVIds(ids))); } /** * Get complete information about a list of terms in comma-separated-value (CSV) format * * @param ids ontology identifiers in CSV format * @return * <ul> * <li>all ids are valid: response consists of a 200 with the chosen information about the ontology terms</li> * <li>any id is not found: response returns 200 with an empty result set.</li> * <li>any id is of the an invalid format: response returns 400</li> * </ul> */ @ApiOperation(value = "Get complete information about a (CSV) list of terms based on their ids", notes = "All fields will be populated providing they have a value.") @RequestMapping(value = TERMS_RESOURCE + "/{ids}/" + COMPLETE_SUB_RESOURCE, method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity<QueryResult<T>> findTermsComplete(@PathVariable(value = "ids") String ids) { return getResultsResponse( ontologyService.findCompleteInfoByOntologyId(validationHelper.validateCSVIds(ids))); } /** * Get history information about a list of terms in comma-separated-value (CSV) format * * @param ids ontology identifiers in CSV format * @return * <ul> * <li>all ids are valid: response consists of a 200 with the chosen information about the ontology terms</li> * <li>any id is not found: response returns 200 with an empty result set.</li> * <li>any id is of the an invalid format: response returns 400</li> * </ul> */ @ApiOperation(value = "Get history information about a (CSV) list of terms based on their ids", notes = "If possible, response fields include: id, isObsolete, name, definition, history.") @RequestMapping(value = TERMS_RESOURCE + "/{ids}/" + HISTORY_SUB_RESOURCE, method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity<QueryResult<T>> findTermsHistory(@PathVariable(value = "ids") String ids) { return getResultsResponse( ontologyService.findHistoryInfoByOntologyId(validationHelper.validateCSVIds(ids))); } /** * Get cross-reference information about a list of terms in comma-separated-value (CSV) format * * @param ids ontology identifiers in CSV format * @return * <ul> * <li>all ids are valid: response consists of a 200 with the chosen information about the ontology terms</li> * <li>any id is not found: response returns 200 with an empty result set.</li> * <li>any id is of the an invalid format: response returns 400</li> * </ul> */ @ApiOperation(value = "Get cross-reference information about a (CSV) list of terms based on their ids", notes = "If possible, response fields include: id, isObsolete, name, definition, xRefs.") @RequestMapping(value = TERMS_RESOURCE + "/{ids}/" + XREFS_SUB_RESOURCE, method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity<QueryResult<T>> findTermsXRefs(@PathVariable(value = "ids") String ids) { return getResultsResponse( ontologyService.findXRefsInfoByOntologyId(validationHelper.validateCSVIds(ids))); } /** * Get taxonomy constraint information about a list of terms in comma-separated-value (CSV) format * * @param ids ontology identifiers in CSV format * @return * <ul> * <li>all ids are valid: response consists of a 200 with the chosen information about the ontology terms</li> * <li>any id is not found: response returns 200 with an empty result set.</li> * <li>any id is of the an invalid format: response returns 400</li> * </ul> */ @ApiOperation(value = "Get taxonomy constraint information about a (CSV) list of terms based on their ids", notes = "If possible, response fields include: id, isObsolete, name, definition, taxonConstraints.") @RequestMapping(value = TERMS_RESOURCE + "/{ids}/" + CONSTRAINTS_SUB_RESOURCE, method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity<QueryResult<T>> findTermsTaxonConstraints(@PathVariable(value = "ids") String ids) { return getResultsResponse( ontologyService.findTaxonConstraintsInfoByOntologyId(validationHelper.validateCSVIds(ids))); } /** * Get cross-ontology relationship information about a list of terms in comma-separated-value (CSV) format * * @param ids ontology identifiers in CSV format * @return * <ul> * <li>all ids are valid: response consists of a 200 with the chosen information about the ontology terms</li> * <li>any id is not found: response returns 200 with an empty result set.</li> * <li>any id is of the an invalid format: response returns 400</li> * </ul> */ @ApiOperation(value = "Get cross ontology relationship information about a (CSV) list of terms based on their ids", notes = "If possible, response fields include: id, isObsolete, name, definition, xRelations.") @RequestMapping(value = TERMS_RESOURCE + "/{ids}/" + XRELATIONS_SUB_RESOURCE, method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity<QueryResult<T>> findTermsXOntologyRelations(@PathVariable(value = "ids") String ids) { return getResultsResponse( ontologyService.findXORelationsInfoByOntologyId(validationHelper.validateCSVIds(ids))); } /** * Get annotation guideline information about a list of terms in comma-separated-value (CSV) format * * @param ids ontology identifiers in CSV format * @return * <ul> * <li>all ids are valid: response consists of a 200 with the chosen information about the ontology terms</li> * <li>any id is not found: response returns 200 with an empty result set.</li> * <li>any id is of the an invalid format: response returns 400</li> * </ul> */ @ApiOperation(value = "Get annotation guideline information about a (CSV) list of terms based on their ids", notes = "If possible, response fields include: id, isObsolete, name, definition, annotationGuidelines.") @RequestMapping(value = TERMS_RESOURCE + "/{ids}/" + GUIDELINES_SUB_RESOURCE, method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity<QueryResult<T>> findTermsAnnotationGuideLines(@PathVariable(value = "ids") String ids) { return getResultsResponse(ontologyService .findAnnotationGuideLinesInfoByOntologyId(validationHelper.validateCSVIds(ids))); } /** * Search for an ontology term via its identifier, or a generic query search * * @param query the query to search against * @param limit the amount of queries to return * @return a {@link QueryResult} instance containing the results of the search */ @ApiOperation(value = "Searches a simple user query, e.g., query=apopto", notes = "If possible, response fields include: id, name, definition, isObsolete") @RequestMapping(value = "/" + SEARCH_RESOUCE, method = {RequestMethod.GET}, produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity<QueryResult<OBOTerm>> ontologySearch( @RequestParam(value = "query") String query, @RequestParam(value = "limit", defaultValue = DEFAULT_ENTRIES_PER_PAGE) int limit, @RequestParam(value = "page", defaultValue = DEFAULT_PAGE_NUMBER) int page) { validationHelper.validateRequestedResults(limit); validationHelper.validatePageIsLessThanPaginationLimit(page); QueryRequest request = buildRequest( query, limit, page, ontologyQueryConverter); return SearchDispatcher.search(request, ontologySearchService); } /** * Retrieves the ancestors of ontology terms * @param ids the term ids in CSV format * @param relations the ontology relationships over which ancestors will be found * @return a result instance containing the ancestors */ @ApiOperation(value = "Retrieves the ancestors of specified ontology terms") @RequestMapping(value = TERMS_RESOURCE + "/{ids}/" + ANCESTORS_SUB_RESOURCE, method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity<QueryResult<T>> findAncestors( @PathVariable(value = "ids") String ids, @RequestParam(value = "relations", defaultValue = DEFAULT_TRAVERSAL_TYPES_CSV) String relations) { return getResultsResponse( ontologyService.findAncestorsInfoByOntologyId( validationHelper.validateCSVIds(ids), asOntologyRelationTypeArray(validationHelper.validateRelationTypes(relations)))); } /** * Retrieves the descendants of ontology terms * @param ids the term ids in CSV format * @param relations the ontology relationships over which descendants will be found * @return a result containing the descendants */ @ApiOperation(value = "Retrieves the descendants of specified ontology terms") @RequestMapping(value = TERMS_RESOURCE + "/{ids}/" + DESCENDANTS_SUB_RESOURCE, method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity<QueryResult<T>> findDescendants( @PathVariable(value = "ids") String ids, @RequestParam(value = "relations", defaultValue = DEFAULT_TRAVERSAL_TYPES_CSV) String relations) { return getResultsResponse( ontologyService.findDescendantsInfoByOntologyId( validationHelper.validateCSVIds(ids), asOntologyRelationTypeArray(validationHelper.validateRelationTypes(relations)))); } /** * Retrieves the paths between ontology terms * @param ids the term ids in CSV format, from which paths begin * @param toIds the term ids in CSV format, to which the paths lead * @param relations the ontology relationships over which descendants will be found * @return a result containing a list of paths between the {@code ids} terms, and {@code toIds} terms */ @ApiOperation(value = "Retrieves the paths between two specified sets of ontology terms. Each path is " + "formed from a list of (term, relationship, term) triples.") @RequestMapping(value = TERMS_RESOURCE + "/{ids}/" + PATHS_SUB_RESOURCE + "/{toIds}", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity<QueryResult<List<OntologyRelationship>>> findPaths( @PathVariable(value = "ids") String ids, @PathVariable(value = "toIds") String toIds, @RequestParam(value = "relations", defaultValue = DEFAULT_TRAVERSAL_TYPES_CSV) String relations) { return getResultsResponse( ontologyService.paths( asSet(validationHelper.validateCSVIds(ids)), asSet(validationHelper.validateCSVIds(toIds)), asOntologyRelationTypeArray(validationHelper.validateRelationTypes(relations)) )); } /** * Retrieves the graphical image corresponding to ontology terms. * * @param ids the term ids whose image is required * @return the image corresponding to the requested term ids */ @ApiOperation(value = "Retrieves the PNG image corresponding to the specified ontology terms") @RequestMapping(value = TERMS_RESOURCE + "/{ids}/" + CHART_SUB_RESOURCE, method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.IMAGE_PNG_VALUE}) public ResponseEntity<InputStreamResource> getChart(@PathVariable(value = "ids") String ids) { try { return createChartResponseEntity(validationHelper.validateCSVIds(ids)); } catch (IOException | RenderingGraphException e) { throw createChartGraphicsException(e); } } /** * Retrieves the graphical image coordination information corresponding to ontology terms. * * @param ids the term ids whose image is required * @return the coordinate information of the terms in the chart */ @ApiOperation(value = "Retrieves coordinate information about terms within the PNG chart from the " + CHART_SUB_RESOURCE + " sub-resource") @RequestMapping(value = TERMS_RESOURCE + "/{ids}/" + CHART_COORDINATES_SUB_RESOURCE, method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE}) public ResponseEntity<GraphImageLayout> getChartCoordinates(@PathVariable(value = "ids") String ids) { try { GraphImageLayout layout = graphImageService .createChart(validationHelper.validateCSVIds(ids), ontologyType.name()).getLayout(); return ResponseEntity .ok() .body(layout); } catch (RenderingGraphException e) { throw createChartGraphicsException(e); } } /** * Creates a {@link ResponseEntity} containing a {@link QueryResult} for a list of results. * * @param results a list of results * @return a {@link ResponseEntity} containing a {@link QueryResult} for a list of results */ <ResponseType> ResponseEntity<QueryResult<ResponseType>> getResultsResponse(List<ResponseType> results) { List<ResponseType> resultsToShow; if (results == null) { resultsToShow = Collections.emptyList(); } else { resultsToShow = results; } QueryResult<ResponseType> queryResult = new QueryResult.Builder<>(resultsToShow.size(), resultsToShow).build(); return new ResponseEntity<>(queryResult, httpHeaders(), HttpStatus.OK); } private RetrievalException createChartGraphicsException(Throwable throwable) { String errorMessage = "Error encountered during creation of ontology chart graphics."; LOGGER.error(errorMessage, throwable); return new RetrievalException(errorMessage); } /** * Delegates the creation of an graphical image, corresponding to the specified list * of {@code ids} and returns the appropriate {@link ResponseEntity}. * * @param ids the terms whose corresponding graphical image is required * @return the image corresponding to the specified terms * @throws IOException if there is an error during creation of the image {@link InputStreamResource} * @throws RenderingGraphException if there was an error during the rendering of the image */ private ResponseEntity<InputStreamResource> createChartResponseEntity(List<String> ids) throws IOException, RenderingGraphException { RenderedImage renderedImage = graphImageService .createChart(ids, ontologyType.name()) .getGraphImage() .render(); ByteArrayOutputStream os = new ByteArrayOutputStream(); ImageIO.write(renderedImage, "png", Base64.getMimeEncoder().wrap(os)); InputStream is = new ByteArrayInputStream(os.toByteArray()); return ResponseEntity .ok() .contentLength(os.size()) .contentType(MediaType.IMAGE_PNG) .header("Content-Encoding","base64") .body(new InputStreamResource(is)); } private QueryRequest buildRequest(String query, int limit, int page, StringToQuickGOQueryConverter converter) { QuickGOQuery userQuery = converter.convert(query); QuickGOQuery restrictedUserQuery = restrictQueryToOTypeResults(userQuery); QueryRequest.Builder builder = new QueryRequest .Builder(restrictedUserQuery) .setPage(new RegularPage(page, limit)); if (!ontologyRetrievalConfig.getSearchReturnedFields().isEmpty()) { ontologyRetrievalConfig.getSearchReturnedFields() .forEach(builder::addProjectedField); } return builder.build(); } /** * Given a {@link QuickGOQuery}, create a composite {@link QuickGOQuery} by * performing a conjunction with another query, which restricts all results * to be of a type corresponding to ontology type}. * * @param query the query that is constrained * @return the new constrained query */ private QuickGOQuery restrictQueryToOTypeResults(QuickGOQuery query) { return and(query, ontologyQueryConverter.convert( OntologyFields.Searchable.ONTOLOGY_TYPE + COLON + ontologyType.name())); } private MultiValueMap<String, String> httpHeaders(){ MultiValueMap<String, String> headers = new HttpHeaders(); headers.add(HttpHeaders.CACHE_CONTROL, String.format(MAX_AGE_HTTP_HEADER, maxAge())); return headers; } private long maxAge(){ long maxAge; final LocalTime now = LocalTime.now(); if (now.isAfter(restProperties.getStartTime())) { maxAge = Duration.between(now, LocalTime.MAX).getSeconds() + restProperties.midnightToEndCacheTime(); } else { maxAge = Duration.between(now, restProperties.getEndTime()).getSeconds(); } assert maxAge > 0; return maxAge; } }
package net.tomp2p.dht; import java.io.IOException; import java.io.Serializable; import java.security.InvalidKeyException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.SignatureException; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Map; import net.tomp2p.connection.DSASignatureFactory; import net.tomp2p.dht.StorageLayer.PutStatus; import net.tomp2p.p2p.PeerBuilder; import net.tomp2p.peers.Number160; import net.tomp2p.peers.Number640; import net.tomp2p.peers.PeerAddress; import net.tomp2p.storage.Data; import net.tomp2p.utils.Utils; import org.junit.Assert; import org.junit.Test; public class TestH2H { private static final DSASignatureFactory factory = new DSASignatureFactory(); @Test public void testPut() throws IOException, ClassNotFoundException, NoSuchAlgorithmException, InvalidKeyException, SignatureException { StringBuilder sb = new StringBuilder( "2b51b720-7ae2-11e3-981f-0800200c9a66"); for (int i = 0; i < 10; i++) { testPut(sb.toString()); sb.append("2b51b720-7ae2-11e3-981f-0800200c9a66"); } } @Test public void testPut0() throws IOException, ClassNotFoundException, NoSuchAlgorithmException, InvalidKeyException, SignatureException { testPut("2b51b720-7ae2-11e3-981f-0800200c9a662b51b720-7ae2-11e3-981f-0800200c9a66"); } private void testPut(String s1) throws IOException, ClassNotFoundException, NoSuchAlgorithmException, InvalidKeyException, SignatureException { PeerDHT p1 = null; PeerDHT p2 = null; try { KeyPairGenerator gen = KeyPairGenerator.getInstance("DSA"); KeyPair keyPairPeer1 = gen.generateKeyPair(); p1 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(1)) .ports(4838).keyPair(keyPairPeer1).start()).start(); KeyPair keyPairPeer2 = gen.generateKeyPair(); p2 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(2)) .masterPeer(p1.peer()).keyPair(keyPairPeer2).start()) .start(); p2.peer().bootstrap().peerAddress(p1.peerAddress()).start() .awaitUninterruptibly(); p1.peer().bootstrap().peerAddress(p2.peerAddress()).start() .awaitUninterruptibly(); KeyPair keyPair = gen.generateKeyPair(); String locationKey = "location"; Number160 lKey = Number160.createHash(locationKey); String domainKey = "domain"; Number160 dKey = Number160.createHash(domainKey); String contentKey = "content"; Number160 cKey = Number160.createHash(contentKey); String versionKey = "version"; Number160 vKey = Number160.createHash(versionKey); String basedOnKey = "based on"; Number160 bKey = Number160.createHash(basedOnKey); H2HTestData testData = new H2HTestData(s1); Data data = new Data(testData); data.ttlSeconds(10000); data.addBasedOn(bKey); data.protectEntryNow(keyPair, factory); FuturePut futurePut1 = p1.put(lKey).data(cKey, data) .domainKey(dKey).versionKey(vKey).keyPair(keyPair).start(); futurePut1.awaitUninterruptibly(); Assert.assertTrue(futurePut1.isSuccess()); } finally { if (p1 != null) { p1.shutdown().awaitUninterruptibly(); } if (p2 != null) { p2.shutdown().awaitUninterruptibly(); } } } @Test public void testRemove1() throws NoSuchAlgorithmException, IOException, InvalidKeyException, SignatureException, ClassNotFoundException { PeerDHT p1 = null; PeerDHT p2 = null; try { KeyPairGenerator gen = KeyPairGenerator.getInstance("DSA"); KeyPair keyPairPeer1 = gen.generateKeyPair(); p1 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(1)) .ports(4838).keyPair(keyPairPeer1).start()).start(); KeyPair keyPairPeer2 = gen.generateKeyPair(); p2 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(2)) .masterPeer(p1.peer()).keyPair(keyPairPeer2).start()) .start(); p2.peer().bootstrap().peerAddress(p1.peerAddress()).start() .awaitUninterruptibly(); p1.peer().bootstrap().peerAddress(p2.peerAddress()).start() .awaitUninterruptibly(); KeyPair keyPair1 = gen.generateKeyPair(); KeyPair keyPair2 = gen.generateKeyPair(); String locationKey = "location"; Number160 lKey = Number160.createHash(locationKey); String contentKey = "content"; Number160 cKey = Number160.createHash(contentKey); String testData1 = "data1"; Data data = new Data(testData1).protectEntryNow(keyPair1, factory); // put trough peer 1 with key pair FuturePut futurePut1 = p1.put(lKey).data(cKey, data) .keyPair(keyPair1).start(); futurePut1.awaitUninterruptibly(); Assert.assertTrue(futurePut1.isSuccess()); FutureGet futureGet1a = p1.get(lKey).contentKey(cKey).start(); futureGet1a.awaitUninterruptibly(); Assert.assertTrue(futureGet1a.isSuccess()); Assert.assertEquals(testData1, (String) futureGet1a.data().object()); FutureGet futureGet1b = p2.get(lKey).contentKey(cKey).start(); futureGet1b.awaitUninterruptibly(); Assert.assertTrue(futureGet1b.isSuccess()); Assert.assertEquals(testData1, (String) futureGet1b.data().object()); // try to remove without key pair FutureRemove futureRemove1a = p1.remove(lKey).contentKey(cKey) .start(); futureRemove1a.awaitUninterruptibly(); Assert.assertFalse(futureRemove1a.isRemoved()); FutureGet futureGet2a = p1.get(lKey).contentKey(cKey).start(); futureGet2a.awaitUninterruptibly(); Assert.assertTrue(futureGet2a.isSuccess()); // should have been not modified Assert.assertEquals(testData1, (String) futureGet2a.data().object()); FutureRemove futureRemove1b = p2.remove(lKey).contentKey(cKey) .start(); futureRemove1b.awaitUninterruptibly(); Assert.assertFalse(futureRemove1b.isRemoved()); FutureGet futureGet2b = p2.get(lKey).contentKey(cKey).start(); futureGet2b.awaitUninterruptibly(); Assert.assertTrue(futureGet2b.isSuccess()); // should have been not modified Assert.assertEquals(testData1, (String) futureGet2b.data().object()); // try to remove with wrong key pair FutureRemove futureRemove2a = p1.remove(lKey).contentKey(cKey) .keyPair(keyPair2).start(); futureRemove2a.awaitUninterruptibly(); Assert.assertFalse(futureRemove2a.isRemoved()); FutureGet futureGet3a = p1.get(lKey).contentKey(cKey).start(); futureGet3a.awaitUninterruptibly(); Assert.assertTrue(futureGet3a.isSuccess()); // should have been not modified Assert.assertEquals(testData1, (String) futureGet3a.data().object()); FutureRemove futureRemove2b = p2.remove(lKey).contentKey(cKey) .start(); futureRemove2b.awaitUninterruptibly(); Assert.assertFalse(futureRemove2b.isRemoved()); FutureGet futureGet3b = p2.get(lKey).contentKey(cKey).start(); futureGet3b.awaitUninterruptibly(); Assert.assertTrue(futureGet3b.isSuccess()); // should have been not modified Assert.assertEquals(testData1, (String) futureGet3b.data().object()); // remove with correct key pair FutureRemove futureRemove4 = p1.remove(lKey).contentKey(cKey) .keyPair(keyPair1).start(); futureRemove4.awaitUninterruptibly(); Assert.assertTrue(futureRemove4.isRemoved()); FutureGet futureGet4a = p2.get(lKey).contentKey(cKey).start(); futureGet4a.awaitUninterruptibly(); Assert.assertTrue(futureGet4a.isEmpty()); // should have been removed Assert.assertNull(futureGet4a.data()); FutureGet futureGet4b = p2.get(lKey).contentKey(cKey).start(); futureGet4b.awaitUninterruptibly(); Assert.assertTrue(futureGet4b.isEmpty()); // should have been removed Assert.assertNull(futureGet4b.data()); } finally { if (p1 != null) { p1.shutdown().awaitUninterruptibly(); } if (p2 != null) { p2.shutdown().awaitUninterruptibly(); } } } @Test public void testRemoveFromTo() throws NoSuchAlgorithmException, IOException, InvalidKeyException, SignatureException, ClassNotFoundException { PeerDHT p1 = null; PeerDHT p2 = null; try { KeyPairGenerator gen = KeyPairGenerator.getInstance("DSA"); KeyPair keyPairPeer1 = gen.generateKeyPair(); p1 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(1)) .ports(4838).keyPair(keyPairPeer1).start()).start(); KeyPair keyPairPeer2 = gen.generateKeyPair(); p2 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(2)) .masterPeer(p1.peer()).keyPair(keyPairPeer2).start()) .start(); p2.peer().bootstrap().peerAddress(p1.peerAddress()).start() .awaitUninterruptibly(); p1.peer().bootstrap().peerAddress(p2.peerAddress()).start() .awaitUninterruptibly(); KeyPair key1 = gen.generateKeyPair(); KeyPair key2 = gen.generateKeyPair(); String locationKey = "location"; Number160 lKey = Number160.createHash(locationKey); // String domainKey = "domain"; // Number160 dKey = Number160.createHash(domainKey); String contentKey = "content"; Number160 cKey = Number160.createHash(contentKey); String testData1 = "data1"; Data data = new Data(testData1).protectEntryNow(key1, factory); // put trough peer 1 with key pair FuturePut futurePut1 = p1.put(lKey).data(cKey, data).keyPair(key1) .start(); futurePut1.awaitUninterruptibly(); Assert.assertTrue(futurePut1.isSuccess()); FutureGet futureGet1a = p1.get(lKey).contentKey(cKey).start(); futureGet1a.awaitUninterruptibly(); Assert.assertTrue(futureGet1a.isSuccess()); Assert.assertEquals(testData1, (String) futureGet1a.data().object()); FutureGet futureGet1b = p2.get(lKey).contentKey(cKey).start(); futureGet1b.awaitUninterruptibly(); Assert.assertTrue(futureGet1b.isSuccess()); Assert.assertEquals(testData1, (String) futureGet1b.data().object()); // try to remove without key pair using from/to FutureRemove futureRemove1a = p1 .remove(lKey) .from(new Number640(lKey, Number160.ZERO, cKey, Number160.ZERO)) .to(new Number640(lKey, Number160.ZERO, cKey, Number160.MAX_VALUE)).start(); futureRemove1a.awaitUninterruptibly(); Assert.assertFalse(futureRemove1a.isRemoved()); FutureGet futureGet2a = p1.get(lKey).contentKey(cKey).start(); futureGet2a.awaitUninterruptibly(); Assert.assertTrue(futureGet2a.isSuccess()); // should have been not modified Assert.assertEquals(testData1, (String) futureGet2a.data().object()); FutureRemove futureRemove1b = p2 .remove(lKey) .from(new Number640(lKey, Number160.ZERO, cKey, Number160.ZERO)) .to(new Number640(lKey, Number160.ZERO, cKey, Number160.MAX_VALUE)).start(); futureRemove1b.awaitUninterruptibly(); Assert.assertFalse(futureRemove1b.isRemoved()); FutureGet futureGet2b = p2.get(lKey).contentKey(cKey).start(); futureGet2b.awaitUninterruptibly(); Assert.assertTrue(futureGet2b.isSuccess()); // should have been not modified Assert.assertEquals(testData1, (String) futureGet2b.data().object()); // remove with wrong key pair FutureRemove futureRemove2a = p1 .remove(lKey) .from(new Number640(lKey, Number160.ZERO, cKey, Number160.ZERO)) .to(new Number640(lKey, Number160.ZERO, cKey, Number160.MAX_VALUE)).keyPair(key2).start(); futureRemove2a.awaitUninterruptibly(); Assert.assertFalse(futureRemove2a.isRemoved()); FutureGet futureGet3a = p2.get(lKey).contentKey(cKey).start(); futureGet3a.awaitUninterruptibly(); Assert.assertTrue(futureGet3a.isSuccess()); // should have been not modified Assert.assertEquals(testData1, (String) futureGet3a.data().object()); FutureRemove futureRemove2b = p2 .remove(lKey) .from(new Number640(lKey, Number160.ZERO, cKey, Number160.ZERO)) .to(new Number640(lKey, Number160.ZERO, cKey, Number160.MAX_VALUE)).keyPair(key2).start(); futureRemove2b.awaitUninterruptibly(); Assert.assertFalse(futureRemove2b.isRemoved()); FutureGet futureGet3b = p2.get(lKey).contentKey(cKey).start(); futureGet3b.awaitUninterruptibly(); Assert.assertTrue(futureGet3b.isSuccess()); // should have been not modified Assert.assertEquals(testData1, (String) futureGet3b.data().object()); // remove with correct key pair FutureRemove futureRemove4 = p1 .remove(lKey) .from(new Number640(lKey, Number160.ZERO, cKey, Number160.ZERO)) .to(new Number640(lKey, Number160.ZERO, cKey, Number160.MAX_VALUE)).keyPair(key1).start(); futureRemove4.awaitUninterruptibly(); Assert.assertTrue(futureRemove4.isRemoved()); FutureGet futureGet4a = p2.get(lKey).contentKey(cKey).start(); futureGet4a.awaitUninterruptibly(); Assert.assertTrue(futureGet4a.isEmpty()); // should have been removed Assert.assertNull(futureGet4a.data()); FutureGet futureGet4b = p2.get(lKey).contentKey(cKey).start(); futureGet4b.awaitUninterruptibly(); Assert.assertTrue(futureGet4b.isEmpty()); // should have been removed Assert.assertNull(futureGet4b.data()); } finally { if (p1 != null) { p1.shutdown().awaitUninterruptibly(); } if (p2 != null) { p2.shutdown().awaitUninterruptibly(); } } } @Test public void getFromToTest1() throws IOException, ClassNotFoundException { PeerDHT p1 = null; PeerDHT p2 = null; try { p1 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(1)) .ports(4838).start()).start(); p2 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(2)) .masterPeer(p1.peer()).start()).start(); p2.peer().bootstrap().peerAddress(p1.peerAddress()).start() .awaitUninterruptibly(); String locationKey = "location"; String contentKey = "content"; List<H2HTestData> content = new ArrayList<H2HTestData>(); for (int i = 0; i < 3; i++) { H2HTestData data = new H2HTestData(randomString(i)); data.generateVersionKey(); if (i > 0) { data.setBasedOnKey(content.get(i - 1).getVersionKey()); } content.add(data); p2.put(Number160.createHash(locationKey)) .data(Number160.createHash(contentKey), new Data(data)) .versionKey(data.getVersionKey()).start() .awaitUninterruptibly(); } FutureGet future = p1 .get(Number160.createHash(locationKey)) .from(new Number640(Number160.createHash(locationKey), Number160.ZERO, Number160.createHash(contentKey), Number160.ZERO)) .to(new Number640(Number160.createHash(locationKey), Number160.ZERO, Number160.createHash(contentKey), Number160.MAX_VALUE)).descending().returnNr(1) .start(); future.awaitUninterruptibly(); Assert.assertEquals( content.get(content.size() - 1).getTestString(), ((H2HTestData) future.data().object()).getTestString()); } finally { if (p1 != null) { p1.shutdown().awaitUninterruptibly(); } if (p2 != null) { p2.shutdown().awaitUninterruptibly(); } } } @Test public void testVersionFork() throws Exception { PeerDHT p1 = null; PeerDHT p2 = null; try { KeyPairGenerator gen = KeyPairGenerator.getInstance("DSA"); KeyPair keyPair1 = gen.generateKeyPair(); p1 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(1)).ports(4838).start()).start(); p2 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(2)).masterPeer(p1.peer()).start()).start(); p2.peer().bootstrap().peerAddress(p1.peerAddress()).start().awaitUninterruptibly(); p1.peer().bootstrap().peerAddress(p2.peerAddress()).start().awaitUninterruptibly(); Number160 locationKey = Number160.createHash(randomString(1)); Number160 contentKey = Number160.createHash(randomString(2)); Data versionA = new Data("versionA").addBasedOn(new Number160(0, Number160.ZERO)).protectEntry(keyPair1); Data versionB = new Data("versionB").addBasedOn(new Number160(0, Number160.ONE)).protectEntry(keyPair1); FuturePut putA = p1.put(locationKey).data(contentKey, versionA, Number160.ONE).keyPair(keyPair1).start() .awaitUninterruptibly(); Assert.assertTrue(putA.isSuccess()); Assert.assertFalse(hasVersionFork(putA)); // put version B where a version conflict should be detected because // is not based on version A FuturePut putB = p1.put(locationKey).data(contentKey, versionB, Number160.ONE).keyPair(keyPair1).start() .awaitUninterruptibly(); Assert.assertTrue(hasVersionFork(putB)); } finally { if (p1 != null) { p1.shutdown().awaitUninterruptibly(); } if (p2 != null) { p2.shutdown().awaitUninterruptibly(); } } } private static boolean hasVersionFork(FuturePut future) throws Exception { if (future.isFailed() || future.rawResult().isEmpty()) { throw new Exception("Future failed"); } for (PeerAddress peeradress : future.rawResult().keySet()) { Map<Number640, Byte> map = future.rawResult().get(peeradress); if (map != null) { for (Number640 key : map.keySet()) { byte putStatus = map.get(key); if (putStatus == -1) { throw new Exception("Got an invalid status: " + putStatus); } else { switch (PutStatus.values()[putStatus]) { case VERSION_FORK: return true; default: break; } } } } } return false; } private String randomString(int i) { return "random" + i; } @Test // copied from Hive2Hive public void testMaxVersionLimit() throws IOException, ClassNotFoundException, NoSuchAlgorithmException, InvalidKeyException, SignatureException, InterruptedException { PeerDHT p1 = null; PeerDHT p2 = null; try { KeyPairGenerator gen = KeyPairGenerator.getInstance("DSA"); // create peers which accept only two versions KeyPair keyPairPeer1 = gen.generateKeyPair(); p1 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(1)).ports(5000).keyPair(keyPairPeer1).start()) .storage(new StorageMemory(1000, 2)).start(); KeyPair keyPairPeer2 = gen.generateKeyPair(); p2 = new PeerBuilderDHT(new PeerBuilder(Number160.createHash(2)).masterPeer(p1.peer()) .keyPair(keyPairPeer2).start()).storage(new StorageMemory(1000, 2)).start(); p2.peer().bootstrap().peerAddress(p1.peerAddress()).start().awaitUninterruptibly(); p1.peer().bootstrap().peerAddress(p2.peerAddress()).start().awaitUninterruptibly(); KeyPair keyPair1 = gen.generateKeyPair(); Number160 lKey = Number160.createHash("location"); Number160 dKey = Number160.createHash("domain"); Number160 cKey = Number160.createHash("content"); // put first version FuturePut futurePut = p1.put(lKey).domainKey(dKey).data(cKey, new Data("version1").protectEntry(keyPair1)) .versionKey(new Number160(0, new Number160(0))).keyPair(keyPair1).start(); futurePut.awaitUninterruptibly(); Assert.assertTrue(futurePut.isSuccess()); // put second version futurePut = p1.put(lKey).domainKey(dKey).data(cKey, new Data("version2").protectEntry(keyPair1)) .versionKey(new Number160(1, new Number160(0))).keyPair(keyPair1).start(); futurePut.awaitUninterruptibly(); Assert.assertTrue(futurePut.isSuccess()); // put third version futurePut = p1.put(lKey).domainKey(dKey).data(cKey, new Data("version3").protectEntry(keyPair1)) .versionKey(new Number160(2, new Number160(0))).keyPair(keyPair1).start(); futurePut.awaitUninterruptibly(); Assert.assertTrue(futurePut.isSuccess()); // wait for maintenance to kick in Thread.sleep(1500); // first version should be not available FutureGet futureGet = p1.get(lKey).domainKey(dKey).contentKey(cKey).versionKey(new Number160(0)).start(); futureGet.awaitUninterruptibly(); Assert.assertTrue(futureGet.isSuccess()); Assert.assertNull(futureGet.data()); } finally { p1.shutdown().awaitUninterruptibly(); p2.shutdown().awaitUninterruptibly(); } } } class H2HTestData extends NetworkContent { private static final long serialVersionUID = -4190279666159015217L; private final String testString; public H2HTestData(String testContent) { this.testString = testContent; } @Override public int getTimeToLive() { return 10000; } public String getTestString() { return testString; } } abstract class NetworkContent implements Serializable { private static final long serialVersionUID = 1L; private Number160 versionKey = Number160.ZERO; private Number160 basedOnKey = Number160.ZERO; public abstract int getTimeToLive(); public Number160 getVersionKey() { return versionKey; } public void setVersionKey(Number160 versionKey) { this.versionKey = versionKey; } public Number160 getBasedOnKey() { return basedOnKey; } public void setBasedOnKey(Number160 versionKey) { this.basedOnKey = versionKey; } public void generateVersionKey() { // get the current time long timestamp = new Date().getTime(); // get a MD5 hash of the object itself byte[] hash = null; try { hash = Utils.makeMD5Hash(Utils.encodeJavaObject(this)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // use time stamp value and the first part of the MD5 hash as version // key versionKey = new Number160(timestamp, new Number160(Arrays.copyOf(hash, Number160.BYTE_ARRAY_SIZE))); } }
package sgdk.rescomp.type; import java.awt.Dimension; import java.awt.Rectangle; import java.awt.geom.Area; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import sgdk.tool.ImageUtil; import sgdk.tool.Random; public class SpriteCell extends Rectangle implements Comparable<SpriteCell> { public static enum OptimizationType { BALANCED, MIN_SPRITE, MIN_TILE, NONE }; public static final Comparator<SpriteCell> sizeAndCoverageComparator = new Comparator<SpriteCell>() { @Override public int compare(SpriteCell o1, SpriteCell o2) { int result = Integer.compare(o1.numTile, o2.numTile); if (result == 0) result = java.lang.Double.compare(o1.getCoverage(), o2.getCoverage()); // we want ascending order return -result; } }; public final OptimizationType opt; public final int numTile; public int coveredPix; public SpriteCell(Rectangle r, OptimizationType opt) { super(r); this.opt = opt; numTile = (width * height) / 64; coveredPix = -1; } public SpriteCell(int x, int y, int width, int height, OptimizationType opt) { super(x, y, width, height); this.opt = opt; numTile = (width * height) / 64; coveredPix = -1; } public boolean isSingleTile() { return (width == 8) && (height == 8); } public List<SpriteCell> mutate() { final List<SpriteCell> result = new ArrayList<>(4); // switch (Random.nextInt() % 3) // default: // case 0: // // small move mutation // result.add(mutateMove(1)); // break; // case 1: // // size mutation // result.add(mutateSize(false)); // break; // case 2: // // split mutation // result.addAll(mutateSplit()); // break; switch (Random.nextInt() & 7) { default: case 0: // small move mutation result.add(mutateMove(1)); break; case 1: // big move mutation result.add(mutateMove(4)); break; case 2: // size mutation result.add(mutateSize(false)); break; case 3: // multi size mutation result.add(mutateSize(true)); break; case 4: // move + size mutation result.add(mutateMove(1).mutateSize(false)); break; case 5: // big move + multi size mutation result.add(mutateMove(4).mutateSize(true)); break; case 6: // split mutation result.addAll(mutateSplit()); break; case 7: // move + split mutation result.addAll(mutateMove(1).mutateSplit()); break; } return result; } private SpriteCell mutateMove(int move) { final Rectangle newRegion = new Rectangle(this); switch (Random.nextInt() & 3) { default: case 0: newRegion.x += move; break; case 1: newRegion.x -= move; break; case 2: newRegion.y += move; break; case 3: newRegion.y -= move; break; } return new SpriteCell(newRegion, opt); } private SpriteCell mutateSize(boolean multi) { final Rectangle newRegion = new Rectangle(this); int it = 1; if (multi) it += Random.nextInt() & 3; while (it > 0) { switch (Random.nextInt() & 3) { default: case 0: if (newRegion.width < 32) { newRegion.width += 8; it } break; case 1: if (newRegion.width > 8) { newRegion.width -= 8; it } break; case 2: if (newRegion.height < 32) { newRegion.height += 8; it } break; case 3: if (newRegion.height > 8) { newRegion.height -= 8; it } break; } } return new SpriteCell(newRegion, opt); } private List<SpriteCell> mutateSplit() { final List<SpriteCell> result = new ArrayList<>(4); final Rectangle newRegion = new Rectangle(this); final int sw = Random.nextInt(newRegion.width / 8) * 8; final int sh = Random.nextInt(newRegion.height / 8) * 8; if ((sw > 32) || (sh > 32)) System.out.println("error"); final Rectangle r1 = new Rectangle(x, y, sw, sh); final Rectangle r2 = new Rectangle(x + sw, y, width - sw, sh); final Rectangle r3 = new Rectangle(x, y + sh, sw, height - sh); final Rectangle r4 = new Rectangle(x + sw, y + sh, width - sw, height - sh); if (!r1.isEmpty()) result.add(new SpriteCell(r1, opt)); if (!r2.isEmpty()) result.add(new SpriteCell(r2, opt)); if (!r3.isEmpty()) result.add(new SpriteCell(r3, opt)); if (!r4.isEmpty()) result.add(new SpriteCell(r4, opt)); return result; } public double getScore() { return getBaseScore() + (getCoverageInv() / 100d); } public double getBaseScore() { switch (opt) { default: case BALANCED: return (numTile / 25d) + (1d / 10d); case MIN_SPRITE: return (numTile / 50d) + (1d / 5d); case MIN_TILE: return (numTile / 10d) + (1d / 25d); } // return (1 / 10d); // return (numTile / 20d) + (1 / 8d) + ((region.width / 8) / 10d); // return (numTile / 20d) + (1 / 8d); // return (numTile / 20d) + (1 / 50d); // return (numTile / 20d); // return (numTile / 20d) + (1 / 10d); } public double getCoverage() { if (coveredPix == -1) return 0d; return (double) coveredPix / (double) (numTile * 64); } public double getCoverageInv() { return 1d - getCoverage(); } @Override public int compareTo(SpriteCell o) { return java.lang.Double.compare(getScore(), o.getScore()); } @Override public String toString() { return "[" + x + "," + y + "-" + width + "," + height + "] cov= " + (int) (getCoverage() * 100d) + "%"; } public static SpriteCell optimizePosition(byte[] image, Dimension imageDim, SpriteCell spr) { final Rectangle imageBounds = new Rectangle(imageDim); Rectangle region = new Rectangle(spr); // optimize on right while (!ImageUtil.hasOpaquePixelOnEdge(image, imageDim, region, false, false, true, false) && region.intersects(imageBounds)) region.x // optimize on bottom while (!ImageUtil.hasOpaquePixelOnEdge(image, imageDim, region, false, false, false, true) && region.intersects(imageBounds)) region.y // optimize on left while (!ImageUtil.hasOpaquePixelOnEdge(image, imageDim, region, true, false, false, false) && region.intersects(imageBounds)) region.x++; // optimize on top while (!ImageUtil.hasOpaquePixelOnEdge(image, imageDim, region, false, true, false, false) && region.intersects(imageBounds)) region.y++; return new SpriteCell(region, spr.opt); } public static SpriteCell optimizeSize(byte[] image, Dimension imageDim, SpriteCell spr) { Rectangle region = new Rectangle(spr); final int coveredPixel = ImageUtil.getOpaquePixelCount(image, imageDim, region); // don't need sprite here if (coveredPixel == 0) return null; // optimize on left do { region.x += 8; region.width -= 8; } while ((region.width > 0) && (ImageUtil.getOpaquePixelCount(image, imageDim, region) == coveredPixel)); // restore last change region.x -= 8; region.width += 8; // optimize on top do { region.y += 8; region.height -= 8; } while ((region.height > 0) && (ImageUtil.getOpaquePixelCount(image, imageDim, region) == coveredPixel)); // restore last change region.y -= 8; region.height += 8; // optimize on right do region.width -= 8; while ((region.width > 0) && (ImageUtil.getOpaquePixelCount(image, imageDim, region) == coveredPixel)); region.width += 8; // optimize on bottom do region.height -= 8; while ((region.height > 0) && (ImageUtil.getOpaquePixelCount(image, imageDim, region) == coveredPixel)); region.height += 8; return new SpriteCell(region, spr.opt); } /** * Try to optimize the input position / size part depending the given intersecting parts list */ public static SpriteCell optimizeSpritePart(SpriteCell part, List<SpriteCell> intersectingParts) { final Area area = new Area(part); for (SpriteCell sp : intersectingParts) area.subtract(new Area(sp)); // get area bounds final Rectangle bounds = area.getBounds(); // align size on 8 bounds.setBounds(bounds.x, bounds.y, ((bounds.width + 7) / 8) * 8, ((bounds.height + 7) / 8) * 8); return new SpriteCell(bounds, part.opt); } /** * Fix cell position (cannot be negative) */ public static SpriteCell fixPosition(Dimension imageDim, SpriteCell spr) { Rectangle region = new Rectangle(spr); // fix on right if (region.getMaxX() > imageDim.getWidth()) region.x -= region.getMaxX() - imageDim.getWidth(); // fix on bottom if (region.getMaxY() > imageDim.getHeight()) region.y -= region.getMaxY() - imageDim.getHeight(); // fix on left if (region.x < 0) region.x = 0; // fix on top if (region.y < 0) region.y = 0; return new SpriteCell(region, spr.opt); } }
package ca.cumulonimbus.pressurenetsdk; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONObject; import android.content.Context; import android.location.Location; import android.os.AsyncTask; import android.os.Message; import android.os.Messenger; /** * Make pressureNET Live API calls and manage the results locally * * @author jacob * */ public class CbApi { Context context; String apiServerURL = "https://pressurenet.cumulonimbus.ca/list/?"; String apiConditionsServerURL = "https://pressurenet.cumulonimbus.ca/conditions/list/?"; private CbDb db; private CbApiCall apiCall; private ArrayList<CbWeather> callResults = new ArrayList<CbWeather>(); private Messenger replyResult = null; private CbService caller; /** * Make an API call and store the results * * @return */ public long makeAPICall(CbApiCall call, CbService caller, Messenger ms) { this.replyResult = ms; this.caller = caller; apiCall = call; APIDataDownload api = new APIDataDownload(); api.setReplyToApp(ms); api.execute(""); return System.currentTimeMillis(); } /** * When an API call finishes we'll have an ArrayList of results. Save them * into the database * * @param results * @return */ private boolean saveAPIResults(ArrayList<CbWeather> results) { db.open(); System.out.println("saving api results..."); if(results.size()> 0) { db.addWeatherArrayList(results); } db.close(); return false; } public CbApi(Context ctx) { context = ctx; db = new CbDb(context); } private class APIDataDownload extends AsyncTask<String, String, String> { Messenger replyToApp = null; public Messenger getReplyToApp() { return replyToApp; } public void setReplyToApp(Messenger replyToApp) { this.replyToApp = replyToApp; } @Override protected String doInBackground(String... arg0) { String responseText = ""; try { DefaultHttpClient client = new DefaultHttpClient(); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("min_lat", apiCall.getMinLat() + "" + "")); nvps.add(new BasicNameValuePair("max_lat", apiCall.getMaxLat() + "" + "")); nvps.add(new BasicNameValuePair("min_lon", apiCall.getMinLon() + "" + "")); nvps.add(new BasicNameValuePair("max_lon", apiCall.getMaxLon() + "" + "")); nvps.add(new BasicNameValuePair("start_time", apiCall .getStartTime() + "")); nvps.add(new BasicNameValuePair("end_time", apiCall .getEndTime() + "")); nvps.add(new BasicNameValuePair("api_key", apiCall.getApiKey())); nvps.add(new BasicNameValuePair("format", apiCall.getFormat())); nvps.add(new BasicNameValuePair("limit", apiCall.getLimit() + "")); nvps.add(new BasicNameValuePair("global", apiCall.isGlobal() + "")); nvps.add(new BasicNameValuePair("since_last_call", apiCall .isSinceLastCall() + "")); String paramString = URLEncodedUtils.format(nvps, "utf-8"); String serverURL = apiServerURL; System.out.println("CALLING " + apiCall.getCallType()); if (apiCall.getCallType().equals("Readings")) { serverURL = apiServerURL; } else { serverURL = apiConditionsServerURL; } serverURL = serverURL + paramString; System.out.println("cbservice api sending " + serverURL); HttpGet get = new HttpGet(serverURL); // Execute the GET call and obtain the response HttpResponse getResponse = client.execute(get); HttpEntity responseEntity = getResponse.getEntity(); System.out.println("response " + responseEntity.getContentLength()); BufferedReader r = new BufferedReader(new InputStreamReader( responseEntity.getContent())); StringBuilder total = new StringBuilder(); String line; if (r != null) { while ((line = r.readLine()) != null) { total.append(line); } responseText = total.toString(); } } catch (Exception e) { System.out.println("api error"); e.printStackTrace(); } return responseText; } protected void onPostExecute(String result) { callResults = processJSONResult(result); saveAPIResults(callResults); System.out.println("saved " + callResults.size() + " api call results"); caller.notifyAPIResult(replyToApp, callResults.size()); } } /** * Take a JSON string and return the data in a useful structure * * @param resultJSON */ private ArrayList<CbWeather> processJSONResult(String resultJSON) { ArrayList<CbWeather> obsFromJSON = new ArrayList<CbWeather>(); System.out.println("processing json result for call type " + apiCall.getCallType()); try { JSONArray jsonArray = new JSONArray(resultJSON); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); try { if(apiCall.getCallType().equals("Readings")) { CbObservation singleObs = new CbObservation(); Location location = new Location("network"); location.setLatitude(jsonObject.getDouble("latitude")); location.setLongitude(jsonObject.getDouble("longitude")); location.setAccuracy((float) jsonObject .getDouble("location_accuracy")); singleObs.setLocation(location); singleObs.setTime(jsonObject.getLong("daterecorded")); singleObs.setTimeZoneOffset(jsonObject.getLong("tzoffset")); singleObs.setSharing(jsonObject.getString("sharing")); singleObs.setUser_id(jsonObject.getString("user_id")); singleObs.setObservationValue(jsonObject .getDouble("reading")); obsFromJSON.add(singleObs); } else { CbCurrentCondition current = new CbCurrentCondition(); Location location = new Location("network"); location.setLatitude(jsonObject.getDouble("latitude")); location.setLongitude(jsonObject.getDouble("longitude")); current.setLocation(location); current.setGeneral_condition(jsonObject.getString("general_condition")); current.setTime(jsonObject.getLong("daterecorded")); //current.setTzoffset(jsonObject.getInt("tzoffset")); //current.setSharing_policy(jsonObject.getString("sharing")); //current.setUser_id(jsonObject.getString("user_id")); current.setWindy(jsonObject.getString("windy")); current.setFog_thickness(jsonObject.getString("fog_thickness")); current.setWindy(jsonObject.getString("precipitation_type")); current.setWindy(jsonObject.getString("precipitation_amount")); current.setWindy(jsonObject.getString("precipitation_unit")); current.setWindy(jsonObject.getString("thunderstorm_intensity")); current.setWindy(jsonObject.getString("user_comment")); obsFromJSON.add(current); } } catch (Exception e) { e.printStackTrace(); } } // TODO: Add dates and trends prior to graphing. // ArrayList<CbObservation> detailedList = obsFromJSON = CbObservation.addTrends(obsFromJSON); } catch (Exception e) { e.printStackTrace(); } return obsFromJSON; } }
package net.sf.cglib; import java.util.*; abstract class SorterTemplate { private static final int MERGESORT_THRESHOLD = 12; private static final int QUICKSORT_THRESHOLD = 7; abstract protected void swap(int i, int j); abstract protected int compare(int i, int j); protected void quickSort(int lo, int hi) { quickSortHelper(lo, hi); insertionSort(lo, hi); } private void quickSortHelper(int lo, int hi) { for (;;) { int diff = hi - lo; if (diff <= QUICKSORT_THRESHOLD) { break; } int i = (hi + lo) / 2; if (compare(lo, i) > 0) { swap(lo, i); } if (compare(lo, hi) > 0) { swap(lo, hi); } if (compare(i, hi) > 0) { swap(i, hi); } int j = hi - 1; swap(i, j); i = lo; int v = j; for (;;) { while (compare(++i, v) < 0) { /* nothing */; } while (compare(--j, v) > 0) { /* nothing */; } if (j < i) { break; } swap(i, j); } swap(i, hi - 1); if (j - lo <= hi - i + 1) { quickSortHelper(lo, j); lo = i + 1; } else { quickSortHelper(i + 1, hi); hi = j; } } } private void insertionSort(int lo, int hi) { for (int i = lo + 1 ; i <= hi; i++) { for (int j = i; j > lo; j if (compare(j - 1, j) > 0) { swap(j - 1, j); } else { break; } } } } protected void mergeSort(int lo, int hi) { int diff = hi - lo; if (diff <= MERGESORT_THRESHOLD) { insertionSort(lo, hi); return; } int mid = lo + diff / 2; mergeSort(lo, mid); mergeSort(mid, hi); merge(lo, mid, hi, mid - lo, hi - mid); } private void merge(int lo, int pivot, int hi, int len1, int len2) { if (len1 == 0 || len2 == 0) { return; } if (len1 + len2 == 2) { if (compare(pivot, lo) < 0) { swap(pivot, lo); } return; } int first_cut, second_cut; int len11, len22; if (len1 > len2) { len11 = len1 / 2; first_cut = lo + len11; second_cut = lower(pivot, hi, first_cut); len22 = second_cut - pivot; } else { len22 = len2 / 2; second_cut = pivot + len22; first_cut = upper(lo, pivot, second_cut); len11 = first_cut - lo; } rotate(first_cut, pivot, second_cut); int new_mid = first_cut + len22; merge(lo, first_cut, new_mid, len11, len22); merge(new_mid, second_cut, hi, len1 - len11, len2 - len22); } private void rotate(int lo, int mid, int hi) { int lot = lo; int hit = mid - 1; while (lot < hit) { swap(lot++, hit } lot = mid; hit = hi - 1; while (lot < hit) { swap(lot++, hit } lot = lo; hit = hi - 1; while (lot < hit) { swap(lot++, hit } } private int lower(int lo, int hi, int val) { int len = hi - lo; while (len > 0) { int half = len / 2; int mid= lo + half; if (compare(mid, val) < 0) { lo = mid + 1; len = len - half -1; } else { len = half; } } return lo; } private int upper(int lo, int hi, int val) { int len = hi - lo; while (len > 0) { int half = len / 2; int mid = lo + half; if (compare(val, mid) < 0) { len = half; } else { lo = mid + 1; len = len - half -1; } } return lo; } }
package com.intellij.openapi.extensions.impl; import com.intellij.openapi.Disposable; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.extensions.*; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.EmptyRunnable; import com.intellij.openapi.util.Pair; import com.intellij.util.ArrayUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.OpenTHashSet; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import org.picocontainer.ComponentAdapter; import org.picocontainer.PicoContainer; import java.util.*; import java.util.function.BiPredicate; import java.util.function.Predicate; import java.util.stream.Stream; /** * @author AKireyev */ @SuppressWarnings({"SynchronizeOnThis", "NonPrivateFieldAccessedInSynchronizedContext"}) public abstract class ExtensionPointImpl<T> implements ExtensionPoint<T> { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.extensions.impl.ExtensionPointImpl"); // test-only private static Set<ExtensionPointImpl<?>> POINTS_IN_READONLY_MODE; private final String myName; private final String myClassName; private volatile List<T> myExtensionsCache; // but instead returns Object[], so, we cannot use toArray() anymore. @Nullable private volatile T[] myExtensionsCacheAsArray; protected final ExtensionsAreaImpl myOwner; private final PluginDescriptor myDescriptor; // guarded by this @NotNull protected List<ExtensionComponentAdapter> myAdapters = Collections.emptyList(); @SuppressWarnings("unchecked") @NotNull // guarded by this private ExtensionPointListener<T>[] myListeners = ExtensionPointListener.EMPTY_ARRAY; @Nullable protected Class<T> myExtensionClass; ExtensionPointImpl(@NotNull String name, @NotNull String className, @NotNull ExtensionsAreaImpl owner, @NotNull PluginDescriptor pluginDescriptor) { myName = name; myClassName = className; myOwner = owner; myDescriptor = pluginDescriptor; } @NotNull @Override public String getName() { return myName; } @Override public AreaInstance getArea() { return myOwner.getAreaInstance(); } @NotNull @Override public String getClassName() { return myClassName; } @Override public void registerExtension(@NotNull T extension) { registerExtension(extension, LoadingOrder.ANY, null); } @Override public void registerExtension(@NotNull T extension, @NotNull LoadingOrder order) { registerExtension(extension, order, null); } @Override public void registerExtension(@NotNull T extension, @NotNull Disposable parentDisposable) { registerExtension(extension, LoadingOrder.ANY, parentDisposable); } @NotNull final PluginDescriptor getDescriptor() { return myDescriptor; } // extension will be not part of pico container @Override public synchronized void registerExtension(@NotNull T extension, @NotNull LoadingOrder order, @Nullable Disposable parentDisposable) { checkReadOnlyMode(); checkExtensionType(extension, null); for (ExtensionComponentAdapter adapter : myAdapters) { if (adapter instanceof ObjectComponentAdapter && ((ObjectComponentAdapter)adapter).myComponentInstance == extension) { LOG.error("Extension was already added: " + extension); return; } } ObjectComponentAdapter<T> adapter = new ObjectComponentAdapter<>(extension, order); registerExtensionAdapter(adapter); notifyListenersOnAdd(extension, adapter.getPluginDescriptor(), myListeners); if (parentDisposable == null) { return; } Disposer.register(parentDisposable, new Disposable() { @Override public void dispose() { synchronized (ExtensionPointImpl.this) { List<ExtensionComponentAdapter> list = myAdapters; int index = ContainerUtil.indexOfIdentity(list, adapter); if (index < 0) { LOG.error("Extension to be removed not found: " + adapter.myComponentInstance); } list.remove(index); clearCache(); notifyListenersOnRemove(adapter.myComponentInstance, adapter.getPluginDescriptor(), myListeners); } } }); } /** * There are valid cases where we need to register a lot of extensions programmatically, * e.g. see SqlDialectTemplateRegistrar, so, special method for bulk insertion is introduced. */ public synchronized void registerExtensions(@NotNull List<? extends T> extensions) { for (ExtensionComponentAdapter adapter : myAdapters) { if (adapter instanceof ObjectComponentAdapter) { Object instance = ((ObjectComponentAdapter)adapter).myComponentInstance; if (ContainerUtil.containsIdentity(extensions, instance)) { LOG.error("Extension was already added: " + instance); return; } } } int firstIndex = findInsertionIndexForAnyOrder(); int index = firstIndex; if (myAdapters == Collections.<ExtensionComponentAdapter>emptyList()) { myAdapters = new ArrayList<>(); } for (T extension : extensions) { myAdapters.add(index++, new ObjectComponentAdapter<>(extension, LoadingOrder.ANY)); } clearCache(); for (int i = firstIndex; i < index; i++) { //noinspection unchecked notifyListenersOnAdd(((ObjectComponentAdapter<T>)myAdapters.get(i)).myComponentInstance, null, myListeners); } } private synchronized int findInsertionIndexForAnyOrder() { int index = myAdapters.size(); while (index > 0) { ExtensionComponentAdapter lastAdapter = myAdapters.get(index - 1); if (lastAdapter.getOrder() == LoadingOrder.LAST) { index } else { break; } } return index; } private synchronized void checkExtensionType(@NotNull T extension, @Nullable ExtensionComponentAdapter adapter) { Class<T> extensionClass = getExtensionClass(); if (!extensionClass.isInstance(extension)) { String message = "Extension " + extension.getClass() + " does not implement " + extensionClass; if (adapter != null) { message += ". It came from " + adapter; } throw new RuntimeException(message); } } private void notifyListenersOnAdd(@NotNull T extension, @Nullable PluginDescriptor pluginDescriptor, @NotNull ExtensionPointListener<T>[] listeners) { for (ExtensionPointListener<T> listener : listeners) { try { listener.extensionAdded(extension, pluginDescriptor); } catch (ProcessCanceledException e) { throw e; } catch (Throwable e) { LOG.error(e); } } } @NotNull @Override public List<T> getExtensionList() { List<T> result = myExtensionsCache; if (result == null) { synchronized (this) { result = myExtensionsCache; if (result == null) { T[] array = processAdapters(); myExtensionsCacheAsArray = array; result = array.length == 0 ? Collections.emptyList() : ContainerUtil.immutableList(array); myExtensionsCache = result; } } } return result; } @Override @NotNull public T[] getExtensions() { T[] array = myExtensionsCacheAsArray; if (array == null) { synchronized (this) { array = myExtensionsCacheAsArray; if (array == null) { myExtensionsCacheAsArray = array = processAdapters(); myExtensionsCache = array.length == 0 ? Collections.emptyList() : ContainerUtil.immutableList(array); } } } return array.length == 0 ? array : array.clone(); } @NotNull @Override public Stream<T> extensions() { return getExtensionList().stream(); } @Override public boolean hasAnyExtensions() { final List<T> cache = myExtensionsCache; if (cache != null) { return !cache.isEmpty(); } synchronized (this) { return myAdapters.size() > 0; } } private boolean processingAdaptersNow; // guarded by this @NotNull private synchronized T[] processAdapters() { if (processingAdaptersNow) { throw new IllegalStateException("Recursive processAdapters() detected. You must have called 'getExtensions()' from within your extension constructor - don't. Either pass extension via constructor parameter or call getExtensions() later."); } checkReadOnlyMode(); int totalSize = myAdapters.size(); Class<T> extensionClass = getExtensionClass(); T[] result = ArrayUtil.newArray(extensionClass, totalSize); if (totalSize == 0) { return result; } // check before to avoid any "restore" work if already cancelled CHECK_CANCELED.run(); processingAdaptersNow = true; try { List<ExtensionComponentAdapter> adapters = myAdapters; LoadingOrder.sort(adapters); OpenTHashSet<T> duplicates = new OpenTHashSet<>(adapters.size()); ExtensionPointListener<T>[] listeners = myListeners; int extensionIndex = 0; //noinspection ForLoopReplaceableByForEach for (int i = 0; i < adapters.size(); i++) { ExtensionComponentAdapter adapter = adapters.get(i); try { boolean isNotifyThatAdded = listeners.length != 0 && !adapter.isInstanceCreated(); // do not call CHECK_CANCELED here in loop because it is called by createInstance() @SuppressWarnings("unchecked") T extension = (T)adapter.createInstance(myOwner.getPicoContainer()); if (!duplicates.add(extension)) { T duplicate = duplicates.get(extension); LOG.error("Duplicate extension found: " + extension + "; " + " Prev extension: " + duplicate + ";\n" + " Adapter: " + adapter + ";\n" + " Extension class: " + getExtensionClass() + ";\n" + " result:" + Arrays.asList(result)); } else { checkExtensionType(extension, adapter); // registerExtension can throw error for not correct extension, so, add to result only if call successful result[extensionIndex++] = extension; if (isNotifyThatAdded) { notifyListenersOnAdd(extension, adapter.getPluginDescriptor(), listeners); } } } catch (ExtensionNotApplicableException ignore) { if (LOG.isDebugEnabled()) { LOG.debug(adapter + " not loaded because it reported that not applicable"); } } catch (ProcessCanceledException e) { throw e; } catch (Throwable e) { LOG.error(e); } } if (extensionIndex != result.length) { result = Arrays.copyOf(result, extensionIndex); } return result; } finally { processingAdaptersNow = false; } } // used in upsource // remove extensions for which implementation class is not available public synchronized void removeUnloadableExtensions() { List<ExtensionComponentAdapter> adapters = myAdapters; for (int i = adapters.size() - 1; i >= 0; i ExtensionComponentAdapter adapter = adapters.get(i); try { adapter.getImplementationClass(); } catch (Throwable e) { removeAdapter(adapter, i); clearCache(); } } } @Override @Nullable public T getExtension() { List<T> extensions = getExtensionList(); return extensions.isEmpty() ? null : extensions.get(0); } @Override public synchronized boolean hasExtension(@NotNull T extension) { // method is deprecated and used only by one external plugin, ignore not efficient implementation return ContainerUtil.containsIdentity(getExtensionList(), extension); } /** * Put extension point in read-only mode and replace existing extensions by supplied. * For tests this method is more preferable than {@link #checkExtensionType} because makes registration more isolated and strict * (no one can modify extension point until `parentDisposable` is not disposed). * * Please use {@link com.intellij.testFramework.PlatformTestUtil#maskExtensions(ExtensionPointName, List, Disposable)} instead of direct usage. */ @SuppressWarnings("JavadocReference") @TestOnly public synchronized void maskAll(@NotNull List<T> list, @NotNull Disposable parentDisposable) { if (POINTS_IN_READONLY_MODE == null) { //noinspection AssignmentToStaticFieldFromInstanceMethod POINTS_IN_READONLY_MODE = ContainerUtil.newIdentityTroveSet(); } else { checkReadOnlyMode(); } List<T> oldList = myExtensionsCache; T[] oldArray = myExtensionsCacheAsArray; // any read access will use supplied list, any write access can lead to unpredictable results - asserted in clearCache myExtensionsCache = list; myExtensionsCacheAsArray = list.toArray(ArrayUtil.newArray(getExtensionClass(), 0)); POINTS_IN_READONLY_MODE.add(this); if (oldList != null) { for (T extension : oldList) { notifyListenersOnRemove(extension, null, myListeners); } } for (T extension : list) { notifyListenersOnAdd(extension, null, myListeners); } Disposer.register(parentDisposable, new Disposable() { @Override public void dispose() { synchronized (this) { POINTS_IN_READONLY_MODE.remove(ExtensionPointImpl.this); myExtensionsCache = oldList; myExtensionsCacheAsArray = oldArray; for (T extension : list) { notifyListenersOnRemove(extension, null, myListeners); } if (oldList != null) { for (T extension : oldList) { notifyListenersOnAdd(extension, null, myListeners); } } } } }); } @Override public synchronized void unregisterExtensions(@NotNull Predicate<T> filter) { List<T> extensions = getExtensionList(); List<ExtensionComponentAdapter> loadedAdapters = myAdapters; ExtensionPointListener<T>[] listeners = myListeners; List<Pair<T, PluginDescriptor>> removed = listeners.length == 0 ? null : new ArrayList<>(); for (int i = loadedAdapters.size() - 1; i >= 0; i T extension = extensions.get(i); if (filter.test(extension)) { continue; } ExtensionComponentAdapter adapter = loadedAdapters.remove(i); if (removed != null) { removed.add(new Pair<>(extension, adapter.getPluginDescriptor())); } } clearCache(); if (removed != null) { for (Pair<T, PluginDescriptor> pair : removed) { notifyListenersOnRemove(pair.first, pair.second, listeners); } } } @Override public synchronized void unregisterExtension(@NotNull T extension) { T[] extensions = myExtensionsCacheAsArray; List<ExtensionComponentAdapter> adapters = myAdapters; for (int i = 0; i < adapters.size(); i++) { ExtensionComponentAdapter adapter = adapters.get(i); if (adapter instanceof ObjectComponentAdapter) { if (((ObjectComponentAdapter)adapter).myComponentInstance != extension) { continue; } } else if (extensions == null || extensions[i] != extension) { continue; } adapters.remove(i); clearCache(); notifyListenersOnRemove(extension, adapter.getPluginDescriptor(), myListeners); return; } // there is a possible case that particular extension was replaced in particular environment, e.g. Upsource // replaces some IntelliJ extensions (important for CoreApplicationEnvironment), so, just log as error instead of throw error LOG.warn("Extension to be removed not found: " + extension); } @Override public void unregisterExtension(@NotNull Class<? extends T> extensionClass) { String classNameToUnregister = extensionClass.getCanonicalName(); if (!unregisterExtensions((className, adapter) -> !className.equals(classNameToUnregister), /* stopAfterFirstMatch = */ true)) { LOG.warn("Extension to be removed not found: " + extensionClass); } } @Override public synchronized boolean unregisterExtensions(@NotNull BiPredicate<String, ExtensionComponentAdapter> extensionClassFilter, boolean stopAfterFirstMatch) { boolean found = false; for (int i = myAdapters.size() - 1; i >= 0; i ExtensionComponentAdapter adapter = myAdapters.get(i); if (extensionClassFilter.test(adapter.getAssignableToClassName(), adapter)) { continue; } removeAdapter(adapter, i); clearCache(); if (stopAfterFirstMatch) { return true; } else { found = true; } } return found; } private void notifyListenersOnRemove(@NotNull T extensionObject, @Nullable PluginDescriptor pluginDescriptor, @NotNull ExtensionPointListener<T>[] listeners) { for (ExtensionPointListener<T> listener : listeners) { try { listener.extensionRemoved(extensionObject, pluginDescriptor); } catch (Throwable e) { LOG.error(e); } } } @Override public synchronized void addExtensionPointListener(@NotNull ExtensionPointListener<T> listener, boolean invokeForLoadedExtensions, @Nullable Disposable parentDisposable) { if (invokeForLoadedExtensions) { addExtensionPointListener(listener); } else { addListener(listener); } if (parentDisposable != null) { Disposer.register(parentDisposable, () -> removeExtensionPointListener(listener)); } } // true if added private synchronized boolean addListener(@NotNull ExtensionPointListener<T> listener) { if (ArrayUtil.indexOf(myListeners, listener) != -1) return false; //noinspection unchecked myListeners = ArrayUtil.append(myListeners, listener, n-> n == 0 ? ExtensionPointListener.EMPTY_ARRAY : new ExtensionPointListener[n]); return true; } @SuppressWarnings("UnusedReturnValue") private synchronized boolean removeListener(@NotNull ExtensionPointListener<T> listener) { if (ArrayUtil.indexOf(myListeners, listener) == -1) return false; //noinspection unchecked myListeners = ArrayUtil.remove(myListeners, listener, n-> n == 0 ? ExtensionPointListener.EMPTY_ARRAY : new ExtensionPointListener[n]); return true; } @Override public synchronized void addExtensionPointListener(@NotNull ExtensionPointListener<T> listener) { // old contract - "on add point listener, instantiate all point extensions and call listeners for all loaded" getExtensionList(); if (addListener(listener)) { notifyListenersAboutLoadedExtensions(myAdapters, listener, false); } } @Override public void removeExtensionPointListener(@NotNull ExtensionPointListener<T> listener) { removeListener(listener); } @Override public synchronized void reset() { List<ExtensionComponentAdapter> adapters = myAdapters; myAdapters = Collections.emptyList(); notifyListenersAboutLoadedExtensions(adapters, null, true); clearCache(); } private synchronized void notifyListenersAboutLoadedExtensions(@NotNull List<ExtensionComponentAdapter> loadedAdapters, @Nullable ExtensionPointListener<T> onlyListener, boolean isRemoved) { ExtensionPointListener<T>[] listeners = myListeners; if (listeners.length == 0) { return; } T[] extensions = myExtensionsCacheAsArray; for (int i = 0, size = loadedAdapters.size(); i < size; i++) { ExtensionComponentAdapter adapter = loadedAdapters.get(i); T extension; if (adapter instanceof ObjectComponentAdapter) { //noinspection unchecked extension = ((ObjectComponentAdapter<T>)adapter).myComponentInstance; } else if (extensions == null) { continue; } else { extension = extensions[i]; } if (isRemoved) { if (onlyListener == null) { notifyListenersOnRemove(extension, adapter.getPluginDescriptor(), listeners); } else { onlyListener.extensionRemoved(extension, adapter.getPluginDescriptor()); } } else { if (onlyListener == null) { notifyListenersOnAdd(extension, adapter.getPluginDescriptor(), listeners); } else { onlyListener.extensionAdded(extension, adapter.getPluginDescriptor()); } } } } @NotNull @Override public Class<T> getExtensionClass() { // racy single-check: we don't care whether the access to 'myExtensionClass' is thread-safe // but initial store in a local variable is crucial to prevent instruction reordering Class<T> extensionClass = myExtensionClass; if (extensionClass == null) { try { ClassLoader pluginClassLoader = myDescriptor.getPluginClassLoader(); @SuppressWarnings("unchecked") Class<T> extClass = (Class<T>)(pluginClassLoader == null ? Class.forName(myClassName) : Class.forName(myClassName, true, pluginClassLoader)); myExtensionClass = extensionClass = extClass; } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } return extensionClass; } @Override public String toString() { return getName(); } // private, internal only for tests synchronized void registerExtensionAdapter(@NotNull ExtensionComponentAdapter adapter) { if (myAdapters == Collections.<ExtensionComponentAdapter>emptyList()) { myAdapters = new ArrayList<>(); } myAdapters.add(adapter); clearCache(); } private synchronized void clearCache() { myExtensionsCache = null; myExtensionsCacheAsArray = null; // asserted here because clearCache is called on any write action checkReadOnlyMode(); } private void checkReadOnlyMode() { if (isInReadOnlyMode()) { throw new IllegalStateException(this + " in a read-only mode and cannot be modified"); } } private synchronized void removeAdapter(@NotNull ExtensionComponentAdapter adapter, int index) { if (adapter instanceof ComponentAdapter) { myOwner.getPicoContainer().unregisterComponent(((ComponentAdapter)adapter).getComponentKey()); } myAdapters.remove(index); T extensionInstance; // it is not optimization - ObjectComponentAdapter must be checked explicitly because there is a chance that adapters were not yet processed, // but adapter was registered explicitly (and so, already initialized and we must call `extensionRemoved` for this instance) if (adapter instanceof ExtensionPointImpl.ObjectComponentAdapter) { //noinspection unchecked extensionInstance = (T)((ObjectComponentAdapter)adapter).myComponentInstance; } else { T[] array = myExtensionsCacheAsArray; if (array == null) { return; } else { extensionInstance = array[index]; } } notifyListenersOnRemove(extensionInstance, adapter.getPluginDescriptor(), myListeners); } @NotNull protected abstract ExtensionComponentAdapter createAdapter(@NotNull Element extensionElement, @NotNull PluginDescriptor pluginDescriptor); @NotNull ExtensionComponentAdapter createAndRegisterAdapter(@NotNull Element extensionElement, @NotNull PluginDescriptor pluginDescriptor) { ExtensionComponentAdapter adapter = createAdapter(extensionElement, pluginDescriptor); registerExtensionAdapter(adapter); return adapter; } @NotNull protected static ExtensionComponentAdapter doCreateAdapter(@NotNull String implementationClassName, @NotNull Element extensionElement, boolean isNeedToDeserialize, @NotNull PluginDescriptor pluginDescriptor, boolean isConstructorInjectionSupported) { String orderId = extensionElement.getAttributeValue("id"); LoadingOrder order = LoadingOrder.readOrder(extensionElement.getAttributeValue("order")); Element effectiveElement = isNeedToDeserialize ? extensionElement : null; if (isConstructorInjectionSupported) { return new XmlExtensionAdapter.ConstructorInjectionAdapter(implementationClassName, pluginDescriptor, orderId, order, effectiveElement); } else { return new XmlExtensionAdapter(implementationClassName, pluginDescriptor, orderId, order, effectiveElement); } } @TestOnly final synchronized void notifyAreaReplaced(@NotNull ExtensionsArea oldArea) { for (final ExtensionPointListener<T> listener : myListeners) { if (listener instanceof ExtensionPointAndAreaListener) { ((ExtensionPointAndAreaListener)listener).areaReplaced(oldArea); } } } private static final class ObjectComponentAdapter<T> extends ExtensionComponentAdapter { private final T myComponentInstance; private ObjectComponentAdapter(@NotNull T extension, @NotNull LoadingOrder loadingOrder) { super(extension.getClass().getName(), null, null, loadingOrder); myComponentInstance = extension; } @Override boolean isInstanceCreated() { return true; } @NotNull @Override public T createInstance(@Nullable PicoContainer container) { return myComponentInstance; } } public synchronized boolean isInReadOnlyMode() { return POINTS_IN_READONLY_MODE != null && POINTS_IN_READONLY_MODE.contains(this); } @SuppressWarnings("FieldAccessedSynchronizedAndUnsynchronized") static Runnable CHECK_CANCELED = EmptyRunnable.getInstance(); public static void setCheckCanceledAction(Runnable checkCanceled) { CHECK_CANCELED = () -> { try { checkCanceled.run(); } catch (ProcessCanceledException e) { if (!isInsideClassInitializer(e.getStackTrace())) { // otherwise ExceptionInInitializerError happens and the class is screwed forever throw e; } } }; } private static boolean isInsideClassInitializer(StackTraceElement[] trace) { //noinspection SpellCheckingInspection return Arrays.stream(trace).anyMatch(s -> "<clinit>".equals(s.getMethodName())); } }
package com.intellij.util.indexing.hash.building; import com.google.gson.Gson; import com.google.gson.stream.JsonWriter; import com.intellij.concurrency.JobLauncher; import com.intellij.openapi.application.ApplicationInfo; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.EmptyProgressIndicator; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileVisitor; import com.intellij.psi.SingleRootFileViewProvider; import com.intellij.psi.stubs.StubIndexExtension; import com.intellij.psi.stubs.StubUpdatingIndex; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.hash.ContentHashEnumerator; import com.intellij.util.indexing.FileBasedIndexExtension; import com.intellij.util.indexing.IndexInfrastructureVersion; import com.intellij.util.indexing.hash.HashBasedIndexGenerator; import com.intellij.util.indexing.hash.StubHashBasedIndexGenerator; import com.intellij.util.io.PathKt; import com.intellij.util.io.zip.JBZipEntry; import com.intellij.util.io.zip.JBZipFile; import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.io.StringWriter; import java.nio.file.Files; import java.nio.file.Path; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import java.util.zip.ZipEntry; public class IndexesExporter { private static final Logger LOG = Logger.getInstance(IndexesExporter.class); private final Project myProject; public IndexesExporter(@NotNull Project project) { myProject = project; } @NotNull public static IndexesExporter getInstance(@NotNull Project project) { return project.getService(IndexesExporter.class); } @SuppressWarnings("HardCodedStringLiteral") public void exportIndices(@NotNull List<IndexChunk> chunks, @NotNull Path out, @NotNull Path zipFile, @NotNull ProgressIndicator indicator) { Path indexRoot = PathKt.createDirectories(out.resolve("unpacked")); indicator.setIndeterminate(false); AtomicInteger idx = new AtomicInteger(); if (!JobLauncher.getInstance().invokeConcurrentlyUnderProgress(chunks, indicator, chunk -> { indicator.setText("Indexing chunk " + chunk.getName()); Path chunkRoot = indexRoot.resolve(chunk.getName()); ReadAction.run(() -> processChunkUnderReadAction(chunkRoot, chunk)); indicator.setFraction(((double) idx.incrementAndGet()) / chunks.size()); return true; })) { throw new RuntimeException("Failed to execute indexing jobs"); } zipIndexOut(indexRoot, zipFile, indicator); } public void exportIndexesChunk(@NotNull IndexChunk chunk, @NotNull Path temp, @NotNull Path zipFile) { Path chunkRoot = PathKt.createDirectories(temp.resolve("unpacked")); ReadAction.run(() -> processChunkUnderReadAction(chunkRoot, chunk)); zipIndexOut(chunkRoot, zipFile, new EmptyProgressIndicator()); } private void processChunkUnderReadAction(@NotNull Path chunkRoot, @NotNull IndexChunk chunk) { List<FileBasedIndexExtension<?, ?>> exportableFileBasedIndexExtensions = FileBasedIndexExtension .EXTENSION_POINT_NAME .extensions() .filter(ex -> ex.dependsOnFileContent()) .filter(ex -> !(ex instanceof StubUpdatingIndex)) .collect(Collectors.toList()); List<HashBasedIndexGenerator<?, ?>> fileBasedGenerators = ContainerUtil.map(exportableFileBasedIndexExtensions, ex -> getGenerator(chunkRoot, ex)); List<StubIndexExtension<?, ?>> exportableStubIndexExtensions = StubIndexExtension.EP_NAME.getExtensionList(); StubHashBasedIndexGenerator stubGenerator = new StubHashBasedIndexGenerator(chunkRoot, exportableStubIndexExtensions); List<HashBasedIndexGenerator<?, ?>> allGenerators = new ArrayList<>(fileBasedGenerators); allGenerators.add(stubGenerator); generate(chunk, allGenerators, chunkRoot); deleteEmptyIndices(fileBasedGenerators, chunkRoot.resolve("empty-indices.txt")); deleteEmptyIndices(stubGenerator.getStubGenerators(), chunkRoot.resolve("empty-stub-indices.txt")); IndexInfrastructureVersion indexInfrastructureVersion = new IndexInfrastructureVersion(exportableFileBasedIndexExtensions, exportableStubIndexExtensions); Path metadataFile = chunkRoot.resolve("metadata.json"); writeIndexVersionsMetadata(metadataFile, chunk, indexInfrastructureVersion); printStatistics(chunk, fileBasedGenerators, stubGenerator); printMetadata(metadataFile); } @NotNull public static String getOsNameForIndexVersions() { if (SystemInfo.isWindows) return "windows"; if (SystemInfo.isMac) return "mac"; if (SystemInfo.isLinux) return "linux"; throw new Error("Unknown OS. " + SystemInfo.getOsNameAndVersion()); } private static void writeIndexVersionsMetadata(@NotNull Path metadataFile, @NotNull IndexChunk indexChunk, @NotNull IndexInfrastructureVersion infrastructureVersion) { StringWriter sw = new StringWriter(); try(JsonWriter writer = new Gson().newBuilder().setPrettyPrinting().create().newJsonWriter(sw)) { writer.beginObject(); writer.name("metadata_version"); writer.value("1"); writer.name("os"); writer.value(getOsNameForIndexVersions()); writer.name("index_kind"); writer.value(indexChunk.getKind()); writer.name("index_name"); writer.value(indexChunk.getName()); writer.name("sources"); writer.beginObject(); writer.name("hash"); writer.value(indexChunk.getContentsHash()); writer.name("os"); writer.value(getOsNameForIndexVersions()); writer.endObject(); writer.name("build"); writer.beginObject(); writer.name("os"); writer.value(SystemInfo.getOsNameAndVersion()); writer.name("intellij_version"); writer.value(ApplicationInfo.getInstance().getFullVersion()); writer.name("intellij_build"); writer.value(ApplicationInfo.getInstance().getBuild().toString()); writer.name("intellij_product_code"); writer.value(ApplicationInfo.getInstance().getBuild().getProductCode()); writer.endObject(); writer.name("indexes"); writer.beginObject(); writer.name("os"); writer.value(getOsNameForIndexVersions()); //what root indexes to be included here? writer.name("versions"); writer.beginObject(); Map<String, String> allIndexVersions = new LinkedHashMap<>(); allIndexVersions.putAll(ContainerUtil.map2Map(infrastructureVersion.getFileBasedIndexVersions().entrySet(), e -> Pair.create(e.getKey(), String.valueOf(e.getValue())))); allIndexVersions.putAll(ContainerUtil.map2Map(infrastructureVersion.getStubIndexVersions().entrySet(), e -> Pair.create(e.getKey(), String.valueOf(e.getValue())))); for (Map.Entry<String, String> e : allIndexVersions.entrySet()) { writer.name(e.getKey()); writer.value(e.getValue()); } writer.endObject(); writer.endObject(); writer.endObject(); } catch (Exception e) { throw new RuntimeException("Failed to generate versions JSON. " + e.getMessage(), e); } try { PathKt.write(metadataFile, sw.toString()); } catch (IOException e) { throw new RuntimeException("Failed to write versions JSON to " + metadataFile + ". " + e.getMessage(), e); } } @NotNull private static <K, V> HashBasedIndexGenerator<K, V> getGenerator(Path chunkRoot, FileBasedIndexExtension<K, V> extension) { return new HashBasedIndexGenerator<>(extension, chunkRoot); } private static void deleteEmptyIndices(@NotNull List<HashBasedIndexGenerator<?, ?>> generators, @NotNull Path dumpEmptyIndicesNamesFile) { Set<String> emptyIndices = new TreeSet<>(); for (HashBasedIndexGenerator<?, ?> generator : generators) { if (generator.isEmpty()) { emptyIndices.add(generator.getExtension().getName().getName()); Path indexRoot = generator.getIndexRoot(); PathKt.delete(indexRoot); } } if (!emptyIndices.isEmpty()) { String emptyIndicesText = String.join("\n", emptyIndices); try { PathKt.write(dumpEmptyIndicesNamesFile, emptyIndicesText); } catch (IOException e) { throw new RuntimeException("Failed to write indexes file " + dumpEmptyIndicesNamesFile + ". " + e.getMessage(), e); } } } private static void zipIndexOut(@NotNull Path indexRoot, @NotNull Path zipFile, @NotNull ProgressIndicator indicator) { indicator.setIndeterminate(true); indicator.setText("Zipping index pack"); try (JBZipFile file = new JBZipFile(zipFile.toFile())) { Files.walk(indexRoot).forEach(p -> { if (Files.isDirectory(p)) return; String relativePath = indexRoot.relativize(p).toString(); try { JBZipEntry entry = file.getOrCreateEntry(relativePath); entry.setMethod(ZipEntry.STORED); entry.setDataFromFile(p.toFile()); } catch (IOException e) { throw new RuntimeException("Failed to add " + relativePath + " entry to the target archive. " + e.getMessage(), e); } }); } catch (Exception e) { throw new RuntimeException("Failed to generate indexes archive at " + zipFile + ". " + e.getMessage(), e); } } private void generate(@NotNull IndexChunk chunk, @NotNull Collection<HashBasedIndexGenerator<?, ?>> generators, @NotNull Path chunkOut) { try { ContentHashEnumerator hashEnumerator = new ContentHashEnumerator(chunkOut.resolve("hashes")); try { for (HashBasedIndexGenerator<?, ?> generator : generators) { generator.openIndex(); } for (VirtualFile root : chunk.getRoots()) { VfsUtilCore.visitChildrenRecursively(root, new VirtualFileVisitor<Boolean>() { @Override public boolean visitFile(@NotNull VirtualFile file) { if (!file.isDirectory() && !SingleRootFileViewProvider.isTooLargeForIntelligence(file)) { for (HashBasedIndexGenerator<?, ?> generator : generators) { generator.indexFile(file, myProject, hashEnumerator); } } return true; } }); } } finally { hashEnumerator.close(); } } catch (IOException e) { throw new RuntimeException(e); } finally { try { for (HashBasedIndexGenerator<?, ?> generator : generators) { generator.closeIndex(); } } catch (IOException e) { throw new RuntimeException(e); } } } private static void printMetadata(@NotNull Path metadataFile) { try { String text = PathKt.readText(metadataFile); LOG.warn(metadataFile.getFileName().toString() + ":\n" + text + "\n\n"); } catch (IOException e){ throw new RuntimeException("Failed to read " + metadataFile + ". " + e.getMessage(), e); } } private static void printStatistics(@NotNull IndexChunk chunk, @NotNull List<HashBasedIndexGenerator<?, ?>> fileBasedGenerators, @NotNull StubHashBasedIndexGenerator stubGenerator) { StringBuilder stats = new StringBuilder(); stats.append("Statistics for index chunk ").append(chunk.getName()).append("\n"); stats.append("File based indices (").append(fileBasedGenerators.size()).append(")").append("\n"); for (HashBasedIndexGenerator<?, ?> generator : fileBasedGenerators) { appendGeneratorStatistics(stats, generator); } Collection<HashBasedIndexGenerator<?, ?>> stubGenerators = stubGenerator.getStubGenerators(); stats.append("Stub indices (").append(stubGenerators.size()).append(")").append("\n"); for (HashBasedIndexGenerator<?, ?> generator : stubGenerators) { appendGeneratorStatistics(stats, generator); } LOG.warn("Statistics\n" + stats); } private static void appendGeneratorStatistics(@NotNull StringBuilder stringBuilder, @NotNull HashBasedIndexGenerator<?, ?> generator) { stringBuilder .append(" ") .append("Generator for ") .append(generator.getExtension().getName().getName()) .append(" indexed ") .append(generator.getIndexedFilesNumber()) .append(" files"); if (generator.isEmpty()) { stringBuilder.append(" (empty result)"); } stringBuilder.append("\n"); } }
package com.intellij.ide.ui.laf.darcula.ui; import com.intellij.ide.ui.laf.darcula.DarculaUIUtil; import com.intellij.openapi.ui.ComboBoxWithWidePopup; import com.intellij.openapi.ui.ErrorBorderCapable; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.registry.Registry; import com.intellij.ui.*; import com.intellij.util.ui.JBInsets; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.border.Border; import javax.swing.plaf.ComponentUI; import javax.swing.plaf.UIResource; import javax.swing.plaf.basic.*; import javax.swing.text.JTextComponent; import java.awt.*; import java.awt.event.*; import java.awt.geom.Path2D; import java.awt.geom.Rectangle2D; import java.awt.geom.RoundRectangle2D; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import static com.intellij.ide.ui.laf.darcula.DarculaUIUtil.*; /** * @author Konstantin Bulenkov */ public class DarculaComboBoxUI extends BasicComboBoxUI implements Border, ErrorBorderCapable { @SuppressWarnings("UnregisteredNamedColor") private static final Color NON_EDITABLE_BACKGROUND = JBColor.namedColor("ComboBox.nonEditableBackground", JBColor.namedColor("ComboBox.darcula.nonEditableBackground", new JBColor(0xfcfcfc, 0x3c3f41))); public DarculaComboBoxUI() {} @SuppressWarnings("unused") @Deprecated public DarculaComboBoxUI(JComboBox c) {} @SuppressWarnings({"MethodOverridesStaticMethodOfSuperclass", "unused"}) public static ComponentUI createUI(final JComponent c) { return new DarculaComboBoxUI(); } private KeyListener editorKeyListener; private FocusListener editorFocusListener; private PropertyChangeListener propertyListener; @Override protected void installDefaults() { super.installDefaults(); installDarculaDefaults(); } @Override protected void uninstallDefaults() { super.uninstallDefaults(); uninstallDarculaDefaults(); } protected void installDarculaDefaults() { comboBox.setBorder(this); } protected void uninstallDarculaDefaults() { comboBox.setBorder(null); } @Override protected void installListeners() { super.installListeners(); propertyListener = createPropertyListener(); comboBox.addPropertyChangeListener(propertyListener); } @Override public void uninstallListeners() { super.uninstallListeners(); if (propertyListener != null) { comboBox.removePropertyChangeListener(propertyListener); propertyListener = null; } } @Override protected ComboPopup createPopup() { if (comboBox.getClientProperty(DarculaJBPopupComboPopup.CLIENT_PROP) != null) { return new DarculaJBPopupComboPopup<Object>(comboBox); } return new CustomComboPopup(comboBox); } protected PropertyChangeListener createPropertyListener() { return e -> { if ("enabled".equals(e.getPropertyName())) { EditorTextField etf = UIUtil.findComponentOfType((JComponent)editor, EditorTextField.class); if (etf != null) { boolean enabled = e.getNewValue() == Boolean.TRUE; Color color = UIManager.getColor(enabled ? "TextField.background" : "ComboBox.disabledBackground"); etf.setBackground(color); } } }; } @Override protected JButton createArrowButton() { Color bg = comboBox.getBackground(); Color fg = comboBox.getForeground(); JButton button = new BasicArrowButton(SwingConstants.SOUTH, bg, fg, fg, fg) { @Override public void paint(Graphics g) { Graphics2D g2 = (Graphics2D)g.create(); Rectangle r = new Rectangle(getSize()); JBInsets.removeFrom(r, JBUI.insets(1, 0, 1, 1)); try { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE); g2.translate(r.x, r.y); float bw = BW.getFloat(); float lw = LW.getFloat(); float arc = COMPONENT_ARC.getFloat(); arc = arc > bw + lw ? arc - bw - lw : 0.0f; Path2D innerShape = new Path2D.Float(); innerShape.moveTo(lw, bw + lw); innerShape.lineTo(r.width - bw - lw - arc, bw + lw); innerShape.quadTo(r.width - bw - lw, bw + lw, r.width - bw - lw, bw + lw + arc); innerShape.lineTo(r.width - bw - lw, r.height - bw - lw - arc); innerShape.quadTo(r.width - bw - lw, r.height - bw - lw, r.width - bw - lw - arc, r.height - bw - lw); innerShape.lineTo(lw, r.height - bw - lw); innerShape.closePath(); g2.setColor(JBUI.CurrentTheme.Arrow.backgroundColor(comboBox.isEnabled(), comboBox.isEditable())); g2.fill(innerShape); // Paint vertical line if (comboBox.isEditable()) { g2.setColor(getOutlineColor(comboBox.isEnabled(), false)); g2.fill(new Rectangle2D.Float(0, bw + lw, LW.getFloat(), r.height - (bw + lw) * 2)); } g2.setColor(JBUI.CurrentTheme.Arrow.foregroundColor(comboBox.isEnabled())); g2.fill(getArrowShape(this)); } finally { g2.dispose(); } } @Override public Dimension getPreferredSize() { return getArrowButtonPreferredSize(comboBox); } }; button.setBorder(JBUI.Borders.empty()); button.setOpaque(false); return button; } @SuppressWarnings("unused") @Deprecated protected Color getArrowButtonFillColor(Color defaultColor) { return JBUI.CurrentTheme.Arrow.backgroundColor(comboBox.isEnabled(), comboBox.isEditable()); } @NotNull static Dimension getArrowButtonPreferredSize(@Nullable JComboBox comboBox) { Insets i = comboBox != null ? comboBox.getInsets() : getDefaultComboBoxInsets(); int height = (isCompact(comboBox) ? COMPACT_HEIGHT.get() : MINIMUM_HEIGHT.get()) + i.top + i.bottom; return new Dimension(ARROW_BUTTON_WIDTH.get() + i.left, height); } static Shape getArrowShape(Component button) { Rectangle r = new Rectangle(button.getSize()); JBInsets.removeFrom(r, JBUI.insets(1, 0, 1, 1)); int tW = JBUI.scale(9); int tH = JBUI.scale(5); int xU = (r.width - tW) / 2 - JBUI.scale(1); int yU = (r.height - tH) / 2 + JBUI.scale(1); Path2D path = new Path2D.Float(); path.moveTo(xU, yU); path.lineTo(xU + tW, yU); path.lineTo(xU + tW / 2.0f, yU + tH); path.lineTo(xU, yU); path.closePath(); return path; } @NotNull private static JBInsets getDefaultComboBoxInsets() { return JBUI.insets(3); } @Override public void paint(Graphics g, JComponent c) { Container parent = c.getParent(); if (parent != null) { g.setColor(DarculaUIUtil.isTableCellEditor(c) && editor != null ? editor.getBackground() : parent.getBackground()); g.fillRect(0, 0, c.getWidth(), c.getHeight()); } Graphics2D g2 = (Graphics2D)g.create(); Rectangle r = new Rectangle(c.getSize()); JBInsets.removeFrom(r, JBUI.insets(1)); try { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE); g2.translate(r.x, r.y); float bw = BW.getFloat(); float arc = COMPONENT_ARC.getFloat(); boolean editable = comboBox.isEnabled() && editor != null && comboBox.isEditable(); g2.setColor(editable ? editor.getBackground() : comboBox.isEnabled() ? NON_EDITABLE_BACKGROUND : UIUtil.getPanelBackground()); g2.fill(new RoundRectangle2D.Float(bw, bw, r.width - bw * 2, r.height - bw * 2, arc, arc)); } finally { g2.dispose(); } if (!comboBox.isEditable()) { checkFocus(); paintCurrentValue(g, rectangleForCurrentValue(), hasFocus); } } /** * @deprecated Use {@link DarculaUIUtil#isTableCellEditor(Component)} instead */ @Deprecated protected static boolean isTableCellEditor(JComponent c) { return DarculaUIUtil.isTableCellEditor(c); } @Override public void paintCurrentValue(Graphics g, Rectangle bounds, boolean hasFocus) { ListCellRenderer renderer = comboBox.getRenderer(); @SuppressWarnings("unchecked") Component c = renderer.getListCellRendererComponent(listBox, comboBox.getSelectedItem(), -1, false, false); c.setFont(comboBox.getFont()); c.setBackground(comboBox.isEnabled() ? NON_EDITABLE_BACKGROUND : UIUtil.getPanelBackground()); if (hasFocus && !isPopupVisible(comboBox)) { c.setForeground(listBox.getForeground()); } else { c.setForeground(comboBox.isEnabled() ? comboBox.getForeground() : JBColor.namedColor("ComboBox.disabledForeground", comboBox.getForeground())); } // paint selection in table-cell-editor mode correctly boolean changeOpaque = c instanceof JComponent && DarculaUIUtil.isTableCellEditor(comboBox) && c.isOpaque(); if (changeOpaque) { ((JComponent)c).setOpaque(false); } boolean shouldValidate = false; if (c instanceof JPanel) { shouldValidate = true; } Rectangle r = new Rectangle(bounds); Icon icon = null; Insets iPad = null; Border border = null; if (c instanceof SimpleColoredComponent) { SimpleColoredComponent cc = (SimpleColoredComponent)c; iPad = cc.getIpad(); border = cc.getBorder(); cc.setBorder(JBUI.Borders.empty()); cc.setIpad(JBUI.emptyInsets()); icon = cc.getIcon(); if (!cc.isIconOnTheRight() && icon instanceof OffsetIcon) { cc.setIcon(((OffsetIcon)icon).getIcon()); } } else if (c instanceof JLabel) { JLabel cc = (JLabel)c; border = cc.getBorder(); cc.setBorder(JBUI.Borders.empty()); icon = cc.getIcon(); if (icon instanceof OffsetIcon) { cc.setIcon(((OffsetIcon)icon).getIcon()); } } currentValuePane.paintComponent(g, c, comboBox, r.x, r.y, r.width, r.height, shouldValidate); // return opaque for combobox popup items painting if (changeOpaque) { ((JComponent)c).setOpaque(true); } if (c instanceof SimpleColoredComponent) { SimpleColoredComponent cc = (SimpleColoredComponent)c; cc.setIpad(iPad); cc.setIcon(icon); cc.setBorder(border); } else if (c instanceof JLabel) { JLabel cc = (JLabel)c; cc.setBorder(border); cc.setIcon(icon); } } @Override protected ComboBoxEditor createEditor() { ComboBoxEditor comboBoxEditor = super.createEditor(); // Reset fixed columns amount set to 9 by default if (comboBoxEditor instanceof BasicComboBoxEditor) { JTextField tf = (JTextField)comboBoxEditor.getEditorComponent(); tf.setColumns(0); } installEditorKeyListener(comboBoxEditor); return comboBoxEditor; } protected void installEditorKeyListener(@NotNull ComboBoxEditor cbe) { Component ec = cbe.getEditorComponent(); if (ec != null) { editorKeyListener = new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { process(e); } @Override public void keyReleased(KeyEvent e) { process(e); } private void process(KeyEvent e) { final int code = e.getKeyCode(); if ((code == KeyEvent.VK_UP || code == KeyEvent.VK_DOWN) && e.getModifiers() == 0) { comboBox.dispatchEvent(e); } } }; ec.addKeyListener(editorKeyListener); } } @Override public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { if (!(c instanceof JComponent)) return; Graphics2D g2 = (Graphics2D)g.create(); float bw = BW.getFloat(); Rectangle r = new Rectangle(x, y, width, height); try { checkFocus(); if (!DarculaUIUtil.isTableCellEditor(c)) { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE); JBInsets.removeFrom(r, JBUI.insets(1)); g2.translate(r.x, r.y); float lw = LW.getFloat(); float arc = COMPONENT_ARC.getFloat(); Object op = comboBox.getClientProperty("JComponent.outline"); if (comboBox.isEnabled() && op != null) { paintOutlineBorder(g2, r.width, r.height, arc, true, hasFocus, Outline.valueOf(op.toString())); } else { if (hasFocus) { paintOutlineBorder(g2, r.width, r.height, arc, true, true, Outline.focus); } Path2D border = new Path2D.Float(Path2D.WIND_EVEN_ODD); border.append(new RoundRectangle2D.Float(bw, bw, r.width - bw * 2, r.height - bw * 2, arc, arc), false); arc = arc > lw ? arc - lw : 0.0f; border.append(new RoundRectangle2D.Float(bw + lw, bw + lw, r.width - (bw + lw) * 2, r.height - (bw + lw) * 2, arc, arc), false); g2.setColor(getOutlineColor(c.isEnabled(), hasFocus)); g2.fill(border); } } else { paintCellEditorBorder(g2, c, r, hasFocus); } } finally { g2.dispose(); } } protected void checkFocus() { hasFocus = false; if (!comboBox.isEnabled()) { hasFocus = false; return; } hasFocus = hasFocus(comboBox); if (hasFocus) return; ComboBoxEditor ed = comboBox.getEditor(); if (ed != null) { hasFocus = hasFocus(ed.getEditorComponent()); } } protected static boolean hasFocus(Component c) { Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); return owner != null && SwingUtilities.isDescendingFrom(owner, c); } @Override public Insets getBorderInsets(Component c) { return DarculaUIUtil.isTableCellEditor(c) || isCompact(c) ? JBUI.insets(2, 3) : getDefaultComboBoxInsets(); } @Override public boolean isBorderOpaque() { return false; } protected Dimension getSizeWithButton(Dimension size, Dimension editorSize) { Insets i = getInsets(); Dimension abSize = arrowButton.getPreferredSize(); if (abSize == null) { abSize = JBUI.emptySize(); } if (isCompact(comboBox) && size != null) { JBInsets.removeFrom(size, padding); // don't count paddings in compact mode } int editorHeight = editorSize != null ? editorSize.height + i.top + i.bottom : 0; int editorWidth = editorSize != null ? editorSize.width + i.left + padding.left + padding.right : 0; editorWidth = Math.max(editorWidth, MINIMUM_WIDTH.get() + i.left); int width = size != null ? size.width : 0; int height = size != null ? size.height : 0; width = Math.max(editorWidth + abSize.width, width + padding.left); height = Math.max(Math.max(editorHeight, Math.max(abSize.height, height)), (isCompact(comboBox) ? COMPACT_HEIGHT.get() : MINIMUM_HEIGHT.get()) + i.top + i.bottom); return new Dimension(width, height); } @Override public Dimension getPreferredSize(JComponent c) { return getSizeWithButton(super.getMinimumSize(c), editor != null ? editor.getPreferredSize() : null); } @Override public Dimension getMinimumSize(JComponent c) { Dimension minSize = super.getMinimumSize(c); Insets i = c.getInsets(); minSize.width = MINIMUM_WIDTH.get() + ARROW_BUTTON_WIDTH.get() + i.left + i.right; return getSizeWithButton(minSize, editor != null ? editor.getMinimumSize() : null); } @Override protected void configureEditor() { super.configureEditor(); if (editor instanceof JComponent) { JComponent jEditor = (JComponent)editor; jEditor.setOpaque(false); jEditor.setBorder(JBUI.Borders.empty()); editorFocusListener = new FocusAdapter() { @Override public void focusGained(FocusEvent e) { update(); } @Override public void focusLost(FocusEvent e) { update(); } private void update() { if (comboBox != null) { comboBox.repaint(); } } }; if (editor instanceof JTextComponent) { editor.addFocusListener(editorFocusListener); } else { EditorTextField etf = UIUtil.findComponentOfType((JComponent)editor, EditorTextField.class); if (etf != null) { etf.addFocusListener(editorFocusListener); Color c = UIManager.getColor(comboBox.isEnabled() ? "TextField.background" : "ComboBox.disabledBackground"); etf.setBackground(c); } } } if (Registry.is("ide.ui.composite.editor.for.combobox")) { // BasicComboboxUI sets focusability depending on the combobox focusability. // JPanel usually is unfocusable and uneditable. // It could be set as an editor when people want to have a composite component as an editor. // In such cases we should restore unfocusable state for panels. if (editor instanceof JPanel) { editor.setFocusable(false); } } } @Override protected void unconfigureEditor() { super.unconfigureEditor(); if (editorKeyListener != null) { editor.removeKeyListener(editorKeyListener); } if (editor instanceof JTextComponent) { if (editorFocusListener != null) { editor.removeFocusListener(editorFocusListener); } } else { EditorTextField etf = UIUtil.findComponentOfType((JComponent)editor, EditorTextField.class); if (etf != null) { if (editorFocusListener != null) { etf.removeFocusListener(editorFocusListener); } } } } @Override protected LayoutManager createLayoutManager() { return new ComboBoxLayoutManager() { @Override public void layoutContainer(Container parent) { JComboBox cb = (JComboBox)parent; if (arrowButton != null) { Dimension aps = arrowButton.getPreferredSize(); if (cb.getComponentOrientation().isLeftToRight()) { arrowButton.setBounds(cb.getWidth() - aps.width, 0, aps.width, cb.getHeight()); } else { arrowButton.setBounds(0, 0, aps.width, cb.getHeight()); } } layoutEditor(); } }; } protected void layoutEditor() { if (comboBox.isEditable() && editor != null) { Rectangle er = rectangleForCurrentValue(); Dimension eps = editor.getPreferredSize(); if (eps.height < er.height) { int delta = (er.height - eps.height) / 2; er.y += delta; } er.height = eps.height; editor.setBounds(er); } } @Override protected Rectangle rectangleForCurrentValue() { Rectangle rect = new Rectangle(comboBox.getSize()); Insets i = getInsets(); JBInsets.removeFrom(rect, i); rect.width -= arrowButton != null ? (arrowButton.getWidth() - i.left) : rect.height; JBInsets.removeFrom(rect, padding); rect.width += comboBox.isEditable() ? 0 : padding.right; return rect; } // Wide popup that uses preferred size protected static class CustomComboPopup extends BasicComboPopup { public CustomComboPopup(JComboBox combo) { super(combo); } @Override protected void configurePopup() { super.configurePopup(); Border border = UIManager.getBorder("ComboPopup.border"); setBorder(border != null ? border : SystemInfo.isMac ? JBUI.Borders.empty() : IdeBorderFactory.createBorder()); putClientProperty("JComboBox.isCellEditor", DarculaUIUtil.isTableCellEditor(comboBox)); } @Override public void updateUI() { setUI(new BasicPopupMenuUI() { @Override public void uninstallDefaults() {} @Override public void installDefaults() { if (popupMenu.getLayout() == null || popupMenu.getLayout() instanceof UIResource) { popupMenu.setLayout(new DefaultMenuLayout(popupMenu, BoxLayout.Y_AXIS)); } popupMenu.setOpaque(true); LookAndFeel.installColorsAndFont(popupMenu, "PopupMenu.background", "PopupMenu.foreground", "PopupMenu.font"); } }); } @Override public void show(Component invoker, int x, int y) { if (comboBox instanceof ComboBoxWithWidePopup) { Dimension popupSize = comboBox.getSize(); int minPopupWidth = ((ComboBoxWithWidePopup)comboBox).getMinimumPopupWidth(); Insets insets = getInsets(); popupSize.width = Math.max(popupSize.width, minPopupWidth); popupSize.setSize(popupSize.width - (insets.right + insets.left), getPopupHeightForRowCount(comboBox.getMaximumRowCount())); scroller.setMaximumSize(popupSize); scroller.setPreferredSize(popupSize); scroller.setMinimumSize(popupSize); list.revalidate(); } super.show(invoker, x, y); } @Override protected void configureList() { super.configureList(); list.setBackground(UIManager.getColor("Label.background")); //noinspection unchecked list.setCellRenderer(new MyDelegateRenderer()); } protected void customizeListRendererComponent(JComponent component) { component.setBorder(JBUI.Borders.empty(2, 8)); } @Override protected PropertyChangeListener createPropertyChangeListener() { PropertyChangeListener listener = super.createPropertyChangeListener(); return new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { listener.propertyChange(evt); if ("renderer".equals(evt.getPropertyName())) { if (!(list.getCellRenderer() instanceof MyDelegateRenderer)) { //noinspection unchecked list.setCellRenderer(new MyDelegateRenderer()); } } } }; } private class MyDelegateRenderer implements ListCellRenderer { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { //noinspection unchecked Component component = comboBox.getRenderer().getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (component instanceof JComponent) { customizeListRendererComponent((JComponent)component); component.setPreferredSize(UIUtil.updateListRowHeight(component.getPreferredSize())); } return component; } } } }
package org.jboss.reddeer.jface.wizard; import static org.hamcrest.core.AllOf.allOf; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.hamcrest.Matcher; import org.jboss.reddeer.common.logging.Logger; import org.jboss.reddeer.swt.api.Button; import org.jboss.reddeer.swt.condition.JobIsRunning; import org.jboss.reddeer.swt.condition.ShellWithTextIsActive; import org.jboss.reddeer.swt.impl.button.PushButton; import org.jboss.reddeer.swt.impl.shell.DefaultShell; import org.jboss.reddeer.swt.wait.TimePeriod; import org.jboss.reddeer.swt.wait.WaitWhile; /** * A dialog where are wizard pages displayed. It can operate Next, Back, Cancel * and Finish buttons. * * @author Lucia Jelinkova * @author apodhrad * @since 0.6 * */ public class WizardDialog { protected final Logger log = Logger.getLogger(this.getClass()); protected int currentPage; protected Properties properties; protected Map<WizardPage, Matcher<WizardDialog>> wizardPageMap; public WizardDialog() { properties = new Properties(); wizardPageMap = new HashMap<WizardPage, Matcher<WizardDialog>>(); } public void setProperty(Object key, Object value) { properties.put(key, value); } public Object getProperty(Object key) { return properties.get(key); } /** * Returns a current wizard page * * @return current wizard page or null when there is not any wizard page */ public WizardPage getCurrentWizardPage() { for (WizardPage wizardPage : wizardPageMap.keySet()) { Matcher<WizardDialog> matcher = wizardPageMap.get(wizardPage); if (matcher.matches(this)) { return wizardPage; } } log.warn("No wizard page found in page index '" + currentPage + "'"); return null; } /** * Automatically lists to desired wizard page and returns it. * * @param page index of desired wizard page * @return instance of desired WizardPage */ public WizardPage getWizardPage(int pageIndex){ selectPage(pageIndex); return getCurrentWizardPage(); } /** * Adds a new wizard page * * @param page * wizard page * @param pageIndex * wizard page index */ public void addWizardPage(WizardPage page, int pageIndex) { wizardPageMap.put(page, new WizardPageIndex(pageIndex)); } /** * Adds a new wizard page * * @param page * wizard page * @param pageIndex * wizard page index * @param matcher * matcher when the wizard page will be displayed */ public void addWizardPage(WizardPage page, int pageIndex, Matcher<WizardDialog> matcher) { wizardPageMap.put(page, allOf(new WizardPageIndex(pageIndex), matcher)); } /** * Click the finish button in wizard dialog. */ public void finish() { finish(TimePeriod.LONG); } /** * Click the finish button in wizard dialog. * @param timeout to wait for wizard shell to close. */ public void finish(TimePeriod timeout) { log.info("Finish wizard"); String shellText = new DefaultShell().getText(); Button button = new PushButton("Finish"); button.click(); new WaitWhile(new ShellWithTextIsActive(shellText), timeout); new WaitWhile(new JobIsRunning(), timeout); } /** * Click the cancel button in wizard dialog. */ public void cancel() { log.info("Cancel wizard"); String shellText = new DefaultShell().getText(); new WaitWhile(new JobIsRunning()); new PushButton("Cancel").click(); new WaitWhile(new ShellWithTextIsActive(shellText)); new WaitWhile(new JobIsRunning()); } /** * Click the next button in wizard dialog. */ public void next() { log.info("Go to next wizard page"); Button button = new PushButton("Next >"); button.click(); currentPage++; } /** * Click the back button in wizard dialog. */ public void back() { log.info("Go to previous wizard page"); Button button = new PushButton("< Back"); button.click(); currentPage } /** * Go to the specific page of wizard dialog. First wizard dialog page has index 0. * @param pageIndex of desired wizard page */ public void selectPage(int pageIndex) { if (pageIndex != currentPage) { boolean goBack = pageIndex < currentPage; while (pageIndex != currentPage) { if (goBack) { back(); } else { next(); } } } } /** * Get page index of current wizard page. * @return current wizard page index */ public int getPageIndex() { return currentPage; } }
package org.slc.sli.util; import java.io.StringWriter; import com.liferay.portal.kernel.util.GetterUtil; import com.liferay.portal.kernel.util.PropsUtil; import org.slc.sli.util.PropsKeys; import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.Writer; import java.net.URISyntaxException; import javax.imageio.ImageIO; import org.apache.commons.codec.binary.Base64; public class VelocityUtil { public static String velocityHeaderRes(String headerRes) { String headervm = ""; try { InputStream in = VelocityUtil.class .getResourceAsStream("/templates/wheader.vm"); headervm = convertStreamToString(in); headervm = headervm.replace("$header", headerRes); headervm = headervm.replace( "$menu_arrow1", "data:image/png;base64," + getEncodedImg(GetterUtil.getString(PropsUtil .get(PropsKeys.MENU_ARROW)))); headervm = headervm.replace( "$arrow", "data:image/png;base64," + getEncodedImg(GetterUtil.getString(PropsUtil .get(PropsKeys.ARROW)))); headervm = headervm.replace( "$arrow_w", "data:image/png;base64," + getEncodedImg(GetterUtil.getString(PropsUtil .get(PropsKeys.ARROW_W)))); } catch (FileNotFoundException fne) { } catch (IOException ioe) { } catch (Exception e) { e.printStackTrace(); } return headervm; } public static String getEncodedImg(String imageName) throws IOException, URISyntaxException { InputStream imageIs = VelocityUtil.class.getResourceAsStream(imageName); System.out.println(imageIs); BufferedImage img = ImageIO.read(imageIs); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(img, "png", baos); baos.flush(); String encodedImage = Base64.encodeBase64String(baos.toByteArray()); InputStream is = new ByteArrayInputStream(encodedImage.getBytes()); BufferedReader bufReader = new BufferedReader(new InputStreamReader(is)); StringBuilder strBdr = new StringBuilder(); String line; while ((line = bufReader.readLine()) != null) { strBdr.append(line); } baos.close(); return strBdr.toString(); } public static String velocityFooterRes(String headerRes) { String footervm = ""; try { InputStream in = VelocityUtil.class .getResourceAsStream("/templates/wfooter.vm"); footervm = convertStreamToString(in); footervm = footervm.replace("$footer", headerRes); } catch (FileNotFoundException fne) { } catch (IOException ioe) { } catch (Exception e) { e.printStackTrace(); } return footervm; } /** * Convert the file contents to string * */ protected static String convertStreamToString(InputStream is) throws IOException { /* * To convert the InputStream to String we use the Reader.read(char[] * buffer) method. We iterate until the Reader return -1 which means * there's no more data to read. We use the StringWriter class to * produce the string. */ if (is != null) { Writer writer = new StringWriter(); char[] buffer = new char[1024]; try { Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); int n; while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } } finally { is.close(); } return writer.toString(); } else { return ""; } } }
package com.aldebaran.qi; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; import com.aldebaran.qi.serialization.MethodDescription; import com.aldebaran.qi.serialization.SignatureUtilities; /** * Utilities tools to communicate with native code (Code in C++) */ public class NativeTools { /** * Header of error message key */ private static final String ERROR_MESSAGE_HEADER = "$ERROR_MESSAGE_NativeTools_"; /** * Footer of error message key */ private static final String ERROR_MESSAGE_FOOTER = "$"; /** * Next message error ID */ private static final AtomicLong NEXT_EXCEPTION_ID = new AtomicLong(0); /** * Map of error messages stored to be get later */ private static final Map<String, Exception> ERRORS_MAP = new HashMap<String, Exception>(); /** * Get the real exception corresponding to given one.<br> * If the given exception have special message, we get our stored exception, * else return the exception itself * * @param exception Exception to get its real version * @return Real exception */ static Exception obtainRealException(Exception exception) { // Test if its a managed exception String message = exception.toString(); int start = message.indexOf(ERROR_MESSAGE_HEADER); if (start < 0) { return exception; } int end = message.indexOf(ERROR_MESSAGE_FOOTER, start + ERROR_MESSAGE_HEADER.length()); if (end < start) { return exception; } // /It is a managed exception, extract the key and get the associated // exception String key = message.substring(start, end + ERROR_MESSAGE_FOOTER.length()); Exception realException = ERRORS_MAP.get(key); if (realException == null) { return exception; } return realException; } /** * Store an exception and return a replace one to use * * @param exception Exception to store * @return Exception to use */ private static RuntimeException storeException(Exception exception) { String message = ERROR_MESSAGE_HEADER + NEXT_EXCEPTION_ID.getAndIncrement() + ERROR_MESSAGE_FOOTER; ERRORS_MAP.put(message, exception); return new RuntimeException(message+": "+exception.getMessage(), exception); } /** * Call a Java method (Generally called from JNI) * * @param instance Instance on which the method is called. * @param methodName Method name to call. * @param javaSignature Method Java signature. * @param arguments Method parameters. * @return Method result. */ public static Object callJava(final Object instance, final String methodName, final String javaSignature, final Object[] arguments) { if (instance != null) { try { MethodDescription methodDescription = MethodDescription.fromJNI(methodName, javaSignature); Class<?> claz = instance.getClass(); Method method = null; int distance = Integer.MAX_VALUE; int dist; for (Method meth : claz.getMethods()) { dist = methodDescription.distance(meth); if (dist < distance) { distance = dist; method = meth; } } if (method != null) { Class<?>[] parametersTarget = method.getParameterTypes(); for (int index = arguments.length - 1; index >= 0; index arguments[index] = SignatureUtilities.convert(arguments[index], parametersTarget[index]); } method.setAccessible(true); Object result = method.invoke(instance, arguments); Class<?> returnType = methodDescription.getReturnType(); if (void.class.equals(returnType) || Void.class.equals(returnType)) return null; return SignatureUtilities.convertValueJavaToLibQI(result, methodDescription.getReturnType()); } } catch (InvocationTargetException invocationTargetException) { // We are interested by the cause, because we want hide the // reflection/proxy part and obtain the real exception throw storeException((Exception) invocationTargetException.getCause()); } catch (Exception exception) { throw storeException(exception); } } return null; } }
package org.psjava.solutions.site; import java.io.ByteArrayInputStream; import java.io.File; import java.io.InputStream; import java.util.ArrayList; import java.util.Scanner; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.psjava.util.DataKeeper; import play.api.Play; import play.libs.F.Function0; import play.libs.F.Promise; import play.mvc.Controller; import play.mvc.Result; import views.html.*; import japa.parser.JavaParser; import japa.parser.ast.CompilationUnit; import japa.parser.ast.body.ClassOrInterfaceDeclaration; import japa.parser.ast.body.JavadocComment; import japa.parser.ast.visitor.VoidVisitorAdapter; public class SolutionsSiteController extends Controller { public static Result index() { return ok(index.render()); } public static Promise<Result> showSolution(final String siteName, final String problemId, final String title) { if (containsUpper(siteName) || containsUpper(title)) return createNotFoundPromise(); return Promise.promise(new Function0<Result>() { @Override public Result apply() throws Throwable { // damn play.. cant read the file after dist! final File zipFile = Play.getFile("public/solutions-master.zip", Play.current()); String content; ZipFile z = new ZipFile(zipFile); try { ZipEntry e = z.getEntry("solutions-master/src/main/java/org/psjava/solutions/code/" + siteName + "_" + problemId.toLowerCase() + "/" + "Main.java"); if (e == null) return notFound("unknown problem"); InputStream is = z.getInputStream(e); try { content = FileUtil.loadUTF8(is).trim(); } finally { is.close(); } } finally { z.close(); } CompilationUnit cu = JavaParser.parse(new ByteArrayInputStream(content.getBytes("UTF-8")), "UTF-8"); final DataKeeper<Boolean> ok = DataKeeper.create(false); final ArrayList<String> hints = new ArrayList<String>(); new VoidVisitorAdapter<Object>() { @Override public void visit(ClassOrInterfaceDeclaration n, Object arg) { JavadocComment doc = n.getJavaDoc(); Scanner scan = new Scanner(doc.getContent()); while (scan.hasNextLine()) { String line = scan.nextLine(); if (line.contains("@title")) { String titleInDoc = line.substring(line.indexOf("@title") + 6).trim(); String adjusted = titleInDoc.replace(' ', '-').toLowerCase(); if (adjusted.equals(title)) ok.set(true); } if (line.contains("@hint")) hints.add(line.substring(line.indexOf("@hint") + 5).trim()); } scan.close(); } }.visit(cu, null); if (ok.get()) return ok(solution.render(content, hints, siteName, problemId)); else return notFound("unknown problem"); } }); } private static boolean containsUpper(String text) { return !text.toLowerCase().equals(text); } private static Promise<Result> createNotFoundPromise() { return Promise.promise(new Function0<Result>() { @Override public Result apply() throws Throwable { return badRequest("bad request"); } }); } }
package com.facebook.presto.sql.planner; import com.facebook.presto.execution.ExchangePlanFragmentSource; import com.facebook.presto.metadata.ColumnHandle; import com.facebook.presto.metadata.FunctionHandle; import com.facebook.presto.metadata.Metadata; import com.facebook.presto.metadata.TableHandle; import com.facebook.presto.operator.AggregationOperator; import com.facebook.presto.operator.FilterAndProjectOperator; import com.facebook.presto.operator.FilterFunction; import com.facebook.presto.operator.FilterFunctions; import com.facebook.presto.operator.HashAggregationOperator; import com.facebook.presto.operator.HashJoinOperator; import com.facebook.presto.operator.InMemoryOrderByOperator; import com.facebook.presto.operator.LimitOperator; import com.facebook.presto.operator.AggregationFunctionDefinition; import com.facebook.presto.operator.Operator; import com.facebook.presto.operator.OperatorStats; import com.facebook.presto.operator.ProjectionFunction; import com.facebook.presto.operator.ProjectionFunctions; import com.facebook.presto.operator.SourceHashProvider; import com.facebook.presto.operator.SourceHashProviderFactory; import com.facebook.presto.operator.TopNOperator; import com.facebook.presto.operator.Input; import com.facebook.presto.sql.analyzer.Session; import com.facebook.presto.sql.analyzer.Symbol; import com.facebook.presto.sql.analyzer.Type; import com.facebook.presto.sql.planner.plan.AggregationNode; import com.facebook.presto.sql.planner.plan.ExchangeNode; import com.facebook.presto.sql.planner.plan.FilterNode; import com.facebook.presto.sql.planner.plan.JoinNode; import com.facebook.presto.sql.planner.plan.LimitNode; import com.facebook.presto.sql.planner.plan.OutputNode; import com.facebook.presto.sql.planner.plan.PlanNode; import com.facebook.presto.sql.planner.plan.PlanVisitor; import com.facebook.presto.sql.planner.plan.ProjectNode; import com.facebook.presto.sql.planner.plan.SortNode; import com.facebook.presto.sql.planner.plan.TableScanNode; import com.facebook.presto.sql.planner.plan.TopNNode; import com.facebook.presto.sql.tree.ComparisonExpression; import com.facebook.presto.sql.tree.Expression; import com.facebook.presto.sql.tree.FunctionCall; import com.facebook.presto.sql.tree.QualifiedNameReference; import com.facebook.presto.sql.tree.SortItem; import com.facebook.presto.tuple.FieldOrderedTupleComparator; import com.facebook.presto.tuple.TupleReadable; import com.facebook.presto.util.IterableTransformer; import com.facebook.presto.util.MoreFunctions; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Ordering; import io.airlift.units.DataSize; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.google.common.base.Functions.forMap; import static com.google.common.base.Preconditions.checkNotNull; public class LocalExecutionPlanner { private final Session session; private final Metadata metadata; private final PlanFragmentSourceProvider sourceProvider; private final Map<Symbol, Type> types; private final PlanFragmentSource split; private final Map<TableHandle, TableScanPlanFragmentSource> tableScans; private final OperatorStats operatorStats; private final Map<String, ExchangePlanFragmentSource> exchangeSources; private final SourceHashProviderFactory joinHashFactory; private final DataSize maxOperatorMemoryUsage; public LocalExecutionPlanner(Session session, Metadata metadata, PlanFragmentSourceProvider sourceProvider, Map<Symbol, Type> types, PlanFragmentSource split, Map<TableHandle, TableScanPlanFragmentSource> tableScans, Map<String, ExchangePlanFragmentSource> exchangeSources, OperatorStats operatorStats, SourceHashProviderFactory joinHashFactory, DataSize maxOperatorMemoryUsage) { this.session = checkNotNull(session, "session is null"); this.tableScans = tableScans; this.operatorStats = Preconditions.checkNotNull(operatorStats, "operatorStats is null"); this.metadata = checkNotNull(metadata, "metadata is null"); this.sourceProvider = checkNotNull(sourceProvider, "sourceProvider is null"); this.types = checkNotNull(types, "types is null"); this.split = split; this.exchangeSources = ImmutableMap.copyOf(checkNotNull(exchangeSources, "exchangeSources is null")); this.joinHashFactory = checkNotNull(joinHashFactory, "joinHashFactory is null"); this.maxOperatorMemoryUsage = Preconditions.checkNotNull(maxOperatorMemoryUsage, "maxOperatorMemoryUsage is null"); } public Operator plan(PlanNode plan) { return plan.accept(new Visitor(), null); } private class Visitor extends PlanVisitor<Void, Operator> { @Override public Operator visitExchange(ExchangeNode node, Void context) { int sourceFragmentId = node.getSourceFragmentId(); ExchangePlanFragmentSource source = exchangeSources.get(String.valueOf(sourceFragmentId)); Preconditions.checkState(source != null, "Exchange source for fragment %s was not found: available sources %s", sourceFragmentId, exchangeSources.keySet()); return sourceProvider.createDataStream(source, ImmutableList.<ColumnHandle>of()); } @Override public Operator visitOutput(OutputNode node, Void context) { PlanNode source = node.getSource(); Operator sourceOperator = plan(node.getSource()); Map<Symbol, Integer> symbolToChannelMappings = mapSymbolsToChannels(source.getOutputSymbols()); List<Symbol> resultSymbols = Lists.transform(node.getColumnNames(), forMap(node.getAssignments())); if (resultSymbols.equals(source.getOutputSymbols())) { // no need for a projection -- the output matches the result of the underlying operator return sourceOperator; } List<ProjectionFunction> projections = new ArrayList<>(); for (Symbol symbol : resultSymbols) { ProjectionFunction function = ProjectionFunctions.singleColumn(types.get(symbol).getRawType(), symbolToChannelMappings.get(symbol), 0); projections.add(function); } return new FilterAndProjectOperator(sourceOperator, FilterFunctions.TRUE_FUNCTION, projections); } @Override public Operator visitTopN(TopNNode node, Void context) { Preconditions.checkArgument(node.getOrderBy().size() == 1, "Order by multiple fields not yet supported"); Symbol orderBySymbol = Iterables.getOnlyElement(node.getOrderBy()); PlanNode source = node.getSource(); Map<Symbol, Integer> symbolToChannelMappings = mapSymbolsToChannels(source.getOutputSymbols()); List<ProjectionFunction> projections = new ArrayList<>(); for (int i = 0; i < node.getOutputSymbols().size(); i++) { Symbol symbol = node.getOutputSymbols().get(i); ProjectionFunction function = ProjectionFunctions.singleColumn(types.get(symbol).getRawType(), symbolToChannelMappings.get(symbol), 0); projections.add(function); } Ordering<TupleReadable> ordering = Ordering.from(FieldOrderedTupleComparator.INSTANCE); if (node.getOrderings().get(orderBySymbol) == SortItem.Ordering.ASCENDING) { ordering = ordering.reverse(); } return new TopNOperator(plan(source), (int) node.getCount(), symbolToChannelMappings.get(orderBySymbol), projections, ordering); } @Override public Operator visitSort(SortNode node, Void context) { PlanNode source = node.getSource(); Map<Symbol, Integer> symbolToChannelMappings = mapSymbolsToChannels(source.getOutputSymbols()); int[] outputChannels = new int[node.getOutputSymbols().size()]; for (int i = 0; i < node.getOutputSymbols().size(); i++) { Symbol symbol = node.getOutputSymbols().get(i); outputChannels[i] = symbolToChannelMappings.get(symbol); } Preconditions.checkArgument(node.getOrderBy().size() == 1, "Order by multiple fields not yet supported"); Symbol orderBySymbol = Iterables.getOnlyElement(node.getOrderBy()); int[] sortFields = new int[] { 0 }; boolean[] sortOrder = new boolean[] { node.getOrderings().get(orderBySymbol) == SortItem.Ordering.ASCENDING}; return new InMemoryOrderByOperator(plan(source), symbolToChannelMappings.get(orderBySymbol), outputChannels, 1_000_000, sortFields, sortOrder, maxOperatorMemoryUsage); } @Override public Operator visitLimit(LimitNode node, Void context) { PlanNode source = node.getSource(); return new LimitOperator(plan(source), node.getCount()); } @Override public Operator visitAggregation(AggregationNode node, Void context) { PlanNode source = node.getSource(); Operator sourceOperator = plan(source); Map<Symbol, Integer> symbolToChannelMappings = mapSymbolsToChannels(source.getOutputSymbols()); List<AggregationFunctionDefinition> functionDefinitions = new ArrayList<>(); for (Map.Entry<Symbol, FunctionCall> entry : node.getAggregations().entrySet()) { List<Input> arguments = new ArrayList<>(); for (Expression argument : entry.getValue().getArguments()) { int channel = symbolToChannelMappings.get(Symbol.fromQualifiedName(((QualifiedNameReference) argument).getName())); int field = 0; // TODO: support composite channels arguments.add(new Input(channel, field)); } FunctionHandle functionHandle = node.getFunctions().get(entry.getKey()); AggregationFunctionDefinition functionDefinition = metadata.getFunction(functionHandle).bind(arguments); functionDefinitions.add(functionDefinition); } Operator aggregationOperator; if (node.getGroupBy().isEmpty()) { aggregationOperator = new AggregationOperator(sourceOperator, node.getStep(), functionDefinitions); } else { Preconditions.checkArgument(node.getGroupBy().size() <= 1, "Only single GROUP BY key supported at this time"); Symbol groupBySymbol = Iterables.getOnlyElement(node.getGroupBy()); aggregationOperator = new HashAggregationOperator(sourceOperator, symbolToChannelMappings.get(groupBySymbol), node.getStep(), functionDefinitions, 100_000, maxOperatorMemoryUsage); } List<ProjectionFunction> projections = new ArrayList<>(); for (int i = 0; i < node.getOutputSymbols().size(); ++i) { Symbol symbol = node.getOutputSymbols().get(i); projections.add(ProjectionFunctions.singleColumn(types.get(symbol).getRawType(), i, 0)); } return new FilterAndProjectOperator(aggregationOperator, FilterFunctions.TRUE_FUNCTION, projections); } @Override public Operator visitFilter(FilterNode node, Void context) { PlanNode source = node.getSource(); Operator sourceOperator = plan(source); Map<Symbol, Integer> symbolToChannelMappings = mapSymbolsToChannels(source.getOutputSymbols()); FilterFunction filter = new InterpretedFilterFunction(node.getPredicate(), symbolToChannelMappings, metadata, session); List<ProjectionFunction> projections = new ArrayList<>(); for (int i = 0; i < node.getOutputSymbols().size(); i++) { Symbol symbol = node.getOutputSymbols().get(i); ProjectionFunction function = ProjectionFunctions.singleColumn(types.get(symbol).getRawType(), symbolToChannelMappings.get(symbol), 0); projections.add(function); } return new FilterAndProjectOperator(sourceOperator, filter, projections); } @Override public Operator visitProject(ProjectNode node, Void context) { PlanNode source = node.getSource(); Operator sourceOperator = plan(node.getSource()); Map<Symbol, Integer> symbolToChannelMappings = mapSymbolsToChannels(source.getOutputSymbols()); List<ProjectionFunction> projections = new ArrayList<>(); for (int i = 0; i < node.getExpressions().size(); i++) { Symbol symbol = node.getOutputSymbols().get(i); Expression expression = node.getExpressions().get(i); ProjectionFunction function; if (expression instanceof QualifiedNameReference) { // fast path when we know it's a direct symbol reference Symbol reference = Symbol.fromQualifiedName(((QualifiedNameReference) expression).getName()); function = ProjectionFunctions.singleColumn(types.get(reference).getRawType(), symbolToChannelMappings.get(symbol), 0); } else { function = new InterpretedProjectionFunction(types.get(symbol), expression, symbolToChannelMappings, metadata, session); } projections.add(function); } return new FilterAndProjectOperator(sourceOperator, FilterFunctions.TRUE_FUNCTION, projections); } @Override public Operator visitTableScan(TableScanNode node, Void context) { List<ColumnHandle> columns = IterableTransformer.on(node.getAssignments().entrySet()) .orderBy(Ordering.explicit(node.getOutputSymbols()).onResultOf(MoreFunctions.<Symbol, ColumnHandle>keyGetter())) .transform(MoreFunctions.<Symbol, ColumnHandle>valueGetter()) .list(); // table scan only works with a split Preconditions.checkState(split != null || tableScans != null, "This fragment does not have a split"); PlanFragmentSource tableSplit = split; if (tableSplit == null) { tableSplit = tableScans.get(node.getTable()); } Operator operator = sourceProvider.createDataStream(tableSplit, columns); return operator; } @Override public Operator visitJoin(JoinNode node, Void context) { ComparisonExpression comparison = (ComparisonExpression) node.getCriteria(); Symbol first = Symbol.fromQualifiedName(((QualifiedNameReference) comparison.getLeft()).getName()); Symbol second = Symbol.fromQualifiedName(((QualifiedNameReference) comparison.getRight()).getName()); Map<Symbol, Integer> probeMappings = mapSymbolsToChannels(node.getLeft().getOutputSymbols()); Map<Symbol, Integer> buildMappings = mapSymbolsToChannels(node.getRight().getOutputSymbols()); int probeChannel; int buildChannel; if (node.getLeft().getOutputSymbols().contains(first)) { probeChannel = probeMappings.get(first); buildChannel = buildMappings.get(second); } else { probeChannel = probeMappings.get(second); buildChannel = buildMappings.get(first); } SourceHashProvider hashProvider = joinHashFactory.getSourceHashProvider(node, LocalExecutionPlanner.this, buildChannel, operatorStats); Operator leftOperator = plan(node.getLeft()); HashJoinOperator operator = new HashJoinOperator(hashProvider, leftOperator, probeChannel); return operator; } @Override protected Operator visitPlan(PlanNode node, Void context) { throw new UnsupportedOperationException("not yet implemented"); } } private Map<Symbol, Integer> mapSymbolsToChannels(List<Symbol> outputs) { Map<Symbol, Integer> symbolToChannelMappings = new HashMap<>(); for (int i = 0; i < outputs.size(); i++) { symbolToChannelMappings.put(outputs.get(i), i); } return symbolToChannelMappings; } }
package app.sunstreak.yourpisd.util; import java.io.IOException; import java.io.InputStream; import java.net.CookieHandler; import java.net.CookieManager; import java.net.CookieStore; import java.net.HttpCookie; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.Iterator; import java.util.Set; import javax.net.ssl.HttpsURLConnection; import android.graphics.Bitmap; import android.graphics.BitmapFactory; public class Request { /** * * @param url * @param cookies * @param requestProperties * @param isSecure * @return * @throws java.io.IOException * @throws Exception */ public static Object[] getBitmap(String url, Set<String> cookies, ArrayList<String[]> requestProperties, boolean isSecure) { try { CookieManager cm = new CookieManager(); CookieHandler.setDefault(cm); CookieStore cs = cm.getCookieStore(); URL obj = new URL(url); HttpURLConnection conn = ((HttpURLConnection) conn)obj.openConnection(); conn.setRequestMethod("GET"); conn.setUseCaches(false); // what does this do? if (requestProperties != null && requestProperties.size() > 0) for (String[] property : requestProperties) conn.addRequestProperty(property[0], property[1]); // Concatenates the cookies into one cookie string, seperated by // semicolons. if (cookies != null && cookies.size() > 0) { String cookieRequest = concatCookies(cookies); conn.setRequestProperty("Cookie", cookieRequest); } int responseCode = conn.getResponseCode(); for (HttpCookie c : cs.getCookies()) { cookies.add(c.toString()); } InputStream in = conn.getInputStream(); Bitmap bmp = BitmapFactory.decodeStream(in); return new Object[] { bmp, responseCode, cookies }; } catch (IOException e) { e.printStackTrace(); return null; } } private static String concatCookies(Set<String> cookies) { StringBuilder sb = new StringBuilder(); for (Iterator<String> it = cookies.iterator(); it.hasNext();) { sb.append(it.next()); if (it.hasNext()) sb.append("; "); } return sb.toString(); } }
package at.sw2017xp3.regionalo; import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.SearchView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageButton; import android.widget.TextView; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import at.sw2017xp3.regionalo.model.Product; import at.sw2017xp3.regionalo.util.HttpUtils; import at.sw2017xp3.regionalo.util.JsonObjectMapper; import java.util.ArrayList; import java.util.Objects; public class HomeActivity extends AppCompatActivity implements View.OnClickListener{ private Button buttonMeat_; private Button buttonVegetables_; private Button buttonFruit_; private Button buttonOthers_; private Button buttonMilk_; private Button buttonCereals_; private ViewGroup searchField_; private ArrayList<ImageButton> numberImageButton; private ArrayList<TextView> numberTextviewProducer; private ArrayList<TextView> numberTextviewCategory; private ArrayList<TextView> numberTextviewPrice; private ArrayList<TextView> numberTextviewPlace; private ArrayList<TextView> numberTextviewProduct; private Button btnLogin_; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); buttonMeat_ = (Button) findViewById(R.id.buttonMeat); buttonMeat_.setOnClickListener(this); buttonVegetables_ = (Button) findViewById(R.id.buttonVegetables); buttonVegetables_.setOnClickListener(this); buttonFruit_ = (Button) findViewById(R.id.buttonFruit); buttonFruit_.setOnClickListener(this); buttonCereals_ = (Button) findViewById(R.id.buttonCereals); buttonCereals_.setOnClickListener(this); buttonOthers_ = (Button) findViewById(R.id.buttonOthers); buttonOthers_.setOnClickListener(this); buttonMilk_ = (Button) findViewById(R.id.buttonMilk); buttonMilk_.setOnClickListener(this); searchField_ = (ViewGroup) findViewById(R.id.searchView); // searchField_.setOnClickListener(this); setUpListeners(); Uri uri = Uri.parse("http://sw-ma-xp3.bplaced.net/MySQLadmin/featured.php"); // .buildUpon() // .appendQueryParameter("id", "1").build(); new GetProductTask().execute(uri.toString()); } private class GetProductTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { try { return downloadContent(params[0]); } catch (IOException e) { return "Unable to retrieve data. URL may be invalid."; } } @Override protected void onPostExecute(String result) { Toast.makeText(HomeActivity.this, result, Toast.LENGTH_LONG).show(); } } private String downloadContent(String myurl) throws IOException { InputStream is = null; int length = 10000; try { HttpURLConnection conn = HttpUtils.httpGet(myurl); String contentAsString = HttpUtils.convertInputStreamToString(conn.getInputStream(), length); JSONArray arr = new JSONArray(contentAsString); //featured products JSONObject mJsonObject = arr.getJSONObject(0);//one product String allProductNames; Product p = JsonObjectMapper.CreateProduct(mJsonObject); return p.getName(); } catch (Exception ex) { return ""; } finally { if (is != null) { is.close(); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.loginbutton, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.buttonLogin) { Intent myIntent = new Intent(this, LoginActivity.class); startActivity(myIntent); } return super.onOptionsItemSelected(item); } @Override public void onClick(View v) { } public void setUpListeners () { for (int i = 1; i <= 6; i++) { String rndBtn = "imgButtonRnd" + i; String textViewProducer = "textViewRndProducer" + i; String textViewCategory = "textViewRndCategory" + i; String textViewPrice = "textViewRndPrice" + i; String textViewPlace = "textViewRndPlace" + i; String textViewProduct = "textViewRndProduct" + i; int idBtn = getResources (). getIdentifier ( rndBtn , "id" , R . class . getPackage (). getName ()); int idProducer = getResources (). getIdentifier ( textViewProducer , "id" , R . class . getPackage (). getName ()); int idCategory = getResources (). getIdentifier ( textViewCategory , "id" , R . class . getPackage (). getName ()); int idPrice = getResources (). getIdentifier ( textViewPrice , "id" , R . class . getPackage (). getName ()); int idPlace = getResources (). getIdentifier ( textViewProduct , "id" , R . class . getPackage (). getName ()); int idProduct = getResources (). getIdentifier ( textViewPlace , "id" , R . class . getPackage (). getName ()); ImageButton rndImgBtn = (ImageButton) findViewById(idBtn); rndImgBtn.setOnClickListener(this); TextView idProducerTxt = (TextView) findViewById(idProducer); idProducerTxt.setOnClickListener(this); TextView idCategoryTxt = (TextView) findViewById(idCategory); idCategoryTxt.setOnClickListener(this); TextView idPriceTxt = (TextView) findViewById(idPrice); idPriceTxt.setOnClickListener(this); TextView idPlaceTxt = (TextView) findViewById(idPlace); idPlaceTxt.setOnClickListener(this); TextView idProductTxt = (TextView) findViewById(idProduct); idProductTxt.setOnClickListener(this); numberImageButton = new ArrayList<>(); numberTextviewProducer = new ArrayList<>(); numberTextviewCategory = new ArrayList<>(); numberTextviewPrice = new ArrayList<>(); numberTextviewPlace = new ArrayList<>(); numberTextviewProduct = new ArrayList<>(); } } }
package au.id.swords.third; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.content.Context; import android.widget.Button; import android.widget.Spinner; import android.widget.ListView; import android.widget.TextView; import android.widget.EditText; import android.widget.TableRow; import android.widget.ImageButton; import android.widget.RadioButton; import android.widget.AdapterView; import android.widget.TableLayout; import android.widget.ProgressBar; import android.widget.ViewFlipper; import android.widget.ArrayAdapter; import android.widget.SimpleCursorAdapter; import android.widget.AdapterView.AdapterContextMenuInfo; import android.view.Menu; import android.view.MenuItem; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.View; import android.view.View.OnClickListener; import android.view.Gravity; import android.view.LayoutInflater; import android.text.Editable; import android.text.TextWatcher; import android.database.Cursor; import java.util.Random; import java.util.Vector; public class ThirdActivity extends Activity { ThirdDb mDb; ThirdConfig mConfig; boolean mConfigImmutable = false; DiceCounter[] mDice; ButtonCounter mMul; ButtonCounter mMod; TableLayout mLog; ViewFlipper mFlip; RadioButton mFlipPresets; RadioButton mFlipResults; SimpleCursorAdapter mProfiles; ArrayAdapter<ThirdConfig> mPresets; Cursor mProfileCursor; Cursor mPresetCursor; Spinner mProfileView; ListView mPresetView; TextView mResult; Vector<TextView> mResultLog; Integer mProfile; Random mRNG; private static final int ACT_NAME_PRESET = 0; private static final int ACT_NAME_PROFILE = 1; private static final int ACT_DEL_PROFILE = 2; private static final int ADD_PRESET = Menu.FIRST; private static final int ADD_PROFILE = Menu.FIRST + 1; private static final int RENAME_PRESET = Menu.FIRST + 2; private static final int UPDATE_PRESET = Menu.FIRST + 3; private static final int DEL_PRESET = Menu.FIRST + 4; private static final int RENAME_PROFILE = Menu.FIRST + 5; private static final int DEL_PROFILE = Menu.FIRST + 6; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mDice = new DiceCounter[8]; mDice[0] = new DiceCounter(this, 2, R.drawable.d2); mDice[1] = new DiceCounter(this, 4, R.drawable.d4); mDice[2] = new DiceCounter(this, 6, R.drawable.d6); mDice[3] = new DiceCounter(this, 8, R.drawable.d8); mDice[4] = new DiceCounter(this, 10, R.drawable.d10); mDice[5] = new DiceCounter(this, 12, R.drawable.d12); mDice[6] = new DiceCounter(this, 20, R.drawable.d20); mDice[7] = new DiceCounter(this, 100, R.drawable.d100); mMul = new ButtonCounter(this, "mul", R.drawable.mul); mMod = new ButtonCounter(this, "mod", R.drawable.mod); TableLayout t = (TableLayout)findViewById(R.id.counters); for(DiceCounter c: mDice) t.addView(c); t.addView(mMod); t.addView(mMul); setConfig(new ThirdConfig()); Button reset = (Button)findViewById(R.id.reset); reset.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { resetCounters(); } }); Button roll = (Button)findViewById(R.id.roll); roll.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { roll(); } }); mFlip = (ViewFlipper)findViewById(R.id.preset_flipper); mFlip.setDisplayedChild(0); mFlipPresets = (RadioButton)findViewById(R.id.show_presets); mFlipResults = (RadioButton)findViewById(R.id.show_results); mFlipPresets.setChecked(true); mFlipPresets.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { mFlip.setDisplayedChild(0); } }); mFlipResults.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { mFlip.setDisplayedChild(1); } }); mDb = new ThirdDb(this); mProfileView = (Spinner)findViewById(R.id.profiles); mProfileView.setOnItemSelectedListener( new AdapterView.OnItemSelectedListener() { public void onItemSelected(AdapterView parent, View v, int pos, long id) { setProfile(new Integer((int)id)); } public void onNothingSelected(AdapterView parent) { } }); mPresetView = (ListView)findViewById(R.id.presets); mPresetView.setOnItemClickListener(new ListView.OnItemClickListener() { public void onItemClick(AdapterView parent, View v, int pos, long id) { setConfig((ThirdConfig)parent.getItemAtPosition(pos)); roll(); } }); registerForContextMenu(mPresetView); loadProfiles(); mLog = (TableLayout)findViewById(R.id.log); mResult = (TextView)findViewById(R.id.result); mResultLog = new Vector<TextView>(); mResultLog.add((TextView)findViewById(R.id.result_log1)); mResultLog.add((TextView)findViewById(R.id.result_log2)); mResultLog.add((TextView)findViewById(R.id.result_log3)); mResultLog.add((TextView)findViewById(R.id.result_log4)); mRNG = new Random(); } @Override public boolean onCreateOptionsMenu(Menu menu) { boolean result = super.onCreateOptionsMenu(menu); menu.add(Menu.NONE, ADD_PRESET, Menu.NONE, R.string.add_preset); menu.add(Menu.NONE, ADD_PROFILE, Menu.NONE, R.string.add_profile); menu.add(Menu.NONE, RENAME_PROFILE, Menu.NONE, R.string.rename_profile); if(mProfileView.getCount() > 1) { menu.add(Menu.NONE, DEL_PROFILE, Menu.NONE, R.string.del_profile); } return result; } @Override public boolean onOptionsItemSelected(MenuItem item) { Intent i; switch(item.getItemId()) { case ADD_PRESET: i = new Intent(this, ThirdNamePreset.class); i.putExtra("config", describeConfig()); startActivityForResult(i, ACT_NAME_PRESET); return true; case ADD_PROFILE: i = new Intent(this, ThirdNameProfile.class); startActivityForResult(i, ACT_NAME_PROFILE); return true; case RENAME_PROFILE: i = new Intent(this, ThirdNameProfile.class); i.putExtra("id", mProfile); i.putExtra("name", getProfileName()); startActivityForResult(i, ACT_NAME_PROFILE); return true; case DEL_PROFILE: i = new Intent(this, ThirdDelProfile.class); i.putExtra("id", mProfile); i.putExtra("name", getProfileName()); startActivityForResult(i, ACT_DEL_PROFILE); return true; } return super.onOptionsItemSelected(item); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo info) { super.onCreateContextMenu(menu, v, info); menu.add(Menu.NONE, RENAME_PRESET, Menu.NONE, R.string.rename_preset); menu.add(Menu.NONE, UPDATE_PRESET, Menu.NONE, R.string.update_preset); menu.add(Menu.NONE, DEL_PRESET, Menu.NONE, R.string.del_preset); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info; info = (AdapterContextMenuInfo)item.getMenuInfo(); ThirdConfig conf = mPresets.getItem(info.position); switch(item.getItemId()) { case RENAME_PRESET: Intent i = new Intent(this, ThirdNamePreset.class); i.putExtra("id", conf.getId()); i.putExtra("name", conf.getName()); i.putExtra("config", conf.describe()); startActivityForResult(i, ACT_NAME_PRESET); return true; case UPDATE_PRESET: mDb.updatePreset(conf.getId(), mConfig); loadPresets(); return true; case DEL_PRESET: mDb.deletePreset(conf.getId()); loadPresets(); return true; } return super.onContextItemSelected(item); } @Override protected void onActivityResult(int reqCode, int resCode, Intent intent) { super.onActivityResult(reqCode, resCode, intent); if(resCode == RESULT_CANCELED) return; switch(reqCode) { case ACT_NAME_PRESET: { String name = intent.getStringExtra("name"); Integer id = intent.getIntExtra("id", 0); if(id != 0) { mDb.renamePreset(id, name); } else { mConfig.setName(name); mDb.addPreset(mProfile, mConfig); } loadPresets(); } break; case ACT_NAME_PROFILE: { String name = intent.getStringExtra("name"); Integer id = intent.getIntExtra("id", 0); if(id != 0) { mDb.renameProfile(id, name); } else { mDb.addProfile(name); } loadProfiles(); } break; case ACT_DEL_PROFILE: { Integer id = intent.getIntExtra("id", 0); if(id != 0) { mDb.deleteProfile(id); if(mProfile == id) unsetProfile(); loadProfiles(); } } break; } } private void loadProfiles() { mProfileCursor = mDb.getAllProfiles(); startManagingCursor(mProfileCursor); String[] cols = new String[] {"name"}; int[] views = new int[] {android.R.id.text1}; mProfiles = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, mProfileCursor, cols, views); mProfiles.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item); mProfileView.setAdapter(mProfiles); if(mProfile == null) { int index = mProfileCursor.getColumnIndex("_id"); mProfileCursor.moveToFirst(); setProfile(new Integer(mProfileCursor.getInt(index))); } } private void loadPresets() { mPresetCursor = mDb.getPresets(mProfile); startManagingCursor(mPresetCursor); mPresetCursor.moveToFirst(); mPresets = new ArrayAdapter(this, R.layout.preset); while(!mPresetCursor.isAfterLast()) { mPresets.add(new ThirdConfig(mPresetCursor)); mPresetCursor.moveToNext(); } mPresetView.setAdapter(mPresets); } private void setProfile(Integer profile) { mProfile = profile; loadPresets(); } private void unsetProfile() { mProfile = null; } private void updateConfig() { if(mConfigImmutable) return; for(DiceCounter c: mDice) mConfig.setDie(c.sides, c.getValue()); mConfig.setMultiplier(mMul.getValue()); mConfig.setModifier(mMod.getValue()); } private void setConfig(ThirdConfig conf) { mConfig = conf; updateFromConfig(); } private void updateCounters() { for(DiceCounter c: mDice) c.setValue(mConfig.getDie(c.sides)); mMul.setValue(mConfig.getMultiplier()); mMod.setValue(mConfig.getModifier()); } private void updateDescription() { TextView label = (TextView)findViewById(R.id.config); label.setText(describeConfig()); TextView range = (TextView)findViewById(R.id.range); range.setText(mConfig.describeRange()); ProgressBar bar = (ProgressBar)findViewById(R.id.result_bar); bar.setMax(mConfig.getRange()); bar.setProgress(0); } private void updateFromConfig() { mConfigImmutable = true; updateCounters(); updateDescription(); mConfigImmutable = false; } private String describeConfig() { return mConfig.describe(); } private String getProfileName() { int pos = mProfileView.getSelectedItemPosition(); int index = mProfileCursor.getColumnIndex("name"); return mProfileCursor.getString(index); } private void clearLog() { mLog.removeAllViews(); } private void addLog(String label, String outcome) { TableRow row = new TableRow(this); mLog.addView(row); TextView tv1 = new TextView(this); tv1.setText(String.valueOf(mLog.getChildCount())); tv1.setGravity(Gravity.CENTER_HORIZONTAL); row.addView(tv1); TextView tv2 = new TextView(this); tv2.setText(label); row.addView(tv2); TextView tv3 = new TextView(this); tv3.setText(outcome); tv3.setGravity(Gravity.RIGHT); row.addView(tv3); } private Integer rollDie(Integer sides) { return mRNG.nextInt(sides) + 1; } private void roll() { Integer result = new Integer(0); Integer outcome; clearLog(); Vector<Integer> v = mConfig.getDice(); for(Integer sides: v) { outcome = rollDie(Math.abs(sides)); String label = String.format("d%d", Math.abs(sides)); addLog(label, outcome.toString()); result += outcome; } Integer mul = mConfig.getMultiplier(); if(mul != 1) { addLog("*", mul.toString()); result *= mul; } Integer mod = mConfig.getModifier(); if(mod != 0) { String sign = (mod < 0) ? "-" : "+"; addLog(sign, String.valueOf(Math.abs(mod))); result += mod; } ProgressBar bar = (ProgressBar)findViewById(R.id.result_bar); bar.setProgress(result - mConfig.getMin()); shiftResults(); mResult.setText(result.toString()); } private void shiftResults() { String value = mResult.getText().toString(); String next; for(TextView v: mResultLog) { if(value == "") break; next = v.getText().toString(); v.setText(value); value = next; } } private void resetCounters() { mConfig.reset(); updateFromConfig(); } abstract private class Counter extends TableRow { String mName; EditText mCounter; public Counter(Context ctx, String name) { super(ctx); mName = name; } protected void initCounter() { mCounter.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) { updateConfig(); updateDescription(); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { } }); } public Integer getValue() { try { return new Integer(mCounter.getText().toString()); } catch(NumberFormatException e) { return new Integer(0); } } public Integer setValue(Integer value) { mCounter.setText(value.toString()); return getValue(); } public void resetValue() { setValue(0); } public Integer modValue(Integer mod) { Integer value = getValue(); return setValue(value + mod); } } private class ButtonCounter extends Counter { ImageButton mButton; public ButtonCounter(Context ctx, String name, int image) { super(ctx, name); LayoutInflater li; li = (LayoutInflater)ctx.getSystemService( ctx.LAYOUT_INFLATER_SERVICE); li.inflate(R.layout.counter, this); mButton = (ImageButton)findViewById(R.id.button); mButton.setImageResource(image); mButton.setOnClickListener(new ImageButton.OnClickListener() { public void onClick(View v) { modValue(1); } }); mCounter = (EditText)findViewById(R.id.counter); initCounter(); } } private class DiceCounter extends ButtonCounter { int sides; public DiceCounter(Context ctx, int sides, int image) { super(ctx, String.format("d%d", sides), image); this.sides = sides; } } }
package com.afifzafri.studentsdb; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.TextView; import android.widget.Toast; import org.w3c.dom.Text; public class SearchData extends AppCompatActivity { // initialize object DBHelper mydb; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search_data); mydb = new DBHelper(this); // get intent and data passed Intent intentPage = getIntent(); String intstudID = intentPage.getStringExtra("STUD_ID"); final EditText sid = (EditText)findViewById(R.id.editSearch); ImageButton btnSearch = (ImageButton)findViewById(R.id.btnSearch); ImageButton btnCall = (ImageButton)findViewById(R.id.btnCall); ImageButton btnMsg = (ImageButton)findViewById(R.id.btnMsg); final ImageButton btnEdit = (ImageButton)findViewById(R.id.btnEdit); final TextView resID = (TextView)findViewById(R.id.resStudID); final TextView resName = (TextView)findViewById(R.id.resName); final TextView resIC = (TextView)findViewById(R.id.resIC); final TextView resDOB = (TextView)findViewById(R.id.resDOB); final TextView resAddress = (TextView)findViewById(R.id.resAddress); final TextView resProgram = (TextView)findViewById(R.id.resProgram); final TextView resPhone = (TextView)findViewById(R.id.resPhone); final TextView resEmail = (TextView)findViewById(R.id.resEmail); // hide edit button btnEdit.setVisibility(View.GONE); // check if intent send an id value, populate the result if(intstudID != null) { // if come from view data activity, hide the search sid.setVisibility(View.GONE); btnSearch.setVisibility(View.GONE); // access cursor data Cursor cursor = mydb.searchData(intstudID); cursor.moveToFirst(); String id = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_ID)); String name = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_NAME)); String ic = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_IC)); String dob = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_DOB)); String address = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_ADDRESS)); String program = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_PROGRAM)); String phone = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_PHONE)); String email = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_EMAIL)); //append all the data resID.setText(id); resName.setText(name); resIC.setText(ic); resDOB.setText(dob); resAddress.setText(address); resProgram.setText(program); resPhone.setText(phone); resEmail.setText(email); // show edit button btnEdit.setVisibility(View.VISIBLE); // show toast message Toast.makeText(getApplicationContext(), "Data found",Toast.LENGTH_SHORT).show(); // close cursor if (!cursor.isClosed()) { cursor.close(); } } // action when search button clicked btnSearch.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String studid = sid.getText().toString(); // access cursor data Cursor cursor = mydb.searchData(studid); cursor.moveToFirst(); // check if cursor return data or not (data found in db or not) if(cursor.getCount() < 1) { // empty all result resID.setText(""); resName.setText(""); resIC.setText(""); resDOB.setText(""); resAddress.setText(""); resProgram.setText(""); resPhone.setText(""); resEmail.setText(""); // hide edit button btnEdit.setVisibility(View.GONE); // show toast message Toast.makeText(getApplicationContext(), "No data found",Toast.LENGTH_SHORT).show(); } else { String id = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_ID)); String name = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_NAME)); String ic = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_IC)); String dob = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_DOB)); String address = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_ADDRESS)); String program = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_PROGRAM)); String phone = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_PHONE)); String email = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_EMAIL)); //append all the data resID.setText(id); resName.setText(name); resIC.setText(ic); resDOB.setText(dob); resAddress.setText(address); resProgram.setText(program); resPhone.setText(phone); resEmail.setText(email); // show edit button btnEdit.setVisibility(View.VISIBLE); // show toast message Toast.makeText(getApplicationContext(), "Data found",Toast.LENGTH_SHORT).show(); } // close cursor if (!cursor.isClosed()) { cursor.close(); } } }); // action when edit button clicked btnEdit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String resStudID = resID.getText().toString(); // allow edit only if student id available if(resStudID != "") { // intent to open new activity Intent intentPage = new Intent(SearchData.this, EditViewData.class); intentPage.putExtra("STUD_ID",resStudID); startActivity(intentPage); } else { // show toast message Toast.makeText(getApplicationContext(), "No data to edit",Toast.LENGTH_SHORT).show(); } } }); // open dialer when call button clicked btnCall.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intentPage = new Intent(Intent.ACTION_DIAL); intentPage.setData(Uri.parse("tel:"+resPhone.getText().toString())); startActivity(intentPage); } }); // open messaging app (default or whatsapp, user can choose) btnMsg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Uri uri = Uri.parse("smsto:" + resPhone.getText().toString()); Intent i = new Intent(Intent.ACTION_SENDTO, uri); startActivity(Intent.createChooser(i, "")); } }); } }
package com.bsv.www.storyproducer; import android.app.Dialog; import android.media.MediaPlayer; import android.media.MediaRecorder; import android.os.Bundle; import android.os.Environment; import com.getbase.floatingactionbutton.FloatingActionButton; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.Button; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.io.File; import java.io.IOException; public class TransFrag extends Fragment { private MediaRecorder audioRecorder; private static final String SLIDE_NUM = "slidenum"; private static final String NUM_OF_SLIDES = "numofslide"; private static final String STORY_NAME = "storyname"; private String outputFile=null; private File output = null; private String fileName = "recording"; private int record_count = 2; public static TransFrag newInstance(int position, int numOfSlides, String storyName){ TransFrag frag = new TransFrag(); Bundle args = new Bundle(); args.putInt(SLIDE_NUM, position); args.putInt(NUM_OF_SLIDES, numOfSlides); args.putString(STORY_NAME, storyName); frag.setArguments(args); return frag; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { int currentSlide = getArguments().getInt(SLIDE_NUM); String storyName = getArguments().getString(STORY_NAME); // Inflate the layout for this fragment ViewGroup view = (ViewGroup) inflater.inflate(R.layout.fragment_trans, container, false); //Change Slide Number and add on click TextView slideNum = (TextView)view.findViewById(R.id.trans_slide_indicator); // Setting Story Text FileSystem fileSystem = new FileSystem(); fileSystem.loadSlideContent(storyName, currentSlide); ImageView slideimage = (ImageView)view.findViewById(R.id.trans_image_slide); slideimage.setImageBitmap(fileSystem.getImage(storyName, currentSlide)); TextView slideTitle = (TextView)view.findViewById(R.id.trans_slide_title_primary); slideTitle.setText(fileSystem.getTitle()); TextView slideSubTitle = (TextView)view.findViewById(R.id.trans_slide_title_secondary); slideSubTitle.setText(fileSystem.getSlideVerse()); TextView slideVerse = (TextView)view.findViewById(R.id.trans_scripture_title); slideVerse.setText(fileSystem.getSlideVerse()); TextView slideContent = (TextView)view.findViewById(R.id.trans_scripture_body); slideContent.setText(fileSystem.getSlideContent()); slideNum.setText("#" + (getArguments().getInt(SLIDE_NUM) + 1)); slideNum.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { launchSlideSelectDialog(); } }); //stuff for saving and playing the audio //TODO test to see where exacly getPath is in our files and if we even need the directory path output = getContext().getCacheDir(); outputFile = output.getPath(); outputFile += "/BSVP/" + getArguments().getString(STORY_NAME) + "/" + fileName + SLIDE_NUM + ".mp3"; final FloatingActionButton floatingActionButton1 = (FloatingActionButton) view.findViewById(R.id.trans_record); final FloatingActionButton floatingActionButton2 = (FloatingActionButton) view.findViewById(R.id.trans_play); floatingActionButton2.setVisibility(View.INVISIBLE); floatingActionButton1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); //TODO handle an event when you simply click -> it crashes when you do this //hopefully the click function above this does that. floatingActionButton1.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: v.setPressed(true); audioRecorder = createAudioRecorder(outputFile); startAudioRecorder(audioRecorder); Toast.makeText(getContext(), "Recording Started", Toast.LENGTH_LONG).show(); break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_OUTSIDE: case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_POINTER_DOWN: case MotionEvent.ACTION_POINTER_UP: Toast.makeText(getContext(), "Recording Stopped", Toast.LENGTH_LONG).show(); stopAudioRecorder(audioRecorder); //keep track of the number of records if (record_count == 2) { record_count floatingActionButton2.setVisibility(View.VISIBLE); } else if (record_count == 1) { record_count floatingActionButton1.setColorNormalResId(R.color.yellow); } else if (record_count == 0) { floatingActionButton1.setColorNormalResId(R.color.green); } break; case MotionEvent.ACTION_MOVE: break; } return true; } }); floatingActionButton2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MediaPlayer m = new MediaPlayer(); try { m.setDataSource(outputFile); } catch (IOException e) { e.printStackTrace(); } try { m.prepare(); } catch (IOException e) { e.printStackTrace(); } m.start(); Toast.makeText(getContext(), "Playing Audio", Toast.LENGTH_LONG).show(); } }); return view; } private void startAudioRecorder(MediaRecorder recorder){ try { recorder.prepare(); recorder.start(); } catch (IllegalStateException | IOException e){ e.printStackTrace(); } } private void stopAudioRecorder(MediaRecorder recorder){ recorder.stop(); recorder.release(); //recorder = null; } private MediaRecorder createAudioRecorder(String fileName){ MediaRecorder mediaRecorder = new MediaRecorder(); mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC); mediaRecorder.setOutputFile(fileName); return mediaRecorder; } private void launchSlideSelectDialog() { final Dialog dialog = new Dialog(getContext()); int[] slides = new int[getArguments().getInt(NUM_OF_SLIDES)]; for (int i = 0; i < getArguments().getInt(NUM_OF_SLIDES); i++) { slides[i] = (i + 1); } final DialogListAdapter dialogListAdapter = new DialogListAdapter(getActivity(), slides, getArguments().getInt(SLIDE_NUM)); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.dialog_slide_indicator); ListView listView = (ListView)dialog.findViewById(R.id.dialog_listview); listView.setAdapter(dialogListAdapter); Button okText = (Button)dialog.findViewById(R.id.dialog_ok); Button cancelText = (Button)dialog.findViewById(R.id.dialog_cancel); cancelText.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); okText.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); // getActivity() } }); dialog.show(); } }
package com.egg.android.citest; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private TextView mTextContent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); } private void initView() { mTextContent = (TextView) findViewById(R.id.text_main_content); mTextContent.setText("CI is OK, and apk is on fir.im http://fir.im/87dg"); mTextContent.setTextColor(Color.MAGENTA); } }
package com.opengamma.web.analytics; import java.util.Collections; import java.util.List; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.opengamma.util.ArgumentChecker; /** * Collection of {@link AnalyticsColumnGroup}s that make up the columns in a grid. */ public class AnalyticsColumnGroups { private final List<AnalyticsColumn> _columns = Lists.newArrayList(); private final List<AnalyticsColumnGroup> _columnGroups; /* package */ AnalyticsColumnGroups(List<AnalyticsColumnGroup> columnGroups) { ArgumentChecker.notNull(columnGroups, "columnGroups"); ArgumentChecker.notNull(columnGroups, "columnGroups"); for (AnalyticsColumnGroup group : columnGroups) { _columns.addAll(group.getColumns()); } _columnGroups = ImmutableList.copyOf(columnGroups); } /** * @return A instance containing no column groups */ /* package */ static AnalyticsColumnGroups empty() { return new AnalyticsColumnGroups(Collections.<AnalyticsColumnGroup>emptyList()); } /** * @return Total number of columns in all column groups */ public int getColumnCount() { return _columns.size(); } /** * Returns the column at an index * @param index The column index, zero based * @return The column at the specified index */ public AnalyticsColumn getColumn(int index) { return _columns.get(index); } /** * @return The column groups in the order they should be displayed */ public List<AnalyticsColumnGroup> getGroups() { return _columnGroups; } @Override public String toString() { return "AnalyticsColumnGroups [_columns=" + _columns + ", _columnGroups=" + _columnGroups + "]"; } }
package pl.grzeslowski.jsupla.protocol.structs.sc; import pl.grzeslowski.jsupla.protocol.calltypes.ServerClientCallType; import java.util.Arrays; import static pl.grzeslowski.jsupla.protocol.ProtoPreconditions.checkArrayLength; import static pl.grzeslowski.jsupla.protocol.consts.JavaConsts.INT_SIZE; import static pl.grzeslowski.jsupla.protocol.consts.ProtoConsts.SUPLA_SENDER_NAME_MAXSIZE; public final class TSC_SuplaEvent implements ServerClient { public final int event; public final int channelId; /** * unsigned. */ public final int durationMs; public final int senderId; /** * Including the terminating null byte ('\0'). */ public final int senderNameSize; /** * UTF-8. */ public final byte[] senderName; public TSC_SuplaEvent(int event, int channelId, int durationMs, int senderId, int senderNameSize, byte[] senderName) { this.event = event; this.channelId = channelId; this.durationMs = durationMs; this.senderId = senderId; this.senderNameSize = senderNameSize; this.senderName = checkArrayLength(senderName, SUPLA_SENDER_NAME_MAXSIZE); } @Override public ServerClientCallType callType() { throw new UnsupportedOperationException(); } @Override public int size() { return INT_SIZE * 5 + SUPLA_SENDER_NAME_MAXSIZE; } @Override public String toString() { return "TSC_SuplaEvent{" + "event=" + event + ", channelId=" + channelId + ", durationMs=" + durationMs + ", senderId=" + senderId + ", senderNameSize=" + senderNameSize + ", senderName=" + Arrays.toString(senderName) + '}'; } }
package com.pencilbox.netknight.utils; import android.util.Log; public class MyLog { private static final boolean DEBUG=true; public static void logd(Object o ,String msg){ if(DEBUG){ String clazz = o.getClass().getName(); Log.d(clazz.substring(clazz.lastIndexOf('.')+1),msg); } } public static void loge(Object o ,String msg){ if(DEBUG){ String clazz = o.getClass().getName(); Log.e(clazz.substring(clazz.lastIndexOf('.')+1),msg); } } }
package com.samourai.wallet; import android.animation.ObjectAnimator; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.ActivityInfo; import android.graphics.Color; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.support.v4.content.LocalBroadcastManager; import android.support.v4.widget.SwipeRefreshLayout; import android.text.Html; import android.text.InputType; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.animation.AnticipateInterpolator; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import android.util.Log; import org.apache.commons.lang3.tuple.Pair; import org.bitcoinj.core.Address; import org.bitcoinj.core.AddressFormatException; import org.bitcoinj.core.DumpedPrivateKey; import org.bitcoinj.core.ECKey; import org.bitcoinj.core.TransactionInput; import org.bitcoinj.core.TransactionOutput; import org.bitcoinj.core.TransactionWitness; import org.bitcoinj.crypto.BIP38PrivateKey; import org.bitcoinj.crypto.MnemonicException; import com.dm.zbar.android.scanner.ZBarConstants; import com.dm.zbar.android.scanner.ZBarScannerActivity; import com.samourai.wallet.JSONRPC.JSONRPC; import com.samourai.wallet.JSONRPC.PoW; import com.samourai.wallet.JSONRPC.TrustedNodeUtil; import com.samourai.wallet.access.AccessFactory; import com.samourai.wallet.api.APIFactory; import com.samourai.wallet.api.Tx; import com.samourai.wallet.bip47.BIP47Meta; import com.samourai.wallet.bip47.BIP47Util; import com.samourai.wallet.bip47.rpc.*; import com.samourai.wallet.crypto.AESUtil; import com.samourai.wallet.crypto.DecryptionException; import com.samourai.wallet.hd.HD_Address; import com.samourai.wallet.hd.HD_Wallet; import com.samourai.wallet.hd.HD_WalletFactory; import com.samourai.wallet.hf.HardForkUtil; import com.samourai.wallet.hf.ReplayProtectionActivity; import com.samourai.wallet.hf.ReplayProtectionWarningActivity; import com.samourai.wallet.payload.PayloadUtil; import com.samourai.wallet.segwit.BIP49Util; import com.samourai.wallet.segwit.P2SH_P2WPKH; import com.samourai.wallet.send.FeeUtil; import com.samourai.wallet.send.MyTransactionInput; import com.samourai.wallet.send.MyTransactionOutPoint; import com.samourai.wallet.send.RBFSpend; import com.samourai.wallet.send.RBFUtil; import com.samourai.wallet.send.SendFactory; import com.samourai.wallet.send.SuggestedFee; import com.samourai.wallet.send.SweepUtil; import com.samourai.wallet.send.UTXO; import com.samourai.wallet.send.PushTx; import com.samourai.wallet.service.WebSocketService; import com.samourai.wallet.util.AddressFactory; import com.samourai.wallet.util.AppUtil; import com.samourai.wallet.util.BlockExplorerUtil; import com.samourai.wallet.util.CharSequenceX; import com.samourai.wallet.util.DateUtil; import com.samourai.wallet.util.ExchangeRateFactory; import com.samourai.wallet.util.MonetaryUtil; import com.samourai.wallet.util.PrefsUtil; import com.samourai.wallet.util.PrivKeyReader; import com.samourai.wallet.util.TimeOutUtil; import com.samourai.wallet.util.TorUtil; import com.samourai.wallet.util.TypefaceUtil; import org.bitcoinj.core.Coin; import org.bitcoinj.crypto.TransactionSignature; import org.bitcoinj.params.MainNetParams; import org.bitcoinj.core.Transaction; import org.bitcoinj.script.Script; import org.bitcoinj.script.ScriptBuilder; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.encoders.DecoderException; import net.i2p.android.ext.floatingactionbutton.FloatingActionButton; import net.i2p.android.ext.floatingactionbutton.FloatingActionsMenu; import net.sourceforge.zbar.Symbol; import java.io.IOException; import java.math.BigInteger; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import info.guardianproject.netcipher.proxy.OrbotHelper; public class BalanceActivity extends Activity { private final static int SCAN_COLD_STORAGE = 2011; private final static int SCAN_QR = 2012; private LinearLayout layoutAlert = null; private LinearLayout tvBalanceBar = null; private TextView tvBalanceAmount = null; private TextView tvBalanceUnits = null; private ListView txList = null; private List<Tx> txs = null; private HashMap<String, Boolean> txStates = null; private TransactionAdapter txAdapter = null; private SwipeRefreshLayout swipeRefreshLayout = null; private FloatingActionsMenu ibQuickSend = null; private FloatingActionButton actionReceive = null; private FloatingActionButton actionSend = null; private FloatingActionButton actionBIP47 = null; private boolean isBTC = true; private RefreshTask refreshTask = null; private PoWTask powTask = null; private RBFTask rbfTask = null; private CPFPTask cpfpTask = null; public static final String ACTION_INTENT = "com.samourai.wallet.BalanceFragment.REFRESH"; protected BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(final Context context, Intent intent) { if(ACTION_INTENT.equals(intent.getAction())) { final boolean notifTx = intent.getBooleanExtra("notifTx", false); final boolean fetch = intent.getBooleanExtra("fetch", false); final String rbfHash; final String blkHash; if(intent.hasExtra("rbf")) { rbfHash = intent.getStringExtra("rbf"); } else { rbfHash = null; } if(intent.hasExtra("hash")) { blkHash = intent.getStringExtra("hash"); } else { blkHash = null; } BalanceActivity.this.runOnUiThread(new Runnable() { @Override public void run() { tvBalanceAmount.setText(""); tvBalanceUnits.setText(""); refreshTx(notifTx, fetch, false, false); if(BalanceActivity.this != null) { try { PayloadUtil.getInstance(BalanceActivity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(BalanceActivity.this).getGUID() + AccessFactory.getInstance(BalanceActivity.this).getPIN())); } catch(MnemonicException.MnemonicLengthException mle) { ; } catch(JSONException je) { ; } catch(IOException ioe) { ; } catch(DecryptionException de) { ; } if(rbfHash != null) { new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(rbfHash + "\n\n" + getString(R.string.rbf_incoming)) .setCancelable(true) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { doExplorerView(rbfHash); } }) .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { ; } }).show(); } } } }); if(BalanceActivity.this != null && blkHash != null && PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.USE_TRUSTED_NODE, false) == true && TrustedNodeUtil.getInstance().isSet()) { BalanceActivity.this.runOnUiThread(new Runnable() { @Override public void run() { if(powTask == null || powTask.getStatus().equals(AsyncTask.Status.FINISHED)) { powTask = new PoWTask(); powTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, blkHash); } } }); } } } }; protected BroadcastReceiver torStatusReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.i("BalanceActivity", "torStatusReceiver onReceive()"); if (OrbotHelper.ACTION_STATUS.equals(intent.getAction())) { boolean enabled = (intent.getStringExtra(OrbotHelper.EXTRA_STATUS).equals(OrbotHelper.STATUS_ON)); Log.i("BalanceActivity", "status:" + enabled); TorUtil.getInstance(BalanceActivity.this).setStatusFromBroadcast(enabled); } } }; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_balance); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); if(SamouraiWallet.getInstance().isTestNet()) { setTitle(getText(R.string.app_name) + ":" + "TestNet"); } LayoutInflater inflator = BalanceActivity.this.getLayoutInflater(); tvBalanceBar = (LinearLayout)inflator.inflate(R.layout.balance_layout, null); tvBalanceBar.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if(isBTC) { isBTC = false; } else { isBTC = true; } displayBalance(); txAdapter.notifyDataSetChanged(); return false; } }); tvBalanceAmount = (TextView)tvBalanceBar.findViewById(R.id.BalanceAmount); tvBalanceUnits = (TextView)tvBalanceBar.findViewById(R.id.BalanceUnits); ibQuickSend = (FloatingActionsMenu)findViewById(R.id.wallet_menu); actionSend = (FloatingActionButton)findViewById(R.id.send); actionSend.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(BalanceActivity.this, SendActivity.class); intent.putExtra("via_menu", true); startActivity(intent); } }); actionReceive = (FloatingActionButton)findViewById(R.id.receive); actionReceive.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { try { HD_Wallet hdw = HD_WalletFactory.getInstance(BalanceActivity.this).get(); if(hdw != null) { if(SamouraiWallet.getInstance().getCurrentSelectedAccount() == 2 || (SamouraiWallet.getInstance().getCurrentSelectedAccount() == 0 && SamouraiWallet.getInstance().getShowTotalBalance()) ) { new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(R.string.receive2Samourai) .setCancelable(false) .setPositiveButton(R.string.generate_receive_yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Intent intent = new Intent(BalanceActivity.this, ReceiveActivity.class); startActivity(intent); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { ; } }).show(); } else { Intent intent = new Intent(BalanceActivity.this, ReceiveActivity.class); startActivity(intent); } } } catch(IOException | MnemonicException.MnemonicLengthException e) { ; } } }); actionBIP47 = (FloatingActionButton)findViewById(R.id.bip47); actionBIP47.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(BalanceActivity.this, com.samourai.wallet.bip47.BIP47Activity.class); startActivity(intent); } }); txs = new ArrayList<Tx>(); txStates = new HashMap<String, Boolean>(); txList = (ListView)findViewById(R.id.txList); txAdapter = new TransactionAdapter(); txList.setAdapter(txAdapter); txList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, final View view, int position, long id) { if(position == 0) { return; } long viewId = view.getId(); View v = (View)view.getParent(); final Tx tx = txs.get(position - 1); ImageView ivTxStatus = (ImageView)v.findViewById(R.id.TransactionStatus); TextView tvConfirmationCount = (TextView)v.findViewById(R.id.ConfirmationCount); if(viewId == R.id.ConfirmationCount || viewId == R.id.TransactionStatus) { if(txStates.containsKey(tx.getHash()) && txStates.get(tx.getHash()) == true) { txStates.put(tx.getHash(), false); displayTxStatus(false, tx.getConfirmations(), tvConfirmationCount, ivTxStatus); } else { txStates.put(tx.getHash(), true); displayTxStatus(true, tx.getConfirmations(), tvConfirmationCount, ivTxStatus); } } else { String message = getString(R.string.options_unconfirmed_tx); // RBF if(tx.getConfirmations() < 1 && tx.getAmount() < 0.0 && RBFUtil.getInstance().contains(tx.getHash())) { AlertDialog.Builder builder = new AlertDialog.Builder(BalanceActivity.this); builder.setTitle(R.string.app_name); builder.setMessage(message); builder.setCancelable(true); builder.setPositiveButton(R.string.options_bump_fee, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, int whichButton) { if(rbfTask == null || rbfTask.getStatus().equals(AsyncTask.Status.FINISHED)) { rbfTask = new RBFTask(); rbfTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, tx.getHash()); } } }); builder.setNegativeButton(R.string.options_block_explorer, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, int whichButton) { doExplorerView(tx.getHash()); } }); AlertDialog alert = builder.create(); alert.show(); } // CPFP receive else if(tx.getConfirmations() < 1 && tx.getAmount() >= 0.0) { AlertDialog.Builder builder = new AlertDialog.Builder(BalanceActivity.this); builder.setTitle(R.string.app_name); builder.setMessage(message); builder.setCancelable(true); builder.setPositiveButton(R.string.options_bump_fee, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, int whichButton) { if(cpfpTask == null || cpfpTask.getStatus().equals(AsyncTask.Status.FINISHED)) { cpfpTask = new CPFPTask(); cpfpTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, tx.getHash()); } } }); builder.setNegativeButton(R.string.options_block_explorer, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, int whichButton) { doExplorerView(tx.getHash()); } }); AlertDialog alert = builder.create(); alert.show(); } // CPFP spend else if(tx.getConfirmations() < 1 && tx.getAmount() < 0.0) { AlertDialog.Builder builder = new AlertDialog.Builder(BalanceActivity.this); builder.setTitle(R.string.app_name); builder.setMessage(message); builder.setCancelable(true); builder.setPositiveButton(R.string.options_bump_fee, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, int whichButton) { if(cpfpTask == null || cpfpTask.getStatus().equals(AsyncTask.Status.FINISHED)) { cpfpTask = new CPFPTask(); cpfpTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, tx.getHash()); } } }); builder.setNegativeButton(R.string.options_block_explorer, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, int whichButton) { doExplorerView(tx.getHash()); } }); AlertDialog alert = builder.create(); alert.show(); } else { doExplorerView(tx.getHash()); return; } } } }); swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swiperefresh); swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { new Handler().post(new Runnable() { @Override public void run() { refreshTx(false, true, true, false); } }); } }); swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light); IntentFilter filter = new IntentFilter(ACTION_INTENT); LocalBroadcastManager.getInstance(BalanceActivity.this).registerReceiver(receiver, filter); // TorUtil.getInstance(BalanceActivity.this).setStatusFromBroadcast(false); registerReceiver(torStatusReceiver, new IntentFilter(OrbotHelper.ACTION_STATUS)); boolean notifTx = false; boolean fetch = false; Bundle extras = getIntent().getExtras(); if(extras != null && extras.containsKey("notifTx")) { notifTx = extras.getBoolean("notifTx"); } if(extras != null && extras.containsKey("uri")) { fetch = extras.getBoolean("fetch"); } refreshTx(notifTx, fetch, false, true); // user checks mnemonic & passphrase if(PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.CREDS_CHECK, 0L) == 0L) { AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.recovery_checkup) .setMessage(BalanceActivity.this.getText(R.string.recovery_checkup_message)) .setCancelable(false) .setPositiveButton(R.string.next, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); try { final String seed = HD_WalletFactory.getInstance(BalanceActivity.this).get().getMnemonic(); final String passphrase = HD_WalletFactory.getInstance(BalanceActivity.this).get().getPassphrase(); final String message = BalanceActivity.this.getText(R.string.mnemonic) + ":<br><br><b>" + seed + "</b><br><br>" + BalanceActivity.this.getText(R.string.passphrase) + ":<br><br><b>" + passphrase + "</b>"; AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.recovery_checkup) .setMessage(Html.fromHtml(message)) .setCancelable(false) .setPositiveButton(R.string.recovery_checkup_finish, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { PrefsUtil.getInstance(BalanceActivity.this).setValue(PrefsUtil.CREDS_CHECK, System.currentTimeMillis() / 1000L); dialog.dismiss(); } }); if(!isFinishing()) { dlg.show(); } } catch(IOException | MnemonicException.MnemonicLengthException e) { Toast.makeText(BalanceActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); } } }); if(!isFinishing()) { dlg.show(); } } } @Override public void onResume() { super.onResume(); // IntentFilter filter = new IntentFilter(ACTION_INTENT); // LocalBroadcastManager.getInstance(BalanceActivity.this).registerReceiver(receiver, filter); if(TorUtil.getInstance(BalanceActivity.this).statusFromBroadcast()) { OrbotHelper.requestStartTor(BalanceActivity.this); } AppUtil.getInstance(BalanceActivity.this).checkTimeOut(); if(!AppUtil.getInstance(BalanceActivity.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) { startService(new Intent(BalanceActivity.this.getApplicationContext(), WebSocketService.class)); } } @Override public void onPause() { super.onPause(); // LocalBroadcastManager.getInstance(BalanceActivity.this).unregisterReceiver(receiver); ibQuickSend.collapse(); } @Override public void onDestroy() { LocalBroadcastManager.getInstance(BalanceActivity.this).unregisterReceiver(receiver); unregisterReceiver(torStatusReceiver); if(AppUtil.getInstance(BalanceActivity.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) { stopService(new Intent(BalanceActivity.this.getApplicationContext(), WebSocketService.class)); } super.onDestroy(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); if(!OrbotHelper.isOrbotInstalled(BalanceActivity.this)) { menu.findItem(R.id.action_tor).setVisible(false); } else if(TorUtil.getInstance(BalanceActivity.this).statusFromBroadcast()) { OrbotHelper.requestStartTor(BalanceActivity.this); menu.findItem(R.id.action_tor).setIcon(R.drawable.tor_on); } else { menu.findItem(R.id.action_tor).setIcon(R.drawable.tor_off); } menu.findItem(R.id.action_refresh).setVisible(false); menu.findItem(R.id.action_share_receive).setVisible(false); menu.findItem(R.id.action_ricochet).setVisible(false); menu.findItem(R.id.action_empty_ricochet).setVisible(false); menu.findItem(R.id.action_sign).setVisible(false); menu.findItem(R.id.action_fees).setVisible(false); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); // noinspection SimplifiableIfStatement if (id == R.id.action_settings) { doSettings(); } else if (id == R.id.action_sweep) { doSweep(); } else if (id == R.id.action_utxo) { doUTXO(); } else if (id == R.id.action_tor) { if(!OrbotHelper.isOrbotInstalled(BalanceActivity.this)) { ; } else if(TorUtil.getInstance(BalanceActivity.this).statusFromBroadcast()) { item.setIcon(R.drawable.tor_off); TorUtil.getInstance(BalanceActivity.this).setStatusFromBroadcast(false); } else { OrbotHelper.requestStartTor(BalanceActivity.this); item.setIcon(R.drawable.tor_on); TorUtil.getInstance(BalanceActivity.this).setStatusFromBroadcast(true); } return true; } else if (id == R.id.action_backup) { if(SamouraiWallet.getInstance().hasPassphrase(BalanceActivity.this)) { try { if(HD_WalletFactory.getInstance(BalanceActivity.this).get() != null && SamouraiWallet.getInstance().hasPassphrase(BalanceActivity.this)) { doBackup(); } else { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.passphrase_needed_for_backup).setCancelable(false); AlertDialog alert = builder.create(); alert.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); }}); if(!isFinishing()) { alert.show(); } } } catch(MnemonicException.MnemonicLengthException mle) { ; } catch(IOException ioe) { ; } } else { Toast.makeText(BalanceActivity.this, R.string.passphrase_required, Toast.LENGTH_SHORT).show(); } } else if (id == R.id.action_scan_qr) { doScan(); } else { ; } return super.onOptionsItemSelected(item); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if(resultCode == Activity.RESULT_OK && requestCode == SCAN_COLD_STORAGE) { if(data != null && data.getStringExtra(ZBarConstants.SCAN_RESULT) != null) { final String strResult = data.getStringExtra(ZBarConstants.SCAN_RESULT); doPrivKey(strResult); } } else if(resultCode == Activity.RESULT_CANCELED && requestCode == SCAN_COLD_STORAGE) { ; } else if(resultCode == Activity.RESULT_OK && requestCode == SCAN_QR) { if(data != null && data.getStringExtra(ZBarConstants.SCAN_RESULT) != null) { final String strResult = data.getStringExtra(ZBarConstants.SCAN_RESULT); Intent intent = new Intent(BalanceActivity.this, SendActivity.class); intent.putExtra("uri", strResult); startActivity(intent); } } else if(resultCode == Activity.RESULT_CANCELED && requestCode == SCAN_QR) { ; } else { ; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.ask_you_sure_exit).setCancelable(false); AlertDialog alert = builder.create(); alert.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.yes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { try { PayloadUtil.getInstance(BalanceActivity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(BalanceActivity.this).getGUID() + AccessFactory.getInstance(BalanceActivity.this).getPIN())); } catch(MnemonicException.MnemonicLengthException mle) { ; } catch(JSONException je) { ; } catch(IOException ioe) { ; } catch(DecryptionException de) { ; } Intent intent = new Intent(BalanceActivity.this, ExodusActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS | Intent.FLAG_ACTIVITY_SINGLE_TOP); BalanceActivity.this.startActivity(intent); }}); alert.setButton(AlertDialog.BUTTON_NEGATIVE, getString(R.string.no), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); if(!isFinishing()) { alert.show(); } return true; } else { ; } return false; } private void doSettings() { TimeOutUtil.getInstance().updatePin(); Intent intent = new Intent(BalanceActivity.this, SettingsActivity.class); startActivity(intent); } private void doUTXO() { Intent intent = new Intent(BalanceActivity.this, UTXOActivity.class); startActivity(intent); } private void doScan() { Intent intent = new Intent(BalanceActivity.this, ZBarScannerActivity.class); intent.putExtra(ZBarConstants.SCAN_MODES, new int[]{ Symbol.QRCODE } ); startActivityForResult(intent, SCAN_QR); } private void doSweepViaScan() { Intent intent = new Intent(BalanceActivity.this, ZBarScannerActivity.class); intent.putExtra(ZBarConstants.SCAN_MODES, new int[]{ Symbol.QRCODE } ); startActivityForResult(intent, SCAN_COLD_STORAGE); } private void doSweep() { AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(R.string.action_sweep) .setCancelable(false) .setPositiveButton(R.string.enter_privkey, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { final EditText privkey = new EditText(BalanceActivity.this); privkey.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(R.string.enter_privkey) .setView(privkey) .setCancelable(false) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { final String strPrivKey = privkey.getText().toString(); if(strPrivKey != null && strPrivKey.length() > 0) { doPrivKey(strPrivKey); } } }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }); if(!isFinishing()) { dlg.show(); } } }).setNegativeButton(R.string.scan, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { doSweepViaScan(); } }); if(!isFinishing()) { dlg.show(); } } private void doPrivKey(final String data) { PrivKeyReader privKeyReader = null; String format = null; try { privKeyReader = new PrivKeyReader(new CharSequenceX(data), null); format = privKeyReader.getFormat(); } catch(Exception e) { Toast.makeText(BalanceActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); return; } if(format != null) { if(format.equals(PrivKeyReader.BIP38)) { final PrivKeyReader pvr = privKeyReader; final EditText password38 = new EditText(BalanceActivity.this); AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(R.string.bip38_pw) .setView(password38) .setCancelable(false) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String password = password38.getText().toString(); ProgressDialog progress = new ProgressDialog(BalanceActivity.this); progress.setCancelable(false); progress.setTitle(R.string.app_name); progress.setMessage(getString(R.string.decrypting_bip38)); progress.show(); boolean keyDecoded = false; try { BIP38PrivateKey bip38 = new BIP38PrivateKey(SamouraiWallet.getInstance().getCurrentNetworkParams(), data); final ECKey ecKey = bip38.decrypt(password); if(ecKey != null && ecKey.hasPrivKey()) { if(progress != null && progress.isShowing()) { progress.cancel(); } pvr.setPassword(new CharSequenceX(password)); keyDecoded = true; Toast.makeText(BalanceActivity.this, pvr.getFormat(), Toast.LENGTH_SHORT).show(); Toast.makeText(BalanceActivity.this, pvr.getKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(), Toast.LENGTH_SHORT).show(); } } catch(Exception e) { e.printStackTrace(); Toast.makeText(BalanceActivity.this, R.string.bip38_pw_error, Toast.LENGTH_SHORT).show(); } if(progress != null && progress.isShowing()) { progress.cancel(); } if(keyDecoded) { SweepUtil.getInstance(BalanceActivity.this).sweep(pvr, false); } } }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Toast.makeText(BalanceActivity.this, R.string.bip38_pw_error, Toast.LENGTH_SHORT).show(); } }); if(!isFinishing()) { dlg.show(); } } else if(privKeyReader != null) { SweepUtil.getInstance(BalanceActivity.this).sweep(privKeyReader, false); } else { ; } } else { Toast.makeText(BalanceActivity.this, R.string.cannot_recognize_privkey, Toast.LENGTH_SHORT).show(); } } private void doBackup() { try { final String passphrase = HD_WalletFactory.getInstance(BalanceActivity.this).get().getPassphrase(); final String[] export_methods = new String[2]; export_methods[0] = getString(R.string.export_to_clipboard); export_methods[1] = getString(R.string.export_to_email); new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.options_export) .setSingleChoiceItems(export_methods, 0, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { try { PayloadUtil.getInstance(BalanceActivity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(BalanceActivity.this).getGUID() + AccessFactory.getInstance(BalanceActivity.this).getPIN())); } catch (IOException ioe) { ; } catch (JSONException je) { ; } catch (DecryptionException de) { ; } catch (MnemonicException.MnemonicLengthException mle) { ; } String encrypted = null; try { encrypted = AESUtil.encrypt(PayloadUtil.getInstance(BalanceActivity.this).getPayload().toString(), new CharSequenceX(passphrase), AESUtil.DefaultPBKDF2Iterations); } catch (Exception e) { Toast.makeText(BalanceActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); } finally { if (encrypted == null) { Toast.makeText(BalanceActivity.this, R.string.encryption_error, Toast.LENGTH_SHORT).show(); return; } } JSONObject obj = PayloadUtil.getInstance(BalanceActivity.this).putPayload(encrypted, true); if (which == 0) { android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(android.content.Context.CLIPBOARD_SERVICE); android.content.ClipData clip = null; clip = android.content.ClipData.newPlainText("Wallet backup", obj.toString()); clipboard.setPrimaryClip(clip); Toast.makeText(BalanceActivity.this, R.string.copied_to_clipboard, Toast.LENGTH_SHORT).show(); } else { Intent email = new Intent(Intent.ACTION_SEND); email.putExtra(Intent.EXTRA_SUBJECT, "Samourai Wallet backup"); email.putExtra(Intent.EXTRA_TEXT, obj.toString()); email.setType("message/rfc822"); startActivity(Intent.createChooser(email, BalanceActivity.this.getText(R.string.choose_email_client))); } dialog.dismiss(); } } ).show(); } catch(IOException ioe) { ioe.printStackTrace(); Toast.makeText(BalanceActivity.this, "HD wallet error", Toast.LENGTH_SHORT).show(); } catch(MnemonicException.MnemonicLengthException mle) { mle.printStackTrace(); Toast.makeText(BalanceActivity.this, "HD wallet error", Toast.LENGTH_SHORT).show(); } } private class TransactionAdapter extends BaseAdapter { private LayoutInflater inflater = null; private static final int TYPE_ITEM = 0; private static final int TYPE_BALANCE = 1; TransactionAdapter() { inflater = (LayoutInflater)BalanceActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { if(txs == null) { txs = new ArrayList<Tx>(); txStates = new HashMap<String, Boolean>(); } return txs.size() + 1; } @Override public String getItem(int position) { if(txs == null) { txs = new ArrayList<Tx>(); txStates = new HashMap<String, Boolean>(); } if(position == 0) { return ""; } return txs.get(position - 1).toString(); } @Override public long getItemId(int position) { return position - 1; } @Override public int getItemViewType(int position) { return position == 0 ? TYPE_BALANCE : TYPE_ITEM; } @Override public int getViewTypeCount() { return 2; } @Override public View getView(final int position, View convertView, final ViewGroup parent) { View view = null; int type = getItemViewType(position); if(convertView == null) { if(type == TYPE_BALANCE) { view = tvBalanceBar; } else { view = inflater.inflate(R.layout.tx_layout_simple, parent, false); } } else { view = convertView; } if(type == TYPE_BALANCE) { ; } else { view.findViewById(R.id.TransactionStatus).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ((ListView)parent).performItemClick(v, position, 0); } }); view.findViewById(R.id.ConfirmationCount).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ((ListView)parent).performItemClick(v, position, 0); } }); Tx tx = txs.get(position - 1); TextView tvTodayLabel = (TextView)view.findViewById(R.id.TodayLabel); String strDateGroup = DateUtil.getInstance(BalanceActivity.this).group(tx.getTS()); if(position == 1) { tvTodayLabel.setText(strDateGroup); tvTodayLabel.setVisibility(View.VISIBLE); } else { Tx prevTx = txs.get(position - 2); String strPrevDateGroup = DateUtil.getInstance(BalanceActivity.this).group(prevTx.getTS()); if(strPrevDateGroup.equals(strDateGroup)) { tvTodayLabel.setVisibility(View.GONE); } else { tvTodayLabel.setText(strDateGroup); tvTodayLabel.setVisibility(View.VISIBLE); } } String strDetails = null; String strTS = DateUtil.getInstance(BalanceActivity.this).formatted(tx.getTS()); long _amount = 0L; if(tx.getAmount() < 0.0) { _amount = Math.abs((long)tx.getAmount()); strDetails = BalanceActivity.this.getString(R.string.you_sent); } else { _amount = (long)tx.getAmount(); strDetails = BalanceActivity.this.getString(R.string.you_received); } String strAmount = null; String strUnits = null; if(isBTC) { strAmount = getBTCDisplayAmount(_amount); strUnits = getBTCDisplayUnits(); } else { strAmount = getFiatDisplayAmount(_amount); strUnits = getFiatDisplayUnits(); } TextView tvDirection = (TextView)view.findViewById(R.id.TransactionDirection); TextView tvDirection2 = (TextView)view.findViewById(R.id.TransactionDirection2); TextView tvDetails = (TextView)view.findViewById(R.id.TransactionDetails); ImageView ivTxStatus = (ImageView)view.findViewById(R.id.TransactionStatus); TextView tvConfirmationCount = (TextView)view.findViewById(R.id.ConfirmationCount); tvDirection.setTypeface(TypefaceUtil.getInstance(BalanceActivity.this).getAwesomeTypeface()); if(tx.getAmount() < 0.0) { tvDirection.setTextColor(Color.RED); tvDirection.setText(Character.toString((char) TypefaceUtil.awesome_arrow_up)); } else { tvDirection.setTextColor(Color.GREEN); tvDirection.setText(Character.toString((char) TypefaceUtil.awesome_arrow_down)); } if(txStates.containsKey(tx.getHash()) && txStates.get(tx.getHash()) == false) { txStates.put(tx.getHash(), false); displayTxStatus(false, tx.getConfirmations(), tvConfirmationCount, ivTxStatus); } else { txStates.put(tx.getHash(), true); displayTxStatus(true, tx.getConfirmations(), tvConfirmationCount, ivTxStatus); } tvDirection2.setText(strDetails + " " + strAmount + " " + strUnits); if(tx.getPaymentCode() != null) { String strTaggedTS = strTS + " "; String strSubText = " " + BIP47Meta.getInstance().getDisplayLabel(tx.getPaymentCode()) + " "; strTaggedTS += strSubText; tvDetails.setText(strTaggedTS); } else { tvDetails.setText(strTS); } } return view; } } private void refreshTx(final boolean notifTx, final boolean fetch, final boolean dragged, final boolean launch) { if(refreshTask == null || refreshTask.getStatus().equals(AsyncTask.Status.FINISHED)) { refreshTask = new RefreshTask(dragged, launch); refreshTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, notifTx ? "1" : "0", fetch ? "1" : "0"); } } private void displayBalance() { String strFiat = PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.CURRENT_FIAT, "USD"); double btc_fx = ExchangeRateFactory.getInstance(BalanceActivity.this).getAvgPrice(strFiat); long balance = 0L; if(SamouraiWallet.getInstance().getShowTotalBalance()) { if(SamouraiWallet.getInstance().getCurrentSelectedAccount() == 0) { balance = APIFactory.getInstance(BalanceActivity.this).getXpubBalance(); } else { if(APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().size() > 0) { try { if(APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().get(HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(SamouraiWallet.getInstance().getCurrentSelectedAccount() - 1).xpubstr()) != null) { balance = APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().get(HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(SamouraiWallet.getInstance().getCurrentSelectedAccount() - 1).xpubstr()); } } catch(IOException ioe) { ; } catch(MnemonicException.MnemonicLengthException mle) { ; } } } } else { if(APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().size() > 0) { try { if(APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().get(HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(SamouraiWallet.getInstance().getCurrentSelectedAccount()).xpubstr()) != null) { balance = APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().get(HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(SamouraiWallet.SAMOURAI_ACCOUNT).xpubstr()); } } catch(IOException ioe) { ; } catch(MnemonicException.MnemonicLengthException mle) { ; } } } double btc_balance = (((double)balance) / 1e8); double fiat_balance = btc_fx * btc_balance; if(isBTC) { tvBalanceAmount.setText(getBTCDisplayAmount(balance)); tvBalanceUnits.setText(getBTCDisplayUnits()); } else { tvBalanceAmount.setText(MonetaryUtil.getInstance().getFiatFormat(strFiat).format(fiat_balance)); tvBalanceUnits.setText(strFiat); } } private String getBTCDisplayAmount(long value) { String strAmount = null; DecimalFormat df = new DecimalFormat(" df.setMinimumIntegerDigits(1); df.setMinimumFractionDigits(1); df.setMaximumFractionDigits(8); int unit = PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.BTC_UNITS, MonetaryUtil.UNIT_BTC); switch(unit) { case MonetaryUtil.MICRO_BTC: strAmount = df.format(((double)(value * 1000000L)) / 1e8); break; case MonetaryUtil.MILLI_BTC: strAmount = df.format(((double)(value * 1000L)) / 1e8); break; default: strAmount = Coin.valueOf(value).toPlainString(); break; } return strAmount; } private String getBTCDisplayUnits() { return (String) MonetaryUtil.getInstance().getBTCUnits()[PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.BTC_UNITS, MonetaryUtil.UNIT_BTC)]; } private String getFiatDisplayAmount(long value) { String strFiat = PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.CURRENT_FIAT, "USD"); double btc_fx = ExchangeRateFactory.getInstance(BalanceActivity.this).getAvgPrice(strFiat); String strAmount = MonetaryUtil.getInstance().getFiatFormat(strFiat).format(btc_fx * (((double)value) / 1e8)); return strAmount; } private String getFiatDisplayUnits() { return PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.CURRENT_FIAT, "USD"); } private void displayTxStatus(boolean heads, long confirmations, TextView tvConfirmationCount, ImageView ivTxStatus) { if(heads) { if(confirmations == 0) { rotateTxStatus(tvConfirmationCount, true); ivTxStatus.setVisibility(View.VISIBLE); ivTxStatus.setImageResource(R.drawable.ic_query_builder_white); tvConfirmationCount.setVisibility(View.GONE); } else if(confirmations > 3) { rotateTxStatus(tvConfirmationCount, true); ivTxStatus.setVisibility(View.VISIBLE); ivTxStatus.setImageResource(R.drawable.ic_done_white); tvConfirmationCount.setVisibility(View.GONE); } else { rotateTxStatus(ivTxStatus, false); tvConfirmationCount.setVisibility(View.VISIBLE); tvConfirmationCount.setText(Long.toString(confirmations)); ivTxStatus.setVisibility(View.GONE); } } else { if(confirmations < 100) { rotateTxStatus(ivTxStatus, false); tvConfirmationCount.setVisibility(View.VISIBLE); tvConfirmationCount.setText(Long.toString(confirmations)); ivTxStatus.setVisibility(View.GONE); } else { rotateTxStatus(ivTxStatus, false); tvConfirmationCount.setVisibility(View.VISIBLE); tvConfirmationCount.setText("\u221e"); ivTxStatus.setVisibility(View.GONE); } } } private void rotateTxStatus(View view, boolean clockwise) { float degrees = 360f; if(!clockwise) { degrees = -360f; } ObjectAnimator animation = ObjectAnimator.ofFloat(view, "rotationY", 0.0f, degrees); animation.setDuration(1000); animation.setRepeatCount(0); animation.setInterpolator(new AnticipateInterpolator()); animation.start(); } private void doExplorerView(String strHash) { if(strHash != null) { int sel = PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.BLOCK_EXPLORER, 0); if(sel >= BlockExplorerUtil.getInstance().getBlockExplorerTxUrls().length) { sel = 0; } CharSequence url = BlockExplorerUtil.getInstance().getBlockExplorerTxUrls()[sel]; Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url + strHash)); startActivity(browserIntent); } } private class RefreshTask extends AsyncTask<String, Void, String> { private String strProgressTitle = null; private String strProgressMessage = null; private ProgressDialog progress = null; private Handler handler = null; private boolean dragged = false; private boolean launch = false; public RefreshTask(boolean dragged, boolean launch) { super(); Log.d("BalanceActivity", "RefreshTask, dragged==" + dragged); handler = new Handler(); this.dragged = dragged; this.launch = launch; } @Override protected void onPreExecute() { Log.d("BalanceActivity", "RefreshTask.preExecute()"); if(progress != null && progress.isShowing()) { progress.dismiss(); } if(!dragged) { strProgressTitle = BalanceActivity.this.getText(R.string.app_name).toString(); strProgressMessage = BalanceActivity.this.getText(R.string.refresh_tx_pre).toString(); progress = new ProgressDialog(BalanceActivity.this); progress.setCancelable(true); progress.setTitle(strProgressTitle); progress.setMessage(strProgressMessage); progress.show(); } } @Override protected String doInBackground(String... params) { Log.d("BalanceActivity", "doInBackground()"); final boolean notifTx = params[0].equals("1") ? true : false; final boolean fetch = params[1].equals("1") ? true : false; // TBD: check on lookahead/lookbehind for all incoming payment codes if(fetch || txs.size() == 0) { APIFactory.getInstance(BalanceActivity.this).initWallet(); } try { int acc = 0; txs = APIFactory.getInstance(BalanceActivity.this).getAllXpubTxs(); if(txs != null) { Collections.sort(txs, new APIFactory.TxMostRecentDateComparator()); } if(AddressFactory.getInstance().getHighestTxReceiveIdx(acc) > HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(acc).getReceive().getAddrIdx()) { HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(acc).getReceive().setAddrIdx(AddressFactory.getInstance().getHighestTxReceiveIdx(acc)); } if(AddressFactory.getInstance().getHighestTxChangeIdx(acc) > HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(acc).getChange().getAddrIdx()) { HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(acc).getChange().setAddrIdx(AddressFactory.getInstance().getHighestTxChangeIdx(acc)); } if(AddressFactory.getInstance().getHighestBIP49ReceiveIdx() > BIP49Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getReceive().getAddrIdx()) { BIP49Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getReceive().setAddrIdx(AddressFactory.getInstance().getHighestBIP49ReceiveIdx()); } if(AddressFactory.getInstance().getHighestBIP49ChangeIdx() > BIP49Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getChange().getAddrIdx()) { BIP49Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getChange().setAddrIdx(AddressFactory.getInstance().getHighestBIP49ChangeIdx()); } } catch(IOException ioe) { ioe.printStackTrace(); } catch(MnemonicException.MnemonicLengthException mle) { mle.printStackTrace(); } finally { ; } if(!dragged) { strProgressMessage = BalanceActivity.this.getText(R.string.refresh_tx).toString(); publishProgress(); } handler.post(new Runnable() { public void run() { if(dragged) { swipeRefreshLayout.setRefreshing(false); } tvBalanceAmount.setText(""); tvBalanceUnits.setText(""); displayBalance(); txAdapter.notifyDataSetChanged(); } }); PrefsUtil.getInstance(BalanceActivity.this).setValue(PrefsUtil.FIRST_RUN, false); if(notifTx) { // check for incoming payment code notification tx try { PaymentCode pcode = BIP47Util.getInstance(BalanceActivity.this).getPaymentCode(); // Log.i("BalanceFragment", "payment code:" + pcode.toString()); // Log.i("BalanceFragment", "notification address:" + pcode.notificationAddress().getAddressString()); APIFactory.getInstance(BalanceActivity.this).getNotifAddress(pcode.notificationAddress().getAddressString()); } catch (AddressFormatException afe) { afe.printStackTrace(); Toast.makeText(BalanceActivity.this, "HD wallet error", Toast.LENGTH_SHORT).show(); } strProgressMessage = BalanceActivity.this.getText(R.string.refresh_incoming_notif_tx).toString(); publishProgress(); // check on outgoing payment code notification tx List<Pair<String,String>> outgoingUnconfirmed = BIP47Meta.getInstance().getOutgoingUnconfirmed(); // Log.i("BalanceFragment", "outgoingUnconfirmed:" + outgoingUnconfirmed.size()); for(Pair<String,String> pair : outgoingUnconfirmed) { // Log.i("BalanceFragment", "outgoing payment code:" + pair.getLeft()); // Log.i("BalanceFragment", "outgoing payment code tx:" + pair.getRight()); int confirmations = APIFactory.getInstance(BalanceActivity.this).getNotifTxConfirmations(pair.getRight()); if(confirmations > 0) { BIP47Meta.getInstance().setOutgoingStatus(pair.getLeft(), BIP47Meta.STATUS_SENT_CFM); } if(confirmations == -1) { BIP47Meta.getInstance().setOutgoingStatus(pair.getLeft(), BIP47Meta.STATUS_NOT_SENT); } } if(!dragged) { strProgressMessage = BalanceActivity.this.getText(R.string.refresh_outgoing_notif_tx).toString(); publishProgress(); } Intent intent = new Intent("com.samourai.wallet.BalanceActivity.RESTART_SERVICE"); LocalBroadcastManager.getInstance(BalanceActivity.this).sendBroadcast(intent); } if(!dragged) { if(PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.GUID_V, 0) < 4) { Log.i("BalanceActivity", "guid_v < 4"); try { String _guid = AccessFactory.getInstance(BalanceActivity.this).createGUID(); String _hash = AccessFactory.getInstance(BalanceActivity.this).getHash(_guid, new CharSequenceX(AccessFactory.getInstance(BalanceActivity.this).getPIN()), AESUtil.DefaultPBKDF2Iterations); PayloadUtil.getInstance(BalanceActivity.this).saveWalletToJSON(new CharSequenceX(_guid + AccessFactory.getInstance().getPIN())); PrefsUtil.getInstance(BalanceActivity.this).setValue(PrefsUtil.ACCESS_HASH, _hash); PrefsUtil.getInstance(BalanceActivity.this).setValue(PrefsUtil.ACCESS_HASH2, _hash); Log.i("BalanceActivity", "guid_v == 4"); } catch(MnemonicException.MnemonicLengthException | IOException | JSONException | DecryptionException e) { ; } } else if(!launch) { try { PayloadUtil.getInstance(BalanceActivity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(BalanceActivity.this).getGUID() + AccessFactory.getInstance(BalanceActivity.this).getPIN())); } catch(Exception e) { } } else { ; } } /* if(PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.XPUB44LOCK, false) == false) { try { String[] s = HD_WalletFactory.getInstance(BalanceActivity.this).get().getXPUBs(); for(int i = 0; i < s.length; i++) { APIFactory.getInstance(BalanceActivity.this).lockXPUB(s[0], false); } } catch(IOException | MnemonicException.MnemonicLengthException e) { ; } } if(PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.XPUB49LOCK, false) == false) { ; } */ return "OK"; } @Override protected void onPostExecute(String result) { if(!dragged) { if(progress != null && progress.isShowing()) { progress.dismiss(); } } } @Override protected void onProgressUpdate(Void... values) { if(!dragged) { progress.setTitle(strProgressTitle); progress.setMessage(strProgressMessage); } } } private class PoWTask extends AsyncTask<String, Void, String> { private boolean isOK = true; private String strBlockHash = null; @Override protected String doInBackground(String... params) { strBlockHash = params[0]; JSONRPC jsonrpc = new JSONRPC(TrustedNodeUtil.getInstance().getUser(), TrustedNodeUtil.getInstance().getPassword(), TrustedNodeUtil.getInstance().getNode(), TrustedNodeUtil.getInstance().getPort()); JSONObject nodeObj = jsonrpc.getBlockHeader(strBlockHash); if(nodeObj != null && nodeObj.has("hash")) { PoW pow = new PoW(strBlockHash); String hash = pow.calcHash(nodeObj); if(hash != null && hash.toLowerCase().equals(strBlockHash.toLowerCase())) { JSONObject headerObj = APIFactory.getInstance(BalanceActivity.this).getBlockHeader(strBlockHash); if(headerObj != null && headerObj.has("")) { if(!pow.check(headerObj, nodeObj, hash)) { isOK = false; } } } else { isOK = false; } } return "OK"; } @Override protected void onPostExecute(String result) { if(!isOK) { new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(getString(R.string.trusted_node_pow_failed) + "\n" + "Block hash:" + strBlockHash) .setCancelable(false) .setPositiveButton(R.string.close, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }).show(); } } @Override protected void onPreExecute() { ; } } private class CPFPTask extends AsyncTask<String, Void, String> { private List<UTXO> utxos = null; private Handler handler = null; @Override protected void onPreExecute() { handler = new Handler(); utxos = APIFactory.getInstance(BalanceActivity.this).getUtxos(); } @Override protected String doInBackground(String... params) { Looper.prepare(); Log.d("BalanceActivity", "hash:" + params[0]); JSONObject txObj = APIFactory.getInstance(BalanceActivity.this).getTxInfo(params[0]); if(txObj.has("inputs") && txObj.has("outputs")) { final SuggestedFee suggestedFee = FeeUtil.getInstance().getSuggestedFee(); try { JSONArray inputs = txObj.getJSONArray("inputs"); JSONArray outputs = txObj.getJSONArray("outputs"); int p2pkh = 0; int p2wpkh = 0; for(int i = 0; i < inputs.length(); i++) { if(inputs.getJSONObject(i).has("outpoint") && inputs.getJSONObject(i).getJSONObject("outpoint").has("scriptpubkey")) { String scriptpubkey = inputs.getJSONObject(i).getJSONObject("outpoint").getString("scriptpubkey"); Script script = new Script(Hex.decode(scriptpubkey)); Address address = script.getToAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()); if(address.isP2SHAddress()) { p2wpkh++; } else { p2pkh++; } } } FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getHighFee()); BigInteger estimatedFee = FeeUtil.getInstance().estimatedFeeSegwit(p2pkh, p2wpkh, outputs.length()); long total_inputs = 0L; long total_outputs = 0L; long fee = 0L; UTXO utxo = null; for(int i = 0; i < inputs.length(); i++) { JSONObject obj = inputs.getJSONObject(i); if(obj.has("outpoint")) { JSONObject objPrev = obj.getJSONObject("outpoint"); if(objPrev.has("value")) { total_inputs += objPrev.getLong("value"); } } } for(int i = 0; i < outputs.length(); i++) { JSONObject obj = outputs.getJSONObject(i); if(obj.has("value")) { total_outputs += obj.getLong("value"); String addr = obj.getString("address"); Log.d("BalanceActivity", "checking address:" + addr); if(utxo == null) { utxo = getUTXO(addr); } else { break; } } } boolean feeWarning = false; fee = total_inputs - total_outputs; if(fee > estimatedFee.longValue()) { feeWarning = true; } Log.d("BalanceActivity", "total inputs:" + total_inputs); Log.d("BalanceActivity", "total outputs:" + total_outputs); Log.d("BalanceActivity", "fee:" + fee); Log.d("BalanceActivity", "estimated fee:" + estimatedFee.longValue()); Log.d("BalanceActivity", "fee warning:" + feeWarning); if(utxo != null) { Log.d("BalanceActivity", "utxo found"); List<UTXO> selectedUTXO = new ArrayList<UTXO>(); selectedUTXO.add(utxo); int selected = utxo.getOutpoints().size(); long remainingFee = (estimatedFee.longValue() > fee) ? estimatedFee.longValue() - fee : 0L; Log.d("BalanceActivity", "remaining fee:" + remainingFee); int receiveIdx = AddressFactory.getInstance(BalanceActivity.this).getHighestTxReceiveIdx(0); Log.d("BalanceActivity", "receive index:" + receiveIdx); final String addr = outputs.getJSONObject(0).getString("address"); final String ownReceiveAddr; if(Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), addr).isP2SHAddress()) { ownReceiveAddr = AddressFactory.getInstance(BalanceActivity.this).getBIP49(AddressFactory.RECEIVE_CHAIN).getAddressAsString(); } else { ownReceiveAddr = AddressFactory.getInstance(BalanceActivity.this).get(AddressFactory.RECEIVE_CHAIN).getAddressString(); } Log.d("BalanceActivity", "receive address:" + ownReceiveAddr); long totalAmount = utxo.getValue(); Log.d("BalanceActivity", "amount before fee:" + totalAmount); Pair<Integer,Integer> outpointTypes = FeeUtil.getInstance().getOutpointCount(utxo.getOutpoints()); BigInteger cpfpFee = FeeUtil.getInstance().estimatedFeeSegwit(outpointTypes.getLeft(), outpointTypes.getRight(), 1); Log.d("BalanceActivity", "cpfp fee:" + cpfpFee.longValue()); p2pkh = outpointTypes.getLeft(); p2wpkh = outpointTypes.getRight(); if(totalAmount < (cpfpFee.longValue() + remainingFee)) { Log.d("BalanceActivity", "selecting additional utxo"); Collections.sort(utxos, new UTXO.UTXOComparator()); for(UTXO _utxo : utxos) { totalAmount += _utxo.getValue(); selectedUTXO.add(_utxo); selected += _utxo.getOutpoints().size(); outpointTypes = FeeUtil.getInstance().getOutpointCount(utxo.getOutpoints()); p2pkh += outpointTypes.getLeft(); p2wpkh += outpointTypes.getRight(); cpfpFee = FeeUtil.getInstance().estimatedFeeSegwit(p2pkh, p2wpkh, 1); if(totalAmount > (cpfpFee.longValue() + remainingFee + SamouraiWallet.bDust.longValue())) { break; } } if(totalAmount < (cpfpFee.longValue() + remainingFee + SamouraiWallet.bDust.longValue())) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, R.string.insufficient_funds, Toast.LENGTH_SHORT).show(); } }); FeeUtil.getInstance().setSuggestedFee(suggestedFee); return "KO"; } } cpfpFee = cpfpFee.add(BigInteger.valueOf(remainingFee)); Log.d("BalanceActivity", "cpfp fee:" + cpfpFee.longValue()); final List<MyTransactionOutPoint> outPoints = new ArrayList<MyTransactionOutPoint>(); for(UTXO u : selectedUTXO) { outPoints.addAll(u.getOutpoints()); } long _totalAmount = 0L; for(MyTransactionOutPoint outpoint : outPoints) { _totalAmount += outpoint.getValue().longValue(); } Log.d("BalanceActivity", "checked total amount:" + _totalAmount); assert(_totalAmount == totalAmount); long amount = totalAmount - cpfpFee.longValue(); Log.d("BalanceActivity", "amount after fee:" + amount); if(amount < SamouraiWallet.bDust.longValue()) { Log.d("BalanceActivity", "dust output"); Toast.makeText(BalanceActivity.this, R.string.cannot_output_dust, Toast.LENGTH_SHORT).show(); } final HashMap<String, BigInteger> receivers = new HashMap<String, BigInteger>(); receivers.put(ownReceiveAddr, BigInteger.valueOf(amount)); String message = ""; if(feeWarning) { message += BalanceActivity.this.getString(R.string.fee_bump_not_necessary); message += "\n\n"; } message += BalanceActivity.this.getString(R.string.bump_fee) + " " + Coin.valueOf(remainingFee).toPlainString() + " BTC"; AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(message) .setCancelable(false) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { if(AppUtil.getInstance(BalanceActivity.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) { stopService(new Intent(BalanceActivity.this.getApplicationContext(), WebSocketService.class)); } startService(new Intent(BalanceActivity.this.getApplicationContext(), WebSocketService.class)); Transaction tx = SendFactory.getInstance(BalanceActivity.this).makeTransaction(0, outPoints, receivers); if(tx != null) { tx = SendFactory.getInstance(BalanceActivity.this).signTransaction(tx); final String hexTx = new String(Hex.encode(tx.bitcoinSerialize())); Log.d("BalanceActivity", hexTx); final String strTxHash = tx.getHashAsString(); Log.d("BalanceActivity", strTxHash); boolean isOK = false; try { isOK = PushTx.getInstance(BalanceActivity.this).pushTx(hexTx); if(isOK) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, R.string.cpfp_spent, Toast.LENGTH_SHORT).show(); FeeUtil.getInstance().setSuggestedFee(suggestedFee); Intent _intent = new Intent(BalanceActivity.this, MainActivity2.class); _intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); startActivity(_intent); } }); } else { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, R.string.tx_failed, Toast.LENGTH_SHORT).show(); } }); // reset receive index upon tx fail if(Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), addr).isP2SHAddress()) { int prevIdx = BIP49Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getReceive().getAddrIdx() - 1; BIP49Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getReceive().setAddrIdx(prevIdx); } else { int prevIdx = HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(0).getReceive().getAddrIdx() - 1; HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(0).getReceive().setAddrIdx(prevIdx); } } } catch(MnemonicException.MnemonicLengthException | DecoderException | IOException e) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, "pushTx:" + e.getMessage(), Toast.LENGTH_SHORT).show(); } }); } finally { ; } } } }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { try { if(Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), addr).isP2SHAddress()) { int prevIdx = BIP49Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getReceive().getAddrIdx() - 1; BIP49Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getReceive().setAddrIdx(prevIdx); } else { int prevIdx = HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(0).getReceive().getAddrIdx() - 1; HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(0).getReceive().setAddrIdx(prevIdx); } } catch(MnemonicException.MnemonicLengthException | DecoderException | IOException e) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); } }); } finally { dialog.dismiss(); } } }); if(!isFinishing()) { dlg.show(); } } else { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, R.string.cannot_create_cpfp, Toast.LENGTH_SHORT).show(); } }); } } catch(final JSONException je) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, "cpfp:" + je.getMessage(), Toast.LENGTH_SHORT).show(); } }); } FeeUtil.getInstance().setSuggestedFee(suggestedFee); } else { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, R.string.cpfp_cannot_retrieve_tx, Toast.LENGTH_SHORT).show(); } }); } Looper.loop(); return "OK"; } @Override protected void onPostExecute(String result) { ; } @Override protected void onProgressUpdate(Void... values) { ; } private UTXO getUTXO(String address) { UTXO ret = null; int idx = -1; for(int i = 0; i < utxos.size(); i++) { UTXO utxo = utxos.get(i); Log.d("BalanceActivity", "utxo address:" + utxo.getOutpoints().get(0).getAddress()); if(utxo.getOutpoints().get(0).getAddress().equals(address)) { ret = utxo; idx = i; break; } } if(ret != null) { utxos.remove(idx); return ret; } return null; } } private class RBFTask extends AsyncTask<String, Void, String> { private List<UTXO> utxos = null; private Handler handler = null; private RBFSpend rbf = null; @Override protected void onPreExecute() { handler = new Handler(); utxos = APIFactory.getInstance(BalanceActivity.this).getUtxos(); } @Override protected String doInBackground(final String... params) { Looper.prepare(); Log.d("BalanceActivity", "hash:" + params[0]); rbf = RBFUtil.getInstance().get(params[0]); Log.d("BalanceActivity", "rbf:" + ((rbf == null) ? "null" : "not null")); final Transaction tx = new Transaction(SamouraiWallet.getInstance().getCurrentNetworkParams(), Hex.decode(rbf.getSerializedTx())); Log.d("BalanceActivity", "tx serialized:" + rbf.getSerializedTx()); Log.d("BalanceActivity", "tx inputs:" + tx.getInputs().size()); Log.d("BalanceActivity", "tx outputs:" + tx.getOutputs().size()); JSONObject txObj = APIFactory.getInstance(BalanceActivity.this).getTxInfo(params[0]); if(tx != null && txObj.has("inputs") && txObj.has("outputs")) { try { JSONArray inputs = txObj.getJSONArray("inputs"); JSONArray outputs = txObj.getJSONArray("outputs"); int p2pkh = 0; int p2wpkh = 0; for(int i = 0; i < inputs.length(); i++) { if(inputs.getJSONObject(i).has("outpoint") && inputs.getJSONObject(i).getJSONObject("outpoint").has("scriptpubkey")) { String scriptpubkey = inputs.getJSONObject(i).getJSONObject("outpoint").getString("scriptpubkey"); Script script = new Script(Hex.decode(scriptpubkey)); Address address = script.getToAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()); if(address.isP2SHAddress()) { p2wpkh++; } else { p2pkh++; } } } SuggestedFee suggestedFee = FeeUtil.getInstance().getSuggestedFee(); FeeUtil.getInstance().setSuggestedFee(FeeUtil.getInstance().getHighFee()); BigInteger estimatedFee = FeeUtil.getInstance().estimatedFeeSegwit(p2pkh, p2wpkh, outputs.length()); long total_inputs = 0L; long total_outputs = 0L; long fee = 0L; long total_change = 0L; List<String> selfAddresses = new ArrayList<String>(); for(int i = 0; i < inputs.length(); i++) { JSONObject obj = inputs.getJSONObject(i); if(obj.has("outpoint")) { JSONObject objPrev = obj.getJSONObject("outpoint"); if(objPrev.has("value")) { total_inputs += objPrev.getLong("value"); } } } for(int i = 0; i < outputs.length(); i++) { JSONObject obj = outputs.getJSONObject(i); if(obj.has("value")) { total_outputs += obj.getLong("value"); String _addr = obj.getString("address"); selfAddresses.add(_addr); if(_addr != null && rbf.getChangeAddrs().contains(_addr.toString())) { total_change += obj.getLong("value"); } } } boolean isBIP49 = true; isBIP49 = Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), outputs.getJSONObject(0).getString("address")).isP2SHAddress(); boolean feeWarning = false; fee = total_inputs - total_outputs; if(fee > estimatedFee.longValue()) { feeWarning = true; } long remainingFee = (estimatedFee.longValue() > fee) ? estimatedFee.longValue() - fee : 0L; Log.d("BalanceActivity", "total inputs:" + total_inputs); Log.d("BalanceActivity", "total outputs:" + total_outputs); Log.d("BalanceActivity", "total change:" + total_change); Log.d("BalanceActivity", "fee:" + fee); Log.d("BalanceActivity", "estimated fee:" + estimatedFee.longValue()); Log.d("BalanceActivity", "fee warning:" + feeWarning); Log.d("BalanceActivity", "remaining fee:" + remainingFee); List<TransactionOutput> txOutputs = new ArrayList<TransactionOutput>(); txOutputs.addAll(tx.getOutputs()); long remainder = remainingFee; if(total_change > remainder) { for(TransactionOutput output : txOutputs) { if(rbf.getChangeAddrs().contains(output.getAddressFromP2SH(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString()) || rbf.getChangeAddrs().contains(output.getAddressFromP2PKHScript(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString())) { if(output.getValue().longValue() >= (remainder + SamouraiWallet.bDust.longValue())) { output.setValue(Coin.valueOf(output.getValue().longValue() - remainder)); remainder = 0L; break; } else { remainder -= output.getValue().longValue(); output.setValue(Coin.valueOf(0L)); // output will be discarded later } } } } // original inputs are not modified List<MyTransactionInput> _inputs = new ArrayList<MyTransactionInput>(); List<TransactionInput> txInputs = tx.getInputs(); for(TransactionInput input : txInputs) { MyTransactionInput _input = new MyTransactionInput(SamouraiWallet.getInstance().getCurrentNetworkParams(), null, new byte[0], input.getOutpoint(), input.getOutpoint().getHash().toString(), (int)input.getOutpoint().getIndex()); _input.setSequenceNumber(SamouraiWallet.RBF_SEQUENCE_NO); _inputs.add(_input); Log.d("BalanceActivity", "add outpoint:" + _input.getOutpoint().toString()); } Pair<Integer,Integer> outpointTypes = null; if(remainder > 0L) { List<UTXO> selectedUTXO = new ArrayList<UTXO>(); long selectedAmount = 0L; int selected = 0; long _remainingFee = remainder; Collections.sort(utxos, new UTXO.UTXOComparator()); for(UTXO _utxo : utxos) { Log.d("BalanceActivity", "utxo value:" + _utxo.getValue()); // do not select utxo that are change outputs in current rbf tx boolean isChange = false; boolean isSelf = false; for(MyTransactionOutPoint outpoint : _utxo.getOutpoints()) { if(rbf.containsChangeAddr(outpoint.getAddress())) { Log.d("BalanceActivity", "is change:" + outpoint.getAddress()); Log.d("BalanceActivity", "is change:" + outpoint.getValue().longValue()); isChange = true; break; } if(selfAddresses.contains(outpoint.getAddress())) { Log.d("BalanceActivity", "is self:" + outpoint.getAddress()); Log.d("BalanceActivity", "is self:" + outpoint.getValue().longValue()); isSelf = true; break; } } if(isChange || isSelf) { continue; } selectedUTXO.add(_utxo); selected += _utxo.getOutpoints().size(); Log.d("BalanceActivity", "selected utxo:" + selected); selectedAmount += _utxo.getValue(); Log.d("BalanceActivity", "selected utxo value:" + _utxo.getValue()); outpointTypes = FeeUtil.getInstance().getOutpointCount(_utxo.getOutpoints()); p2pkh += outpointTypes.getLeft(); p2wpkh += outpointTypes.getRight(); _remainingFee = FeeUtil.getInstance().estimatedFeeSegwit(p2pkh, p2wpkh, outputs.length() == 1 ? 2 : outputs.length()).longValue(); Log.d("BalanceActivity", "_remaining fee:" + _remainingFee); if(selectedAmount >= (_remainingFee + SamouraiWallet.bDust.longValue())) { break; } } long extraChange = 0L; if(selectedAmount < (_remainingFee + SamouraiWallet.bDust.longValue())) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, R.string.insufficient_funds, Toast.LENGTH_SHORT).show(); } }); return "KO"; } else { extraChange = selectedAmount - _remainingFee; Log.d("BalanceActivity", "extra change:" + extraChange); } boolean addedChangeOutput = false; // parent tx didn't have change output if(outputs.length() == 1 && extraChange > 0L) { try { String change_address = null; if(isBIP49) { change_address = BIP49Util.getInstance(BalanceActivity.this).getAddressAt(AddressFactory.CHANGE_CHAIN, BIP49Util.getInstance(BalanceActivity.this).getWallet().getAccount(0).getChange().getAddrIdx()).getAddressAsString(); } else { int changeIdx = HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(0).getChange().getAddrIdx(); change_address = HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(0).getChange().getAddressAt(changeIdx).getAddressString(); } Script toOutputScript = ScriptBuilder.createOutputScript(org.bitcoinj.core.Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), change_address)); TransactionOutput output = new TransactionOutput(SamouraiWallet.getInstance().getCurrentNetworkParams(), null, Coin.valueOf(extraChange), toOutputScript.getProgram()); txOutputs.add(output); addedChangeOutput = true; } catch(MnemonicException.MnemonicLengthException | IOException e) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); Toast.makeText(BalanceActivity.this, R.string.cannot_create_change_output, Toast.LENGTH_SHORT).show(); } }); return "KO"; } } // parent tx had change output else { for(TransactionOutput output : txOutputs) { Log.d("BalanceActivity", "checking for change:" + output.getAddressFromP2PKHScript(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString()); if(rbf.containsChangeAddr(output.getAddressFromP2PKHScript(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString())) { Log.d("BalanceActivity", "before extra:" + output.getValue().longValue()); output.setValue(Coin.valueOf(extraChange + output.getValue().longValue())); Log.d("BalanceActivity", "after extra:" + output.getValue().longValue()); addedChangeOutput = true; break; } } } // sanity check if(extraChange > 0L && !addedChangeOutput) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, R.string.cannot_create_change_output, Toast.LENGTH_SHORT).show(); } }); return "KO"; } // update keyBag w/ any new paths final HashMap<String,String> keyBag = rbf.getKeyBag(); for(UTXO _utxo : selectedUTXO) { for(MyTransactionOutPoint outpoint : _utxo.getOutpoints()) { MyTransactionInput _input = new MyTransactionInput(SamouraiWallet.getInstance().getCurrentNetworkParams(), null, new byte[0], outpoint, outpoint.getTxHash().toString(), outpoint.getTxOutputN()); _input.setSequenceNumber(SamouraiWallet.RBF_SEQUENCE_NO); _inputs.add(_input); Log.d("BalanceActivity", "add selected outpoint:" + _input.getOutpoint().toString()); String path = APIFactory.getInstance(BalanceActivity.this).getUnspentPaths().get(outpoint.getAddress()); if(path != null) { if(Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), outpoint.getAddress()).isP2SHAddress()) { rbf.addKey(outpoint.toString(), path + "/49"); } else { rbf.addKey(outpoint.toString(), path); } } else { String pcode = BIP47Meta.getInstance().getPCode4Addr(outpoint.getAddress()); int idx = BIP47Meta.getInstance().getIdx4Addr(outpoint.getAddress()); rbf.addKey(outpoint.toString(), pcode + "/" + idx); } } } rbf.setKeyBag(keyBag); } // BIP69 sort of outputs/inputs final Transaction _tx = new Transaction(SamouraiWallet.getInstance().getCurrentNetworkParams()); List<TransactionOutput> _txOutputs = new ArrayList<TransactionOutput>(); _txOutputs.addAll(txOutputs); Collections.sort(_txOutputs, new SendFactory.BIP69OutputComparator()); for(TransactionOutput to : _txOutputs) { // zero value outputs discarded here if(to.getValue().longValue() > 0L) { _tx.addOutput(to); } } List<MyTransactionInput> __inputs = new ArrayList<MyTransactionInput>(); __inputs.addAll(_inputs); Collections.sort(__inputs, new SendFactory.BIP69InputComparator()); for(TransactionInput input : __inputs) { _tx.addInput(input); } FeeUtil.getInstance().setSuggestedFee(suggestedFee); String message = ""; if(feeWarning) { message += BalanceActivity.this.getString(R.string.fee_bump_not_necessary); message += "\n\n"; } message += BalanceActivity.this.getString(R.string.bump_fee) + " " + Coin.valueOf(remainingFee).toPlainString() + " BTC"; AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(message) .setCancelable(false) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Transaction __tx = signTx(_tx); final String hexTx = new String(Hex.encode(__tx.bitcoinSerialize())); Log.d("BalanceActivity", hexTx); final String strTxHash = __tx.getHashAsString(); Log.d("BalanceActivity", strTxHash); if(__tx != null) { boolean isOK = false; try { isOK = PushTx.getInstance(BalanceActivity.this).pushTx(hexTx); if(isOK) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, R.string.rbf_spent, Toast.LENGTH_SHORT).show(); RBFSpend _rbf = rbf; // includes updated 'keyBag' _rbf.setSerializedTx(hexTx); _rbf.setHash(strTxHash); _rbf.setPrevHash(params[0]); RBFUtil.getInstance().add(_rbf); Intent _intent = new Intent(BalanceActivity.this, MainActivity2.class); _intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); startActivity(_intent); } }); } else { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, R.string.tx_failed, Toast.LENGTH_SHORT).show(); } }); } } catch(final DecoderException de) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, "pushTx:" + de.getMessage(), Toast.LENGTH_SHORT).show(); } }); } finally { ; } } } }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }); if(!isFinishing()) { dlg.show(); } } catch(final JSONException je) { handler.post(new Runnable() { public void run() { Toast.makeText(BalanceActivity.this, "rbf:" + je.getMessage(), Toast.LENGTH_SHORT).show(); } }); } } else { Toast.makeText(BalanceActivity.this, R.string.cpfp_cannot_retrieve_tx, Toast.LENGTH_SHORT).show(); } Looper.loop(); return "OK"; } @Override protected void onPostExecute(String result) { ; } @Override protected void onProgressUpdate(Void... values) { ; } private Transaction signTx(Transaction tx) { HashMap<String,ECKey> keyBag = new HashMap<String,ECKey>(); HashMap<String,String> keys = rbf.getKeyBag(); for(String outpoint : keys.keySet()) { ECKey ecKey = null; String[] s = keys.get(outpoint).split("/"); if(s.length == 4) { P2SH_P2WPKH p2sh_p2wphk = AddressFactory.getInstance(BalanceActivity.this).getBIP49(0, Integer.parseInt(s[1]), Integer.parseInt(s[2])); ecKey = p2sh_p2wphk.getECKey(); } if(s.length == 3) { HD_Address hd_address = AddressFactory.getInstance(BalanceActivity.this).get(0, Integer.parseInt(s[1]), Integer.parseInt(s[2])); String strPrivKey = hd_address.getPrivateKeyString(); DumpedPrivateKey pk = new DumpedPrivateKey(SamouraiWallet.getInstance().getCurrentNetworkParams(), strPrivKey); ecKey = pk.getKey(); } else if(s.length == 2) { try { PaymentAddress address = BIP47Util.getInstance(BalanceActivity.this).getReceiveAddress(new PaymentCode(s[0]), Integer.parseInt(s[1])); ecKey = address.getReceiveECKey(); } catch(Exception e) { ; } } else { ; } Log.i("BalanceActivity", "outpoint:" + outpoint); Log.i("BalanceActivity", "ECKey address from ECKey:" + ecKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString()); if(ecKey != null) { keyBag.put(outpoint, ecKey); } else { throw new RuntimeException("ECKey error: cannot process private key"); // Log.i("ECKey error", "cannot process private key"); } } List<TransactionInput> inputs = tx.getInputs(); for (int i = 0; i < inputs.size(); i++) { ECKey ecKey = keyBag.get(inputs.get(i).getOutpoint().toString()); TransactionOutput connectedOutput = inputs.get(i).getOutpoint().getConnectedOutput(); Script scriptPubKey = connectedOutput.getScriptPubKey(); byte[] connectedPubKeyScript = inputs.get(i).getOutpoint().getConnectedPubKeyScript(); String address = new Script(connectedPubKeyScript).getToAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(); if(Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), address).isP2SHAddress()) { final P2SH_P2WPKH p2shp2wpkh = new P2SH_P2WPKH(ecKey.getPubKey(), SamouraiWallet.getInstance().getCurrentNetworkParams()); System.out.println("pubKey:" + Hex.toHexString(ecKey.getPubKey())); // final Script scriptPubKey = p2shp2wpkh.segWitOutputScript(); // System.out.println("scriptPubKey:" + Hex.toHexString(scriptPubKey.getProgram())); System.out.println("to address from script:" + scriptPubKey.getToAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString()); final Script redeemScript = p2shp2wpkh.segWitRedeemScript(); System.out.println("redeem script:" + Hex.toHexString(redeemScript.getProgram())); final Script scriptCode = redeemScript.scriptCode(); System.out.println("script code:" + Hex.toHexString(scriptCode.getProgram())); TransactionSignature sig = tx.calculateWitnessSignature(i, ecKey, scriptCode, connectedOutput.getValue(), Transaction.SigHash.ALL, false); final TransactionWitness witness = new TransactionWitness(2); witness.setPush(0, sig.encodeToBitcoin()); witness.setPush(1, ecKey.getPubKey()); tx.setWitness(i, witness); final ScriptBuilder sigScript = new ScriptBuilder(); sigScript.data(redeemScript.getProgram()); tx.getInput(i).setScriptSig(sigScript.build()); tx.getInput(i).getScriptSig().correctlySpends(tx, i, scriptPubKey, connectedOutput.getValue(), Script.ALL_VERIFY_FLAGS); } else { Log.i("BalanceActivity", "sign outpoint:" + inputs.get(i).getOutpoint().toString()); Log.i("BalanceActivity", "ECKey address from keyBag:" + ecKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString()); Log.i("BalanceActivity", "script:" + ScriptBuilder.createOutputScript(ecKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()))); Log.i("BalanceActivity", "script:" + Hex.toHexString(ScriptBuilder.createOutputScript(ecKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams())).getProgram())); TransactionSignature sig = tx.calculateSignature(i, ecKey, ScriptBuilder.createOutputScript(ecKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams())).getProgram(), Transaction.SigHash.ALL, false); tx.getInput(i).setScriptSig(ScriptBuilder.createInputScript(sig, ecKey)); } } return tx; } } }
package org.itevents.service.transactional; import org.itevents.dao.UserDao; import org.itevents.model.Event; import org.itevents.model.User; import org.itevents.service.UserService; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.inject.Inject; import java.util.List; @Service("userService") @Transactional public class MyBatisUserService implements UserService { @Inject private UserDao userDao; @Inject private PasswordEncoder passwordEncoder; @Override public void addUser(User user) { userDao.addUser(user); } @Override public User getUser(int id) { return userDao.getUser(id); } @Override public User getUserByName(String name) { return userDao.getUserByName(name); } @Override @PreAuthorize("isAuthenticated()") public User getAuthorizedUser() { return getUserByName(SecurityContextHolder.getContext().getAuthentication().getName()); } @Override @PreAuthorize("isAuthenticated()") public void activateUserSubscription(User user) { user.setSubscribed(true); userDao.updateUser(user); } @Override @PreAuthorize("isAuthenticated()") public void deactivateUserSubscription(User user) { user.setSubscribed(false); userDao.updateUser(user); } @Override public List<User> getAllUsers() { return userDao.getAllUsers(); } @Override public List<User> getSubscribedUsers() { return userDao.getSubscribedUsers(); } @Override public List<User> getUsersByEvent(Event event) { return userDao.getUsersByEvent(event); } @Override public boolean matchPasswordByLogin(User user, String password) { String encodedPassword = userDao.getEncodedUserPassword(user); return passwordEncoder.matches(password, encodedPassword); } }
package aho.uozu.yakbox; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class LoadActivity extends AppCompatActivity { private ListView mListView; private List<String> mItems; private ArrayAdapter<String> mAdapter; private Storage mStorage; private static final String TAG = "Yakbox-Load"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_load); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); toolbar.setLogo(R.drawable.ic_launcher_sml); ActionBar ab = getSupportActionBar(); if (ab != null) { ab.setDisplayHomeAsUpEnabled(true); } mStorage = Storage.getInstance(this); try { mItems = mStorage.getSavedRecordingNames(); } catch (Storage.StorageUnavailableException e) { String msg = "Error: Can't access storage"; Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show(); mItems = new ArrayList<>(); } Collections.sort(mItems); // Configure list view mListView = (ListView) findViewById(R.id.list); mAdapter = new ArrayAdapter<>(this, R.layout.load_list_item, mItems); mListView.setAdapter(mAdapter); // short taps mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String recordingName = ((TextView) view).getText().toString(); Intent i = new Intent(); i.putExtra("name", recordingName); setResult(RESULT_OK, i); finish(); } }); // long taps mListView.setLongClickable(true); mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { showDeleteDialog(position); return true; } }); } private void showDeleteDialog(final int itemIdx) { AlertDialog.Builder builder = new AlertDialog.Builder(this); String name = mItems.get(itemIdx); builder .setMessage(getString(R.string.delete_dialog_msg) + " " + name + "?") .setPositiveButton(R.string.delete_dialog_positive, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { deleteRecording(itemIdx); } }) .setNegativeButton(R.string.delete_dialog_negative, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }); builder.show(); } private void deleteRecording(int itemIdx) { String name = mItems.get(itemIdx); mItems.remove(itemIdx); mAdapter.notifyDataSetChanged(); try { mStorage.deleteRecording(name); } catch (IOException e) { Log.e(TAG, "Error deleting " + name, e); } } }
package com.soctec.soctec.core; import java.util.ArrayList; import java.util.Locale; import android.accounts.Account; import android.accounts.AccountManager; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.graphics.drawable.Icon; import android.net.wifi.WifiManager; import android.os.Vibrator; import android.support.v7.app.AppCompatActivity; import android.support.v7.app.ActionBar; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.app.FragmentPagerAdapter; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.Toast; import com.soctec.soctec.R; import com.soctec.soctec.achievements.Achievement; import com.soctec.soctec.achievements.AchievementCreator; import com.soctec.soctec.achievements.AchievementUnlocker; import com.soctec.soctec.achievements.Stats; import com.soctec.soctec.network.ConnectionChecker; import com.soctec.soctec.network.NetworkHandler; import com.soctec.soctec.profile.Profile; import com.soctec.soctec.profile.ProfileActivity; import com.soctec.soctec.profile.ProfileMatchActivity; import com.soctec.soctec.utils.Encryptor; import com.soctec.soctec.utils.FileHandler; /** * MainActivity is a tabbed activity, and sets up most of the other objects for the App * @author Jesper, Joakim, David, Carl-Henrik, Robin * @version 1.3 */ public class MainActivity extends AppCompatActivity implements ActionBar.TabListener { SectionsPagerAdapter mSectionsPagerAdapter; ViewPager mViewPager; ConnectionChecker connectionChecker = null; private Stats stats; private AchievementCreator creator; private AchievementUnlocker unlocker; private static int REQUEST_CODE = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); String account = getPlayAcc(); if(account == null) account = "walla"; //TODO crash and burn (handle this some way...) //Initialize the FileHandler FileHandler.getInstance().setContext(this); //Initialize the Profile String userCode = new Encryptor().encrypt(account); Profile.setUserCode(userCode); Profile.initProfile(); //Initialize the Achievement engine stats = new Stats(); creator = new AchievementCreator(); unlocker = new AchievementUnlocker(stats, creator); creator.addObserver(unlocker); creator.createFromFile(); //Initialize networkHandler. Start server thread NetworkHandler.getInstance(this).startThread(); //Initialize the ActionBar setupActionBar(); mViewPager.addOnPageChangeListener(new PageChangeListener()); //Display help to user. Only on the very first startup TODO: test if this works SharedPreferences settings = getSharedPreferences("MyPrefsFile", 0); if (settings.getBoolean("first_time", true)) { //Do this only the first startup Toast.makeText(getApplicationContext(), "first time", Toast.LENGTH_SHORT).show(); settings.edit().putBoolean("my_first_time", false).apply(); } } /** * Initiate the BroadcastReceiver and register it. */ public void startReceiver() { IntentFilter intentFilter = new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION); registerReceiver( connectionChecker = new ConnectionChecker(MainActivity.this), intentFilter); Log.i("Main", "Receiver started!"); } /** * Tells ScanActivity to start scanning * @param v currently unused */ public void scanNow (View v) { startActivityForResult( new Intent(getApplicationContext(), ScanActivity.class), REQUEST_CODE); mViewPager.setCurrentItem(1); updateAchievementFragment(); } /** * Initiates refresh of AchievementFragment by retrieving the fragment from * mSectionsPagerAdapter and calling the method */ protected void updateAchievementFragment() { AchievementsFragment aF = (AchievementsFragment)mSectionsPagerAdapter.getFragment(2); aF.refreshAchievements(unlocker.getUnlockableAchievements(), stats.getAchievements()); } /** * Called when an activity started with "startActivityForResult()" has finished. * @param requestCode Indicates which request this method call is a response to * @param resultCode The result of the request * @param data The data from the finished activity. */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { mViewPager.setCurrentItem(1); if(resultCode == RESULT_OK && requestCode == REQUEST_CODE) { String scannedCode = data.getExtras().getString("result"); NetworkHandler.getInstance(this).sendScanInfoToPeer(scannedCode); } } /** * Starts NetworkHandler and registers connectionChecker as receiver */ @Override protected void onResume() { super.onResume(); NetworkHandler.getInstance(this).startThread(); IntentFilter intentFilter = new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION); registerReceiver(connectionChecker, intentFilter); mViewPager.setCurrentItem(1); } /** * Stops NetworkHandler and unregisters connectionChecker as receiver */ @Override protected void onPause() { super.onPause(); NetworkHandler.getInstance(this).stopThread(); unregisterReceiver(connectionChecker); } /** * Makes sure the application only exits when in main fragment * and back button is pressed. Otherwise switches to main fragment. */ @Override public void onBackPressed() { if (mViewPager.getCurrentItem()==1) super.onBackPressed(); else mViewPager.setCurrentItem(1); } /** * Called by NetworkHandler when data has been received from a peer. * @param idFromPeer The unique ID of the peer * @param profileFromPeer The peer's profile data */ public void receiveDataFromPeer(String idFromPeer, ArrayList<ArrayList<String>> profileFromPeer) { Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE); vibrator.vibrate(100); unlocker.receiveEvent(1, idFromPeer); for(Achievement achi : stats.getLastCompleted()) { Intent showerIntent = new Intent(this, AchievementShowerActivity.class); showerIntent.putExtra("AchievementObject", achi); startActivity(showerIntent); } //Match profile stuff Bundle b = new Bundle(); b.putSerializable("list1", Profile.getProfile()); b.putSerializable("list2", profileFromPeer); Intent matchIntent = new Intent(this, ProfileMatchActivity.class); matchIntent.putExtras(b); startActivity(matchIntent); updateAchievementFragment(); } /** * Update the QR image * @param QR */ public void updateQR(Bitmap QR) { Log.i("MainFrag", "Update qr"); ImageView im = (ImageView) findViewById(R.id.qr_image); im.setImageBitmap(QR); } /** * Returns the device's google account name * @return the device's google account name */ private String getPlayAcc() { String accMail = null; AccountManager manager = (AccountManager) getSystemService(ACCOUNT_SERVICE); Account[] list = manager.getAccounts(); for(Account account : list) { if(account.type.equalsIgnoreCase("com.google")) //TODO Felhatering vid avsaknad av gmail-konto { accMail = account.name; break; } } return accMail; } public class PageChangeListener implements ViewPager.OnPageChangeListener { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { if (position == 0) { mViewPager.setCurrentItem(0); scanNow(null); //mViewPager.setCurrentItem(1); } } @Override public void onPageScrollStateChanged(int state) { } } /** * Sets up the ActionBar */ private void setupActionBar() { final ActionBar actionBar = getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); // Create the adapter that will return a fragment for each of the three // primary sections of the activity. mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); // Set up the ViewPager with the sections adapter. mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mSectionsPagerAdapter); // When swiping between different sections, select the corresponding // tab. We can also use ActionBar.Tab#select() to do this if we have // a reference to the Tab. mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { actionBar.setSelectedNavigationItem(position); } }); // For each of the sections in the app, add a tab to the action bar. for(int i = 0; i < mSectionsPagerAdapter.getCount(); i++) { // Create a tab with text corresponding to the page title defined by // the adapter. Also specify this Activity object, which implements // the TabListener interface, as the callback (listener) for when // this tab is selected. actionBar.addTab( actionBar.newTab() .setIcon(mSectionsPagerAdapter.getIcon(i)) .setTabListener(this)); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if(id == R.id.action_settings) { return true; } else if(id == R.id.action_profile) { Intent intent = new Intent(this, ProfileActivity.class); startActivity(intent); } return super.onOptionsItemSelected(item); } @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { // When the given tab is selected, switch to the corresponding page in // the ViewPager. mViewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } /** * A {@link FragmentPagerAdapter} that returns a fragment corresponding to * one of the sections/tabs/pages. */ public class SectionsPagerAdapter extends FragmentPagerAdapter { FragmentManager fragmentManager; public SectionsPagerAdapter(FragmentManager fm) { super(fm); fragmentManager = fm; } public Fragment getFragment(int position) { return fragmentManager.getFragments().get(position); } @Override public Fragment getItem(int position) { // getItem is called to instantiate the fragment for the given page. switch(position) { case 0: return new ScanFragment(); case 1: return new MainFragment(); case 2: return new AchievementsFragment(); } return null; } @Override public int getCount() { return 3; } @Override public CharSequence getPageTitle(int position) { Locale l = Locale.getDefault(); switch(position) { case 0: return getString(R.string.title_section3).toUpperCase(l); case 1: return getString(R.string.title_section1).toUpperCase(l); case 2: return getString(R.string.title_section2).toUpperCase(l); } return null; } public int getIcon(int position) { Locale l = Locale.getDefault(); FileHandler fileHandler = FileHandler.getInstance(); switch(position) { case 0: return fileHandler.getResourceID("camera6", "drawable"); case 1: return fileHandler.getResourceID("qricon", "drawable"); case 2: return fileHandler.getResourceID("trophy", "drawable"); } return 0; } } }