answer
stringlengths
17
10.2M
package de.slackspace.openkeepass.domain; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import de.slackspace.openkeepass.parser.UUIDXmlAdapter; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class Entry implements KeePassFileElement { private static final String USER_NAME = "UserName"; private static final String NOTES = "Notes"; private static final String URL = "URL"; private static final String PASSWORD = "Password"; private static final String TITLE = "Title"; @XmlTransient private KeePassFileElement parent; @XmlElement(name = "UUID") @XmlJavaTypeAdapter(UUIDXmlAdapter.class) private String uuid; @XmlElement(name = "String") private List<Property> properties = new ArrayList<Property>(); @XmlElement(name = "History") private History history; Entry() { } public Entry(String uuid) { setUuid(uuid); } public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } public List<Property> getProperties() { return properties; } public void setProperties(List<Property> properties) { this.properties = properties; } public String getTitle() { return getValueFromProperty(TITLE); } public void setTitle(String title) { setValue(false, TITLE, title); } public String getPassword() { return getValueFromProperty(PASSWORD); } public void setPassword(String password) { setValue(true, PASSWORD, password); } public String getUrl() { return getValueFromProperty(URL); } public void setUrl(String url) { setValue(false, URL, url); } public String getNotes() { return getValueFromProperty(NOTES); } public void setNotes(String notes) { setValue(false, NOTES, notes); } public String getUsername() { return getValueFromProperty(USER_NAME); } public void setUsername(String username) { setValue(false, USER_NAME, username); } public boolean isTitleProtected() { return getPropertyByName(TITLE).isProtected(); } public boolean isPasswordProtected() { return getPropertyByName(PASSWORD).isProtected(); } public void setParent(KeePassFileElement element) { this.parent = element; for (Property property : properties) { property.setParent(this); } } private void setValue(boolean isProtected, String propertyName, String propertyValue) { Property property = getPropertyByName(propertyName); if (property == null) { property = new Property(propertyName, propertyValue, isProtected); properties.add(property); } else { property.setValue(new PropertyValue(isProtected, propertyValue)); } } private String getValueFromProperty(String name) { Property property = getPropertyByName(name); if (property != null) { return property.getValue(); } return null; } /** * Retrieves a property by it's name (ignores case) * * @param name the name of the property to find * @return the property if found, null otherwise */ public Property getPropertyByName(String name) { for (Property property : properties) { if (property.getKey().equalsIgnoreCase(name)) { return property; } } return null; } public History getHistory() { return history; } public void setHistory(History history) { this.history = history; } @Override public String toString() { return "Entry [uuid=" + uuid + ", getTitle()=" + getTitle() + ", getPassword()=" + getPassword() + ", getUsername()=" + getUsername() + "]"; } }
package de.themoep.inventorygui; import org.bukkit.entity.HumanEntity; import org.bukkit.inventory.ItemStack; /** * This is an element that allows for controlling the pagination of the gui. * <b>Untested und potentially unfinished.</b> */ public class GuiPageElement extends StaticGuiElement { private PageAction pageAction; /** * An element that allows for controlling the pagination of the gui. * @param slotChar The character to replace in the gui setup string * @param item The {@link ItemStack} representing this element * @param pageAction What kind of page action you want to happen when interacting with the element. * @param text The text to display on this element, placeholders are automatically * replaced, see {@link InventoryGui#replaceVars} for a list of the * placeholder variables. Empty text strings are also filter out, use * a single space if you want to add an empty line!<br> * If it's not set/empty the item's default name will be used */ public GuiPageElement(char slotChar, ItemStack item, PageAction pageAction, String... text) { super(slotChar, item, click -> { switch (pageAction) { case NEXT: if (click.getGui().getPageNumber() + 1 < click.getGui().getPageAmount()) { click.getGui().playClickSound(); click.getGui().setPageNumber(click.getGui().getPageNumber() + 1); } break; case PREVIOUS: if (click.getGui().getPageNumber() > 0) { click.getGui().playClickSound(); click.getGui().setPageNumber(click.getGui().getPageNumber() - 1); } break; case FIRST: click.getGui().playClickSound(); click.getGui().setPageNumber(0); break; case LAST: click.getGui().playClickSound(); click.getGui().setPageNumber(click.getGui().getPageAmount() - 1); break; } return true; }, text); this.pageAction = pageAction; } @Override public ItemStack getItem(HumanEntity who, int slot) { if (((pageAction == PageAction.FIRST || pageAction == PageAction.LAST) && gui.getPageAmount() < 3) || (pageAction == PageAction.NEXT && gui.getPageNumber() + 1 >= gui.getPageAmount()) || (pageAction == PageAction.PREVIOUS && gui.getPageNumber() == 0)) { return gui.getFiller() != null ? gui.getFiller().getItem(who, slot) : null; } if (pageAction == PageAction.PREVIOUS) { setNumber(gui.getPageNumber()); } else if (pageAction == PageAction.NEXT) { setNumber(gui.getPageNumber() + 2); } else if (pageAction == PageAction.LAST) { setNumber(gui.getPageAmount()); } return super.getItem(who, slot).clone(); } public enum PageAction { NEXT, PREVIOUS, FIRST, LAST; } }
package edu.hm.hafner.analysis; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Stream; import java.util.Stack; import edu.hm.hafner.util.LookaheadStream; /** * Parses a report file line by line for issues using a pre-defined regular expression. If the regular expression * matches then the abstract method {@link #createIssue(Matcher, LookaheadStream, IssueBuilder)} will be called. Sub * classes need to provide an implementation that transforms the {@link Matcher} instance into a new issue. If required, * sub classes may consume additional lines from the report file before control is handed back to the template method of * this parser. * * @author Ullrich Hafner */ public abstract class LookaheadParser extends IssueParser { private static final long serialVersionUID = 3240719494150024894L; /** Pattern identifying an ant task debug output prefix. */ protected static final String ANT_TASK = "^(?:.*\\[[^]]*\\])?\\s*"; private static final String ENTERING_DIRECTORY = "Entering directory"; private static final String LEAVING_DIRECTORY = "Leaving directory"; private static final Pattern MAKE_PATH = Pattern.compile(".*make(?:\\[\\d+])?: " + ENTERING_DIRECTORY + " [`'](?<dir>.*)['`]"); private static final String CMAKE_PREFIX = "-- Build files have"; private static final Pattern CMAKE_PATH = Pattern.compile(CMAKE_PREFIX + " been written to: (?<dir>.*)"); private static final int MAX_LINE_LENGTH = 4000; // see JENKINS-55805 private final Pattern pattern; private final Stack<String> recursiveMakeDirectories; /** * Creates a new instance of {@link LookaheadParser}. * * @param pattern * pattern of compiler warnings. */ protected LookaheadParser(final String pattern) { super(); this.pattern = Pattern.compile(pattern); this.recursiveMakeDirectories = new Stack<>(); } @Override public Report parse(final ReaderFactory readerFactory) throws ParsingException, ParsingCanceledException { Report report = new Report(); try (Stream<String> lines = readerFactory.readStream()) { try (LookaheadStream lookahead = new LookaheadStream(lines, readerFactory.getFileName())) { parse(report, lookahead); } } return postProcess(report); } private void parse(final Report report, final LookaheadStream lookahead) { try (IssueBuilder builder = new IssueBuilder()) { while (lookahead.hasNext()) { String line = lookahead.next(); handleDirectoryChanges(builder, line); if (isLineInteresting(line)) { Matcher matcher = pattern.matcher(line); if (matcher.find()) { createIssue(matcher, lookahead, builder).ifPresent(report::add); } } if (Thread.interrupted()) { throw new ParsingCanceledException(); } } } } /** * When changing directories using Make output, save new directory to our stack for later use, then return it for * use now. * * @param line * the line to parse * * * @return The new directory to change to */ private String newMakeDirectory(final String line) { recursiveMakeDirectories.push(extractDirectory(line, MAKE_PATH)); return recursiveMakeDirectories.peek(); } /** * When changing directories using Make output, set our stack to the last directory seen, and return that directory. * * @return The last directory seen, or an empty String if we have returned to the beginning */ private String lastMakeDirectory() { if (!recursiveMakeDirectories.empty()) { recursiveMakeDirectories.pop(); if (!recursiveMakeDirectories.empty()) { return recursiveMakeDirectories.peek(); } } return ""; } /** * Uses Make and CMake output to track directory structure as the compiler moves between source locations. * * @param builder * {@link IssueBuilder} to set directory for * @param line * the line to parse */ private void handleDirectoryChanges(final IssueBuilder builder, final String line) { if (line.contains(ENTERING_DIRECTORY)) { builder.setDirectory(newMakeDirectory(line)); } else if (line.contains(LEAVING_DIRECTORY)) { builder.setDirectory(lastMakeDirectory()); } else if (line.contains(CMAKE_PREFIX)) { builder.setDirectory(extractDirectory(line, CMAKE_PATH)); } } private String extractDirectory(final String line, final Pattern makePath) throws ParsingException { if (!makePath.toString().contains("<dir>")) { throw new IllegalArgumentException( String.format("%s does not contain a capture group named 'dir'", makePath.toString())); } Matcher makeLineMatcher = makePath.matcher(line); if (makeLineMatcher.matches()) { return makeLineMatcher.group("dir"); } throw new ParsingException( String.format("Unable to change directory using: %s to match %s", makePath.toString(), line)); } /** * Creates a new issue for the specified pattern. This method is called for each matching line in the specified * file. If a match is a false positive, then return {@link Optional#empty()} to ignore this warning. * * @param matcher * the regular expression matcher * @param lookahead * the lookahead stream to read additional lines * @param builder * the issue builder to use * * @return a new annotation for the specified pattern * @throws ParsingException * Signals that during parsing a non recoverable error has been occurred */ protected abstract Optional<Issue> createIssue(Matcher matcher, LookaheadStream lookahead, IssueBuilder builder) throws ParsingException; /** * Returns whether the specified line is interesting. Each interesting line will be matched by the defined regular * expression. Here a parser can implement some fast checks (i.e. string or character comparisons) in order to see * if a required condition is met. This default implementation does always return {@code true}. * * @param line * the line to inspect * * @return {@code true} if the line should be handed over to the regular expression scanner, {@code false} if the * line does not contain a warning. */ protected boolean isLineInteresting(final String line) { return line.length() < MAX_LINE_LENGTH; // skip long lines, see JENKINS-55805 } /** * Post processes the issues. This default implementation does nothing. * * @param report * the issues after the parsing process * * @return the post processed issues */ protected Report postProcess(final Report report) { return report; } }
package edu.wright.hendrix11.conway.logic; import java.util.ArrayList; import java.util.List; import java.util.Objects; /** * @author Joe Hendrix */ public class Cell { private Grid grid; private boolean alive = false; private Cell northernCell; private Cell southernCell; private Cell easternCell; private Cell westernCell; public Cell(Grid grid) { this.grid = grid; } private boolean classInv() { boolean invariant = true; if (northernCell != null && !Objects.equals(northernCell.southernCell, this)) { invariant = false; } if (southernCell != null && !Objects.equals(southernCell.northernCell, this)) { invariant = false; } if (easternCell != null && !Objects.equals(easternCell.westernCell, this)) { invariant = false; } if (westernCell != null && !Objects.equals(westernCell.easternCell, this)) { invariant = false; } if (northernCell != null && easternCell != null) { if (!Objects.equals(northernCell.easternCell, easternCell.northernCell)) { invariant = false; } } if (northernCell != null && westernCell != null) { if (!Objects.equals(northernCell.westernCell, westernCell.northernCell)) { invariant = false; } } if (southernCell != null && easternCell != null) { if (!Objects.equals(southernCell.easternCell, easternCell.southernCell)) { invariant = false; } } if (southernCell != null && westernCell != null) { if (!Objects.equals(southernCell.westernCell, southernCell.westernCell)) { invariant = false; } } return invariant; } public List<Cell> getNeighbors() { List<Cell> neighbors = new ArrayList<>(); neighbors.add(getNorthernCell()); neighbors.add(southernCell); neighbors.add(easternCell); neighbors.add(westernCell); neighbors.add(getNorthEasternCell()); neighbors.add(getNorthWesternCell()); neighbors.add(getSouthEasternCell()); neighbors.add(getSouthWesternCell()); assert neighbors.size() == 8; return neighbors; } public void setNorthernCell(Cell northernCell) { northernCell.southernCell = this; this.northernCell = northernCell; } public void setWesternCell(Cell westernCell) { westernCell.easternCell = this; this.westernCell = westernCell; } public void setEasternCell(Cell easternCell) { easternCell.westernCell = this; this.easternCell = easternCell; } public void setSouthernCell(Cell southernCell) { southernCell.northernCell = this; this.southernCell = southernCell; } public Cell getNorthernCell() { return northernCell; } public void growNorth() { if(northernCell == null) { setNorthernCell(new Cell()); if(easternCell != null) { northernCell.setEasternCell(new Cell()); easternCell.setNorthernCell(northernCell.easternCell); } if(westernCell != null) { northernCell.setWesternCell(new Cell()); westernCell.setNorthernCell(northernCell.westernCell); } } } private Cell getNorthEasternCell() { Cell northEasternCell = null; if (northernCell != null) { northEasternCell = northernCell.easternCell; } else if (easternCell != null) { northEasternCell = easternCell.northernCell; } return northEasternCell; } private Cell getNorthWesternCell() { Cell northWesternCell = null; if (northernCell != null) { northWesternCell = northernCell.westernCell; } else if (westernCell != null) { northWesternCell = westernCell.northernCell; } return northWesternCell; } private Cell getSouthEasternCell() { Cell southEasternCell = null; if (southernCell != null) { southEasternCell = southernCell.easternCell; } else if (easternCell != null) { southEasternCell = easternCell.southernCell; } return southEasternCell; } private Cell getSouthWesternCell() { Cell southWesternCell = null; if (southernCell != null) { southWesternCell = southernCell.westernCell; } else if (westernCell != null) { southWesternCell = westernCell.southernCell; } return southWesternCell; } public void toggle() { alive = !alive; if (alive) { grid.addLivingCell(this); } else { grid.removeDeadCell(this); } } public boolean isAlive() { return alive; } public int getNumberLivingNeighbors() { int count = 0; for (Cell neighbor : getNeighbors()) { if (neighbor != null && neighbor.isAlive()) { count++; } } assert count >= 0 && count <= 8; return count; } @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals(Object o) { return this == o; } }
package innovimax.mixthem.arguments; /** * <p>This is the representation of a parameter value.</p> * @author Innovimax * @version 1.0 */ public class ParamValue { private final String text; private final int number; /** * Constructor * @param text The String value of the parameter. */ public ParamValue(String text) { this.text = test; this.number = -1; } /** * Constructor * @param number The Integer value of the parameter. */ public ParamValue(int number) { this.text = null; this.number = number; } /** * Returns the parameter value as a String. * @return The parameter value as a String */ public String stringValue() { return this.text; } /** * Returns the parameter value as an Integer. * @return The parameter value as an Integer */ public int intValue() { return this.number; } }
package io.schinzel.basicutils.thrower; import io.schinzel.basicutils.Checker; import java.util.List; import java.util.Map; /** * The purpose of this class is to offer less verbose exception throwing in * general and variable checking in particular. * * @author schinzel */ @SuppressWarnings({"WeakerAccess", "UnusedReturnValue"}) public class Thrower { /** * * @return An ThrowerInstance for chaining of Thrower methods. */ public static ThrowerInstance createInstance(){ return new ThrowerInstance(); } /** * Throws runtime exception if the argument value with the argument name is null. * * @param value The value to check * @param variableName The name of the value to check * @return The argument value checked */ public static Object throwIfVarNull(Object value, String variableName) { ThrowerMessage.create(value == null).message("Argument '" + variableName + "' cannot be null"); return value; } /** * Throws runtime exception if the argument value with the argument name is empty. * * @param value The value to check * @param variableName The name of the value to check * @return The argument value checked */ public static String throwIfVarEmpty(String value, String variableName) { ThrowerMessage.create(Checker.isEmpty(value)).message("Argument '" + variableName + "' cannot be empty"); return value; } /** * Throws runtime exception if the argument value with the argument name is empty. * * @param <T> The type of the list * @param value The value to check * @param variableName The name of the value to check * @return The argument value checked */ public static <T> List<T> throwIfVarEmpty(List<T> value, String variableName) { ThrowerMessage.create(Checker.isEmpty(value)).message("Argument '" + variableName + "' cannot be empty"); return value; } /** * Throws runtime exception if the argument value with the argument name is empty. * * @param <K> The type of the keys in the map * @param <V> The type of the values in the map * @param value The value to check * @param variableName The name of the value to check * @return The argument value checked */ public static <K, V> Map<K, V> throwIfVarEmpty(Map<K, V> value, String variableName) { ThrowerMessage.create(Checker.isEmpty(value)).message("Argument '" + variableName + "' cannot be empty"); return value; } /** * Throws a runtime exception if argument value is less than argument min. * * @param valueToCheck The value to check. * @param variableName The name of the variable that holds the value to * check. Used to create more useful exception message. * @param min The min value the argument value should not be less than. * @return The argument value checked */ public static int throwIfVarTooSmall(int valueToCheck, String variableName, int min) { Thrower.throwIfTrue(valueToCheck < min) .message("The value %1$d in variable '%2$s' is too small. Min value is %3$d.", valueToCheck, variableName, min); return valueToCheck; } /** * Throws a runtime exception if argument value is less than argument min. * * @param valueToCheck The value to check. * @param variableName The name of the variable that holds the value to * check. Used to create more useful exception message. * @param max The max value the argument value should not be larger than. * @return The argument value checked */ public static int throwIfVarTooLarge(int valueToCheck, String variableName, int max) { Thrower.throwIfTrue(valueToCheck > max) .message("The value %1$d in variable '%2$s' is too large. Max value is %3$d.", valueToCheck, variableName, max); return valueToCheck; } /** * Throws runtime exception if argument value is less than argument min or * larger than argument max. * * @param valueToCheck The value to check * @param variableName The name of the variable that holds the value to * check. Used to create more useful exception message. * @param min The minimum allowed value that the argument value can have * @param max The maximum allowed value that the argument value can have * @return The argument value checked */ public static int throwIfVarOutsideRange(int valueToCheck, String variableName, int min, int max) { Thrower.throwIfTrue((max < min), "Error using method. Max cannot be smaller than min."); Thrower.throwIfVarEmpty(variableName, "variable"); Thrower.throwIfVarTooSmall(valueToCheck, variableName, min); Thrower.throwIfVarTooLarge(valueToCheck, variableName, max); return valueToCheck; } /** * Throw runtime exception if argument expression is false. * * @param expression The expression to check * @param message The exception message */ public static void throwIfFalse(boolean expression, String message) { Thrower.throwIfFalse(expression).message(message); } /** * Throw if argument expression is false. * * @param expression The expression to check * @return Thrower message for chaining the exception message. */ public static ThrowerMessage throwIfFalse(boolean expression) { return ThrowerMessage.create(!expression); } /** * Throw if argument expression is true. * * @param expression The boolean expression to evaluate. * @param message The exception message */ public static void throwIfTrue(boolean expression, String message) { throwIfFalse(!expression, message); } /** * Throw if argument expression is true. * * @param expression The expression to check * @return Thrower message for chaining the exception message. */ public static ThrowerMessage throwIfTrue(boolean expression) { return ThrowerMessage.create(expression); } /** * Throw if argument expression is true. * * @param object The object to check for null * @return Thrower message for chaining the exception message. */ public static ThrowerMessage throwIfNull(Object object) { return ThrowerMessage.create(object == null); } /** * Throw if argument object is null. * * @param object The object to check for null * @param message The exception message */ public static void throwIfNull(Object object, String message) { Thrower.throwIfNull(object).message(message); } }
package lmo.tcp.bridge.client; import java.net.URI; import java.util.Date; import java.util.Timer; import java.util.TimerTask; import lmo.tcp.bridge.listener.BridgeClientListener; import lmo.tcp.bridge.server.BridgeServer; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; /** * * @author LMO */ public class BridgeClientForm extends javax.swing.JFrame { BridgeClient client = null; static Logger logger = Logger.getLogger("UI"); boolean started = false; /** * Creates new form BridgeClientForm */ public BridgeClientForm() { initComponents(); if (onDemandCheckBox.isSelected()) { connectButtonActionPerformed(null); } } /** * 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() { idField = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); serverLabel = new javax.swing.JLabel(); serverField = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); remoteServerField = new javax.swing.JTextField(); localPortField = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); connectButton = new javax.swing.JButton(); jLabel5 = new javax.swing.JLabel(); remoteIdField = new javax.swing.JTextField(); onDemandCheckBox = new javax.swing.JCheckBox(); jSeparator1 = new javax.swing.JSeparator(); startButton = new javax.swing.JButton(); serverStatusLabel = new javax.swing.JLabel(); clientStatusField = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("TCP Bridge Client"); setResizable(false); idField.setText("2"); jLabel1.setText("Local ID"); serverLabel.setText("Bridge Server"); serverField.setText("103.9.89.165:1783"); jLabel2.setText("Remote Server"); remoteServerField.setText("localhost:3389"); remoteServerField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { remoteServerFieldActionPerformed(evt); } }); localPortField.setText("13000"); jLabel3.setText("Local Port"); connectButton.setText("Connect"); connectButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { connectButtonActionPerformed(evt); } }); jLabel5.setText("Remote ID"); remoteIdField.setText("2"); onDemandCheckBox.setSelected(true); onDemandCheckBox.setText("On demand"); jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL); startButton.setText("Start"); startButton.setEnabled(false); startButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { startButtonActionPerformed(evt); } }); serverStatusLabel.setText("..."); clientStatusField.setText("..."); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(serverStatusLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(onDemandCheckBox, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(serverLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(serverField) .addComponent(idField) .addComponent(connectButton, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 0, Short.MAX_VALUE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 7, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(jLabel5) .addComponent(jLabel3)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(remoteServerField, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(remoteIdField, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(localPortField, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(startButton, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addComponent(clientStatusField, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSeparator1) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(remoteServerField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(remoteIdField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(localPortField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(startButton))) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(serverField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(serverLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(idField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(connectButton) .addComponent(onDemandCheckBox)))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(clientStatusField, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(serverStatusLabel, javax.swing.GroupLayout.Alignment.TRAILING)))) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void connectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_connectButtonActionPerformed final Timer timer = new Timer(); BridgeClientListener listener = new BridgeClientListener() { @Override public void onConnectionStart() { connectButton.setText("Disconnect"); startButton.setEnabled(true); serverStatusLabel.setText("connected"); final long startMs = new Date().getTime(); timer.schedule(new TimerTask() { @Override public void run() { long runtime = (new Date().getTime() - startMs) / 1000; long sec = runtime % 60; long min = runtime / 60 % 60; long hour = runtime / 60 / 60; serverStatusLabel.setText(String.format("%d:%02d:%02d", hour, min, sec)); } }, 0, 1000); if (onDemandCheckBox.isSelected() && started) { startButtonActionPerformed(null); } } @Override public void onConnectionEnd() { connectButton.setText("Connect"); if (onDemandCheckBox.isSelected()) { connectButtonActionPerformed(null); } startButton.setEnabled(false); serverStatusLabel.setText("disconnected"); timer.cancel(); timer.purge(); } @Override public void onServerStart() { startButton.setText("Stop"); clientStatusField.setText("remote connection started"); } @Override public void onServerEnd() { startButton.setText("Start"); if (onDemandCheckBox.isSelected() && started) { startButtonActionPerformed(null); } clientStatusField.setText("remote connection ended"); } }; if (client != null && client.isConnected()) { client.disconnect(); } else { URI serverURI = URI.create("tcp://" + serverField.getText()); int id = Integer.parseInt(idField.getText()); client = new BridgeClient(serverURI.getHost(), serverURI.getPort(), id, System.getProperty("user.name")); client.setListener(listener); client.connect(); } }//GEN-LAST:event_connectButtonActionPerformed private void remoteServerFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_remoteServerFieldActionPerformed // TODO add your handling code here: }//GEN-LAST:event_remoteServerFieldActionPerformed private void startButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startButtonActionPerformed if (client.isConnected()) { if (!client.isStarted()) { int localPort = Integer.parseInt(localPortField.getText()); URI remoteURI = URI.create("tcp://" + remoteServerField.getText()); int dstId = Integer.parseInt(remoteIdField.getText()); int dstPort = remoteURI.getPort(); String dstHost = remoteURI.getHost(); client.setRemote(dstId, dstHost, dstPort, localPort); client.start(); if (evt != null) { started = true; } } else { client.stop(); if (evt != null) { started = false; } } } }//GEN-LAST:event_startButtonActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { BasicConfigurator.configure(); if (args.length == 1) { new BridgeServer(Integer.parseInt(args[0])).start(); return; } else if (args.length == 7) { final Timer timer = new Timer(); final BridgeClient client = new BridgeClient(args[0], Integer.parseInt(args[1]), Integer.parseInt(args[2]), System.getProperty("user.name")); client.setRemote(Integer.parseInt(args[3]), args[4], Integer.parseInt(args[5]), Integer.parseInt(args[6])); client.setListener(new BridgeClientListener() { @Override public void onConnectionStart() { final long startMs = new Date().getTime(); timer.schedule(new TimerTask() { @Override public void run() { long runtime = (new Date().getTime() - startMs) / 1000; long sec = runtime % 60; long min = runtime / 60 % 60; long hour = runtime / 60 / 60; logger.info(String.format("%d:%02d:%02d", hour, min, sec)); } }, 0, 5000); logger.info("server connection started, starting local server"); client.start(); } @Override public void onConnectionEnd() { timer.cancel(); timer.purge(); client.stop(); logger.info("server connection ended, starting again"); client.connect(); } @Override public void onServerStart() { logger.info("local server started"); } @Override public void onServerEnd() { logger.info("local server ended"); } }); client.connect(); return; } else if (args.length > 0) { logger.info("shost sport srcid dstid rhost rport lport"); return; } /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Windows".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(BridgeClientForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(BridgeClientForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(BridgeClientForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(BridgeClientForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new BridgeClientForm().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel clientStatusField; private javax.swing.JButton connectButton; private javax.swing.JTextField idField; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel5; private javax.swing.JSeparator jSeparator1; private javax.swing.JTextField localPortField; private javax.swing.JCheckBox onDemandCheckBox; private javax.swing.JTextField remoteIdField; private javax.swing.JTextField remoteServerField; private javax.swing.JTextField serverField; private javax.swing.JLabel serverLabel; private javax.swing.JLabel serverStatusLabel; private javax.swing.JButton startButton; // End of variables declaration//GEN-END:variables }
package mcjty.immcraft.blocks.book; import mcjty.immcraft.api.book.IBook; import mcjty.immcraft.api.handles.ActionInterfaceHandle; import mcjty.immcraft.api.helpers.InventoryHelper; import mcjty.immcraft.blocks.generic.GenericImmcraftTE; import mcjty.immcraft.books.BookPage; import mcjty.immcraft.books.BookParser; import mcjty.immcraft.network.PacketHandler; import mcjty.immcraft.network.PacketPageFlip; import mcjty.lib.tools.ChatTools; import mcjty.lib.tools.ItemStackTools; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.NetworkManager; import net.minecraft.network.play.server.SPacketUpdateTileEntity; import net.minecraft.util.EnumHand; import net.minecraft.util.ResourceLocation; import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.TextFormatting; import java.util.Collections; import java.util.List; public class BookStandTE extends GenericImmcraftTE { private ItemStack currentBook = ItemStackTools.getEmptyStack(); // Pages and pageNumber are client side only private List<BookPage> pages = null; private int pageNumber = 0; public BookStandTE() { addInterfaceHandle(new ActionInterfaceHandle("l").action(this::pageDec).scale(.60f)); addInterfaceHandle(new ActionInterfaceHandle("r").action(this::pageInc).scale(.60f)); } @Override public void onDataPacket(NetworkManager net, SPacketUpdateTileEntity packet) { boolean oldBook = ItemStackTools.isValid(currentBook); super.onDataPacket(net, packet); if (getWorld().isRemote) { // If needed send a render update. boolean newBook = ItemStackTools.isValid(currentBook); if (oldBook != newBook) { getWorld().markBlockRangeForRenderUpdate(getPos(), getPos()); } } } // Only use clientside public List<BookPage> getPages() { if (pages == null) { if (ItemStackTools.isEmpty(currentBook)) { pages = Collections.emptyList(); return pages; } ResourceLocation json = ((IBook) currentBook.getItem()).getJson(); BookParser parser = new BookParser(); pages = parser.parse(json, 768, 1024); if (pageNumber >= pages.size()) { pageNumber = 0; markDirtyClient(); } } return pages; } public boolean hasBook() { return ItemStackTools.isValid(currentBook); } public int getPageNumber() { return pageNumber; } private boolean pageDec(EntityPlayer player) { PacketHandler.INSTANCE.sendTo(new PacketPageFlip(getPos(), -1), (EntityPlayerMP) player); return true; } private boolean pageInc(EntityPlayer player) { PacketHandler.INSTANCE.sendTo(new PacketPageFlip(getPos(), 1), (EntityPlayerMP) player); return true; } public void pageDecClient() { if (pageNumber > 0) { pageNumber getWorld().markBlockRangeForRenderUpdate(getPos(), getPos()); } } public void pageIncClient() { if (pages != null && pageNumber < pages.size()-1) { pageNumber++; getWorld().markBlockRangeForRenderUpdate(getPos(), getPos()); } } public EnumStandState getState() { if (ItemStackTools.isEmpty(currentBook)) { return EnumStandState.EMPTY; } else if (pageNumber == 0) { return EnumStandState.CLOSED; } else { return EnumStandState.OPEN; } } @Override public void readFromNBT(NBTTagCompound compound) { super.readFromNBT(compound); if (compound.hasKey("book")) { currentBook = ItemStackTools.loadFromNBT(compound.getCompoundTag("book")); } else { currentBook = ItemStackTools.getEmptyStack(); pages = null; pageNumber = 0; } } @Override public NBTTagCompound writeToNBT(NBTTagCompound tagCompound) { super.writeToNBT(tagCompound); if (ItemStackTools.isValid(currentBook)) { NBTTagCompound compound = new NBTTagCompound(); currentBook.writeToNBT(compound); tagCompound.setTag("book", compound); } return tagCompound; } @Override public boolean onActivate(EntityPlayer player) { boolean rc = super.onActivate(player); if (getWorld().isRemote) { if (pageNumber == 0 && !player.isSneaking()) { pageIncClient(); return true; } return false; } if (rc) { return rc; } if (ItemStackTools.isValid(currentBook)) { if (player.isSneaking()) { InventoryHelper.giveItemToPlayer(player, currentBook); currentBook = ItemStackTools.getEmptyStack(); markDirtyClient(); } return true; } ItemStack heldItem = player.getHeldItem(EnumHand.MAIN_HAND); if (ItemStackTools.isValid(heldItem)) { if (heldItem.getItem() instanceof IBook) { currentBook = heldItem.splitStack(1); player.openContainer.detectAndSendChanges(); markDirtyClient(); return true; } else { ChatTools.addChatMessage(player, new TextComponentString(TextFormatting.YELLOW + "This is not a supported book!")); return false; } } return rc; } }
package me.abje.lingua.interpreter; import me.abje.lingua.Phase; import me.abje.lingua.interpreter.obj.Obj; import me.abje.lingua.lexer.Lexer; import me.abje.lingua.lexer.Morpher; import me.abje.lingua.parser.ParseException; import me.abje.lingua.parser.Parser; import me.abje.lingua.parser.expr.Expr; import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.Scanner; /** * The phase which produces objects from expressions. Usually the last phase in the pipeline. */ public class Interpreter implements Phase<Expr, Obj> { /** * The environment used for interpretation. */ private Environment env = new Environment(); public static void main(String[] args) throws FileNotFoundException { if (args.length == 1) { try { Interpreter interpreter = new Interpreter(); new Intrinsics(interpreter.env.getGlobals()).register(); interpreter.addImport("core"); interpreter.addImport(args[0]); } catch (ParseException | InterpreterException e) { e.printStackTrace(); } } else if (args.length == 0) { Scanner in = new Scanner(System.in); Interpreter interpreter = new Interpreter(); new Intrinsics(interpreter.env.getGlobals()).register(); interpreter.addImport("core"); System.out.print("> "); int num = 0; while (in.hasNextLine()) { try { Parser parser = new Parser(new Morpher(new Lexer(new StringReader(in.nextLine())))); List<Expr> exprs = new ArrayList<>(); Expr expr; while ((expr = parser.next()) != null) { exprs.add(expr); } for (Expr x : exprs) { Obj value = interpreter.next(x); do { num++; } while (interpreter.env.has("res" + num)); String varName = "res" + num; interpreter.env.define(varName, value); System.out.println(varName + " = " + value); } } catch (ParseException | InterpreterException e) { e.printStackTrace(); } System.out.print("> "); } } else { System.err.println("Usage: lingua [script]"); } } public void addImport(String fullName) { try { String name = fullName.replace('.', '/') + ".ling"; InputStream classpathStream = Interpreter.class.getResourceAsStream("/" + name); if (classpathStream != null) { interpret(new InputStreamReader(classpathStream)); } else { File file = new File(name); interpret(new FileReader(file)); } } catch (FileNotFoundException e) { throw new InterpreterException("not found: " + fullName); } } /** * Interprets the given expression. * * @param expr The expression to interpret. * @return The result of interpreting the expression. */ public Obj next(Expr expr) { return expr.evaluate(this); } /** * Interprets each expression in the given input. * * @param reader The input. */ public void interpret(Reader reader) { Parser parser = new Parser(new Morpher(new Lexer(reader))); List<Expr> exprs = new ArrayList<>(); Expr expr; while ((expr = parser.next()) != null) { exprs.add(expr); } exprs.forEach(this::next); } /** * Returns the environment used for interpretation. */ public Environment getEnv() { return env; } }
package mezz.jei.gui.ingredients; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import com.mojang.blaze3d.platform.GlStateManager; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.AbstractGui; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.renderer.Rectangle2d; import net.minecraft.client.renderer.RenderHelper; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.tags.ItemTags; import net.minecraft.tags.Tag; import net.minecraft.tags.TagCollection; import net.minecraft.util.ResourceLocation; import net.minecraft.util.text.TextFormatting; import mezz.jei.Internal; import mezz.jei.api.gui.drawable.IDrawable; import mezz.jei.api.gui.ingredient.IGuiIngredient; import mezz.jei.api.gui.ingredient.ITooltipCallback; import mezz.jei.api.helpers.IModIdHelper; import mezz.jei.api.ingredients.IIngredientHelper; import mezz.jei.api.ingredients.IIngredientRenderer; import mezz.jei.api.recipe.IFocus; import mezz.jei.gui.Focus; import mezz.jei.gui.TooltipRenderer; import mezz.jei.ingredients.IngredientFilter; import mezz.jei.ingredients.IngredientManager; import mezz.jei.render.IngredientRenderHelper; import mezz.jei.util.ErrorUtil; import mezz.jei.util.Translator; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class GuiIngredient<T> extends AbstractGui implements IGuiIngredient<T> { private static final Logger LOGGER = LogManager.getLogger(); private final int slotIndex; private final boolean input; private final Rectangle2d rect; private final int xPadding; private final int yPadding; private final CycleTimer cycleTimer; private final List<T> displayIngredients = new ArrayList<>(); // ingredients, taking focus into account private final List<T> allIngredients = new ArrayList<>(); // all ingredients, ignoring focus private final IIngredientRenderer<T> ingredientRenderer; private final IIngredientHelper<T> ingredientHelper; @Nullable private ITooltipCallback<T> tooltipCallback; @Nullable private IDrawable background; private boolean enabled; public GuiIngredient( int slotIndex, boolean input, IIngredientRenderer<T> ingredientRenderer, IIngredientHelper<T> ingredientHelper, Rectangle2d rect, int xPadding, int yPadding, int cycleOffset ) { this.ingredientRenderer = ingredientRenderer; this.ingredientHelper = ingredientHelper; this.slotIndex = slotIndex; this.input = input; this.rect = rect; this.xPadding = xPadding; this.yPadding = yPadding; this.cycleTimer = new CycleTimer(cycleOffset); } public Rectangle2d getRect() { return rect; } public boolean isMouseOver(double xOffset, double yOffset, double mouseX, double mouseY) { return enabled && (mouseX >= xOffset + rect.getX()) && (mouseY >= yOffset + rect.getY()) && (mouseX < xOffset + rect.getX() + rect.getWidth()) && (mouseY < yOffset + rect.getY() + rect.getHeight()); } @Nullable @Override public T getDisplayedIngredient() { return cycleTimer.getCycledItem(displayIngredients); } @Override public List<T> getAllIngredients() { return allIngredients; } public void set(@Nullable List<T> ingredients, @Nullable Focus<T> focus) { this.displayIngredients.clear(); this.allIngredients.clear(); List<T> displayIngredients; if (ingredients == null) { displayIngredients = Collections.emptyList(); } else { displayIngredients = ingredients; } T match = getMatch(displayIngredients, focus); if (match != null) { this.displayIngredients.add(match); } else { displayIngredients = filterOutHidden(displayIngredients); this.displayIngredients.addAll(displayIngredients); } if (ingredients != null) { this.allIngredients.addAll(ingredients); } enabled = !this.displayIngredients.isEmpty(); } private List<T> filterOutHidden(List<T> ingredients) { if (ingredients.isEmpty()) { return ingredients; } IngredientManager ingredientManager = Internal.getIngredientManager(); IngredientFilter ingredientFilter = Internal.getIngredientFilter(); List<T> visible = new ArrayList<>(); for (T ingredient : ingredients) { if (ingredient == null || ingredientManager.isIngredientVisible(ingredient, ingredientFilter)) { visible.add(ingredient); } if (visible.size() > 100) { return visible; } } if (visible.size() > 0) { return visible; } return ingredients; } public void setBackground(IDrawable background) { this.background = background; } @Nullable private T getMatch(Collection<T> ingredients, @Nullable Focus<T> focus) { if (focus != null && isMode(focus.getMode())) { T focusValue = focus.getValue(); return ingredientHelper.getMatch(ingredients, focusValue); } return null; } public void setTooltipCallback(@Nullable ITooltipCallback<T> tooltipCallback) { this.tooltipCallback = tooltipCallback; } public void draw(int xOffset, int yOffset) { cycleTimer.onDraw(); if (background != null) { background.draw(xOffset + rect.getX(), yOffset + rect.getY()); } T value = getDisplayedIngredient(); try { ingredientRenderer.render(xOffset + rect.getX() + xPadding, yOffset + rect.getY() + yPadding, value); } catch (RuntimeException | LinkageError e) { if (value != null) { throw ErrorUtil.createRenderIngredientException(e, value); } throw e; } } @Override public void drawHighlight(int color, int xOffset, int yOffset) { int x = rect.getX() + xOffset + xPadding; int y = rect.getY() + yOffset + yPadding; GlStateManager.disableLighting(); GlStateManager.disableDepthTest(); fill(x, y, x + rect.getWidth() - xPadding * 2, y + rect.getHeight() - yPadding * 2, color); GlStateManager.color4f(1f, 1f, 1f, 1f); } public void drawOverlays(int xOffset, int yOffset, int mouseX, int mouseY) { T value = getDisplayedIngredient(); if (value != null) { drawTooltip(xOffset, yOffset, mouseX, mouseY, value); } } private void drawTooltip(int xOffset, int yOffset, int mouseX, int mouseY, T value) { try { GlStateManager.disableDepthTest(); RenderHelper.disableStandardItemLighting(); fill(xOffset + rect.getX() + xPadding, yOffset + rect.getY() + yPadding, xOffset + rect.getX() + rect.getWidth() - xPadding, yOffset + rect.getY() + rect.getHeight() - yPadding, 0x7FFFFFFF); GlStateManager.color4f(1f, 1f, 1f, 1f); IModIdHelper modIdHelper = Internal.getHelpers().getModIdHelper(); List<String> tooltip = IngredientRenderHelper.getIngredientTooltipSafe(value, ingredientRenderer, ingredientHelper, modIdHelper); if (tooltipCallback != null) { tooltipCallback.onTooltip(slotIndex, input, value, tooltip); } Minecraft minecraft = Minecraft.getInstance(); FontRenderer fontRenderer = ingredientRenderer.getFontRenderer(minecraft, value); if (value instanceof ItemStack) { //noinspection unchecked Collection<ItemStack> itemStacks = (Collection<ItemStack>) this.allIngredients; ResourceLocation tagEquivalent = getTagEquivalent(itemStacks); if (tagEquivalent != null) { final String acceptsAny = Translator.translateToLocalFormatted("jei.tooltip.recipe.tag", tagEquivalent); tooltip.add(TextFormatting.GRAY + acceptsAny); } } TooltipRenderer.drawHoveringText(value, tooltip, xOffset + mouseX, yOffset + mouseY, fontRenderer); GlStateManager.enableDepthTest(); } catch (RuntimeException e) { LOGGER.error("Exception when rendering tooltip on {}.", value, e); } } @Nullable private static ResourceLocation getTagEquivalent(Collection<ItemStack> itemStacks) { if (itemStacks.size() < 2) { return null; } Set<Item> items = itemStacks.stream() .filter(Objects::nonNull) .map(ItemStack::getItem) .collect(Collectors.toSet()); TagCollection<Item> collection = ItemTags.getCollection(); Collection<Tag<Item>> tags = collection.getTagMap().values(); for (Tag<Item> tag : tags) { if (tag.getAllElements().equals(items)) { return tag.getId(); } } return null; } @Override public boolean isInput() { return input; } public boolean isMode(IFocus.Mode mode) { return (input && mode == IFocus.Mode.INPUT) || (!input && mode == IFocus.Mode.OUTPUT); } }
package mx.com.geexco.test.undertow.us; import io.undertow.Handlers; import io.undertow.Undertow; import io.undertow.server.handlers.form.EagerFormParsingHandler; import java.net.InetAddress; import mx.com.geexco.test.undertow.us.dao.RegistrationSource; import mx.com.geexco.test.undertow.us.handlers.ListaRegistradosHandler; import mx.com.geexco.test.undertow.us.handlers.NotificationHandler; import mx.com.geexco.test.undertow.us.handlers.RegistrationHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author gxc-mg */ public class MainApp { private static Logger log = LoggerFactory.getLogger("Main"); public static void main(String[] args) { log.info("INITIALIZING"); String hostname = ""; try { hostname = InetAddress.getLocalHost().getHostName(); } catch (Exception ex) { log.error("Error on getLocalhost", ex); return; } String port = System.getProperty("server.port"); log.info("System port: " + port); if (port == null) { port = "8080"; } int puerto = Integer.valueOf(port); RegistrationSource reg = new RegistrationSource(); String serviceKey = System.getProperty("GCM_KEY"); if (serviceKey == null) { log.error("Service cannot start without a serviceKey"); return; } log.info("serviceKey: ****" + serviceKey.substring(serviceKey.length() - 8)); Undertow server = Undertow.builder().setWorkerThreads(10) .addHttpListener(puerto, hostname) .setHandler(Handlers.path() .addExactPath("/api/register", new EagerFormParsingHandler().setNext(new RegistrationHandler(reg))) .addExactPath("/api/notify", new EagerFormParsingHandler().setNext(new NotificationHandler(reg, serviceKey))) .addExactPath("/api/list", new EagerFormParsingHandler().setNext(new ListaRegistradosHandler(reg))) ).build(); log.info("Server started on " + hostname + ":" + puerto); server.start(); } }
package net.aicomp.javachallenge2015; import java.util.ArrayList; import java.util.Random; import java.util.Scanner; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; public class Bookmaker { private static boolean DEBUG = false; private static final int PLAYERS_NUM = 4; private static final int MAP_WIDTH = 40; private static final int BLOCK_WIDTH = 5; private static final int INITIAL_LIFE = 5; private static final int FORCED_END_TURN = 10000; private static final int PANEL_REBIRTH_TURN = 5 * 4; public static final int PLAYER_REBIRTH_TURN = 5 * 4; public static final int ATTACKED_PAUSE_TURN = 5 * 4; public static final int MUTEKI_TURN = 10 * 4; private static final int REPULSION = 7; public static final int ACTION_TIME_LIMIT = 2000; private static final int TIME_TO_FALL = 1 * 4; public static final String READY = "Ready"; public static final String UP = "U"; public static final String DOWN = "D"; public static final String RIGHT = "R"; public static final String LEFT = "L"; public static final String ATTACK = "A"; public static final String NONE = "N"; public static final String[] DIRECTION = { UP, LEFT, DOWN, RIGHT }; private static Player[] players; private static Random rnd; private static int turn; private static int[][] board = new int[MAP_WIDTH][MAP_WIDTH]; private static final String EXEC_COMMAND = "a"; private static final String PAUSE_COMMAND = "p"; private static final String UNPAUSE_COMMAND = "u"; public static void main(String[] args) throws InterruptedException, ParseException { Options options = new Options() .addOption( EXEC_COMMAND, true, "The command and arguments with double quotation marks to execute AI program (e.g. -a \"java MyAI\")") .addOption( PAUSE_COMMAND, true, "The command and arguments with double quotation marks to pause AI program (e.g. -p \"echo pause\")") .addOption( UNPAUSE_COMMAND, true, "The command and arguments with double quotation marks to unpause AI program (e.g. -u \"echo unpause\")"); CommandLineParser parser = new DefaultParser(); CommandLine line = parser.parse(options, args); if (!hasCompleteArgs(line)) { HelpFormatter help = new HelpFormatter(); help.printHelp("java -jar JavaChallenge2015.jar [OPTIONS]\n" + "[OPTIONS]: ", "", options, "", true); return; } String[] execAICommands = line.getOptionValues(EXEC_COMMAND); String[] pauseAICommands = line.getOptionValues(PAUSE_COMMAND); String[] unpauseAICommands = line.getOptionValues(UNPAUSE_COMMAND); rnd = new Random(System.currentTimeMillis()); turn = 0; players = new Player[PLAYERS_NUM]; for (int i = 0; i < players.length; i++) { players[i] = new Player(INITIAL_LIFE, execAICommands[i], pauseAICommands[i], unpauseAICommands[i]); } rebirthPhase(); while (!isFinished()) { int turnPlayer = turn % PLAYERS_NUM; String command = infromationPhase(turnPlayer); printLOG(command); // DEBUG if (DEBUG && turnPlayer == 0 && players[turnPlayer].isOnBoard() && !players[turnPlayer].isPausing(turn)) { command = new Scanner(System.in).next(); } actionPhase(turnPlayer, command); rebirthPhase(); turn++; } System.out.println("Game Finished!"); } /** * null4 * 14 * * @param line * @author J.Kobayashi * @return {@code true}{@code false} */ private static boolean hasCompleteArgs(CommandLine line) { if (line == null) { return false; } if (!line.hasOption(EXEC_COMMAND) || line.getOptionValues(EXEC_COMMAND).length != PLAYERS_NUM) { return false; } if (!line.hasOption(PAUSE_COMMAND)) { return true; } if (line.getOptionValues(PAUSE_COMMAND).length != PLAYERS_NUM) { return false; } if (!line.hasOption(UNPAUSE_COMMAND)) { return true; } if (line.getOptionValues(UNPAUSE_COMMAND).length != PLAYERS_NUM) { return false; } return true; } private static void printLOG(String command) { System.out.println(turn); for (Player player : players) { System.out.print(player.life + " "); } System.out.println(); for (int x = 0; x < MAP_WIDTH; x++) { outer: for (int y = 0; y < MAP_WIDTH; y++) { if (DEBUG) { for (int playerID = 0; playerID < PLAYERS_NUM; playerID++) { Player player = players[playerID]; if (player.isOnBoard() && player.x == x && player.y == y) { char c = (char) (playerID + 'A'); System.out.print(c + "" + c); continue outer; } } } System.out.print(" " + board[x][y]); } System.out.println(); } for (Player player : players) { if (player.isOnBoard()) { System.out.println(player.x + " " + player.y + " " + Bookmaker.DIRECTION[player.dir]); } else { System.out.println((-1) + " " + (-1) + " " + Bookmaker.DIRECTION[player.dir]); } } System.out.println(command); } private static void rebirthPhase() { for (int i = 0; i < MAP_WIDTH; i++) { for (int j = 0; j < MAP_WIDTH; j++) { if (board[i][j] < 0) { board[i][j]++; } else if (board[i][j] == 1) { board[i][j] = -PANEL_REBIRTH_TURN; } else if (board[i][j] > 1) { board[i][j] } } } for (int i = 0; i < PLAYERS_NUM; i++) { Player p = players[i]; if (p.isOnBoard() && !p.isMuteki(turn)) { if (board[p.x][p.y] < 0) { p.drop(turn); } } else if (p.isAlive() && !p.isOnBoard() && p.rebirthTurn == turn) { search: while (true) { int x = nextInt(); int y = nextInt(); for (int j = 0; j < PLAYERS_NUM; j++) { if (i == j) { continue; } Player other = players[j]; if (other.isOnBoard() && dist(x, y, other.x, other.y) <= REPULSION) { continue search; } } p.reBirthOn(x, y, turn); p.dir = nextDir(); break; } } } } private static String infromationPhase(int turnPlayer) { if (!players[turnPlayer].isAlive()) { return NONE; } ArrayList<Integer> lifes = new ArrayList<Integer>(); ArrayList<String> wheres = new ArrayList<String>(); for (int i = 0; i < PLAYERS_NUM; i++) { lifes.add(players[i].life); if (players[i].isOnBoard()) { wheres.add(players[i].x + " " + players[i].y); } else { wheres.add((-1) + " " + (-1)); } } String command = players[turnPlayer].getAction(turnPlayer, turn, board, lifes, wheres); return command; } private static void actionPhase(int turnPlayer, String command) { Player p = players[turnPlayer]; if (!p.isOnBoard() || p.isPausing(turn) || command.equals(NONE)) { return; } if (command.equals(ATTACK)) { int xNow = p.x / BLOCK_WIDTH; int yNow = p.y / BLOCK_WIDTH; for (int x = 0; x < MAP_WIDTH; x++) { for (int y = 0; y < MAP_WIDTH; y++) { int xBlock = x / BLOCK_WIDTH; int yBlock = y / BLOCK_WIDTH; if (p.dir == 0) { if (yBlock == yNow && xBlock < xNow && board[x][y] == 0) { board[x][y] = dist(xBlock, yBlock, xNow, yNow) * TIME_TO_FALL; } } else if (p.dir == 1) { if (xBlock == xNow && yBlock < yNow && board[x][y] == 0) { board[x][y] = dist(xBlock, yBlock, xNow, yNow) * TIME_TO_FALL; } } else if (p.dir == 2) { if (yBlock == yNow && xBlock > xNow && board[x][y] == 0) { board[x][y] = dist(xBlock, yBlock, xNow, yNow) * TIME_TO_FALL; } } else if (p.dir == 3) { if (xBlock == xNow && yBlock > yNow && board[x][y] == 0) { board[x][y] = dist(xBlock, yBlock, xNow, yNow) * TIME_TO_FALL; } } } } p.attackedPause(turn); return; } { int tox = -1, toy = -1; if (command.equals(UP)) { tox = p.x - 1; toy = p.y; } else if (command.equals(RIGHT)) { tox = p.x; toy = p.y + 1; } else if (command.equals(DOWN)) { tox = p.x + 1; toy = p.y; } else if (command.equals(LEFT)) { tox = p.x; toy = p.y - 1; } else { return; } if (!isInside(tox, toy)) { return; } p.directTo(command); for (int i = 0; i < PLAYERS_NUM; i++) { if (!players[i].isOnBoard() || i == turnPlayer) { continue; } if (dist(tox, toy, players[i].x, players[i].y) < REPULSION) { return; } } p.moveTo(tox, toy); } } private static int dist(int x1, int y1, int x2, int y2) { return Math.abs(x1 - x2) + Math.abs(y1 - y2); } private static int nextInt() { int ret = (int) (rnd.nextDouble() * MAP_WIDTH); return ret; } private static int nextDir() { int rng = rnd.nextInt(4); return rng; } private static boolean isInside(int x, int y) { return 0 <= x && x < MAP_WIDTH && 0 <= y && y < MAP_WIDTH; } private static boolean isFinished() { int livingCnt = 0; for (int i = 0; i < players.length; i++) { if (players[i].life > 0) { livingCnt++; } } return livingCnt == 1 || turn > FORCED_END_TURN; } }
package net.bramp.ffmpeg.builder; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import net.bramp.ffmpeg.FFmpegUtils; import net.bramp.ffmpeg.probe.FFmpegProbeResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.concurrent.TimeUnit; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; /** * Builds a ffmpeg command line * * @author bramp */ public class FFmpegBuilder { final static Logger LOG = LoggerFactory.getLogger(FFmpegBuilder.class); public enum Strict { VERY, // strictly conform to a older more strict version of the spec or reference software STRICT, // strictly conform to all the things in the spec no matter what consequences NORMAL, // normal UNOFFICAL, // allow unofficial extensions EXPERIMENTAL; // ffmpeg command line requires these options in the lower case public String toString() { return name().toLowerCase(); } } public enum Verbosity { QUIET, PANIC, FATAL, ERROR, WARNING, INFO, VERBOSE, DEBUG; public String toString() { return name().toLowerCase(); } } // Global Settings boolean override = true; int pass = 0; String pass_prefix; Verbosity verbosity = Verbosity.ERROR; // Input settings String format; Long startOffset; // in millis boolean read_at_native_frame_rate = false; final List<String> inputs = new ArrayList<>(); final Map<String, FFmpegProbeResult> inputProbes = new TreeMap<>(); final List<String> extra_args = new ArrayList<>(); // Output final List<FFmpegOutputBuilder> outputs = new ArrayList<FFmpegOutputBuilder>(); public FFmpegBuilder overrideOutputFiles(boolean override) { this.override = override; return this; } public boolean getOverrideOutputFiles() { return this.override; } public FFmpegBuilder setPass(int pass) { this.pass = pass; return this; } public FFmpegBuilder setPassPrefix(String prefix) { this.pass_prefix = prefix; return this; } public FFmpegBuilder setVerbosity(Verbosity verbosity) { checkNotNull(verbosity); this.verbosity = verbosity; return this; } public FFmpegBuilder readAtNativeFrameRate() { this.read_at_native_frame_rate = true; return this; } public FFmpegBuilder addInput(FFmpegProbeResult result) { checkNotNull(result); String filename = checkNotNull(result.format).filename; inputProbes.put(filename, result); return addInput(filename); } public FFmpegBuilder addInput(String filename) { checkNotNull(filename); inputs.add(filename); return this; } protected void clearInputs() { inputs.clear(); inputProbes.clear(); } public FFmpegBuilder setInput(FFmpegProbeResult result) { checkNotNull(result); clearInputs(); return addInput(result); } public FFmpegBuilder setInput(String filename) { checkNotNull(filename); clearInputs(); return addInput(filename); } public FFmpegBuilder setFormat(String format) { this.format = checkNotNull(format); return this; } public FFmpegBuilder setStartOffset(long duration, TimeUnit units) { checkNotNull(duration); checkNotNull(units); this.startOffset = units.toMillis(duration); return this; } /** * Add additional ouput arguments (for flags which aren't currently supported). * * @param values */ public FFmpegBuilder addExtraArgs(String... values) { checkArgument(values.length > 0, "One or more values must be supplied"); for (String value : values) { extra_args.add(checkNotNull(value)); } return this; } /** * Create new output file * * @param filename * @return A new FFmpegOutputBuilder */ public FFmpegOutputBuilder addOutput(String filename) { FFmpegOutputBuilder output = new FFmpegOutputBuilder(this, filename); outputs.add(output); return output; } public FFmpegOutputBuilder addOutput(URI uri) { FFmpegOutputBuilder output = new FFmpegOutputBuilder(this, uri); outputs.add(output); return output; } /** * Create new output (to stdout) */ public FFmpegOutputBuilder addStdoutOutput() { return addOutput("-"); } public List<String> build() { ImmutableList.Builder<String> args = new ImmutableList.Builder<String>(); Preconditions.checkArgument(!inputs.isEmpty(), "At least one input must be specified"); Preconditions.checkArgument(!outputs.isEmpty(), "At least one output must be specified"); args.add(override ? "-y" : "-n"); args.add("-v", this.verbosity.toString()); if (startOffset != null) { args.add("-ss").add(FFmpegUtils.millisecondsToString(startOffset)); } if (format != null) { args.add("-f", format); } if (read_at_native_frame_rate) { args.add("-re"); } args.addAll(extra_args); for (String input : inputs) { args.add("-i").add(input); } if (pass > 0) { args.add("-pass").add(Integer.toString(pass)); if (pass_prefix != null) { args.add("-passlogfile").add(pass_prefix); } } for (FFmpegOutputBuilder output : this.outputs) { args.addAll(output.build(pass)); } return args.build(); } }
package net.morematerials.listeners; import net.morematerials.MoreMaterials; import net.morematerials.materials.CustomFuel; import net.morematerials.materials.MMCustomBlock; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.inventory.FurnaceBurnEvent; import org.bukkit.event.inventory.FurnaceSmeltEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.inventory.ItemStack; import org.getspout.spout.block.SpoutCraftBlock; import org.getspout.spoutapi.SpoutManager; import org.getspout.spoutapi.block.SpoutBlock; import org.getspout.spoutapi.inventory.SpoutItemStack; import org.getspout.spoutapi.material.Block; import org.getspout.spoutapi.material.block.GenericCustomBlock; import org.getspout.spoutapi.material.item.GenericCustomItem; import org.getspout.spoutapi.material.item.GenericCustomTool; import org.getspout.spoutapi.player.SpoutPlayer; import org.getspout.spoutapi.sound.SoundEffect; public class MMListener implements Listener { private MoreMaterials plugin; public MMListener(MoreMaterials plugin) { this.plugin = plugin; } @EventHandler public void onPlayerInteract(PlayerInteractEvent event) { // The click events for hold item. if (event.getAction() == Action.LEFT_CLICK_AIR || event.getAction() == Action.LEFT_CLICK_BLOCK) { SpoutItemStack stack = new SpoutItemStack(event.getPlayer().getItemInHand()); if (stack.getMaterial() instanceof GenericCustomItem) { this.plugin.getHandlerManager().triggerHandlers("HoldLeftClick", ((GenericCustomItem) stack.getMaterial()).getCustomId(), event); } else if (stack.getMaterial() instanceof GenericCustomBlock) { this.plugin.getHandlerManager().triggerHandlers("HoldLeftClick", ((GenericCustomBlock) stack.getMaterial()).getCustomId(), event); } } else if (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) { SpoutItemStack stack = new SpoutItemStack(event.getPlayer().getItemInHand()); if (stack.getMaterial() instanceof GenericCustomItem) { this.plugin.getHandlerManager().triggerHandlers("HoldRightClick", ((GenericCustomItem) stack.getMaterial()).getCustomId(), event); } else if (stack.getMaterial() instanceof GenericCustomBlock) { this.plugin.getHandlerManager().triggerHandlers("HoldRightClick", ((GenericCustomBlock) stack.getMaterial()).getCustomId(), event); } } // The click event for the block you clicked on if (event.getAction() == Action.LEFT_CLICK_BLOCK || event.getAction() == Action.RIGHT_CLICK_BLOCK) { Block block = ((SpoutCraftBlock) event.getClickedBlock()).getBlockType(); if (block instanceof GenericCustomBlock) { if (event.getAction() == Action.LEFT_CLICK_BLOCK) { this.plugin.getHandlerManager().triggerHandlers("LeftClick", ((GenericCustomBlock) block).getCustomId(), event); } else { this.plugin.getHandlerManager().triggerHandlers("RightClick", ((GenericCustomBlock) block).getCustomId(), event); } } } } @EventHandler public void onPlayerMove(PlayerMoveEvent event) { Location location = event.getPlayer().getLocation(); Block block = ((SpoutCraftBlock) location.getWorld().getBlockAt(location)).getBlockType(); // Touch represents a block you are standing in. if (block instanceof GenericCustomBlock) { this.plugin.getHandlerManager().triggerHandlers("Touch", ((GenericCustomBlock) block).getCustomId(), event); } block = ((SpoutCraftBlock) location.getWorld().getBlockAt(location.subtract(0, 1, 0))).getBlockType(); // Walkover represents the block under your position. if (block instanceof GenericCustomBlock) { this.plugin.getHandlerManager().triggerHandlers("Walkover", ((GenericCustomBlock) block).getCustomId(), event); } } @EventHandler public void onBlockBreak(BlockBreakEvent event) { // Make sure we have a valid event. if (event.getPlayer() == null || event.getPlayer().getGameMode() == GameMode.CREATIVE) { return; } SpoutPlayer player = (SpoutPlayer) event.getPlayer(); // Check for durability and ItemDropRequired. if (player.getItemInHand() != null) { SpoutItemStack stack = new SpoutItemStack(player.getItemInHand()); // Check for ItemDropRequired Block block = ((SpoutCraftBlock) event.getBlock()).getBlockType(); if (block instanceof GenericCustomBlock) { GenericCustomBlock customBlock = (GenericCustomBlock) block; Object material = this.plugin.getSmpManager().getMaterial(customBlock.getCustomId()); // Make sure this is an MoreMaterials block. if (material != null && material instanceof MMCustomBlock) { if (((MMCustomBlock) material).getItemDropRequired()) { // Forbid tools without modifier Boolean prevent = !(stack.getMaterial() instanceof GenericCustomTool); if (!prevent) { prevent = ((GenericCustomTool) stack.getMaterial()).getStrengthModifier(customBlock) <= 1.0; } if (prevent) { event.setCancelled(true); SpoutBlock spoutBlock = (SpoutBlock) event.getBlock(); spoutBlock.setType(org.bukkit.Material.AIR); spoutBlock.setCustomBlock(null); } } } } if (stack.isCustomItem() && stack.getMaterial() instanceof GenericCustomTool) { GenericCustomTool tool = (GenericCustomTool) stack.getMaterial(); // Do durability stuff durability. if (tool.getMaxDurability() == 0) { return; } else if (GenericCustomTool.getDurability(stack) + 1 < tool.getMaxDurability()) { GenericCustomTool.setDurability(stack, (short) (GenericCustomTool.getDurability(stack) + 1)); player.setItemInHand(stack); } else { player.setItemInHand(new ItemStack(Material.AIR)); //FIXME must be added to spoutPlugin SpoutManager.getSoundManager().playSoundEffect(player, SoundEffect.BREAK); } } } } @EventHandler public void OnFurnaceBurn(FurnaceBurnEvent event) { SpoutItemStack item = new SpoutItemStack(event.getFuel()); if (item.getMaterial() instanceof CustomFuel && ((CustomFuel)item.getMaterial()).getBurnTime() > 0) { event.setBurning(true); event.setBurnTime(((CustomFuel)item.getMaterial()).getBurnTime()); } } @EventHandler public void onPlayerSmelt(FurnaceSmeltEvent event) { SpoutItemStack itemStack = this.plugin.getFurnaceRecipeManager().getResult(new SpoutItemStack(event.getSource())); if (itemStack != null) { event.setResult(itemStack); } } }
package tlc2.tool.fp; import java.io.IOException; import java.text.DecimalFormat; import java.util.Random; public abstract class FPSetTest extends AbstractFPSetTest { private long previousTimestamp; private long previousSize; private final DecimalFormat df = new DecimalFormat(" public void testSimpleFill() throws IOException { long freeMemory = getFreeMemoryInBytes(); final FPSet fpSet = getFPSet(freeMemory); fpSet.init(1, tmpdir, filename); long fp = 1L; assertFalse(fpSet.put(fp)); assertTrue(fpSet.contains(fp++)); assertFalse(fpSet.put(fp)); assertTrue(fpSet.contains(fp++)); assertFalse(fpSet.put(fp)); assertTrue(fpSet.contains(fp++)); assertFalse(fpSet.put(fp)); assertTrue(fpSet.contains(fp++)); } /** * Test filling a {@link FPSet} with max int + 1 random * @throws IOException */ public void testMaxFPSetSizeRnd() throws IOException { Random rnd = new Random(15041980L); // amount to ~514 (mb) with 4gb system mem long freeMemory = getFreeMemoryInBytes(); final FPSet fpSet = getFPSet(freeMemory); fpSet.init(1, tmpdir, filename); long predecessor = 0L; // fill with max int + 1 final long l = Integer.MAX_VALUE + 2L; for (long i = 1; i < l; i++) { // make sure set still contains predecessor if (predecessor != 0L) { assertTrue(fpSet.contains(predecessor)); } predecessor = rnd.nextLong(); assertFalse(fpSet.put(predecessor)); long currentSize = fpSet.size(); assertTrue(i == currentSize); printInsertionSpeed(currentSize); } // try creating a check point fpSet.beginChkpt(); fpSet.commitChkpt(); assertEquals(l, fpSet.size()); } // insertion speed private void printInsertionSpeed(final long currentSize) { long currentTimestamp = System.currentTimeMillis(); // print every minute if (currentTimestamp - previousTimestamp >= (60 * 1000d)) { long insertions = (long) (currentSize - previousSize); System.out.println(df.format(insertions) + " insertions/min"); previousTimestamp = currentTimestamp; previousSize = currentSize; } } /** * Test filling a {@link FPSet} with max int + 1 * @throws IOException */ public void testMaxFPSetSize() throws IOException { final FPSet fpSet = getFPSet(getFreeMemoryInBytes()); fpSet.init(1, tmpdir, filename); long counter = 0; // fill with max int + 1 final long l = Integer.MAX_VALUE + 2L; // choose value in the interval [-l/2, l/2] for (long i = (l/2) * -1; i < l; i++) { long value = -1; if (i % 2 != 0) { value = l - i; } else { value = i; } assertFalse(fpSet.put(value)); long currentSize = fpSet.size(); assertTrue(++counter == currentSize); printInsertionSpeed(currentSize); } // try creating a check point fpSet.beginChkpt(); fpSet.commitChkpt(); assertEquals(l, fpSet.size()); } }
package net.openhft.chronicle.map; import net.openhft.chronicle.core.Jvm; import net.openhft.chronicle.core.OS; import net.openhft.chronicle.hash.ChronicleFileLockException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.IOException; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; import java.nio.channels.OverlappingFileLockException; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; public final class FileLockUtil { /** * Java file locks are maintained on a per JVM basis. So we need to manage them. */ private static final String DISABLE_LOCKING = "chronicle.map.disable.locking"; private static final ConcurrentHashMap<File, FileLockReference> FILE_LOCKS = new ConcurrentHashMap<>(); private static final boolean USE_EXCLUSIVE_LOCKING = !Jvm.getBoolean(DISABLE_LOCKING); private static final boolean USE_SHARED_LOCKING = !OS.isWindows() && !Jvm.getBoolean(DISABLE_LOCKING) && !"shared".equalsIgnoreCase(System.getProperty(DISABLE_LOCKING)); private static final AtomicBoolean LOCK_WARNING_PRINTED = new AtomicBoolean(); private FileLockUtil() { } public static void acquireSharedFileLock(@NotNull final File canonicalFile, @NotNull final FileChannel channel) { if (USE_SHARED_LOCKING) FILE_LOCKS.compute(canonicalFile, (f, flr) -> { try { if (flr == null) return new FileLockReference(channel.lock(0, Long.MAX_VALUE, true)); else { if (!flr.fileLock.isShared()) { throw newUnableToAcquireSharedFileLockException(canonicalFile, null); } flr.reserve(); return flr; // keep the old one } } catch (IOException | IllegalStateException e) { throw newUnableToAcquireSharedFileLockException(canonicalFile, e); } } ); else printWarningTheFirstTime(); } public static void acquireExclusiveFileLock(@NotNull final File canonicalFile, @NotNull final FileChannel channel) { if (USE_EXCLUSIVE_LOCKING) FILE_LOCKS.compute(canonicalFile, (f, flr) -> { if (flr == null) { try { final FileLock fileLock = channel.lock(0, Long.MAX_VALUE, false); return new FileLockReference(fileLock); } catch (IOException e) { throw newUnableToAcquireExclusiveFileLockException(canonicalFile, e); } } else { throw newUnableToAcquireExclusiveFileLockException(canonicalFile, null); } } ); else printWarningTheFirstTime(); } public static void releaseSharedFileLock(@NotNull final File canonicalFile) { if (USE_SHARED_LOCKING) releaseFileLock0(canonicalFile); else printWarningTheFirstTime(); } public static void releaseExclusiveFileLock(@NotNull final File canonicalFile) { if (USE_EXCLUSIVE_LOCKING) releaseFileLock0(canonicalFile); else printWarningTheFirstTime(); } /** * @deprecated Use {@link #releaseExclusiveFileLock(File)} or {@link #releaseSharedFileLock(File)} instead. */ @Deprecated public static void releaseFileLock(@NotNull final File canonicalFile) { releaseExclusiveFileLock(canonicalFile); } private static void releaseFileLock0(@NotNull File canonicalFile) { FILE_LOCKS.compute(canonicalFile, (f, flr) -> { if (flr == null) throw new ChronicleFileLockException("Trying to release lock on file " + canonicalFile + " that did not exist"); else { final int cnt = flr.release(); if (cnt == 0) return null; // Remove the old one else return flr; } } ); } /** * Tries to execute a closure under exclusive file lock. * If USE_LOCKING is false, provides synchronization only within local JVM. * * @param fileIOAction Closure to run, can throw {@link IOException}s. * @return <code>true</code> if the lock was successfully acquired and IO action was executed, <code>false</code> otherwise. */ public static boolean tryRunExclusively(@NotNull final File canonicalFile, @NotNull final FileChannel fileChannel, @NotNull final FileIOAction fileIOAction) { AtomicBoolean locked = new AtomicBoolean(false); FILE_LOCKS.compute(canonicalFile, (f, flr) -> { if (flr != null) return flr; try { if (USE_EXCLUSIVE_LOCKING) { try (FileLock ignored = fileChannel.tryLock()) { if (ignored == null) return null; fileIOAction.fileIOAction(); locked.set(true); } catch (OverlappingFileLockException ignored) { // File lock is being held by this JVM, unsuccessful attempt. } } else { fileIOAction.fileIOAction(); locked.set(true); } return null; } catch (Exception e) { throw Jvm.rethrow(e); } } ); return locked.get(); } /** * Executes a closure under exclusive file lock. * If USE_LOCKING is false, provides synchronization only within local JVM. * * @param fileIOAction Closure to run, can throw {@link IOException}s. */ public static void runExclusively(@NotNull final File canonicalFile, @NotNull final FileChannel fileChannel, @NotNull final FileIOAction fileIOAction) { FILE_LOCKS.compute(canonicalFile, (f, flr) -> { if (flr != null) throw new ChronicleFileLockException("A file lock instance already exists for the file " + canonicalFile); try { if (USE_EXCLUSIVE_LOCKING) { try (FileLock ignored = fileChannel.lock()) { fileIOAction.fileIOAction(); } } else { fileIOAction.fileIOAction(); } return null; } catch (Exception e) { throw Jvm.rethrow(e); } } ); } static void dump() { System.out.println(FILE_LOCKS); } private static ChronicleFileLockException newUnableToAcquireSharedFileLockException(@NotNull final File canonicalFile, @Nullable final Exception e) { return new ChronicleFileLockException("Unable to acquire a shared file lock for " + canonicalFile + ". " + "Make sure another process is not recovering the map.", e); } private static ChronicleFileLockException newUnableToAcquireExclusiveFileLockException(@NotNull final File canonicalFile, @Nullable final Exception e) { return new ChronicleFileLockException("Unable to acquire an exclusive file lock for " + canonicalFile + ". " + "Make sure no other process is using the map.", e); } private static void printWarningTheFirstTime() { if (LOCK_WARNING_PRINTED.compareAndSet(false, true)) { Jvm.warn().on(FileLockUtil.class, "File locking is disabled or not supported on this platform (" + System.getProperty("os.name") + "). " + "Make sure you are not running ChronicleMapBuilder::*recover* methods when other processes or threads have the mapped file open!"); } } // This class is not thread-safe but instances // are protected by means of the FILE_LOCKS map private static final class FileLockReference { private final FileLock fileLock; private int refCount; FileLockReference(@NotNull final FileLock fileLock) { this.fileLock = fileLock; refCount = 1; } int reserve() { if (refCount == 0) throw new IllegalStateException("Ref counter previously released"); return ++refCount; } int release() { final int cnt = --refCount; if (cnt == 0) { try { fileLock.release(); } catch (IOException e) { throw new ChronicleFileLockException(e); } } if (cnt < 0) throw new IllegalStateException("Ref counter was " + cnt); return cnt; } @Override public String toString() { return "FileLockReference{" + "fileLock=" + fileLock + ", refCount=" + refCount + '}'; } } @FunctionalInterface interface FileIOAction { void fileIOAction() throws IOException; } }
package net.wyun.wcrs.wechat.po; /** * * * @author qikuo * @date 2017-2-28 */ public class WeixinUserInfo { private String openId; private int subscribe; private String subscribeTime; private String nickname; // 120 private int sex; private String country; private String province; private String city; // zh_CN private String language; private String headImgUrl; public String getOpenId() { return openId; } public void setOpenId(String openId) { this.openId = openId; } public int getSubscribe() { return subscribe; } public void setSubscribe(int subscribe) { this.subscribe = subscribe; } public String getSubscribeTime() { return subscribeTime; } public void setSubscribeTime(String subscribeTime) { this.subscribeTime = subscribeTime; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public int getSex() { return sex; } public void setSex(int sex) { this.sex = sex; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } public String getHeadImgUrl() { return headImgUrl; } public void setHeadImgUrl(String headImgUrl) { this.headImgUrl = headImgUrl; } @Override public String toString() { return "WeixinUserInfo [" + (openId != null ? "openId=" + openId + ", " : "") + "subscribe=" + subscribe + ", " + (subscribeTime != null ? "subscribeTime=" + subscribeTime + ", " : "") + (nickname != null ? "nickname=" + nickname + ", " : "") + "sex=" + sex + ", " + (country != null ? "country=" + country + ", " : "") + (province != null ? "province=" + province + ", " : "") + (city != null ? "city=" + city + ", " : "") + (language != null ? "language=" + language + ", " : "") + (headImgUrl != null ? "headImgUrl=" + headImgUrl : "") + "]"; } }
package to.etc.domui.login; public interface IUser { /** * The user's login ID. * @return */ String getLoginID(); /** * Return a display name for the user; this usually is the full formal name. * @return */ String getDisplayName(); // /** // * The set of names representing the rights the user has. // * @return // */ // Set<String> getRightNames(); boolean hasRight(String r); boolean hasRight(String r, Object dataElement); }
package net.xprova.verilogparser; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.misc.Interval; import net.xprova.netlist.GateLibrary; import net.xprova.netlist.Module; import net.xprova.netlist.Net; import net.xprova.netlist.Netlist; import net.xprova.netlist.PinConnection; import net.xprova.netlist.PinDirection; import net.xprova.netlist.Port; import net.xprova.verilogparser.Verilog2001Parser.Continuous_assignContext; import net.xprova.verilogparser.Verilog2001Parser.DescriptionContext; import net.xprova.verilogparser.Verilog2001Parser.ExpressionContext; import net.xprova.verilogparser.Verilog2001Parser.Inout_declarationContext; import net.xprova.verilogparser.Verilog2001Parser.Input_declarationContext; import net.xprova.verilogparser.Verilog2001Parser.List_of_port_connectionsContext; import net.xprova.verilogparser.Verilog2001Parser.List_of_portsContext; import net.xprova.verilogparser.Verilog2001Parser.Module_declarationContext; import net.xprova.verilogparser.Verilog2001Parser.Module_instanceContext; import net.xprova.verilogparser.Verilog2001Parser.Module_instantiationContext; import net.xprova.verilogparser.Verilog2001Parser.Module_itemContext; import net.xprova.verilogparser.Verilog2001Parser.Module_or_generate_itemContext; import net.xprova.verilogparser.Verilog2001Parser.Module_or_generate_item_declarationContext; import net.xprova.verilogparser.Verilog2001Parser.Named_port_connectionContext; import net.xprova.verilogparser.Verilog2001Parser.Net_assignmentContext; import net.xprova.verilogparser.Verilog2001Parser.Net_declarationContext; import net.xprova.verilogparser.Verilog2001Parser.Net_identifierContext; import net.xprova.verilogparser.Verilog2001Parser.Net_typeContext; import net.xprova.verilogparser.Verilog2001Parser.Ordered_port_connectionContext; import net.xprova.verilogparser.Verilog2001Parser.Output_declarationContext; import net.xprova.verilogparser.Verilog2001Parser.PortContext; import net.xprova.verilogparser.Verilog2001Parser.Port_declarationContext; import net.xprova.verilogparser.Verilog2001Parser.Port_identifierContext; import net.xprova.verilogparser.Verilog2001Parser.PrimaryContext; import net.xprova.verilogparser.Verilog2001Parser.RangeContext; import net.xprova.verilogparser.Verilog2001Parser.Source_textContext; import net.xprova.verilogparser.Verilog2001Parser.TermContext; /** * * Module * */ public class VerilogParser { // class members private static CommonTokenStream tokenStream; private static GateLibrary library1; private static Verilog2001Parser parser1; // error messages private final static String ERR_MSG_1 = "port <%s> not declared in module header"; private final static String ERR_MSG_2 = "could not parse port list"; private final static String ERR_MSG_3 = "direction of port <%s> unspecified"; private final static String ERR_MSG_4 = "unsupported grammar"; private final static String ERR_MSG_5 = "port <%s> declared more than once in module header"; private final static String ERR_MSG_6 = "unsupported net declaration grammar"; private final static String ERR_MSG_7 = "Unsupported grammar for bit range"; private final static String ERR_MSG_8 = "net redefinition"; private final static String ERR_MSG_9 = "declaration mismatch between port <%s> [%d:%d] and wire <%s> [%d:%d]"; private final static String ERR_MSG_10 = "implicit declaratin of array net"; private final static String ERR_MSG_12 = "gate instantiation is not supported"; private final static String ERR_MSG_13 = "unsupported module connection"; private final static String ERR_MSG_15 = "redefinition of module instance <%s>"; private final static String ERR_MSG_16 = "module %s does not exist in library"; private final static String ERR_MSG_17 = "non-scalar net <%s> must be explicitly declared"; // exception generation and handling private static void fail(String filename, String errMsg, Module_itemContext itemCon) throws UnsupportedGrammerException { Interval int1 = itemCon.getSourceInterval(); // get token interval Token firstToken = tokenStream.get(int1.a); int lineNum = firstToken.getLine(); // get line of first token // Determining j, first token in int1 which occurs at a different line int j; for (j = int1.a; j < int1.b; j++) { if (tokenStream.get(j).getLine() != lineNum) break; } // form a string from tokens 1 through j-1 String tokenStr = tokenStream.getText(new Interval(int1.a, j)); System.err.printf("Parser error (%s:%d): %s\n", filename, lineNum, tokenStr); System.err.println(errMsg); throw new UnsupportedGrammerException(""); } private static void fail(String errMsg) throws UnsupportedGrammerException { throw new UnsupportedGrammerException(errMsg); } // parsing API public static ArrayList<Netlist> parseFile(String verilogFile, GateLibrary library) throws Exception { // pass null as `library` to parse without library FileInputStream stream1 = new FileInputStream(verilogFile); return getNetlists(verilogFile, new ANTLRInputStream(stream1), library == null ? new GateLibrary() : library); } public static ArrayList<Netlist> parseString(String str, GateLibrary library) throws Exception { // pass null as `library` to parse without library return getNetlists("STRING", new ANTLRInputStream(str), library == null ? new GateLibrary() : library); } // parsing methods private static void createParser(String filename, ANTLRInputStream antlr, GateLibrary library1) { // ANTLR parsing Verilog2001Lexer lexer1 = new Verilog2001Lexer(antlr); CommonTokenStream tokenStream = new CommonTokenStream(lexer1); parser1 = new Verilog2001Parser(tokenStream); VerilogParser.tokenStream = tokenStream; VerilogParser.library1 = library1; } private static ArrayList<Netlist> getNetlists(String filename, ANTLRInputStream antlr, GateLibrary library1) throws Exception { // ANTLR parsing createParser(filename, antlr, library1); Source_textContext source = parser1.source_text(); List<DescriptionContext> modules = source.description(); int nModules = modules.size(); ArrayList<Netlist> netlistArr = new ArrayList<Netlist>(); for (int j = 0; j < nModules; j++) { Module_declarationContext module = modules.get(j).module_declaration(); Netlist netlist = new Netlist(); netlist.name = module.module_identifier().getText(); List_of_portsContext portList = module.list_of_ports(); if (portList == null) { fail(ERR_MSG_4); } ArrayList<String> ports = new ArrayList<String>(); for (int i = 0; i < portList.port().size(); i++) { ports.add(portList.port(i).getText()); } // Initialize member variables netlist.ports = new HashMap<String, Port>(); netlist.nets = new HashMap<String, Net>(); netlist.modules = new HashMap<String, Module>(); netlist.orderedPorts = ports; List<Module_itemContext> x = module.module_item(); // parse ports parsePortList(module, netlist); // main parsing loop: // initially goes through the module items adding them to either // netDefs, modDefs, assignDefs or throwing a parsing exception ArrayList<Module_itemContext> netDefs = new ArrayList<Module_itemContext>(); ArrayList<Module_itemContext> modDefs = new ArrayList<Module_itemContext>(); ArrayList<Module_itemContext> assignDefs = new ArrayList<Module_itemContext>(); for (int i = 0; i < x.size(); i++) { Module_itemContext itemCon = x.get(i); if (itemCon.port_declaration() != null) { // port declaration parsePortDeclaration(filename, itemCon, netlist); continue; } Module_or_generate_itemContext modItem = itemCon.module_or_generate_item(); if (modItem != null) { if (modItem.gate_instantiation() != null) { fail(filename, ERR_MSG_12, itemCon); continue; } if (modItem.module_instantiation() != null) { modDefs.add(itemCon); continue; } Module_or_generate_item_declarationContext modItem2 = modItem.module_or_generate_item_declaration(); if (modItem2 != null) { Net_declarationContext netDec = modItem2.net_declaration(); if (netDec != null) { // net declaration Net_typeContext netType = netDec.net_type(); if (netType.getText().equals("wire")) { // net definition netDefs.add(itemCon); continue; } } else { fail(filename, ERR_MSG_6, itemCon); } } Continuous_assignContext conAssignItem = modItem.continuous_assign(); if (conAssignItem != null) { List<Net_assignmentContext> assignList = conAssignItem.list_of_net_assignments() .net_assignment(); for (Net_assignmentContext conAssign : assignList) { String lval = conAssign.net_lvalue().getText(); String rval = conAssign.expression().getText(); // boolean isEscapedL = lval.startsWith("\\"); boolean isEscapedR = rval.startsWith("\\"); boolean looksArrL = lval.contains(":"); boolean looksArrR = rval.contains(":"); boolean looksConcatL = lval.contains("{"); boolean nestedConcatR = (rval.indexOf("{") != rval.lastIndexOf("{")); // check lval if (looksArrL || looksConcatL) fail(filename, ERR_MSG_4, itemCon); // check rval if ((looksArrR || nestedConcatR) && !isEscapedR) fail(filename, ERR_MSG_4, itemCon); // item can be parsed: assignDefs.add(itemCon); } continue; } } // Unsupported grammar fail(filename, ERR_MSG_4, itemCon); } // now process netDefs then modDefs // order is important: nets must be populated before processing // modules for (Module_itemContext entry : netDefs) { parseNetDeclaration(filename, entry, netlist); } for (Module_itemContext entry : modDefs) { parseModuleInstantiation(filename, entry, netlist); } for (Module_itemContext entry : assignDefs) { parseAssignStatement(filename, entry, netlist); } checkAll(netlist); netlistArr.add(netlist); } return netlistArr; } private static void parsePortList(Module_declarationContext module, Netlist netlist) throws UnsupportedGrammerException { if (module.list_of_ports() == null) { fail(ERR_MSG_2); } List<PortContext> portList = module.list_of_ports().port(); if (portList.size() == 1 && "".equals(portList.get(0).getText())) { System.out.println("warning: empty port list"); return; } for (int i = 0; i < portList.size(); i++) { String name = portList.get(i).getText(); Port p = new Port(name, PinDirection.UNKONWN); if (netlist.ports.containsKey(name)) { String emsg = String.format(ERR_MSG_5, name); fail(emsg); } netlist.ports.put(name, p); netlist.nets.put(name, p); } } private static void parseAssignStatement(String filename, Module_itemContext itemCon, Netlist netlist) throws Exception { List<Net_assignmentContext> assignList = itemCon.module_or_generate_item().continuous_assign() .list_of_net_assignments().net_assignment(); for (Net_assignmentContext conAssign : assignList) { String lval = conAssign.net_lvalue().getText(); String rval = conAssign.expression().getText(); boolean isConcatR = rval.contains("{"); if (isConcatR) { int k1 = rval.indexOf("{"); int k2 = rval.indexOf("}"); String netNamesStr = rval.substring(k1 + 1, k2); String[] netNames = netNamesStr.split(","); int bitIndex = 0; for (String netName : netNames) { String wireModID = "WIRE_NG_INTERNAL_u" + netlist.modules.size(); Module m = new Module(wireModID, "WIRE_NG_INTERNAL"); netlist.modules.put(wireModID, m); // segment below in this for loop is from // processModulePinConnection (tokens == 1) m.connections.put("IN", new PinConnection(netName, 0, PinDirection.IN)); m.connections.put("OUT", new PinConnection(lval, bitIndex, PinDirection.OUT)); Net net = netlist.nets.get(netName); if (net == null) { // implicit net declaration netlist.nets.put(netName, new Net(netName)); } else { // check if bit 0 is in net range if (!netlist.nets.get(netName).inRange(0)) { String msg1_a = "net <%s> does not have bit <%d>"; String msg2 = String.format(msg1_a, netName, 0); fail(filename, msg2, itemCon); } } bitIndex += 1; } } else { String wireModID = "WIRE_NG_INTERNAL_u" + netlist.modules.size(); Module m = new Module(wireModID, "WIRE_NG_INTERNAL"); netlist.modules.put(wireModID, m); ParserRuleContext zpL = conAssign.net_lvalue(); ParserRuleContext zpR = conAssign.expression(); Port pIn = new Port("IN", PinDirection.IN); Port pOut = new Port("OUT", PinDirection.OUT); processModulePinConnection(filename, m, zpL, lval, itemCon, pOut, netlist); processModulePinConnection(filename, m, zpR, rval, itemCon, pIn, netlist); } } } private static void parseModuleInstantiation(String filename, Module_itemContext itemCon, Netlist netlist) throws Exception { Module_or_generate_itemContext modItem = itemCon.module_or_generate_item(); Module_instantiationContext modIns = modItem.module_instantiation(); String id = modIns.module_identifier().getText(); List<Module_instanceContext> instances = modIns.module_instance(); for (int j = 0; j < instances.size(); j++) { Module_instanceContext i = instances.get(j); Module m = new Module(); m.type = id; m.id = i.name_of_instance().getText(); ArrayList<Port> modulePorts = library1.get(id); if (modulePorts == null) { String msg2 = String.format(ERR_MSG_16, id); fail(filename, msg2, itemCon); } List_of_port_connectionsContext conList = i.list_of_port_connections(); List<Ordered_port_connectionContext> orderedCons = conList.ordered_port_connection(); List<Named_port_connectionContext> namedCons = conList.named_port_connection(); boolean ordered = orderedCons.size() > 0; int conCount = ordered ? orderedCons.size() : namedCons.size(); if (conCount > modulePorts.size()) { String strE = String.format( "module instantiation contains %d ports while only %d are defined in library", conCount, modulePorts.size()); fail(filename, strE, itemCon); } for (int k = 0; k < conCount; k++) { ExpressionContext expr; expr = ordered ? orderedCons.get(k).expression() : namedCons.get(k).expression(); List<TermContext> termList = expr.term(); if (termList.size() != 1) { fail(filename, ERR_MSG_4, itemCon); } TermContext z = termList.get(0); PrimaryContext zp = z.primary(); String port_con = ""; if (zp.hierarchical_identifier() != null) { port_con = zp.hierarchical_identifier().getText(); } else if (zp.number() != null) { port_con = zp.number().getText(); } else { fail("ERR_MSG_2"); } String port_id = ordered ? modulePorts.get(k).id : namedCons.get(k).port_identifier().getText(); // PinDirection dir = library1.getPort(id, port_id).direction; Port port = library1.getPort(id, port_id); processModulePinConnection(filename, m, zp, port_con, itemCon, port, netlist); } if (netlist.modules.containsKey(m.id)) { String msg = String.format(ERR_MSG_15, m.id); fail(filename, msg, itemCon); } netlist.modules.put(m.id, m); } } private static void parseNetDeclaration(String filename, Module_itemContext itemCon, Netlist netlist) throws UnsupportedGrammerException { Module_or_generate_itemContext modItem = itemCon.module_or_generate_item(); Module_or_generate_item_declarationContext modItem2 = modItem.module_or_generate_item_declaration(); Net_declarationContext netDec = modItem2.net_declaration(); RangeContext r = netDec.range(); int start = 0, end = 0; if (r != null) { ExpressionContext expMSB = r.msb_constant_expression().constant_expression().expression(); ExpressionContext expLSB = r.lsb_constant_expression().constant_expression().expression(); try { start = Integer.parseInt(expMSB.getText()); end = Integer.parseInt(expLSB.getText()); } catch (Exception e) { fail(filename, ERR_MSG_7, itemCon); } } List<Net_identifierContext> list = netDec.list_of_net_identifiers().net_identifier(); for (int j = 0; j < list.size(); j++) { String netName = list.get(j).getText(); if (netlist.nets.get(netName) != null) { fail(filename, ERR_MSG_8, itemCon); } else { Net net = new Net(netName); net.start = start; net.end = end; netlist.nets.put(netName, net); } } } private static void parsePortDeclaration(String filename, Module_itemContext itemCon, Netlist netlist) throws UnsupportedGrammerException { Port_declarationContext portDec = itemCon.port_declaration(); Input_declarationContext inp = portDec.input_declaration(); Output_declarationContext outp = portDec.output_declaration(); Inout_declarationContext inout = portDec.inout_declaration(); List<Port_identifierContext> portList = null; RangeContext r = null; PinDirection direction = PinDirection.UNKONWN; if (inp != null) { portList = inp.list_of_port_identifiers().port_identifier(); direction = PinDirection.IN; r = inp.range(); } else if (outp != null) { portList = outp.list_of_port_identifiers().port_identifier(); direction = PinDirection.OUT; r = outp.range(); } else if (inout != null) { portList = inout.list_of_port_identifiers().port_identifier(); direction = PinDirection.INOUT; r = inout.range(); // fail(ERR_MSG_14, itemCon); } for (int j = 0; j < portList.size(); j++) { Port_identifierContext portIdent = portList.get(j); String portName = portIdent.getText(); // now need to lookup this port in ArrayList ports Port p = netlist.ports.get(portName); if (p == null) { // port wasn't declared in module header String str = String.format(ERR_MSG_1, portName); fail(filename, str, itemCon); } p.direction = direction; if (r != null) { ExpressionContext expMSB = r.msb_constant_expression().constant_expression().expression(); ExpressionContext expLSB = r.lsb_constant_expression().constant_expression().expression(); try { p.start = Integer.parseInt(expMSB.getText()); p.end = Integer.parseInt(expLSB.getText()); } catch (Exception e) { fail(filename, ERR_MSG_7, itemCon); } } } } private static void processModulePinConnection(String filename, Module m, ParserRuleContext zp, String port_con, Module_itemContext itemCon, Port port, Netlist netlist) throws UnsupportedGrammerException { // this function does the following: // - adds a PinConnection to the `connections` set of Module `m` // - create any single-bit nets that the port connection references, and // adds them to netlist.nets // inputs: // filename : quoted when throwing parsing exceptions // m : Module object // zp : holds the tokens for the net to which the port is connected // port_id : id of module port to be connected // port_con : net to be connected to module // itemCon : context of module instantiation (needed when throwing // Exceptions) // dir : direction of pin int tokens = zp.stop.getTokenIndex() - zp.start.getTokenIndex() + 1; if (tokens == 1) { // identifier, e.g. x Net net = netlist.nets.get(port_con); if (net == null) { // implicit net declaration if (port.getCount() > 1) { // implicit net declaration with array ports is not // supported atm fail(filename, ERR_MSG_10, itemCon); } else { netlist.nets.put(port_con, new Net(port_con)); } } for (int bit : port.getBits()) { PinConnection pcon = new PinConnection(port_con, bit, port.direction); String pID = port.getCount() > 1 ? (port.id + "[" + bit + "]") : port.id; m.connections.put(pID, pcon); } } else if (tokens == 4 || tokens == 5) { // indexed identifier, e.g. x[1] int spaceBuffer = tokens == 5 ? 1 : 0; Token token2 = tokenStream.get(zp.start.getTokenIndex() + 1 + spaceBuffer); Token token3 = tokenStream.get(zp.start.getTokenIndex() + 2 + spaceBuffer); Token token4 = tokenStream.get(zp.start.getTokenIndex() + 3 + spaceBuffer); if (token2.getText().equals("[") && token4.getText().equals("]")) { port_con = zp.start.getText(); int pin = Integer.parseInt(token3.getText()); PinConnection pcon = new PinConnection(port_con, pin, port.direction); m.connections.put(port.id, pcon); // check if net port_con is explicitly declared if (!netlist.nets.containsKey(port_con)) { String msg2 = String.format(ERR_MSG_17, port_con); fail(filename, msg2, itemCon); } // check if bit is in net range if (!netlist.nets.get(port_con).inRange(pin)) { String msg1_a = "net <%s> does not have bit <%d>"; String msg2 = String.format(msg1_a, port_con, pin); fail(filename, msg2, itemCon); } } } else { fail(filename, ERR_MSG_13, itemCon); } } // checks private static void checkAll(Netlist netlist) throws Exception { checkPortDirections(netlist); checkPortsAndNets(netlist); } private static void checkPortDirections(Netlist netlist) throws UnsupportedGrammerException { // verify no ports have UNKNOWN direction for (Map.Entry<String, Port> entry : netlist.ports.entrySet()) { if (entry.getValue().direction == PinDirection.UNKONWN) { String msg = String.format(ERR_MSG_3, entry.getValue().id); fail(msg); } } } private static void checkPortsAndNets(Netlist netlist) throws UnsupportedGrammerException { // verify that port definitions match any existing net definitions for (Map.Entry<String, Port> entry : netlist.ports.entrySet()) { Port port = entry.getValue(); Net net = netlist.nets.get(port.id); if (net != null) { if (net.start != port.start || net.end != port.end) { String emsg = String.format(ERR_MSG_9, port.id, port.start, port.end, net.id, net.start, net.end); fail(emsg); } } } } // extract module dependencies public static void getDependencies(String verilogFile) throws IOException { // HashMap<String, HashSet<String>> result = new HashMap<String, // HashSet<String>>(); FileInputStream stream1 = new FileInputStream(verilogFile); ANTLRInputStream antlr = new ANTLRInputStream(stream1); // ANTLR parsing Verilog2001Lexer lexer1 = new Verilog2001Lexer(antlr); CommonTokenStream tokenStream = new CommonTokenStream(lexer1); Verilog2001Parser parser1 = new Verilog2001Parser(tokenStream); Source_textContext source = parser1.source_text(); List<DescriptionContext> modules = source.description(); int nModules = modules.size(); for (int j = 0; j < nModules; j++) { Module_declarationContext module = modules.get(j).module_declaration(); String design = module.module_identifier().getText(); for (Module_itemContext itemCon : module.module_item()) { Module_or_generate_itemContext modItem = itemCon.module_or_generate_item(); if (modItem != null) { Module_instantiationContext mi = modItem.module_instantiation(); if (mi != null) { String id = mi.module_identifier().getText(); System.out.printf("Found instance <%s> in <%s>\n", id, design); } } } } } }
package nl.yacht.lakesideresort.domain; import javax.persistence.*; import javax.validation.constraints.AssertTrue; import java.time.LocalDate; @Entity public class Booking { //variabelen @Id @GeneratedValue(strategy = GenerationType.AUTO) private long bookingnumber; @ManyToOne private Guest guest; @ManyToOne private Room room; private LocalDate startDate; private LocalDate endDate; @AssertTrue(message = "Start date must be before end date") public boolean datesAreValid(){ return startDate.isBefore(endDate); } public Booking() { //default constructor } public Booking(long bookingnumber, Guest guest, Room room, LocalDate startDate, LocalDate endDate) { this.bookingnumber = bookingnumber; this.guest = guest; this.room = room; this.startDate = startDate; this.endDate = endDate; } public Booking(long bookingnumber) { this.bookingnumber = bookingnumber; } public Booking(Guest guest, Room room, LocalDate startDate, LocalDate endDate) { this.guest = guest; this.room = room; this.startDate = startDate; this.endDate = endDate; } public long getBookingnumber() { return bookingnumber; } public void setBookingnumber(long bookingnumber) { this.bookingnumber = bookingnumber; } public Guest getGuest() { return guest; } public void setGuest(Guest guest) { this.guest = guest; } public Room getRoom() { return room; } public void setRoom(Room room) { this.room = room; } public LocalDate getStartDate() { return startDate; } public void setStartDate(LocalDate startDate) { this.startDate = startDate; } public void setStartDate(String startDate) { this.startDate = LocalDate.parse(startDate); } public LocalDate getEndDate() { return endDate; } public void setEndDate(LocalDate endDate) { this.endDate = endDate; } public void setEndDate(String endDate) { this.endDate = LocalDate.parse(endDate); } public boolean isBetween(LocalDate date) { return (date.isEqual(startDate) || date.isAfter(startDate)) && (date.isEqual(endDate) || date.isBefore(endDate)); } }
package openblocks.common.item; import java.util.List; import net.minecraft.block.Block; import net.minecraft.client.model.ModelBiped; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.monster.EntityMob; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayer.EnumStatus; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.Item; import net.minecraft.item.ItemArmor; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.play.server.S0APacketUseBed; import net.minecraft.util.*; import net.minecraft.world.World; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.util.Constants; import net.minecraftforge.event.entity.player.PlayerSleepInBedEvent; import openblocks.OpenBlocks; import openblocks.client.model.ModelSleepingBag; import openmods.reflection.FieldAccess; import openmods.utils.BlockUtils; import openmods.utils.ItemUtils; import openmods.utils.TagUtils; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class ItemSleepingBag extends ItemArmor { private static final String TAG_SPAWN = "Spawn"; private static final String TAG_POSITION = "Position"; private static final String TAG_SLEEPING = "Sleeping"; private static final String TAG_SLOT = "Slot"; private static final int ARMOR_CHESTPIECE_TYPE = 1; private static final int ARMOR_CHESTPIECE_SLOT = 2; private static final FieldAccess<Boolean> IS_SLEEPING = FieldAccess.create(EntityPlayer.class, "sleeping", "field_71083_bS"); private static final FieldAccess<Integer> SLEEPING_TIMER = FieldAccess.create(EntityPlayer.class, "sleepTimer", "field_71076_b"); public static final String TEXTURE_SLEEPINGBAG = "openblocks:textures/models/sleepingbag.png"; public ItemSleepingBag() { super(ArmorMaterial.IRON, 2, ARMOR_CHESTPIECE_TYPE); setCreativeTab(OpenBlocks.tabOpenBlocks); } @Override public String getArmorTexture(ItemStack stack, Entity entity, int slot, String type) { return TEXTURE_SLEEPINGBAG; } @Override @SideOnly(Side.CLIENT) public void registerIcons(IIconRegister registry) { itemIcon = registry.registerIcon("openblocks:sleepingbag"); } @Override @SideOnly(Side.CLIENT) public ModelBiped getArmorModel(EntityLivingBase entityLiving, ItemStack itemStack, int armorSlot) { return armorSlot == ARMOR_CHESTPIECE_TYPE? ModelSleepingBag.instance : null; } @Override public ItemStack onItemRightClick(ItemStack sleepingBagStack, World world, EntityPlayer player) { if (!world.isRemote) { ItemStack currentArmor = getChestpieceSlot(player); if (currentArmor != null) currentArmor = currentArmor.copy(); final ItemStack sleepingBagCopy = sleepingBagStack.copy(); NBTTagCompound tag = ItemUtils.getItemTag(sleepingBagCopy); tag.setInteger(TAG_SLOT, player.inventory.currentItem); setChestpieceSlot(player, sleepingBagCopy); if (currentArmor != null) return currentArmor; sleepingBagStack.stackSize = 0; } return sleepingBagStack; } @Override public boolean isValidArmor(ItemStack stack, int armorType, Entity entity) { return armorType == ARMOR_CHESTPIECE_TYPE; } @Override public void onArmorTick(World world, EntityPlayer player, ItemStack itemStack) { if (!(player instanceof EntityPlayerMP)) return; if (player.isPlayerSleeping()) return; NBTTagCompound tag = ItemUtils.getItemTag(itemStack); if (tag.getBoolean(TAG_SLEEPING)) { // player just woke up restoreOriginalSpawn(player, tag); restoreOriginalPosition(player, tag); tag.removeTag(TAG_SLEEPING); getOutOfSleepingBag(player); } else { // player just put in on final int posX = MathHelper.floor_double(player.posX); final int posY = MathHelper.floor_double(player.posY); final int posZ = MathHelper.floor_double(player.posZ); if (canPlayerSleep(player, world, posX, posY, posZ)) { storeOriginalSpawn(player, tag); storeOriginalPosition(player, tag); tag.setBoolean(TAG_SLEEPING, true); sleepSafe((EntityPlayerMP)player, world, posX, posY, posZ); } else getOutOfSleepingBag(player); } } private static EntityPlayer.EnumStatus sleepSafe(EntityPlayerMP player, World world, int x, int y, int z) { if (player.isRiding()) player.mountEntity(null); IS_SLEEPING.set(player, true); SLEEPING_TIMER.set(player, 0); player.playerLocation = new ChunkCoordinates(x, y, z); player.motionX = player.motionZ = player.motionY = 0.0D; world.updateAllPlayersSleepingFlag(); S0APacketUseBed sleepPacket = new S0APacketUseBed(player, x, y, z); player.getServerForPlayer().getEntityTracker().func_151247_a(player, sleepPacket); player.playerNetServerHandler.sendPacket(sleepPacket); return EntityPlayer.EnumStatus.OK; } private static EnumStatus vanillaCanSleep(EntityPlayer player, World world, int x, int y, int z) { PlayerSleepInBedEvent event = new PlayerSleepInBedEvent(player, x, y, z); MinecraftForge.EVENT_BUS.post(event); if (event.result != null) return event.result; if (player.isPlayerSleeping() || !player.isEntityAlive()) return EntityPlayer.EnumStatus.OTHER_PROBLEM; if (!world.provider.isSurfaceWorld()) return EntityPlayer.EnumStatus.NOT_POSSIBLE_HERE; if (world.isDaytime()) return EntityPlayer.EnumStatus.NOT_POSSIBLE_NOW; List<?> list = world.getEntitiesWithinAABB(EntityMob.class, AxisAlignedBB.getBoundingBox(x - 8, y - 5, z - 8, x + 8, y + 5, z + 8)); if (!list.isEmpty()) return EntityPlayer.EnumStatus.NOT_SAFE; return EntityPlayer.EnumStatus.OK; } private static boolean canPlayerSleep(EntityPlayer player, World world, int x, int y, int z) { if (!world.isAirBlock(x, y, z) || !checkGroundCollision(world, x, y - 1, z)) { player.addChatComponentMessage(new ChatComponentTranslation("openblocks.misc.oh_no_ground")); return false; } EnumStatus status = vanillaCanSleep(player, world, x, y, z); if (status == EnumStatus.OK) return true; switch (status) { case NOT_POSSIBLE_NOW: player.addChatComponentMessage(new ChatComponentTranslation("tile.bed.noSleep")); break; case NOT_SAFE: player.addChatComponentMessage(new ChatComponentTranslation("tile.bed.notSafe")); break; default: break; } return false; } private static boolean checkGroundCollision(World world, int x, int y, int z) { Block block = world.getBlock(x, y, z); AxisAlignedBB aabb = block.getCollisionBoundingBoxFromPool(world, x, y, z); if (aabb == null) return true; double dx = aabb.maxX - aabb.minX; double dy = aabb.maxY - aabb.minY; double dz = aabb.maxZ - aabb.minZ; return (dx >= 0.5) && (dy >= 0.5) && (dz >= 0.5); } private static boolean isChestplate(ItemStack stack) { if (stack == null) return false; Item item = stack.getItem(); if (item instanceof ItemSleepingBag) return false; if (item instanceof ItemArmor) { ItemArmor armorItem = (ItemArmor)item; return armorItem.armorType == ARMOR_CHESTPIECE_TYPE; } return false; } private static Integer getReturnSlot(NBTTagCompound tag) { if (tag.hasKey(TAG_SLOT, Constants.NBT.TAG_ANY_NUMERIC)) { int slot = tag.getInteger(TAG_SLOT); if (slot < 9 && slot >= 0) return slot; } return null; } private static boolean tryReturnToSlot(EntityPlayer player, ItemStack sleepingBag) { NBTTagCompound tag = ItemUtils.getItemTag(sleepingBag); final Integer returnSlot = getReturnSlot(tag); tag.removeTag(TAG_SLOT); if (returnSlot == null) { setChestpieceSlot(player, null); return false; } final ItemStack possiblyArmor = player.inventory.mainInventory[returnSlot]; if (isChestplate(possiblyArmor)) { setChestpieceSlot(player, possiblyArmor); } else { setChestpieceSlot(player, null); if (possiblyArmor != null) return false; } player.inventory.setInventorySlotContents(returnSlot, sleepingBag); return true; } private static void getOutOfSleepingBag(EntityPlayer player) { ItemStack stack = getChestpieceSlot(player); if (isSleepingBag(stack)) { if (!tryReturnToSlot(player, stack)) { if (!player.inventory.addItemStackToInventory(stack)) { BlockUtils.dropItemStackInWorld(player.worldObj, player.posX, player.posY, player.posZ, stack); } } } } private static void storeOriginalSpawn(EntityPlayer player, NBTTagCompound tag) { ChunkCoordinates spawn = player.getBedLocation(player.worldObj.provider.dimensionId); if (spawn != null) tag.setTag(TAG_SPAWN, TagUtils.store(spawn)); } private static void restoreOriginalSpawn(EntityPlayer player, NBTTagCompound tag) { if (tag.hasKey(TAG_SPAWN)) { ChunkCoordinates coords = TagUtils.readCoord(tag.getCompoundTag(TAG_SPAWN)).asChunkCoordinate(); player.setSpawnChunk(coords, false, player.worldObj.provider.dimensionId); tag.removeTag(TAG_SPAWN); } } private static void storeOriginalPosition(Entity e, NBTTagCompound tag) { tag.setTag(TAG_POSITION, TagUtils.store(e.posX, e.posY, e.posZ)); } private static void restoreOriginalPosition(Entity e, NBTTagCompound tag) { if (tag.hasKey(TAG_POSITION)) { Vec3 position = TagUtils.readVec(tag.getCompoundTag(TAG_POSITION)); e.setPosition(position.xCoord, position.yCoord, position.zCoord); tag.removeTag(TAG_POSITION); } } public static boolean isWearingSleepingBag(EntityPlayer player) { ItemStack armor = getChestpieceSlot(player); return isSleepingBag(armor); } private static boolean isSleepingBag(ItemStack armor) { return armor != null && armor.getItem() instanceof ItemSleepingBag; } private static ItemStack setChestpieceSlot(EntityPlayer player, ItemStack chestpiece) { return player.inventory.armorInventory[ARMOR_CHESTPIECE_SLOT] = chestpiece; } private static ItemStack getChestpieceSlot(EntityPlayer player) { return player.inventory.armorInventory[ARMOR_CHESTPIECE_SLOT]; } }
package org.dynmap.kzedmap; import java.awt.Color; import java.awt.image.BufferedImage; import java.awt.image.WritableRaster; import java.io.File; import java.io.IOException; import java.util.Map; import javax.imageio.ImageIO; import org.bukkit.World; import org.dynmap.debug.Debug; public class DefaultTileRenderer implements MapTileRenderer { protected static Color translucent = new Color(0, 0, 0, 0); private String name; protected int maximumHeight = 127; @Override public String getName() { return name; } public DefaultTileRenderer(Map<String, Object> configuration) { name = (String) configuration.get("prefix"); Object o = configuration.get("maximumheight"); if (o != null) { maximumHeight = Integer.parseInt(String.valueOf(o)); if (maximumHeight > 127) maximumHeight = 127; } } public boolean render(KzedMapTile tile, File outputFile) { World world = tile.getWorld(); BufferedImage im = new BufferedImage(KzedMap.tileWidth, KzedMap.tileHeight, BufferedImage.TYPE_INT_RGB); WritableRaster r = im.getRaster(); boolean isempty = true; int ix = KzedMap.anchorx + tile.px / 2 + tile.py / 2 - ((127-maximumHeight)/2); int iy = maximumHeight; int iz = KzedMap.anchorz + tile.px / 2 - tile.py / 2 + ((127-maximumHeight)/2); int jx, jz; int x, y; /* draw the map */ for (y = 0; y < KzedMap.tileHeight;) { jx = ix; jz = iz; for (x = KzedMap.tileWidth - 1; x >= 0; x -= 2) { Color c1 = scan(world, jx, iy, jz, 0); Color c2 = scan(world, jx, iy, jz, 2); isempty = isempty && c1 == translucent && c2 == translucent; r.setPixel(x, y, new int[] { c1.getRed(), c1.getGreen(), c1.getBlue() }); r.setPixel(x - 1, y, new int[] { c2.getRed(), c2.getGreen(), c2.getBlue() }); jx++; jz++; } y++; jx = ix; jz = iz - 1; for (x = KzedMap.tileWidth - 1; x >= 0; x -= 2) { Color c1 = scan(world, jx, iy, jz, 2); jx++; jz++; Color c2 = scan(world, jx, iy, jz, 0); isempty = isempty && c1 == translucent && c2 == translucent; r.setPixel(x, y, new int[] { c1.getRed(), c1.getGreen(), c1.getBlue() }); r.setPixel(x - 1, y, new int[] { c2.getRed(), c2.getGreen(), c2.getBlue() }); } y++; ix++; iz } /* save the generated tile */ saveImage(im, outputFile); im.flush(); tile.file = outputFile; ((KzedMap) tile.getMap()).invalidateTile(new KzedZoomedMapTile(world, (KzedMap) tile.getMap(), tile)); return !isempty; } protected Color scan(World world, int x, int y, int z, int seq) { for (;;) { if (y < 0) return translucent; int id = world.getBlockTypeIdAt(x, y, z); switch (seq) { case 0: x break; case 1: y break; case 2: z++; break; case 3: y break; } seq = (seq + 1) & 3; if (id != 0) { Color[] colors = KzedMap.colors.get(id); if (colors != null) { Color c = colors[seq]; if (c.getAlpha() > 0) { /* we found something that isn't transparent! */ if (c.getAlpha() == 255) { /* it's opaque - the ray ends here */ return c; } /* this block is transparent, so recurse */ Color bg = scan(world, x, y, z, seq); int cr = c.getRed(); int cg = c.getGreen(); int cb = c.getBlue(); int ca = c.getAlpha(); cr *= ca; cg *= ca; cb *= ca; int na = 255 - ca; return new Color((bg.getRed() * na + cr) >> 8, (bg.getGreen() * na + cg) >> 8, (bg.getBlue() * na + cb) >> 8); } } } } } /* save rendered tile, update zoom-out tile */ public void saveImage(BufferedImage im, File outputFile) { Debug.debug("saving image " + outputFile.getPath()); /* save image */ try { ImageIO.write(im, "png", outputFile); } catch (IOException e) { Debug.error("Failed to save image: " + outputFile.getPath(), e); } catch (java.lang.NullPointerException e) { Debug.error("Failed to save image (NullPointerException): " + outputFile.getPath(), e); } } }
package org.formula.binding; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import org.formula.annotation.Form; import org.formula.annotation.FormField; import org.formula.converter.Converter; import org.formula.event.FormCommitValidationEvent; import org.formula.event.FormCommittedEvent; import org.formula.event.FormEditValidationEvent; import org.formula.event.FormEnableEvent; import org.formula.event.FormEnableListener; import org.formula.event.FormEvent; import org.formula.event.FormFieldFocusGainedEvent; import org.formula.event.FormFieldFocusLostEvent; import org.formula.event.FormFieldListener; import org.formula.event.FormInitializedEvent; import org.formula.event.FormListener; import org.formula.event.FormPropertyEditedEvent; import org.formula.event.FormRefreshedEvent; import org.formula.event.FormRolledBackEvent; import org.formula.event.FormValidationListener; import org.formula.validation.ConfirmationHandler; import org.formula.validation.FieldValidator; import org.formula.validation.ValidationResult; import org.formula.validation.Validator; import org.minimalcode.beans.ObjectWrapper; public abstract class AbstractFormBinder implements FormBinder, PropertyChangeListener { private final Set<FormListener> formListeners = new HashSet<FormListener>(); private final Set<FormFieldListener> formFieldListeners = new HashSet<FormFieldListener>(); private final Set<FormValidationListener> formValidationListeners = new HashSet<FormValidationListener>(); private final Set<FormEnableListener> formEnableListeners = new HashSet<FormEnableListener>(); private final PropertyMap propertyMap = new PropertyMap(); private final Map<String, Converter> converters = new HashMap<String, Converter>(); private final Map<String, Set<FormFieldBinding>> formFieldBindings = new HashMap<String, Set<FormFieldBinding>>(); private final Map<String, Integer> indexMap = new HashMap<String, Integer>(); private Object form; private Object model; private Map<Object, ObjectWrapper> objectWrappers = new HashMap<Object, ObjectWrapper>(); private Validator validator; private ConfirmationHandler confirmationHandler; private boolean initialized = false; public AbstractFormBinder() { } public AbstractFormBinder(Object form) { setForm(form); } @Override public Object getProperty(String property) { return this.propertyMap.get(property); } @Override public Object getProperty(String property, int index) { property = property.replaceFirst("#", "#" + index); return getProperty(property); } @Override public void setProperty(String property, Object value) { this.propertyMap.put(property, value); } @Override public void setProperty(String property, Object value, int index) { property = property.replaceFirst("#", "#" + index); setProperty(property, value); } @Override public void enableProperty(String property, boolean enable) { Set<FormFieldBinding> formFieldBindings = this.formFieldBindings.get(property); if (formFieldBindings != null) { for (FormFieldBinding formFieldBinding : formFieldBindings) { formFieldBinding.enable(enable); } } } @Override public void enableProperty(String property, boolean enable, int index) { property = property.replaceFirst("#", "#" + index); enableProperty(property, enable); } @Override public void focusProperty(String property) { Set<FormFieldBinding> formFieldBindings = this.formFieldBindings.get(property); if (formFieldBindings != null) { for (FormFieldBinding formFieldBinding : formFieldBindings) { formFieldBinding.focus(); } } } @Override public void focusProperty(String property, int index) { property = property.replaceFirst("#", "#" + index); focusProperty(property); } @Override public void showProperty(String property, boolean visible) { Set<FormFieldBinding> formFieldBindings = this.formFieldBindings.get(property); if (formFieldBindings != null) { for (FormFieldBinding formFieldBinding : formFieldBindings) { formFieldBinding.show(visible); } } } @Override public void showProperty(String property, boolean visible, int index) { property = property.replaceFirst("#", "#" + index); showProperty(property, visible); } protected Object getForm() { return this.form; } @Override public void setForm(Object form) { if (!form.getClass().isAnnotationPresent(Form.class)) { throw new BindingException(form.getClass().getName() + " does not have a @Form annotation."); } else if (this.form != null) { throw new BindingException("FormBinder " + getClass().getName() + " is already bound to form " + this.form.getClass().getName() + "."); } this.form = form; propertyMap.addPropertyChangeListener(this); bindForm(); if (this.model != null) { this.initialized = false; init(); validate(); } } protected Object getModel() { return model; } @Override public void setModel(Object model) { this.initialized = false; this.objectWrappers.clear(); this.model = model; if (!(model instanceof Map)) { this.objectWrappers.put(model, new ObjectWrapper(model)); for (String key : this.propertyMap.keySet()) { Matcher matcher = FormBinder.INDEXDED_PROPERTY_KEY_PATTERN.matcher(key); if (matcher.matches()) { String indexKey = matcher.group(2); int index = Integer.valueOf(matcher.group(3)); Object indexedModel = getIndexedValueAt(indexKey, index, getModel()); this.objectWrappers.put(indexedModel, new ObjectWrapper(indexedModel)); } } } init(); validate(); } @Override public void refresh() { read(); fireFormEvent(new FormRefreshedEvent(this)); } public Validator getValidator() { return validator; } public void setValidator(Validator validator) { this.validator = validator; } public ConfirmationHandler getConfirmationHandler() { return confirmationHandler; } public void setConfirmationHandler(ConfirmationHandler confirmationHandler) { this.confirmationHandler = confirmationHandler; } protected void addConverter(String property, Converter converter) { this.converters.put(property, converter); } protected Set<FormBinding> bindForm() { Form formAnnotation = this.form.getClass().getAnnotation(Form.class); Class validatorClass = formAnnotation.validator(); try { Validator validator = (Validator) validatorClass.newInstance(); setValidator(validator); } catch (Exception e) { throw new BindingException(e.getClass().getName() + " when creating validator " + validatorClass.getName() + ".", e); } Set<FormBinding> formBindings = bindFormFields(); validator.setView(this.form); validator.setFormBindings(formBindings); return formBindings; } protected abstract Set<FormBinding> bindFormFields(); protected FormFieldBinding bindFormField(Field field, Object container) { try { field.setAccessible(true); Object formField = field.get(container); FormField formFieldAnnotation = field.getAnnotation(FormField.class); String property = formFieldAnnotation.property(); if (property.contains(" int index = 0; String key = container.getClass() + ";" + property; if (!this.indexMap.containsKey(key)) { indexMap.put(key, 0); } else { index = indexMap.get(key) + 1; indexMap.put(key, index); } property = property.replace("#", "#" + String.valueOf(index)); } boolean required = formFieldAnnotation.required(); boolean errorIndicator = formFieldAnnotation.errorIndicator(); Converter converter = null; Class converterClass = formFieldAnnotation.converter(); try { converter = (Converter) converterClass.newInstance(); if (!property.isEmpty()) { addConverter(property, converter); } } catch (Exception e) { throw new BindingException(e.getClass().getName() + " when creating converter " + converterClass.getName() + ".", e); } String[] labelProperties = formFieldAnnotation.labelProperties(); String optionsProperty = formFieldAnnotation.optionsProperty(); String maxProperty = formFieldAnnotation.maxProperty(); FormFieldBinding formFieldBinding = bindFormField(formField, property, labelProperties, optionsProperty, maxProperty, required, errorIndicator, converter); Class validatorClass = formFieldAnnotation.validator(); try { FieldValidator fieldValidator = (FieldValidator) validatorClass.newInstance(); fieldValidator.setFormFieldBinding(formFieldBinding); getValidator().addFieldValidator(fieldValidator); } catch (Exception e) { throw new BindingException(e.getClass().getName() + " when creating validator " + validatorClass.getName() + ".", e); } Set<FormFieldBinding> formFieldBindingSet = this.formFieldBindings.get(property); if (formFieldBindingSet == null) { formFieldBindingSet = new HashSet<FormFieldBinding>(); this.formFieldBindings.put(property, formFieldBindingSet); } formFieldBindingSet.add(formFieldBinding); for (String labelProperty : labelProperties) { formFieldBindingSet = this.formFieldBindings.get(labelProperty); if (formFieldBindingSet == null) { formFieldBindingSet = new HashSet<FormFieldBinding>(); this.formFieldBindings.put(labelProperty, formFieldBindingSet); } formFieldBindingSet.add(formFieldBinding); } return formFieldBinding; } catch (IllegalAccessException e) { throw new BindingException(e.getClass().getName() + " when creating binding for field " + field + ".", e); } } protected abstract FormFieldBinding bindFormField(Object formField, String property, String[] labelProperties, String optionsProperty, String maxProperty, boolean required, boolean errorIndicator, Converter converter); @Override public void propertyChange(PropertyChangeEvent e) { fireFormEvent(new FormPropertyEditedEvent(this, e.getPropertyName(), e.getOldValue(), e.getNewValue())); if (this.initialized) { ValidationResult validationResult = validate(); if (validationResult != null) { fireFormValidationEvent(new FormEditValidationEvent(this, validationResult)); } } } protected void init() { read(); this.initialized = true; fireFormEvent(new FormInitializedEvent(this)); } protected ValidationResult validate() { if (this.initialized && getValidator() != null) { ValidationResult validationResult = getValidator().validate(this.propertyMap); return validationResult; } else { return null; } } @Override public void commit() { commit(this); } @Override public void commit(Object source) { ValidationResult validationResult = validate(); fireFormValidationEvent(new FormCommitValidationEvent(this, validationResult)); if (!validationResult.hasErrors() && (this.confirmationHandler == null || this.confirmationHandler.confirmCommit(this.propertyMap))) { write(); fireFormEvent(new FormCommittedEvent(source)); } } @Override public void rollback() { read(); fireFormEvent(new FormRolledBackEvent(this)); } @Override public void enable(boolean enable, boolean requestFocus) { fireFormEnableEvent(new FormEnableEvent(this, enable, requestFocus)); } @Override public synchronized void addFormListener(FormListener listener) { if (listener != null) { this.formListeners.add(listener); } } @Override public synchronized void removeFormListener(FormListener listener) { if (listener != null) { this.formListeners.remove(listener); } } @Override public synchronized void addFormFieldListener(FormFieldListener listener) { if (listener != null) { this.formFieldListeners.add(listener); } } @Override public synchronized void removeFormFieldListener(FormFieldListener listener) { if (listener != null) { this.formFieldListeners.remove(listener); } } @Override public synchronized void addFormValidationListener(FormValidationListener listener) { if (listener != null) { this.formValidationListeners.add(listener); } } @Override public synchronized void removeFormValidationListener(FormValidationListener listener) { if (listener != null) { this.formValidationListeners.remove(listener); } } @Override public synchronized void addFormEnableListener(FormEnableListener listener) { if (listener != null) { this.formEnableListeners.add(listener); } } @Override public synchronized void removeFormEnableListener(FormEnableListener listener) { if (listener != null) { this.formEnableListeners.remove(listener); } } protected void fireFormEvent(FormEvent e) { ArrayList<Object> listeners = new ArrayList<Object>(formListeners); // We want to formbindings like for example the commit button binding to do their things // before anything the application does. Collections.sort(listeners, new Comparator<Object>() { public int compare(Object listener1, Object listener2) { if (listener1 instanceof FormBinding && !(listener2 instanceof FormBinding)) { return -1; } else if (listener2 instanceof FormBinding && !(listener1 instanceof FormBinding)) { return 1; } return 0; } }); for (Object listener : listeners) { FormListener formListener = (FormListener) listener; if (e instanceof FormPropertyEditedEvent) { if (this.initialized) { formListener.formPropertyEdited((FormPropertyEditedEvent) e); } } else if (e instanceof FormInitializedEvent) { formListener.formInitialized((FormInitializedEvent) e); } else if (e instanceof FormRefreshedEvent) { formListener.formRefreshed((FormRefreshedEvent) e); } else if (e instanceof FormCommittedEvent) { formListener.formCommitted((FormCommittedEvent) e); } else if (e instanceof FormRolledBackEvent) { formListener.formRolledBack((FormRolledBackEvent) e); } } } protected void fireFormFieldEvent(FormEvent e) { Object[] listeners = formFieldListeners.toArray(); for (Object listener : listeners) { FormFieldListener formFieldListener = (FormFieldListener) listener; if (e instanceof FormFieldFocusGainedEvent) { formFieldListener.formFieldFocusGained((FormFieldFocusGainedEvent) e); } else if (e instanceof FormFieldFocusLostEvent) { formFieldListener.formFieldFocusLost((FormFieldFocusLostEvent) e); } } } protected void fireFormValidationEvent(FormEvent e) { Object[] listeners = formValidationListeners.toArray(); for (Object listener : listeners) { FormValidationListener formValidationListener = (FormValidationListener) listener; if (e instanceof FormEditValidationEvent) { formValidationListener.formEditValidation((FormEditValidationEvent) e); } else if (e instanceof FormCommitValidationEvent) { formValidationListener.formCommitValidation((FormCommitValidationEvent) e); } } } protected void fireFormEnableEvent(FormEvent e) { Object[] listeners = formEnableListeners.toArray(); for (Object listener : listeners) { FormEnableListener formEnableListener = (FormEnableListener) listener; if (e instanceof FormEnableEvent) { formEnableListener.formEnable((FormEnableEvent) e); } } } protected PropertyMap getPropertyMap() { return propertyMap; } @SuppressWarnings("unchecked") private void read() { for (String key : this.propertyMap.keySet()) { Object value = null; if (getModel() instanceof Map) { Map modelMap = (Map) getModel(); value = modelMap.get(key); } else { Matcher matcher = FormBinder.INDEXDED_PROPERTY_KEY_PATTERN.matcher(key); if (matcher.matches()) { String indexKey = matcher.group(2); int index = Integer.valueOf(matcher.group(3)); String property = matcher.group(4); value = getIndexedValueAt(indexKey, index, getModel()); value = this.objectWrappers.get(value).getValue(property); } else { value = this.objectWrappers.get(getModel()).getValue(key); } } if (value instanceof List) { // This is most likely an optionsProperty. If not then someone's done something wrong somewhere. ArrayList<?> list = new ArrayList(); list.addAll((List) value); value = list; } this.propertyMap.put(key, value); } } @SuppressWarnings("unchecked") private void write() { for (String key : this.propertyMap.keySet()) { Object value = this.propertyMap.get(key); if (getModel() instanceof Map) { Map modelMap = (Map) model; modelMap.put(key, value); } else { Matcher matcher = FormBinder.INDEXDED_PROPERTY_KEY_PATTERN.matcher(key); if (matcher.matches()) { String indexKey = matcher.group(2); int index = Integer.valueOf(matcher.group(3)); String property = matcher.group(4); Object indexedModel = getIndexedValueAt(indexKey, index, getModel()); if (this.objectWrappers.get(indexedModel).getProperty(property).isWritable()) { this.objectWrappers.get(indexedModel).setValue(property, value); } } else { if (this.objectWrappers.get(getModel()).getProperty(key).isWritable()) { this.objectWrappers.get(getModel()).setValue(key, value); } } } } } private Object getIndexedValueAt(String key, int index, Object model) { Object value = null; if (key == null || key.isEmpty()) { if (model instanceof Iterator) { Iterator iterator = ((Iterable) model).iterator(); for (int i = 0; i <= index; ++i) { value = iterator.next(); } } else { throw new BindingException(getClass().getName() + " expected the model to be an iterable but it was " + model.getClass().getName() + "."); } } else { value = new ObjectWrapper(model).getIndexedValue(key, index); } return value; } }
package org.lightmare.jpa.jta; import java.io.IOException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import javax.ejb.EJBException; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.ejb.TransactionManagementType; import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; import javax.transaction.HeuristicMixedException; import javax.transaction.HeuristicRollbackException; import javax.transaction.RollbackException; import javax.transaction.SystemException; import javax.transaction.UserTransaction; import org.hibernate.cfg.NotYetImplementedException; import org.lightmare.cache.MetaData; import org.lightmare.cache.TransactionHolder; import org.lightmare.ejb.handlers.BeanHandler; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.ObjectUtils; /** * Class to manage {@link javax.transaction.UserTransaction} for * {@link javax.ejb.Stateless} bean {@link java.lang.reflect.Proxy} calls * * @author levan * */ public class BeanTransactions { private static final String MANDATORY_ERROR = "TransactionAttributeType.MANDATORY must always be called within transaction"; private static final String NEVER_ERROR = "TransactionAttributeType.NEVER is called within transaction"; private static final String SUPPORTS_ERROR = "TransactionAttributeType.SUPPORTS is not yet implemented"; /** * Inner class to cache {@link EntityTransaction}s and {@link EntityManager} * s in one {@link Collection} for {@link UserTransaction} implementation * * @author levan * */ private static class TransactionData { EntityManager em; EntityTransaction entityTransaction; } private static TransactionData createTransactionData( EntityTransaction entityTransaction, EntityManager em) { TransactionData transactionData = new TransactionData(); transactionData.em = em; transactionData.entityTransaction = entityTransaction; return transactionData; } /** * Gets existing transaction from cache * * @param entityTransactions * @return {@link UserTransaction} */ public static UserTransaction getTransaction( EntityTransaction... entityTransactions) { UserTransaction transaction = TransactionHolder.getTransaction(); if (transaction == null) { transaction = UserTransactionFactory.get(entityTransactions); TransactionHolder.setTransaction(transaction); } else { // If entityTransactions array is available then adds it to // UserTransaction object UserTransactionFactory.join(transaction, entityTransactions); } return transaction; } /** * Gets existing transaction from cache * * @param entityTransactions * @return {@link UserTransaction} */ public static UserTransaction getTransaction(Collection<EntityManager> ems) { UserTransaction transaction = TransactionHolder.getTransaction(); if (transaction == null) { transaction = UserTransactionFactory.get(); TransactionHolder.setTransaction(transaction); } Collection<TransactionData> entityTransactions = getEntityTransactions(ems); addEntityTransactions((UserTransactionImpl) transaction, entityTransactions); return transaction; } /** * Gets appropriated {@link TransactionAttributeType} for instant * {@link Method} of {@link javax.ejb.Stateless} bean * * @param metaData * @param method * @return {@link TransactionAttributeType} */ public static TransactionAttributeType getTransactionType( MetaData metaData, Method method) { TransactionAttributeType type; if (method == null) { type = null; } else { TransactionAttributeType attrType = metaData .getTransactionAttrType(); TransactionManagementType manType = metaData .getTransactionManType(); TransactionAttribute attr = method .getAnnotation(TransactionAttribute.class); if (manType.equals(TransactionManagementType.CONTAINER)) { if (attr == null) { type = attrType; } else { type = attr.value(); } } else { type = null; } } return type; } /** * Gets status of passed transaction by {@link UserTransaction#getStatus()} * method call * * @param transaction * @return <code>int</code> * @throws IOException */ private static int getStatus(UserTransaction transaction) throws IOException { int status; try { status = transaction.getStatus(); } catch (SystemException ex) { throw new IOException(ex); } return status; } /** * Checks if transaction is active and if it is not vegins transaction * * @param entityTransaction */ private static void beginEntityTransaction( EntityTransaction entityTransaction) { if (ObjectUtils.notTrue(entityTransaction.isActive())) { entityTransaction.begin(); } } private static EntityTransaction getEntityTransaction(EntityManager em) { EntityTransaction entityTransaction; if (em == null) { entityTransaction = null; } else { entityTransaction = em.getTransaction(); beginEntityTransaction(entityTransaction); } return entityTransaction; } private static Collection<TransactionData> getEntityTransactions( Collection<EntityManager> ems) { Collection<TransactionData> entityTransactions; if (CollectionUtils.valid(ems)) { entityTransactions = new ArrayList<TransactionData>(); for (EntityManager em : ems) { EntityTransaction entityTransaction = getEntityTransaction(em); TransactionData transactionData = createTransactionData( entityTransaction, em); entityTransactions.add(transactionData); } } else { entityTransactions = null; } return entityTransactions; } private static void addEntityTransaction(UserTransactionImpl transaction, EntityTransaction entityTransaction, EntityManager em) { if (ObjectUtils.notNull(entityTransaction)) { transaction.addTransaction(entityTransaction); } if (ObjectUtils.notNull(em)) { transaction.addEntityManager(em); } } private static void addEntityTransactions(UserTransactionImpl transaction, Collection<TransactionData> entityTransactions) { if (CollectionUtils.valid(entityTransactions)) { for (TransactionData transactionData : entityTransactions) { addEntityTransaction(transaction, transactionData.entityTransaction, transactionData.em); } } } private static void addEntityManager(UserTransactionImpl transaction, EntityManager em) { if (ObjectUtils.notNull(em)) { transaction.addEntityManager(em); } } private static void addEntityManagers(UserTransactionImpl transaction, Collection<EntityManager> ems) { if (CollectionUtils.valid(ems)) { for (EntityManager em : ems) { addEntityManager(transaction, em); } } } private static void addReqNewTransaction(UserTransactionImpl transaction, EntityTransaction entityTransaction, EntityManager em) { if (ObjectUtils.notNull(entityTransaction)) { transaction.pushReqNew(entityTransaction); } if (ObjectUtils.notNull(em)) { transaction.pushReqNewEm(em); } } private static void addReqNewTransactions(UserTransactionImpl transaction, Collection<TransactionData> entityTransactions) { if (CollectionUtils.valid(entityTransactions)) { for (TransactionData transactionData : entityTransactions) { addReqNewTransaction(transaction, transactionData.entityTransaction, transactionData.em); } } } private static void addCaller(UserTransactionImpl transaction, BeanHandler handler) { Object caller = transaction.getCaller(); if (caller == null) { transaction.setCaller(handler); } } /** * Decides whether create or join {@link UserTransaction} by * {@link TransactionAttribute} annotation * * @param handler * @param type * @param transaction * @param em * @throws IOException */ private static void addTransaction(BeanHandler handler, TransactionAttributeType type, UserTransactionImpl transaction, Collection<EntityManager> ems) throws IOException { Collection<TransactionData> entityTransactions; addCaller(transaction, handler); if (type.equals(TransactionAttributeType.NOT_SUPPORTED)) { addEntityManagers(transaction, ems); } else if (type.equals(TransactionAttributeType.REQUIRED)) { entityTransactions = getEntityTransactions(ems); addEntityTransactions(transaction, entityTransactions); } else if (type.equals(TransactionAttributeType.REQUIRES_NEW)) { entityTransactions = getEntityTransactions(ems); addReqNewTransactions(transaction, entityTransactions); } else if (type.equals(TransactionAttributeType.MANDATORY)) { int status = getStatus(transaction); if (status == 0) { addEntityManagers(transaction, ems); throw new EJBException(MANDATORY_ERROR); } else { entityTransactions = getEntityTransactions(ems); addEntityTransactions(transaction, entityTransactions); } } else if (type.equals(TransactionAttributeType.NEVER)) { try { int status = getStatus(transaction); if (status > 0) { throw new EJBException(NEVER_ERROR); } } finally { addEntityManagers(transaction, ems); } } else if (type.equals(TransactionAttributeType.SUPPORTS)) { try { throw new NotYetImplementedException(SUPPORTS_ERROR); } finally { addEntityManagers(transaction, ems); } } } /** * Defines which {@link TransactionAttribute} is used on bean {@link Class} * and decides whether create or join {@link UserTransaction} by this * annotation * * @param handler * @param method * @param entityTransaction * @throws IOException */ public static TransactionAttributeType addTransaction(BeanHandler handler, Method method, Collection<EntityManager> ems) throws IOException { TransactionAttributeType type; MetaData metaData = handler.getMetaData(); type = getTransactionType(metaData, method); UserTransactionImpl transaction = (UserTransactionImpl) getTransaction(); if (ObjectUtils.notNull(type)) { addTransaction(handler, type, transaction, ems); } else { addEntityManagers(transaction, ems); } return type; } /** * Commits passed {@link UserTransaction} with {@link IOException} throw * * @param transaction * @throws IOException */ private static void commit(UserTransaction transaction) throws IOException { try { transaction.commit(); } catch (SecurityException ex) { throw new IOException(ex); } catch (IllegalStateException ex) { throw new IOException(ex); } catch (RollbackException ex) { throw new IOException(ex); } catch (HeuristicMixedException ex) { throw new IOException(ex); } catch (HeuristicRollbackException ex) { throw new IOException(ex); } catch (SystemException ex) { throw new IOException(ex); } } /** * Commits all {@link TransactionAttributeType.REQUIRES_NEW} transactions * for passed {@link UserTransactionImpl} with {@link IOException} throw * * @param transaction * @throws IOException */ private static void commitReqNew(UserTransactionImpl transaction) throws IOException { try { transaction.commitReqNew(); } catch (SecurityException ex) { throw new IOException(ex); } catch (IllegalStateException ex) { throw new IOException(ex); } catch (RollbackException ex) { throw new IOException(ex); } catch (HeuristicMixedException ex) { throw new IOException(ex); } catch (HeuristicRollbackException ex) { throw new IOException(ex); } catch (SystemException ex) { throw new IOException(ex); } } /** * Calls {@link UserTransaction#rollback()} method of passed * {@link UserTransaction} with {@link IOException} throw * * @param transaction * @throws IOException */ private static void rollback(UserTransaction transaction) throws IOException { try { transaction.rollback(); } catch (IllegalStateException ex) { throw new IOException(ex); } catch (SecurityException ex) { throw new IOException(ex); } catch (SystemException ex) { throw new IOException(ex); } } /** * Calls {@link UserTransactionImpl#rollbackReqNews()} method of passed * {@link UserTransaction} with {@link IOException} throw * * @param transaction * @throws IOException */ private static void rollbackReqNew(UserTransactionImpl transaction) throws IOException { try { transaction.rollbackReqNews(); } catch (IllegalStateException ex) { throw new IOException(ex); } catch (SecurityException ex) { throw new IOException(ex); } catch (SystemException ex) { throw new IOException(ex); } } /** * Rollbacks passed {@link UserTransaction} by * {@link TransactionAttributeType#REQUIRES_NEW} or all other * * @param type * @param handler * @throws IOException */ private static void rollbackTransaction(TransactionAttributeType type, BeanHandler handler) throws IOException { UserTransactionImpl transaction = (UserTransactionImpl) getTransaction(); if (type.equals(TransactionAttributeType.REQUIRES_NEW)) { rollbackReqNew(transaction); } else { rollback(transaction); } } /** * Decides whether rollback or not {@link UserTransaction} by * {@link TransactionAttribute} annotation * * @param handler * @param method * @throws IOException */ public static void rollbackTransaction(BeanHandler handler, Method method) throws IOException { TransactionAttributeType type = getTransactionType( handler.getMetaData(), method); if (ObjectUtils.notNull(type)) { rollbackTransaction(type, handler); } else { closeEntityManagers(); } } /** * Decides whether commit or not {@link UserTransaction} by * {@link TransactionAttribute} annotation * * @param type * @param handler * @throws IOException */ private static void commitTransaction(TransactionAttributeType type, BeanHandler handler) throws IOException { UserTransactionImpl transaction = (UserTransactionImpl) getTransaction(); if (type.equals(TransactionAttributeType.REQUIRED)) { boolean check = transaction.checkCaller(handler); if (check) { commit(transaction); } } else if (type.equals(TransactionAttributeType.REQUIRES_NEW)) { commitReqNew(transaction); } else { transaction.closeEntityManagers(); } } /** * Decides whether commit or not {@link UserTransaction} by * {@link TransactionAttribute} annotation * * @param handler * @param method * @throws IOException */ public static void commitTransaction(BeanHandler handler, Method method) throws IOException { TransactionAttributeType type = getTransactionType( handler.getMetaData(), method); if (ObjectUtils.notNull(type)) { commitTransaction(type, handler); } else { closeEntityManagers(); } } /** * Closes cached {@link EntityManager}s after method calll */ public static void closeEntityManagers() { UserTransactionImpl transaction = (UserTransactionImpl) getTransaction(); transaction.closeEntityManagers(); } /** * Removes {@link UserTransaction} attribute from cache if passed * {@link BeanHandler} is first in EJB injection method chain * * @param handler * @param type */ private static void remove(BeanHandler handler, TransactionAttributeType type) { UserTransactionImpl transaction = (UserTransactionImpl) getTransaction(); boolean check = transaction.checkCaller(handler); if (check) { TransactionHolder.removeTransaction(); } } /** * Removes {@link UserTransaction} attribute from cache if * {@link TransactionAttributeType} is null or if passed {@link BeanHandler} * is first in EJB injection method chain * * @param handler * @param method */ public static void remove(BeanHandler handler, Method method) { TransactionAttributeType type = getTransactionType( handler.getMetaData(), method); if (ObjectUtils.notNull(type)) { remove(handler, type); } else { TransactionHolder.removeTransaction(); } } }
package org.lightmare.jpa.jta; import java.io.IOException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import javax.ejb.EJBException; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.ejb.TransactionManagementType; import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; import javax.transaction.HeuristicMixedException; import javax.transaction.HeuristicRollbackException; import javax.transaction.RollbackException; import javax.transaction.SystemException; import javax.transaction.UserTransaction; import org.hibernate.cfg.NotYetImplementedException; import org.lightmare.cache.MetaData; import org.lightmare.cache.TransactionHolder; import org.lightmare.ejb.handlers.BeanHandler; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.ObjectUtils; /** * Class to manage {@link javax.transaction.UserTransaction} for * {@link javax.ejb.Stateless} bean {@link java.lang.reflect.Proxy} calls * * @author levan * */ public class BeanTransactions { private static final String MANDATORY_ERROR = "TransactionAttributeType.MANDATORY must always be called within transaction"; private static final String NEVER_ERROR = "TransactionAttributeType.NEVER is called within transaction"; private static final String SUPPORTS_ERROR = "TransactionAttributeType.SUPPORTS is not yet implemented"; /** * Inner class to cache {@link EntityTransaction}s and {@link EntityManager} * s in one {@link Collection} for {@link UserTransaction} implementation * * @author levan * */ private static class TransactionData { EntityManager em; EntityTransaction entityTransaction; } private static TransactionData createTransactionData( EntityTransaction entityTransaction, EntityManager em) { TransactionData transactionData = new TransactionData(); transactionData.em = em; transactionData.entityTransaction = entityTransaction; return transactionData; } /** * Gets existing transaction from cache * * @param entityTransactions * @return {@link UserTransaction} */ public static UserTransaction getTransaction( EntityTransaction... entityTransactions) { UserTransaction transaction = TransactionHolder.getTransaction(); if (transaction == null) { transaction = UserTransactionFactory.get(entityTransactions); TransactionHolder.setTransaction(transaction); } else { // If entityTransactions array is available then adds it to // UserTransaction object UserTransactionFactory.join(transaction, entityTransactions); } return transaction; } /** * Gets existing transaction from cache * * @param entityTransactions * @return {@link UserTransaction} */ public static UserTransaction getTransaction(Collection<EntityManager> ems) { UserTransaction transaction = TransactionHolder.getTransaction(); if (transaction == null) { transaction = UserTransactionFactory.get(); TransactionHolder.setTransaction(transaction); } Collection<TransactionData> entityTransactions = getEntityTransactions(ems); addEntityTransactions((UserTransactionImpl) transaction, entityTransactions); return transaction; } /** * Gets appropriated {@link TransactionAttributeType} for instant * {@link Method} of {@link javax.ejb.Stateless} bean * * @param metaData * @param method * @return {@link TransactionAttributeType} */ public static TransactionAttributeType getTransactionType( MetaData metaData, Method method) { TransactionAttributeType type; if (method == null) { type = null; } else { TransactionAttributeType attrType = metaData .getTransactionAttrType(); TransactionManagementType manType = metaData .getTransactionManType(); TransactionAttribute attr = method .getAnnotation(TransactionAttribute.class); if (manType.equals(TransactionManagementType.CONTAINER)) { if (attr == null) { type = attrType; } else { type = attr.value(); } } else { type = null; } } return type; } /** * Gets status of passed transaction by {@link UserTransaction#getStatus()} * method call * * @param transaction * @return <code>int</code> * @throws IOException */ private static int getStatus(UserTransaction transaction) throws IOException { int status; try { status = transaction.getStatus(); } catch (SystemException ex) { throw new IOException(ex); } return status; } /** * Checks if transaction is active and if it is not begins transaction * * @param entityTransaction */ private static void beginEntityTransaction( EntityTransaction entityTransaction) { if (ObjectUtils.notTrue(entityTransaction.isActive())) { entityTransaction.begin(); } } /** * Gets {@link EntityTransaction} from passed {@link EntityManager} and * begins it * * @param em * @return {@link EntityTransaction} */ private static EntityTransaction getEntityTransaction(EntityManager em) { EntityTransaction entityTransaction; if (em == null) { entityTransaction = null; } else { entityTransaction = em.getTransaction(); beginEntityTransaction(entityTransaction); } return entityTransaction; } /** * * @param ems * @return {@link Collection}<EntityTransaction> */ private static Collection<TransactionData> getEntityTransactions( Collection<EntityManager> ems) { Collection<TransactionData> entityTransactions; if (CollectionUtils.valid(ems)) { entityTransactions = new ArrayList<TransactionData>(); for (EntityManager em : ems) { EntityTransaction entityTransaction = getEntityTransaction(em); TransactionData transactionData = createTransactionData( entityTransaction, em); entityTransactions.add(transactionData); } } else { entityTransactions = null; } return entityTransactions; } private static void addEntityTransaction(UserTransactionImpl transaction, EntityTransaction entityTransaction, EntityManager em) { if (ObjectUtils.notNull(entityTransaction)) { transaction.addTransaction(entityTransaction); } if (ObjectUtils.notNull(em)) { transaction.addEntityManager(em); } } private static void addEntityTransactions(UserTransactionImpl transaction, Collection<TransactionData> entityTransactions) { if (CollectionUtils.valid(entityTransactions)) { for (TransactionData transactionData : entityTransactions) { addEntityTransaction(transaction, transactionData.entityTransaction, transactionData.em); } } } private static void addEntityManager(UserTransactionImpl transaction, EntityManager em) { if (ObjectUtils.notNull(em)) { transaction.addEntityManager(em); } } private static void addEntityManagers(UserTransactionImpl transaction, Collection<EntityManager> ems) { if (CollectionUtils.valid(ems)) { for (EntityManager em : ems) { addEntityManager(transaction, em); } } } private static void addReqNewTransaction(UserTransactionImpl transaction, EntityTransaction entityTransaction, EntityManager em) { if (ObjectUtils.notNull(entityTransaction)) { transaction.pushReqNew(entityTransaction); } if (ObjectUtils.notNull(em)) { transaction.pushReqNewEm(em); } } private static void addReqNewTransactions(UserTransactionImpl transaction, Collection<TransactionData> entityTransactions) { if (CollectionUtils.valid(entityTransactions)) { for (TransactionData transactionData : entityTransactions) { addReqNewTransaction(transaction, transactionData.entityTransaction, transactionData.em); } } } private static void addCaller(UserTransactionImpl transaction, BeanHandler handler) { Object caller = transaction.getCaller(); if (caller == null) { transaction.setCaller(handler); } } /** * Decides whether create or join {@link UserTransaction} by * {@link TransactionAttribute} annotation * * @param handler * @param type * @param transaction * @param em * @throws IOException */ private static void addTransaction(BeanHandler handler, TransactionAttributeType type, UserTransactionImpl transaction, Collection<EntityManager> ems) throws IOException { Collection<TransactionData> entityTransactions; addCaller(transaction, handler); if (type.equals(TransactionAttributeType.NOT_SUPPORTED)) { addEntityManagers(transaction, ems); } else if (type.equals(TransactionAttributeType.REQUIRED)) { entityTransactions = getEntityTransactions(ems); addEntityTransactions(transaction, entityTransactions); } else if (type.equals(TransactionAttributeType.REQUIRES_NEW)) { entityTransactions = getEntityTransactions(ems); addReqNewTransactions(transaction, entityTransactions); } else if (type.equals(TransactionAttributeType.MANDATORY)) { int status = getStatus(transaction); if (status == 0) { addEntityManagers(transaction, ems); throw new EJBException(MANDATORY_ERROR); } else { entityTransactions = getEntityTransactions(ems); addEntityTransactions(transaction, entityTransactions); } } else if (type.equals(TransactionAttributeType.NEVER)) { try { int status = getStatus(transaction); if (status > 0) { throw new EJBException(NEVER_ERROR); } } finally { addEntityManagers(transaction, ems); } } else if (type.equals(TransactionAttributeType.SUPPORTS)) { try { throw new NotYetImplementedException(SUPPORTS_ERROR); } finally { addEntityManagers(transaction, ems); } } } /** * Defines which {@link TransactionAttribute} is used on bean {@link Class} * and decides whether create or join {@link UserTransaction} by this * annotation * * @param handler * @param method * @param entityTransaction * @throws IOException */ public static TransactionAttributeType addTransaction(BeanHandler handler, Method method, Collection<EntityManager> ems) throws IOException { TransactionAttributeType type; MetaData metaData = handler.getMetaData(); type = getTransactionType(metaData, method); UserTransactionImpl transaction = (UserTransactionImpl) getTransaction(); if (ObjectUtils.notNull(type)) { addTransaction(handler, type, transaction, ems); } else { addEntityManagers(transaction, ems); } return type; } /** * Commits passed {@link UserTransaction} with {@link IOException} throw * * @param transaction * @throws IOException */ private static void commit(UserTransaction transaction) throws IOException { try { transaction.commit(); } catch (SecurityException ex) { throw new IOException(ex); } catch (IllegalStateException ex) { throw new IOException(ex); } catch (RollbackException ex) { throw new IOException(ex); } catch (HeuristicMixedException ex) { throw new IOException(ex); } catch (HeuristicRollbackException ex) { throw new IOException(ex); } catch (SystemException ex) { throw new IOException(ex); } } /** * Commits all {@link TransactionAttributeType.REQUIRES_NEW} transactions * for passed {@link UserTransactionImpl} with {@link IOException} throw * * @param transaction * @throws IOException */ private static void commitReqNew(UserTransactionImpl transaction) throws IOException { try { transaction.commitReqNew(); } catch (SecurityException ex) { throw new IOException(ex); } catch (IllegalStateException ex) { throw new IOException(ex); } catch (RollbackException ex) { throw new IOException(ex); } catch (HeuristicMixedException ex) { throw new IOException(ex); } catch (HeuristicRollbackException ex) { throw new IOException(ex); } catch (SystemException ex) { throw new IOException(ex); } } /** * Calls {@link UserTransaction#rollback()} method of passed * {@link UserTransaction} with {@link IOException} throw * * @param transaction * @throws IOException */ private static void rollback(UserTransaction transaction) throws IOException { try { transaction.rollback(); } catch (IllegalStateException ex) { throw new IOException(ex); } catch (SecurityException ex) { throw new IOException(ex); } catch (SystemException ex) { throw new IOException(ex); } } /** * Calls {@link UserTransactionImpl#rollbackReqNews()} method of passed * {@link UserTransaction} with {@link IOException} throw * * @param transaction * @throws IOException */ private static void rollbackReqNew(UserTransactionImpl transaction) throws IOException { try { transaction.rollbackReqNews(); } catch (IllegalStateException ex) { throw new IOException(ex); } catch (SecurityException ex) { throw new IOException(ex); } catch (SystemException ex) { throw new IOException(ex); } } /** * Rollbacks passed {@link UserTransaction} by * {@link TransactionAttributeType} distinguishes only * {@link TransactionAttributeType#REQUIRES_NEW} case or uses standard * rollback for all other * * @param type * @param handler * @throws IOException */ private static void rollbackTransaction(TransactionAttributeType type, BeanHandler handler) throws IOException { UserTransactionImpl transaction = (UserTransactionImpl) getTransaction(); if (type.equals(TransactionAttributeType.REQUIRES_NEW)) { rollbackReqNew(transaction); } else { rollback(transaction); } } /** * Decides which rollback method to call of {@link UserTransaction} * implementation by {@link TransactionAttribute} annotation * * @param handler * @param method * @throws IOException */ public static void rollbackTransaction(BeanHandler handler, Method method) throws IOException { TransactionAttributeType type = getTransactionType( handler.getMetaData(), method); if (ObjectUtils.notNull(type)) { rollbackTransaction(type, handler); } else { closeEntityManagers(); } } /** * Decides whether commit or not {@link UserTransaction} by * {@link TransactionAttribute} annotation * * @param type * @param handler * @throws IOException */ private static void commitTransaction(TransactionAttributeType type, BeanHandler handler) throws IOException { UserTransactionImpl transaction = (UserTransactionImpl) getTransaction(); if (type.equals(TransactionAttributeType.REQUIRED)) { boolean check = transaction.checkCaller(handler); if (check) { commit(transaction); } } else if (type.equals(TransactionAttributeType.REQUIRES_NEW)) { commitReqNew(transaction); } else { transaction.closeEntityManagers(); } } /** * Decides whether commit or not {@link UserTransaction} by * {@link TransactionAttribute} annotation * * @param handler * @param method * @throws IOException */ public static void commitTransaction(BeanHandler handler, Method method) throws IOException { TransactionAttributeType type = getTransactionType( handler.getMetaData(), method); if (ObjectUtils.notNull(type)) { commitTransaction(type, handler); } else { closeEntityManagers(); } } /** * Closes cached {@link EntityManager}s after method calll */ public static void closeEntityManagers() { UserTransactionImpl transaction = (UserTransactionImpl) getTransaction(); transaction.closeEntityManagers(); } /** * Removes {@link UserTransaction} attribute from cache if passed * {@link BeanHandler} is first in EJB injection method chain * * @param handler * @param type */ private static void remove(BeanHandler handler, TransactionAttributeType type) { UserTransactionImpl transaction = (UserTransactionImpl) getTransaction(); boolean check = transaction.checkCaller(handler); if (check) { TransactionHolder.removeTransaction(); } } /** * Removes {@link UserTransaction} attribute from cache if * {@link TransactionAttributeType} is null or if passed {@link BeanHandler} * is first in EJB injection method chain * * @param handler * @param method */ public static void remove(BeanHandler handler, Method method) { TransactionAttributeType type = getTransactionType( handler.getMetaData(), method); if (ObjectUtils.notNull(type)) { remove(handler, type); } else { TransactionHolder.removeTransaction(); } } }
package org.osiam.storage.entities; import javax.persistence.Basic; import javax.persistence.Entity; import javax.persistence.Table; import org.osiam.resources.scim.Email; import org.osiam.storage.entities.jpa_converters.EmailTypeConverter; /** * Email Entity */ @Entity @Table(name = "scim_email") public class EmailEntity extends BaseMultiValuedAttributeEntityWithValue { /** * <p> * The type of this Email. * </p> * * <p> * Custom type mapping is provided by {@link EmailTypeConverter}. * </p> */ @Basic private Email.Type type; // @Basic is needed for JPA meta model generator public Email.Type getType() { return type; } public void setType(Email.Type type) { this.type = type; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + (type == null ? 0 : type.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (getClass() != obj.getClass()) { return false; } EmailEntity other = (EmailEntity) obj; if (type == null) { if (other.type != null) { return false; } } else if (!type.equals(other.type)) { return false; } return true; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("EmailEntity [type=").append(type).append(", getValue()=").append(getValue()) .append(", isPrimary()=").append(isPrimary()).append("]"); return builder.toString(); } }
package org.osiam.storage.query; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.Expression; import javax.persistence.criteria.JoinType; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import javax.persistence.criteria.SetJoin; import org.joda.time.format.ISODateTimeFormat; import org.osiam.resources.scim.Address; import org.osiam.resources.scim.Email; import org.osiam.resources.scim.Entitlement; import org.osiam.resources.scim.Im; import org.osiam.resources.scim.PhoneNumber; import org.osiam.resources.scim.Photo; import org.osiam.storage.entities.AddressEntity; import org.osiam.storage.entities.AddressEntity_; import org.osiam.storage.entities.BaseMultiValuedAttributeEntityWithValue_; import org.osiam.storage.entities.BaseMultiValuedAttributeEntity_; import org.osiam.storage.entities.EmailEntity; import org.osiam.storage.entities.EmailEntity_; import org.osiam.storage.entities.EntitlementEntity; import org.osiam.storage.entities.EntitlementEntity_; import org.osiam.storage.entities.GroupEntity; import org.osiam.storage.entities.GroupEntity_; import org.osiam.storage.entities.ImEntity; import org.osiam.storage.entities.ImEntity_; import org.osiam.storage.entities.MetaEntity_; import org.osiam.storage.entities.NameEntity_; import org.osiam.storage.entities.PhoneNumberEntity; import org.osiam.storage.entities.PhoneNumberEntity_; import org.osiam.storage.entities.PhotoEntity; import org.osiam.storage.entities.PhotoEntity_; import org.osiam.storage.entities.ResourceEntity_; import org.osiam.storage.entities.RoleEntity; import org.osiam.storage.entities.RoleEntity_; import org.osiam.storage.entities.UserEntity; import org.osiam.storage.entities.UserEntity_; import org.osiam.storage.entities.X509CertificateEntity; public enum UserQueryField implements QueryField<UserEntity> { EXTERNALID("externalid") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { return constraint.createPredicateForStringField(root.get(ResourceEntity_.externalId), value, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { return root.get(ResourceEntity_.externalId); } }, META_CREATED("meta.created") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { Date date = ISODateTimeFormat.dateTimeParser().parseDateTime(value).toDate(); return constraint.createPredicateForDateField(root.get(ResourceEntity_.meta).get(MetaEntity_.created), date, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { return root.get(ResourceEntity_.meta).get(MetaEntity_.created); } }, META_LASTMODIFIED("meta.lastmodified") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { Date date = ISODateTimeFormat.dateTimeParser().parseDateTime(value).toDate(); return constraint.createPredicateForDateField( root.get(ResourceEntity_.meta).get(MetaEntity_.lastModified), date, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { return root.get(ResourceEntity_.meta).get(MetaEntity_.lastModified); } }, META_LOCATION("meta.location") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { return constraint.createPredicateForStringField(root.get(ResourceEntity_.meta) .get(MetaEntity_.location), value, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { return root.get(ResourceEntity_.meta).get(MetaEntity_.location); } }, USERNAME("username") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { return constraint.createPredicateForStringField(root.get(UserEntity_.userName), value, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { return root.get(UserEntity_.userName); } }, DISPLAYNAME("displayname") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { return constraint.createPredicateForStringField(root.get(UserEntity_.displayName), value, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { return root.get(UserEntity_.displayName); } }, NICKNAME("nickname") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { return constraint.createPredicateForStringField(root.get(UserEntity_.nickName), value, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { return root.get(UserEntity_.nickName); } }, PROFILEURL("profileurl") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { return constraint.createPredicateForStringField(root.get(UserEntity_.profileUrl), value, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { return root.get(UserEntity_.profileUrl); } }, TITLE("title") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { return constraint.createPredicateForStringField(root.get(UserEntity_.title), value, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { return root.get(UserEntity_.title); } }, USERTYPE("usertype") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { return constraint.createPredicateForStringField(root.get(UserEntity_.userType), value, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { return root.get(UserEntity_.userType); } }, PREFERREDLANGUAGE("preferredlanguage") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { return constraint.createPredicateForStringField(root.get(UserEntity_.preferredLanguage), value, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { return root.get(UserEntity_.preferredLanguage); } }, LOCALE("locale") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { return constraint.createPredicateForStringField(root.get(UserEntity_.locale), value, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { return root.get(UserEntity_.locale); } }, TIMEZONE("timezone") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { return constraint.createPredicateForStringField(root.get(UserEntity_.timezone), value, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { return root.get(UserEntity_.timezone); } }, ACTIVE("active") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { return constraint.createPredicateForBooleanField(root.get(UserEntity_.active), Boolean.valueOf(value), cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { return root.get(UserEntity_.active); } }, NAME_FORMATTED("name.formatted") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { return constraint.createPredicateForStringField(root.get(UserEntity_.name).get(NameEntity_.formatted), value, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { return root.get(UserEntity_.name).get(NameEntity_.formatted); } }, NAME_FAMILYNAME("name.familyname") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { return constraint.createPredicateForStringField(root.get(UserEntity_.name).get(NameEntity_.familyName), value, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { return root.get(UserEntity_.name).get(NameEntity_.familyName); } }, NAME_GIVENNAME("name.givenname") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { return constraint.createPredicateForStringField(root.get(UserEntity_.name).get(NameEntity_.givenName), value, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { return root.get(UserEntity_.name).get(NameEntity_.givenName); } }, NAME_MIDDLENAME("name.middlename") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { return constraint.createPredicateForStringField(root.get(UserEntity_.name).get(NameEntity_.middleName), value, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { return root.get(UserEntity_.name).get(NameEntity_.middleName); } }, NAME_HONORIFICPREFIX("name.honorificprefix") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { return constraint.createPredicateForStringField( root.get(UserEntity_.name).get(NameEntity_.honorificPrefix), value, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { return root.get(UserEntity_.name).get(NameEntity_.honorificPrefix); } }, NAME_HONORIFICSUFFIX("name.honorificsuffix") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { return constraint.createPredicateForStringField( root.get(UserEntity_.name).get(NameEntity_.honorificSuffix), value, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { return root.get(UserEntity_.name).get(NameEntity_.honorificSuffix); } }, PASSWORD("password") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { return constraint.createPredicateForStringField(root.get(UserEntity_.password), value, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { throw handleSortByFieldNotSupported(toString()); } }, EMAILS("emails") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { return EMAILS_VALUE.addFilter(root, constraint, value, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { return EMAILS_VALUE.createSortByField(root, cb); } }, EMAILS_VALUE("emails.value") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { SetJoin<UserEntity, EmailEntity> join = root.join(UserEntity_.emails, JoinType.LEFT); return constraint.createPredicateForStringField(join.get(BaseMultiValuedAttributeEntityWithValue_.value), value, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { throw handleSortByFieldNotSupported(toString()); } }, EMAILS_TYPE("emails.type") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { Email.Type emailType = null; if (constraint != FilterConstraint.PRESENT) { emailType = new Email.Type(value); } SetJoin<UserEntity, EmailEntity> join = root.join(UserEntity_.emails, JoinType.LEFT); return constraint.createPredicateForMultiValuedAttributeTypeField(join.get(EmailEntity_.type), // NOSONAR - // XEntity_.X // will // be filled by JPA provider emailType, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { throw handleSortByFieldNotSupported(toString()); } }, EMAILS_PRIMARY("emails.primary") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { SetJoin<UserEntity, EmailEntity> join = root.join(UserEntity_.emails, JoinType.LEFT); return constraint.createPredicateForBooleanField(join.get(BaseMultiValuedAttributeEntity_.primary), // NOSONAR // XEntity_.X // will be filled by JPA provider Boolean.valueOf(value), cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { throw handleSortByFieldNotSupported(toString()); } }, PHONENUMBERS("phonenumbers") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { return PHONENUMBERS_VALUE.addFilter(root, constraint, value, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { return PHONENUMBERS_VALUE.createSortByField(root, cb); } }, PHONENUMBERS_VALUE("phonenumbers.value") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { SetJoin<UserEntity, PhoneNumberEntity> join = root.join(UserEntity_.phoneNumbers, JoinType.LEFT); return constraint.createPredicateForStringField(join.get(BaseMultiValuedAttributeEntityWithValue_.value), value, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { throw handleSortByFieldNotSupported(toString()); } }, PHONENUMBERS_TYPE("phonenumbers.type") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { PhoneNumber.Type phoneNumberType = null; if (constraint != FilterConstraint.PRESENT) { phoneNumberType = new PhoneNumber.Type(value); } SetJoin<UserEntity, PhoneNumberEntity> join = root.join(UserEntity_.phoneNumbers, JoinType.LEFT); return constraint.createPredicateForMultiValuedAttributeTypeField(join.get(PhoneNumberEntity_.type), // NOSONAR // XEntity_.X will be filled by JPA provider phoneNumberType, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { throw handleSortByFieldNotSupported(toString()); } }, PHONENUMBERS_PRIMARY("phonenumbers.primary") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { SetJoin<UserEntity, PhoneNumberEntity> join = root.join(UserEntity_.phoneNumbers, JoinType.LEFT); return constraint.createPredicateForBooleanField(join.get(PhoneNumberEntity_.primary), Boolean.valueOf(value), cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { throw handleSortByFieldNotSupported(toString()); } }, IMS("ims") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { return IMS_VALUE.addFilter(root, constraint, value, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { return IMS_VALUE.createSortByField(root, cb); } }, IMS_VALUE("ims.value") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { SetJoin<UserEntity, ImEntity> join = root.join(UserEntity_.ims, JoinType.LEFT); return constraint.createPredicateForStringField(join.get(BaseMultiValuedAttributeEntityWithValue_.value), value, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { throw handleSortByFieldNotSupported(toString()); } }, IMS_TYPE("ims.type") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { Im.Type imType = null; if (constraint != FilterConstraint.PRESENT) { imType = new Im.Type(value); } SetJoin<UserEntity, ImEntity> join = root.join(UserEntity_.ims, JoinType.LEFT); return constraint.createPredicateForMultiValuedAttributeTypeField(join.get(ImEntity_.type), imType, cb); // NOSONAR // XEntity_.X will be filled by JPA provider } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { throw handleSortByFieldNotSupported(toString()); } }, IMS_PRIMARY("ims.primary") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { SetJoin<UserEntity, ImEntity> join = root.join(UserEntity_.ims, JoinType.LEFT); return constraint.createPredicateForBooleanField(join.get(ImEntity_.primary), Boolean.valueOf(value), cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { throw handleSortByFieldNotSupported(toString()); } }, PHOTOS("photos") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { return PHOTOS_VALUE.addFilter(root, constraint, value, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { return PHOTOS_VALUE.createSortByField(root, cb); } }, PHOTOS_VALUE("photos.value") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { SetJoin<UserEntity, PhotoEntity> join = root.join(UserEntity_.photos, JoinType.LEFT); return constraint.createPredicateForStringField(join.get(BaseMultiValuedAttributeEntityWithValue_.value), value, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { throw handleSortByFieldNotSupported(toString()); } }, PHOTOS_TYPE("photos.type") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { Photo.Type photoType = null; if (constraint != FilterConstraint.PRESENT) { photoType = new Photo.Type(value); } SetJoin<UserEntity, PhotoEntity> join = root.join(UserEntity_.photos, JoinType.LEFT); return constraint.createPredicateForMultiValuedAttributeTypeField(join.get(PhotoEntity_.type), photoType, cb); // NOSONAR - // XEntity_.X will be filled by JPA provider } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { throw handleSortByFieldNotSupported(toString()); } }, PHOTOS_PRIMARY("photos.primary") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { SetJoin<UserEntity, PhotoEntity> join = root.join(UserEntity_.photos, JoinType.LEFT); return constraint .createPredicateForBooleanField(join.get(PhotoEntity_.primary), Boolean.valueOf(value), cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { throw handleSortByFieldNotSupported(toString()); } }, ADDRESSES_REGION("addresses.region") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { SetJoin<UserEntity, AddressEntity> join = root.join(UserEntity_.addresses, JoinType.LEFT); return constraint.createPredicateForStringField(join.get(AddressEntity_.region), value, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { throw handleSortByFieldNotSupported(toString()); } }, ADDRESSES_STREETADDRESS("addresses.streetaddress") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { SetJoin<UserEntity, AddressEntity> join = root.join(UserEntity_.addresses, JoinType.LEFT); return constraint.createPredicateForStringField(join.get(AddressEntity_.streetAddress), value, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { throw handleSortByFieldNotSupported(toString()); } }, ADDRESSES_FORMATTED("addresses.formatted") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { SetJoin<UserEntity, AddressEntity> join = root.join(UserEntity_.addresses, JoinType.LEFT); return constraint.createPredicateForStringField(join.get(AddressEntity_.formatted), value, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { throw handleSortByFieldNotSupported(toString()); } }, ADDRESSES_POSTALCODE("addresses.postalcode") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { SetJoin<UserEntity, AddressEntity> join = root.join(UserEntity_.addresses, JoinType.LEFT); return constraint.createPredicateForStringField(join.get(AddressEntity_.postalCode), value, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { throw handleSortByFieldNotSupported(toString()); } }, ADDRESSES_LOCALITY("addresses.locality") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { SetJoin<UserEntity, AddressEntity> join = root.join(UserEntity_.addresses, JoinType.LEFT); return constraint.createPredicateForStringField(join.get(AddressEntity_.locality), value, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { throw handleSortByFieldNotSupported(toString()); } }, ADDRESSES_TYPE("addresses.type") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { Address.Type addressType = null; if (constraint != FilterConstraint.PRESENT) { addressType = new Address.Type(value); } SetJoin<UserEntity, AddressEntity> join = root.join(UserEntity_.addresses, JoinType.LEFT); return constraint.createPredicateForMultiValuedAttributeTypeField(join.get(AddressEntity_.type), addressType, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { throw handleSortByFieldNotSupported(toString()); } }, ADDRESSES_COUNTRY("addresses.country") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { SetJoin<UserEntity, AddressEntity> join = root.join(UserEntity_.addresses, JoinType.LEFT); return constraint.createPredicateForStringField(join.get(AddressEntity_.country), value, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { throw handleSortByFieldNotSupported(toString()); } }, ADDRESSES_PRIMARY("addresses.primary") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { SetJoin<UserEntity, AddressEntity> join = root.join(UserEntity_.addresses, JoinType.LEFT); return constraint.createPredicateForBooleanField(join.get(AddressEntity_.primary), Boolean.valueOf(value), cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { throw handleSortByFieldNotSupported(toString()); } }, ENTITLEMENTS("entitlements") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { return ENTITLEMENTS_VALUE.addFilter(root, constraint, value, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { return ENTITLEMENTS_VALUE.createSortByField(root, cb); } }, ENTITLEMENTS_VALUE("entitlements.value") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { SetJoin<UserEntity, EntitlementEntity> join = root.join(UserEntity_.entitlements, JoinType.LEFT); return constraint.createPredicateForStringField(join.get(BaseMultiValuedAttributeEntityWithValue_.value), value, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { throw handleSortByFieldNotSupported(toString()); } }, ENTITLEMENTS_TYPE("entitlements.type") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { Entitlement.Type type = null; if (constraint != FilterConstraint.PRESENT) { type = new Entitlement.Type(value); } SetJoin<UserEntity, EntitlementEntity> join = root.join(UserEntity_.entitlements, JoinType.LEFT); return constraint.createPredicateForMultiValuedAttributeTypeField(join.get(EntitlementEntity_.type), type, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { throw handleSortByFieldNotSupported(toString()); } }, ENTITLEMENTS_PRIMARY("entitlements.primary") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { SetJoin<UserEntity, EntitlementEntity> join = root.join(UserEntity_.entitlements, JoinType.LEFT); return constraint.createPredicateForBooleanField(join.get(EntitlementEntity_.primary), Boolean.valueOf(value), cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { throw handleSortByFieldNotSupported(toString()); } }, ROLES("roles") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { return ROLES_VALUE.addFilter(root, constraint, value, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { return ROLES_VALUE.createSortByField(root, cb); } }, ROLES_VALUE("roles.value") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { SetJoin<UserEntity, RoleEntity> join = root.join(UserEntity_.roles, JoinType.LEFT); return constraint.createPredicateForStringField(join.get(BaseMultiValuedAttributeEntityWithValue_.value), value, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { throw handleSortByFieldNotSupported(toString()); } }, ROLES_PRIMARY("roles.primary") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { SetJoin<UserEntity, RoleEntity> join = root.join(UserEntity_.roles, JoinType.LEFT); return constraint.createPredicateForBooleanField(join.get(RoleEntity_.primary), Boolean.valueOf(value), cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { throw handleSortByFieldNotSupported(toString()); } }, X509CERTIFICATES("x509certificates") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { return X509CERTIFICATES_VALUE.addFilter(root, constraint, value, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { return X509CERTIFICATES_VALUE.createSortByField(root, cb); } }, X509CERTIFICATES_VALUE("x509certificates.value") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { SetJoin<UserEntity, X509CertificateEntity> join = root.join(UserEntity_.x509Certificates, JoinType.LEFT); return constraint.createPredicateForStringField(join.get(BaseMultiValuedAttributeEntityWithValue_.value), value, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { throw handleSortByFieldNotSupported(toString()); } }, GROUPS("groups") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { return GROUPS_VALUE.addFilter(root, constraint, value, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { return GROUPS_VALUE.createSortByField(root, cb); } }, GROUPS_VALUE("groups.value") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { final SetJoin<UserEntity, GroupEntity> join = root.join(ResourceEntity_.groups, JoinType.LEFT); return constraint.createPredicateForStringField(join.get(ResourceEntity_.id), value, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { throw handleSortByFieldNotSupported(toString()); } }, GROUPS_DISPLAY("groups.display") { @Override public Predicate addFilter(Root<UserEntity> root, FilterConstraint constraint, String value, CriteriaBuilder cb) { final SetJoin<UserEntity, GroupEntity> join = root.join(ResourceEntity_.groups, JoinType.LEFT); return constraint.createPredicateForStringField(join.get(GroupEntity_.displayName), value, cb); } @Override public Expression<?> createSortByField(Root<UserEntity> root, CriteriaBuilder cb) { throw handleSortByFieldNotSupported(toString()); } }; private static final Map<String, UserQueryField> STRING_TO_ENUM = new HashMap<>(); static { for (UserQueryField filterField : values()) { STRING_TO_ENUM.put(filterField.toString(), filterField); } } private final String name; private UserQueryField(String name) { this.name = name; } protected RuntimeException handleSortByFieldNotSupported(String fieldName) { throw new RuntimeException("Sorting by " + fieldName + " is not supported yet"); // NOSONAR - will be removed // after implementing } @Override public String toString() { return name; } public static UserQueryField fromString(String name) { return STRING_TO_ENUM.get(name); } }
package org.realityforge.getopt4j; import java.text.ParseException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * Parser for command line arguments. * * This parses command lines according to the standard (?) of * GNU utilities. Note that CLArgs uses a backing hash table for the options index and * so duplicate arguments are only returned by getArguments(). * * @see ParserControl * @see CLOption * @see CLOptionDescriptor */ public final class CLArgsParser { //cached character == Integer.MAX_VALUE when invalid private static final int INVALID = Integer.MAX_VALUE; private static final int STATE_NORMAL = 0; private static final int STATE_REQUIRE_2ARGS = 1; private static final int STATE_REQUIRE_ARG = 2; private static final int STATE_OPTIONAL_ARG = 3; private static final int STATE_NO_OPTIONS = 4; private static final int STATE_OPTION_MODE = 5; private static final char[] ARG_SEPARATORS = new char[]{ (char) 0, '=' }; private static final char[] NULL_SEPARATORS = new char[]{ (char) 0 }; private CLOptionDescriptor[] _optionDescriptors; private List<CLOption> _options; private HashMap<Integer, CLOption> _id2Option; private HashMap<String, CLOption> _name2Option; private ParserControl _control; private String _errorMessage; private String[] _unParsedArgs = new String[]{}; //variables used while parsing options. private char _ch; private String[] _args; private boolean _isLong; private int _argIndex; private int _stringIndex; private int _stringLength; private int _lastChar = INVALID; private int _lastOptionId; private CLOption _option; private int _state = STATE_NORMAL; private int _argIndexForMultiArg; /** * Create a parser that can deal with options and parses certain args. * * @param args the args, typically that passed to the * <code>public static void main(String[] args)</code> method. * @param optionDescriptors the option descriptors * @param control the parser control used determine behaviour of parser */ public CLArgsParser( final String[] args, final CLOptionDescriptor[] optionDescriptors, final ParserControl control ) { _optionDescriptors = optionDescriptors; _control = control; _options = new ArrayList<CLOption>(); _args = args; try { parse(); checkIncompatibilities( _options ); buildOptionIndex(); } catch ( final ParseException pe ) { _errorMessage = pe.getMessage(); } } /** * Create a parser that deals with options and parses certain args. * * @param args the args * @param optionDescriptors the option descriptors */ public CLArgsParser( final String[] args, final CLOptionDescriptor[] optionDescriptors ) { this( args, optionDescriptors, null ); } /** * Retrieve an array of arguments that have not been parsed * due to the parser halting. * * @return an array of unparsed args */ public String[] getUnParsedArgs() { return _unParsedArgs; } /** * Retrieve a list of options that were parsed from command list. * * @return the list of options */ public List<CLOption> getArguments() { return _options; } /** * Retrieve the {@link CLOption} with specified id, or * <code>null</code> if no command line option is found. * * @param id the command line option id * @return the {@link CLOption} with the specified id, or <code>null</code> if no CLOption is found. * @see CLOption */ public CLOption getArgumentById( final int id ) { return _id2Option.get( id ); } /** * Retrieve the {@link CLOption} with specified name, or * <code>null</code> if no command line option is found. * * @param name the command line option name * @return the {@link CLOption} with the specified name, or * <code>null</code> if no CLOption is found. * @see CLOption */ public CLOption getArgumentByName( final String name ) { return _name2Option.get( name ); } /** * Retrieve an error message that occured during parsing if one existed. * * @return the error string */ public String getErrorString() { return _errorMessage; } /** * Get Descriptor for option id. * * @param id the id * @return the descriptor */ private CLOptionDescriptor getDescriptorFor( final int id ) { for ( final CLOptionDescriptor descriptor : _optionDescriptors ) { if ( descriptor.getId() == id ) { return descriptor; } } return null; } /** * Retrieve a descriptor by name. * * @param name the name * @return the descriptor */ private CLOptionDescriptor getDescriptorFor( final String name ) { for ( final CLOptionDescriptor optionDescriptor : _optionDescriptors ) { if ( optionDescriptor.getName().equals( name ) ) { return optionDescriptor; } } return null; } /** * Check for duplicates of an option. * It is an error to have duplicates unless appropriate flags is set in descriptor. * * @param arguments the arguments */ private void checkIncompatibilities( final List<CLOption> arguments ) throws ParseException { final int size = arguments.size(); for ( int i = 0; i < size; i++ ) { final CLOption option = arguments.get( i ); final int id = option.getId(); final CLOptionDescriptor descriptor = getDescriptorFor( id ); //this occurs when id == 0 and user has not supplied a descriptor //for arguments if ( null == descriptor ) { continue; } final int[] incompatible = descriptor.getIncompatible(); checkIncompatible( arguments, incompatible, i ); } } private void checkIncompatible( final List<CLOption> arguments, final int[] incompatible, final int original ) throws ParseException { final int size = arguments.size(); for ( int i = 0; i < size; i++ ) { if ( original == i ) { continue; } final CLOption option = arguments.get( i ); final int id = option.getId(); for ( final int anIncompatible : incompatible ) { if ( id == anIncompatible ) { final CLOption originalOption = arguments.get( original ); final int originalId = originalOption.getId(); final String message; if ( id == originalId ) { message = "Duplicate options for " + describeDualOption( originalId ) + " found."; } else { message = "Incompatible options -" + describeDualOption( id ) + " and " + describeDualOption( originalId ) + " found."; } throw new ParseException( message, 0 ); } } } } /** * Require state to be placed in for option. * * @param descriptor the Option Descriptor * @return the state */ private int getStateFor( final CLOptionDescriptor descriptor ) { final int flags = descriptor.getFlags(); if ( ( flags & CLOptionDescriptor.ARGUMENTS_REQUIRED_2 ) == CLOptionDescriptor.ARGUMENTS_REQUIRED_2 ) { return STATE_REQUIRE_2ARGS; } else if ( ( flags & CLOptionDescriptor.ARGUMENT_REQUIRED ) == CLOptionDescriptor.ARGUMENT_REQUIRED ) { return STATE_REQUIRE_ARG; } else if ( ( flags & CLOptionDescriptor.ARGUMENT_OPTIONAL ) == CLOptionDescriptor.ARGUMENT_OPTIONAL ) { return STATE_OPTIONAL_ARG; } else { return STATE_NORMAL; } } private String describeDualOption( final int id ) { final CLOptionDescriptor descriptor = getDescriptorFor( id ); if ( null == descriptor ) { return "<parameter>"; } else { final StringBuilder sb = new StringBuilder(); boolean hasCharOption = false; if ( Character.isLetter( (char) id ) ) { sb.append( '-' ); sb.append( (char) id ); hasCharOption = true; } final String longOption = descriptor.getName(); if ( null != longOption ) { if ( hasCharOption ) { sb.append( '/' ); } sb.append( " sb.append( longOption ); } return sb.toString(); } } /** * Create a string array that is subset of input array. * The sub-array should start at array entry indicated by index. That array element * should only include characters from charIndex onwards. * * @param array the original array * @param index the cut-point in array * @param charIndex the cut-point in element of array * @return the result array */ private String[] subArray( final String[] array, final int index, final int charIndex ) { final int remaining = array.length - index; final String[] result = new String[ remaining ]; if ( remaining > 1 ) { System.arraycopy( array, index + 1, result, 1, remaining - 1 ); } result[ 0 ] = array[ index ].substring( charIndex - 1 ); return result; } /** * Actually parse arguments */ private void parse() throws ParseException { if ( 0 == _args.length ) { return; } _stringLength = _args[ _argIndex ].length(); while ( true ) { _ch = peekAtChar(); if ( _argIndex >= _args.length ) { break; } if ( null != _control && _control.isFinished( _lastOptionId ) ) { //this may need mangling due to peeks _unParsedArgs = subArray( _args, _argIndex, _stringIndex ); return; } if ( STATE_OPTION_MODE == _state ) { //if get to an arg barrier then return to normal mode //else continue accumulating options if ( 0 == _ch ) { getChar(); //strip the null _state = STATE_NORMAL; } else { parseShortOption(); } } else if ( STATE_NORMAL == _state ) { parseNormal(); } else if ( STATE_NO_OPTIONS == _state ) { //should never get to here when stringIndex != 0 addOption( new CLOption( _args[ _argIndex++ ] ) ); } else if ( STATE_OPTIONAL_ARG == _state && '-' == _ch ) { _state = STATE_NORMAL; addOption( _option ); } else { parseArguments(); } } if ( _option != null ) { if ( STATE_OPTIONAL_ARG == _state ) { _options.add( _option ); } else if ( STATE_REQUIRE_ARG == _state ) { final CLOptionDescriptor descriptor = getDescriptorFor( _option.getId() ); final String message = "Missing argument to option " + getOptionDescription( descriptor ); throw new ParseException( message, 0 ); } else if ( STATE_REQUIRE_2ARGS == _state ) { if ( 1 == _option.getArgumentCount() ) { _option.addArgument( "" ); _options.add( _option ); } else { final CLOptionDescriptor descriptor = getDescriptorFor( _option.getId() ); final String message = "Missing argument to option " + getOptionDescription( descriptor ); throw new ParseException( message, 0 ); } } else { throw new ParseException( "IllegalState " + _state + ": " + _option, 0 ); } } } private String getOptionDescription( final CLOptionDescriptor descriptor ) { if ( _isLong ) { return "--" + descriptor.getName(); } else { return "-" + (char) descriptor.getId(); } } private char peekAtChar() { if ( INVALID == _lastChar ) { _lastChar = readChar(); } return (char) _lastChar; } private char getChar() { if ( INVALID != _lastChar ) { final char result = (char) _lastChar; _lastChar = INVALID; return result; } else { return readChar(); } } private char readChar() { if ( _stringIndex >= _stringLength ) { _argIndex++; _stringIndex = 0; if ( _argIndex < _args.length ) { _stringLength = _args[ _argIndex ].length(); } else { _stringLength = 0; } return 0; } if ( _argIndex >= _args.length ) { return 0; } return _args[ _argIndex ].charAt( _stringIndex++ ); } private Token nextToken( final char[] separators ) { _ch = getChar(); if ( isSeparator( _ch, separators ) ) { _ch = getChar(); return new Token( Token.TOKEN_SEPARATOR, null ); } final StringBuilder sb = new StringBuilder(); do { sb.append( _ch ); _ch = getChar(); } while ( !isSeparator( _ch, separators ) ); return new Token( Token.TOKEN_STRING, sb.toString() ); } private boolean isSeparator( final char ch, final char[] separators ) { for ( final char separator : separators ) { if ( ch == separator ) { return true; } } return false; } private void addOption( final CLOption option ) { _options.add( option ); _lastOptionId = option.getId(); _option = null; } private void parseOption( final CLOptionDescriptor descriptor, final String optionString ) throws ParseException { if ( null == descriptor ) { throw new ParseException( "Unknown option " + optionString, 0 ); } _state = getStateFor( descriptor ); _option = new CLOption( descriptor ); if ( STATE_NORMAL == _state ) { addOption( _option ); } } private void parseShortOption() throws ParseException { _ch = getChar(); final CLOptionDescriptor descriptor = getDescriptorFor( _ch ); _isLong = false; parseOption( descriptor, "-" + _ch ); if ( STATE_NORMAL == _state ) { _state = STATE_OPTION_MODE; } } private void parseArguments() throws ParseException { if ( STATE_REQUIRE_ARG == _state ) { if ( '=' == _ch || 0 == _ch ) { getChar(); } final Token token = nextToken( NULL_SEPARATORS ); _option.addArgument( token.getValue() ); addOption( _option ); _state = STATE_NORMAL; } else if ( STATE_OPTIONAL_ARG == _state ) { if ( '-' == _ch || 0 == _ch ) { getChar(); //consume stray character addOption( _option ); _state = STATE_NORMAL; return; } if ( '=' == _ch ) { getChar(); } final Token token = nextToken( NULL_SEPARATORS ); _option.addArgument( token.getValue() ); addOption( _option ); _state = STATE_NORMAL; } else if ( STATE_REQUIRE_2ARGS == _state ) { if ( 0 == _option.getArgumentCount() ) { _argIndexForMultiArg = _argIndex; final Token token = nextToken( ARG_SEPARATORS ); if ( Token.TOKEN_SEPARATOR == token.getType() ) { final CLOptionDescriptor descriptor = getDescriptorFor( _option.getId() ); final String message = "Unable to parse first argument for option " + getOptionDescription( descriptor ); throw new ParseException( message, 0 ); } else { _option.addArgument( token.getValue() ); } } else //2nd argument { final StringBuilder sb = new StringBuilder(); _ch = getChar(); if ( _argIndex != _argIndexForMultiArg && _ch != 0 ) { _lastChar = _ch; } while ( _argIndex == _argIndexForMultiArg ) { sb.append( _ch ); _ch = getChar(); } final String argument = sb.toString(); //System.out.println( "Argument:" + argument ); _option.addArgument( argument ); addOption( _option ); _option = null; _state = STATE_NORMAL; } } } /** * Parse Options from Normal mode. */ private void parseNormal() throws ParseException { if ( '-' != _ch ) { //Parse the arguments that are not options final String argument = nextToken( NULL_SEPARATORS ).getValue(); addOption( new CLOption( argument ) ); _state = STATE_NORMAL; } else { getChar(); // strip the - if ( 0 == peekAtChar() ) { throw new ParseException( "Malformed option -", 0 ); } else { _ch = peekAtChar(); //if it is a short option then parse it else ... if ( '-' != _ch ) { parseShortOption(); } else { getChar(); // strip the - //-- sequence .. it can either mean a change of state //to STATE_NO_OPTIONS or else a long option if ( 0 == peekAtChar() ) { getChar(); _state = STATE_NO_OPTIONS; } else { //its a long option final String optionName = nextToken( ARG_SEPARATORS ).getValue(); final CLOptionDescriptor descriptor = getDescriptorFor( optionName ); _isLong = true; parseOption( descriptor, "--" + optionName ); } } } } } /** * Build the _optionIndex lookup map for the parsed options. */ private void buildOptionIndex() { final int size = _options.size(); _id2Option = new HashMap<Integer, CLOption>( size * 2 ); _name2Option = new HashMap<String, CLOption>( size * 2 ); for ( final CLOption option : _options ) { final CLOptionDescriptor descriptor = getDescriptorFor( option.getId() ); _id2Option.put( option.getId(), option ); if ( null != descriptor && null != descriptor.getName() ) { _name2Option.put( descriptor.getName(), option ); } } } }
package org.ringingmaster.engine; //TODO where should this live? import org.ringingmaster.engine.method.Bell; import org.ringingmaster.engine.notation.Place; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import static com.google.common.base.Preconditions.checkArgument; /** * Represents the number of bells in a notation / method type. * * @author Steve Lake * */ public enum NumberOfBells implements Iterable<Place>, Comparable<NumberOfBells> { BELLS_3(3, "Singles"), BELLS_4(4, "Minimus"), BELLS_5(5, "Doubles"), BELLS_6(6, "Minor"), BELLS_7(7, "Triples"), BELLS_8(8, "Major"), BELLS_9(9, "Caters"), BELLS_10(10, "Royal"), BELLS_11(11, "Cinques"), BELLS_12(12, "Maximus"), BELLS_13(13, "Sextuples"), BELLS_14(14, "Fourteen"), BELLS_15(15, "Septuples"), BELLS_16(16, "Sixteen"), BELLS_17(17, "Octuples"), BELLS_18(18, "Eighteen"), BELLS_19(19, "Ninteen"), BELLS_20(20, "Twenty"), BELLS_21(21, "Twenty-one"), BELLS_22(22, "Twenty-two"), BELLS_23(23, "Twenty-three"), BELLS_24(24, "Twenty-four"), BELLS_25(25, "Twenty-five"), BELLS_26(26, "Twenty-six"), BELLS_27(27, "Twenty-seven"), BELLS_28(28, "Twenty-eight"), BELLS_29(29, "Twenty-nine"), BELLS_30(30, "Thirty"); private static Map<Integer, NumberOfBells> entity = new HashMap<>(); static { for(final NumberOfBells value : NumberOfBells.values()) { entity.put(value.bellCount, value); } } private final String name; private final String displayString; private final int bellCount; private final Bell tenor; private final Place tenorPlace; NumberOfBells(final int bellCount, final String name) { checkArgument(bellCount > 0); this.name = name; checkArgument(name.length() > 0); this.bellCount = bellCount; this.tenor = Bell.valueOf(bellCount-1); this.tenorPlace = Place.valueOf(bellCount-1); this.displayString = name + " (" + bellCount + ")"; } /** * Get the 1 based integer number of bells. e.g. For BELLS_8 return 8 * @return int */ @Deprecated //TODO should this be replaced with a compareto? public int toInt() { return bellCount; } public Bell getTenor() { return tenor; } public Place getTenorPlace() { return tenorPlace; } public String getName() { return name; } public String getDisplayString() { return displayString; } public boolean isEven() { return (bellCount % 2) == 0; } public static NumberOfBells valueOf(final int bellCount) { return entity.get(bellCount); } @Override public Iterator<Place> iterator() { return new Iterator<Place>() { int notationPlaceIndex = 0; @Override public boolean hasNext() { return notationPlaceIndex < bellCount; } @Override public Place next() { return Place.valueOf(notationPlaceIndex++); } @Override public void remove() { throw new UnsupportedOperationException("NumberOfBells.iterator() does not support remove()"); } }; } @Override public String toString() { return getDisplayString(); } }
package permafrost.tundra.data; import com.wm.data.IData; import com.wm.data.IDataCursor; import com.wm.data.IDataFactory; import com.wm.data.IDataPortable; import com.wm.data.IDataUtil; import com.wm.util.Table; import com.wm.util.coder.IDataCodable; import com.wm.util.coder.ValuesCodable; import permafrost.tundra.io.StreamHelper; import permafrost.tundra.lang.ArrayHelper; import permafrost.tundra.lang.CharsetHelper; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.StringWriter; import java.math.BigDecimal; import java.math.BigInteger; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonArrayBuilder; import javax.json.JsonNumber; import javax.json.JsonObject; import javax.json.JsonObjectBuilder; import javax.json.JsonReader; import javax.json.JsonReaderFactory; import javax.json.JsonString; import javax.json.JsonStructure; import javax.json.JsonValue; import javax.json.JsonWriter; /** * Deserializes and serializes IData objects from and to JSON. */ public class IDataJSONParser extends IDataTextParser { /** * Initialization on demand holder idiom. */ private static class Holder { /** * The singleton instance of the class. */ private static final IDataJSONParser INSTANCE = new IDataJSONParser(); } /** * Disallow instantiation of this class. */ private IDataJSONParser() {} /** * Returns the singleton instance of this class. * * @return The singleton instance of this class. */ public static IDataJSONParser getInstance() { return Holder.INSTANCE; } /** * Encodes the given IData document as JSON to the given output stream. * * @param outputStream The stream to write the encoded IData to. * @param document The IData document to be encoded. * @param charset The character set to use. * @throws IOException If there is a problem writing to the stream. */ public void encode(OutputStream outputStream, IData document, Charset charset) throws IOException { StreamHelper.copy(StreamHelper.normalize(encodeToString(document), charset), outputStream); } /** * Returns an IData representation of the JSON data in the given input stream. * * @param inputStream The input stream to be decoded. * @param charset The character set to use. * @return An IData representation of the given input stream data. * @throws IOException If there is a problem reading from the stream. */ public IData decode(InputStream inputStream, Charset charset) throws IOException { JsonReaderFactory factory = Json.createReaderFactory(null); JsonReader reader = factory.createReader(inputStream, CharsetHelper.normalize(charset)); JsonStructure structure = reader.read(); reader.close(); Object object = fromJsonValue(structure); IData output = null; if (object instanceof IData) { output = (IData)object; } else if (object instanceof Object[]) { output = IDataFactory.create(); IDataCursor cursor = output.getCursor(); IDataUtil.put(cursor, "recordWithNoID", object); } return output; } /** * The MIME media type for JSON. * * @return JSON MIME media type. */ public String getContentType() { return "application/json"; } /** * Converts an JSON value to an appropriate webMethods compatible representation. * * @param input The JSON value to convert. * @return The converted Object. */ protected static Object fromJsonValue(JsonValue input) { Object output = null; if (input != null) { JsonValue.ValueType type = input.getValueType(); if (type == JsonValue.ValueType.OBJECT) { output = fromJsonObject((JsonObject)input); } else if (type == JsonValue.ValueType.ARRAY) { output = fromJsonArray((JsonArray)input); } else if (type == JsonValue.ValueType.TRUE) { output = Boolean.TRUE; } else if (type == JsonValue.ValueType.FALSE) { output = Boolean.FALSE; } else if (type == JsonValue.ValueType.NUMBER) { output = fromJsonNumber((JsonNumber)input); } else if (type == JsonValue.ValueType.STRING) { output = fromJsonString((JsonString)input); } else if (type != JsonValue.ValueType.NULL) { throw new IllegalArgumentException("Unexpected JSON value type: " + type.toString()); } } return output; } /** * Converts a JSON string to an appropriate webMethods compatible representation. * * @param input The JSON string to convert. * @return The converted Object. */ protected static Object fromJsonString(JsonString input) { return input.getString(); } /** * Converts a JSON number to an appropriate webMethods compatible representation. * * @param input The JSON number to convert. * @return The converted Object. */ protected static Object fromJsonNumber(JsonNumber input) { Object output; if (input.isIntegral()) { output = input.longValue(); } else { output = input.doubleValue(); } return output; } /** * Converts a JSON object to an IData document. * * @param input The JSON object to be converted. * @return The converted IData document. */ protected static IData fromJsonObject(JsonObject input) { if (input == null) return null; Iterator<String> iterator = input.keySet().iterator(); IData output = IDataFactory.create(); IDataCursor cursor = output.getCursor(); while (iterator.hasNext()) { String key = iterator.next(); JsonValue value = input.get(key); IDataUtil.put(cursor, key, fromJsonValue(value)); } cursor.destroy(); return output; } /** * Converts a JSON array to an Object[]. * * @param input The JSON array to convert. * @return The converted Object[]. */ protected static Object[] fromJsonArray(JsonArray input) { if (input == null) return null; List<Object> output = new ArrayList<Object>(input.size()); for(JsonValue item : input) { Object object = fromJsonValue(item); output.add(object); } return ArrayHelper.normalize(output); } /** * Returns a JSON representation of the given IData object. * * @param input The IData to convert to JSON. * @return The JSON representation of the IData. */ @Override public String encodeToString(IData input) throws IOException { StringWriter stringWriter = new StringWriter(); JsonWriter writer = Json.createWriter(stringWriter); IDataCursor cursor = input.getCursor(); Object[] array = IDataUtil.getObjectArray(cursor, "recordWithNoID"); cursor.destroy(); if (array != null) { writer.write(toJsonArray(array)); } else { writer.write(toJsonObject(input)); } writer.close(); return stringWriter.toString(); } /** * Converts an IData document to a JSON object. * * @param input An IData document. * @return A JSON object. */ protected static JsonObject toJsonObject(IData input) { JsonObjectBuilder builder = Json.createObjectBuilder(); if (input != null) { IDataCursor cursor = input.getCursor(); while (cursor.next()) { String key = cursor.getKey(); Object value = cursor.getValue(); if (value == null) { builder.addNull(key); } else if (value instanceof IData[] || value instanceof Table || value instanceof IDataCodable[] || value instanceof IDataPortable[] || value instanceof ValuesCodable[]) { builder.add(key, toJsonArray(IDataHelper.toIDataArray(value))); } else if (value instanceof IData || value instanceof IDataCodable || value instanceof IDataPortable || value instanceof ValuesCodable) { builder.add(key, toJsonObject(IDataHelper.toIData(value))); } else if (value instanceof Object[]) { builder.add(key, toJsonArray((Object[])value)); } else if (value instanceof Boolean) { builder.add(key, ((Boolean)value)); } else if (value instanceof Integer) { builder.add(key, ((Integer)value).intValue()); } else if (value instanceof Long) { builder.add(key, ((Long)value).longValue()); } else if (value instanceof BigInteger) { builder.add(key, (BigInteger)value); } else if (value instanceof Float) { builder.add(key, ((Float)value)); } else if (value instanceof Double) { builder.add(key, ((Double)value)); } else if (value instanceof BigDecimal) { builder.add(key, (BigDecimal)value); } else { builder.add(key, value.toString()); } } } return builder.build(); } /** * Converts an Object[] to a JSON array. * * @param input An Object[] to be converted. * @return A JSON array. */ protected static JsonArray toJsonArray(Object[] input) { JsonArrayBuilder builder = Json.createArrayBuilder(); if (input != null) { for (Object value : input) { if (value == null) { builder.addNull(); } else if (value instanceof IData[] || value instanceof Table || value instanceof IDataCodable[] || value instanceof IDataPortable[] || value instanceof ValuesCodable[]) { builder.add(toJsonArray(IDataHelper.toIDataArray(value))); } else if (value instanceof IData || value instanceof IDataCodable || value instanceof IDataPortable || value instanceof ValuesCodable) { builder.add(toJsonObject(IDataHelper.toIData(value))); } else if (value instanceof Object[]) { builder.add(toJsonArray((Object[])value)); } else if (value instanceof Boolean) { builder.add(((Boolean)value)); } else if (value instanceof Integer) { builder.add(((Integer)value).intValue()); } else if (value instanceof Long) { builder.add(((Long)value).longValue()); } else if (value instanceof BigInteger) { builder.add((BigInteger)value); } else if (value instanceof Float) { builder.add(((Float)value)); } else if (value instanceof Double) { builder.add(((Double)value)); } else if (value instanceof BigDecimal) { builder.add((BigDecimal)value); } else { builder.add(value.toString()); } } } return builder.build(); } }
package se.claremont.autotest.common; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; public class LogFolder { public static String testRunLogFolder = null; //Used for test case logging @SuppressWarnings("FieldCanBeLocal") private static String baseLogFolder = null; //Read from Settings /** * Sets the values to run time values. * * @param testSetName The name of the testSet. Normally used to get test case logs in correct folder */ public static void setLogFolder(String testSetName){ if(testRunLogFolder == null){ baseLogFolder = TestRun.settings.getValue(Settings.SettingParameters.BASE_LOG_FOLDER); if(!baseLogFolder.endsWith("\\") || !baseLogFolder.endsWith("/")){ baseLogFolder = baseLogFolder + "\\"; } testRunLogFolder = baseLogFolder.replace("\\", File.separator).replace("/", File.separator) + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + "_" + testSetName + File.separator; } } }
package seedu.address.commons.core; import java.awt.Point; import java.io.Serializable; import java.util.Objects; /** * A Serializable class that contains the GUI settings. */ public class GuiSettings implements Serializable { private static final double DEFAULT_HEIGHT = 600; private static final double DEFAULT_WIDTH = 740; private double windowWidth; private double windowHeight; private Point windowCoordinates; public GuiSettings() { windowWidth = DEFAULT_WIDTH; windowHeight = DEFAULT_HEIGHT; windowCoordinates = null; // null represent no coordinates } public GuiSettings(double windowWidth, double windowHeight, int xPosition, int yPosition) { this.windowWidth = windowWidth; this.windowHeight = windowHeight; windowCoordinates = new Point(xPosition, yPosition); } public double getWindowWidth() { return windowWidth; } public double getWindowHeight() { return windowHeight; } public Point getWindowCoordinates() { return windowCoordinates; } @Override public boolean equals(Object other) { if (other == this) { return true; } if (!(other instanceof GuiSettings)) { //this handles null as well. return false; } GuiSettings o = (GuiSettings) other; return windowWidth == o.windowWidth && windowHeight == o.windowHeight && Objects.equals(windowCoordinates.x, o.windowCoordinates.x) && Objects.equals(windowCoordinates.y, o.windowCoordinates.y); } @Override public int hashCode() { return Objects.hash(windowWidth, windowHeight, windowCoordinates); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Width : " + windowWidth + "\n"); sb.append("Height : " + windowHeight + "\n"); sb.append("Position : " + windowCoordinates); return sb.toString(); } }
package seedu.taskboss.model.task; import seedu.taskboss.model.category.UniqueCategoryList; /** * A read-only immutable interface for a Task in TaskBoss. * Implementations should guarantee: details are present and not null, field values are validated. */ public interface ReadOnlyTask { Name getName(); PriorityLevel getPriorityLevel(); Information getInformation(); DateTime getStartDateTime(); DateTime getEndDateTime(); Recurrence getRecurrence(); boolean isRecurring(); /** * The returned CategoryList is a deep copy of the internal CategoryList, * changes on the returned list will not affect the task's internal categories. */ UniqueCategoryList getCategories(); /** * Returns true if both have the same state. (interfaces cannot override .equals) */ default boolean isSameStateAs(ReadOnlyTask other) { return other == this // short circuit if same object || (other != null // this is first to avoid NPE below && other.getName().equals(this.getName()) // state checks here onwards && other.getPriorityLevel().equals(this.getPriorityLevel()) && other.getStartDateTime().equals(this.getStartDateTime()) && other.getEndDateTime().equals(this.getEndDateTime()) && other.getInformation().equals(this.getInformation())) && other.getRecurrence().equals(this.getRecurrence()) && other.getCategories().equals(this.getCategories()); } //@@author A0147990R /** * Formats the task as text, showing all contact details. */ default String getAsText() { final StringBuilder builder = new StringBuilder(); builder.append(getName()); checkEmptyValue(builder, " Priority Level: ", getPriorityLevel().value); checkEmptyValue(builder, " Start Date: ", getStartDateTime().toString()); checkEmptyValue(builder, " End Date: ", getEndDateTime().toString()); checkEmptyValue(builder, " Information: ", getInformation().toString()); checkEmptyValue(builder, " Recurrence: ", getRecurrence().toString()); builder.append(" Categories: "); getCategories().forEach(builder::append); builder.append("\n"); return builder.toString(); } /** * Append the field and value to the builder if the value is not empty; */ default void checkEmptyValue(StringBuilder builder, String field, String value) { String EMPTY_STRING = ""; String PRIORITY_FIELD = " Priority Level: "; String PRIORITY_NO_VALUE = "No priority"; String RECURRENCE_FIELD = " Recurrence: "; String RECURRENCE_NONE = "NONE"; //don't append 'no priority' value if (field.equals(PRIORITY_FIELD) && value.equals(PRIORITY_NO_VALUE)) { return; } //don't append 'none' recurrence value if (field.equals(RECURRENCE_FIELD) && value.equals(RECURRENCE_NONE)) { return; } if (!value.equals(EMPTY_STRING)) { builder.append(field) .append(value); } } }
package six.com.crawler.work.downer; import java.io.Serializable; /** * @author six * @date 201671 3:36:49 */ public enum DownerType implements Serializable { OKHTTP(1), HTTPCLIENT(2), CHROME(3), PHANTOMJS(4), FILE(5); final int value; DownerType(int value) { this.value = value; } public int value() { return value; } public static DownerType valueOf(int type) { if (1==type) { return OKHTTP; }else if (2==type) { return HTTPCLIENT; } else if (3==type) { return CHROME; } else if (4==type) { return PHANTOMJS; } else if (5==type){ return FILE; }else { return OKHTTP; } } }
package test.api.rest.activity; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import javastrava.api.v3.model.StravaActivity; import javastrava.api.v3.model.StravaSegmentEffort; import javastrava.api.v3.model.reference.StravaResourceState; import javastrava.api.v3.service.exception.UnauthorizedException; import org.junit.Test; import test.api.model.StravaActivityTest; import test.api.rest.APITest; import test.utils.RateLimitedTestRunner; import test.utils.TestUtils; public class GetActivityTest extends APITest { /** * <p> * Test retrieval of a known {@link StravaActivity} that belongs to the authenticated user; it should be a detailed {@link StravaResourceState * representation} * </p> * * @throws Exception * * @throws UnauthorizedException * Thrown when security token is invalid */ @Test public void testGetActivity_knownActivityBelongsToAuthenticatedUser() throws Exception { RateLimitedTestRunner.run(() -> { final StravaActivity activity = api().getActivity(TestUtils.ACTIVITY_FOR_AUTHENTICATED_USER, null); assertNotNull("Returned null StravaActivity for known activity with id " + TestUtils.ACTIVITY_FOR_AUTHENTICATED_USER, activity); assertEquals("Returned activity is not a detailed representation as expected - " + activity.getResourceState(), StravaResourceState.DETAILED, activity.getResourceState()); StravaActivityTest.validateActivity(activity, TestUtils.ACTIVITY_FOR_AUTHENTICATED_USER, StravaResourceState.DETAILED); }); } /** * <p> * Test retrieval of a known {@link StravaActivity} that DOES NOT belong to the authenticated user; it should be a summary {@link StravaResourceState * representation} * </p> * * @throws Exception * * @throws UnauthorizedException * Thrown when security token is invalid */ @Test public void testGetActivity_knownActivityBelongsToUnauthenticatedUser() throws Exception { RateLimitedTestRunner.run(() -> { final StravaActivity activity = api().getActivity(TestUtils.ACTIVITY_FOR_UNAUTHENTICATED_USER, null); assertNotNull("Returned null StravaActivity for known activity with id " + TestUtils.ACTIVITY_FOR_UNAUTHENTICATED_USER, activity); assertEquals("Returned activity is not a summary representation as expected - " + activity.getResourceState(), StravaResourceState.SUMMARY, activity.getResourceState()); StravaActivityTest.validateActivity(activity, TestUtils.ACTIVITY_FOR_UNAUTHENTICATED_USER, StravaResourceState.SUMMARY); }); } /** * <p> * Test retrieval of a known {@link StravaActivity}, complete with all {@link StravaSegmentEffort efforts} * </p> * * @throws Exception * * @throws UnauthorizedException * Thrown when security token is invalid */ @Test public void testGetActivity_knownActivityWithEfforts() throws Exception { RateLimitedTestRunner.run(() -> { final StravaActivity activity = api().getActivity(TestUtils.ACTIVITY_WITH_EFFORTS, Boolean.TRUE); assertNotNull("Returned null StravaActivity for known activity with id " + TestUtils.ACTIVITY_WITH_EFFORTS, activity); assertNotNull("StravaActivity " + TestUtils.ACTIVITY_WITH_EFFORTS + " was returned but segmentEfforts is null", activity.getSegmentEfforts()); assertNotEquals("StravaActivity " + TestUtils.ACTIVITY_WITH_EFFORTS + " was returned but segmentEfforts is empty", 0, activity.getSegmentEfforts() .size()); StravaActivityTest.validateActivity(activity); }); } /** * <p> * Test retrieval of a known {@link StravaActivity}, without the non-important/hidden efforts being returned (i.e. includeAllEfforts = false) * </p> * * @throws Exception */ @Test public void testGetActivity_knownActivityWithoutEfforts() throws Exception { RateLimitedTestRunner.run(() -> { final StravaActivity activity = api().getActivity(TestUtils.ACTIVITY_WITH_EFFORTS, Boolean.FALSE); assertNotNull("Returned null StravaActivity for known activity with id " + TestUtils.ACTIVITY_WITH_EFFORTS, activity); assertNotNull("Returned null segment efforts for known activity, when they were expected", activity.getSegmentEfforts()); StravaActivityTest.validateActivity(activity, TestUtils.ACTIVITY_WITH_EFFORTS, activity.getResourceState()); }); } /** * Can we get a private activity with VIEW_PRIVATE scope * * @throws Exception */ @Test public void testGetActivity_privateAuthenticatedUser() throws Exception { RateLimitedTestRunner.run(() -> { final StravaActivity activity = APITest.createPrivateActivity("GetActivityTest.testGetActivity_privateAuthenticatedUser"); StravaActivity response = null; try { response = apiWithViewPrivate().getActivity(activity.getId(), null); } finally { forceDeleteActivity(response); } StravaActivityTest.validateActivity(response); }); } @Test public void testGetActivity_privateBelongsToOtherUser() throws Exception { RateLimitedTestRunner.run(() -> { final StravaActivity activity = api().getActivity(TestUtils.ACTIVITY_PRIVATE_OTHER_USER, null); // Should get an activity which only has an id assertNotNull(activity); final StravaActivity comparisonActivity = new StravaActivity(); comparisonActivity.setId(TestUtils.ACTIVITY_PRIVATE_OTHER_USER); comparisonActivity.setResourceState(StravaResourceState.PRIVATE); assertEquals(comparisonActivity, activity); StravaActivityTest.validateActivity(activity); }); } /** * Can we get a private activity belonging to the authenticated user, without VIEW_PRIVATE scope? * * @throws Exception */ @Test public void testGetActivity_privateNoViewPrivateScope() throws Exception { RateLimitedTestRunner.run(() -> { final StravaActivity activity = APITest.createPrivateActivity("GetActivityTest.testGetActivity_privateNoViewPrivateScope"); StravaActivity response = null; try { response = api().getActivity(activity.getId(), null); } finally { forceDeleteActivity(response); } StravaActivityTest.validateActivity(response, response.getId(), StravaResourceState.PRIVATE); }); } @Test public void testGetActivity_run() throws Exception { RateLimitedTestRunner.run(() -> { final StravaActivity activity = api().getActivity(TestUtils.ACTIVITY_RUN_OTHER_USER, null); assertNotNull(activity); StravaActivityTest.validateActivity(activity); }); } /** * <p> * Test retrieval of a non-existent {@link StravaActivity} * </p> * * <p> * Should return <code>null</code> * </p> * * @throws Exception * * @throws UnauthorizedException * Thrown when security token is invalid */ @Test public void testGetActivity_unknownActivity() throws Exception { RateLimitedTestRunner.run(() -> { final StravaActivity activity = api().getActivity(TestUtils.ACTIVITY_INVALID, null); assertNull("Got an activity for an invalid activity id " + TestUtils.ACTIVITY_INVALID, activity); }); } }
package uk.co.jemos.podam.api; import net.jcip.annotations.Immutable; import net.jcip.annotations.ThreadSafe; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.co.jemos.podam.common.*; import uk.co.jemos.podam.exceptions.PodamMockeryException; import java.lang.annotation.Annotation; import java.lang.reflect.*; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicReference; import javax.validation.Constraint; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.ws.Holder; /** * The PODAM factory implementation * * @author mtedone * * @since 1.0.0 * */ @ThreadSafe @Immutable public class PodamFactoryImpl implements PodamFactory { private static final String RESOLVING_COLLECTION_EXCEPTION_STR = "An exception occurred while resolving the collection"; private static final String MAP_CREATION_EXCEPTION_STR = "An exception occurred while creating a Map object"; private static final String UNCHECKED_STR = "unchecked"; private static final String THE_ANNOTATION_VALUE_STR = "The annotation value: "; private static final Type[] NO_TYPES = new Type[0]; private static final Object[] NO_ARGS = new Object[0]; /** Application logger */ private static final Logger LOG = LoggerFactory .getLogger(PodamFactoryImpl.class.getName()); /** * External factory to delegate production this factory cannot handle * <p> * The default is {@link NullExternalFactory}. * </p> */ private PodamFactory externalFactory = NullExternalFactory.getInstance(); /** * The strategy to use to fill data. * <p> * The default is {@link RandomDataProviderStrategy}. * </p> */ private DataProviderStrategy strategy = RandomDataProviderStrategy.getInstance(); /** * The strategy to use to introspect data. * <p> * The default is {@link DefaultClassInfoStrategy}. * </p> */ private ClassInfoStrategy classInfoStrategy = DefaultClassInfoStrategy.getInstance(); /** * Default constructor. */ public PodamFactoryImpl() { this(NullExternalFactory.getInstance(), RandomDataProviderStrategy.getInstance()); } /** * Constructor with non-default strategy * * @param strategy * The strategy to use to fill data */ public PodamFactoryImpl(DataProviderStrategy strategy) { this(NullExternalFactory.getInstance(), strategy); } /** * Constructor with non-default external factory * * @param externalFactory * External factory to delegate production this factory cannot * handle */ public PodamFactoryImpl(PodamFactory externalFactory) { this(externalFactory, RandomDataProviderStrategy.getInstance()); } /** * Full constructor. * * @param externalFactory * External factory to delegate production this factory cannot * handle * @param strategy * The strategy to use to fill data */ public PodamFactoryImpl(PodamFactory externalFactory, DataProviderStrategy strategy) { this.externalFactory = externalFactory; this.strategy = strategy; } /** * {@inheritDoc} */ @Override public <T> T manufacturePojoWithFullData(Class<T> pojoClass, Type... genericTypeArgs) { ConstructorAdaptiveComparator constructorComparator = findConstructorComparator(); constructorComparator.addHeavyClass(pojoClass); T retValue = this.manufacturePojo(pojoClass, genericTypeArgs); constructorComparator.removeHeavyClass(pojoClass); return retValue; } /** * {@inheritDoc} */ @Override public <T> T manufacturePojo(Class<T> pojoClass, Type... genericTypeArgs) { Map<Class<?>, Integer> pojos = new HashMap<Class<?>, Integer>(); pojos.put(pojoClass, 0); try { Class<?> declaringClass = null; AttributeMetadata pojoMetadata = new AttributeMetadata(pojoClass, genericTypeArgs, declaringClass); return this.manufacturePojoInternal(pojoClass, pojoMetadata, pojos, genericTypeArgs); } catch (InstantiationException e) { throw new PodamMockeryException(e.getMessage(), e); } catch (IllegalAccessException e) { throw new PodamMockeryException(e.getMessage(), e); } catch (InvocationTargetException e) { throw new PodamMockeryException(e.getMessage(), e); } catch (ClassNotFoundException e) { throw new PodamMockeryException(e.getMessage(), e); } } /** * {@inheritDoc} */ @Override public <T> T populatePojo(T pojo, Type... genericTypeArgs) { Map<Class<?>, Integer> pojos = new HashMap<Class<?>, Integer>(); pojos.put(pojo.getClass(), 0); final Map<String, Type> typeArgsMap = new HashMap<String, Type>(); Type[] genericTypeArgsExtra = fillTypeArgMap(typeArgsMap, pojo.getClass(), genericTypeArgs); try { return this.populatePojoInternal(pojo, pojos, typeArgsMap, genericTypeArgsExtra); } catch (InstantiationException e) { throw new PodamMockeryException(e.getMessage(), e); } catch (IllegalAccessException e) { throw new PodamMockeryException(e.getMessage(), e); } catch (InvocationTargetException e) { throw new PodamMockeryException(e.getMessage(), e); } catch (ClassNotFoundException e) { throw new PodamMockeryException(e.getMessage(), e); } } /** * {@inheritDoc} */ @Override public DataProviderStrategy getStrategy() { return strategy; } /** * {@inheritDoc} */ @Override public PodamFactory setStrategy(DataProviderStrategy strategy) { this.strategy = strategy; return this; } /** * {@inheritDoc} */ @Override public ClassInfoStrategy getClassStrategy() { return classInfoStrategy; } /** * {@inheritDoc} */ @Override public PodamFactory setClassStrategy(ClassInfoStrategy classInfoStrategy) { this.classInfoStrategy = classInfoStrategy; return this; } /** * {@inheritDoc} */ @Override public PodamFactory getExternalFactory() { return externalFactory; } /** * {@inheritDoc} */ @Override public PodamFactory setExternalFactory(PodamFactory externalFactory) { this.externalFactory = externalFactory; return this; } private Type[] fillTypeArgMap(final Map<String, Type> typeArgsMap, final Class<?> pojoClass, final Type[] genericTypeArgs) { TypeVariable<?>[] array = pojoClass.getTypeParameters(); List<TypeVariable<?>> typeParameters = new ArrayList<TypeVariable<?>>(Arrays.asList(array)); Iterator<TypeVariable<?>> iterator = typeParameters.iterator(); /* Removing types, which are already in typeArgsMap */ while (iterator.hasNext()) { if (typeArgsMap.containsKey(iterator.next().getName())) { iterator.remove(); } } List<Type> genericTypes = new ArrayList<Type>(Arrays.asList(genericTypeArgs)); Iterator<Type> iterator2 = genericTypes.iterator(); /* Removing types, which are type variables */ while (iterator2.hasNext()) { if (iterator2.next() instanceof TypeVariable) { iterator2.remove(); } } if (typeParameters.size() > genericTypes.size()) { String msg = pojoClass.getCanonicalName() + " is missing generic type arguments, expected " + typeParameters + " found " + Arrays.toString(genericTypeArgs); throw new IllegalStateException(msg); } int i; for (i = 0; i < typeParameters.size(); i++) { typeArgsMap.put(typeParameters.get(i).getName(), genericTypes.get(0)); genericTypes.remove(0); } Type[] genericTypeArgsExtra; if (genericTypes.size() > 0) { genericTypeArgsExtra = genericTypes.toArray(new Type[genericTypes.size()]); } else { genericTypeArgsExtra = NO_TYPES; } /* Adding types, which were specified during inheritance */ Class<?> clazz = pojoClass; while (clazz != null) { Type superType = clazz.getGenericSuperclass(); clazz = clazz.getSuperclass(); if (superType instanceof ParameterizedType) { ParameterizedType paramType = (ParameterizedType) superType; Type[] actualParamTypes = paramType.getActualTypeArguments(); TypeVariable<?>[] paramTypes = clazz.getTypeParameters(); for (i = 0; i < actualParamTypes.length && i < paramTypes.length; i++) { if (actualParamTypes[i] instanceof Class) { typeArgsMap.put(paramTypes[i].getName(), actualParamTypes[i]); } } } } return genericTypeArgsExtra; } private Object instantiatePojoWithoutConstructors( Class<?> pojoClass, Map<Class<?>, Integer> pojos, Map<String, Type> typeArgsMap, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { Object retValue = null; // If no publicly accessible constructors are available, // the best we can do is to find a constructor (e.g. // getInstance()) Method[] declaredMethods = pojoClass.getDeclaredMethods(); strategy.sort(declaredMethods); // A candidate factory method is a method which returns the // Class type // The parameters to pass to the method invocation Object[] parameterValues = null; for (Method candidateConstructor : declaredMethods) { if (!Modifier.isStatic(candidateConstructor.getModifiers()) || !candidateConstructor.getReturnType().equals(pojoClass) || retValue != null) { continue; } parameterValues = getParameterValuesForMethod(candidateConstructor, pojoClass, pojos, typeArgsMap, genericTypeArgs); try { retValue = candidateConstructor.invoke(pojoClass, parameterValues); LOG.debug("Could create an instance using " + candidateConstructor); } catch (Exception t) { LOG.debug( "PODAM could not create an instance for constructor: " + candidateConstructor + ". Will try another one...", t); } } if (retValue == null) { LOG.debug("For class {} PODAM could not possibly create" + " a value statically. Will try other means.", pojoClass); } return retValue; } /** * It resolves generic parameter type * * * @param paramType * The generic parameter type * @param typeArgsMap * A map of resolved types * @param methodGenericTypeArgs * Return value posible generic types of the generic parameter * type * @return value for class representing the generic parameter type */ private Class<?> resolveGenericParameter(Type paramType, Map<String, Type> typeArgsMap, AtomicReference<Type[]> methodGenericTypeArgs) { Class<?> parameterType = null; methodGenericTypeArgs.set(NO_TYPES); if (paramType instanceof TypeVariable<?>) { final TypeVariable<?> typeVariable = (TypeVariable<?>) paramType; final Type type = typeArgsMap.get(typeVariable.getName()); if (type != null) { parameterType = resolveGenericParameter(type, typeArgsMap, methodGenericTypeArgs); } } else if (paramType instanceof ParameterizedType) { ParameterizedType pType = (ParameterizedType) paramType; parameterType = (Class<?>) pType.getRawType(); methodGenericTypeArgs.set(pType.getActualTypeArguments()); } else if (paramType instanceof WildcardType) { WildcardType wType = (WildcardType) paramType; Type[] bounds = wType.getLowerBounds(); String msg; if (bounds != null && bounds.length > 0) { msg = "Lower bounds:"; } else { bounds = wType.getUpperBounds(); msg = "Upper bounds:"; } if (bounds != null && bounds.length > 0) { LOG.debug(msg + Arrays.toString(bounds)); parameterType = resolveGenericParameter(bounds[0], typeArgsMap, methodGenericTypeArgs); } } else if (paramType instanceof Class) { parameterType = (Class<?>) paramType; } if (parameterType == null) { LOG.warn("Unrecognized type {}. Will use Object instead", paramType); parameterType = Object.class; } return parameterType; } /** * It returns the boolean value indicated in the annotation. * * @param annotations * The collection of annotations for the annotated attribute * @param attributeMetadata * The attribute's metadata, if any, used for customisation * @return The boolean value indicated in the annotation */ private Boolean getBooleanValueForAnnotation(List<Annotation> annotations, AttributeMetadata attributeMetadata) { Boolean retValue = null; for (Annotation annotation : annotations) { if (PodamBooleanValue.class.isAssignableFrom(annotation.getClass())) { PodamBooleanValue localStrategy = (PodamBooleanValue) annotation; retValue = localStrategy.boolValue(); break; } } if (retValue == null) { retValue = strategy.getBoolean(attributeMetadata); } return retValue; } private Byte getByteValueWithinRange(List<Annotation> annotations, AttributeMetadata attributeMetadata) { Byte retValue = null; for (Annotation annotation : annotations) { if (PodamByteValue.class.isAssignableFrom(annotation.getClass())) { PodamByteValue intStrategy = (PodamByteValue) annotation; String numValueStr = intStrategy.numValue(); if (null != numValueStr && !"".equals(numValueStr)) { try { retValue = Byte.valueOf(numValueStr); } catch (NumberFormatException nfe) { String errMsg = "The precise value: " + numValueStr + " cannot be converted to a byte type. An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg, nfe); } } else { byte minValue = intStrategy.minValue(); byte maxValue = intStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getByteInRange(minValue, maxValue, attributeMetadata); } break; } } if (retValue == null) { retValue = strategy.getByte(attributeMetadata); } return retValue; } private Short getShortValueWithinRange(List<Annotation> annotations, AttributeMetadata attributeMetadata) { Short retValue = null; for (Annotation annotation : annotations) { if (PodamShortValue.class.isAssignableFrom(annotation.getClass())) { PodamShortValue shortStrategy = (PodamShortValue) annotation; String numValueStr = shortStrategy.numValue(); if (null != numValueStr && !"".equals(numValueStr)) { try { retValue = Short.valueOf(numValueStr); } catch (NumberFormatException nfe) { String errMsg = "The precise value: " + numValueStr + " cannot be converted to a short type. An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg, nfe); } } else { short minValue = shortStrategy.minValue(); short maxValue = shortStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getShortInRange(minValue, maxValue, attributeMetadata); } break; } } if (retValue == null) { retValue = strategy.getShort(attributeMetadata); } return retValue; } /** * It creates and returns a random {@link Character} value * * @param annotations * The list of annotations which might customise the return value * * @param attributeMetadata * The attribute's metadata, if any, used for customisation * * @return A random {@link Character} value */ private Character getCharacterValueWithinRange( List<Annotation> annotations, AttributeMetadata attributeMetadata) { Character retValue = null; for (Annotation annotation : annotations) { if (PodamCharValue.class.isAssignableFrom(annotation.getClass())) { PodamCharValue annotationStrategy = (PodamCharValue) annotation; char charValue = annotationStrategy.charValue(); if (charValue != ' ') { retValue = charValue; } else { char minValue = annotationStrategy.minValue(); char maxValue = annotationStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getCharacterInRange(minValue, maxValue, attributeMetadata); } break; } } if (retValue == null) { retValue = strategy.getCharacter(attributeMetadata); } return retValue; } private Integer getIntegerValueWithinRange(List<Annotation> annotations, AttributeMetadata attributeMetadata) { Integer retValue = null; for (Annotation annotation : annotations) { if (PodamIntValue.class.isAssignableFrom(annotation.getClass())) { PodamIntValue intStrategy = (PodamIntValue) annotation; String numValueStr = intStrategy.numValue(); if (null != numValueStr && !"".equals(numValueStr)) { try { retValue = Integer.valueOf(numValueStr); } catch (NumberFormatException nfe) { String errMsg = THE_ANNOTATION_VALUE_STR + numValueStr + " could not be converted to an Integer. An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg, nfe); } } else { int minValue = intStrategy.minValue(); int maxValue = intStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getIntegerInRange(minValue, maxValue, attributeMetadata); } break; } } if (retValue == null) { retValue = strategy.getInteger(attributeMetadata); } return retValue; } private Float getFloatValueWithinRange(List<Annotation> annotations, AttributeMetadata attributeMetadata) { Float retValue = null; for (Annotation annotation : annotations) { if (PodamFloatValue.class.isAssignableFrom(annotation.getClass())) { PodamFloatValue floatStrategy = (PodamFloatValue) annotation; String numValueStr = floatStrategy.numValue(); if (null != numValueStr && !"".equals(numValueStr)) { try { retValue = Float.valueOf(numValueStr); } catch (NumberFormatException nfe) { String errMsg = THE_ANNOTATION_VALUE_STR + numValueStr + " could not be converted to a Float. An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg, nfe); } } else { float minValue = floatStrategy.minValue(); float maxValue = floatStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getFloatInRange(minValue, maxValue, attributeMetadata); } break; } } if (retValue == null) { retValue = strategy.getFloat(attributeMetadata); } return retValue; } /** * It creates and returns a random {@link Double} value * * @param annotations * The list of annotations which might customise the return value * * @param attributeMetadata * The attribute's metadata, if any, used for customisation * * * @return a random {@link Double} value */ private Double getDoubleValueWithinRange(List<Annotation> annotations, AttributeMetadata attributeMetadata) { Double retValue = null; for (Annotation annotation : annotations) { if (PodamDoubleValue.class.isAssignableFrom(annotation.getClass())) { PodamDoubleValue doubleStrategy = (PodamDoubleValue) annotation; String numValueStr = doubleStrategy.numValue(); if (null != numValueStr && !"".equals(numValueStr)) { try { retValue = Double.valueOf(numValueStr); } catch (NumberFormatException nfe) { String errMsg = THE_ANNOTATION_VALUE_STR + numValueStr + " could not be converted to a Double. An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg, nfe); } } else { double minValue = doubleStrategy.minValue(); double maxValue = doubleStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getDoubleInRange(minValue, maxValue, attributeMetadata); } break; } } if (retValue == null) { retValue = strategy.getDouble(attributeMetadata); } return retValue; } private Long getLongValueWithinRange(List<Annotation> annotations, AttributeMetadata attributeMetadata) { Long retValue = null; for (Annotation annotation : annotations) { if (PodamLongValue.class.isAssignableFrom(annotation.getClass())) { PodamLongValue longStrategy = (PodamLongValue) annotation; String numValueStr = longStrategy.numValue(); if (null != numValueStr && !"".equals(numValueStr)) { try { retValue = Long.valueOf(numValueStr); } catch (NumberFormatException nfe) { String errMsg = THE_ANNOTATION_VALUE_STR + numValueStr + " could not be converted to a Long. An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg, nfe); } } else { long minValue = longStrategy.minValue(); long maxValue = longStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getLongInRange(minValue, maxValue, attributeMetadata); } break; } } if (retValue == null) { retValue = strategy.getLong(attributeMetadata); } return retValue; } /** * It attempts to resolve the given class as a wrapper class and if this is * the case it assigns a random value * * * @param boxedType * The class which might be a wrapper class * @param annotations * The attribute's annotations, if any, used for customisation * @param attributeMetadata * The attribute's metadata, if any, used for customisation * @return {@code null} if this is not a wrapper class, otherwise an Object * with the value for the wrapper class */ private Object resolveBoxedValue(Class<?> boxedType, List<Annotation> annotations, AttributeMetadata attributeMetadata) { Object retValue = null; if (boxedType.equals(Integer.class) || boxedType.equals(int.class)) { retValue = getIntegerValueWithinRange(annotations, attributeMetadata); } else if (boxedType.equals(Long.class) || boxedType.equals(long.class)) { retValue = getLongValueWithinRange(annotations, attributeMetadata); } else if (boxedType.equals(Float.class) || boxedType.equals(float.class)) { retValue = getFloatValueWithinRange(annotations, attributeMetadata); } else if (boxedType.equals(Double.class) || boxedType.equals(double.class)) { retValue = getDoubleValueWithinRange(annotations, attributeMetadata); } else if (boxedType.equals(Boolean.class) || boxedType.equals(boolean.class)) { retValue = getBooleanValueForAnnotation(annotations, attributeMetadata); } else if (boxedType.equals(Byte.class) || boxedType.equals(byte.class)) { retValue = getByteValueWithinRange(annotations, attributeMetadata); } else if (boxedType.equals(Short.class) || boxedType.equals(short.class)) { retValue = getShortValueWithinRange(annotations, attributeMetadata); } else if (boxedType.equals(Character.class) || boxedType.equals(char.class)) { retValue = getCharacterValueWithinRange(annotations, attributeMetadata); } else { throw new IllegalArgumentException( String.format("%s is unsupported wrapper type", boxedType)); } return retValue; } /** * It creates and returns an instance of the given class if at least one of * its constructors has been annotated with {@link PodamConstructor} * * @param <T> * The type of the instance to return * * @param pojoClass * The class of which an instance is required * @param pojos * How many instances of the same class have been created so far * @param typeArgsMap * a map relating the generic class arguments ("&lt;T, V&gt;" for * example) with their actual types * @param genericTypeArgs * The generic type arguments for the current generic class * instance * @return an instance of the given class if at least one of its * constructors has been annotated with {@link PodamConstructor} * @throws SecurityException * If an security was violated */ @SuppressWarnings({ UNCHECKED_STR }) private <T> T instantiatePojo(Class<T> pojoClass, Map<Class<?>, Integer> pojos, Map<String, Type> typeArgsMap, Type... genericTypeArgs) throws SecurityException { T retValue = null; Constructor<?>[] constructors = pojoClass.getConstructors(); if (constructors.length == 0 || Modifier.isAbstract(pojoClass.getModifiers())) { /* No public constructors, we will try static factory methods */ try { retValue = (T) instantiatePojoWithoutConstructors( pojoClass, pojos, typeArgsMap, genericTypeArgs); } catch (Exception e) { LOG.debug("We couldn't create an instance for pojo: " + pojoClass + " with factory methods, will " + " try non-public constructors.", e); } /* Then non-public constructors */ if (retValue == null) { constructors = pojoClass.getDeclaredConstructors(); } } if (retValue == null && constructors.length > 0) { /* We want constructor with minumum number of parameters * to speed up the creation */ strategy.sort(constructors); for (Constructor<?> constructor : constructors) { try { Object[] parameterValues = getParameterValuesForConstructor( constructor, pojoClass, pojos, typeArgsMap, genericTypeArgs); // Being a generic method we cannot be sure on the identity of // T, therefore the mismatch between the newInstance() return // value (Object) and T is acceptable, thus the SuppressWarning // annotation // Security hack if (!constructor.isAccessible()) { constructor.setAccessible(true); } retValue = (T) constructor.newInstance(parameterValues); if (retValue != null) { LOG.debug("We could create an instance with constructor: " + constructor); break; } } catch (Exception e) { LOG.debug("We couldn't create an instance for pojo: {} with" + " constructor: {}. Will try with another one.", pojoClass, constructor, e); } } } if (retValue == null) { LOG.debug("For class {} PODAM could not possibly create" + " a value. Will try other means.", pojoClass); } return retValue; } @SuppressWarnings(UNCHECKED_STR) private <T> T manufacturePojoInternal(Class<T> pojoClass, AttributeMetadata pojoMetadata, Map<Class<?>, Integer> pojos, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { LOG.debug("Manufacturing {} with parameters {}", pojoClass, Arrays.toString(genericTypeArgs)); T retValue = null; // reuse object from memoization table T objectToReuse = (T) strategy.getMemoizedObject(pojoMetadata); if (objectToReuse != null) { LOG.debug("Fetched memoized object for {}", pojoClass); return objectToReuse; } if (pojoClass.isEnum()) { int enumConstantsLength = pojoClass.getEnumConstants().length; if (enumConstantsLength > 0) { int enumIndex = strategy.getIntegerInRange(0, enumConstantsLength - 1, new AttributeMetadata(pojoClass, genericTypeArgs, pojoClass)); return pojoClass.getEnumConstants()[enumIndex]; } } if (pojoClass.isPrimitive()) { // For JDK POJOs we can't retrieve attribute name return (T) resolveBoxedValue(pojoClass, Collections.<Annotation>emptyList(), new AttributeMetadata(pojoClass, genericTypeArgs, pojoClass)); } if (pojoClass.isInterface()) { Class<T> specificClass = (Class<T>) strategy .getSpecificClass(pojoClass); if (!specificClass.equals(pojoClass)) { return this.manufacturePojoInternal(specificClass, pojoMetadata, pojos, genericTypeArgs); } else { return resortToExternalFactory( "{} is an interface. Resorting to {} external factory", pojoClass, genericTypeArgs); } } final Map<String, Type> typeArgsMap = new HashMap<String, Type>(); Type[] genericTypeArgsExtra = fillTypeArgMap(typeArgsMap, pojoClass, genericTypeArgs); try { retValue = instantiatePojo(pojoClass, pojos, typeArgsMap, genericTypeArgsExtra); } catch (SecurityException e) { throw new PodamMockeryException( "Security exception while applying introspection.", e); } if (retValue == null) { if (Modifier.isAbstract(pojoClass.getModifiers())) { Class<T> specificClass = (Class<T>) strategy .getSpecificClass(pojoClass); if (!specificClass.equals(pojoClass)) { return this.manufacturePojoInternal(specificClass, pojoMetadata, pojos, genericTypeArgs); } } return resortToExternalFactory( "Failed to manufacture {}. Resorting to {} external factory", pojoClass, genericTypeArgs); } // update memoization cache with new object // the reference is stored before properties are set so that recursive // properties can use it strategy.cacheMemoizedObject(pojoMetadata, retValue); if (retValue != null) { populatePojoInternal(retValue, pojos, typeArgsMap, genericTypeArgsExtra); } return retValue; } @SuppressWarnings(UNCHECKED_STR) private <T> T populatePojoInternal(T pojo, Map<Class<?>, Integer> pojos, Map<String, Type> typeArgsMap, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { Class<?> pojoClass = pojo.getClass(); if (pojo instanceof Collection && ((Collection<?>)pojo).size() == 0) { fillCollection((Collection<? super Object>)pojo, pojos, typeArgsMap, genericTypeArgs); } else if (pojo instanceof Map && ((Map<?,?>)pojo).size() == 0) { fillMap((Map<? super Object,? super Object>)pojo, pojos, typeArgsMap, genericTypeArgs); } Class<?>[] parameterTypes = null; Class<?> attributeType = null; ClassInfo classInfo = classInfoStrategy.getClassInfo(pojo.getClass()); Set<ClassAttribute> classAttributes = classInfo.getClassAttributes(); // According to JavaBeans standards, setters should have only // one argument Object setterArg = null; Iterator<ClassAttribute> iter = classAttributes.iterator(); while (iter.hasNext()) { ClassAttribute attribute = iter.next(); Set<Method> setters = attribute.getSetters(); if (setters.isEmpty()) { if (attribute.getGetters().isEmpty()) { iter.remove(); } continue; } else { iter.remove(); } /* We want to find setter defined the latest */ Method setter = null; for (Method current : setters) { if (setter == null || setter.getDeclaringClass().isAssignableFrom(current.getDeclaringClass())) { setter = current; } } parameterTypes = setter.getParameterTypes(); if (parameterTypes.length != 1) { LOG.warn("Skipping setter with non-single arguments {}", setter); continue; } // A class which has got an attribute to itself (e.g. // recursive hierarchies) attributeType = parameterTypes[0]; // If an attribute has been annotated with // PodamAttributeStrategy, it takes the precedence over any // other strategy. Additionally we don't pass the attribute // metadata for value customisation; if user went to the extent // of specifying a PodamAttributeStrategy annotation for an // attribute they are already customising the value assigned to // that attribute. String attributeName = PodamUtils .extractFieldNameFromSetterMethod(setter); List<Annotation> pojoAttributeAnnotations = PodamUtils.getAttributeAnnotations( attribute.getAttribute(), setter); AttributeStrategy<?> attributeStrategy = findAttributeStrategy(pojoAttributeAnnotations, attributeType); if (null != attributeStrategy) { LOG.debug("The attribute: " + attributeName + " will be filled using the following strategy: " + attributeStrategy); setterArg = returnAttributeDataStrategyValue(attributeType, attributeStrategy); } else { Type[] typeArguments = NO_TYPES; // If the parameter is a generic parameterized type resolve // the actual type arguments Type genericType = setter.getGenericParameterTypes()[0]; if (genericType instanceof ParameterizedType) { final ParameterizedType attributeParameterizedType = (ParameterizedType) genericType; typeArguments = attributeParameterizedType .getActualTypeArguments(); } else if (genericType instanceof TypeVariable) { final TypeVariable<?> typeVariable = (TypeVariable<?>) genericType; Type type = typeArgsMap.get(typeVariable.getName()); if (type instanceof ParameterizedType) { final ParameterizedType attributeParameterizedType = (ParameterizedType) type; typeArguments = attributeParameterizedType .getActualTypeArguments(); attributeType = (Class<?>) attributeParameterizedType .getRawType(); } else { attributeType = (Class<?>) type; } } AtomicReference<Type[]> typeGenericTypeArgs = new AtomicReference<Type[]>(NO_TYPES); for (int i = 0; i < typeArguments.length; i++) { if (typeArguments[i] instanceof TypeVariable) { Class<?> resolvedType = resolveGenericParameter(typeArguments[i], typeArgsMap, typeGenericTypeArgs); if (!Collection.class.isAssignableFrom(resolvedType) && !Map.class.isAssignableFrom(resolvedType)) { typeArguments[i] = resolvedType; } } } setterArg = manufactureAttributeValue(pojo, pojos, attributeType, genericType, pojoAttributeAnnotations, attributeName, typeArgsMap, typeArguments); } try { setter.invoke(pojo, setterArg); } catch(IllegalAccessException e) { LOG.warn("{} is not accessible. Setting it to accessible." + " However this is a security hack and your code" + " should really adhere to JavaBeans standards.", setter.toString()); setter.setAccessible(true); setter.invoke(pojo, setterArg); } } for (ClassAttribute readOnlyAttribute : classAttributes) { Method getter = readOnlyAttribute.getGetters().iterator().next(); if (getter != null && !getter.getReturnType().isPrimitive()) { if (getter.getGenericParameterTypes().length == 0) { Object fieldValue = null; try { fieldValue = getter.invoke(pojo, NO_ARGS); } catch(Exception e) { LOG.debug("Cannot access {}, skipping", getter); } if (fieldValue != null) { LOG.debug("Populating read-only field {}", getter); Type[] genericTypeArgsAll; Map<String, Type> paramTypeArgsMap; if (getter.getGenericReturnType() instanceof ParameterizedType) { paramTypeArgsMap = new HashMap<String, Type>(typeArgsMap); ParameterizedType paramType = (ParameterizedType) getter.getGenericReturnType(); Type[] actualTypes = paramType.getActualTypeArguments(); fillTypeArgMap(paramTypeArgsMap, getter.getReturnType(), actualTypes); genericTypeArgsAll = fillTypeArgMap(paramTypeArgsMap, getter.getReturnType(), genericTypeArgs); } else { paramTypeArgsMap = typeArgsMap; genericTypeArgsAll = genericTypeArgs; } Class<?> fieldClass = fieldValue.getClass(); Integer depth = pojos.get(fieldClass); if (depth == null) { depth = -1; } if (depth <= strategy.getMaxDepth(fieldClass)) { pojos.put(fieldClass, depth + 1); populatePojoInternal(fieldValue, pojos, paramTypeArgsMap, genericTypeArgsAll); pojos.put(fieldClass, depth); } else { LOG.warn("Loop in filling read-only field {} detected.", getter); } } } else { LOG.warn("Skipping invalid getter {}", getter); } } } // It executes any extra methods Collection<Method> extraMethods = classInfoStrategy.getExtraMethods(pojoClass); if (null != extraMethods) { for (Method extraMethod : extraMethods) { Object[] args = getParameterValuesForMethod(extraMethod, pojoClass, pojos, typeArgsMap, genericTypeArgs); extraMethod.invoke(pojo, args); } } return pojo; } private Object manufactureAttributeValue(Object pojo, Map<Class<?>, Integer> pojos, Class<?> attributeType, Type genericAttributeType, List<Annotation> annotations, String attributeName, Map<String, Type> typeArgsMap, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { Object attributeValue = null; Class<?> pojoClass = (pojo instanceof Class ? (Class<?>) pojo : pojo.getClass()); Class<?> realAttributeType; if (Object.class.equals(attributeType) && attributeType != genericAttributeType) { AtomicReference<Type[]> elementGenericTypeArgs = new AtomicReference<Type[]>(NO_TYPES); realAttributeType = resolveGenericParameter(genericAttributeType, typeArgsMap, elementGenericTypeArgs); } else { realAttributeType = attributeType; } AttributeMetadata attributeMetadata = new AttributeMetadata( attributeName, realAttributeType, genericTypeArgs, annotations, pojoClass); // Primitive type if (realAttributeType.isPrimitive() || isWrapper(realAttributeType)) { attributeValue = resolveBoxedValue(realAttributeType, annotations, attributeMetadata); // String type } else if (realAttributeType.equals(String.class)) { attributeValue = resolveStringValue(annotations, attributeMetadata); } else if (realAttributeType.isArray()) { // Array type attributeValue = resolveArrayElementValue(realAttributeType, genericAttributeType, attributeName, pojos, annotations, pojo, typeArgsMap); // Otherwise it's a different type of Object (including // the Object class) } else if (Collection.class.isAssignableFrom(realAttributeType)) { attributeValue = resolveCollectionValueWhenCollectionIsPojoAttribute( pojo, pojos, realAttributeType, attributeName, annotations, typeArgsMap, genericTypeArgs); } else if (Map.class.isAssignableFrom(realAttributeType)) { attributeValue = resolveMapValueWhenMapIsPojoAttribute(pojo, pojos, realAttributeType, attributeName, annotations, typeArgsMap, genericTypeArgs); } else if (realAttributeType.isEnum()) { // Enum type int enumConstantsLength = realAttributeType.getEnumConstants().length; if (enumConstantsLength > 0) { int enumIndex = strategy.getIntegerInRange(0, enumConstantsLength, attributeMetadata) % enumConstantsLength; attributeValue = realAttributeType.getEnumConstants()[enumIndex]; } } else if (Type.class.isAssignableFrom(realAttributeType)) { Type paremeterType = null; if (genericAttributeType instanceof ParameterizedType) { ParameterizedType parametrized = (ParameterizedType) genericAttributeType; Type[] arguments = parametrized.getActualTypeArguments(); if (arguments.length > 0) { paremeterType = arguments[0]; } } else if (realAttributeType.getTypeParameters().length > 0) { paremeterType = realAttributeType.getTypeParameters()[0]; } if (paremeterType != null) { AtomicReference<Type[]> elementGenericTypeArgs = new AtomicReference<Type[]>(NO_TYPES); attributeValue = resolveGenericParameter(paremeterType, typeArgsMap, elementGenericTypeArgs); } else { LOG.error("{} is missing generic type argument, supplied {} {}", genericAttributeType, typeArgsMap, Arrays.toString(genericTypeArgs)); } } // For any other type, we use the PODAM strategy if (attributeValue == null) { TypeVariable<?>[] typeParams = attributeType.getTypeParameters(); Type[] genericTypeArgsAll = mergeActualAndSuppliedGenericTypes( typeParams, genericTypeArgs, typeArgsMap); Integer depth = pojos.get(realAttributeType); if (depth == null) { depth = -1; } if (depth <= strategy.getMaxDepth(pojoClass)) { pojos.put(realAttributeType, depth + 1); attributeValue = this.manufacturePojoInternal( realAttributeType, attributeMetadata, pojos, genericTypeArgsAll); pojos.put(realAttributeType, depth); } else { attributeValue = resortToExternalFactory( "Loop in {} production detected. Resorting to {} external factory", realAttributeType, genericTypeArgsAll); } } return attributeValue; } /** * Finds constructor comparator from current strategy. * * @return {@link ConstructorAdaptiveComparator} of the current strategy */ private ConstructorAdaptiveComparator findConstructorComparator() { AbstractRandomDataProviderStrategy sortingStrategy; if (getStrategy() instanceof AbstractRandomDataProviderStrategy) { sortingStrategy = (AbstractRandomDataProviderStrategy) getStrategy(); } else { throw new IllegalStateException("manufacturePojoWithFullData can" + " only be used with strategies derived from" + " AbstractRandomDataProviderStrategy"); } if (sortingStrategy.getConstructorComparator() instanceof ConstructorAdaptiveComparator) { return (ConstructorAdaptiveComparator) sortingStrategy.getConstructorComparator(); } else { throw new IllegalStateException("manufacturePojoWithFullData can" + " only be used with constructor comparators derived from" + " ConstructorAdaptiveComparator"); } } /** * Delegates POJO manufacturing to an external factory * * @param <T> * The type of the instance to return * @param msg * Message to log, must contain two parameters * @param pojoClass * The class of which an instance is required * @param genericTypeArgs * The generic type arguments for the current generic class * instance * @return instance of POJO produced by external factory or null */ private <T> T resortToExternalFactory(String msg, Class<T> pojoClass, Type... genericTypeArgs) { LOG.warn(msg, pojoClass, externalFactory.getClass().getName()); ConstructorAdaptiveComparator constuctorComparator = findConstructorComparator(); if (constuctorComparator.isHeavyClass(pojoClass)) { return externalFactory.<T>manufacturePojoWithFullData(pojoClass, genericTypeArgs); } else { return externalFactory.<T>manufacturePojo(pojoClass, genericTypeArgs); } } /** * Utility to merge actual types with supplied array of generic type * substitutions * * @param actualTypes * an array of types used for field or POJO declaration * @param suppliedTypes * an array of supplied types for generic type substitution * @param typeArgsMap * a map relating the generic class arguments ("&lt;T, V&gt;" for * example) with their actual types * @return An array of merged actual and supplied types with generic types * resolved */ private Type[] mergeActualAndSuppliedGenericTypes( Type[] actualTypes, Type[] suppliedTypes, Map<String, Type> typeArgsMap) { List<Type> resolvedTypes = new ArrayList<Type>(); List<Type> substitutionTypes = new ArrayList<Type>(Arrays.asList(suppliedTypes)); for (int i = 0; i < actualTypes.length; i++) { Type type = null; if (actualTypes[i] instanceof TypeVariable) { type = typeArgsMap.get(((TypeVariable<?>)actualTypes[i]).getName()); } else if (actualTypes[i] instanceof Class) { type = actualTypes[i]; } else if (actualTypes[i] instanceof WildcardType) { AtomicReference<Type[]> methodGenericTypeArgs = new AtomicReference<Type[]>(NO_TYPES); type = resolveGenericParameter(actualTypes[i], typeArgsMap, methodGenericTypeArgs); } if (type != null) { resolvedTypes.add(type); if (!substitutionTypes.isEmpty() && substitutionTypes.get(0).equals(type)) { substitutionTypes.remove(0); } } } Type[] resolved = resolvedTypes.toArray(new Type[resolvedTypes.size()]); Type[] supplied = substitutionTypes.toArray(new Type[substitutionTypes.size()]); return mergeTypeArrays(resolved, supplied); } private String resolveStringValue(List<Annotation> annotations, AttributeMetadata attributeMetadata) throws InstantiationException, IllegalAccessException { String retValue = null; if (annotations == null || annotations.isEmpty()) { retValue = strategy.getStringValue(attributeMetadata); } else { for (Annotation annotation : annotations) { if (!PodamStringValue.class.isAssignableFrom(annotation .getClass())) { continue; } // A specific value takes precedence over the length PodamStringValue podamAnnotation = (PodamStringValue) annotation; if (podamAnnotation.strValue() != null && podamAnnotation.strValue().length() > 0) { retValue = podamAnnotation.strValue(); } else { retValue = strategy.getStringOfLength( podamAnnotation.length(), attributeMetadata); } } if (retValue == null) { retValue = strategy.getStringValue(attributeMetadata); } } return retValue; } private AttributeStrategy<?> findAttributeStrategy( List<Annotation> annotations, Class<?> attributeType) throws InstantiationException, IllegalAccessException { List<Annotation> localAnnotations = new ArrayList<Annotation>(annotations); Iterator<Annotation> iter = localAnnotations.iterator(); while (iter.hasNext()) { Annotation annotation = iter.next(); if (annotation instanceof PodamStrategyValue) { PodamStrategyValue strategyAnnotation = (PodamStrategyValue) annotation; return strategyAnnotation.value().newInstance(); } /* Find real class out of proxy */ Class<? extends Annotation> annotationClass = annotation.getClass(); if (Proxy.isProxyClass(annotationClass)) { Class<?>[] interfaces = annotationClass.getInterfaces(); if (interfaces.length == 1) { @SuppressWarnings("unchecked") Class<? extends Annotation> tmp = (Class<? extends Annotation>) interfaces[0]; annotationClass = tmp; } } Class<AttributeStrategy<?>> attrStrategyClass; if ((attrStrategyClass = strategy.getStrategyForAnnotation(annotationClass)) != null) { return attrStrategyClass.newInstance(); } if (annotation.annotationType().getAnnotation(Constraint.class) != null) { if (annotation instanceof NotNull) { /* We don't need to do anything for NotNull constraint */ iter.remove(); } else if (!NotNull.class.getPackage().equals(annotationClass.getPackage())) { LOG.warn("Please, registrer AttributeStratergy for custom " + "constraint {}, in DataProviderStrategy! Value " + "will be left to null", annotation); } } else { iter.remove(); } } AttributeStrategy<?> retValue = null; if (!localAnnotations.isEmpty() && !Collection.class.isAssignableFrom(attributeType) && !Map.class.isAssignableFrom(attributeType) && !attributeType.isArray()) { retValue = new BeanValidationStrategy(localAnnotations, attributeType); } return retValue; } /** * It returns {@code true} if this class is a wrapper class, {@code false} * otherwise * * @param candidateWrapperClass * The class to check * @return {@code true} if this class is a wrapper class, {@code false} * otherwise */ private boolean isWrapper(Class<?> candidateWrapperClass) { return candidateWrapperClass.equals(Byte.class) ? true : candidateWrapperClass.equals(Boolean.class) ? true : candidateWrapperClass.equals(Character.class) ? true : candidateWrapperClass.equals(Short.class) ? true : candidateWrapperClass .equals(Integer.class) ? true : candidateWrapperClass .equals(Long.class) ? true : candidateWrapperClass .equals(Float.class) ? true : candidateWrapperClass .equals(Double.class) ? true : false; } private Collection<? super Object> resolveCollectionValueWhenCollectionIsPojoAttribute( Object pojo, Map<Class<?>, Integer> pojos, Class<?> collectionType, String attributeName, List<Annotation> annotations, Map<String, Type> typeArgsMap, Type... genericTypeArgs) { // This needs to be generic because collections can be of any type Collection<? super Object> retValue = null; if (null != pojo && null != attributeName) { retValue = PodamUtils.getFieldValue(pojo, attributeName); } retValue = resolveCollectionType(collectionType, retValue); if (null == retValue) { return null; } try { Class<?> typeClass = null; AtomicReference<Type[]> elementGenericTypeArgs = new AtomicReference<Type[]>( NO_TYPES); if (genericTypeArgs == null || genericTypeArgs.length == 0) { LOG.warn("The collection attribute: " + attributeName + " does not have a type. We will assume Object for you"); // Support for non-generified collections typeClass = Object.class; } else { Type actualTypeArgument = genericTypeArgs[0]; typeClass = resolveGenericParameter(actualTypeArgument, typeArgsMap, elementGenericTypeArgs); } fillCollection(pojos, annotations, attributeName, retValue, typeClass, elementGenericTypeArgs.get()); } catch (SecurityException e) { throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, e); } catch (IllegalArgumentException e) { throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, e); } catch (InstantiationException e) { throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, e); } catch (IllegalAccessException e) { throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, e); } catch (ClassNotFoundException e) { throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, e); } catch (InvocationTargetException e) { throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, e); } return retValue; } private void fillCollection(Collection<? super Object> collection, Map<Class<?>, Integer> pojos, Map<String, Type> typeArgsMap, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { Class<?> pojoClass = collection.getClass(); Annotation[] annotations = collection.getClass().getAnnotations(); AtomicReference<Type[]> elementGenericTypeArgs = new AtomicReference<Type[]>( NO_TYPES); Class<?> collectionClass = pojoClass; Type[] typeParams = collectionClass.getTypeParameters(); main : while (typeParams.length < 1) { for (Type genericIface : collectionClass.getGenericInterfaces()) { Class<?> clazz = resolveGenericParameter(genericIface, typeArgsMap, elementGenericTypeArgs); if (Collection.class.isAssignableFrom(clazz)) { collectionClass = clazz; typeParams = elementGenericTypeArgs.get(); continue main; } } Type type = collectionClass.getGenericSuperclass(); if (type != null) { Class<?> clazz = resolveGenericParameter(type, typeArgsMap, elementGenericTypeArgs); if (Collection.class.isAssignableFrom(clazz)) { collectionClass = clazz; typeParams = elementGenericTypeArgs.get(); continue main; } } if (Collection.class.equals(collectionClass)) { LOG.warn("Collection {} doesn't have generic types," + "will use Object instead", pojoClass); typeParams = new Type[] { Object.class }; } } Class<?> elementTypeClass = resolveGenericParameter(typeParams[0], typeArgsMap, elementGenericTypeArgs); Type[] elementGenericArgs = mergeTypeArrays(elementGenericTypeArgs.get(), genericTypeArgs); String attributeName = null; fillCollection(pojos, Arrays.asList(annotations), attributeName, collection, elementTypeClass, elementGenericArgs); } private void fillCollection(Map<Class<?>, Integer> pojos, List<Annotation> annotations, String attributeName, Collection<? super Object> collection, Class<?> collectionElementType, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { // If the user defined a strategy to fill the collection elements, // we use it Holder<AttributeStrategy<?>> elementStrategyHolder = new Holder<AttributeStrategy<?>>(); Holder<AttributeStrategy<?>> keyStrategyHolder = null; Integer nbrElements = findCollectionSize(annotations, collectionElementType, elementStrategyHolder, keyStrategyHolder); AttributeStrategy<?> elementStrategy = elementStrategyHolder.value; try { if (collection.size() > nbrElements) { collection.clear(); } for (int i = collection.size(); i < nbrElements; i++) { // The default Object element; if (null != elementStrategy && (elementStrategy instanceof ObjectStrategy) && Object.class.equals(collectionElementType)) { LOG.debug("Element strategy is ObjectStrategy and collection element is of type Object: using the ObjectStrategy strategy"); element = elementStrategy.getValue(); } else if (null != elementStrategy && !(elementStrategy instanceof ObjectStrategy)) { LOG.debug("Collection elements will be filled using the following strategy: " + elementStrategy); element = returnAttributeDataStrategyValue( collectionElementType, elementStrategy); } else { Map<String, Type> nullTypeArgsMap = new HashMap<String, Type>(); element = manufactureAttributeValue(collection, pojos, collectionElementType, collectionElementType, annotations, attributeName, nullTypeArgsMap, genericTypeArgs); } collection.add(element); } } catch (UnsupportedOperationException e) { LOG.warn("Cannot fill immutable collection {}", collection.getClass()); } } private Map<? super Object, ? super Object> resolveMapValueWhenMapIsPojoAttribute( Object pojo, Map<Class<?>, Integer> pojos, Class<?> attributeType, String attributeName, List<Annotation> annotations, Map<String, Type> typeArgsMap, Type... genericTypeArgs) { Map<? super Object, ? super Object> retValue = null; if (null != pojo && null != attributeName) { retValue = PodamUtils.getFieldValue(pojo, attributeName); } retValue = resolveMapType(attributeType, retValue); if (null == retValue) { return null; } try { Class<?> keyClass = null; Class<?> elementClass = null; AtomicReference<Type[]> keyGenericTypeArgs = new AtomicReference<Type[]>( NO_TYPES); AtomicReference<Type[]> elementGenericTypeArgs = new AtomicReference<Type[]>( NO_TYPES); if (genericTypeArgs == null || genericTypeArgs.length == 0) { LOG.warn("Map attribute: " + attributeName + " is non-generic. We will assume a Map<Object, Object> for you."); keyClass = Object.class; elementClass = Object.class; } else { // Expected only key, value type if (genericTypeArgs.length != 2) { throw new IllegalStateException( "In a Map only key value generic type are expected."); } Type[] actualTypeArguments = genericTypeArgs; keyClass = resolveGenericParameter(actualTypeArguments[0], typeArgsMap, keyGenericTypeArgs); elementClass = resolveGenericParameter(actualTypeArguments[1], typeArgsMap, elementGenericTypeArgs); } MapArguments mapArguments = new MapArguments(); mapArguments.setAttributeName(attributeName); mapArguments.setPojos(pojos); mapArguments.setAnnotations(annotations); mapArguments.setMapToBeFilled(retValue); mapArguments.setKeyClass(keyClass); mapArguments.setElementClass(elementClass); mapArguments.setKeyGenericTypeArgs(keyGenericTypeArgs.get()); mapArguments .setElementGenericTypeArgs(elementGenericTypeArgs.get()); fillMap(mapArguments); } catch (InstantiationException e) { throw new PodamMockeryException(MAP_CREATION_EXCEPTION_STR, e); } catch (IllegalAccessException e) { throw new PodamMockeryException(MAP_CREATION_EXCEPTION_STR, e); } catch (SecurityException e) { throw new PodamMockeryException(MAP_CREATION_EXCEPTION_STR, e); } catch (ClassNotFoundException e) { throw new PodamMockeryException(MAP_CREATION_EXCEPTION_STR, e); } catch (InvocationTargetException e) { throw new PodamMockeryException(MAP_CREATION_EXCEPTION_STR, e); } return retValue; } private void fillMap(Map<? super Object, ? super Object> map, Map<Class<?>, Integer> pojos, Map<String, Type> typeArgsMap, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { Class<?> pojoClass = map.getClass(); Class<?> mapClass = pojoClass; AtomicReference<Type[]> elementGenericTypeArgs = new AtomicReference<Type[]>( NO_TYPES); Type[] typeParams = mapClass.getTypeParameters(); main : while (typeParams.length < 2) { for (Type genericIface : mapClass.getGenericInterfaces()) { Class<?> clazz = resolveGenericParameter(genericIface, typeArgsMap, elementGenericTypeArgs); if (Map.class.isAssignableFrom(clazz)) { typeParams = elementGenericTypeArgs.get(); mapClass = clazz; continue main; } } Type type = mapClass.getGenericSuperclass(); if (type != null) { Class<?> clazz = resolveGenericParameter(type, typeArgsMap, elementGenericTypeArgs); if (Map.class.isAssignableFrom(clazz)) { typeParams = elementGenericTypeArgs.get(); mapClass = clazz; continue main; } } if (Map.class.equals(mapClass)) { LOG.warn("Map {} doesn't have generic types," + "will use Object, Object instead", pojoClass); typeParams = new Type[] { Object.class, Object.class }; } } AtomicReference<Type[]> keyGenericTypeArgs = new AtomicReference<Type[]>( NO_TYPES); Class<?> keyClass = resolveGenericParameter(typeParams[0], typeArgsMap, keyGenericTypeArgs); Class<?> elementClass = resolveGenericParameter(typeParams[1], typeArgsMap, elementGenericTypeArgs); Type[] keyGenericArgs = mergeTypeArrays(keyGenericTypeArgs.get(), genericTypeArgs); Type[] elementGenericArgs = mergeTypeArrays(elementGenericTypeArgs.get(), genericTypeArgs); MapArguments mapArguments = new MapArguments(); mapArguments.setPojos(pojos); mapArguments.setAnnotations(Arrays.asList(pojoClass.getAnnotations())); mapArguments.setMapToBeFilled(map); mapArguments.setKeyClass(keyClass); mapArguments.setElementClass(elementClass); mapArguments.setKeyGenericTypeArgs(keyGenericArgs); mapArguments.setElementGenericTypeArgs(elementGenericArgs); fillMap(mapArguments); } private void fillMap(MapArguments mapArguments) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { // If the user defined a strategy to fill the collection elements, // we use it Holder<AttributeStrategy<?>> elementStrategyHolder = new Holder<AttributeStrategy<?>>(); Holder<AttributeStrategy<?>> keyStrategyHolder = new Holder<AttributeStrategy<?>>(); Integer nbrElements = findCollectionSize(mapArguments.getAnnotations(), mapArguments.getElementClass(), elementStrategyHolder, keyStrategyHolder); AttributeStrategy<?> keyStrategy = keyStrategyHolder.value; AttributeStrategy<?> elementStrategy = elementStrategyHolder.value; Map<? super Object, ? super Object> map = mapArguments.getMapToBeFilled(); try { if (map.size() > nbrElements) { map.clear(); } for (int i = map.size(); i < nbrElements; i++) { Object keyValue = null; Object elementValue = null; MapKeyOrElementsArguments valueArguments = new MapKeyOrElementsArguments(); valueArguments.setAttributeName(mapArguments.getAttributeName()); valueArguments.setMapToBeFilled(mapArguments.getMapToBeFilled()); valueArguments.setPojos(mapArguments.getPojos()); valueArguments.setAnnotations(mapArguments.getAnnotations()); valueArguments.setKeyOrValueType(mapArguments.getKeyClass()); valueArguments.setElementStrategy(keyStrategy); valueArguments.setGenericTypeArgs(mapArguments .getKeyGenericTypeArgs()); keyValue = getMapKeyOrElementValue(valueArguments); valueArguments.setKeyOrValueType(mapArguments.getElementClass()); valueArguments.setElementStrategy(elementStrategy); valueArguments.setGenericTypeArgs(mapArguments .getElementGenericTypeArgs()); elementValue = getMapKeyOrElementValue(valueArguments); /* ConcurrentHashMap doesn't allow null values */ if (elementValue != null || !(map instanceof ConcurrentHashMap)) { map.put(keyValue, elementValue); } } } catch (UnsupportedOperationException e) { LOG.warn("Cannot fill immutable map {}", map.getClass()); } } private Object getMapKeyOrElementValue( MapKeyOrElementsArguments keyOrElementsArguments) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { Object retValue = null; if (null != keyOrElementsArguments.getElementStrategy() && ObjectStrategy.class.isAssignableFrom(keyOrElementsArguments .getElementStrategy().getClass()) && Object.class.equals(keyOrElementsArguments .getKeyOrValueType())) { LOG.debug("Element strategy is ObjectStrategy and Map key or value type is of type Object: using the ObjectStrategy strategy"); retValue = keyOrElementsArguments.getElementStrategy().getValue(); } else if (null != keyOrElementsArguments.getElementStrategy() && !ObjectStrategy.class .isAssignableFrom(keyOrElementsArguments .getElementStrategy().getClass())) { LOG.debug("Map key or value will be filled using the following strategy: " + keyOrElementsArguments.getElementStrategy()); retValue = returnAttributeDataStrategyValue( keyOrElementsArguments.getKeyOrValueType(), keyOrElementsArguments.getElementStrategy()); } else { Map<String, Type> nullTypeArgsMap = new HashMap<String, Type>(); retValue = manufactureAttributeValue( keyOrElementsArguments.getMapToBeFilled(), keyOrElementsArguments.getPojos(), keyOrElementsArguments.getKeyOrValueType(), keyOrElementsArguments.getKeyOrValueType(), keyOrElementsArguments.getAnnotations(), keyOrElementsArguments.getAttributeName(), nullTypeArgsMap, keyOrElementsArguments.getGenericTypeArgs()); } return retValue; } private Object resolveArrayElementValue(Class<?> attributeType, Type genericType, String attributeName, Map<Class<?>, Integer> pojos, List<Annotation> annotations, Object pojo, Map<String, Type> typeArgsMap) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { Class<?> componentType = null; Type genericComponentType = null; AtomicReference<Type[]> genericTypeArgs = new AtomicReference<Type[]>( NO_TYPES); if (genericType instanceof GenericArrayType) { genericComponentType = ((GenericArrayType) genericType).getGenericComponentType(); if (genericComponentType instanceof TypeVariable) { TypeVariable<?> componentTypeVariable = (TypeVariable<?>) genericComponentType; final Type resolvedType = typeArgsMap.get(componentTypeVariable.getName()); componentType = resolveGenericParameter(resolvedType, typeArgsMap, genericTypeArgs); } } else if (genericType instanceof Class) { Class<?> arrayClass = (Class<?>) genericType; genericComponentType = arrayClass.getComponentType(); } else { genericComponentType = attributeType.getComponentType(); } if (componentType == null) { componentType = attributeType.getComponentType(); } // If the user defined a strategy to fill the collection elements, // we use it Holder<AttributeStrategy<?>> elementStrategyHolder = new Holder<AttributeStrategy<?>>(); Holder<AttributeStrategy<?>> keyStrategyHolder = null; Integer nbrElements = findCollectionSize(annotations, attributeType, elementStrategyHolder, keyStrategyHolder); AttributeStrategy<?> elementStrategy = elementStrategyHolder.value; Object arrayElement = null; Object array = Array.newInstance(componentType, nbrElements); for (int i = 0; i < nbrElements; i++) { // The default if (null != elementStrategy && (elementStrategy instanceof ObjectStrategy) && Object.class.equals(componentType)) { LOG.debug("Element strategy is ObjectStrategy and array element is of type Object: using the ObjectStrategy strategy"); arrayElement = elementStrategy.getValue(); } else if (null != elementStrategy && !(elementStrategy instanceof ObjectStrategy)) { LOG.debug("Array elements will be filled using the following strategy: " + elementStrategy); arrayElement = returnAttributeDataStrategyValue(componentType, elementStrategy); } else { arrayElement = manufactureAttributeValue(array, pojos, componentType, genericComponentType, annotations, attributeName, typeArgsMap, genericTypeArgs.get()); } Array.set(array, i, arrayElement); } return array; } private Integer findCollectionSize(List<Annotation> annotations, Class<?> collectionElementType, Holder<AttributeStrategy<?>> elementStrategyHolder, Holder<AttributeStrategy<?>> keyStrategyHolder) throws InstantiationException, IllegalAccessException { // If the user defined a strategy to fill the collection elements, // we use it Size size = null; for (Annotation annotation : annotations) { if (annotation instanceof PodamCollection) { PodamCollection collectionAnnotation = (PodamCollection) annotation; if (null != elementStrategyHolder) { Class<? extends AttributeStrategy<?>> strategy = collectionAnnotation.collectionElementStrategy(); if (null == strategy || ObjectStrategy.class.isAssignableFrom(strategy)) { strategy = collectionAnnotation.mapElementStrategy(); } if (null != strategy) { elementStrategyHolder.value = strategy.newInstance(); } } if (null != keyStrategyHolder) { Class<? extends AttributeStrategy<?>> strategy = collectionAnnotation.mapKeyStrategy(); if (null != strategy) { keyStrategyHolder.value = strategy.newInstance(); } } return collectionAnnotation.nbrElements(); } else if (annotation instanceof Size) { size = (Size) annotation; } } Integer nbrElements = strategy .getNumberOfCollectionElements(collectionElementType); if (null != size) { if (nbrElements > size.max()) { nbrElements = size.max(); } if (nbrElements < size.min()) { nbrElements = size.min(); } } return nbrElements; } /** * Given a collection type it returns an instance * * <ul> * <li>The default type for a {@link List} is an {@link ArrayList}</li> * <li>The default type for a {@link Queue} is a {@link LinkedList}</li> * <li>The default type for a {@link Set} is a {@link HashSet}</li> * </ul> * * @param collectionType * The collection type * * @param defaultValue * Default value for the collection, can be null * @return an instance of the collection type or null */ private Collection<? super Object> resolveCollectionType( Class<?> collectionType, Collection<? super Object> defaultValue) { Collection<? super Object> retValue = null; // Default list and set are ArrayList and HashSet. If users // wants a particular collection flavour they have to initialise // the collection if (null != defaultValue && (defaultValue.getClass().getModifiers() & Modifier.PRIVATE) == 0) { /* Default collection, which is not immutable */ retValue = defaultValue; } else { if (Queue.class.isAssignableFrom(collectionType)) { if (collectionType.isAssignableFrom(LinkedList.class)) { retValue = new LinkedList<Object>(); } } else if (Set.class.isAssignableFrom(collectionType)) { if (collectionType.isAssignableFrom(HashSet.class)) { retValue = new HashSet<Object>(); } } else { if (collectionType.isAssignableFrom(ArrayList.class)) { retValue = new ArrayList<Object>(); } } if (null != retValue && null != defaultValue) { retValue.addAll(defaultValue); } } return retValue; } /** * It manufactures and returns a default instance for each map type * * <p> * The default implementation for a {@link ConcurrentMap} is * {@link ConcurrentHashMap} * </p> * * <p> * The default implementation for a {@link SortedMap} is a {@link TreeMap} * </p> * * <p> * The default Map is none of the above was recognised is a {@link HashMap} * </p> * * @param mapType * The attribute type implementing Map * @param defaultValue * Default value for map * @return A default instance for each map type or null * */ private Map<? super Object, ? super Object> resolveMapType( Class<?> mapType, Map<? super Object, ? super Object> defaultValue) { Map<? super Object, ? super Object> retValue = null; if (null != defaultValue && (defaultValue.getClass().getModifiers() & Modifier.PRIVATE) == 0) { /* Default map, which is not immutable */ retValue = defaultValue; } else { if (SortedMap.class.isAssignableFrom(mapType)) { if (mapType.isAssignableFrom(TreeMap.class)) { retValue = new TreeMap<Object, Object>(); } } else if (ConcurrentMap.class.isAssignableFrom(mapType)) { if (mapType.isAssignableFrom(ConcurrentHashMap.class)) { retValue = new ConcurrentHashMap<Object, Object>(); } } else { if (mapType.isAssignableFrom(HashMap.class)) { retValue = new HashMap<Object, Object>(); } } } return retValue; } private Object[] getParameterValuesForConstructor( Constructor<?> constructor, Class<?> pojoClass, Map<Class<?>, Integer> pojos, Map<String, Type> typeArgsMap, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { Object[] parameterValues; Class<?>[] parameterTypes = constructor.getParameterTypes(); if (parameterTypes.length == 0) { parameterValues = NO_ARGS; } else { parameterValues = new Object[parameterTypes.length]; Annotation[][] parameterAnnotations = constructor.getParameterAnnotations(); Type[] genericTypes = constructor.getGenericParameterTypes(); for (int idx = 0; idx < parameterTypes.length; idx++) { List<Annotation> annotations = Arrays .asList(parameterAnnotations[idx]); Type genericType = (idx < genericTypes.length) ? genericTypes[idx] : parameterTypes[idx]; parameterValues[idx] = manufactureParameterValue(pojoClass, parameterTypes[idx], genericType, annotations, typeArgsMap, pojos, genericTypeArgs); } } return parameterValues; } private Object[] getParameterValuesForMethod( Method method, Class<?> pojoClass, Map<Class<?>, Integer> pojos, Map<String, Type> typeArgsMap, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { Object[] parameterValues; Class<?>[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length == 0) { parameterValues = NO_ARGS; } else { parameterValues = new Object[parameterTypes.length]; Annotation[][] parameterAnnotations = method.getParameterAnnotations(); Type[] genericTypes = method.getGenericParameterTypes(); for (int idx = 0; idx < parameterTypes.length; idx++) { List<Annotation> annotations = Arrays .asList(parameterAnnotations[idx]); Type genericType = (idx < genericTypes.length) ? genericTypes[idx] : parameterTypes[idx]; parameterValues[idx] = manufactureParameterValue(pojoClass, parameterTypes[idx], genericType, annotations, typeArgsMap, pojos, genericTypeArgs); } } return parameterValues; } private Object manufactureParameterValue(Class<?> pojoClass, Class<?> parameterType, Type genericType, List<Annotation> annotations, final Map<String, Type> typeArgsMap, Map<Class<?>, Integer> pojos, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { Object parameterValue = null; AttributeStrategy<?> attributeStrategy = findAttributeStrategy(annotations, parameterType); if (null != attributeStrategy) { LOG.debug("The parameter: " + genericType + " will be filled using the following strategy: " + attributeStrategy); return returnAttributeDataStrategyValue(parameterType, attributeStrategy); } if (Collection.class.isAssignableFrom(parameterType)) { Collection<? super Object> defaultValue = null; Collection<? super Object> collection = resolveCollectionType( parameterType, defaultValue); if (collection != null) { Class<?> collectionElementType; AtomicReference<Type[]> collectionGenericTypeArgs = new AtomicReference<Type[]>( NO_TYPES); if (genericType instanceof ParameterizedType) { ParameterizedType pType = (ParameterizedType) genericType; Type actualTypeArgument = pType.getActualTypeArguments()[0]; collectionElementType = resolveGenericParameter( actualTypeArgument, typeArgsMap, collectionGenericTypeArgs); } else { LOG.warn("Collection parameter {} type is non-generic." + "We will assume a Collection<Object> for you.", genericType); collectionElementType = Object.class; } Type[] genericTypeArgsAll = mergeTypeArrays( collectionGenericTypeArgs.get(), genericTypeArgs); String attributeName = null; fillCollection(pojos, annotations, attributeName, collection, collectionElementType, genericTypeArgsAll); parameterValue = collection; } } else if (Map.class.isAssignableFrom(parameterType)) { Map<? super Object, ? super Object> defaultValue = null; Map<? super Object, ? super Object> map = resolveMapType(parameterType, defaultValue); if (map != null) { Class<?> keyClass; Class<?> elementClass; AtomicReference<Type[]> keyGenericTypeArgs = new AtomicReference<Type[]>( NO_TYPES); AtomicReference<Type[]> elementGenericTypeArgs = new AtomicReference<Type[]>( NO_TYPES); if (genericType instanceof ParameterizedType) { ParameterizedType pType = (ParameterizedType) genericType; Type[] actualTypeArguments = pType.getActualTypeArguments(); keyClass = resolveGenericParameter(actualTypeArguments[0], typeArgsMap, keyGenericTypeArgs); elementClass = resolveGenericParameter( actualTypeArguments[1], typeArgsMap, elementGenericTypeArgs); } else { LOG.warn("Map parameter {} type is non-generic." + "We will assume a Map<Object,Object> for you.", genericType); keyClass = Object.class; elementClass = Object.class; } Type[] genericTypeArgsAll = mergeTypeArrays( elementGenericTypeArgs.get(), genericTypeArgs); MapArguments mapArguments = new MapArguments(); mapArguments.setPojos(pojos); mapArguments.setAnnotations(annotations); mapArguments.setMapToBeFilled(map); mapArguments.setKeyClass(keyClass); mapArguments.setElementClass(elementClass); mapArguments.setKeyGenericTypeArgs(keyGenericTypeArgs.get()); mapArguments.setElementGenericTypeArgs(genericTypeArgsAll); fillMap(mapArguments); parameterValue = map; } } if (parameterValue == null) { Map<String, Type> typeArgsMapForParam; if (genericType instanceof ParameterizedType) { typeArgsMapForParam = new HashMap<String, Type>(typeArgsMap); ParameterizedType parametrizedType = (ParameterizedType) genericType; TypeVariable<?>[] argumentTypes = parameterType.getTypeParameters(); Type[] argumentGenericTypes = parametrizedType.getActualTypeArguments(); for (int k = 0; k < argumentTypes.length; k++) { if (argumentGenericTypes[k] instanceof Class) { Class<?> genericParam = (Class<?>) argumentGenericTypes[k]; typeArgsMapForParam.put(argumentTypes[k].getName(), genericParam); } } } else { typeArgsMapForParam = typeArgsMap; } String attributeName = null; parameterValue = manufactureAttributeValue(pojoClass, pojos, parameterType, genericType, annotations, attributeName, typeArgsMapForParam, genericTypeArgs); } return parameterValue; } /** * Utility method to merge two arrays * * @param original * The main array * @param extra * The additional array, optionally may be null * @return A merged array of original and extra arrays */ private Type[] mergeTypeArrays(Type[] original, Type[] extra) { Type[] merged; if (extra != null) { merged = new Type[original.length + extra.length]; System.arraycopy(original, 0, merged, 0, original.length); System.arraycopy(extra, 0, merged, original.length, extra.length); } else { merged = original; } return merged; } private Object returnAttributeDataStrategyValue(Class<?> attributeType, AttributeStrategy<?> attributeStrategy) throws IllegalArgumentException { Object retValue = attributeStrategy.getValue(); if (retValue != null) { Class<?> desiredType = attributeType.isPrimitive() ? PodamUtils.primitiveToBoxedType(attributeType) : attributeType; if (!desiredType.isAssignableFrom(retValue.getClass())) { String errMsg = "The type of the Podam Attribute Strategy is not " + attributeType.getName() + " but " + retValue.getClass().getName() + ". An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg); } } return retValue; } }
package uk.co.jemos.podam.api; import java.lang.annotation.Annotation; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.GenericArrayType; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicReference; import net.jcip.annotations.Immutable; import net.jcip.annotations.ThreadSafe; import uk.co.jemos.podam.annotations.PodamBooleanValue; import uk.co.jemos.podam.annotations.PodamByteValue; import uk.co.jemos.podam.annotations.PodamCharValue; import uk.co.jemos.podam.annotations.PodamCollection; import uk.co.jemos.podam.annotations.PodamConstructor; import uk.co.jemos.podam.annotations.PodamDoubleValue; import uk.co.jemos.podam.annotations.PodamFloatValue; import uk.co.jemos.podam.annotations.PodamIntValue; import uk.co.jemos.podam.annotations.PodamLongValue; import uk.co.jemos.podam.annotations.PodamShortValue; import uk.co.jemos.podam.annotations.PodamStrategyValue; import uk.co.jemos.podam.annotations.PodamStringValue; import uk.co.jemos.podam.annotations.strategies.ObjectStrategy; import uk.co.jemos.podam.dto.AttributeMetadata; import uk.co.jemos.podam.dto.ClassInfo; import uk.co.jemos.podam.exceptions.PodamMockeryException; import uk.co.jemos.podam.utils.PodamConstants; import uk.co.jemos.podam.utils.PodamUtils; /** * The PODAM factory implementation * * @author mtedone * * @since 1.0.0 * */ @ThreadSafe @Immutable public class PodamFactoryImpl implements PodamFactory { /** Application logger */ private final org.apache.log4j.Logger LOG = org.apache.log4j.Logger .getLogger(PodamFactoryImpl.class.getName()); /** * The strategy to use to fill data. * <p> * The default is {@link RandomDataProviderStrategy}. * </p> */ private final DataProviderStrategy strategy; private List<Class<? extends Annotation>> excludeAnnotations; /** * Default constructor. */ public PodamFactoryImpl() { this(RandomDataProviderStrategy.getInstance()); } /** * Full constructor. * * @param strategy * The strategy to use to fill data */ public PodamFactoryImpl(DataProviderStrategy strategy) { super(); this.strategy = strategy; } /** * {@inheritDoc} */ public <T> T manufacturePojo(Class<T> pojoClass, Type... genericTypeArgs) { return this.manufacturePojoInternal(pojoClass, 0, genericTypeArgs); } /** * {@inheritDoc} */ public DataProviderStrategy getStrategy() { return strategy; } /** * Fills type agruments map * <p> * This method places required and provided types for object creation * into a map, which will be used for type mapping. * </p> * * @param typeArgsMap * a map to fill * @param typeParameters * Type arguments needed for a generics object creation * @param genericTypeArgs * Type arguments provided for a generics object by caller * @return Array of unused provided generic type arguments */ private Type[] fillTypeArgMap( final Map<String, Type> typeArgsMap, final TypeVariable<?>[] typeParameters, final Type[] genericTypeArgs) { int i; for (i = 0; i < typeParameters.length; i++) { typeArgsMap.put(typeParameters[i].getName(), genericTypeArgs[i]); } Type[] genericTypeArgsExtra; if (typeParameters.length < genericTypeArgs.length) { genericTypeArgsExtra = Arrays.copyOfRange(genericTypeArgs, i, genericTypeArgs.length); } else { genericTypeArgsExtra = null; } return genericTypeArgsExtra; } private Object createNewInstanceForClassWithoutConstructors( Class<?> pojoClass, Class<?> clazz, Type... genericTypeArgs) throws IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { final TypeVariable<?>[] typeParameters = pojoClass.getTypeParameters(); if (typeParameters.length > genericTypeArgs.length) { LOG.info(pojoClass.getCanonicalName() + " is missing generic type arguments, expected " + typeParameters.length + " found " + genericTypeArgs.length + ". Returning null."); return null; } Object retValue = null; Constructor<?>[] constructors = clazz.getConstructors(); if (constructors.length == 0) { final Map<String, Type> typeArgsMap = new HashMap<String, Type>(); Type[] genericTypeArgsExtra = fillTypeArgMap(typeArgsMap, typeParameters, genericTypeArgs); if (genericTypeArgsExtra != null) { LOG.warn(String.format("Lost %d generic type arguments", genericTypeArgsExtra.length)); } // If no publicly accessible constructors are available, // the best we can do is to find a constructor (e.g. // getInstance()) Method[] declaredMethods = clazz.getDeclaredMethods(); // A candidate factory method is a method which returns the // Class type // The parameters to pass to the method invocation Object[] parameterValues = null; for (Method candidateConstructor : declaredMethods) { if (!Modifier.isStatic(candidateConstructor.getModifiers()) || !candidateConstructor.getReturnType().equals(clazz)) { continue; } // if (clazz.getName().startsWith("java.") || // clazz.getName().startsWith("javax.")) { // if (candidateConstructor.getParameterTypes().length != 0) { // continue; // return candidateConstructor.invoke(clazz, new Object[] {}); parameterValues = new Object[candidateConstructor .getParameterTypes().length]; Type[] parameterTypes = candidateConstructor .getGenericParameterTypes(); if (parameterTypes.length == 0) { // There is a factory method with no arguments retValue = candidateConstructor.invoke(clazz, new Object[] {}); } else { // This is a factory method with arguments Annotation[][] parameterAnnotations = candidateConstructor .getParameterAnnotations(); int idx = 0; for (Type paramType : parameterTypes) { AtomicReference<Type[]> methodGenericTypeArgs = new AtomicReference<Type[]>(); Class<?> parameterType = resolveGenericParameter(paramType, typeArgsMap, methodGenericTypeArgs); List<Annotation> annotations = Arrays .asList(parameterAnnotations[idx]); String attributeName = null; if (Collection.class.isAssignableFrom(parameterType)) { Collection<? super Object> listType = resolveCollectionType(parameterType); Class<?> elementType; if (paramType instanceof ParameterizedType) { elementType = (Class<?>) methodGenericTypeArgs.get()[0]; } else { elementType = Object.class; } int nbrElements = strategy .getNumberOfCollectionElements(); for (Annotation annotation : annotations) { if (annotation.annotationType().equals( PodamCollection.class)) { PodamCollection ann = (PodamCollection) annotation; nbrElements = ann.nbrElements(); } } for (int i = 0; i < nbrElements; i++) { Object attributeValue = manufactureAttributeValue( clazz, elementType, annotations, attributeName); listType.add(attributeValue); } parameterValues[idx] = listType; } else if (Map.class.isAssignableFrom(parameterType)) { Map<? super Object, ? super Object> mapType = resolveMapType(parameterType); Class<?> keyClass; Class<?> valueClass; if (paramType instanceof ParameterizedType) { keyClass = (Class<?>) methodGenericTypeArgs.get()[0]; valueClass = (Class<?>) methodGenericTypeArgs.get()[1]; } else { keyClass = Object.class; valueClass = Object.class; } int nbrElements = strategy .getNumberOfCollectionElements(); for (Annotation annotation : annotations) { if (annotation.annotationType().equals( PodamCollection.class)) { PodamCollection ann = (PodamCollection) annotation; nbrElements = ann.nbrElements(); } } for (int i = 0; i < nbrElements; i++) { Object keyValue = manufactureAttributeValue( clazz, keyClass, annotations, attributeName); Object elementValue = manufactureAttributeValue( clazz, valueClass, annotations, attributeName); mapType.put(keyValue, elementValue); } parameterValues[idx] = mapType; } else { parameterValues[idx] = manufactureAttributeValue( clazz, parameterType, annotations, attributeName, typeArgsMap, genericTypeArgs); } idx++; } } try { retValue = candidateConstructor.invoke(clazz, parameterValues); LOG.info("Could create an instance using " + candidateConstructor); break; } catch (Throwable t) { LOG.warn("PODAM could not create an instance for constructor: " + candidateConstructor + ". Will try another one..."); } } } else { // There are public constructors. We need the no-arg // one for now. boolean resolved = false; for (Constructor<?> constructor : constructors) { // if (constructor.getParameterTypes().length != 0) { // continue; try { Object[] constructorArgs = getParameterValuesForConstructor( constructor, pojoClass, genericTypeArgs); retValue = constructor.newInstance(constructorArgs); resolved = true; LOG.info("For class: " + clazz.getName() + " a valid constructor: " + constructor + " was found. PODAM will use it to create an instance."); break; } catch (Throwable t) { LOG.warn("Couldn't create attribute with constructor: " + constructor + ". Will check if other constructors are available"); } } if (!resolved) { LOG.warn("For class: " + clazz.getName() + " PODAM could not possibly create a value. This attribute will be returned as null."); } } return retValue; } /** * It resolves generic parameter type * * * @param paramType * The generic parameter type * @param typeArgsMap * A map of resolved types * @param methodGenericTypeArgs * Return value posible generic types of the generic parameter type * @return value for class representing the generic parameter type */ private Class<?> resolveGenericParameter(Type paramType, Map<String, Type> typeArgsMap, AtomicReference<Type[]> methodGenericTypeArgs) { Class<?> parameterType; methodGenericTypeArgs.set(new Type[] {}); if (paramType instanceof TypeVariable<?>) { final String typeName = ((TypeVariable<?>) paramType).getName(); final Type type = typeArgsMap.get(typeName); parameterType = resolveGenericParameter(type, typeArgsMap, methodGenericTypeArgs); } else if (paramType instanceof ParameterizedType) { ParameterizedType pType = (ParameterizedType) paramType; parameterType = (Class<?>) pType.getRawType(); methodGenericTypeArgs.set(pType.getActualTypeArguments()); } else if (paramType instanceof WildcardType) { WildcardType wType = (WildcardType) paramType; Type[] bounds = wType.getLowerBounds(); String msg; if (bounds != null && bounds.length > 0) { msg = "Lower bounds:"; } else { bounds = wType.getUpperBounds(); msg = "Upper bounds:"; } if (bounds != null && bounds.length > 0) { LOG.debug(msg + Arrays.toString(bounds)); parameterType = resolveGenericParameter(bounds[0], typeArgsMap, methodGenericTypeArgs); } else { LOG.warn("Unrecognized argument type" + wType.toString() + ". Will use Object intead"); parameterType = Object.class; } } else if (paramType instanceof Class) { parameterType = (Class<?>) paramType; } else { LOG.warn("Unrecognized argument type" + paramType.getClass().getSimpleName() + ". Will use Object intead"); parameterType = Object.class; } return parameterType; } private Object resolvePrimitiveValue(Class<?> primitiveClass, List<Annotation> annotations, AttributeMetadata attributeMetadata) { Object retValue = null; if (primitiveClass.equals(int.class)) { if (annotations.isEmpty()) { retValue = strategy.getInteger(attributeMetadata); } else { retValue = getIntegerValueWithinRange(annotations, attributeMetadata); if (retValue == null) { retValue = strategy.getInteger(attributeMetadata); } } } else if (primitiveClass.equals(long.class)) { if (annotations.isEmpty()) { retValue = strategy.getLong(attributeMetadata); } else { retValue = getLongValueWithinRange(annotations, attributeMetadata); if (retValue == null) { retValue = strategy.getLong(attributeMetadata); } } } else if (primitiveClass.equals(float.class)) { if (annotations.isEmpty()) { retValue = strategy.getFloat(attributeMetadata); } else { retValue = getFloatValueWithinRange(annotations, attributeMetadata); if (retValue == null) { retValue = strategy.getFloat(attributeMetadata); } } } else if (primitiveClass.equals(double.class)) { if (annotations.isEmpty()) { retValue = strategy.getDouble(attributeMetadata); } else { retValue = getDoubleValueWithinRange(annotations, attributeMetadata); if (retValue == null) { retValue = strategy.getDouble(attributeMetadata); } } } else if (primitiveClass.equals(boolean.class)) { if (annotations.isEmpty()) { retValue = strategy.getBoolean(attributeMetadata); } else { retValue = getBooleanValueForAnnotation(annotations); if (retValue == null) { retValue = strategy.getBoolean(attributeMetadata); } } } else if (primitiveClass.equals(byte.class)) { if (annotations.isEmpty()) { retValue = strategy.getByte(attributeMetadata); } else { retValue = getByteValueWithinRange(annotations, attributeMetadata); if (retValue == null) { retValue = strategy.getByte(attributeMetadata); } } } else if (primitiveClass.equals(short.class)) { if (annotations.isEmpty()) { retValue = strategy.getShort(attributeMetadata); } else { retValue = getShortValueWithinRange(annotations, attributeMetadata); if (retValue == null) { retValue = strategy.getShort(attributeMetadata); } } } else if (primitiveClass.equals(char.class)) { if (annotations.isEmpty()) { retValue = strategy.getCharacter(attributeMetadata); } else { retValue = getCharacterValueWithinRange(annotations, attributeMetadata); if (retValue == null) { retValue = strategy.getCharacter(attributeMetadata); } } } return retValue; } /** * It returns the boolean value indicated in the annotation. * * @param annotations * The collection of annotations for the annotated attribute * @return The boolean value indicated in the annotation */ private Boolean getBooleanValueForAnnotation(List<Annotation> annotations) { Boolean retValue = null; for (Annotation annotation : annotations) { if (PodamBooleanValue.class.isAssignableFrom(annotation.getClass())) { PodamBooleanValue strategy = (PodamBooleanValue) annotation; retValue = strategy.boolValue(); break; } } return retValue; } private Byte getByteValueWithinRange(List<Annotation> annotations, AttributeMetadata attributeMetadata) { Byte retValue = null; for (Annotation annotation : annotations) { if (PodamByteValue.class.isAssignableFrom(annotation.getClass())) { PodamByteValue intStrategy = (PodamByteValue) annotation; String numValueStr = intStrategy.numValue(); if (null != numValueStr && !"".equals(numValueStr)) { try { retValue = Byte.valueOf(numValueStr); } catch (NumberFormatException nfe) { String errMsg = "The precise value: " + numValueStr + " cannot be converted to a byte type. An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg, nfe); } } else { byte minValue = intStrategy.minValue(); byte maxValue = intStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getByteInRange(minValue, maxValue, attributeMetadata); } break; } } return retValue; } private Short getShortValueWithinRange(List<Annotation> annotations, AttributeMetadata attributeMetadata) { Short retValue = null; for (Annotation annotation : annotations) { if (PodamShortValue.class.isAssignableFrom(annotation.getClass())) { PodamShortValue shortStrategy = (PodamShortValue) annotation; String numValueStr = shortStrategy.numValue(); if (null != numValueStr && !"".equals(numValueStr)) { try { retValue = Short.valueOf(numValueStr); } catch (NumberFormatException nfe) { String errMsg = "The precise value: " + numValueStr + " cannot be converted to a short type. An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg, nfe); } } else { short minValue = shortStrategy.minValue(); short maxValue = shortStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getShortInRange(minValue, maxValue, attributeMetadata); } break; } } return retValue; } /** * It creates and returns a random {@link Character} value * * @param annotations * The list of annotations which might customise the return value * @param attributeMetadata * * @return A random {@link Character} value */ private Character getCharacterValueWithinRange( List<Annotation> annotations, AttributeMetadata attributeMetadata) { Character retValue = null; for (Annotation annotation : annotations) { if (PodamCharValue.class.isAssignableFrom(annotation.getClass())) { PodamCharValue annotationStrategy = (PodamCharValue) annotation; char charValue = annotationStrategy.charValue(); if (charValue != ' ') { retValue = charValue; } else { char minValue = annotationStrategy.minValue(); char maxValue = annotationStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getCharacterInRange(minValue, maxValue, attributeMetadata); } break; } } return retValue; } private Integer getIntegerValueWithinRange(List<Annotation> annotations, AttributeMetadata attributeMetadata) { Integer retValue = null; for (Annotation annotation : annotations) { if (PodamIntValue.class.isAssignableFrom(annotation.getClass())) { PodamIntValue intStrategy = (PodamIntValue) annotation; String numValueStr = intStrategy.numValue(); if (null != numValueStr && !"".equals(numValueStr)) { try { retValue = Integer.valueOf(numValueStr); } catch (NumberFormatException nfe) { String errMsg = "The annotation value: " + numValueStr + " could not be converted to an Integer. An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg, nfe); } } else { int minValue = intStrategy.minValue(); int maxValue = intStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getIntegerInRange(minValue, maxValue, attributeMetadata); } break; } } return retValue; } private Float getFloatValueWithinRange(List<Annotation> annotations, AttributeMetadata attributeMetadata) { Float retValue = null; for (Annotation annotation : annotations) { if (PodamFloatValue.class.isAssignableFrom(annotation.getClass())) { PodamFloatValue floatStrategy = (PodamFloatValue) annotation; String numValueStr = floatStrategy.numValue(); if (null != numValueStr && !"".equals(numValueStr)) { try { retValue = Float.valueOf(numValueStr); } catch (NumberFormatException nfe) { String errMsg = "The annotation value: " + numValueStr + " could not be converted to a Float. An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg, nfe); } } else { float minValue = floatStrategy.minValue(); float maxValue = floatStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getFloatInRange(minValue, maxValue, attributeMetadata); } break; } } return retValue; } /** * It creates and returns a random {@link Double} value * * @param annotations * The list of annotations which might customise the return value * @param attributeMetadata * * * @return a random {@link Double} value */ private Double getDoubleValueWithinRange(List<Annotation> annotations, AttributeMetadata attributeMetadata) { Double retValue = null; for (Annotation annotation : annotations) { if (PodamDoubleValue.class.isAssignableFrom(annotation.getClass())) { PodamDoubleValue doubleStrategy = (PodamDoubleValue) annotation; String numValueStr = doubleStrategy.numValue(); if (null != numValueStr && !"".equals(numValueStr)) { try { retValue = Double.valueOf(numValueStr); } catch (NumberFormatException nfe) { String errMsg = "The annotation value: " + numValueStr + " could not be converted to a Double. An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg, nfe); } } else { double minValue = doubleStrategy.minValue(); double maxValue = doubleStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getDoubleInRange(minValue, maxValue, attributeMetadata); } break; } } return retValue; } private Long getLongValueWithinRange(List<Annotation> annotations, AttributeMetadata attributeMetadata) { Long retValue = null; for (Annotation annotation : annotations) { if (PodamLongValue.class.isAssignableFrom(annotation.getClass())) { PodamLongValue longStrategy = (PodamLongValue) annotation; String numValueStr = longStrategy.numValue(); if (null != numValueStr && !"".equals(numValueStr)) { try { retValue = Long.valueOf(numValueStr); } catch (NumberFormatException nfe) { String errMsg = "The annotation value: " + numValueStr + " could not be converted to a Long. An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg, nfe); } } else { long minValue = longStrategy.minValue(); long maxValue = longStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getLongInRange(minValue, maxValue, attributeMetadata); } break; } } return retValue; } /** * It attempts to resolve the given class as a wrapper class and if this is * the case it assigns a random value * * * @param candidateWrapperClass * The class which might be a wrapper class * @param attributeMetadata * @return {@code null} if this is not a wrapper class, otherwise an Object * with the value for the wrapper class */ private Object resolveWrapperValue(Class<?> candidateWrapperClass, List<Annotation> annotations, AttributeMetadata attributeMetadata) { Object retValue = null; if (candidateWrapperClass.equals(Integer.class)) { if (annotations.isEmpty()) { retValue = strategy.getInteger(attributeMetadata); } else { retValue = getIntegerValueWithinRange(annotations, attributeMetadata); if (retValue == null) { retValue = strategy.getInteger(attributeMetadata); } } } else if (candidateWrapperClass.equals(Long.class)) { if (annotations.isEmpty()) { retValue = strategy.getLong(attributeMetadata); } else { retValue = getLongValueWithinRange(annotations, attributeMetadata); if (retValue == null) { retValue = strategy.getLong(attributeMetadata); } } } else if (candidateWrapperClass.equals(Float.class)) { if (annotations.isEmpty()) { retValue = strategy.getFloat(attributeMetadata); } else { retValue = getFloatValueWithinRange(annotations, attributeMetadata); if (retValue == null) { retValue = strategy.getFloat(attributeMetadata); } } } else if (candidateWrapperClass.equals(Double.class)) { if (annotations.isEmpty()) { retValue = strategy.getDouble(attributeMetadata); } else { retValue = getDoubleValueWithinRange(annotations, attributeMetadata); if (retValue == null) { retValue = strategy.getDouble(attributeMetadata); } } } else if (candidateWrapperClass.equals(Boolean.class)) { if (annotations.isEmpty()) { retValue = strategy.getBoolean(attributeMetadata); } else { retValue = getBooleanValueForAnnotation(annotations); if (retValue == null) { retValue = strategy.getBoolean(attributeMetadata); } } } else if (candidateWrapperClass.equals(Byte.class)) { if (annotations.isEmpty()) { retValue = strategy.getByte(attributeMetadata); } else { retValue = getByteValueWithinRange(annotations, attributeMetadata); if (retValue == null) { retValue = strategy.getByte(attributeMetadata); } } } else if (candidateWrapperClass.equals(Short.class)) { if (annotations.isEmpty()) { retValue = strategy.getShort(attributeMetadata); } else { retValue = getShortValueWithinRange(annotations, attributeMetadata); if (retValue == null) { retValue = strategy.getShort(attributeMetadata); } } } else if (candidateWrapperClass.equals(Character.class)) { if (annotations.isEmpty()) { retValue = strategy.getCharacter(attributeMetadata); } else { retValue = getCharacterValueWithinRange(annotations, attributeMetadata); if (retValue == null) { retValue = strategy.getCharacter(attributeMetadata); } } } return retValue; } @SuppressWarnings("unchecked") private <T> T resolvePojoWithoutSetters(Class<T> pojoClass, int depth, Type... genericTypeArgs) throws IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { T retValue = null; Constructor<?>[] constructors = pojoClass.getConstructors(); if (constructors.length == 0) { retValue = (T) createNewInstanceForClassWithoutConstructors( pojoClass, pojoClass); } else { // Not terribly efficient but necessary boolean podamConstructorAnnotationFound = checkIfConstructorAnnotationPresent(constructors); for (Constructor<?> constructor : constructors) { // If we know at least one constructor has been annotated with // PodamConstructor, we use it, otherwise we take our best shot if (constructor.getAnnotation(PodamConstructor.class) == null && podamConstructorAnnotationFound) { continue; } Object[] parameterValues = getParameterValuesForConstructor( constructor, pojoClass, genericTypeArgs); // Being a generic method we cannot be sure on the identify of // T, therefore the mismatch between the newInstance() return // value // (Object) and T is acceptable, thus the SuppressWarning // annotation try { retValue = (T) constructor.newInstance(parameterValues); if (retValue instanceof Collection && ((Collection)retValue).size() == 0) { LOG.info("We could create an instance with constructor: " + constructor + ", but collection is empty" + ". Will try with another one."); } else { LOG.info("We could create an instance with constructor: " + constructor); break; } } catch (Throwable t) { LOG.warn("We couldn't create an instance for pojo: " + pojoClass + " for constructor: " + constructor + ". Will try with another one."); } } } return retValue; } /** * It checks whether at least one constructor has got a * {@link PodamConstructor} annotation. * * @param constructors * The array of constructors * @return {@code true} if at least one constructor contains a * {@link PodamConstructor} annotation, {@code false} otherwise. */ private boolean checkIfConstructorAnnotationPresent( Constructor<?>[] constructors) { boolean retValue = false; for (Constructor<?> constructor : constructors) { if (constructor.getAnnotation(PodamConstructor.class) != null) { retValue = true; break; } } return retValue; } /** * Generic method which returns an instance of the given class filled with * dummy values * * @param <T> * The type for which a filled instance is required * * @param pojoClass * The name of the class for which an instance filled with values * is required * @param depth * How many times {@code dtoClass} has been found * @param genericTypeArgs * The generic type arguments for the current generic class * instance * @return An instance of <T> filled with dummy values * * @throws PodamMockeryException * if a problem occurred while creating a POJO instance or while * setting its state */ @SuppressWarnings("unchecked") private <T> T manufacturePojoInternal(Class<T> pojoClass, int depth, Type... genericTypeArgs) { try { final TypeVariable<?>[] typeParameters = pojoClass .getTypeParameters(); if (typeParameters.length > genericTypeArgs.length) { LOG.info(pojoClass.getCanonicalName() + " is missing generic type arguments, expected " + typeParameters.length + " found " + genericTypeArgs.length + ". Returning null."); return null; } T retValue = null; if (pojoClass.isPrimitive()) { // For JDK POJOs we can't retrieve attribute name ArrayList<Annotation> annotations = new ArrayList<Annotation>(); return (T) resolvePrimitiveValue(pojoClass, annotations, new AttributeMetadata(null, pojoClass, annotations)); } if (pojoClass.isInterface() || Modifier.isAbstract(pojoClass.getModifiers())) { LOG.warn("Cannot instantiate an interface or abstract class. Returning null."); return null; } ClassInfo classInfo = PodamUtils.getClassInfo(pojoClass, excludeAnnotations); if (classInfo.getClassSetters().isEmpty()) { // A rudimentary attempt to manage immutable classes (e.g. with // constructor only and final fields - no setters) return this.resolvePojoWithoutSetters(pojoClass, depth, genericTypeArgs); } // If a public no-arg constructor can be found we use that, // otherwise we try to find a non-public one and we use that. If the // class does not have a no-arg constructor we search for a suitable // constructor. Constructor<T> defaultConstructor = null; try { defaultConstructor = pojoClass.getConstructor(new Class[] {}); retValue = defaultConstructor.newInstance(); } catch (SecurityException e) { throw new PodamMockeryException( "Security exception while applying introspection.", e); } catch (NoSuchMethodException e) { try { LOG.warn("The POJO " + pojoClass + " does not have a public no-arg constructor. This violates JavaBean standards. " + "However in our kindness we'll look for an alternate public constructor " + "for you and we'll use the first we find..."); Constructor<?>[] constructors = pojoClass.getConstructors(); if (constructors == null || constructors.length == 0) { LOG.warn("No public constructors were found. " + "We'll look for a default, non-public constructor. "); defaultConstructor = pojoClass .getDeclaredConstructor(new Class[] {}); LOG.info("Will use: " + defaultConstructor); defaultConstructor.setAccessible(true); retValue = defaultConstructor.newInstance(); } else { LOG.info("Will use: " + constructors[0]); // It uses the first public constructor found Object[] parameterValuesForConstructor = getParameterValuesForConstructor( constructors[0], pojoClass, genericTypeArgs); constructors[0].setAccessible(true); retValue = (T) constructors[0] .newInstance(parameterValuesForConstructor); } } catch (SecurityException e1) { throw new PodamMockeryException( "Security exception while applying introspection.", e); } catch (NoSuchMethodException e2) { LOG.warn("No default (public or non-public) constructors were found. " + "Also no other public constructors were found. " + "Your last hope is that we find a non-public, non-default constructor."); Constructor<?>[] constructors = pojoClass .getDeclaredConstructors(); if (constructors == null || constructors.length == 0) { throw new IllegalStateException( "The POJO " + pojoClass + " appears without constructors. How is this possible? "); } LOG.info("Will use: " + constructors[0]); // It uses the first public constructor found Object[] parameterValuesForConstructor = getParameterValuesForConstructor( constructors[0], pojoClass, genericTypeArgs); constructors[0].setAccessible(true); retValue = (T) constructors[0] .newInstance(parameterValuesForConstructor); } } Class<?>[] parameterTypes = null; Class<?> attributeType = null; // According to JavaBeans standards, setters should have only // one argument Object setterArg = null; for (Method setter : classInfo.getClassSetters()) { List<Annotation> pojoAttributeAnnotations = retrieveFieldAnnotations( pojoClass, setter); String attributeName = PodamUtils .extractFieldNameFromSetterMethod(setter); parameterTypes = setter.getParameterTypes(); if (parameterTypes.length != 1) { throw new IllegalStateException( "A JavaBean setter should have only one argument"); } // A class which has got an attribute to itself (e.g. // recursive hierarchies) attributeType = parameterTypes[0]; // If an attribute has been annotated with // PodamAttributeStrategy, it takes the precedence over any // other strategy. Additionally we don't pass the attribute // metadata for value customisation; if user went to the extent // of specifying a PodamAttributeStrategy annotation for an // attribute they are already customising the value assigned to // that attribute. PodamStrategyValue attributeStrategyAnnotation = containsAttributeStrategyAnnotation(pojoAttributeAnnotations); if (null != attributeStrategyAnnotation) { AttributeStrategy<?> attributeStrategy = attributeStrategyAnnotation .value().newInstance(); if (LOG.isDebugEnabled()) { LOG.debug("The attribute: " + attributeName + " will be filled using the following strategy: " + attributeStrategy); } // TODO To pass the AttributeMetadata setterArg = returnAttributeDataStrategyValue(attributeType, attributeStrategy); } else { final Map<String, Type> typeArgsMap = new HashMap<String, Type>(); Type[] genericTypeArgsExtra = fillTypeArgMap(typeArgsMap, typeParameters, genericTypeArgs); if (genericTypeArgsExtra != null) { LOG.warn(String.format("Lost %d generic type arguments", genericTypeArgsExtra.length)); } if (attributeType.equals(pojoClass)) { if (depth < PodamConstants.MAX_DEPTH) { depth++; setterArg = this.manufacturePojoInternal( attributeType, depth); setter.invoke(retValue, setterArg); continue; } else { setterArg = createNewInstanceForClassWithoutConstructors( pojoClass, pojoClass); setter.invoke(retValue, setterArg); depth = 0; continue; } } Type[] typeArguments = new Type[] {}; // If the parameter is a generic parameterized type resolve // the actual type arguments if (setter.getGenericParameterTypes()[0] instanceof ParameterizedType) { final ParameterizedType attributeParameterizedType = (ParameterizedType) setter .getGenericParameterTypes()[0]; typeArguments = attributeParameterizedType .getActualTypeArguments(); } else if (setter.getGenericParameterTypes()[0] instanceof TypeVariable) { final TypeVariable<?> typeVariable = (TypeVariable<?>) setter .getGenericParameterTypes()[0]; Type type = typeArgsMap.get(typeVariable.getName()); if (type instanceof ParameterizedType) { final ParameterizedType attributeParameterizedType = (ParameterizedType) type; typeArguments = attributeParameterizedType .getActualTypeArguments(); attributeType = (Class<?>) attributeParameterizedType .getRawType(); } else { attributeType = (Class<?>) type; } } setterArg = manufactureAttributeValue(pojoClass, attributeType, pojoAttributeAnnotations, attributeName, typeArgsMap, typeArguments); } if (setterArg != null) { // If the setter is not public we set it to accessible or // otherwise the invocation will fail. if (!Modifier.isPublic(setter.getModifiers())) { LOG.warn("The setter: " + setter.getName() + " is not public. Setting it to accessible(true). " + "However if you have got security in place to avoid these kind of things, you will get an error"); setter.setAccessible(true); } setter.invoke(retValue, setterArg); } else { LOG.warn("Couldn't find a suitable value for attribute: " + attributeName + ". This POJO attribute will be left to null."); } } return retValue; } catch (InstantiationException e) { throw new PodamMockeryException( "An instantiation exception occurred", e); } catch (IllegalAccessException e) { throw new PodamMockeryException("An illegal access occurred", e); } catch (IllegalArgumentException e) { throw new PodamMockeryException("An illegal argument was passed", e); } catch (InvocationTargetException e) { throw new PodamMockeryException("Invocation Target Exception", e); } catch (ClassNotFoundException e) { throw new PodamMockeryException("Invocation Target Exception", e); } } private Object manufactureAttributeValue(Class<?> pojoClass, Class<?> attributeType, List<Annotation> annotations, String attributeName, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, IllegalArgumentException, ClassNotFoundException { return manufactureAttributeValue(pojoClass, attributeType, annotations, attributeName, null, genericTypeArgs); } private Object manufactureAttributeValue(Class<?> pojoClass, Class<?> attributeType, List<Annotation> annotations, String attributeName, Map<String, Type> typeArgsMap, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, IllegalArgumentException, ClassNotFoundException { Object attributeValue = null; Class<?> realAttributeType; if (genericTypeArgs.length > 0 && genericTypeArgs[0] instanceof Class && attributeType.isAssignableFrom((Class)genericTypeArgs[0])) { realAttributeType = (Class)genericTypeArgs[0]; } else { realAttributeType = attributeType; } AttributeMetadata attributeMetadata = new AttributeMetadata( attributeName, realAttributeType, annotations); if (realAttributeType.isPrimitive()) { attributeValue = resolvePrimitiveValue(realAttributeType, annotations, attributeMetadata); } else if (isWrapper(realAttributeType)) { attributeValue = resolveWrapperValue(realAttributeType, annotations, attributeMetadata); } else if (realAttributeType.equals(String.class)) { attributeValue = resolveStringValue(annotations, attributeMetadata); // Is this an array? } else if (realAttributeType.getName().startsWith("[")) { attributeValue = resolveArrayElementValue(realAttributeType, annotations, pojoClass, attributeName, typeArgsMap); // Otherwise it's a different type of Object (including // the Object class) } else if (Collection.class.isAssignableFrom(realAttributeType)) { attributeValue = resolveCollectionValueWhenCollectionIsPojoAttribute( pojoClass, realAttributeType, attributeName, annotations, typeArgsMap, genericTypeArgs); } else if (Map.class.isAssignableFrom(realAttributeType)) { attributeValue = resolveMapValueWhenMapIsPojoAttribute(pojoClass, realAttributeType, attributeName, annotations, typeArgsMap, genericTypeArgs); } else if (realAttributeType.getName().startsWith("java.") || realAttributeType.getName().startsWith("javax.")) { // For classes in the Java namespace we attempt the no-args or the // factory constructor strategy attributeValue = createNewInstanceForClassWithoutConstructors( pojoClass, realAttributeType, genericTypeArgs); } else if (realAttributeType.isEnum()) { int enumConstantsLength = realAttributeType.getEnumConstants().length; if (enumConstantsLength > 0) { int enumIndex = strategy.getIntegerInRange(0, enumConstantsLength, attributeMetadata) % enumConstantsLength; attributeValue = realAttributeType.getEnumConstants()[enumIndex]; // attributeValue = realAttributeType.getEnumConstants()[0]; } } else { // For any class not in the Java namespace, we try the PODAM // strategy attributeValue = this.manufacturePojo(realAttributeType, genericTypeArgs); } return attributeValue; } private String resolveStringValue(List<Annotation> annotations, AttributeMetadata attributeMetadata) throws InstantiationException, IllegalAccessException { String retValue = null; if (annotations == null || annotations.isEmpty()) { retValue = strategy.getStringValue(attributeMetadata); } else { for (Annotation annotation : annotations) { if (!PodamStringValue.class.isAssignableFrom(annotation .getClass())) { continue; } // A specific value takes precedence over the length PodamStringValue podamAnnotation = (PodamStringValue) annotation; if (podamAnnotation.strValue() != null && podamAnnotation.strValue().length() > 0) { retValue = podamAnnotation.strValue(); } else { retValue = strategy.getStringOfLength( podamAnnotation.length(), attributeMetadata); } } if (retValue == null) { retValue = strategy.getStringValue(attributeMetadata); } } return retValue; } /** * It returns a {@link PodamStrategyValue} if one was specified, or * {@code null} otherwise. * * @param annotations * The list of annotations * @return {@code true} if the list of annotations contains at least one * {@link PodamStrategyValue} annotation. */ private PodamStrategyValue containsAttributeStrategyAnnotation( List<Annotation> annotations) { PodamStrategyValue retValue = null; for (Annotation annotation : annotations) { if (PodamStrategyValue.class .isAssignableFrom(annotation.getClass())) { retValue = (PodamStrategyValue) annotation; break; } } return retValue; } /** * It returns {@code true} if this class is a wrapper class, {@code false} * otherwise * * @param candidateWrapperClass * The class to check * @return {@code true} if this class is a wrapper class, {@code false} * otherwise */ private boolean isWrapper(Class<?> candidateWrapperClass) { return candidateWrapperClass.equals(Byte.class) ? true : candidateWrapperClass.equals(Boolean.class) ? true : candidateWrapperClass.equals(Character.class) ? true : candidateWrapperClass.equals(Short.class) ? true : candidateWrapperClass .equals(Integer.class) ? true : candidateWrapperClass .equals(Long.class) ? true : candidateWrapperClass .equals(Float.class) ? true : candidateWrapperClass .equals(Double.class) ? true : false; } /** * Given the original class and the setter method, it returns all * annotations for the field or an empty collection if no custom annotations * were found on the field * * @param clazz * The class containing the annotated attribute * @param setter * The setter method * @return all annotations for the field * @throws NoSuchFieldException * If the field could not be found * @throws SecurityException * if a security exception occurred */ private List<Annotation> retrieveFieldAnnotations(Class<?> clazz, Method setter) { List<Annotation> retValue = new ArrayList<Annotation>(); // Checks if the field has got any custom annotations String attributeName = PodamUtils .extractFieldNameFromSetterMethod(setter); Field setterField = null; while (clazz != null) { try { setterField = clazz.getDeclaredField(attributeName); break; } catch (NoSuchFieldException e) { clazz = clazz.getSuperclass(); } catch (SecurityException e) { throw e; } } if (setterField != null) { Annotation[] annotations = setterField.getAnnotations(); if (annotations != null && annotations.length != 0) { retValue = Arrays.asList(annotations); } } return retValue; } @SuppressWarnings({ "unchecked" }) private Collection<? super Object> resolveCollectionValueWhenCollectionIsPojoAttribute( Class<?> pojoClass, Class<?> collectionType, String attributeName, List<Annotation> annotations, Map<String, Type> typeArgsMap, Type... genericTypeArgs) { // This needs to be generic because collections can be of any type Collection<? super Object> retValue = null; try { try { validateAttributeName(attributeName); // Checks whether the user initialized the collection in the // class // definition Object newInstance = pojoClass.newInstance(); Field field = null; Class<?> clazz = pojoClass; while (clazz != null) { try { field = clazz.getDeclaredField(attributeName); break; } catch (NoSuchFieldException e) { clazz = clazz.getSuperclass(); } catch (SecurityException e) { throw e; } } if (field == null) { throw new NoSuchFieldException(); } // It allows to invoke Field.get on private fields field.setAccessible(true); Collection<? super Object> coll = (Collection<? super Object>) field .get(newInstance); if (null != coll) { retValue = coll; } else { retValue = resolveCollectionType(collectionType); } } catch (Exception e) { // Name is empty or could not call an empty constructor // (probably this call is for a parameterized constructor) // Create a new Collection retValue = resolveCollectionType(collectionType); } Class<?> typeClass = null; AtomicReference<Type[]> elementGenericTypeArgs = new AtomicReference<Type[]>(new Type[] {}); if (genericTypeArgs == null || genericTypeArgs.length == 0) { LOG.warn("The collection attribute: " + attributeName + " does not have a type. We will assume Object for you"); // Support for non-generified collections typeClass = Object.class; } else { Type actualTypeArgument = genericTypeArgs[0]; typeClass = resolveGenericParameter(actualTypeArgument, typeArgsMap, elementGenericTypeArgs); } fillCollection(pojoClass, attributeName, annotations, retValue, typeClass, elementGenericTypeArgs.get()); } catch (SecurityException e) { throw new PodamMockeryException( "An exception occurred while resolving the collection", e); } catch (IllegalArgumentException e) { throw new PodamMockeryException( "An exception occurred while resolving the collection", e); } catch (InstantiationException e) { throw new PodamMockeryException( "An exception occurred while resolving the collection", e); } catch (IllegalAccessException e) { throw new PodamMockeryException( "An exception occurred while resolving the collection", e); } catch (ClassNotFoundException e) { throw new PodamMockeryException( "An exception occurred while resolving the collection", e); } catch (InvocationTargetException e) { throw new PodamMockeryException( "An exception occurred while resolving the collection", e); } return retValue; } private void fillCollection(Class<?> pojoClass, String attributeName, List<Annotation> annotations, Collection<? super Object> collection, Class<?> collectionElementType, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { // If the user defined a strategy to fill the collection elements, // we use it PodamCollection collectionAnnotation = null; AttributeStrategy<?> elementStrategy = null; for (Annotation annotation : annotations) { if (PodamCollection.class.isAssignableFrom(annotation.getClass())) { collectionAnnotation = (PodamCollection) annotation; break; } } int nbrElements = strategy.getNumberOfCollectionElements(); if (null != collectionAnnotation) { nbrElements = collectionAnnotation.nbrElements(); elementStrategy = collectionAnnotation.collectionElementStrategy() .newInstance(); } for (int i = 0; i < nbrElements; i++) { // The default if (null != elementStrategy && ObjectStrategy.class.isAssignableFrom(elementStrategy .getClass()) && Object.class.equals(collectionElementType)) { LOG.debug("Element strategy is ObjectStrategy and collection element is of type Object: using the ObjectStrategy strategy"); collection.add(elementStrategy.getValue()); } else if (null != elementStrategy && !ObjectStrategy.class.isAssignableFrom(elementStrategy .getClass())) { LOG.debug("Collection elements will be filled using the following strategy: " + elementStrategy); Object strategyValue = returnAttributeDataStrategyValue( collectionElementType, elementStrategy); collection.add(strategyValue); } else { collection.add(manufactureAttributeValue(pojoClass, collectionElementType, annotations, attributeName, genericTypeArgs)); } } } private Map<? super Object, ? super Object> resolveMapValueWhenMapIsPojoAttribute( Class<?> pojoClass, Class<?> attributeType, String attributeName, List<Annotation> annotations, Map<String, Type> typeArgsMap, Type... genericTypeArgs) { Map<? super Object, ? super Object> retValue = null; try { try { validateAttributeName(attributeName); // Checks whether the user initialized the collection in the // class // definition Class<?> workClass = pojoClass; Object newInstance = null; Field field = null; newInstance = pojoClass.newInstance(); while (workClass != null) { try { field = workClass.getDeclaredField(attributeName); break; } catch (NoSuchFieldException e) { workClass = workClass.getSuperclass(); } } if (field == null) { throw new IllegalStateException( "It was not possible to retrieve field: " + attributeName); } // Will throw exception if invalid // It allows to invoke Field.get on private fields field.setAccessible(true); @SuppressWarnings("unchecked") Map<? super Object, ? super Object> coll = (Map<? super Object, ? super Object>) field .get(newInstance); if (null != coll) { retValue = coll; } else { retValue = resolveMapType(attributeType); } } catch (Exception e) { // Name is empty or could not call an empty constructor // (probably this call is for a parameterized constructor) // Create a new Map retValue = resolveMapType(attributeType); } Class<?> keyClass = null; Class<?> elementClass = null; AtomicReference<Type[]> keyGenericTypeArgs = new AtomicReference<Type[]>(new Type[] {}); AtomicReference<Type[]> elementGenericTypeArgs = new AtomicReference<Type[]>(new Type[] {}); if (genericTypeArgs == null || genericTypeArgs.length == 0) { LOG.warn("Map attribute: " + attributeName + " is non-generic. We will assume a Map<Object, Object> for you."); keyClass = Object.class; elementClass = Object.class; } else { // Expected only key, value type if (genericTypeArgs.length != 2) { throw new IllegalStateException( "In a Map only key value generic type are expected."); } Type[] actualTypeArguments = genericTypeArgs; keyClass = resolveGenericParameter(actualTypeArguments[0], typeArgsMap, keyGenericTypeArgs); elementClass = resolveGenericParameter(actualTypeArguments[1], typeArgsMap, elementGenericTypeArgs); } fillMap(pojoClass, attributeName, annotations, retValue, keyClass, elementClass, keyGenericTypeArgs.get(), elementGenericTypeArgs.get()); } catch (InstantiationException e) { throw new PodamMockeryException( "An exception occurred while creating a Map object", e); } catch (IllegalAccessException e) { throw new PodamMockeryException( "An exception occurred while creating a Map object", e); } catch (SecurityException e) { throw new PodamMockeryException( "An exception occurred while creating a Map object", e); } catch (ClassNotFoundException e) { throw new PodamMockeryException( "An exception occurred while creating a Map object", e); } catch (InvocationTargetException e) { throw new PodamMockeryException( "An exception occurred while creating a Map object", e); } return retValue; } private void fillMap(Class<?> pojoClass, String attributeName, List<Annotation> annotations, Map<? super Object, ? super Object> mapToBeFilled, Class<?> keyClass, Class<?> elementClass, Type[] keyGenericTypeArgs, Type[] elementGenericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { // If the user defined a strategy to fill the collection elements, // we use it PodamCollection collectionAnnotation = null; AttributeStrategy<?> keyStrategy = null; AttributeStrategy<?> elementStrategy = null; for (Annotation annotation : annotations) { if (PodamCollection.class.isAssignableFrom(annotation.getClass())) { collectionAnnotation = (PodamCollection) annotation; break; } } int nbrElements = strategy.getNumberOfCollectionElements(); if (null != collectionAnnotation) { nbrElements = collectionAnnotation.nbrElements(); keyStrategy = collectionAnnotation.mapKeyStrategy().newInstance(); elementStrategy = collectionAnnotation.mapElementStrategy() .newInstance(); } for (int i = 0; i < nbrElements; i++) { Object keyValue = null; Object elementValue = null; keyValue = getMapKeyOrElementValue(pojoClass, attributeName, annotations, keyClass, collectionAnnotation, keyStrategy, keyGenericTypeArgs); elementValue = getMapKeyOrElementValue(pojoClass, attributeName, annotations, elementClass, collectionAnnotation, elementStrategy, elementGenericTypeArgs); mapToBeFilled.put(keyValue, elementValue); } } private Object getMapKeyOrElementValue(Class<?> pojoClass, String attributeName, List<Annotation> annotations, Class<?> keyOrValueType, PodamCollection collectionAnnotation, AttributeStrategy<?> elementStrategy, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { Object retValue = null; if (null != elementStrategy && ObjectStrategy.class.isAssignableFrom(elementStrategy .getClass()) && Object.class.equals(keyOrValueType)) { LOG.debug("Element strategy is ObjectStrategy and Map key or value type is of type Object: using the ObjectStrategy strategy"); retValue = elementStrategy.getValue(); } else if (null != elementStrategy && !ObjectStrategy.class.isAssignableFrom(elementStrategy .getClass())) { LOG.debug("Map key or value will be filled using the following strategy: " + elementStrategy); retValue = returnAttributeDataStrategyValue(keyOrValueType, elementStrategy); } else { retValue = manufactureAttributeValue(pojoClass, keyOrValueType, annotations, attributeName, genericTypeArgs); } return retValue; } private Object resolveArrayElementValue(Class<?> attributeType, List<Annotation> annotations, Class<?> pojoClass, String attributeName, Map<String, Type> typeArgsMap) throws IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { Class<?> componentType = attributeType.getComponentType(); AtomicReference<Type[]> genericTypeArgs = new AtomicReference<Type[]>(new Type[] {}); if (null != attributeName) { try { final Type genericType = pojoClass.getDeclaredField( attributeName).getGenericType(); if (genericType instanceof GenericArrayType) { final Type type = ((GenericArrayType) genericType) .getGenericComponentType(); if (type instanceof TypeVariable<?>) { final Type typeVarType = typeArgsMap .get(((TypeVariable<?>) type).getName()); componentType = resolveGenericParameter(typeVarType, typeArgsMap, genericTypeArgs); } } } catch (NoSuchFieldException e) { LOG.info("Cannot get the declared field type for field " + attributeName + " of class " + pojoClass.getName()); } } int nbrElements = strategy.getNumberOfCollectionElements(); Object arrayElement = null; // If the user defined a strategy to fill the collection elements, // we use it PodamCollection collectionAnnotation = null; AttributeStrategy<?> elementStrategy = null; for (Annotation annotation : annotations) { if (PodamCollection.class.isAssignableFrom(annotation.getClass())) { collectionAnnotation = (PodamCollection) annotation; break; } } if (null != collectionAnnotation) { nbrElements = collectionAnnotation.nbrElements(); elementStrategy = collectionAnnotation.collectionElementStrategy() .newInstance(); } Object array = Array.newInstance(componentType, nbrElements); for (int i = 0; i < nbrElements; i++) { // The default if (null != elementStrategy && ObjectStrategy.class .isAssignableFrom(collectionAnnotation .collectionElementStrategy()) && Object.class.equals(componentType)) { LOG.debug("Element strategy is ObjectStrategy and array element is of type Object: using the ObjectStrategy strategy"); arrayElement = elementStrategy.getValue(); } else if (null != elementStrategy && !ObjectStrategy.class .isAssignableFrom(collectionAnnotation .collectionElementStrategy())) { LOG.debug("Array elements will be filled using the following strategy: " + elementStrategy); arrayElement = returnAttributeDataStrategyValue(componentType, elementStrategy); } else { arrayElement = manufactureAttributeValue(pojoClass, componentType, annotations, attributeName, typeArgsMap, genericTypeArgs.get()); } Array.set(array, i, arrayElement); } return array; } /** * Given a collection type it returns an instance * <p> * <ul> * <li>The default type for a {@link List} is an {@link ArrayList}</li> * <li>The default type for a {@link Queue} is a {@link LinkedList}</li> * <li>The default type for a {@link Set} is a {@link HashSet}</li> * </ul> * * </p> * * @param collectionType * The collection type * * @return an instance of the collection type */ @SuppressWarnings({ "rawtypes", "unchecked" }) private Collection<? super Object> resolveCollectionType( Class<?> collectionType) { Collection<? super Object> retValue = null; // Default list and set are ArrayList and HashSet. If users // wants a particular collection flavour they have to initialise // the collection if (List.class.isAssignableFrom(collectionType) || collectionType.equals(Collection.class)) { retValue = new ArrayList(); } else if (Queue.class.isAssignableFrom(collectionType)) { retValue = new LinkedList(); } else if (Set.class.isAssignableFrom(collectionType)) { retValue = new HashSet(); } else { throw new IllegalArgumentException("Collection type: " + collectionType + " not supported"); } return retValue; } /** * It manufactures and returns a default instance for each map type * * <p> * The default implementation for a {@link ConcurrentMap} is * {@link ConcurrentHashMap} * </p> * * <p> * The default implementation for a {@link SortedMap} is a {@link TreeMap} * </p> * * <p> * The default Map is none of the above was recognised is a {@link HashMap} * </p> * * @param attributeType * The attribute type * @return A default instance for each map type * */ @SuppressWarnings({ "unchecked", "rawtypes" }) private Map<? super Object, ? super Object> resolveMapType( Class<?> attributeType) { Map<? super Object, ? super Object> retValue = null; if (SortedMap.class.isAssignableFrom(attributeType)) { retValue = new TreeMap(); } else if (ConcurrentMap.class.isAssignableFrom(attributeType)) { retValue = new ConcurrentHashMap(); } else { retValue = new HashMap(); } return retValue; } private void validateAttributeName(String attributeName) { if (attributeName == null || "".equals(attributeName)) { throw new IllegalArgumentException( "The field name must not be null or empty!"); } } private Object[] getParameterValuesForConstructor( Constructor<?> constructor, Class<?> pojoClass, Type... genericTypeArgs) throws IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { final TypeVariable<?>[] typeParameters = pojoClass.getTypeParameters(); if (typeParameters.length > genericTypeArgs.length) { LOG.info(pojoClass.getCanonicalName() + " is missing generic type arguments, expected " + typeParameters.length + " found " + genericTypeArgs.length + ". Returning null."); return null; } final Map<String, Type> typeArgsMap = new HashMap<String, Type>(); Type[] genericTypeArgsExtra = fillTypeArgMap(typeArgsMap, typeParameters, genericTypeArgs); Annotation[][] parameterAnnotations = constructor .getParameterAnnotations(); Object[] parameterValues = new Object[constructor.getParameterTypes().length]; // Found a constructor with @PodamConstructor annotation Class<?>[] parameterTypes = constructor.getParameterTypes(); int idx = 0; for (Class<?> parameterType : parameterTypes) { List<Annotation> annotations = Arrays .asList(parameterAnnotations[idx]); if (parameterType.equals(pojoClass)) { // Recursive hierarchy in the constructor? If so the POJO should // also have a no-arg constructor // to avoid infinite looping Class<?> declaringClass = constructor.getDeclaringClass(); Constructor<?> noArgConstructor = null; try { noArgConstructor = declaringClass .getConstructor(new Class<?>[] {}); } catch (NoSuchMethodException e) { String errorMsg = "For class: " + declaringClass + " a constructor with its own type as argument does not have a no-arg constructor. Impossible to create an instance of this argument."; LOG.error(errorMsg); throw new IllegalArgumentException(errorMsg); } parameterValues[idx] = noArgConstructor .newInstance(new Object[] {}); } else { String attributeName = null; if (Collection.class.isAssignableFrom(parameterType)) { Collection<? super Object> collection = resolveCollectionType(parameterType); Type type = constructor.getGenericParameterTypes()[idx]; Class<?> collectionElementType; AtomicReference<Type[]> collectionGenericTypeArgs = new AtomicReference<Type[]>(new Type[] {}); if (type instanceof ParameterizedType) { ParameterizedType pType = (ParameterizedType) type; Type actualTypeArgument = pType .getActualTypeArguments()[0]; collectionElementType = resolveGenericParameter(actualTypeArgument, typeArgsMap, collectionGenericTypeArgs); } else { collectionElementType = Object.class; } Type[] genericTypeArgsAll; if (genericTypeArgsExtra != null) { Type[] genericTypeArgsMain = collectionGenericTypeArgs.get(); genericTypeArgsAll = new Type[ genericTypeArgsMain.length + genericTypeArgsExtra.length]; System.arraycopy(genericTypeArgsMain, 0, genericTypeArgsAll, 0, genericTypeArgsMain.length); System.arraycopy(genericTypeArgsExtra, 0, genericTypeArgsAll, genericTypeArgsMain.length, genericTypeArgsExtra.length); } else { genericTypeArgsAll = collectionGenericTypeArgs.get(); } fillCollection(pojoClass, attributeName, annotations, collection, collectionElementType, genericTypeArgsAll); parameterValues[idx] = collection; } else if (Map.class.isAssignableFrom(parameterType)) { Map<? super Object, ? super Object> mapType = resolveMapType(parameterType); Type type = constructor.getGenericParameterTypes()[idx]; Class<?> keyClass; Class<?> elementClass; AtomicReference<Type[]> keyGenericTypeArgs = new AtomicReference<Type[]>(new Type[] {}); AtomicReference<Type[]> elementGenericTypeArgs = new AtomicReference<Type[]>(new Type[] {}); if (type instanceof ParameterizedType) { ParameterizedType pType = (ParameterizedType) type; Type[] actualTypeArguments = pType .getActualTypeArguments(); keyClass = resolveGenericParameter(actualTypeArguments[0], typeArgsMap, keyGenericTypeArgs); elementClass = resolveGenericParameter(actualTypeArguments[1], typeArgsMap, elementGenericTypeArgs); } else { keyClass = Object.class; elementClass = Object.class; } fillMap(pojoClass, attributeName, annotations, mapType, keyClass, elementClass, keyGenericTypeArgs.get(), elementGenericTypeArgs.get()); parameterValues[idx] = mapType; } else { parameterValues[idx] = manufactureAttributeValue(pojoClass, parameterType, annotations, attributeName, genericTypeArgs); } } idx++; } return parameterValues; } private Object returnAttributeDataStrategyValue(Class<?> attributeType, AttributeStrategy<?> attributeStrategy) throws InstantiationException, IllegalAccessException { Object retValue = null; Method attributeStrategyMethod = null; try { attributeStrategyMethod = attributeStrategy.getClass().getMethod( PodamConstants.PODAM_ATTRIBUTE_STRATEGY_METHOD_NAME, new Class<?>[] {}); if (!attributeType.isAssignableFrom(attributeStrategyMethod .getReturnType())) { String errMsg = "The type of the Podam Attribute Strategy is not " + attributeType.getName() + " but " + attributeStrategyMethod.getReturnType().getName() + ". An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg); } retValue = attributeStrategy.getValue(); } catch (SecurityException e) { throw new IllegalStateException( "A security issue occurred while retrieving the Podam Attribute Strategy details", e); } catch (NoSuchMethodException e) { throw new IllegalStateException( "It seems the Podam Attribute Annotation is of the wrong type", e); } return retValue; } /** * @return the excludeAnnotations */ public List<Class<? extends Annotation>> getExcludeAnnotations() { return excludeAnnotations; } /** * @param excludeAnnotations the excludeAnnotations to set */ public void setExcludeAnnotations( List<Class<? extends Annotation>> excludeAnnotations) { this.excludeAnnotations = excludeAnnotations; } }
package io.branch.referral; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.Activity; import android.app.Application; import android.content.Context; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.util.SparseArray; import android.view.ActionMode; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.view.Window; import android.view.WindowManager; import android.view.accessibility.AccessibilityEvent; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; /** * <p> * The core object required when using Branch SDK. You should declare an object of this type at * the class-level of each Activity or Fragment that you wish to use Branch functionality within. * </p> * * <p> * Normal instantiation of this object would look like this: * </p> * * <pre style="background:#fff;padding:10px;border:2px solid silver;"> * Branch.getInstance(this.getApplicationContext()) // from an Activity * * Branch.getInstance(getActivity().getApplicationContext()) // from a Fragment * </pre> * */ public class Branch { private static final String TAG = "BranchSDK"; /** * Hard-coded {@link String} that denotes a {@link BranchLinkData#tags}; applies to links that * are shared with others directly as a user action, via social media for instance. */ public static final String FEATURE_TAG_SHARE = "share"; /** * Hard-coded {@link String} that denotes a 'referral' tag; applies to links that are associated * with a referral program, incentivized or not. */ public static final String FEATURE_TAG_REFERRAL = "referral"; /** * Hard-coded {@link String} that denotes a 'referral' tag; applies to links that are sent as * referral actions by users of an app using an 'invite contacts' feature for instance. */ public static final String FEATURE_TAG_INVITE = "invite"; /** * Hard-coded {@link String} that denotes a link that is part of a commercial 'deal' or offer. */ public static final String FEATURE_TAG_DEAL = "deal"; /** * Hard-coded {@link String} that denotes a link tagged as a gift action within a service or * product. */ public static final String FEATURE_TAG_GIFT = "gift"; /** * The code to be passed as part of a deal or gift; retrieved from the Branch object as a * tag upon initialisation. Of {@link String} format. */ public static final String REDEEM_CODE = "$redeem_code"; /** * <p>Default value of referral bucket; referral buckets contain credits that are used when users * are referred to your apps. These can be viewed in the Branch dashboard under Referrals.</p> */ public static final String REFERRAL_BUCKET_DEFAULT = "default"; /** * <p>Hard-coded value for referral code type. Referral codes will always result on "credit" actions. * Even if they are of 0 value.</p> */ public static final String REFERRAL_CODE_TYPE = "credit"; /** * Branch SDK version for the current release of the Branch SDK. */ public static final int REFERRAL_CREATION_SOURCE_SDK = 2; /** * Key value for referral code as a parameter. */ public static final String REFERRAL_CODE = "referral_code"; /** * The redirect URL provided when the link is handled by a desktop client. */ public static final String REDIRECT_DESKTOP_URL = "$desktop_url"; /** * The redirect URL provided when the link is handled by an Android device. */ public static final String REDIRECT_ANDROID_URL = "$android_url"; /** * The redirect URL provided when the link is handled by an iOS device. */ public static final String REDIRECT_IOS_URL = "$ios_url"; /** * The redirect URL provided when the link is handled by a large form-factor iOS device such as * an iPad. */ public static final String REDIRECT_IPAD_URL = "$ipad_url"; /** * The redirect URL provided when the link is handled by an Amazon Fire device. */ public static final String REDIRECT_FIRE_URL = "$fire_url"; /** * The redirect URL provided when the link is handled by a Blackberry device. */ public static final String REDIRECT_BLACKBERRY_URL = "$blackberry_url"; /** * The redirect URL provided when the link is handled by a Windows Phone device. */ public static final String REDIRECT_WINDOWS_PHONE_URL = "$windows_phone_url"; public static final String OG_TITLE = "$og_title"; public static final String OG_DESC = "$og_description"; public static final String OG_IMAGE_URL = "$og_image_url"; public static final String OG_VIDEO = "$og_video"; public static final String OG_URL = "$og_url"; /** * Unique identifier for the app in use. */ public static final String OG_APP_ID = "$og_app_id"; /** * {@link String} value denoting the deep link path to override Branch's default one. By * default, Branch will use yourapp://open?link_click_id=12345. If you specify this key/value, * Branch will use yourapp://'$deeplink_path'?link_click_id=12345 */ public static final String DEEPLINK_PATH = "$deeplink_path"; /** * {@link String} value indicating whether the link should always initiate a deep link action. * By default, unless overridden on the dashboard, Branch will only open the app if they are * 100% sure the app is installed. This setting will cause the link to always open the app. * Possible values are "true" or "false" */ public static final String ALWAYS_DEEPLINK = "$always_deeplink"; /** * An {@link Integer} value indicating the user to reward for applying a referral code. In this * case, the user applying the referral code receives credit. */ public static final int REFERRAL_CODE_LOCATION_REFERREE = 0; /** * An {@link Integer} value indicating the user to reward for applying a referral code. In this * case, the user who created the referral code receives credit. */ public static final int REFERRAL_CODE_LOCATION_REFERRING_USER = 2; /** * An {@link Integer} value indicating the user to reward for applying a referral code. In this * case, both the creator and applicant receive credit */ public static final int REFERRAL_CODE_LOCATION_BOTH = 3; /** * An {@link Integer} value indicating the calculation type of the referral code. In this case, * the referral code can be applied continually. */ public static final int REFERRAL_CODE_AWARD_UNLIMITED = 1; /** * An {@link Integer} value indicating the calculation type of the referral code. In this case, * a user can only apply a specific referral code once. */ public static final int REFERRAL_CODE_AWARD_UNIQUE = 0; /** * An {@link Integer} value indicating the link type. In this case, the link can be used an * unlimited number of times. */ public static final int LINK_TYPE_UNLIMITED_USE = 0; /** * An {@link Integer} value indicating the link type. In this case, the link can be used only * once. After initial use, subsequent attempts will not validate. */ public static final int LINK_TYPE_ONE_TIME_USE = 1; private static final int SESSION_KEEPALIVE = 2000; /** * <p>An {@link Integer} value defining the timeout period in milliseconds to wait during a * looping task before triggering an actual connection close during a session close action.</p> */ private static final int PREVENT_CLOSE_TIMEOUT = 500; /** * <p>A {@link Branch} object that is instantiated on init and holds the singleton instance of * the class during application runtime.</p> */ private static Branch branchReferral_; private BranchRemoteInterface kRemoteInterface_; private PrefHelper prefHelper_; private SystemObserver systemObserver_; private Context context_; final Object lock; private Timer closeTimer; private Timer rotateCloseTimer; private boolean keepAlive_; private Semaphore serverSema_; private ServerRequestQueue requestQueue_; private int networkCount_; private boolean hasNetwork_; private SparseArray<String> debugListenerInitHistory_; private OnTouchListener debugOnTouchListener_; private Handler debugHandler_; private boolean debugStarted_; private Map<BranchLinkData, String> linkCache_; private ScheduledFuture<?> appListingSchedule_; /* BranchActivityLifeCycleObserver instance. Should be initialised on creating Instance with Application object. */ private BranchActivityLifeCycleObserver activityLifeCycleObserver_; /* Set to true when application is instantiating {@BranchApp} by extending or adding manifest entry. */ private static boolean isAutoSessionMode_ = false; /* Set to true when {@link Activity} life cycle callbacks are registered. */ private static boolean isActivityLifeCycleCallbackRegistered_ = false; /* Enumeration for defining session initialisation state. */ private enum SESSION_STATE {INITIALISED, INITIALISING, UNINITIALISED} /* Holds the current Session state. Default is set to UNINITIALISED. */ private SESSION_STATE initState_ = SESSION_STATE.UNINITIALISED; /** * <p>The main constructor of the Branch class is private because the class uses the Singleton * pattern.</p> * * <p>Use {@link #getInstance(Context) getInstance} method when instantiating.</p> * * @param context A {@link Context} from which this call was made. */ private Branch(Context context) { prefHelper_ = PrefHelper.getInstance(context); kRemoteInterface_ = new BranchRemoteInterface(context); systemObserver_ = new SystemObserver(context); requestQueue_ = ServerRequestQueue.getInstance(context); serverSema_ = new Semaphore(1); closeTimer = new Timer(); rotateCloseTimer = new Timer(); lock = new Object(); keepAlive_ = false; networkCount_ = 0; hasNetwork_ = true; debugListenerInitHistory_ = new SparseArray<String>(); debugOnTouchListener_ = retrieveOnTouchListener(); debugHandler_ = new Handler(); debugStarted_ = false; linkCache_ = new HashMap<BranchLinkData, String>(); } /** * <p>Singleton method to return the pre-initialised object of the type {@link Branch}. * Make sure your app is instantiating {@link BranchApp} before calling this method.</p> * * @return An initialised singleton {@link Branch} object * * @throws BranchException Exception<br> * 1) If your {@link Application} is not instance of {@link BranchApp}.<br> * 2) If the minimum API level is below 14. */ public static Branch getInstance() throws BranchException { /* Check if BranchApp is instantiated. */ if (branchReferral_ == null ) { throw BranchException.getInstantiationException(); } else if(isAutoSessionMode_ == true){ /* Check if Activity life cycle callbacks are set if in auto session mode. */ if (isActivityLifeCycleCallbackRegistered_ == false) { throw BranchException.getAPILevelException(); } } return branchReferral_; } public static Branch getInstance(Context context, String branchKey) { if (branchReferral_ == null) { branchReferral_ = Branch.initInstance(context); } branchReferral_.context_ = context.getApplicationContext(); if (branchKey.startsWith("key_")) { branchReferral_.prefHelper_.setBranchKey(branchKey); } else { branchReferral_.prefHelper_.setAppKey(branchKey); } return branchReferral_; } private static Branch getBranchInstance(Context context, boolean isLive) { if (branchReferral_ == null) { branchReferral_ = Branch.initInstance(context); String branchKey = branchReferral_.prefHelper_.readBranchKey(isLive); if (branchKey == null || branchKey.equalsIgnoreCase(PrefHelper.NO_STRING_VALUE)) { Log.i("BranchSDK", "Branch Warning: Please enter your branch_key in your project's Manifest file!"); branchReferral_.prefHelper_.setBranchKey(PrefHelper.NO_STRING_VALUE); } else { branchReferral_.prefHelper_.setBranchKey(branchKey); } } branchReferral_.context_ = context; /* If {@link Application} is instantiated register for activity life cycle events. */ if (context instanceof BranchApp) { isAutoSessionMode_ = true; branchReferral_.setActivityLifeCycleObserver((Application) context); } return branchReferral_; } /** * <p>Singleton method to return the pre-initialised, or newly initialise and return, a singleton * object of the type {@link Branch}.</p> * * <p>Use this whenever you need to call a method directly on the {@link Branch} object.</p> * * @param context A {@link Context} from which this call was made. * * @return An initialised {@link Branch} object, either fetched from a pre-initialised * instance within the singleton class, or a newly instantiated object where * one was not already requested during the current app lifecycle. */ public static Branch getInstance(Context context) { return getBranchInstance(context, true); } /** * <p>If you configured the your Strings file according to the guide, you'll be able to use * the test version of your app by just calling this static method before calling initSession.</p> * * @param context A {@link Context} from which this call was made. * * @return An initialised {@link Branch} object. */ public static Branch getTestInstance(Context context) { return getBranchInstance(context, false); } /** * <p>Singleton method to return the pre-initialised, or newly initialise and return, a singleton * object of the type {@link Branch}.</p> * * <p>Use this whenever you need to call a method directly on the {@link Branch} object.</p> * * @param context A {@link Context} from which this call was made. * * @return An initialised {@link Branch} object, either fetched from a pre-initialised * instance within the singleton class, or a newly instantiated object where * one was not already requested during the current app lifecycle. */ public static Branch getAutoInstance(Context context) { isAutoSessionMode_ = true; getBranchInstance(context, true); branchReferral_.setActivityLifeCycleObserver((Application)context); return branchReferral_; } /** * <p>If you configured the your Strings file according to the guide, you'll be able to use * the test version of your app by just calling this static method before calling initSession.</p> * * @param context A {@link Context} from which this call was made. * * @return An initialised {@link Branch} object. */ public static Branch getAutoTestInstance(Context context) { isAutoSessionMode_ = true; getBranchInstance(context, false); branchReferral_.setActivityLifeCycleObserver((Application)context); return branchReferral_; } /** * <p>Initialises an instance of the Branch object.</p> * * @param context A {@link Context} from which this call was made. * * @return An initialised {@link Branch} object. */ private static Branch initInstance(Context context) { return new Branch(context.getApplicationContext()); } /** * <p>Manually sets the {@link Boolean} value, that indicates that the Branch API connection has * been initialised, to false - forcing re-initialisation.</p> */ public void resetUserSession() { initState_ = SESSION_STATE.UNINITIALISED; } /** * <p>Sets the number of times to re-attempt a timed-out request to the Branch API, before * considering the request to have failed entirely. Default 5.</p> * * @param retryCount An {@link Integer} specifying the number of times to retry before giving * up and declaring defeat. */ public void setRetryCount(int retryCount) { if (prefHelper_ != null && retryCount > 0) { prefHelper_.setRetryCount(retryCount); } } /** * <p>Sets the amount of time in milliseconds to wait before re-attempting a timed-out request * to the Branch API. Default 3000 ms.</p> * * @param retryInterval An {@link Integer} value specifying the number of milliseconds to * wait before re-attempting a timed-out request. */ public void setRetryInterval(int retryInterval) { if (prefHelper_ != null && retryInterval > 0) { prefHelper_.setRetryInterval(retryInterval); } } /** * <p>Sets the duration in milliseconds that the system should wait for a response before considering * any Branch API call to have timed out. Default 3000 ms.</p> * * <p>Increase this to perform better in low network speed situations, but at the expense of * responsiveness to error situation.</p> * * @param timeout An {@link Integer} value specifying the number of milliseconds to wait before * considering the request to have timed out. */ public void setNetworkTimeout(int timeout) { if (prefHelper_ != null && timeout > 0) { prefHelper_.setTimeout(timeout); } } /** * <p>Sets the library to function in debug mode, enabling logging of all requests.</p> * <p>If you want to flag debug, call this <b>before</b> initUserSession</p> */ public void setDebug() { prefHelper_.setExternDebug(); } /** * <p>Calls the {@link PrefHelper#disableExternAppListing()} on the local instance to prevent * a list of installed apps from being returned to the Branch API.</p> */ public void disableAppList() { prefHelper_.disableExternAppListing(); } /** * <p>If there's further Branch API call happening within the two seconds, we then don't close * the session; otherwise, we close the session after two seconds.</p> * * <p>Call this method if you don't want this smart session feature and would rather manage * the session yourself.</p> * * <p><b>Note:</b> smart session - we keep session alive for two seconds</p> */ public void disableSmartSession() { prefHelper_.disableSmartSession(); } /** * <p>Initialises a session with the Branch API, assigning a {@link BranchReferralInitListener} * to perform an action upon successful initialisation.</p> * * @param callback A {@link BranchReferralInitListener} instance that will be called following * successful (or unsuccessful) initialisation of the session with the Branch API. * * @return A {@link Boolean} value, indicating <i>false</i> if initialisation is * unsuccessful. */ public boolean initSession(BranchReferralInitListener callback) { initSession(callback, (Activity) null); return false; } /** * <p>Initialises a session with the Branch API, passing the {@link Activity} and assigning a * {@link BranchReferralInitListener} to perform an action upon successful initialisation.</p> * * @param callback A {@link BranchReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * * @param activity The calling {@link Activity} for context. * * @return A {@link Boolean} value, indicating <i>false</i> if initialisation is * unsuccessful. */ public boolean initSession(BranchReferralInitListener callback, Activity activity) { if (systemObserver_.getUpdateState(false) == 0 && !hasUser()) { prefHelper_.setIsReferrable(); } else { prefHelper_.clearIsReferrable(); } initUserSessionInternal(callback, activity); return false; } /** * <p>Initialises a session with the Branch API.</p> * * @param callback A {@link BranchReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * * @param data A {@link Uri} variable containing the details of the source link that * led to this initialisation action. * * @return A {@link Boolean} value that will return <i>false</i> if the supplied * <i>data</i> parameter cannot be handled successfully - i.e. is not of a * valid URI format. */ public boolean initSession(BranchReferralInitListener callback, Uri data) { return initSession(callback, data, null); } /** * <p>Initialises a session with the Branch API.</p> * * @param callback A {@link BranchReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * * @param data A {@link Uri} variable containing the details of the source link that * led to this initialisation action. * * @param activity The calling {@link Activity} for context. * * @return A {@link Boolean} value that will return <i>false</i> if the supplied * <i>data</i> parameter cannot be handled successfully - i.e. is not of a * valid URI format. */ public boolean initSession(BranchReferralInitListener callback, Uri data, Activity activity) { boolean uriHandled = readAndStripParam(data, activity); initSession(callback, activity); return uriHandled; } /** * <p>Initialises a session with the Branch API, without a callback or {@link Activity}.</p> * * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSession() { return initSession((Activity) null); } /** * <p>Initialises a session with the Branch API, without a callback or {@link Activity}.</p> * * @param activity The calling {@link Activity} for context. * * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSession(Activity activity) { return initSession(null, activity); } /** * <p>Initialises a session with the Branch API, with associated data from the supplied * {@link Uri}.</p> * * @param data A {@link Uri} variable containing the details of the source link that * led to this * initialisation action. * * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSessionWithData(Uri data) { return initSessionWithData(data, null); } /** * <p>Initialises a session with the Branch API, with associated data from the supplied * {@link Uri}.</p> * * @param data A {@link Uri} variable containing the details of the source link that led to this * initialisation action. * * @param activity The calling {@link Activity} for context. * * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSessionWithData(Uri data, Activity activity) { boolean uriHandled = readAndStripParam(data, activity); initSession(null, activity); return uriHandled; } /** * <p>Initialises a session with the Branch API, specifying whether the initialisation can count * as a referrable action.</p> * * @param isReferrable A {@link Boolean} value indicating whether this initialisation * session should be considered as potentially referrable or not. * By default, a user is only referrable if initSession results in a * fresh install. Overriding this gives you control of who is referrable. * * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSession(boolean isReferrable) { return initSession(null, isReferrable, (Activity)null); } /** * <p>Initialises a session with the Branch API, specifying whether the initialisation can count * as a referrable action, and supplying the calling {@link Activity} for context.</p> * * @param isReferrable A {@link Boolean} value indicating whether this initialisation * session should be considered as potentially referrable or not. * By default, a user is only referrable if initSession results in a * fresh install. Overriding this gives you control of who is referrable. * * @param activity The calling {@link Activity} for context. * * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSession(boolean isReferrable, Activity activity) { return initSession(null, isReferrable, activity); } /** * <p>Initialises a session with the Branch API.</p> * * @param callback A {@link BranchReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * * @param isReferrable A {@link Boolean} value indicating whether this initialisation * session should be considered as potentially referrable or not. * By default, a user is only referrable if initSession results in a * fresh install. Overriding this gives you control of who is referrable. * * @param data A {@link Uri} variable containing the details of the source link that * led to this initialisation action. * * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSession(BranchReferralInitListener callback, boolean isReferrable, Uri data) { return initSession(callback, isReferrable, data, null); } /** * <p>Initialises a session with the Branch API.</p> * * @param callback A {@link BranchReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * * @param isReferrable A {@link Boolean} value indicating whether this initialisation * session should be considered as potentially referrable or not. * By default, a user is only referrable if initSession results in a * fresh install. Overriding this gives you control of who is referrable. * * @param data A {@link Uri} variable containing the details of the source link that * led to this initialisation action. * * @param activity The calling {@link Activity} for context. * * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSession(BranchReferralInitListener callback, boolean isReferrable, Uri data, Activity activity) { boolean uriHandled = readAndStripParam(data, activity); initSession(callback, isReferrable, activity); return uriHandled; } /** * <p>Initialises a session with the Branch API.</p> * * @param callback A {@link BranchReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * * @param isReferrable A {@link Boolean} value indicating whether this initialisation * session should be considered as potentially referrable or not. * By default, a user is only referrable if initSession results in a * fresh install. Overriding this gives you control of who is referrable. * * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSession(BranchReferralInitListener callback, boolean isReferrable) { return initSession(callback, isReferrable, (Activity)null); } /** * <p>Initialises a session with the Branch API.</p> * * @param callback A {@link BranchReferralInitListener} instance that will be called * following successful (or unsuccessful) initialisation of the session * with the Branch API. * @param isReferrable A {@link Boolean} value indicating whether this initialisation * session should be considered as potentially referrable or not. * By default, a user is only referrable if initSession results in a * fresh install. Overriding this gives you control of who is referrable. * @param activity The calling {@link Activity} for context. * @return A {@link Boolean} value that returns <i>false</i> if unsuccessful. */ public boolean initSession(BranchReferralInitListener callback, boolean isReferrable, Activity activity) { if (isReferrable) { this.prefHelper_.setIsReferrable(); } else { this.prefHelper_.clearIsReferrable(); } initUserSessionInternal(callback, activity); return false; } private void initUserSessionInternal(BranchReferralInitListener callback, Activity activity) { //If already initialised if (hasUser() && hasSession() && initState_ == SESSION_STATE.INITIALISED) { if (callback != null) callback.onInitFinished(new JSONObject(), null); clearCloseTimer(); keepAlive(); } //If uninitialised or initialising else { //If initialising ,then set new callbacks. if (initState_ == SESSION_STATE.INITIALISING) { requestQueue_.setInstallOrOpenCallback(callback); } //if Uninitialised move request to the front if there is an existing request or create a new request. else { initState_ = SESSION_STATE.INITIALISING; initializeSession(callback); } } if (activity != null && debugListenerInitHistory_.get(System.identityHashCode(activity)) == null) { debugListenerInitHistory_.put(System.identityHashCode(activity), "init"); View view = activity.getWindow().getDecorView().findViewById(android.R.id.content); if (view != null) { view.setOnTouchListener(debugOnTouchListener_); } } } /** * <p>Set the current activity window for the debug touch events. Only for internal usage.</p> * * @param activity The current activity. */ private void setTouchDebugInternal(Activity activity){ if (activity != null && debugListenerInitHistory_.get(System.identityHashCode(activity)) == null) { debugListenerInitHistory_.put(System.identityHashCode(activity), "init"); activity.getWindow().setCallback(new BranchWindowCallback(activity.getWindow().getCallback())); } } private void clearTouchDebugInternal(Activity activity) { if (activity.getWindow().getCallback() instanceof BranchWindowCallback) { Window.Callback originalCallback = ((BranchWindowCallback) activity.getWindow().getCallback()).callback_; activity.getWindow().setCallback(originalCallback); debugListenerInitHistory_.remove(System.identityHashCode(activity)); } } private OnTouchListener retrieveOnTouchListener() { if (debugOnTouchListener_ == null) { debugOnTouchListener_ = new OnTouchListener() { class KeepDebugConnectionTask extends TimerTask { public void run() { if (!prefHelper_.keepDebugConnection()) { debugHandler_.post(_longPressed); } } } Runnable _longPressed = new Runnable() { private boolean started = false; private Timer timer; public void run() { debugHandler_.removeCallbacks(_longPressed); if (!started) { Log.i("Branch Debug","======= Start Debug Session ======="); prefHelper_.setDebug(); timer = new Timer(); timer.scheduleAtFixedRate(new KeepDebugConnectionTask(), new Date(), 20000); } else { Log.i("Branch Debug","======= End Debug Session ======="); prefHelper_.clearDebug(); timer.cancel(); timer = null; } this.started = !this.started; } }; @Override public boolean onTouch(View v, MotionEvent ev) { int pointerCount = ev.getPointerCount(); final int actionPerformed = ev.getAction(); switch (actionPerformed & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: if (systemObserver_.isSimulator()) { debugHandler_.postDelayed(_longPressed, PrefHelper.DEBUG_TRIGGER_PRESS_TIME); } break; case MotionEvent.ACTION_MOVE: break; case MotionEvent.ACTION_CANCEL: debugHandler_.removeCallbacks(_longPressed); break; case MotionEvent.ACTION_UP: v.performClick(); debugHandler_.removeCallbacks(_longPressed); break; case MotionEvent.ACTION_POINTER_DOWN: if (pointerCount == PrefHelper.DEBUG_TRIGGER_NUM_FINGERS) { debugHandler_.postDelayed(_longPressed, PrefHelper.DEBUG_TRIGGER_PRESS_TIME); } break; } return true; } }; } return debugOnTouchListener_; } /** * <p>Closes the current session, dependent on the state of the * {@link PrefHelper#getSmartSession()} {@link Boolean} value. If <i>true</i>, take no action. * If false, close the sesion via the {@link #executeClose()} method.</p> * <p>Note that if smartSession is enabled, closeSession cannot be called within * a 2 second time span of another Branch action. This has to do with the method that * Branch uses to keep a session alive during Activity transitions</p> */ public void closeSession() { if (isAutoSessionMode_) { /* * Ignore any session close request from user if session is managed * automatically.This is handle situation of closeSession() in * closed by developer by error while running in auto session mode. */ return; } if (prefHelper_.getSmartSession()) { if (keepAlive_) { return; } // else, real close synchronized(lock) { clearCloseTimer(); rotateCloseTimer.schedule(new TimerTask() { @Override public void run() { executeClose(); } }, PREVENT_CLOSE_TIMEOUT); } } else { executeClose(); } if (prefHelper_.getExternAppListing()) { if (appListingSchedule_ == null) { scheduleListOfApps(); } } } /* * <p>Closes the current session. Should be called by on getting the last actvity onStop() event. * </p> */ private void closeSessionInternal(){ executeClose(); if (prefHelper_.getExternAppListing()) { if (appListingSchedule_ == null) { scheduleListOfApps(); } } } /** * <p>Perform the state-safe actions required to terminate any open session, and report the * closed application event to the Branch API.</p> */ private void executeClose() { if (initState_ != SESSION_STATE.UNINITIALISED) { if (!hasNetwork_) { // if there's no network connectivity, purge the old install/open ServerRequest req = requestQueue_.peek(); if (req != null && (req instanceof ServerRequestRegisterInstall) || (req instanceof ServerRequestRegisterOpen)) { requestQueue_.dequeue(); } } else { if (!requestQueue_.containsClose()) { ServerRequest req = new ServerRequestRegisterClose(context_); handleNewRequest(req); } } initState_ = SESSION_STATE.UNINITIALISED; } } private boolean readAndStripParam(Uri data, Activity activity) { if (data != null && data.isHierarchical()) { if (data.getQueryParameter(Defines.Jsonkey.LinkClickID.getKey()) != null) { prefHelper_.setLinkClickIdentifier(data.getQueryParameter(Defines.Jsonkey.LinkClickID.getKey())); String paramString = "link_click_id=" + data.getQueryParameter(Defines.Jsonkey.LinkClickID.getKey()); String uriString = activity.getIntent().getDataString(); if (data.getQuery().length() == paramString.length()) { paramString = "\\?" + paramString; } else if ((uriString.length()-paramString.length()) == uriString.indexOf(paramString)) { paramString = "&" + paramString; } else { paramString = paramString + "&"; } Uri newData = Uri.parse(uriString.replaceFirst(paramString, "")); activity.getIntent().setData(newData); return true; } } return false; } /** * <p>Identifies the current user to the Branch API by supplying a unique identifier as a * {@link String} value. No callback.</p> * * @param userId A {@link String} value containing the unique identifier of the user. */ public void setIdentity(String userId) { setIdentity(userId, null); } /** * <p>Identifies the current user to the Branch API by supplying a unique identifier as a * {@link String} value, with a callback specified to perform a defined action upon successful * response to request.</p> * * @param userId A {@link String} value containing the unique identifier of the user. * @param callback A {@link BranchReferralInitListener} callback instance that will return * the data associated with the user id being assigned, if available. */ public void setIdentity(String userId, BranchReferralInitListener callback) { ServerRequest req = new ServerRequestIdentifyUserRequest(context_, callback, userId); if (!req.constructError_ && !req.handleErrors(context_)) { handleNewRequest(req); } else { if (((ServerRequestIdentifyUserRequest) req).isExistingID()) { ((ServerRequestIdentifyUserRequest) req).handleUserExist(branchReferral_); } } } /** * Indicates whether or not this user has a custom identity specified for them. Note that this is independent of installs. * If you call setIdentity, this device will have that identity associated with this user until logout is called. * This includes persisting through uninstalls, as we track device id. * * @return A {@link Boolean} value that will return <i>true</i> only if user already has an identity. * */ public boolean isUserIdentified() { return !prefHelper_.getIdentity().equals(PrefHelper.NO_STRING_VALUE); } /** * <p>This method should be called if you know that a different person is about to use the app. For example, * if you allow users to log out and let their friend use the app, you should call this to notify Branch * to create a new user for this device. This will clear the first and latest params, as a new session is created.</p> */ public void logout() { ServerRequest req = new ServerRequestLogout(context_); if (!req.constructError_ && !req.handleErrors(context_)) { handleNewRequest(req); } } /** * <p>Fire-and-forget retrieval of action count for the current session. Without a callback.</p> */ public void loadActionCounts() { loadActionCounts(null); } /** * <p>Gets the total action count, with a callback to perform a predefined * action following successful report of state change. You'll then need to * call getUniqueActions or getTotalActions in the callback to update the * totals in your UX.</p> * * @param callback A {@link BranchReferralStateChangedListener} callback instance that will * trigger actions defined therein upon a referral state change. */ public void loadActionCounts(BranchReferralStateChangedListener callback) { ServerRequest req = new ServerRequestGetReferralCount(context_, callback); if (!req.constructError_ && !req.handleErrors(context_)) { handleNewRequest(req); } } /** * <p>Fire-and-forget retrieval of rewards for the current session. Without a callback.</p> */ public void loadRewards() { loadRewards(null); } /** * <p>Retrieves rewards for the current session, with a callback to perform a predefined * action following successful report of state change. You'll then need to call getCredits * in the callback to update the credit totals in your UX.</p> * * @param callback A {@link BranchReferralStateChangedListener} callback instance that will * trigger actions defined therein upon a referral state change. */ public void loadRewards(BranchReferralStateChangedListener callback) { ServerRequest req = new ServerRequestGetRewards(context_, callback); if (!req.constructError_ && !req.handleErrors(context_)) { handleNewRequest(req); } } /** * <p>Retrieve the number of credits available for the "default" bucket.</p> * * @return An {@link Integer} value of the number credits available in the "default" bucket. */ public int getCredits() { return prefHelper_.getCreditCount(); } /** * Returns an {@link Integer} of the number of credits available for use within the supplied * bucket name. * * @param bucket A {@link String} value indicating the name of the bucket to get credits for. * * @return An {@link Integer} value of the number credits available in the specified * bucket. */ public int getCreditsForBucket(String bucket) { return prefHelper_.getCreditCount(bucket); } /** * <p>Gets the total number of times that the specified action has been carried out.</p> * * @param action A {@link String} value containing the name of the action to count. * * @return An {@link Integer} value of the total number of times that an action has * been executed. */ public int getTotalCountsForAction(String action) { return prefHelper_.getActionTotalCount(action); } /** * <p>Gets the number of unique times that the specified action has been carried out.</p> * * @param action A {@link String} value containing the name of the action to count. * * @return An {@link Integer} value of the number of unique times that the * specified action has been carried out. */ public int getUniqueCountsForAction(String action) { return prefHelper_.getActionUniqueCount(action); } /** * <p>Redeems the specified number of credits from the "default" bucket, if there are sufficient * credits within it. If the number to redeem exceeds the number available in the bucket, all of * the available credits will be redeemed instead.</p> * * @param count A {@link Integer} specifying the number of credits to attempt to redeem from * the bucket. */ public void redeemRewards(int count) { redeemRewards(Defines.Jsonkey.DefaultBucket.getKey(), count, null); } /** * <p>Redeems the specified number of credits from the "default" bucket, if there are sufficient * credits within it. If the number to redeem exceeds the number available in the bucket, all of * the available credits will be redeemed instead.</p> * * @param count A {@link Integer} specifying the number of credits to attempt to redeem from * the bucket. * * @param callback A {@link BranchReferralStateChangedListener} callback instance that will * trigger actions defined therein upon a executing redeem rewards. */ public void redeemRewards(int count, BranchReferralStateChangedListener callback) { redeemRewards(Defines.Jsonkey.DefaultBucket.getKey(), count, callback); } /** * <p>Redeems the specified number of credits from the named bucket, if there are sufficient * credits within it. If the number to redeem exceeds the number available in the bucket, all of * the available credits will be redeemed instead.</p> * * @param bucket A {@link String} value containing the name of the referral bucket to attempt * to redeem credits from. * * @param count A {@link Integer} specifying the number of credits to attempt to redeem from * the specified bucket. */ public void redeemRewards(final String bucket, final int count) { redeemRewards(bucket, count, null); } /** * <p>Redeems the specified number of credits from the named bucket, if there are sufficient * credits within it. If the number to redeem exceeds the number available in the bucket, all of * the available credits will be redeemed instead.</p> * * @param bucket A {@link String} value containing the name of the referral bucket to attempt * to redeem credits from. * @param count A {@link Integer} specifying the number of credits to attempt to redeem from * the specified bucket. * @param callback A {@link BranchReferralStateChangedListener} callback instance that will * trigger actions defined therein upon a executing redeem rewards. */ public void redeemRewards(final String bucket, final int count, BranchReferralStateChangedListener callback) { ServerRequestRedeemRewards req = new ServerRequestRedeemRewards(context_, bucket, count, callback); if (!req.constructError_ && !req.handleErrors(context_)) { handleNewRequest(req); } } /** * <p>Gets the credit history of the specified bucket and triggers a callback to handle the * response.</p> * * @param callback A {@link BranchListResponseListener} callback instance that will trigger * actions defined therein upon receipt of a response to a create link request. */ public void getCreditHistory(BranchListResponseListener callback) { getCreditHistory(null, null, 100, CreditHistoryOrder.kMostRecentFirst, callback); } /** * <p>Gets the credit history of the specified bucket and triggers a callback to handle the * response.</p> * * @param bucket A {@link String} value containing the name of the referral bucket that the * code will belong to. * * @param callback A {@link BranchListResponseListener} callback instance that will trigger * actions defined therein upon receipt of a response to a create link request. */ public void getCreditHistory(final String bucket, BranchListResponseListener callback) { getCreditHistory(bucket, null, 100, CreditHistoryOrder.kMostRecentFirst, callback); } /** * <p>Gets the credit history of the specified bucket and triggers a callback to handle the * response.</p> * * @param afterId A {@link String} value containing the ID of the history record to begin after. * This allows for a partial history to be retrieved, rather than the entire * credit history of the bucket. * * @param length A {@link Integer} value containing the number of credit history records to * return. * * @param order A {@link CreditHistoryOrder} object indicating which order the results should * be returned in. * * <p>Valid choices:</p> * * <ul> * <li>{@link CreditHistoryOrder#kMostRecentFirst}</li> * <li>{@link CreditHistoryOrder#kLeastRecentFirst}</li> * </ul> * * @param callback A {@link BranchListResponseListener} callback instance that will trigger * actions defined therein upon receipt of a response to a create link request. */ public void getCreditHistory(final String afterId, final int length, final CreditHistoryOrder order, BranchListResponseListener callback) { getCreditHistory(null, afterId, length, order, callback); } /** * <p>Gets the credit history of the specified bucket and triggers a callback to handle the * response.</p> * * @param bucket A {@link String} value containing the name of the referral bucket that the * code will belong to. * @param afterId A {@link String} value containing the ID of the history record to begin after. * This allows for a partial history to be retrieved, rather than the entire * credit history of the bucket. * @param length A {@link Integer} value containing the number of credit history records to * return. * @param order A {@link CreditHistoryOrder} object indicating which order the results should * be returned in. * <p/> * <p>Valid choices:</p> * <p/> * <ul> * <li>{@link CreditHistoryOrder#kMostRecentFirst}</li> * <li>{@link CreditHistoryOrder#kLeastRecentFirst}</li> * </ul> * @param callback A {@link BranchListResponseListener} callback instance that will trigger * actions defined therein upon receipt of a response to a create link request. */ public void getCreditHistory(final String bucket, final String afterId, final int length, final CreditHistoryOrder order, BranchListResponseListener callback) { ServerRequest req = new ServerRequestGetRewardHistory(context_, bucket, afterId, length, order, callback); if (!req.constructError_ && !req.handleErrors(context_)) { handleNewRequest(req); } } /** * <p>A void call to indicate that the user has performed a specific action and for that to be * reported to the Branch API, with additional app-defined meta data to go along with that action.</p> * * @param action A {@link String} value to be passed as an action that the user has carried * out. For example "registered" or "logged in". * @param metadata A {@link JSONObject} containing app-defined meta-data to be attached to a * user action that has just been completed. */ public void userCompletedAction(final String action, JSONObject metadata) { if (metadata != null) metadata = filterOutBadCharacters(metadata); ServerRequest req = new ServerRequestActionCompleted(context_, action, metadata); if (!req.constructError_ && !req.handleErrors(context_)) { handleNewRequest(req); } } /** * <p>A void call to indicate that the user has performed a specific action and for that to be * reported to the Branch API.</p> * * @param action A {@link String} value to be passed as an action that the user has carried * out. For example "registered" or "logged in". */ public void userCompletedAction(final String action) { userCompletedAction(action, null); } /** * <p>Returns the parameters associated with the link that referred the user. This is only set once, * the first time the user is referred by a link. Think of this as the user referral parameters. * It is also only set if isReferrable is equal to true, which by default is only true * on a fresh install (not upgrade or reinstall). This will change on setIdentity (if the * user already exists from a previous device) and logout.</p> * * @return A {@link JSONObject} containing the install-time parameters as configured * locally. */ public JSONObject getFirstReferringParams() { String storedParam = prefHelper_.getInstallParams(); return convertParamsStringToDictionary(storedParam); } /** * <p>Returns the parameters associated with the link that referred the session. If a user * clicks a link, and then opens the app, initSession will return the paramters of the link * and then set them in as the latest parameters to be retrieved by this method. By default, * sessions persist for the duration of time that the app is in focus. For example, if you * minimize the app, these parameters will be cleared when closeSession is called.</p> * * @return A {@link JSONObject} containing the latest referring parameters as * configured locally. */ public JSONObject getLatestReferringParams() { String storedParam = prefHelper_.getSessionParams(); return convertParamsStringToDictionary(storedParam); } /** * <p>Configures and requests a short URL to be generated by the Branch servers, via a synchronous * call; with a duration specified within which an app session should be matched to the link.</p> * * @return A {@link String} containing the resulting short URL. */ public String getShortUrlSync() { return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, null, null, null, stringifyParams(null), null, false); } /** * <p>Configures and requests a short URL to be generated by the Branch servers, via a synchronous * call; with a duration specified within which an app session should be matched to the link.</p> * * @param params A {@link JSONObject} value containing the deep linked params associated with * the link that will be passed into a new app session when clicked * * @return A {@link String} containing the resulting short URL. */ public String getShortUrlSync(JSONObject params) { return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, null, null, null, stringifyParams(filterOutBadCharacters(params)), null, false); } /** * <p>Configures and requests a referral URL to be generated by the Branch servers, via a synchronous * call; with a duration specified within which an app session should be matched to the link.</p> * * @param channel A {@link String} denoting the channel that the link belongs to. Should not * exceed 128 characters. * * @param params A {@link JSONObject} value containing the deep linked params associated with * the link that will be passed into a new app session when clicked * * @return A {@link String} containing the resulting referral URL. */ public String getReferralUrlSync(String channel, JSONObject params) { return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, channel, FEATURE_TAG_REFERRAL, null, stringifyParams(filterOutBadCharacters(params)), null, false); } /** * <p>Configures and requests a referral URL to be generated by the Branch servers, via a synchronous * call; with a duration specified within which an app session should be matched to the link.</p> * * @param tags An iterable {@link Collection} of {@link String} tags associated with a deep * link. * * @param channel A {@link String} denoting the channel that the link belongs to. Should not * exceed 128 characters. * * @param params A {@link JSONObject} value containing the deep linked params associated with * the link that will be passed into a new app session when clicked * * @return A {@link String} containing the resulting referral URL. */ public String getReferralUrlSync(Collection<String> tags, String channel, JSONObject params) { return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, FEATURE_TAG_REFERRAL, null, stringifyParams(filterOutBadCharacters(params)), null, false); } /** * <p>Configures and requests a content URL (defined as feature = sharing) to be generated by the Branch servers, via a synchronous * call</p> * * @param channel A {@link String} denoting the channel that the link belongs to. Should not * exceed 128 characters. * * @param params A {@link JSONObject} value containing the deep linked params associated with * the link that will be passed into a new app session when clicked * * @return A {@link String} containing the resulting content URL. */ public String getContentUrlSync(String channel, JSONObject params) { return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, channel, FEATURE_TAG_SHARE, null, stringifyParams(filterOutBadCharacters(params)), null, false); } /** * <p>Configures and requests a content URL (defined as feature = sharing) to be generated by the Branch servers, via a synchronous * call</p> * * @param tags An iterable {@link Collection} of {@link String} tags associated with a deep * link. * * @param channel A {@link String} denoting the channel that the link belongs to. Should not * exceed 128 characters. * * @param params A {@link JSONObject} value containing the deep linked params associated with * the link that will be passed into a new app session when clicked * * @return A {@link String} containing the resulting content URL. */ public String getContentUrlSync(Collection<String> tags, String channel, JSONObject params) { return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, FEATURE_TAG_SHARE, null, stringifyParams(filterOutBadCharacters(params)), null, false); } /** * <p>Configures and requests a short URL to be generated by the Branch servers, via a synchronous * call; with a duration specified within which an app session should be matched to the link.</p> * * @param channel A {@link String} denoting the channel that the link belongs to. Should not * exceed 128 characters. * * @param feature A {@link String} value identifying the feature that the link makes use of. * Should not exceed 128 characters. * * @param stage A {@link String} value identifying the stage in an application or user flow process. * Should not exceed 128 characters. * * @param params A {@link JSONObject} value containing the deep linked params associated with * the link that will be passed into a new app session when clicked * * @return A {@link String} containing the resulting short URL. */ public String getShortUrlSync(String channel, String feature, String stage, JSONObject params) { return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), null, false); } public String getShortUrlSync(String alias, String channel, String feature, String stage, JSONObject params) { return generateShortLink(alias, LINK_TYPE_UNLIMITED_USE, 0, null, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), null, false); } /** * <p>Configures and requests a short URL to be generated by the Branch servers, via a synchronous * call; with a duration specified within which an app session should be matched to the link.</p> * * @param type An {@link int} that can be used for scenarios where you want the link to * only deep link the first time. * * @param channel A {@link String} denoting the channel that the link belongs to. Should not * exceed 128 characters. * * @param feature A {@link String} value identifying the feature that the link makes use of. * Should not exceed 128 characters. * * @param stage A {@link String} value identifying the stage in an application or user flow * process. Should not exceed 128 characters. * * @param params A {@link JSONObject} value containing the deep linked params associated with * the link that will be passed into a new app session when clicked * * @return A {@link String} containing the resulting short URL. */ public String getShortUrlSync(int type, String channel, String feature, String stage, JSONObject params) { return generateShortLink(null, type, 0, null, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), null, false); } /** * <p>Configures and requests a short URL to be generated by the Branch servers, via a synchronous * call; with a duration specified within which an app session should be matched to the link.</p> * * @param channel A {@link String} denoting the channel that the link belongs to. Should not * exceed 128 characters. * * @param feature A {@link String} value identifying the feature that the link makes use of. * Should not exceed 128 characters. * * @param stage A {@link String} value identifying the stage in an application or user flow * process. Should not exceed 128 characters. * * @param params A {@link JSONObject} value containing the deep linked params associated with * the link that will be passed into a new app session when clicked * * @param duration A {@link Integer} value specifying the time that Branch allows a click to * remain outstanding and be eligible to be matched with a new app session. * * @return A {@link String} containing the resulting short URL. */ public String getShortUrlSync(String channel, String feature, String stage, JSONObject params, int duration) { return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, duration, null, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), null, false); } /** * <p>Configures and requests a short URL to be generated by the Branch servers, via a synchronous * call; with a duration specified within which an app session should be matched to the link.</p> * * @param tags An iterable {@link Collection} of {@link String} tags associated with a deep * link. * * @param channel A {@link String} denoting the channel that the link belongs to. Should not * exceed 128 characters. * * @param feature A {@link String} value identifying the feature that the link makes use of. * Should not exceed 128 characters. * * @param stage A {@link String} value identifying the stage in an application or user flow * process. Should not exceed 128 characters. * * @param params A {@link JSONObject} value containing the deep linked params associated with * the link that will be passed into a new app session when clicked * * @return A {@link String} containing the resulting short URL. */ public String getShortUrlSync(Collection<String> tags, String channel, String feature, String stage, JSONObject params) { return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), null, false); } public String getShortUrlSync(String alias, Collection<String> tags, String channel, String feature, String stage, JSONObject params) { return generateShortLink(alias, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), null, false); } /** * <p>Configures and requests a short URL to be generated by the Branch servers, via a synchronous * call; with a duration specified within which an app session should be matched to the link.</p> * * @param type An {@link int} that can be used for scenarios where you want the link to * only deep link the first time. * * @param tags An iterable {@link Collection} of {@link String} tags associated with a deep * link. * * @param channel A {@link String} denoting the channel that the link belongs to. Should not * exceed 128 characters. * * @param feature A {@link String} value identifying the feature that the link makes use of. * Should not exceed 128 characters. * * @param stage A {@link String} value identifying the stage in an application or user flow * process. Should not exceed 128 characters. * * @param params A {@link JSONObject} value containing the deep linked params associated with * the link that will be passed into a new app session when clicked * * @return A {@link String} containing the resulting short URL. */ public String getShortUrlSync(int type, Collection<String> tags, String channel, String feature, String stage, JSONObject params) { return generateShortLink(null, type, 0, tags, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), null, false); } /** * <p>Configures and requests a short URL to be generated by the Branch servers, via a synchronous * call; with a duration specified within which an app session should be matched to the link.</p> * * @param tags An iterable {@link Collection} of {@link String} tags associated with a deep * link. * * @param channel A {@link String} denoting the channel that the link belongs to. Should not * exceed 128 characters. * * @param feature A {@link String} value identifying the feature that the link makes use of. * Should not exceed 128 characters. * * @param stage A {@link String} value identifying the stage in an application or user flow * process. Should not exceed 128 characters. * * @param params A {@link JSONObject} value containing the deep linked params associated with * the link that will be passed into a new app session when clicked * * @param duration A {@link Integer} value specifying the time that Branch allows a click to * remain outstanding and be eligible to be matched with a new app session. * * @return A {@link String} containing the resulting short URL. */ public String getShortUrlSync(Collection<String> tags, String channel, String feature, String stage, JSONObject params, int duration) { return generateShortLink(null, LINK_TYPE_UNLIMITED_USE, duration, tags, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), null, false); } /** * <p>Configures and requests a short URL to be generated by the Branch servers.</p> * * @param callback A {@link BranchLinkCreateListener} callback instance that will trigger * actions defined therein upon receipt of a response to a create link request. */ public void getShortUrl(BranchLinkCreateListener callback) { generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, null, null, null, stringifyParams(null), callback, true); } /** * <p>Configures and requests a short URL to be generated by the Branch servers.</p> * * @param params A {@link JSONObject} value containing the deep linked params associated with * the link that will be passed into a new app session when clicked * * @param callback A {@link BranchLinkCreateListener} callback instance that will trigger * actions defined therein upon receipt of a response to a create link request. * * @see BranchLinkData * @see BranchLinkData#putParams(String) * @see BranchLinkCreateListener */ public void getShortUrl(JSONObject params, BranchLinkCreateListener callback) { generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, null, null, null, stringifyParams(filterOutBadCharacters(params)), callback, true); } /** * <p>Configures and requests a referral URL (feature = referral) to be generated by the Branch servers.</p> * * @param channel A {@link String} denoting the channel that the link belongs to. Should not * exceed 128 characters. * * @param params A {@link JSONObject} value containing the deep linked params associated with * the link that will be passed into a new app session when clicked * * @param callback A {@link BranchLinkCreateListener} callback instance that will trigger * actions defined therein upon receipt of a response to a create link request. * * @see BranchLinkData * @see BranchLinkData#putChannel(String) * @see BranchLinkData#putParams(String) * @see BranchLinkCreateListener */ public void getReferralUrl(String channel, JSONObject params, BranchLinkCreateListener callback) { generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, channel, FEATURE_TAG_REFERRAL, null, stringifyParams(filterOutBadCharacters(params)), callback, true); } /** * <p>Configures and requests a referral URL (feature = referral) to be generated by the Branch servers.</p> * * @param tags An iterable {@link Collection} of {@link String} tags associated with a deep * link. * * @param channel A {@link String} denoting the channel that the link belongs to. Should not * exceed 128 characters. * * @param params A {@link JSONObject} value containing the deep linked params associated with * the link that will be passed into a new app session when clicked * * @param callback A {@link BranchLinkCreateListener} callback instance that will trigger * actions defined therein upon receipt of a response to a create link request. * * @see BranchLinkData * @see BranchLinkData#putTags(Collection) * @see BranchLinkData#putChannel(String) * @see BranchLinkData#putParams(String) * @see BranchLinkCreateListener */ public void getReferralUrl(Collection<String> tags, String channel, JSONObject params, BranchLinkCreateListener callback) { generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, FEATURE_TAG_REFERRAL, null, stringifyParams(filterOutBadCharacters(params)), callback, true); } /** * <p>Configures and requests a content URL (defined as feature = sharing) to be generated by the Branch servers.</p> * * @param channel A {@link String} denoting the channel that the link belongs to. Should not * exceed 128 characters. * * @param params A {@link JSONObject} value containing the deep linked params associated with * the link that will be passed into a new app session when clicked * * @param callback A {@link BranchLinkCreateListener} callback instance that will trigger * actions defined therein upon receipt of a response to a create link request. * * @see BranchLinkData * @see BranchLinkData#putChannel(String) * @see BranchLinkData#putParams(String) * @see BranchLinkCreateListener */ public void getContentUrl(String channel, JSONObject params, BranchLinkCreateListener callback) { generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, channel, FEATURE_TAG_SHARE, null, stringifyParams(filterOutBadCharacters(params)), callback, true); } /** * <p>Configures and requests a content URL (defined as feature = sharing) to be generated by the Branch servers.</p> * * @param tags An iterable {@link Collection} of {@link String} tags associated with a deep * link. * * @param channel A {@link String} denoting the channel that the link belongs to. Should not * exceed 128 characters. * * @param params A {@link JSONObject} value containing the deep linked params associated with * the link that will be passed into a new app session when clicked * * @param callback A {@link BranchLinkCreateListener} callback instance that will trigger * actions defined therein upon receipt of a response to a create link request. * * @see BranchLinkData * @see BranchLinkData#putTags(Collection) * @see BranchLinkData#putChannel(String) * @see BranchLinkData#putParams(String) * @see BranchLinkCreateListener */ public void getContentUrl(Collection<String> tags, String channel, JSONObject params, BranchLinkCreateListener callback) { generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, FEATURE_TAG_SHARE, null, stringifyParams(filterOutBadCharacters(params)), callback, true); } /** * <p>Configures and requests a short URL to be generated by the Branch servers.</p> * * @param channel A {@link String} denoting the channel that the link belongs to. Should not * exceed 128 characters. * * @param feature A {@link String} value identifying the feature that the link makes use of. * Should not exceed 128 characters. * * @param stage A {@link String} value identifying the stage in an application or user flow * process. Should not exceed 128 characters. * * @param params A {@link JSONObject} value containing the deep linked params associated with * the link that will be passed into a new app session when clicked * * @param callback A {@link BranchLinkCreateListener} callback instance that will trigger * actions defined therein upon receipt of a response to a create link request. * * @see BranchLinkData * @see BranchLinkData#putChannel(String) * @see BranchLinkData#putFeature(String) * @see BranchLinkData#putStage(String) * @see BranchLinkData#putParams(String) * @see BranchLinkCreateListener */ public void getShortUrl(String channel, String feature, String stage, JSONObject params, BranchLinkCreateListener callback) { generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, null, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), callback, true); } public void getShortUrl(String alias, String channel, String feature, String stage, JSONObject params, BranchLinkCreateListener callback) { generateShortLink(alias, LINK_TYPE_UNLIMITED_USE, 0, null, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), callback, true); } /** * <p>Configures and requests a short URL to be generated by the Branch servers.</p> * * @param type An {@link int} that can be used for scenarios where you want the link to * only deep link the first time. * * @param channel A {@link String} denoting the channel that the link belongs to. Should not * exceed 128 characters. * * @param feature A {@link String} value identifying the feature that the link makes use of. * Should not exceed 128 characters. * * @param stage A {@link String} value identifying the stage in an application or user flow process. * Should not exceed 128 characters. * * @param params A {@link JSONObject} value containing the deep linked params associated with * the link that will be passed into a new app session when clicked * * @param callback A {@link BranchLinkCreateListener} callback instance that will trigger * actions defined therein upon receipt of a response to a create link request. * * @see BranchLinkData * @see BranchLinkData#putType(int) * @see BranchLinkData#putChannel(String) * @see BranchLinkData#putFeature(String) * @see BranchLinkData#putStage(String) * @see BranchLinkData#putParams(String) * @see BranchLinkCreateListener */ public void getShortUrl(int type, String channel, String feature, String stage, JSONObject params, BranchLinkCreateListener callback) { generateShortLink(null, type, 0, null, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), callback, true); } /** * <p>Configures and requests a short URL to be generated by the Branch servers.</p> * * @param channel A {@link String} denoting the channel that the link belongs to. Should not * exceed 128 characters. * * @param feature A {@link String} value identifying the feature that the link makes use of. * Should not exceed 128 characters. * * @param stage A {@link String} value identifying the stage in an application or user flow * process. Should not exceed 128 characters. * * @param params A {@link JSONObject} value containing the deep linked params associated with * the link that will be passed into a new app session when clicked * * @param duration An {@link int} the time that Branch allows a click to remain outstanding and * be eligible to be matched with a new app session. * * @param callback A {@link BranchLinkCreateListener} callback instance that will trigger * actions defined therein upon receipt of a response to a create link request. * * @see BranchLinkData * @see BranchLinkData#putTags(Collection) * @see BranchLinkData#putChannel(String) * @see BranchLinkData#putFeature(String) * @see BranchLinkData#putStage(String) * @see BranchLinkData#putParams(String) * @see BranchLinkCreateListener */ public void getShortUrl(String channel, String feature, String stage, JSONObject params, int duration, BranchLinkCreateListener callback) { generateShortLink(null, LINK_TYPE_UNLIMITED_USE, duration, null, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), callback, true); } /** * <p>Configures and requests a short URL to be generated by the Branch servers.</p> * * @param tags An iterable {@link Collection} of {@link String} tags associated with a deep * link. * * @param channel A {@link String} denoting the channel that the link belongs to. Should not * exceed 128 characters. * * @param feature A {@link String} value identifying the feature that the link makes use of. * Should not exceed 128 characters. * * @param stage A {@link String} value identifying the stage in an application or user flow * process. Should not exceed 128 characters. * * @param params A {@link JSONObject} value containing the deep linked params associated with * the link that will be passed into a new app session when clicked * * @param callback A {@link BranchLinkCreateListener} callback instance that will trigger * actions defined therein upon receipt of a response to a create link request. * * @see BranchLinkData * @see BranchLinkData#putTags(Collection) * @see BranchLinkData#putChannel(String) * @see BranchLinkData#putFeature(String) * @see BranchLinkData#putStage(String) * @see BranchLinkData#putParams(String) * @see BranchLinkCreateListener */ public void getShortUrl(Collection<String> tags, String channel, String feature, String stage, JSONObject params, BranchLinkCreateListener callback) { generateShortLink(null, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), callback, true); } public void getShortUrl(String alias, Collection<String> tags, String channel, String feature, String stage, JSONObject params, BranchLinkCreateListener callback) { generateShortLink(alias, LINK_TYPE_UNLIMITED_USE, 0, tags, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), callback, true); } /** * <p>Configures and requests a short URL to be generated by the Branch servers.</p> * * @param type An {@link int} that can be used for scenarios where you want the link to * only deep link the first time. * * @param tags An iterable {@link Collection} of {@link String} tags associated with a deep * link. * * @param channel A {@link String} denoting the channel that the link belongs to. Should not * exceed 128 characters. * * @param feature A {@link String} value identifying the feature that the link makes use of. * Should not exceed 128 characters. * * @param stage A {@link String} value identifying the stage in an application or user flow * process. Should not exceed 128 characters. * * @param params A {@link JSONObject} value containing the deep linked params associated with * the link that will be passed into a new app session when clicked * * @param callback A {@link BranchLinkCreateListener} callback instance that will trigger * actions defined therein upon receipt of a response to a create link request. * * @see BranchLinkData * @see BranchLinkData#putType(int) * @see BranchLinkData#putTags(Collection) * @see BranchLinkData#putChannel(String) * @see BranchLinkData#putFeature(String) * @see BranchLinkData#putStage(String) * @see BranchLinkData#putParams(String) * @see BranchLinkCreateListener */ public void getShortUrl(int type, Collection<String> tags, String channel, String feature, String stage, JSONObject params, BranchLinkCreateListener callback) { generateShortLink(null, type, 0, tags, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), callback, true); } /** * <p>Configures and requests a short URL to be generated by the Branch servers.</p> * * @param tags An iterable {@link Collection} of {@link String} tags associated with a deep * link. * * @param channel A {@link String} denoting the channel that the link belongs to. Should not * exceed 128 characters. * * @param feature A {@link String} value identifying the feature that the link makes use of. * Should not exceed 128 characters. * * @param stage A {@link String} value identifying the stage in an application or user flow * process. Should not exceed 128 characters. * * @param params A {@link JSONObject} value containing the deep linked params associated with * the link that will be passed into a new app session when clicked * * @param duration An {@link int} the time that Branch allows a click to remain outstanding * and be eligible to be matched with a new app session. * * @param callback A {@link BranchLinkCreateListener} callback instance that will trigger * actions defined therein upon receipt of a response to a create link request. * * @see BranchLinkData * @see BranchLinkData#putTags(Collection) * @see BranchLinkData#putChannel(String) * @see BranchLinkData#putFeature(String) * @see BranchLinkData#putStage(String) * @see BranchLinkData#putParams(String) * @see BranchLinkData#putDuration(int) * @see BranchLinkCreateListener */ public void getShortUrl(Collection<String> tags, String channel, String feature, String stage, JSONObject params, int duration, BranchLinkCreateListener callback) { generateShortLink(null, LINK_TYPE_UNLIMITED_USE, duration, tags, channel, feature, stage, stringifyParams(filterOutBadCharacters(params)), callback, true); } /** * <p>Configures and requests a referral code to be generated by the Branch servers.</p> * * @param callback A {@link BranchReferralInitListener} callback instance that will trigger * actions defined therein upon receipt of a response to a referral code request. */ public void getReferralCode(BranchReferralInitListener callback) { ServerRequest req = new ServerRequestGetReferralCode(context_, callback); if (!req.constructError_ && !req.handleErrors(context_)) { handleNewRequest(req); } } /** * <p>Configures and requests a referral code to be generated by the Branch servers.</p> * * @param amount An {@link Integer} value of credits associated with this referral code. * * @param callback A {@link BranchReferralInitListener} callback instance that will trigger * actions defined therein upon receipt of a response to a referral code request. */ public void getReferralCode(final int amount, BranchReferralInitListener callback) { this.getReferralCode(null, amount, null, REFERRAL_BUCKET_DEFAULT, REFERRAL_CODE_AWARD_UNLIMITED, REFERRAL_CODE_LOCATION_REFERRING_USER, callback); } /** * <p>Configures and requests a referral code to be generated by the Branch servers.</p> * * @param prefix A {@link String} containing the developer-specified prefix code to be applied * to the start of a referral code. e.g. for code OFFER4867, the prefix would * be "OFFER". * * @param amount An {@link Integer} value of credits associated with this referral code. * * @param callback A {@link BranchReferralInitListener} callback instance that will trigger * actions defined therein upon receipt of a response to a referral code request. */ public void getReferralCode(final String prefix, final int amount, BranchReferralInitListener callback) { this.getReferralCode(prefix, amount, null, REFERRAL_BUCKET_DEFAULT, REFERRAL_CODE_AWARD_UNLIMITED, REFERRAL_CODE_LOCATION_REFERRING_USER, callback); } /** * <p>Configures and requests a referral code to be generated by the Branch servers.</p> * * @param amount An {@link Integer} value of credits associated with this referral code. * * @param expiration Optional expiration {@link Date} of the offer code. * * @param callback A {@link BranchReferralInitListener} callback instance that will trigger * actions defined therein upon receipt of a response to a referral code * request. */ public void getReferralCode(final int amount, final Date expiration, BranchReferralInitListener callback) { this.getReferralCode(null, amount, expiration, REFERRAL_BUCKET_DEFAULT, REFERRAL_CODE_AWARD_UNLIMITED, REFERRAL_CODE_LOCATION_REFERRING_USER, callback); } /** * <p>Configures and requests a referral code to be generated by the Branch servers.</p> * * @param prefix A {@link String} containing the developer-specified prefix code to be * applied to the start of a referral code. e.g. for code OFFER4867, the * prefix would be "OFFER". * * @param amount An {@link Integer} value of credits associated with this referral code. * * @param expiration Optional expiration {@link Date} of the offer code. * * @param callback A {@link BranchReferralInitListener} callback instance that will trigger * actions defined therein upon receipt of a response to a referral code * request. */ public void getReferralCode(final String prefix, final int amount, final Date expiration, BranchReferralInitListener callback) { this.getReferralCode(prefix, amount, expiration, REFERRAL_BUCKET_DEFAULT, REFERRAL_CODE_AWARD_UNLIMITED, REFERRAL_CODE_LOCATION_REFERRING_USER, callback); } /** * <p>Configures and requests a referral code to be generated by the Branch servers.</p> * * @param prefix A {@link String} containing the developer-specified prefix code to be * applied to the start of a referral code. e.g. for code OFFER4867, the * prefix would be "OFFER". * * @param amount An {@link Integer} value of credits associated with this referral code. * * @param calculationType The type of referral calculation. i.e. * {@link #LINK_TYPE_UNLIMITED_USE} or * {@link #LINK_TYPE_ONE_TIME_USE} * * @param location The user to reward for applying the referral code. * * <p>Valid options:</p> * * <ul> * <li>{@link #REFERRAL_CODE_LOCATION_REFERREE}</li> * <li>{@link #REFERRAL_CODE_LOCATION_REFERRING_USER}</li> * <li>{@link #REFERRAL_CODE_LOCATION_BOTH}</li> * </ul> * * @param callback A {@link BranchReferralInitListener} callback instance that will * trigger actions defined therein upon receipt of a response to a * referral code request. */ public void getReferralCode(final String prefix, final int amount, final int calculationType, final int location, BranchReferralInitListener callback) { this.getReferralCode(prefix, amount, null, REFERRAL_BUCKET_DEFAULT, calculationType, location, callback); } /** * <p>Configures and requests a referral code to be generated by the Branch servers.</p> * * @param prefix A {@link String} containing the developer-specified prefix code to * be applied to the start of a referral code. e.g. for code OFFER4867, * the prefix would be "OFFER". * @param amount An {@link Integer} value of credits associated with this referral code. * @param expiration Optional expiration {@link Date} of the offer code. * @param bucket A {@link String} value containing the name of the referral bucket * that the code will belong to. * @param calculationType The type of referral calculation. i.e. * {@link #LINK_TYPE_UNLIMITED_USE} or * {@link #LINK_TYPE_ONE_TIME_USE} * @param location The user to reward for applying the referral code. * <p/> * <p>Valid options:</p> * <p/> * <ul> * <li>{@link #REFERRAL_CODE_LOCATION_REFERREE}</li> * <li>{@link #REFERRAL_CODE_LOCATION_REFERRING_USER}</li> * <li>{@link #REFERRAL_CODE_LOCATION_BOTH}</li> * </ul> * @param callback A {@link BranchReferralInitListener} callback instance that will * trigger actions defined therein upon receipt of a response to a * referral code request. */ public void getReferralCode(final String prefix, final int amount, final Date expiration, final String bucket, final int calculationType, final int location, BranchReferralInitListener callback) { String date = null; if (expiration != null) date = convertDate(expiration); ServerRequest req = new ServerRequestGetReferralCode(context_, prefix, amount, date, bucket, calculationType, location, callback); if (!req.constructError_ && !req.handleErrors(context_)) { handleNewRequest(req); } } /** * <p>Validates the supplied referral code on initialisation without applying it to the current * session.</p> * * @param code A {@link String} object containing the referral code supplied. * @param callback A {@link BranchReferralInitListener} callback to handle the server response * of the referral submission request. */ public void validateReferralCode(final String code, BranchReferralInitListener callback) { ServerRequest req = new ServerRequestValidateReferralCode(context_, callback, code); if (!req.constructError_ && !req.handleErrors(context_)) { handleNewRequest(req); } } /** * <p>Applies a supplied referral code to the current user session upon initialisation.</p> * * @param code A {@link String} object containing the referral code supplied. * @param callback A {@link BranchReferralInitListener} callback to handle the server * response of the referral submission request. * @see BranchReferralInitListener */ public void applyReferralCode(final String code, final BranchReferralInitListener callback) { ServerRequest req = new ServerRequestApplyReferralCode(context_, callback, code); if (!req.constructError_ && !req.handleErrors(context_)) { handleNewRequest(req); } } // PRIVATE FUNCTIONS private String convertDate(Date date) { return android.text.format.DateFormat.format("yyyy-MM-dd", date).toString(); } private String stringifyParams(JSONObject params) { if (params == null) { params = new JSONObject(); } try { params.put("source", "android"); } catch (JSONException e) { e.printStackTrace(); } return params.toString(); } private String generateShortLink(final String alias, final int type, final int duration, final Collection<String> tags, final String channel, final String feature, final String stage, final String params, BranchLinkCreateListener callback, boolean async) { ServerRequestCreateUrl req = new ServerRequestCreateUrl(context_, alias, type, duration, tags, channel, feature, stage, params, callback, async); if (!req.constructError_ && !req.handleErrors(context_)) { if (linkCache_.containsKey(req.getLinkPost())) { String url = linkCache_.get(req.getLinkPost()); if (callback != null) { callback.onLinkCreate(url, null); } return url; } else { if (async) { generateShortLinkAsync(req); } else { return generateShortLinkSync(req); } } } return null; } private String generateShortLinkSync(ServerRequest req) { if (initState_ == SESSION_STATE.INITIALISED) { ServerResponse response = kRemoteInterface_.createCustomUrlSync(req.getPost()); String url = prefHelper_.getUserURL(); if (response.getStatusCode() == 200) { try { url = response.getObject().getString("url"); if (response.getLinkData() != null) { linkCache_.put(response.getLinkData(), url); } } catch (JSONException e) { e.printStackTrace(); } } return url; } else { Log.i("BranchSDK", "Branch Warning: User session has not been initialized"); } return null; } private void generateShortLinkAsync(final ServerRequest req) { handleNewRequest(req); } private JSONObject filterOutBadCharacters(JSONObject inputObj) { JSONObject filteredObj = new JSONObject(); if (inputObj != null) { Iterator<?> keys = inputObj.keys(); while (keys.hasNext()) { String key = (String) keys.next(); try { if (inputObj.has(key) && inputObj.get(key).getClass().equals(String.class)) { filteredObj.put(key, inputObj.getString(key).replace("\n", "\\n").replace("\r", "\\r").replace("\"", "\\\"")); } else if (inputObj.has(key)) { filteredObj.put(key, inputObj.get(key)); } } catch(JSONException ignore) { } } } return filteredObj; } private JSONObject convertParamsStringToDictionary(String paramString) { if (paramString.equals(PrefHelper.NO_STRING_VALUE)) { return new JSONObject(); } else { try { return new JSONObject(paramString); } catch (JSONException e) { byte[] encodedArray = Base64.decode(paramString.getBytes(), Base64.NO_WRAP); try { return new JSONObject(new String(encodedArray)); } catch (JSONException ex) { ex.printStackTrace(); return new JSONObject(); } } } } /** * <p>Schedules a repeating threaded task to get the following details and report them to the * Branch API <b>once a week</b>:</p> * <p/> * <pre style="background:#fff;padding:10px;border:2px solid silver;"> * int interval = 7 * 24 * 60 * 60; * appListingSchedule_ = scheduler.scheduleAtFixedRate( * periodicTask, (days * 24 + hours) * 60 * 60, interval, TimeUnit.SECONDS);</pre> * <p/> * <ul> * <li>{@link SystemObserver#getAppKey()}</li> * <li>{@link SystemObserver#getOS()}</li> * <li>{@link SystemObserver#getDeviceFingerPrintID()}</li> * <li>{@link SystemObserver#getListOfApps()}</li> * </ul> * * @see {@link SystemObserver} * @see {@link PrefHelper} */ private void scheduleListOfApps() { ScheduledThreadPoolExecutor scheduler = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1); Runnable periodicTask = new Runnable() { @Override public void run() { ServerRequest req = new ServerRequestSendAppList(context_); if (!req.constructError_ && !req.handleErrors(context_)) { handleNewRequest(req); } } }; Date date = new Date(); Calendar calendar = GregorianCalendar.getInstance(); calendar.setTime(date); int days = Calendar.SATURDAY - calendar.get(Calendar.DAY_OF_WEEK); // days to Saturday int hours = 2 - calendar.get(Calendar.HOUR_OF_DAY); // hours to 2am, can be negative if (days == 0 && hours < 0) { days = 7; } int interval = 7 * 24 * 60 * 60; appListingSchedule_ = scheduler.scheduleAtFixedRate(periodicTask, (days * 24 + hours) * 60 * 60, interval, TimeUnit.SECONDS); } private void processNextQueueItem() { try { serverSema_.acquire(); if (networkCount_ == 0 && requestQueue_.getSize() > 0) { networkCount_ = 1; ServerRequest req = requestQueue_.peek(); serverSema_.release(); //All request except Install request need a valid IdentityID if (!(req instanceof ServerRequestRegisterInstall) && !hasUser()) { Log.i("BranchSDK", "Branch Error: User session has not been initialized!"); networkCount_ = 0; handleFailure(requestQueue_.getSize() - 1, BranchError.ERR_NO_SESSION); return; } //All request except open and install need a session to execute else if (!req.isSessionInitRequest() && (!hasSession() || !hasDeviceFingerPrint())) { networkCount_ = 0; handleFailure(requestQueue_.getSize() - 1, BranchError.ERR_NO_SESSION); return; } else { BranchPostTask postTask = new BranchPostTask(req); postTask.execute(); } } else { serverSema_.release(); } } catch (Exception e) { e.printStackTrace(); } } private void handleFailure(int index, int statusCode) { ServerRequest req; if (index >= requestQueue_.getSize()) { req = requestQueue_.peekAt(requestQueue_.getSize() - 1); } else { req = requestQueue_.peekAt(index); } handleFailure(req, statusCode); } private void handleFailure(final ServerRequest req, int statusCode) { if (req == null) return; req.handleFailure(statusCode); } private void updateAllRequestsInQueue() { try { for (int i = 0; i < requestQueue_.getSize(); i++) { ServerRequest req = requestQueue_.peekAt(i); if (req.getPost() != null) { Iterator<?> keys = req.getPost().keys(); while (keys.hasNext()) { String key = (String) keys.next(); if (key.equals(Defines.Jsonkey.SessionID.getKey())) { req.getPost().put(key, prefHelper_.getSessionID()); } else if (key.equals(Defines.Jsonkey.IdentityID.getKey())) { req.getPost().put(key, prefHelper_.getIdentityID()); } } } } } catch (JSONException e) { e.printStackTrace(); } } private void clearCloseTimer() { if (rotateCloseTimer == null) return; rotateCloseTimer.cancel(); rotateCloseTimer.purge(); rotateCloseTimer = new Timer(); } private void clearTimer() { if (closeTimer == null) return; closeTimer.cancel(); closeTimer.purge(); closeTimer = new Timer(); } private void keepAlive() { keepAlive_ = true; synchronized(lock) { clearTimer(); closeTimer.schedule(new TimerTask() { @Override public void run() { new Thread(new Runnable() { @Override public void run() { keepAlive_ = false; } }).start(); } }, SESSION_KEEPALIVE); } } private boolean hasSession() { return !prefHelper_.getSessionID().equals(PrefHelper.NO_STRING_VALUE); } private boolean hasDeviceFingerPrint() { return !prefHelper_.getDeviceFingerPrintID().equals(PrefHelper.NO_STRING_VALUE); } private boolean hasUser() { return !prefHelper_.getIdentityID().equals(PrefHelper.NO_STRING_VALUE); } private void insertRequestAtFront(ServerRequest req) { if (networkCount_ == 0) { requestQueue_.insert(req, 0); } else { requestQueue_.insert(req, 1); } } private void registerInstallOrOpen(ServerRequest req, BranchReferralInitListener callback) { // If there isn't already an Open / Install request, add one to the queue if (!requestQueue_.containsInstallOrOpen()) { insertRequestAtFront(req); } // If there is already one in the queue, make sure it's in the front. // Make sure a callback is associated with this request. This callback can // be cleared if the app is terminated while an Open/Install is pending. else { requestQueue_.moveInstallOrOpenToFront(req, networkCount_, callback); } processNextQueueItem(); } private void initializeSession(BranchReferralInitListener callback) { if ((prefHelper_.getBranchKey() == null || prefHelper_.getBranchKey().equalsIgnoreCase(PrefHelper.NO_STRING_VALUE)) && (prefHelper_.getAppKey() == null || prefHelper_.getAppKey().equalsIgnoreCase(PrefHelper.NO_STRING_VALUE))) { initState_ = SESSION_STATE.UNINITIALISED; //Report Key error on callback if (callback != null) { callback.onInitFinished(null, new BranchError("Trouble initializing Branch.", RemoteInterface.NO_BRANCH_KEY_STATUS)); } Log.i("BranchSDK", "Branch Warning: Please enter your branch_key in your project's res/values/strings.xml!"); return; } else if (prefHelper_.getBranchKey() != null && prefHelper_.getBranchKey().startsWith("key_test_")) { Log.i("BranchSDK", "Branch Warning: You are using your test app's Branch Key. Remember to change it to live Branch Key during deployment."); } if (hasUser()) { registerInstallOrOpen(new ServerRequestRegisterOpen(context_, callback, kRemoteInterface_.getSystemObserver()), callback); } else { registerInstallOrOpen(new ServerRequestRegisterInstall(context_, callback, kRemoteInterface_.getSystemObserver(), PrefHelper.NO_STRING_VALUE), callback); } } /** * Handles execution of a new request other than open or install. * Checks for the session initialisation and adds a install/Open request in front of this request * if the request need session to execute. * * @param req The {@link ServerRequest} to execute */ private void handleNewRequest(ServerRequest req) { //If not initialised put an open or install request in front of this request(only if this needs session) if (initState_ != SESSION_STATE.INITIALISED && req.isSessionInitRequest() == false) { if((req instanceof ServerRequestLogout)){ Log.i(TAG, "Branch is not initialized, cannot logout"); return; } if((req instanceof ServerRequestRegisterClose)){ Log.i(TAG, "Branch is not initialized, cannot close session"); return; } else{ initializeSession(null); } } requestQueue_.enqueue(req); processNextQueueItem(); } @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) private void setActivityLifeCycleObserver(Application application) { try { activityLifeCycleObserver_ = new BranchActivityLifeCycleObserver(); /* Set an observer for activity life cycle events. */ application.unregisterActivityLifecycleCallbacks(activityLifeCycleObserver_); application.registerActivityLifecycleCallbacks(activityLifeCycleObserver_); isActivityLifeCycleCallbackRegistered_ = true; } catch (NoSuchMethodError Ex) { isActivityLifeCycleCallbackRegistered_ = false; /* LifeCycleEvents are available only from API level 14. */ Log.w(TAG, BranchException.BRANCH_API_LVL_ERR_MSG); } } /** * <p>Class that observes activity life cycle events and determines when to start and stop * session.</p> */ @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) private class BranchActivityLifeCycleObserver implements Application.ActivityLifecycleCallbacks{ private int activityCnt_ = 0; //Keep the count of live activities. @Override public void onActivityCreated(Activity activity, Bundle bundle) {} @Override public void onActivityStarted(Activity activity) { if (activityCnt_ < 1) { // Check if this is the first Activity.If so start a session. initSession();// indicate starting of session. } activityCnt_++; } @Override public void onActivityResumed(Activity activity) { //Set the activity for touch debug if (prefHelper_.getTouchDebugging()) { setTouchDebugInternal(activity); } } @Override public void onActivityPaused(Activity activity) { clearTouchDebugInternal(activity); } @Override public void onActivityStopped(Activity activity) { activityCnt_--; // Check if this is the last activity.If so stop // session. if (activityCnt_ < 1) { closeSessionInternal(); } } @Override public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {} @Override public void onActivityDestroyed(Activity activity) {} } /** * <p>An Interface class that is implemented by all classes that make use of * {@link BranchReferralInitListener}, defining a single method that takes a list of params in * {@link JSONObject} format, and an error message of {@link BranchError} format that will be * returned on failure of the request response.</p> * * @see JSONObject * @see BranchError */ public interface BranchReferralInitListener { public void onInitFinished(JSONObject referringParams, BranchError error); } /** * <p>An Interface class that is implemented by all classes that make use of * {@link BranchReferralStateChangedListener}, defining a single method that takes a value of * {@link Boolean} format, and an error message of {@link BranchError} format that will be * returned on failure of the request response.</p> * * @see Boolean * @see BranchError */ public interface BranchReferralStateChangedListener { public void onStateChanged(boolean changed, BranchError error); } /** * <p>An Interface class that is implemented by all classes that make use of * {@link BranchLinkCreateListener}, defining a single method that takes a URL * {@link String} format, and an error message of {@link BranchError} format that will be * returned on failure of the request response.</p> * * @see String * @see BranchError */ public interface BranchLinkCreateListener { public void onLinkCreate(String url, BranchError error); } /** * <p>An Interface class that is implemented by all classes that make use of * {@link BranchListResponseListener}, defining a single method that takes a list of * {@link JSONArray} format, and an error message of {@link BranchError} format that will be * returned on failure of the request response.</p> * * @see JSONArray * @see BranchError */ public interface BranchListResponseListener { public void onReceivingResponse(JSONArray list, BranchError error); } /** * <p>enum containing the sort options for return of credit history.</p> */ public enum CreditHistoryOrder { kMostRecentFirst, kLeastRecentFirst } /** * Asynchronous task handling execution of server requests. Execute the network task on background * thread and request are executed in sequential manner. Handles the request execution in * Synchronous-Asynchronous pattern. Should be invoked only form main thread and the results are * published in the main thread. */ private class BranchPostTask extends AsyncTask<Void, Void, ServerResponse> { int timeOut_ = 0; ServerRequest thisReq_; public BranchPostTask(ServerRequest request) { thisReq_ = request; timeOut_ = prefHelper_.getTimeout(); } @Override protected ServerResponse doInBackground(Void... voids) { if (thisReq_.isGetRequest()) { return kRemoteInterface_.make_restful_get(thisReq_.getRequestUrl(), thisReq_.getRequestPath(), timeOut_); } else { return kRemoteInterface_.make_restful_post(thisReq_.getPost(), thisReq_.getRequestUrl(), thisReq_.getRequestPath(), timeOut_); } } @Override protected void onPostExecute(ServerResponse serverResponse) { super.onPostExecute(serverResponse); if (serverResponse != null) { try { int status = serverResponse.getStatusCode(); hasNetwork_ = true; //If the request is not succeeded if (status != 200) { //If failed request is an initialisation request then mark session not initialised if (thisReq_.isSessionInitRequest()) { initState_ = SESSION_STATE.UNINITIALISED; } //On a bad request continue processing if (status == 409) { if (thisReq_ instanceof ServerRequestCreateUrl) { ((ServerRequestCreateUrl) thisReq_).handleDuplicateURLError(); } else { Log.i("BranchSDK", "Branch API Error: Conflicting resource error code from API"); handleFailure(0, status); } } //On Network error or Branch is down fail all the pending requests in the queue except //for request which need to be replayed on failure. else { hasNetwork_ = false; //Collect all request from the queue which need to be failed. ArrayList<ServerRequest> requestToFail = new ArrayList<ServerRequest>(); for (int i = 0; i < requestQueue_.getSize(); i++) { requestToFail.add(requestQueue_.peekAt(i)); } //Remove the requests from the request queue first for (ServerRequest req : requestToFail) { if (!req.shouldRetryOnFail()) { requestQueue_.remove(req); } } // Then, set the network count to zero, indicating that requests can be started again. networkCount_ = 0; //Finally call the request callback with the error. for (ServerRequest req : requestToFail) { req.handleFailure(status); //If request need to be replayed, no need for the callbacks if (req.shouldRetryOnFail()) req.clearCallbacks(); } } } //If the request succeeded else { hasNetwork_ = true; //On create new url cache the url. if (thisReq_ instanceof ServerRequestCreateUrl) { final String url = serverResponse.getObject().getString("url"); // cache the link linkCache_.put(serverResponse.getLinkData(), url); } //On Logout clear the link cache and all pending requests else if (thisReq_ instanceof ServerRequestLogout) { linkCache_.clear(); requestQueue_.clear(); } //On setting a new identity Id clear teh link cache else if (thisReq_ instanceof ServerRequestIdentifyUserRequest) { try { String new_Identity_Id = serverResponse.getObject().getString(Defines.Jsonkey.IdentityID.getKey()); if (!prefHelper_.getIdentityID().equals(new_Identity_Id)) { linkCache_.clear(); } } catch (Exception ignore) { } } //Publish success to listeners thisReq_.onRequestSucceeded(serverResponse, branchReferral_); //If this request changes a session update the session-id to queued requests. if (thisReq_.isSessionInitRequest()) { updateAllRequestsInQueue(); initState_ = SESSION_STATE.INITIALISED; } requestQueue_.dequeue(); } networkCount_ = 0; if (hasNetwork_ && initState_ != SESSION_STATE.UNINITIALISED) { processNextQueueItem(); } } catch (JSONException ex) { ex.printStackTrace(); } } } } public class BranchWindowCallback implements Window.Callback { private Runnable longPressed_; private Window.Callback callback_; public BranchWindowCallback(Window.Callback callback) { callback_ = callback; if (longPressed_ == null) { longPressed_ = new Runnable() { private Timer timer; public void run() { debugHandler_.removeCallbacks(longPressed_); if (!debugStarted_) { Log.i("Branch Debug","======= Start Debug Session ======="); prefHelper_.setDebug(); timer = new Timer(); timer.scheduleAtFixedRate(new KeepDebugConnectionTask(), new Date(), 20000); } else { Log.i("Branch Debug","======= End Debug Session ======="); prefHelper_.clearDebug(); if (timer != null) { timer.cancel(); timer = null; } } debugStarted_ = !debugStarted_; } }; } } class KeepDebugConnectionTask extends TimerTask { public void run() { if (debugStarted_ && !prefHelper_.keepDebugConnection() && longPressed_ != null) { debugHandler_.post(longPressed_); } } } @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1) @Override public boolean dispatchGenericMotionEvent(MotionEvent event) { return callback_.dispatchGenericMotionEvent(event); } @Override public boolean dispatchKeyEvent(KeyEvent event) { return callback_.dispatchKeyEvent(event); } @TargetApi(Build.VERSION_CODES.HONEYCOMB) @Override public boolean dispatchKeyShortcutEvent(KeyEvent event) { return callback_.dispatchKeyShortcutEvent(event); } @Override public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { return callback_.dispatchPopulateAccessibilityEvent(event); } @Override public boolean dispatchTouchEvent(MotionEvent event) { switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: if (systemObserver_.isSimulator()) { debugHandler_.postDelayed(longPressed_, PrefHelper.DEBUG_TRIGGER_PRESS_TIME); } break; case MotionEvent.ACTION_MOVE: break; case MotionEvent.ACTION_CANCEL: debugHandler_.removeCallbacks(longPressed_); break; case MotionEvent.ACTION_UP: debugHandler_.removeCallbacks(longPressed_); break; case MotionEvent.ACTION_POINTER_DOWN: if (event.getPointerCount() == PrefHelper.DEBUG_TRIGGER_NUM_FINGERS) { debugHandler_.postDelayed(longPressed_, PrefHelper.DEBUG_TRIGGER_PRESS_TIME); } break; default: break; } return callback_.dispatchTouchEvent(event); } @Override public boolean dispatchTrackballEvent(MotionEvent event) { return callback_.dispatchTrackballEvent(event); } @Override public void onActionModeFinished(ActionMode mode) { callback_.onActionModeFinished(mode); } @Override public void onActionModeStarted(ActionMode mode) { callback_.onActionModeStarted(mode); } @Override public void onAttachedToWindow() { callback_.onAttachedToWindow(); } @Override public void onContentChanged() { callback_.onContentChanged(); } @Override public boolean onCreatePanelMenu(int featureId, Menu menu) { return callback_.onCreatePanelMenu(featureId, menu); } @Override public View onCreatePanelView(int featureId) { return callback_.onCreatePanelView(featureId); } @SuppressLint("MissingSuperCall") @Override public void onDetachedFromWindow() { callback_.onDetachedFromWindow(); } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { return callback_.onMenuItemSelected(featureId, item); } @Override public boolean onMenuOpened(int featureId, Menu menu) { return callback_.onMenuOpened(featureId, menu); } @Override public void onPanelClosed(int featureId, Menu menu) { callback_.onPanelClosed(featureId, menu); } @Override public boolean onPreparePanel(int featureId, View view, Menu menu) { return callback_.onPreparePanel(featureId, view, menu); } @Override public boolean onSearchRequested() { return callback_.onSearchRequested(); } @Override public void onWindowAttributesChanged(WindowManager.LayoutParams attrs) { callback_.onWindowAttributesChanged(attrs); } @Override public void onWindowFocusChanged(boolean hasFocus) { callback_.onWindowFocusChanged(hasFocus); } @TargetApi(Build.VERSION_CODES.HONEYCOMB) @Override public ActionMode onWindowStartingActionMode(ActionMode.Callback callback) { return callback_.onWindowStartingActionMode(callback); } } }
package org.codehaus.groovy.control; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.security.CodeSource; import java.util.*; import org.codehaus.groovy.GroovyBugError; import org.codehaus.groovy.ast.ASTNode; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.CompileUnit; import org.codehaus.groovy.ast.ModuleNode; import org.codehaus.groovy.classgen.AsmClassGenerator; import org.codehaus.groovy.classgen.ClassCompletionVerifier; import org.codehaus.groovy.classgen.ClassGenerator; import org.codehaus.groovy.classgen.GeneratorContext; import org.codehaus.groovy.classgen.VariableScopeVisitor; import org.codehaus.groovy.classgen.Verifier; import org.codehaus.groovy.control.io.InputStreamReaderSource; import org.codehaus.groovy.control.io.ReaderSource; import org.codehaus.groovy.control.messages.ExceptionMessage; import org.codehaus.groovy.control.messages.Message; import org.codehaus.groovy.control.messages.SimpleMessage; import org.codehaus.groovy.syntax.SyntaxException; import org.codehaus.groovy.syntax.ClassSource; import org.codehaus.groovy.syntax.SourceSummary; import org.codehaus.groovy.tools.GroovyClass; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.ClassWriter; import groovy.lang.GroovyClassLoader; import groovy.lang.GroovyRuntimeException; /** * Collects all compilation data as it is generated by the compiler system. * Allows additional source units to be added and compilation run again (to * affect only the deltas). * * @author <a href="mailto:cpoirier@dreaming.org">Chris Poirier</a> * @author <a href="mailto:blackdrag@gmx.org">Jochen Theodorou</a> * @version $Id$ */ public class CompilationUnit extends ProcessingUnit { // CONSTRUCTION AND SUCH protected HashMap sources; // The SourceUnits from which this unit is built protected Map summariesBySourceName; // Summary of each SourceUnit protected Map summariesByPublicClassName; // Summary of each SourceUnit protected Map classSourcesByPublicClassName; // Summary of each Class protected ArrayList names; // Names for each SourceUnit in sources. protected LinkedList queuedSources; protected CompileUnit ast; // The overall AST for this CompilationUnit. protected ArrayList generatedClasses; // The classes generated during classgen. protected Verifier verifier; // For use by verify(). protected boolean debug; // Controls behaviour of classgen() and other routines. protected boolean configured; // Set true after the first configure() operation protected ClassgenCallback classgenCallback; // A callback for use during classgen() protected ProgressCallback progressCallback; // A callback for use during compile() protected ResolveVisitor resolveVisitor; LinkedList[] phaseOperations; /** * Initializes the CompilationUnit with defaults. */ public CompilationUnit() { this(null, null, null); } /** * Initializes the CompilationUnit with defaults except for class loader. */ public CompilationUnit(GroovyClassLoader loader) { this(null, null, loader); } /** * Initializes the CompilationUnit with no security considerations. */ public CompilationUnit(CompilerConfiguration configuration) { this(configuration, null, null); } /** * Initializes the CompilationUnit with a CodeSource for controlling * security stuff and a class loader for loading classes. */ public CompilationUnit(CompilerConfiguration configuration, CodeSource security, GroovyClassLoader loader) { super(configuration, loader, null); this.names = new ArrayList(); this.queuedSources = new LinkedList(); this.sources = new HashMap(); this.summariesBySourceName = new HashMap(); this.summariesByPublicClassName = new HashMap(); this.classSourcesByPublicClassName = new HashMap(); this.ast = new CompileUnit(this.classLoader, security, this.configuration); this.generatedClasses = new ArrayList(); this.verifier = new Verifier(); this.resolveVisitor = new ResolveVisitor(this); phaseOperations = new LinkedList[Phases.ALL+1]; for (int i=0; i<phaseOperations.length; i++) { phaseOperations[i] = new LinkedList(); } addPhaseOperation(new SourceUnitOperation() { public void call(SourceUnit source) throws CompilationFailedException { source.parse(); } }, Phases.PARSING); addPhaseOperation(summarize, Phases.PARSING); addPhaseOperation(convert, Phases.CONVERSION); addPhaseOperation(resolve, Phases.SEMANTIC_ANALYSIS); addPhaseOperation(compileCompleteCheck, Phases.CANONICALIZATION); addPhaseOperation(classgen, Phases.CLASS_GENERATION); addPhaseOperation(output); this.classgenCallback = null; } public void addPhaseOperation(SourceUnitOperation op, int phase) { if (phase<0 || phase>Phases.ALL) throw new IllegalArgumentException("phase "+phase+" is unknown"); phaseOperations[phase].add(op); } public void addPhaseOperation(PrimaryClassNodeOperation op, int phase) { if (phase<0 || phase>Phases.ALL) throw new IllegalArgumentException("phase "+phase+" is unknown"); phaseOperations[phase].add(op); } public void addPhaseOperation(GroovyClassOperation op) { phaseOperations[Phases.OUTPUT].addFirst(op); } /** * Configures its debugging mode and classloader classpath from a given compiler configuration. * This cannot be done more than once due to limitations in {@link java.net.URLClassLoader URLClassLoader}. */ public void configure(CompilerConfiguration configuration) { super.configure(configuration); this.debug = configuration.getDebug(); if (!this.configured && this.classLoader instanceof GroovyClassLoader) { appendCompilerConfigurationClasspathToClassLoader(configuration, (GroovyClassLoader) this.classLoader); } this.configured = true; } private void appendCompilerConfigurationClasspathToClassLoader(CompilerConfiguration configuration, GroovyClassLoader classLoader) { /*for (Iterator iterator = configuration.getClasspath().iterator(); iterator.hasNext(); ) { classLoader.addClasspath((String) iterator.next()); }*/ } /** * Returns the CompileUnit that roots our AST. */ public CompileUnit getAST() { return this.ast; } /** * Get the source summaries */ public Map getSummariesBySourceName() { return summariesBySourceName; } public Map getSummariesByPublicClassName() { return summariesByPublicClassName; } public Map getClassSourcesByPublicClassName() { return classSourcesByPublicClassName; } public boolean isPublicClass(String className) { return summariesByPublicClassName.containsKey(className); } /** * Get the GroovyClasses generated by compile(). */ public List getClasses() { return generatedClasses; } /** * Convenience routine to get the first ClassNode, for * when you are sure there is only one. */ public ClassNode getFirstClassNode() { return (ClassNode) ((ModuleNode) this.ast.getModules().get(0)).getClasses().get(0); } /** * Convenience routine to get the named ClassNode. */ public ClassNode getClassNode(final String name) { final ClassNode[] result = new ClassNode[]{null}; PrimaryClassNodeOperation handler = new PrimaryClassNodeOperation() { public void call(SourceUnit source, GeneratorContext context, ClassNode classNode) { if (classNode.getName().equals(name)) { result[0] = classNode; } } }; try { applyToPrimaryClassNodes(handler); } catch (CompilationFailedException e) { if (debug) e.printStackTrace(); } return result[0]; } // SOURCE CREATION /** * Adds a set of file paths to the unit. */ public void addSources(String[] paths) { for (int i = 0; i < paths.length; i++) { File file = new File(paths[i]); addSource(file); } } /** * Adds a set of source files to the unit. */ public void addSources(File[] files) { for (int i = 0; i < files.length; i++) { addSource(files[i]); } } /** * Adds a source file to the unit. */ public SourceUnit addSource(File file) { return addSource(new SourceUnit(file, configuration, classLoader, getErrorCollector())); } /** * Adds a source file to the unit. */ public SourceUnit addSource(URL url) { return addSource(new SourceUnit(url, configuration, classLoader,getErrorCollector())); } /** * Adds a InputStream source to the unit. */ public SourceUnit addSource(String name, InputStream stream) { ReaderSource source = new InputStreamReaderSource(stream, configuration); return addSource(new SourceUnit(name, source, configuration, classLoader, getErrorCollector())); } /** * Adds a SourceUnit to the unit. */ public SourceUnit addSource(SourceUnit source) { String name = source.getName(); source.setClassLoader(this.classLoader); for (Iterator iter = queuedSources.iterator(); iter.hasNext();) { SourceUnit su = (SourceUnit) iter.next(); if (name.equals(su.getName())) return su; } queuedSources.add(source); return source; } /** * Returns an iterator on the unit's SourceUnits. */ public Iterator iterator() { return new Iterator() { Iterator nameIterator = names.iterator(); public boolean hasNext() { return nameIterator.hasNext(); } public Object next() { String name = (String) nameIterator.next(); return sources.get(name); } public void remove() { throw new UnsupportedOperationException(); } }; } /** * Adds a ClassNode directly to the unit (ie. without source). * WARNING: the source is needed for error reporting, using * this method without setting a SourceUnit will cause * NullPinterExceptions */ public void addClassNode(ClassNode node) { ModuleNode module = new ModuleNode(this.ast); this.ast.addModule(module); module.addClass(node); } // EXTERNAL CALLBACKS /** * A callback interface you can use to "accompany" the classgen() * code as it traverses the ClassNode tree. You will be called-back * for each primary and inner class. Use setClassgenCallback() before * running compile() to set your callback. */ public static abstract class ClassgenCallback { public abstract void call(ClassVisitor writer, ClassNode node) throws CompilationFailedException; } /** * Sets a ClassgenCallback. You can have only one, and setting * it to null removes any existing setting. */ public void setClassgenCallback(ClassgenCallback visitor) { this.classgenCallback = visitor; } /** * A callback interface you can use to get a callback after every * unit of the compile process. You will be called-back with a * ProcessingUnit and a phase indicator. Use setProgressCallback() * before running compile() to set your callback. */ public static abstract class ProgressCallback { public abstract void call(ProcessingUnit context, int phase) throws CompilationFailedException; } /** * Sets a ProgressCallback. You can have only one, and setting * it to null removes any existing setting. */ public void setProgressCallback(ProgressCallback callback) { this.progressCallback = callback; } // ACTIONS /** * Synonym for compile(Phases.ALL). */ public void compile() throws CompilationFailedException { compile(Phases.ALL); } /** * Compiles the compilation unit from sources. */ public void compile(int throughPhase) throws CompilationFailedException { // To support delta compilations, we always restart // the compiler. The individual passes are responsible // for not reprocessing old code. gotoPhase(Phases.INITIALIZATION); throughPhase = Math.min(throughPhase,Phases.ALL); while (throughPhase >= phase && phase <= Phases.ALL) { for (Iterator it = phaseOperations[phase].iterator(); it.hasNext();) { Object operation = it.next(); if (operation instanceof PrimaryClassNodeOperation) { applyToPrimaryClassNodes((PrimaryClassNodeOperation) operation); } else if (operation instanceof SourceUnitOperation) { applyToSourceUnits((SourceUnitOperation)operation); } else { applyToGeneratedGroovyClasses((GroovyClassOperation)operation); } } if (dequeued()) continue; if (progressCallback != null) progressCallback.call(this, phase); completePhase(); applyToSourceUnits(mark); gotoPhase(phase+1); if (phase==Phases.CLASS_GENERATION) { sortClasses(); } } errorCollector.failIfErrors(); } private void sortClasses() throws CompilationFailedException { Iterator modules = this.ast.getModules().iterator(); while (modules.hasNext()) { ModuleNode module = (ModuleNode) modules.next(); // before we actually do the sorting we should check // for cyclic references List classes = module.getClasses(); for (Iterator iter = classes.iterator(); iter.hasNext();) { ClassNode start = (ClassNode) iter.next(); ClassNode cn = start; HashSet parents = new HashSet(); do { if (parents.contains(cn.getName())) { getErrorCollector().addErrorAndContinue( new SimpleMessage("cyclic inheritance involving "+cn.getName()+" in class "+start.getName(),this) ); cn=null; } else { parents.add(cn.getName()); cn = cn.getSuperClass(); } } while (cn!=null); } errorCollector.failIfErrors(); module.sortClasses(); } } /** * Dequeues any source units add through addSource and resets the compiler phase * to initialization. * * Note: this does not mean a file is recompiled. If a SoucreUnit has already passed * a phase it is skipped until a higher phase is reached. * @return TODO * * @throws CompilationFailedException */ protected boolean dequeued() throws CompilationFailedException { boolean dequeue = !queuedSources.isEmpty(); while (!queuedSources.isEmpty()) { SourceUnit su = (SourceUnit) queuedSources.removeFirst(); String name = su.getName(); names.add(name); sources.put(name,su); } if (dequeue) { gotoPhase(Phases.INITIALIZATION); } return dequeue; } /** * Adds summary of each class to maps */ private SourceUnitOperation summarize = new SourceUnitOperation() { public void call(SourceUnit source) throws CompilationFailedException { SourceSummary sourceSummary = source.getSourceSummary(); if (sourceSummary != null) { summariesBySourceName.put(source.getName(),sourceSummary); List publicClassSources = sourceSummary.getPublicClassSources(); if (publicClassSources == null || publicClassSources.size() == 0) { //todo - is this the best way to handle scripts? summariesByPublicClassName.put("*NoName*",sourceSummary); // nothing to put into classSourcesByClassName as no ClassSource } else { Iterator itr = publicClassSources.iterator(); while (itr.hasNext()) { ClassSource classSource = (ClassSource)itr.next(); summariesByPublicClassName.put(classSource.getName(),sourceSummary); classSourcesByPublicClassName.put(classSource.getName(),classSource); } } } } }; /** * Resolves all types */ private SourceUnitOperation resolve = new SourceUnitOperation() { public void call(SourceUnit source) throws CompilationFailedException { List classes = source.ast.getClasses(); for (Iterator it = classes.iterator(); it.hasNext();) { ClassNode node = (ClassNode) it.next(); VariableScopeVisitor scopeVisitor = new VariableScopeVisitor(source); scopeVisitor.visitClass(node); resolveVisitor.startResolving(node,source); } } }; /** * Runs convert() on a single SourceUnit. */ private SourceUnitOperation convert = new SourceUnitOperation() { public void call(SourceUnit source) throws CompilationFailedException { source.convert(); CompilationUnit.this.ast.addModule(source.getAST()); if (CompilationUnit.this.progressCallback != null) { CompilationUnit.this.progressCallback.call(source, CompilationUnit.this.phase); } } }; private GroovyClassOperation output = new GroovyClassOperation() { public void call(GroovyClass gclass) throws CompilationFailedException { boolean failures = false; String name = gclass.getName().replace('.', File.separatorChar) + ".class"; File path = new File(configuration.getTargetDirectory(), name); // Ensure the path is ready for the file File directory = path.getParentFile(); if (directory != null && !directory.exists()) { directory.mkdirs(); } // Create the file and write out the data byte[] bytes = gclass.getBytes(); FileOutputStream stream = null; try { stream = new FileOutputStream(path); stream.write(bytes, 0, bytes.length); } catch (IOException e) { getErrorCollector().addError(Message.create(e.getMessage(),CompilationUnit.this)); failures = true; } finally { if (stream != null) { try { stream.close(); } catch (Exception e) { } } } } }; /* checks if all needed classes are compiled before generating the bytecode */ private SourceUnitOperation compileCompleteCheck = new SourceUnitOperation() { public void call(SourceUnit source) throws CompilationFailedException { List classes = source.ast.getClasses(); for (Iterator it = classes.iterator(); it.hasNext();) { ClassNode node = (ClassNode) it.next(); CompileUnit cu = node.getCompileUnit(); for (Iterator iter = cu.iterateClassNodeToCompile(); iter.hasNext();) { String name = (String) iter.next(); SourceUnit su = ast.getScriptSourceLocation(name); List classesInSourceUnit = su.ast.getClasses(); StringBuffer message = new StringBuffer(); message .append ("Compilation incomplete: expected to find the class ") .append (name) .append (" in ") .append (su.getName()); if (classesInSourceUnit.size()==0) { message.append(", but the file seems not to contain any classes"); } else { message.append(", but the file contains the classes: "); boolean first = true; for (Iterator suClassesIter = classesInSourceUnit .iterator(); suClassesIter.hasNext();) { ClassNode cn = (ClassNode) suClassesIter.next(); if (!first) { message.append(", "); } else { first=false; } message.append(cn.getName()); } } getErrorCollector().addErrorAndContinue( new SimpleMessage(message.toString(),CompilationUnit.this) ); iter.remove(); } } } }; /** * Runs classgen() on a single ClassNode. */ private PrimaryClassNodeOperation classgen = new PrimaryClassNodeOperation() { public boolean needSortedInput() { return true; } public void call(SourceUnit source, GeneratorContext context, ClassNode classNode) throws CompilationFailedException { // Run the Verifier on the outer class try { verifier.visitClass(classNode); } catch (GroovyRuntimeException rpe) { ASTNode node = rpe.getNode(); getErrorCollector().addError( new SyntaxException(rpe.getMessage(),null,node.getLineNumber(),node.getColumnNumber()), source ); } LabelVerifier lv = new LabelVerifier(source); lv.visitClass(classNode); ClassCompletionVerifier completionVerifier = new ClassCompletionVerifier(source); completionVerifier.visitClass(classNode); // because the class may be generated even if a error was found // and that class may have an invalid format we fail here if needed getErrorCollector().failIfErrors(); // Prep the generator machinery ClassVisitor visitor = createClassVisitor(); String sourceName = (source == null ? classNode.getModule().getDescription() : source.getName()); // only show the file name and its extension like javac does in its stacktraces rather than the full path // also takes care of both \ and / depending on the host compiling environment if (sourceName != null) sourceName = sourceName.substring(Math.max(sourceName.lastIndexOf('\\'), sourceName.lastIndexOf('/')) + 1); ClassGenerator generator = new AsmClassGenerator(context, visitor, classLoader, sourceName); // Run the generation and create the class (if required) generator.visitClass(classNode); byte[] bytes = ((ClassWriter) visitor).toByteArray(); generatedClasses.add(new GroovyClass(classNode.getName(), bytes)); // Handle any callback that's been set if (CompilationUnit.this.classgenCallback != null) { classgenCallback.call(visitor, classNode); } // Recurse for inner classes LinkedList innerClasses = generator.getInnerClasses(); while (!innerClasses.isEmpty()) { classgen.call(source, context, (ClassNode) innerClasses.removeFirst()); } } }; protected ClassVisitor createClassVisitor() { return new ClassWriter(true); } // PHASE HANDLING /** * Updates the phase marker on all sources. */ protected void mark() throws CompilationFailedException { applyToSourceUnits(mark); } /** * Marks a single SourceUnit with the current phase, * if it isn't already there yet. */ private SourceUnitOperation mark = new SourceUnitOperation() { public void call(SourceUnit source) throws CompilationFailedException { if (source.phase < phase) { source.gotoPhase(phase); } if (source.phase == phase && phaseComplete && !source.phaseComplete) { source.completePhase(); } } }; // LOOP SIMPLIFICATION FOR SourceUnit OPERATIONS /** * An callback interface for use in the applyToSourceUnits loop driver. */ public static abstract class SourceUnitOperation { public abstract void call(SourceUnit source) throws CompilationFailedException; } /** * A loop driver for applying operations to all SourceUnits. * Automatically skips units that have already been processed * through the current phase. */ public void applyToSourceUnits(SourceUnitOperation body) throws CompilationFailedException { Iterator keys = names.iterator(); while (keys.hasNext()) { String name = (String) keys.next(); SourceUnit source = (SourceUnit) sources.get(name); if ( (source.phase < phase) || (source.phase == phase && !source.phaseComplete)) { try { body.call(source); } catch (CompilationFailedException e) { throw e; } catch (Exception e) { GroovyBugError gbe = new GroovyBugError(e); changeBugText(gbe,source); throw gbe; } catch (GroovyBugError e) { changeBugText(e,source); throw e; } } } getErrorCollector().failIfErrors(); } // LOOP SIMPLIFICATION FOR PRIMARY ClassNode OPERATIONS /** * An callback interface for use in the applyToSourceUnits loop driver. */ public static abstract class PrimaryClassNodeOperation { public abstract void call(SourceUnit source, GeneratorContext context, ClassNode classNode) throws CompilationFailedException; public boolean needSortedInput(){ return false; } } public static abstract class GroovyClassOperation { public abstract void call(GroovyClass gclass) throws CompilationFailedException; } private List getPrimaryClassNodes(boolean sort) { ArrayList unsorted = new ArrayList(); Iterator modules = this.ast.getModules().iterator(); while (modules.hasNext()) { ModuleNode module = (ModuleNode) modules.next(); Iterator classNodes = module.getClasses().iterator(); while (classNodes.hasNext()) { ClassNode classNode = (ClassNode) classNodes.next(); unsorted.add(classNode); } } if(sort==false) return unsorted; int[] index = new int[unsorted.size()]; { int i = 0; for (Iterator iter = unsorted.iterator(); iter.hasNext(); i++) { ClassNode element = (ClassNode) iter.next(); int count = 0; while (element!=null){ count++; element = element.getSuperClass(); } index[i] = count; } } ArrayList sorted = new ArrayList(unsorted.size()); int start = 0; for (int i=0; i<index.length; i++) { int min = -1; for (int j=0; j<index.length; j++) { if (index[j]==-1) continue; if (min==-1) { min = j; } else if (index[j]<index[min]) { min = j; } } sorted.add(unsorted.get(min)); index[min] = -1; } return sorted; } /** * A loop driver for applying operations to all primary ClassNodes in * our AST. Automatically skips units that have already been processed * through the current phase. */ public void applyToPrimaryClassNodes(PrimaryClassNodeOperation body) throws CompilationFailedException { Iterator classNodes = getPrimaryClassNodes(body.needSortedInput()).iterator(); while (classNodes.hasNext()) { SourceUnit context=null; try { ClassNode classNode = (ClassNode) classNodes.next(); context = classNode.getModule().getContext(); if (context == null || context.phase <= phase) { body.call(context, new GeneratorContext(this.ast), classNode); } } catch (CompilationFailedException e) { // fall thorugh, getErrorREporter().failIfErrors() will triger } catch (NullPointerException npe){ throw npe; } catch (GroovyBugError e) { changeBugText(e,context); throw e; } catch (Exception e) { // check the exception for a nested compilation exception ErrorCollector nestedCollector = null; for (Throwable next = e.getCause(); next!=e && next!=null; next=next.getCause()) { if (!(next instanceof MultipleCompilationErrorsException)) continue; MultipleCompilationErrorsException mcee = (MultipleCompilationErrorsException) next; nestedCollector = mcee.collector; break; } if (nestedCollector!=null) { getErrorCollector().addCollectorContents(nestedCollector); } else { getErrorCollector().addError(new ExceptionMessage(e,configuration.getDebug(),this)); } } } getErrorCollector().failIfErrors(); } public void applyToGeneratedGroovyClasses(GroovyClassOperation body) throws CompilationFailedException { if (this.phase != Phases.OUTPUT && !(this.phase == Phases.CLASS_GENERATION && this.phaseComplete)) { throw new GroovyBugError("CompilationUnit not ready for output(). Current phase="+getPhaseDescription()); } boolean failures = false; Iterator iterator = this.generatedClasses.iterator(); while (iterator.hasNext()) { // Get the class and calculate its filesystem name GroovyClass gclass = (GroovyClass) iterator.next(); try { body.call(gclass); } catch (CompilationFailedException e) { // fall thorugh, getErrorREporter().failIfErrors() will triger } catch (NullPointerException npe){ throw npe; } catch (GroovyBugError e) { changeBugText(e,null); throw e; } catch (Exception e) { GroovyBugError gbe = new GroovyBugError(e); throw gbe; } } getErrorCollector().failIfErrors(); } private void changeBugText(GroovyBugError e, SourceUnit context) { e.setBugText("exception in phase '"+getPhaseDescription()+"' in source unit '"+((context!=null)?context.getName():"?")+"' "+e.getBugText()); } }
/* * Without any limit of programming knowledge, * let's try to produce an awesome class for generating that song! */ public class SongCrazy { public static void main(String[] args) { String[] animals = {"spider", "bird", "cat", "dog", "fennekin"}; String[] secondline = { "That wriggled and iggled and jiggled inside her.", "How absurd to swallow a bird.", "Imagine that to swallow a cat.", "What a hog to swallow a dog.", "I think she's burnin'." }; startLine("fly", "."); end(); for (int x = 0; x < 5; x++) { startLine(animals[x],","); System.out.println(secondline[x]); for (int y = x; y > 0; y swallowAtoCatchB(animals[y], animals[y-1]); } swallowAtoCatchB("spider", "fly"); end(); } System.out.println("There was an old woman who swallowed a horse,"); System.out.println("She died of course."); } public static void startLine(String something, String punctuation) { System.out.println("There was an old woman who swallowed a " + something + punctuation); } public static void swallowAtoCatchB(String first, String second) { System.out.println("She swallowed the " + first + " to catch the " + second + ","); } public static void end() { System.out.println("I don't know why she swallowed that fly,"); System.out.println("Perhaps she'll die.\n"); } }
package tutorial.outlier; import de.lmu.ifi.dbs.elki.algorithm.AbstractDistanceBasedAlgorithm; import de.lmu.ifi.dbs.elki.algorithm.outlier.OutlierAlgorithm; import de.lmu.ifi.dbs.elki.data.type.TypeInformation; import de.lmu.ifi.dbs.elki.data.type.TypeUtil; import de.lmu.ifi.dbs.elki.database.Database; import de.lmu.ifi.dbs.elki.database.datastore.DataStoreFactory; import de.lmu.ifi.dbs.elki.database.datastore.DataStoreUtil; import de.lmu.ifi.dbs.elki.database.datastore.WritableDoubleDataStore; import de.lmu.ifi.dbs.elki.database.ids.DBIDIter; import de.lmu.ifi.dbs.elki.database.ids.DBIDUtil; import de.lmu.ifi.dbs.elki.database.ids.DBIDs; import de.lmu.ifi.dbs.elki.database.ids.KNNList; import de.lmu.ifi.dbs.elki.database.query.distance.DistanceQuery; import de.lmu.ifi.dbs.elki.database.query.knn.KNNQuery; import de.lmu.ifi.dbs.elki.database.relation.DoubleRelation; import de.lmu.ifi.dbs.elki.database.relation.MaterializedDoubleRelation; import de.lmu.ifi.dbs.elki.database.relation.Relation; import de.lmu.ifi.dbs.elki.distance.distancefunction.DistanceFunction; import de.lmu.ifi.dbs.elki.logging.Logging; import de.lmu.ifi.dbs.elki.result.outlier.InvertedOutlierScoreMeta; import de.lmu.ifi.dbs.elki.result.outlier.OutlierResult; import de.lmu.ifi.dbs.elki.result.outlier.OutlierScoreMeta; import de.lmu.ifi.dbs.elki.utilities.documentation.Reference; import de.lmu.ifi.dbs.elki.utilities.optionhandling.OptionID; import de.lmu.ifi.dbs.elki.utilities.optionhandling.constraints.CommonConstraints; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameterization.Parameterization; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.IntParameter; @Reference(authors = "V. Hautamäki and I. Kärkkäinen and P. Fränti", title = "Outlier detection using k-nearest neighbour graph", booktitle = "Proc. 17th Int. Conf. Pattern Recognition, ICPR 2004", url = "http://dx.doi.org/10.1109/ICPR.2004.1334558") public class ODIN<O> extends AbstractDistanceBasedAlgorithm<O, OutlierResult> implements OutlierAlgorithm { /** * Class logger. */ private static final Logging LOG = Logging.getLogger(ODIN.class); /** * Number of neighbors for kNN graph. */ int k; /** * Constructor. * * @param distanceFunction Distance function * @param k k parameter */ public ODIN(DistanceFunction<? super O> distanceFunction, int k) { super(distanceFunction); this.k = k; } /** * Run the ODIN algorithm * * Tutorial note: the <em>signature</em> of this method depends on the types * that we requested in the {@link #getInputTypeRestriction} method. Here we * requested a single relation of type {@code O} , the data type of our * distance function. * * @param database Database to run on. * @param relation Relation to process. * @return ODIN outlier result. */ public OutlierResult run(Database database, Relation<O> relation) { // Get the query functions: DistanceQuery<O> dq = database.getDistanceQuery(relation, getDistanceFunction()); KNNQuery<O> knnq = database.getKNNQuery(dq, k); // Get the objects to process, and a data storage for counting and output: DBIDs ids = relation.getDBIDs(); WritableDoubleDataStore scores = DataStoreUtil.makeDoubleStorage(ids, DataStoreFactory.HINT_DB, 0.); // Process all objects for (DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) { // Find the nearest neighbors (using an index, if available!) KNNList neighbors = knnq.getKNNForDBID(iter, k); // For each neighbor, except ourselves, increase the in-degree: for (DBIDIter nei = neighbors.iter(); nei.valid(); nei.advance()) { if (DBIDUtil.equal(iter, nei)) { continue; } scores.put(nei, scores.doubleValue(nei) + 1); } } // Compute maximum double min = Double.POSITIVE_INFINITY, max = 0.0; for (DBIDIter iter = ids.iter(); iter.valid(); iter.advance()) { min = Math.min(min, scores.doubleValue(iter)); max = Math.max(max, scores.doubleValue(iter)); } // Wrap the result and add metadata. // By actually specifying theoretical min, max and baseline, we get a better // visualization (try it out - or see the screenshots in the tutorial)! OutlierScoreMeta meta = new InvertedOutlierScoreMeta(min, max, 0., ids.size() - 1, k); DoubleRelation rel = new MaterializedDoubleRelation("ODIN In-Degree", "odin", scores, ids); return new OutlierResult(meta, rel); } @Override public TypeInformation[] getInputTypeRestriction() { return TypeUtil.array(getDistanceFunction().getInputTypeRestriction()); } @Override protected Logging getLogger() { return LOG; } /** * Parameterization class. * * @author Erich Schubert * * @apiviz.exclude * * @param <O> Object type */ public static class Parameterizer<O> extends AbstractDistanceBasedAlgorithm.Parameterizer<O> { /** * Parameter for the number of nearest neighbors: * * <pre> * -odin.k &lt;int&gt; * </pre> */ public static final OptionID K_ID = new OptionID("odin.k", "Number of neighbors to use for kNN graph."); /** * Number of nearest neighbors to use. */ int k; @Override protected void makeOptions(Parameterization config) { super.makeOptions(config); IntParameter param = new IntParameter(K_ID); // Since in a database context, the 1 nearest neighbor // will usually be the query object itself, we require // this value to be at least 2. param.addConstraint(CommonConstraints.GREATER_THAN_ONE_INT); if (config.grab(param)) { k = param.intValue(); } } @Override protected ODIN<O> makeInstance() { return new ODIN<>(distanceFunction, k); } } }
package etomica.nbratom.cell; import etomica.Atom; import etomica.AtomIterator; import etomica.Phase; import etomica.PhaseCellManager; import etomica.PhaseEvent; import etomica.PhaseListener; import etomica.SimulationEvent; import etomica.Space; import etomica.action.AtomActionTranslateBy; import etomica.action.AtomGroupAction; import etomica.atom.AtomPositionDefinition; import etomica.atom.iterator.AtomIteratorTree; import etomica.data.DataSourceCOM; import etomica.integrator.MCMove; import etomica.integrator.mcmove.MCMoveEvent; import etomica.integrator.mcmove.MCMoveListener; import etomica.lattice.CellLattice; import etomica.space.Boundary; import etomica.space.Vector; /** * Class that defines and manages construction and use of lattice of cells * for cell-based neighbor listing. */ //TODO modify assignCellAll to loop through cells to get all atoms to be assigned //no need for index when assigning cell //different iterator needed public class NeighborCellManager implements PhaseCellManager { private final CellLattice lattice; private final Space space; private final AtomIteratorTree atomIterator; private final AtomPositionDefinition positionDefinition; private final Phase phase; /** * Constructs manager for neighbor cells in the given phase. The number of * cells in each dimension is given by nCells. Position definition for each * atom is that given by its type (it is set to null in this class). */ public NeighborCellManager(Phase phase, int nCells) { this(phase,nCells, null); } /** * Construct manager for neighbor cells in the given phase. The number * of cells in each dimension is given by nCells. Position definition is * used to determine the cell a given atom is in; if null, the position * definition given by the atom's type is used. Position definition is * declared final. */ public NeighborCellManager(Phase phase, int nCells, AtomPositionDefinition positionDefinition) { this.positionDefinition = positionDefinition; this.phase = phase; space = phase.space(); atomIterator = new AtomIteratorTree(); atomIterator.setDoAllNodes(true); atomIterator.setRoot(phase.speciesMaster); lattice = new CellLattice(phase.boundary().dimensions(), NeighborCell.FACTORY); int[] size = new int[space.D()]; for(int i=0; i<space.D(); i++) size[i] = nCells; lattice.setSize(size); //listener to phase to detect addition of new SpeciesAgent //or new atom phase.speciesMaster.addListener(new PhaseListener() { public void actionPerformed(SimulationEvent evt) { actionPerformed((PhaseEvent)evt); } public void actionPerformed(PhaseEvent evt) { if(evt.type() == PhaseEvent.ATOM_ADDED) { Atom atom = evt.atom(); //new species agent requires another list in each cell if(atom.type.getNbrManagerAgent().getPotentials().length > 0) { assignCell(atom); } } } }); } public CellLattice getLattice() { return lattice; } /** * Assigns cells to all molecules in the phase. */ public void assignCellAll() { atomIterator.reset(); while(atomIterator.hasNext()) { Atom atom = atomIterator.nextAtom(); if (atom.type.isInteracting() && (atom.type.getMass()!=Double.POSITIVE_INFINITY || ((AtomSequencerCell)atom.seq).cell == null)) { assignCell(atom); } } } /** * Assigns the cell for the given atom. * @param atom */ public void assignCell(Atom atom) { AtomSequencerCell seq = (AtomSequencerCell)atom.seq; Vector position = (positionDefinition != null) ? positionDefinition.position(atom) : atom.type.getPositionDefinition().position(atom); NeighborCell newCell = (NeighborCell)lattice.site(position); if(newCell != seq.cell) {assignCell(seq, newCell);} } /** * Assigns atom sequencer to given cell in the list of the given index. */ public void assignCell(AtomSequencerCell seq, NeighborCell newCell) { if(seq.cell != null) seq.cell.occupants().remove(seq.nbrLink); seq.cell = newCell; if(newCell != null) { newCell.occupants().add(seq.nbrLink); } }//end of assignCell public MCMoveListener makeMCMoveListener() { return new MyMCMoveListener(); } private class MyMCMoveListener implements MCMoveListener { public MyMCMoveListener() { treeIterator = new AtomIteratorTree(); treeIterator.setDoAllNodes(true); moleculePosition = new DataSourceCOM(space); translator = new AtomActionTranslateBy(space); moleculeTranslator = new AtomGroupAction(translator); } public void actionPerformed(SimulationEvent evt) { actionPerformed((MCMoveEvent)evt); } public void actionPerformed(MCMoveEvent evt) { if (!evt.isTrialNotify && evt.wasAccepted) { return; } MCMove move = evt.mcMove; AtomIterator iterator = move.affectedAtoms(phase); iterator.reset(); while (iterator.hasNext()) { Atom atom = iterator.nextAtom(); if (!atom.node.isLeaf()) { treeIterator.setRoot(atom); treeIterator.reset(); while (treeIterator.hasNext()) { Atom childAtom = treeIterator.nextAtom(); updateCell(childAtom); } } else { updateCell(atom); } } } private void updateCell(Atom atom) { Boundary boundary = phase.boundary(); if (((AtomSequencerCell)atom.seq).cell != null) { if (!atom.node.isLeaf()) { Vector shift = boundary.centralImage(moleculePosition.position(atom)); if (!shift.isZero()) { translator.setTranslationVector(shift); moleculeTranslator.actionPerformed(atom); } } else { Vector shift = boundary.centralImage(atom.coord.position()); if (!shift.isZero()) { atom.coord.position().PE(shift); } } assignCell(atom); } } private final AtomIteratorTree treeIterator; private final AtomPositionDefinition moleculePosition; private final AtomActionTranslateBy translator; private final AtomGroupAction moleculeTranslator; } }//end of NeighborCellManager
/* * Thibaut Colar Sep 2, 2009 */ package net.colar.netbeans.fan.indexer; import java.io.IOException; import java.util.Collection; import java.util.Iterator; import org.netbeans.modules.parsing.api.Snapshot; import org.netbeans.modules.parsing.spi.indexing.Context; import org.netbeans.modules.parsing.spi.indexing.EmbeddingIndexer; import org.netbeans.modules.parsing.spi.indexing.EmbeddingIndexerFactory; import org.netbeans.modules.parsing.spi.indexing.Indexable; import org.netbeans.modules.parsing.spi.indexing.support.IndexingSupport; /** * Indexer Factory impl. * @author thibautc */ public class FanIndexerFactory extends EmbeddingIndexerFactory { static{System.err.println("Fantom - Init indexer Factory");} public static final String NAME = "FanIndexer"; public static final int VERSION = 1; @Override public EmbeddingIndexer createIndexer(Indexable indexable, Snapshot snapshot) { if (snapshot.getSource().getFileObject() != null) { return new FanIndexer(); } return null; } @Override public void filesDeleted(Iterable<? extends Indexable> deleted, Context context) { try { IndexingSupport is = IndexingSupport.getInstance(context); Iterator<? extends Indexable> it = deleted.iterator(); while (it.hasNext()) { is.removeDocuments(it.next()); } } catch (IOException e) { e.printStackTrace(); } } @Override public void filesDirty(Iterable<? extends Indexable> iterable, Context context) { try { IndexingSupport is = IndexingSupport.getInstance(context); Iterator<? extends Indexable> it = iterable.iterator(); while (it.hasNext()) { is.markDirtyDocuments(it.next()); } } catch (IOException e) { e.printStackTrace(); } } @Override public String getIndexerName() { return NAME; } @Override public int getIndexVersion() { return VERSION; } }
package net.finmath.montecarlo; import java.util.HashMap; import java.util.Map; import net.finmath.exception.CalculationException; import net.finmath.stochastic.RandomVariableInterface; /** * Base class for product needing an MonteCarloSimulationInterface * * @author Christian Fries */ public abstract class AbstractMonteCarloProduct { public AbstractMonteCarloProduct() { super(); } /** * This method returns the value random variable of the product within the specified model, evaluated at a given evalutationTime. * * For a lattice this is often the value conditional to evalutationTime, for a Monte-Carlo simulation this is the (sum of) value discounted to evaluation time. * * More generally: The value random variable is a random variable <i>V<sup>*(t)</sup></i> such that * the time-<i>t</i> conditional expectation of <i>V<sup>*(t)</sup></i> is equal * to the value of the financial product in time <i>t</i>. * * An example for <i>V<sup>*(t)</sup></i> is the sum of <i>t</i>-discounted payoffs. * * Cashflows prior evaluationTime are not considered. * * @param evaluationTime The time on which this products value should be observed. * @param model The model used to price the product. * @return The random variable representing the value of the product discounted to evaluation time * @throws net.finmath.exception.CalculationException */ public abstract RandomVariableInterface getValue(double evaluationTime, MonteCarloSimulationInterface model) throws CalculationException; /** * This method returns the value of the product under the specified model. * * @param model A model used to evaluate the product. * @return The value of the product. * @throws net.finmath.exception.CalculationException */ public double getValue(MonteCarloSimulationInterface model) throws CalculationException { Map<String, Object> value = getValues(model); return (Double) value.get("value"); } /** * This method returns the value of the product under the specified model and other information in a key-value map. * * @param model A model used to evaluate the product. * @return The values of the product. * @throws net.finmath.exception.CalculationException */ public Map<String, Object> getValues(MonteCarloSimulationInterface model) throws CalculationException { RandomVariableInterface values = getValue(0.0, model); if(values == null) return null; // Sum up values on path double value = values.getAverage(); double error = values.getStandardError(); Map<String, Object> results = new HashMap<String, Object>(); results.put("value", value); results.put("error", error); return results; } /** * This method returns the value under shifted market data (or model parameters). * In its default implementation it does bump (creating a new model) and revalue. * Override the way the new model is created, to implemented improved techniques (proxy scheme, re-calibration). * * @param model The model used to price the product, except for the market data to modify * @param dataModified The new market data object to use (could be of different types) * * @return The values of the product. * @throws net.finmath.exception.CalculationException */ public Map<String, Object> getValuesForModifiedData(MonteCarloSimulationInterface model, Map<String,Object> dataModified) throws CalculationException { MonteCarloSimulationInterface modelModified = model.getCloneWithModifiedData(dataModified); return getValues(modelModified); } /** * This method returns the value under shifted market data (or model parameters). * In its default implementation it does bump (creating a new model) and revalue. * Override the way the new model is created, to implemented improved techniques (proxy scheme, re-calibration). * * @param model The model used to price the product, except for the market data to modify * @param entityKey The entity to change, it depends on the model if the model reacts to this key. * @param dataModified The new market data object to use (could be of different types) * * @return The values of the product. * @throws net.finmath.exception.CalculationException */ public Map<String, Object> getValuesForModifiedData(MonteCarloSimulationInterface model, String entityKey, Object dataModified) throws CalculationException { Map<String, Object> dataModifiedMap = new HashMap<String, Object>(); dataModifiedMap.put(entityKey, dataModified); return getValuesForModifiedData(model, dataModifiedMap); } }
package net.jayschwa.android.preference; import android.content.Context; import android.content.res.TypedArray; import android.preference.DialogPreference; import android.util.AttributeSet; import android.view.View; import android.widget.SeekBar; /** * @author Jay Weisskopf */ public class SliderPreference extends DialogPreference { protected float mValue = DEFAULT_VALUE; protected int mSeekBarValue; protected int mSeekBarResolution = 10000; protected CharSequence[] mSummaries; protected final static float DEFAULT_VALUE = 0.5f; /** * @param context * @param attrs */ public SliderPreference(Context context, AttributeSet attrs) { super(context, attrs); setup(context, attrs); } /** * @param context * @param attrs * @param defStyle */ public SliderPreference(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); setup(context, attrs); } private void setup(Context context, AttributeSet attrs) { setDialogLayoutResource(R.layout.slider_preference_dialog); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SliderPreference); try { setSummary(a.getTextArray(R.styleable.SliderPreference_android_summary)); } catch (Exception e) { // Do nothing } a.recycle(); } @Override protected Object onGetDefaultValue(TypedArray a, int index) { return a.getFloat(index, DEFAULT_VALUE); } @Override protected void onSetInitialValue(boolean restoreValue, Object defaultValue) { setValue(restoreValue ? getPersistedFloat(mValue) : (Float) defaultValue); } @Override public CharSequence getSummary() { if (mSummaries != null && mSummaries.length > 0) { int index = (int) (mValue * mSummaries.length); index = Math.min(index, mSummaries.length - 1); return mSummaries[index]; } else { return super.getSummary(); } } public void setSummary(CharSequence[] summaries) { mSummaries = summaries; } @Override public void setSummary(CharSequence summary) { super.setSummary(summary); mSummaries = null; } @Override public void setSummary(int summaryResId) { try { setSummary(getContext().getResources().getStringArray(summaryResId)); } catch (Exception e) { super.setSummary(summaryResId); } } public float getValue() { return mValue; } public void setValue(float value) { value = Math.max(0, Math.min(value, 1)); // clamp to [0, 1] if (shouldPersist()) { persistFloat(value); } if (value != mValue) { mValue = value; notifyChanged(); } } protected void setSeekBarValue(int value) { mSeekBarValue = value; } @Override protected View onCreateDialogView() { mSeekBarValue = (int) (mValue * mSeekBarResolution); View view = super.onCreateDialogView(); SeekBar seekbar = (SeekBar) view.findViewById(R.id.slider_preference_seekbar); seekbar.setMax(mSeekBarResolution); seekbar.setProgress(mSeekBarValue); seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser) { SliderPreference.this.setSeekBarValue(progress); } } }); return view; } @Override protected void onDialogClosed(boolean positiveResult) { final float newValue = (float) mSeekBarValue / mSeekBarResolution; if (positiveResult && callChangeListener(newValue)) { setValue(newValue); } super.onDialogClosed(positiveResult); } // TODO: Save and restore preference state. }
// DistanceMatrix.java // This package may be distributed under the package net.maizegenetics.popgen.distance; import net.maizegenetics.util.FormattedOutput; import net.maizegenetics.util.TableReport; import net.maizegenetics.taxa.TaxaList; import net.maizegenetics.taxa.Taxon; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; /** * storage for pairwise distance matrices.<p> * * features: * - printing in in PHYLIP format, * - computation of (weighted) squared distance to other distance matrix * - Fills in all of array... * * @version $Id: DistanceMatrix.java,v 1.8 2009/07/07 16:19:37 tcasstevens Exp $ * * @author Korbinian Strimmer * @author Alexei Drummond */ public class DistanceMatrix implements IdGroupMatrix, TableReport { // Private stuff /** sequence identifiers */ private TaxaList taxaList; /** distances [seq1][seq2] */ private double[][] distance = null; static final long serialVersionUID = 4725925229860707633L; /** I like doing things my self! */ private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { out.writeByte(1); //Version number out.writeObject(taxaList); out.writeObject(distance); } private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { byte version = in.readByte(); switch (version) { default: { taxaList= (TaxaList) in.readObject(); distance = (double[][]) in.readObject(); } } } /** constructor */ public DistanceMatrix() { } /** constructor taking distances array and IdGroup */ public DistanceMatrix(double[][] distance, TaxaList taxaList) { super(); this.distance = distance; this.taxaList=taxaList; } /** * constructor that takes a distance matrix and clones the distances * and IdGroup */ public DistanceMatrix(DistanceMatrix dm) { double[][] copy = new double[dm.distance.length][]; for (int i = 0; i < copy.length; i++) { copy[i] = new double[dm.distance[i].length]; System.arraycopy(dm.distance[i], 0, copy[i], 0, dm.distance[i].length); } distance = copy; taxaList= dm.taxaList; } /** * constructor that takes a distance matrix and clones the distances, * of a the identifiers in taxaList. */ public DistanceMatrix(DistanceMatrix dm, TaxaList subset) { int index1, index2; distance = new double[subset.numberOfTaxa()][subset.numberOfTaxa()]; for (int i = 0; i < distance.length; i++) { index1 = dm.whichIdNumber(subset.taxaName(i)); distance[i][i] = dm.distance[index1][index1]; for (int j = 0; j < i; j++) { index2 = dm.whichIdNumber(subset.taxaName(j)); distance[i][j] = dm.distance[index1][index2]; distance[j][i] = distance[i][j]; } } taxaList= subset; } /** print alignment (PHYLIP format) */ public void printPHYLIP(PrintWriter out) { // PHYLIP header line out.println(" " + distance.length); FormattedOutput format = FormattedOutput.getInstance(); for (int i = 0; i < distance.length; i++) { format.displayLabel(out, taxaList.taxaName(i), 10); out.print(" "); for (int j = 0; j < distance.length; j++) { // Chunks of 6 blocks each if (j % 6 == 0 && j != 0) { out.println(); out.print(" "); } out.print(" "); format.displayDecimal(out, distance[i][j], 5); } out.println(); } } /** returns representation of this alignment as a string */ public String toString() { StringWriter sw = new StringWriter(); printPHYLIP(new PrintWriter(sw)); return sw.toString(); } /** compute squared distance to second distance matrix */ public double squaredDistance(DistanceMatrix mat, boolean weighted) { double sum = 0; for (int i = 0; i < distance.length - 1; i++) { for (int j = i + 1; j < distance.length; j++) { double diff = distance[i][j] - mat.distance[i][j]; double weight; if (weighted) { // Fitch-Margoliash weight // (variances proportional to distances) weight = 1.0 / (distance[i][j] * distance[i][j]); } else { // Cavalli-Sforza-Edwards weight // (homogeneity of variances) weight = 1.0; } sum += weight * diff * diff; } } return 2.0 * sum; // we counted only half the matrix } /** compute absolute distance to second distance matrix */ public double absoluteDistance(DistanceMatrix mat) { double sum = 0; for (int i = 0; i < distance.length - 1; i++) { for (int j = i + 1; j < distance.length; j++) { double diff = Math.abs(distance[i][j] - mat.distance[i][j]); sum += diff; } } return 2.0 * sum; // we counted only half the matrix } /** * Returns the number of rows and columns that the distance matrix has. */ public int getSize() { return distance.length; } /** * Returns the distances as a 2-dimensional array of doubles. Matrix is cloned first so it can be altered freely. */ public final double[][] getClonedDistances() { double[][] copy = new double[distance.length][]; for (int i = 0; i < copy.length; i++) { copy[i] = new double[distance[i].length]; System.arraycopy(distance[i], 0, copy[i], 0, distance[i].length); } return copy; } /** * Returns the distances as a 2-dimensional array of doubles (in the actual array used to store the distances) */ protected final double[][] getDistances() { return getClonedDistances(); } public final double getDistance(final int row, final int col) { return distance[row][col]; } /** * Sets both upper and lower triangles. * @deprecated Needs to have a Builder */ public void setDistance(int i, int j, double dist) { distance[i][j] = distance[j][i] = dist; } /** * Adds a delta to both upper and lower triangle distances. * @deprecated Needs to have a Builder */ public void addDistance(int i, int j, double delta) { distance[i][j] += delta; distance[j][i] += delta; } /** * Returns the mean pairwise distance of this matrix */ public double meanDistance() { double dist = 0.0; int count = 0; for (int i = 0; i < distance.length; i++) { for (int j = 0; j < distance[i].length; j++) { if ((i != j)&&(!Double.isNaN(distance[i][j]))) { dist += distance[i][j]; count += 1; } } } return dist / (double) count; } //IdGroup interface public Taxon getTaxon(int i) { return taxaList.get(i); } public int numberOfTaxa() { return taxaList.numberOfTaxa(); } public int whichIdNumber(String name) { return taxaList.indicesMatchingTaxon(name).get(0); } public int whichIdNumber(Taxon id) { return taxaList.indicesMatchingTaxon(id).get(0); } /** * Return TaxaList of this alignment. */ public TaxaList getTaxaList() { return taxaList; } /** * test whether this matrix is a symmetric distance matrix * */ public boolean isSymmetric() { for (int i = 0; i < distance.length; i++) { if (distance[i][i] != 0) { return false; } } for (int i = 0; i < distance.length - 1; i++) { for (int j = i + 1; j < distance.length; j++) { if (distance[i][j] != distance[j][i]) { return false; } } } return true; } private final boolean isIn(int value, int[] set) { if (set == null) { return false; } for (int i = 0; i < set.length; i++) { if (set[i] == value) { return true; } } return false; } /** * @param fromIndex the index of the thing (taxa,sequence) from which we want to find the closest (excluding self) * @param exclusion indexes of things that should not be considered, may be null * @return the index of the member closes to the specified */ public int getClosestIndex(int fromIndex, int[] exclusion) { double min = Double.POSITIVE_INFINITY; int index = -1; for (int i = 0; i < distance.length; i++) { if (i != fromIndex && !isIn(i, exclusion)) { double d = distance[fromIndex][i]; if (d < min) { min = d; index = i; } } } return index; } /** * @deprecated Needs to have a Builder */ @Deprecated protected final void setIdGroup(TaxaList base) { this.taxaList= base; } /** * @deprecated Needs to have a Builder */ @Deprecated protected final void setDistances(double[][] matrix) { this.distance = matrix; } public Object[] getTableColumnNames() { String[] colNames = new String[getSize() + 1]; colNames[0] = "Taxa"; for (int i = 0; i < distance[0].length; i++) { colNames[i + 1] = getTaxon(i).toString(); } return colNames; } /** * Returns specified row. * * @param row row number * * @return row */ public Object[] getRow(int row) { Object[] result = new Object[distance[row].length + 1]; result[0] = getTaxon(row); for (int j = 1; j <= distance[row].length; j++) { result[j] = "" + distance[row][j - 1]; } return result; } public String getTableTitle() { return "Alignment Distance Matrix"; } public int getRowCount() { if (distance != null) { return distance.length; } else { return 0; } } public int getElementCount() { return getRowCount() * getColumnCount(); } public int getColumnCount() { if ((distance != null) && distance[0] != null) { return distance[0].length + 1; } else { return 0; } } @Override public Object[][] getTableData() { // TODO Auto-generated method stub return null; } @Override public Object[][] getTableData(int start, int end) { // TODO Auto-generated method stub return null; } @Override public Object getValueAt(int rowIndex, int columnIndex) { if (columnIndex == 0) return getTaxon(rowIndex); return new Double(distance[rowIndex][columnIndex - 1]); } public String getColumnName(int col) { if (col == 0) { return "Taxa"; } return getTaxon(col-1).toString(); } }
package net.mcft.copy.betterstorage.item; import java.util.List; import net.mcft.copy.betterstorage.content.Items; import net.mcft.copy.betterstorage.misc.Constants; import net.mcft.copy.betterstorage.misc.CurrentItem; import net.mcft.copy.betterstorage.utils.StackUtils; import net.minecraft.block.Block; import net.minecraft.client.renderer.texture.IconRegister; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityList; import net.minecraft.entity.monster.EntitySlime; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.Facing; import net.minecraft.util.Icon; import net.minecraft.util.MathHelper; import net.minecraft.world.World; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class ItemBucketSlime extends ItemBetterStorage { @SideOnly(Side.CLIENT) private Icon iconMagmaCube, iconMazeSlime; public ItemBucketSlime(int id) { super(id); setContainerItem(bucketEmpty); } @Override @SideOnly(Side.CLIENT) public void registerIcons(IconRegister iconRegister) { itemIcon = iconRegister.registerIcon(Constants.modId + ":bucketSlime"); iconMagmaCube = iconRegister.registerIcon(Constants.modId + ":bucketSlime_magmaCube"); iconMazeSlime = iconRegister.registerIcon(Constants.modId + ":bucketSlime_mazeSlime"); } @Override public Icon getIcon(ItemStack stack, int pass) { String id = StackUtils.get(stack, "Slime", "Slime", "id"); if (id.equals("LavaSlime")) return iconMagmaCube; else if (id.equals("TwilightForest.Maze Slime")) return iconMazeSlime; else return itemIcon; } @Override @SideOnly(Side.CLIENT) public Icon getIconIndex(ItemStack stack) { return getIcon(stack, 0); } @Override @SideOnly(Side.CLIENT) public void addInformation(ItemStack stack, EntityPlayer player, List list, boolean advancedTooltips) { String id = StackUtils.get(stack, "Slime", "Slime", "id"); String name = StackUtils.get(stack, (String)null, "Slime", "name"); if ((name != null) || advancedTooltips) list.add("Contains: " + ((name != null) ? ("\"" + name + "\"" + (advancedTooltips ? " (" + id + ")" : "")) : id)); } @Override public boolean onItemUse(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ) { if (!world.isRemote) { Block block = Block.blocksList[world.getBlockId(x, y, z)]; x += Facing.offsetsXForSide[side]; y += Facing.offsetsYForSide[side]; z += Facing.offsetsZForSide[side]; String id = StackUtils.get(stack, "Slime", "Slime", "id"); String name = StackUtils.get(stack, (String)null, "Slime", "name"); Entity entity = EntityList.createEntityByName(id, world); if ((entity != null) && (entity instanceof EntitySlime)) { EntitySlime slime = (EntitySlime)entity; float rotation = MathHelper.wrapAngleTo180_float(world.rand.nextFloat() * 360.0F); slime.setLocationAndAngles(x + 0.5, y, z + 0.5, rotation, 0.0F); slime.rotationYawHead = slime.renderYawOffset = rotation; if (name != null) slime.setCustomNameTag(name); slime.setSlimeSize(1); world.spawnEntityInWorld(slime); slime.playSound("mob.slime.big", 1.2F, 0.6F); player.setCurrentItemOrArmor(CurrentItem.HELD, new ItemStack(Item.bucketEmpty)); } } return true; } public static void pickUpSlime(EntityPlayer player, EntitySlime slime) { if (slime.isDead || (slime.getSlimeSize() != 1)) return; ItemStack stack = new ItemStack(Items.slimeBucket); String entityId = EntityList.getEntityString(slime); if (!entityId.equals("Slime")) StackUtils.set(stack, entityId, "Slime", "id"); if (slime.hasCustomNameTag()) StackUtils.set(stack, slime.getCustomNameTag(), "Slime", "name"); player.setCurrentItemOrArmor(CurrentItem.HELD, stack); slime.playSound("mob.slime.big", 1.2F, 0.8F); slime.isDead = true; } }
package net.sf.mzmine.visualizers.rawdata.tic; import java.util.Date; import net.sf.mzmine.interfaces.Scan; import net.sf.mzmine.io.RawDataFile; import net.sf.mzmine.io.RawDataFile.PreloadLevel; import net.sf.mzmine.taskcontrol.Task; import net.sf.mzmine.taskcontrol.TaskController; import net.sf.mzmine.taskcontrol.Task.TaskPriority; import net.sf.mzmine.util.RawDataAcceptor; import net.sf.mzmine.util.RawDataRetrievalTask; import org.jfree.data.xy.DefaultTableXYDataset; import org.jfree.data.xy.XYSeries; class TICDataSet extends DefaultTableXYDataset implements RawDataAcceptor { // redraw the chart every 100 ms while updating private static final int REDRAW_INTERVAL = 100; private RawDataFile rawDataFile; private int[] scanNumbers; private XYSeries series; private TICVisualizer visualizer; private boolean xicMode = false; private double mzRangeMin, mzRangeMax; private Date lastRedrawTime = new Date(); TICDataSet(RawDataFile rawDataFile, int msLevel, TICVisualizer visualizer) { series = new XYSeries(rawDataFile.getOriginalFile().getName(), false, false); addSeries(series); this.visualizer = visualizer; this.rawDataFile = rawDataFile; scanNumbers = rawDataFile.getScanNumbers(msLevel); assert scanNumbers != null; setTICMode(); } void setTICMode() { xicMode = false; Task updateTask = new RawDataRetrievalTask(rawDataFile, scanNumbers, this); /* * if the file data is preloaded in memory, we can update the visualizer * in this thread, otherwise start a task */ if (rawDataFile.getPreloadLevel() == PreloadLevel.PRELOAD_ALL_SCANS) { visualizer.taskStarted(updateTask); updateTask.run(); visualizer.taskFinished(updateTask); } else TaskController.getInstance().addTask(updateTask, TaskPriority.HIGH, visualizer); } void setXICMode(double mzMin, double mzMax) { this.mzRangeMin = mzMin; this.mzRangeMax = mzMax; xicMode = true; Task updateTask = new RawDataRetrievalTask(rawDataFile, scanNumbers, this); /* * if the file data is preloaded in memory, we can update the visualizer * in this thread, otherwise start a task */ if (rawDataFile.getPreloadLevel() == PreloadLevel.PRELOAD_ALL_SCANS) { visualizer.taskStarted(updateTask); updateTask.run(); visualizer.taskFinished(updateTask); } else TaskController.getInstance().addTask(updateTask, visualizer); } int getSeriesIndex(double retentionTime, double intensity) { int seriesIndex = series.indexOf(retentionTime); if (seriesIndex < 0) return -1; if (series.getY(seriesIndex).equals(intensity)) return seriesIndex; return -1; } int getScanNumber(int index) { return scanNumbers[index]; } RawDataFile getRawDataFile() { return rawDataFile; } /** * @see net.sf.mzmine.util.RawDataAcceptor#getTaskDescription() */ public String getTaskDescription() { return "Updating TIC visualizer of " + rawDataFile; } /** * @see net.sf.mzmine.util.RawDataAcceptor#addScan(net.sf.mzmine.interfaces.Scan) */ public void addScan(Scan scan) { double intensityValues[] = scan.getIntensityValues(); double mzValues[] = null; double totalIntensity = 0; if (xicMode) mzValues = scan.getMZValues(); for (int j = 0; j < intensityValues.length; j++) { if ((!xicMode) || ((mzValues[j] >= mzRangeMin) && (mzValues[j] <= mzRangeMax))) totalIntensity += intensityValues[j]; } // redraw every REDRAW_INTERVAL ms boolean notify = false; Date currentTime = new Date(); if (currentTime.getTime() - lastRedrawTime.getTime() > REDRAW_INTERVAL) { notify = true; lastRedrawTime = currentTime; } // always redraw when we add last value if (scan.getScanNumber() == scanNumbers[scanNumbers.length - 1]) notify = true; int index = series.indexOf(scan.getRetentionTime() * 1000); if (index < 0) { series.add(scan.getRetentionTime() * 1000, totalIntensity, notify); } else { series.updateByIndex(index, totalIntensity); } } }
package com.db.gui; import java.awt.Color; import java.awt.Dimension; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Insets; import java.awt.Rectangle; import javax.swing.JComponent; import javax.swing.LookAndFeel; import javax.swing.UIManager; import javax.swing.plaf.ComponentUI; import com.sun.java.swing.SwingUtilities2; /** * This class draws the ui for a FastProgressBar. * * @author Dave Longley */ public class FastProgressBarUI extends ComponentUI { /** * Shared ui object. */ protected static FastProgressBarUI smFastProgressBarUI; /** * The meter color. */ protected Color mMeterColor; /** * The empty meter text color. */ protected Color mEmptyMeterTextColor; /** * The full meter text color. */ protected Color mFullMeterTextColor; /** * Creates a new FastProgressBarUI. */ public FastProgressBarUI() { } /** * Creates a new FastProgressBarUI for a specific fast progress bar. * * @param progressBar the progress bar to create the ui for. */ public FastProgressBarUI(FastProgressBar progressBar) { // install defaults installDefaults(progressBar); } /** * Creates a new FastProgressBarUI for the passed component. * * @param c the component to create the ui for. */ public static ComponentUI createUI(JComponent c) { if(smFastProgressBarUI == null) { smFastProgressBarUI = new FastProgressBarUI(); } return smFastProgressBarUI; } /** * Installs default values for this ui onto the passed progress bar. * * @param progressBar the progressBar to install defaults on. */ protected void installDefaults(FastProgressBar progressBar) { LookAndFeel.installProperty(progressBar, "opaque", Boolean.TRUE); LookAndFeel.installBorder(progressBar,"ProgressBar.border"); LookAndFeel.installColorsAndFont(progressBar, "ProgressBar.background", "ProgressBar.foreground", "ProgressBar.font"); // reset text and meter colors resetTextAndMeterColors(); } /** * Gets the bounding box for painting the progress meter. * * @param progressBar the progress bar to paint the meter for. * * @return the bounding box for painting the progress meter. */ protected Rectangle getProgressBarBounds(FastProgressBar progressBar) { Rectangle rect = progressBar.getBounds(); // get insets Insets insets = progressBar.getInsets(); // subtract insets rect.x += insets.left; rect.y += insets.top; rect.width -= insets.right; rect.height -= insets.bottom; return rect; } /** * Gets the indeterminate box bounds for the passed progress bar. * * @param progressBarBounds the bounds for the progress bar. * @param percentage the percentage of the indeterminate value for the * progress bar. * * @return the indeterminate box bounds. */ protected Rectangle getBoxBounds( Rectangle progressBarBounds, double percentage) { Rectangle rect = new Rectangle(); // set the width and height of the box rect.width = progressBarBounds.width / 10; rect.height = progressBarBounds.height; // map the indeterminate value to the progress bar bounds less // the size of the box and store it as the box's x coordinate rect.x = (int)Math.round(percentage * (progressBarBounds.width - rect.width)); return rect; } /** * Gets the determinate meter bounds for the passed progress bar. * * @param progressBarBounds the bounds for the progress bar. * @param percentage the percentage of the current value for the * progress bar. * * @return the determinate meter bounds. */ protected Rectangle getMeterBounds( Rectangle progressBarBounds, double percentage) { Rectangle rect = new Rectangle(); // set the height of the meter rect.height = progressBarBounds.height; // map the current value to the progress bar bounds and store // it as the meter's width rect.width = (int)Math.round(percentage * progressBarBounds.width); return rect; } /** * Paints this ui for the passed progress bar. The ui will paint * an indeterminate progress box. * * @param g the graphics to paint with. * @param progressBar the progress bar to paint for. */ protected void paintIndeterminateBox( Graphics2D g, FastProgressBar progressBar) { // get the progress bar bounds Rectangle progressBarBounds = getProgressBarBounds(progressBar); // get the percentage double percentage = progressBar.getIndeterminatePercentage(); // paint indeterminate box Rectangle rect = getBoxBounds(progressBarBounds, percentage); g.setColor(getMeterColor()); g.fill(rect); // paint text paintText(progressBar, g, progressBarBounds, rect); } /** * Paints this ui for the passed progress bar. The ui will paint * a determinate progress meter. * * @param g the graphics to paint with. * @param progressBar the progress bar to paint for. */ protected void paintDeterminateMeter( Graphics2D g, FastProgressBar progressBar) { // get the progress bar bounds Rectangle progressBarBounds = getProgressBarBounds(progressBar); // get the indeterminate percentage double percentage = progressBar.getPercentage(); // paint determinate meter Rectangle rect = getMeterBounds(progressBarBounds, percentage); g.setColor(getMeterColor()); g.fill(rect); // paint text paintText(progressBar, g, progressBarBounds, rect); } /** * Paints the text for the passed progress bar on top of an existing * indeterminate box or determinate meter. * * @param progressBar the progress bar to paint the text for. * @param g the graphics to paint with. * @param progressBarBounds the bounds for the progress bar. * @param boxOrMeterBounds the bounds for the existing box or meter. */ protected void paintText( FastProgressBar progressBar, Graphics2D g, Rectangle progressBarBounds, Rectangle boxOrMeterBounds) { // get text, ensure it is not null String text = progressBar.getText(); if(text != null) { // get the old clipping bounds Rectangle oldClipBounds = g.getClipBounds(); // set font g.setFont(progressBar.getFont()); // get the text width FontMetrics fontMetrics = progressBar.getFontMetrics(progressBar.getFont()); int textWidth = SwingUtilities2.stringWidth( progressBar, fontMetrics, text); // get progress bar width and height double width = progressBarBounds.width; double height = progressBarBounds.height; // set the text x position int x = (int)Math.round((width - textWidth) / 2); // get text height int textHeight = fontMetrics.getHeight(); // get text baseline position int baseline = (int)Math.round((height - textHeight) / 2.0D); // get text y position int y = baseline + fontMetrics.getAscent(); // draw empty meter text g.setColor(getEmptyMeterTextColor()); SwingUtilities2.drawString(progressBar, g, text, x, y); // set clipping bounds g.setClip(boxOrMeterBounds); // draw full meter text g.setColor(getFullMeterTextColor()); SwingUtilities2.drawString(progressBar, g, text, x, y); // restore the old clipping bounds g.setClip(oldClipBounds); } } /** * Paints this ui for the passed progress bar. Either paints it * an indeterminate progress box or as a determinate progress meter. * * @param g the graphics to paint with. * @param progressBar the progress bar to paint. */ public void paint(Graphics g, FastProgressBar progressBar) { // get 2d graphics Graphics2D g2d = (Graphics2D)g; if(progressBar.isIndeterminate()) { paintIndeterminateBox(g2d, progressBar); } else { paintDeterminateMeter(g2d, progressBar); } } /** * Paints this ui for the passed component. The component will * be cast to a FastProgressBar. * * @param g the graphics to paint with. * @param component the component to paint. */ public void paint(Graphics g, JComponent component) { paint(g, (FastProgressBar)component); } /** * Gets the minimum size for the passed component. * * @param c the component to get the minimum size for. * * @return the component's minimum size. */ public Dimension getMinimumSize(JComponent c) { return new Dimension(10, 10); } /** * Gets the maximum size for the passed component. * * @param c the component to get the maximum size for. * * @return the component's maximum size. */ public Dimension getMaximumSize(JComponent c) { return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE); } /** * Gets the preferred size for the passed component. * * @param c the component to get the prefererd size for. * * @return the component's preferred size. */ public Dimension getPreferredSize(JComponent c) { Dimension size = getMinimumSize(c); // cast component to a progress bar FastProgressBar progressBar = (FastProgressBar)c; // get font metrics for progress bar FontMetrics fontMetrics = progressBar.getFontMetrics(progressBar.getFont()); // get text size Dimension textSize = new Dimension(0, 0); // always set preferred height to text height (add descent to ensure // there is enough space for text at the bottom) textSize.height = fontMetrics.getHeight() + fontMetrics.getDescent(); // set preferred width to text width, if there is text if(progressBar.getText() != null) { textSize.width = SwingUtilities2.stringWidth( progressBar, fontMetrics, progressBar.getText()); } // increase size as necessary size.width = Math.max(size.width, textSize.width); size.height = Math.max(size.height, textSize.height); // get progress bar insets Insets insets = progressBar.getInsets(); // add insets size.width += insets.left + insets.right; size.height += insets.top + insets.bottom; return size; } /** * Sets the meter color. * * @param color the meter color. */ public void setMeterColor(Color color) { mMeterColor = color; } /** * Gets the meter color. * * @return the meter color. */ public Color getMeterColor() { return mMeterColor; } /** * Sets the empty meter text color. * * @param color the empty meter text color. */ public void setEmptyMeterTextColor(Color color) { mEmptyMeterTextColor = color; } /** * Gets the empty meter text color. * * @return the empty meter text color. */ public Color getEmptyMeterTextColor() { return mEmptyMeterTextColor; } /** * Sets the full meter text color. * * @param color the full meter text color. */ public void setFullMeterTextColor(Color color) { mFullMeterTextColor = color; } /** * Gets the full meter text color. * * @return the full meter text color. */ public Color getFullMeterTextColor() { return mFullMeterTextColor; } /** * Resets the meter color to its default setting. */ public void resetMeterColor() { // set the meter color setMeterColor(UIManager.getColor("ProgressBar.foreground")); } /** * Resets the text colors to their default settings. */ public void resetTextColors() { // set the text colors setEmptyMeterTextColor( UIManager.getColor("ProgressBar.selectionBackground")); setFullMeterTextColor( UIManager.getColor("ProgressBar.selectionForeground")); } /** * Resets the text and meter colors to their default settings. */ public void resetTextAndMeterColors() { // reset meter color resetMeterColor(); // reset text colors resetTextColors(); } }
package ol; import ol.control.FullScreen; import ol.control.MousePosition; import ol.control.Rotate; import ol.control.ScaleLine; import ol.control.ZoomSlider; import ol.control.ZoomToExtent; import ol.interaction.DragAndDrop; import ol.interaction.KeyboardPan; import ol.interaction.KeyboardZoom; import ol.layer.Image; import ol.layer.LayerOptions; import ol.layer.Tile; import ol.proj.Projection; import ol.proj.ProjectionOptions; import ol.source.ImageWMS; import ol.source.ImageWMSOptions; import ol.source.MapQuest; import ol.source.MapQuestOptions; import ol.source.Stamen; import ol.source.StamenOptions; import ol.source.ImageStatic; import ol.source.ImageStaticOptions; /** * Factory to create GWT-OL3 instances from JavaScript based on OL3-Interfaces. * Can be also done with GIN. * When GWT supports Java 8 (hopefully in GWT 3.0) factory methods can directly created in the interfaces. * * @author Tino Desjardins * */ public class OLFactory { /** Map **/ public static native <T> Map createMap(MapOptions mapOptions) /*-{ return new $wnd.ol.Map(mapOptions); }-*/; public static native <T> MapOptions createMapOptions() /*-{ return {}; }-*/; /** Layers **/ public static native <T> Image createImageLayer(LayerOptions layerOptions) /*-{ return new $wnd.ol.layer.Image(layerOptions); }-*/; public static native <T> Tile createTileLayer(LayerOptions layerOptions) /*-{ return new $wnd.ol.layer.Tile(layerOptions); }-*/; public static native <T> LayerOptions createLayerOptions() /*-{ return {}; }-*/; /** Sources **/ public static native <T> ImageStatic createImageStaticSource(ImageStaticOptions imageStaticOptions) /*-{ return new $wnd.ol.source.ImageStatic(imageStaticOptions); }-*/; public static native <T> ImageWMS createImageWMSSource(ImageWMSOptions imageWMSOptions) /*-{ return new $wnd.ol.source.ImageWMS(imageWMSOptions); }-*/; public static native <T> MapQuest createMapQuestSource(MapQuestOptions mapQuestOptions) /*-{ return new $wnd.ol.source.MapQuest(mapQuestOptions); }-*/; public static native <T> MapQuestOptions createMapQuestOptions() /*-{ return {}; }-*/; public static native <T> Stamen createStamenSource(StamenOptions stamenOptions) /*-{ return new $wnd.ol.source.Stamen(stamenOptions); }-*/; public static native <T> StamenOptions createStamenOptions() /*-{ return {}; }-*/; /** Projection **/ public static native <T> Projection createProjection(ProjectionOptions projectionOptions) /*-{ return new $wnd.ol.proj.Projection(projectionOptions); }-*/; /** View **/ public static native <T> View createView() /*-{ return new $wnd.ol.View(); }-*/; public static native <T> View createView(ViewOptions viewOptions) /*-{ return new $wnd.ol.View(viewOptions); }-*/; /** Controls **/ public static native <T> FullScreen createFullScreen() /*-{ return new $wnd.ol.control.FullScreen(); }-*/; public static native <T> MousePosition createMousePosition() /*-{ return new $wnd.ol.control.MousePosition(); }-*/; public static native <T> Rotate createRotate() /*-{ return new $wnd.ol.control.Rotate(); }-*/; public static native <T> ScaleLine createScaleLine() /*-{ return new $wnd.ol.control.ScaleLine(); }-*/; public static native <T> ZoomToExtent createZoomToExtent() /*-{ return new $wnd.ol.control.ZoomToExtent(); }-*/; public static native <T> ZoomSlider createZoomSlider() /*-{ return new $wnd.ol.control.ZoomSlider(); }-*/; /** Interactions **/ public static native <T> DragAndDrop createDragAndDrop() /*-{ return new $wnd.ol.interaction.DragAndDrop(); }-*/; public static native <T> KeyboardPan createKeyboardPan() /*-{ return new $wnd.ol.interaction.KeyboardPan(); }-*/; public static native <T> KeyboardZoom createKeyboardZoom() /*-{ return new $wnd.ol.interaction.KeyboardZoom(); }-*/; /** Common **/ /** * Creates a common object for options. * * @return common options object */ public static native <T> T createOptions() /*-{ return {}; }-*/; /** * Creates a common object for params. * * @return common params object */ public static native <T> T createParams() /*-{ return {}; }-*/; public static native <T> Collection<T> createCollection() /*-{ return new $wnd.ol.Collection(); }-*/; /** * Creates a coordinate. * * @return coordParams coordinate params */ public static double[] createCoordinate(double... coordParams) { return coordParams; }; /** * Creates an extent. * * @param minX * @param minY * @param maxX * @param maxY * @return */ public static native double[] createExtent(double minX, double minY, double maxX, double maxY) /*-{ return [minX, minY, maxX, maxY]; }-*/; /** * Creates a size * * @param width * @param height * @return size */ public static native int[] createSize(int width, int height) /*-{ return [width, height]; }-*/; }
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FilterInputStream; import java.io.FilterOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.io.Reader; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.lang.ref.SoftReference; import java.math.BigInteger; import java.net.ConnectException; import java.net.HttpURLConnection; import java.net.InetAddress; import java.net.MalformedURLException; import java.net.NoRouteToHostException; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.URL; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.PriorityQueue; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import javax.servlet.AsyncContext; import javax.servlet.AsyncEvent; import javax.servlet.AsyncListener; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONStreamAware; import org.json.simple.JSONValue; public class Nxt extends HttpServlet { static final String VERSION = "0.5.10"; static final long GENESIS_BLOCK_ID = 2680262203532249785L; static final long CREATOR_ID = 1739068987193023818L; static final byte[] CREATOR_PUBLIC_KEY = { 18, 89, -20, 33, -45, 26, 48, -119, -115, 124, -47, 96, -97, -128, -39, 102, -117, 71, 120, -29, -39, 126, -108, 16, 68, -77, -97, 12, 68, -46, -27, 27 }; static final int BLOCK_HEADER_LENGTH = 224; static final int MAX_NUMBER_OF_TRANSACTIONS = 255; static final int MAX_PAYLOAD_LENGTH = 32640; static final int MAX_ARBITRARY_MESSAGE_LENGTH = 1000; static final int ALIAS_SYSTEM_BLOCK = 22000; static final int TRANSPARENT_FORGING_BLOCK = 30000; static final int ARBITRARY_MESSAGES_BLOCK = 40000; static final int TRANSPARENT_FORGING_BLOCK_2 = 47000; static final int TRANSPARENT_FORGING_BLOCK_3 = 51000; static final byte[] CHECKSUM_TRANSPARENT_FORGING = { 27, -54, -59, -98, 49, -42, 48, -68, -112, 49, 41, 94, -41, 78, -84, 27, -87, -22, -28, 36, -34, -90, 112, -50, -9, 5, 89, -35, 80, -121, -128, 112 }; static final long MAX_BALANCE = 1000000000L; static final long initialBaseTarget = 153722867L; static final long maxBaseTarget = 153722867000000000L; static final long MAX_ASSET_QUANTITY = 1000000000L; static final BigInteger two64 = new BigInteger("18446744073709551616"); static long epochBeginning; static final String alphabet = "0123456789abcdefghijklmnopqrstuvwxyz"; static String myPlatform; static String myScheme; static String myAddress; static String myHallmark; static int myPort; static boolean shareMyAddress; static Set<String> allowedUserHosts; static Set<String> allowedBotHosts; static int blacklistingPeriod; static final int LOGGING_MASK_EXCEPTIONS = 1; static final int LOGGING_MASK_NON200_RESPONSES = 2; static final int LOGGING_MASK_200_RESPONSES = 4; static int communicationLoggingMask; static final AtomicInteger transactionCounter = new AtomicInteger(); static final ConcurrentMap<Long, Nxt.Transaction> transactions = new ConcurrentHashMap(); static final ConcurrentMap<Long, Nxt.Transaction> unconfirmedTransactions = new ConcurrentHashMap(); static final ConcurrentMap<Long, Nxt.Transaction> doubleSpendingTransactions = new ConcurrentHashMap(); static final ConcurrentMap<Long, Nxt.Transaction> nonBroadcastedTransactions = new ConcurrentHashMap(); static Set<String> wellKnownPeers; static int maxNumberOfConnectedPublicPeers; static int connectTimeout; static int readTimeout; static boolean enableHallmarkProtection; static int pushThreshold; static int pullThreshold; static int sendToPeersLimit; static final AtomicInteger peerCounter = new AtomicInteger(); static final ConcurrentMap<String, Nxt.Peer> peers = new ConcurrentHashMap(); static final Object blocksAndTransactionsLock = new Object(); static final AtomicInteger blockCounter = new AtomicInteger(); static final ConcurrentMap<Long, Nxt.Block> blocks = new ConcurrentHashMap(); static final AtomicReference<Nxt.Block> lastBlock = new AtomicReference(); static volatile Nxt.Peer lastBlockchainFeeder; static final ConcurrentMap<Long, Nxt.Account> accounts = new ConcurrentHashMap(); static final ConcurrentMap<String, Nxt.Alias> aliases = new ConcurrentHashMap(); static final ConcurrentMap<Long, Nxt.Alias> aliasIdToAliasMappings = new ConcurrentHashMap(); static final ConcurrentMap<Long, Nxt.Asset> assets = new ConcurrentHashMap(); static final ConcurrentMap<String, Long> assetNameToIdMappings = new ConcurrentHashMap(); static final ConcurrentMap<Long, Nxt.AskOrder> askOrders = new ConcurrentHashMap(); static final ConcurrentMap<Long, Nxt.BidOrder> bidOrders = new ConcurrentHashMap(); static final ConcurrentMap<Long, TreeSet<Nxt.AskOrder>> sortedAskOrders = new ConcurrentHashMap(); static final ConcurrentMap<Long, TreeSet<Nxt.BidOrder>> sortedBidOrders = new ConcurrentHashMap(); static final ConcurrentMap<String, Nxt.User> users = new ConcurrentHashMap(); static final ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(8); static final ExecutorService sendToPeersService = Executors.newFixedThreadPool(10); static int getEpochTime(long time) { return (int)((time - epochBeginning + 500L) / 1000L); } static final ThreadLocal<SimpleDateFormat> logDateFormat = new ThreadLocal() { protected SimpleDateFormat initialValue() { return new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss.SSS] "); } }; static final boolean debug = System.getProperty("nxt.debug") != null; static final boolean enableStackTraces = System.getProperty("nxt.enableStackTraces") != null; static void logMessage(String message) { System.out.println(((SimpleDateFormat)logDateFormat.get()).format(new Date()) + message); } static void logMessage(String message, Exception e) { if (enableStackTraces) { logMessage(message); e.printStackTrace(); } else { logMessage(message + ":\n" + e.toString()); } } static void logDebugMessage(String message) { if (debug) { logMessage("DEBUG: " + message); } } static void logDebugMessage(String message, Exception e) { if (debug) { if (enableStackTraces) { logMessage("DEBUG: " + message); e.printStackTrace(); } else { logMessage("DEBUG: " + message + ":\n" + e.toString()); } } } static byte[] convert(String string) { byte[] bytes = new byte[string.length() / 2]; for (int i = 0; i < bytes.length; i++) { bytes[i] = ((byte)Integer.parseInt(string.substring(i * 2, i * 2 + 2), 16)); } return bytes; } static String convert(byte[] bytes) { StringBuilder string = new StringBuilder(); for (byte b : bytes) { int number; string.append("0123456789abcdefghijklmnopqrstuvwxyz".charAt((number = b & 0xFF) >> 4)).append("0123456789abcdefghijklmnopqrstuvwxyz".charAt(number & 0xF)); } return string.toString(); } static String convert(long objectId) { BigInteger id = BigInteger.valueOf(objectId); if (objectId < 0L) { id = id.add(two64); } return id.toString(); } static long parseUnsignedLong(String number) { if (number == null) { throw new IllegalArgumentException("trying to parse null"); } BigInteger bigInt = new BigInteger(number.trim()); if ((bigInt.signum() < 0) || (bigInt.compareTo(two64) != -1)) { throw new IllegalArgumentException("overflow: " + number); } return bigInt.longValue(); } static MessageDigest getMessageDigest(String algorithm) { try { return MessageDigest.getInstance(algorithm); } catch (NoSuchAlgorithmException e) { logMessage("Missing message digest algorithm: " + algorithm); System.exit(1); } return null; } static void matchOrders(long assetId) { TreeSet<Nxt.AskOrder> sortedAskOrders = (TreeSet)sortedAskOrders.get(Long.valueOf(assetId)); TreeSet<Nxt.BidOrder> sortedBidOrders = (TreeSet)sortedBidOrders.get(Long.valueOf(assetId)); while ((!sortedAskOrders.isEmpty()) && (!sortedBidOrders.isEmpty())) { Nxt.AskOrder askOrder = (Nxt.AskOrder)sortedAskOrders.first(); Nxt.BidOrder bidOrder = (Nxt.BidOrder)sortedBidOrders.first(); if (askOrder.price > bidOrder.price) { break; } int quantity = askOrder.quantity < bidOrder.quantity ? askOrder.quantity : bidOrder.quantity; long price = (askOrder.height < bidOrder.height) || ((askOrder.height == bidOrder.height) && (askOrder.id < bidOrder.id)) ? askOrder.price : bidOrder.price; if (askOrder.quantity -= quantity == 0) { askOrders.remove(Long.valueOf(askOrder.id)); sortedAskOrders.remove(askOrder); } askOrder.account.addToBalanceAndUnconfirmedBalance(quantity * price); if (bidOrder.quantity -= quantity == 0) { bidOrders.remove(Long.valueOf(bidOrder.id)); sortedBidOrders.remove(bidOrder); } bidOrder.account.addToAssetAndUnconfirmedAssetBalance(Long.valueOf(assetId), quantity); } } static class Account { final long id; private long balance; final int height; final AtomicReference<byte[]> publicKey = new AtomicReference(); private final Map<Long, Integer> assetBalances = new HashMap(); private long unconfirmedBalance; private final Map<Long, Integer> unconfirmedAssetBalances = new HashMap(); private Account(long id) { this.id = id; this.height = ((Nxt.Block)Nxt.lastBlock.get()).height; } static Account addAccount(long id) { Account account = new Account(id); Nxt.accounts.put(Long.valueOf(id), account); return account; } boolean setOrVerify(byte[] key) { return (this.publicKey.compareAndSet(null, key)) || (Arrays.equals(key, (byte[])this.publicKey.get())); } void generateBlock(String secretPhrase) { Set<Nxt.Transaction> sortedTransactions = new TreeSet(); for (Nxt.Transaction transaction : Nxt.unconfirmedTransactions.values()) { if ((transaction.referencedTransaction == 0L) || (Nxt.transactions.get(Long.valueOf(transaction.referencedTransaction)) != null)) { sortedTransactions.add(transaction); } } Map<Long, Nxt.Transaction> newTransactions = new HashMap(); Set<String> newAliases = new HashSet(); Map<Long, Long> accumulatedAmounts = new HashMap(); int payloadLength = 0; while (payloadLength <= 32640) { int prevNumberOfNewTransactions = newTransactions.size(); for (Nxt.Transaction transaction : sortedTransactions) { int transactionLength = transaction.getSize(); if ((newTransactions.get(Long.valueOf(transaction.getId())) == null) && (payloadLength + transactionLength <= 32640)) { long sender = transaction.getSenderAccountId(); Long accumulatedAmount = (Long)accumulatedAmounts.get(Long.valueOf(sender)); if (accumulatedAmount == null) { accumulatedAmount = Long.valueOf(0L); } long amount = (transaction.amount + transaction.fee) * 100L; if ((accumulatedAmount.longValue() + amount <= ((Account)Nxt.accounts.get(Long.valueOf(sender))).getBalance()) && (transaction.validateAttachment())) { switch (transaction.type) { case 1: switch (transaction.subtype) { case 1: if (!newAliases.add(((Nxt.Transaction.MessagingAliasAssignmentAttachment)transaction.attachment).alias.toLowerCase())) {} break; } default: accumulatedAmounts.put(Long.valueOf(sender), Long.valueOf(accumulatedAmount.longValue() + amount)); newTransactions.put(Long.valueOf(transaction.getId()), transaction); payloadLength += transactionLength; } } } } if (newTransactions.size() == prevNumberOfNewTransactions) { break; } } Nxt.Block previousBlock = (Nxt.Block)Nxt.lastBlock.get(); Nxt.Block block; Nxt.Block block; if (previousBlock.height < 30000) { block = new Nxt.Block(1, Nxt.getEpochTime(System.currentTimeMillis()), previousBlock.getId(), newTransactions.size(), 0, 0, 0, null, Nxt.Crypto.getPublicKey(secretPhrase), null, new byte[64]); } else { byte[] previousBlockHash = Nxt.getMessageDigest("SHA-256").digest(previousBlock.getBytes()); block = new Nxt.Block(2, Nxt.getEpochTime(System.currentTimeMillis()), previousBlock.getId(), newTransactions.size(), 0, 0, 0, null, Nxt.Crypto.getPublicKey(secretPhrase), null, new byte[64], previousBlockHash); } int i = 0; for (Map.Entry<Long, Nxt.Transaction> transactionEntry : newTransactions.entrySet()) { Nxt.Transaction transaction = (Nxt.Transaction)transactionEntry.getValue(); block.totalAmount += transaction.amount; block.totalFee += transaction.fee; block.payloadLength += transaction.getSize(); block.transactions[(i++)] = ((Long)transactionEntry.getKey()).longValue(); } Arrays.sort(block.transactions); MessageDigest digest = Nxt.getMessageDigest("SHA-256"); for (i = 0; i < block.transactions.length; i++) { Nxt.Transaction transaction = (Nxt.Transaction)newTransactions.get(Long.valueOf(block.transactions[i])); digest.update(transaction.getBytes()); block.blockTransactions[i] = transaction; } block.payloadHash = digest.digest(); if (previousBlock.height < 30000) { block.generationSignature = Nxt.Crypto.sign(previousBlock.generationSignature, secretPhrase); } else { digest.update(previousBlock.generationSignature); block.generationSignature = digest.digest(Nxt.Crypto.getPublicKey(secretPhrase)); } byte[] data = block.getBytes(); byte[] data2 = new byte[data.length - 64]; System.arraycopy(data, 0, data2, 0, data2.length); block.blockSignature = Nxt.Crypto.sign(data2, secretPhrase); if ((block.verifyBlockSignature()) && (block.verifyGenerationSignature())) { JSONObject request = block.getJSONObject(); request.put("requestType", "processBlock"); Nxt.Peer.sendToSomePeers(request); } else { Nxt.logMessage("Generated an incorrect block. Waiting for the next one..."); } } int getEffectiveBalance() { Nxt.Block lastBlock = (Nxt.Block)Nxt.lastBlock.get(); if ((lastBlock.height < 51000) && (this.height < 47000)) { if (this.height == 0) { return (int)(getBalance() / 100L); } if (lastBlock.height - this.height < 1440) { return 0; } int receivedInlastBlock = 0; for (Nxt.Transaction transaction : lastBlock.blockTransactions) { if (transaction.recipient == this.id) { receivedInlastBlock += transaction.amount; } } return (int)(getBalance() / 100L) - receivedInlastBlock; } return (int)(getGuaranteedBalance(1440) / 100L); } static long getId(byte[] publicKey) { byte[] publicKeyHash = Nxt.getMessageDigest("SHA-256").digest(publicKey); BigInteger bigInteger = new BigInteger(1, new byte[] { publicKeyHash[7], publicKeyHash[6], publicKeyHash[5], publicKeyHash[4], publicKeyHash[3], publicKeyHash[2], publicKeyHash[1], publicKeyHash[0] }); return bigInteger.longValue(); } synchronized Integer getAssetBalance(Long assetId) { return (Integer)this.assetBalances.get(assetId); } synchronized Integer getUnconfirmedAssetBalance(Long assetId) { return (Integer)this.unconfirmedAssetBalances.get(assetId); } synchronized void addToAssetBalance(Long assetId, int quantity) { Integer assetBalance = (Integer)this.assetBalances.get(assetId); if (assetBalance == null) { this.assetBalances.put(assetId, Integer.valueOf(quantity)); } else { this.assetBalances.put(assetId, Integer.valueOf(assetBalance.intValue() + quantity)); } } synchronized void addToUnconfirmedAssetBalance(Long assetId, int quantity) { Integer unconfirmedAssetBalance = (Integer)this.unconfirmedAssetBalances.get(assetId); if (unconfirmedAssetBalance == null) { this.unconfirmedAssetBalances.put(assetId, Integer.valueOf(quantity)); } else { this.unconfirmedAssetBalances.put(assetId, Integer.valueOf(unconfirmedAssetBalance.intValue() + quantity)); } } synchronized void addToAssetAndUnconfirmedAssetBalance(Long assetId, int quantity) { Integer assetBalance = (Integer)this.assetBalances.get(assetId); if (assetBalance == null) { this.assetBalances.put(assetId, Integer.valueOf(quantity)); this.unconfirmedAssetBalances.put(assetId, Integer.valueOf(quantity)); } else { this.assetBalances.put(assetId, Integer.valueOf(assetBalance.intValue() + quantity)); this.unconfirmedAssetBalances.put(assetId, Integer.valueOf(((Integer)this.unconfirmedAssetBalances.get(assetId)).intValue() + quantity)); } } synchronized long getBalance() { return this.balance; } long getGuaranteedBalance(int numberOfConfirmations) { long guaranteedBalance = getBalance(); ArrayList<Nxt.Block> lastBlocks = Nxt.Block.getLastBlocks(numberOfConfirmations - 1); byte[] accountPublicKey = (byte[])this.publicKey.get(); for (Iterator i$ = lastBlocks.iterator(); i$.hasNext();) { block = (Nxt.Block)i$.next(); if (Arrays.equals(block.generatorPublicKey, accountPublicKey)) { if (guaranteedBalance -= block.totalFee * 100L <= 0L) { return 0L; } } for (i = block.blockTransactions.length; i { Nxt.Transaction transaction = block.blockTransactions[i]; if (Arrays.equals(transaction.senderPublicKey, accountPublicKey)) { long deltaBalance = transaction.getSenderDeltaBalance(); if ((deltaBalance > 0L) && (guaranteedBalance -= deltaBalance <= 0L)) { return 0L; } if ((deltaBalance < 0L) && (guaranteedBalance += deltaBalance <= 0L)) { return 0L; } } if (transaction.recipient == this.id) { long deltaBalance = transaction.getRecipientDeltaBalance(); if ((deltaBalance > 0L) && (guaranteedBalance -= deltaBalance <= 0L)) { return 0L; } if ((deltaBalance < 0L) && (guaranteedBalance += deltaBalance <= 0L)) { return 0L; } } } } Nxt.Block block; int i; return guaranteedBalance; } synchronized long getUnconfirmedBalance() { return this.unconfirmedBalance; } void addToBalance(long amount) { synchronized (this) { this.balance += amount; } updatePeerWeights(); } void addToUnconfirmedBalance(long amount) { synchronized (this) { this.unconfirmedBalance += amount; } updateUserUnconfirmedBalance(); } void addToBalanceAndUnconfirmedBalance(long amount) { synchronized (this) { this.balance += amount; this.unconfirmedBalance += amount; } updatePeerWeights(); updateUserUnconfirmedBalance(); } private void updatePeerWeights() { for (Nxt.Peer peer : Nxt.peers.values()) { if ((peer.accountId == this.id) && (peer.adjustedWeight > 0L)) { peer.updateWeight(); } } } private void updateUserUnconfirmedBalance() { JSONObject response = new JSONObject(); response.put("response", "setBalance"); response.put("balance", Long.valueOf(getUnconfirmedBalance())); byte[] accountPublicKey = (byte[])this.publicKey.get(); for (Nxt.User user : Nxt.users.values()) { if ((user.secretPhrase != null) && (Arrays.equals(user.publicKey, accountPublicKey))) { user.send(response); } } } } static class Alias { final Nxt.Account account; final long id; final String alias; volatile String uri; volatile int timestamp; Alias(Nxt.Account account, long id, String alias, String uri, int timestamp) { this.account = account; this.id = id; this.alias = alias; this.uri = uri; this.timestamp = timestamp; } } static class AskOrder implements Comparable<AskOrder> { final long id; final long height; final Nxt.Account account; final long asset; volatile int quantity; final long price; AskOrder(long id, Nxt.Account account, long asset, int quantity, long price) { this.id = id; this.height = ((Nxt.Block)Nxt.lastBlock.get()).height; this.account = account; this.asset = asset; this.quantity = quantity; this.price = price; } public int compareTo(AskOrder o) { if (this.price < o.price) { return -1; } if (this.price > o.price) { return 1; } if (this.height < o.height) { return -1; } if (this.height > o.height) { return 1; } if (this.id < o.id) { return -1; } if (this.id > o.id) { return 1; } return 0; } } static class Asset { final long accountId; final String name; final String description; final int quantity; Asset(long accountId, String name, String description, int quantity) { this.accountId = accountId; this.name = name; this.description = description; this.quantity = quantity; } } static class BidOrder implements Comparable<BidOrder> { final long id; final long height; final Nxt.Account account; final long asset; volatile int quantity; final long price; BidOrder(long id, Nxt.Account account, long asset, int quantity, long price) { this.id = id; this.height = ((Nxt.Block)Nxt.lastBlock.get()).height; this.account = account; this.asset = asset; this.quantity = quantity; this.price = price; } public int compareTo(BidOrder o) { if (this.price > o.price) { return -1; } if (this.price < o.price) { return 1; } if (this.height < o.height) { return -1; } if (this.height > o.height) { return 1; } if (this.id < o.id) { return -1; } if (this.id > o.id) { return 1; } return 0; } } static class Block implements Serializable { static final long serialVersionUID = 0L; static final long[] emptyLong = new long[0]; static final Nxt.Transaction[] emptyTransactions = new Nxt.Transaction[0]; final int version; final int timestamp; final long previousBlock; int totalAmount; int totalFee; int payloadLength; byte[] payloadHash; final byte[] generatorPublicKey; byte[] generationSignature; byte[] blockSignature; final byte[] previousBlockHash; int index; final long[] transactions; long baseTarget; int height; volatile long nextBlock; BigInteger cumulativeDifficulty; transient Nxt.Transaction[] blockTransactions; volatile transient long id; Block(int version, int timestamp, long previousBlock, int numberOfTransactions, int totalAmount, int totalFee, int payloadLength, byte[] payloadHash, byte[] generatorPublicKey, byte[] generationSignature, byte[] blockSignature) { this(version, timestamp, previousBlock, numberOfTransactions, totalAmount, totalFee, payloadLength, payloadHash, generatorPublicKey, generationSignature, blockSignature, null); } Block(int version, int timestamp, long previousBlock, int numberOfTransactions, int totalAmount, int totalFee, int payloadLength, byte[] payloadHash, byte[] generatorPublicKey, byte[] generationSignature, byte[] blockSignature, byte[] previousBlockHash) { if ((numberOfTransactions > 255) || (numberOfTransactions < 0)) { throw new IllegalArgumentException("attempted to create a block with " + numberOfTransactions + " transactions"); } if ((payloadLength > 32640) || (payloadLength < 0)) { throw new IllegalArgumentException("attempted to create a block with payloadLength " + payloadLength); } this.version = version; this.timestamp = timestamp; this.previousBlock = previousBlock; this.totalAmount = totalAmount; this.totalFee = totalFee; this.payloadLength = payloadLength; this.payloadHash = payloadHash; this.generatorPublicKey = generatorPublicKey; this.generationSignature = generationSignature; this.blockSignature = blockSignature; this.previousBlockHash = previousBlockHash; this.transactions = (numberOfTransactions == 0 ? emptyLong : new long[numberOfTransactions]); this.blockTransactions = (numberOfTransactions == 0 ? emptyTransactions : new Nxt.Transaction[numberOfTransactions]); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); this.blockTransactions = (this.transactions.length == 0 ? emptyTransactions : new Nxt.Transaction[this.transactions.length]); } void analyze() { synchronized (Nxt.blocksAndTransactionsLock) { for (int i = 0; i < this.transactions.length; i++) { this.blockTransactions[i] = ((Nxt.Transaction)Nxt.transactions.get(Long.valueOf(this.transactions[i]))); if (this.blockTransactions[i] == null) { throw new IllegalStateException("Missing transaction " + Nxt.convert(this.transactions[i])); } } if (this.previousBlock == 0L) { this.baseTarget = 153722867L; this.cumulativeDifficulty = BigInteger.ZERO; Nxt.blocks.put(Long.valueOf(2680262203532249785L), this); Nxt.lastBlock.set(this); Nxt.Account.addAccount(1739068987193023818L); } else { Block previousLastBlock = (Block)Nxt.lastBlock.get(); previousLastBlock.nextBlock = getId(); previousLastBlock.height += 1; this.baseTarget = calculateBaseTarget(); this.cumulativeDifficulty = previousLastBlock.cumulativeDifficulty.add(Nxt.two64.divide(BigInteger.valueOf(this.baseTarget))); if ((previousLastBlock.getId() != this.previousBlock) || (!Nxt.lastBlock.compareAndSet(previousLastBlock, this))) { throw new IllegalStateException("Last block not equal to this.previousBlock"); } Nxt.Account generatorAccount = (Nxt.Account)Nxt.accounts.get(Long.valueOf(getGeneratorAccountId())); generatorAccount.addToBalanceAndUnconfirmedBalance(this.totalFee * 100L); if (Nxt.blocks.putIfAbsent(Long.valueOf(getId()), this) != null) { throw new IllegalStateException("duplicate block id: " + getId()); } } for (Nxt.Transaction transaction : this.blockTransactions) { transaction.height = this.height; long sender = transaction.getSenderAccountId(); Nxt.Account senderAccount = (Nxt.Account)Nxt.accounts.get(Long.valueOf(sender)); if (!senderAccount.setOrVerify(transaction.senderPublicKey)) { throw new RuntimeException("sender public key mismatch"); } senderAccount.addToBalanceAndUnconfirmedBalance(-(transaction.amount + transaction.fee) * 100L); Nxt.Account recipientAccount = (Nxt.Account)Nxt.accounts.get(Long.valueOf(transaction.recipient)); if (recipientAccount == null) { recipientAccount = Nxt.Account.addAccount(transaction.recipient); } switch (transaction.type) { case 0: switch (transaction.subtype) { case 0: recipientAccount.addToBalanceAndUnconfirmedBalance(transaction.amount * 100L); } break; case 1: switch (transaction.subtype) { case 1: Nxt.Transaction.MessagingAliasAssignmentAttachment attachment = (Nxt.Transaction.MessagingAliasAssignmentAttachment)transaction.attachment; String normalizedAlias = attachment.alias.toLowerCase(); Nxt.Alias alias = (Nxt.Alias)Nxt.aliases.get(normalizedAlias); if (alias == null) { long aliasId = transaction.getId(); alias = new Nxt.Alias(senderAccount, aliasId, attachment.alias, attachment.uri, this.timestamp); Nxt.aliases.put(normalizedAlias, alias); Nxt.aliasIdToAliasMappings.put(Long.valueOf(aliasId), alias); } else { alias.uri = attachment.uri; alias.timestamp = this.timestamp; } break; } break; case 2: switch (transaction.subtype) { case 0: Nxt.Transaction.ColoredCoinsAssetIssuanceAttachment attachment = (Nxt.Transaction.ColoredCoinsAssetIssuanceAttachment)transaction.attachment; long assetId = transaction.getId(); Nxt.Asset asset = new Nxt.Asset(sender, attachment.name, attachment.description, attachment.quantity); Nxt.assets.put(Long.valueOf(assetId), asset); Nxt.assetNameToIdMappings.put(attachment.name.toLowerCase(), Long.valueOf(assetId)); Nxt.sortedAskOrders.put(Long.valueOf(assetId), new TreeSet()); Nxt.sortedBidOrders.put(Long.valueOf(assetId), new TreeSet()); senderAccount.addToAssetAndUnconfirmedAssetBalance(Long.valueOf(assetId), attachment.quantity); break; case 1: Nxt.Transaction.ColoredCoinsAssetTransferAttachment attachment = (Nxt.Transaction.ColoredCoinsAssetTransferAttachment)transaction.attachment; senderAccount.addToAssetAndUnconfirmedAssetBalance(Long.valueOf(attachment.asset), -attachment.quantity); recipientAccount.addToAssetAndUnconfirmedAssetBalance(Long.valueOf(attachment.asset), attachment.quantity); break; case 2: Nxt.Transaction.ColoredCoinsAskOrderPlacementAttachment attachment = (Nxt.Transaction.ColoredCoinsAskOrderPlacementAttachment)transaction.attachment; Nxt.AskOrder order = new Nxt.AskOrder(transaction.getId(), senderAccount, attachment.asset, attachment.quantity, attachment.price); senderAccount.addToAssetAndUnconfirmedAssetBalance(Long.valueOf(attachment.asset), -attachment.quantity); Nxt.askOrders.put(Long.valueOf(order.id), order); ((TreeSet)Nxt.sortedAskOrders.get(Long.valueOf(attachment.asset))).add(order); Nxt.matchOrders(attachment.asset); break; case 3: Nxt.Transaction.ColoredCoinsBidOrderPlacementAttachment attachment = (Nxt.Transaction.ColoredCoinsBidOrderPlacementAttachment)transaction.attachment; Nxt.BidOrder order = new Nxt.BidOrder(transaction.getId(), senderAccount, attachment.asset, attachment.quantity, attachment.price); senderAccount.addToBalanceAndUnconfirmedBalance(-attachment.quantity * attachment.price); Nxt.bidOrders.put(Long.valueOf(order.id), order); ((TreeSet)Nxt.sortedBidOrders.get(Long.valueOf(attachment.asset))).add(order); Nxt.matchOrders(attachment.asset); break; case 4: Nxt.Transaction.ColoredCoinsAskOrderCancellationAttachment attachment = (Nxt.Transaction.ColoredCoinsAskOrderCancellationAttachment)transaction.attachment; Nxt.AskOrder order = (Nxt.AskOrder)Nxt.askOrders.remove(Long.valueOf(attachment.order)); ((TreeSet)Nxt.sortedAskOrders.get(Long.valueOf(order.asset))).remove(order); senderAccount.addToAssetAndUnconfirmedAssetBalance(Long.valueOf(order.asset), order.quantity); break; case 5: Nxt.Transaction.ColoredCoinsBidOrderCancellationAttachment attachment = (Nxt.Transaction.ColoredCoinsBidOrderCancellationAttachment)transaction.attachment; Nxt.BidOrder order = (Nxt.BidOrder)Nxt.bidOrders.remove(Long.valueOf(attachment.order)); ((TreeSet)Nxt.sortedBidOrders.get(Long.valueOf(order.asset))).remove(order); senderAccount.addToBalanceAndUnconfirmedBalance(order.quantity * order.price); } break; } } } } private long calculateBaseTarget() { if (getId() == 2680262203532249785L) { return 153722867L; } Block previousBlock = (Block)Nxt.blocks.get(Long.valueOf(this.previousBlock)); long curBaseTarget = previousBlock.baseTarget; long newBaseTarget = BigInteger.valueOf(curBaseTarget).multiply(BigInteger.valueOf(this.timestamp - previousBlock.timestamp)).divide(BigInteger.valueOf(60L)).longValue(); if ((newBaseTarget < 0L) || (newBaseTarget > 153722867000000000L)) { newBaseTarget = 153722867000000000L; } if (newBaseTarget < curBaseTarget / 2L) { newBaseTarget = curBaseTarget / 2L; } if (newBaseTarget == 0L) { newBaseTarget = 1L; } long twofoldCurBaseTarget = curBaseTarget * 2L; if (twofoldCurBaseTarget < 0L) { twofoldCurBaseTarget = 153722867000000000L; } if (newBaseTarget > twofoldCurBaseTarget) { newBaseTarget = twofoldCurBaseTarget; } return newBaseTarget; } static Block getBlock(JSONObject blockData) { try { int version = ((Long)blockData.get("version")).intValue(); int timestamp = ((Long)blockData.get("timestamp")).intValue(); long previousBlock = Nxt.parseUnsignedLong((String)blockData.get("previousBlock")); int numberOfTransactions = ((Long)blockData.get("numberOfTransactions")).intValue(); int totalAmount = ((Long)blockData.get("totalAmount")).intValue(); int totalFee = ((Long)blockData.get("totalFee")).intValue(); int payloadLength = ((Long)blockData.get("payloadLength")).intValue(); byte[] payloadHash = Nxt.convert((String)blockData.get("payloadHash")); byte[] generatorPublicKey = Nxt.convert((String)blockData.get("generatorPublicKey")); byte[] generationSignature = Nxt.convert((String)blockData.get("generationSignature")); byte[] blockSignature = Nxt.convert((String)blockData.get("blockSignature")); byte[] previousBlockHash = version == 1 ? null : Nxt.convert((String)blockData.get("previousBlockHash")); if ((numberOfTransactions > 255) || (payloadLength > 32640)) { return null; } return new Block(version, timestamp, previousBlock, numberOfTransactions, totalAmount, totalFee, payloadLength, payloadHash, generatorPublicKey, generationSignature, blockSignature, previousBlockHash); } catch (RuntimeException e) {} return null; } byte[] getBytes() { ByteBuffer buffer = ByteBuffer.allocate(224); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.putInt(this.version); buffer.putInt(this.timestamp); buffer.putLong(this.previousBlock); buffer.putInt(this.transactions.length); buffer.putInt(this.totalAmount); buffer.putInt(this.totalFee); buffer.putInt(this.payloadLength); buffer.put(this.payloadHash); buffer.put(this.generatorPublicKey); buffer.put(this.generationSignature); if (this.version > 1) { buffer.put(this.previousBlockHash); } buffer.put(this.blockSignature); return buffer.array(); } volatile transient String stringId = null; volatile transient long generatorAccountId; private transient SoftReference<JSONStreamAware> jsonRef; long getId() { calculateIds(); return this.id; } String getStringId() { calculateIds(); return this.stringId; } long getGeneratorAccountId() { calculateIds(); return this.generatorAccountId; } private void calculateIds() { if (this.stringId != null) { return; } byte[] hash = Nxt.getMessageDigest("SHA-256").digest(getBytes()); BigInteger bigInteger = new BigInteger(1, new byte[] { hash[7], hash[6], hash[5], hash[4], hash[3], hash[2], hash[1], hash[0] }); this.id = bigInteger.longValue(); this.stringId = bigInteger.toString(); this.generatorAccountId = Nxt.Account.getId(this.generatorPublicKey); } JSONObject getJSONObject() { JSONObject block = new JSONObject(); block.put("version", Integer.valueOf(this.version)); block.put("timestamp", Integer.valueOf(this.timestamp)); block.put("previousBlock", Nxt.convert(this.previousBlock)); block.put("numberOfTransactions", Integer.valueOf(this.transactions.length)); block.put("totalAmount", Integer.valueOf(this.totalAmount)); block.put("totalFee", Integer.valueOf(this.totalFee)); block.put("payloadLength", Integer.valueOf(this.payloadLength)); block.put("payloadHash", Nxt.convert(this.payloadHash)); block.put("generatorPublicKey", Nxt.convert(this.generatorPublicKey)); block.put("generationSignature", Nxt.convert(this.generationSignature)); if (this.version > 1) { block.put("previousBlockHash", Nxt.convert(this.previousBlockHash)); } block.put("blockSignature", Nxt.convert(this.blockSignature)); JSONArray transactionsData = new JSONArray(); for (Nxt.Transaction transaction : this.blockTransactions) { transactionsData.add(transaction.getJSONObject()); } block.put("transactions", transactionsData); return block; } synchronized JSONStreamAware getJSONStreamAware() { if (this.jsonRef != null) { JSONStreamAware json = (JSONStreamAware)this.jsonRef.get(); if (json != null) { return json; } } JSONStreamAware json = new JSONStreamAware() { private char[] jsonChars = Nxt.Block.this.getJSONObject().toJSONString().toCharArray(); public void writeJSONString(Writer out) throws IOException { out.write(this.jsonChars); } }; this.jsonRef = new SoftReference(json); return json; } static ArrayList<Block> getLastBlocks(int numberOfBlocks) { ArrayList<Block> lastBlocks = new ArrayList(numberOfBlocks); long curBlock = ((Block)Nxt.lastBlock.get()).getId(); do { Block block = (Block)Nxt.blocks.get(Long.valueOf(curBlock)); lastBlocks.add(block); curBlock = block.previousBlock; } while ((lastBlocks.size() < numberOfBlocks) && (curBlock != 0L)); return lastBlocks; } public static final Comparator<Block> heightComparator = new Comparator() { public int compare(Nxt.Block o1, Nxt.Block o2) { return o1.height > o2.height ? 1 : o1.height < o2.height ? -1 : 0; } }; static void loadBlocks(String fileName) throws FileNotFoundException { try { FileInputStream fileInputStream = new FileInputStream(fileName);Throwable localThrowable3 = null; try { ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);Throwable localThrowable4 = null; try { Nxt.blockCounter.set(objectInputStream.readInt()); Nxt.blocks.clear(); Nxt.blocks.putAll((HashMap)objectInputStream.readObject()); } catch (Throwable localThrowable1) { localThrowable4 = localThrowable1;throw localThrowable1; } finally {} } catch (Throwable localThrowable2) { localThrowable3 = localThrowable2;throw localThrowable2; } finally { if (fileInputStream != null) { if (localThrowable3 != null) { try { fileInputStream.close(); } catch (Throwable x2) { localThrowable3.addSuppressed(x2); } } else { fileInputStream.close(); } } } } catch (FileNotFoundException e) { throw e; } catch (IOException|ClassNotFoundException e) { Nxt.logMessage("Error loading blocks from " + fileName, e); System.exit(1); } } static boolean popLastBlock() { try { response = new JSONObject(); response.put("response", "processNewData"); JSONArray addedUnconfirmedTransactions = new JSONArray(); Block block; synchronized (Nxt.blocksAndTransactionsLock) { block = (Block)Nxt.lastBlock.get(); if (block.getId() == 2680262203532249785L) { return false; } Block previousBlock = (Block)Nxt.blocks.get(Long.valueOf(block.previousBlock)); if (previousBlock == null) { Nxt.logMessage("Previous block is null"); throw new IllegalStateException(); } if (!Nxt.lastBlock.compareAndSet(block, previousBlock)) { Nxt.logMessage("This block is no longer last block"); throw new IllegalStateException(); } Nxt.Account generatorAccount = (Nxt.Account)Nxt.accounts.get(Long.valueOf(block.getGeneratorAccountId())); generatorAccount.addToBalanceAndUnconfirmedBalance(-block.totalFee * 100L); for (long transactionId : block.transactions) { Nxt.Transaction transaction = (Nxt.Transaction)Nxt.transactions.remove(Long.valueOf(transactionId)); Nxt.unconfirmedTransactions.put(Long.valueOf(transactionId), transaction); Nxt.Account senderAccount = (Nxt.Account)Nxt.accounts.get(Long.valueOf(transaction.getSenderAccountId())); senderAccount.addToBalance((transaction.amount + transaction.fee) * 100L); Nxt.Account recipientAccount = (Nxt.Account)Nxt.accounts.get(Long.valueOf(transaction.recipient)); recipientAccount.addToBalanceAndUnconfirmedBalance(-transaction.amount * 100L); JSONObject addedUnconfirmedTransaction = new JSONObject(); addedUnconfirmedTransaction.put("index", Integer.valueOf(transaction.index)); addedUnconfirmedTransaction.put("timestamp", Integer.valueOf(transaction.timestamp)); addedUnconfirmedTransaction.put("deadline", Short.valueOf(transaction.deadline)); addedUnconfirmedTransaction.put("recipient", Nxt.convert(transaction.recipient)); addedUnconfirmedTransaction.put("amount", Integer.valueOf(transaction.amount)); addedUnconfirmedTransaction.put("fee", Integer.valueOf(transaction.fee)); addedUnconfirmedTransaction.put("sender", Nxt.convert(transaction.getSenderAccountId())); addedUnconfirmedTransaction.put("id", transaction.getStringId()); addedUnconfirmedTransactions.add(addedUnconfirmedTransaction); } } JSONArray addedOrphanedBlocks = new JSONArray(); JSONObject addedOrphanedBlock = new JSONObject(); addedOrphanedBlock.put("index", Integer.valueOf(block.index)); addedOrphanedBlock.put("timestamp", Integer.valueOf(block.timestamp)); addedOrphanedBlock.put("numberOfTransactions", Integer.valueOf(block.transactions.length)); addedOrphanedBlock.put("totalAmount", Integer.valueOf(block.totalAmount)); addedOrphanedBlock.put("totalFee", Integer.valueOf(block.totalFee)); addedOrphanedBlock.put("payloadLength", Integer.valueOf(block.payloadLength)); addedOrphanedBlock.put("generator", Nxt.convert(block.getGeneratorAccountId())); addedOrphanedBlock.put("height", Integer.valueOf(block.height)); addedOrphanedBlock.put("version", Integer.valueOf(block.version)); addedOrphanedBlock.put("block", block.getStringId()); addedOrphanedBlock.put("baseTarget", BigInteger.valueOf(block.baseTarget).multiply(BigInteger.valueOf(100000L)).divide(BigInteger.valueOf(153722867L))); addedOrphanedBlocks.add(addedOrphanedBlock); response.put("addedOrphanedBlocks", addedOrphanedBlocks); if (addedUnconfirmedTransactions.size() > 0) { response.put("addedUnconfirmedTransactions", addedUnconfirmedTransactions); } for (Nxt.User user : Nxt.users.values()) { user.send(response); } } catch (RuntimeException e) { JSONObject response; Nxt.logMessage("Error popping last block", e); return false; } return true; } static boolean pushBlock(ByteBuffer buffer, boolean savingFlag) { int curTime = Nxt.getEpochTime(System.currentTimeMillis()); Block block; JSONArray addedConfirmedTransactions; JSONArray removedUnconfirmedTransactions; synchronized (Nxt.blocksAndTransactionsLock) { try { Block previousLastBlock = (Block)Nxt.lastBlock.get(); buffer.flip(); int version = buffer.getInt(); if (version != (previousLastBlock.height < 30000 ? 1 : 2)) { return false; } if (previousLastBlock.height == 30000) { byte[] checksum = Nxt.Transaction.calculateTransactionsChecksum(); if (Nxt.CHECKSUM_TRANSPARENT_FORGING == null) { System.out.println(Arrays.toString(checksum)); } else { if (!Arrays.equals(checksum, Nxt.CHECKSUM_TRANSPARENT_FORGING)) { Nxt.logMessage("Checksum failed at block 30000"); return false; } Nxt.logMessage("Checksum passed at block 30000"); } } int blockTimestamp = buffer.getInt(); long previousBlock = buffer.getLong(); int numberOfTransactions = buffer.getInt(); int totalAmount = buffer.getInt(); int totalFee = buffer.getInt(); int payloadLength = buffer.getInt(); byte[] payloadHash = new byte[32]; buffer.get(payloadHash); byte[] generatorPublicKey = new byte[32]; buffer.get(generatorPublicKey); byte[] previousBlockHash; byte[] generationSignature; byte[] previousBlockHash; if (version == 1) { byte[] generationSignature = new byte[64]; buffer.get(generationSignature); previousBlockHash = null; } else { generationSignature = new byte[32]; buffer.get(generationSignature); previousBlockHash = new byte[32]; buffer.get(previousBlockHash); if (!Arrays.equals(Nxt.getMessageDigest("SHA-256").digest(previousLastBlock.getBytes()), previousBlockHash)) { return false; } } byte[] blockSignature = new byte[64]; buffer.get(blockSignature); if ((blockTimestamp > curTime + 15) || (blockTimestamp <= previousLastBlock.timestamp)) { return false; } if ((payloadLength > 32640) || (224 + payloadLength != buffer.capacity()) || (numberOfTransactions > 255)) { return false; } block = new Block(version, blockTimestamp, previousBlock, numberOfTransactions, totalAmount, totalFee, payloadLength, payloadHash, generatorPublicKey, generationSignature, blockSignature, previousBlockHash); if ((block.transactions.length > 255) || (block.previousBlock != previousLastBlock.getId()) || (block.getId() == 0L) || (Nxt.blocks.get(Long.valueOf(block.getId())) != null) || (!block.verifyGenerationSignature()) || (!block.verifyBlockSignature())) { return false; } block.index = Nxt.blockCounter.incrementAndGet(); HashMap<Long, Nxt.Transaction> blockTransactions = new HashMap(); HashSet<String> blockAliases = new HashSet(); for (int i = 0; i < block.transactions.length; i++) { Nxt.Transaction transaction = Nxt.Transaction.getTransaction(buffer); transaction.index = Nxt.transactionCounter.incrementAndGet(); if (blockTransactions.put(Long.valueOf(block.transactions[i] = transaction.getId()), transaction) != null) { return false; } switch (transaction.type) { case 1: switch (transaction.subtype) { case 1: if (!blockAliases.add(((Nxt.Transaction.MessagingAliasAssignmentAttachment)transaction.attachment).alias.toLowerCase())) { return false; } break; } break; } } Arrays.sort(block.transactions); HashMap<Long, Long> accumulatedAmounts = new HashMap(); HashMap<Long, HashMap<Long, Long>> accumulatedAssetQuantities = new HashMap(); int calculatedTotalAmount = 0;int calculatedTotalFee = 0; MessageDigest digest = Nxt.getMessageDigest("SHA-256"); for (int i = 0; i < block.transactions.length; i++) { Nxt.Transaction transaction = (Nxt.Transaction)blockTransactions.get(Long.valueOf(block.transactions[i])); if ((transaction.timestamp > curTime + 15) || (transaction.deadline < 1) || ((transaction.timestamp + transaction.deadline * 60 < blockTimestamp) && (previousLastBlock.height > 303)) || (transaction.fee <= 0) || (transaction.fee > 1000000000L) || (transaction.amount < 0) || (transaction.amount > 1000000000L) || (!transaction.validateAttachment()) || (Nxt.transactions.get(Long.valueOf(block.transactions[i])) != null) || ((transaction.referencedTransaction != 0L) && (Nxt.transactions.get(Long.valueOf(transaction.referencedTransaction)) == null) && (blockTransactions.get(Long.valueOf(transaction.referencedTransaction)) == null)) || ((Nxt.unconfirmedTransactions.get(Long.valueOf(block.transactions[i])) == null) && (!transaction.verify()))) { break; } long sender = transaction.getSenderAccountId(); Long accumulatedAmount = (Long)accumulatedAmounts.get(Long.valueOf(sender)); if (accumulatedAmount == null) { accumulatedAmount = Long.valueOf(0L); } accumulatedAmounts.put(Long.valueOf(sender), Long.valueOf(accumulatedAmount.longValue() + (transaction.amount + transaction.fee) * 100L)); if (transaction.type == 0) { if (transaction.subtype != 0) { break; } calculatedTotalAmount += transaction.amount; } else if (transaction.type == 1) { if ((transaction.subtype != 0) && (transaction.subtype != 1)) { break; } } else { if (transaction.type != 2) { break; } if (transaction.subtype == 1) { Nxt.Transaction.ColoredCoinsAssetTransferAttachment attachment = (Nxt.Transaction.ColoredCoinsAssetTransferAttachment)transaction.attachment; HashMap<Long, Long> accountAccumulatedAssetQuantities = (HashMap)accumulatedAssetQuantities.get(Long.valueOf(sender)); if (accountAccumulatedAssetQuantities == null) { accountAccumulatedAssetQuantities = new HashMap(); accumulatedAssetQuantities.put(Long.valueOf(sender), accountAccumulatedAssetQuantities); } Long assetAccumulatedAssetQuantities = (Long)accountAccumulatedAssetQuantities.get(Long.valueOf(attachment.asset)); if (assetAccumulatedAssetQuantities == null) { assetAccumulatedAssetQuantities = Long.valueOf(0L); } accountAccumulatedAssetQuantities.put(Long.valueOf(attachment.asset), Long.valueOf(assetAccumulatedAssetQuantities.longValue() + attachment.quantity)); } else if (transaction.subtype == 2) { Nxt.Transaction.ColoredCoinsAskOrderPlacementAttachment attachment = (Nxt.Transaction.ColoredCoinsAskOrderPlacementAttachment)transaction.attachment; HashMap<Long, Long> accountAccumulatedAssetQuantities = (HashMap)accumulatedAssetQuantities.get(Long.valueOf(sender)); if (accountAccumulatedAssetQuantities == null) { accountAccumulatedAssetQuantities = new HashMap(); accumulatedAssetQuantities.put(Long.valueOf(sender), accountAccumulatedAssetQuantities); } Long assetAccumulatedAssetQuantities = (Long)accountAccumulatedAssetQuantities.get(Long.valueOf(attachment.asset)); if (assetAccumulatedAssetQuantities == null) { assetAccumulatedAssetQuantities = Long.valueOf(0L); } accountAccumulatedAssetQuantities.put(Long.valueOf(attachment.asset), Long.valueOf(assetAccumulatedAssetQuantities.longValue() + attachment.quantity)); } else if (transaction.subtype == 3) { Nxt.Transaction.ColoredCoinsBidOrderPlacementAttachment attachment = (Nxt.Transaction.ColoredCoinsBidOrderPlacementAttachment)transaction.attachment; accumulatedAmounts.put(Long.valueOf(sender), Long.valueOf(accumulatedAmount.longValue() + attachment.quantity * attachment.price)); } else { if ((transaction.subtype != 0) && (transaction.subtype != 4) && (transaction.subtype != 5)) { break; } } } calculatedTotalFee += transaction.fee; digest.update(transaction.getBytes()); } if ((i != block.transactions.length) || (calculatedTotalAmount != block.totalAmount) || (calculatedTotalFee != block.totalFee)) { return false; } if (!Arrays.equals(digest.digest(), block.payloadHash)) { return false; } for (Map.Entry<Long, Long> accumulatedAmountEntry : accumulatedAmounts.entrySet()) { Nxt.Account senderAccount = (Nxt.Account)Nxt.accounts.get(accumulatedAmountEntry.getKey()); if (senderAccount.getBalance() < ((Long)accumulatedAmountEntry.getValue()).longValue()) { return false; } } for (Map.Entry<Long, HashMap<Long, Long>> accumulatedAssetQuantitiesEntry : accumulatedAssetQuantities.entrySet()) { senderAccount = (Nxt.Account)Nxt.accounts.get(accumulatedAssetQuantitiesEntry.getKey()); for (Map.Entry<Long, Long> accountAccumulatedAssetQuantitiesEntry : ((HashMap)accumulatedAssetQuantitiesEntry.getValue()).entrySet()) { long asset = ((Long)accountAccumulatedAssetQuantitiesEntry.getKey()).longValue(); long quantity = ((Long)accountAccumulatedAssetQuantitiesEntry.getValue()).longValue(); if (senderAccount.getAssetBalance(Long.valueOf(asset)).intValue() < quantity) { return false; } } } Nxt.Account senderAccount; previousLastBlock.height += 1; for (Map.Entry<Long, Nxt.Transaction> transactionEntry : blockTransactions.entrySet()) { Nxt.Transaction transaction = (Nxt.Transaction)transactionEntry.getValue(); transaction.height = block.height; transaction.block = block.getId(); if (Nxt.transactions.putIfAbsent(transactionEntry.getKey(), transaction) != null) { Nxt.logMessage("duplicate transaction id " + transactionEntry.getKey()); return false; } } block.analyze(); addedConfirmedTransactions = new JSONArray(); removedUnconfirmedTransactions = new JSONArray(); for (Map.Entry<Long, Nxt.Transaction> transactionEntry : blockTransactions.entrySet()) { Nxt.Transaction transaction = (Nxt.Transaction)transactionEntry.getValue(); JSONObject addedConfirmedTransaction = new JSONObject(); addedConfirmedTransaction.put("index", Integer.valueOf(transaction.index)); addedConfirmedTransaction.put("blockTimestamp", Integer.valueOf(block.timestamp)); addedConfirmedTransaction.put("transactionTimestamp", Integer.valueOf(transaction.timestamp)); addedConfirmedTransaction.put("sender", Nxt.convert(transaction.getSenderAccountId())); addedConfirmedTransaction.put("recipient", Nxt.convert(transaction.recipient)); addedConfirmedTransaction.put("amount", Integer.valueOf(transaction.amount)); addedConfirmedTransaction.put("fee", Integer.valueOf(transaction.fee)); addedConfirmedTransaction.put("id", transaction.getStringId()); addedConfirmedTransactions.add(addedConfirmedTransaction); Nxt.Transaction removedTransaction = (Nxt.Transaction)Nxt.unconfirmedTransactions.remove(transactionEntry.getKey()); if (removedTransaction != null) { JSONObject removedUnconfirmedTransaction = new JSONObject(); removedUnconfirmedTransaction.put("index", Integer.valueOf(removedTransaction.index)); removedUnconfirmedTransactions.add(removedUnconfirmedTransaction); Nxt.Account senderAccount = (Nxt.Account)Nxt.accounts.get(Long.valueOf(removedTransaction.getSenderAccountId())); senderAccount.addToUnconfirmedBalance((removedTransaction.amount + removedTransaction.fee) * 100L); } } if (savingFlag) { Nxt.Transaction.saveTransactions("transactions.nxt"); saveBlocks("blocks.nxt", false); } } catch (RuntimeException e) { Nxt.logMessage("Error pushing block", e); return false; } } if (block.timestamp >= curTime - 15) { JSONObject request = block.getJSONObject(); request.put("requestType", "processBlock"); Nxt.Peer.sendToSomePeers(request); } JSONArray addedRecentBlocks = new JSONArray(); JSONObject addedRecentBlock = new JSONObject(); addedRecentBlock.put("index", Integer.valueOf(block.index)); addedRecentBlock.put("timestamp", Integer.valueOf(block.timestamp)); addedRecentBlock.put("numberOfTransactions", Integer.valueOf(block.transactions.length)); addedRecentBlock.put("totalAmount", Integer.valueOf(block.totalAmount)); addedRecentBlock.put("totalFee", Integer.valueOf(block.totalFee)); addedRecentBlock.put("payloadLength", Integer.valueOf(block.payloadLength)); addedRecentBlock.put("generator", Nxt.convert(block.getGeneratorAccountId())); addedRecentBlock.put("height", Integer.valueOf(block.height)); addedRecentBlock.put("version", Integer.valueOf(block.version)); addedRecentBlock.put("block", block.getStringId()); addedRecentBlock.put("baseTarget", BigInteger.valueOf(block.baseTarget).multiply(BigInteger.valueOf(100000L)).divide(BigInteger.valueOf(153722867L))); addedRecentBlocks.add(addedRecentBlock); JSONObject response = new JSONObject(); response.put("response", "processNewData"); response.put("addedConfirmedTransactions", addedConfirmedTransactions); if (removedUnconfirmedTransactions.size() > 0) { response.put("removedUnconfirmedTransactions", removedUnconfirmedTransactions); } response.put("addedRecentBlocks", addedRecentBlocks); for (Nxt.User user : Nxt.users.values()) { user.send(response); } return true; } static void saveBlocks(String fileName, boolean flag) { try { FileOutputStream fileOutputStream = new FileOutputStream(fileName);Throwable localThrowable3 = null; try { ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);Throwable localThrowable4 = null; try { objectOutputStream.writeInt(Nxt.blockCounter.get()); objectOutputStream.writeObject(new HashMap(Nxt.blocks)); } catch (Throwable localThrowable1) { localThrowable4 = localThrowable1;throw localThrowable1; } finally {} } catch (Throwable localThrowable2) { localThrowable3 = localThrowable2;throw localThrowable2; } finally { if (fileOutputStream != null) { if (localThrowable3 != null) { try { fileOutputStream.close(); } catch (Throwable x2) { localThrowable3.addSuppressed(x2); } } else { fileOutputStream.close(); } } } } catch (IOException e) { Nxt.logMessage("Error saving blocks to " + fileName, e); throw new RuntimeException(e); } } boolean verifyBlockSignature() { Nxt.Account account = (Nxt.Account)Nxt.accounts.get(Long.valueOf(getGeneratorAccountId())); if (account == null) { return false; } byte[] data = getBytes(); byte[] data2 = new byte[data.length - 64]; System.arraycopy(data, 0, data2, 0, data2.length); return (Nxt.Crypto.verify(this.blockSignature, data2, this.generatorPublicKey)) && (account.setOrVerify(this.generatorPublicKey)); } boolean verifyGenerationSignature() { try { Block previousBlock = (Block)Nxt.blocks.get(Long.valueOf(this.previousBlock)); if (previousBlock == null) { return false; } if ((this.version == 1) && (!Nxt.Crypto.verify(this.generationSignature, previousBlock.generationSignature, this.generatorPublicKey))) { return false; } Nxt.Account account = (Nxt.Account)Nxt.accounts.get(Long.valueOf(getGeneratorAccountId())); if ((account == null) || (account.getEffectiveBalance() <= 0)) { return false; } int elapsedTime = this.timestamp - previousBlock.timestamp; BigInteger target = BigInteger.valueOf(((Block)Nxt.lastBlock.get()).baseTarget).multiply(BigInteger.valueOf(account.getEffectiveBalance())).multiply(BigInteger.valueOf(elapsedTime)); MessageDigest digest = Nxt.getMessageDigest("SHA-256"); byte[] generationSignatureHash; byte[] generationSignatureHash; if (this.version == 1) { generationSignatureHash = digest.digest(this.generationSignature); } else { digest.update(previousBlock.generationSignature); generationSignatureHash = digest.digest(this.generatorPublicKey); if (!Arrays.equals(this.generationSignature, generationSignatureHash)) { return false; } } BigInteger hit = new BigInteger(1, new byte[] { generationSignatureHash[7], generationSignatureHash[6], generationSignatureHash[5], generationSignatureHash[4], generationSignatureHash[3], generationSignatureHash[2], generationSignatureHash[1], generationSignatureHash[0] }); return hit.compareTo(target) < 0; } catch (RuntimeException e) { Nxt.logMessage("Error verifying block generation signature", e); } return false; } } static class Crypto { static byte[] getPublicKey(String secretPhrase) { try { byte[] publicKey = new byte[32]; Nxt.Curve25519.keygen(publicKey, null, Nxt.getMessageDigest("SHA-256").digest(secretPhrase.getBytes("UTF-8"))); return publicKey; } catch (RuntimeException|UnsupportedEncodingException e) { Nxt.logMessage("Error getting public key", e); } return null; } static byte[] sign(byte[] message, String secretPhrase) { try { byte[] P = new byte[32]; byte[] s = new byte[32]; MessageDigest digest = Nxt.getMessageDigest("SHA-256"); Nxt.Curve25519.keygen(P, s, digest.digest(secretPhrase.getBytes("UTF-8"))); byte[] m = digest.digest(message); digest.update(m); byte[] x = digest.digest(s); byte[] Y = new byte[32]; Nxt.Curve25519.keygen(Y, null, x); digest.update(m); byte[] h = digest.digest(Y); byte[] v = new byte[32]; Nxt.Curve25519.sign(v, h, x, s); byte[] signature = new byte[64]; System.arraycopy(v, 0, signature, 0, 32); System.arraycopy(h, 0, signature, 32, 32); return signature; } catch (RuntimeException|UnsupportedEncodingException e) { Nxt.logMessage("Error in signing message", e); } return null; } static boolean verify(byte[] signature, byte[] message, byte[] publicKey) { try { byte[] Y = new byte[32]; byte[] v = new byte[32]; System.arraycopy(signature, 0, v, 0, 32); byte[] h = new byte[32]; System.arraycopy(signature, 32, h, 0, 32); Nxt.Curve25519.verify(Y, v, h, publicKey); MessageDigest digest = Nxt.getMessageDigest("SHA-256"); byte[] m = digest.digest(message); digest.update(m); byte[] h2 = digest.digest(Y); return Arrays.equals(h, h2); } catch (RuntimeException e) { Nxt.logMessage("Error in Nxt.Crypto verify", e); } return false; } } static class Curve25519 { public static final int KEY_SIZE = 32; public static final byte[] ZERO = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; public static final byte[] PRIME = { -19, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 127 }; public static final byte[] ORDER = { -19, -45, -11, 92, 26, 99, 18, 88, -42, -100, -9, -94, -34, -7, -34, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16 }; private static final int P25 = 33554431; private static final int P26 = 67108863; public static final void clamp(byte[] k) { k[31] = ((byte)(k[31] & 0x7F)); k[31] = ((byte)(k[31] | 0x40)); int tmp22_21 = 0;k[tmp22_21] = ((byte)(k[tmp22_21] & 0xF8)); } public static final void keygen(byte[] P, byte[] s, byte[] k) { clamp(k); core(P, s, k, null); } public static final void curve(byte[] Z, byte[] k, byte[] P) { core(Z, null, k, P); } public static final boolean sign(byte[] v, byte[] h, byte[] x, byte[] s) { byte[] tmp1 = new byte[65]; byte[] tmp2 = new byte[33]; for (int i = 0; i < 32; i++) { v[i] = 0; } i = mula_small(v, x, 0, h, 32, -1); mula_small(v, v, 0, ORDER, 32, (15 - v[31]) / 16); mula32(tmp1, v, s, 32, 1); divmod(tmp2, tmp1, 64, ORDER, 32); int w = 0; for (i = 0; i < 32; i++) { w |= (v[i] = tmp1[i]); } return w != 0; } public static final void verify(byte[] Y, byte[] v, byte[] h, byte[] P) { byte[] d = new byte[32]; Nxt.Curve25519.long10[] p = { new Nxt.Curve25519.long10(), new Nxt.Curve25519.long10() }; Nxt.Curve25519.long10[] s = { new Nxt.Curve25519.long10(), new Nxt.Curve25519.long10() }; Nxt.Curve25519.long10[] yx = { new Nxt.Curve25519.long10(), new Nxt.Curve25519.long10(), new Nxt.Curve25519.long10() }; Nxt.Curve25519.long10[] yz = { new Nxt.Curve25519.long10(), new Nxt.Curve25519.long10(), new Nxt.Curve25519.long10() }; Nxt.Curve25519.long10[] t1 = { new Nxt.Curve25519.long10(), new Nxt.Curve25519.long10(), new Nxt.Curve25519.long10() }; Nxt.Curve25519.long10[] t2 = { new Nxt.Curve25519.long10(), new Nxt.Curve25519.long10(), new Nxt.Curve25519.long10() }; int vi = 0;int hi = 0;int di = 0;int nvh = 0; set(p[0], 9); unpack(p[1], P); x_to_y2(t1[0], t2[0], p[1]); sqrt(t1[0], t2[0]); int j = is_negative(t1[0]); t2[0]._0 += 39420360L; mul(t2[1], BASE_2Y, t1[0]); sub(t1[j], t2[0], t2[1]); add(t1[(1 - j)], t2[0], t2[1]); cpy(t2[0], p[1]); t2[0]._0 -= 9L; sqr(t2[1], t2[0]); recip(t2[0], t2[1], 0); mul(s[0], t1[0], t2[0]); sub(s[0], s[0], p[1]); s[0]._0 -= 486671L; mul(s[1], t1[1], t2[0]); sub(s[1], s[1], p[1]); s[1]._0 -= 486671L; mul_small(s[0], s[0], 1L); mul_small(s[1], s[1], 1L); for (int i = 0; i < 32; i++) { vi = vi >> 8 ^ v[i] & 0xFF ^ (v[i] & 0xFF) << 1; hi = hi >> 8 ^ h[i] & 0xFF ^ (h[i] & 0xFF) << 1; nvh = vi ^ hi ^ 0xFFFFFFFF; di = nvh & (di & 0x80) >> 7 ^ vi; di ^= nvh & (di & 0x1) << 1; di ^= nvh & (di & 0x2) << 1; di ^= nvh & (di & 0x4) << 1; di ^= nvh & (di & 0x8) << 1; di ^= nvh & (di & 0x10) << 1; di ^= nvh & (di & 0x20) << 1; di ^= nvh & (di & 0x40) << 1; d[i] = ((byte)di); } di = (nvh & (di & 0x80) << 1 ^ vi) >> 8; set(yx[0], 1); cpy(yx[1], p[di]); cpy(yx[2], s[0]); set(yz[0], 0); set(yz[1], 1); set(yz[2], 1); vi = 0; hi = 0; for (i = 32; i { vi = vi << 8 | v[i] & 0xFF; hi = hi << 8 | h[i] & 0xFF; di = di << 8 | d[i] & 0xFF; for (j = 8; j { mont_prep(t1[0], t2[0], yx[0], yz[0]); mont_prep(t1[1], t2[1], yx[1], yz[1]); mont_prep(t1[2], t2[2], yx[2], yz[2]); int k = ((vi ^ vi >> 1) >> j & 0x1) + ((hi ^ hi >> 1) >> j & 0x1); mont_dbl(yx[2], yz[2], t1[k], t2[k], yx[0], yz[0]); k = di >> j & 0x2 ^ (di >> j & 0x1) << 1; mont_add(t1[1], t2[1], t1[k], t2[k], yx[1], yz[1], p[(di >> j & 0x1)]); mont_add(t1[2], t2[2], t1[0], t2[0], yx[2], yz[2], s[(((vi ^ hi) >> j & 0x2) >> 1)]); } } int k = (vi & 0x1) + (hi & 0x1); recip(t1[0], yz[k], 0); mul(t1[1], yx[k], t1[0]); pack(t1[1], Y); } private static final class long10 { public long _0; public long _1; public long _2; public long _3; public long _4; public long _5; public long _6; public long _7; public long _8; public long _9; public long10() {} public long10(long _0, long _1, long _2, long _3, long _4, long _5, long _6, long _7, long _8, long _9) { this._0 = _0;this._1 = _1;this._2 = _2; this._3 = _3;this._4 = _4;this._5 = _5; this._6 = _6;this._7 = _7;this._8 = _8; this._9 = _9; } } private static final void cpy32(byte[] d, byte[] s) { for (int i = 0; i < 32; i++) { d[i] = s[i]; } } private static final int mula_small(byte[] p, byte[] q, int m, byte[] x, int n, int z) { int v = 0; for (int i = 0; i < n; i++) { v += (q[(i + m)] & 0xFF) + z * (x[i] & 0xFF); p[(i + m)] = ((byte)v); v >>= 8; } return v; } private static final int mula32(byte[] p, byte[] x, byte[] y, int t, int z) { int n = 31; int w = 0; for (int i = 0; i < t; i++) { int zy = z * (y[i] & 0xFF); w += mula_small(p, p, i, x, 31, zy) + (p[(i + 31)] & 0xFF) + zy * (x[31] & 0xFF); p[(i + 31)] = ((byte)w); w >>= 8; } p[(i + 31)] = ((byte)(w + (p[(i + 31)] & 0xFF))); return w >> 8; } private static final void divmod(byte[] q, byte[] r, int n, byte[] d, int t) { int rn = 0; int dt = (d[(t - 1)] & 0xFF) << 8; if (t > 1) { dt |= d[(t - 2)] & 0xFF; } while (n { int z = rn << 16 | (r[n] & 0xFF) << 8; if (n > 0) { z |= r[(n - 1)] & 0xFF; } z /= dt; rn += mula_small(r, r, n - t + 1, d, t, -z); q[(n - t + 1)] = ((byte)(z + rn & 0xFF)); mula_small(r, r, n - t + 1, d, t, -rn); rn = r[n] & 0xFF; r[n] = 0; } r[(t - 1)] = ((byte)rn); } private static final int numsize(byte[] x, int n) { while ((n-- != 0) && (x[n] == 0)) {} return n + 1; } private static final byte[] egcd32(byte[] x, byte[] y, byte[] a, byte[] b) { int bn = 32; for (int i = 0; i < 32; i++) { int tmp21_20 = 0;y[i] = tmp21_20;x[i] = tmp21_20; } x[0] = 1; int an = numsize(a, 32); if (an == 0) { return y; } byte[] temp = new byte[32]; for (;;) { int qn = bn - an + 1; divmod(temp, b, bn, a, an); bn = numsize(b, bn); if (bn == 0) { return x; } mula32(y, x, temp, qn, -1); qn = an - bn + 1; divmod(temp, a, an, b, bn); an = numsize(a, an); if (an == 0) { return y; } mula32(x, y, temp, qn, -1); } } private static final void unpack(Nxt.Curve25519.long10 x, byte[] m) { x._0 = (m[0] & 0xFF | (m[1] & 0xFF) << 8 | (m[2] & 0xFF) << 16 | (m[3] & 0xFF & 0x3) << 24); x._1 = ((m[3] & 0xFF & 0xFFFFFFFC) >> 2 | (m[4] & 0xFF) << 6 | (m[5] & 0xFF) << 14 | (m[6] & 0xFF & 0x7) << 22); x._2 = ((m[6] & 0xFF & 0xFFFFFFF8) >> 3 | (m[7] & 0xFF) << 5 | (m[8] & 0xFF) << 13 | (m[9] & 0xFF & 0x1F) << 21); x._3 = ((m[9] & 0xFF & 0xFFFFFFE0) >> 5 | (m[10] & 0xFF) << 3 | (m[11] & 0xFF) << 11 | (m[12] & 0xFF & 0x3F) << 19); x._4 = ((m[12] & 0xFF & 0xFFFFFFC0) >> 6 | (m[13] & 0xFF) << 2 | (m[14] & 0xFF) << 10 | (m[15] & 0xFF) << 18); x._5 = (m[16] & 0xFF | (m[17] & 0xFF) << 8 | (m[18] & 0xFF) << 16 | (m[19] & 0xFF & 0x1) << 24); x._6 = ((m[19] & 0xFF & 0xFFFFFFFE) >> 1 | (m[20] & 0xFF) << 7 | (m[21] & 0xFF) << 15 | (m[22] & 0xFF & 0x7) << 23); x._7 = ((m[22] & 0xFF & 0xFFFFFFF8) >> 3 | (m[23] & 0xFF) << 5 | (m[24] & 0xFF) << 13 | (m[25] & 0xFF & 0xF) << 21); x._8 = ((m[25] & 0xFF & 0xFFFFFFF0) >> 4 | (m[26] & 0xFF) << 4 | (m[27] & 0xFF) << 12 | (m[28] & 0xFF & 0x3F) << 20); x._9 = ((m[28] & 0xFF & 0xFFFFFFC0) >> 6 | (m[29] & 0xFF) << 2 | (m[30] & 0xFF) << 10 | (m[31] & 0xFF) << 18); } private static final boolean is_overflow(Nxt.Curve25519.long10 x) { return ((x._0 > 67108844L) && ((x._1 & x._3 & x._5 & x._7 & x._9) == 33554431L) && ((x._2 & x._4 & x._6 & x._8) == 67108863L)) || (x._9 > 33554431L); } private static final void pack(Nxt.Curve25519.long10 x, byte[] m) { int ld = 0;int ud = 0; ld = (is_overflow(x) ? 1 : 0) - (x._9 < 0L ? 1 : 0); ud = ld * -33554432; ld *= 19; long t = ld + x._0 + (x._1 << 26); m[0] = ((byte)(int)t); m[1] = ((byte)(int)(t >> 8)); m[2] = ((byte)(int)(t >> 16)); m[3] = ((byte)(int)(t >> 24)); t = (t >> 32) + (x._2 << 19); m[4] = ((byte)(int)t); m[5] = ((byte)(int)(t >> 8)); m[6] = ((byte)(int)(t >> 16)); m[7] = ((byte)(int)(t >> 24)); t = (t >> 32) + (x._3 << 13); m[8] = ((byte)(int)t); m[9] = ((byte)(int)(t >> 8)); m[10] = ((byte)(int)(t >> 16)); m[11] = ((byte)(int)(t >> 24)); t = (t >> 32) + (x._4 << 6); m[12] = ((byte)(int)t); m[13] = ((byte)(int)(t >> 8)); m[14] = ((byte)(int)(t >> 16)); m[15] = ((byte)(int)(t >> 24)); t = (t >> 32) + x._5 + (x._6 << 25); m[16] = ((byte)(int)t); m[17] = ((byte)(int)(t >> 8)); m[18] = ((byte)(int)(t >> 16)); m[19] = ((byte)(int)(t >> 24)); t = (t >> 32) + (x._7 << 19); m[20] = ((byte)(int)t); m[21] = ((byte)(int)(t >> 8)); m[22] = ((byte)(int)(t >> 16)); m[23] = ((byte)(int)(t >> 24)); t = (t >> 32) + (x._8 << 12); m[24] = ((byte)(int)t); m[25] = ((byte)(int)(t >> 8)); m[26] = ((byte)(int)(t >> 16)); m[27] = ((byte)(int)(t >> 24)); t = (t >> 32) + (x._9 + ud << 6); m[28] = ((byte)(int)t); m[29] = ((byte)(int)(t >> 8)); m[30] = ((byte)(int)(t >> 16)); m[31] = ((byte)(int)(t >> 24)); } private static final void cpy(Nxt.Curve25519.long10 out, Nxt.Curve25519.long10 in) { out._0 = in._0;out._1 = in._1; out._2 = in._2;out._3 = in._3; out._4 = in._4;out._5 = in._5; out._6 = in._6;out._7 = in._7; out._8 = in._8;out._9 = in._9; } private static final void set(Nxt.Curve25519.long10 out, int in) { out._0 = in;out._1 = 0L; out._2 = 0L;out._3 = 0L; out._4 = 0L;out._5 = 0L; out._6 = 0L;out._7 = 0L; out._8 = 0L;out._9 = 0L; } private static final void add(Nxt.Curve25519.long10 xy, Nxt.Curve25519.long10 x, Nxt.Curve25519.long10 y) { x._0 += y._0;x._1 += y._1; x._2 += y._2;x._3 += y._3; x._4 += y._4;x._5 += y._5; x._6 += y._6;x._7 += y._7; x._8 += y._8;x._9 += y._9; } private static final void sub(Nxt.Curve25519.long10 xy, Nxt.Curve25519.long10 x, Nxt.Curve25519.long10 y) { x._0 -= y._0;x._1 -= y._1; x._2 -= y._2;x._3 -= y._3; x._4 -= y._4;x._5 -= y._5; x._6 -= y._6;x._7 -= y._7; x._8 -= y._8;x._9 -= y._9; } private static final Nxt.Curve25519.long10 mul_small(Nxt.Curve25519.long10 xy, Nxt.Curve25519.long10 x, long y) { long t = x._8 * y; xy._8 = (t & 0x3FFFFFF); t = (t >> 26) + x._9 * y; xy._9 = (t & 0x1FFFFFF); t = 19L * (t >> 25) + x._0 * y; xy._0 = (t & 0x3FFFFFF); t = (t >> 26) + x._1 * y; xy._1 = (t & 0x1FFFFFF); t = (t >> 25) + x._2 * y; xy._2 = (t & 0x3FFFFFF); t = (t >> 26) + x._3 * y; xy._3 = (t & 0x1FFFFFF); t = (t >> 25) + x._4 * y; xy._4 = (t & 0x3FFFFFF); t = (t >> 26) + x._5 * y; xy._5 = (t & 0x1FFFFFF); t = (t >> 25) + x._6 * y; xy._6 = (t & 0x3FFFFFF); t = (t >> 26) + x._7 * y; xy._7 = (t & 0x1FFFFFF); t = (t >> 25) + xy._8; xy._8 = (t & 0x3FFFFFF); xy._9 += (t >> 26); return xy; } private static final Nxt.Curve25519.long10 mul(Nxt.Curve25519.long10 xy, Nxt.Curve25519.long10 x, Nxt.Curve25519.long10 y) { long x_0 = x._0;long x_1 = x._1;long x_2 = x._2;long x_3 = x._3;long x_4 = x._4; long x_5 = x._5;long x_6 = x._6;long x_7 = x._7;long x_8 = x._8;long x_9 = x._9; long y_0 = y._0;long y_1 = y._1;long y_2 = y._2;long y_3 = y._3;long y_4 = y._4; long y_5 = y._5;long y_6 = y._6;long y_7 = y._7;long y_8 = y._8;long y_9 = y._9; long t = x_0 * y_8 + x_2 * y_6 + x_4 * y_4 + x_6 * y_2 + x_8 * y_0 + 2L * (x_1 * y_7 + x_3 * y_5 + x_5 * y_3 + x_7 * y_1) + 38L * (x_9 * y_9); xy._8 = (t & 0x3FFFFFF); t = (t >> 26) + x_0 * y_9 + x_1 * y_8 + x_2 * y_7 + x_3 * y_6 + x_4 * y_5 + x_5 * y_4 + x_6 * y_3 + x_7 * y_2 + x_8 * y_1 + x_9 * y_0; xy._9 = (t & 0x1FFFFFF); t = x_0 * y_0 + 19L * ((t >> 25) + x_2 * y_8 + x_4 * y_6 + x_6 * y_4 + x_8 * y_2) + 38L * (x_1 * y_9 + x_3 * y_7 + x_5 * y_5 + x_7 * y_3 + x_9 * y_1); xy._0 = (t & 0x3FFFFFF); t = (t >> 26) + x_0 * y_1 + x_1 * y_0 + 19L * (x_2 * y_9 + x_3 * y_8 + x_4 * y_7 + x_5 * y_6 + x_6 * y_5 + x_7 * y_4 + x_8 * y_3 + x_9 * y_2); xy._1 = (t & 0x1FFFFFF); t = (t >> 25) + x_0 * y_2 + x_2 * y_0 + 19L * (x_4 * y_8 + x_6 * y_6 + x_8 * y_4) + 2L * (x_1 * y_1) + 38L * (x_3 * y_9 + x_5 * y_7 + x_7 * y_5 + x_9 * y_3); xy._2 = (t & 0x3FFFFFF); t = (t >> 26) + x_0 * y_3 + x_1 * y_2 + x_2 * y_1 + x_3 * y_0 + 19L * (x_4 * y_9 + x_5 * y_8 + x_6 * y_7 + x_7 * y_6 + x_8 * y_5 + x_9 * y_4); xy._3 = (t & 0x1FFFFFF); t = (t >> 25) + x_0 * y_4 + x_2 * y_2 + x_4 * y_0 + 19L * (x_6 * y_8 + x_8 * y_6) + 2L * (x_1 * y_3 + x_3 * y_1) + 38L * (x_5 * y_9 + x_7 * y_7 + x_9 * y_5); xy._4 = (t & 0x3FFFFFF); t = (t >> 26) + x_0 * y_5 + x_1 * y_4 + x_2 * y_3 + x_3 * y_2 + x_4 * y_1 + x_5 * y_0 + 19L * (x_6 * y_9 + x_7 * y_8 + x_8 * y_7 + x_9 * y_6); xy._5 = (t & 0x1FFFFFF); t = (t >> 25) + x_0 * y_6 + x_2 * y_4 + x_4 * y_2 + x_6 * y_0 + 19L * (x_8 * y_8) + 2L * (x_1 * y_5 + x_3 * y_3 + x_5 * y_1) + 38L * (x_7 * y_9 + x_9 * y_7); xy._6 = (t & 0x3FFFFFF); t = (t >> 26) + x_0 * y_7 + x_1 * y_6 + x_2 * y_5 + x_3 * y_4 + x_4 * y_3 + x_5 * y_2 + x_6 * y_1 + x_7 * y_0 + 19L * (x_8 * y_9 + x_9 * y_8); xy._7 = (t & 0x1FFFFFF); t = (t >> 25) + xy._8; xy._8 = (t & 0x3FFFFFF); xy._9 += (t >> 26); return xy; } private static final Nxt.Curve25519.long10 sqr(Nxt.Curve25519.long10 x2, Nxt.Curve25519.long10 x) { long x_0 = x._0;long x_1 = x._1;long x_2 = x._2;long x_3 = x._3;long x_4 = x._4; long x_5 = x._5;long x_6 = x._6;long x_7 = x._7;long x_8 = x._8;long x_9 = x._9; long t = x_4 * x_4 + 2L * (x_0 * x_8 + x_2 * x_6) + 38L * (x_9 * x_9) + 4L * (x_1 * x_7 + x_3 * x_5); x2._8 = (t & 0x3FFFFFF); t = (t >> 26) + 2L * (x_0 * x_9 + x_1 * x_8 + x_2 * x_7 + x_3 * x_6 + x_4 * x_5); x2._9 = (t & 0x1FFFFFF); t = 19L * (t >> 25) + x_0 * x_0 + 38L * (x_2 * x_8 + x_4 * x_6 + x_5 * x_5) + 76L * (x_1 * x_9 + x_3 * x_7); x2._0 = (t & 0x3FFFFFF); t = (t >> 26) + 2L * (x_0 * x_1) + 38L * (x_2 * x_9 + x_3 * x_8 + x_4 * x_7 + x_5 * x_6); x2._1 = (t & 0x1FFFFFF); t = (t >> 25) + 19L * (x_6 * x_6) + 2L * (x_0 * x_2 + x_1 * x_1) + 38L * (x_4 * x_8) + 76L * (x_3 * x_9 + x_5 * x_7); x2._2 = (t & 0x3FFFFFF); t = (t >> 26) + 2L * (x_0 * x_3 + x_1 * x_2) + 38L * (x_4 * x_9 + x_5 * x_8 + x_6 * x_7); x2._3 = (t & 0x1FFFFFF); t = (t >> 25) + x_2 * x_2 + 2L * (x_0 * x_4) + 38L * (x_6 * x_8 + x_7 * x_7) + 4L * (x_1 * x_3) + 76L * (x_5 * x_9); x2._4 = (t & 0x3FFFFFF); t = (t >> 26) + 2L * (x_0 * x_5 + x_1 * x_4 + x_2 * x_3) + 38L * (x_6 * x_9 + x_7 * x_8); x2._5 = (t & 0x1FFFFFF); t = (t >> 25) + 19L * (x_8 * x_8) + 2L * (x_0 * x_6 + x_2 * x_4 + x_3 * x_3) + 4L * (x_1 * x_5) + 76L * (x_7 * x_9); x2._6 = (t & 0x3FFFFFF); t = (t >> 26) + 2L * (x_0 * x_7 + x_1 * x_6 + x_2 * x_5 + x_3 * x_4) + 38L * (x_8 * x_9); x2._7 = (t & 0x1FFFFFF); t = (t >> 25) + x2._8; x2._8 = (t & 0x3FFFFFF); x2._9 += (t >> 26); return x2; } private static final void recip(Nxt.Curve25519.long10 y, Nxt.Curve25519.long10 x, int sqrtassist) { Nxt.Curve25519.long10 t0 = new Nxt.Curve25519.long10(); Nxt.Curve25519.long10 t1 = new Nxt.Curve25519.long10(); Nxt.Curve25519.long10 t2 = new Nxt.Curve25519.long10(); Nxt.Curve25519.long10 t3 = new Nxt.Curve25519.long10(); Nxt.Curve25519.long10 t4 = new Nxt.Curve25519.long10(); sqr(t1, x); sqr(t2, t1); sqr(t0, t2); mul(t2, t0, x); mul(t0, t2, t1); sqr(t1, t0); mul(t3, t1, t2); sqr(t1, t3); sqr(t2, t1); sqr(t1, t2); sqr(t2, t1); sqr(t1, t2); mul(t2, t1, t3); sqr(t1, t2); sqr(t3, t1); for (int i = 1; i < 5; i++) { sqr(t1, t3); sqr(t3, t1); } mul(t1, t3, t2); sqr(t3, t1); sqr(t4, t3); for (i = 1; i < 10; i++) { sqr(t3, t4); sqr(t4, t3); } mul(t3, t4, t1); for (i = 0; i < 5; i++) { sqr(t1, t3); sqr(t3, t1); } mul(t1, t3, t2); sqr(t2, t1); sqr(t3, t2); for (i = 1; i < 25; i++) { sqr(t2, t3); sqr(t3, t2); } mul(t2, t3, t1); sqr(t3, t2); sqr(t4, t3); for (i = 1; i < 50; i++) { sqr(t3, t4); sqr(t4, t3); } mul(t3, t4, t2); for (i = 0; i < 25; i++) { sqr(t4, t3); sqr(t3, t4); } mul(t2, t3, t1); sqr(t1, t2); sqr(t2, t1); if (sqrtassist != 0) { mul(y, x, t2); } else { sqr(t1, t2); sqr(t2, t1); sqr(t1, t2); mul(y, t1, t0); } } private static final int is_negative(Nxt.Curve25519.long10 x) { return (int)(((is_overflow(x)) || (x._9 < 0L) ? 1 : 0) ^ x._0 & 1L); } private static final void sqrt(Nxt.Curve25519.long10 x, Nxt.Curve25519.long10 u) { Nxt.Curve25519.long10 v = new Nxt.Curve25519.long10();Nxt.Curve25519.long10 t1 = new Nxt.Curve25519.long10();Nxt.Curve25519.long10 t2 = new Nxt.Curve25519.long10(); add(t1, u, u); recip(v, t1, 1); sqr(x, v); mul(t2, t1, x); t2._0 -= 1L; mul(t1, v, t2); mul(x, u, t1); } private static final void mont_prep(Nxt.Curve25519.long10 t1, Nxt.Curve25519.long10 t2, Nxt.Curve25519.long10 ax, Nxt.Curve25519.long10 az) { add(t1, ax, az); sub(t2, ax, az); } private static final void mont_add(Nxt.Curve25519.long10 t1, Nxt.Curve25519.long10 t2, Nxt.Curve25519.long10 t3, Nxt.Curve25519.long10 t4, Nxt.Curve25519.long10 ax, Nxt.Curve25519.long10 az, Nxt.Curve25519.long10 dx) { mul(ax, t2, t3); mul(az, t1, t4); add(t1, ax, az); sub(t2, ax, az); sqr(ax, t1); sqr(t1, t2); mul(az, t1, dx); } private static final void mont_dbl(Nxt.Curve25519.long10 t1, Nxt.Curve25519.long10 t2, Nxt.Curve25519.long10 t3, Nxt.Curve25519.long10 t4, Nxt.Curve25519.long10 bx, Nxt.Curve25519.long10 bz) { sqr(t1, t3); sqr(t2, t4); mul(bx, t1, t2); sub(t2, t1, t2); mul_small(bz, t2, 121665L); add(t1, t1, bz); mul(bz, t1, t2); } private static final void x_to_y2(Nxt.Curve25519.long10 t, Nxt.Curve25519.long10 y2, Nxt.Curve25519.long10 x) { sqr(t, x); mul_small(y2, x, 486662L); add(t, t, y2); t._0 += 1L; mul(y2, t, x); } private static final void core(byte[] Px, byte[] s, byte[] k, byte[] Gx) { Nxt.Curve25519.long10 dx = new Nxt.Curve25519.long10(); Nxt.Curve25519.long10 t1 = new Nxt.Curve25519.long10(); Nxt.Curve25519.long10 t2 = new Nxt.Curve25519.long10(); Nxt.Curve25519.long10 t3 = new Nxt.Curve25519.long10(); Nxt.Curve25519.long10 t4 = new Nxt.Curve25519.long10(); Nxt.Curve25519.long10[] x = { new Nxt.Curve25519.long10(), new Nxt.Curve25519.long10() }; Nxt.Curve25519.long10[] z = { new Nxt.Curve25519.long10(), new Nxt.Curve25519.long10() }; if (Gx != null) { unpack(dx, Gx); } else { set(dx, 9); } set(x[0], 1); set(z[0], 0); cpy(x[1], dx); set(z[1], 1); for (int i = 32; i { if (i == 0) { i = 0; } for (j = 8; j { int bit1 = (k[i] & 0xFF) >> j & 0x1; int bit0 = (k[i] & 0xFF ^ 0xFFFFFFFF) >> j & 0x1; Nxt.Curve25519.long10 ax = x[bit0]; Nxt.Curve25519.long10 az = z[bit0]; Nxt.Curve25519.long10 bx = x[bit1]; Nxt.Curve25519.long10 bz = z[bit1]; mont_prep(t1, t2, ax, az); mont_prep(t3, t4, bx, bz); mont_add(t1, t2, t3, t4, ax, az, dx); mont_dbl(t1, t2, t3, t4, bx, bz); } } int j; recip(t1, z[0], 0); mul(dx, x[0], t1); pack(dx, Px); if (s != null) { x_to_y2(t2, t1, dx); recip(t3, z[1], 0); mul(t2, x[1], t3); add(t2, t2, dx); t2._0 += 486671L; dx._0 -= 9L; sqr(t3, dx); mul(dx, t2, t3); sub(dx, dx, t1); dx._0 -= 39420360L; mul(t1, dx, BASE_R2Y); if (is_negative(t1) != 0) { cpy32(s, k); } else { mula_small(s, ORDER_TIMES_8, 0, k, 32, -1); } byte[] temp1 = new byte[32]; byte[] temp2 = new byte[64]; byte[] temp3 = new byte[64]; cpy32(temp1, ORDER); cpy32(s, egcd32(temp2, temp3, s, temp1)); if ((s[31] & 0x80) != 0) { mula_small(s, s, 0, ORDER, 32, 1); } } } private static final byte[] ORDER_TIMES_8 = { 104, -97, -82, -25, -46, 24, -109, -64, -78, -26, -68, 23, -11, -50, -9, -90, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -128 }; private static final Nxt.Curve25519.long10 BASE_2Y = new Nxt.Curve25519.long10(39999547L, 18689728L, 59995525L, 1648697L, 57546132L, 24010086L, 19059592L, 5425144L, 63499247L, 16420658L); private static final Nxt.Curve25519.long10 BASE_R2Y = new Nxt.Curve25519.long10(5744L, 8160848L, 4790893L, 13779497L, 35730846L, 12541209L, 49101323L, 30047407L, 40071253L, 6226132L); } static class Peer implements Comparable<Peer> { static final int STATE_NONCONNECTED = 0; static final int STATE_CONNECTED = 1; static final int STATE_DISCONNECTED = 2; final int index; String platform; String announcedAddress; boolean shareAddress; String hallmark; long accountId; int weight; int date; long adjustedWeight; String application; String version; long blacklistingTime; int state; long downloadedVolume; long uploadedVolume; Peer(String announcedAddress, int index) { this.announcedAddress = announcedAddress; this.index = index; } static Peer addPeer(String address, String announcedAddress) { try { new URL("http://" + address); } catch (MalformedURLException e) { Nxt.logDebugMessage("malformed peer address " + address, e); return null; } try { new URL("http://" + announcedAddress); } catch (MalformedURLException e) { Nxt.logDebugMessage("malformed peer announced address " + announcedAddress, e); announcedAddress = ""; } if ((address.equals("localhost")) || (address.equals("127.0.0.1")) || (address.equals("0:0:0:0:0:0:0:1"))) { return null; } if ((Nxt.myAddress != null) && (Nxt.myAddress.length() > 0) && (Nxt.myAddress.equals(announcedAddress))) { return null; } Peer peer = (Peer)Nxt.peers.get(announcedAddress.length() > 0 ? announcedAddress : address); if (peer == null) { peer = new Peer(announcedAddress, Nxt.peerCounter.incrementAndGet()); Nxt.peers.put(announcedAddress.length() > 0 ? announcedAddress : address, peer); } return peer; } boolean analyzeHallmark(String realHost, String hallmark) { if (hallmark == null) { return true; } try { byte[] hallmarkBytes; try { hallmarkBytes = Nxt.convert(hallmark); } catch (NumberFormatException e) { return false; } ByteBuffer buffer = ByteBuffer.wrap(hallmarkBytes); buffer.order(ByteOrder.LITTLE_ENDIAN); byte[] publicKey = new byte[32]; buffer.get(publicKey); int hostLength = buffer.getShort(); byte[] hostBytes = new byte[hostLength]; buffer.get(hostBytes); String host = new String(hostBytes, "UTF-8"); if ((host.length() > 100) || (!host.equals(realHost))) { return false; } int weight = buffer.getInt(); if ((weight <= 0) || (weight > 1000000000L)) { return false; } int date = buffer.getInt(); buffer.get(); byte[] signature = new byte[64]; buffer.get(signature); byte[] data = new byte[hallmarkBytes.length - 64]; System.arraycopy(hallmarkBytes, 0, data, 0, data.length); if (Nxt.Crypto.verify(signature, data, publicKey)) { this.hallmark = hallmark; long accountId = Nxt.Account.getId(publicKey); LinkedList<Peer> groupedPeers = new LinkedList(); int validDate = 0; this.accountId = accountId; this.weight = weight; this.date = date; for (Peer peer : Nxt.peers.values()) { if (peer.accountId == accountId) { groupedPeers.add(peer); if (peer.date > validDate) { validDate = peer.date; } } } long totalWeight = 0L; for (Peer peer : groupedPeers) { if (peer.date == validDate) { totalWeight += peer.weight; } else { peer.weight = 0; } } for (Peer peer : groupedPeers) { peer.adjustedWeight = (1000000000L * peer.weight / totalWeight); peer.updateWeight(); } return true; } } catch (RuntimeException|UnsupportedEncodingException e) { Nxt.logDebugMessage("Failed to analyze hallmark for peer " + realHost, e); } return false; } void blacklist() { this.blacklistingTime = System.currentTimeMillis(); JSONObject response = new JSONObject(); response.put("response", "processNewData"); JSONArray removedKnownPeers = new JSONArray(); JSONObject removedKnownPeer = new JSONObject(); removedKnownPeer.put("index", Integer.valueOf(this.index)); removedKnownPeers.add(removedKnownPeer); response.put("removedKnownPeers", removedKnownPeers); JSONArray addedBlacklistedPeers = new JSONArray(); JSONObject addedBlacklistedPeer = new JSONObject(); addedBlacklistedPeer.put("index", Integer.valueOf(this.index)); addedBlacklistedPeer.put("announcedAddress", this.announcedAddress.length() > 30 ? this.announcedAddress.substring(0, 30) + "..." : this.announcedAddress); for (String wellKnownPeer : Nxt.wellKnownPeers) { if (this.announcedAddress.equals(wellKnownPeer)) { addedBlacklistedPeer.put("wellKnown", Boolean.valueOf(true)); break; } } addedBlacklistedPeers.add(addedBlacklistedPeer); response.put("addedBlacklistedPeers", addedBlacklistedPeers); for (Nxt.User user : Nxt.users.values()) { user.send(response); } } public int compareTo(Peer o) { long weight = getWeight();long weight2 = o.getWeight(); if (weight > weight2) { return -1; } if (weight < weight2) { return 1; } return this.index - o.index; } void connect() { JSONObject request = new JSONObject(); request.put("requestType", "getInfo"); if ((Nxt.myAddress != null) && (Nxt.myAddress.length() > 0)) { request.put("announcedAddress", Nxt.myAddress); } if ((Nxt.myHallmark != null) && (Nxt.myHallmark.length() > 0)) { request.put("hallmark", Nxt.myHallmark); } request.put("application", "NRS"); request.put("version", "0.5.10"); request.put("platform", Nxt.myPlatform); request.put("scheme", Nxt.myScheme); request.put("port", Integer.valueOf(Nxt.myPort)); request.put("shareAddress", Boolean.valueOf(Nxt.shareMyAddress)); JSONObject response = send(request); if (response != null) { this.application = ((String)response.get("application")); this.version = ((String)response.get("version")); this.platform = ((String)response.get("platform")); this.shareAddress = Boolean.TRUE.equals(response.get("shareAddress")); if (analyzeHallmark(this.announcedAddress, (String)response.get("hallmark"))) { setState(1); } } } void deactivate() { if (this.state == 1) { disconnect(); } setState(0); JSONObject response = new JSONObject(); response.put("response", "processNewData"); JSONArray removedActivePeers = new JSONArray(); JSONObject removedActivePeer = new JSONObject(); removedActivePeer.put("index", Integer.valueOf(this.index)); removedActivePeers.add(removedActivePeer); response.put("removedActivePeers", removedActivePeers); if (this.announcedAddress.length() > 0) { JSONArray addedKnownPeers = new JSONArray(); JSONObject addedKnownPeer = new JSONObject(); addedKnownPeer.put("index", Integer.valueOf(this.index)); addedKnownPeer.put("announcedAddress", this.announcedAddress.length() > 30 ? this.announcedAddress.substring(0, 30) + "..." : this.announcedAddress); for (String wellKnownPeer : Nxt.wellKnownPeers) { if (this.announcedAddress.equals(wellKnownPeer)) { addedKnownPeer.put("wellKnown", Boolean.valueOf(true)); break; } } addedKnownPeers.add(addedKnownPeer); response.put("addedKnownPeers", addedKnownPeers); } for (Nxt.User user : Nxt.users.values()) { user.send(response); } } void disconnect() { setState(2); } static Peer getAnyPeer(int state, boolean applyPullThreshold) { List<Peer> selectedPeers = new ArrayList(); for (Peer peer : Nxt.peers.values()) { if ((peer.blacklistingTime <= 0L) && (peer.state == state) && (peer.announcedAddress.length() > 0) && ((!applyPullThreshold) || (!Nxt.enableHallmarkProtection) || (peer.getWeight() >= Nxt.pullThreshold))) { selectedPeers.add(peer); } } long hit; if (selectedPeers.size() > 0) { long totalWeight = 0L; for (Peer peer : selectedPeers) { long weight = peer.getWeight(); if (weight == 0L) { weight = 1L; } totalWeight += weight; } hit = ThreadLocalRandom.current().nextLong(totalWeight); for (Peer peer : selectedPeers) { long weight = peer.getWeight(); if (weight == 0L) { weight = 1L; } if (hit -= weight < 0L) { return peer; } } } return null; } static int getNumberOfConnectedPublicPeers() { int numberOfConnectedPeers = 0; for (Peer peer : Nxt.peers.values()) { if ((peer.state == 1) && (peer.announcedAddress.length() > 0)) { numberOfConnectedPeers++; } } return numberOfConnectedPeers; } int getWeight() { if (this.accountId == 0L) { return 0; } Nxt.Account account = (Nxt.Account)Nxt.accounts.get(Long.valueOf(this.accountId)); if (account == null) { return 0; } return (int)(this.adjustedWeight * (account.getBalance() / 100L) / 1000000000L); } String getSoftware() { StringBuilder buf = new StringBuilder(); buf.append(this.application == null ? "?" : this.application.substring(0, Math.min(this.application.length(), 10))); buf.append(" ("); buf.append(this.version == null ? "?" : this.version.substring(0, Math.min(this.version.length(), 10))); buf.append(")").append(" @ "); buf.append(this.platform == null ? "?" : this.platform.substring(0, Math.min(this.platform.length(), 12))); return buf.toString(); } void removeBlacklistedStatus() { setState(0); this.blacklistingTime = 0L; JSONObject response = new JSONObject(); response.put("response", "processNewData"); JSONArray removedBlacklistedPeers = new JSONArray(); JSONObject removedBlacklistedPeer = new JSONObject(); removedBlacklistedPeer.put("index", Integer.valueOf(this.index)); removedBlacklistedPeers.add(removedBlacklistedPeer); response.put("removedBlacklistedPeers", removedBlacklistedPeers); JSONArray addedKnownPeers = new JSONArray(); JSONObject addedKnownPeer = new JSONObject(); addedKnownPeer.put("index", Integer.valueOf(this.index)); addedKnownPeer.put("announcedAddress", this.announcedAddress.length() > 30 ? this.announcedAddress.substring(0, 30) + "..." : this.announcedAddress); for (String wellKnownPeer : Nxt.wellKnownPeers) { if (this.announcedAddress.equals(wellKnownPeer)) { addedKnownPeer.put("wellKnown", Boolean.valueOf(true)); break; } } addedKnownPeers.add(addedKnownPeer); response.put("addedKnownPeers", addedKnownPeers); for (Nxt.User user : Nxt.users.values()) { user.send(response); } } void removePeer() { Nxt.peers.values().remove(this); JSONObject response = new JSONObject(); response.put("response", "processNewData"); JSONArray removedKnownPeers = new JSONArray(); JSONObject removedKnownPeer = new JSONObject(); removedKnownPeer.put("index", Integer.valueOf(this.index)); removedKnownPeers.add(removedKnownPeer); response.put("removedKnownPeers", removedKnownPeers); for (Nxt.User user : Nxt.users.values()) { user.send(response); } } static void sendToSomePeers(JSONObject request) { request.put("protocol", Integer.valueOf(1)); final JSONStreamAware jsonStreamAware = new JSONStreamAware() { final char[] jsonChars = this.val$request.toJSONString().toCharArray(); public void writeJSONString(Writer out) throws IOException { out.write(this.jsonChars); } }; int successful = 0; List<Future<JSONObject>> expectedResponses = new ArrayList(); for (Peer peer : Nxt.peers.values()) { if ((!Nxt.enableHallmarkProtection) || (peer.getWeight() >= Nxt.pushThreshold)) { if ((peer.blacklistingTime == 0L) && (peer.state == 1) && (peer.announcedAddress.length() > 0)) { Future<JSONObject> futureResponse = Nxt.sendToPeersService.submit(new Callable() { public JSONObject call() { return this.val$peer.send(jsonStreamAware); } }); expectedResponses.add(futureResponse); } if (expectedResponses.size() >= Nxt.sendToPeersLimit - successful) { for (Future<JSONObject> future : expectedResponses) { try { JSONObject response = (JSONObject)future.get(); if ((response != null) && (response.get("error") == null)) { successful++; } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (ExecutionException e) { Nxt.logDebugMessage("Error in sendToSomePeers", e); } } expectedResponses.clear(); } if (successful >= Nxt.sendToPeersLimit) { return; } } } } JSONObject send(final JSONObject request) { request.put("protocol", Integer.valueOf(1)); send(new JSONStreamAware() { public void writeJSONString(Writer out) throws IOException { request.writeJSONString(out); } }); } JSONObject send(JSONStreamAware request) { String log = null; boolean showLog = false; HttpURLConnection connection = null; JSONObject response; try { if (Nxt.communicationLoggingMask != 0) { log = "\"" + this.announcedAddress + "\": " + request.toString(); } URL url = new URL("http: connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setConnectTimeout(Nxt.connectTimeout); connection.setReadTimeout(Nxt.readTimeout); Nxt.CountingOutputStream cos = new Nxt.CountingOutputStream(connection.getOutputStream()); Writer writer = new BufferedWriter(new OutputStreamWriter(cos, "UTF-8"));Throwable localThrowable4 = null; try { request.writeJSONString(writer); } catch (Throwable localThrowable1) { localThrowable4 = localThrowable1;throw localThrowable1; } finally { if (writer != null) { if (localThrowable4 != null) { try { writer.close(); } catch (Throwable x2) { localThrowable4.addSuppressed(x2); } } else { writer.close(); } } } updateUploadedVolume(cos.getCount()); if (connection.getResponseCode() == 200) { int numberOfBytes; JSONObject response; if ((Nxt.communicationLoggingMask & 0x4) != 0) { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[65536]; InputStream inputStream = connection.getInputStream();x2 = null; try { while ((numberOfBytes = inputStream.read(buffer)) > 0) { byteArrayOutputStream.write(buffer, 0, numberOfBytes); } } catch (Throwable localThrowable2) { x2 = localThrowable2;throw localThrowable2; } finally { if (inputStream != null) { if (x2 != null) { try { inputStream.close(); } catch (Throwable x2) { x2.addSuppressed(x2); } } else { inputStream.close(); } } } String responseValue = byteArrayOutputStream.toString("UTF-8"); log = log + " >>> " + responseValue; showLog = true; updateDownloadedVolume(responseValue.getBytes("UTF-8").length); response = (JSONObject)JSONValue.parse(responseValue); } else { Nxt.CountingInputStream cis = new Nxt.CountingInputStream(connection.getInputStream()); Object reader = new BufferedReader(new InputStreamReader(cis, "UTF-8"));numberOfBytes = null; try { response = (JSONObject)JSONValue.parse((Reader)reader); } catch (Throwable localThrowable5) { JSONObject response; numberOfBytes = localThrowable5;throw localThrowable5; } finally { if (reader != null) { if (numberOfBytes != null) { try { ((Reader)reader).close(); } catch (Throwable x2) { numberOfBytes.addSuppressed(x2); } } else { ((Reader)reader).close(); } } } updateDownloadedVolume(cis.getCount()); } } else { if ((Nxt.communicationLoggingMask & 0x2) != 0) { log = log + " >>> Peer responded with HTTP " + connection.getResponseCode() + " code!"; showLog = true; } disconnect(); response = null; } } catch (RuntimeException|IOException e) { if ((!(e instanceof ConnectException)) && (!(e instanceof UnknownHostException)) && (!(e instanceof NoRouteToHostException)) && (!(e instanceof SocketTimeoutException)) && (!(e instanceof SocketException))) { Nxt.logDebugMessage("Error sending JSON request", e); } if ((Nxt.communicationLoggingMask & 0x1) != 0) { log = log + " >>> " + e.toString(); showLog = true; } if (this.state == 0) { blacklist(); } else { disconnect(); } response = null; } if (showLog) { Nxt.logMessage(log + "\n"); } if (connection != null) { connection.disconnect(); } return response; } void setState(int state) { JSONObject response; JSONObject response; if ((this.state == 0) && (state != 0)) { response = new JSONObject(); response.put("response", "processNewData"); if (this.announcedAddress.length() > 0) { JSONArray removedKnownPeers = new JSONArray(); JSONObject removedKnownPeer = new JSONObject(); removedKnownPeer.put("index", Integer.valueOf(this.index)); removedKnownPeers.add(removedKnownPeer); response.put("removedKnownPeers", removedKnownPeers); } JSONArray addedActivePeers = new JSONArray(); JSONObject addedActivePeer = new JSONObject(); addedActivePeer.put("index", Integer.valueOf(this.index)); if (state == 2) { addedActivePeer.put("disconnected", Boolean.valueOf(true)); } for (Map.Entry<String, Peer> peerEntry : Nxt.peers.entrySet()) { if (peerEntry.getValue() == this) { addedActivePeer.put("address", ((String)peerEntry.getKey()).length() > 30 ? ((String)peerEntry.getKey()).substring(0, 30) + "..." : (String)peerEntry.getKey()); break; } } addedActivePeer.put("announcedAddress", this.announcedAddress.length() > 30 ? this.announcedAddress.substring(0, 30) + "..." : this.announcedAddress); addedActivePeer.put("weight", Integer.valueOf(getWeight())); addedActivePeer.put("downloaded", Long.valueOf(this.downloadedVolume)); addedActivePeer.put("uploaded", Long.valueOf(this.uploadedVolume)); addedActivePeer.put("software", getSoftware()); for (String wellKnownPeer : Nxt.wellKnownPeers) { if (this.announcedAddress.equals(wellKnownPeer)) { addedActivePeer.put("wellKnown", Boolean.valueOf(true)); break; } } addedActivePeers.add(addedActivePeer); response.put("addedActivePeers", addedActivePeers); for (Nxt.User user : Nxt.users.values()) { user.send(response); } } else if ((this.state != 0) && (state != 0)) { response = new JSONObject(); response.put("response", "processNewData"); JSONArray changedActivePeers = new JSONArray(); JSONObject changedActivePeer = new JSONObject(); changedActivePeer.put("index", Integer.valueOf(this.index)); changedActivePeer.put(state == 1 ? "connected" : "disconnected", Boolean.valueOf(true)); changedActivePeers.add(changedActivePeer); response.put("changedActivePeers", changedActivePeers); for (Nxt.User user : Nxt.users.values()) { user.send(response); } } this.state = state; } void updateDownloadedVolume(long volume) { this.downloadedVolume += volume; JSONObject response = new JSONObject(); response.put("response", "processNewData"); JSONArray changedActivePeers = new JSONArray(); JSONObject changedActivePeer = new JSONObject(); changedActivePeer.put("index", Integer.valueOf(this.index)); changedActivePeer.put("downloaded", Long.valueOf(this.downloadedVolume)); changedActivePeers.add(changedActivePeer); response.put("changedActivePeers", changedActivePeers); for (Nxt.User user : Nxt.users.values()) { user.send(response); } } void updateUploadedVolume(long volume) { this.uploadedVolume += volume; JSONObject response = new JSONObject(); response.put("response", "processNewData"); JSONArray changedActivePeers = new JSONArray(); JSONObject changedActivePeer = new JSONObject(); changedActivePeer.put("index", Integer.valueOf(this.index)); changedActivePeer.put("uploaded", Long.valueOf(this.uploadedVolume)); changedActivePeers.add(changedActivePeer); response.put("changedActivePeers", changedActivePeers); for (Nxt.User user : Nxt.users.values()) { user.send(response); } } void updateWeight() { JSONObject response = new JSONObject(); response.put("response", "processNewData"); JSONArray changedActivePeers = new JSONArray(); JSONObject changedActivePeer = new JSONObject(); changedActivePeer.put("index", Integer.valueOf(this.index)); changedActivePeer.put("weight", Integer.valueOf(getWeight())); changedActivePeers.add(changedActivePeer); response.put("changedActivePeers", changedActivePeers); for (Nxt.User user : Nxt.users.values()) { user.send(response); } } } static class Transaction implements Comparable<Transaction>, Serializable { static final long serialVersionUID = 0L; static final byte TYPE_PAYMENT = 0; static final byte TYPE_MESSAGING = 1; static final byte TYPE_COLORED_COINS = 2; static final byte SUBTYPE_PAYMENT_ORDINARY_PAYMENT = 0; static final byte SUBTYPE_MESSAGING_ARBITRARY_MESSAGE = 0; static final byte SUBTYPE_MESSAGING_ALIAS_ASSIGNMENT = 1; static final byte SUBTYPE_COLORED_COINS_ASSET_ISSUANCE = 0; static final byte SUBTYPE_COLORED_COINS_ASSET_TRANSFER = 1; static final byte SUBTYPE_COLORED_COINS_ASK_ORDER_PLACEMENT = 2; static final byte SUBTYPE_COLORED_COINS_BID_ORDER_PLACEMENT = 3; static final byte SUBTYPE_COLORED_COINS_ASK_ORDER_CANCELLATION = 4; static final byte SUBTYPE_COLORED_COINS_BID_ORDER_CANCELLATION = 5; static final int ASSET_ISSUANCE_FEE = 1000; final byte type; final byte subtype; int timestamp; final short deadline; final byte[] senderPublicKey; final long recipient; final int amount; final int fee; final long referencedTransaction; byte[] signature; Nxt.Transaction.Attachment attachment; int index; long block; int height; Transaction(byte type, byte subtype, int timestamp, short deadline, byte[] senderPublicKey, long recipient, int amount, int fee, long referencedTransaction, byte[] signature) { this.type = type; this.subtype = subtype; this.timestamp = timestamp; this.deadline = deadline; this.senderPublicKey = senderPublicKey; this.recipient = recipient; this.amount = amount; this.fee = fee; this.referencedTransaction = referencedTransaction; this.signature = signature; this.height = 2147483647; } public int compareTo(Transaction o) { if (this.height < o.height) { return -1; } if (this.height > o.height) { return 1; } if (this.fee * o.getSize() > o.fee * getSize()) { return -1; } if (this.fee * o.getSize() < o.fee * getSize()) { return 1; } if (this.timestamp < o.timestamp) { return -1; } if (this.timestamp > o.timestamp) { return 1; } if (this.index < o.index) { return -1; } if (this.index > o.index) { return 1; } return 0; } public static final Comparator<Transaction> timestampComparator = new Comparator() { public int compare(Nxt.Transaction o1, Nxt.Transaction o2) { return o1.timestamp > o2.timestamp ? 1 : o1.timestamp < o2.timestamp ? -1 : 0; } }; private static final int TRANSACTION_BYTES_LENGTH = 128; volatile transient long id; int getSize() { return 128 + (this.attachment == null ? 0 : this.attachment.getSize()); } byte[] getBytes() { ByteBuffer buffer = ByteBuffer.allocate(getSize()); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.put(this.type); buffer.put(this.subtype); buffer.putInt(this.timestamp); buffer.putShort(this.deadline); buffer.put(this.senderPublicKey); buffer.putLong(this.recipient); buffer.putInt(this.amount); buffer.putInt(this.fee); buffer.putLong(this.referencedTransaction); buffer.put(this.signature); if (this.attachment != null) { buffer.put(this.attachment.getBytes()); } return buffer.array(); } volatile transient String stringId = null; volatile transient long senderAccountId; long getId() { calculateIds(); return this.id; } String getStringId() { calculateIds(); return this.stringId; } long getSenderAccountId() { calculateIds(); return this.senderAccountId; } private void calculateIds() { if (this.stringId != null) { return; } byte[] hash = Nxt.getMessageDigest("SHA-256").digest(getBytes()); BigInteger bigInteger = new BigInteger(1, new byte[] { hash[7], hash[6], hash[5], hash[4], hash[3], hash[2], hash[1], hash[0] }); this.id = bigInteger.longValue(); this.stringId = bigInteger.toString(); this.senderAccountId = Nxt.Account.getId(this.senderPublicKey); } JSONObject getJSONObject() { JSONObject transaction = new JSONObject(); transaction.put("type", Byte.valueOf(this.type)); transaction.put("subtype", Byte.valueOf(this.subtype)); transaction.put("timestamp", Integer.valueOf(this.timestamp)); transaction.put("deadline", Short.valueOf(this.deadline)); transaction.put("senderPublicKey", Nxt.convert(this.senderPublicKey)); transaction.put("recipient", Nxt.convert(this.recipient)); transaction.put("amount", Integer.valueOf(this.amount)); transaction.put("fee", Integer.valueOf(this.fee)); transaction.put("referencedTransaction", Nxt.convert(this.referencedTransaction)); transaction.put("signature", Nxt.convert(this.signature)); if (this.attachment != null) { transaction.put("attachment", this.attachment.getJSONObject()); } return transaction; } long getRecipientDeltaBalance() { return this.amount * 100L + (this.attachment == null ? 0L : this.attachment.getRecipientDeltaBalance()); } long getSenderDeltaBalance() { return -(this.amount + this.fee) * 100L + (this.attachment == null ? 0L : this.attachment.getSenderDeltaBalance()); } static Transaction getTransaction(ByteBuffer buffer) { byte type = buffer.get(); byte subtype = buffer.get(); int timestamp = buffer.getInt(); short deadline = buffer.getShort(); byte[] senderPublicKey = new byte[32]; buffer.get(senderPublicKey); long recipient = buffer.getLong(); int amount = buffer.getInt(); int fee = buffer.getInt(); long referencedTransaction = buffer.getLong(); byte[] signature = new byte[64]; buffer.get(signature); Transaction transaction = new Transaction(type, subtype, timestamp, deadline, senderPublicKey, recipient, amount, fee, referencedTransaction, signature); switch (type) { case 1: switch (subtype) { case 0: int messageLength = buffer.getInt(); if (messageLength <= 1000) { byte[] message = new byte[messageLength]; buffer.get(message); transaction.attachment = new Nxt.Transaction.MessagingArbitraryMessageAttachment(message); } break; case 1: int aliasLength = buffer.get(); byte[] alias = new byte[aliasLength]; buffer.get(alias); int uriLength = buffer.getShort(); byte[] uri = new byte[uriLength]; buffer.get(uri); try { transaction.attachment = new Nxt.Transaction.MessagingAliasAssignmentAttachment(new String(alias, "UTF-8").intern(), new String(uri, "UTF-8").intern()); } catch (RuntimeException|UnsupportedEncodingException e) { Nxt.logDebugMessage("Error parsing alias assignment", e); } } break; case 2: switch (subtype) { case 0: int nameLength = buffer.get(); byte[] name = new byte[nameLength]; buffer.get(name); int descriptionLength = buffer.getShort(); byte[] description = new byte[descriptionLength]; buffer.get(description); int quantity = buffer.getInt(); try { transaction.attachment = new Nxt.Transaction.ColoredCoinsAssetIssuanceAttachment(new String(name, "UTF-8").intern(), new String(description, "UTF-8").intern(), quantity); } catch (RuntimeException|UnsupportedEncodingException e) { Nxt.logDebugMessage("Error in asset issuance", e); } break; case 1: long asset = buffer.getLong(); int quantity = buffer.getInt(); transaction.attachment = new Nxt.Transaction.ColoredCoinsAssetTransferAttachment(asset, quantity); break; case 2: long asset = buffer.getLong(); int quantity = buffer.getInt(); long price = buffer.getLong(); transaction.attachment = new Nxt.Transaction.ColoredCoinsAskOrderPlacementAttachment(asset, quantity, price); break; case 3: long asset = buffer.getLong(); int quantity = buffer.getInt(); long price = buffer.getLong(); transaction.attachment = new Nxt.Transaction.ColoredCoinsBidOrderPlacementAttachment(asset, quantity, price); break; case 4: long order = buffer.getLong(); transaction.attachment = new Nxt.Transaction.ColoredCoinsAskOrderCancellationAttachment(order); break; case 5: long order = buffer.getLong(); transaction.attachment = new Nxt.Transaction.ColoredCoinsBidOrderCancellationAttachment(order); } break; } return transaction; } static Transaction getTransaction(JSONObject transactionData) { byte type = ((Long)transactionData.get("type")).byteValue(); byte subtype = ((Long)transactionData.get("subtype")).byteValue(); int timestamp = ((Long)transactionData.get("timestamp")).intValue(); short deadline = ((Long)transactionData.get("deadline")).shortValue(); byte[] senderPublicKey = Nxt.convert((String)transactionData.get("senderPublicKey")); long recipient = Nxt.parseUnsignedLong((String)transactionData.get("recipient")); int amount = ((Long)transactionData.get("amount")).intValue(); int fee = ((Long)transactionData.get("fee")).intValue(); long referencedTransaction = Nxt.parseUnsignedLong((String)transactionData.get("referencedTransaction")); byte[] signature = Nxt.convert((String)transactionData.get("signature")); Transaction transaction = new Transaction(type, subtype, timestamp, deadline, senderPublicKey, recipient, amount, fee, referencedTransaction, signature); JSONObject attachmentData = (JSONObject)transactionData.get("attachment"); switch (type) { case 1: switch (subtype) { case 0: String message = (String)attachmentData.get("message"); transaction.attachment = new Nxt.Transaction.MessagingArbitraryMessageAttachment(Nxt.convert(message)); break; case 1: String alias = (String)attachmentData.get("alias"); String uri = (String)attachmentData.get("uri"); transaction.attachment = new Nxt.Transaction.MessagingAliasAssignmentAttachment(alias.trim(), uri.trim()); } break; case 2: switch (subtype) { case 0: String name = (String)attachmentData.get("name"); String description = (String)attachmentData.get("description"); int quantity = ((Long)attachmentData.get("quantity")).intValue(); transaction.attachment = new Nxt.Transaction.ColoredCoinsAssetIssuanceAttachment(name.trim(), description.trim(), quantity); break; case 1: long asset = Nxt.parseUnsignedLong((String)attachmentData.get("asset")); int quantity = ((Long)attachmentData.get("quantity")).intValue(); transaction.attachment = new Nxt.Transaction.ColoredCoinsAssetTransferAttachment(asset, quantity); break; case 2: long asset = Nxt.parseUnsignedLong((String)attachmentData.get("asset")); int quantity = ((Long)attachmentData.get("quantity")).intValue(); long price = ((Long)attachmentData.get("price")).longValue(); transaction.attachment = new Nxt.Transaction.ColoredCoinsAskOrderPlacementAttachment(asset, quantity, price); break; case 3: long asset = Nxt.parseUnsignedLong((String)attachmentData.get("asset")); int quantity = ((Long)attachmentData.get("quantity")).intValue(); long price = ((Long)attachmentData.get("price")).longValue(); transaction.attachment = new Nxt.Transaction.ColoredCoinsBidOrderPlacementAttachment(asset, quantity, price); break; case 4: transaction.attachment = new Nxt.Transaction.ColoredCoinsAskOrderCancellationAttachment(Nxt.parseUnsignedLong((String)attachmentData.get("order"))); break; case 5: transaction.attachment = new Nxt.Transaction.ColoredCoinsBidOrderCancellationAttachment(Nxt.parseUnsignedLong((String)attachmentData.get("order"))); } break; } return transaction; } static void loadTransactions(String fileName) throws FileNotFoundException { try { FileInputStream fileInputStream = new FileInputStream(fileName);Throwable localThrowable3 = null; try { ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);Throwable localThrowable4 = null; try { Nxt.transactionCounter.set(objectInputStream.readInt()); Nxt.transactions.clear(); Nxt.transactions.putAll((HashMap)objectInputStream.readObject()); } catch (Throwable localThrowable1) { localThrowable4 = localThrowable1;throw localThrowable1; } finally {} } catch (Throwable localThrowable2) { localThrowable3 = localThrowable2;throw localThrowable2; } finally { if (fileInputStream != null) { if (localThrowable3 != null) { try { fileInputStream.close(); } catch (Throwable x2) { localThrowable3.addSuppressed(x2); } } else { fileInputStream.close(); } } } } catch (FileNotFoundException e) { throw e; } catch (IOException|ClassNotFoundException e) { Nxt.logMessage("Error loading transactions from " + fileName, e); System.exit(1); } } static void processTransactions(JSONObject request, String parameterName) { JSONArray transactionsData = (JSONArray)request.get(parameterName); JSONArray validTransactionsData = new JSONArray(); for (Object transactionData : transactionsData) { Transaction transaction = getTransaction((JSONObject)transactionData); try { int curTime = Nxt.getEpochTime(System.currentTimeMillis()); if ((transaction.timestamp > curTime + 15) || (transaction.deadline < 1) || (transaction.timestamp + transaction.deadline * 60 < curTime) || (transaction.fee <= 0) || (transaction.validateAttachment())) { long senderId; boolean doubleSpendingTransaction; synchronized (Nxt.blocksAndTransactionsLock) { long id = transaction.getId(); if ((Nxt.transactions.get(Long.valueOf(id)) == null) && (Nxt.unconfirmedTransactions.get(Long.valueOf(id)) == null) && (Nxt.doubleSpendingTransactions.get(Long.valueOf(id)) == null) && (!transaction.verify())) { continue; } senderId = transaction.getSenderAccountId(); Nxt.Account account = (Nxt.Account)Nxt.accounts.get(Long.valueOf(senderId)); boolean doubleSpendingTransaction; if (account == null) { doubleSpendingTransaction = true; } else { int amount = transaction.amount + transaction.fee; synchronized (account) { boolean doubleSpendingTransaction; if (account.getUnconfirmedBalance() < amount * 100L) { doubleSpendingTransaction = true; } else { doubleSpendingTransaction = false; account.addToUnconfirmedBalance(-amount * 100L); if (transaction.type == 2) { if (transaction.subtype == 1) { Nxt.Transaction.ColoredCoinsAssetTransferAttachment attachment = (Nxt.Transaction.ColoredCoinsAssetTransferAttachment)transaction.attachment; Integer unconfirmedAssetBalance = account.getUnconfirmedAssetBalance(Long.valueOf(attachment.asset)); if ((unconfirmedAssetBalance == null) || (unconfirmedAssetBalance.intValue() < attachment.quantity)) { doubleSpendingTransaction = true; account.addToUnconfirmedBalance(amount * 100L); } else { account.addToUnconfirmedAssetBalance(Long.valueOf(attachment.asset), -attachment.quantity); } } else if (transaction.subtype == 2) { Nxt.Transaction.ColoredCoinsAskOrderPlacementAttachment attachment = (Nxt.Transaction.ColoredCoinsAskOrderPlacementAttachment)transaction.attachment; Integer unconfirmedAssetBalance = account.getUnconfirmedAssetBalance(Long.valueOf(attachment.asset)); if ((unconfirmedAssetBalance == null) || (unconfirmedAssetBalance.intValue() < attachment.quantity)) { doubleSpendingTransaction = true; account.addToUnconfirmedBalance(amount * 100L); } else { account.addToUnconfirmedAssetBalance(Long.valueOf(attachment.asset), -attachment.quantity); } } else if (transaction.subtype == 3) { Nxt.Transaction.ColoredCoinsBidOrderPlacementAttachment attachment = (Nxt.Transaction.ColoredCoinsBidOrderPlacementAttachment)transaction.attachment; if (account.getUnconfirmedBalance() < attachment.quantity * attachment.price) { doubleSpendingTransaction = true; account.addToUnconfirmedBalance(amount * 100L); } else { account.addToUnconfirmedBalance(-attachment.quantity * attachment.price); } } } } } } transaction.index = Nxt.transactionCounter.incrementAndGet(); if (doubleSpendingTransaction) { Nxt.doubleSpendingTransactions.put(Long.valueOf(transaction.getId()), transaction); } else { Nxt.unconfirmedTransactions.put(Long.valueOf(transaction.getId()), transaction); if (parameterName.equals("transactions")) { validTransactionsData.add(transactionData); } } } response = new JSONObject(); response.put("response", "processNewData"); JSONArray newTransactions = new JSONArray(); JSONObject newTransaction = new JSONObject(); newTransaction.put("index", Integer.valueOf(transaction.index)); newTransaction.put("timestamp", Integer.valueOf(transaction.timestamp)); newTransaction.put("deadline", Short.valueOf(transaction.deadline)); newTransaction.put("recipient", Nxt.convert(transaction.recipient)); newTransaction.put("amount", Integer.valueOf(transaction.amount)); newTransaction.put("fee", Integer.valueOf(transaction.fee)); newTransaction.put("sender", Nxt.convert(senderId)); newTransaction.put("id", transaction.getStringId()); newTransactions.add(newTransaction); if (doubleSpendingTransaction) { response.put("addedDoubleSpendingTransactions", newTransactions); } else { response.put("addedUnconfirmedTransactions", newTransactions); } for (Nxt.User user : Nxt.users.values()) { user.send(response); } } } catch (RuntimeException e) { JSONObject response; Nxt.logMessage("Error processing transaction", e); } } if (validTransactionsData.size() > 0) { JSONObject peerRequest = new JSONObject(); peerRequest.put("requestType", "processTransactions"); peerRequest.put("transactions", validTransactionsData); Nxt.Peer.sendToSomePeers(peerRequest); } } static void saveTransactions(String fileName) { try { FileOutputStream fileOutputStream = new FileOutputStream(fileName);Throwable localThrowable3 = null; try { ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);Throwable localThrowable4 = null; try { objectOutputStream.writeInt(Nxt.transactionCounter.get()); objectOutputStream.writeObject(new HashMap(Nxt.transactions)); objectOutputStream.close(); } catch (Throwable localThrowable1) { localThrowable4 = localThrowable1;throw localThrowable1; } finally {} } catch (Throwable localThrowable2) { localThrowable3 = localThrowable2;throw localThrowable2; } finally { if (fileOutputStream != null) { if (localThrowable3 != null) { try { fileOutputStream.close(); } catch (Throwable x2) { localThrowable3.addSuppressed(x2); } } else { fileOutputStream.close(); } } } } catch (IOException e) { Nxt.logMessage("Error saving transactions to " + fileName, e); throw new RuntimeException(e); } } void sign(String secretPhrase) { this.signature = Nxt.Crypto.sign(getBytes(), secretPhrase); try { while (!verify()) { this.timestamp += 1; this.signature = new byte[64]; this.signature = Nxt.Crypto.sign(getBytes(), secretPhrase); } } catch (RuntimeException e) { Nxt.logMessage("Error signing transaction", e); } } boolean validateAttachment() { if (this.fee > 1000000000L) { return false; } switch (this.type) { case 0: switch (this.subtype) { case 0: return (this.amount > 0) && (this.amount < 1000000000L); } return false; case 1: switch (this.subtype) { case 0: if (((Nxt.Block)Nxt.lastBlock.get()).height < 40000) { return false; } try { Nxt.Transaction.MessagingArbitraryMessageAttachment attachment = (Nxt.Transaction.MessagingArbitraryMessageAttachment)this.attachment; return (this.amount == 0) && (attachment.message.length <= 1000); } catch (RuntimeException e) { Nxt.logDebugMessage("Error validating arbitrary message", e); return false; } case 1: if (((Nxt.Block)Nxt.lastBlock.get()).height < 22000) { return false; } try { Nxt.Transaction.MessagingAliasAssignmentAttachment attachment = (Nxt.Transaction.MessagingAliasAssignmentAttachment)this.attachment; if ((this.recipient != 1739068987193023818L) || (this.amount != 0) || (attachment.alias.length() == 0) || (attachment.alias.length() > 100) || (attachment.uri.length() > 1000)) { return false; } String normalizedAlias = attachment.alias.toLowerCase(); for (int i = 0; i < normalizedAlias.length(); i++) { if ("0123456789abcdefghijklmnopqrstuvwxyz".indexOf(normalizedAlias.charAt(i)) < 0) { return false; } } Nxt.Alias alias = (Nxt.Alias)Nxt.aliases.get(normalizedAlias); return (alias == null) || (Arrays.equals((byte[])alias.account.publicKey.get(), this.senderPublicKey)); } catch (RuntimeException e) { Nxt.logDebugMessage("Error in alias assignment validation", e); return false; } } return false; } return false; } boolean verify() { Nxt.Account account = (Nxt.Account)Nxt.accounts.get(Long.valueOf(getSenderAccountId())); if (account == null) { return false; } byte[] data = getBytes(); for (int i = 64; i < 128; i++) { data[i] = 0; } return (Nxt.Crypto.verify(this.signature, data, this.senderPublicKey)) && (account.setOrVerify(this.senderPublicKey)); } public static byte[] calculateTransactionsChecksum() { synchronized (Nxt.blocksAndTransactionsLock) { PriorityQueue<Transaction> sortedTransactions = new PriorityQueue(Nxt.transactions.size(), new Comparator() { public int compare(Nxt.Transaction o1, Nxt.Transaction o2) { long id1 = o1.getId(); long id2 = o2.getId(); return o1.timestamp > o2.timestamp ? 1 : o1.timestamp < o2.timestamp ? -1 : id1 > id2 ? 1 : id1 < id2 ? -1 : 0; } }); sortedTransactions.addAll(Nxt.transactions.values()); MessageDigest digest = Nxt.getMessageDigest("SHA-256"); while (!sortedTransactions.isEmpty()) { digest.update(((Transaction)sortedTransactions.poll()).getBytes()); } return digest.digest(); } } static abstract interface Attachment { public abstract int getSize(); public abstract byte[] getBytes(); public abstract JSONObject getJSONObject(); public abstract long getRecipientDeltaBalance(); public abstract long getSenderDeltaBalance(); } static class MessagingArbitraryMessageAttachment implements Nxt.Transaction.Attachment, Serializable { static final long serialVersionUID = 0L; final byte[] message; MessagingArbitraryMessageAttachment(byte[] message) { this.message = message; } public int getSize() { return 4 + this.message.length; } public byte[] getBytes() { ByteBuffer buffer = ByteBuffer.allocate(getSize()); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.putInt(this.message.length); buffer.put(this.message); return buffer.array(); } public JSONObject getJSONObject() { JSONObject attachment = new JSONObject(); attachment.put("message", Nxt.convert(this.message)); return attachment; } public long getRecipientDeltaBalance() { return 0L; } public long getSenderDeltaBalance() { return 0L; } } static class MessagingAliasAssignmentAttachment implements Nxt.Transaction.Attachment, Serializable { static final long serialVersionUID = 0L; final String alias; final String uri; MessagingAliasAssignmentAttachment(String alias, String uri) { this.alias = alias; this.uri = uri; } public int getSize() { try { return 1 + this.alias.getBytes("UTF-8").length + 2 + this.uri.getBytes("UTF-8").length; } catch (RuntimeException|UnsupportedEncodingException e) { Nxt.logMessage("Error in getBytes", e); } return 0; } public byte[] getBytes() { try { byte[] alias = this.alias.getBytes("UTF-8"); byte[] uri = this.uri.getBytes("UTF-8"); ByteBuffer buffer = ByteBuffer.allocate(1 + alias.length + 2 + uri.length); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.put((byte)alias.length); buffer.put(alias); buffer.putShort((short)uri.length); buffer.put(uri); return buffer.array(); } catch (RuntimeException|UnsupportedEncodingException e) { Nxt.logMessage("Error in getBytes", e); } return null; } public JSONObject getJSONObject() { JSONObject attachment = new JSONObject(); attachment.put("alias", this.alias); attachment.put("uri", this.uri); return attachment; } public long getRecipientDeltaBalance() { return 0L; } public long getSenderDeltaBalance() { return 0L; } } static class ColoredCoinsAssetIssuanceAttachment implements Nxt.Transaction.Attachment, Serializable { static final long serialVersionUID = 0L; String name; String description; int quantity; ColoredCoinsAssetIssuanceAttachment(String name, String description, int quantity) { this.name = name; this.description = (description == null ? "" : description); this.quantity = quantity; } public int getSize() { try { return 1 + this.name.getBytes("UTF-8").length + 2 + this.description.getBytes("UTF-8").length + 4; } catch (RuntimeException|UnsupportedEncodingException e) { Nxt.logMessage("Error in getBytes", e); } return 0; } public byte[] getBytes() { try { byte[] name = this.name.getBytes("UTF-8"); byte[] description = this.description.getBytes("UTF-8"); ByteBuffer buffer = ByteBuffer.allocate(1 + name.length + 2 + description.length + 4); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.put((byte)name.length); buffer.put(name); buffer.putShort((short)description.length); buffer.put(description); buffer.putInt(this.quantity); return buffer.array(); } catch (RuntimeException|UnsupportedEncodingException e) { Nxt.logMessage("Error in getBytes", e); } return null; } public JSONObject getJSONObject() { JSONObject attachment = new JSONObject(); attachment.put("name", this.name); attachment.put("description", this.description); attachment.put("quantity", Integer.valueOf(this.quantity)); return attachment; } public long getRecipientDeltaBalance() { return 0L; } public long getSenderDeltaBalance() { return 0L; } } static class ColoredCoinsAssetTransferAttachment implements Nxt.Transaction.Attachment, Serializable { static final long serialVersionUID = 0L; long asset; int quantity; ColoredCoinsAssetTransferAttachment(long asset, int quantity) { this.asset = asset; this.quantity = quantity; } public int getSize() { return 12; } public byte[] getBytes() { ByteBuffer buffer = ByteBuffer.allocate(getSize()); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.putLong(this.asset); buffer.putInt(this.quantity); return buffer.array(); } public JSONObject getJSONObject() { JSONObject attachment = new JSONObject(); attachment.put("asset", Nxt.convert(this.asset)); attachment.put("quantity", Integer.valueOf(this.quantity)); return attachment; } public long getRecipientDeltaBalance() { return 0L; } public long getSenderDeltaBalance() { return 0L; } } static class ColoredCoinsAskOrderPlacementAttachment implements Nxt.Transaction.Attachment, Serializable { static final long serialVersionUID = 0L; long asset; int quantity; long price; ColoredCoinsAskOrderPlacementAttachment(long asset, int quantity, long price) { this.asset = asset; this.quantity = quantity; this.price = price; } public int getSize() { return 20; } public byte[] getBytes() { ByteBuffer buffer = ByteBuffer.allocate(getSize()); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.putLong(this.asset); buffer.putInt(this.quantity); buffer.putLong(this.price); return buffer.array(); } public JSONObject getJSONObject() { JSONObject attachment = new JSONObject(); attachment.put("asset", Nxt.convert(this.asset)); attachment.put("quantity", Integer.valueOf(this.quantity)); attachment.put("price", Long.valueOf(this.price)); return attachment; } public long getRecipientDeltaBalance() { return 0L; } public long getSenderDeltaBalance() { return 0L; } } static class ColoredCoinsBidOrderPlacementAttachment implements Nxt.Transaction.Attachment, Serializable { static final long serialVersionUID = 0L; long asset; int quantity; long price; ColoredCoinsBidOrderPlacementAttachment(long asset, int quantity, long price) { this.asset = asset; this.quantity = quantity; this.price = price; } public int getSize() { return 20; } public byte[] getBytes() { ByteBuffer buffer = ByteBuffer.allocate(getSize()); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.putLong(this.asset); buffer.putInt(this.quantity); buffer.putLong(this.price); return buffer.array(); } public JSONObject getJSONObject() { JSONObject attachment = new JSONObject(); attachment.put("asset", Nxt.convert(this.asset)); attachment.put("quantity", Integer.valueOf(this.quantity)); attachment.put("price", Long.valueOf(this.price)); return attachment; } public long getRecipientDeltaBalance() { return 0L; } public long getSenderDeltaBalance() { return -this.quantity * this.price; } } static class ColoredCoinsAskOrderCancellationAttachment implements Nxt.Transaction.Attachment, Serializable { static final long serialVersionUID = 0L; long order; ColoredCoinsAskOrderCancellationAttachment(long order) { this.order = order; } public int getSize() { return 8; } public byte[] getBytes() { ByteBuffer buffer = ByteBuffer.allocate(getSize()); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.putLong(this.order); return buffer.array(); } public JSONObject getJSONObject() { JSONObject attachment = new JSONObject(); attachment.put("order", Nxt.convert(this.order)); return attachment; } public long getRecipientDeltaBalance() { return 0L; } public long getSenderDeltaBalance() { return 0L; } } static class ColoredCoinsBidOrderCancellationAttachment implements Nxt.Transaction.Attachment, Serializable { static final long serialVersionUID = 0L; long order; ColoredCoinsBidOrderCancellationAttachment(long order) { this.order = order; } public int getSize() { return 8; } public byte[] getBytes() { ByteBuffer buffer = ByteBuffer.allocate(getSize()); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.putLong(this.order); return buffer.array(); } public JSONObject getJSONObject() { JSONObject attachment = new JSONObject(); attachment.put("order", Nxt.convert(this.order)); return attachment; } public long getRecipientDeltaBalance() { return 0L; } public long getSenderDeltaBalance() { Nxt.BidOrder bidOrder = (Nxt.BidOrder)Nxt.bidOrders.get(Long.valueOf(this.order)); if (bidOrder == null) { return 0L; } return bidOrder.quantity * bidOrder.price; } } } static class User { final ConcurrentLinkedQueue<JSONObject> pendingResponses; AsyncContext asyncContext; volatile boolean isInactive; volatile String secretPhrase; volatile byte[] publicKey; User() { this.pendingResponses = new ConcurrentLinkedQueue(); } void deinitializeKeyPair() { this.secretPhrase = null; this.publicKey = null; } BigInteger initializeKeyPair(String secretPhrase) { this.publicKey = Nxt.Crypto.getPublicKey(secretPhrase); this.secretPhrase = secretPhrase; byte[] publicKeyHash = Nxt.getMessageDigest("SHA-256").digest(this.publicKey); return new BigInteger(1, new byte[] { publicKeyHash[7], publicKeyHash[6], publicKeyHash[5], publicKeyHash[4], publicKeyHash[3], publicKeyHash[2], publicKeyHash[1], publicKeyHash[0] }); } void send(JSONObject response) { synchronized (this) { if (this.asyncContext == null) { if (this.isInactive) { return; } if (this.pendingResponses.size() > 1000) { this.pendingResponses.clear(); this.isInactive = true; if (this.secretPhrase == null) { Nxt.users.values().remove(this); } return; } this.pendingResponses.offer(response); } else { JSONArray responses = new JSONArray(); JSONObject pendingResponse; while ((pendingResponse = (JSONObject)this.pendingResponses.poll()) != null) { responses.add(pendingResponse); } responses.add(response); JSONObject combinedResponse = new JSONObject(); combinedResponse.put("responses", responses); this.asyncContext.getResponse().setContentType("text/plain; charset=UTF-8"); try { Writer writer = this.asyncContext.getResponse().getWriter();Throwable localThrowable2 = null; try { combinedResponse.writeJSONString(writer); } catch (Throwable localThrowable1) { localThrowable2 = localThrowable1;throw localThrowable1; } finally { if (writer != null) { if (localThrowable2 != null) { try { writer.close(); } catch (Throwable x2) { localThrowable2.addSuppressed(x2); } } else { writer.close(); } } } } catch (IOException e) { Nxt.logMessage("Error sending response to user", e); } this.asyncContext.complete(); this.asyncContext = null; } } } } static class UserAsyncListener implements AsyncListener { final Nxt.User user; UserAsyncListener(Nxt.User user) { this.user = user; } public void onComplete(AsyncEvent asyncEvent) throws IOException {} public void onError(AsyncEvent asyncEvent) throws IOException { synchronized (this.user) { this.user.asyncContext.getResponse().setContentType("text/plain; charset=UTF-8"); Writer writer = this.user.asyncContext.getResponse().getWriter();Throwable localThrowable2 = null; try { new JSONObject().writeJSONString(writer); } catch (Throwable localThrowable1) { localThrowable2 = localThrowable1;throw localThrowable1; } finally { if (writer != null) { if (localThrowable2 != null) { try { writer.close(); } catch (Throwable x2) { localThrowable2.addSuppressed(x2); } } else { writer.close(); } } } this.user.asyncContext.complete(); this.user.asyncContext = null; } } public void onStartAsync(AsyncEvent asyncEvent) throws IOException {} public void onTimeout(AsyncEvent asyncEvent) throws IOException { synchronized (this.user) { this.user.asyncContext.getResponse().setContentType("text/plain; charset=UTF-8"); Writer writer = this.user.asyncContext.getResponse().getWriter();Throwable localThrowable2 = null; try { new JSONObject().writeJSONString(writer); } catch (Throwable localThrowable1) { localThrowable2 = localThrowable1;throw localThrowable1; } finally { if (writer != null) { if (localThrowable2 != null) { try { writer.close(); } catch (Throwable x2) { localThrowable2.addSuppressed(x2); } } else { writer.close(); } } } this.user.asyncContext.complete(); this.user.asyncContext = null; } } } public void init(ServletConfig servletConfig) throws ServletException { logMessage("NRS 0.5.10 starting..."); if (debug) { logMessage("DEBUG logging enabled"); } if (enableStackTraces) { logMessage("logging of exception stack traces enabled"); } try { Calendar calendar = Calendar.getInstance(); calendar.set(15, 0); calendar.set(1, 2013); calendar.set(2, 10); calendar.set(5, 24); calendar.set(11, 12); calendar.set(12, 0); calendar.set(13, 0); calendar.set(14, 0); epochBeginning = calendar.getTimeInMillis(); myPlatform = servletConfig.getInitParameter("myPlatform"); logMessage("\"myPlatform\" = \"" + myPlatform + "\""); if (myPlatform == null) { myPlatform = "PC"; } else { myPlatform = myPlatform.trim(); } myScheme = servletConfig.getInitParameter("myScheme"); logMessage("\"myScheme\" = \"" + myScheme + "\""); if (myScheme == null) { myScheme = "http"; } else { myScheme = myScheme.trim(); } String myPort = servletConfig.getInitParameter("myPort"); logMessage("\"myPort\" = \"" + myPort + "\""); try { myPort = Integer.parseInt(myPort); } catch (NumberFormatException e) { myPort = myScheme.equals("https") ? 7875 : 7874; logMessage("Invalid value for myPort " + myPort + ", using default " + myPort); } myAddress = servletConfig.getInitParameter("myAddress"); logMessage("\"myAddress\" = \"" + myAddress + "\""); if (myAddress != null) { myAddress = myAddress.trim(); } String shareMyAddress = servletConfig.getInitParameter("shareMyAddress"); logMessage("\"shareMyAddress\" = \"" + shareMyAddress + "\""); shareMyAddress = Boolean.parseBoolean(shareMyAddress); myHallmark = servletConfig.getInitParameter("myHallmark"); logMessage("\"myHallmark\" = \"" + myHallmark + "\""); if (myHallmark != null) { myHallmark = myHallmark.trim(); try { convert(myHallmark); } catch (NumberFormatException e) { logMessage("Your hallmark is invalid: " + myHallmark); System.exit(1); } } String wellKnownPeers = servletConfig.getInitParameter("wellKnownPeers"); logMessage("\"wellKnownPeers\" = \"" + wellKnownPeers + "\""); if (wellKnownPeers != null) { Set<String> set = new HashSet(); for (String wellKnownPeer : wellKnownPeers.split(";")) { wellKnownPeer = wellKnownPeer.trim(); if (wellKnownPeer.length() > 0) { set.add(wellKnownPeer); Nxt.Peer.addPeer(wellKnownPeer, wellKnownPeer); } } wellKnownPeers = Collections.unmodifiableSet(set); } else { wellKnownPeers = Collections.emptySet(); logMessage("No wellKnownPeers defined, it is unlikely to work"); } String maxNumberOfConnectedPublicPeers = servletConfig.getInitParameter("maxNumberOfConnectedPublicPeers"); logMessage("\"maxNumberOfConnectedPublicPeers\" = \"" + maxNumberOfConnectedPublicPeers + "\""); try { maxNumberOfConnectedPublicPeers = Integer.parseInt(maxNumberOfConnectedPublicPeers); } catch (NumberFormatException e) { maxNumberOfConnectedPublicPeers = 10; logMessage("Invalid value for maxNumberOfConnectedPublicPeers " + maxNumberOfConnectedPublicPeers + ", using default " + maxNumberOfConnectedPublicPeers); } String connectTimeout = servletConfig.getInitParameter("connectTimeout"); logMessage("\"connectTimeout\" = \"" + connectTimeout + "\""); try { connectTimeout = Integer.parseInt(connectTimeout); } catch (NumberFormatException e) { connectTimeout = 1000; logMessage("Invalid value for connectTimeout " + connectTimeout + ", using default " + connectTimeout); } String readTimeout = servletConfig.getInitParameter("readTimeout"); logMessage("\"readTimeout\" = \"" + readTimeout + "\""); try { readTimeout = Integer.parseInt(readTimeout); } catch (NumberFormatException e) { readTimeout = 1000; logMessage("Invalid value for readTimeout " + readTimeout + ", using default " + readTimeout); } String enableHallmarkProtection = servletConfig.getInitParameter("enableHallmarkProtection"); logMessage("\"enableHallmarkProtection\" = \"" + enableHallmarkProtection + "\""); enableHallmarkProtection = Boolean.parseBoolean(enableHallmarkProtection); String pushThreshold = servletConfig.getInitParameter("pushThreshold"); logMessage("\"pushThreshold\" = \"" + pushThreshold + "\""); try { pushThreshold = Integer.parseInt(pushThreshold); } catch (NumberFormatException e) { pushThreshold = 0; logMessage("Invalid value for pushThreshold " + pushThreshold + ", using default " + pushThreshold); } String pullThreshold = servletConfig.getInitParameter("pullThreshold"); logMessage("\"pullThreshold\" = \"" + pullThreshold + "\""); try { pullThreshold = Integer.parseInt(pullThreshold); } catch (NumberFormatException e) { pullThreshold = 0; logMessage("Invalid value for pullThreshold " + pullThreshold + ", using default " + pullThreshold); } String allowedUserHosts = servletConfig.getInitParameter("allowedUserHosts"); logMessage("\"allowedUserHosts\" = \"" + allowedUserHosts + "\""); if (allowedUserHosts != null) { if (!allowedUserHosts.trim().equals("*")) { Set<String> set = new HashSet(); for (String allowedUserHost : allowedUserHosts.split(";")) { allowedUserHost = allowedUserHost.trim(); if (allowedUserHost.length() > 0) { set.add(allowedUserHost); } } allowedUserHosts = Collections.unmodifiableSet(set); } } String allowedBotHosts = servletConfig.getInitParameter("allowedBotHosts"); logMessage("\"allowedBotHosts\" = \"" + allowedBotHosts + "\""); if (allowedBotHosts != null) { if (!allowedBotHosts.trim().equals("*")) { Set<String> set = new HashSet(); for (String allowedBotHost : allowedBotHosts.split(";")) { allowedBotHost = allowedBotHost.trim(); if (allowedBotHost.length() > 0) { set.add(allowedBotHost); } } allowedBotHosts = Collections.unmodifiableSet(set); } } String blacklistingPeriod = servletConfig.getInitParameter("blacklistingPeriod"); logMessage("\"blacklistingPeriod\" = \"" + blacklistingPeriod + "\""); try { blacklistingPeriod = Integer.parseInt(blacklistingPeriod); } catch (NumberFormatException e) { blacklistingPeriod = 300000; logMessage("Invalid value for blacklistingPeriod " + blacklistingPeriod + ", using default " + blacklistingPeriod); } String communicationLoggingMask = servletConfig.getInitParameter("communicationLoggingMask"); logMessage("\"communicationLoggingMask\" = \"" + communicationLoggingMask + "\""); try { communicationLoggingMask = Integer.parseInt(communicationLoggingMask); } catch (NumberFormatException e) { logMessage("Invalid value for communicationLogginMask " + communicationLoggingMask + ", using default 0"); } String sendToPeersLimit = servletConfig.getInitParameter("sendToPeersLimit"); logMessage("\"sendToPeersLimit\" = \"" + sendToPeersLimit + "\""); try { sendToPeersLimit = Integer.parseInt(sendToPeersLimit); } catch (NumberFormatException e) { sendToPeersLimit = 10; logMessage("Invalid value for sendToPeersLimit " + sendToPeersLimit + ", using default " + sendToPeersLimit); } try { logMessage("Loading transactions..."); Nxt.Transaction.loadTransactions("transactions.nxt"); logMessage("...Done"); } catch (FileNotFoundException e) { logMessage("transactions.nxt not found, starting from scratch"); transactions.clear(); long[] recipients = { new BigInteger("163918645372308887").longValue(), new BigInteger("620741658595224146").longValue(), new BigInteger("723492359641172834").longValue(), new BigInteger("818877006463198736").longValue(), new BigInteger("1264744488939798088").longValue(), new BigInteger("1600633904360147460").longValue(), new BigInteger("1796652256451468602").longValue(), new BigInteger("1814189588814307776").longValue(), new BigInteger("1965151371996418680").longValue(), new BigInteger("2175830371415049383").longValue(), new BigInteger("2401730748874927467").longValue(), new BigInteger("2584657662098653454").longValue(), new BigInteger("2694765945307858403").longValue(), new BigInteger("3143507805486077020").longValue(), new BigInteger("3684449848581573439").longValue(), new BigInteger("4071545868996394636").longValue(), new BigInteger("4277298711855908797").longValue(), new BigInteger("4454381633636789149").longValue(), new BigInteger("4747512364439223888").longValue(), new BigInteger("4777958973882919649").longValue(), new BigInteger("4803826772380379922").longValue(), new BigInteger("5095742298090230979").longValue(), new BigInteger("5271441507933314159").longValue(), new BigInteger("5430757907205901788").longValue(), new BigInteger("5491587494620055787").longValue(), new BigInteger("5622658764175897611").longValue(), new BigInteger("5982846390354787993").longValue(), new BigInteger("6290807999797358345").longValue(), new BigInteger("6785084810899231190").longValue(), new BigInteger("6878906112724074600").longValue(), new BigInteger("7017504655955743955").longValue(), new BigInteger("7085298282228890923").longValue(), new BigInteger("7446331133773682477").longValue(), new BigInteger("7542917420413518667").longValue(), new BigInteger("7549995577397145669").longValue(), new BigInteger("7577840883495855927").longValue(), new BigInteger("7579216551136708118").longValue(), new BigInteger("8278234497743900807").longValue(), new BigInteger("8517842408878875334").longValue(), new BigInteger("8870453786186409991").longValue(), new BigInteger("9037328626462718729").longValue(), new BigInteger("9161949457233564608").longValue(), new BigInteger("9230759115816986914").longValue(), new BigInteger("9306550122583806885").longValue(), new BigInteger("9433259657262176905").longValue(), new BigInteger("9988839211066715803").longValue(), new BigInteger("10105875265190846103").longValue(), new BigInteger("10339765764359265796").longValue(), new BigInteger("10738613957974090819").longValue(), new BigInteger("10890046632913063215").longValue(), new BigInteger("11494237785755831723").longValue(), new BigInteger("11541844302056663007").longValue(), new BigInteger("11706312660844961581").longValue(), new BigInteger("12101431510634235443").longValue(), new BigInteger("12186190861869148835").longValue(), new BigInteger("12558748907112364526").longValue(), new BigInteger("13138516747685979557").longValue(), new BigInteger("13330279748251018740").longValue(), new BigInteger("14274119416917666908").longValue(), new BigInteger("14557384677985343260").longValue(), new BigInteger("14748294830376619968").longValue(), new BigInteger("14839596582718854826").longValue(), new BigInteger("15190676494543480574").longValue(), new BigInteger("15253761794338766759").longValue(), new BigInteger("15558257163011348529").longValue(), new BigInteger("15874940801139996458").longValue(), new BigInteger("16516270647696160902").longValue(), new BigInteger("17156841960446798306").longValue(), new BigInteger("17228894143802851995").longValue(), new BigInteger("17240396975291969151").longValue(), new BigInteger("17491178046969559641").longValue(), new BigInteger("18345202375028346230").longValue(), new BigInteger("18388669820699395594").longValue() }; int[] amounts = { 36742, 1970092, 349130, 24880020, 2867856, 9975150, 2690963, 7648, 5486333, 34913026, 997515, 30922966, 6650, 44888, 2468850, 49875751, 49875751, 9476393, 49875751, 14887912, 528683, 583546, 7315, 19925363, 29856290, 5320, 4987575, 5985, 24912938, 49875751, 2724712, 1482474, 200999, 1476156, 498758, 987540, 16625250, 5264386, 15487585, 2684479, 14962725, 34913026, 5033128, 2916900, 49875751, 4962637, 170486123, 8644631, 22166945, 6668388, 233751, 4987575, 11083556, 1845403, 49876, 3491, 3491, 9476, 49876, 6151, 682633, 49875751, 482964, 4988, 49875751, 4988, 9144, 503745, 49875751, 52370, 29437998, 585375, 9975150 }; byte[][] signatures = { { 41, 115, -41, 7, 37, 21, -3, -41, 120, 119, 63, -101, 108, 48, -117, 1, -43, 32, 85, 95, 65, 42, 92, -22, 123, -36, 6, -99, -61, -53, 93, 7, 23, 8, -30, 65, 57, -127, -2, 42, -92, -104, 11, 72, -66, 108, 17, 113, 99, -117, -75, 123, 110, 107, 119, -25, 67, 64, 32, 117, 111, 54, 82, -14 }, { 118, 43, 84, -91, -110, -102, 100, -40, -33, -47, -13, -7, -88, 2, -42, -66, -38, -22, 105, -42, -69, 78, 51, -55, -48, 49, -89, 116, -96, -104, -114, 14, 94, 58, -115, -8, 111, -44, 76, -104, 54, -15, 126, 31, 6, -80, 65, 6, 124, 37, -73, 92, 4, 122, 122, -108, 1, -54, 31, -38, -117, -1, -52, -56 }, { 79, 100, -101, 107, -6, -61, 40, 32, -98, 32, 80, -59, -76, -23, -62, 38, 4, 105, -106, -105, -121, -85, 13, -98, -77, 126, -125, 103, 12, -41, 1, 2, 45, -62, -69, 102, 116, -61, 101, -14, -68, -31, 9, 110, 18, 2, 33, -98, -37, -128, 17, -19, 124, 125, -63, 92, -70, 96, 96, 125, 91, 8, -65, -12 }, { 58, -99, 14, -97, -75, -10, 110, -102, 119, -3, -2, -12, -82, -33, -27, 118, -19, 55, -109, 6, 110, -10, 108, 30, 94, -113, -5, -98, 19, 12, -125, 14, -77, 33, -128, -21, 36, -120, -12, -81, 64, 95, 67, -3, 100, 122, -47, 127, -92, 114, 68, 72, 2, -40, 80, 117, -17, -56, 103, 37, -119, 3, 22, 23 }, { 76, 22, 121, -4, -77, -127, 18, -102, 7, 94, -73, -96, 108, -11, 81, -18, -37, -85, -75, 86, -119, 94, 126, 95, 47, -36, -16, -50, -9, 95, 60, 15, 14, 93, -108, -83, -67, 29, 2, -53, 10, -118, -51, -46, 92, -23, -56, 60, 46, -90, -84, 126, 60, 78, 12, 53, 61, 121, -6, 77, 112, 60, 40, 63 }, { 64, 121, -73, 68, 4, -103, 81, 55, -41, -81, -63, 10, 117, -74, 54, -13, -85, 79, 21, 116, -25, -12, 21, 120, -36, -80, 53, -78, 103, 25, 55, 6, -75, 96, 80, -125, -11, -103, -20, -41, 121, -61, -40, 63, 24, -81, -125, 90, -12, -40, -52, -1, -114, 14, -44, -112, -80, 83, -63, 88, -107, -10, -114, -86 }, { -81, 126, -41, -34, 66, -114, -114, 114, 39, 32, -125, -19, -95, -50, -111, -51, -33, 51, 99, -127, 58, 50, -110, 44, 80, -94, -96, 68, -69, 34, 86, 3, -82, -69, 28, 20, -111, 69, 18, -41, -23, 27, -118, 20, 72, 21, -112, 53, -87, -81, -47, -101, 123, -80, 99, -15, 33, -120, -8, 82, 80, -8, -10, -45 }, { 92, 77, 53, -87, 26, 13, -121, -39, -62, -42, 47, 4, 7, 108, -15, 112, 103, 38, -50, -74, 60, 56, -63, 43, -116, 49, -106, 69, 118, 65, 17, 12, 31, 127, -94, 55, -117, -29, -117, 31, -95, -110, -2, 63, -73, -106, -88, -41, -19, 69, 60, -17, -16, 61, 32, -23, 88, -106, -96, 37, -96, 114, -19, -99 }, { 68, -26, 57, -56, -30, 108, 61, 24, 106, -56, -92, 99, -59, 107, 25, -110, -57, 80, 79, -92, -107, 90, 54, -73, -40, -39, 78, 109, -57, -62, -17, 6, -25, -29, 37, 90, -24, -27, -61, -69, 44, 121, 107, -72, -57, 108, 32, -69, -21, -41, 126, 91, 118, 11, -91, 50, -11, 116, 126, -96, -39, 110, 105, -52 }, { 48, 108, 123, 50, -50, -58, 33, 14, 59, 102, 17, -18, -119, 4, 10, -29, 36, -56, -31, 43, -71, -48, -14, 87, 119, -119, 40, 104, -44, -76, -24, 2, 48, -96, -7, 16, -119, -3, 108, 78, 125, 88, 61, -53, -3, -16, 20, -83, 74, 124, -47, -17, -15, -21, -23, -119, -47, 105, -4, 115, -20, 77, 57, 88 }, { 33, 101, 79, -35, 32, -119, 20, 120, 34, -80, -41, 90, -22, 93, -20, -45, 9, 24, -46, 80, -55, -9, -24, -78, -124, 27, -120, -36, -51, 59, -38, 7, 113, 125, 68, 109, 24, -121, 111, 37, -71, 100, -111, 78, -43, -14, -76, -44, 64, 103, 16, -28, -44, -103, 74, 81, -118, -74, 47, -77, -65, 8, 42, -100 }, { -63, -96, -95, -111, -85, -98, -85, 42, 87, 29, -62, -57, 57, 48, 9, -39, -110, 63, -103, -114, -48, -11, -92, 105, -26, -79, -11, 78, -118, 14, -39, 1, -115, 74, 70, -41, -119, -68, -39, -60, 64, 31, 25, -111, -16, -20, 61, -22, 17, -13, 57, -110, 24, 61, -104, 21, -72, -69, 56, 116, -117, 93, -1, -123 }, { -18, -70, 12, 112, -111, 10, 22, 31, -120, 26, 53, 14, 10, 69, 51, 45, -50, -127, -22, 95, 54, 17, -8, 54, -115, 36, -79, 12, -79, 82, 4, 1, 92, 59, 23, -13, -85, -87, -110, -58, 84, -31, -48, -105, -101, -92, -9, 28, -109, 77, -47, 100, -48, -83, 106, -102, 70, -95, 94, -1, -99, -15, 21, 99 }, { 109, 123, 54, 40, -120, 32, -118, 49, -52, 0, -103, 103, 101, -9, 32, 78, 124, -56, 88, -19, 101, -32, 70, 67, -41, 85, -103, 1, 1, -105, -51, 10, 4, 51, -26, -19, 39, -43, 63, -41, -101, 80, 106, -66, 125, 47, -117, -120, -93, -120, 99, -113, -17, 61, 102, -2, 72, 9, -124, 123, -128, 78, 43, 96 }, { -22, -63, 20, 65, 5, -89, -123, -61, 14, 34, 83, -113, 34, 85, 26, -21, 1, 16, 88, 55, -92, -111, 14, -31, -37, -67, -8, 85, 39, -112, -33, 8, 28, 16, 107, -29, 1, 3, 100, -53, 2, 81, 52, -94, -14, 36, -123, -82, -6, -118, 104, 75, -99, -82, -100, 7, 30, -66, 0, -59, 108, -54, 31, 20 }, { 0, 13, -74, 28, -54, -12, 45, 36, -24, 55, 43, -110, -72, 117, -110, -56, -72, 85, 79, -89, -92, 65, -67, -34, -24, 38, 67, 42, 84, -94, 91, 13, 100, 89, 20, -95, -76, 2, 116, 34, 67, 52, -80, -101, -22, -32, 51, 32, -76, 44, -93, 11, 42, -69, -12, 7, -52, -55, 122, -10, 48, 21, 92, 110 }, { -115, 19, 115, 28, -56, 118, 111, 26, 18, 123, 111, -96, -115, 120, 105, 62, -123, -124, 101, 51, 3, 18, -89, 127, 48, -27, 39, -78, -118, 5, -2, 6, -105, 17, 123, 26, 25, -62, -37, 49, 117, 3, 10, 97, -7, 54, 121, -90, -51, -49, 11, 104, -66, 11, -6, 57, 5, -64, -8, 59, 82, -126, 26, -113 }, { 16, -53, 94, 99, -46, -29, 64, -89, -59, 116, -21, 53, 14, -77, -71, 95, 22, -121, -51, 125, -14, -96, 95, 95, 32, 96, 79, 41, -39, -128, 79, 0, 5, 6, -115, 104, 103, 77, -92, 93, -109, 58, 96, 97, -22, 116, -62, 11, 30, -122, 14, 28, 69, 124, 63, -119, 19, 80, -36, -116, -76, -58, 36, 87 }, { 109, -82, 33, -119, 17, 109, -109, -16, 98, 108, 111, 5, 98, 1, -15, -32, 22, 46, -65, 117, -78, 119, 35, -35, -3, 41, 23, -97, 55, 69, 58, 9, 20, -113, -121, -13, -41, -48, 22, -73, -1, -44, -73, 3, -10, -122, 19, -103, 10, -26, -128, 62, 34, 55, 54, -43, 35, -30, 115, 64, -80, -20, -25, 67 }, { -16, -74, -116, -128, 52, 96, -75, 17, -22, 72, -43, 22, -95, -16, 32, -72, 98, 46, -4, 83, 34, -58, -108, 18, 17, -58, -123, 53, -108, 116, 18, 2, 7, -94, -126, -45, 72, -69, -65, -89, 64, 31, -78, 78, -115, 106, 67, 55, -123, 104, -128, 36, -23, -90, -14, -87, 78, 19, 18, -128, 39, 73, 35, 120 }, { 20, -30, 15, 111, -82, 39, -108, 57, -80, 98, -19, -27, 100, -18, 47, 77, -41, 95, 80, -113, -128, -88, -76, 115, 65, -53, 83, 115, 7, 2, -104, 3, 120, 115, 14, -116, 33, -15, -120, 22, -56, -8, -69, 5, -75, 94, 124, 12, -126, -48, 51, -105, 22, -66, -93, 16, -63, -74, 32, 114, -54, -3, -47, -126 }, { 56, -101, 55, -1, 64, 4, -64, 95, 31, -15, 72, 46, 67, -9, 68, -43, -55, 28, -63, -17, -16, 65, 11, -91, -91, 32, 88, 41, 60, 67, 105, 8, 58, 102, -79, -5, -113, -113, -67, 82, 50, -26, 116, -78, -103, 107, 102, 23, -74, -47, 115, -50, -35, 63, -80, -32, 72, 117, 47, 68, 86, -20, -35, 8 }, { 21, 27, 20, -59, 117, -102, -42, 22, -10, 121, 41, -59, 115, 15, -43, 54, -79, -62, -16, 58, 116, 15, 88, 108, 114, 67, 3, -30, -99, 78, 103, 11, 49, 63, -4, -110, -27, 41, 70, -57, -69, -18, 70, 30, -21, 66, -104, -27, 3, 53, 50, 100, -33, 54, -3, -78, 92, 85, -78, 54, 19, 32, 95, 9 }, { -93, 65, -64, -79, 82, 85, -34, -90, 122, -29, -40, 3, -80, -40, 32, 26, 102, -73, 17, 53, -93, -29, 122, 86, 107, -100, 50, 56, -28, 124, 90, 14, 93, -88, 97, 101, -85, -50, 46, -109, -88, -127, -112, 63, -89, 24, -34, -9, -116, -59, -87, -86, -12, 111, -111, 87, -87, -13, -73, -124, -47, 7, 1, 9 }, { 60, -99, -77, -20, 112, -75, -34, 100, -4, -96, 81, 71, -116, -62, 38, -68, 105, 7, -126, 21, -125, -25, -56, -11, -59, 95, 117, 108, 32, -38, -65, 13, 46, 65, -46, -89, 0, 120, 5, 23, 40, 110, 114, 79, 111, -70, 8, 16, -49, -52, -82, -18, 108, -43, 81, 96, 72, -65, 70, 7, -37, 58, 46, -14 }, { -95, -32, 85, 78, 74, -53, 93, -102, -26, -110, 86, 1, -93, -50, -23, -108, -37, 97, 19, 103, 94, -65, -127, -21, 60, 98, -51, -118, 82, -31, 27, 7, -112, -45, 79, 95, -20, 90, -4, -40, 117, 100, -6, 19, -47, 53, 53, 48, 105, 91, -70, -34, -5, -87, -57, -103, -112, -108, -40, 87, -25, 13, -76, -116 }, { 44, -122, -70, 125, -60, -32, 38, 69, -77, -103, 49, -124, -4, 75, -41, -84, 68, 74, 118, 15, -13, 115, 117, -78, 42, 89, 0, -20, -12, -58, -97, 10, -48, 95, 81, 101, 23, -67, -23, 74, -79, 21, 97, 123, 103, 101, -50, -115, 116, 112, 51, 50, -124, 27, 76, 40, 74, 10, 65, -49, 102, 95, 5, 35 }, { -6, 57, 71, 5, -61, -100, -21, -9, 47, -60, 59, 108, -75, 105, 56, 41, -119, 31, 37, 27, -86, 120, -125, -108, 121, 104, -21, -70, -57, -104, 2, 11, 118, 104, 68, 6, 7, -90, -70, -61, -16, 77, -8, 88, 31, -26, 35, -44, 8, 50, 51, -88, -62, -103, 54, -41, -2, 117, 98, -34, 49, -123, 83, -58 }, { 54, 21, -36, 126, -50, -72, 82, -5, -122, -116, 72, -19, -18, -68, -71, -27, 97, -22, 53, -94, 47, -6, 15, -92, -55, 127, 13, 13, -69, 81, -82, 8, -50, 10, 84, 110, -87, -44, 61, -78, -65, 84, -32, 48, -8, -105, 35, 116, -68, -116, -6, 75, -77, 120, -95, 74, 73, 105, 39, -87, 98, -53, 47, 10 }, { -113, 116, 37, -1, 95, -89, -93, 113, 36, -70, -57, -99, 94, 52, -81, -118, 98, 58, -36, 73, 82, -67, -80, 46, 83, -127, -8, 73, 66, -27, 43, 7, 108, 32, 73, 1, -56, -108, 41, -98, -15, 49, 1, 107, 65, 44, -68, 126, -28, -53, 120, -114, 126, -79, -14, -105, -33, 53, 5, -119, 67, 52, 35, -29 }, { 98, 23, 23, 83, 78, -89, 13, 55, -83, 97, -30, -67, 99, 24, 47, -4, -117, -34, -79, -97, 95, 74, 4, 21, 66, -26, 15, 80, 60, -25, -118, 14, 36, -55, -41, -124, 90, -1, 84, 52, 31, 88, 83, 121, -47, -59, -10, 17, 51, -83, 23, 108, 19, 104, 32, 29, -66, 24, 21, 110, 104, -71, -23, -103 }, { 12, -23, 60, 35, 6, -52, -67, 96, 15, -128, -47, -15, 40, 3, 54, -81, 3, 94, 3, -98, -94, -13, -74, -101, 40, -92, 90, -64, -98, 68, -25, 2, -62, -43, 112, 32, -78, -123, 26, -80, 126, 120, -88, -92, 126, -128, 73, -43, 87, -119, 81, 111, 95, -56, -128, -14, 51, -40, -42, 102, 46, 106, 6, 6 }, { -38, -120, -11, -114, -7, -105, -98, 74, 114, 49, 64, -100, 4, 40, 110, -21, 25, 6, -92, -40, -61, 48, 94, -116, -71, -87, 75, -31, 13, -119, 1, 5, 33, -69, -16, -125, -79, -46, -36, 3, 40, 1, -88, -118, -107, 95, -23, -107, -49, 44, -39, 2, 108, -23, 39, 50, -51, -59, -4, -42, -10, 60, 10, -103 }, { 67, -53, 55, -32, -117, 3, 94, 52, -115, -127, -109, 116, -121, -27, -115, -23, 98, 90, -2, 48, -54, -76, 108, -56, 99, 30, -35, -18, -59, 25, -122, 3, 43, -13, -109, 34, -10, 123, 117, 113, -112, -85, -119, -62, -78, -114, -96, 101, 72, -98, 28, 89, -98, -121, 20, 115, 89, -20, 94, -55, 124, 27, -76, 94 }, { 15, -101, 98, -21, 8, 5, -114, -64, 74, 123, 99, 28, 125, -33, 22, 23, -2, -56, 13, 91, 27, -105, -113, 19, 60, -7, -67, 107, 70, 103, -107, 13, -38, -108, -77, -29, 2, 9, -12, 21, 12, 65, 108, -16, 69, 77, 96, -54, 55, -78, -7, 41, -48, 124, -12, 64, 113, -45, -21, -119, -113, 88, -116, 113 }, { -17, 77, 10, 84, -57, -12, 101, 21, -91, 92, 17, -32, -26, 77, 70, 46, 81, -55, 40, 44, 118, -35, -97, 47, 5, 125, 41, -127, -72, 66, -18, 2, 115, -13, -74, 126, 86, 80, 11, -122, -29, -68, 113, 54, -117, 107, -75, -107, -54, 72, -44, 98, -111, -33, -56, -40, 93, -47, 84, -43, -45, 86, 65, -84 }, { -126, 60, -56, 121, 31, -124, -109, 100, -118, -29, 106, 94, 5, 27, 13, -79, 91, -111, -38, -42, 18, 61, -100, 118, -18, -4, -60, 121, 46, -22, 6, 4, -37, -20, 124, -43, 51, -57, -49, -44, -24, -38, 81, 60, -14, -97, -109, -11, -5, -85, 75, -17, -124, -96, -53, 52, 64, 100, -118, -120, 6, 60, 76, -110 }, { -12, -40, 115, -41, 68, 85, 20, 91, -44, -5, 73, -105, -81, 32, 116, 32, -28, 69, 88, -54, 29, -53, -51, -83, 54, 93, -102, -102, -23, 7, 110, 15, 34, 122, 84, 52, -121, 37, -103, -91, 37, -77, -101, 64, -18, 63, -27, -75, -112, -11, 1, -69, -25, -123, -99, -31, 116, 11, 4, -42, -124, 98, -2, 53 }, { -128, -69, -16, -33, -8, -112, 39, -57, 113, -76, -29, -37, 4, 121, -63, 12, -54, -66, -121, 13, -4, -44, 50, 27, 103, 101, 44, -115, 12, -4, -8, 10, 53, 108, 90, -47, 46, -113, 5, -3, -111, 8, -66, -73, 57, 72, 90, -33, 47, 99, 50, -55, 53, -4, 96, 87, 57, 26, 53, -45, -83, 39, -17, 45 }, { -121, 125, 60, -9, -79, -128, -19, 113, 54, 77, -23, -89, 105, -5, 47, 114, -120, -88, 31, 25, -96, -75, -6, 76, 9, -83, 75, -109, -126, -47, -6, 2, -59, 64, 3, 74, 100, 110, -96, 66, -3, 10, -124, -6, 8, 50, 109, 14, -109, 79, 73, 77, 67, 63, -50, 10, 86, -63, -125, -86, 35, -26, 7, 83 }, { 36, 31, -77, 126, 106, 97, 63, 81, -37, -126, 69, -127, -22, -69, 104, -111, 93, -49, 77, -3, -38, -112, 47, -55, -23, -68, -8, 78, -127, -28, -59, 10, 22, -61, -127, -13, -72, -14, -87, 14, 61, 76, -89, 81, -97, -97, -105, 94, -93, -9, -3, -104, -83, 59, 104, 121, -30, 106, -2, 62, -51, -72, -63, 55 }, { 81, -88, -8, -96, -31, 118, -23, -38, -94, 80, 35, -20, -93, -102, 124, 93, 0, 15, 36, -127, -41, -19, 6, -124, 94, -49, 44, 26, -69, 43, -58, 9, -18, -3, -2, 60, -122, -30, -47, 124, 71, 47, -74, -68, 4, -101, -16, 77, -120, -15, 45, -12, 68, -77, -74, 63, -113, 44, -71, 56, 122, -59, 53, -44 }, { 122, 30, 27, -79, 32, 115, -104, -28, -53, 109, 120, 121, -115, -65, -87, 101, 23, 10, 122, 101, 29, 32, 56, 63, -23, -48, -51, 51, 16, -124, -41, 6, -71, 49, -20, 26, -57, 65, 49, 45, 7, 49, -126, 54, -122, -43, 1, -5, 111, 117, 104, 117, 126, 114, -77, 66, -127, -50, 69, 14, 70, 73, 60, 112 }, { 104, -117, 105, -118, 35, 16, -16, 105, 27, -87, -43, -59, -13, -23, 5, 8, -112, -28, 18, -1, 48, 94, -82, 55, 32, 16, 59, -117, 108, -89, 101, 9, -35, 58, 70, 62, 65, 91, 14, -43, -104, 97, 1, -72, 16, -24, 79, 79, -85, -51, -79, -55, -128, 23, 109, -95, 17, 92, -38, 109, 65, -50, 46, -114 }, { 44, -3, 102, -60, -85, 66, 121, -119, 9, 82, -47, -117, 67, -28, 108, 57, -47, -52, -24, -82, 65, -13, 85, 107, -21, 16, -24, -85, 102, -92, 73, 5, 7, 21, 41, 47, -118, 72, 43, 51, -5, -64, 100, -34, -25, 53, -45, -115, 30, -72, -114, 126, 66, 60, -24, -67, 44, 48, 22, 117, -10, -33, -89, -108 }, { -7, 71, -93, -66, 3, 30, -124, -116, -48, -76, -7, -62, 125, -122, -60, -104, -30, 71, 36, -110, 34, -126, 31, 10, 108, 102, -53, 56, 104, -56, -48, 12, 25, 21, 19, -90, 45, -122, -73, -112, 97, 96, 115, 71, 127, -7, -46, 84, -24, 102, -104, -96, 28, 8, 37, -84, -13, -65, -6, 61, -85, -117, -30, 70 }, { -112, 39, -39, -24, 127, -115, 68, -1, -111, -43, 101, 20, -12, 39, -70, 67, -50, 68, 105, 69, -91, -106, 91, 4, -52, 75, 64, -121, 46, -117, 31, 10, -125, 77, 51, -3, -93, 58, 79, 121, 126, -29, 56, -101, 1, -28, 49, 16, -80, 92, -62, 83, 33, 17, 106, 89, -9, 60, 79, 38, -74, -48, 119, 24 }, { 105, -118, 34, 52, 111, 30, 38, -73, 125, -116, 90, 69, 2, 126, -34, -25, -41, -67, -23, -105, -12, -75, 10, 69, -51, -95, -101, 92, -80, -73, -120, 2, 71, 46, 11, -85, -18, 125, 81, 117, 33, -89, -42, 118, 51, 60, 89, 110, 97, -118, -111, -36, 75, 112, -4, -8, -36, -49, -55, 35, 92, 70, -37, 36 }, { 71, 4, -113, 13, -48, 29, -56, 82, 115, -38, -20, -79, -8, 126, -111, 5, -12, -56, -107, 98, 111, 19, 127, -10, -42, 24, -38, -123, 59, 51, -64, 3, 47, -1, -83, -127, -58, 86, 33, -76, 5, 71, -80, -50, -62, 116, 75, 20, -126, 23, -31, -21, 24, -83, -19, 114, -17, 1, 110, -70, -119, 126, 82, -83 }, { -77, -69, -45, -78, -78, 69, 35, 85, 84, 25, -66, -25, 53, -38, -2, 125, -38, 103, 88, 31, -9, -43, 15, -93, 69, -22, -13, -20, 73, 3, -100, 7, 26, -18, 123, -14, -78, 113, 79, -57, -109, -118, 105, -104, 75, -88, -24, -109, 73, -126, 9, 55, 98, -120, 93, 114, 74, 0, -86, -68, 47, 29, 75, 67 }, { -104, 11, -85, 16, -124, -91, 66, -91, 18, -67, -122, -57, -114, 88, 79, 11, -60, -119, 89, 64, 57, 120, -11, 8, 52, -18, -67, -127, 26, -19, -69, 2, -82, -56, 11, -90, -104, 110, -10, -68, 87, 21, 28, 87, -5, -74, -21, -84, 120, 70, -17, 102, 72, -116, -69, 108, -86, -79, -74, 115, -78, -67, 6, 45 }, { -6, -101, -17, 38, -25, -7, -93, 112, 13, -33, 121, 71, -79, -122, -95, 22, 47, -51, 16, 84, 55, -39, -26, 37, -36, -18, 11, 119, 106, -57, 42, 8, -1, 23, 7, -63, -9, -50, 30, 35, -125, 83, 9, -60, -94, -15, -76, 120, 18, -103, -70, 95, 26, 48, -103, -95, 10, 113, 66, 54, -96, -4, 37, 111 }, { -124, -53, 43, -59, -73, 99, 71, -36, -31, 61, -25, -14, -71, 48, 17, 10, -26, -21, -22, 104, 64, -128, 27, -40, 111, -70, -90, 91, -81, -88, -10, 11, -62, 127, -124, -2, -67, -69, 65, 73, 40, 82, 112, -112, 100, -26, 30, 86, 30, 1, -105, 45, 103, -47, -124, 58, 105, 24, 20, 108, -101, 84, -34, 80 }, { 28, -1, 84, 111, 43, 109, 57, -23, 52, -95, 110, -50, 77, 15, 80, 85, 125, -117, -10, 8, 59, -58, 18, 97, -58, 45, 92, -3, 56, 24, -117, 9, -73, -9, 48, -99, 50, -24, -3, -41, -43, 48, -77, -8, -89, -42, 126, 73, 28, -65, -108, 54, 6, 34, 32, 2, -73, -123, -106, -52, -73, -106, -112, 109 }, { 73, -76, -7, 49, 67, -34, 124, 80, 111, -91, -22, -121, -74, 42, -4, -18, 84, -3, 38, 126, 31, 54, -120, 65, -122, -14, -38, -80, -124, 90, 37, 1, 51, 123, 69, 48, 109, -112, -63, 27, 67, -127, 29, 79, -26, 99, -24, -100, 51, 103, -105, 13, 85, 74, 12, -37, 43, 80, -113, 6, 70, -107, -5, -80 }, { 110, -54, 109, 21, -124, 98, 90, -26, 69, -44, 17, 117, 78, -91, -7, -18, -81, -43, 20, 80, 48, -109, 117, 125, -67, 19, -15, 69, -28, 47, 15, 4, 34, -54, 51, -128, 18, 61, -77, -122, 100, -58, -118, -36, 5, 32, 43, 15, 60, -55, 120, 123, -77, -76, -121, 77, 93, 16, -73, 54, 46, -83, -39, 125 }, { 115, -15, -42, 111, -124, 52, 29, -124, -10, -23, 41, -128, 65, -60, -121, 6, -42, 14, 98, -80, 80, -46, -38, 64, 16, 84, -50, 47, -97, 11, -88, 12, 68, -127, -92, 87, -22, 54, -49, 33, -4, -68, 21, -7, -45, 84, 107, 57, 8, -106, 0, -87, -104, 93, -43, -98, -92, -72, 110, -14, -66, 119, 14, -68 }, { -19, 7, 7, 66, -94, 18, 36, 8, -58, -31, 21, -113, -124, -5, -12, 105, 40, -62, 57, -56, 25, 117, 49, 17, -33, 49, 105, 113, -26, 78, 97, 2, -22, -84, 49, 67, -6, 33, 89, 28, 30, 12, -3, -23, -45, 7, -4, -39, -20, 25, -91, 55, 53, 21, -94, 17, -54, 109, 125, 124, 122, 117, -125, 60 }, { -28, -104, -46, -22, 71, -79, 100, 48, -90, -57, -30, -23, -24, 1, 2, -31, 85, -6, -113, -116, 105, -31, -109, 106, 1, 78, -3, 103, -6, 100, -44, 15, -100, 97, 59, -42, 22, 83, 113, -118, 112, -57, 80, -45, -86, 72, 77, -26, -106, 50, 28, -24, 41, 22, -73, 108, 18, -93, 30, 8, -11, -16, 124, 106 }, { 16, -119, -109, 115, 67, 36, 28, 74, 101, -58, -82, 91, 4, -97, 111, -77, -37, -125, 126, 3, 10, -99, -115, 91, -66, -83, -81, 10, 7, 92, 26, 6, -45, 66, -26, 118, -77, 13, -91, 20, -18, -33, -103, 43, 75, -100, -5, -64, 117, 30, 5, -100, -90, 13, 18, -52, 26, 24, -10, 24, -31, 53, 88, 112 }, { 7, -90, 46, 109, -42, 108, -84, 124, -28, -63, 34, -19, -76, 88, -121, 23, 54, -73, -15, -52, 84, -119, 64, 20, 92, -91, -58, -121, -117, -90, -102, 1, 49, 21, 3, -85, -3, 38, 117, 73, -38, -71, -37, 40, -2, -50, -47, -46, 75, -105, 125, 126, -13, 68, 50, -81, -43, -93, 85, -79, 52, 98, 118, 50 }, { -104, 65, -61, 12, 68, 106, 37, -64, 40, -114, 61, 73, 74, 61, -113, -79, 57, 47, -57, -21, -68, -62, 23, -18, 93, -7, -55, -88, -106, 104, -126, 5, 53, 97, 100, -67, -112, -88, 41, 24, 95, 15, 25, -67, 79, -69, 53, 21, -128, -101, 73, 17, 7, -98, 5, -2, 33, -113, 99, -72, 125, 7, 18, -105 }, { -17, 28, 79, 34, 110, 86, 43, 27, -114, -112, -126, -98, -121, 126, -21, 111, 58, -114, -123, 75, 117, -116, 7, 107, 90, 80, -75, -121, 116, -11, -76, 0, -117, -52, 76, -116, 115, -117, 61, -7, 55, -34, 38, 101, 86, -19, -36, -92, -94, 61, 88, -128, -121, -103, 84, 19, -83, -102, 122, -111, 62, 112, 20, 3 }, { -127, -90, 28, -77, -48, -56, -10, 84, -41, 59, -115, 68, -74, -104, -119, -49, -37, -90, -57, 66, 108, 110, -62, -107, 88, 90, 29, -65, 74, -38, 95, 8, 120, 88, 96, -65, -109, 68, -63, -4, -16, 90, 7, 39, -56, -110, -100, 86, -39, -53, -89, -35, 127, -42, -48, -36, 53, -66, 109, -51, 51, -23, -12, 73 }, { -12, 78, 81, 30, 124, 22, 56, -112, 58, -99, 30, -98, 103, 66, 89, 92, -52, -20, 26, 82, -92, -18, 96, 7, 38, 21, -9, -25, -17, 4, 43, 15, 111, 103, -48, -50, -83, 52, 59, 103, 102, 83, -105, 87, 20, -120, 35, -7, -39, -24, 29, -39, -35, -87, 88, 120, 126, 19, 108, 34, -59, -20, 86, 47 }, { 19, -70, 36, 55, -42, -49, 33, 100, 105, -5, 89, 43, 3, -85, 60, -96, 43, -46, 86, -33, 120, -123, -99, -100, -34, 48, 82, -37, 34, 78, 127, 12, -39, -76, -26, 117, 74, -60, -68, -2, -37, -56, -6, 94, -27, 81, 32, -96, -19, -32, -77, 22, -56, -49, -38, -60, 45, -69, 40, 106, -106, -34, 101, -75 }, { 57, -92, -44, 8, -79, -88, -82, 58, -116, 93, 103, -127, 87, -121, -28, 31, -108, -14, -23, 38, 57, -83, -33, -110, 24, 6, 68, 124, -89, -35, -127, 5, -118, -78, -127, -35, 112, -34, 30, 24, -70, -71, 126, 39, -124, 122, -35, -97, -18, 25, 119, 79, 119, -65, 59, -20, -84, 120, -47, 4, -106, -125, -38, -113 }, { 18, -93, 34, -80, -43, 127, 57, -118, 24, -119, 25, 71, 59, -29, -108, -99, -122, 58, 44, 0, 42, -111, 25, 94, -36, 41, -64, -53, -78, -119, 85, 7, -45, -70, 81, -84, 71, -61, -68, -79, 112, 117, 19, 18, 70, 95, 108, -58, 48, 116, -89, 43, 66, 55, 37, -37, -60, 104, 47, -19, -56, 97, 73, 26 }, { 78, 4, -111, -36, 120, 111, -64, 46, 99, 125, -5, 97, -126, -21, 60, -78, -33, 89, 25, -60, 0, -49, 59, -118, 18, 3, -60, 30, 105, -92, -101, 15, 63, 50, 25, 2, -116, 78, -5, -25, -59, 74, -116, 64, -55, -121, 1, 69, 51, -119, 43, -6, -81, 14, 5, 84, -67, -73, 67, 24, 82, -37, 109, -93 }, { -44, -30, -64, -68, -21, 74, 124, 122, 114, -89, -91, -51, 89, 32, 96, -1, -101, -112, -94, 98, -24, -31, -50, 100, -72, 56, 24, 30, 105, 115, 15, 3, -67, 107, -18, 111, -38, -93, -11, 24, 36, 73, -23, 108, 14, -41, -65, 32, 51, 22, 95, 41, 85, -121, -35, -107, 0, 105, -112, 59, 48, -22, -84, 46 }, { 4, 38, 54, -84, -78, 24, -48, 8, -117, 78, -95, 24, 25, -32, -61, 26, -97, -74, 46, -120, -125, 27, 73, 107, -17, -21, -6, -52, 47, -68, 66, 5, -62, -12, -102, -127, 48, -69, -91, -81, -33, -13, -9, -12, -44, -73, 40, -58, 120, -120, 108, 101, 18, -14, -17, -93, 113, 49, 76, -4, -113, -91, -93, -52 }, { 28, -48, 70, -35, 123, -31, 16, -52, 72, 84, -51, 78, 104, 59, -102, -112, 29, 28, 25, 66, 12, 75, 26, -85, 56, -12, -4, -92, 49, 86, -27, 12, 44, -63, 108, 82, -76, -97, -41, 95, -48, -95, -115, 1, 64, -49, -97, 90, 65, 46, -114, -127, -92, 79, 100, 49, 116, -58, -106, 9, 117, -7, -91, 96 }, { 58, 26, 18, 76, 127, -77, -58, -87, -116, -44, 60, -32, -4, -76, -124, 4, -60, 82, -5, -100, -95, 18, 2, -53, -50, -96, -126, 105, 93, 19, 74, 13, 87, 125, -72, -10, 42, 14, 91, 44, 78, 52, 60, -59, -27, -37, -57, 17, -85, 31, -46, 113, 100, -117, 15, 108, -42, 12, 47, 63, 1, 11, -122, -3 } }; for (int i = 0; i < recipients.length; i++) { Nxt.Transaction transaction = new Nxt.Transaction((byte)0, (byte)0, 0, (short)0, CREATOR_PUBLIC_KEY, recipients[i], amounts[i], 0, 0L, signatures[i]); transactions.put(Long.valueOf(transaction.getId()), transaction); } for (Nxt.Transaction transaction : transactions.values()) { transaction.index = transactionCounter.incrementAndGet(); transaction.block = 2680262203532249785L; } Nxt.Transaction.saveTransactions("transactions.nxt"); } try { logMessage("Loading blocks..."); Nxt.Block.loadBlocks("blocks.nxt"); logMessage("...Done"); } catch (FileNotFoundException e) { logMessage("blocks.nxt not found, starting from scratch"); blocks.clear(); Nxt.Block block = new Nxt.Block(-1, 0, 0L, transactions.size(), 1000000000, 0, transactions.size() * 128, null, CREATOR_PUBLIC_KEY, new byte[64], new byte[] { 105, -44, 38, -60, -104, -73, 10, -58, -47, 103, -127, -128, 53, 101, 39, -63, -2, -32, 48, -83, 115, 47, -65, 118, 114, -62, 38, 109, 22, 106, 76, 8, -49, -113, -34, -76, 82, 79, -47, -76, -106, -69, -54, -85, 3, -6, 110, 103, 118, 15, 109, -92, 82, 37, 20, 2, 36, -112, 21, 72, 108, 72, 114, 17 }); block.index = blockCounter.incrementAndGet(); blocks.put(Long.valueOf(2680262203532249785L), block); int i = 0; for (Iterator i$ = transactions.keySet().iterator(); i$.hasNext();) { long transaction = ((Long)i$.next()).longValue(); block.transactions[(i++)] = transaction; } Arrays.sort(block.transactions); MessageDigest digest = getMessageDigest("SHA-256"); for (i = 0; i < block.transactions.length; i++) { Nxt.Transaction transaction = (Nxt.Transaction)transactions.get(Long.valueOf(block.transactions[i])); digest.update(transaction.getBytes()); block.blockTransactions[i] = transaction; } block.payloadHash = digest.digest(); block.baseTarget = 153722867L; block.cumulativeDifficulty = BigInteger.ZERO; lastBlock.set(block); Nxt.Block.saveBlocks("blocks.nxt", false); } logMessage("Scanning blockchain..."); Map<Long, Nxt.Block> loadedBlocks = new HashMap(blocks); blocks.clear(); long curBlockId = 2680262203532249785L; Nxt.Block curBlock; while ((curBlock = (Nxt.Block)loadedBlocks.get(Long.valueOf(curBlockId))) != null) { curBlock.analyze(); curBlockId = curBlock.nextBlock; } logMessage("...Done"); scheduledThreadPool.scheduleWithFixedDelay(new Runnable() { public void run() { try { if (Nxt.Peer.getNumberOfConnectedPublicPeers() < Nxt.maxNumberOfConnectedPublicPeers) { Nxt.Peer peer = Nxt.Peer.getAnyPeer(ThreadLocalRandom.current().nextInt(2) == 0 ? 0 : 2, false); if (peer != null) { peer.connect(); } } } catch (Exception e) { Nxt.logDebugMessage("Error connecting to peer", e); } catch (Throwable t) { Nxt.logMessage("CRITICAL ERROR. PLEASE REPORT TO THE DEVELOPERS.\n" + t.toString()); t.printStackTrace(); System.exit(1); } } }, 0L, 5L, TimeUnit.SECONDS); scheduledThreadPool.scheduleWithFixedDelay(new Runnable() { public void run() { try { curTime = System.currentTimeMillis(); for (Nxt.Peer peer : Nxt.peers.values()) { if ((peer.blacklistingTime > 0L) && (peer.blacklistingTime + Nxt.blacklistingPeriod <= curTime)) { peer.removeBlacklistedStatus(); } } } catch (Exception e) { long curTime; Nxt.logDebugMessage("Error un-blacklisting peer", e); } catch (Throwable t) { Nxt.logMessage("CRITICAL ERROR. PLEASE REPORT TO THE DEVELOPERS.\n" + t.toString()); t.printStackTrace(); System.exit(1); } } }, 0L, 1L, TimeUnit.SECONDS); scheduledThreadPool.scheduleWithFixedDelay(new Runnable() { private final JSONObject getPeersRequest; public void run() { try { Nxt.Peer peer = Nxt.Peer.getAnyPeer(1, true); if (peer != null) { JSONObject response = peer.send(this.getPeersRequest); if (response != null) { JSONArray peers = (JSONArray)response.get("peers"); for (Object peerAddress : peers) { String address = ((String)peerAddress).trim(); if (address.length() > 0) { Nxt.Peer.addPeer(address, address); } } } } } catch (Exception e) { Nxt.logDebugMessage("Error requesting peers from a peer", e); } catch (Throwable t) { Nxt.logMessage("CRITICAL ERROR. PLEASE REPORT TO THE DEVELOPERS.\n" + t.toString()); t.printStackTrace(); System.exit(1); } } }, 0L, 5L, TimeUnit.SECONDS); scheduledThreadPool.scheduleWithFixedDelay(new Runnable() { private final JSONObject getUnconfirmedTransactionsRequest; public void run() { try { Nxt.Peer peer = Nxt.Peer.getAnyPeer(1, true); if (peer != null) { JSONObject response = peer.send(this.getUnconfirmedTransactionsRequest); if (response != null) { Nxt.Transaction.processTransactions(response, "unconfirmedTransactions"); } } } catch (Exception e) { Nxt.logDebugMessage("Error processing unconfirmed transactions from peer", e); } catch (Throwable t) { Nxt.logMessage("CRITICAL ERROR. PLEASE REPORT TO THE DEVELOPERS.\n" + t.toString()); t.printStackTrace(); System.exit(1); } } }, 0L, 5L, TimeUnit.SECONDS); scheduledThreadPool.scheduleWithFixedDelay(new Runnable() { public void run() { try { int curTime = Nxt.getEpochTime(System.currentTimeMillis()); JSONArray removedUnconfirmedTransactions = new JSONArray(); Iterator<Nxt.Transaction> iterator = Nxt.unconfirmedTransactions.values().iterator(); while (iterator.hasNext()) { Nxt.Transaction transaction = (Nxt.Transaction)iterator.next(); if ((transaction.timestamp + transaction.deadline * 60 < curTime) || (!transaction.validateAttachment())) { iterator.remove(); Nxt.Account account = (Nxt.Account)Nxt.accounts.get(Long.valueOf(transaction.getSenderAccountId())); account.addToUnconfirmedBalance((transaction.amount + transaction.fee) * 100L); JSONObject removedUnconfirmedTransaction = new JSONObject(); removedUnconfirmedTransaction.put("index", Integer.valueOf(transaction.index)); removedUnconfirmedTransactions.add(removedUnconfirmedTransaction); } } if (removedUnconfirmedTransactions.size() > 0) { response = new JSONObject(); response.put("response", "processNewData"); response.put("removedUnconfirmedTransactions", removedUnconfirmedTransactions); for (Nxt.User user : Nxt.users.values()) { user.send(response); } } } catch (Exception e) { JSONObject response; Nxt.logDebugMessage("Error removing unconfirmed transactions", e); } catch (Throwable t) { Nxt.logMessage("CRITICAL ERROR. PLEASE REPORT TO THE DEVELOPERS.\n" + t.toString()); t.printStackTrace(); System.exit(1); } } }, 0L, 1L, TimeUnit.SECONDS); scheduledThreadPool.scheduleWithFixedDelay(new Runnable() { private final JSONObject getCumulativeDifficultyRequest; private final JSONObject getMilestoneBlockIdsRequest; public void run() { try { Nxt.Peer peer = Nxt.Peer.getAnyPeer(1, true); if (peer != null) { Nxt.lastBlockchainFeeder = peer; JSONObject response = peer.send(this.getCumulativeDifficultyRequest); if (response != null) { BigInteger curCumulativeDifficulty = ((Nxt.Block)Nxt.lastBlock.get()).cumulativeDifficulty; String peerCumulativeDifficulty = (String)response.get("cumulativeDifficulty"); if (peerCumulativeDifficulty == null) { return; } BigInteger betterCumulativeDifficulty = new BigInteger(peerCumulativeDifficulty); if (betterCumulativeDifficulty.compareTo(curCumulativeDifficulty) > 0) { response = peer.send(this.getMilestoneBlockIdsRequest); if (response != null) { long commonBlockId = 2680262203532249785L; JSONArray milestoneBlockIds = (JSONArray)response.get("milestoneBlockIds"); for (Object milestoneBlockId : milestoneBlockIds) { long blockId = Nxt.parseUnsignedLong((String)milestoneBlockId); Nxt.Block block = (Nxt.Block)Nxt.blocks.get(Long.valueOf(blockId)); if (block != null) { commonBlockId = blockId; break; } } int numberOfBlocks; int i; do { JSONObject request = new JSONObject(); request.put("requestType", "getNextBlockIds"); request.put("blockId", Nxt.convert(commonBlockId)); response = peer.send(request); if (response == null) { return; } JSONArray nextBlockIds = (JSONArray)response.get("nextBlockIds"); numberOfBlocks = nextBlockIds.size(); if (numberOfBlocks == 0) { return; } for (i = 0; i < numberOfBlocks; i++) { long blockId = Nxt.parseUnsignedLong((String)nextBlockIds.get(i)); if (Nxt.blocks.get(Long.valueOf(blockId)) == null) { break; } commonBlockId = blockId; } } while (i == numberOfBlocks); if (((Nxt.Block)Nxt.lastBlock.get()).height - ((Nxt.Block)Nxt.blocks.get(Long.valueOf(commonBlockId))).height < 720) { long curBlockId = commonBlockId; LinkedList<Nxt.Block> futureBlocks = new LinkedList(); HashMap<Long, Nxt.Transaction> futureTransactions = new HashMap(); for (;;) { JSONObject request = new JSONObject(); request.put("requestType", "getNextBlocks"); request.put("blockId", Nxt.convert(curBlockId)); response = peer.send(request); if (response == null) { break; } JSONArray nextBlocks = (JSONArray)response.get("nextBlocks"); numberOfBlocks = nextBlocks.size(); if (numberOfBlocks == 0) { break; } synchronized (Nxt.blocksAndTransactionsLock) { for (i = 0; i < numberOfBlocks; i++) { JSONObject blockData = (JSONObject)nextBlocks.get(i); Nxt.Block block = Nxt.Block.getBlock(blockData); if (block == null) { peer.blacklist(); return; } curBlockId = block.getId(); boolean alreadyPushed = false; if (block.previousBlock == ((Nxt.Block)Nxt.lastBlock.get()).getId()) { ByteBuffer buffer = ByteBuffer.allocate(224 + block.payloadLength); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.put(block.getBytes()); JSONArray transactionsData = (JSONArray)blockData.get("transactions"); for (Object transaction : transactionsData) { buffer.put(Nxt.Transaction.getTransaction((JSONObject)transaction).getBytes()); } if (Nxt.Block.pushBlock(buffer, false)) { alreadyPushed = true; } else { peer.blacklist(); return; } } if ((!alreadyPushed) && (Nxt.blocks.get(Long.valueOf(block.getId())) == null) && (block.transactions.length <= 255)) { futureBlocks.add(block); JSONArray transactionsData = (JSONArray)blockData.get("transactions"); for (int j = 0; j < block.transactions.length; j++) { Nxt.Transaction transaction = Nxt.Transaction.getTransaction((JSONObject)transactionsData.get(j)); block.transactions[j] = transaction.getId(); block.blockTransactions[j] = transaction; futureTransactions.put(Long.valueOf(block.transactions[j]), transaction); } } } } } if ((!futureBlocks.isEmpty()) && (((Nxt.Block)Nxt.lastBlock.get()).height - ((Nxt.Block)Nxt.blocks.get(Long.valueOf(commonBlockId))).height < 720)) { synchronized (Nxt.blocksAndTransactionsLock) { Nxt.Block.saveBlocks("blocks.nxt.bak", true); Nxt.Transaction.saveTransactions("transactions.nxt.bak"); curCumulativeDifficulty = ((Nxt.Block)Nxt.lastBlock.get()).cumulativeDifficulty; while ((((Nxt.Block)Nxt.lastBlock.get()).getId() != commonBlockId) && (Nxt.Block.popLastBlock())) {} if (((Nxt.Block)Nxt.lastBlock.get()).getId() == commonBlockId) { for (Nxt.Block block : futureBlocks) { if (block.previousBlock == ((Nxt.Block)Nxt.lastBlock.get()).getId()) { ByteBuffer buffer = ByteBuffer.allocate(224 + block.payloadLength); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.put(block.getBytes()); for (Nxt.Transaction transaction : block.blockTransactions) { buffer.put(transaction.getBytes()); } if (!Nxt.Block.pushBlock(buffer, false)) { break; } } } } if (((Nxt.Block)Nxt.lastBlock.get()).cumulativeDifficulty.compareTo(curCumulativeDifficulty) < 0) { Nxt.Block.loadBlocks("blocks.nxt.bak"); Nxt.Transaction.loadTransactions("transactions.nxt.bak"); peer.blacklist(); Nxt.accounts.clear(); Nxt.aliases.clear(); Nxt.aliasIdToAliasMappings.clear(); Nxt.unconfirmedTransactions.clear(); Nxt.doubleSpendingTransactions.clear(); Nxt.logMessage("Re-scanning blockchain..."); Map<Long, Nxt.Block> loadedBlocks = new HashMap(Nxt.blocks); Nxt.blocks.clear(); long currentBlockId = 2680262203532249785L; Nxt.Block currentBlock; while ((currentBlock = (Nxt.Block)loadedBlocks.get(Long.valueOf(currentBlockId))) != null) { currentBlock.analyze(); currentBlockId = currentBlock.nextBlock; } Nxt.logMessage("...Done"); } } } synchronized (Nxt.blocksAndTransactionsLock) { Nxt.Block.saveBlocks("blocks.nxt", false); Nxt.Transaction.saveTransactions("transactions.nxt"); } } } } } } } catch (Exception e) { Nxt.logDebugMessage("Error in milestone blocks processing thread", e); } catch (Throwable t) { Nxt.logMessage("CRITICAL ERROR. PLEASE REPORT TO THE DEVELOPERS.\n" + t.toString()); t.printStackTrace(); System.exit(1); } } }, 0L, 1L, TimeUnit.SECONDS); scheduledThreadPool.scheduleWithFixedDelay(new Runnable() { private final ConcurrentMap<Nxt.Account, Nxt.Block> lastBlocks = new ConcurrentHashMap(); private final ConcurrentMap<Nxt.Account, BigInteger> hits = new ConcurrentHashMap(); public void run() { try { HashMap<Nxt.Account, Nxt.User> unlockedAccounts = new HashMap(); for (Nxt.User user : Nxt.users.values()) { if (user.secretPhrase != null) { Nxt.Account account = (Nxt.Account)Nxt.accounts.get(Long.valueOf(Nxt.Account.getId(user.publicKey))); if ((account != null) && (account.getEffectiveBalance() > 0)) { unlockedAccounts.put(account, user); } } } for (Map.Entry<Nxt.Account, Nxt.User> unlockedAccountEntry : unlockedAccounts.entrySet()) { Nxt.Account account = (Nxt.Account)unlockedAccountEntry.getKey(); Nxt.User user = (Nxt.User)unlockedAccountEntry.getValue(); Nxt.Block lastBlock = (Nxt.Block)Nxt.lastBlock.get(); if (this.lastBlocks.get(account) != lastBlock) { long effectiveBalance = account.getEffectiveBalance(); if (effectiveBalance > 0L) { MessageDigest digest = Nxt.getMessageDigest("SHA-256"); byte[] generationSignatureHash; byte[] generationSignatureHash; if (lastBlock.height < 30000) { byte[] generationSignature = Nxt.Crypto.sign(lastBlock.generationSignature, user.secretPhrase); generationSignatureHash = digest.digest(generationSignature); } else { digest.update(lastBlock.generationSignature); generationSignatureHash = digest.digest(user.publicKey); } BigInteger hit = new BigInteger(1, new byte[] { generationSignatureHash[7], generationSignatureHash[6], generationSignatureHash[5], generationSignatureHash[4], generationSignatureHash[3], generationSignatureHash[2], generationSignatureHash[1], generationSignatureHash[0] }); this.lastBlocks.put(account, lastBlock); this.hits.put(account, hit); JSONObject response = new JSONObject(); response.put("response", "setBlockGenerationDeadline"); response.put("deadline", Long.valueOf(hit.divide(BigInteger.valueOf(lastBlock.baseTarget).multiply(BigInteger.valueOf(effectiveBalance))).longValue() - (Nxt.getEpochTime(System.currentTimeMillis()) - lastBlock.timestamp))); user.send(response); } } else { int elapsedTime = Nxt.getEpochTime(System.currentTimeMillis()) - lastBlock.timestamp; if (elapsedTime > 0) { BigInteger target = BigInteger.valueOf(lastBlock.baseTarget).multiply(BigInteger.valueOf(account.getEffectiveBalance())).multiply(BigInteger.valueOf(elapsedTime)); if (((BigInteger)this.hits.get(account)).compareTo(target) < 0) { account.generateBlock(user.secretPhrase); } } } } } catch (Exception e) { Nxt.logDebugMessage("Error in block generation thread", e); } catch (Throwable t) { Nxt.logMessage("CRITICAL ERROR. PLEASE REPORT TO THE DEVELOPERS.\n" + t.toString()); t.printStackTrace(); System.exit(1); } } }, 0L, 1L, TimeUnit.SECONDS); scheduledThreadPool.scheduleWithFixedDelay(new Runnable() { public void run() { try { JSONArray transactionsData = new JSONArray(); for (Nxt.Transaction transaction : Nxt.nonBroadcastedTransactions.values()) { if ((Nxt.unconfirmedTransactions.get(Long.valueOf(transaction.id)) == null) && (Nxt.transactions.get(Long.valueOf(transaction.id)) == null)) { transactionsData.add(transaction.getJSONObject()); } else { Nxt.nonBroadcastedTransactions.remove(Long.valueOf(transaction.id)); } } if (transactionsData.size() > 0) { JSONObject peerRequest = new JSONObject(); peerRequest.put("requestType", "processTransactions"); peerRequest.put("transactions", transactionsData); Nxt.Peer.sendToSomePeers(peerRequest); } } catch (Exception e) { Nxt.logDebugMessage("Error in transaction re-broadcasting thread", e); } catch (Throwable t) { Nxt.logMessage("CRITICAL ERROR. PLEASE REPORT TO THE DEVELOPERS.\n" + t.toString()); t.printStackTrace(); System.exit(1); } } }, 0L, 60L, TimeUnit.SECONDS); logMessage("NRS 0.5.10 started successfully."); } catch (Exception e) { logMessage("Error initializing Nxt servlet", e); System.exit(1); } } public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, private"); resp.setHeader("Pragma", "no-cache"); resp.setDateHeader("Expires", 0L); Nxt.User user = null; long accountId; try { String userPasscode = req.getParameter("user"); String secretPhrase; if (userPasscode == null) { JSONObject response = new JSONObject(); if ((allowedBotHosts != null) && (!allowedBotHosts.contains(req.getRemoteHost()))) { response.put("errorCode", Integer.valueOf(7)); response.put("errorDescription", "Not allowed"); } else { String requestType = req.getParameter("requestType"); if (requestType == null) { response.put("errorCode", Integer.valueOf(1)); response.put("errorDescription", "Incorrect request"); } else { localObject1 = requestType;int i = -1; switch (((String)localObject1).hashCode()) { case 1708941985: if (((String)localObject1).equals("assignAlias")) { i = 0; } break; case 62209885: if (((String)localObject1).equals("broadcastTransaction")) { i = 1; } break; case -907924844: if (((String)localObject1).equals("decodeHallmark")) { i = 2; } break; case 1183136939: if (((String)localObject1).equals("decodeToken")) { i = 3; } break; case -347064830: if (((String)localObject1).equals("getAccountBlockIds")) { i = 4; } break; case -1836634766: if (((String)localObject1).equals("getAccountId")) { i = 5; } break; case -1594290433: if (((String)localObject1).equals("getAccountPublicKey")) { i = 6; } break; case -1415951151: if (((String)localObject1).equals("getAccountTransactionIds")) { i = 7; } break; case 1948728474: if (((String)localObject1).equals("getAlias")) { i = 8; } break; case 122324821: if (((String)localObject1).equals("getAliasId")) { i = 9; } break; case -502897730: if (((String)localObject1).equals("getAliasIds")) { i = 10; } break; case -502886798: if (((String)localObject1).equals("getAliasURI")) { i = 11; } break; case 697674406: if (((String)localObject1).equals("getBalance")) { i = 12; } break; case 1949657815: if (((String)localObject1).equals("getBlock")) { i = 13; } break; case -431881575: if (((String)localObject1).equals("getConstants")) { i = 14; } break; case 1755958186: if (((String)localObject1).equals("getGuaranteedBalance")) { i = 15; } break; case 635655024: if (((String)localObject1).equals("getMyInfo")) { i = 16; } break; case -75245096: if (((String)localObject1).equals("getPeer")) { i = 17; } break; case 1962369435: if (((String)localObject1).equals("getPeers")) { i = 18; } break; case 1965583067: if (((String)localObject1).equals("getState")) { i = 19; } break; case -75121853: if (((String)localObject1).equals("getTime")) { i = 20; } break; case 1500977576: if (((String)localObject1).equals("getTransaction")) { i = 21; } break; case -996573277: if (((String)localObject1).equals("getTransactionBytes")) { i = 22; } break; case -1835768118: if (((String)localObject1).equals("getUnconfirmedTransactionIds")) { i = 23; } break; case -1994749631: if (((String)localObject1).equals("getAccountCurrentAskOrderIds")) { i = 24; } break; case -2059286587: if (((String)localObject1).equals("getAccountCurrentBidOrderIds")) { i = 25; } break; case 1455291851: if (((String)localObject1).equals("getAskOrder")) { i = 26; } break; case 1199720685: if (((String)localObject1).equals("getAskOrderIds")) { i = 27; } break; case -1582371385: if (((String)localObject1).equals("getBidOrder")) { i = 28; } break; case 1135183729: if (((String)localObject1).equals("getBidOrderIds")) { i = 29; } break; case -944172977: if (((String)localObject1).equals("listAccountAliases")) { i = 30; } break; case 246104597: if (((String)localObject1).equals("markHost")) { i = 31; } break; case 691453791: if (((String)localObject1).equals("sendMessage")) { i = 32; } break; case 9950744: if (((String)localObject1).equals("sendMoney")) { i = 33; } break; } switch (i) { case 0: String secretPhrase = req.getParameter("secretPhrase"); String alias = req.getParameter("alias"); String uri = req.getParameter("uri"); String feeValue = req.getParameter("fee"); String deadlineValue = req.getParameter("deadline"); String referencedTransactionValue = req.getParameter("referencedTransaction"); if (secretPhrase == null) { response.put("errorCode", Integer.valueOf(3)); response.put("errorDescription", "\"secretPhrase\" not specified"); } else if (alias == null) { response.put("errorCode", Integer.valueOf(3)); response.put("errorDescription", "\"alias\" not specified"); } else if (uri == null) { response.put("errorCode", Integer.valueOf(3)); response.put("errorDescription", "\"uri\" not specified"); } else if (feeValue == null) { response.put("errorCode", Integer.valueOf(3)); response.put("errorDescription", "\"fee\" not specified"); } else if (deadlineValue == null) { response.put("errorCode", Integer.valueOf(3)); response.put("errorDescription", "\"deadline\" not specified"); } else { alias = alias.trim(); if ((alias.length() == 0) || (alias.length() > 100)) { response.put("errorCode", Integer.valueOf(4)); response.put("errorDescription", "Incorrect \"alias\" (length must be in [1..100] range)"); } else { String normalizedAlias = alias.toLowerCase(); for (int i = 0; i < normalizedAlias.length(); i++) { if ("0123456789abcdefghijklmnopqrstuvwxyz".indexOf(normalizedAlias.charAt(i)) < 0) { break; } } if (i != normalizedAlias.length()) { response.put("errorCode", Integer.valueOf(4)); response.put("errorDescription", "Incorrect \"alias\" (must contain only digits and latin letters)"); } else { uri = uri.trim(); if (uri.length() > 1000) { response.put("errorCode", Integer.valueOf(4)); response.put("errorDescription", "Incorrect \"uri\" (length must be not longer than 1000 characters)"); } else { try { int fee = Integer.parseInt(feeValue); if ((fee <= 0) || (fee >= 1000000000L)) { throw new Exception(); } try { short deadline = Short.parseShort(deadlineValue); if (deadline < 1) { throw new Exception(); } long referencedTransaction = referencedTransactionValue == null ? 0L : parseUnsignedLong(referencedTransactionValue); byte[] publicKey = Nxt.Crypto.getPublicKey(secretPhrase); long accountId = Nxt.Account.getId(publicKey); Nxt.Account account = (Nxt.Account)accounts.get(Long.valueOf(accountId)); if (account == null) { response.put("errorCode", Integer.valueOf(6)); response.put("errorDescription", "Not enough funds"); } else if (fee * 100L > account.getUnconfirmedBalance()) { response.put("errorCode", Integer.valueOf(6)); response.put("errorDescription", "Not enough funds"); } else { Nxt.Alias aliasData = (Nxt.Alias)aliases.get(normalizedAlias); if ((aliasData != null) && (aliasData.account != account)) { response.put("errorCode", Integer.valueOf(8)); response.put("errorDescription", "\"" + alias + "\" is already used"); } else { int timestamp = getEpochTime(System.currentTimeMillis()); Nxt.Transaction transaction = new Nxt.Transaction((byte)1, (byte)1, timestamp, deadline, publicKey, 1739068987193023818L, 0, fee, referencedTransaction, new byte[64]); transaction.attachment = new Nxt.Transaction.MessagingAliasAssignmentAttachment(alias, uri); transaction.sign(secretPhrase); JSONObject peerRequest = new JSONObject(); peerRequest.put("requestType", "processTransactions"); JSONArray transactionsData = new JSONArray(); transactionsData.add(transaction.getJSONObject()); peerRequest.put("transactions", transactionsData); Nxt.Peer.sendToSomePeers(peerRequest); response.put("transaction", transaction.getStringId()); nonBroadcastedTransactions.put(Long.valueOf(transaction.id), transaction); } } } catch (Exception e) { response.put("errorCode", Integer.valueOf(4)); response.put("errorDescription", "Incorrect \"deadline\""); } } catch (Exception e) { response.put("errorCode", Integer.valueOf(4)); response.put("errorDescription", "Incorrect \"fee\""); } } } } } break; case 1: String transactionBytes = req.getParameter("transactionBytes"); if (transactionBytes == null) { response.put("errorCode", Integer.valueOf(3)); response.put("errorDescription", "\"transactionBytes\" not specified"); } else { try { ByteBuffer buffer = ByteBuffer.wrap(convert(transactionBytes)); buffer.order(ByteOrder.LITTLE_ENDIAN); Nxt.Transaction transaction = Nxt.Transaction.getTransaction(buffer); JSONObject peerRequest = new JSONObject(); peerRequest.put("requestType", "processTransactions"); JSONArray transactionsData = new JSONArray(); transactionsData.add(transaction.getJSONObject()); peerRequest.put("transactions", transactionsData); Nxt.Peer.sendToSomePeers(peerRequest); response.put("transaction", transaction.getStringId()); } catch (Exception e) { response.put("errorCode", Integer.valueOf(4)); response.put("errorDescription", "Incorrect \"transactionBytes\""); } } break; case 2: String hallmarkValue = req.getParameter("hallmark"); if (hallmarkValue == null) { response.put("errorCode", Integer.valueOf(3)); response.put("errorDescription", "\"hallmark\" not specified"); } else { try { byte[] hallmark = convert(hallmarkValue); ByteBuffer buffer = ByteBuffer.wrap(hallmark); buffer.order(ByteOrder.LITTLE_ENDIAN); byte[] publicKey = new byte[32]; buffer.get(publicKey); int hostLength = buffer.getShort(); byte[] hostBytes = new byte[hostLength]; buffer.get(hostBytes); String host = new String(hostBytes, "UTF-8"); int weight = buffer.getInt(); int date = buffer.getInt(); buffer.get(); byte[] signature = new byte[64]; buffer.get(signature); response.put("account", convert(Nxt.Account.getId(publicKey))); response.put("host", host); response.put("weight", Integer.valueOf(weight)); int year = date / 10000; int month = date % 10000 / 100; int day = date % 100; response.put("date", (year < 1000 ? "0" : year < 100 ? "00" : year < 10 ? "000" : "") + year + "-" + (month < 10 ? "0" : "") + month + "-" + (day < 10 ? "0" : "") + day); byte[] data = new byte[hallmark.length - 64]; System.arraycopy(hallmark, 0, data, 0, data.length); response.put("valid", Boolean.valueOf((host.length() > 100) || (weight <= 0) || (weight > 1000000000L) ? false : Nxt.Crypto.verify(signature, data, publicKey))); } catch (Exception e) { response.put("errorCode", Integer.valueOf(4)); response.put("errorDescription", "Incorrect \"hallmark\""); } } break; case 3: String website = req.getParameter("website"); String token = req.getParameter("token"); if (website == null) { response.put("errorCode", Integer.valueOf(3)); response.put("errorDescription", "\"website\" not specified"); } else if (token == null) { response.put("errorCode", Integer.valueOf(3)); response.put("errorDescription", "\"token\" not specified"); } else { byte[] websiteBytes = website.trim().getBytes("UTF-8"); byte[] tokenBytes = new byte[100]; int i = 0;int j = 0; try { for (; i < token.length(); j += 5) { long number = Long.parseLong(token.substring(i, i + 8), 32); tokenBytes[j] = ((byte)(int)number); tokenBytes[(j + 1)] = ((byte)(int)(number >> 8)); tokenBytes[(j + 2)] = ((byte)(int)(number >> 16)); tokenBytes[(j + 3)] = ((byte)(int)(number >> 24)); tokenBytes[(j + 4)] = ((byte)(int)(number >> 32));i += 8; } } catch (Exception e) {} if (i != 160) { response.put("errorCode", Integer.valueOf(4)); response.put("errorDescription", "Incorrect \"token\""); } else { byte[] publicKey = new byte[32]; System.arraycopy(tokenBytes, 0, publicKey, 0, 32); int timestamp = tokenBytes[32] & 0xFF | (tokenBytes[33] & 0xFF) << 8 | (tokenBytes[34] & 0xFF) << 16 | (tokenBytes[35] & 0xFF) << 24; byte[] signature = new byte[64]; System.arraycopy(tokenBytes, 36, signature, 0, 64); byte[] data = new byte[websiteBytes.length + 36]; System.arraycopy(websiteBytes, 0, data, 0, websiteBytes.length); System.arraycopy(tokenBytes, 0, data, websiteBytes.length, 36); boolean valid = Nxt.Crypto.verify(signature, data, publicKey); response.put("account", convert(Nxt.Account.getId(publicKey))); response.put("timestamp", Integer.valueOf(timestamp)); response.put("valid", Boolean.valueOf(valid)); } } break; case 4: String account = req.getParameter("account"); String timestampValue = req.getParameter("timestamp"); if (account == null) { response.put("errorCode", Integer.valueOf(3)); response.put("errorDescription", "\"account\" not specified"); } else if (timestampValue == null) { response.put("errorCode", Integer.valueOf(3)); response.put("errorDescription", "\"timestamp\" not specified"); } else { try { Nxt.Account accountData = (Nxt.Account)accounts.get(Long.valueOf(parseUnsignedLong(account))); if (accountData == null) { response.put("errorCode", Integer.valueOf(5)); response.put("errorDescription", "Unknown account"); } else { try { int timestamp = Integer.parseInt(timestampValue); if (timestamp < 0) { throw new Exception(); } PriorityQueue<Nxt.Block> sortedBlocks = new PriorityQueue(11, Nxt.Block.heightComparator); byte[] accountPublicKey = (byte[])accountData.publicKey.get(); for (Nxt.Block block : blocks.values()) { if ((block.timestamp >= timestamp) && (Arrays.equals(block.generatorPublicKey, accountPublicKey))) { sortedBlocks.offer(block); } } JSONArray blockIds = new JSONArray(); while (!sortedBlocks.isEmpty()) { blockIds.add(((Nxt.Block)sortedBlocks.poll()).getStringId()); } response.put("blockIds", blockIds); } catch (Exception e) { response.put("errorCode", Integer.valueOf(4)); response.put("errorDescription", "Incorrect \"timestamp\""); } } } catch (Exception e) { response.put("errorCode", Integer.valueOf(4)); response.put("errorDescription", "Incorrect \"account\""); } } break; case 5: String secretPhrase = req.getParameter("secretPhrase"); if (secretPhrase == null) { response.put("errorCode", Integer.valueOf(3)); response.put("errorDescription", "\"secretPhrase\" not specified"); } else { byte[] publicKeyHash = getMessageDigest("SHA-256").digest(Nxt.Crypto.getPublicKey(secretPhrase)); BigInteger bigInteger = new BigInteger(1, new byte[] { publicKeyHash[7], publicKeyHash[6], publicKeyHash[5], publicKeyHash[4], publicKeyHash[3], publicKeyHash[2], publicKeyHash[1], publicKeyHash[0] }); response.put("accountId", bigInteger.toString()); } break; case 6: String account = req.getParameter("account"); if (account == null) { response.put("errorCode", Integer.valueOf(3)); response.put("errorDescription", "\"account\" not specified"); } else { try { Nxt.Account accountData = (Nxt.Account)accounts.get(Long.valueOf(parseUnsignedLong(account))); if (accountData == null) { response.put("errorCode", Integer.valueOf(5)); response.put("errorDescription", "Unknown account"); } else if (accountData.publicKey.get() != null) { response.put("publicKey", convert((byte[])accountData.publicKey.get())); } } catch (Exception e) { response.put("errorCode", Integer.valueOf(4)); response.put("errorDescription", "Incorrect \"account\""); } } break; case 7: String account = req.getParameter("account"); String timestampValue = req.getParameter("timestamp"); if (account == null) { response.put("errorCode", Integer.valueOf(3)); response.put("errorDescription", "\"account\" not specified"); } else if (timestampValue == null) { response.put("errorCode", Integer.valueOf(3)); response.put("errorDescription", "\"timestamp\" not specified"); } else { try { Nxt.Account accountData = (Nxt.Account)accounts.get(Long.valueOf(parseUnsignedLong(account))); if (accountData == null) { response.put("errorCode", Integer.valueOf(5)); response.put("errorDescription", "Unknown account"); } else { try { int timestamp = Integer.parseInt(timestampValue); if (timestamp < 0) { throw new Exception(); } int type; try { type = Integer.parseInt(req.getParameter("type")); } catch (Exception e) { type = -1; } int subtype; try { subtype = Integer.parseInt(req.getParameter("subtype")); } catch (Exception e) { subtype = -1; } PriorityQueue<Nxt.Transaction> sortedTransactions = new PriorityQueue(11, Nxt.Transaction.timestampComparator); byte[] accountPublicKey = (byte[])accountData.publicKey.get(); for (Nxt.Transaction transaction : transactions.values()) { if (((transaction.recipient == accountData.id) || (Arrays.equals(transaction.senderPublicKey, accountPublicKey))) && ((type < 0) || (transaction.type == type)) && ((subtype < 0) || (transaction.subtype == subtype)) && (((Nxt.Block)blocks.get(Long.valueOf(transaction.block))).timestamp >= timestamp)) { sortedTransactions.offer(transaction); } } JSONArray transactionIds = new JSONArray(); while (!sortedTransactions.isEmpty()) { transactionIds.add(((Nxt.Transaction)sortedTransactions.poll()).getStringId()); } response.put("transactionIds", transactionIds); } catch (Exception e) { response.put("errorCode", Integer.valueOf(4)); response.put("errorDescription", "Incorrect \"timestamp\""); } } } catch (Exception e) { response.put("errorCode", Integer.valueOf(4)); response.put("errorDescription", "Incorrect \"account\""); } } break; case 8: String alias = req.getParameter("alias"); if (alias == null) { response.put("errorCode", Integer.valueOf(3)); response.put("errorDescription", "\"alias\" not specified"); } else { try { Nxt.Alias aliasData = (Nxt.Alias)aliasIdToAliasMappings.get(Long.valueOf(parseUnsignedLong(alias))); if (aliasData == null) { response.put("errorCode", Integer.valueOf(5)); response.put("errorDescription", "Unknown alias"); } else { response.put("account", convert(aliasData.account.id)); response.put("alias", aliasData.alias); if (aliasData.uri.length() > 0) { response.put("uri", aliasData.uri); } response.put("timestamp", Integer.valueOf(aliasData.timestamp)); } } catch (Exception e) { response.put("errorCode", Integer.valueOf(4)); response.put("errorDescription", "Incorrect \"alias\""); } } break; case 9: String alias = req.getParameter("alias"); if (alias == null) { response.put("errorCode", Integer.valueOf(3)); response.put("errorDescription", "\"alias\" not specified"); } else { Nxt.Alias aliasData = (Nxt.Alias)aliases.get(alias.toLowerCase()); if (aliasData == null) { response.put("errorCode", Integer.valueOf(5)); response.put("errorDescription", "Unknown alias"); } else { response.put("id", convert(aliasData.id)); } } break; case 10: String timestampValue = req.getParameter("timestamp"); if (timestampValue == null) { response.put("errorCode", Integer.valueOf(3)); response.put("errorDescription", "\"timestamp\" not specified"); } else { try { int timestamp = Integer.parseInt(timestampValue); if (timestamp < 0) { throw new Exception(); } JSONArray aliasIds = new JSONArray(); for (Map.Entry<Long, Nxt.Alias> aliasEntry : aliasIdToAliasMappings.entrySet()) { if (((Nxt.Alias)aliasEntry.getValue()).timestamp >= timestamp) { aliasIds.add(convert(((Long)aliasEntry.getKey()).longValue())); } } response.put("aliasIds", aliasIds); } catch (Exception e) { response.put("errorCode", Integer.valueOf(4)); response.put("errorDescription", "Incorrect \"timestamp\""); } } break; case 11: String alias = req.getParameter("alias"); if (alias == null) { response.put("errorCode", Integer.valueOf(3)); response.put("errorDescription", "\"alias\" not specified"); } else { Nxt.Alias aliasData = (Nxt.Alias)aliases.get(alias.toLowerCase()); if (aliasData == null) { response.put("errorCode", Integer.valueOf(5)); response.put("errorDescription", "Unknown alias"); } else if (aliasData.uri.length() > 0) { response.put("uri", aliasData.uri); } } break; case 12: String account = req.getParameter("account"); if (account == null) { response.put("errorCode", Integer.valueOf(3)); response.put("errorDescription", "\"account\" not specified"); } else { try { Nxt.Account accountData = (Nxt.Account)accounts.get(Long.valueOf(parseUnsignedLong(account))); if (accountData == null) { response.put("balance", Integer.valueOf(0)); response.put("unconfirmedBalance", Integer.valueOf(0)); response.put("effectiveBalance", Integer.valueOf(0)); } else { synchronized (accountData) { response.put("balance", Long.valueOf(accountData.getBalance())); response.put("unconfirmedBalance", Long.valueOf(accountData.getUnconfirmedBalance())); response.put("effectiveBalance", Long.valueOf(accountData.getEffectiveBalance() * 100L)); } } } catch (Exception e) { response.put("errorCode", Integer.valueOf(4)); response.put("errorDescription", "Incorrect \"account\""); } } break; case 13: String block = req.getParameter("block"); if (block == null) { response.put("errorCode", Integer.valueOf(3)); response.put("errorDescription", "\"block\" not specified"); } else { try { Nxt.Block blockData = (Nxt.Block)blocks.get(Long.valueOf(parseUnsignedLong(block))); if (blockData == null) { response.put("errorCode", Integer.valueOf(5)); response.put("errorDescription", "Unknown block"); } else { response.put("height", Integer.valueOf(blockData.height)); response.put("generator", convert(blockData.getGeneratorAccountId())); response.put("timestamp", Integer.valueOf(blockData.timestamp)); response.put("numberOfTransactions", Integer.valueOf(blockData.transactions.length)); response.put("totalAmount", Integer.valueOf(blockData.totalAmount)); response.put("totalFee", Integer.valueOf(blockData.totalFee)); response.put("payloadLength", Integer.valueOf(blockData.payloadLength)); response.put("version", Integer.valueOf(blockData.version)); response.put("baseTarget", convert(blockData.baseTarget)); if (blockData.previousBlock != 0L) { response.put("previousBlock", convert(blockData.previousBlock)); } if (blockData.nextBlock != 0L) { response.put("nextBlock", convert(blockData.nextBlock)); } response.put("payloadHash", convert(blockData.payloadHash)); response.put("generationSignature", convert(blockData.generationSignature)); if (blockData.version > 1) { response.put("previousBlockHash", convert(blockData.previousBlockHash)); } response.put("blockSignature", convert(blockData.blockSignature)); JSONArray transactions = new JSONArray(); for (long transactionId : blockData.transactions) { transactions.add(convert(transactionId)); } response.put("transactions", transactions); } } catch (Exception e) { response.put("errorCode", Integer.valueOf(4)); response.put("errorDescription", "Incorrect \"block\""); } } break; case 14: response.put("genesisBlockId", convert(2680262203532249785L)); response.put("genesisAccountId", convert(1739068987193023818L)); response.put("maxBlockPayloadLength", Integer.valueOf(32640)); response.put("maxArbitraryMessageLength", Integer.valueOf(1000)); JSONArray transactionTypes = new JSONArray(); JSONObject transactionType = new JSONObject(); transactionType.put("value", Byte.valueOf((byte)0)); transactionType.put("description", "Payment"); JSONArray subtypes = new JSONArray(); JSONObject subtype = new JSONObject(); subtype.put("value", Byte.valueOf((byte)0)); subtype.put("description", "Ordinary payment"); subtypes.add(subtype); transactionType.put("subtypes", subtypes); transactionTypes.add(transactionType); transactionType = new JSONObject(); transactionType.put("value", Byte.valueOf((byte)1)); transactionType.put("description", "Messaging"); subtypes = new JSONArray(); subtype = new JSONObject(); subtype.put("value", Byte.valueOf((byte)0)); subtype.put("description", "Arbitrary message"); subtypes.add(subtype); subtype = new JSONObject(); subtype.put("value", Byte.valueOf((byte)1)); subtype.put("description", "Alias assignment"); subtypes.add(subtype); transactionType.put("subtypes", subtypes); transactionTypes.add(transactionType); transactionType = new JSONObject(); transactionType.put("value", Byte.valueOf((byte)2)); transactionType.put("description", "Colored coins"); subtypes = new JSONArray(); subtype = new JSONObject(); subtype.put("value", Byte.valueOf((byte)0)); subtype.put("description", "Asset issuance"); subtypes.add(subtype); subtype = new JSONObject(); subtype.put("value", Byte.valueOf((byte)1)); subtype.put("description", "Asset transfer"); subtypes.add(subtype); subtype = new JSONObject(); subtype.put("value", Byte.valueOf((byte)2)); subtype.put("description", "Ask order placement"); subtypes.add(subtype); subtype = new JSONObject(); subtype.put("value", Byte.valueOf((byte)3)); subtype.put("description", "Bid order placement"); subtypes.add(subtype); subtype = new JSONObject(); subtype.put("value", Byte.valueOf((byte)4)); subtype.put("description", "Ask order cancellation"); subtypes.add(subtype); subtype = new JSONObject(); subtype.put("value", Byte.valueOf((byte)5)); subtype.put("description", "Bid order cancellation"); subtypes.add(subtype); transactionType.put("subtypes", subtypes); transactionTypes.add(transactionType); response.put("transactionTypes", transactionTypes); JSONArray peerStates = new JSONArray(); JSONObject peerState = new JSONObject(); peerState.put("value", Integer.valueOf(0)); peerState.put("description", "Non-connected"); peerStates.add(peerState); peerState = new JSONObject(); peerState.put("value", Integer.valueOf(1)); peerState.put("description", "Connected"); peerStates.add(peerState); peerState = new JSONObject(); peerState.put("value", Integer.valueOf(2)); peerState.put("description", "Disconnected"); peerStates.add(peerState); response.put("peerStates", peerStates); break; case 15: String account = req.getParameter("account"); String numberOfConfirmationsValue = req.getParameter("numberOfConfirmations"); if (account == null) { response.put("errorCode", Integer.valueOf(3)); response.put("errorDescription", "\"account\" not specified"); } else if (numberOfConfirmationsValue == null) { response.put("errorCode", Integer.valueOf(3)); response.put("errorDescription", "\"numberOfConfirmations\" not specified"); } else { try { Nxt.Account accountData = (Nxt.Account)accounts.get(Long.valueOf(parseUnsignedLong(account))); if (accountData == null) { response.put("guaranteedBalance", Integer.valueOf(0)); } else { try { int numberOfConfirmations = Integer.parseInt(numberOfConfirmationsValue); response.put("guaranteedBalance", Long.valueOf(accountData.getGuaranteedBalance(numberOfConfirmations))); } catch (Exception e) { response.put("errorCode", Integer.valueOf(4)); response.put("errorDescription", "Incorrect \"numberOfConfirmations\""); } } } catch (Exception e) { response.put("errorCode", Integer.valueOf(4)); response.put("errorDescription", "Incorrect \"account\""); } } break; case 16: response.put("host", req.getRemoteHost()); response.put("address", req.getRemoteAddr()); break; case 17: String peer = req.getParameter("peer"); if (peer == null) { response.put("errorCode", Integer.valueOf(3)); response.put("errorDescription", "\"peer\" not specified"); } else { Nxt.Peer peerData = (Nxt.Peer)peers.get(peer); if (peerData == null) { response.put("errorCode", Integer.valueOf(5)); response.put("errorDescription", "Unknown peer"); } else { response.put("state", Integer.valueOf(peerData.state)); response.put("announcedAddress", peerData.announcedAddress); if (peerData.hallmark != null) { response.put("hallmark", peerData.hallmark); } response.put("weight", Integer.valueOf(peerData.getWeight())); response.put("downloadedVolume", Long.valueOf(peerData.downloadedVolume)); response.put("uploadedVolume", Long.valueOf(peerData.uploadedVolume)); response.put("application", peerData.application); response.put("version", peerData.version); response.put("platform", peerData.platform); } } break; case 18: JSONArray peers = new JSONArray(); peers.addAll(peers.keySet()); response.put("peers", peers); break; case 19: response.put("version", "0.5.10"); response.put("time", Integer.valueOf(getEpochTime(System.currentTimeMillis()))); response.put("lastBlock", ((Nxt.Block)lastBlock.get()).getStringId()); response.put("cumulativeDifficulty", ((Nxt.Block)lastBlock.get()).cumulativeDifficulty.toString()); long totalEffectiveBalance = 0L; for (Nxt.Account account : accounts.values()) { long effectiveBalance = account.getEffectiveBalance(); if (effectiveBalance > 0L) { totalEffectiveBalance += effectiveBalance; } } response.put("totalEffectiveBalance", Long.valueOf(totalEffectiveBalance * 100L)); response.put("numberOfBlocks", Integer.valueOf(blocks.size())); response.put("numberOfTransactions", Integer.valueOf(transactions.size())); response.put("numberOfAccounts", Integer.valueOf(accounts.size())); response.put("numberOfAssets", Integer.valueOf(assets.size())); response.put("numberOfOrders", Integer.valueOf(askOrders.size() + bidOrders.size())); response.put("numberOfAliases", Integer.valueOf(aliases.size())); response.put("numberOfPeers", Integer.valueOf(peers.size())); response.put("numberOfUsers", Integer.valueOf(users.size())); response.put("lastBlockchainFeeder", lastBlockchainFeeder == null ? null : lastBlockchainFeeder.announcedAddress); response.put("availableProcessors", Integer.valueOf(Runtime.getRuntime().availableProcessors())); response.put("maxMemory", Long.valueOf(Runtime.getRuntime().maxMemory())); response.put("totalMemory", Long.valueOf(Runtime.getRuntime().totalMemory())); response.put("freeMemory", Long.valueOf(Runtime.getRuntime().freeMemory())); break; case 20: response.put("time", Integer.valueOf(getEpochTime(System.currentTimeMillis()))); break; case 21: String transaction = req.getParameter("transaction"); if (transaction == null) { response.put("errorCode", Integer.valueOf(3)); response.put("errorDescription", "\"transaction\" not specified"); } else { try { long transactionId = parseUnsignedLong(transaction); Nxt.Transaction transactionData = (Nxt.Transaction)transactions.get(Long.valueOf(transactionId)); if (transactionData == null) { transactionData = (Nxt.Transaction)unconfirmedTransactions.get(Long.valueOf(transactionId)); if (transactionData == null) { response.put("errorCode", Integer.valueOf(5)); response.put("errorDescription", "Unknown transaction"); } else { response = transactionData.getJSONObject(); response.put("sender", convert(transactionData.getSenderAccountId())); } } else { response = transactionData.getJSONObject(); response.put("sender", convert(transactionData.getSenderAccountId())); Nxt.Block block = (Nxt.Block)blocks.get(Long.valueOf(transactionData.block)); response.put("block", block.getStringId()); response.put("confirmations", Integer.valueOf(((Nxt.Block)lastBlock.get()).height - block.height + 1)); } } catch (Exception e) { response.put("errorCode", Integer.valueOf(4)); response.put("errorDescription", "Incorrect \"transaction\""); } } break; case 22: String transaction = req.getParameter("transaction"); if (transaction == null) { response.put("errorCode", Integer.valueOf(3)); response.put("errorDescription", "\"transaction\" not specified"); } else { try { long transactionId = parseUnsignedLong(transaction); Nxt.Transaction transactionData = (Nxt.Transaction)transactions.get(Long.valueOf(transactionId)); if (transactionData == null) { transactionData = (Nxt.Transaction)unconfirmedTransactions.get(Long.valueOf(transactionId)); if (transactionData == null) { response.put("errorCode", Integer.valueOf(5)); response.put("errorDescription", "Unknown transaction"); } else { response.put("bytes", convert(transactionData.getBytes())); } } else { response.put("bytes", convert(transactionData.getBytes())); Nxt.Block block = (Nxt.Block)blocks.get(Long.valueOf(transactionData.block)); response.put("confirmations", Integer.valueOf(((Nxt.Block)lastBlock.get()).height - block.height + 1)); } } catch (Exception e) { response.put("errorCode", Integer.valueOf(4)); response.put("errorDescription", "Incorrect \"transaction\""); } } break; case 23: JSONArray transactionIds = new JSONArray(); for (Nxt.Transaction transaction : unconfirmedTransactions.values()) { transactionIds.add(transaction.getStringId()); } response.put("unconfirmedTransactionIds", transactionIds); break; case 24: String account = req.getParameter("account"); if (account == null) { response.put("errorCode", Integer.valueOf(3)); response.put("errorDescription", "\"account\" not specified"); } else { try { Nxt.Account accountData = (Nxt.Account)accounts.get(Long.valueOf(parseUnsignedLong(account))); if (accountData == null) { response.put("errorCode", Integer.valueOf(5)); response.put("errorDescription", "Unknown account"); } else { long assetId; boolean assetIsNotUsed; try { assetId = parseUnsignedLong(req.getParameter("asset")); assetIsNotUsed = false; } catch (Exception e) { assetId = 0L; assetIsNotUsed = true; } JSONArray orderIds = new JSONArray(); for (Nxt.AskOrder askOrder : askOrders.values()) { if (((assetIsNotUsed) || (askOrder.asset == assetId)) && (askOrder.account == accountData)) { orderIds.add(convert(askOrder.id)); } } response.put("askOrderIds", orderIds); } } catch (Exception e) { response.put("errorCode", Integer.valueOf(4)); response.put("errorDescription", "Incorrect \"account\""); } } break; case 25: String account = req.getParameter("account"); if (account == null) { response.put("errorCode", Integer.valueOf(3)); response.put("errorDescription", "\"account\" not specified"); } else { try { Nxt.Account accountData = (Nxt.Account)accounts.get(Long.valueOf(parseUnsignedLong(account))); if (accountData == null) { response.put("errorCode", Integer.valueOf(5)); response.put("errorDescription", "Unknown account"); } else { long assetId; boolean assetIsNotUsed; try { assetId = parseUnsignedLong(req.getParameter("asset")); assetIsNotUsed = false; } catch (Exception e) { assetId = 0L; assetIsNotUsed = true; } JSONArray orderIds = new JSONArray(); for (Nxt.BidOrder bidOrder : bidOrders.values()) { if (((assetIsNotUsed) || (bidOrder.asset == assetId)) && (bidOrder.account == accountData)) { orderIds.add(convert(bidOrder.id)); } } response.put("bidOrderIds", orderIds); } } catch (Exception e) { response.put("errorCode", Integer.valueOf(4)); response.put("errorDescription", "Incorrect \"account\""); } } break; case 26: String order = req.getParameter("order"); if (order == null) { response.put("errorCode", Integer.valueOf(3)); response.put("errorDescription", "\"order\" not specified"); } else { try { Nxt.AskOrder orderData = (Nxt.AskOrder)askOrders.get(Long.valueOf(parseUnsignedLong(order))); if (orderData == null) { response.put("errorCode", Integer.valueOf(5)); response.put("errorDescription", "Unknown ask order"); } else { response.put("account", convert(orderData.account.id)); response.put("asset", convert(orderData.asset)); response.put("quantity", Integer.valueOf(orderData.quantity)); response.put("price", Long.valueOf(orderData.price)); } } catch (Exception e) { response.put("errorCode", Integer.valueOf(4)); response.put("errorDescription", "Incorrect \"order\""); } } break; case 27: JSONArray orderIds = new JSONArray(); for (Long orderId : askOrders.keySet()) { orderIds.add(convert(orderId.longValue())); } response.put("askOrderIds", orderIds); break; case 28: String order = req.getParameter("order"); if (order == null) { response.put("errorCode", Integer.valueOf(3)); response.put("errorDescription", "\"order\" not specified"); } else { try { Nxt.BidOrder orderData = (Nxt.BidOrder)bidOrders.get(Long.valueOf(parseUnsignedLong(order))); if (orderData == null) { response.put("errorCode", Integer.valueOf(5)); response.put("errorDescription", "Unknown bid order"); } else { response.put("account", convert(orderData.account.id)); response.put("asset", convert(orderData.asset)); response.put("quantity", Integer.valueOf(orderData.quantity)); response.put("price", Long.valueOf(orderData.price)); } } catch (Exception e) { response.put("errorCode", Integer.valueOf(4)); response.put("errorDescription", "Incorrect \"order\""); } } break; case 29: JSONArray orderIds = new JSONArray(); for (Long orderId : bidOrders.keySet()) { orderIds.add(convert(orderId.longValue())); } response.put("bidOrderIds", orderIds); break; case 30: String account = req.getParameter("account"); if (account == null) { response.put("errorCode", Integer.valueOf(3)); response.put("errorDescription", "\"account\" not specified"); } else { try { long accountId = parseUnsignedLong(account); Nxt.Account accountData = (Nxt.Account)accounts.get(Long.valueOf(accountId)); if (accountData == null) { response.put("errorCode", Integer.valueOf(5)); response.put("errorDescription", "Unknown account"); } else { JSONArray aliases = new JSONArray(); for (Nxt.Alias alias : aliases.values()) { if (alias.account.id == accountId) { JSONObject aliasData = new JSONObject(); aliasData.put("alias", alias.alias); aliasData.put("uri", alias.uri); aliases.add(aliasData); } } response.put("aliases", aliases); } } catch (Exception e) { response.put("errorCode", Integer.valueOf(4)); response.put("errorDescription", "Incorrect \"account\""); } } break; case 31: String secretPhrase = req.getParameter("secretPhrase"); String host = req.getParameter("host"); String weightValue = req.getParameter("weight"); String dateValue = req.getParameter("date"); if (secretPhrase == null) { response.put("errorCode", Integer.valueOf(3)); response.put("errorDescription", "\"secretPhrase\" not specified"); } else if (host == null) { response.put("errorCode", Integer.valueOf(3)); response.put("errorDescription", "\"host\" not specified"); } else if (weightValue == null) { response.put("errorCode", Integer.valueOf(3)); response.put("errorDescription", "\"weight\" not specified"); } else if (dateValue == null) { response.put("errorCode", Integer.valueOf(3)); response.put("errorDescription", "\"date\" not specified"); } else if (host.length() > 100) { response.put("errorCode", Integer.valueOf(4)); response.put("errorDescription", "Incorrect \"host\" (the length exceeds 100 chars limit)"); } else { try { int weight = Integer.parseInt(weightValue); if ((weight <= 0) || (weight > 1000000000L)) { throw new Exception(); } try { int date = Integer.parseInt(dateValue.substring(0, 4)) * 10000 + Integer.parseInt(dateValue.substring(5, 7)) * 100 + Integer.parseInt(dateValue.substring(8, 10)); byte[] publicKey = Nxt.Crypto.getPublicKey(secretPhrase); byte[] hostBytes = host.getBytes("UTF-8"); ByteBuffer buffer = ByteBuffer.allocate(34 + hostBytes.length + 4 + 4 + 1); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.put(publicKey); buffer.putShort((short)hostBytes.length); buffer.put(hostBytes); buffer.putInt(weight); buffer.putInt(date); byte[] data = buffer.array(); byte[] signature; do { data[(data.length - 1)] = ((byte)ThreadLocalRandom.current().nextInt()); signature = Nxt.Crypto.sign(data, secretPhrase); } while (!Nxt.Crypto.verify(signature, data, publicKey)); response.put("hallmark", convert(data) + convert(signature)); } catch (Exception e) { response.put("errorCode", Integer.valueOf(4)); response.put("errorDescription", "Incorrect \"date\""); } } catch (Exception e) { response.put("errorCode", Integer.valueOf(4)); response.put("errorDescription", "Incorrect \"weight\""); } } break; case 32: String secretPhrase = req.getParameter("secretPhrase"); String recipientValue = req.getParameter("recipient"); String messageValue = req.getParameter("message"); String feeValue = req.getParameter("fee"); String deadlineValue = req.getParameter("deadline"); String referencedTransactionValue = req.getParameter("referencedTransaction"); if (secretPhrase == null) { response.put("errorCode", Integer.valueOf(3)); response.put("errorDescription", "\"secretPhrase\" not specified"); } else if (recipientValue == null) { response.put("errorCode", Integer.valueOf(3)); response.put("errorDescription", "\"recipient\" not specified"); } else if (messageValue == null) { response.put("errorCode", Integer.valueOf(3)); response.put("errorDescription", "\"message\" not specified"); } else if (feeValue == null) { response.put("errorCode", Integer.valueOf(3)); response.put("errorDescription", "\"fee\" not specified"); } else if (deadlineValue == null) { response.put("errorCode", Integer.valueOf(3)); response.put("errorDescription", "\"deadline\" not specified"); } else { try { long recipient = parseUnsignedLong(recipientValue); try { byte[] message = convert(messageValue); if (message.length > 1000) { response.put("errorCode", Integer.valueOf(4)); response.put("errorDescription", "Incorrect \"message\" (length must be not longer than 1000 bytes)"); } else { try { int fee = Integer.parseInt(feeValue); if ((fee <= 0) || (fee >= 1000000000L)) { throw new Exception(); } try { short deadline = Short.parseShort(deadlineValue); if (deadline < 1) { throw new Exception(); } long referencedTransaction = referencedTransactionValue == null ? 0L : parseUnsignedLong(referencedTransactionValue); byte[] publicKey = Nxt.Crypto.getPublicKey(secretPhrase); Nxt.Account account = (Nxt.Account)accounts.get(Long.valueOf(Nxt.Account.getId(publicKey))); if ((account == null) || (fee * 100L > account.getUnconfirmedBalance())) { response.put("errorCode", Integer.valueOf(6)); response.put("errorDescription", "Not enough funds"); } else { int timestamp = getEpochTime(System.currentTimeMillis()); Nxt.Transaction transaction = new Nxt.Transaction((byte)1, (byte)0, timestamp, deadline, publicKey, recipient, 0, fee, referencedTransaction, new byte[64]); transaction.attachment = new Nxt.Transaction.MessagingArbitraryMessageAttachment(message); transaction.sign(secretPhrase); JSONObject peerRequest = new JSONObject(); peerRequest.put("requestType", "processTransactions"); JSONArray transactionsData = new JSONArray(); transactionsData.add(transaction.getJSONObject()); peerRequest.put("transactions", transactionsData); Nxt.Peer.sendToSomePeers(peerRequest); response.put("transaction", transaction.getStringId()); response.put("bytes", convert(transaction.getBytes())); nonBroadcastedTransactions.put(Long.valueOf(transaction.id), transaction); } } catch (Exception e) { response.put("errorCode", Integer.valueOf(4)); response.put("errorDescription", "Incorrect \"deadline\""); } } catch (Exception e) { response.put("errorCode", Integer.valueOf(4)); response.put("errorDescription", "Incorrect \"fee\""); } } } catch (Exception e) { response.put("errorCode", Integer.valueOf(4)); response.put("errorDescription", "Incorrect \"message\""); } } catch (Exception e) { response.put("errorCode", Integer.valueOf(4)); response.put("errorDescription", "Incorrect \"recipient\""); } } break; case 33: secretPhrase = req.getParameter("secretPhrase"); String recipientValue = req.getParameter("recipient"); String amountValue = req.getParameter("amount"); String feeValue = req.getParameter("fee"); String deadlineValue = req.getParameter("deadline"); String referencedTransactionValue = req.getParameter("referencedTransaction"); if (secretPhrase == null) { response.put("errorCode", Integer.valueOf(3)); response.put("errorDescription", "\"secretPhrase\" not specified"); } else if (recipientValue == null) { response.put("errorCode", Integer.valueOf(3)); response.put("errorDescription", "\"recipient\" not specified"); } else if (amountValue == null) { response.put("errorCode", Integer.valueOf(3)); response.put("errorDescription", "\"amount\" not specified"); } else if (feeValue == null) { response.put("errorCode", Integer.valueOf(3)); response.put("errorDescription", "\"fee\" not specified"); } else if (deadlineValue == null) { response.put("errorCode", Integer.valueOf(3)); response.put("errorDescription", "\"deadline\" not specified"); } else { try { long recipient = parseUnsignedLong(recipientValue); try { int amount = Integer.parseInt(amountValue); if ((amount <= 0) || (amount >= 1000000000L)) { throw new Exception(); } try { int fee = Integer.parseInt(feeValue); if ((fee <= 0) || (fee >= 1000000000L)) { throw new Exception(); } try { short deadline = Short.parseShort(deadlineValue); if (deadline < 1) { throw new Exception(); } long referencedTransaction = referencedTransactionValue == null ? 0L : parseUnsignedLong(referencedTransactionValue); byte[] publicKey = Nxt.Crypto.getPublicKey(secretPhrase); Nxt.Account account = (Nxt.Account)accounts.get(Long.valueOf(Nxt.Account.getId(publicKey))); if (account == null) { response.put("errorCode", Integer.valueOf(6)); response.put("errorDescription", "Not enough funds"); } else if ((amount + fee) * 100L > account.getUnconfirmedBalance()) { response.put("errorCode", Integer.valueOf(6)); response.put("errorDescription", "Not enough funds"); } else { Nxt.Transaction transaction = new Nxt.Transaction((byte)0, (byte)0, getEpochTime(System.currentTimeMillis()), deadline, publicKey, recipient, amount, fee, referencedTransaction, new byte[64]); transaction.sign(secretPhrase); JSONObject peerRequest = new JSONObject(); peerRequest.put("requestType", "processTransactions"); JSONArray transactionsData = new JSONArray(); transactionsData.add(transaction.getJSONObject()); peerRequest.put("transactions", transactionsData); Nxt.Peer.sendToSomePeers(peerRequest); response.put("transaction", transaction.getStringId()); response.put("bytes", convert(transaction.getBytes())); nonBroadcastedTransactions.put(Long.valueOf(transaction.id), transaction); } } catch (Exception e) { response.put("errorCode", Integer.valueOf(4)); response.put("errorDescription", "Incorrect \"deadline\""); } } catch (Exception e) { response.put("errorCode", Integer.valueOf(4)); response.put("errorDescription", "Incorrect \"fee\""); } } catch (Exception e) { response.put("errorCode", Integer.valueOf(4)); response.put("errorDescription", "Incorrect \"amount\""); } } catch (Exception e) { response.put("errorCode", Integer.valueOf(4)); response.put("errorDescription", "Incorrect \"recipient\""); } } break; default: response.put("errorCode", Integer.valueOf(1)); response.put("errorDescription", "Incorrect request"); } } } resp.setContentType("text/plain; charset=UTF-8"); Writer writer = resp.getWriter();Object localObject1 = null; try { response.writeJSONString(writer); } catch (Throwable localThrowable6) { localObject1 = localThrowable6;throw localThrowable6; } finally { if (writer != null) { if (localObject1 != null) { try { writer.close(); } catch (Throwable x2) { ((Throwable)localObject1).addSuppressed(x2); } } else { writer.close(); } } } return; } if ((allowedUserHosts != null) && (!allowedUserHosts.contains(req.getRemoteHost()))) { JSONObject response = new JSONObject(); response.put("response", "denyAccess"); ??? = new JSONArray(); ???.add(response); JSONObject combinedResponse = new JSONObject(); combinedResponse.put("responses", ???); resp.setContentType("text/plain; charset=UTF-8"); Object writer = resp.getWriter();secretPhrase = null; try { combinedResponse.writeJSONString((Writer)writer); } catch (Throwable localThrowable2) { secretPhrase = localThrowable2;throw localThrowable2; } finally { if (writer != null) { if (secretPhrase != null) { try { ((Writer)writer).close(); } catch (Throwable x2) { secretPhrase.addSuppressed(x2); } } else { ((Writer)writer).close(); } } } return; } user = (Nxt.User)users.get(userPasscode); if (user == null) { user = new Nxt.User(); ??? = (Nxt.User)users.putIfAbsent(userPasscode, user); if (??? != null) { user = ???; user.isInactive = false; } } else { user.isInactive = false; } int index; int index; int index; switch (req.getParameter("requestType")) { case "generateAuthorizationToken": String secretPhrase = req.getParameter("secretPhrase"); if (!user.secretPhrase.equals(secretPhrase)) { JSONObject response = new JSONObject(); response.put("response", "showMessage"); response.put("message", "Invalid secret phrase!"); user.pendingResponses.offer(response); } else { byte[] website = req.getParameter("website").trim().getBytes("UTF-8"); byte[] data = new byte[website.length + 32 + 4]; System.arraycopy(website, 0, data, 0, website.length); System.arraycopy(user.publicKey, 0, data, website.length, 32); int timestamp = getEpochTime(System.currentTimeMillis()); data[(website.length + 32)] = ((byte)timestamp); data[(website.length + 32 + 1)] = ((byte)(timestamp >> 8)); data[(website.length + 32 + 2)] = ((byte)(timestamp >> 16)); data[(website.length + 32 + 3)] = ((byte)(timestamp >> 24)); byte[] token = new byte[100]; System.arraycopy(data, website.length, token, 0, 36); System.arraycopy(Nxt.Crypto.sign(data, user.secretPhrase), 0, token, 36, 64); String tokenString = ""; for (int ptr = 0; ptr < 100; ptr += 5) { long number = token[ptr] & 0xFF | (token[(ptr + 1)] & 0xFF) << 8 | (token[(ptr + 2)] & 0xFF) << 16 | (token[(ptr + 3)] & 0xFF) << 24 | (token[(ptr + 4)] & 0xFF) << 32; if (number < 32L) { tokenString = tokenString + "0000000"; } else if (number < 1024L) { tokenString = tokenString + "000000"; } else if (number < 32768L) { tokenString = tokenString + "00000"; } else if (number < 1048576L) { tokenString = tokenString + "0000"; } else if (number < 33554432L) { tokenString = tokenString + "000"; } else if (number < 1073741824L) { tokenString = tokenString + "00"; } else if (number < 34359738368L) { tokenString = tokenString + "0"; } tokenString = tokenString + Long.toString(number, 32); } JSONObject response = new JSONObject(); response.put("response", "showAuthorizationToken"); response.put("token", tokenString); user.pendingResponses.offer(response); } break; case "getInitialData": JSONArray unconfirmedTransactions = new JSONArray(); JSONArray activePeers = new JSONArray();JSONArray knownPeers = new JSONArray();JSONArray blacklistedPeers = new JSONArray(); JSONArray recentBlocks = new JSONArray(); for (Nxt.Transaction transaction : unconfirmedTransactions.values()) { JSONObject unconfirmedTransaction = new JSONObject(); unconfirmedTransaction.put("index", Integer.valueOf(transaction.index)); unconfirmedTransaction.put("timestamp", Integer.valueOf(transaction.timestamp)); unconfirmedTransaction.put("deadline", Short.valueOf(transaction.deadline)); unconfirmedTransaction.put("recipient", convert(transaction.recipient)); unconfirmedTransaction.put("amount", Integer.valueOf(transaction.amount)); unconfirmedTransaction.put("fee", Integer.valueOf(transaction.fee)); unconfirmedTransaction.put("sender", convert(transaction.getSenderAccountId())); unconfirmedTransactions.add(unconfirmedTransaction); } for (Map.Entry<String, Nxt.Peer> peerEntry : peers.entrySet()) { String address = (String)peerEntry.getKey(); Nxt.Peer peer = (Nxt.Peer)peerEntry.getValue(); if (peer.blacklistingTime > 0L) { JSONObject blacklistedPeer = new JSONObject(); blacklistedPeer.put("index", Integer.valueOf(peer.index)); blacklistedPeer.put("announcedAddress", peer.announcedAddress.length() > 0 ? peer.announcedAddress : peer.announcedAddress.length() > 30 ? peer.announcedAddress.substring(0, 30) + "..." : address); for (String wellKnownPeer : wellKnownPeers) { if (peer.announcedAddress.equals(wellKnownPeer)) { blacklistedPeer.put("wellKnown", Boolean.valueOf(true)); break; } } blacklistedPeers.add(blacklistedPeer); } else if (peer.state == 0) { if (peer.announcedAddress.length() > 0) { JSONObject knownPeer = new JSONObject(); knownPeer.put("index", Integer.valueOf(peer.index)); knownPeer.put("announcedAddress", peer.announcedAddress.length() > 30 ? peer.announcedAddress.substring(0, 30) + "..." : peer.announcedAddress); for (String wellKnownPeer : wellKnownPeers) { if (peer.announcedAddress.equals(wellKnownPeer)) { knownPeer.put("wellKnown", Boolean.valueOf(true)); break; } } knownPeers.add(knownPeer); } } else { JSONObject activePeer = new JSONObject(); activePeer.put("index", Integer.valueOf(peer.index)); if (peer.state == 2) { activePeer.put("disconnected", Boolean.valueOf(true)); } activePeer.put("address", address.length() > 30 ? address.substring(0, 30) + "..." : address); activePeer.put("announcedAddress", peer.announcedAddress.length() > 30 ? peer.announcedAddress.substring(0, 30) + "..." : peer.announcedAddress); activePeer.put("weight", Integer.valueOf(peer.getWeight())); activePeer.put("downloaded", Long.valueOf(peer.downloadedVolume)); activePeer.put("uploaded", Long.valueOf(peer.uploadedVolume)); activePeer.put("software", peer.getSoftware()); for (String wellKnownPeer : wellKnownPeers) { if (peer.announcedAddress.equals(wellKnownPeer)) { activePeer.put("wellKnown", Boolean.valueOf(true)); break; } } activePeers.add(activePeer); } } long blockId = ((Nxt.Block)lastBlock.get()).getId(); int numberOfBlocks = 0; while (numberOfBlocks < 60) { numberOfBlocks++; Nxt.Block block = (Nxt.Block)blocks.get(Long.valueOf(blockId)); JSONObject recentBlock = new JSONObject(); recentBlock.put("index", Integer.valueOf(block.index)); recentBlock.put("timestamp", Integer.valueOf(block.timestamp)); recentBlock.put("numberOfTransactions", Integer.valueOf(block.transactions.length)); recentBlock.put("totalAmount", Integer.valueOf(block.totalAmount)); recentBlock.put("totalFee", Integer.valueOf(block.totalFee)); recentBlock.put("payloadLength", Integer.valueOf(block.payloadLength)); recentBlock.put("generator", convert(block.getGeneratorAccountId())); recentBlock.put("height", Integer.valueOf(block.height)); recentBlock.put("version", Integer.valueOf(block.version)); recentBlock.put("block", block.getStringId()); recentBlock.put("baseTarget", BigInteger.valueOf(block.baseTarget).multiply(BigInteger.valueOf(100000L)).divide(BigInteger.valueOf(153722867L))); recentBlocks.add(recentBlock); if (blockId == 2680262203532249785L) { break; } blockId = block.previousBlock; } JSONObject response = new JSONObject(); response.put("response", "processInitialData"); response.put("version", "0.5.10"); if (unconfirmedTransactions.size() > 0) { response.put("unconfirmedTransactions", unconfirmedTransactions); } if (activePeers.size() > 0) { response.put("activePeers", activePeers); } if (knownPeers.size() > 0) { response.put("knownPeers", knownPeers); } if (blacklistedPeers.size() > 0) { response.put("blacklistedPeers", blacklistedPeers); } if (recentBlocks.size() > 0) { response.put("recentBlocks", recentBlocks); } user.pendingResponses.offer(response); break; case "getNewData": break; case "lockAccount": user.deinitializeKeyPair(); JSONObject response = new JSONObject(); response.put("response", "lockAccount"); user.pendingResponses.offer(response); break; case "removeActivePeer": if ((allowedUserHosts == null) && (!InetAddress.getByName(req.getRemoteAddr()).isLoopbackAddress())) { JSONObject response = new JSONObject(); response.put("response", "showMessage"); response.put("message", "This operation is allowed to local host users only!"); user.pendingResponses.offer(response); } else { index = Integer.parseInt(req.getParameter("peer")); for (Nxt.Peer peer : peers.values()) { if (peer.index == index) { if ((peer.blacklistingTime != 0L) || (peer.state == 0)) { break; } peer.deactivate(); break; } } } break; case "removeBlacklistedPeer": if ((allowedUserHosts == null) && (!InetAddress.getByName(req.getRemoteAddr()).isLoopbackAddress())) { JSONObject response = new JSONObject(); response.put("response", "showMessage"); response.put("message", "This operation is allowed to local host users only!"); user.pendingResponses.offer(response); } else { index = Integer.parseInt(req.getParameter("peer")); for (Nxt.Peer peer : peers.values()) { if (peer.index == index) { if (peer.blacklistingTime <= 0L) { break; } peer.removeBlacklistedStatus(); break; } } } break; case "removeKnownPeer": if ((allowedUserHosts == null) && (!InetAddress.getByName(req.getRemoteAddr()).isLoopbackAddress())) { JSONObject response = new JSONObject(); response.put("response", "showMessage"); response.put("message", "This operation is allowed to local host users only!"); user.pendingResponses.offer(response); } else { index = Integer.parseInt(req.getParameter("peer")); for (Nxt.Peer peer : peers.values()) { if (peer.index == index) { peer.removePeer(); break; } } } break; case "sendMoney": if (user.secretPhrase != null) { String recipientValue = req.getParameter("recipient");String amountValue = req.getParameter("amount");String feeValue = req.getParameter("fee");String deadlineValue = req.getParameter("deadline"); String secretPhrase = req.getParameter("secretPhrase"); int amount = 0;int fee = 0; short deadline = 0; long recipient; try { recipient = parseUnsignedLong(recipientValue); amount = Integer.parseInt(amountValue.trim()); fee = Integer.parseInt(feeValue.trim()); deadline = (short)(int)(Double.parseDouble(deadlineValue) * 60.0D); } catch (Exception e) { JSONObject response = new JSONObject(); response.put("response", "notifyOfIncorrectTransaction"); response.put("message", "One of the fields is filled incorrectly!"); response.put("recipient", recipientValue); response.put("amount", amountValue); response.put("fee", feeValue); response.put("deadline", deadlineValue); user.pendingResponses.offer(response); break; } if (!user.secretPhrase.equals(secretPhrase)) { JSONObject response = new JSONObject(); response.put("response", "notifyOfIncorrectTransaction"); response.put("message", "Wrong secret phrase!"); response.put("recipient", recipientValue); response.put("amount", amountValue); response.put("fee", feeValue); response.put("deadline", deadlineValue); user.pendingResponses.offer(response); } else if ((amount <= 0) || (amount > 1000000000L)) { JSONObject response = new JSONObject(); response.put("response", "notifyOfIncorrectTransaction"); response.put("message", "\"Amount\" must be greater than 0!"); response.put("recipient", recipientValue); response.put("amount", amountValue); response.put("fee", feeValue); response.put("deadline", deadlineValue); user.pendingResponses.offer(response); } else if ((fee <= 0) || (fee > 1000000000L)) { JSONObject response = new JSONObject(); response.put("response", "notifyOfIncorrectTransaction"); response.put("message", "\"Fee\" must be greater than 0!"); response.put("recipient", recipientValue); response.put("amount", amountValue); response.put("fee", feeValue); response.put("deadline", deadlineValue); user.pendingResponses.offer(response); } else if (deadline < 1) { JSONObject response = new JSONObject(); response.put("response", "notifyOfIncorrectTransaction"); response.put("message", "\"Deadline\" must be greater or equal to 1 minute!"); response.put("recipient", recipientValue); response.put("amount", amountValue); response.put("fee", feeValue); response.put("deadline", deadlineValue); user.pendingResponses.offer(response); } else { Nxt.Account account = (Nxt.Account)accounts.get(Long.valueOf(Nxt.Account.getId(user.publicKey))); if ((account == null) || ((amount + fee) * 100L > account.getUnconfirmedBalance())) { JSONObject response = new JSONObject(); response.put("response", "notifyOfIncorrectTransaction"); response.put("message", "Not enough funds!"); response.put("recipient", recipientValue); response.put("amount", amountValue); response.put("fee", feeValue); response.put("deadline", deadlineValue); user.pendingResponses.offer(response); } else { Nxt.Transaction transaction = new Nxt.Transaction((byte)0, (byte)0, getEpochTime(System.currentTimeMillis()), deadline, user.publicKey, recipient, amount, fee, 0L, new byte[64]); transaction.sign(user.secretPhrase); JSONObject peerRequest = new JSONObject(); peerRequest.put("requestType", "processTransactions"); JSONArray transactionsData = new JSONArray(); transactionsData.add(transaction.getJSONObject()); peerRequest.put("transactions", transactionsData); Nxt.Peer.sendToSomePeers(peerRequest); JSONObject response = new JSONObject(); response.put("response", "notifyOfAcceptedTransaction"); user.pendingResponses.offer(response); nonBroadcastedTransactions.put(Long.valueOf(transaction.id), transaction); } } } break; case "unlockAccount": String secretPhrase = req.getParameter("secretPhrase"); for (Nxt.User u : users.values()) { if (secretPhrase.equals(u.secretPhrase)) { u.deinitializeKeyPair(); if (!u.isInactive) { JSONObject response = new JSONObject(); response.put("response", "lockAccount"); u.pendingResponses.offer(response); } } } BigInteger bigInt = user.initializeKeyPair(secretPhrase); accountId = bigInt.longValue(); JSONObject response = new JSONObject(); response.put("response", "unlockAccount"); response.put("account", bigInt.toString()); if (secretPhrase.length() < 30) { response.put("secretPhraseStrength", Integer.valueOf(1)); } else { response.put("secretPhraseStrength", Integer.valueOf(5)); } Nxt.Account account = (Nxt.Account)accounts.get(Long.valueOf(accountId)); if (account == null) { response.put("balance", Integer.valueOf(0)); } else { response.put("balance", Long.valueOf(account.getUnconfirmedBalance())); long effectiveBalance = account.getEffectiveBalance(); if (effectiveBalance > 0L) { JSONObject response2 = new JSONObject(); response2.put("response", "setBlockGenerationDeadline"); Nxt.Block lastBlock = (Nxt.Block)lastBlock.get(); MessageDigest digest = getMessageDigest("SHA-256"); byte[] generationSignatureHash; byte[] generationSignatureHash; if (lastBlock.height < 30000) { byte[] generationSignature = Nxt.Crypto.sign(lastBlock.generationSignature, user.secretPhrase); generationSignatureHash = digest.digest(generationSignature); } else { digest.update(lastBlock.generationSignature); generationSignatureHash = digest.digest(user.publicKey); } BigInteger hit = new BigInteger(1, new byte[] { generationSignatureHash[7], generationSignatureHash[6], generationSignatureHash[5], generationSignatureHash[4], generationSignatureHash[3], generationSignatureHash[2], generationSignatureHash[1], generationSignatureHash[0] }); response2.put("deadline", Long.valueOf(hit.divide(BigInteger.valueOf(lastBlock.baseTarget).multiply(BigInteger.valueOf(effectiveBalance))).longValue() - (getEpochTime(System.currentTimeMillis()) - lastBlock.timestamp))); user.pendingResponses.offer(response2); } JSONArray myTransactions = new JSONArray(); byte[] accountPublicKey = (byte[])account.publicKey.get(); for (Nxt.Transaction transaction : unconfirmedTransactions.values()) { if (Arrays.equals(transaction.senderPublicKey, accountPublicKey)) { JSONObject myTransaction = new JSONObject(); myTransaction.put("index", Integer.valueOf(transaction.index)); myTransaction.put("transactionTimestamp", Integer.valueOf(transaction.timestamp)); myTransaction.put("deadline", Short.valueOf(transaction.deadline)); myTransaction.put("account", convert(transaction.recipient)); myTransaction.put("sentAmount", Integer.valueOf(transaction.amount)); if (transaction.recipient == accountId) { myTransaction.put("receivedAmount", Integer.valueOf(transaction.amount)); } myTransaction.put("fee", Integer.valueOf(transaction.fee)); myTransaction.put("numberOfConfirmations", Integer.valueOf(0)); myTransaction.put("id", transaction.getStringId()); myTransactions.add(myTransaction); } else if (transaction.recipient == accountId) { JSONObject myTransaction = new JSONObject(); myTransaction.put("index", Integer.valueOf(transaction.index)); myTransaction.put("transactionTimestamp", Integer.valueOf(transaction.timestamp)); myTransaction.put("deadline", Short.valueOf(transaction.deadline)); myTransaction.put("account", convert(transaction.getSenderAccountId())); myTransaction.put("receivedAmount", Integer.valueOf(transaction.amount)); myTransaction.put("fee", Integer.valueOf(transaction.fee)); myTransaction.put("numberOfConfirmations", Integer.valueOf(0)); myTransaction.put("id", transaction.getStringId()); myTransactions.add(myTransaction); } } long blockId = ((Nxt.Block)lastBlock.get()).getId(); int numberOfConfirmations = 1; while (myTransactions.size() < 1000) { Nxt.Block block = (Nxt.Block)blocks.get(Long.valueOf(blockId)); if ((block.totalFee > 0) && (Arrays.equals(block.generatorPublicKey, accountPublicKey))) { JSONObject myTransaction = new JSONObject(); myTransaction.put("index", block.getStringId()); myTransaction.put("blockTimestamp", Integer.valueOf(block.timestamp)); myTransaction.put("block", block.getStringId()); myTransaction.put("earnedAmount", Integer.valueOf(block.totalFee)); myTransaction.put("numberOfConfirmations", Integer.valueOf(numberOfConfirmations)); myTransaction.put("id", "-"); myTransactions.add(myTransaction); } for (Nxt.Transaction transaction : block.blockTransactions) { if (Arrays.equals(transaction.senderPublicKey, accountPublicKey)) { JSONObject myTransaction = new JSONObject(); myTransaction.put("index", Integer.valueOf(transaction.index)); myTransaction.put("blockTimestamp", Integer.valueOf(block.timestamp)); myTransaction.put("transactionTimestamp", Integer.valueOf(transaction.timestamp)); myTransaction.put("account", convert(transaction.recipient)); myTransaction.put("sentAmount", Integer.valueOf(transaction.amount)); if (transaction.recipient == accountId) { myTransaction.put("receivedAmount", Integer.valueOf(transaction.amount)); } myTransaction.put("fee", Integer.valueOf(transaction.fee)); myTransaction.put("numberOfConfirmations", Integer.valueOf(numberOfConfirmations)); myTransaction.put("id", transaction.getStringId()); myTransactions.add(myTransaction); } else if (transaction.recipient == accountId) { JSONObject myTransaction = new JSONObject(); myTransaction.put("index", Integer.valueOf(transaction.index)); myTransaction.put("blockTimestamp", Integer.valueOf(block.timestamp)); myTransaction.put("transactionTimestamp", Integer.valueOf(transaction.timestamp)); myTransaction.put("account", convert(transaction.getSenderAccountId())); myTransaction.put("receivedAmount", Integer.valueOf(transaction.amount)); myTransaction.put("fee", Integer.valueOf(transaction.fee)); myTransaction.put("numberOfConfirmations", Integer.valueOf(numberOfConfirmations)); myTransaction.put("id", transaction.getStringId()); myTransactions.add(myTransaction); } } if (blockId == 2680262203532249785L) { break; } blockId = block.previousBlock; numberOfConfirmations++; } if (myTransactions.size() > 0) { JSONObject response2 = new JSONObject(); response2.put("response", "processNewData"); response2.put("addedMyTransactions", myTransactions); user.pendingResponses.offer(response2); } } user.pendingResponses.offer(response); break; default: JSONObject response = new JSONObject(); response.put("response", "showMessage"); response.put("message", "Incorrect request!"); user.pendingResponses.offer(response); } } catch (Exception e) { if (user != null) { logMessage("Error processing GET request", e); JSONObject response = new JSONObject(); response.put("response", "showMessage"); response.put("message", e.toString()); user.pendingResponses.offer(response); } else { logDebugMessage("Error processing GET request", e); } } if (user != null) { synchronized (user) { JSONArray responses = new JSONArray(); JSONObject pendingResponse; while ((pendingResponse = (JSONObject)user.pendingResponses.poll()) != null) { responses.add(pendingResponse); } Object writer; if (responses.size() > 0) { JSONObject combinedResponse = new JSONObject(); combinedResponse.put("responses", responses); if (user.asyncContext != null) { user.asyncContext.getResponse().setContentType("text/plain; charset=UTF-8"); Object writer = user.asyncContext.getResponse().getWriter();accountId = null; try { combinedResponse.writeJSONString((Writer)writer); } catch (Throwable localThrowable3) { accountId = localThrowable3;throw localThrowable3; } finally { if (writer != null) { if (accountId != null) { try { ((Writer)writer).close(); } catch (Throwable x2) { accountId.addSuppressed(x2); } } else { ((Writer)writer).close(); } } } user.asyncContext.complete(); user.asyncContext = req.startAsync(); user.asyncContext.addListener(new Nxt.UserAsyncListener(user)); user.asyncContext.setTimeout(5000L); } else { resp.setContentType("text/plain; charset=UTF-8"); writer = resp.getWriter();accountId = null; try { combinedResponse.writeJSONString((Writer)writer); } catch (Throwable localThrowable4) { accountId = localThrowable4;throw localThrowable4; } finally { if (writer != null) { if (accountId != null) { try { ((Writer)writer).close(); } catch (Throwable x2) { accountId.addSuppressed(x2); } } else { ((Writer)writer).close(); } } } } } else { if (user.asyncContext != null) { user.asyncContext.getResponse().setContentType("text/plain; charset=UTF-8"); Object writer = user.asyncContext.getResponse().getWriter();writer = null; try { new JSONObject().writeJSONString((Writer)writer); } catch (Throwable localThrowable5) { writer = localThrowable5;throw localThrowable5; } finally { if (writer != null) { if (writer != null) { try { ((Writer)writer).close(); } catch (Throwable x2) { ((Throwable)writer).addSuppressed(x2); } } else { ((Writer)writer).close(); } } } user.asyncContext.complete(); } user.asyncContext = req.startAsync(); user.asyncContext.addListener(new Nxt.UserAsyncListener(user)); user.asyncContext.setTimeout(5000L); } } } } public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Nxt.Peer peer = null; JSONObject response = new JSONObject(); try { ??? = new Nxt.CountingInputStream(req.getInputStream()); ??? = new BufferedReader(new InputStreamReader(???, "UTF-8"));Throwable localThrowable3 = null; JSONObject request; try { request = (JSONObject)JSONValue.parse(???); } catch (Throwable localThrowable1) { localThrowable3 = localThrowable1;throw localThrowable1; } finally { if (??? != null) { if (localThrowable3 != null) { try { ???.close(); } catch (Throwable x2) { localThrowable3.addSuppressed(x2); } } else { ???.close(); } } } if (request == null) { return; } peer = Nxt.Peer.addPeer(req.getRemoteHost(), ""); if (peer != null) { if (peer.state == 2) { peer.setState(1); } peer.updateDownloadedVolume(???.getCount()); } if ((request.get("protocol") != null) && (((Number)request.get("protocol")).intValue() == 1)) { switch ((String)request.get("requestType")) { case "getCumulativeDifficulty": response.put("cumulativeDifficulty", ((Nxt.Block)lastBlock.get()).cumulativeDifficulty.toString()); break; case "getInfo": if (peer != null) { String announcedAddress = (String)request.get("announcedAddress"); if (announcedAddress != null) { announcedAddress = announcedAddress.trim(); if (announcedAddress.length() > 0) { peer.announcedAddress = announcedAddress; } } String application = (String)request.get("application"); if (application == null) { application = "?"; } else { application = application.trim(); if (application.length() > 20) { application = application.substring(0, 20) + "..."; } } peer.application = application; String version = (String)request.get("version"); if (version == null) { version = "?"; } else { version = version.trim(); if (version.length() > 10) { version = version.substring(0, 10) + "..."; } } peer.version = version; String platform = (String)request.get("platform"); if (platform == null) { platform = "?"; } else { platform = platform.trim(); if (platform.length() > 10) { platform = platform.substring(0, 10) + "..."; } } peer.platform = platform; peer.shareAddress = Boolean.TRUE.equals(request.get("shareAddress")); if (peer.analyzeHallmark(req.getRemoteHost(), (String)request.get("hallmark"))) { peer.setState(1); } } if ((myHallmark != null) && (myHallmark.length() > 0)) { response.put("hallmark", myHallmark); } response.put("application", "NRS"); response.put("version", "0.5.10"); response.put("platform", myPlatform); response.put("shareAddress", Boolean.valueOf(shareMyAddress)); break; case "getMilestoneBlockIds": JSONArray milestoneBlockIds = new JSONArray(); Nxt.Block block = (Nxt.Block)lastBlock.get(); int jumpLength = block.height * 4 / 1461 + 1; for (; block.height > 0; goto 1017) { milestoneBlockIds.add(block.getStringId()); int i = 0; if ((i < jumpLength) && (block.height > 0)) { block = (Nxt.Block)blocks.get(Long.valueOf(block.previousBlock));i++; } } response.put("milestoneBlockIds", milestoneBlockIds); break; case "getNextBlockIds": JSONArray nextBlockIds = new JSONArray(); Nxt.Block block = (Nxt.Block)blocks.get(Long.valueOf(parseUnsignedLong((String)request.get("blockId")))); while ((block != null) && (nextBlockIds.size() < 1440)) { block = (Nxt.Block)blocks.get(Long.valueOf(block.nextBlock)); if (block != null) { nextBlockIds.add(block.getStringId()); } } response.put("nextBlockIds", nextBlockIds); break; case "getNextBlocks": Object nextBlocks = new ArrayList(); int totalLength = 0; Nxt.Block block = (Nxt.Block)blocks.get(Long.valueOf(parseUnsignedLong((String)request.get("blockId")))); while (block != null) { block = (Nxt.Block)blocks.get(Long.valueOf(block.nextBlock)); if (block != null) { int length = 224 + block.payloadLength; if (totalLength + length > 1048576) { break; } ((List)nextBlocks).add(block); totalLength += length; } } JSONArray nextBlocksArray = new JSONArray(); for (Nxt.Block nextBlock : (List)nextBlocks) { nextBlocksArray.add(nextBlock.getJSONStreamAware()); } response.put("nextBlocks", nextBlocksArray); break; case "getPeers": JSONArray peers = new JSONArray(); for (Nxt.Peer otherPeer : peers.values()) { if ((otherPeer.blacklistingTime == 0L) && (otherPeer.announcedAddress.length() > 0) && (otherPeer.state == 1) && (otherPeer.shareAddress)) { peers.add(otherPeer.announcedAddress); } } response.put("peers", peers); break; case "getUnconfirmedTransactions": JSONArray transactionsData = new JSONArray(); for (Nxt.Transaction transaction : unconfirmedTransactions.values()) { transactionsData.add(transaction.getJSONObject()); } response.put("unconfirmedTransactions", transactionsData); break; case "processBlock": Nxt.Block block = Nxt.Block.getBlock(request); boolean accepted; if (block == null) { boolean accepted = false; if (peer != null) { peer.blacklist(); } } else { ByteBuffer buffer = ByteBuffer.allocate(224 + block.payloadLength); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.put(block.getBytes()); JSONArray transactionsData = (JSONArray)request.get("transactions"); for (Object transaction : transactionsData) { buffer.put(Nxt.Transaction.getTransaction((JSONObject)transaction).getBytes()); } accepted = Nxt.Block.pushBlock(buffer, true); } response.put("accepted", Boolean.valueOf(accepted)); break; case "processTransactions": Nxt.Transaction.processTransactions(request, "transactions"); break; default: response.put("error", "Unsupported request type!"); } } else { logDebugMessage("Unsupported protocol " + request.get("protocol")); response.put("error", "Unsupported protocol!"); } } catch (RuntimeException e) { logDebugMessage("Error processing POST request", e); response.put("error", e.toString()); } resp.setContentType("text/plain; charset=UTF-8"); Nxt.CountingOutputStream cos = new Nxt.CountingOutputStream(resp.getOutputStream()); Writer writer = new BufferedWriter(new OutputStreamWriter(cos, "UTF-8"));??? = null; try { response.writeJSONString(writer); } catch (Throwable localThrowable4) { ??? = localThrowable4;throw localThrowable4; } finally { if (writer != null) { if (??? != null) { try { writer.close(); } catch (Throwable x2) { ???.addSuppressed(x2); } } else { writer.close(); } } } if (peer != null) { peer.updateUploadedVolume(cos.getCount()); } } static class CountingOutputStream extends FilterOutputStream { private long count; public CountingOutputStream(OutputStream out) { super(); } public void write(int b) throws IOException { this.count += 1L; super.write(b); } public long getCount() { return this.count; } } static class CountingInputStream extends FilterInputStream { private long count; public CountingInputStream(InputStream in) { super(); } public int read() throws IOException { int read = super.read(); if (read >= 0) { this.count += 1L; } return read; } public int read(byte[] b, int off, int len) throws IOException { int read = super.read(b, off, len); if (read >= 0) { this.count += 1L; } return read; } public long skip(long n) throws IOException { long skipped = super.skip(n); if (skipped >= 0L) { this.count += skipped; } return skipped; } public long getCount() { return this.count; } } public void destroy() { shutdownExecutor(scheduledThreadPool); shutdownExecutor(sendToPeersService); try { Nxt.Block.saveBlocks("blocks.nxt", true); logMessage("Saved blocks.nxt"); } catch (RuntimeException e) { logMessage("Error saving blocks", e); } try { Nxt.Transaction.saveTransactions("transactions.nxt"); logMessage("Saved transactions.nxt"); } catch (RuntimeException e) { logMessage("Error saving transactions", e); } logMessage("NRS 0.5.10 stopped."); } private static void shutdownExecutor(ExecutorService executor) { executor.shutdown(); try { executor.awaitTermination(10L, TimeUnit.SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } if (!executor.isTerminated()) { logMessage("some threads didn't terminate, forcing shutdown"); executor.shutdownNow(); } } }
package pl.shockah.godwit.asset; import com.badlogic.gdx.assets.AssetLoaderParameters; import com.badlogic.gdx.assets.AssetManager; import javax.annotation.Nonnull; import javax.annotation.Nullable; import pl.shockah.godwit.Godwit; public class Asset<T> { @Nonnull public final String fileName; @Nonnull public final Class<T> clazz; @Nullable public final AssetLoaderParameters<T> parameters; public Asset(@Nonnull String fileName, @Nonnull Class<T> clazz) { this(fileName, clazz, null); } public Asset(@Nonnull String fileName, @Nonnull Class<T> clazz, @Nullable AssetLoaderParameters<T> parameters) { this.fileName = fileName; this.clazz = clazz; this.parameters = parameters; } protected static AssetManager getAssetManager() { return Godwit.getInstance().assetManager; } public void load() { getAssetManager().load(fileName, clazz, parameters); } public void unload() { getAssetManager().unload(fileName); } public void finishLoading() { AssetManager manager = getAssetManager(); if (manager.isLoaded(fileName, clazz)) return; manager.finishLoadingAsset(fileName); } public T get() { finishLoading(); return getAssetManager().get(fileName, clazz); } }
package org.eddy; import org.assertj.core.util.Lists; import org.eddy.classLoader.Some; import org.junit.Test; import javax.script.*; import java.util.*; public class JsTest { @Test public void test() throws ScriptException { ScriptEngineManager engineManager = new ScriptEngineManager(); ScriptEngine scriptEngine = engineManager.getEngineByName("javascript"); Bindings bindings = scriptEngine.createBindings(); List<Some> arg = new ArrayList<>(); arg.add(new Some()); Map<String, List<Some>> maps = new HashMap<>(); maps.put("key", arg); bindings.put("i", 1L); bindings.put("arr", arg); bindings.put("map", maps); // Object object = scriptEngine.eval("function f(){return i + 1} function fx(){return arr[0]} f(); fx();", bindings); //function f(){for(var s in map.keySet()){return s;}} // Object object2 = scriptEngine.eval("function f(){return map.get('key')[0]} f(); ", bindings); Object object2 = scriptEngine.eval("function f(){return map.keySet().toArray()[0]} f(); ", bindings); System.out.println(object2); } }
package wombat.util.files; import java.awt.Component; import java.awt.FileDialog; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.io.*; import java.net.InetAddress; import java.util.*; import javax.swing.JOptionPane; import javax.swing.text.BadLocationException; import javax.swing.undo.CannotRedoException; import javax.swing.undo.CannotUndoException; import wombat.gui.frames.FindReplaceDialog; import wombat.gui.frames.MainFrame; import wombat.gui.text.SchemeTextArea; import wombat.gui.text.sta.SharedTextArea; import wombat.util.Options; import wombat.util.errors.ErrorManager; import net.infonode.docking.*; import net.infonode.docking.util.*; /** * Manage open documents. */ public final class DocumentManager implements FocusListener { static DocumentManager me; // Next file to create. int lastIndex; // GUI references. MainFrame Main; RootWindow Root; TabWindow Documents; StringViewMap Views = new StringViewMap(); // Active documents. List<SchemeTextArea> allDocuments; SchemeTextArea activeDocument; // Hide constructor. private DocumentManager() {} /** * Manage documents. * * @param main The main frame. * @param root The root window (for splitting when strange things happen). * @param views View map (holds all of the documents). * @param documents Document tab manager (holds open documents at first). */ public static DocumentManager init(MainFrame main, RootWindow root, StringViewMap views, TabWindow documents) { if (me == null) { me = new DocumentManager(); me.lastIndex = 0; me.Main = main; me.Root = root; me.Views = views; me.Documents = documents; me.allDocuments = new ArrayList<SchemeTextArea>(); } return me; } /** * Create a new document. */ public static boolean New() { if (me == null) throw new RuntimeException("Document manager not initialized."); // Create the document ID. me.lastIndex++; String id = "document-" + me.lastIndex; // Create the actual document and add it to the GUI. SchemeTextArea ss = new SchemeTextArea(true, true); me.allDocuments.add(ss); ss.code.addFocusListener(me); me.Views.addView(id, new View("<new document>", null, ss)); ss.myView = me.Views.getView(id); ss.myView.addListener(new ViewCloseListener(ss)); me.Documents.addTab(me.Views.getView(id)); // If everything is set up correctly, make sure that the document correctly displays. // This fixes issues with closing all of the documents then making a new one. if (me.Root != null && !me.Documents.isShowing()) me.Root.setWindow(new SplitWindow(false, 0.6f, me.Documents, me.Root.getWindow())); // Focus the new window. ss.code.requestFocusInWindow(); me.activeDocument = ss; return true; } /** * Load a file from a dialog. * @return If the load worked. */ public static boolean Open() { if (me == null) throw new RuntimeException("Document manager not initialized."); // Choose a file. FileDialog fc = new FileDialog(me.Main, "Open...", FileDialog.LOAD); fc.setVisible(true); if (fc.getFile() == null) return false; // Sanity check. File file = new File(fc.getDirectory(), fc.getFile()); if (!file.exists()) { ErrorManager.logError("Unable to load file (does not exist): " + fc.getFile()); return false; } // Actually open it. return Open(file); } /** * Load a specific file. * @param file The file to load. * @return If the load worked. */ public static boolean Open(File file) { if (me == null) throw new RuntimeException("Document manager not initialized."); // Check if the document was already opened, it it was use that one. for (SchemeTextArea ss : me.allDocuments) { if (ss.myFile != null && ss.myFile.equals(file)) { for (int i = 0; i < me.Documents.getChildWindowCount(); i++) { if (me.Documents.getChildWindow(i).equals(ss.myView)) { me.Documents.setSelectedTab(i); ss.code.requestFocusInWindow(); return true; } } } } // Otherwise, load the document. me.lastIndex++; // Generate an internal ID for it. String id = "document-" + me.lastIndex; String filename = file.getName(); // Try to load it. try { // Opened files that no longer exist, just make a new one. if (!file.exists()) file.createNewFile(); // Create the text area and add it to the GUI. SchemeTextArea ss = new SchemeTextArea(file, true, true); me.allDocuments.add(ss); ss.myFile = file; ss.code.addFocusListener(me); me.Views.addView(id, new View(filename, null, ss)); ss.myView = me.Views.getView(id); ss.myView.addListener(new ViewCloseListener(ss)); me.Documents.addTab(me.Views.getView(id)); // Sanity check for if we closed all of the documents and want a new one. if (me.Root != null && !me.Documents.isShowing()) me.Root.setWindow(new SplitWindow(false, 0.6f, me.Documents, me.Root.getWindow())); // If there is an empty <new document> open, replace that one. if (me.activeDocument != null && me.activeDocument.isEmpty() && me.activeDocument.myFile == null && me.activeDocument.myView != null && "<new document>".equals(me.activeDocument.myView.getTitle())) { me.activeDocument.close(); } // Finally, focus on the new one. ss.code.requestFocusInWindow(); me.activeDocument = ss; // Add it to the document manager. RecentDocumentManager.addFile(file); // It worked. return true; } catch(IOException ex) { ErrorManager.logError("Unable to load file (" + file.getName() + "): " + ex.getMessage()); return false; } } /** * Save the current file. * @return If the save worked. */ public static boolean Save() { if (me == null) throw new RuntimeException("Document manager not initialized."); if (!verifyActiveDocument()) return false; if (me.activeDocument.myFile == null) return SaveAs(); try { me.activeDocument.save(); RecentDocumentManager.addFile(me.activeDocument.myFile); return true; } catch(FileNotFoundException ex) { return false; } catch(IOException ex) { return false; } } /** * Save the active file with a new name. * @return If it worked. */ public static boolean SaveAs() { if (me == null) throw new RuntimeException("Document manager not initialized."); if (!verifyActiveDocument()) return false; FileDialog fc = new FileDialog(me.Main, "Save as...", FileDialog.SAVE); fc.setVisible(true); if (fc.getFile() == null) return false; File file = new File(fc.getDirectory(), fc.getFile()); me.activeDocument.myFile = file; if (me.activeDocument instanceof SharedTextArea && ((SharedTextArea) me.activeDocument).isShared()) { String docName = ((SharedTextArea) me.activeDocument).getDocumentName(); me.activeDocument.myView.getViewProperties().setTitle(file.getName() + " (" + docName + ")"); } else { me.activeDocument.myView.getViewProperties().setTitle(file.getName()); } return Save(); } /** * Close the active document. * @return If it worked. */ public static boolean Close(boolean force) { if (me == null) throw new RuntimeException("Document manager not initialized."); if (verifyActiveDocument()) return false; if (!me.activeDocument.isEmpty()) { String name = me.activeDocument.myView.getViewProperties().getTitle(); if (me.activeDocument.isDirty()) { if (Options.ConfirmOnClose) { int result = JOptionPane.showConfirmDialog( me.activeDocument, "Save " + name + " before closing?\n\n(If you select no, any unsaved work will be lost.)", "Close...", (force ? JOptionPane.YES_NO_OPTION : JOptionPane.YES_NO_CANCEL_OPTION)); if (result == JOptionPane.YES_OPTION){ if (!Save()) return false; } else if (result == JOptionPane.CANCEL_OPTION) { return false; } } else { Save(); } } } // Close it. int i = me.allDocuments.indexOf(me.activeDocument); me.allDocuments.remove(me.activeDocument); me.activeDocument.close(); me.activeDocument.myView.close(); // Get a new active document. try { me.activeDocument = me.allDocuments.get(Math.max(0, i - 1)); me.activeDocument.requestFocusInWindow(); } catch(Exception e) { throw e; } return true; } /** * Close all documents. * @return If it worked. */ public static boolean CloseAll() { if (me == null) throw new RuntimeException("Document manager not initialized."); boolean closedAll = true; while (verifyActiveDocument() && closedAll) { me.activeDocument = me.allDocuments.get(0); closedAll &= Close(true); } return closedAll; } /** * Reload all documents (to update formatting). * @return If it worked. */ public static boolean ReloadAll() { if (me == null) throw new RuntimeException("Document manager not initialized."); for (SchemeTextArea ss : me.allDocuments) ss.refresh(); return me.Main.updateDisplay(); } /** * Run the active document. * @return If it worked. */ public static boolean Run() { if (me == null) throw new RuntimeException("Document manager not initialized."); if (!verifyActiveDocument()) return false; // TODO: DEBUG System.err.println("active: " + me.activeDocument); System.err.println("all (" + me.allDocuments.size() + "): " + me.allDocuments); String name = me.activeDocument.myView.getViewProperties().getTitle(); if (me.activeDocument.myFile == null || me.activeDocument.isDirty()) { if (Options.ConfirmOnRun) { if (JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog( me.activeDocument, "Save " + name + " before running?\n\n(You must save your code to run it.)", "Save...", JOptionPane.YES_NO_OPTION)) { if (!Save()) return false; } else { return false; } } else { if (!Save()) return false; } } try { me.Main.doCommand("(load \"" + me.activeDocument.myFile.getCanonicalPath().replace("\\", "/") + "\")"); me.Main.focusREPL(); } catch (IOException e) { e.printStackTrace(); } return true; } /** * Check that the active document is really active and that we haven't removed it. * @return True if we have a valid active document. */ private static boolean verifyActiveDocument() { if (!me.allDocuments.contains(me.activeDocument)) me.activeDocument = null; if (me.allDocuments.isEmpty()) return false; if (me.activeDocument == null) { me.activeDocument = me.allDocuments.get(0); me.activeDocument.requestFocus(); verifyActiveDocument(); } return true; } /** * Format the active document. * @return If it worked. */ public static boolean Format() { if (me == null) throw new RuntimeException("Document manager not initialized."); if (!verifyActiveDocument()) return false; me.activeDocument.format(); return true; } /** * Insert a tab / return. * * @param insertReturn Insert a newline before tabbing. * @return If it worked. */ public static boolean Tab(boolean insertReturn) { if (me == null) throw new RuntimeException("Document manager not initialized."); SchemeTextArea doc = me.activeDocument; if (doc == null) return false; if (insertReturn) { try { doc.code.getDocument().insertString(doc.code.getCaretPosition(), "\n", null); } catch (BadLocationException ble) { ErrorManager.logError("Unable to add a new line on ENTER."); } } doc.tab(); return true; } /** * Undo on the active document. * @return If it worked. */ public static boolean Undo() { if (me == null) throw new RuntimeException("Document manager not initialized."); SchemeTextArea doc = me.activeDocument; try { if (doc.Undo.canUndo()) doc.Undo.undo(); return true; } catch (CannotUndoException e) { return false; } } /** * Redo on the active document. * @return If it worked. */ public static boolean Redo() { if (me == null) throw new RuntimeException("Document manager not initialized."); SchemeTextArea doc = me.activeDocument; try { if (doc.Undo.canRedo()) doc.Undo.redo(); return true; } catch (CannotRedoException e) { return false; } } /** * Show the find/replace dialog for the current document. */ public static void FindReplace() { if (me == null) throw new RuntimeException("Document manager not initialized."); SchemeTextArea doc = me.activeDocument; new FindReplaceDialog(me.Main, doc.code).setVisible(true); } /** * Keep track of which text area last had focus. * @param e The event. */ @Override public void focusGained(FocusEvent e) { if (!(e.getSource() instanceof Component)) return; Component c = (Component) e.getSource(); while (c != null) { if (c instanceof SchemeTextArea) { activeDocument = (SchemeTextArea) c; return; } c = c.getParent(); } } /** * Ignore this. * @param e */ @Override public void focusLost(FocusEvent e) { } /** * Create a new shared document. * @throws Exception If we cannot host. */ public static boolean HostShared() throws Exception { if (me == null) throw new RuntimeException("Document manager not initialized."); SharedTextArea ss = new SharedTextArea(InetAddress.getLocalHost(), SharedTextArea.NEXT_PORT++, true); me.allDocuments.add(ss); ss.code.addFocusListener(me); me.lastIndex++; String id = "document-" + me.lastIndex; me.Views.addView(id, new View("<new document> (" + ss.getDocumentName() + ")", null, ss)); ss.myView = me.Views.getView(id); me.Documents.addTab(me.Views.getView(id)); if (me.Root != null && !me.Documents.isShowing()) me.Root.setWindow(new SplitWindow(false, 0.6f, me.Documents, me.Root.getWindow())); ss.code.requestFocusInWindow(); return true; } /** * Create a new shared document. * @param host The name of the server * @param port The port on the server * @throws Exception If we cannot host. */ public static boolean JoinShared(InetAddress host, int port) throws Exception { if (me == null) throw new RuntimeException("Document manager not initialized."); SharedTextArea ss = new SharedTextArea(host, port, false); me.allDocuments.add(ss); ss.code.addFocusListener(me); me.lastIndex++; String id = "document-" + me.lastIndex; me.Views.addView(id, new View("<new document> (" + ss.getDocumentName() + ")", null, ss)); ss.myView = me.Views.getView(id); me.Documents.addTab(me.Views.getView(id)); if (me.Root != null && !me.Documents.isShowing()) me.Root.setWindow(new SplitWindow(false, 0.6f, me.Documents, me.Root.getWindow())); ss.code.requestFocusInWindow(); return true; } /** * Disconnect from an active shared document. */ public static void DisconnectShared() { if (me == null) throw new RuntimeException("Document manager not initialized."); if (!verifyActiveDocument()) return; if (!(me.activeDocument instanceof SharedTextArea)) return; SharedTextArea sta = (SharedTextArea) me.activeDocument; sta.disconnect(); if (sta.myFile == null) sta.myView.getViewProperties().setTitle("<new document>"); else sta.myView.getViewProperties().setTitle(sta.myFile.getName()); } /** * Get the file that the active document is using. * @return The filename. */ public static File getActiveFile() { if (me == null) throw new RuntimeException("Document manager not initialized."); if (!verifyActiveDocument()) return null; else return me.activeDocument.myFile; } /** * True if the active document is a shared text area. * @return True/false */ public static boolean isActiveShared() { return (me != null && me.activeDocument != null && me.activeDocument instanceof SharedTextArea && ((SharedTextArea) me.activeDocument).isShared()); } } /** * Remove documents from the scheme text area when they're closed. */ class ViewCloseListener implements DockingWindowListener { SchemeTextArea SS; public ViewCloseListener(SchemeTextArea ss) { SS = ss; } /** * When the window is closed. * @param event Event parameters. */ @Override public void windowClosed(DockingWindow event) { SS.close(); DocumentManager.me.allDocuments.remove(SS); } @Override public void windowUndocking(DockingWindow event) throws OperationAbortedException {} @Override public void windowUndocked(DockingWindow event) {} @Override public void windowShown(DockingWindow event) {} @Override public void windowRestoring(DockingWindow event) throws OperationAbortedException {} @Override public void windowRestored(DockingWindow event) {} @Override public void windowRemoved(DockingWindow event, DockingWindow arg1) {} @Override public void windowMinimizing(DockingWindow event) throws OperationAbortedException {} @Override public void windowMinimized(DockingWindow event) {} @Override public void windowMaximizing(DockingWindow event) throws OperationAbortedException {} @Override public void windowMaximized(DockingWindow event) {} @Override public void windowHidden(DockingWindow event) {} @Override public void windowDocking(DockingWindow event) throws OperationAbortedException {} @Override public void windowDocked(DockingWindow event) {} @Override public void windowClosing(DockingWindow event) throws OperationAbortedException {} @Override public void windowAdded(DockingWindow event, DockingWindow arg1) {} @Override public void viewFocusChanged(View event, View arg1) {} }
package hex.glm; import hex.*; import hex.glm.GLMModel.GLMParameters.Family; import water.*; import water.DTask.DKeyTask; import water.H2O.H2OCountedCompleter; import water.fvec.Chunk; import water.fvec.Frame; import water.fvec.Vec; import water.util.JCodeGen; import water.util.MathUtils; import water.util.SB; import water.util.TwoDimTable; import java.util.Arrays; import java.util.HashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; public class GLMModel extends SupervisedModel<GLMModel,GLMModel.GLMParameters,GLMModel.GLMOutput> { final DataInfo _dinfo; public GLMModel(Key selfKey, GLMParameters parms, GLMOutput output, DataInfo dinfo, double ymu, double ySigma, double lambda_max, long nobs) { super(selfKey, parms, output); _ymu = ymu; _ySigma = ySigma; _lambda_max = lambda_max; _nobs = nobs; _dinfo = dinfo; } public DataInfo dinfo() { return _dinfo; } public static class GetScoringModelTask extends DTask.DKeyTask<GetScoringModelTask,GLMModel> { final double _lambda; public GLMModel _res; public GetScoringModelTask(H2OCountedCompleter cmp, Key modelKey, double lambda){ super(cmp,modelKey); _lambda = lambda; } @Override public void map(GLMModel m) { _res = m.clone(); _res._output = (GLMOutput)_res._output.clone(); Submodel sm = Double.isNaN(_lambda)?_res._output._submodels[_res._output._best_lambda_idx]:_res._output.submodelForLambda(_lambda); assert sm != null : "GLM[" + m._key + "]: missing submodel for lambda " + _lambda; sm = (Submodel) sm.clone(); _res._output._submodels = new Submodel[]{sm}; _res._output.setSubmodelIdx(0, _res,null, null); } } private int rank(double [] ds) { int res = 0; for(double d:ds) if(d != 0) ++res; return res; } @Override public ModelMetrics.MetricBuilder makeMetricBuilder(String[] domain) { return new GLMValidation(domain,_ymu, _parms, rank(beta()), _output._threshold); } public double [] beta() { return _output._global_beta;} public String [] names(){ return _output._names;} public GLMValidation validation(){ return _output._submodels[_output._best_lambda_idx].trainVal; } @Override public double[] score0(Chunk[] chks, int row_in_chunk, double[] tmp, double[] preds) { double eta = 0.0; final double [] b = beta(); if(!_parms._use_all_factor_levels){ // good level 0 of all factors for(int i = 0; i < _dinfo._catOffsets.length-1; ++i) if(chks[i].atd(row_in_chunk) != 0) eta += b[_dinfo._catOffsets[i] + (int)(chks[i].atd(row_in_chunk))-1]; } else { // do not skip any levels for(int i = 0; i < _dinfo._catOffsets.length-1; ++i) eta += b[_dinfo._catOffsets[i] + (int)chks[i].atd(row_in_chunk)]; } final int noff = _dinfo.numStart() - _dinfo._cats ; for(int i = _dinfo._cats; i < b.length-1-noff; ++i) eta += b[noff+i]*chks[i].atd(row_in_chunk); eta += b[b.length-1]; // intercept double mu = _parms.linkInv(eta); preds[0] = mu; if( _parms._family == Family.binomial ) { // threshold for prediction if(Double.isNaN(mu)){ preds[0] = Double.NaN; preds[1] = Double.NaN; preds[2] = Double.NaN; } else { preds[0] = (mu >= _output._threshold ? 1 : 0); preds[1] = 1.0 - mu; // class 0 preds[2] = mu; // class 1 } } return preds; } public static class GLMParameters extends SupervisedModel.SupervisedParameters { // public int _response; // TODO: the standard is now _response_column in SupervisedModel.SupervisedParameters public boolean _standardize = true; public Family _family; public Link _link = Link.family_default; public Solver _solver = Solver.IRLSM; public final double _tweedie_variance_power; public final double _tweedie_link_power; public double [] _alpha = null; public double [] _lambda = null; public double _prior = -1; public boolean _lambda_search = false; public int _nlambdas = -1; public double _lambda_min_ratio = -1; // special public boolean _use_all_factor_levels = false; public double _beta_epsilon = 1e-4; public int _max_iterations = -1; public int _n_folds; boolean _intercept = true; public Key<Frame> _beta_constraints = null; // internal parameter, handle with care. GLM will stop when there is more than this number of active predictors (after strong rule screening) public int _max_active_predictors = -1; public void validate(GLM glm) { if(_n_folds < 0) glm.error("n_folds","must be >= 0"); if(_n_folds == 1)_n_folds = 0; // 0 or 1 means no n_folds if(_lambda_search && _nlambdas == -1) _nlambdas = 100; if(_beta_constraints != null) { Frame f = _beta_constraints.get(); if(f == null) glm.error("beta_constraints","Missing frame for beta constraints"); Vec v = f.vec("names"); if(v == null)glm.error("beta_constraints","Beta constraints parameter must have names column with valid coefficient names"); // todo: check the coefficient names v = f.vec("upper_bounds"); if(v != null && !v.isNumeric()) glm.error("beta_constraints","upper_bounds must be numeric if present");v = f.vec("upper_bounds"); v = f.vec("lower_bounds"); if(v != null && !v.isNumeric()) glm.error("beta_constraints","lower_bounds must be numeric if present"); v = f.vec("beta_given"); if(v != null && !v.isNumeric()) glm.error("beta_constraints","beta_given must be numeric if present");v = f.vec("upper_bounds"); v = f.vec("beta_start"); if(v != null && !v.isNumeric()) glm.error("beta_constraints","beta_start must be numeric if present"); } if(_family == Family.binomial) { Frame frame = DKV.getGet(_train); if (frame != null) { Vec response = frame.vec(_response_column); if (response != null) { if (response.min() != 0 || response.max() != 1) { glm.error("_response_column", "Illegal response for family binomial, must be binary, got min = " + response.min() + ", max = " + response.max() + ")"); } } } } if(!_lambda_search) { glm.hide("_lambda_min_ratio", "only applies if lambda search is on."); glm.hide("_nlambdas", "only applies if lambda search is on."); } if(_link != Link.family_default) { // check we have compatible link switch (_family) { case gaussian: if (_link != Link.identity && _link != Link.log && _link != Link.inverse) throw new IllegalArgumentException("Incompatible link function for selected family. Only identity, log and inverse links are allowed for family=gaussian."); break; case binomial: if (_link != Link.logit && _link != Link.log) throw new IllegalArgumentException("Incompatible link function for selected family. Only logit and log links are allowed for family=binomial. Got " + _link); break; case poisson: if (_link != Link.log && _link != Link.identity) throw new IllegalArgumentException("Incompatible link function for selected family. Only log and identity links are allowed for family=poisson."); break; case gamma: if (_link != Link.inverse && _link != Link.log && _link != Link.identity) throw new IllegalArgumentException("Incompatible link function for selected family. Only inverse, log and identity links are allowed for family=gamma."); break; // case tweedie: // if (_link != Link.tweedie) // break; default: H2O.fail(); } } } public GLMParameters(){ this(Family.gaussian, Link.family_default); assert _link == Link.family_default; } public GLMParameters(Family f){this(f,f.defaultLink);} public GLMParameters(Family f, Link l){this(f,l,null, null);} public GLMParameters(Family f, Link l, double [] lambda, double [] alpha){ this._family = f; this._lambda = lambda; this._alpha = alpha; _tweedie_link_power = Double.NaN; _tweedie_variance_power = Double.NaN; _link = l; } public GLMParameters(Family f, double [] lambda, double [] alpha, double twVar, double twLnk){ this._lambda = lambda; this._alpha = alpha; this._tweedie_variance_power = twVar; this._tweedie_link_power = twLnk; _family = f; _link = f.defaultLink; } public final double variance(double mu){ switch(_family) { case gaussian: return 1; case binomial: return mu * (1 - mu); case poisson: return mu; case gamma: return mu * mu; // case tweedie: // return Math.pow(mu, _tweedie_variance_power); default: throw new RuntimeException("unknown family Id " + this); } } public final boolean canonical(){ switch(_family){ case gaussian: return _link == Link.identity; case binomial: return _link == Link.logit; case poisson: return _link == Link.log; case gamma: return _link == Link.inverse; // case tweedie: // return false; default: throw H2O.unimpl(); } } public final double deviance(double yr, double ym){ switch(_family){ case gaussian: return (yr - ym) * (yr - ym); case binomial: // if(yr == ym) return 0; // return 2*( -yr * eta - Math.log(1 - ym)); return 2 * ((y_log_y(yr, ym)) + y_log_y(1 - yr, 1 - ym)); case poisson: if( yr == 0 ) return 2 * ym; return 2 * ((yr * Math.log(yr / ym)) - (yr - ym)); case gamma: if( yr == 0 ) return -2; return -2 * (Math.log(yr / ym) - (yr - ym) / ym); // case tweedie: // // Theory of Dispersion Models: Jorgensen // // pg49: $$ d(y;\mu) = 2 [ y \cdot \left(\tau^{-1}(y) - \tau^{-1}(\mu) \right) - \kappa \{ \tau^{-1}(y)\} + \kappa \{ \tau^{-1}(\mu)\} ] $$ // // pg133: $$ \frac{ y^{2 - p} }{ (1 - p) (2-p) } - \frac{y \cdot \mu^{1-p}}{ 1-p} + \frac{ \mu^{2-p} }{ 2 - p }$$ // double one_minus_p = 1 - _tweedie_variance_power; // double two_minus_p = 2 - _tweedie_variance_power; // return Math.pow(yr, two_minus_p) / (one_minus_p * two_minus_p) - (yr * (Math.pow(ym, one_minus_p)))/one_minus_p + Math.pow(ym, two_minus_p)/two_minus_p; default: throw new RuntimeException("unknown family " + _family); } } public final double deviance(float yr, float ym){ switch(_family){ case gaussian: return (yr - ym) * (yr - ym); case binomial: // if(yr == ym) return 0; // return 2*( -yr * eta - Math.log(1 - ym)); return 2 * ((y_log_y(yr, ym)) + y_log_y(1 - yr, 1 - ym)); case poisson: if( yr == 0 ) return 2 * ym; return 2 * ((yr * Math.log(yr / ym)) - (yr - ym)); case gamma: if( yr == 0 ) return -2; return -2 * (Math.log(yr / ym) - (yr - ym) / ym); // case tweedie: // // Theory of Dispersion Models: Jorgensen // // pg49: $$ d(y;\mu) = 2 [ y \cdot \left(\tau^{-1}(y) - \tau^{-1}(\mu) \right) - \kappa \{ \tau^{-1}(y)\} + \kappa \{ \tau^{-1}(\mu)\} ] $$ // // pg133: $$ \frac{ y^{2 - p} }{ (1 - p) (2-p) } - \frac{y \cdot \mu^{1-p}}{ 1-p} + \frac{ \mu^{2-p} }{ 2 - p }$$ // double one_minus_p = 1 - _tweedie_variance_power; // double two_minus_p = 2 - _tweedie_variance_power; // return Math.pow(yr, two_minus_p) / (one_minus_p * two_minus_p) - (yr * (Math.pow(ym, one_minus_p)))/one_minus_p + Math.pow(ym, two_minus_p)/two_minus_p; default: throw new RuntimeException("unknown family " + _family); } } public final double likelihood(double yr, double eta, double ym){ switch(_family){ case gaussian: return .5 * (yr - ym) * (yr - ym); case binomial: if(yr == ym) return 0; return .5 * deviance(yr, ym); // double res = Math.log(1 + Math.exp((1 - 2*yr) * eta)); // assert Math.abs(res - .5 * deviance(yr,eta,ym)) < 1e-8:res + " != " + .5*deviance(yr,eta,ym) +" yr = " + yr + ", ym = " + ym + ", eta = " + eta; // return res; // double res = -yr * eta - Math.log(1 - ym); // return res; case poisson: if( yr == 0 ) return 2 * ym; return 2 * ((yr * Math.log(yr / ym)) - (yr - ym)); case gamma: if( yr == 0 ) return -2; return -2 * (Math.log(yr / ym) - (yr - ym) / ym); // case tweedie: // // Theory of Dispersion Models: Jorgensen // // pg49: $$ d(y;\mu) = 2 [ y \cdot \left(\tau^{-1}(y) - \tau^{-1}(\mu) \right) - \kappa \{ \tau^{-1}(y)\} + \kappa \{ \tau^{-1}(\mu)\} ] $$ // // pg133: $$ \frac{ y^{2 - p} }{ (1 - p) (2-p) } - \frac{y \cdot \mu^{1-p}}{ 1-p} + \frac{ \mu^{2-p} }{ 2 - p }$$ // double one_minus_p = 1 - _tweedie_variance_power; // double two_minus_p = 2 - _tweedie_variance_power; // return Math.pow(yr, two_minus_p) / (one_minus_p * two_minus_p) - (yr * (Math.pow(ym, one_minus_p)))/one_minus_p + Math.pow(ym, two_minus_p)/two_minus_p; default: throw new RuntimeException("unknown family " + _family); } } public final double link(double x) { switch(_link) { case identity: return x; case logit: assert 0 <= x && x <= 1:"x out of bounds, expected <0,1> range, got " + x; return Math.log(x / (1 - x)); case log: return Math.log(x); case inverse: double xx = (x < 0) ? Math.min(-1e-5, x) : Math.max(1e-5, x); return 1.0 / xx; // case tweedie: // return Math.pow(x, _tweedie_link_power); default: throw new RuntimeException("unknown link function " + this); } } public final double linkDeriv(double x) { switch(_link) { case logit: double div = (x * (1 - x)); if(div < 1e-6) return 1e6; // avoid numerical instability return 1.0 / div; case identity: return 1; case log: return 1.0 / x; case inverse: return -1.0 / (x * x); // case tweedie: // return _tweedie_link_power * Math.pow(x, _tweedie_link_power - 1); default: throw H2O.unimpl(); } } public final double linkInv(double x) { switch(_link) { case identity: return x; case logit: return 1.0 / (Math.exp(-x) + 1.0); case log: return Math.exp(x); case inverse: double xx = (x < 0) ? Math.min(-1e-5, x) : Math.max(1e-5, x); return 1.0 / xx; // case tweedie: // return Math.pow(x, 1/ _tweedie_link_power); default: throw new RuntimeException("unexpected link function id " + this); } } public final double linkInvDeriv(double x) { switch(_link) { case identity: return 1; case logit: double g = Math.exp(-x); double gg = (g + 1) * (g + 1); return g / gg; case log: //return (x == 0)?MAX_SQRT:1/x; return Math.max(Math.exp(x), Double.MIN_NORMAL); case inverse: double xx = (x < 0) ? Math.min(-1e-5, x) : Math.max(1e-5, x); return -1 / (xx * xx); // case tweedie: // double vp = (1. - _tweedie_link_power) / _tweedie_link_power; // return (1/ _tweedie_link_power) * Math.pow(x, vp); default: throw new RuntimeException("unexpected link function id " + this); } } // supported families public enum Family { gaussian(Link.identity), binomial(Link.logit), poisson(Link.log), gamma(Link.inverse)/*, tweedie(Link.tweedie)*/; public final Link defaultLink; Family(Link link){defaultLink = link;} } public static enum Link {family_default, identity, logit, log,inverse,/* tweedie*/} public static enum Solver {AUTO, IRLSM, L_BFGS, COORDINATE_DESCENT} // helper function static final double y_log_y(double y, double mu) { if(y == 0)return 0; if(mu < Double.MIN_NORMAL) mu = Double.MIN_NORMAL; return y * Math.log(y / mu); } } public static class GLM_LBFGS_Parameters extends GLMParameters {} public static class Submodel extends Iced { final double lambda_value; final int iteration; final long run_time; GLMValidation trainVal; // training set validation GLMValidation holdOutVal; // hold-out set validation GLMValidation xVal; // x-validation final int rank; public final int [] idxs; final boolean sparseCoef; public double [] beta; public double [] norm_beta; public Submodel(double lambda , double [] beta, double [] norm_beta, long run_time, int iteration, boolean sparseCoef){ this.lambda_value = lambda; this.run_time = run_time; this.iteration = iteration; int r = 0; if(beta != null){ final double [] b = norm_beta != null?norm_beta:beta; // grab the indeces of non-zero coefficients for(double d:beta)if(d != 0)++r; idxs = MemoryManager.malloc4(sparseCoef?r:beta.length); int j = 0; for(int i = 0; i < beta.length; ++i) if(!sparseCoef || beta[i] != 0)idxs[j++] = i; j = 0; this.beta = MemoryManager.malloc8d(idxs.length); for(int i:idxs) this.beta[j++] = beta[i]; if(norm_beta != null){ j = 0; this.norm_beta = MemoryManager.malloc8d(idxs.length); for(int i:idxs) this.norm_beta[j++] = norm_beta[i]; } } else idxs = null; rank = r; this.sparseCoef = sparseCoef; } } public static void setSubmodel(H2O.H2OCountedCompleter cmp, Key modelKey, final double lambda, double[] beta, double[] norm_beta, final int iteration, long runtime, boolean sparseCoef, final GLMValidation trainVal, final GLMValidation holdOutval, final Frame tFrame, final Frame vFrame){ final Submodel sm = new Submodel(lambda,beta, norm_beta, runtime, iteration,sparseCoef); sm.trainVal = trainVal; sm.holdOutVal = holdOutval; if(cmp != null) cmp.addToPendingCount(1); Future f = new TAtomic<GLMModel>(cmp){ @Override public GLMModel atomic(GLMModel old) { if(old == null) return old; // job could've been cancelled! if(old._output._submodels == null){ old._output = (GLMOutput)old._output.clone(); old._output._submodels = new Submodel[]{sm}; } else { int id = old._output.submodelIdForLambda(lambda); if (id < 0) { id = -id - 1; Submodel [] sms = Arrays.copyOf(old._output._submodels, old._output._submodels.length + 1); for (int i = sms.length-1; i > id; --i) sms[i] = sms[i - 1]; sms[id] = sm; old._output = (GLMOutput)old._output.clone(); old._output._submodels = sms; } else { if (old._output._submodels[id].iteration <= sm.iteration) old._output._submodels[id] = sm; } } // can not call pickBestSubmodel now, pickBestSubmodel will call makeModelMEtrics which in turns calls Frame.checksum // which will request RollupStats and taht will hit assertion error since we are in TAtomic and would thus be blocking on task with the same prioriry // should be ok to pickBestModel only at the very end, may need to revisit if showing incremental results... // old._output.pickBestModel(false, old, tFrame, vFrame); old._run_time = Math.max(old._run_time,sm.run_time); return old; } }.fork(modelKey); if(cmp == null && f != null) try { f.get(); } catch (InterruptedException e) { throw new RuntimeException(e); } catch (ExecutionException e) { throw new RuntimeException(e); } } public int rank(double lambda){return -1;} public final double _lambda_max; public final double _ymu; public final double _ySigma; public final long _nobs; long _run_time; public static class GLMOutput extends SupervisedModel.SupervisedOutput { Submodel[] _submodels; String[] _coefficient_names; int _best_lambda_idx; double _threshold; double[] _global_beta; public boolean _binomial; public int rank() { return _submodels[_best_lambda_idx].rank; } public boolean isNormalized() { return _submodels != null && _submodels[_best_lambda_idx].norm_beta != null; } public String[] coefficientNames() { return _coefficient_names; } public GLMOutput(String[] column_names, String[][] domains, String[] coefficient_names, double[] coefficients, float threshold, boolean binomial) { _names = column_names; _domains = domains; _global_beta = coefficients; _coefficient_names = coefficient_names; _submodels = new Submodel[]{new Submodel(-1, coefficients, null, -1, -1, false)}; _threshold = threshold; _binomial = binomial; } public GLMOutput() { } public GLMOutput(GLM glm) { super(glm); String[] cnames = glm._dinfo.coefNames(); _names = glm._dinfo._adaptedFrame.names(); _coefficient_names = Arrays.copyOf(cnames, cnames.length + 1); _coefficient_names[_coefficient_names.length-1] = "Intercept"; _binomial = glm._parms._family == Family.binomial; } @Override public int nclasses() { return _binomial ? 2 : 1; } private static String[] binomialClassNames = new String[]{"0", "1"}; @Override public String[] classNames() { return _binomial ? binomialClassNames : null; } public int submodelIdForLambda(double lambda) { if (lambda >= _submodels[0].lambda_value) return 0; int i = _submodels.length - 1; for (; i >= 0; --i) // first condition to cover lambda == 0 case (0/0 is Inf in java!) if (lambda == _submodels[i].lambda_value || Math.abs(_submodels[i].lambda_value - lambda) / lambda < 1e-5) return i; else if (_submodels[i].lambda_value > lambda) return -i - 2; return -1; } public Submodel submodelForLambda(double lambda) { return _submodels[submodelIdForLambda(lambda)]; } public int rank(double lambda) { Submodel sm = submodelForLambda(lambda); if (sm == null) return 0; return submodelForLambda(lambda).rank; } public void pickBestModel(boolean useAuc, GLMModel m, Frame tFrame, Frame vFrame) { int bestId = _submodels.length - 1; if (_submodels.length > 2) { boolean xval = false; boolean hval = false; GLMValidation bestVal = null; if (_submodels[1].xVal != null) { // skip null model xval = true; bestVal = _submodels[1].xVal; } else if (_submodels[1].holdOutVal != null) { hval = true; bestVal = _submodels[1].holdOutVal; } else bestVal = _submodels[0].trainVal; for (int i = 1; i < _submodels.length; ++i) { GLMValidation val = xval ? _submodels[i].xVal : hval ? _submodels[i].holdOutVal : _submodels[i].trainVal; Frame f = hval ? vFrame : tFrame; if (val == null || val == bestVal) continue; if ((useAuc && val.computeAUC(m.clone(), f) > bestVal.computeAUC(m, f)) || val.residual_deviance < bestVal.residual_deviance) { bestVal = val; bestId = i; } } } setSubmodelIdx(_best_lambda_idx = bestId, m, tFrame, vFrame); } public ModelMetrics setModelMetrics(ModelMetrics mm) { for (int i = 0; i < _model_metrics.length; ++i) // Dup removal if (_model_metrics[i].equals(mm._key)) { _model_metrics[i] = mm._key; return mm; } _model_metrics = Arrays.copyOf(_model_metrics, _model_metrics.length + 1); _model_metrics[_model_metrics.length - 1] = mm._key; return mm; // Flow coding } public void setSubmodelIdx(int l, GLMModel m, Frame tFrame, Frame vFrame){ _best_lambda_idx = l; if (_submodels[l].trainVal != null && tFrame != null) _training_metrics = _submodels[l].trainVal.makeModelMetrics(m,tFrame,tFrame.vec(m._output.responseName()).sigma()); if(_submodels[l].holdOutVal != null && vFrame != null) { _threshold = _submodels[l].trainVal.bestThreshold(); _validation_metrics = _submodels[l].holdOutVal.makeModelMetrics(m, vFrame, vFrame.vec(m._output.responseName()).sigma()); } if(_global_beta == null) _global_beta = MemoryManager.malloc8d(_coefficient_names.length); else Arrays.fill(_global_beta,0); int j = 0; for(int i:_submodels[l].idxs) _global_beta[i] = _submodels[l].beta[j++]; } public double [] beta() { return _global_beta;} public Submodel bestSubmodel(){ return _submodels[_best_lambda_idx];} } public static void setXvalidation(H2OCountedCompleter cmp, Key modelKey, final double lambda, final GLMValidation val){ throw H2O.unimpl(); // // expected cmp has already set correct pending count // new TAtomic<GLMModel>(cmp){ // @Override // public GLMModel atomic(GLMModel old) { // if(old == null)return old; // job could've been cancelled // old._output._submodels = old._output._submodels.clone(); // int id = old._output.submodelIdForLambda(lambda); // old._output._submodels[id] = (Submodel)old._output._submodels[id].clone(); // old._output._submodels[id].xVal = val; // old._output.pickBestModel(false); // return old; // }.fork(modelKey); } /** * get beta coefficients in a map indexed by name * @return the estimated coefficients */ public HashMap<String,Double> coefficients(){ HashMap<String, Double> res = new HashMap<String, Double>(); final double [] b = beta(); if(b != null) for(int i = 0; i < b.length; ++i)res.put(_output._coefficient_names[i],b[i]); return res; } static class FinalizeAndUnlockTsk extends DKeyTask<FinalizeAndUnlockTsk,GLMModel> { final Key _jobKey; final Key _validFrame; final Key _trainFrame; final double [] _likelihoods; final double [] _objectives; final int [] _scoring_iters; final int [] _scoring_times; final int _iter; public FinalizeAndUnlockTsk(H2OCountedCompleter cmp, Key modelKey, Key jobKey, Key trainFrame, Key validFrame, int iter, int [] scoring_iters, int [] scoring_times, double [] likelihoods, double [] objectives){ super(cmp, modelKey); _jobKey = jobKey; _validFrame = validFrame; _trainFrame = trainFrame; _scoring_iters = scoring_iters; _scoring_times = scoring_times; _likelihoods = likelihoods; _objectives = objectives; _iter = iter; } @Override protected void map(GLMModel glmModel) { Frame tFrame = DKV.getGet(_trainFrame); Frame vFrame = (_validFrame != null)? DKV.get(_validFrame).<Frame>get():null; glmModel._output.pickBestModel(glmModel._parms._family == Family.binomial, glmModel, tFrame, vFrame); // String[] colTypes, // /String[] colFormats, String colHeaderForRowHeaders) { String [] names = new String[]{"Family","Link", "Regularization", "Number of Predictors Total","Number of Active Predictors", "Number of Iterations", "Training Frame"}; String [] types = new String[]{"string","string","string","int","int","int","string"}; String [] formats = new String[]{"%s","%s","%s","%d","%d","%d","%s"}; if(glmModel._parms._lambda_search) { names = new String[]{"Family", "Link", "Regularization", "Lambda Search", "Number of Predictors Total", "Number of Active Predictors", "Number of Iterations", "Training Frame"}; types = new String[]{"string","string","string","string","int","int","int","string"}; formats = new String[]{"%s","%s","%s","%s","%d","%d","%d","%s"}; } glmModel._output._model_summary = new TwoDimTable("GLM Model", "summary", new String[]{""}, names , types , formats,""); glmModel._output._model_summary.set(0,0,glmModel._parms._family.toString()); glmModel._output._model_summary.set(0,1,glmModel._parms._link.toString()); String regularization = "None"; if(glmModel._parms._lambda != null && !(glmModel._parms._lambda.length == 1 && glmModel._parms._lambda[0] == 0)) { // have regularization if(glmModel._parms._alpha[0] == 0) regularization = "Ridge ( lambda = "; else if(glmModel._parms._alpha[0] == 1) regularization = "Lasso (lambda = "; else regularization = "Elastic Net (alpha = " + MathUtils.roundToNDigits(glmModel._parms._alpha[0],4) +", lambda = "; regularization = regularization + MathUtils.roundToNDigits(glmModel._parms._lambda[glmModel._output._best_lambda_idx],4) + " )"; } glmModel._output._model_summary.set(0,2,regularization); int lambdaSearch = 0; if(glmModel._parms._lambda_search) { lambdaSearch = 1; glmModel._output._model_summary.set(0,3,"nlambda = " + glmModel._parms._nlambdas + ", lambda_max = " + MathUtils.roundToNDigits(glmModel._lambda_max,4) + ", best_lambda_id = " + glmModel._output._best_lambda_idx); } int intercept = glmModel._parms._intercept?1:0; glmModel._output._model_summary.set(0,3+lambdaSearch,Integer.toString(glmModel.beta().length - intercept)); glmModel._output._model_summary.set(0,4+lambdaSearch,Integer.toString(glmModel._output.rank() - intercept)); glmModel._output._model_summary.set(0,5+lambdaSearch,Integer.valueOf(_iter)); glmModel._output._model_summary.set(0,6+lambdaSearch,_trainFrame.toString()); if(_scoring_iters != null) { glmModel._output._scoring_history = new TwoDimTable("Scoring History", "", new String[_scoring_iters.length], new String[]{"iteration", "time [ms]", "likelihood", "objective"}, new String[]{"int", "int", "double", "double"}, new String[]{"%d","%d", "%.5f", "%.5f"}, ""); for (int i = 0; i < _scoring_iters.length; ++i) { glmModel._output._scoring_history.set(i,0,_scoring_iters[i]); glmModel._output._scoring_history.set(i,1,_scoring_times[i]); glmModel._output._scoring_history.set(i,2,_likelihoods[i]); glmModel._output._scoring_history.set(i,3,_objectives[i]); } } glmModel.update(_jobKey); glmModel.unlock(_jobKey); } } @Override protected double[] score0(double[] data, double[] preds) { double eta = 0.0; final double [] b = beta(); if(!_parms._use_all_factor_levels){ // good level 0 of all factors for(int i = 0; i < _dinfo._catOffsets.length-1; ++i) if(data[i] != 0) eta += b[_dinfo._catOffsets[i] + (int)(data[i]-1)]; } else { // do not good any levels! for(int i = 0; i < _dinfo._catOffsets.length-1; ++i) eta += b[_dinfo._catOffsets[i] + (int)data[i]]; } final int noff = _dinfo.numStart() - _dinfo._cats; for(int i = _dinfo._cats; i < data.length; ++i) eta += b[noff+i]*data[i]; eta += b[b.length-1]; // reduce intercept double mu = _parms.linkInv(eta); preds[0] = mu; if( _parms._family == Family.binomial ) { // threshold for prediction if(Double.isNaN(mu)){ preds[0] = Double.NaN; preds[1] = Double.NaN; preds[2] = Double.NaN; } else { preds[0] = (mu >= _output._threshold ? 1 : 0); preds[1] = 1.0 - mu; // class 0 preds[2] = mu; // class 1 } } return preds; } @Override protected void toJavaPredictBody(SB body, SB classCtx, SB file) { final int nclass = _output.nclasses(); String mname = JCodeGen.toJavaId(_key.toString()); JCodeGen.toStaticVar(classCtx,"BETA",beta(),"The Coefficients"); JCodeGen.toStaticVar(classCtx,"CATOFFS",_dinfo._catOffsets,"Categorical Offsets"); body.ip("double eta = 0.0;").nl(); body.ip("final double [] b = BETA;").nl(); if(!_parms._use_all_factor_levels){ // good level 0 of all factors body.ip("for(int i = 0; i < CATOFFS.length-1; ++i) if(data[i] != 0)").nl(); body.ip(" eta += b[CATOFFS[i] + (int)(data[i]-1)];").nl(); } else { // do not good any levels! body.ip("for(int i = 0; i < CATOFFS.length-1; ++i)").nl(); body.ip(" eta += b[CATOFFS[i] + (int)(data[i])];").nl(); } final int noff = _dinfo.numStart() - _dinfo._cats; body.ip("for(int i = ").p(_dinfo._cats).p("; i < data.length; ++i)").nl(); body.ip(" eta += b[").p(noff).p("+i]*data[i];").nl(); body.ip("eta += b[b.length-1]; // reduce intercept").nl(); body.ip("double mu = hex.genmodel.GenModel.GLM_").p(_parms._link.toString()).p("Inv(eta"); // if( _parms._link == hex.glm.GLMModel.GLMParameters.Link.tweedie ) body.p(",").p(_parms._tweedie_link_power); body.p(");").nl(); body.ip("preds[0] = mu;").nl(); if( _parms._family == Family.binomial ) { // threshold for prediction body.ip("preds[0] = mu > ").p(_output._threshold).p(" ? 1 : 0);").nl(); body.ip("preds[1] = 1.0 - mu; // class 0").nl(); body.ip("preds[2] = mu; // class 1").nl(); } } @Override protected SB toJavaInit(SB sb, SB fileContext) { sb.nl(); sb.ip("public boolean isSupervised() { return true; }").nl(); sb.ip("public int nfeatures() { return "+_output.nfeatures()+"; }").nl(); sb.ip("public int nclasses() { return "+_output.nclasses()+"; }").nl(); sb.ip("public ModelCategory getModelCategory() { return ModelCategory."+_output.getModelCategory()+"; }").nl(); return sb; } }
package hex.tree.drf; import hex.Model; import static hex.genmodel.GenModel.getPrediction; import hex.schemas.DRFV2; import hex.tree.*; import hex.tree.DTree.DecidedNode; import hex.tree.DTree.LeafNode; import hex.tree.DTree.UndecidedNode; import static hex.tree.drf.TreeMeasuresCollector.asSSE; import static hex.tree.drf.TreeMeasuresCollector.asVotes; import water.*; import water.fvec.Chunk; import water.fvec.Frame; import water.fvec.Vec; import water.util.Log; import water.util.ModelUtils; import water.util.RandomUtils; import water.util.Timer; import java.util.Arrays; import java.util.Random; /** Gradient Boosted Trees * * Based on "Elements of Statistical Learning, Second Edition, page 387" */ public class DRF extends SharedTree<hex.tree.drf.DRFModel, hex.tree.drf.DRFModel.DRFParameters, hex.tree.drf.DRFModel.DRFOutput> { protected int _mtry; protected long _actual_seed; @Override public Model.ModelCategory[] can_build() { return new Model.ModelCategory[]{ Model.ModelCategory.Regression, Model.ModelCategory.Binomial, Model.ModelCategory.Multinomial, }; } static final boolean DEBUG_DETERMINISTIC = false; //for debugging only // Called from an http request public DRF( hex.tree.drf.DRFModel.DRFParameters parms) { super("DRF",parms); init(false); } @Override public DRFV2 schema() { return new DRFV2(); } /** Start the DRF training Job on an F/J thread. */ @Override public Job<hex.tree.drf.DRFModel> trainModel() { return start(new DRFDriver(), _parms._ntrees/*work for progress bar*/); } @Override public Vec vresponse() { return super.vresponse() == null ? response() : super.vresponse(); } /** Initialize the ModelBuilder, validating all arguments and preparing the * training frame. This call is expected to be overridden in the subclasses * and each subclass will start with "super.init();". This call is made * by the front-end whenever the GUI is clicked, and needs to be fast; * heavy-weight prep needs to wait for the trainModel() call. */ @Override public void init(boolean expensive) { super.init(expensive); // Initialize local variables if (!(0.0 < _parms._sample_rate && _parms._sample_rate <= 1.0)) throw new IllegalArgumentException("Sample rate should be interval (0,1> but it is " + _parms._sample_rate); if (DEBUG_DETERMINISTIC && _parms._seed == -1) _parms._seed = 0x1321e74a0192470cL; // fixed version of seed else if (_parms._seed == -1) _actual_seed = RandomUtils.getDeterRNG(0xd280524ad7fe0602L).nextLong(); else _actual_seed = _parms._seed; if (_parms._sample_rate==1f && _valid!=null) Log.warn("Sample rate is 100% and no validation dataset is specified. There are no OOB data to compute out-of-bag error estimation!"); if (!_parms._convert_to_enum && _parms._do_grpsplit) { Log.info("Group splitting not supported for DRF regression. Forcing group splitting to false."); _parms._do_grpsplit = false; } } // A standard DTree with a few more bits. Support for sampling during // training, and replaying the sample later on the identical dataset to // e.g. compute OOBEE. static class DRFTree extends DTree { final int _mtrys; // Number of columns to choose amongst in splits final long _seeds[]; // One seed for each chunk, for sampling final transient Random _rand; // RNG for split decisions & sampling DRFTree( Frame fr, int ncols, char nbins, char nclass, int min_rows, int mtrys, long seed ) { super(fr._names, ncols, nbins, nclass, min_rows, seed); _mtrys = mtrys; _rand = createRNG(seed); _seeds = new long[fr.vecs()[0].nChunks()]; for( int i=0; i<_seeds.length; i++ ) _seeds[i] = _rand.nextLong(); } // Return a deterministic chunk-local RNG. Can be kinda expensive. public Random rngForChunk( int cidx ) { long seed = _seeds[cidx]; return createRNG(seed); } } /** Fill work columns: * - classification: set 1 in the corresponding wrk col according to row response * - regression: copy response into work column (there is only 1 work column) */ private class SetWrkTask extends MRTask<SetWrkTask> { @Override public void map( Chunk chks[] ) { Chunk cy = chk_resp(chks); for( int i=0; i<cy._len; i++ ) { if( cy.isNA(i) ) continue; if (_parms._convert_to_enum) { int cls = (int)cy.at8(i); chk_work(chks,cls).set(i,1L); } else { float pred = (float) cy.atd(i); chk_work(chks,0).set(i,pred); } } } } private class DRFDriver extends Driver { protected int _ntreesFromCheckpoint; // Classification or Regression: // Tree votes/SSE of individual trees on OOB rows public transient TreeMeasuresCollector.TreeMeasures _treeMeasuresOnOOB; // Tree votes/SSE per individual features on permutated OOB rows public transient TreeMeasuresCollector.TreeMeasures[/*features*/] _treeMeasuresOnSOOB; // Variable importance beased on tree split decisions private transient float[/*nfeatures*/] _improvPerVar; private void initTreeMeasurements() { _improvPerVar = new float[_ncols]; final int ntrees = _parms._ntrees; // Preallocate tree votes if (_model._output.isClassifier()) { _treeMeasuresOnOOB = new TreeMeasuresCollector.TreeVotes(ntrees); _treeMeasuresOnSOOB = new TreeMeasuresCollector.TreeVotes[_ncols]; for (int i=0; i<_ncols; i++) _treeMeasuresOnSOOB[i] = new TreeMeasuresCollector.TreeVotes(ntrees); } else { _treeMeasuresOnOOB = new TreeMeasuresCollector.TreeSSE(ntrees); _treeMeasuresOnSOOB = new TreeMeasuresCollector.TreeSSE[_ncols]; for (int i=0; i<_ncols; i++) _treeMeasuresOnSOOB[i] = new TreeMeasuresCollector.TreeSSE(ntrees); } } @Override protected void buildModel() { _mtry = (_parms._mtries==-1) ? // classification: mtry=sqrt(_ncols), regression: mtry=_ncols/3 ( _parms._convert_to_enum ? Math.max((int)Math.sqrt(_ncols),1) : Math.max(_ncols/3,1)) : _parms._mtries; if (!(1 <= _mtry && _mtry <= _ncols)) throw new IllegalArgumentException("Computed mtry should be in interval <1,#cols> but it is " + _mtry); // Initialize TreeVotes for classification, MSE arrays for regression initTreeMeasurements(); // Append number of trees participating in on-the-fly scoring _train.add("OUT_BAG_TREES", _response.makeZero()); // Prepare working columns new SetWrkTask().doAll(_train); // If there was a check point recompute tree_<_> and oob columns based on predictions from previous trees // but only if OOB validation is requested. if (_valid==null && _parms._checkpoint) { Timer t = new Timer(); // Compute oob votes for each output level new OOBScorer(_ncols, _nclass, _parms._sample_rate, _model._output._treeKeys).doAll(_train); Log.info("Reconstructing oob stats from checkpointed model took " + t); } // The RNG used to pick split columns Random rand = createRNG(_actual_seed); // To be deterministic get random numbers for previous trees and // put random generator to the same state for (int i=0; i<_ntreesFromCheckpoint; i++) rand.nextLong(); int tid; DTree[] ktrees = null; // Prepare tree statistics TreeStats tstats = _model._output._treeStats!=null ? _model._output._treeStats : new TreeStats(); // Build trees until we hit the limit for( tid=0; tid<_parms._ntrees; tid++) { // Building tid-tree if (tid!=0 || !_parms._checkpoint) { // do not make initial scoring if model already exist doScoringAndSaveModel(false, _valid==null, _parms._build_tree_one_node); } // At each iteration build K trees (K = nclass = response column domain size) // TODO: parallelize more? build more than k trees at each time, we need to care about temporary data // Idea: launch more DRF at once. Timer kb_timer = new Timer(); ktrees = buildNextKTrees(_train,_mtry,_parms._sample_rate,rand,tid); Log.info((tid+1) + ". tree was built " + kb_timer.toString()); DRF.this.update(1); if( !isRunning() ) return; // If canceled during building, do not bulkscore // Check latest predictions tstats.updateBy(ktrees); _model._output.addKTrees(ktrees); } doScoringAndSaveModel(true, _valid==null, _parms._build_tree_one_node); } // Build the next random k-trees representing tid-th tree private DTree[] buildNextKTrees(Frame fr, int mtrys, float sample_rate, Random rand, int tid) { // We're going to build K (nclass) trees - each focused on correcting // errors for a single class. final DTree[] ktrees = new DTree[_nclass]; // Initial set of histograms. All trees; one leaf per tree (the root // leaf); all columns DHistogram hcs[][][] = new DHistogram[_nclass][1/*just root leaf*/][_ncols]; // Adjust nbins for the top-levels int adj_nbins = Math.max((1<<(10-0)),_parms._nbins); // Use for all k-trees the same seed. NOTE: this is only to make a fair // view for all k-trees final boolean classification = _parms._convert_to_enum; final long[] _distribution = _model._output._distribution; long rseed = rand.nextLong(); // Initially setup as-if an empty-split had just happened for( int k=0; k<_nclass; k++ ) { if( _distribution[k] != 0 ) { // Ignore missing classes // The Boolean Optimization cannot be applied here for RF ! // This optimization assumes the 2nd tree of a 2-class system is the // inverse of the first. This is false for DRF (and true for GBM) - // DRF picks a random different set of columns for the 2nd tree. //if( k==1 && _nclass==2 ) continue; ktrees[k] = new DRFTree(fr,_ncols,(char)_parms._nbins,(char)_nclass,_parms._min_rows,mtrys,rseed); boolean isBinom = classification; new DRFUndecidedNode(ktrees[k],-1, DHistogram.initialHist(fr,_ncols,adj_nbins,hcs[k][0],isBinom) ); // The "root" node } } // Sample - mark the lines by putting 'OUT_OF_BAG' into nid(<klass>) vector Timer t_1 = new Timer(); Sample ss[] = new Sample[_nclass]; for( int k=0; k<_nclass; k++) if (ktrees[k] != null) ss[k] = new Sample((DRFTree)ktrees[k], sample_rate).dfork(0,new Frame(vec_nids(fr,k),vec_resp(fr,k)), _parms._build_tree_one_node); for( int k=0; k<_nclass; k++) if( ss[k] != null ) ss[k].getResult(); Log.debug("Sampling took: + " + t_1); int[] leafs = new int[_nclass]; // Define a "working set" of leaf splits, from leafs[i] to tree._len for each tree i // One Big Loop till the ktrees are of proper depth. // Adds a layer to the trees each pass. Timer t_2 = new Timer(); int depth=0; for( ; depth<_parms._max_depth; depth++ ) { if( !isRunning() ) return null; hcs = buildLayer(fr, _parms._nbins, ktrees, leafs, hcs, true, _parms._build_tree_one_node); // If we did not make any new splits, then the tree is split-to-death if( hcs == null ) break; } Log.debug("Tree build took: " + t_2); // Each tree bottomed-out in a DecidedNode; go 1 more level and insert // LeafNodes to hold predictions. Timer t_3 = new Timer(); for( int k=0; k<_nclass; k++ ) { DTree tree = ktrees[k]; if( tree == null ) continue; int leaf = leafs[k] = tree.len(); for( int nid=0; nid<leaf; nid++ ) { if( tree.node(nid) instanceof DecidedNode ) { DecidedNode dn = tree.decided(nid); for( int i=0; i<dn._nids.length; i++ ) { int cnid = dn._nids[i]; if( cnid == -1 || // Bottomed out (predictors or responses known constant) tree.node(cnid) instanceof UndecidedNode || // Or chopped off for depth (tree.node(cnid) instanceof DecidedNode && // Or not possible to split ((DecidedNode)tree.node(cnid))._split.col()==-1) ) { LeafNode ln = new DRFLeafNode(tree,nid); ln._pred = dn.pred(i); // Set prediction into the leaf dn._nids[i] = ln.nid(); // Mark a leaf here } } // Handle the trivial non-splitting tree if( nid==0 && dn._split.col() == -1 ) new DRFLeafNode(tree,-1,0); } } } // -- k-trees are done Log.debug("Nodes propagation: " + t_3); // Move rows into the final leaf rows Timer t_4 = new Timer(); CollectPreds cp = new CollectPreds(ktrees,leafs).doAll(fr,_parms._build_tree_one_node); final boolean importance = true; //FIXME: cheap enough? if (importance) { if (classification) asVotes(_treeMeasuresOnOOB).append(cp.rightVotes, cp.allRows); // Track right votes over OOB rows for this tree else /* regression */ asSSE (_treeMeasuresOnOOB).append(cp.sse, cp.allRows); } Log.debug("CollectPreds done: " + t_4); // Collect leaves stats for (int i=0; i<ktrees.length; i++) if( ktrees[i] != null ) ktrees[i].leaves = ktrees[i].len() - leafs[i]; // DEBUG: Print the generated K trees //printGenerateTrees(ktrees); return ktrees; } // Collect and write predictions into leafs. private class CollectPreds extends MRTask<CollectPreds> { final DTree _trees[]; // Read-only, shared (except at the histograms in the Nodes) /* @OUT */ long rightVotes; // number of right votes over OOB rows (performed by this tree) represented by DTree[] _trees /* @OUT */ long allRows; // number of all OOB rows (sampled by this tree) /* @OUT */ float sse; // Sum of squares for this tree only CollectPreds(DTree trees[], int leafs[]) { _trees=trees; } final boolean importance = true; @Override public void map( Chunk[] chks ) { final Chunk y = importance ? chk_resp(chks) : null; // Response final float [] rpred = importance ? new float [1+_nclass] : null; // Row prediction final double[] rowdata = importance ? new double[_ncols] : null; // Pre-allocated row data final Chunk oobt = chk_oobt(chks); // Out-of-bag rows counter over all trees // Iterate over all rows for( int row=0; row<oobt._len; row++ ) { boolean wasOOBRow = false; // For all tree (i.e., k-classes) for( int k=0; k<_nclass; k++ ) { final DTree tree = _trees[k]; if( tree == null ) continue; // Empty class is ignored // If we have all constant responses, then we do not split even the // root and the residuals should be zero. if( tree.root() instanceof LeafNode ) continue; final Chunk nids = chk_nids(chks,k); // Node-ids for this tree/class final Chunk ct = chk_tree(chks,k); // k-tree working column holding votes for given row int nid = (int)nids.at8(row); // Get Node to decide from // Update only out-of-bag rows // This is out-of-bag row - but we would like to track on-the-fly prediction for the row if( ScoreBuildHistogram.isOOBRow(nid) ) { // The row should be OOB for all k-trees !!! assert k==0 || wasOOBRow : "Something is wrong: k-class trees oob row computing is broken! All k-trees should agree on oob row!"; wasOOBRow = true; nid = ScoreBuildHistogram.oob2Nid(nid); if( tree.node(nid) instanceof UndecidedNode ) // If we bottomed out the tree nid = tree.node(nid).pid(); // Then take parent's decision DecidedNode dn = tree.decided(nid); // Must have a decision point if( dn._split.col() == -1 ) // Unable to decide? dn = tree.decided(tree.node(nid).pid()); // Then take parent's decision int leafnid = dn.ns(chks,row); // Decide down to a leafnode // Setup Tree(i) - on the fly prediction of i-tree for row-th row // - for classification: cumulative number of votes for this row // - for regression: cumulative sum of prediction of each tree - has to be normalized by number of trees double prediction = ((LeafNode)tree.node(leafnid)).pred(); // Prediction for this k-class and this row if (importance) rpred[1+k] = (float) prediction; // for both regression and classification ct.set(row, (float) (ct.atd(row) + prediction)); // For this tree this row is out-of-bag - i.e., a tree voted for this row oobt.set(row, _nclass > 1 ? 1 : oobt.atd(row) + 1); // for regression track number of trees, for classification boolean flag is enough } // reset help column for this row and this k-class nids.set(row, 0); } /* end of k-trees iteration */ if (importance) { if (wasOOBRow && !y.isNA(row)) { if (_parms._convert_to_enum) { int treePred = getPrediction(rpred, data_row(chks, row, rowdata)); int actuPred = (int) y.at8(row); if (treePred==actuPred) rightVotes++; // No miss ! } else { // regression float treePred = rpred[1]; float actuPred = (float) y.atd(row); sse += (actuPred-treePred)*(actuPred-treePred); } allRows++; } } } } @Override public void reduce(CollectPreds mrt) { rightVotes += mrt.rightVotes; allRows += mrt.allRows; sse += mrt.sse; } } @Override protected DRFModel makeModel( Key modelKey, DRFModel.DRFParameters parms, double mse_train, double mse_valid ) { return new DRFModel(modelKey,parms,new DRFModel.DRFOutput(DRF.this,mse_train,mse_valid)); } } @Override protected DecidedNode makeDecided( UndecidedNode udn, DHistogram hs[] ) { return new DRFDecidedNode(udn,hs); } // DRF DTree decision node: same as the normal DecidedNode, but // specifies a decision algorithm given complete histograms on all // columns. DRF algo: find the lowest error amongst *all* columns. static class DRFDecidedNode extends DecidedNode { DRFDecidedNode( UndecidedNode n, DHistogram[] hs ) { super(n,hs); } @Override public UndecidedNode makeUndecidedNode(DHistogram[] hs ) { return new DRFUndecidedNode(_tree,_nid,hs); } // Find the column with the best split (lowest score). Unlike RF, DRF // scores on all columns and selects splits on all columns. @Override public DTree.Split bestCol( UndecidedNode u, DHistogram[] hs ) { DTree.Split best = new DTree.Split(-1,-1,null,(byte)0,Double.MAX_VALUE,Double.MAX_VALUE,Double.MAX_VALUE,0L,0L,0,0); if( hs == null ) return best; for( int i=0; i<u._scoreCols.length; i++ ) { int col = u._scoreCols[i]; DTree.Split s = hs[col].scoreMSE(col, _tree._min_rows); if( s == null ) continue; if( s.se() < best.se() ) best = s; if( s.se() <= 0 ) break; // No point in looking further! } return best; } } // DRF DTree undecided node: same as the normal UndecidedNode, but specifies // a list of columns to score on now, and then decide over later. // DRF algo: use all columns static class DRFUndecidedNode extends UndecidedNode { DRFUndecidedNode( DTree tree, int pid, DHistogram hs[] ) { super(tree,pid,hs); } // Randomly select mtry columns to 'score' in following pass over the data. @Override public int[] scoreCols( DHistogram[] hs ) { DRFTree tree = (DRFTree)_tree; int[] cols = new int[hs.length]; int len=0; // Gather all active columns to choose from. for( int i=0; i<hs.length; i++ ) { if( hs[i]==null ) continue; // Ignore not-tracked cols assert hs[i]._min < hs[i]._maxEx && hs[i].nbins() > 1 : "broken histo range "+hs[i]; cols[len++] = i; // Gather active column } int choices = len; // Number of columns I can choose from assert choices > 0; // Draw up to mtry columns at random without replacement. for( int i=0; i<tree._mtrys; i++ ) { if( len == 0 ) break; // Out of choices! int idx2 = tree._rand.nextInt(len); int col = cols[idx2]; // The chosen column cols[idx2] = cols[--len]; // Compress out of array; do not choose again cols[len] = col; // Swap chosen in just after 'len' } assert choices - len > 0; return Arrays.copyOfRange(cols, len, choices); } } static class DRFLeafNode extends LeafNode { DRFLeafNode( DTree tree, int pid ) { super(tree,pid); } DRFLeafNode( DTree tree, int pid, int nid ) { super(tree, pid, nid); } // Insert just the predictions: a single byte/short if we are predicting a // single class, or else the full distribution. @Override protected AutoBuffer compress(AutoBuffer ab) { assert !Double.isNaN(_pred); return ab.put4f((float)_pred); } @Override protected int size() { return 4; } } // Deterministic sampling static class Sample extends MRTask<Sample> { final DRFTree _tree; final float _rate; Sample( DRFTree tree, float rate ) { _tree = tree; _rate = rate; } @Override public void map( Chunk nids, Chunk ys ) { Random rand = _tree.rngForChunk(nids.cidx()); for( int row=0; row<nids._len; row++ ) if( rand.nextFloat() >= _rate || Double.isNaN(ys.atd(row)) ) { nids.set(row, ScoreBuildHistogram.OUT_OF_BAG); // Flag row as being ignored by sampling } } } // Read the 'tree' columns, do model-specific math and put the results in the // fs[] array, and return the sum. Dividing any fs[] element by the sum // turns the results into a probability distribution. @Override protected float score1( Chunk chks[], float fs[/*nclass*/], int row ) { float sum=0; for( int k=0; k<_nclass; k++ ) // Sum across of likelyhoods sum+=(fs[k+1]=(float)chk_tree(chks,k).atd(row)); if (_nclass == 1) sum /= (float)chk_oobt(chks).atd(row); // for regression average per trees voted for this row (only trees which have row in "out-of-bag" return sum; } }
package to.mmo.cmdlineoptions; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.List; public class CmdOptions { private static CmdOptions instance; public static class Option { private String name; private ArrayList<String> cmd; private String description; private ArrayList<String> defaultParameter; private ArrayList<String> possibleParams; private boolean set; private ArrayList<String> values; public ArrayList<String> getValues() { return values; } public ArrayList<String> getDefaultParameter() { return defaultParameter; } public Option() { values = new ArrayList<String>(); cmd = new ArrayList<String>(); defaultParameter = new ArrayList<String>(); possibleParams = new ArrayList<String>(); } public Option addCommand(String cmd) { this.cmd.add(cmd); return this; } public Option addDefaultParameter(String d) { this.defaultParameter.add(d); return this; } public Option addPossibleParameter(String p) { this.possibleParams.add(p); return this; } public Option addValue(String value) { this.values.add(value); return this; } public String getName() { return name; } public Option setName(String name) { this.name = name; return this; } public String getDescription() { return description; } public Option setDescription(String description) { this.description = description; return this; } public boolean isSet() { return set; } public boolean valuesContains(String value) { return values.contains(value); } public int getIndexOf(String value) { return values.indexOf(value); } public Option setSet(boolean set) { this.set = set; return this; } public String toString() { String ret = name + " ("; for (String s : cmd) { ret += s + ", "; } ret += ")" + (defaultParameter != null ? ": default=" + defaultParameter : "") + (description != null ? "\n\t\t" + description : ""); if (possibleParams != null) { boolean start = true; ret += "\n\t\t(Possible parameters: "; for (String s : possibleParams) { ret += (start ? "" : ", ") + s; start = false; } ret += ")"; } if (set) { ret += "\n\t\t--> current Setting: "; if (values.size() > 0) { boolean start = true; for (String s : values) { ret += (start ? "" : ",") + s; start = false; } } else { ret += "true"; } // ret += "\n"; } return ret; } } private HashMap<String, Option> options; private CmdOptions() { options = new HashMap<String, Option>(); this.createOption("help") .setDescription( "Show all possible options and their parameters.") .addCommand("--help").addCommand("-h").addCommand("-?"); } public static CmdOptions i() { if (instance == null) { instance = new CmdOptions(); } return instance; } public Option createOption(String name) { Option o = new Option(); o.setName(name); this.options.put(name, o); return o; } public String[] get(String name) { return getOption(name); } public String[] getOption(String name) { if (options.get(name).values.size() > 0) return options.get(name).values.toArray(new String[0]); else if (options.get(name).defaultParameter != null) return options.get(name).getValues().toArray(new String[0]); return null; } public List<String> getValuesAsList(String name) { if (options.get(name).getValues().size() > 0) { return options.get(name).getValues(); } return null; } public Integer[] getOptionAsInt(String name) { if (options.get(name).values.size() > 0) { ArrayList<Integer> list = new ArrayList<Integer>(); for (String o : options.get(name).values) { list.add(Integer.parseInt(o)); } return list.toArray(new Integer[0]); } else if (options.get(name).getDefaultParameter().size() > 0) { ArrayList<Integer> list = new ArrayList<Integer>(); for (String o : options.get(name).getDefaultParameter()) { list.add(Integer.parseInt(o)); } return list.toArray(new Integer[0]); } return null; } public Double[] getOptionAsDouble(String name) { if (options.get(name).values.size() > 0) { ArrayList<Double> list = new ArrayList<Double>(); for (String o : options.get(name).values) { list.add(Double.parseDouble(o)); } return list.toArray(new Double[0]); } else if (options.get(name).getDefaultParameter().size() > 0) { ArrayList<Double> list = new ArrayList<Double>(); for (String o : options.get(name).getDefaultParameter()) { list.add(Double.parseDouble(o)); } return list.toArray(new Double[0]); } return null; } public boolean isSet(String option) { return options.get(option).set; } public boolean isSet(String option, String parameter) { for (String o : options.get(option).values) { if (o.equals(parameter)) { return true; } } return false; } public String toString(boolean help) { StringBuilder b = new StringBuilder(); if (help) { b.append("Possible options:\n"); } b.append("-options\n"); Option[] vars = options.values().toArray(new Option[0]); Arrays.sort(vars, new Comparator<Option>() { @Override public int compare(Option o1, Option o2) { return o1.name.compareTo(o2.name); } }); for (Option o : vars) { b.append("\t").append(o.toString()).append("\n"); } b.append("/options\n"); return b.toString(); } public void parse(String[] args) { // now parse if (args.length > 0) { int i = 0; String arg = null; // iterate through all options for (; i < args.length; ++i) { arg = args[i]; Option o = null; // search for correct option for (Option op : options.values()) { for (String s : op.cmd) if (arg.equals(s)) { o = op; break; } } // if it is unknown if (o == null) { System.err.println("Unrecognized option '" + arg + "'"); continue; } o.set = true; // now iterate through the parameters int j = i + 1; while (args.length > j && !args[j].startsWith("-")) { if (o.possibleParams.size() > 0) { if (o.possibleParams.contains(args[j])) o.values.add(args[j]); else System.err.println("Parameter \"" + args[j] + "\" for Option \"" + o.name + "\" not allowed!"); } else { o.values.add(args[j]); } ++j; } i = j - 1; } } if (options.get("help").set) { System.out.println(this.toString(true)); System.exit(0); } // set default for that options that aren't set for (Option o : options.values()) { if (!o.set && o.defaultParameter != null && o.defaultParameter.equals("")) { System.err .println(o.name + " (" + o.getName() + "): has no default parameter and has to be set on commandline!"); System.exit(1); } if (!o.set && o.defaultParameter != null) o.values.addAll(o.defaultParameter); } System.out.println(this.toString(false)); } }
package org.jpos.q2; import org.jline.reader.LineReader; import org.jpos.util.Loggeable; import java.io.*; import java.util.LinkedHashMap; import java.util.Map; public class CLIContext { private boolean stopped = false; private OutputStream out; private OutputStream err; private InputStream in; private LineReader reader; private Map<Object, Object> userData; private CLI cli; private String activeSubSystem = null; @SuppressWarnings("unused") private CLIContext() { } private CLIContext(CLI cli, OutputStream out, OutputStream err, InputStream in, LineReader reader, Map<Object, Object> userData) { this.cli = cli; this.out = out; this.err = err; this.in = in; this.reader = reader; this.userData = userData; } public String getActiveSubSystem() { return activeSubSystem; } public void setActiveSubSystem(String subSystem) { String activeSubSystem = getActiveSubSystem(); if (subSystem == null && activeSubSystem != null) { getUserData().remove(activeSubSystem); } this.activeSubSystem = subSystem; } public boolean isStopped() { return stopped; } public void setStopped(boolean stopped) { this.stopped = stopped; } public LineReader getReader() { return reader; } public void setReader(LineReader reader) { this.reader = reader; } public OutputStream getOutputStream() { return out; } public OutputStream getErrorStream() { return err; } public InputStream getInputStream() { return in; } public Map<Object,Object> getUserData() { return userData; } public boolean isInteractive() { return cli.isInteractive(); } public CLI getCLI() { return cli; } public void printUserData() { getUserData().forEach((k,v) -> { println("Key: " + k.toString()); println("Value: " + v.toString()); }); } public void printThrowable(Throwable t) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); t.printStackTrace(new PrintStream(baos)); println (baos.toString()); } public void printLoggeable(Loggeable l, String indent) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); l.dump (new PrintStream(baos), indent); println (baos.toString()); } public void print(String s) { if (isInteractive()) { PrintWriter writer = getReader().getTerminal().writer(); writer.print(s); writer.flush(); } else { try { out.write(s.getBytes()); out.flush(); } catch (IOException ignored) { ignored.printStackTrace(); } } } public void println(String s) { print (s + System.getProperty("line.separator")); } public boolean confirm(String prompt) { return "yes".equalsIgnoreCase(getReader().readLine(prompt)); } public String readSecurely(String prompt) { return getReader().readLine(prompt, '*'); } public static Builder builder() { return new Builder(); } public static class Builder { OutputStream out; OutputStream err; InputStream in; LineReader reader; CLI cli; private Builder () { } public Builder out (OutputStream out) { this.out = out; return this; } public Builder err (OutputStream err) { this.err = err; return this; } public Builder in (InputStream in) { this.in = in; return this; } public Builder reader (LineReader reader) { this.reader = reader; return this; } public Builder cli (CLI cli) { this.cli = cli; return this; } public CLIContext build() { if (reader != null) { if (out == null) out = reader.getTerminal().output(); if (err == null) err = out; } return new CLIContext(cli, out, err, in, reader, new LinkedHashMap()); } } }
package com.allforfunmc.refineddiamond; import com.allforfunmc.scaffolding.BlockOfScaffolding; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.Item.ToolMaterial; import net.minecraft.item.ItemStack; import net.minecraftforge.common.util.EnumHelper; import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class Code { public static Item refinedDiamond; public static Item hotDiamond; public static Item refinedpick; public static Item refinedaxe; public static Block Refined_Diamond_Block; public static void Items() { ToolMaterial RefinedDiamondTool = EnumHelper.addToolMaterial("refinedDiamond", 5, 3500, 50F, 15, 1); refinedDiamond = new RefinedDiamond(); GameRegistry.registerItem(refinedDiamond, "refinedDiamond"); hotDiamond = new HotDiamond(); GameRegistry.registerItem(hotDiamond, "hotDiamond"); refinedpick = new RefinedPick(RefinedDiamondTool); GameRegistry.registerItem(refinedpick, "refinedpick"); GameRegistry.addSmelting(new ItemStack(Items.diamond), new ItemStack(hotDiamond), 0F); GameRegistry.addSmelting(new ItemStack(refinedDiamond), new ItemStack(hotDiamond, 2), 0F); refinedaxe = new RefinedAxe(RefinedDiamondTool); GameRegistry.registerItem(refinedaxe, "refinedaxe"); /* * Recipes */ //Shapeless Recipes GameRegistry.addShapelessRecipe(new ItemStack(Items.diamond), new ItemStack(hotDiamond)); //Shaped Recipes GameRegistry.addRecipe(new ItemStack(refinedDiamond,2), new Object[] { " H ", "H H", " H ", 'H', hotDiamond }); GameRegistry.addRecipe(new ItemStack(refinedpick), new Object[]{ "RRR", " S ", " S ", 'R', refinedDiamond, 'S', Items.stick }); /* * Block */ Refined_Diamond_Block = new Refined_Diamond_Block(Material.rock); GameRegistry.registerBlock(Refined_Diamond_Block, "Refined_Diamond_Block"); GameRegistry.addRecipe(new ItemStack(Refined_Diamond_Block), new Object[]{ "RRR", "RRR", "RRR", 'R', refinedDiamond }); /* * Tab */ public static CreativeTabs tabCustom = new CreativeTabs("All For Fun Mods") { @Override @SideOnly(Side.CLIENT) public Item getTabIconItem() { return Items.ender_eye; } }; } }
package foam.nanos.http; import com.sun.net.httpserver.*; import foam.core.*; import foam.dao.DAO; import foam.nanos.*; import java.io.IOException; import java.net.URI; import javax.servlet.http.HttpServlet; public class NanoHttpHandler extends ContextAwareSupport implements HttpHandler { public NanoHttpHandler(X x) { x_ = x; } @Override public void handle(HttpExchange exchange) throws IOException { URI requestURI = exchange.getRequestURI(); String path = requestURI.getPath(); String query = requestURI.getQuery(); // AuthService auth = this.X.get(AuthService); String[] urlParams = path.split("/"); /* * Get the item right after the first slash * E.g.: /foo/bar => ['', 'foo', 'bar'] */ String serviceKey = urlParams[1]; Object service = x_.get(serviceKey); System.out.println("HTTP Request: " + path + ", " + serviceKey); if ( service instanceof HttpHandler ) { ((HttpHandler) service).handle(exchange); } if ( service instanceof HttpServlet ) { this.handleServlet((HttpServlet) service, exchange); } if ( service instanceof DAO ) { // todo auth check, server==true check this.handleServlet(new ServiceServlet(service), exchange); } else { String errorMsg = "Service " + serviceKey + " does not have a HttpHandler"; throw new RuntimeException(errorMsg); } } public void handleServlet(HttpServlet s, HttpExchange exchange) throws IOException { if ( s instanceof ContextAware ) ((ContextAware) s).setX(this.getX()); new ServletHandler(s).handle(exchange); } }
package leapTools; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; import org.apache.tools.ant.DirectoryScanner; import java.io.*; /** ANT-task preprocessing JADE sources into JADE-LEAP sources for J2SE, PJAVA and MIDP environments @author Giovanni Caire - TILAB */ public class Preprocessor extends Task { // File exclusion markers private static final String ALL_EXCLUDE_FILE_MARKER = "//#ALL_EXCLUDE_FILE"; private static final String J2SE_EXCLUDE_FILE_MARKER = "//#J2SE_EXCLUDE_FILE"; private static final String J2ME_EXCLUDE_FILE_MARKER = "//#J2ME_EXCLUDE_FILE"; private static final String PJAVA_EXCLUDE_FILE_MARKER = "//#PJAVA_EXCLUDE_FILE"; private static final String MIDP_EXCLUDE_FILE_MARKER = "//#MIDP_EXCLUDE_FILE"; private static final String DOTNET_EXCLUDE_FILE_MARKER = "//#DOTNET_EXCLUDE_FILE"; private static final String ANDROID_EXCLUDE_FILE_MARKER = "//#ANDROID_EXCLUDE_FILE"; // Code exclusion/inclusion markers. Note that the LEAP preprocessor // directives are conceived so that the non-preprocessed version of // a file is the version for J2SE (except for JADE-only code) --> // There is no need for J2SE specific code exclusion/inclusion markers private static final String ALL_EXCLUDE_BEGIN_MARKER = "//#ALL_EXCLUDE_BEGIN"; private static final String ALL_EXCLUDE_END_MARKER = "//#ALL_EXCLUDE_END"; private static final String ALL_INCLUDE_BEGIN_MARKER = "/*#ALL_INCLUDE_BEGIN"; private static final String ALL_INCLUDE_END_MARKER = "#ALL_INCLUDE_END*/"; private static final String J2SE_EXCLUDE_BEGIN_MARKER = "//#J2SE_EXCLUDE_BEGIN"; private static final String J2SE_EXCLUDE_END_MARKER = "//#J2SE_EXCLUDE_END"; private static final String J2SE_INCLUDE_BEGIN_MARKER = "/*#J2SE_INCLUDE_BEGIN"; private static final String J2SE_INCLUDE_END_MARKER = "#J2SE_INCLUDE_END*/"; private static final String J2ME_EXCLUDE_BEGIN_MARKER = "//#J2ME_EXCLUDE_BEGIN"; private static final String J2ME_EXCLUDE_END_MARKER = "//#J2ME_EXCLUDE_END"; private static final String J2ME_INCLUDE_BEGIN_MARKER = "/*#J2ME_INCLUDE_BEGIN"; private static final String J2ME_INCLUDE_END_MARKER = "#J2ME_INCLUDE_END*/"; private static final String PJAVA_EXCLUDE_BEGIN_MARKER = "//#PJAVA_EXCLUDE_BEGIN"; private static final String PJAVA_EXCLUDE_END_MARKER = "//#PJAVA_EXCLUDE_END"; private static final String PJAVA_INCLUDE_BEGIN_MARKER = "/*#PJAVA_INCLUDE_BEGIN"; private static final String PJAVA_INCLUDE_END_MARKER = "#PJAVA_INCLUDE_END*/"; private static final String MIDP_EXCLUDE_BEGIN_MARKER = "//#MIDP_EXCLUDE_BEGIN"; private static final String MIDP_EXCLUDE_END_MARKER = "//#MIDP_EXCLUDE_END"; private static final String MIDP_INCLUDE_BEGIN_MARKER = "/*#MIDP_INCLUDE_BEGIN"; private static final String MIDP_INCLUDE_END_MARKER = "#MIDP_INCLUDE_END*/"; private static final String DOTNET_EXCLUDE_BEGIN_MARKER = "//#DOTNET_EXCLUDE_BEGIN"; private static final String DOTNET_EXCLUDE_END_MARKER = "//#DOTNET_EXCLUDE_END"; private static final String DOTNET_INCLUDE_BEGIN_MARKER = "/*#DOTNET_INCLUDE_BEGIN"; private static final String DOTNET_INCLUDE_END_MARKER = "#DOTNET_INCLUDE_END*/"; private static final String ANDROID_EXCLUDE_BEGIN_MARKER = "//#ANDROID_EXCLUDE_BEGIN"; private static final String ANDROID_EXCLUDE_END_MARKER = "//#ANDROID_EXCLUDE_END"; private static final String ANDROID_INCLUDE_BEGIN_MARKER = "/*#ANDROID_INCLUDE_BEGIN"; private static final String ANDROID_INCLUDE_END_MARKER = "#ANDROID_INCLUDE_END*/"; // No-debug version generation markers private static final String NODEBUG_EXCLUDE_BEGIN_MARKER = "//#NODEBUG_EXCLUDE_BEGIN"; private static final String NODEBUG_EXCLUDE_END_MARKER = "//#NODEBUG_EXCLUDE_END"; // Predefined preprocessing types private static final String J2SE = "j2se"; private static final String PJAVA = "pjava"; private static final String MIDP = "midp"; private static final String DOTNET = "DotNET"; private static final String ANDROID = "android"; // Preprocessing results private static final int KEEP = 0; private static final int OVERWRITE = 1; private static final int REMOVE = 2; private boolean verbose = false; private int removedCnt = 0; private int modifiedCnt = 0; // The file that is being preprocessed private String target; // The base directory for recursive pre-processing private String basedir; // The type of preprocessing private String type; // The setter method for the "target" attribute public void setTarget(String target) { this.target = target; } // The setter method for the "basedir" attribute public void setBasedir(String basedir) { this.basedir = basedir; } // The setter method for the "type" attribute public void setType(String type) { this.type = type; } // The setter method for the "verbose" attribute public void setVerbose(boolean verbose) { this.verbose = verbose; } // The method executing the task public void execute() throws BuildException { // Prepare appropriate preprocessing markers String[] ebms = null; String[] eems = null; String[] ims = null; String[] efms = null; if (DOTNET.equalsIgnoreCase(type)) { // For DOTNET ebms = new String[] { ALL_EXCLUDE_BEGIN_MARKER, J2ME_EXCLUDE_BEGIN_MARKER, PJAVA_EXCLUDE_BEGIN_MARKER, DOTNET_EXCLUDE_BEGIN_MARKER, ANDROID_EXCLUDE_BEGIN_MARKER}; eems = new String[] { ALL_EXCLUDE_END_MARKER, J2ME_EXCLUDE_END_MARKER, PJAVA_EXCLUDE_END_MARKER, DOTNET_EXCLUDE_END_MARKER, ANDROID_EXCLUDE_END_MARKER}; ims = new String[] { ALL_INCLUDE_BEGIN_MARKER, ALL_INCLUDE_END_MARKER, J2ME_INCLUDE_BEGIN_MARKER, J2ME_INCLUDE_END_MARKER, PJAVA_INCLUDE_BEGIN_MARKER, PJAVA_INCLUDE_END_MARKER, DOTNET_INCLUDE_BEGIN_MARKER, DOTNET_INCLUDE_END_MARKER, ANDROID_INCLUDE_BEGIN_MARKER, ANDROID_INCLUDE_END_MARKER}; efms = new String[] { ALL_EXCLUDE_FILE_MARKER, DOTNET_EXCLUDE_FILE_MARKER}; } else if (MIDP.equalsIgnoreCase(type)) { // For MIDP ebms = new String[] { ALL_EXCLUDE_BEGIN_MARKER, J2ME_EXCLUDE_BEGIN_MARKER, MIDP_EXCLUDE_BEGIN_MARKER, J2SE_EXCLUDE_BEGIN_MARKER}; eems = new String[] { ALL_EXCLUDE_END_MARKER, J2ME_EXCLUDE_END_MARKER, MIDP_EXCLUDE_END_MARKER, J2SE_EXCLUDE_END_MARKER}; ims = new String[] { ALL_INCLUDE_BEGIN_MARKER, ALL_INCLUDE_END_MARKER, J2ME_INCLUDE_BEGIN_MARKER, J2ME_INCLUDE_END_MARKER, MIDP_INCLUDE_BEGIN_MARKER, MIDP_INCLUDE_END_MARKER}; efms = new String[] { ALL_EXCLUDE_FILE_MARKER, J2ME_EXCLUDE_FILE_MARKER, MIDP_EXCLUDE_FILE_MARKER}; } else if (PJAVA.equalsIgnoreCase(type)) { // For PJAVA ebms = new String[] { ALL_EXCLUDE_BEGIN_MARKER, J2ME_EXCLUDE_BEGIN_MARKER, PJAVA_EXCLUDE_BEGIN_MARKER, J2SE_EXCLUDE_BEGIN_MARKER}; eems = new String[] { ALL_EXCLUDE_END_MARKER, J2ME_EXCLUDE_END_MARKER, PJAVA_EXCLUDE_END_MARKER, J2SE_EXCLUDE_END_MARKER}; ims = new String[] { ALL_INCLUDE_BEGIN_MARKER, ALL_INCLUDE_END_MARKER, J2ME_INCLUDE_BEGIN_MARKER, J2ME_INCLUDE_END_MARKER, PJAVA_INCLUDE_BEGIN_MARKER, PJAVA_INCLUDE_END_MARKER}; efms = new String[] { ALL_EXCLUDE_FILE_MARKER, J2ME_EXCLUDE_FILE_MARKER, PJAVA_EXCLUDE_FILE_MARKER}; } else if (ANDROID.equalsIgnoreCase(type)) { // For ANDROID ebms = new String[] { ALL_EXCLUDE_BEGIN_MARKER, J2ME_EXCLUDE_BEGIN_MARKER, ANDROID_EXCLUDE_BEGIN_MARKER, J2SE_EXCLUDE_BEGIN_MARKER}; eems = new String[] { ALL_EXCLUDE_END_MARKER, J2ME_EXCLUDE_END_MARKER, ANDROID_EXCLUDE_END_MARKER, J2SE_EXCLUDE_END_MARKER}; ims = new String[] { ALL_INCLUDE_BEGIN_MARKER, ALL_INCLUDE_END_MARKER, J2ME_INCLUDE_BEGIN_MARKER, J2ME_INCLUDE_END_MARKER, ANDROID_INCLUDE_BEGIN_MARKER, ANDROID_INCLUDE_END_MARKER}; efms = new String[] { ALL_EXCLUDE_FILE_MARKER, J2ME_EXCLUDE_FILE_MARKER, ANDROID_EXCLUDE_FILE_MARKER}; } else if (J2SE.equalsIgnoreCase(type)) { // For J2SE ebms = new String[] { ALL_EXCLUDE_BEGIN_MARKER, J2SE_EXCLUDE_BEGIN_MARKER}; eems = new String[] { ALL_EXCLUDE_END_MARKER, J2SE_EXCLUDE_END_MARKER}; ims = new String[] { ALL_INCLUDE_BEGIN_MARKER, ALL_INCLUDE_END_MARKER, J2SE_INCLUDE_BEGIN_MARKER, J2SE_INCLUDE_END_MARKER}; efms = new String[] { ALL_EXCLUDE_FILE_MARKER, J2SE_EXCLUDE_FILE_MARKER}; } else { // User defined preprocessing type String upperCaseType = type.toUpperCase(); ebms = new String[] {"//#"+upperCaseType+"_EXCLUDE_BEGIN"}; eems = new String[] {"//#"+upperCaseType+"_EXCLUDE_END"}; ims = new String[] { "/*#"+upperCaseType+"_INCLUDE_BEGIN", "#"+upperCaseType+"_INCLUDE_END*/", }; efms = new String[] {"//#"+upperCaseType+"_EXCLUDE_FILE"}; } if (basedir != null) { // Recursive preprocessing (use basedir arg and ignore target arg if any) File d = new File(basedir); if (d.isDirectory()) { DirectoryScanner scanner = new DirectoryScanner(); scanner.setBasedir(d); scanner.setIncludes(new String[] {"**/*.java"}); scanner.scan(); String[] files = scanner.getIncludedFiles(); System.out.println("Preprocessing "+files.length+" files."); for (int i = 0; i < files.length; ++i) { execute(d.getPath()+"/"+files[i], ebms, eems, ims, efms); } System.out.println("Modified "+modifiedCnt+" files."); System.out.println("Removed "+removedCnt+" files."); } else { throw new BuildException("Error: "+basedir+" is not a directory."); } } else { // Single file preprocessing (use target arg and ignore basedir arg if any) execute(target, ebms, eems, ims, efms); } } /** Preprocess a single file */ private void execute(String file, String[] ebms, String[] eems, String[] ims, String[] efms) throws BuildException { if (verbose) { System.out.println("Preprocessing file "+file+" (type: "+type+")"); } try { // Get a reader to read the file File targetFile = new File(file); FileReader fr = new FileReader(targetFile); BufferedReader reader = new BufferedReader(fr); // Get a writer to write into the preprocessed file File preprocFile = File.createTempFile(targetFile.getName(), "tmp", targetFile.getParentFile()); FileWriter fw = new FileWriter(preprocFile); BufferedWriter writer = new BufferedWriter(fw); // Preprocess int result = preprocess(reader, writer, ebms, eems, ims, efms); // Close both streams reader.close(); writer.close(); switch (result) { case OVERWRITE: // The preprocessing modified the target file. // Overwrite it with the preprocessed one if (!targetFile.delete()) { System.out.println("Can't overwrite target file with preprocessed file"); throw new BuildException("Can't overwrite target file "+target+" with preprocessed file"); } preprocFile.renameTo(targetFile); if (verbose) { System.out.println("File "+preprocFile.getName()+" modified."); } modifiedCnt++; break; case REMOVE: // The preprocessing found that the target file must be excluded. // Remove both the target file and the preprocessed one if (!targetFile.delete()) { System.out.println("Can't delete target file"); throw new BuildException("Can't delete target file "+target); } if (!preprocFile.delete()) { System.out.println("Can't delete temporary preprocessed file "+preprocFile.getName()); throw new BuildException("Can't delete temporary preprocessed file "+preprocFile.getName()); } if (verbose) { System.out.println("File "+preprocFile.getName()+" removed."); } removedCnt++; break; case KEEP: // The preprocessing didn't touch the target file. // Just removed the preprocessed file if (!preprocFile.delete()) { System.out.println("Can't delete temporary preprocessed file "+preprocFile.getName()); throw new BuildException("Can't delete temporary preprocessed file "+preprocFile.getName()); } break; default: throw new BuildException("Unexpected preprocessing result for file "+preprocFile.getName()); } } catch (Exception e) { e.printStackTrace(); throw new BuildException(e.getMessage()); } } private int preprocess(BufferedReader reader, BufferedWriter writer, String[] excludeBeginMarkers, String[] excludeEndMarkers, String[] includeMarkers, String[] excludeFileMarkers) throws IOException { String line = null; boolean skip = false; int result = KEEP; String nextExcludeEndMarker = null; while (true) { line = reader.readLine(); if (line == null) { // Preprocessing terminated break; } String trimmedLine = line.trim(); // Check if this is an exclude-file marker if (isMarker(trimmedLine, excludeFileMarkers)) { return REMOVE; } if (!skip) { // Normal processing: Check if this is an EXCLUDE_BEGIN Marker if (isMarker(trimmedLine, excludeBeginMarkers)) { // Enter SKIP mode result = OVERWRITE; skip = true; nextExcludeEndMarker = getExcludeEndMarker(trimmedLine, excludeEndMarkers); } else { // Just copy the line into the preprocessed file unless // the (trimmed) line starts with an INCLUDE Marker if (!isMarker(trimmedLine, includeMarkers)) { writer.write(line); writer.newLine(); } else { result = OVERWRITE; } } } else { // SKIP mode if (trimmedLine.startsWith(nextExcludeEndMarker)) { // Exit SKIP mode skip = false; nextExcludeEndMarker = null; } } } return result; } private boolean isMarker(String s, String[] markers) { for (int i = 0; i < markers.length; ++i) { if (s.startsWith(markers[i])) { return true; } } return false; } private String getExcludeEndMarker(String s, String[] endMarkers) { int rootLength = s.indexOf("BEGIN"); String root = s.substring(0, rootLength); for (int i = 0; i < endMarkers.length; ++i) { if (endMarkers[i].startsWith(root)) { return endMarkers[i]; } } return null; } }
package cgeo.geocaching.network; import cgeo.geocaching.files.LocalStorage; import cgeo.geocaching.settings.Settings; import cgeo.geocaching.utils.Log; import cgeo.geocaching.utils.TextUtils; import ch.boye.httpclientandroidlib.HttpEntity; import ch.boye.httpclientandroidlib.HttpResponse; import ch.boye.httpclientandroidlib.NameValuePair; import ch.boye.httpclientandroidlib.client.HttpClient; import ch.boye.httpclientandroidlib.client.entity.UrlEncodedFormEntity; import ch.boye.httpclientandroidlib.client.methods.HttpGet; import ch.boye.httpclientandroidlib.client.methods.HttpPost; import ch.boye.httpclientandroidlib.client.methods.HttpRequestBase; import ch.boye.httpclientandroidlib.client.params.ClientPNames; import ch.boye.httpclientandroidlib.entity.StringEntity; import ch.boye.httpclientandroidlib.entity.mime.MultipartEntity; import ch.boye.httpclientandroidlib.entity.mime.content.FileBody; import ch.boye.httpclientandroidlib.entity.mime.content.StringBody; import ch.boye.httpclientandroidlib.impl.client.DecompressingHttpClient; import ch.boye.httpclientandroidlib.impl.client.DefaultHttpClient; import ch.boye.httpclientandroidlib.impl.client.LaxRedirectStrategy; import ch.boye.httpclientandroidlib.params.BasicHttpParams; import ch.boye.httpclientandroidlib.params.CoreConnectionPNames; import ch.boye.httpclientandroidlib.params.CoreProtocolPNames; import ch.boye.httpclientandroidlib.params.HttpParams; import ch.boye.httpclientandroidlib.util.EntityUtils; import org.apache.commons.lang3.CharEncoding; import org.apache.commons.lang3.StringUtils; import org.eclipse.jdt.annotation.Nullable; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.nio.charset.Charset; public abstract class Network { /** User agent id */ private final static String PC_USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1"; /** Native user agent, taken from a Android 2.2 Nexus **/ private final static String NATIVE_USER_AGENT = "Mozilla/5.0 (Linux; U; Android 2.2; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1"; private static final String PATTERN_PASSWORD = "(?<=[\\?&])[Pp]ass(w(or)?d)?=[^& private static final Charset CHARSET_UTF8 = Charset.forName("UTF-8"); private final static HttpParams clientParams = new BasicHttpParams(); static { clientParams.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, CharEncoding.UTF_8); clientParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000); clientParams.setParameter(CoreConnectionPNames.SO_TIMEOUT, 90000); clientParams.setParameter(ClientPNames.HANDLE_REDIRECTS, true); } private static String hidePassword(final String message) { return message.replaceAll(PATTERN_PASSWORD, "password=***"); } private static HttpClient getHttpClient() { final DefaultHttpClient client = new DefaultHttpClient(); client.setCookieStore(Cookies.cookieStore); client.setParams(clientParams); client.setRedirectStrategy(new LaxRedirectStrategy()); return new DecompressingHttpClient(client); } /** * POST HTTP request * * @param uri the URI to request * @param params the parameters to add to the POST request * @return the HTTP response, or null in case of an encoding error params */ @Nullable public static HttpResponse postRequest(final String uri, final Parameters params) { return request("POST", uri, params, null, null); } /** * POST HTTP request * * @param uri the URI to request * @param params the parameters to add to the POST request * @params headers the headers to add to the request * @return the HTTP response, or null in case of an encoding error params */ @Nullable public static HttpResponse postRequest(final String uri, final Parameters params, final Parameters headers) { return request("POST", uri, params, headers, null); } /** * POST HTTP request with Json POST DATA * * @param uri the URI to request * @param json the json object to add to the POST request * @return the HTTP response, or null in case of an encoding error params */ @Nullable public static HttpResponse postJsonRequest(final String uri, final JSONObject json) { HttpPost request = new HttpPost(uri); request.addHeader("Content-Type", "application/json; charset=utf-8"); if (json != null) { try { request.setEntity(new StringEntity(json.toString(), CharEncoding.UTF_8)); } catch (UnsupportedEncodingException e) { Log.e("postJsonRequest:JSON Entity: UnsupportedEncodingException"); return null; } } return doLogRequest(request); } /** * Multipart POST HTTP request * * @param uri the URI to request * @param params the parameters to add to the POST request * @param fileFieldName the name of the file field name * @param fileContentType the content-type of the file * @param file the file to include in the request * @return the HTTP response, or null in case of an encoding error param */ @Nullable public static HttpResponse postRequest(final String uri, final Parameters params, final String fileFieldName, final String fileContentType, final File file) { final MultipartEntity entity = new MultipartEntity(); for (final NameValuePair param : params) { try { entity.addPart(param.getName(), new StringBody(param.getValue(), CHARSET_UTF8)); } catch (final UnsupportedEncodingException e) { Log.e("Network.postRequest: unsupported encoding for parameter " + param.getName(), e); return null; } } entity.addPart(fileFieldName, new FileBody(file, fileContentType)); final HttpPost request = new HttpPost(uri); request.setEntity(entity); addHeaders(request, null, null); return doLogRequest(request); } /** * Make an HTTP request * * @param method * the HTTP method to use ("GET" or "POST") * @param uri * the URI to request * @param params * the parameters to add to the URI * @param headers * the headers to add to the request * @param cacheFile * the cache file used to cache this query * @return the HTTP response, or null in case of an encoding error in a POST request arguments */ @Nullable private static HttpResponse request(final String method, final String uri, @Nullable final Parameters params, @Nullable final Parameters headers, @Nullable final File cacheFile) { HttpRequestBase request; if (method.equals("GET")) { final String fullUri = params == null ? uri : Uri.parse(uri).buildUpon().encodedQuery(params.toString()).build().toString(); request = new HttpGet(fullUri); } else { request = new HttpPost(uri); if (params != null) { try { ((HttpPost) request).setEntity(new UrlEncodedFormEntity(params, CharEncoding.UTF_8)); } catch (final UnsupportedEncodingException e) { Log.e("request", e); return null; } } } addHeaders(request, headers, cacheFile); return doLogRequest(request); } /** * Add headers to HTTP request. * @param request * the request to add headers to * @param headers * the headers to add (in addition to the standard headers), can be null * @param cacheFile * if non-null, the file to take ETag and If-Modified-Since information from */ private static void addHeaders(final HttpRequestBase request, @Nullable final Parameters headers, @Nullable final File cacheFile) { for (final NameValuePair header : Parameters.extend(Parameters.merge(headers, cacheHeaders(cacheFile)), "Accept-Charset", "utf-8,iso-8859-1;q=0.8,utf-16;q=0.8,*;q=0.7", "Accept-Language", "en-US,*;q=0.9", "X-Requested-With", "XMLHttpRequest")) { request.setHeader(header.getName(), header.getValue()); } request.getParams().setParameter(CoreProtocolPNames.USER_AGENT, Settings.getUseNativeUa() ? NATIVE_USER_AGENT : PC_USER_AGENT); } /** * Perform an HTTP request and log it. * * @param request * the request to try * @return * the response, or null if there has been a failure */ @Nullable private static HttpResponse doLogRequest(final HttpRequestBase request) { final String reqLogStr = request.getMethod() + " " + hidePassword(request.getURI().toString()); Log.d(reqLogStr); final HttpClient client = getHttpClient(); final long before = System.currentTimeMillis(); try { final HttpResponse response = client.execute(request); int status = response.getStatusLine().getStatusCode(); if (status == 200) { Log.d(status + formatTimeSpan(before) + reqLogStr); } else { Log.w(status + " [" + response.getStatusLine().getReasonPhrase() + "]" + formatTimeSpan(before) + reqLogStr); } return response; } catch (final IOException e) { final String timeSpan = formatTimeSpan(before); Log.w("Failure" + timeSpan + reqLogStr + " (" + e.toString() + ")"); } return null; } @Nullable private static Parameters cacheHeaders(@Nullable final File cacheFile) { if (cacheFile == null || !cacheFile.exists()) { return null; } final String etag = LocalStorage.getSavedHeader(cacheFile, LocalStorage.HEADER_ETAG); if (etag != null) { // The ETag is a more robust check than a timestamp. If we have an ETag, it is enough // to identify the right version of the resource. return new Parameters("If-None-Match", etag); } final String lastModified = LocalStorage.getSavedHeader(cacheFile, LocalStorage.HEADER_LAST_MODIFIED); if (lastModified != null) { return new Parameters("If-Modified-Since", lastModified); } return null; } /** * GET HTTP request * * @param uri * the URI to request * @param params * the parameters to add the the GET request * @param cacheFile * the name of the file storing the cached resource, or null not to use one * @return the HTTP response */ @Nullable public static HttpResponse getRequest(final String uri, @Nullable final Parameters params, @Nullable final File cacheFile) { return request("GET", uri, params, null, cacheFile); } /** * GET HTTP request * * @param uri * the URI to request * @param params * the parameters to add the the GET request * @return the HTTP response */ @Nullable public static HttpResponse getRequest(final String uri, @Nullable final Parameters params) { return request("GET", uri, params, null, null); } /** * GET HTTP request * * @param uri * the URI to request * @param params * the parameters to add the the GET request * @param headers * the headers to add to the GET request * @return the HTTP response */ @Nullable public static HttpResponse getRequest(final String uri, @Nullable final Parameters params, @Nullable final Parameters headers) { return request("GET", uri, params, headers, null); } /** * GET HTTP request * * @param uri * the URI to request * @return the HTTP response */ @Nullable public static HttpResponse getRequest(final String uri) { return request("GET", uri, null, null, null); } private static String formatTimeSpan(final long before) { // don't use String.format in a pure logging routine, it has very bad performance return " (" + (System.currentTimeMillis() - before) + " ms) "; } static public boolean isSuccess(@Nullable final HttpResponse response) { return response != null && response.getStatusLine().getStatusCode() == 200; } static public boolean isPageNotFound(@Nullable final HttpResponse response) { return response != null && response.getStatusLine().getStatusCode() == 404; } /** * Get the result of a GET HTTP request returning a JSON body. * * @param uri the base URI of the GET HTTP request * @param params the query parameters, or <code>null</code> if there are none * @return a JSON object if the request was successful and the body could be decoded, <code>null</code> otherwise */ @Nullable public static JSONObject requestJSON(final String uri, @Nullable final Parameters params) { final HttpResponse response = request("GET", uri, params, new Parameters("Accept", "application/json, text/javascript, */*; q=0.01"), null); final String responseData = getResponseData(response, false); if (responseData != null) { try { return new JSONObject(responseData); } catch (final JSONException e) { Log.w("Network.requestJSON", e); } } return null; } /** * Get the input stream corresponding to a HTTP response if it exists. * * @param response a HTTP response, which can be null * @return the input stream if the HTTP request is successful, <code>null</code> otherwise */ @Nullable public static InputStream getResponseStream(@Nullable final HttpResponse response) { if (!isSuccess(response)) { return null; } assert(response != null); final HttpEntity entity = response.getEntity(); if (entity == null) { return null; } try { return entity.getContent(); } catch (final IOException e) { Log.e("Network.getResponseStream", e); return null; } } @Nullable private static String getResponseDataNoError(final HttpResponse response, boolean replaceWhitespace) { try { String data = EntityUtils.toString(response.getEntity(), CharEncoding.UTF_8); return replaceWhitespace ? TextUtils.replaceWhitespace(data) : data; } catch (Exception e) { Log.e("getResponseData", e); return null; } } /** * Get the body of a HTTP response. * * {@link TextUtils#replaceWhitespace(String)} will be called on the result * * @param response a HTTP response, which can be null * @return the body if the response comes from a successful HTTP request, <code>null</code> otherwise */ @Nullable public static String getResponseData(@Nullable final HttpResponse response) { return getResponseData(response, true); } @Nullable public static String getResponseDataAlways(@Nullable final HttpResponse response) { return response != null ? getResponseDataNoError(response, false) : null; } /** * Get the body of a HTTP response. * * @param response a HTTP response, which can be null * @param replaceWhitespace <code>true</code> if {@link TextUtils#replaceWhitespace(String)} * should be called on the body * @return the body if the response comes from a successful HTTP request, <code>null</code> otherwise */ @Nullable public static String getResponseData(@Nullable final HttpResponse response, boolean replaceWhitespace) { if (!isSuccess(response)) { return null; } assert response != null; // Caught above return getResponseDataNoError(response, replaceWhitespace); } @Nullable public static String rfc3986URLEncode(String text) { final String encoded = encode(text); return encoded != null ? StringUtils.replace(encoded.replace("+", "%20"), "%7E", "~") : null; } @Nullable public static String decode(final String text) { try { return URLDecoder.decode(text, CharEncoding.UTF_8); } catch (UnsupportedEncodingException e) { Log.e("Network.decode", e); } return null; } @Nullable public static String encode(final String text) { try { return URLEncoder.encode(text, CharEncoding.UTF_8); } catch (UnsupportedEncodingException e) { Log.e("Network.encode", e); } return null; } /** * Checks if the device has network connection. * * @param context * context of the application, cannot be null * * @return <code>true</code> if the device is connected to the network. */ public static boolean isNetworkConnected(Context context) { ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = conMan.getActiveNetworkInfo(); return activeNetwork != null && activeNetwork.isConnected(); } }
package com.google.refine; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.refine.commands.Command; import com.google.refine.io.FileProjectManager; import edu.mit.simile.butterfly.Butterfly; import edu.mit.simile.butterfly.ButterflyModule; public class RefineServlet extends Butterfly { static private final String VERSION = "2.0"; private static final long serialVersionUID = 2386057901503517403L; private static final String JAVAX_SERVLET_CONTEXT_TEMPDIR = "javax.servlet.context.tempdir"; static private RefineServlet s_singleton; static private File s_dataDir; static final private Map<String, Command> commands = new HashMap<String, Command>(); // timer for periodically saving projects static private Timer _timer; final static Logger logger = LoggerFactory.getLogger("refine"); public static String getVersion() { return VERSION; } final static protected long s_autoSavePeriod = 1000 * 60 * 5; // 5 minutes static protected class AutoSaveTimerTask extends TimerTask { public void run() { try { ProjectManager.singleton.save(false); // quick, potentially incomplete save } finally { _timer.schedule(new AutoSaveTimerTask(), s_autoSavePeriod); // we don't use scheduleAtFixedRate because that might result in // bunched up events when the computer is put in sleep mode } } } protected ServletConfig config; @Override public void init() throws ServletException { super.init(); s_singleton = this; logger.trace("> initialize"); String data = getInitParameter("refine.data"); if (data == null) { throw new ServletException("can't find servlet init config 'refine.data', I have to give up initializing"); } s_dataDir = new File(data); FileProjectManager.initialize(s_dataDir); if (_timer == null) { _timer = new Timer("autosave"); _timer.schedule(new AutoSaveTimerTask(), s_autoSavePeriod); } logger.trace("< initialize"); } @Override public void destroy() { logger.trace("> destroy"); // cancel automatic periodic saving and force a complete save. if (_timer != null) { _timer.cancel(); _timer = null; } if (ProjectManager.singleton != null) { ProjectManager.singleton.dispose(); ProjectManager.singleton = null; } this.config = null; logger.trace("< destroy"); super.destroy(); } @Override public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (request.getPathInfo().startsWith("/command/")) { String commandKey = getCommandKey(request); Command command = commands.get(commandKey); if (command != null) { if (request.getMethod().equals("GET")) { logger.trace("> GET {}", commandKey); command.doGet(request, response); logger.trace("< GET {}", commandKey); } else if (request.getMethod().equals("POST")) { logger.trace("> POST {}", commandKey); command.doPost(request, response); logger.trace("< POST {}", commandKey); } else { response.sendError(405); } } else { response.sendError(404); } } else { super.service(request, response); } } protected String getCommandKey(HttpServletRequest request) { // A command path has this format: /command/module-name/command-name/... String path = request.getPathInfo().substring("/command/".length()); int slash1 = path.indexOf('/'); if (slash1 >= 0) { int slash2 = path.indexOf('/', slash1 + 1); if (slash2 > 0) { path = path.substring(0, slash2); } } return path; } private File tempDir = null; public File getTempDir() { if (tempDir == null) { File tempDir = (File) this.config.getServletContext().getAttribute(JAVAX_SERVLET_CONTEXT_TEMPDIR); if (tempDir == null) { throw new RuntimeException("This app server doesn't support temp directories"); } } return tempDir; } public File getTempFile(String name) { return new File(getTempDir(), name); } public File getCacheDir(String name) { File dir = new File(new File(s_dataDir, "cache"), name); dir.mkdirs(); return dir; } public String getConfiguration(String name, String def) { return null; } /** * Register a single command. * * @param module the module the command belongs to * @param name command verb for command * @param commandObject object implementing the command * @return true if command was loaded and registered successfully */ protected boolean registerOneCommand(ButterflyModule module, String name, Command commandObject) { return registerOneCommand(module.getName() + "/" + name, commandObject); } /** * Register a single command. * * @param path path for command * @param commandObject object implementing the command * @return true if command was loaded and registered successfully */ protected boolean registerOneCommand(String path, Command commandObject) { if (commands.containsKey(path)) { return false; } commandObject.init(this); commands.put(path, commandObject); return true; } // Currently only for test purposes protected boolean unregisterCommand(String verb) { return commands.remove(verb) != null; } /** * Register a single command. Used by extensions. * * @param module the module the command belongs to * @param name command verb for command * @param commandObject object implementing the command * * @return true if command was loaded and registered successfully */ static public boolean registerCommand(ButterflyModule module, String commandName, Command commandObject) { return s_singleton.registerOneCommand(module, commandName, commandObject); } static private class ClassMapping { final String from; final String to; ClassMapping(String from, String to) { this.from = from; this.to = to; } } static final private List<ClassMapping> classMappings = new ArrayList<ClassMapping>(); /** * Add a mapping that determines how old class names can be updated to newer * class names. Such updates are desirable as the Java code changes from version * to version. If the "from" argument ends with *, then it's considered a prefix; * otherwise, it's an exact string match. * * @param from * @param to */ static public void registerClassMapping(String from, String to) { classMappings.add(new ClassMapping(from, to.endsWith("*") ? to.substring(0, to.length() - 1) : to)); } static { registerClassMapping("com.metaweb.*", "com.google.*"); registerClassMapping("com.google.gridworks.*", "com.google.refine.*"); } static final private Map<String, String> classMappingsCache = new HashMap<String, String>(); static public Class<?> getClass(String className) throws ClassNotFoundException { String toClassName = classMappingsCache.get(className); if (toClassName == null) { toClassName = className; for (ClassMapping m : classMappings) { if (m.from.endsWith("*")) { if (toClassName.startsWith(m.from.substring(0, m.from.length() - 1))) { toClassName = m.to + toClassName.substring(m.from.length() - 1); } } else { if (m.from.equals(toClassName)) { toClassName = m.to; } } } classMappingsCache.put(className, toClassName); } return Class.forName(toClassName); } }
package com.app.fixthys.widget; import android.content.Context; import android.content.res.TypedArray; import android.graphics.PorterDuff; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.support.v4.content.ContextCompat; import android.support.v4.graphics.drawable.DrawableCompat; import android.util.AttributeSet; import android.widget.TextView; import com.app.fixthys.R; import com.app.fixthys.utils.FontUtils; static void setTypeface(Context context, TextView textView, AttributeSet attrs) { TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.DTextView); Drawable leftDrawable = null; Drawable topDrawable = null; Typeface typeface = null; Drawable rightDrawable = null; Drawable bottomDrawable = null; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { leftDrawable = ta.getDrawable(R.styleable.DTextView_leftDrawable); rightDrawable = ta.getDrawable(R.styleable.DTextView_rightDrawable); bottomDrawable = ta.getDrawable(R.styleable.DTextView_bottomDrawable); topDrawable = ta.getDrawable(R.styleable.DTextView_topDrawable); } else { final int drawableLeftId = ta.getResourceId(R.styleable.DTextView_leftDrawable, -1); final int drawableRightId = ta.getResourceId(R.styleable.DTextView_rightDrawable, -1); final int drawableBottomId = ta.getResourceId(R.styleable.DTextView_bottomDrawable, -1); final int drawableTopId = ta.getResourceId(R.styleable.DTextView_topDrawable, -1); if (drawableLeftId != -1) leftDrawable = AppCompatResources.getDrawable(context, drawableLeftId); if (drawableRightId != -1) rightDrawable = AppCompatResources.getDrawable(context, drawableRightId); if (drawableBottomId != -1) bottomDrawable = AppCompatResources.getDrawable(context, drawableBottomId); if (drawableTopId != -1) topDrawable = AppCompatResources.getDrawable(context, drawableTopId); } int type = ta.getInt(R.styleable.DTextView_textFontFace, 1); typeface = FontUtils.fontName(context, type); if (leftDrawable != null || topDrawable != null || rightDrawable != null || bottomDrawable != null) textView.setCompoundDrawablesWithIntrinsicBounds(leftDrawable, topDrawable, rightDrawable, bottomDrawable); textView.setTypeface(typeface); ta.recycle(); } }
package com.rho.sync; import com.xruby.runtime.builtin.RubyHash; import com.xruby.runtime.lang.RubyValue; /** * The Class SyncObject. */ public class SyncObject { /* track the database operation to use */ private String _db_operation; /** The _primary key. */ private int _primaryKey = -1; /** The _attrib. */ private String _attrib; /** The _source id. */ private int _sourceId = -1; /** The _object. */ private String _object; /** The _value. */ private String _value; /** The _created at. */ private String _createdAt; /** The _updated at. */ private String _updatedAt; /** The _update type. */ private String _updateType; /** * Instantiates a new sync object. * * @param attrib the attrib * @param sourceId the source id * @param object the object * @param value the value * @param updateType the update type */ public SyncObject(String attrib, int sourceId, String object, String value, String updateType) { this._attrib = attrib; this._sourceId = sourceId; this._object = object; this._value = value; this._updateType = updateType; } /** * Dehydrate. * * @return the int */ public int insertIntoDatabase() { try { SyncUtil.adapter.insertIntoTable(SyncUtil .createString(SyncConstants.OBJECTS_TABLE), this .getHashFromValues()); } catch (Exception e) { System.out.println("There was an error inserting the record: " + e.getMessage()); return SyncConstants.SYNC_OBJECT_ERROR; } return SyncConstants.SYNC_OBJECT_SUCCESS; } public void deleteFromDatabase() { RubyHash hash = SyncUtil.createHash(); hash.add(SyncUtil.createString("object"), SyncUtil .createString(this.getObject())); hash.add(SyncUtil.createString("attrib"), SyncUtil .createString(this.getObject())); SyncUtil.adapter.deleteFromTable(SyncUtil .createString(SyncConstants.OBJECTS_TABLE), (RubyValue) hash); } /** * Delete from database by source. * * @param id the id */ public static void deleteFromDatabaseBySource(int id) { RubyHash hash = SyncUtil.createHash(); hash.add(SyncUtil.createString("source_id"), SyncUtil .createInteger((long) id)); SyncUtil.adapter.deleteFromTable(SyncUtil .createString(SyncConstants.OBJECTS_TABLE), (RubyValue) hash); } /** * Gets the hash from values. * * @return the hash from values */ private RubyHash getHashFromValues() { RubyHash hash = SyncUtil.createHash(); hash.add(SyncUtil.createString("attrib"), SyncUtil .createString(this.getAttrib())); hash.add(SyncUtil.createString("source_id"), SyncUtil .createInteger((long) this.getSourceId())); hash.add(SyncUtil.createString("object"), SyncUtil .createString(this.getObject())); hash.add(SyncUtil.createString("value"), SyncUtil .createString(this.getValue())); hash.add(SyncUtil.createString("created_at"), SyncUtil .createString(this.getCreatedAt())); hash.add(SyncUtil.createString("updated_at"), SyncUtil .createString(this.getUpdatedAt())); hash.add(SyncUtil.createString("update_type"), SyncUtil .createString(this.getUpdateType())); return hash; } /** * Gets the attrib. * * @return the attrib */ public String getAttrib() { return _attrib; } /** * Gets the created at. * * @return the created at */ public String getCreatedAt() { return _createdAt; } /** * Gets the object. * * @return the object */ public String getObject() { return _object; } /** * Gets the primary key. * * @return the primary key */ public int getPrimaryKey() { return _primaryKey; } /** * Gets the source id. * * @return the source id */ public int getSourceId() { return _sourceId; } /** * Gets the updated at. * * @return the updated at */ public String getUpdatedAt() { return _updatedAt; } /** * Gets the update type. * * @return the update type */ public String getUpdateType() { return _updateType; } /** * Gets the value. * * @return the value */ public String getValue() { return _value == null ? "" : _value; } /** * Sets the attrib. * * @param attrib the new attrib */ public void setAttrib(String attrib) { this._attrib = attrib; } /** * Sets the created at. * * @param createdAt the new created at */ public void setCreatedAt(String createdAt) { this._createdAt = createdAt; } /** * Sets the object. * * @param object the new object */ public void setObject(String object) { this._object = object; } /** * Sets the primary key. * * @param primaryKey the new primary key */ public void setPrimaryKey(int primaryKey) { this._primaryKey = primaryKey; } /** * Sets the source id. * * @param sourceId the new source id */ public void setSourceId(int sourceId) { this._sourceId = sourceId; } /** * Sets the updated at. * * @param updatedAt the new updated at */ public void setUpdatedAt(String updatedAt) { this._updatedAt = updatedAt; } /** * Sets the update type. * * @param updateType the new update type */ public void setUpdateType(String updateType) { this._updateType = updateType; } /** * Sets the value. * * @param value the new value */ public void setValue(String value) { this._value = value; } public String getDbOperation() { return _db_operation; } public void setDbOperation(String _db_operation) { this._db_operation = _db_operation; } }
package net.sf.jaer.graphics; import java.beans.PropertyChangeEvent; import java.nio.FloatBuffer; import java.util.Arrays; import java.util.Iterator; import java.util.Random; import net.sf.jaer.chip.AEChip; import net.sf.jaer.event.ApsDvsEvent; import net.sf.jaer.event.ApsDvsEventPacket; import net.sf.jaer.event.BasicEvent; import net.sf.jaer.event.EventPacket; import net.sf.jaer.event.PolarityEvent; import net.sf.jaer.event.orientation.OrientationEventInterface; import net.sf.jaer.util.filter.LowpassFilter2d; import net.sf.jaer.util.histogram.SimpleHistogram; import ch.unizh.ini.jaer.chip.retina.DvsDisplayConfigInterface; import eu.seebetter.ini.chips.DavisChip; import eu.seebetter.ini.chips.davis.DavisBaseCamera; import eu.seebetter.ini.chips.davis.DavisVideoContrastController; /** * Class adapted from AEChipRenderer to render not only AE events but also * frames. * * The frame buffer is RGBA so four bytes per pixel. The rendering uses a * texture which is a power of two multiple of image size, so watch out for * getWidth and getHeight; they return this value and not the number of pixels * being rendered from the chip. * * Besides the pixmaps for APS samples and ON and OFF events, an additional * pixmap is provided for pixel annotation; see {@link #getAnnotateMap() }. * * @author christian, tobi * @see ChipRendererDisplayMethod */ public class AEFrameChipRenderer extends AEChipRenderer { /** * PropertyChange events */ public static final String EVENT_NEW_FRAME_AVAILBLE = "newFrameAvailable"; /** * Set true after we have added a property change listener */ protected boolean addedPropertyChangeListener = false; public int textureWidth; //due to hardware acceloration reasons, has to be a 2^x with x a natural number public int textureHeight; //due to hardware acceloration reasons, has to be a 2^x with x a natural number /** * Fields used to reduce method calls */ protected int sizeX, sizeY, maxADC, numEventTypes; /** * Used to mark time of frame event */ protected int timestampFrameStart = 0; /** * Used to mark time of frame event */ protected int timestampFrameEnd = 0; /** * low pass temporal filter that computes time-averaged min and max gray * values */ protected LowpassFilter2d autoContrast2DLowpassRangeFilter = new LowpassFilter2d(); // 2 lp values are min and max log intensities from each frame /** * min and max values of rendered gray values */ protected float minValue, maxValue, annotateAlpha; /** * RGBA rendering colors for ON and OFF DVS events */ protected float[] onColor, offColor; /** * The linear buffer of RGBA pixel colors of image frame brightness values */ protected FloatBuffer pixBuffer; protected FloatBuffer onMap, onBuffer; protected FloatBuffer offMap, offBuffer; protected FloatBuffer annotateMap; // double buffered histogram so we can accumulate new histogram while old one is still being rendered and returned to caller private final int histStep = 4; // histogram bin step in ADC counts of 1024 levels private SimpleHistogram adcSampleValueHistogram1 = new SimpleHistogram(0, histStep, (DavisChip.MAX_ADC + 1) / histStep, 0); private SimpleHistogram adcSampleValueHistogram2 = new SimpleHistogram(0, histStep, (DavisChip.MAX_ADC + 1) / histStep, 0); /** * Histogram objects used to collect APS statistics */ protected SimpleHistogram currentHist = adcSampleValueHistogram1, nextHist = adcSampleValueHistogram2; protected DavisVideoContrastController contrastController = null; /** * Boolean on whether to compute the histogram of gray levels */ protected boolean computeHistograms = false; private boolean displayAnnotation = false; public AEFrameChipRenderer(AEChip chip) { super(chip); if (chip.getNumPixels() == 0) { log.warning("chip has zero pixels; is the constuctor of AEFrameChipRenderer called before size of the AEChip is set?"); return; } onColor = new float[4]; offColor = new float[4]; checkPixmapAllocation(); if (chip instanceof DavisChip) { contrastController = new DavisVideoContrastController((DavisChip) chip); contrastController.getSupport().addPropertyChangeListener(this); } else { log.warning("cannot make a DavisVideoContrastController for this chip because it does not extend DavisChip"); } // when contrast controller properties change, inform this so this can pass on to the chip } /** * Overridden to make gray buffer special for bDVS array */ @Override protected void resetPixmapGrayLevel(float value) { maxValue = Float.MIN_VALUE; minValue = Float.MAX_VALUE; setAnnotateAlpha(1.0f); checkPixmapAllocation(); final int n = 4 * textureWidth * textureHeight; boolean madebuffer = false; if ((grayBuffer == null) || (grayBuffer.capacity() != n)) { grayBuffer = FloatBuffer.allocate(n); // BufferUtil.newFloatBuffer(n); madebuffer = true; } if (madebuffer || (value != grayValue)) { grayBuffer.rewind(); for (int y = 0; y < textureWidth; y++) { for (int x = 0; x < textureHeight; x++) { if (isDisplayFrames()) { grayBuffer.put(0); grayBuffer.put(0); grayBuffer.put(0); grayBuffer.put(1.0f); } else if (colorMode == ColorMode.GrayTime) { grayBuffer.put(1.0f); grayBuffer.put(1.0f); grayBuffer.put(1.0f); grayBuffer.put(1.0f); } else { grayBuffer.put(grayValue); grayBuffer.put(grayValue); grayBuffer.put(grayValue); grayBuffer.put(1.0f); } } } } grayBuffer.rewind(); System.arraycopy(grayBuffer.array(), 0, pixmap.array(), 0, n); System.arraycopy(grayBuffer.array(), 0, pixBuffer.array(), 0, n); pixmap.rewind(); pixBuffer.rewind(); pixmap.limit(n); pixBuffer.limit(n); setColors(); resetMaps(); } protected void resetMaps() { setColors(); checkPixmapAllocation(); final int n = 4 * textureWidth * textureHeight; if ((grayBuffer == null) || (grayBuffer.capacity() != n)) { grayBuffer = FloatBuffer.allocate(n); // BufferUtil.newFloatBuffer(n); } grayBuffer.rewind(); //Fill maps with fully transparent values Arrays.fill(grayBuffer.array(), 0.0f); System.arraycopy(grayBuffer.array(), 0, onMap.array(), 0, n); System.arraycopy(grayBuffer.array(), 0, offMap.array(), 0, n); // if(displayAnnotation) Arrays.fill(annotateMap.array(), 0); grayBuffer.rewind(); onMap.rewind(); offMap.rewind(); onMap.limit(n); offMap.limit(n); } public synchronized void clearAnnotationMap() { resetAnnotationFrame(0); } @Override public synchronized void resetAnnotationFrame(float resetValue) { checkPixmapAllocation(); final int n = 4 * textureWidth * textureHeight; if ((grayBuffer == null) || (grayBuffer.capacity() != n)) { grayBuffer = FloatBuffer.allocate(n); // BufferUtil.newFloatBuffer(n); } grayBuffer.rewind(); //Fill maps with fully transparent values Arrays.fill(grayBuffer.array(), resetValue); System.arraycopy(grayBuffer.array(), 0, annotateMap.array(), 0, n); grayBuffer.rewind(); annotateMap.rewind(); annotateMap.limit(n); } @Override public synchronized void setColorMode(ColorMode colorMode) { super.setColorMode(colorMode); setColors(); } private void setColors() { checkPixmapAllocation(); switch (colorMode) { case GrayLevel: case Contrast: onColor[0] = 1.0f; onColor[1] = 1.0f; onColor[2] = 1.0f; onColor[3] = 0.0f; offColor[0] = 0.0f; offColor[1] = 0.0f; offColor[2] = 0.0f; offColor[3] = 0.0f; break; case RedGreen: default: onColor[0] = 0.0f; onColor[1] = 1.0f; onColor[2] = 0.0f; onColor[3] = 0.0f; offColor[0] = 1.0f; offColor[1] = 0.0f; offColor[2] = 0.0f; offColor[3] = 0.0f; break; } } /** * warning counter for some warnings */ protected int warningCount = 0; /** * interval to print warning messages */ protected static int WARNING_INTERVAL = 100; @Override public synchronized void render(EventPacket pkt) { if (!addedPropertyChangeListener) { if (chip instanceof AEChip) { AEChip aeChip = chip; if (aeChip.getAeViewer() != null) { aeChip.getAeViewer().addPropertyChangeListener(this); addedPropertyChangeListener = true; } } } numEventTypes = pkt.getNumCellTypes(); if (pkt instanceof ApsDvsEventPacket) { renderApsDvsEvents(pkt); } else { renderDvsEvents(pkt); } } protected void renderApsDvsEvents(EventPacket pkt) { if (getChip() instanceof DavisBaseCamera) { computeHistograms = ((DavisBaseCamera) chip).isShowImageHistogram() || ((DavisChip) chip).isAutoExposureEnabled(); } if (!accumulateEnabled) { resetMaps(); if (numEventTypes > 2) { resetAnnotationFrame(0.0f); } } ApsDvsEventPacket packet = (ApsDvsEventPacket) pkt; checkPixmapAllocation(); resetSelectedPixelEventCount(); // TODO fix locating pixel with xsel ysel this.packet = packet; if (!(packet.getEventPrototype() instanceof ApsDvsEvent)) { if ((warningCount++ % WARNING_INTERVAL) == 0) { log.warning("wrong input event class, got " + packet.getEventPrototype() + " but we need to have " + ApsDvsEvent.class); } return; } boolean displayEvents = isDisplayEvents(), displayFrames = isDisplayFrames(), paused = chip.getAeViewer().isPaused(), backwards = packet.getDurationUs() < 0; Iterator allItr = packet.fullIterator(); setSpecialCount(0); while (allItr.hasNext()) { //The iterator only iterates over the DVS events ApsDvsEvent e = (ApsDvsEvent) allItr.next(); if (e.isSpecial()) { setSpecialCount(specialCount + 1); // TODO optimize special count increment continue; } int type = e.getType(); boolean isAdcSampleFlag = e.isSampleEvent(); if (!isAdcSampleFlag) { if (displayEvents) { if ((xsel >= 0) && (ysel >= 0)) { // find correct mouse pixel interpretation to make sounds for large pixels int xs = xsel, ys = ysel; if ((e.x == xs) && (e.y == ys)) { playSpike(type); } } updateEventMaps(e); } } else if (!backwards && isAdcSampleFlag && displayFrames) { // TODO need to handle single step updates here updateFrameBuffer(e); } } } protected void renderDvsEvents(EventPacket pkt) { checkPixmapAllocation(); resetSelectedPixelEventCount(); // TODO fix locating pixel with xsel ysel if (!accumulateEnabled) { resetMaps(); if (numEventTypes > 2) { resetAnnotationFrame(0.0f); } } setSpecialCount(0); this.packet = pkt; Iterator itr = packet.inputIterator(); while (itr.hasNext()) { //The iterator only iterates over the DVS events PolarityEvent e = (PolarityEvent) itr.next(); if (e.isSpecial()) { setSpecialCount(specialCount + 1); // TODO optimize special count increment continue; } int type = e.getType(); if ((xsel >= 0) && (ysel >= 0)) { // find correct mouse pixel interpretation to make sounds for large pixels int xs = xsel, ys = ysel; if ((e.x == xs) && (e.y == ys)) { playSpike(type); } } updateEventMaps(e); } } private Random random = new Random(); protected void updateFrameBuffer(ApsDvsEvent e) { float[] buf = pixBuffer.array(); // TODO if playing backwards, then frame will come out white because B sample comes before A if (e.isStartOfFrame()) { startFrame(e.timestamp); } else if (e.isResetRead()) { int index = getIndex(e); if ((index < 0) || (index >= buf.length)) { return; } float val = e.getAdcSample(); buf[index] = val; buf[index + 1] = val; buf[index + 2] = val; } else if (e.isSignalRead()) { int index = getIndex(e); if ((index < 0) || (index >= buf.length)) { return; } int val = ((int) buf[index] - e.getAdcSample()); if (val < 0) { val = 0; } if ((val >= 0) && (val < minValue)) { // tobi only update min if it is >0, to deal with sensors with bad column read, like 240C minValue = val; } else if (val > maxValue) { maxValue = val; } // right here sample-reset value of this pixel is in val if (computeHistograms) { if (!((DavisChip) chip).getAutoExposureController().isCenterWeighted()) { nextHist.add(val); } else { // randomly add histogram values to histogram depending on distance from center of image // to implement a simple form of center weighting of the histogram float d = (1 - Math.abs(((float) e.x - (sizeX / 2)) / sizeX)) + Math.abs(((float) e.y - (sizeY / 2)) / sizeY); // d is zero at center, 1 at corners d*=d; float r = random.nextFloat(); if (r > d) { nextHist.add(val); } } } float fval = normalizeFramePixel(val); buf[index] = fval; buf[index + 1] = fval; buf[index + 2] = fval; buf[index + 3] = 1; } else if (e.isEndOfFrame()) { endFrame(e.timestamp); SimpleHistogram tmp = currentHist; if (computeHistograms) { currentHist = nextHist; nextHist = tmp; nextHist.reset(); } ((DavisChip) chip).controlExposure(); } } protected void startFrame(int ts) { timestampFrameStart = ts; maxValue = Float.MIN_VALUE; minValue = Float.MAX_VALUE; System.arraycopy(grayBuffer.array(), 0, pixBuffer.array(), 0, pixBuffer.array().length); } protected void endFrame(int ts) { timestampFrameEnd = ts; System.arraycopy(pixBuffer.array(), 0, pixmap.array(), 0, pixBuffer.array().length); if ((contrastController != null) && (minValue != Float.MAX_VALUE) && (maxValue != Float.MIN_VALUE)) { contrastController.endFrame(minValue, maxValue, timestampFrameEnd); } getSupport().firePropertyChange(EVENT_NEW_FRAME_AVAILBLE, null, this); // TODO document what is sent and send something reasonable } /** * changes alpha of ON map * * @param index 0-(size of pixel array-1) of pixel */ protected void updateEventMaps(PolarityEvent e) { float[] map; int index = getIndex(e); if (packet.getNumCellTypes() > 2) { map = onMap.array(); } else if (e.polarity == ApsDvsEvent.Polarity.On) { map = onMap.array(); } else { map = offMap.array(); } if ((index < 0) || (index >= map.length)) { return; } if (packet.getNumCellTypes() > 2) { checkTypeColors(packet.getNumCellTypes()); if (e.special) { setSpecialCount(specialCount + 1); // TODO optimize special count increment return; } int type = e.getType(); if ((e.x == xsel) && (e.y == ysel)) { playSpike(type); } int ind = getPixMapIndex(e.x, e.y); float[] c = typeColorRGBComponents[type]; float alpha = map[index + 3] + (1.0f / colorScale); alpha = normalizeEvent(alpha); if ((e instanceof OrientationEventInterface) && (((OrientationEventInterface) e).isHasOrientation() == false)) { // if event is orientation event but orientation was not set, just draw as gray level map[ind] = 1.0f; //if(f[0]>1f) f[0]=1f; map[ind + 1] = 1.0f; //if(f[1]>1f) f[1]=1f; map[ind + 2] = 1.0f; //if(f[2]>1f) f[2]=1f; } else { // if color scale is 1, then last value is used as the pixel value, which quantizes the color to full scale. map[ind] = c[0]; //if(f[0]>1f) f[0]=1f; map[ind + 1] = c[1]; //if(f[1]>1f) f[1]=1f; map[ind + 2] = c[2]; //if(f[2]>1f) f[2]=1f; } map[index + 3] += alpha; } else if (colorMode == ColorMode.ColorTime) { int ts0 = packet.getFirstTimestamp(); float dt = packet.getDurationUs(); int ind = (int) Math.floor(((NUM_TIME_COLORS - 1) * (e.timestamp - ts0)) / dt); if (ind < 0) { ind = 0; } else if (ind >= timeColors.length) { ind = timeColors.length - 1; } map[index] = timeColors[ind][0]; map[index + 1] = timeColors[ind][1]; map[index + 2] = timeColors[ind][2]; map[index + 3] = 0.5f; } else if (colorMode == ColorMode.GrayTime) { int ts0 = packet.getFirstTimestamp(); float dt = packet.getDurationUs(); float v = 0.95f - (0.95f * ((e.timestamp - ts0) / dt)); map[index] = v; map[index + 1] = v; map[index + 2] = v; map[index + 3] = 1.0f; } else { float alpha = map[index + 3] + (1.0f / colorScale); alpha = normalizeEvent(alpha); if ((e.polarity == PolarityEvent.Polarity.On) || ignorePolarityEnabled) { map[index] = onColor[0]; map[index + 1] = onColor[1]; map[index + 2] = onColor[2]; } else { map[index] = offColor[0]; map[index + 1] = offColor[1]; map[index + 2] = offColor[2]; } map[index + 3] = alpha; } } protected final int INTERVAL_BETWEEEN_OUT_OF_BOUNDS_EXCEPTIONS_PRINTED_MS = 1000; protected long lastWarningPrintedTimeMs = Integer.MAX_VALUE; /** * Returns index to R (red) value in RGBA pixmap * * @param e * @return index to red entry in RGBA pixmap */ protected int getIndex(BasicEvent e) { int x = e.x, y = e.y; if ((x < 0) || (y < 0) || (x >= sizeX) || (y >= sizeY)) { if ((System.currentTimeMillis() - lastWarningPrintedTimeMs) > INTERVAL_BETWEEEN_OUT_OF_BOUNDS_EXCEPTIONS_PRINTED_MS) { log.warning(String.format("Event %s out of bounds and cannot be rendered in bounds sizeX=%d sizeY=%d - delaying next warning for %dms", e.toString(), sizeX, sizeY, INTERVAL_BETWEEEN_OUT_OF_BOUNDS_EXCEPTIONS_PRINTED_MS)); lastWarningPrintedTimeMs = System.currentTimeMillis(); } return -1; } return 4 * (x + (y * textureWidth)); } @Override protected void checkPixmapAllocation() { if ((sizeX != chip.getSizeX()) || (sizeY != chip.getSizeY())) { sizeX = chip.getSizeX(); textureWidth = ceilingPow2(sizeX); sizeY = chip.getSizeY(); textureHeight = ceilingPow2(sizeY); } final int n = 4 * textureWidth * textureHeight; if ((pixmap == null) || (pixmap.capacity() < n) || (pixBuffer.capacity() < n) || (onMap.capacity() < n) || (offMap.capacity() < n) || (annotateMap.capacity() < n)) { pixmap = FloatBuffer.allocate(n); // BufferUtil.newFloatBuffer(n); pixBuffer = FloatBuffer.allocate(n); onMap = FloatBuffer.allocate(n); offMap = FloatBuffer.allocate(n); annotateMap = FloatBuffer.allocate(n); } } /** * Overrides color scale setting to NOT update the stored accumulated pixmap * when the color scale is changed. * * */ @Override synchronized public void setColorScale(int colorScale) { int old = this.colorScale; if (colorScale < 1) { colorScale = 1; } if (colorScale > 128) { colorScale = 128; } this.colorScale = colorScale; prefs.putInt("Chip2DRenderer.colorScale", colorScale); getSupport().firePropertyChange(EVENT_COLOR_SCALE_CHANGE, old, colorScale); } /** * computes power of two value that is equal to or greater than argument * * @param n value, e.g. 3 * @return power of two that is >=n, e.g. 4 */ protected static int ceilingPow2(int n) { int pow2 = 1; while (n > pow2) { pow2 = pow2 << 1; } return pow2; } /** * Returns pixmap for ON events * * @return a float buffer. Obtain a pixel from it using getPixMapIndex * @see #getPixMapIndex(int, int) */ public FloatBuffer getOnMap() { onMap.rewind(); checkPixmapAllocation(); return onMap; } /** * Returns pixmap for OFF events * * @return a float buffer. Obtain a pixel from it using getPixMapIndex * @see #getPixMapIndex(int, int) */ public FloatBuffer getOffMap() { offMap.rewind(); checkPixmapAllocation(); return offMap; } /** * Returns pixmap for annotated pixels * * @return a float buffer. Obtain a pixel from it using getPixMapIndex * @see #getPixMapIndex(int, int) */ public FloatBuffer getAnnotateMap() { annotateMap.rewind(); checkPixmapAllocation(); return annotateMap; } /** * Returns index into pixmap * * @param x * @param y * @return the index */ @Override public int getPixMapIndex(int x, int y) { return 4 * (x + (y * textureWidth)); } /** * Overridden to return ON and OFF map values as R and G channels. B channel * is returned 0. Note that this method returns rendering of events; it * disregards APS frame values. * * @param x * @param y * @return */ public float[] getDvsRenderedValuesAtPixel(int x, int y) { int k = getPixMapIndex(x, y); float[] f = new float[3]; f[0] = onMap.get(k + 3); f[1] = offMap.get(k + 3); f[2] = 0; // return alpha channel which is the ON and OFF value that is rendered (RGB are 1 for ON and OFF maps) return f; //To change body of generated methods, choose Tools | Templates. } /** * Overridden to combine ON and OFF map values to a gray value by averaging * them. Note that this method returns rendering of events; it disregards * APS frame values. * * @param x * @param y * @return */ public float getApsGrayValueAtPixel(int x, int y) { int k = getPixMapIndex(x, y); float[] pm = pixmap.array(); return (pm[k] + pm[k + 1] + pm[k + 2]) / 3; } /** * Sets RGB color components all to same gray value g * * @param x pixel x, 0,0 is LL corner * @param y pixel y * @param g gray value in range 0-1 */ public void setApsGrayValueAtPixel(int x, int y, float g) { int k = getPixMapIndex(x, y); float[] pm = pixmap.array(); pm[k] = g; pm[k + 1] = g; pm[k + 2] = g; } /** * Returns the buffer holding the image frame brightness values in RGBA * order */ public FloatBuffer getPixBuffer() { return pixBuffer; } /** * sets a specific value of the pixmap * * @param index * @param value */ @Override public void setAnnotateValue(int index, float value) { annotateMap.put(index, value); } /** * sets a specific color (rgb float 0-1) of the pixmap * * @param index * @param value */ @Override public void setAnnotateColorRGB(int index, float[] value) { annotateMap.put(index, value[0]); annotateMap.put(index + 1, value[1]); annotateMap.put(index + 2, value[2]); annotateMap.put(index + 3, getAnnotateAlpha()); } /** * sets a specific color (rgb float 0-1) of the pixmap * * @param index * @param value */ public void setAnnotateColorRGBA(int index, float[] value) { annotateMap.put(index, value[0]); annotateMap.put(index + 1, value[1]); annotateMap.put(index + 2, value[2]); annotateMap.put(index + 3, value[3]); } /** * sets a specific color (rgb float 0-1) of the pixmap * * @param x * @param y * @param value */ @Override public void setAnnotateColorRGB(int x, int y, float[] value) { int index = getPixMapIndex(x, y); annotateMap.put(index, value[0]); annotateMap.put(index + 1, value[1]); annotateMap.put(index + 2, value[2]); annotateMap.put(index + 3, getAnnotateAlpha()); } /** * sets a specific color (rgb float 0-1) of the pixmap * * @param x * @param y * @param value */ public void setAnnotateColorRGBA(int x, int y, float[] value) { int index = getPixMapIndex(x, y); annotateMap.put(index, value[0]); annotateMap.put(index + 1, value[1]); annotateMap.put(index + 2, value[2]); annotateMap.put(index + 3, value[3]); } /** * Returns the width of the texture used to render output. Note this is NOT * the chip dimension; it is a power of 2 multiple that is next larger to * chip size. * * @return power of 2 multiple that is next larger to chip size */ @Override public int getWidth() { return textureWidth; } /** * Returns the height of the texture used to render output. Note this is NOT * the chip dimension; it is a power of 2 multiple that is next larger to * chip size. * * @return power of 2 multiple that is next larger to chip size */ @Override public int getHeight() { return textureHeight; } /** * Computes the normalized gray value from an ADC sample value using * brightness (offset), contrast (multiplier), and gamma (power law). Takes * account of the autoContrast setting which attempts to set value * automatically to get image in range of display. * * @param value the ADC value * @return the gray value */ private float normalizeFramePixel(float value) { if (contrastController != null) { return contrastController.normalizePixelGrayValue(value, maxADC); } else { return 0; } } private float normalizeEvent(float value) { if (value < 0) { value = 0; } else if (value > 1) { value = 1; } return value; } public int getMaxADC() { return maxADC; } public void setMaxADC(int max) { maxADC = max; } /** * @return the gray level of the rendered data; used to determine whether a * pixel needs to be drawn */ @Override public float getGrayValue() { if (isDisplayFrames() || (colorMode == ColorMode.Contrast) || (colorMode == ColorMode.GrayLevel)) { grayValue = 0.5f; } else if (colorMode == ColorMode.GrayTime) { grayValue = 1.0f; } else { grayValue = 0.0f; } return this.grayValue; } /** * Returns the current valid histogram of ADC sample values. New ADC values * are accumulated to another histogram and the histograms are swapped when * a new frame has finished being captured. * * @return the adcSampleValueHistogram */ public SimpleHistogram getAdcSampleValueHistogram() { return currentHist; } public int getWidthInPixels() { return getWidth(); } public int getHeightInPixels() { return getHeight(); } /** * @return the annotateAlpha */ public float getAnnotateAlpha() { return annotateAlpha; } /** * Sets the alpha of the annotation layer. This alpha determines the * transparency of the annotation. * * @param annotateAlpha the annotateAlpha to set */ public void setAnnotateAlpha(float annotateAlpha) { this.annotateAlpha = annotateAlpha; } /** * Returns whether the annotation layer is displayed * * @return the displayAnnotation */ public boolean isDisplayAnnotation() { return displayAnnotation; } /** * Sets whether the annotation layer is displayed. * * @param displayAnnotation the displayAnnotation to set */ public void setDisplayAnnotation(boolean displayAnnotation) { this.displayAnnotation = displayAnnotation; } /** * Sets whether an external renderer adds data to the array and resets it * * @param extRender */ @Override public void setExternalRenderer(boolean extRender) { externalRenderer = extRender; displayAnnotation = extRender; } public boolean isDisplayFrames() { return ((DvsDisplayConfigInterface) chip.getBiasgen()).isDisplayFrames(); } public boolean isDisplayEvents() { return ((DvsDisplayConfigInterface) chip.getBiasgen()).isDisplayEvents(); } /** * @return the contrastController */ public DavisVideoContrastController getContrastController() { return contrastController; } /** * @param contrastController the contrastController to set */ public void setContrastController(DavisVideoContrastController contrastController) { this.contrastController = contrastController; } public boolean isUseAutoContrast() { return contrastController.isUseAutoContrast(); } public void setUseAutoContrast(boolean useAutoContrast) { contrastController.setUseAutoContrast(useAutoContrast); } public float getContrast() { return contrastController.getContrast(); } public void setContrast(float contrast) { contrastController.setContrast(contrast); } public float getBrightness() { return contrastController.getBrightness(); } public void setBrightness(float brightness) { contrastController.setBrightness(brightness); } public float getGamma() { return contrastController.getGamma(); } public void setGamma(float gamma) { contrastController.setGamma(gamma); } public void setAutoContrastTimeconstantMs(float tauMs) { contrastController.setAutoContrastTimeconstantMs(tauMs); } @Override public void propertyChange(PropertyChangeEvent pce) { super.propertyChange(pce); //To change body of generated methods, choose Tools | Templates. chip.getBiasgen().getSupport().firePropertyChange(pce); // pass on events to chip configuration } /** * Returns the timestamp of the pixel read out at the start of the frame * readout (not the exposure start) * * @return the timestampFrameStart */ public int getTimestampFrameStart() { return timestampFrameStart; } /** * Returns the timestamp of the pixel read out at end of the frame (not the * exposure end) * * @return the timestampFrameEnd */ public int getTimestampFrameEnd() { return timestampFrameEnd; } }
package net.wurstclient.features.mods; import java.lang.reflect.Field; import java.util.Collection; import java.util.Comparator; import java.util.TreeMap; import net.wurstclient.features.Mod; import net.wurstclient.features.mods.blocks.*; import net.wurstclient.features.mods.chat.AntiSpamMod; import net.wurstclient.features.mods.chat.FancyChatMod; import net.wurstclient.features.mods.chat.HomeMod; import net.wurstclient.features.mods.combat.*; import net.wurstclient.features.mods.fun.DerpMod; import net.wurstclient.features.mods.fun.HeadRollMod; import net.wurstclient.features.mods.fun.HeadlessMod; import net.wurstclient.features.mods.fun.LsdMod; import net.wurstclient.features.mods.fun.MileyCyrusMod; import net.wurstclient.features.mods.fun.SkinDerpMod; import net.wurstclient.features.mods.fun.TiredMod; import net.wurstclient.features.mods.items.CmdBlockMod; import net.wurstclient.features.mods.items.CrashChestMod; import net.wurstclient.features.mods.items.CrashTagMod; import net.wurstclient.features.mods.items.KillPotionMod; import net.wurstclient.features.mods.items.TrollPotionMod; import net.wurstclient.features.mods.movement.*; import net.wurstclient.features.mods.other.*; import net.wurstclient.features.mods.render.*; import net.wurstclient.features.mods.retro.AntiFireMod; import net.wurstclient.features.mods.retro.AntiPotionMod; import net.wurstclient.features.mods.retro.FastBowMod; import net.wurstclient.features.mods.retro.FastEatMod; import net.wurstclient.features.mods.retro.ForcePushMod; import net.wurstclient.features.mods.retro.RegenMod; public class ModManager { private final TreeMap<String, Mod> mods = new TreeMap<>(new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.compareToIgnoreCase(o2); } }); public final AntiAfkMod antiAfkMod = new AntiAfkMod(); public final AntiBlindMod antiBlindMod = new AntiBlindMod(); public final AntiCactusMod antiCactusMod = new AntiCactusMod(); public final AntiFireMod antiFireMod = new AntiFireMod(); public final AntiKnockbackMod antiKnockbackMod = new AntiKnockbackMod(); public final AntiPotionMod antiPotionMod = new AntiPotionMod(); public final AntiSpamMod antiSpamMod = new AntiSpamMod(); public final AutoArmorMod autoArmorMod = new AutoArmorMod(); public final AutoBuildMod autoBuildMod = new AutoBuildMod(); public final AutoLeaveMod autoLeaveMod = new AutoLeaveMod(); public final AutoEatMod autoEatMod = new AutoEatMod(); public final AutoFishMod autoFishMod = new AutoFishMod(); public final AutoMineMod autoMineMod = new AutoMineMod(); public final AutoRespawnMod autoRespawnMod = new AutoRespawnMod(); public final AutoSignMod autoSignMod = new AutoSignMod(); public final AutoSplashPotMod autoSplashPotMod = new AutoSplashPotMod(); public final AutoSoupMod autoSoupMod = new AutoSoupMod(); public final AutoSprintMod autoSprintMod = new AutoSprintMod(); public final AutoStealMod autoStealMod = new AutoStealMod(); public final AutoSwitchMod autoSwitchMod = new AutoSwitchMod(); public final AutoSwordMod autoSwordMod = new AutoSwordMod(); public final AutoToolMod autoToolMod = new AutoToolMod(); public final AutoWalkMod autoWalkMod = new AutoWalkMod(); public final BaseFinderMod baseFinderMod = new BaseFinderMod(); public final BlinkMod blinkMod = new BlinkMod(); public final BoatFlyMod boatFlyMod = new BoatFlyMod(); public final BonemealAuraMod bonemealAuraMod = new BonemealAuraMod(); public final BowAimbotMod bowAimbotMod = new BowAimbotMod(); public final BuildRandomMod buildRandomMod = new BuildRandomMod(); public final BunnyHopMod bunnyHopMod = new BunnyHopMod(); public final CaveFinderMod caveFinderMod = new CaveFinderMod(); public final ChestEspMod chestEspMod = new ChestEspMod(); public final ClickAuraMod clickAuraMod = new ClickAuraMod(); public final CmdBlockMod cmdBlockMod = new CmdBlockMod(); public final CrashChestMod crashChestMod = new CrashChestMod(); public final CrashTagMod crashTagMod = new CrashTagMod(); public final CriticalsMod criticalsMod = new CriticalsMod(); public final DerpMod derpMod = new DerpMod(); public final DolphinMod dolphinMod = new DolphinMod(); public final ExtraElytraMod extraElytraMod = new ExtraElytraMod(); public final FancyChatMod fancyChatMod = new FancyChatMod(); public final FastBreakMod fastBreakMod = new FastBreakMod(); public final FastBowMod fastBowMod = new FastBowMod(); public final FastEatMod fastEatMod = new FastEatMod(); public final FastLadderMod fastLadderMod = new FastLadderMod(); public final FastPlaceMod fastPlaceMod = new FastPlaceMod(); public final FightBotMod fightBotMod = new FightBotMod(); public final FlightMod flightMod = new FlightMod(); public final FollowMod followMod = new FollowMod(); public final ForceOpMod forceOpMod = new ForceOpMod(); public final ForcePushMod forcePushMod = new ForcePushMod(); public final FreecamMod freecamMod = new FreecamMod(); public final FullbrightMod fullbrightMod = new FullbrightMod(); public final GhostHandMod ghostHandMod = new GhostHandMod(); public final GlideMod glideMod = new GlideMod(); public final HeadlessMod headlessMod = new HeadlessMod(); public final HeadRollMod headRollMod = new HeadRollMod(); public final HealthTagsMod healthTagsMod = new HealthTagsMod(); public final HighJumpMod highJumpMod = new HighJumpMod(); public final HomeMod homeMod = new HomeMod(); public final InstantBunkerMod instantBunkerMod = new InstantBunkerMod(); public final ItemEspMod itemEspMod = new ItemEspMod(); public final JesusMod jesusMod = new JesusMod(); public final JetpackMod jetpackMod = new JetpackMod(); public final KaboomMod kaboomMod = new KaboomMod(); public final KillauraLegitMod killauraLegitMod = new KillauraLegitMod(); public final KillauraMod killauraMod = new KillauraMod(); public final KillPotionMod killPotionMod = new KillPotionMod(); public final LiquidsMod liquidsMod = new LiquidsMod(); public final LogSpammerMod logSpammerMod = new LogSpammerMod(); public final LsdMod lsdMod = new LsdMod(); public final MassTpaMod massTpaMod = new MassTpaMod(); public final MenuWalkMod menuWalkMod = new MenuWalkMod(); public final MileyCyrusMod mileyCyrusMod = new MileyCyrusMod(); public final MobEspMod mobEspMod = new MobEspMod(); public final MultiAuraMod multiAuraMod = new MultiAuraMod(); public final NameProtectMod nameProtectMod = new NameProtectMod(); public final NameTagsMod nameTagsMod = new NameTagsMod(); public final NavigatorMod navigatorMod = new NavigatorMod(); public final NoClipMod noClipMod = new NoClipMod(); public final NoFallMod noFallMod = new NoFallMod(); public final NoHurtcamMod noHurtcamMod = new NoHurtcamMod(); public final NoOverlayMod noOverlayMod = new NoOverlayMod(); public final NoSlowdownMod noSlowdownMod = new NoSlowdownMod(); public final NoWeatherMod noWeatherMod = new NoWeatherMod(); public final NoWebMod noWebMod = new NoWebMod(); public final NukerMod nukerMod = new NukerMod(); public final NukerLegitMod nukerLegitMod = new NukerLegitMod(); public final OverlayMod overlayMod = new OverlayMod(); public final PanicMod panicMod = new PanicMod(); public final ParkourMod parkourMod = new ParkourMod(); public final PhaseMod phaseMod = new PhaseMod(); public final PlayerEspMod playerEspMod = new PlayerEspMod(); public final PlayerFinderMod playerFinderMod = new PlayerFinderMod(); public final PotionSaverMod potionSaverMod = new PotionSaverMod(); public final ProphuntEspMod prophuntEspMod = new ProphuntEspMod(); public final ProtectMod protectMod = new ProtectMod(); public final RegenMod regenMod = new RegenMod(); public final RemoteViewMod remoteViewMod = new RemoteViewMod(); public final SafeWalkMod safeWalkMod = new SafeWalkMod(); public final ScaffoldWalkMod scaffoldWalkMod = new ScaffoldWalkMod(); public final SearchMod searchMod = new SearchMod(); public final SkinDerpMod skinDerpMod = new SkinDerpMod(); public final SneakMod sneakMod = new SneakMod(); public final SpammerMod spammerMod = new SpammerMod(); public final SpeedHackMod speedHackMod = new SpeedHackMod(); public final SpeedNukerMod speedNukerMod = new SpeedNukerMod(); public final SpiderMod spiderMod = new SpiderMod(); public final StepMod stepMod = new StepMod(); public final TemplateToolMod templateToolMod = new TemplateToolMod(); public final ThrowMod throwMod = new ThrowMod(); public final TimerMod timerMod = new TimerMod(); public final TiredMod tiredMod = new TiredMod(); public final TracersMod tracersMod = new TracersMod(); public final TpAuraMod tpAuraMod = new TpAuraMod(); public final TrajectoriesMod trajectoriesMod = new TrajectoriesMod(); public final TriggerBotMod triggerBotMod = new TriggerBotMod(); public final TrollPotionMod trollPotionMod = new TrollPotionMod(); public final TrueSightMod trueSightMod = new TrueSightMod(); public final TunnellerMod tunnellerMod = new TunnellerMod(); public final XRayMod xRayMod = new XRayMod(); public ModManager() { try { for(Field field : ModManager.class.getFields()) if(field.getName().endsWith("Mod")) { Mod mod = (Mod)field.get(this); mods.put(mod.getName(), mod); mod.initSettings(); } }catch(Exception e) { e.printStackTrace(); } } public Mod getModByName(String name) { return mods.get(name); } public Collection<Mod> getAllMods() { return mods.values(); } public int countMods() { return mods.size(); } }
package org.bouncycastle.asn1.x9; import java.math.BigInteger; import java.util.Enumeration; import java.util.Hashtable; import org.bouncycastle.asn1.DERObjectIdentifier; import org.bouncycastle.math.ec.ECCurve; import org.bouncycastle.util.encoders.Hex; /** * table of the current named curves defined in X.962 EC-DSA. */ public class X962NamedCurves { static final ECCurve cFp192v1 = new ECCurve.Fp( new BigInteger("6277101735386680763835789423207666416083908700390324961279"), new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16), new BigInteger("64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1", 16)); static final X9ECParameters prime192v1 = new X9ECParameters( cFp192v1, cFp192v1.decodePoint( Hex.decode("03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012")), new BigInteger("ffffffffffffffffffffffff99def836146bc9b1b4d22831", 16), BigInteger.valueOf(1), Hex.decode("3045AE6FC8422f64ED579528D38120EAE12196D5")); static final ECCurve cFp192v2 = new ECCurve.Fp( new BigInteger("6277101735386680763835789423207666416083908700390324961279"), new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16), new BigInteger("cc22d6dfb95c6b25e49c0d6364a4e5980c393aa21668d953", 16)); static final X9ECParameters prime192v2 = new X9ECParameters( cFp192v2, cFp192v2.decodePoint( Hex.decode("03eea2bae7e1497842f2de7769cfe9c989c072ad696f48034a")), new BigInteger("ffffffffffffffffffffffff5fb1a724dc80418648d8dd31", 16), BigInteger.valueOf(1), Hex.decode("31a92ee2029fd10d901b113e990710f0d21ac6b6")); static final ECCurve cFp192v3 = new ECCurve.Fp( new BigInteger("6277101735386680763835789423207666416083908700390324961279"), new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16), new BigInteger("22123dc2395a05caa7423daeccc94760a7d462256bd56916", 16)); static final X9ECParameters prime192v3 = new X9ECParameters( cFp192v3, cFp192v3.decodePoint( Hex.decode("027d29778100c65a1da1783716588dce2b8b4aee8e228f1896")), new BigInteger("ffffffffffffffffffffffff7a62d031c83f4294f640ec13", 16), BigInteger.valueOf(1), Hex.decode("c469684435deb378c4b65ca9591e2a5763059a2e")); static final ECCurve cFp239v1 = new ECCurve.Fp( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); static final X9ECParameters prime239v1 = new X9ECParameters( cFp239v1, cFp239v1.decodePoint( Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), new BigInteger("7fffffffffffffffffffffff7fffff9e5e9a9f5d9071fbd1522688909d0b", 16), BigInteger.valueOf(1), Hex.decode("e43bb460f0b80cc0c0b075798e948060f8321b7d")); static final ECCurve cFp239v2 = new ECCurve.Fp( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), new BigInteger("617fab6832576cbbfed50d99f0249c3fee58b94ba0038c7ae84c8c832f2c", 16)); static final X9ECParameters prime239v2 = new X9ECParameters( cFp239v2, cFp239v2.decodePoint( Hex.decode("0238af09d98727705120c921bb5e9e26296a3cdcf2f35757a0eafd87b830e7")), new BigInteger("7fffffffffffffffffffffff800000cfa7e8594377d414c03821bc582063", 16), BigInteger.valueOf(1), Hex.decode("e8b4011604095303ca3b8099982be09fcb9ae616")); static final ECCurve cFp239v3 = new ECCurve.Fp( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), new BigInteger("255705fa2a306654b1f4cb03d6a750a30c250102d4988717d9ba15ab6d3e", 16)); static final X9ECParameters prime239v3 = new X9ECParameters( cFp239v3, cFp239v3.decodePoint( Hex.decode("036768ae8e18bb92cfcf005c949aa2c6d94853d0e660bbf854b1c9505fe95a")), new BigInteger("7fffffffffffffffffffffff7fffff975deb41b3a6057c3c432146526551", 16), BigInteger.valueOf(1), Hex.decode("7d7374168ffe3471b60a857686a19475d3bfa2ff")); static final ECCurve cFp256v1 = new ECCurve.Fp( new BigInteger("115792089210356248762697446949407573530086143415290314195533631308867097853951"), new BigInteger("ffffffff00000001000000000000000000000000fffffffffffffffffffffffc", 16), new BigInteger("5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b", 16)); static final X9ECParameters prime256v1 = new X9ECParameters( cFp256v1, cFp256v1.decodePoint( Hex.decode("036b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296")), new BigInteger("ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551", 16), BigInteger.valueOf(1), Hex.decode("c49d360886e704936a6678e1139d26b7819f7e90")); *//* /* * F2m Curves static final ECCurve c2m163v1 = new ECCurve.F2m( 163, new BigInteger("0800000000000000000000000000000107"), new BigInteger("072546B5435234A422E0789675F432C89435DE5242", 16), new BigInteger("00C9517D06D5240D3CFF38C74B20B6CD4D6F9DD4D9", 16));*/ /* static final X9ECParameters c2pnb163v1 = new X9ECParameters( c2m163v1, c2m163v1.decodePoint( Hex.decode("0307AF69989546103D79329FCC3D74880F33BBE803CB")), new BigInteger("0400000000000000000001E60FC8821CC74DAEAFC1", 16), BigInteger.valueOf(2), Hex.decode("D2CofB15760860DEF1EEF4D696E6768756151754"));*/ static final Hashtable objIds = new Hashtable(); static final Hashtable curves = new Hashtable(); static final Hashtable names = new Hashtable(); static { objIds.put("prime192v1", X9ObjectIdentifiers.prime192v1); objIds.put("prime192v2", X9ObjectIdentifiers.prime192v2); objIds.put("prime192v3", X9ObjectIdentifiers.prime192v3); objIds.put("prime239v1", X9ObjectIdentifiers.prime239v1); objIds.put("prime239v2", X9ObjectIdentifiers.prime239v2); objIds.put("prime239v3", X9ObjectIdentifiers.prime239v3); objIds.put("prime256v1", X9ObjectIdentifiers.prime256v1); names.put(X9ObjectIdentifiers.prime192v1, "prime192v1"); names.put(X9ObjectIdentifiers.prime192v2, "prime192v2"); names.put(X9ObjectIdentifiers.prime192v3, "prime192v3"); names.put(X9ObjectIdentifiers.prime239v1, "prime239v1"); names.put(X9ObjectIdentifiers.prime239v2, "prime239v2"); names.put(X9ObjectIdentifiers.prime239v3, "prime239v3"); names.put(X9ObjectIdentifiers.prime256v1, "prime256v1"); curves.put(X9ObjectIdentifiers.prime192v1, prime192v1); curves.put(X9ObjectIdentifiers.prime192v2, prime192v2); curves.put(X9ObjectIdentifiers.prime192v3, prime192v3); curves.put(X9ObjectIdentifiers.prime239v1, prime239v1); curves.put(X9ObjectIdentifiers.prime239v2, prime239v2); curves.put(X9ObjectIdentifiers.prime239v3, prime239v3); curves.put(X9ObjectIdentifiers.prime256v1, prime256v1); } public static X9ECParameters getByName( String name) { DERObjectIdentifier oid = (DERObjectIdentifier)objIds.get(name.toLowerCase()); if (oid != null) { return (X9ECParameters)curves.get(oid); } return null; } /** * return the X9ECParameters object for the named curve represented by * the passed in object identifier. Null if the curve isn't present. * * @param oid an object identifier representing a named curve, if present. */ public static X9ECParameters getByOID( DERObjectIdentifier oid) { return (X9ECParameters)curves.get(oid); } /** * return the object identifier signified by the passed in name. Null * if there is no object identifier associated with name. * * @return the object identifier associated with name, if present. */ public static DERObjectIdentifier getOID( String name) { return (DERObjectIdentifier)objIds.get(name); } /** * return the named curve name represented by the given object identifier. */ public static String getName( DERObjectIdentifier oid) { return (String)names.get(oid); } /** * returns an enumeration containing the name strings for curves * contained in this structure. */ public static Enumeration getNames() { return objIds.keys(); } }
package org.concord.framework.logging; public interface LogManager { void logAction(int level, String message); void logAction(int level, String message, int priority); void logObservation(int level, String message); void logObservation(int level, String message, int priority); void logLoggable(Loggable loggable); void logLoggable(Loggable loggable, LogHintMessage hint); void close(); void registerLoggable(Loggable loggable); void unregisterLoggable(Loggable loggable); void unregisterAllLoggables(); java.util.logging.Logger getLogger(); }
package afk.ge.tokyo.ems.systems; import afk.ge.ems.Engine; import afk.ge.ems.ISystem; import afk.ge.tokyo.ems.components.TextLabel; import afk.ge.tokyo.ems.nodes.TextLabelNode; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.font.FontRenderContext; import java.awt.font.LineMetrics; import java.awt.image.BufferedImage; import java.util.List; /** * * @author Jw */ public class TextLabelSystem implements ISystem { public static final int PAD = 3; private FontRenderContext frc = new FontRenderContext(null, true, true); private Font font = new Font("Myriad Pro", Font.BOLD, 10); private Engine engine; @Override public boolean init(Engine engine) { this.engine = engine; return true; } @Override public void update(float t, float dt) { List<TextLabelNode> nodes = engine.getNodeList(TextLabelNode.class); for (TextLabelNode node : nodes) { if (node.label.isUpdated()) { node.image.setImage(createTextLabel(node.label)); node.label.setUpdated(false); } } } private BufferedImage createTextLabel(TextLabel label) { String str = label.getText(); LineMetrics metrics = font.getLineMetrics(str, frc); Rectangle r = font.getStringBounds(str, frc).getBounds(); int width = r.width; int height = (int)(metrics.getAscent()+metrics.getDescent()); BufferedImage image = new BufferedImage(width+PAD*2, height+PAD*2, BufferedImage.TRANSLUCENT); Graphics2D g = image.createGraphics(); g.setFont(font); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); // g.setBackground(Color.BLACK); // g.clearRect(0, 0, image.getWidth(), image.getHeight()); g.setColor(new Color(0xE62C2A2B)); g.fillRoundRect(0, 0, image.getWidth(), image.getHeight(), 5, 5); g.setColor(new Color(0xD1D2D4)); g.drawString(str, PAD, PAD+metrics.getAscent()); g.dispose(); return image; } @Override public void destroy() { } }
package org.dita.dost.invoker; import static org.dita.dost.util.Constants.*; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import org.dita.dost.exception.DITAOTException; import org.dita.dost.log.DITAOTJavaLogger; import org.dita.dost.log.DITAOTLogger; import org.dita.dost.log.MessageUtils; import org.dita.dost.module.Content; import org.dita.dost.module.ContentImpl; import org.dita.dost.platform.Integrator; import org.dita.dost.util.Configuration; import org.dita.dost.writer.PropertiesWriter; /** * Command line tool for running DITA OT. * * @version 1.0 2005-5-31 * @author Zhang, Yuan Peng */ public final class CommandLineInvoker { /**logger.*/ private static DITAOTLogger logger = new DITAOTJavaLogger(); /** Map to store input parameters.*/ private static final Map<String, String> paramMap = new HashMap<String,String>(); static { paramMap.put("/basedir", "basedir"); paramMap.put("/ditadir", "dita.dir"); paramMap.put("/i", "args.input"); paramMap.put("/if", "dita.input"); paramMap.put("/id", "dita.input.dirname"); paramMap.put("/artlbl", "args.artlbl"); paramMap.put("/draft", "args.draft"); paramMap.put("/ftr", "args.ftr"); paramMap.put("/hdr", "args.hdr"); paramMap.put("/hdf", "args.hdf"); paramMap.put("/csspath", "args.csspath"); paramMap.put("/cssroot", "args.cssroot"); paramMap.put("/css", "args.css"); paramMap.put("/filter", "args.filter"); paramMap.put("/ditaext", "dita.extname"); paramMap.put("/outdir", "output.dir"); paramMap.put("/transtype", "transtype"); paramMap.put("/indexshow", "args.indexshow"); paramMap.put("/outext", "args.outext"); paramMap.put("/copycss", "args.copycss"); paramMap.put("/xsl", "args.xsl"); //Added by William on 2010-06-21 for bug:3012392 start paramMap.put("/xslpdf", "args.xsl.pdf"); //Added by William on 2010-06-21 for bug:3012392 end paramMap.put("/tempdir", "dita.temp.dir"); paramMap.put("/cleantemp", "clean.temp"); paramMap.put("/foimgext", "args.fo.img.ext"); paramMap.put("/javahelptoc", "args.javahelp.toc"); paramMap.put("/javahelpmap", "args.javahelp.map"); paramMap.put("/eclipsehelptoc", "args.eclipsehelp.toc"); paramMap.put("/eclipsecontenttoc", "args.eclipsecontent.toc"); paramMap.put("/xhtmltoc", "args.xhtml.toc"); paramMap.put("/xhtmlclass", "args.xhtml.classattr"); paramMap.put("/usetasklabels", "args.gen.task.lbl"); paramMap.put("/logdir", "args.logdir"); paramMap.put("/ditalocale", "args.dita.locale"); paramMap.put("/fooutputrellinks", "args.fo.output.rel.links"); paramMap.put("/foincluderellinks", "args.fo.include.rellinks"); paramMap.put("/odtincluderellinks", "args.odt.include.rellinks"); paramMap.put("/retaintopicfo", "retain.topic.fo"); paramMap.put("/version", "args.eclipse.version"); paramMap.put("/provider", "args.eclipse.provider"); paramMap.put("/fouserconfig", "args.fo.userconfig"); paramMap.put("/htmlhelpincludefile", "args.htmlhelp.includefile"); paramMap.put("/validate", "validate"); paramMap.put("/outercontrol", "outer.control"); paramMap.put("/generateouter", "generate.copy.outer"); paramMap.put("/onlytopicinmap", "onlytopic.in.map"); paramMap.put("/debug", "args.debug"); //added on 20100824 to disable grammar pool caching start paramMap.put("/grammarcache", "args.grammar.cache"); //added on 20100824 to disable grammar pool caching end paramMap.put("/odtimgembed", "args.odt.img.embed"); } /**propertyFile store input params.*/ private String propertyFile = null; /**antBuildFile run the ant.*/ private String antBuildFile = null; /**ditaDir.*/ private String ditaDir = null; /**debugMode.*/ private boolean debugMode = false; /** * Whether or not this instance has successfully been * constructed and is ready to run. */ private boolean readyToRun = false; /** * Constructor: CommandLineInvoker. */ public CommandLineInvoker() { } /** * Getter function of ditaDir. * @return Returns the ditaDir. */ public String getDitaDir() { return ditaDir; } /** * Process input arguments. * * @param args args * @throws DITAOTException Exception */ public void processArguments(final String[] args) throws DITAOTException { final Properties prop = new Properties(); if(args.length == 0){ printUsage(); readyToRun = false; return; } /* * validate dita.dir and init log message file */ String inputDitaDir = null; for (int i = 0; i < args.length; i++) { final String arg = args[i]; if (arg.startsWith("/ditadir:")) { inputDitaDir = arg.substring(arg.indexOf(":") + 1); } } ditaDir = new File(inputDitaDir, "").getAbsolutePath(); antBuildFile = new File(ditaDir, "build.xml").getAbsolutePath(); if (!new File(ditaDir, "build_template.xml").exists()) { throw new DITAOTException("Invalid dita-ot home directory '" + ditaDir + "', please specify the correct dita-ot home directory using '/ditadir'."); } MessageUtils.loadMessages(new File(new File(ditaDir, "resource"), "messages.xml").getAbsolutePath()); /* * Process input arguments */ for (int i = 0; i < args.length; i++) { final String arg = args[i]; if ("-help".equals(arg) || "-h".equals(arg) || "help".equals(arg)) { // plain "help" is a bug, keep for backwards compatibility printUsage(); return; } else if ("-version".equals(arg)) { printVersion(); return; } else if ("/debug".equals(arg) || "/d".equals(arg)) { debugMode = true; continue; } final int colonPos = arg.indexOf(COLON); if (colonPos == -1) { printUsage(); final Properties params = new Properties(); params.put("%1", arg); throw new DITAOTException(MessageUtils.getMessage("DOTJ001F", params).toString()); } final String javaArg = arg.substring(0, colonPos); final String antArg = paramMap.get(javaArg.toLowerCase()); if (antArg == null) { printUsage(); final Properties params = new Properties(); params.put("%1", javaArg); throw new DITAOTException(MessageUtils.getMessage("DOTJ002F", params).toString()); } String antArgValue = arg.substring(colonPos + 1); if (antArgValue.trim().length() == 0) { printUsage(); final Properties params = new Properties(); params.put("%1", javaArg); throw new DITAOTException(MessageUtils.getMessage("DOTJ003F", params).toString()); } //Added by William on 2009-11-09 for bug:2893493 start if (antArg.equals("clean.temp") && !("yes".equalsIgnoreCase(antArgValue) || "no".equalsIgnoreCase(antArgValue))) { antArgValue = "yes"; } //Added by William on 2009-11-09 for bug:2893493 end prop.put(antArg, antArgValue); } /* * Init base directory for transformation */ final String baseDir = new File(prop.getProperty("basedir", "")).getAbsolutePath(); prop.put("basedir", baseDir); prop.put("dita.dir", ditaDir); /* * Init temp directory * */ String tempDir; if (prop.containsKey("dita.temp.dir")) { tempDir = prop.getProperty("dita.temp.dir"); } else { final java.text.DateFormat format = new java.text.SimpleDateFormat("yyyyMMddHHmmssSSS"); final String timestamp = format.format(new java.util.Date()); prop.setProperty("dita.temp.dir", TEMP_DIR_DEFAULT + FILE_SEPARATOR + "temp" + timestamp); tempDir = prop.getProperty("dita.temp.dir"); } //tempDir = prop.getProperty("dita.temp.dir", TEMP_DIR_DEFAULT); File tempPath = new File(tempDir); if (!tempPath.isAbsolute()) { tempPath = new File(baseDir, tempDir); } if (!(tempPath.exists() || tempPath.mkdirs())) { String msg = null; final Properties params = new Properties(); params.put("%1", tempPath.getAbsoluteFile()); msg = MessageUtils.getMessage("DOTJ004F", params).toString(); throw new DITAOTException(msg); } propertyFile = new File(tempPath, "property.temp").getAbsolutePath(); /* * Output input params into temp property file */ final PropertiesWriter propWriter = new PropertiesWriter(); final Content content = new ContentImpl(); content.setValue(prop); propWriter.setContent(content); propWriter.write(propertyFile); readyToRun = true; } /** * Start ant process to execute the build process. * * @throws IOException IOException */ public void startAnt() throws IOException { final List<String> cmd = new ArrayList<String>(INT_8); cmd.add(getCommandRunner()); cmd.add("-f"); cmd.add(antBuildFile); cmd.add("-logger"); cmd.add("org.dita.dost.log.DITAOTBuildLogger"); cmd.add("-propertyfile"); cmd.add(propertyFile); if (debugMode){ cmd.add("-d"); } // targets cmd.add("init"); final String[] cmds = new String[cmd.size()]; cmd.toArray(cmds); startTransformation(cmds); } /** * Get Ant executable. * @return Ant executable file name */ private String getCommandRunner() { return (OS_NAME.toLowerCase().indexOf(OS_NAME_WINDOWS) != -1) ? "ant.bat" : "ant"; } /** * begin transformation. * @param cmd cmd * @throws IOException exception */ private void startTransformation(final String[] cmd) throws IOException { BufferedReader outReader = null; final Process antProcess = Runtime.getRuntime().exec(cmd); try { /* * Get output messages and print to console. * Note: Since these messages have been logged to the log file, * there is no need to output them to log file. */ outReader = new BufferedReader(new InputStreamReader(antProcess.getInputStream())); for (String line = outReader.readLine(); line != null; line = outReader.readLine()) { System.out.println(line); } } finally { if (outReader != null) { try { outReader.close(); } catch (final IOException e) { logger.logException(e); } } } BufferedReader errReader = null; try { errReader = new BufferedReader(new InputStreamReader(antProcess.getErrorStream())); for (String line = errReader.readLine(); line != null; line = errReader.readLine()) { System.err.println(line); } } finally { if (errReader != null) { try { errReader.close(); } catch (final IOException e) { logger.logException(e); } } } } /** * print dita version. */ private void printVersion() { System.out.println(Configuration.configuration.get("otversion")); } /** * Prints the usage information for this class to <code>System.out</code>. */ private void printUsage() { System.out.println("java -jar lib/dost.jar [mandatory parameters] [options]"); System.out.println("Mandatory parameters:"); System.out.println(" /i: specify path and name of the input file"); System.out.println(" /transtype: specify the transformation type"); System.out.println("Options: "); System.out.println(" -help, -h print this message"); System.out.println(" -version print the version information and exit"); System.out.println(" /basedir: specify the working directory"); System.out.println(" /ditadir: specify the toolkit's home directory. Default is \"temp\""); System.out.println(" /outdir: specify the output directory"); System.out.println(" /tempdir: specify the temporary directory"); System.out.println(" /logdir: specify the log directory"); System.out.println(" /ditaext: specify the file extension name to be used in the temp directory. Default is \".xml\""); System.out.println(" /filter: specify the name of the file that contains the filter/flaggin/revision information"); System.out.println(" /draft: specify whether to output draft info. Valid values are \"no\" and \"yes\". Default is \"no\" (hide them)."); System.out.println(" /artlbl: specify whether to output artwork filenames. Valid values are \"no\" and \"yes\""); System.out.println(" /ftr: specify the file to be placed in the BODY running-footing area"); System.out.println(" /hdr: specify the file to be placed in the BODY running-heading area"); System.out.println(" /hdf: specify the file to be placed in the HEAD area"); System.out.println(" /csspath: specify the path for css reference"); System.out.println(" /css: specify user css file"); System.out.println(" /cssroot: specify the root directory for user specified css file"); System.out.println(" /copycss: specify whether to copy user specified css files. Valid values are \"no\" and \"yes\""); System.out.println(" /indexshow: specify whether each index entry should display within the body of the text itself. Valid values are \"no\" and \"yes\""); System.out.println(" /outext: specify the output file extension for generated xhtml files. Default is \".html\""); System.out.println(" /xsl: specify the xsl file used to replace the default xsl file"); System.out.println(" /xslpdf: specify the xsl file used to replace the default xsl file when transforming pdf"); System.out.println(" /cleantemp: specify whether to clean the temp directory before each build. Valid values are \"no\" and \"yes\". Default is \"yes\""); System.out.println(" /foimgext: specify the extension of image file in legacy pdf transformation. Default is \".jpg\""); System.out.println(" /fooutputrellinks For legacy PDF transform: determine if links are included in the PDF. Values are \"no\" and \"yes\". Default is \"no\"."); System.out.println(" /foincluderellinks For default PDF transform: determine which links are included in the PDF. Values are \"none\", \"all\", and \"nofamily\". Default is \"none\"."); System.out.println(" /odtincluderellinks For default ODT transform: determine which links are included in the ODT. Values are \"none\", \"all\", and \"nofamily\". Default is \"none\"."); System.out.println(" /retaintopicfo specify that topic.fo file should be preserved in the output directory. Specify any value, such as \"yes\", to preserve the file."); System.out.println(" /javahelptoc: specify the root file name of the output javahelp toc file in javahelp transformation. Default is the name of the input ditamap file"); System.out.println(" /javahelpmap: specify the root file name of the output javahelp map file in javahelp transformation. Default is the name of the input ditamap file"); System.out.println(" /eclipsehelptoc: specify the root file name of the output eclipsehelp toc file in eclipsehelp transformation. Default is the name of the input ditamap file"); System.out.println(" /eclipsecontenttoc: specify the root file name of the output Eclipse content provider toc file in eclipsecontent transformation. Default is the name of the input ditamap file"); System.out.println(" /xhtmltoc: specify the root file name of the output xhtml toc file in xhtml transformation"); System.out.println(" /xhtmlclass: specify whether DITA element names and ancestry are included in XHTML class attributes. Only \"yes\" and \"no\" are valid values. The default is yes. "); System.out.println(" /usetasklabels: specify whether DITA Task sections should get headings. Only \"YES\" and \"NO\" are valid values. The default is NO. "); System.out.println(" /validate: specify whether the ditamap/dita/xml files to be validated"); System.out.println(" /outercontrol: specify how to respond to the overflowing dita/topic files. Only \"fail\", \"warn\" and \"quiet\" are valid values. The default is warn. "); System.out.println(" /generateouter: specify how to deal with the overflowing dita/topic files. Only \"1\", \"2\" and \"3\" are valid values. The default is 1. Option 1: Only generate/copy files that fit within the designated output directory. Option 2: Generate/copy all files, even those that will end up outside of the output directory. Option 3: the old solution,adjust the input.dir according to the referenced files" + "(It is the most secure way to avoid broken links). (not default option any more but keep this as the option of backward compatibility)."); System.out.println(" /onlytopicinmap: specify whether make dita processor only resolve dita/topic files which are referenced by primary ditamap files Only \"true\" and \"false\" are valid values. The default is false. "); System.out.println(" /debug: specify whether extra debug information should be included in the log. Only \"yes\" and \"no\" are valid values. The default is no. "); System.out.println(" /grammarcache: specify whether grammar pool caching is used when parsing dita files. Only \"yes\" and \"no\" are valid values. The default is yes. "); System.out.println(" /odtimgembed: specify whether embedding images as binary data in odt transform. Only \"yes\" and \"no\" are valid values. The default is yes. "); } /** * Get the input parameter and map them into parameters which can be * accepted by Ant build task. Then start the building process * * @param args args * */ public static void main(final String[] args) { final CommandLineInvoker invoker = new CommandLineInvoker(); final Integrator integrator = new Integrator(); try { invoker.processArguments(args); if (invoker.readyToRun) { integrator.setDitaDir(new File(invoker.getDitaDir())); integrator.setProperties(new File("integrator.properties")); integrator.execute(); invoker.startAnt(); } } catch (final Exception e) { logger.logException(e); } } }
package algorithms.imageProcessing; import algorithms.util.PairInt; import java.util.Set; import java.util.logging.Logger; /** * The erosion filter iterates over all pixels in the image, checking whether * the current non-null pixel can be nulled without disconnecting any adjacent * pixels. * * TODO: the erosion filter doesn't know the overall shape so corners and lines * could be improved in the final result by adding templates to the filter * to find and handle potential lines and corners in a non-resolution dependent * way. * * TODO: It's all boolean rules, so it looks like a clever way of using boolean * logic on more than 1 pixel as the current being tested for nullability, * at the same time should reduce common comparisons and make a faster filter. * * @author nichole */ public class ErosionFilter extends AbstractLineThinner { protected boolean useLineDrawingMode = false; protected boolean debug = false; private boolean performEndOfLineCheck = true; private Logger log = Logger.getLogger(this.getClass().getName()); /** * for images which are already line drawings, that is images such as * maps with only lines, or for block images, use this to avoid a gap filling * stage that fills single pixel gaps surrounded by non-zero pixels. * (Else, the filter applies such a gap filling algorithm to help avoid * creating bubbles in thick lines). */ @Override public void useLineDrawingMode() { useLineDrawingMode = true; } @Override public void setDebug(boolean setToDebug) { debug = setToDebug; } @Override public void applyFilter(final GreyscaleImage input) { GreyscaleImage output = input.copyImage(); if (!useLineDrawingMode) { prefillGapsSurroundedByNeighbors(output); } int count = 1; int maxIter = 100; int nIter = 0; GreyscaleImage input2; while ((count > 0) && (nIter < maxIter)) { count = 0; input2 = output.copyImage(); // alternate the directions of approach to 'erode' from both 'sides' if ((nIter & 1) == 0) { for (int i = 0; i < input2.getWidth(); i++) { for (int j = 0; j < input2.getHeight(); j++) { boolean nulled = process(input2, output, i, j); if (nulled) { count++; } } } } else { for (int i = (input2.getWidth() - 1); i > -1; i for (int j = (input2.getHeight() - 1); j > -1; j boolean nulled = process(input2, output, i, j); if (nulled) { count++; } } } } log.fine("nulled " + count + " pixels"); nIter++; } input.resetTo(output); } /** * instead of dilation, just fill in any gaps that have 4 neighbors already * filled in. This should not act upon many pixels. * * @param input */ protected void prefillGapsSurroundedByNeighbors(final GreyscaleImage input) { int w = input.getWidth(); int h = input.getHeight(); int count = 1; for (int i = 0; i < w; i++) { for (int j = 0; j < h; j++) { if (input.getValue(i, j) > 0) { continue; } if (!isASmallerSearchRegion(i, j, w, h) && hasImmediateFourNeighbors(input, i, j)) { float avg = input.getValue(i, j + 1) + input.getValue(i + 1, j) + input.getValue(i, j - 1) + input.getValue(i - 1, j); avg /= 4.f; input.setValue(i, j, (int)avg); count++; } } } log.fine("filled in " + count + " pixels"); } /** * within the surrounding 8 pixels, return false if the point is the * endpoint of a line with width of 1 pixel, or * return true if nulling the center point * would not disconnect the othe points or return true if the point. * * TODO: compute the runtime complexity of this. * * @param input * @param row * @param col * @return */ private boolean canBeNulled(final GreyscaleImage input, int col, int row) { /* handle edge cases, that is searches constrained to regions smaller than the full 3x3 neighborhood region, that is regions of sizes 2X2 or 2x3 or 3X2 */ int w = input.getWidth(); int h = input.getHeight(); boolean isASmallerSearchRegion = isASmallerSearchRegion( col, row, w, h); if (isASmallerSearchRegion) { boolean doesDisconnect = isASmallerSearchRegionAndDoesDisconnect( input, col, row); return !doesDisconnect; } /* check that this isn't the endpoint of a 1 pixel width line. */ if (isTheEndOfAOnePixelLine(input, col, row)) { return false; } /* else, try the 8 pixel neighborhood with C being the current (col, row) and @ being the pixel tested for disconnection by setting C to 0. . is a 0 ? is an AND between possible '1's. ("At Least One") _ is a pixel that can be ignored (1) (2) (3) (4) (5) (6) (7) (8) @ . ? _ @ _ ? . @ ? . _ ? ? ? ? ? ? ? ? ? _ . ? . C ? . C . ? C . ? C @ ? C . . C . . C ? @ C ? ? ? ? ? ? ? ? ? ? ? . _ ? . @ _ @ _ @ . ? _ . ? */ boolean doesDisconnect = doesDisconnect(input, col, row); return !doesDisconnect; } /** * this assumes that the invoker has checked that (col, row) has 1 pixel * to each side and 1 above and below. * @param input * @param col * @param row * @return */ protected boolean hasImmediateFourNeighbors(final GreyscaleImage input, int col, int row) { if ((input.getValue(col, row + 1) > 0) && (input.getValue(col + 1, row) > 0) && (input.getValue(col, row - 1) > 0) && (input.getValue(col - 1, row) > 0)) { return true; } return false; } /** * this assumes that the invoker has checked that (col, row) has 1 pixel * to each side and 1 above and below. * @return */ protected boolean hasImmediateFourNeighbors(PairInt p, Set<PairInt> points, Set<PairInt> overridePointsAdded, Set<PairInt> overridePointsRemoved) { for (int nIdx = 0; nIdx < fourNeighborsX.length; nIdx++) { int x = p.getX() + fourNeighborsX[nIdx]; int y = p.getY() + fourNeighborsY[nIdx]; PairInt p2 = new PairInt(x, y); if (overridePointsRemoved.contains(p2)) { return false; } if (!overridePointsAdded.contains(p2) && !points.contains(p2)) { return false; } } return true; } /** * for the full 8 neighbor region, determine whether nulling the pixel * at (col, row) would disconnect the remaining line. Note that the * boolean logic is embedded in the comments. One should be able to * combine the rules for multiple pixel tests to reduce the redundant * comparisons for the regions in common. * * Note, that row and col are expected to be at least 1 pixel distant * from the image borders. * * @param input * @param col * @param row * @return */ protected boolean doesDisconnect(final GreyscaleImage input, int col, int row) { /* coordinates of the 8 neighbors as already created PairInts without bound checks. indexes are found as +1 of the difference relative to center, for example, a point for (col-1, row-1) is found as neighborCoords[0][0] */ PairInt[][] neighborCoords = createCoordinatePointsForEightNeighbors( col, row); /* 6 7 8 +1 2 transformed by 90 rot: 15 11 6 11 *C* 12 0 1 16 C* 7 15 16 17 -1 0 17 12 8 -1 0 1 0 1 2 disconnects: -- if (6 || 7 || 8) && (11 && 17) && !(15) && !(16) -- if (6 || 7 || 8) && (12 && 15) && !(16) && !(17) -- if (6 || 7 || 8) && (15 || 16 || 17) && !(11) && !(12) -- if !(6) && !(7) && (8) && (11) && !(12) -- if (6) && !(7) && !(8) && !(11) && (12) does not disconnect -- if (6 || 7 || 8) && !(15) && !(16) && !(17) && !(11) && !(12) then rotate 90 and test, then rotate 90 and test, then rotate 90 and test */ for (int nRot = 0; nRot < 4; nRot++) { if (nRot > 0) { rotateBy90(neighborCoords); } if (//if (6 || 7 || 8) (input.getValue(neighborCoords[0][2].getX(), neighborCoords[0][2].getY()) > 0) || (input.getValue(neighborCoords[1][2].getX(), neighborCoords[1][2].getY()) > 0) || (input.getValue(neighborCoords[2][2].getX(), neighborCoords[2][2].getY()) > 0) ) { if ( //if (6 || 7 || 8) && (11 && 17) && !(15) && !(16) ( (input.getValue(neighborCoords[0][1].getX(), neighborCoords[0][1].getY()) > 0) && (input.getValue(neighborCoords[2][0].getX(), neighborCoords[2][0].getY()) > 0) ) && ( (input.getValue(neighborCoords[0][0].getX(), neighborCoords[0][0].getY()) == 0) && (input.getValue(neighborCoords[1][0].getX(), neighborCoords[1][0].getY()) == 0) ) ) { return true; } else if (//if (6 || 7 || 8) && (12 && 15) && !(16) && !(17) ( (input.getValue(neighborCoords[2][1].getX(), neighborCoords[2][1].getY()) > 0) && (input.getValue(neighborCoords[0][0].getX(), neighborCoords[0][0].getY()) > 0) ) && ( (input.getValue(neighborCoords[1][0].getX(), neighborCoords[1][0].getY()) == 0) && (input.getValue(neighborCoords[2][0].getX(), neighborCoords[2][0].getY()) == 0) ) ) { return true; } else if (//if (6 || 7 || 8) && (15 || 16 || 17) && !(11) && !(12) ( (input.getValue(neighborCoords[0][0].getX(), neighborCoords[0][0].getY()) > 0) || (input.getValue(neighborCoords[1][0].getX(), neighborCoords[1][0].getY()) > 0) || (input.getValue(neighborCoords[2][0].getX(), neighborCoords[2][0].getY()) > 0) ) && ( (input.getValue(neighborCoords[0][1].getX(), neighborCoords[0][1].getY()) == 0) && (input.getValue(neighborCoords[2][1].getX(), neighborCoords[2][1].getY()) == 0) ) ) { return true; } else if (//if (6 || 7 || 8) && !(15) && !(16) && !(17) && !(11) && !(12) (input.getValue(neighborCoords[0][0].getX(), neighborCoords[0][0].getY()) == 0) && (input.getValue(neighborCoords[1][0].getX(), neighborCoords[1][0].getY()) == 0) && (input.getValue(neighborCoords[2][0].getX(), neighborCoords[2][0].getY()) == 0) && (input.getValue(neighborCoords[0][1].getX(), neighborCoords[0][1].getY()) == 0) && (input.getValue(neighborCoords[2][1].getX(), neighborCoords[2][1].getY()) == 0) ) { return false; } } else if (//if (6) && !(7) && !(8) && !(11) && (12) (input.getValue(neighborCoords[0][2].getX(), neighborCoords[0][2].getY()) > 0) && (input.getValue(neighborCoords[1][2].getX(), neighborCoords[1][2].getY()) == 0) && (input.getValue(neighborCoords[2][2].getX(), neighborCoords[2][2].getY()) == 0) && (input.getValue(neighborCoords[0][1].getX(), neighborCoords[0][1].getY()) == 0) && (input.getValue(neighborCoords[2][1].getX(), neighborCoords[2][1].getY()) > 0) ) { return true; } else if (//if !(6) && !(7) && (8) && (11) && !(12) (input.getValue(neighborCoords[0][2].getX(), neighborCoords[0][2].getY()) == 0) && (input.getValue(neighborCoords[1][2].getX(), neighborCoords[1][2].getY()) == 0) && (input.getValue(neighborCoords[2][2].getX(), neighborCoords[2][2].getY()) > 0) && (input.getValue(neighborCoords[0][1].getX(), neighborCoords[0][1].getY()) > 0) && (input.getValue(neighborCoords[2][1].getX(), neighborCoords[2][1].getY()) == 0) ) { return true; } } return false; } private boolean hasAZeroInNeighbors(final GreyscaleImage input, int col, int row) { int ks = 3; int h = ks >> 1; // search for a zero in the neighboring 8 pixels for (int kCol = 0; kCol < ks; kCol++) { int x = kCol - h; int imgX = col + x; if ((imgX < 0) || (imgX > (input.getWidth() - 1))) { continue; } for (int kRow = 0; kRow < ks; kRow++) { int y = kRow - h; int imgY = row + y; if ((imgY < 0) || (imgY > (input.getHeight() - 1))) { continue; } if (input.getValue(imgX, imgY) == 0) { return true; } } } return false; } /** * return true if this endpoint (col, row) is the end of a line that has * a width of 1 pixel. * * @param input * @param col * @param row * @return */ protected boolean isTheEndOfAOnePixelLine(final GreyscaleImage input, int col, int row) { //TODO: this method could be simplified if ((input.getValue(col, row + 1) > 0) && (input.getValue(col + 1, row + 1) == 0) && (input.getValue(col + 1, row) == 0) && (input.getValue(col + 1, row - 1) == 0) && (input.getValue(col, row - 1) == 0) && (input.getValue(col - 1, row - 1) == 0) && (input.getValue(col - 1, row) == 0) && (input.getValue(col - 1, row + 1) == 0) ) { /* further check that line thickness is 1 outside of the 8 neighbors # # # . @ . . C . . . . */ if ((row + 2) > (input.getHeight() - 1)) { return true; } // only 1 of the '#' can be non-zero int count = 0; if (input.getValue(col - 1, row + 2) > 0) { count++; } if (input.getValue(col, row + 2) > 0) { count++; } if (input.getValue(col + 1, row + 2) > 0) { count++; } if (count > 1) { return false; } return true; } if ((input.getValue(col + 1, row + 1) > 0) && (input.getValue(col + 1, row) == 0) && (input.getValue(col + 1, row - 1) == 0) && (input.getValue(col, row - 1) == 0) && (input.getValue(col - 1, row - 1) == 0) && (input.getValue(col - 1, row) == 0) && (input.getValue(col - 1, row + 1) == 0) && (input.getValue(col, row + 1) == 0) ) { /* further check that line thickness is 1 outside of the 8 neighbors # # # . . @ # . C . # . . . */ if ((row + 2) > (input.getHeight() - 1)) { if ((col + 2) > (input.getWidth() - 1)) { return true; } int count = 0; if (input.getValue(col + 2, row + 1) > 0) { count++; } if (input.getValue(col + 2, row) > 0) { count++; } if (count > 1) { return false; } return true; } else if ((col + 2) > (input.getWidth() - 1)) { int count = 0; if (input.getValue(col, row + 2) > 0) { count++; } if (input.getValue(col + 1, row + 2) > 0) { count++; } if (count > 1) { return false; } return true; } // only 1 of the '#' can be non-zero int count = 0; if (input.getValue(col, row + 2) > 0) { count++; } if (input.getValue(col + 1, row + 2) > 0) { count++; } if (input.getValue(col + 2, row + 2) > 0) { count++; } if (input.getValue(col + 2, row + 1) > 0) { count++; } if (input.getValue(col + 2, row) > 0) { count++; } if (count > 1) { return false; } return true; } if ((input.getValue(col + 1, row) > 0) && (input.getValue(col + 1, row + 1) == 0) && (input.getValue(col, row + 1) == 0) && (input.getValue(col - 1, row + 1) == 0) && (input.getValue(col - 1, row) == 0) && (input.getValue(col - 1, row - 1) == 0) && (input.getValue(col, row - 1) == 0) && (input.getValue(col + 1, row - 1) == 0) ) { if ((col + 2) > (input.getWidth() - 1)) { return true; } // only 1 of the '#' can be non-zero int count = 0; if (input.getValue(col + 2, row + 1) > 0) { count++; } if (input.getValue(col + 2, row) > 0) { count++; } if (input.getValue(col + 2, row - 1) > 0) { count++; } if (count > 1) { return false; } return true; } if ((input.getValue(col + 1, row - 1) > 0) && (input.getValue(col + 1, row) == 0) && (input.getValue(col + 1, row + 1) == 0) && (input.getValue(col, row + 1) == 0) && (input.getValue(col - 1, row + 1) == 0) && (input.getValue(col - 1, row) == 0) && (input.getValue(col - 1, row - 1) == 0) && (input.getValue(col, row - 1) == 0) ) { if ((row - 2) < 0) { if ((col + 2) > (input.getWidth() - 1)) { return true; } int count = 0; if (input.getValue(col + 2, row) > 0) { count++; } if (input.getValue(col + 2, row - 1) > 0) { count++; } if (count > 1) { return false; } return true; } else if ((col + 2) > (input.getWidth() - 1)) { int count = 0; if (input.getValue(col, row - 2) > 0) { count++; } if (input.getValue(col + 1, row - 2) > 0) { count++; } if (count > 1) { return false; } return true; } int count = 0; if (input.getValue(col + 2, row) > 0) { count++; } if (input.getValue(col + 2, row - 1) > 0) { count++; } if (input.getValue(col + 2, row - 2) > 0) { count++; } if (input.getValue(col + 1, row - 2) > 0) { count++; } if (input.getValue(col, row - 2) > 0) { count++; } if (count > 1) { return false; } return true; } if ((input.getValue(col, row - 1) > 0) && (input.getValue(col + 1, row - 1) == 0) && (input.getValue(col + 1, row) == 0) && (input.getValue(col + 1, row + 1) == 0) && (input.getValue(col, row + 1) == 0) && (input.getValue(col - 1, row + 1) == 0) && (input.getValue(col - 1, row) == 0) && (input.getValue(col - 1, row - 1) == 0) ) { if ((row - 2) < 0) { return true; } // only 1 of the '#' can be non-zero int count = 0; if (input.getValue(col - 1, row - 2) > 0) { count++; } if (input.getValue(col, row - 2) > 0) { count++; } if (input.getValue(col + 1, row - 2) > 0) { count++; } if (count > 1) { return false; } return true; } if ((input.getValue(col - 1, row - 1) > 0) && (input.getValue(col, row - 1) == 0) && (input.getValue(col + 1, row - 1) == 0) && (input.getValue(col + 1, row) == 0) && (input.getValue(col + 1, row + 1) == 0) && (input.getValue(col, row + 1) == 0) && (input.getValue(col - 1, row + 1) == 0) && (input.getValue(col - 1, row) == 0) ) { if ((col - 2) < 0) { if ((row - 2) < 0) { return true; } // only 1 of the '#' can be non-zero int count = 0; if (input.getValue(col - 1, row - 2) > 0) { count++; } if (input.getValue(col, row - 2) > 0) { count++; } if (count > 1) { return false; } return true; } else if ((row - 2) < 0) { int count = 0; if (input.getValue(col - 2, row) > 0) { count++; } if (input.getValue(col - 2, row - 1) > 0) { count++; } if (count > 1) { return false; } return true; } int count = 0; if (input.getValue(col - 2, row) > 0) { count++; } if (input.getValue(col - 2, row - 1) > 0) { count++; } if (input.getValue(col - 2, row - 2) > 0) { count++; } if (input.getValue(col - 1, row - 2) > 0) { count++; } if (input.getValue(col, row - 2) > 0) { count++; } if (count > 1) { return false; } return true; } if ((input.getValue(col - 1, row) > 0) && (input.getValue(col - 1, row + 1) == 0) && (input.getValue(col, row + 1) == 0) && (input.getValue(col + 1, row + 1) == 0) && (input.getValue(col + 1, row) == 0) && (input.getValue(col + 1, row - 1) == 0) && (input.getValue(col, row - 1) == 0) && (input.getValue(col - 1, row - 1) == 0) ) { if ((col - 2) < 0) { return true; } // only 1 of the '#' can be non-zero int count = 0; if (input.getValue(col - 2, row - 1) > 0) { count++; } if (input.getValue(col - 2, row) > 0) { count++; } if (input.getValue(col - 2, row + 1) > 0) { count++; } if (count > 1) { return false; } return true; } if ((input.getValue(col - 1, row + 1) > 0) && (input.getValue(col, row + 1) == 0) && (input.getValue(col + 1, row + 1) == 0) && (input.getValue(col + 1, row) == 0) && (input.getValue(col + 1, row - 1) == 0) && (input.getValue(col, row - 1) == 0) && (input.getValue(col - 1, row - 1) == 0) && (input.getValue(col - 1, row) == 0) ) { if ((col - 2) < 0) { if ((row + 2) > (input.getHeight() - 1)) { return true; } // only 1 of the '#' can be non-zero int count = 0; if (input.getValue(col - 1, row + 2) > 0) { count++; } if (input.getValue(col, row + 2) > 0) { count++; } if (count > 1) { return false; } return true; } else if ((row + 2) > (input.getHeight() - 1)) { int count = 0; if (input.getValue(col - 2, row) > 0) { count++; } if (input.getValue(col - 2, row + 1) > 0) { count++; } if (count > 1) { return false; } return true; } int count = 0; if (input.getValue(col - 2, row) > 0) { count++; } if (input.getValue(col - 2, row + 1) > 0) { count++; } if (input.getValue(col - 2, row + 2) > 0) { count++; } if (input.getValue(col - 1, row + 2) > 0) { count++; } if (input.getValue(col, row + 2) > 0) { count++; } if (count > 1) { return false; } return true; } return false; } /** * return true if pixel at (i, j) is nullable, that is does not disconnect * other currently connected points. the method does set the pixel value * to 0 if it can and return true if so. * @param input * @param output * @param i * @param j * @return */ boolean process(final GreyscaleImage input, final GreyscaleImage output, int i, int j) { if (output.getValue(i, j) == 0) { return false; } int w = input.getWidth(); int h = input.getHeight(); if (!isASmallerSearchRegion(i, j, w, h) && hasImmediateFourNeighbors(output, i, j)) { return false; } // choosing input here helps to thin a line from one direction // at a time rather than continue thinning from the same // direction if (hasAZeroInNeighbors(input, i, j)) { //if (!doesDisconnectOrIsEndPoint(output, i, j)) { if (canBeNulled(output, i, j)) { output.setValue(i, j, 0); return true; } } return false; } /** * return true if pixel at (i, j) is nullable, that is does not disconnect * other currently connected points. note that if point is not present * in points (or is in overridePointsRemoved) then it returns an immediate * false. the method does set the pixel value * to 0 if it can and return true if so. * * @return */ boolean process(PairInt p, Set<PairInt> points, Set<PairInt> overridePointsAdded, Set<PairInt> overridePointsRemoved, int imageWidth, int imageHeight) { // if point does not exist already in point set, return false if (overridePointsRemoved.contains(p)) { return false; } else if (!points.contains(p) && !overridePointsAdded.contains(p)) { return false; } if (!isASmallerSearchRegion(p.getX(), p.getY(), imageWidth, imageHeight) && hasImmediateFourNeighbors(p, points, overridePointsAdded, overridePointsRemoved)) { return false; } // choosing input here helps to thin a line from one direction // at a time rather than continue thinning from the same // direction if (hasAZeroInNeighbors(p, points, overridePointsAdded, overridePointsRemoved, imageWidth, imageHeight)) { if (canBeNulled(p, points, overridePointsAdded, overridePointsRemoved, imageWidth, imageHeight)) { overridePointsRemoved.add(p); return true; } } return false; } private boolean hasAZeroInNeighbors(PairInt p, Set<PairInt> points, Set<PairInt> overridePointsAdded, Set<PairInt> overridePointsRemoved, int imageWidth, int imageHeight) { for (int nIdx = 0; nIdx < fourNeighborsX.length; nIdx++) { int x = p.getX() + fourNeighborsX[nIdx]; int y = p.getY() + fourNeighborsY[nIdx]; if ((x < 0) || (x > (imageWidth - 1)) || (y < 0) || (y > (imageHeight - 1))) { continue; } PairInt p2 = new PairInt(x, y); if (overridePointsRemoved.contains(p2)) { return true; } if (!overridePointsAdded.contains(p2) && !points.contains(p2)) { return true; } } return false; } protected void overrideEndOfLineCheck() { performEndOfLineCheck = false; } private boolean canBeNulled(PairInt p, Set<PairInt> points, Set<PairInt> overridePointsAdded, Set<PairInt> overridePointsRemoved, int imageWidth, int imageHeight) { /* handle edge cases, that is searches constrained to regions smaller than the full 3x3 neighborhood region, that is regions of sizes 2X2 or 2x3 or 3X2 */ boolean isASmallerSearchRegion = isASmallerSearchRegion( p.getX(), p.getY(), imageWidth, imageHeight); if (isASmallerSearchRegion) { boolean doesDisconnect = isASmallerSearchRegionAndDoesDisconnect( p, points, overridePointsAdded, overridePointsRemoved, imageWidth, imageHeight); return !doesDisconnect; } if (performEndOfLineCheck) { //check that this isn't the endpoint of a 1 pixel width line. if (isTheEndOfAOnePixelLine(p, points, overridePointsAdded, overridePointsRemoved, imageWidth, imageHeight)) { return false; } } /* else, try the 8 pixel neighborhood with C being the current (col, row) and @ being the pixel tested for disconnection by setting C to 0. . is a 0 ? is an AND between possible '1's. ("At Least One") _ is a pixel that can be ignored (1) (2) (3) (4) (5) (6) (7) (8) @ . ? _ @ _ ? . @ ? . _ ? ? ? ? ? ? ? ? ? _ . ? . C ? . C . ? C . ? C @ ? C . . C . . C ? @ C ? ? ? ? ? ? ? ? ? ? ? . _ ? . @ _ @ _ @ . ? _ . ? */ boolean doesDisconnect = doesDisconnect(p, points, overridePointsAdded, overridePointsRemoved, imageWidth, imageHeight); return !doesDisconnect; } private boolean isTheEndOfAOnePixelLine(PairInt p, Set<PairInt> points, Set<PairInt> overridePointsAdded, Set<PairInt> overridePointsRemoved, int imageWidth, int imageHeight) { //TODO: this method could be simplified int col = p.getX(); int row = p.getY(); /* coordinates of the 8 neighbors as already created PairInts without bound checks. indexes are found as +1 of the difference relative to center, for example, a point for (col-1, row-1) is found as neighborCoords[0][0] */ PairInt[][] neighborCoords = createCoordinatePointsForEightNeighbors( col, row); if ( (!overridePointsRemoved.contains(neighborCoords[1][2]) && (overridePointsAdded.contains(neighborCoords[1][2]) || points.contains(neighborCoords[1][2]))) && (overridePointsRemoved.contains(neighborCoords[2][2]) || (!overridePointsAdded.contains(neighborCoords[2][2]) && !points.contains(neighborCoords[2][2]))) && (overridePointsRemoved.contains(neighborCoords[2][1]) || (!overridePointsAdded.contains(neighborCoords[2][1]) && !points.contains(neighborCoords[2][1]))) && (overridePointsRemoved.contains(neighborCoords[2][0]) || (!overridePointsAdded.contains(neighborCoords[2][0]) && !points.contains(neighborCoords[2][0]))) && (overridePointsRemoved.contains(neighborCoords[1][0]) || (!overridePointsAdded.contains(neighborCoords[1][0]) && !points.contains(neighborCoords[1][0]))) && (overridePointsRemoved.contains(neighborCoords[0][0]) || (!overridePointsAdded.contains(neighborCoords[0][0]) && !points.contains(neighborCoords[0][0]))) && (overridePointsRemoved.contains(neighborCoords[0][1]) || (!overridePointsAdded.contains(neighborCoords[0][1]) && !points.contains(neighborCoords[0][1]))) && (overridePointsRemoved.contains(neighborCoords[0][2]) || (!overridePointsAdded.contains(neighborCoords[0][2]) && !points.contains(neighborCoords[0][2]))) ) { /* further check that line thickness is 1 outside of the 8 neighbors # # # . @ . . C . . . . */ if ((row + 2) > (imageHeight - 1)) { return true; } // only 1 of the '#' can be non-zero int count = 0; PairInt p2 = new PairInt(col - 1, row + 2); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } p2 = new PairInt(col, row + 2); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } p2 = new PairInt(col + 1, row + 2); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } if (count > 1) { return false; } return true; } if ( (!overridePointsRemoved.contains(neighborCoords[2][2]) && (overridePointsAdded.contains(neighborCoords[2][2]) || points.contains(neighborCoords[2][2]))) && (overridePointsRemoved.contains(neighborCoords[2][1]) || (!overridePointsAdded.contains(neighborCoords[2][1]) && !points.contains(neighborCoords[2][1]))) && (overridePointsRemoved.contains(neighborCoords[2][0]) || (!overridePointsAdded.contains(neighborCoords[2][0]) && !points.contains(neighborCoords[2][0]))) && (overridePointsRemoved.contains(neighborCoords[1][0]) || (!overridePointsAdded.contains(neighborCoords[1][0]) && !points.contains(neighborCoords[1][0]))) && (overridePointsRemoved.contains(neighborCoords[0][0]) || (!overridePointsAdded.contains(neighborCoords[0][0]) && !points.contains(neighborCoords[0][0]))) && (overridePointsRemoved.contains(neighborCoords[0][1]) || (!overridePointsAdded.contains(neighborCoords[0][1]) && !points.contains(neighborCoords[0][1]))) && (overridePointsRemoved.contains(neighborCoords[0][2]) || (!overridePointsAdded.contains(neighborCoords[0][2]) && !points.contains(neighborCoords[0][2]))) && (overridePointsRemoved.contains(neighborCoords[1][2]) || (!overridePointsAdded.contains(neighborCoords[1][2]) && !points.contains(neighborCoords[1][2]))) ) { /* further check that line thickness is 1 outside of the 8 neighbors # # # . . @ # . C . # . . . */ if ((row + 2) > (imageHeight - 1)) { if ((col + 2) > (imageWidth - 1)) { return true; } int count = 0; PairInt p2 = new PairInt(col + 2, row + 1); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } p2 = new PairInt(col + 2, row); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } if (count > 1) { return false; } return true; } else if ((col + 2) > (imageWidth - 1)) { int count = 0; PairInt p2 = new PairInt(col, row + 2); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } p2 = new PairInt(col + 1, row + 2); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } if (count > 1) { return false; } return true; } // only 1 of the '#' can be non-zero int count = 0; PairInt p2 = new PairInt(col, row + 2); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } p2 = new PairInt(col + 1, row + 2); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } p2 = new PairInt(col + 2, row + 2); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } p2 = new PairInt(col + 2, row + 1); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } p2 = new PairInt(col + 2, row); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } if (count > 1) { return false; } return true; } if ( (!overridePointsRemoved.contains(neighborCoords[2][1]) && (overridePointsAdded.contains(neighborCoords[2][1]) || points.contains(neighborCoords[2][1]))) && (overridePointsRemoved.contains(neighborCoords[2][2]) || (!overridePointsAdded.contains(neighborCoords[2][2]) && !points.contains(neighborCoords[2][2]))) && (overridePointsRemoved.contains(neighborCoords[1][2]) || (!overridePointsAdded.contains(neighborCoords[1][2]) && !points.contains(neighborCoords[1][2]))) && (overridePointsRemoved.contains(neighborCoords[0][2]) || (!overridePointsAdded.contains(neighborCoords[0][2]) && !points.contains(neighborCoords[0][2]))) && (overridePointsRemoved.contains(neighborCoords[0][1]) || (!overridePointsAdded.contains(neighborCoords[0][1]) && !points.contains(neighborCoords[0][1]))) && (overridePointsRemoved.contains(neighborCoords[0][0]) || (!overridePointsAdded.contains(neighborCoords[0][0]) && !points.contains(neighborCoords[0][0]))) && (overridePointsRemoved.contains(neighborCoords[1][0]) || (!overridePointsAdded.contains(neighborCoords[1][0]) && !points.contains(neighborCoords[1][0]))) && (overridePointsRemoved.contains(neighborCoords[2][0]) || (!overridePointsAdded.contains(neighborCoords[2][0]) && !points.contains(neighborCoords[2][0]))) ) { if ((col + 2) > (imageWidth - 1)) { return true; } // only 1 of the '#' can be non-zero int count = 0; PairInt p2 = new PairInt(col + 2, row + 1); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } p2 = new PairInt(col + 2, row); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } p2 = new PairInt(col + 2, row - 1); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } if (count > 1) { return false; } return true; } if ( (!overridePointsRemoved.contains(neighborCoords[2][0]) && (overridePointsAdded.contains(neighborCoords[2][0]) || points.contains(neighborCoords[2][0]))) && (overridePointsRemoved.contains(neighborCoords[2][1]) || (!overridePointsAdded.contains(neighborCoords[2][1]) && !points.contains(neighborCoords[2][1]))) && (overridePointsRemoved.contains(neighborCoords[2][2]) || (!overridePointsAdded.contains(neighborCoords[2][2]) && !points.contains(neighborCoords[2][2]))) && (overridePointsRemoved.contains(neighborCoords[1][2]) || (!overridePointsAdded.contains(neighborCoords[1][2]) && !points.contains(neighborCoords[1][2]))) && (overridePointsRemoved.contains(neighborCoords[0][2]) || (!overridePointsAdded.contains(neighborCoords[0][2]) && !points.contains(neighborCoords[0][2]))) && (overridePointsRemoved.contains(neighborCoords[0][1]) || (!overridePointsAdded.contains(neighborCoords[0][1]) && !points.contains(neighborCoords[0][1]))) && (overridePointsRemoved.contains(neighborCoords[0][0]) || (!overridePointsAdded.contains(neighborCoords[0][0]) && !points.contains(neighborCoords[0][0]))) && (overridePointsRemoved.contains(neighborCoords[1][0]) || (!overridePointsAdded.contains(neighborCoords[1][0]) && !points.contains(neighborCoords[1][0]))) ) { if ((row - 2) < 0) { if ((col + 2) > (imageWidth - 1)) { return true; } int count = 0; PairInt p2 = new PairInt(col + 2, row); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } p2 = new PairInt(col + 2, row - 1); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } if (count > 1) { return false; } return true; } else if ((col + 2) > (imageWidth - 1)) { int count = 0; PairInt p2 = new PairInt(col, row - 2); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } p2 = new PairInt(col + 1, row - 2); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } if (count > 1) { return false; } return true; } int count = 0; PairInt p2 = new PairInt(col + 2, row); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } p2 = new PairInt(col + 2, row - 1); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } p2 = new PairInt(col + 2, row - 2); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } p2 = new PairInt(col + 1, row - 2); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } p2 = new PairInt(col, row - 2); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } if (count > 1) { return false; } return true; } if ( (!overridePointsRemoved.contains(neighborCoords[1][0]) && (overridePointsAdded.contains(neighborCoords[1][0]) || points.contains(neighborCoords[1][0]))) && (overridePointsRemoved.contains(neighborCoords[2][0]) || (!overridePointsAdded.contains(neighborCoords[2][0]) && !points.contains(neighborCoords[2][0]))) && (overridePointsRemoved.contains(neighborCoords[2][1]) || (!overridePointsAdded.contains(neighborCoords[2][1]) && !points.contains(neighborCoords[2][1]))) && (overridePointsRemoved.contains(neighborCoords[2][2]) || (!overridePointsAdded.contains(neighborCoords[2][2]) && !points.contains(neighborCoords[2][2]))) && (overridePointsRemoved.contains(neighborCoords[1][2]) || (!overridePointsAdded.contains(neighborCoords[1][2]) && !points.contains(neighborCoords[1][2]))) && (overridePointsRemoved.contains(neighborCoords[0][2]) || (!overridePointsAdded.contains(neighborCoords[0][2]) && !points.contains(neighborCoords[0][2]))) && (overridePointsRemoved.contains(neighborCoords[0][1]) || (!overridePointsAdded.contains(neighborCoords[0][1]) && !points.contains(neighborCoords[0][1]))) && (overridePointsRemoved.contains(neighborCoords[0][0]) || (!overridePointsAdded.contains(neighborCoords[0][0]) && !points.contains(neighborCoords[0][0]))) ) { if ((row - 2) < 0) { return true; } // only 1 of the '#' can be non-zero int count = 0; PairInt p2 = new PairInt(col - 1, row - 2); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } p2 = new PairInt(col, row - 2); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } p2 = new PairInt(col + 1, row - 2); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } if (count > 1) { return false; } return true; } if ( (!overridePointsRemoved.contains(neighborCoords[0][0]) && (overridePointsAdded.contains(neighborCoords[0][0]) || points.contains(neighborCoords[0][0]))) && (overridePointsRemoved.contains(neighborCoords[1][0]) || (!overridePointsAdded.contains(neighborCoords[1][0]) && !points.contains(neighborCoords[1][0]))) && (overridePointsRemoved.contains(neighborCoords[2][0]) || (!overridePointsAdded.contains(neighborCoords[2][0]) && !points.contains(neighborCoords[2][0]))) && (overridePointsRemoved.contains(neighborCoords[2][1]) || (!overridePointsAdded.contains(neighborCoords[2][1]) && !points.contains(neighborCoords[2][1]))) && (overridePointsRemoved.contains(neighborCoords[2][2]) || (!overridePointsAdded.contains(neighborCoords[2][2]) && !points.contains(neighborCoords[2][2]))) && (overridePointsRemoved.contains(neighborCoords[1][2]) || (!overridePointsAdded.contains(neighborCoords[1][2]) && !points.contains(neighborCoords[1][2]))) && (overridePointsRemoved.contains(neighborCoords[0][2]) || (!overridePointsAdded.contains(neighborCoords[0][2]) && !points.contains(neighborCoords[0][2]))) && (overridePointsRemoved.contains(neighborCoords[0][1]) || (!overridePointsAdded.contains(neighborCoords[0][1]) && !points.contains(neighborCoords[0][1]))) ) { if ((col - 2) < 0) { if ((row - 2) < 0) { return true; } // only 1 of the '#' can be non-zero int count = 0; PairInt p2 = new PairInt(col - 1, row - 2); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } p2 = new PairInt(col, row - 2); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } if (count > 1) { return false; } return true; } else if ((row - 2) < 0) { int count = 0; PairInt p2 = new PairInt(col - 2, row); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } p2 = new PairInt(col - 2, row - 1); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } if (count > 1) { return false; } return true; } int count = 0; PairInt p2 = new PairInt(col - 2, row); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } p2 = new PairInt(col - 2, row - 1); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } p2 = new PairInt(col - 2, row - 2); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } p2 = new PairInt(col - 1, row - 2); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } p2 = new PairInt(col, row - 2); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } if (count > 1) { return false; } return true; } if ( (!overridePointsRemoved.contains(neighborCoords[0][1]) && (overridePointsAdded.contains(neighborCoords[0][1]) || points.contains(neighborCoords[0][1]))) && (overridePointsRemoved.contains(neighborCoords[0][2]) || (!overridePointsAdded.contains(neighborCoords[0][2]) && !points.contains(neighborCoords[0][2]))) && (overridePointsRemoved.contains(neighborCoords[1][2]) || (!overridePointsAdded.contains(neighborCoords[1][2]) && !points.contains(neighborCoords[1][2]))) && (overridePointsRemoved.contains(neighborCoords[2][2]) || (!overridePointsAdded.contains(neighborCoords[2][2]) && !points.contains(neighborCoords[2][2]))) && (overridePointsRemoved.contains(neighborCoords[2][1]) || (!overridePointsAdded.contains(neighborCoords[2][1]) && !points.contains(neighborCoords[2][1]))) && (overridePointsRemoved.contains(neighborCoords[2][0]) || (!overridePointsAdded.contains(neighborCoords[2][0]) && !points.contains(neighborCoords[2][0]))) && (overridePointsRemoved.contains(neighborCoords[1][0]) || (!overridePointsAdded.contains(neighborCoords[1][0]) && !points.contains(neighborCoords[1][0]))) && (overridePointsRemoved.contains(neighborCoords[0][0]) || (!overridePointsAdded.contains(neighborCoords[0][0]) && !points.contains(neighborCoords[0][0]))) ) { if ((col - 2) < 0) { return true; } // only 1 of the '#' can be non-zero int count = 0; PairInt p2 = new PairInt(col - 2, row - 1); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } p2 = new PairInt(col - 2, row); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } p2 = new PairInt(col - 2, row + 1); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } if (count > 1) { return false; } return true; } if ( (!overridePointsRemoved.contains(neighborCoords[0][2]) && (overridePointsAdded.contains(neighborCoords[0][2]) || points.contains(neighborCoords[0][2]))) && (overridePointsRemoved.contains(neighborCoords[1][2]) || (!overridePointsAdded.contains(neighborCoords[1][2]) && !points.contains(neighborCoords[1][2]))) && (overridePointsRemoved.contains(neighborCoords[2][2]) || (!overridePointsAdded.contains(neighborCoords[2][2]) && !points.contains(neighborCoords[2][2]))) && (overridePointsRemoved.contains(neighborCoords[2][1]) || (!overridePointsAdded.contains(neighborCoords[2][1]) && !points.contains(neighborCoords[2][1]))) && (overridePointsRemoved.contains(neighborCoords[2][0]) || (!overridePointsAdded.contains(neighborCoords[2][0]) && !points.contains(neighborCoords[2][0]))) && (overridePointsRemoved.contains(neighborCoords[1][0]) || (!overridePointsAdded.contains(neighborCoords[1][0]) && !points.contains(neighborCoords[1][0]))) && (overridePointsRemoved.contains(neighborCoords[0][0]) || (!overridePointsAdded.contains(neighborCoords[0][0]) && !points.contains(neighborCoords[0][0]))) && (overridePointsRemoved.contains(neighborCoords[0][1]) || (!overridePointsAdded.contains(neighborCoords[0][1]) && !points.contains(neighborCoords[0][1]))) ) { if ((col - 2) < 0) { if ((row + 2) > (imageHeight - 1)) { return true; } // only 1 of the '#' can be non-zero int count = 0; PairInt p2 = new PairInt(col - 1, row + 2); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } p2 = new PairInt(col, row + 2); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } if (count > 1) { return false; } return true; } else if ((row + 2) > (imageHeight - 1)) { int count = 0; PairInt p2 = new PairInt(col - 2, row); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } p2 = new PairInt(col - 2, row + 1); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } if (count > 1) { return false; } return true; } int count = 0; PairInt p2 = new PairInt(col - 2, row); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } p2 = new PairInt(col - 2, row + 1); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } p2 = new PairInt(col - 2, row + 2); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } p2 = new PairInt(col - 1, row + 2); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } p2 = new PairInt(col, row + 2); if ( (!overridePointsRemoved.contains(p2) && (overridePointsAdded.contains(p2) || points.contains(p2))) ) { count++; } if (count > 1) { return false; } return true; } return false; } private void printImage(final GreyscaleImage input) { for (int row = (input.getHeight() - 1); row > -1; row StringBuilder sb = new StringBuilder(String.format("row %2d: ", row)); for (int col = 0; col < input.getWidth(); col++) { int v = input.getValue(col, row); String str = (v == 0) ? String.format(" ") : String.format("%d ", v); sb.append(str); } System.out.println(sb.toString()); } StringBuilder sb = new StringBuilder(String.format(" ")); for (int col = 0; col < input.getWidth(); col++) { sb.append(String.format("%2d", col)); } System.out.println(sb.toString()); System.out.println("\n"); } }
package org.ensembl.healthcheck.test; import org.ensembl.healthcheck.Species; import junit.framework.TestCase; /** * Junit test case for Species */ public class SpeciesTest extends TestCase { public SpeciesTest(String arg) { super(arg); } public void testToString() { Species s = Species.HOMO_SAPIENS; assertEquals("toString method not returning expected result", s.toString(), "homo_sapiens"); } public void testEquals() { assertEquals("equals method not working", Species.HOMO_SAPIENS, Species.HOMO_SAPIENS); assertTrue("compare with == not working", Species.DANIO_RERIO == Species.DANIO_RERIO); assertTrue("species that are the not the same are coming out equal", Species.FUGU_RUBRIPES != Species.CAENORHABDITIS_BRIGGSAE); } public void testAlias() { // not an exhaustive list ... assertEquals(Species.resolveAlias("human"), Species.HOMO_SAPIENS); assertEquals(Species.resolveAlias("rat"), Species.RATTUS_NORVEGICUS); assertEquals(Species.resolveAlias("mus_musculus"), Species.MUS_MUSCULUS); assertEquals(Species.resolveAlias("tetraodon_nigroviridis"), Species.TETRAODON_NIGROVIRIDIS); assertEquals(Species.resolveAlias("apis_mellifera"), Species.APIS_MELLIFERA); assertEquals(Species.resolveAlias("ciona_intestinalis"), Species.CIONA_INTESTINALIS); assertEquals(Species.resolveAlias("littlegreenman"), Species.UNKNOWN); } public void testTaxonomyIDs() { assertEquals(Species.getTaxonomyID(Species.HOMO_SAPIENS), "9606"); assertEquals(Species.getTaxonomyID(Species.DANIO_RERIO), "7955"); assertEquals(Species.getTaxonomyID(Species.TETRAODON_NIGROVIRIDIS), "99883"); assertEquals(Species.getTaxonomyID(Species.CIONA_INTESTINALIS), "7719"); assertEquals(Species.getTaxonomyID(Species.APIS_MELLIFERA), "7460"); assertEquals(Species.getSpeciesFromTaxonomyID("10090"), Species.MUS_MUSCULUS); assertEquals(Species.getSpeciesFromTaxonomyID("10116"), Species.RATTUS_NORVEGICUS); assertEquals(Species.getTaxonomyID(Species.UNKNOWN), ""); assertEquals(Species.getSpeciesFromTaxonomyID("-1"), Species.UNKNOWN); } public void testAssemblyPrefixes() { assertEquals(Species.getSpeciesForAssemblyPrefix("NCBI"), Species.HOMO_SAPIENS); } }
// This file is part of the "OPeNDAP Web Coverage Service Project." // Authors: // Haibo Liu <haibo@iri.columbia.edu> // Nathan David Potter <ndp@opendap.org> // M. Benno Blumenthal <benno@iri.columbia.edu> // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112. package opendap.semantics.IRISail; import org.openrdf.model.*; import org.openrdf.model.impl.StatementImpl; import org.openrdf.model.impl.URIImpl; import org.openrdf.query.*; import org.openrdf.repository.Repository; import org.openrdf.repository.RepositoryConnection; import org.openrdf.repository.RepositoryException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * This class is used to run external inference rules on an Sesame-OWLIM repository. * The inference rules are written in SeRQL. * The inferred statements are added into the repository. The inference rules are run * repeatedly until no rules generate any new statements. * <p/> * The <code>constructQuery</code> is a String Vector holds the inference rules. * The <code>constructContext</code> is a Hash Map holds pairs of inference rules and its ID. */ public class ConstructRuleEvaluator { private Logger log; public static enum ProcessingTypes { NONE, xsString, DropQuotes, RetypeTo, Increment, Function } private Vector<String> constructQuery; private HashMap<String, String> constructContext; private ProcessingTypes postProcessFlag; public ConstructRuleEvaluator() { log = LoggerFactory.getLogger(getClass()); constructQuery = new Vector<String>(); constructContext = new HashMap<String, String>(); } /** * Run all Construct queries and ingest resulting statements into repository * @param repository-repository to use * @throws RepositoryException */ public void runConstruct(Repository repository) throws RepositoryException { log.debug(" log.debug(" log.debug(" GraphQueryResult graphResult = null; RepositoryConnection con = null; Vector<Statement> Added = new Vector<Statement>(); Boolean modelChanged = true; int runNbr = 0; int runNbrMax = 99; long startTime, endTime; startTime = new Date().getTime(); int queryTimes = 0; long ruleStartTime, ruleEndTime; int totalStAdded = 0; // number of statements added int totalStAddedIn1Pass = 0; // number of statements added in 1 PASS findConstruct(repository); //log.debug("Before running the construct rules:\n " + //opendap.coreServlet.Util.getMemoryReport()); con = repository.getConnection(); ValueFactory creatValue = repository.getValueFactory(); //moved from line 159 while (modelChanged && runNbr < runNbrMax) { runNbr++; modelChanged = false; totalStAddedIn1Pass = 0; if(runNbr == 1){ log.info("Total construct rule number = " + this.constructQuery.size()); } //log.debug("Applying Construct Rules. Beginning Pass #" + runNbr // + " \n" + opendap.coreServlet.Util.getMemoryReport()); int ruleNumber = 0; for (String qstring : this.constructQuery) { ruleNumber++; queryTimes++; ruleStartTime = new Date().getTime(); int stAdded = 0; // track statements added by each rule Vector<Statement> toAdd = new Vector<Statement>(); String constructURL = this.constructContext.get(qstring); //URI uriaddress = new URIImpl(constructURL); URI uriaddress = new URIImpl(Terms.externalInferencingContext.getUri()); Resource[] context = new Resource[1]; context[0] = uriaddress; String processedQueryString = convertSWRLQueryToSeasameQuery(qstring); if(runNbr == 1){ log.debug("Original construct: " + qstring); log.debug("Processed construct: " + processedQueryString); } try { //log.debug("Prior to making new repository connection:\n " //+ opendap.coreServlet.Util.getMemoryReport()); log.debug("Original construct rule ID: " + constructURL); GraphQuery graphQuery = con.prepareGraphQuery( QueryLanguage.SERQL, processedQueryString); graphResult = graphQuery.evaluate(); GraphQueryResult graphResultCopy = graphResult; log.debug("Completed querying. "); if (graphResult.hasNext()) { modelChanged = true; // ValueFactory creatValue = repository.getValueFactory(); switch (postProcessFlag) { case xsString: process_xsString(graphResult, creatValue, Added, toAdd, con, context); //log.debug("After processing xs:string:\n " // + opendap.coreServlet.Util // .getMemoryReport()); break; case DropQuotes: process_DropQuotes(graphResult, creatValue, Added, toAdd, con, context); //log.debug("After processing DropQuotes:\n " // + opendap.coreServlet.Util // .getMemoryReport()); break; case RetypeTo: process_RetypeTo(graphResult, creatValue, Added, toAdd, con, context); //log.debug("After processing RetypeTo:\n " // + opendap.coreServlet.Util // .getMemoryReport()); break; case Increment: process_Increment(graphResult, creatValue, Added, toAdd, con, context); //log.debug("After processing Increment:\n " // + opendap.coreServlet.Util // .getMemoryReport()); break; case Function: process_fn(graphResult, creatValue, Added, toAdd, con, context);// postpocessing Join, break; case NONE: default: log.debug("Adding not postprocessed statements ..."); con.add(graphResult, context); /***** * iterator cannot be reset, count fails int nonePostprocessSt = 0; while (graphResultCopy.hasNext()) { graphResultCopy.next(); nonePostprocessSt++; stAdded++; } log.debug("Complete adding "+nonePostprocessSt + " not postprocessed statements"); */ break; } if (toAdd != null) { stAdded += toAdd.size(); } } // if (graphResult.hasNext else { log.debug("The construct rule returns no statements!"); } } catch (QueryEvaluationException e) { log.error("Caught an QueryEvaluationException! Msg: " + e.getMessage()); } catch (RepositoryException e) { log.error("Caught RepositoryException! Msg: " + e.getMessage()); } catch (MalformedQueryException e) { log.error("Caught MalformedQueryException! Msg: " + e.getMessage()); log.error("MalformedQuery: " + processedQueryString); } finally { if (graphResult != null) { try { graphResult.close(); } catch (QueryEvaluationException e) { log.error("Caught a QueryEvaluationException! Msg: " + e.getMessage()); } } } ruleEndTime = new Date().getTime(); double ruleTime = (ruleEndTime - ruleStartTime) / 1000.0; log.debug("Construct rule " + ruleNumber + " takes " + ruleTime + " seconds in loop " + runNbr + " added " + stAdded + " statements"); totalStAdded = totalStAdded + stAdded; totalStAddedIn1Pass = totalStAddedIn1Pass+ stAdded; con.commit(); } // for(String qstring log.info("Completed pass " + runNbr + " of Construct evaluation, "+"queried the repository " + ruleNumber + " times" + " added " + totalStAddedIn1Pass + " statements"); log.info("Queried the repository " + queryTimes + " times"); findConstruct(repository); } // while (modelChanged //the construct rules run too many times if (runNbr >= runNbrMax){ log.warn("The construct rules have executed to the maxmum times allowed!"); } try { con.close(); } catch (RepositoryException e) { log.error("Caught a RepositoryException! Msg: " + e.getMessage()); } endTime = new Date().getTime(); double totaltime = (endTime - startTime) / 1000.0; log.info("In construct for " + totaltime + " seconds"); log.info("Total number of post processed statements added in construct: " + totalStAdded + " \n"); } /** * Find all Construct queries stored in the repository * @param repository-repository to use */ private void findConstruct(Repository repository) { TupleQueryResult result = null; RepositoryConnection con = null; List<String> bindingNames; log.debug("Locating Construct rules..."); try { con = repository.getConnection(); String queryString = "SELECT queries, contexts " + "FROM " + "{contexts} rdfcache:"+Terms.hasSerqlConstructQuery.getLocalId() +" {queries} " + "using namespace " + "rdfcache = <"+ Terms.rdfCacheNamespace+">"; log.debug("queryString: " + queryString); TupleQuery tupleQuery = con.prepareTupleQuery(QueryLanguage.SERQL, queryString); result = tupleQuery.evaluate(); if (result != null) { bindingNames = result.getBindingNames(); while (result.hasNext()) { BindingSet bindingSet = (BindingSet) result.next(); Value firstValue = bindingSet.getValue("queries"); if (!constructQuery.contains(firstValue.stringValue())) { constructQuery.add(firstValue.stringValue()); } //log.debug("Adding construct to import pool: " // + firstValue.toString()); Value secondValue = bindingSet.getValue("contexts"); constructContext.put(firstValue.stringValue(), secondValue .stringValue()); } } else { log.debug("No Construct rules found in the repository!"); } } catch (QueryEvaluationException e) { log.error("Caught an QueryEvaluationException! Msg: " + e.getMessage()); } catch (RepositoryException e) { log.error("Caught RepositoryException! Msg: " + e.getMessage()); } catch (MalformedQueryException e) { log.error("Caught MalformedQueryException! Msg: " + e.getMessage()); } finally { if (result != null) { try { result.close(); } catch (QueryEvaluationException e) { log.error("Caught a QueryEvaluationException! Msg: " + e.getMessage()); } } if(con!=null){ try { con.close(); } catch (RepositoryException e) { log.error("Caught a RepositoryException! Msg: " + e.getMessage()); } } } log.debug("Number of constructs identified: " + constructQuery.size()); } private String convertSWRLQueryToSeasameQuery(String queryString) { postProcessFlag = ProcessingTypes.NONE; Pattern stringPattern = Pattern.compile("xs:string\\(([^)]+)\\)"); Pattern dropquotesPattern = Pattern .compile("iridl:dropquotes\\(([^)]+)\\)"); Pattern minusPattern = Pattern.compile("MINUS.*( using)?"); Pattern rdfCachePattern = Pattern.compile("rdfcache:"+Terms.reTypeToContext.getLocalId()); Pattern xsd2owlPattern = Pattern .compile("xsd2owl:increment\\(([^)]+)\\)"); String pproces4sub2 = "\\{\\s*\\{(\\w+)\\s*\\}\\s*(.+)\\{(\\w+)\\s*\\}\\s*\\}"; Pattern rproces4psub2 = Pattern.compile(pproces4sub2); String processedQueryString = queryString; Matcher mreifStr = rproces4psub2.matcher(processedQueryString); Boolean hasReified = false; if (mreifStr.find()) { //reified statements String reifstr = " {} rdf:type {rdf:Statement} ; " + " rdf:subject {" + mreifStr.group(1) + "} ;" + " rdf:predicate {" + mreifStr.group(2) + "} ;" + " rdf:object {" + mreifStr.group(3) + "} ;"; processedQueryString = mreifStr.replaceFirst(reifstr); hasReified = true; } Matcher stringMatcher = stringPattern.matcher(processedQueryString); // xs:string Matcher dropquotesMatcher = dropquotesPattern .matcher(processedQueryString); // iridl:dropquotes Matcher rdfcacheMatcher = rdfCachePattern.matcher(processedQueryString); // rdfcache:retypeTo Matcher xsd2owlMatcher = xsd2owlPattern.matcher(processedQueryString); // xsdToOwl:increment Pattern comma = Pattern.compile(","); Pattern p_fn_className = Pattern.compile("(([a-z]+):([A-Za-z]+)\\(([^)]+)\\)).+using namespace.+\\2 *= *<import:([^ Pattern.CASE_INSENSITIVE | Pattern.DOTALL | Pattern.MULTILINE); Matcher functionMatcher = p_fn_className.matcher(processedQueryString); if (stringMatcher.find()) { postProcessFlag = ProcessingTypes.xsString; String vname = stringMatcher.group(1); processedQueryString = stringMatcher.replaceAll(vname); log.debug("Will postprocess xs:string(" + vname + ")"); } else if (dropquotesMatcher.find()) { postProcessFlag = ProcessingTypes.DropQuotes; String vname = dropquotesMatcher.group(1); processedQueryString = dropquotesMatcher.replaceAll(vname); Matcher m23 = minusPattern.matcher(processedQueryString); String vname2 = m23.group(1); processedQueryString = m23.replaceFirst(vname2); log.debug("Will postprocess iridl:dropquotes(" + vname + ")"); } else if (rdfcacheMatcher.find()) { postProcessFlag = ProcessingTypes.RetypeTo; log.debug("Will postprocess rdfcache:"+Terms.reTypeToContext.getLocalId()); } else if (xsd2owlMatcher.find()) { postProcessFlag = ProcessingTypes.Increment; String vname = xsd2owlMatcher.group(1); processedQueryString = xsd2owlMatcher.replaceAll(vname); } else if (functionMatcher.find()) { functionMatcher.reset(); //reset the matcher String fullyQualifiedFunctionName; while (functionMatcher.find()) { String expand = ""; String rdfFunctionName = functionMatcher.group(3); String rdfClassName = functionMatcher.group(5); fullyQualifiedFunctionName = rdfClassName + "#" + rdfFunctionName; log.debug("fullyQualifiedFunctionName = " + fullyQualifiedFunctionName); // full name of the function log.debug("class_name = " + rdfClassName); // class name of the function Method myFunction = getMethodForFunction(rdfClassName, rdfFunctionName); if (myFunction != null) { postProcessFlag = ProcessingTypes.Function; } //String[] splittedStr = comma.split(functionMatcher.group(4)); CSVSplitter splitter = new CSVSplitter(); String[] splittedStr = splitter.split(functionMatcher.group(4)); int i = 0; String fn = functionMatcher.group(2); String functionName = functionMatcher.group(3); expand += "} <"+ Terms.callFunction.getUri() +"> {" + fn + ":" + functionName + "} ; <"+ Terms.withArguments.getUri() +"> {} rdf:first {"; for (String element : splittedStr) { i++; if (i < splittedStr.length) { if(!element.equals(",")){ expand += element + "} ; rdf:rest {} rdf:first {"; }else{ expand += element; } log.debug("element " + i + " = " + element); } else { expand += element + "} ; rdf:rest {rdf:nil"; log.debug("element " + i + " = " + element); } log.debug("Will postprocess fn:" + functionMatcher.group(3)); } processedQueryString = processedQueryString.substring(0, functionMatcher.start(1)) + expand + processedQueryString.substring(functionMatcher.end(1)); functionMatcher.reset(processedQueryString); } } return processedQueryString; } /*************************************************************************** * Drop quotes in statements generated from running a construct rule. * * @param graphResult * @param creatValue * @param Added * @param toAdd * @param con * @param context * @throws QueryEvaluationException * @throws RepositoryException */ private static void process_DropQuotes(GraphQueryResult graphResult, ValueFactory creatValue, Vector<Statement> Added, Vector<Statement> toAdd, RepositoryConnection con, Resource[] context) throws QueryEvaluationException, RepositoryException { // pproces2 =\"\\\"([^\\]+)\\\"\"(\^\^[^>]+>)? \. String pproces2 = "\\\"\\\\\\\"([^\\\\]+)\\\\\\\"\\\"(\\^\\^[^>]+>)? \\."; Pattern rproces2 = Pattern.compile(pproces2); while (graphResult.hasNext()) { Statement st = graphResult.next(); Value obj = st.getObject(); URI prd = st.getPredicate(); Resource sbj = st.getSubject(); String statementStr = obj.toString(); String newStatementStr = ""; Matcher m = rproces2.matcher(statementStr); String vname = m.group(1); statementStr = m.replaceAll('"' + vname + '"' + "^^<http://www.w3.org/2001/XMLSchema#string> ."); String patternBn = "^_:"; Pattern bn = Pattern.compile(patternBn); String sbjStr = sbj.toString(); Matcher msbjStr = bn.matcher(sbjStr); if (msbjStr.find()) { // log.debug("Skipping blank node "+sbjStr); } else { newStatementStr = statementStr; } statementStr = newStatementStr; Value stStr = creatValue.createLiteral(statementStr); Statement stToAdd = new StatementImpl(sbj, prd, stStr); toAdd.add(stToAdd); Added.add(stToAdd); con.add(stToAdd, context); // add process_DropQuotes created st } // log.debug("After processing dropQuotes:\n " + // opendap.coreServlet.Util.getMemoryReport()); } /*************************************************************************** * Process "xs:string" in statements generated from running a construct rule. * * @param graphResult * @param creatValue * @param Added * @param toAdd * @param con * @param context * @throws org.openrdf.query.QueryEvaluationException * @throws org.openrdf.repository.RepositoryException */ public static void process_xsString(GraphQueryResult graphResult, ValueFactory creatValue, Vector<Statement> Added, Vector<Statement> toAdd, RepositoryConnection con, Resource[] context) throws QueryEvaluationException, RepositoryException { // pproces1 = (\"[^"]+\")\s+\. String pproces1 = "(\\\"[^\"]+\\\")\\s+\\."; // Create a Pattern object Pattern rproces1 = Pattern.compile(pproces1); // Now create matcher object. while (graphResult.hasNext()) { Statement st = graphResult.next(); Value obj = st.getObject(); URI prd = st.getPredicate(); Resource sbj = st.getSubject(); String statementStr = obj.stringValue(); Matcher m = rproces1.matcher(statementStr); URI dataType = creatValue.createURI("http://www.w3.org/2001/XMLSchema#string"); Value stStr = creatValue.createLiteral(statementStr, dataType); Statement stToAdd = new StatementImpl(sbj, prd, stStr); toAdd.add(stToAdd); Added.add(stToAdd); con.add(stToAdd, context); // add process_xsString created st } // log.debug("After processing xs:string:\n " + // opendap.coreServlet.Util.getMemoryReport()); } /*************************************************************************** * Cast data type in statements generated from running a construct rule * * @param graphResult * @param creatValue * @param Added * @param toAdd * @param con * @param context * @throws QueryEvaluationException * @throws RepositoryException */ private void process_RetypeTo(GraphQueryResult graphResult, ValueFactory creatValue, Vector<Statement> Added, Vector<Statement> toAdd, RepositoryConnection con, Resource[] context) throws QueryEvaluationException, RepositoryException { // pproces3 =\"\\\"([^\\]+)\\\"\"\^\^ String pproces3 = "\\\"\\\\\\\"([^\\\\]+)\\\\\\\"\\\"\\^\\^"; Pattern rproces3 = Pattern.compile(pproces3); String pproces3sub = "(.+)"; Pattern rproces3sub = Pattern.compile(pproces3sub); String pproces3subsub1 = "<"+ Terms.reTypeToContext.getUri() +"> <([^>]+)>"; String pproces3subsub2 = "([^ ]+) <http://www.w3.org/1999/02/22-rdf-syntax-ns#value> (\"(.+)\")\\^\\^"; Pattern rproces3subsub1 = Pattern.compile(pproces3subsub1); Pattern rproces3subsub2 = Pattern.compile(pproces3subsub2); while (graphResult.hasNext()) { Statement st = graphResult.next(); Value obj = st.getObject(); URI prd = st.getPredicate(); Resource sbj = st.getSubject(); String statementStr = obj.toString(); Matcher mproces3 = rproces3.matcher(statementStr); String replace = mproces3.group(1) + '"' + "^^"; statementStr = mproces3.replaceAll(replace); Matcher mproces3sub = rproces3sub.matcher(statementStr); String newStStr = statementStr; String lastline = ""; String line = ""; String node = ""; String value = ""; String newtype = ""; String statement = ""; while (mproces3sub.find()) { String lastline2 = lastline; lastline = line; line = mproces3sub.group(1); Matcher msub1 = rproces3subsub1.matcher(line); if (msub1.find()) { newtype = msub1.group(1); Matcher msub2 = rproces3subsub2.matcher(lastline); if (msub2.find()) { node = msub2.group(1); value = msub2.group(3); } String psub3 = "(.+) " + node + " ."; Pattern cpsub3 = Pattern.compile(psub3); Matcher msub3 = cpsub3.matcher(lastline2); if (msub3.find()) { statement = msub3.group(1); } newStStr = statement + " " + '"' + value + '"' + "^^<" + newtype + "> .\n"; } } Value stStr = creatValue.createLiteral(newStStr); Statement stToAdd = new StatementImpl(sbj, prd, stStr); log.debug("original st=" + st.toString()); log.debug("new stToAdd=" + stToAdd.toString()); log.debug("In postprocess3"); toAdd.add(stToAdd); Added.add(stToAdd); con.add(stToAdd, context);// add process_RetypeTo created st } // log.debug("After processing RetypeTo:\n " + // opendap.coreServlet.Util.getMemoryReport()); } /*************************************************************************** * Increment number by 1 in statements generated from running a construct rule * * @param graphResult * @param creatValue * @param Added * @param toAdd * @param con * @param context * @throws QueryEvaluationException * @throws RepositoryException */ private void process_Increment(GraphQueryResult graphResult, ValueFactory creatValue, Vector<Statement> Added, Vector<Statement> toAdd, RepositoryConnection con, Resource[] context) throws QueryEvaluationException, RepositoryException { String pproces4 = "(.+)"; Pattern rproces4 = Pattern.compile(pproces4); String pproces4sub = "\"(\\d+)\""; Pattern rproces4psub = Pattern.compile(pproces4sub); String pproces4sub2 = "\\{\\s*\\{(\\w+)\\s*\\}\\s*(.+)\\{(\\w+)\\s*\\}\\s*\\}"; Pattern rproces4psub2 = Pattern.compile(pproces4sub2); while (graphResult.hasNext()) { Statement st = graphResult.next(); Value obj = st.getObject(); URI prd = st.getPredicate(); Resource sbj = st.getSubject(); String statementStr = obj.toString(); String numincrStr = ""; // after increment Matcher mproces4 = rproces4.matcher(statementStr); if (mproces4.find()) { statementStr = mproces4.group(1); Matcher mproces4sub = rproces4psub.matcher(statementStr); if (mproces4sub.find()) { // find number, do increment int numincr = Integer.parseInt(mproces4sub.group(1)); // log.debug("before increment numincr = " +numincr); numincr++; numincrStr = Integer.toString(numincr); // log.debug("after increment numincrStr = " +numincrStr); statementStr = numincrStr; Value stStr = creatValue.createLiteral(statementStr); Statement stToAdd = new StatementImpl(sbj, prd, stStr); st = stToAdd; } // log.debug("new st = "+st.toString()); toAdd.add(st); Added.add(st); con.add(st, context);// add st with incremented number // log.debug("Increment added new tatement stToAdd= " // + st.toString()); } else { toAdd.add(st); Added.add(st); con.add(st, context);// add st without increment (not a // number) // log.debug("Increment added original tatement st= " // + st.toString()); } } // while (graphResult.hasNext()) } /*************************************************************************** * process fn created statements * * @param graphResult * @param creatValue * @param Added * @param toAdd * @param con * @param context * @throws QueryEvaluationException * @throws RepositoryException */ private void process_fn(GraphQueryResult graphResult, ValueFactory creatValue, Vector<Statement> Added, Vector<Statement> toAdd, RepositoryConnection con, Resource[] context) throws QueryEvaluationException, RepositoryException { log.debug("Processing fn statements."); URI rdffirst = creatValue.createURI("http://www.w3.org/1999/02/22-rdf-syntax-ns#first"); URI rdfrest = creatValue.createURI("http://www.w3.org/1999/02/22-rdf-syntax-ns#rest"); URI endList = creatValue.createURI("http://www.w3.org/1999/02/22-rdf-syntax-ns#nil"); URI myfn = creatValue.createURI(Terms.callFunction.getUri()); URI myfnlist = creatValue.createURI(Terms.withArguments.getUri()); URI prdLastSt = null; Resource sbjLastSt = null; Statement oldSt = null; while (graphResult.hasNext()) { Statement st = graphResult.next(); URI prd = st.getPredicate(); Value obj = st.getObject(); // listnode is equal to endList until a list is found. While a list is being parsed/processed it is // set to the current list node. After the list is processed it is set back to endList Value listnode = endList; Resource sbj; URI targetPrd; Resource targetSbj; Statement newSt = null; Method func = null; if (prd.equals(myfn)) { targetSbj = sbjLastSt; targetPrd = prdLastSt; String className; // class name String fnName; // function name if (prd.equals(myfn)) { String functionImport = obj.stringValue(); int indexOfLastPoundSign = functionImport.lastIndexOf(" className = functionImport.substring("import:".length(), indexOfLastPoundSign); fnName = functionImport.substring(indexOfLastPoundSign + 1); func = getMethodForFunction(className, fnName); } Boolean isEndList = endList.equals(obj); List<String> rdfList = new ArrayList<String>(); //int statementNbr = 1; while (graphResult.hasNext() && !isEndList) { st = graphResult.next(); // statementNbr++; // log.debug("Current statement " + statementNbr + ": " + st); obj = st.getObject(); prd = st.getPredicate(); sbj = st.getSubject(); if (myfnlist.equals(prd)) { listnode = obj; } else if (listnode.equals(sbj) && rdffirst.equals(prd)) { String elementValue = obj.stringValue(); rdfList.add(elementValue); } else if (listnode.equals(sbj) && rdfrest.equals(prd)) { listnode = obj; isEndList = endList.equals(obj); } } if (func != null) { Value stObj = null; try { // We can pass null here: stObj = (Value) func.invoke(null, rdfList, creatValue); // because we know that the method that is being // invoked is static, so we don't need an // instance of class to invoke the method from. newSt = new StatementImpl(targetSbj, targetPrd, stObj); } catch (IllegalAccessException e) { log.error("Unable to invoke processing function " + func.getName() + "' Caught IllegalAccessException, msg: " + e.getMessage()); } catch (InvocationTargetException e) { log.error("Unable to invoke processing function " + func.getName() + "' Caught InvocationTargetException, msg: " + e.getMessage()); } } else { log.warn("Process Function failed: No processing function found."); } } //if (prd.equals(myfn)) prdLastSt = st.getPredicate(); sbjLastSt = st.getSubject(); if (newSt != null) { log.debug("new st to add = " + newSt.toString()); st = newSt; oldSt = null; } if (oldSt != null) { toAdd.add(oldSt); Added.add(oldSt); con.add(oldSt, context); // add fn created new st log.debug("process_fn add context: " + context[0].toString()); } oldSt = st; } // while (graphResult.hasNext()) if (oldSt != null) { toAdd.add(oldSt); Added.add(oldSt); con.add(oldSt, context); // add fn created new st log.debug("process_fn add context: " + context[0].toString()); } log.debug("After processing fn: " + toAdd.size() + " statements are added.\n "); } /** * Invoke a method from a class. * @param className * @param methodName * @return */ public Method getMethodForFunction(String className, String methodName) { Method method; try { Class<?> methodContext = Class.forName(className); log.debug("getMethodForFunction() - Located java class: " + className); try { method = methodContext.getMethod(methodName, List.class, ValueFactory.class); if (Modifier.isStatic(method.getModifiers())) { log.debug("getMethodForFunction() - Located static java method: " + getProcessingMethodDescription(method)); return method; } /* * for(Constructor c : methodContext.getConstructors()){ * if(c.getGenericParameterTypes().length==0){ * log.debug("getMethodForFunction() - Located java class * '"+className+"' with a no element " + "constructor and the * method "+getProcessingMethodDescription(method)); return * method; } } */ } catch (NoSuchMethodException e) { log.error("getMethodForFunction() - The class '" + className + "' does not contain a method called '" + methodName + "'"); } } catch (ClassNotFoundException e) { log.error("getMethodForFunction() - Unable to locate java class: " + className); } log.error("getMethodForFunction() - Unable to locate the requested java class/method combination. " + "class: '" + className + "' method: '" + methodName + "'"); return null; } public Method getMethodForFunction(Object classInstance, String methodName) { Method method; Class<?> methodContext = classInstance.getClass(); String className = methodContext.getName(); try { method = methodContext.getMethod(methodName, List.class, ValueFactory.class); log.debug("getMethodForFunction() - Located the java method: " + getProcessingMethodDescription(method) + " in an instance of the class '" + className + "'"); return method; } catch (NoSuchMethodException e) { log.error("getMethodForFunction() - The class '" + className + "' does not contain a method called '" + methodName + "'"); } log.error("getMethodForFunction() - Unable to locate the requested java class/method combination. " + "class: '" + className + "' method: '" + methodName + "'"); return null; } public String getProcessingMethodDescription(Method m) { String msg = ""; msg += m.getReturnType().getName() + " "; msg += m.getName(); String params = ""; for (Class c : m.getParameterTypes()) { if (!params.equals("")) params += ", "; params += c.getName(); } msg += "(" + params + ")"; String exceptions = ""; for (Class c : m.getExceptionTypes()) { if (!exceptions.equals("")) exceptions += ", "; exceptions += c.getName(); } msg += " " + exceptions + ";"; return msg; } }
package org.exist.xquery.test; import junit.framework.TestCase; import junit.textui.TestRunner; import org.exist.storage.DBBroker; import org.exist.xmldb.DatabaseInstanceManager; import org.xmldb.api.DatabaseManager; import org.xmldb.api.base.Collection; import org.xmldb.api.base.Database; import org.xmldb.api.base.ResourceSet; import org.xmldb.api.base.XMLDBException; import org.xmldb.api.modules.CollectionManagementService; import org.xmldb.api.modules.XQueryService; public class DocumentUpdateTest extends TestCase { private static final String TEST_COLLECTION_NAME = "testup"; private Database database; private Collection testCollection; /** * Test if the doc, collection and document functions are correctly * notified upon document updates. Call a function once on the empty collection, * then call it again after a document was added, and compare the results. */ public void testUpdate() { String imports = "import module namespace xdb='http://exist-db.org/xquery/xmldb';\n" + "import module namespace util='http://exist-db.org/xquery/util';\n"; try { System.out.println("-- TEST 1: doc() function --"); String query = imports + "declare function local:get-doc($path as xs:string) {\n" + " doc($path)\n" + "};\n" + "let $col := xdb:create-collection('/db', 'testup')\n" + "let $path := '/db/testup/test1.xml'\n" + "let $doc := xdb:store($col, 'test1.xml', <test><n>1</n></test>)\n" + "let $d1 := local:get-doc($path)\n" + "let $remove := xdb:remove('/db/testup', 'test1.xml')\n" + "return string-join((string(count(local:get-doc($path))), string(doc-available($path))), ' ')"; String result = execQuery(query); assertEquals(result, "0 false"); System.out.println("-- TEST 2: document() function --"); query = imports + "declare function local:get-doc($path as xs:string) {\n" + " document($path)\n" + "};\n" + "let $col := xdb:create-collection('/db', 'testup')\n" + "let $path := '/db/testup/test1.xml'\n" + "let $d1 := local:get-doc($path)\n" + "let $doc := xdb:store($col, 'test1.xml', <test><n>1</n></test>)\n" + "return string-join((string(count(local:get-doc($path))), string(doc-available($path))), ' ')"; result = execQuery(query); assertEquals(result, "1 true"); System.out.println("-- TEST 3: collection() function --"); query = imports + "declare function local:xpath($collection as xs:string) {\n" + " for $c in collection($collection) return $c "};\n" + "let $col := xdb:create-collection('/db', 'testup')\n" + "let $path := '/db/testup'\n" + "let $d1 := local:xpath($path)//n/text()\n" + "let $doc := xdb:store($col, 'test1.xml', <test><n>1</n></test>)\n" + "return local:xpath($path)//n/text()"; result = execQuery(query); assertEquals(result, "1"); System.out.println("-- TEST 4: 'update insert' statement --"); query = imports + "declare function local:xpath($collection as xs:string) {\n" + " collection($collection)\n" + "};\n" + "let $col := xdb:create-collection('/db', 'testup')\n" + "let $path := '/db/testup'\n" + "let $d1 := local:xpath($path) "let $doc := xdb:store($col, 'test1.xml', <test><n>1</n></test>)\n" + "return (\n" + " update insert <n>2</n> into collection($path)/test,\n" + " count(local:xpath($path) ")"; result = execQuery(query); assertEquals(result, "2"); System.out.println("-- TEST 5: 'update replace' statement --"); query = "let $doc := " + "<test> " + "<link href=\"features\"/> " + "(: it works with only 1 link :) " + "<link href=\"features/test\"/> " + "</test> " + "let $links := $doc/link/@href " + "return " + "for $link in $links " + "return ( " + "update replace $link with \"123\", " + "(: without the output on the next line, it works :) " + "xs:string($link) " + ")"; XQueryService service = (XQueryService) testCollection.getService("XQueryService", "1.0"); ResourceSet r = service.query(query); assertEquals(r.getSize(), 2); assertEquals(r.getResource(0).getContent().toString(), "123"); assertEquals(r.getResource(1).getContent().toString(), "123"); } catch (XMLDBException e) { e.printStackTrace(); fail(e.getMessage()); } } public void bugtestUpdateAttribute(){ String query1="let $content :=" +"<A><B><C d=\"xxx\">ccc1</C><C d=\"yyy\" e=\"zzz\">ccc2</C></B></A> " +"let $uri := xmldb:store(\"/db/\", \"marktest7.xml\", $content) " +"let $doc := doc($uri) " +"let $xxx := update delete $doc +"return $doc"; String query2="let $doc := doc(\"/db/marktest7.xml\") " +"return " /* * @see TestCase#tearDown() */ protected void tearDown() { try { Collection root = DatabaseManager.getCollection("xmldb:exist://" + DBBroker.ROOT_COLLECTION, "admin", null); CollectionManagementService service = (CollectionManagementService) root.getService( "CollectionManagementService", "1.0"); service.removeCollection(TEST_COLLECTION_NAME); DatabaseManager.deregisterDatabase(database); DatabaseInstanceManager dim = (DatabaseInstanceManager) testCollection.getService( "DatabaseInstanceManager", "1.0"); dim.shutdown(); database = null; testCollection = null; System.out.println("tearDown PASSED"); } catch (XMLDBException e) { fail(e.getMessage()); } } public static void main(String[] args) { TestRunner.run(DocumentUpdateTest.class); } }
package org.apache.xerces.validators.common; import org.apache.xerces.framework.XMLAttrList; import org.apache.xerces.framework.XMLContentSpec; import org.apache.xerces.framework.XMLDocumentHandler; import org.apache.xerces.framework.XMLDocumentScanner; import org.apache.xerces.framework.XMLErrorReporter; import org.apache.xerces.readers.DefaultEntityHandler; import org.apache.xerces.readers.XMLEntityHandler; import org.apache.xerces.utils.ChunkyCharArray; import org.apache.xerces.utils.Hash2intTable; import org.apache.xerces.utils.NamespacesScope; import org.apache.xerces.utils.QName; import org.apache.xerces.utils.StringPool; import org.apache.xerces.utils.XMLCharacterProperties; import org.apache.xerces.utils.XMLMessages; import org.apache.xerces.utils.ImplementationMessages; import org.apache.xerces.parsers.DOMParser; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.InputSource; import org.xml.sax.EntityResolver; import org.xml.sax.Locator; import org.xml.sax.helpers.LocatorImpl; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import java.io.IOException; import java.util.Enumeration; import java.util.Hashtable; import java.util.StringTokenizer; import java.util.Vector; import org.apache.xerces.validators.dtd.DTDGrammar; import org.apache.xerces.validators.schema.SchemaGrammar; import org.apache.xerces.validators.schema.SchemaMessageProvider; import org.apache.xerces.validators.schema.SchemaSymbols; import org.apache.xerces.validators.schema.TraverseSchema; import org.apache.xerces.validators.datatype.DatatypeValidator; import org.apache.xerces.validators.datatype.InvalidDatatypeValueException; /** * This class is the super all-in-one validator used by the parser. * * @version $Id$ */ public final class XMLValidator implements DefaultEntityHandler.EventHandler, XMLEntityHandler.CharDataHandler, XMLDocumentScanner.EventHandler, NamespacesScope.NamespacesHandler { // Constants // debugging private static final boolean PRINT_EXCEPTION_STACK_TRACE = false; private static final boolean DEBUG_PRINT_ATTRIBUTES = false; private static final boolean DEBUG_PRINT_CONTENT = false; private static final boolean DEBUG_SCHEMA_VALIDATION = false; private static final boolean DEBUG_ELEMENT_CHILDREN = false; // Chunk size constants private static final int CHUNK_SHIFT = 8; // 2^8 = 256 private static final int CHUNK_SIZE = (1 << CHUNK_SHIFT); private static final int CHUNK_MASK = CHUNK_SIZE - 1; private static final int INITIAL_CHUNK_COUNT = (1 << (10 - CHUNK_SHIFT)); // 2^10 = 1k // Data // REVISIT: The data should be regrouped and re-organized so that // it's easier to find a meaningful field. // debugging // private static boolean DEBUG = false; // other private Hashtable fIdDefs = null; private Hashtable fIdRefs = null; private Object fNullValue = null; // attribute validators // REVISIT: Validation. A validator per element declaration and // attribute declaration is required to accomodate // Schema facets on simple types. private AttributeValidator fAttValidatorCDATA = null; private AttributeValidator fAttValidatorID = new AttValidatorID(); private AttributeValidator fAttValidatorIDREF = new AttValidatorIDREF(); private AttributeValidator fAttValidatorIDREFS = new AttValidatorIDREFS(); private AttributeValidator fAttValidatorENTITY = new AttValidatorENTITY(); private AttributeValidator fAttValidatorENTITIES = new AttValidatorENTITIES(); private AttributeValidator fAttValidatorNMTOKEN = new AttValidatorNMTOKEN(); private AttributeValidator fAttValidatorNMTOKENS = new AttValidatorNMTOKENS(); private AttributeValidator fAttValidatorNOTATION = new AttValidatorNOTATION(); private AttributeValidator fAttValidatorENUMERATION = new AttValidatorENUMERATION(); private AttributeValidator fAttValidatorDATATYPE = null; // Package access for use by AttributeValidator classes. StringPool fStringPool = null; boolean fValidating = false; boolean fInElementContent = false; int fStandaloneReader = -1; // settings private boolean fValidationEnabled = false; private boolean fDynamicValidation = false; private boolean fValidationEnabledByDynamic = false; private boolean fDynamicDisabledByValidation = false; private boolean fWarningOnDuplicateAttDef = false; private boolean fWarningOnUndeclaredElements = false; // declarations private int fDeclaration[]; private XMLErrorReporter fErrorReporter = null; private DefaultEntityHandler fEntityHandler = null; private QName fCurrentElement = new QName(); //REVISIT: validation private int[] fScopeStack = new int[8]; private int[] fGrammarNameSpaceIndexStack = new int[8]; private int[] fElementTypeStack = new int[8]; private int[] fElementEntityStack = new int[8]; private int[] fElementIndexStack = new int[8]; private int[] fContentSpecTypeStack = new int[8]; private QName[] fElementChildren = new QName[32]; private int fElementChildrenLength = 0; private int[] fElementChildrenOffsetStack = new int[32]; private int fElementDepth = -1; private boolean fNamespacesEnabled = false; private NamespacesScope fNamespacesScope = null; private int fNamespacesPrefix = -1; private QName fRootElement = new QName(); private int fAttrListHandle = -1; private int fCurrentElementEntity = -1; private int fCurrentElementIndex = -1; private int fCurrentContentSpecType = -1; private boolean fSeenDoctypeDecl = false; private final int TOP_LEVEL_SCOPE = -1; private int fCurrentScope = TOP_LEVEL_SCOPE; private int fCurrentSchemaURI = -1; private int fEmptyURI = - 1; private int fXsiPrefix = - 1; private int fXsiURI = -2; private Grammar fGrammar = null; private int fGrammarNameSpaceIndex = -1; private GrammarResolver fGrammarResolver = null; // state and stuff private boolean fScanningDTD = false; private XMLDocumentScanner fDocumentScanner = null; private boolean fCalledStartDocument = false; private XMLDocumentHandler fDocumentHandler = null; private XMLDocumentHandler.DTDHandler fDTDHandler = null; private boolean fSeenRootElement = false; private XMLAttrList fAttrList = null; private int fXMLLang = -1; private LocatorImpl fAttrNameLocator = null; private boolean fCheckedForSchema = false; private boolean fDeclsAreExternal = false; private StringPool.CharArrayRange fCurrentElementCharArrayRange = null; private char[] fCharRefData = null; private boolean fSendCharDataAsCharArray = false; private boolean fBufferDatatype = false; private StringBuffer fDatatypeBuffer = new StringBuffer(); private QName fTempQName = new QName(); private XMLAttributeDecl fTempAttDecl = new XMLAttributeDecl(); private XMLElementDecl fTempElementDecl = new XMLElementDecl(); //REVISIT: ericye, use this temp QName whenever we can!! private boolean fGrammarIsDTDGrammar = false; private boolean fGrammarIsSchemaGrammar = false; // symbols private int fEMPTYSymbol = -1; private int fANYSymbol = -1; private int fMIXEDSymbol = -1; private int fCHILDRENSymbol = -1; private int fCDATASymbol = -1; private int fIDSymbol = -1; private int fIDREFSymbol = -1; private int fIDREFSSymbol = -1; private int fENTITYSymbol = -1; private int fENTITIESSymbol = -1; private int fNMTOKENSymbol = -1; private int fNMTOKENSSymbol = -1; private int fNOTATIONSymbol = -1; private int fENUMERATIONSymbol = -1; private int fREQUIREDSymbol = -1; private int fFIXEDSymbol = -1; private int fDATATYPESymbol = -1; private int fEpsilonIndex = -1; // Constructors /** Constructs an XML validator. */ public XMLValidator(StringPool stringPool, XMLErrorReporter errorReporter, DefaultEntityHandler entityHandler, XMLDocumentScanner documentScanner) { // keep references fStringPool = stringPool; fErrorReporter = errorReporter; fEntityHandler = entityHandler; fDocumentScanner = documentScanner; fEmptyURI = fStringPool.addSymbol(""); fXsiURI = fStringPool.addSymbol(SchemaSymbols.URI_XSI); // initialize fAttrList = new XMLAttrList(fStringPool); entityHandler.setEventHandler(this); entityHandler.setCharDataHandler(this); fDocumentScanner.setEventHandler(this); init(); } // <init>(StringPool,XMLErrorReporter,DefaultEntityHandler,XMLDocumentScanner) public void setGrammarResolver(GrammarResolver grammarResolver){ fGrammarResolver = grammarResolver; } // Public methods // initialization /** Set char data processing preference and handlers. */ public void initHandlers(boolean sendCharDataAsCharArray, XMLDocumentHandler docHandler, XMLDocumentHandler.DTDHandler dtdHandler) { fSendCharDataAsCharArray = sendCharDataAsCharArray; fEntityHandler.setSendCharDataAsCharArray(fSendCharDataAsCharArray); fDocumentHandler = docHandler; fDTDHandler = dtdHandler; } // initHandlers(boolean,XMLDocumentHandler,XMLDocumentHandler.DTDHandler) /** Reset or copy. */ public void resetOrCopy(StringPool stringPool) throws Exception { fAttrList = new XMLAttrList(stringPool); resetCommon(stringPool); } /** Reset. */ public void reset(StringPool stringPool) throws Exception { fAttrList.reset(stringPool); resetCommon(stringPool); } // settings /** * Turning on validation/dynamic turns on validation if it is off, and * this is remembered. Turning off validation DISABLES validation/dynamic * if it is on. Turning off validation/dynamic DOES NOT turn off * validation if it was explicitly turned on, only if it was turned on * BECAUSE OF the call to turn validation/dynamic on. Turning on * validation will REENABLE and turn validation/dynamic back on if it * was disabled by a call that turned off validation while * validation/dynamic was enabled. */ public void setValidationEnabled(boolean flag) throws Exception { fValidationEnabled = flag; fValidationEnabledByDynamic = false; if (fValidationEnabled) { if (fDynamicDisabledByValidation) { fDynamicValidation = true; fDynamicDisabledByValidation = false; } } else if (fDynamicValidation) { fDynamicValidation = false; fDynamicDisabledByValidation = true; } fValidating = fValidationEnabled; } /** Returns true if validation is enabled. */ public boolean getValidationEnabled() { return fValidationEnabled; } /** Sets whether validation is dynamic. */ public void setDynamicValidationEnabled(boolean flag) throws Exception { fDynamicValidation = flag; fDynamicDisabledByValidation = false; if (!fDynamicValidation) { if (fValidationEnabledByDynamic) { fValidationEnabled = false; fValidationEnabledByDynamic = false; } } else if (!fValidationEnabled) { fValidationEnabled = true; fValidationEnabledByDynamic = true; } fValidating = fValidationEnabled; } /** Returns true if validation is dynamic. */ public boolean getDynamicValidationEnabled() { return fDynamicValidation; } /** Sets whether namespaces are enabled. */ public void setNamespacesEnabled(boolean flag) { fNamespacesEnabled = flag; } /** Returns true if namespaces are enabled. */ public boolean getNamespacesEnabled() { return fNamespacesEnabled; } /** Sets whether duplicate attribute definitions signal a warning. */ public void setWarningOnDuplicateAttDef(boolean flag) { fWarningOnDuplicateAttDef = flag; } /** Returns true if duplicate attribute definitions signal a warning. */ public boolean getWarningOnDuplicateAttDef() { return fWarningOnDuplicateAttDef; } /** Sets whether undeclared elements signal a warning. */ public void setWarningOnUndeclaredElements(boolean flag) { fWarningOnUndeclaredElements = flag; } /** Returns true if undeclared elements signal a warning. */ public boolean getWarningOnUndeclaredElements() { return fWarningOnUndeclaredElements; } // DefaultEntityHandler.EventHandler methods /** Start entity reference. */ public void startEntityReference(int entityName, int entityType, int entityContext) throws Exception { fDocumentHandler.startEntityReference(entityName, entityType, entityContext); } /** End entity reference. */ public void endEntityReference(int entityName, int entityType, int entityContext) throws Exception { fDocumentHandler.endEntityReference(entityName, entityType, entityContext); } /** Send end of input notification. */ public void sendEndOfInputNotifications(int entityName, boolean moreToFollow) throws Exception { fDocumentScanner.endOfInput(entityName, moreToFollow); /** Send reader change notifications. */ /** External entity standalone check. */ /** Return true if validating. */ /** Process characters. */ /** Process characters. */ /** Process whitespace. */ /** Process whitespace. */ /** Scans element type. */ /** Scans expected element type. */ /** Scans attribute name. */ /** Call start document. */ /** Call end document. */ /** Call XML declaration. */ /** Call text declaration. */ /** * Signal the scanning of an element name in a start element tag. * * @param element Element name scanned. */ public void element(QName element) throws Exception { fAttrListHandle = -1; } /** * Signal the scanning of an attribute associated to the previous * start element tag. * * @param element Element name scanned. * @param attrName Attribute name scanned. * @param attrValue The string pool index of the attribute value. */ public boolean attribute(QName element, QName attrName, int attrValue) throws Exception { if (fAttrListHandle == -1) { fAttrListHandle = fAttrList.startAttrList(); } // if fAttrList.addAttr returns -1, indicates duplicate att in start tag of an element. // specified: true, search : true return fAttrList.addAttr(attrName, attrValue, fCDATASymbol, true, true) == -1; } /** Call start element. */ public void callStartElement(QName element) throws Exception { if ( DEBUG_SCHEMA_VALIDATION ) System.out.println("\n=======StartElement : " + fStringPool.toString(element.localpart)); // Check after all specified attrs are scanned // (1) report error for REQUIRED attrs that are missing (V_TAGc) // (2) add default attrs (FIXED and NOT_FIXED) if (!fSeenRootElement) { fSeenRootElement = true; rootElementSpecified(element); fStringPool.resetShuffleCount(); } fCheckedForSchema = true; if (fNamespacesEnabled) { bindNamespacesToElementAndAttributes(element, fAttrList); } validateElementAndAttributes(element, fAttrList); if (fAttrListHandle != -1) { fAttrList.endAttrList(); } fDocumentHandler.startElement(element, fAttrList, fAttrListHandle); fAttrListHandle = -1; //before we increment the element depth, add this element's QName to its enclosing element 's children list fElementDepth++; //if (fElementDepth >= 0) { if (fValidating) { // push current length onto stack if (fElementChildrenOffsetStack.length < fElementDepth) { int newarray[] = new int[fElementChildrenOffsetStack.length * 2]; System.arraycopy(fElementChildrenOffsetStack, 0, newarray, 0, fElementChildrenOffsetStack.length); fElementChildrenOffsetStack = newarray; } fElementChildrenOffsetStack[fElementDepth] = fElementChildrenLength; // add this element to children if (fElementChildren.length <= fElementChildrenLength) { QName[] newarray = new QName[fElementChildrenLength * 2]; System.arraycopy(fElementChildren, 0, newarray, 0, fElementChildren.length); fElementChildren = newarray; } QName qname = fElementChildren[fElementChildrenLength]; if (qname == null) { for (int i = fElementChildrenLength; i < fElementChildren.length; i++) { fElementChildren[i] = new QName(); } qname = fElementChildren[fElementChildrenLength]; } qname.setValues(element); fElementChildrenLength++; if (DEBUG_ELEMENT_CHILDREN) { printChildren(); printStack(); } } // One more level of depth //fElementDepth++; ensureStackCapacity(fElementDepth); fCurrentElement.setValues(element); fCurrentElementEntity = fEntityHandler.getReaderId(); fElementTypeStack[fElementDepth] = fCurrentElement.rawname; fElementEntityStack[fElementDepth] = fCurrentElementEntity; fElementIndexStack[fElementDepth] = fCurrentElementIndex; fContentSpecTypeStack[fElementDepth] = fCurrentContentSpecType; //REVISIT: Validation if ( fCurrentElementIndex > -1 && fGrammarIsSchemaGrammar && fValidating) { fCurrentScope = ((SchemaGrammar) fGrammar).getElementDefinedScope(fCurrentElementIndex); } fScopeStack[fElementDepth] = fCurrentScope; fGrammarNameSpaceIndexStack[fElementDepth] = fGrammarNameSpaceIndex; } // callStartElement(QName) private void ensureStackCapacity ( int newElementDepth) { if (newElementDepth == fElementTypeStack.length) { int[] newStack = new int[newElementDepth * 2]; System.arraycopy(fScopeStack, 0, newStack, 0, newElementDepth); fScopeStack = newStack; newStack = new int[newElementDepth * 2]; System.arraycopy(fGrammarNameSpaceIndexStack, 0, newStack, 0, newElementDepth); fGrammarNameSpaceIndexStack = newStack; newStack = new int[newElementDepth * 2]; System.arraycopy(fElementTypeStack, 0, newStack, 0, newElementDepth); fElementTypeStack = newStack; newStack = new int[newElementDepth * 2]; System.arraycopy(fElementEntityStack, 0, newStack, 0, newElementDepth); fElementEntityStack = newStack; newStack = new int[newElementDepth * 2]; System.arraycopy(fElementIndexStack, 0, newStack, 0, newElementDepth); fElementIndexStack = newStack; newStack = new int[newElementDepth * 2]; System.arraycopy(fContentSpecTypeStack, 0, newStack, 0, newElementDepth); fContentSpecTypeStack = newStack; } } /** Call end element. */ public void callEndElement(int readerId) throws Exception { if ( DEBUG_SCHEMA_VALIDATION ) System.out.println("=======EndElement : " + fStringPool.toString(fCurrentElement.localpart)+"\n"); int prefixIndex = fCurrentElement.prefix; // REVISIT: Validation int elementType = fCurrentElement.rawname; if (fCurrentElementEntity != readerId) { fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, XMLMessages.MSG_ELEMENT_ENTITY_MISMATCH, XMLMessages.P78_NOT_WELLFORMED, new Object[] { fStringPool.toString(elementType) }, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } fElementDepth if (fValidating) { int elementIndex = fCurrentElementIndex; if (elementIndex != -1 && fCurrentContentSpecType != -1) { QName children[] = fElementChildren; int childrenOffset = fElementChildrenOffsetStack[fElementDepth + 1] + 1; int childrenLength = fElementChildrenLength - childrenOffset; if (DEBUG_ELEMENT_CHILDREN) { System.out.println("endElement("+fStringPool.toString(fCurrentElement.rawname)+')'); System.out.print("offset: "); System.out.print(childrenOffset); System.out.print(", length: "); System.out.print(childrenLength); System.out.println(); printChildren(); printStack(); } int result = checkContent(elementIndex, children, childrenOffset, childrenLength); if ( DEBUG_SCHEMA_VALIDATION ) System.out.println("!!!!!!!!In XMLValidator, the return value from checkContent : " + result); if (result != -1) { int majorCode = result != childrenLength ? XMLMessages.MSG_CONTENT_INVALID : XMLMessages.MSG_CONTENT_INCOMPLETE; fGrammar.getElementDecl(elementIndex, fTempElementDecl); reportRecoverableXMLError(majorCode, 0, fStringPool.toString(elementType), XMLContentSpec.toString(fGrammar, fStringPool, fTempElementDecl.contentSpecIndex));// REVISIT: getContentSpecAsString(elementIndex)); } } fElementChildrenLength = fElementChildrenOffsetStack[fElementDepth + 1] + 1; } fDocumentHandler.endElement(fCurrentElement); if (fNamespacesEnabled) { fNamespacesScope.decreaseDepth(); } // now pop this element off the top of the element stack //if (fElementDepth-- < 0) { if (fElementDepth < -1) { throw new RuntimeException("FWK008 Element stack underflow"); } if (fElementDepth < 0) { fCurrentElement.clear(); fCurrentElementEntity = -1; fCurrentElementIndex = -1; fCurrentContentSpecType = -1; fInElementContent = false; // Check after document is fully parsed // (1) check that there was an element with a matching id for every // IDREF and IDREFS attr (V_IDREF0) if (fValidating && fIdRefs != null) { checkIdRefs(); } return; } //restore enclosing element to all the "current" variables // REVISIT: Validation. This information needs to be stored. fCurrentElement.prefix = -1; fCurrentElement.localpart = fElementTypeStack[fElementDepth]; fCurrentElement.rawname = fElementTypeStack[fElementDepth]; fCurrentElementEntity = fElementEntityStack[fElementDepth]; fCurrentElementIndex = fElementIndexStack[fElementDepth]; fCurrentContentSpecType = fContentSpecTypeStack[fElementDepth]; //REVISIT: Validation fCurrentScope = fScopeStack[fElementDepth]; //if ( DEBUG_SCHEMA_VALIDATION ) { /** Call start CDATA section. */ /** Call end CDATA section. */ /** Call characters. */ /** Call processing instruction. */ /** Call comment. */ /** Start a new namespace declaration scope. */ /** End a namespace declaration scope. */ /** Normalize attribute value. */ /** Sets the root element. */ /** * Returns true if the element declaration is external. * <p> * <strong>Note:</strong> This method is primarilly useful for * DTDs with internal and external subsets. */ private boolean getElementDeclIsExternal(int elementIndex) { /*if (elementIndex < 0 || elementIndex >= fElementCount) { return false; } int chunk = elementIndex >> CHUNK_SHIFT; int index = elementIndex & CHUNK_MASK; return (fElementDeclIsExternal[chunk][index] != 0); */ if (fGrammarIsDTDGrammar ) { return ((DTDGrammar) fGrammar).getElementDeclIsExternal(elementIndex); } return false; } /** Returns the content spec type for an element index. */ public int getContentSpecType(int elementIndex) { int contentSpecType = -1; if ( elementIndex > -1) { if ( fGrammar.getElementDecl(elementIndex,fTempElementDecl) ) { contentSpecType = fTempElementDecl.type; } } return contentSpecType; } /** Returns the content spec handle for an element index. */ public int getContentSpecHandle(int elementIndex) { int contentSpecHandle = -1; if ( elementIndex > -1) { if ( fGrammar.getElementDecl(elementIndex,fTempElementDecl) ) { contentSpecHandle = fTempElementDecl.contentSpecIndex; } } return contentSpecHandle; } // Protected methods // error reporting /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode) throws Exception { fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, null, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int) /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode, int stringIndex1) throws Exception { Object[] args = { fStringPool.toString(stringIndex1) }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int,int) /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode, String string1) throws Exception { Object[] args = { string1 }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int,String) /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode, int stringIndex1, int stringIndex2) throws Exception { Object[] args = { fStringPool.toString(stringIndex1), fStringPool.toString(stringIndex2) }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int,int,int) /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode, String string1, String string2) throws Exception { Object[] args = { string1, string2 }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int,String,String) /** Report a recoverable xml error. */ protected void reportRecoverableXMLError(int majorCode, int minorCode, String string1, String string2, String string3) throws Exception { Object[] args = { string1, string2, string3 }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, majorCode, minorCode, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } // reportRecoverableXMLError(int,int,String,String,String) // content spec protected int whatCanGoHere(int elementIndex, boolean fullyValid, InsertableElementsInfo info) throws Exception { // Do some basic sanity checking on the info packet. First, make sure // that insertAt is not greater than the child count. It can be equal, // which means to get appendable elements, but not greater. Or, if // the current children array is null, that's bad too. // Since the current children array must have a blank spot for where // the insert is going to be, the child count must always be at least // one. // Make sure that the child count is not larger than the current children // array. It can be equal, which means get appendable elements, but not // greater. if (info.insertAt > info.childCount || info.curChildren == null || info.childCount < 1 || info.childCount > info.curChildren.length) { fErrorReporter.reportError(fErrorReporter.getLocator(), ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN, ImplementationMessages.VAL_WCGHI, 0, null, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } int retVal = 0; try { // Get the content model for this element final XMLContentModel cmElem = getContentModel(elementIndex); // And delegate this call to it retVal = cmElem.whatCanGoHere(fullyValid, info); } catch (CMException excToCatch) { // REVISIT - Translate caught error to the protected error handler interface int majorCode = excToCatch.getErrorCode(); fErrorReporter.reportError(fErrorReporter.getLocator(), ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN, majorCode, 0, null, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); throw excToCatch; } return retVal; } // whatCanGoHere(int,boolean,InsertableElementsInfo):int // attribute information /** Protected for use by AttributeValidator classes. */ protected boolean getAttDefIsExternal(QName element, QName attribute) { int attDefIndex = getAttDef(element, attribute); if (fGrammarIsDTDGrammar ) { return ((DTDGrammar) fGrammar).getAttributeDeclIsExternal(attDefIndex); } return false; } /** addId. */ protected boolean addId(int idIndex) { Integer key = new Integer(idIndex); if (fIdDefs == null) { fIdDefs = new Hashtable(); } else if (fIdDefs.containsKey(key)) { return false; } if (fNullValue == null) { fNullValue = new Object(); } fIdDefs.put(key, fNullValue/*new Integer(elementType)*/); return true; } // addId(int):boolean /** addIdRef. */ protected void addIdRef(int idIndex) { Integer key = new Integer(idIndex); if (fIdDefs != null && fIdDefs.containsKey(key)) { return; } if (fIdRefs == null) { fIdRefs = new Hashtable(); } else if (fIdRefs.containsKey(key)) { return; } if (fNullValue == null) { fNullValue = new Object(); } fIdRefs.put(key, fNullValue/*new Integer(elementType)*/); } // addIdRef(int) // Private methods // other /** Returns true if using a standalone reader. */ private boolean usingStandaloneReader() { return fStandaloneReader == -1 || fEntityHandler.getReaderId() == fStandaloneReader; } /** Returns a locator implementation. */ private LocatorImpl getLocatorImpl(LocatorImpl fillin) { Locator here = fErrorReporter.getLocator(); if (fillin == null) return new LocatorImpl(here); fillin.setPublicId(here.getPublicId()); fillin.setSystemId(here.getSystemId()); fillin.setLineNumber(here.getLineNumber()); fillin.setColumnNumber(here.getColumnNumber()); return fillin; } // getLocatorImpl(LocatorImpl):LocatorImpl // content models /** * This method will handle the querying of the content model for a * particular element. If the element does not have a content model, then * it will be created. */ private XMLContentModel getContentModel(int elementIndex) throws CMException { // See if a content model already exists first XMLContentModel cmRet = getElementContentModel(elementIndex); // If we have one, just return that. Otherwise, gotta create one if (cmRet != null) { return cmRet; } // Get the type of content this element has final int contentSpec = getContentSpecType(elementIndex); // And create the content model according to the spec type if (contentSpec == XMLElementDecl.TYPE_MIXED) { // Just create a mixel content model object. This type of // content model is optimized for mixed content validation. //REVISIT, could not compile // XMLContentSpec specNode = new XMLContentSpec(); // int contentSpecIndex = getContentSpecHandle(elementIndex); // makeContentList(contentSpecIndex, specNode); // cmRet = new MixedContentModel(fCount, fContentList); } else if (contentSpec == XMLElementDecl.TYPE_CHILDREN) { // This method will create an optimal model for the complexity // of the element's defined model. If its simple, it will create // a SimpleContentModel object. If its a simple list, it will // create a SimpleListContentModel object. If its complex, it // will create a DFAContentModel object. //REVISIT: couldnot compile //cmRet = createChildModel(elementIndex); } else if (contentSpec == fDATATYPESymbol) { // cmRet = fSchemaImporter.createDatatypeContentModel(elementIndex); } else { throw new CMException(ImplementationMessages.VAL_CST); } // Add the new model to the content model for this element //REVISIT setContentModel(elementIndex, cmRet); return cmRet; } // getContentModel(int):XMLContentModel // initialization /** Reset pool. */ private void poolReset() { if (fIdDefs != null) { fIdDefs.clear(); } if (fIdRefs != null) { fIdRefs.clear(); } } // poolReset() /** Reset common. */ private void resetCommon(StringPool stringPool) throws Exception { fStringPool = stringPool; fValidating = fValidationEnabled; fValidationEnabledByDynamic = false; fDynamicDisabledByValidation = false; poolReset(); fCalledStartDocument = false; fStandaloneReader = -1; fElementChildrenLength = 0; fElementDepth = -1; fSeenRootElement = false; fSeenDoctypeDecl = false; fNamespacesScope = null; fNamespacesPrefix = -1; fRootElement.clear(); fAttrListHandle = -1; fCheckedForSchema = false; fCurrentScope = TOP_LEVEL_SCOPE; fCurrentSchemaURI = -1; fEmptyURI = - 1; fXsiPrefix = - 1; fGrammar = null; fGrammarNameSpaceIndex = -1; fGrammarResolver = null; fGrammarIsDTDGrammar = false; fGrammarIsSchemaGrammar = false; init(); } // resetCommon(StringPool) /** Initialize. */ private void init() { fEmptyURI = fStringPool.addSymbol(""); fXsiURI = fStringPool.addSymbol(SchemaSymbols.URI_XSI); fEMPTYSymbol = fStringPool.addSymbol("EMPTY"); fANYSymbol = fStringPool.addSymbol("ANY"); fMIXEDSymbol = fStringPool.addSymbol("MIXED"); fCHILDRENSymbol = fStringPool.addSymbol("CHILDREN"); fCDATASymbol = fStringPool.addSymbol("CDATA"); fIDSymbol = fStringPool.addSymbol("ID"); fIDREFSymbol = fStringPool.addSymbol("IDREF"); fIDREFSSymbol = fStringPool.addSymbol("IDREFS"); fENTITYSymbol = fStringPool.addSymbol("ENTITY"); fENTITIESSymbol = fStringPool.addSymbol("ENTITIES"); fNMTOKENSymbol = fStringPool.addSymbol("NMTOKEN"); fNMTOKENSSymbol = fStringPool.addSymbol("NMTOKENS"); fNOTATIONSymbol = fStringPool.addSymbol("NOTATION"); fENUMERATIONSymbol = fStringPool.addSymbol("ENUMERATION"); fREQUIREDSymbol = fStringPool.addSymbol("#REQUIRED"); fFIXEDSymbol = fStringPool.addSymbol("#FIXED"); fDATATYPESymbol = fStringPool.addSymbol("<<datatype>>"); fEpsilonIndex = fStringPool.addSymbol("<<CMNODE_EPSILON>>"); fXMLLang = fStringPool.addSymbol("xml:lang"); /** fEMPTYSymbol = XMLElementDecl.TYPE_EMPTY; fANYSymbol = XMLElementDecl.TYPE_ANY; fMIXEDSymbol = XMLElementDecl.TYPE_MIXED; fCHILDRENSymbol = XMLElementDecl.TYPE_CHILDREN; fCDATASymbol = XMLAttributeDecl.TYPE_CDATA; fIDSymbol = XMLAttributeDecl.TYPE_ID; fIDREFSymbol = XMLAttributeDecl.TYPE_IDREF; fIDREFSSymbol = XMLAttributeDecl.TYPE_IDREF; fENTITYSymbol = XMLAttributeDecl.TYPE_ENTITY; fENTITIESSymbol = XMLAttributeDecl.TYPE_ENTITY; fNMTOKENSymbol = XMLAttributeDecl.TYPE_NMTOKEN; fNMTOKENSSymbol = XMLAttributeDecl.TYPE_NMTOKEN; fNOTATIONSymbol = XMLAttributeDecl.TYPE_NOTATION; fENUMERATIONSymbol = XMLAttributeDecl.TYPE_ENUMERATION; fREQUIREDSymbol = XMLAttributeDecl.DEFAULT_TYPE_REQUIRED; fFIXEDSymbol = XMLAttributeDecl.DEFAULT_TYPE_FIXED; fDATATYPESymbol = XMLElementDecl.TYPE_SIMPLE; **/ } // init() // other // default attribute /** addDefaultAttributes. */ private int addDefaultAttributes(int elementIndex, XMLAttrList attrList, int attrIndex, boolean validationEnabled, boolean standalone) throws Exception { //System.out.println("XMLValidator#addDefaultAttributes"); //System.out.print(" "); //fGrammar.printAttributes(elementIndex); // Check after all specified attrs are scanned // (1) report error for REQUIRED attrs that are missing (V_TAGc) // (2) check that FIXED attrs have matching value (V_TAGd) // (3) add default attrs (FIXED and NOT_FIXED) fGrammar.getElementDecl(elementIndex,fTempElementDecl); //System.out.println("addDefaultAttributes: " + fStringPool.toString(fTempElementDecl.name.localpart)+ // "," + attrIndex + "," + validationEnabled); int elementNameIndex = fTempElementDecl.name.localpart; int attlistIndex = fGrammar.getFirstAttributeDeclIndex(elementIndex); int firstCheck = attrIndex; int lastCheck = -1; while (attlistIndex != -1) { //int adChunk = attlistIndex >> CHUNK_SHIFT; //int adIndex = attlistIndex & CHUNK_MASK; fGrammar.getAttributeDecl(attlistIndex, fTempAttDecl); // TO DO: For ericye Debug only /** Queries the content model for the specified element index. */ /** Sets the content model for the specified element index. */ /*if (elementIndex < 0 || elementIndex >= fElementCount) { return; } int chunk = elementIndex >> CHUNK_SHIFT; int index = elementIndex & CHUNK_MASK; fContentModel[chunk][index] = cm; */ } // query attribute information /** Returns the validatator for an attribute type. */ private AttributeValidator getValidatorForAttType(int attType, boolean list) { if (attType == XMLAttributeDecl.TYPE_CDATA) { if (fAttValidatorCDATA == null) { fAttValidatorCDATA = new AttValidatorCDATA(); } return fAttValidatorCDATA; } if (attType == XMLAttributeDecl.TYPE_ID) { if (fAttValidatorID == null) { fAttValidatorID = new AttValidatorID(); } return fAttValidatorID; } if (attType == XMLAttributeDecl.TYPE_IDREF) { if (!list) { if (fAttValidatorIDREF == null) { fAttValidatorIDREF = new AttValidatorIDREF(); } return fAttValidatorIDREF; } else { if (fAttValidatorIDREFS == null) { fAttValidatorIDREFS = new AttValidatorIDREFS(); } return fAttValidatorIDREFS; } } if (attType == XMLAttributeDecl.TYPE_ENTITY) { if (!list) { if (fAttValidatorENTITY == null) { fAttValidatorENTITY = new AttValidatorENTITY(); } return fAttValidatorENTITY; } else{ if (fAttValidatorENTITIES == null) { fAttValidatorENTITIES = new AttValidatorENTITIES(); } return fAttValidatorENTITIES; } } if (attType == XMLAttributeDecl.TYPE_NMTOKEN) { if (!list) { if (fAttValidatorNMTOKEN == null) { fAttValidatorNMTOKEN = new AttValidatorNMTOKEN(); } return fAttValidatorNMTOKEN; } else{ if (fAttValidatorNMTOKENS == null) { fAttValidatorNMTOKENS = new AttValidatorNMTOKENS(); } return fAttValidatorNMTOKENS; } } if (attType == XMLAttributeDecl.TYPE_NOTATION) { if (fAttValidatorNOTATION == null) { fAttValidatorNOTATION = new AttValidatorNOTATION(); } return fAttValidatorNOTATION; } if (attType == XMLAttributeDecl.TYPE_ENUMERATION) { if (fAttValidatorENUMERATION == null) { fAttValidatorENUMERATION = new AttValidatorENUMERATION(); } return fAttValidatorENUMERATION; } if (attType == XMLAttributeDecl.TYPE_SIMPLE) { if (fAttValidatorDATATYPE == null) { fAttValidatorDATATYPE = null; //REVISIT : !!! used to be fSchemaImporter.createDatatypeAttributeValidator(); } //return fAttValidatorDATATYPE; } return null; //throw new RuntimeException("getValidatorForAttType(" + fStringPool.toString(attType) + ")"); } /** Returns an attribute definition for an element type. */ private int getAttDef(QName element, QName attribute) { if (fGrammar != null) { int scope = fCurrentScope; if (element.uri > -1) { scope = TOP_LEVEL_SCOPE; } int elementIndex = fGrammar.getElementDeclIndex(element.localpart,scope); if (elementIndex == -1) { return -1; } int attDefIndex = fGrammar.getFirstAttributeDeclIndex(elementIndex); while (attDefIndex != -1) { fGrammar.getAttributeDecl(attDefIndex, fTempAttDecl); if (fTempAttDecl.name.localpart == attribute.localpart && fTempAttDecl.name.uri == attribute.uri ) { return attDefIndex; } attDefIndex = fGrammar.getNextAttributeDeclIndex(attDefIndex); } } return -1; } // getAttDef(QName,QName) // validation /** Root element specified. */ private void rootElementSpecified(QName rootElement) throws Exception { // this is what it used to be //if (fDynamicValidation && !fSeenDoctypeDecl) { //fValidating = false; if (fValidating) { // initialize the grammar to be the default one. if (fGrammar == null) { fGrammar = fGrammarResolver.getGrammar(""); //TO DO, for ericye debug only if (fGrammar == null && DEBUG_SCHEMA_VALIDATION) { System.out.println("Oops! no grammar is found for validation"); } if (fDynamicValidation && fGrammar==null) { fValidating = false; } if (fGrammar != null) { if (fGrammar instanceof DTDGrammar) { fGrammarIsDTDGrammar = true; fGrammarIsSchemaGrammar = false; } else if ( fGrammar instanceof SchemaGrammar ) { fGrammarIsSchemaGrammar = true; fGrammarIsDTDGrammar = false; } fGrammarNameSpaceIndex = fEmptyURI; } } if ( fGrammarIsDTDGrammar && ((DTDGrammar) fGrammar).getRootElementQName(fRootElement) ) { String root1 = fStringPool.toString(fRootElement.rawname); String root2 = fStringPool.toString(rootElement.rawname); if (!root1.equals(root2)) { reportRecoverableXMLError(XMLMessages.MSG_ROOT_ELEMENT_TYPE, XMLMessages.VC_ROOT_ELEMENT_TYPE, fRootElement.rawname, rootElement.rawname); } } } if (fNamespacesEnabled) { if (fNamespacesScope == null) { fNamespacesScope = new NamespacesScope(this); fNamespacesPrefix = fStringPool.addSymbol("xmlns"); fNamespacesScope.setNamespaceForPrefix(fNamespacesPrefix, -1); int xmlSymbol = fStringPool.addSymbol("xml"); int xmlNamespace = fStringPool.addSymbol("http: fNamespacesScope.setNamespaceForPrefix(xmlSymbol, xmlNamespace); } } } // rootElementSpecified(QName) /** Switchs to correct validating symbol tables when Schema changes.*/ private void switchGrammar(int newGrammarNameSpaceIndex) { Grammar tempGrammar = fGrammarResolver.getGrammar(fStringPool.toString(newGrammarNameSpaceIndex)); if (tempGrammar == null) { System.out.println(fStringPool.toString(newGrammarNameSpaceIndex) + " grammar not found"); //TO DO report error here } else { fGrammar = tempGrammar; if (fGrammar instanceof DTDGrammar) { fGrammarIsDTDGrammar = true; fGrammarIsSchemaGrammar = false; } else if ( fGrammar instanceof SchemaGrammar ) { fGrammarIsSchemaGrammar = true; fGrammarIsDTDGrammar = false; } } } /** Binds namespaces to the element and attributes. */ private void bindNamespacesToElementAndAttributes(QName element, XMLAttrList attrList) throws Exception { fNamespacesScope.increaseDepth(); int prefix = element.prefix; Vector schemaCandidateURIs = null; Hashtable locationUriPairs = null; if (fValidating) { schemaCandidateURIs = new Vector(); locationUriPairs = new Hashtable(); } if (fAttrListHandle != -1) { int index = attrList.getFirstAttr(fAttrListHandle); while (index != -1) { int attName = attrList.getAttrName(index); int attPrefix = attrList.getAttrPrefix(index); if (fStringPool.equalNames(attName, fXMLLang)) { /** Warning. */ /** Error. */ /** Fatal error. */ /** Returns a string of the location. */ /** Validates element and attributes. */ /** Character data in content. */ /** * Check that the content of an element is valid. * <p> * This is the method of primary concern to the validator. This method is called * upon the scanner reaching the end tag of an element. At that time, the * element's children must be structurally validated, so it calls this method. * The index of the element being checked (in the decl pool), is provided as * well as an array of element name indexes of the children. The validator must * confirm that this element can have these children in this order. * <p> * This can also be called to do 'what if' testing of content models just to see * if they would be valid. * <p> * Note that the element index is an index into the element decl pool, whereas * the children indexes are name indexes, i.e. into the string pool. * <p> * A value of -1 in the children array indicates a PCDATA node. All other * indexes will be positive and represent child elements. The count can be * zero, since some elements have the EMPTY content model and that must be * confirmed. * * @param elementIndex The index within the <code>ElementDeclPool</code> of this * element. * @param childCount The number of entries in the <code>children</code> array. * @param children The children of this element. Each integer is an index within * the <code>StringPool</code> of the child element name. An index * of -1 is used to indicate an occurrence of non-whitespace character * data. * * @return The value -1 if fully valid, else the 0 based index of the child * that first failed. If the value returned is equal to the number * of children, then additional content is required to reach a valid * ending state. * * @exception Exception Thrown on error. */ private int checkContent(int elementIndex, QName[] children, int childOffset, int childCount) throws Exception { // Get the element name index from the element // REVISIT: Validation final int elementType = fCurrentElement.rawname; if (DEBUG_PRINT_CONTENT) { String strTmp = fStringPool.toString(elementType); System.out.println("Name: "+strTmp+", "+ "Count: "+childCount+", "+ "ContentSpecType: " +fCurrentContentSpecType); //+getContentSpecAsString(elementIndex)); for (int index = childOffset; index < (childOffset+childCount) && index < 10; index++) { if (index == 0) { System.out.print(" ("); } String childName = (children[index].localpart == -1) ? "#PCDATA" : fStringPool.toString(children[index].localpart); if (index + 1 == childCount) { System.out.println(childName + ")"); } else if (index + 1 == 10) { System.out.println(childName + ",...)"); } else { System.out.print(childName + ","); } } } // Get out the content spec for this element final int contentType = fCurrentContentSpecType; // debugging //System.out.println("~~~~~~in checkContent, fCurrentContentSpecType : " + fCurrentContentSpecType); // Deal with the possible types of content. We try to optimized here // by dealing specially with content models that don't require the // full DFA treatment. if (contentType == XMLElementDecl.TYPE_EMPTY) { // If the child count is greater than zero, then this is // an error right off the bat at index 0. if (childCount != 0) { return 0; } } else if (contentType == XMLElementDecl.TYPE_ANY) { // This one is open game so we don't pass any judgement on it // at all. Its assumed to fine since it can hold anything. } else if (contentType == XMLElementDecl.TYPE_MIXED || contentType == XMLElementDecl.TYPE_CHILDREN) { // Get the content model for this element, faulting it in if needed XMLContentModel cmElem = null; try { cmElem = getContentModel(elementIndex); return cmElem.validateContent(children, childOffset, childCount); } catch(CMException excToCatch) { // REVISIT - Translate the caught exception to the protected error API int majorCode = excToCatch.getErrorCode(); fErrorReporter.reportError(fErrorReporter.getLocator(), ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN, majorCode, 0, null, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } } else if (contentType == -1) { reportRecoverableXMLError(XMLMessages.MSG_ELEMENT_NOT_DECLARED, XMLMessages.VC_ELEMENT_VALID, elementType); } else if (contentType == XMLElementDecl.TYPE_SIMPLE ) { XMLContentModel cmElem = null; try { // REVISIT: this might not be right //cmElem = getContentModel(elementIndex); //fTempQName.rawname = fTempQName.localpart = fStringPool.addString(fDatatypeBuffer.toString()); //return cmElem.validateContent(1, new QName[] { fTempQName }); fGrammar.getElementDecl(elementIndex, fTempElementDecl); DatatypeValidator dv = fTempElementDecl.datatypeValidator; if (dv == null) { System.out.println("Internal Error: this element have a simpletype "+ "but no datatypevalidator was found, element "+fTempElementDecl.name +",locapart: "+fStringPool.toString(fTempElementDecl.name.localpart)); } else { dv.validate(fDatatypeBuffer.toString()); } } //catch (CMException cme) { // System.out.println("Internal Error in datatype validation"); catch (InvalidDatatypeValueException idve) { fErrorReporter.reportError(fErrorReporter.getLocator(), SchemaMessageProvider.SCHEMA_DOMAIN, SchemaMessageProvider.DatatypeError, SchemaMessageProvider.MSG_NONE, new Object [] { idve.getMessage() }, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } /* boolean DEBUG_DATATYPES = false; if (DEBUG_DATATYPES) { System.out.println("Checking content of datatype"); String strTmp = fStringPool.toString(elementTypeIndex); int contentSpecIndex = fElementDeclPool.getContentSpec(elementIndex); XMLContentSpec csn = new XMLContentSpec(); fElementDeclPool.getContentSpecNode(contentSpecIndex, csn); String contentSpecString = fStringPool.toString(csn.value); System.out.println ( "Name: " + strTmp + ", Count: " + childCount + ", ContentSpec: " + contentSpecString ); for (int index = 0; index < childCount && index < 10; index++) { if (index == 0) System.out.print(" ("); String childName = (children[index] == -1) ? "#PCDATA" : fStringPool.toString(children[index]); if (index + 1 == childCount) System.out.println(childName + ")"); else if (index + 1 == 10) System.out.println(childName + ",...)"); else System.out.print(childName + ","); } } try { // REVISIT - integrate w/ error handling int contentSpecIndex = fElementDeclPool.getContentSpec(elementIndex); XMLContentSpec csn = new XMLContentSpec(); fElementDeclPool.getContentSpecNode(contentSpecIndex, csn); String type = fStringPool.toString(csn.value); DatatypeValidator v = fDatatypeRegistry.getValidatorFor(type); if (v != null) v.validate(fDatatypeBuffer.toString()); else System.out.println("No validator for datatype "+type); } catch (InvalidDatatypeValueException idve) { System.out.println("Incorrect datatype: "+idve.getMessage()); } catch (Exception e) { e.printStackTrace(); System.out.println("Internal error in datatype validation"); } */ } else { fErrorReporter.reportError(fErrorReporter.getLocator(), ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN, ImplementationMessages.VAL_CST, 0, null, XMLErrorReporter.ERRORTYPE_FATAL_ERROR); } // We succeeded return -1; } // checkContent(int,int,int[]):int /** * Check that all ID references were to ID attributes present in the document. * <p> * This method is a convenience call that allows the validator to do any id ref * checks above and beyond those done by the scanner. The scanner does the checks * specificied in the XML spec, i.e. that ID refs refer to ids which were * eventually defined somewhere in the document. * <p> * If the validator is for a Schema perhaps, which defines id semantics beyond * those of the XML specificiation, this is where that extra checking would be * done. For most validators, this is a no-op. * * @exception Exception Thrown on error. */ private void checkIdRefs() throws Exception { if (fIdRefs == null) return; Enumeration en = fIdRefs.keys(); while (en.hasMoreElements()) { Integer key = (Integer)en.nextElement(); if (fIdDefs == null || !fIdDefs.containsKey(key)) { Object[] args = { fStringPool.toString(key.intValue()) }; fErrorReporter.reportError(fErrorReporter.getLocator(), XMLMessages.XML_DOMAIN, XMLMessages.MSG_ELEMENT_WITH_ID_REQUIRED, XMLMessages.VC_IDREF, args, XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR); } } } // checkIdRefs() /** * Checks that all declared elements refer to declared elements * in their content models. This method calls out to the error * handler to indicate warnings. */ private void printChildren() { if (DEBUG_ELEMENT_CHILDREN) { System.out.print('['); for (int i = 0; i < fElementChildrenLength; i++) { System.out.print(' '); QName qname = fElementChildren[i]; if (qname != null) { System.out.print(fStringPool.toString(qname.rawname)); } else { System.out.print("null"); } if (i < fElementChildrenLength - 1) { System.out.print(", "); } System.out.flush(); } System.out.print(" ]"); System.out.println(); } } private void printStack() { if (DEBUG_ELEMENT_CHILDREN) { System.out.print('{'); for (int i = 0; i <= fElementDepth; i++) { System.out.print(' '); System.out.print(fElementChildrenOffsetStack[i]); if (i < fElementDepth) { System.out.print(", "); } System.out.flush(); } System.out.print(" }"); System.out.println(); } } // Interfaces /** * AttributeValidator. */ public interface AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValue, int attType, int enumHandle) throws Exception; } // interface AttributeValidator // Classes /** * AttValidatorCDATA. */ final class AttValidatorCDATA implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... return attValueHandle; } } // class AttValidatorCDATA /** * AttValidatorID. */ final class AttValidatorID implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); String newAttValue = attValue.trim(); if (fValidating) { // REVISIT - can we release the old string? if (newAttValue != attValue) { if (invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } attValueHandle = fStringPool.addSymbol(newAttValue); } else { attValueHandle = fStringPool.addSymbol(attValueHandle); } if (!XMLCharacterProperties.validName(newAttValue)) { reportRecoverableXMLError(XMLMessages.MSG_ID_INVALID, XMLMessages.VC_ID, fStringPool.toString(attribute.rawname), newAttValue); } // ID - check that the id value is unique within the document (V_TAG8) if (element.rawname != -1 && !addId(attValueHandle)) { reportRecoverableXMLError(XMLMessages.MSG_ID_NOT_UNIQUE, XMLMessages.VC_ID, fStringPool.toString(attribute.rawname), newAttValue); } } else if (newAttValue != attValue) { // REVISIT - can we release the old string? attValueHandle = fStringPool.addSymbol(newAttValue); } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if invalid standalong attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorID /** * AttValidatorIDREF. */ final class AttValidatorIDREF implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); String newAttValue = attValue.trim(); if (fValidating) { // REVISIT - can we release the old string? if (newAttValue != attValue) { if (invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } attValueHandle = fStringPool.addSymbol(newAttValue); } else { attValueHandle = fStringPool.addSymbol(attValueHandle); } if (!XMLCharacterProperties.validName(newAttValue)) { reportRecoverableXMLError(XMLMessages.MSG_IDREF_INVALID, XMLMessages.VC_IDREF, fStringPool.toString(attribute.rawname), newAttValue); } // IDREF - remember the id value if (element.rawname != -1) addIdRef(attValueHandle); } else if (newAttValue != attValue) { // REVISIT - can we release the old string? attValueHandle = fStringPool.addSymbol(newAttValue); } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if invalid standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorIDREF /** * AttValidatorIDREFS. */ final class AttValidatorIDREFS implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); StringTokenizer tokenizer = new StringTokenizer(attValue); StringBuffer sb = new StringBuffer(attValue.length()); boolean ok = true; if (tokenizer.hasMoreTokens()) { while (true) { String idName = tokenizer.nextToken(); if (fValidating) { if (!XMLCharacterProperties.validName(idName)) { ok = false; } // IDREFS - remember the id values if (element.rawname != -1) { addIdRef(fStringPool.addSymbol(idName)); } } sb.append(idName); if (!tokenizer.hasMoreTokens()) break; sb.append(' '); } } String newAttValue = sb.toString(); if (fValidating && (!ok || newAttValue.length() == 0)) { reportRecoverableXMLError(XMLMessages.MSG_IDREFS_INVALID, XMLMessages.VC_IDREF, fStringPool.toString(attribute.rawname), newAttValue); } if (!newAttValue.equals(attValue)) { attValueHandle = fStringPool.addString(newAttValue); if (fValidating && invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if invalid standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorIDREFS /** * AttValidatorENTITY. */ final class AttValidatorENTITY implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); String newAttValue = attValue.trim(); if (fValidating) { // REVISIT - can we release the old string? if (newAttValue != attValue) { if (invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } attValueHandle = fStringPool.addSymbol(newAttValue); } else { attValueHandle = fStringPool.addSymbol(attValueHandle); } // ENTITY - check that the value is an unparsed entity name (V_TAGa) if (!fEntityHandler.isUnparsedEntity(attValueHandle)) { reportRecoverableXMLError(XMLMessages.MSG_ENTITY_INVALID, XMLMessages.VC_ENTITY_NAME, fStringPool.toString(attribute.rawname), newAttValue); } } else if (newAttValue != attValue) { // REVISIT - can we release the old string? attValueHandle = fStringPool.addSymbol(newAttValue); } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if invalid standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorENTITY /** * AttValidatorENTITIES. */ final class AttValidatorENTITIES implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); StringTokenizer tokenizer = new StringTokenizer(attValue); StringBuffer sb = new StringBuffer(attValue.length()); boolean ok = true; if (tokenizer.hasMoreTokens()) { while (true) { String entityName = tokenizer.nextToken(); // ENTITIES - check that each value is an unparsed entity name (V_TAGa) if (fValidating && !fEntityHandler.isUnparsedEntity(fStringPool.addSymbol(entityName))) { ok = false; } sb.append(entityName); if (!tokenizer.hasMoreTokens()) { break; } sb.append(' '); } } String newAttValue = sb.toString(); if (fValidating && (!ok || newAttValue.length() == 0)) { reportRecoverableXMLError(XMLMessages.MSG_ENTITIES_INVALID, XMLMessages.VC_ENTITY_NAME, fStringPool.toString(attribute.rawname), newAttValue); } if (!newAttValue.equals(attValue)) { attValueHandle = fStringPool.addString(newAttValue); if (fValidating && invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if invalid standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorENTITIES /** * AttValidatorNMTOKEN. */ final class AttValidatorNMTOKEN implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); String newAttValue = attValue.trim(); if (fValidating) { // REVISIT - can we release the old string? if (newAttValue != attValue) { if (invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } attValueHandle = fStringPool.addSymbol(newAttValue); } else { attValueHandle = fStringPool.addSymbol(attValueHandle); } if (!XMLCharacterProperties.validNmtoken(newAttValue)) { reportRecoverableXMLError(XMLMessages.MSG_NMTOKEN_INVALID, XMLMessages.VC_NAME_TOKEN, fStringPool.toString(attribute.rawname), newAttValue); } } else if (newAttValue != attValue) { // REVISIT - can we release the old string? attValueHandle = fStringPool.addSymbol(newAttValue); } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if invalid standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorNMTOKEN /** * AttValidatorNMTOKENS. */ final class AttValidatorNMTOKENS implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); StringTokenizer tokenizer = new StringTokenizer(attValue); StringBuffer sb = new StringBuffer(attValue.length()); boolean ok = true; if (tokenizer.hasMoreTokens()) { while (true) { String nmtoken = tokenizer.nextToken(); if (fValidating && !XMLCharacterProperties.validNmtoken(nmtoken)) { ok = false; } sb.append(nmtoken); if (!tokenizer.hasMoreTokens()) { break; } sb.append(' '); } } String newAttValue = sb.toString(); if (fValidating && (!ok || newAttValue.length() == 0)) { reportRecoverableXMLError(XMLMessages.MSG_NMTOKENS_INVALID, XMLMessages.VC_NAME_TOKEN, fStringPool.toString(attribute.rawname), newAttValue); } if (!newAttValue.equals(attValue)) { attValueHandle = fStringPool.addString(newAttValue); if (fValidating && invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorNMTOKENS /** * AttValidatorNOTATION. */ final class AttValidatorNOTATION implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); String newAttValue = attValue.trim(); if (fValidating) { // REVISIT - can we release the old string? if (newAttValue != attValue) { if (invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } attValueHandle = fStringPool.addSymbol(newAttValue); } else { attValueHandle = fStringPool.addSymbol(attValueHandle); } // NOTATION - check that the value is in the AttDef enumeration (V_TAGo) if (!fStringPool.stringInList(enumHandle, attValueHandle)) { reportRecoverableXMLError(XMLMessages.MSG_ATTRIBUTE_VALUE_NOT_IN_LIST, XMLMessages.VC_NOTATION_ATTRIBUTES, fStringPool.toString(attribute.rawname), newAttValue, fStringPool.stringListAsString(enumHandle)); } } else if (newAttValue != attValue) { // REVISIT - can we release the old string? attValueHandle = fStringPool.addSymbol(newAttValue); } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if invalid standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorNOTATION /** * AttValidatorENUMERATION. */ final class AttValidatorENUMERATION implements AttributeValidator { // AttributeValidator methods /** Normalize. */ public int normalize(QName element, QName attribute, int attValueHandle, int attType, int enumHandle) throws Exception { // Normalize attribute based upon attribute type... String attValue = fStringPool.toString(attValueHandle); String newAttValue = attValue.trim(); if (fValidating) { // REVISIT - can we release the old string? if (newAttValue != attValue) { if (invalidStandaloneAttDef(element, attribute)) { reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE, XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION, fStringPool.toString(attribute.rawname), attValue, newAttValue); } attValueHandle = fStringPool.addSymbol(newAttValue); } else { attValueHandle = fStringPool.addSymbol(attValueHandle); } // ENUMERATION - check that value is in the AttDef enumeration (V_TAG9) if (!fStringPool.stringInList(enumHandle, attValueHandle)) { reportRecoverableXMLError(XMLMessages.MSG_ATTRIBUTE_VALUE_NOT_IN_LIST, XMLMessages.VC_ENUMERATION, fStringPool.toString(attribute.rawname), newAttValue, fStringPool.stringListAsString(enumHandle)); } } else if (newAttValue != attValue) { // REVISIT - can we release the old string? attValueHandle = fStringPool.addSymbol(newAttValue); } return attValueHandle; } // normalize(QName,QName,int,int,int):int // Package methods /** Returns true if invalid standalone attribute definition. */ boolean invalidStandaloneAttDef(QName element, QName attribute) { if (fStandaloneReader == -1) { return false; } // we are normalizing a default att value... this ok? if (element.rawname == -1) { return false; } return getAttDefIsExternal(element, attribute); } } // class AttValidatorENUMERATION } // class XMLValidator
package org.broad.igv.hic.matrix; import org.broad.igv.hic.MainWindow; import org.broad.igv.util.ObjectCache; import org.broad.igv.util.ParsingUtils; import org.broad.tribble.util.LittleEndianInputStream; import org.broad.tribble.util.LittleEndianOutputStream; import org.broad.tribble.util.SeekableStream; import org.broad.tribble.util.SeekableStreamFactory; import java.io.*; public class DiskResidentBlockMatrix implements BasicMatrix { String path; private String genome; private String chr1; private String chr2; private int binSize; float lowerValue; float upperValue; int dim; int blockSize; int remSize; // Dimension of last block int arrayStartPosition; boolean isLoading = false; ObjectCache<String, float[][]> blockDataCache = new ObjectCache<String, float[][]>(200); private int nFullBlocks; public DiskResidentBlockMatrix(String path) throws IOException { this.path = path; init(); } public String getChr1() { return chr1; } @Override public float getEntry(int row, int col) { int blockRowIdx = row / blockSize; int blockColIdx = col / blockSize; String key = "row" + blockRowIdx + "_col" + blockColIdx; float[][] blockData = blockDataCache.get(key); if (blockData == null) { MainWindow.getInstance().showGlassPane(); blockData = loadBlockData(blockRowIdx, blockColIdx); blockDataCache.put(key, blockData); MainWindow.getInstance().hideGlassPane(); } if (blockData == null) { return Float.NaN; } else { int rowRelative = row - blockRowIdx * blockSize; int colRelative = col - blockColIdx * blockSize; return blockData[rowRelative][colRelative]; } } public synchronized float[][] loadBlockData(int blockRowIdx, int blockColIdx) { String key = "row" + blockRowIdx + "_col" + blockColIdx; float [][] blockData = blockDataCache.get(key); if(blockData != null) return blockData; // In case this was calculated in another thread SeekableStream is = null; try { is = SeekableStreamFactory.getStreamFor(path); int pointsPerBlockRow = blockSize * dim; // Applies to all but the last row int rowDim = blockRowIdx < nFullBlocks ? blockSize : remSize; int colDim = blockColIdx < nFullBlocks ? blockSize : remSize; int l1 = blockRowIdx * pointsPerBlockRow; int l2 = blockColIdx * blockSize * rowDim; long startFilePosition = arrayStartPosition + (l1 + l2) * 4l; int nDataPoints = rowDim * colDim; int nBytes = nDataPoints * 4; byte[] byteArray = new byte[nBytes]; System.out.println("Loading block " + blockRowIdx + " " + blockColIdx + " rowDim=" + rowDim + " colDim=" + colDim + " nDataPoints=" + nDataPoints + " startFilePosition=" + startFilePosition + " endFilePosition=" + (startFilePosition + nBytes) + " thread=" + Thread.currentThread().getName()); is.seek(startFilePosition); is.readFully(byteArray); ByteArrayInputStream bis = new ByteArrayInputStream(byteArray); LittleEndianInputStream les = new LittleEndianInputStream(bis); blockData = new float[rowDim][colDim]; for (int r = 0; r < rowDim; r++) { for (int c = 0; c < colDim; c++) { float f = les.readFloat(); blockData[r][c] = f; } } blockDataCache.put(key, blockData); return blockData; } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. return null; } finally { if (is != null) try { is.close(); } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } } @Override public int getRowDimension() { return dim; //To change body of implemented methods use File | Settings | File Templates. } @Override public int getColumnDimension() { return dim; //To change body of implemented methods use File | Settings | File Templates. } public float getLowerValue() { return lowerValue; } public float getUpperValue() { return upperValue; } @Override public BasicMatrix getSubMatrix(int startRow, int endRow, int startCol, int endCol) { return null; } public int getRemSize() { return remSize; } private void init() throws IOException { // Peak at file to determine version BufferedInputStream bis = null; try { InputStream is = ParsingUtils.openInputStream(path); bis = new BufferedInputStream(is); LittleEndianInputStream les = new LittleEndianInputStream(bis); int bytePosition = 0; int magic = les.readInt(); // <= 6515048 bytePosition += 4; System.out.println("Magic number = " + magic); //if (magic != 6515048) <= ERROR // Version number int version = les.readInt(); bytePosition += 4; System.out.println("Version = " + version); genome = les.readString(); bytePosition += genome.length() + 1; System.out.println("Genome = " + genome); chr1 = les.readString(); bytePosition += chr1.length() + 1; System.out.println("Chr1 = " + chr1); chr2 = les.readString(); bytePosition += chr2.length() + 1; System.out.println("Chr2 = " + chr2); binSize = les.readInt(); bytePosition += 4; System.out.println("binSize = " + binSize); lowerValue = les.readFloat(); bytePosition += 4; System.out.println("Lower value = " + lowerValue); upperValue = les.readFloat(); bytePosition += 4; System.out.println("Upper value = " + upperValue); int nRows = les.readInt(); // # rows, assuming square matrix bytePosition += 4; System.out.println("Row count = " + nRows); int nCols = les.readInt(); bytePosition += 4; System.out.println("Column count = " + nRows); if (nRows == nCols) { dim = nRows; } else { throw new RuntimeException("Non-square matrices not supported"); } blockSize = les.readInt(); bytePosition += 4; System.out.println("Block size = " + blockSize); nFullBlocks = dim / blockSize; remSize = dim - nFullBlocks * blockSize; System.out.println(nFullBlocks + " " + remSize); this.arrayStartPosition = bytePosition; } finally { if (bis != null) bis.close(); } } public static void main(String [] args) throws IOException { DiskResidentRowMatrix bm = new DiskResidentRowMatrix("/Users/jrobinso/projects/hic/pearsons_14__14_250000.bin"); saveAsBlockMatrix(bm, 10, new File("/Users/jrobinso/projects/hic/block_test_chr14_1M.bin")); } public static void saveAsBlockMatrix(DiskResidentRowMatrix bm, int blockSize, File outputFile) throws IOException { LittleEndianOutputStream los = null; try { BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(outputFile)); los = new LittleEndianOutputStream(bos); los.writeInt(6515048); // magic number los.writeInt(2); // version los.writeString(bm.getGenome()); los.writeString(bm.getChr1()); los.writeString(bm.getChr2()); los.writeInt(bm.getBinSize()); los.writeFloat(bm.getLowerValue()); los.writeFloat(bm.getUpperValue()); los.writeInt(bm.getDim()); los.writeInt(bm.getDim()); los.writeInt(blockSize); int nFullBlocks = bm.getDim() / blockSize; int remSize = bm.getDim() - nFullBlocks * blockSize; // Loop through blocks for (int blockRowIdx = 0; blockRowIdx <= nFullBlocks; blockRowIdx++) { int startRow = blockRowIdx * blockSize; int rowDim = blockRowIdx < nFullBlocks ? blockSize : remSize; for (int blockColIdx = 0; blockColIdx <= nFullBlocks; blockColIdx++) { int startCol = blockColIdx * blockSize; int colDim = blockColIdx < nFullBlocks ? blockSize : remSize; for (int r = 0; r < rowDim; r++) { for (int c = 0; c < colDim; c++) { int row = startRow + r; int col = startCol + c; float value = bm.getEntry(row, col); los.writeFloat(value); } } } } } finally { if (los != null) los.close(); } } }
package io.moquette; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.handler.codec.CorruptedFrameException; import io.netty.handler.codec.mqtt.MqttMessage; import io.netty.util.Attribute; import io.netty.util.AttributeKey; import io.netty.util.AttributeMap; import org.slf4j.LoggerFactory; import java.io.UnsupportedEncodingException; /** * * @author andrea */ public class Utils { public static final int MAX_LENGTH_LIMIT = 268435455; public static final byte VERSION_3_1 = 3; public static final byte VERSION_3_1_1 = 4; static byte readMessageType(ByteBuf in) { byte h1 = in.readByte(); byte messageType = (byte) ((h1 & 0x00F0) >> 4); return messageType; } static boolean checkHeaderAvailability(ByteBuf in) { if (in.readableBytes() < 1) { return false; } // byte h1 = in.get(); // byte messageType = (byte) ((h1 & 0x00F0) >> 4); in.skipBytes(1); // skip the messageType byte int remainingLength = Utils.decodeRemainingLenght(in); if (remainingLength == -1) { return false; } // check remaining length if (in.readableBytes() < remainingLength) { return false; } // return messageType == type ? MessageDecoderResult.OK : MessageDecoderResult.NOT_OK; return true; } /** * Decode the variable remaining length as defined in MQTT v3.1 specification (section 2.1). * * @return the decoded length or -1 if needed more data to decode the length field. */ static int decodeRemainingLenght(ByteBuf in) { int multiplier = 1; int value = 0; byte digit; do { if (in.readableBytes() < 1) { return -1; } digit = in.readByte(); value += (digit & 0x7F) * multiplier; multiplier *= 128; } while ((digit & 0x80) != 0); return value; } static ByteBuf encodeRemainingLength(int value) throws CorruptedFrameException { if (value > MAX_LENGTH_LIMIT || value < 0) { throw new CorruptedFrameException("Value should in range 0.." + MAX_LENGTH_LIMIT + " found " + value); } ByteBuf encoded = Unpooled.buffer(4); byte digit; do { digit = (byte) (value % 128); value = value / 128; // if there are more digits to encode, set the top bit of this digit if (value > 0) { digit = (byte) (digit | 0x80); } encoded.writeByte(digit); } while (value > 0); return encoded; } /** * Load a string from the given buffer, reading first the two bytes of len and then the UTF-8 * bytes of the string. * * @return the decoded string or null if NEED_DATA */ static String decodeString(ByteBuf in) throws UnsupportedEncodingException { return new String(readFixedLengthContent(in), "UTF-8"); } /** * Read a byte array from the buffer, use two bytes as length information followed by length * bytes. */ static byte[] readFixedLengthContent(ByteBuf in) throws UnsupportedEncodingException { if (in.readableBytes() < 2) { return null; } int strLen = in.readUnsignedShort(); if (in.readableBytes() < strLen) { return null; } byte[] strRaw = new byte[strLen]; in.readBytes(strRaw); return strRaw; } /** * Return the IoBuffer with string encoded as MSB, LSB and UTF-8 encoded string content. */ public static ByteBuf encodeString(String str) { byte[] raw; try { raw = str.getBytes("UTF-8"); // NB every Java platform has got UTF-8 encoding by default, so this // exception are never raised. } catch (UnsupportedEncodingException ex) { LoggerFactory.getLogger(Utils.class).error(null, ex); return null; } return encodeFixedLengthContent(raw); } /** * Return the IoBuffer with string encoded as MSB, LSB and bytes array content. */ public static ByteBuf encodeFixedLengthContent(byte[] content) { ByteBuf out = Unpooled.buffer(2); out.writeShort(content.length); out.writeBytes(content); return out; } /** * Return the number of bytes to encode the given remaining length value */ static int numBytesToEncode(int len) { if (0 <= len && len <= 127) return 1; if (128 <= len && len <= 16383) return 2; if (16384 <= len && len <= 2097151) return 3; if (2097152 <= len && len <= 268435455) return 4; throw new IllegalArgumentException("value shoul be in the range [0..268435455]"); } static byte encodeFlags(MqttMessage message) { byte flags = 0; if (message.fixedHeader().isDup()) { flags |= 0x08; } if (message.fixedHeader().isRetain()) { flags |= 0x01; } flags |= ((message.fixedHeader().qosLevel().value() & 0x03) << 1); return flags; } // 3 = 3.1, 4 = 3.1.1 // static final AttributeKey<Integer> PROTOCOL_VERSION = AttributeKey.valueOf("version"); // static boolean isMQTT3_1_1(AttributeMap attrsMap) { // Attribute<Integer> versionAttr = attrsMap.attr(PROTOCOL_VERSION); // Integer protocolVersion = versionAttr.get(); // if (protocolVersion == null) { // return true; // return protocolVersion == VERSION_3_1_1; }
package org.opencms.configuration; import org.opencms.i18n.CmsLocaleComparator; import org.opencms.main.CmsLog; import org.opencms.main.OpenCms; import org.opencms.search.CmsSearchAnalyzer; import org.opencms.search.CmsSearchDocumentType; import org.opencms.search.CmsSearchIndex; import org.opencms.search.CmsSearchIndexSource; import org.opencms.search.CmsSearchManager; import org.opencms.search.fields.CmsSearchField; import org.opencms.search.fields.CmsSearchFieldConfiguration; import org.opencms.search.fields.CmsSearchFieldMapping; import org.opencms.search.fields.CmsSearchFieldMappingType; import org.opencms.util.CmsStringUtil; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import org.apache.commons.digester.Digester; import org.dom4j.Element; /** * Lucene search configuration class.<p> * * @author Thomas Weckert * * @version $Revision: 1.24 $ * * @since 6.0.0 */ public class CmsSearchConfiguration extends A_CmsXmlConfiguration implements I_CmsXmlConfiguration { /** The "analyzer" attribute. */ public static final String A_ANALYZER = "analyzer"; /** The "boost" attribute. */ public static final String A_BOOST = "boost"; /** The "displayName" attribute. */ public static final String A_DISPLAY = "display"; /** The "excerpt" attribute. */ public static final String A_EXCERPT = "excerpt"; /** The "index" attribute. */ public static final String A_INDEX = "index"; /** The "store" attribute. */ public static final String A_STORE = "store"; /** The name of the DTD for this configuration. */ public static final String CONFIGURATION_DTD_NAME = "opencms-search.dtd"; /** The name of the default XML file for this configuration. */ public static final String DEFAULT_XML_FILE_NAME = "opencms-search.xml"; /** Node name constant. */ public static final String N_ANALYZER = "analyzer"; /** Node name constant. */ public static final String N_ANALYZERS = "analyzers"; /** Node name constant. */ public static final String N_CLASS = "class"; /** Node name constant. */ public static final String N_CONFIGURATION = "configuration"; /** Node name constant. */ public static final String N_DESCRIPTION = "description"; /** Node name constant. */ public static final String N_DIRECTORY = "directory"; /** Node name constant. */ public static final String N_DOCUMENTTYPE = "documenttype"; /** Node name constant. */ public static final String N_DOCUMENTTYPES = "documenttypes"; /** Node name constant. */ public static final String N_DOCUMENTTYPES_INDEXED = "documenttypes-indexed"; /** Node name constant. */ public static final String N_EXCERPT = "excerpt"; /** Node name constant. */ public static final String N_EXTRACTION_CACHE_MAX_AGE = "extractionCacheMaxAge"; /** Node name constant. */ public static final String N_FIELD = "field"; /** Node name constant. */ public static final String N_FIELDCONFIGURATION = "fieldconfiguration"; /** Node name constant. */ public static final String N_FIELDCONFIGURATIONS = "fieldconfigurations"; /** Node name constant. */ public static final String N_FIELDS = "fields"; /** Node name constant. */ public static final String N_FORCEUNLOCK = "forceunlock"; /** Node name constant. */ public static final String N_HIGHLIGHTER = "highlighter"; /** Node name constant. */ public static final String N_INDEX = "index"; /** Node name constant. */ public static final String N_INDEXER = "indexer"; /** Node name constant. */ public static final String N_INDEXES = "indexes"; /** Node name constant. */ public static final String N_INDEXSOURCE = "indexsource"; /** Node name constant. */ public static final String N_INDEXSOURCES = "indexsources"; /** Node name constant. */ public static final String N_LOCALE = "locale"; /** Node name constant. */ public static final String N_MAPPING = "mapping"; /** Node name constant. */ public static final String N_MIMETYPE = "mimetype"; /** Node name constant. */ public static final String N_MIMETYPES = "mimetypes"; /** Node name constant. */ public static final String N_PROJECT = "project"; /** Node name constant. */ public static final String N_REBUILD = "rebuild"; /** Node name constant. */ public static final String N_RESOURCES = "resources"; /** Node name constant. */ public static final String N_RESOURCETYPE = "resourcetype"; /** Node name constant. */ public static final String N_RESOURCETYPES = "resourcetypes"; /** Node name constant. */ public static final String N_SEARCH = "search"; /** Node name constant. */ public static final String N_SOURCE = "source"; /** Node name constant. */ public static final String N_SOURCES = "sources"; /** Node name constant. */ public static final String N_STEMMER = "stemmer"; /** Node name constant. */ public static final String N_TIMEOUT = "timeout"; /** Node name constant. */ private static final String XPATH_SEARCH = "*/" + N_SEARCH; /** The configured search manager. */ private CmsSearchManager m_searchManager; /** * Public constructor, will be called by configuration manager.<p> */ public CmsSearchConfiguration() { setXmlFileName(DEFAULT_XML_FILE_NAME); if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_SEARCH_CONFIG_INIT_0)); } } /** * @see org.opencms.configuration.I_CmsXmlConfiguration#addXmlDigesterRules(org.apache.commons.digester.Digester) */ public void addXmlDigesterRules(Digester digester) { String xPath = null; // add finish rule digester.addCallMethod(XPATH_SEARCH, "initializeFinished"); // creation of the search manager digester.addObjectCreate(XPATH_SEARCH, A_CLASS, CmsSearchManager.class); // search manager finished digester.addSetNext(XPATH_SEARCH, "setSearchManager"); // directory rule digester.addCallMethod(XPATH_SEARCH + "/" + N_DIRECTORY, "setDirectory", 0); // timeout rule digester.addCallMethod(XPATH_SEARCH + "/" + N_TIMEOUT, "setTimeout", 0); // forceunlock rule digester.addCallMethod(XPATH_SEARCH + "/" + N_FORCEUNLOCK, "setForceunlock", 0); // rule for the max. char. lenght of the search result excerpt digester.addCallMethod(XPATH_SEARCH + "/" + N_EXCERPT, "setMaxExcerptLength", 0); // rule for the max. age of entries in the extraction cache digester.addCallMethod(XPATH_SEARCH + "/" + N_EXTRACTION_CACHE_MAX_AGE, "setExtractionCacheMaxAge", 0); // rule for the highlighter to highlight the search terms in the excerpt of the search result digester.addCallMethod(XPATH_SEARCH + "/" + N_HIGHLIGHTER, "setHighlighter", 0); // document type rule xPath = XPATH_SEARCH + "/" + N_DOCUMENTTYPES + "/" + N_DOCUMENTTYPE; digester.addObjectCreate(xPath, CmsSearchDocumentType.class); digester.addCallMethod(xPath + "/" + N_NAME, "setName", 0); digester.addCallMethod(xPath + "/" + N_CLASS, "setClassName", 0); digester.addCallMethod(xPath + "/" + N_MIMETYPES + "/" + N_MIMETYPE, "addMimeType", 0); digester.addCallMethod(xPath + "/" + N_RESOURCETYPES + "/" + N_RESOURCETYPE, "addResourceType", 0); digester.addSetNext(xPath, "addDocumentTypeConfig"); // analyzer rule xPath = XPATH_SEARCH + "/" + N_ANALYZERS + "/" + N_ANALYZER; digester.addObjectCreate(xPath, CmsSearchAnalyzer.class); digester.addCallMethod(xPath + "/" + N_CLASS, "setClassName", 0); digester.addCallMethod(xPath + "/" + N_STEMMER, "setStemmerAlgorithm", 0); digester.addCallMethod(xPath + "/" + N_LOCALE, "setLocaleString", 0); digester.addSetNext(xPath, "addAnalyzer"); // search index rule xPath = XPATH_SEARCH + "/" + N_INDEXES + "/" + N_INDEX; digester.addObjectCreate(xPath, A_CLASS, CmsSearchIndex.class); digester.addCallMethod(xPath + "/" + N_NAME, "setName", 0); digester.addCallMethod(xPath + "/" + N_REBUILD, "setRebuildMode", 0); digester.addCallMethod(xPath + "/" + N_PROJECT, "setProjectName", 0); digester.addCallMethod(xPath + "/" + N_LOCALE, "setLocaleString", 0); digester.addCallMethod(xPath + "/" + N_CONFIGURATION, "setFieldConfigurationName", 0); digester.addCallMethod(xPath + "/" + N_SOURCES + "/" + N_SOURCE, "addSourceName", 0); digester.addSetNext(xPath, "addSearchIndex"); // search index source rule xPath = XPATH_SEARCH + "/" + N_INDEXSOURCES + "/" + N_INDEXSOURCE; digester.addObjectCreate(xPath, CmsSearchIndexSource.class); digester.addCallMethod(xPath + "/" + N_NAME, "setName", 0); digester.addCallMethod(xPath + "/" + N_INDEXER, "setIndexerClassName", 1); digester.addCallParam(xPath + "/" + N_INDEXER, 0, N_CLASS); digester.addCallMethod(xPath + "/" + N_RESOURCES + "/" + N_RESOURCE, "addResourceName", 0); digester.addCallMethod(xPath + "/" + N_DOCUMENTTYPES_INDEXED + "/" + N_NAME, "addDocumentType", 0); digester.addSetNext(xPath, "addSearchIndexSource"); // field configuration rules xPath = XPATH_SEARCH + "/" + N_FIELDCONFIGURATIONS + "/" + N_FIELDCONFIGURATION; digester.addObjectCreate(xPath, A_CLASS, CmsSearchFieldConfiguration.class); digester.addCallMethod(xPath + "/" + N_NAME, "setName", 0); digester.addCallMethod(xPath + "/" + N_DESCRIPTION, "setDescription", 0); digester.addSetNext(xPath, "addFieldConfiguration"); xPath = xPath + "/" + N_FIELDS + "/" + N_FIELD; digester.addObjectCreate(xPath, CmsSearchField.class); digester.addCallMethod(xPath, "setName", 1); digester.addCallParam(xPath, 0, I_CmsXmlConfiguration.A_NAME); digester.addCallMethod(xPath, "setDisplayNameForConfiguration", 1); digester.addCallParam(xPath, 0, A_DISPLAY); digester.addCallMethod(xPath, "setStored", 1); digester.addCallParam(xPath, 0, A_STORE); digester.addCallMethod(xPath, "setIndexed", 1); digester.addCallParam(xPath, 0, A_INDEX); digester.addCallMethod(xPath, "setInExcerpt", 1); digester.addCallParam(xPath, 0, A_EXCERPT); digester.addCallMethod(xPath, "setAnalyzer", 1); digester.addCallParam(xPath, 0, A_ANALYZER); digester.addCallMethod(xPath, "setBoost", 1); digester.addCallParam(xPath, 0, A_BOOST); digester.addCallMethod(xPath, "setDefaultValue", 1); digester.addCallParam(xPath, 0, A_DEFAULT); digester.addSetNext(xPath, "addField"); xPath = xPath + "/" + N_MAPPING; digester.addObjectCreate(xPath, A_CLASS, CmsSearchFieldMapping.class); digester.addCallMethod(xPath, "setDefaultValue", 1); digester.addCallParam(xPath, 0, A_DEFAULT); digester.addCallMethod(xPath, "setType", 1); digester.addCallParam(xPath, 0, A_TYPE); digester.addCallMethod(xPath, "setParam", 0); digester.addSetNext(xPath, "addMapping"); // generic <param> parameter rules digester.addCallMethod( "*/" + I_CmsXmlConfiguration.N_PARAM, I_CmsConfigurationParameterHandler.ADD_PARAMETER_METHOD, 2); digester.addCallParam("*/" + I_CmsXmlConfiguration.N_PARAM, 0, I_CmsXmlConfiguration.A_NAME); digester.addCallParam("*/" + I_CmsXmlConfiguration.N_PARAM, 1); } /** * @see org.opencms.configuration.I_CmsXmlConfiguration#generateXml(org.dom4j.Element) */ public Element generateXml(Element parent) { // add <search> node Element searchElement = parent.addElement(N_SEARCH); if (OpenCms.getRunLevel() >= OpenCms.RUNLEVEL_3_SHELL_ACCESS) { // initialized OpenCms instance is available, use latest values m_searchManager = OpenCms.getSearchManager(); } // add class attribute (if required) if (!m_searchManager.getClass().equals(CmsSearchManager.class)) { searchElement.addAttribute(A_CLASS, m_searchManager.getClass().getName()); } // add <directory> element searchElement.addElement(N_DIRECTORY).addText(m_searchManager.getDirectory()); // add <timeout> element searchElement.addElement(N_TIMEOUT).addText(String.valueOf(m_searchManager.getTimeout())); // add <forceunlock> element if (m_searchManager.getForceunlock() != null) { searchElement.addElement(N_FORCEUNLOCK).addText(m_searchManager.getForceunlock().toString()); } // add <exerpt> element searchElement.addElement(N_EXCERPT).addText(String.valueOf(m_searchManager.getMaxExcerptLength())); // add <extractionCacheMaxAge> element searchElement.addElement(N_EXTRACTION_CACHE_MAX_AGE).addText( String.valueOf(m_searchManager.getExtractionCacheMaxAge())); // add <highlighter> element searchElement.addElement(N_HIGHLIGHTER).addText(m_searchManager.getHighlighter().getClass().getName()); // <documenttypes> Element documenttypesElement = searchElement.addElement(N_DOCUMENTTYPES); List docTypeKeyList = m_searchManager.getDocumentTypeConfigs(); Iterator docTypeIterator = docTypeKeyList.iterator(); while (docTypeIterator.hasNext()) { CmsSearchDocumentType currSearchDocType = (CmsSearchDocumentType)docTypeIterator.next(); // add the next <documenttype> element Element documenttypeElement = documenttypesElement.addElement(N_DOCUMENTTYPE); // add <name> element documenttypeElement.addElement(N_NAME).addText(currSearchDocType.getName()); // add <class> element documenttypeElement.addElement(N_CLASS).addText(currSearchDocType.getClassName()); // add <mimetypes> element Element mimetypesElement = documenttypeElement.addElement(N_MIMETYPES); // get the list of mimetypes to trigger the document factory class Iterator mimeTypesIterator = currSearchDocType.getMimeTypes().iterator(); while (mimeTypesIterator.hasNext()) { // add <mimetype> element(s) mimetypesElement.addElement(N_MIMETYPE).addText((String)mimeTypesIterator.next()); } // add <resourcetypes> element Element restypesElement = documenttypeElement.addElement(N_RESOURCETYPES); // get the list of Cms resource types to trigger the document factory Iterator resTypesIterator = currSearchDocType.getResourceTypes().iterator(); while (resTypesIterator.hasNext()) { // add <resourcetype> element(s) restypesElement.addElement(N_RESOURCETYPE).addText((String)resTypesIterator.next()); } } // </documenttypes> // <analyzers> Element analyzersElement = searchElement.addElement(N_ANALYZERS); List analyzerLocaleList = new ArrayList(m_searchManager.getAnalyzers().keySet()); // sort Analyzers in ascending order Collections.sort(analyzerLocaleList, CmsLocaleComparator.getComparator()); Iterator analyzersLocaleInterator = analyzerLocaleList.iterator(); while (analyzersLocaleInterator.hasNext()) { CmsSearchAnalyzer searchAnalyzer = m_searchManager.getCmsSearchAnalyzer((Locale)analyzersLocaleInterator.next()); // add the next <analyzer> element Element analyzerElement = analyzersElement.addElement(N_ANALYZER); // add <class> element analyzerElement.addElement(N_CLASS).addText(searchAnalyzer.getClassName()); if (searchAnalyzer.getStemmerAlgorithm() != null) { // add <stemmer> element analyzerElement.addElement(N_STEMMER).addText(searchAnalyzer.getStemmerAlgorithm()); } // add <locale> element analyzerElement.addElement(N_LOCALE).addText(searchAnalyzer.getLocale().toString()); } // </analyzers> // <indexes> Element indexesElement = searchElement.addElement(N_INDEXES); Iterator indexIterator = m_searchManager.getSearchIndexes().iterator(); while (indexIterator.hasNext()) { CmsSearchIndex searchIndex = (CmsSearchIndex)indexIterator.next(); // add the next <index> element Element indexElement = indexesElement.addElement(N_INDEX); // add class attribute (if required) if (!searchIndex.getClass().equals(CmsSearchIndex.class)) { indexElement.addAttribute(A_CLASS, searchIndex.getClass().getName()); } // add <name> element indexElement.addElement(N_NAME).addText(searchIndex.getName()); // add <rebuild> element indexElement.addElement(N_REBUILD).addText(searchIndex.getRebuildMode()); // add <project> element indexElement.addElement(N_PROJECT).addText(searchIndex.getProject()); // add <locale> element indexElement.addElement(N_LOCALE).addText(searchIndex.getLocale().toString()); // add <configuration> element String fieldConfigurationName = searchIndex.getFieldConfigurationName(); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(fieldConfigurationName)) { indexElement.addElement(N_CONFIGURATION).addText(fieldConfigurationName); } // add <sources> element Element sourcesElement = indexElement.addElement(N_SOURCES); // iterate above sourcenames Iterator sourcesIterator = searchIndex.getSourceNames().iterator(); while (sourcesIterator.hasNext()) { // add <source> element sourcesElement.addElement(N_SOURCE).addText((String)sourcesIterator.next()); } // iterate additional params Map indexConfiguration = searchIndex.getConfiguration(); if (indexConfiguration != null) { Iterator it = indexConfiguration.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry)it.next(); String name = entry.getKey().toString(); String value = entry.getValue().toString(); Element paramNode = indexElement.addElement(N_PARAM); paramNode.addAttribute(A_NAME, name); paramNode.addText(value); } } } // </indexes> // <indexsources> Element indexsourcesElement = searchElement.addElement(N_INDEXSOURCES); List indexSources = new ArrayList(m_searchManager.getSearchIndexSources().values()); Iterator indexsourceIterator = indexSources.iterator(); while (indexsourceIterator.hasNext()) { CmsSearchIndexSource searchIndexSource = (CmsSearchIndexSource)indexsourceIterator.next(); // add <indexsource> element(s) Element indexsourceElement = indexsourcesElement.addElement(N_INDEXSOURCE); // add <name> element indexsourceElement.addElement(N_NAME).addText(searchIndexSource.getName()); // add <indexer class=""> element Element indexerElement = indexsourceElement.addElement(N_INDEXER).addAttribute( N_CLASS, searchIndexSource.getIndexerClassName()); Map params = searchIndexSource.getParams(); Iterator paramIterator = params.entrySet().iterator(); while (paramIterator.hasNext()) { Map.Entry entry = (Map.Entry)paramIterator.next(); String name = (String)entry.getKey(); String value = (String)entry.getValue(); // add <param name=""> element(s) indexerElement.addElement(I_CmsXmlConfiguration.N_PARAM).addAttribute( I_CmsXmlConfiguration.A_NAME, name).addText(value); } // add <resources> element Element resourcesElement = indexsourceElement.addElement(N_RESOURCES); Iterator resourceIterator = searchIndexSource.getResourcesNames().iterator(); while (resourceIterator.hasNext()) { // add <resource> element(s) resourcesElement.addElement(N_RESOURCE).addText((String)resourceIterator.next()); } // add <documenttypes-indexed> element Element doctypes_indexedElement = indexsourceElement.addElement(N_DOCUMENTTYPES_INDEXED); Iterator doctypesIterator = searchIndexSource.getDocumentTypes().iterator(); while (doctypesIterator.hasNext()) { // add <name> element(s) doctypes_indexedElement.addElement(N_NAME).addText((String)doctypesIterator.next()); } } // </indexsources> // <fieldconfigurations> Element fieldConfigurationsElement = searchElement.addElement(N_FIELDCONFIGURATIONS); Iterator configs = m_searchManager.getFieldConfigurations().iterator(); while (configs.hasNext()) { CmsSearchFieldConfiguration fieldConfiguration = (CmsSearchFieldConfiguration)configs.next(); Element fieldConfigurationElement = fieldConfigurationsElement.addElement(N_FIELDCONFIGURATION); // add class attribute (if required) if (!fieldConfiguration.getClass().equals(CmsSearchFieldConfiguration.class)) { fieldConfigurationElement.addAttribute(A_CLASS, fieldConfiguration.getClass().getName()); } fieldConfigurationElement.addElement(N_NAME).setText(fieldConfiguration.getName()); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(fieldConfiguration.getDescription())) { fieldConfigurationElement.addElement(N_DESCRIPTION).setText(fieldConfiguration.getDescription()); } // search fields Element fieldsElement = fieldConfigurationElement.addElement(N_FIELDS); Iterator fields = fieldConfiguration.getFields().iterator(); while (fields.hasNext()) { CmsSearchField field = (CmsSearchField)fields.next(); Element fieldElement = fieldsElement.addElement(N_FIELD); fieldElement.addAttribute(A_NAME, field.getName()); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(field.getDisplayNameForConfiguration())) { fieldElement.addAttribute(A_DISPLAY, field.getDisplayNameForConfiguration()); } if (field.isCompressed()) { fieldElement.addAttribute(A_STORE, CmsSearchField.STR_COMPRESS); } else { fieldElement.addAttribute(A_STORE, String.valueOf(field.isStored())); } String index; if (field.isIndexed()) { if (field.isTokenizedAndIndexed()) { // index and tokenized index = CmsStringUtil.TRUE; } else { // indexed but not tokenized index = CmsSearchField.STR_UN_TOKENIZED; } } else { // not indexed at all index = CmsStringUtil.FALSE; } fieldElement.addAttribute(A_INDEX, index); if (field.getBoost() != CmsSearchField.BOOST_DEFAULT) { fieldElement.addAttribute(A_BOOST, String.valueOf(field.getBoost())); } if (field.isInExcerptAndStored()) { fieldElement.addAttribute(A_EXCERPT, String.valueOf(true)); } if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(field.getDefaultValue())) { fieldElement.addAttribute(A_DEFAULT, field.getDefaultValue()); } if (field.getAnalyzer() != null) { String className = field.getAnalyzer().getClass().getName(); if (className.startsWith(CmsSearchField.LUCENE_ANALYZER)) { className = className.substring(CmsSearchField.LUCENE_ANALYZER.length()); } fieldElement.addAttribute(A_ANALYZER, className); } // field mappings Iterator mappings = field.getMappings().iterator(); while (mappings.hasNext()) { CmsSearchFieldMapping mapping = (CmsSearchFieldMapping)mappings.next(); Element mappingElement = fieldElement.addElement(N_MAPPING); mappingElement.addAttribute(A_TYPE, mapping.getType().toString()); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(mapping.getDefaultValue())) { mappingElement.addAttribute(A_DEFAULT, mapping.getDefaultValue()); } // add class attribute (if required) if (!mapping.getClass().equals(CmsSearchFieldMapping.class) || (mapping.getType() == CmsSearchFieldMappingType.DYNAMIC)) { mappingElement.addAttribute(A_CLASS, mapping.getClass().getName()); } if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(mapping.getParam())) { mappingElement.setText(mapping.getParam()); } } } } // </fieldconfigurations> return searchElement; } /** * @see org.opencms.configuration.I_CmsXmlConfiguration#getDtdFilename() */ public String getDtdFilename() { return CONFIGURATION_DTD_NAME; } /** * Returns the generated search manager.<p> * * @return the generated search manager */ public CmsSearchManager getSearchManager() { return m_searchManager; } /** * Will be called when configuration of this object is finished.<p> */ public void initializeFinished() { if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_SEARCH_CONFIG_FINISHED_0)); } } /** * Sets the generated search manager.<p> * * @param manager the search manager to set */ public void setSearchManager(CmsSearchManager manager) { m_searchManager = manager; if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_SEARCH_MANAGER_FINISHED_0)); } } }
package org.pikater.core.agents.system; import jade.content.lang.Codec.CodecException; import jade.content.onto.OntologyException; import jade.content.onto.basic.Action; import jade.content.onto.basic.Result; import jade.domain.FIPAAgentManagement.NotUnderstoodException; import jade.domain.FIPAAgentManagement.RefuseException; import jade.lang.acl.ACLMessage; import jade.lang.acl.MessageTemplate; import jade.proto.AchieveREResponder; import jade.util.leap.ArrayList; import jade.util.leap.Iterator; import jade.util.leap.List; import org.apache.commons.codec.digest.DigestUtils; import org.pikater.shared.database.jpa.JPAFilemapping; //import org.pikater.shared.database.experiment. import org.pikater.shared.database.jpa.JPABatch; import org.pikater.shared.database.jpa.JPAResult; import org.pikater.shared.database.ConnectionProvider; import org.pikater.shared.utilities.logging.PikaterLogger; import org.pikater.shared.utilities.pikaterDatabase.Database; import org.pikater.shared.utilities.pikaterDatabase.daos.DAOs; import org.pikater.shared.utilities.pikaterDatabase.io.PostgreLargeObjectReader; import org.pikater.core.agents.PikaterAgent; import org.pikater.core.ontology.actions.BatchOntology; import org.pikater.core.ontology.actions.DataOntology; import org.pikater.core.ontology.batch.Batch; import org.pikater.core.ontology.batch.SaveBatch; import org.pikater.core.ontology.data.GetFile; import org.pikater.core.ontology.description.ComputationDescription; import org.postgresql.PGConnection; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.regex.Pattern; import org.apache.commons.codec.digest.DigestUtils; import org.pikater.core.agents.PikaterAgent; import org.pikater.core.ontology.actions.BatchOntology; import org.pikater.core.ontology.actions.DataOntology; import org.pikater.core.ontology.batch.Batch; import org.pikater.core.ontology.batch.SaveBatch; import org.pikater.core.ontology.data.GetFile; import org.pikater.core.ontology.description.ComputationDescription; import org.pikater.core.ontology.messages.Agent; import org.pikater.core.ontology.messages.DeleteTempFiles; import org.pikater.core.ontology.messages.Eval; import org.pikater.core.ontology.messages.GetAllMetadata; import org.pikater.core.ontology.messages.GetFileInfo; import org.pikater.core.ontology.messages.GetFiles; import org.pikater.core.ontology.messages.GetMetadata; import org.pikater.core.ontology.messages.GetTheBestAgent; import org.pikater.core.ontology.messages.ImportFile; import org.pikater.core.ontology.messages.LoadResults; import org.pikater.core.ontology.messages.Metadata; import org.pikater.core.ontology.messages.SaveMetadata; import org.pikater.core.ontology.messages.SaveResults; import org.pikater.core.ontology.messages.SavedResult; import org.pikater.core.ontology.messages.ShutdownDatabase; import org.pikater.core.ontology.messages.Task; import org.pikater.core.ontology.messages.TranslateFilename; import org.pikater.core.ontology.messages.UpdateMetadata; import org.pikater.shared.database.ConnectionProvider; import org.pikater.shared.database.jpa.JPABatch; import org.pikater.shared.database.jpa.JPAFilemapping; import org.pikater.shared.database.jpa.JPAResult; import org.pikater.shared.experiment.universalformat.UniversalComputationDescription; import org.pikater.shared.utilities.logging.PikaterLogger; import org.pikater.shared.utilities.pikaterDatabase.Database; import org.pikater.shared.utilities.pikaterDatabase.daos.DAOs; import org.pikater.shared.utilities.pikaterDatabase.io.PostgreLargeObjectReader; import org.postgresql.PGConnection; public class Agent_DataManager extends PikaterAgent { private final String DEFAULT_CONNECTION_PROVIDER = "defaultConnection"; private static final String CONNECTION_ARG_NAME = "connection"; private String connectionBean; private ConnectionProvider connectionProvider; private static final long serialVersionUID = 1L; Connection db; public static String dataFilesPath = "core" + System.getProperty("file.separator") + "data" + System.getProperty("file.separator") + "files" + System.getProperty("file.separator"); public static String datasetsPath = "core" + System.getProperty("file.separator") + "data" + System.getProperty("file.separator"); @Override protected void setup() { try { initDefault(); registerWithDF(); getContentManager().registerOntology(DataOntology.getInstance()); getContentManager().registerOntology(BatchOntology.getInstance()); if (containsArgument(CONNECTION_ARG_NAME)) { connectionBean = getArgumentValue(CONNECTION_ARG_NAME); } else { connectionBean = DEFAULT_CONNECTION_PROVIDER; } connectionProvider = (ConnectionProvider) context.getBean(connectionBean); log("Connecting to " + connectionProvider.getConnectionInfo() + "."); openDBConnection(); } catch (Exception e) { e.printStackTrace(); } File data = new File(dataFilesPath + "temp"); if (!data.exists()) { log("Creating directory: " + Agent_DataManager.dataFilesPath); if (data.mkdirs()) { log("Succesfully created directory: " + dataFilesPath); } else { logError("Error creating directory: " + dataFilesPath); } } try { db.close(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } MessageTemplate mt = MessageTemplate.MatchPerformative(ACLMessage.REQUEST); addBehaviour(new AchieveREResponder(this, mt) { private static final long serialVersionUID = 1L; @Override protected ACLMessage handleRequest(ACLMessage request) throws NotUnderstoodException, RefuseException { try { Action a = (Action) getContentManager().extractContent(request); if (a.getAction() instanceof ImportFile) { return RespondToImportFile(request, a); } if (a.getAction() instanceof TranslateFilename) { return RespondToTranslateFilename(request, a); } if (a.getAction() instanceof SaveBatch) { return RespondToSaveBatch(request, a); } if (a.getAction() instanceof SaveResults) { return RespondToSaveResults(request, a); } if (a.getAction() instanceof SaveMetadata) { return RespondToGetAclMessage(request, a); } if (a.getAction() instanceof GetMetadata) { return ReplyToGetMetadata(request, a); } if (a.getAction() instanceof GetAllMetadata) { return RespondToGetAllMetadata(request, a); } if (a.getAction() instanceof GetTheBestAgent) { return RespondToGetTheBestAgent(request, a); } if (a.getAction() instanceof GetFileInfo) { return RespondToGetFileInfo(request, a); } if (a.getAction() instanceof UpdateMetadata) { return ReplyToUpdateMetadata(request, a); } if (a.getAction() instanceof GetFiles) { return RespondToGetFiles(request, a); } if (a.getAction() instanceof LoadResults) { return RespondToLoadResults(request, a); } if (a.getAction() instanceof DeleteTempFiles) { return RespondToDeleteTempFiles(request); } if (a.getAction() instanceof ShutdownDatabase) { return RespondToShutdownDatabase(request); } if (a.getAction() instanceof GetFile) { return RespondToGetFile(request, a); } } catch (OntologyException e) { e.printStackTrace(); logError("Problem extracting content: " + e.getMessage()); } catch (CodecException e) { e.printStackTrace(); logError("Codec problem: " + e.getMessage()); } catch (SQLException e) { e.printStackTrace(); logError("SQL error: " + e.getMessage()); } catch (Exception e) { e.printStackTrace(); } ACLMessage failure = request.createReply(); failure.setPerformative(ACLMessage.FAILURE); logError("Failure responding to request: " + request.getContent()); return failure; } }); } private ACLMessage RespondToSaveBatch(ACLMessage request, Action a) { System.out.println("RespondToSaveBatch"); SaveBatch saveBatch = (SaveBatch) a.getAction(); Batch batch = saveBatch.getBatch(); ComputationDescription description = batch.getDescription(); UniversalComputationDescription uDescription = description.ExportUniversalComputationDescription(); int userId = batch.getOwnerID(); String batchXml = uDescription.exportXML(); JPABatch batchJpa = new JPABatch(); batchJpa.setName(batch.getName()); batchJpa.setNote(batch.getNote()); batchJpa.setPriority(batch.getPriority()); Database database = new Database(emf, null); database.saveBatch(userId, batchJpa, batchXml); ACLMessage reply = request.createReply(); reply.setPerformative(ACLMessage.INFORM); Result r = new Result(a, "OK"); try { getContentManager().fillContent(reply, r); } catch (CodecException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (OntologyException e) { // TODO Auto-generated catch block e.printStackTrace(); } return reply; } private ACLMessage RespondToGetFile(ACLMessage request, Action a) throws CodecException, OntologyException, ClassNotFoundException, SQLException { String hash = ((GetFile)a.getAction()).getHash(); try { openDBConnection(); PostgreLargeObjectReader reader = new Database(emf, (PGConnection) db).getLargeObjectReader(hash); File temp = new File(dataFilesPath + "temp" + System.getProperty("file.separator") + hash); FileOutputStream out = new FileOutputStream(temp); try { byte[] buf = new byte[100*1024]; int read; while ((read = reader.read(buf, 0, buf.length)) > 0) { out.write(buf, 0, read); } temp.renameTo(new File(dataFilesPath + hash)); } finally { db.close(); out.close(); } } catch (IOException e) { e.printStackTrace(); } ACLMessage reply = request.createReply(); reply.setPerformative(ACLMessage.INFORM); Result r = new Result(a, "OK"); getContentManager().fillContent(reply, r); return reply; } /************************************************************************************************ * Obsolete methods * */ private ACLMessage RespondToImportFile(ACLMessage request, Action a) throws IOException, CodecException, OntologyException, SQLException, ClassNotFoundException { ImportFile im = (ImportFile) a.getAction(); String pathPrefix = dataFilesPath + "temp" + System.getProperty("file.separator"); if (im.isTempFile()) { FileWriter fw = new FileWriter(pathPrefix + im.getExternalFilename()); fw.write(im.getFileContent()); fw.close(); ACLMessage reply = request.createReply(); reply.setPerformative(ACLMessage.INFORM); Result r = new Result(im, pathPrefix + im.getExternalFilename()); getContentManager().fillContent(reply, r); return reply; } if (im.getFileContent() == null) { String path = System.getProperty("user.dir") + System.getProperty("file.separator") + "core" + System.getProperty("file.separator"); path += "incoming" + System.getProperty("file.separator") + im.getExternalFilename(); String internalFilename = md5(path); /** * CREATE??? a new DataSet with empty metadata */ emptyMetadataToDB(internalFilename, im.getExternalFilename()); File f = new File(path); if(DAOs.filemappingDAO.fileExists(internalFilename)){ f.delete(); PikaterLogger.getLogger(Agent_DataManager.class).warn("File " + internalFilename + " already present in the database"); }else{ JPAFilemapping fm=new JPAFilemapping(); fm.setUser(DAOs.userDAO.getByID(im.getUserID()).get(0)); fm.setInternalfilename(internalFilename); fm.setExternalfilename(im.getExternalFilename()); DAOs.filemappingDAO.storeEntity(fm); String newName = Agent_DataManager.dataFilesPath + internalFilename; move(f, new File(newName)); } ACLMessage reply = request.createReply(); reply.setPerformative(ACLMessage.INFORM); Result r = new Result(im, internalFilename); getContentManager().fillContent(reply, r); return reply; } else { String fileContent = im.getFileContent(); String fileName = im.getExternalFilename(); String internalFilename = DigestUtils.md5Hex(fileContent); emptyMetadataToDB(internalFilename, fileName); if(DAOs.filemappingDAO.fileExists(internalFilename)){ PikaterLogger.getLogger(Agent_DataManager.class).warn("File " + internalFilename + " already present in the database"); }else{ JPAFilemapping fm=new JPAFilemapping(); fm.setUser(DAOs.userDAO.getByID(im.getUserID()).get(0)); fm.setInternalfilename(internalFilename); fm.setExternalfilename(im.getExternalFilename()); DAOs.filemappingDAO.storeEntity(fm); String newName = Agent_DataManager.dataFilesPath + internalFilename; FileWriter file = new FileWriter(newName); file.write(fileContent); file.close(); PikaterLogger.getLogger(Agent_DataManager.class).info("Created file: " + newName); } ACLMessage reply = request.createReply(); reply.setPerformative(ACLMessage.INFORM); Result r = new Result(im, internalFilename); getContentManager().fillContent(reply, r); db.close(); return reply; } } private ACLMessage RespondToTranslateFilename(ACLMessage request, Action a) throws SQLException, ClassNotFoundException, CodecException, OntologyException { TranslateFilename tf = (TranslateFilename) a.getAction(); java.util.List<JPAFilemapping> files=null; String internalFilename = "error"; if (tf.getInternalFilename() == null) { files=DAOs.filemappingDAO.getByUserIDandExternalFilename(tf.getUserID(), tf.getExternalFilename()); if(files.size()>0){ internalFilename=files.get(0).getInternalfilename(); } else { String pathPrefix = dataFilesPath + "temp" + System.getProperty("file.separator"); String tempFileName = pathPrefix + tf.getExternalFilename(); if (new File(tempFileName).exists()) internalFilename = "temp" + System.getProperty("file.separator") + tf.getExternalFilename(); } } else { files=DAOs.filemappingDAO.getByUserIDandInternalFilename(tf.getUserID(), tf.getInternalFilename()); if(files.size()>0){ internalFilename=files.get(0).getExternalfilename(); } else { String pathPrefix = dataFilesPath + "temp" + System.getProperty("file.separator"); String tempFileName = pathPrefix + tf.getExternalFilename(); if (new File(tempFileName).exists()) internalFilename = "temp" + System.getProperty("file.separator") + tf.getExternalFilename(); } } ACLMessage reply = request.createReply(); reply.setPerformative(ACLMessage.INFORM); Result r = new Result(tf, internalFilename); getContentManager().fillContent(reply, r); return reply; } private ACLMessage RespondToSaveResults(ACLMessage request, Action a) throws SQLException, ClassNotFoundException { SaveResults sr = (SaveResults) a.getAction(); Task res = sr.getTask(); try { JPAResult jparesult = new JPAResult(); jparesult.setAgentName(res.getAgent().getName()); // nesedi na novy model kde jsou ciselne ID agentu - stary model // pouziva Stringy... // jparesult.setAgentTypeId(res.getAgent().getType()); jparesult.setOptions(res.getAgent().optionsToString()); // cim se ma naplnit serializedFilename? // co tyhle hodnoty co v novem model nejsou? // query += "\'" + // res.getData().removePath(res.getData().getTrain_file_name()) + // query += "\'" + // res.getData().removePath(res.getData().getTest_file_name()) + float Error_rate = Float.MAX_VALUE; float Kappa_statistic = Float.MAX_VALUE; float Mean_absolute_error = Float.MAX_VALUE; float Root_mean_squared_error = Float.MAX_VALUE; float Relative_absolute_error = Float.MAX_VALUE; // percent float Root_relative_squared_error = Float.MAX_VALUE; // percent int duration = Integer.MAX_VALUE; // miliseconds float durationLR = Float.MAX_VALUE; Iterator itr = res.getResult().getEvaluations().iterator(); while (itr.hasNext()) { Eval next_eval = (Eval) itr.next(); if (next_eval.getName().equals("error_rate")) { Error_rate = next_eval.getValue(); } if (next_eval.getName().equals("kappa_statistic")) { Kappa_statistic = next_eval.getValue(); } if (next_eval.getName().equals("mean_absolute_error")) { Mean_absolute_error = next_eval.getValue(); } if (next_eval.getName().equals("root_mean_squared_error")) { Root_mean_squared_error = next_eval.getValue(); } if (next_eval.getName().equals("relative_absolute_error")) { Relative_absolute_error = next_eval.getValue(); } if (next_eval.getName().equals("root_relative_squared_error")) { Root_relative_squared_error = next_eval.getValue(); } if (next_eval.getName().equals("duration")) { duration = (int) next_eval.getValue(); } if (next_eval.getName().equals("durationLR")) { durationLR = (float) next_eval.getValue(); } } String start = getDateTime(); String finish = getDateTime(); if (res.getStart() != null) { start = res.getStart(); } if (res.getFinish() != null){ finish = res.getFinish(); } jparesult.setErrorRate(Error_rate); jparesult.setKappaStatistic(Kappa_statistic); jparesult.setMeanAbsoluteError(Mean_absolute_error); jparesult.setRootMeanSquaredError(Root_mean_squared_error); jparesult.setRelativeAbsoluteError(Relative_absolute_error); jparesult.setRootRelativeSquaredError(Root_relative_squared_error); jparesult.setStart(new Date(Timestamp.valueOf(start).getTime())); // query += "\'" + Timestamp.valueOf(res.getStart()) + "\',"; jparesult.setFinish(new Date(Timestamp.valueOf(finish).getTime())); // query += "\'" + Timestamp.valueOf(res.getFinish()) + "\',"; // v novem modelu tohle neni // query += "\'" + duration + "\',"; // query += "\'" + durationLR + "\',"; // je to ono? jparesult.setSerializedFileName(res.getResult().getObject_filename()); // query += "\'" + res.getResult().getObject_filename() + "\', "; // jparesult.setExperiment(TODO); // query += "\'" + res.getId().getIdentificator() + "\',"; // TODO - // pozor - neni jednoznacne, pouze pro jednoho managera // query += "\'" + res.getProblem_name() + "\',"; jparesult.setNote(res.getNote()); DAOs.resultDAO.storeEntity(jparesult); PikaterLogger.getLogger(Agent_DataManager.class.getCanonicalName()).info("Persisted JPAResult"); }catch(Exception e){ PikaterLogger.getLogger(Agent_DataManager.class.getCanonicalName()).error("Error in SaveResults", e);; } ACLMessage reply = request.createReply(); reply.setPerformative(ACLMessage.INFORM); return reply; } private String getDateTime() { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS"); Date date = new Date(); return dateFormat.format(date); } private ACLMessage RespondToGetAclMessage(ACLMessage request, Action a) throws SQLException, ClassNotFoundException { SaveMetadata saveMetadata = (SaveMetadata) a.getAction(); Metadata metadata = saveMetadata.getMetadata(); openDBConnection(); Statement stmt = db.createStatement(); String query = "UPDATE metadata SET "; query += "numberOfInstances=" + metadata.getNumber_of_instances() + ", "; query += "numberOfAttributes=" + metadata.getNumber_of_attributes() + ", "; query += "missingValues=" + metadata.getMissing_values(); if (metadata.getAttribute_type() != null) { query += ", attributeType=\'" + metadata.getAttribute_type() + "\' "; } if (metadata.getDefault_task() != null) { query += ", defaultTask=\'" + metadata.getDefault_task() + "\' "; } // the external file name contains part o the path // (db/files/name) -> split and use only the [2] part query += " WHERE internalFilename=\'" + metadata.getInternal_name().split(Pattern.quote(System.getProperty("file.separator")))[2] + "\'"; log("Executing query: " + query); stmt.executeUpdate(query); ACLMessage reply = request.createReply(); reply.setPerformative(ACLMessage.INFORM); db.close(); return reply; } private ACLMessage RespondToGetAllMetadata(ACLMessage request, Action a) throws SQLException, ClassNotFoundException, CodecException, OntologyException { GetAllMetadata gm = (GetAllMetadata) a.getAction(); openDBConnection(); Statement stmt = db.createStatement(); String query; if (gm.getResults_required()) { query = "SELECT * FROM metadata WHERE EXISTS " + "(SELECT * FROM results WHERE results.dataFile=metadata.internalFilename)"; if (gm.getExceptions() != null) { Iterator itr = gm.getExceptions().iterator(); while (itr.hasNext()) { Metadata m = (Metadata) itr.next(); query += " AND "; query += "internalFilename <> '" + new File(m.getInternal_name()).getName() + "'"; } } query += " ORDER BY externalFilename"; } else { query = "SELECT * FROM metadata"; if (gm.getExceptions() != null) { query += " WHERE "; boolean first = true; Iterator itr = gm.getExceptions().iterator(); while (itr.hasNext()) { Metadata m = (Metadata) itr.next(); if (!first) { query += " AND "; } query += "internalFilename <> '" + new File(m.getInternal_name()).getName() + "'"; first = false; } } query += " ORDER BY externalFilename"; } List allMetadata = new ArrayList(); ResultSet rs = stmt.executeQuery(query); while (rs.next()) { Metadata m = new Metadata(); m.setAttribute_type(rs.getString("attributeType")); m.setDefault_task(rs.getString("defaultTask")); m.setExternal_name(rs.getString("externalFilename")); m.setInternal_name(rs.getString("internalFilename")); m.setMissing_values(rs.getBoolean("missingValues")); m.setNumber_of_attributes(rs.getInt("numberOfAttributes")); m.setNumber_of_instances(rs.getInt("numberOfInstances")); allMetadata.add(m); } log("Executing query: " + query); ACLMessage reply = request.createReply(); reply.setPerformative(ACLMessage.INFORM); Result _result = new Result(a.getAction(), allMetadata); getContentManager().fillContent(reply, _result); db.close(); return reply; } private ACLMessage RespondToGetTheBestAgent(ACLMessage request, Action a) throws SQLException, ClassNotFoundException, CodecException, OntologyException { GetTheBestAgent g = (GetTheBestAgent) a.getAction(); String name = g.getNearest_file_name(); openDBConnection(); Statement stmt = db.createStatement(); String query = "SELECT * FROM results " + "WHERE dataFile =\'" + name + "\'" + " AND errorRate = (SELECT MIN(errorRate) FROM results " + "WHERE dataFile =\'" + name + "\')"; log("Executing query: " + query); ResultSet rs = stmt.executeQuery(query); if (!rs.isBeforeFirst()) { ACLMessage reply = request.createReply(); reply.setPerformative(ACLMessage.FAILURE); reply.setContent("There are no results for this file in the database."); db.close(); return reply; } rs.next(); Agent agent = new Agent(); agent.setName(rs.getString("agentName")); agent.setType(rs.getString("agentType")); agent.setOptions(agent.stringToOptions(rs.getString("options"))); agent.setGui_id(rs.getString("errorRate")); ACLMessage reply = request.createReply(); reply.setPerformative(ACLMessage.INFORM); Result _result = new Result(a.getAction(), agent); getContentManager().fillContent(reply, _result); db.close(); return reply; } private ACLMessage RespondToGetFileInfo(ACLMessage request, Action a) throws SQLException, ClassNotFoundException, CodecException, OntologyException { GetFileInfo gfi = (GetFileInfo) a.getAction(); String query = "SELECT * FROM filemetadata WHERE " + gfi.toSQLCondition(); openDBConnection(); Statement stmt = db.createStatement(); log("Executing query: " + query); ResultSet rs = stmt.executeQuery(query); List fileInfos = new ArrayList(); while (rs.next()) { Metadata m = new Metadata(); m.setAttribute_type(rs.getString("attributeType")); m.setDefault_task(rs.getString("defaultTask")); m.setExternal_name(rs.getString("externalFilename")); m.setInternal_name(rs.getString("internalFilename")); m.setMissing_values(rs.getBoolean("missingValues")); m.setNumber_of_attributes(rs.getInt("numberOfAttributes")); m.setNumber_of_instances(rs.getInt("numberOfInstances")); fileInfos.add(m); } Result r = new Result(a.getAction(), fileInfos); ACLMessage reply = request.createReply(); reply.setPerformative(ACLMessage.INFORM); getContentManager().fillContent(reply, r); db.close(); return reply; } private ACLMessage RespondToGetFiles(ACLMessage request, Action a) throws SQLException, ClassNotFoundException, CodecException, OntologyException { GetFiles gf = (GetFiles) a.getAction(); java.util.List<JPAFilemapping> userFiles=DAOs.filemappingDAO.getByUserID(gf.getUserID()); ArrayList files = new ArrayList(); for(JPAFilemapping fm:userFiles){ files.add(fm.getExternalfilename()); } Result r = new Result(a.getAction(), files); ACLMessage reply = request.createReply(); reply.setPerformative(ACLMessage.INFORM); getContentManager().fillContent(reply, r); db.close(); return reply; } private ACLMessage RespondToShutdownDatabase(ACLMessage request) throws SQLException, ClassNotFoundException { PikaterLogger.getLogger(Agent_DataManager.class).warn("Database SHUTDOWN initiated in DataManager"); ACLMessage reply = request.createReply(); reply.setPerformative(ACLMessage.INFORM); return reply; } private ACLMessage RespondToDeleteTempFiles(ACLMessage request) { String path = this.dataFilesPath + "temp" + System.getProperty("file.separator"); File tempDir = new File(path); String[] files = tempDir.list(); if (files != null) { for (String file : files) { File d = new File(path + file); d.delete(); } } ACLMessage reply = request.createReply(); reply.setPerformative(ACLMessage.INFORM); return reply; } private ACLMessage RespondToLoadResults(ACLMessage request, Action a) throws SQLException, ClassNotFoundException, CodecException, OntologyException { LoadResults lr = (LoadResults) a.getAction(); String query = "SELECT * FROM resultsExternal " + lr.asSQLCondition(); log(query); openDBConnection(); Statement stmt = db.createStatement(); ResultSet rs = stmt.executeQuery(query); ArrayList results = new ArrayList(); while (rs.next()) { SavedResult sr = new SavedResult(); sr.setAgentType(rs.getString("agentType")); sr.setAgentOptions(rs.getString("options")); sr.setTrainFile(rs.getString("trainFileExt")); sr.setTestFile(rs.getString("testFileExt")); sr.setErrorRate(rs.getDouble("errorRate")); sr.setKappaStatistic(rs.getDouble("kappaStatistic")); sr.setMeanAbsError(rs.getDouble("meanAbsoluteError")); sr.setRMSE(rs.getDouble("rootMeanSquaredError")); sr.setRootRelativeSquaredError(rs.getDouble("rootRelativeSquaredError")); sr.setRelativeAbsoluteError(rs.getDouble("relativeAbsoluteError")); sr.setDate("nodate"); results.add(sr); } Result r = new Result(a.getAction(), results); ACLMessage reply = request.createReply(); reply.setPerformative(ACLMessage.INFORM); getContentManager().fillContent(reply, r); db.close(); return reply; } private void openDBConnection() throws SQLException, ClassNotFoundException { db = connectionProvider.getConnection(); } private void emptyMetadataToDB(String internalFilename, String externalFilename) throws SQLException, ClassNotFoundException { openDBConnection(); Statement stmt = db.createStatement(); String query = "SELECT COUNT(*) AS number FROM metadata WHERE internalFilename = \'" + internalFilename + "\'"; String query1 = "SELECT COUNT(*) AS number FROM jpafilemapping WHERE internalFilename = \'" + internalFilename + "\'"; log("Executing query " + query); log("Executing query " + query1); ResultSet rs = stmt.executeQuery(query); rs.next(); int isInMetadata = rs.getInt("number"); ResultSet rs1 = stmt.executeQuery(query1); rs1.next(); int isInFileMapping = rs1.getInt("number"); if (isInMetadata == 0 && isInFileMapping == 1) { log("Executing query: " + query); query = "INSERT into metadata (externalFilename, internalFilename, defaultTask, " + "attributeType, numberOfInstances, numberOfAttributes, missingValues)" + "VALUES (\'" + externalFilename + "\',\'" + internalFilename + "\', null, " + "null, 0, 0, false)"; stmt.executeUpdate(query); } // stmt.close(); db.close(); } private ACLMessage ReplyToGetMetadata(ACLMessage request, Action a) throws SQLException, ClassNotFoundException, CodecException, OntologyException { GetMetadata gm = (GetMetadata) a.getAction(); openDBConnection(); Statement stmt = db.createStatement(); String query = "SELECT * FROM metadata WHERE internalfilename = '" + gm.getInternal_filename() + "'"; Metadata m = new Metadata(); ResultSet rs = stmt.executeQuery(query); while (rs.next()) { m.setAttribute_type(rs.getString("attributeType")); m.setDefault_task(rs.getString("defaultTask")); m.setExternal_name(rs.getString("externalFilename")); m.setInternal_name(rs.getString("internalFilename")); m.setMissing_values(rs.getBoolean("missingValues")); m.setNumber_of_attributes(rs.getInt("numberOfAttributes")); m.setNumber_of_instances(rs.getInt("numberOfInstances")); } log("Executing query: " + query); ACLMessage reply = request.createReply(); reply.setPerformative(ACLMessage.INFORM); Result _result = new Result(a.getAction(), m); getContentManager().fillContent(reply, _result); db.close(); return reply; } private ACLMessage ReplyToUpdateMetadata(ACLMessage request, Action a) throws SQLException, ClassNotFoundException { UpdateMetadata updateMetadata = (UpdateMetadata) a.getAction(); Metadata metadata = updateMetadata.getMetadata(); openDBConnection(); Statement stmt = db.createStatement(); /** JPAGlobalMetaData newValues=new JPAGlobalMetaData(); newValues.setDefaultTaskType(DAOs.taskTypeDAO.createOrGetByName(metadata.getDefault_task())); newValues.setNumberofInstances(metadata.getNumber_of_instances()); java.util.List<JPADataSetLO> dslos=DAOs.dataSetDAO.getByHash(metadata.getInternal_name()); if(dslos.size()>0){ JPAGlobalMetaData globMD=dslos.get(0).getGlobalMetaData(); if(globMD==null){ glo } } **/ String query = "UPDATE metadata SET "; query += "numberOfInstances=" + metadata.getNumber_of_instances() + ", "; query += "numberOfAttributes=" + metadata.getNumber_of_attributes() + ", "; query += "missingValues=" + metadata.getMissing_values() + ""; if (metadata.getAttribute_type() != null) { query += ", attributeType=\'" + metadata.getAttribute_type() + "\' "; } if (metadata.getDefault_task() != null) { query += ", defaultTask=\'" + metadata.getDefault_task() + "\' "; } query += " WHERE internalFilename =\'" + metadata.getInternal_name() + "\'"; log("Executing query: " + query); stmt.executeUpdate(query); ACLMessage reply = request.createReply(); reply.setPerformative(ACLMessage.INFORM); db.close(); return reply; } // Move file (src) to File/directory dest. public static synchronized void move(File src, File dest) throws FileNotFoundException, IOException { copy(src, dest); src.delete(); } // Copy file (src) to File/directory dest. public static synchronized void copy(File src, File dest) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dest); // Transfer bytes from in to out byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); } private String md5(String path) { StringBuffer sb = null; try { FileInputStream fs = new FileInputStream(path); sb = new StringBuffer(); int ch; while ((ch = fs.read()) != -1) { sb.append((char) ch); } fs.close(); } catch (FileNotFoundException e) { e.printStackTrace(); logError("File not found: " + path + " -- " + e.getMessage()); } catch (IOException e) { e.printStackTrace(); logError("Error reading file: " + path + " -- " + e.getMessage()); } String md5 = DigestUtils.md5Hex(sb.toString()); log("MD5 hash of file " + path + " is " + md5); return md5; } /********************************************************************* * End of obsolete methods */ }
package org.epics.pvmanager.sys; import org.epics.util.time.Timestamp; import org.epics.util.time.TimestampFormat; import static org.epics.vtype.ValueFactory.*; /** * * @author carcassi */ class TimeChannelHandler extends SystemChannelHandler { private static final TimestampFormat timeFormat = new TimestampFormat("yyyy/MM/dd HH:mm:ss.SSS"); public TimeChannelHandler(String channelName) { super(channelName); } @Override protected Object createValue() { Timestamp time = Timestamp.now(); String formatted = timeFormat.format(time); return newVString(formatted, alarmNone(), newTime(time)); } }
package be.ibridge.kettle.core.database; import java.io.StringReader; import java.sql.BatchUpdateException; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.ParameterMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Calendar; import java.util.Hashtable; import java.util.Properties; import org.eclipse.core.runtime.IProgressMonitor; import be.ibridge.kettle.core.Const; import be.ibridge.kettle.core.Counter; import be.ibridge.kettle.core.DBCache; import be.ibridge.kettle.core.DBCacheEntry; import be.ibridge.kettle.core.LogWriter; import be.ibridge.kettle.core.Result; import be.ibridge.kettle.core.Row; import be.ibridge.kettle.core.exception.KettleDatabaseBatchException; import be.ibridge.kettle.core.exception.KettleDatabaseException; import be.ibridge.kettle.core.util.StringUtil; import be.ibridge.kettle.core.value.Value; import be.ibridge.kettle.trans.step.dimensionlookup.DimensionLookupMeta; /** * Database handles the process of connecting to, reading from, writing to and updating databases. * The database specific parameters are defined in DatabaseInfo. * * @author Matt * @since 05-04-2003 * */ public class Database { private DatabaseMeta databaseMeta; private int rowlimit; private int commitsize; private Connection connection; private Statement sel_stmt; private PreparedStatement pstmt; private PreparedStatement prepStatementLookup; private PreparedStatement prepStatementUpdate; private PreparedStatement prepStatementInsert; private PreparedStatement pstmt_pun; private PreparedStatement pstmt_dup; private PreparedStatement pstmt_seq; private CallableStatement cstmt; // private ResultSetMetaData rsmd; private DatabaseMetaData dbmd; private Row rowinfo; private int written; private LogWriter log; /** * Counts the number of rows written to a batch. */ private int batchCounter; /** * Construnct a new Database Connection * @param inf The Database Connection Info to construct the connection with. */ public Database(DatabaseMeta inf) { log=LogWriter.getInstance(); databaseMeta = inf; pstmt = null; // rsmd = null; rowinfo = null; dbmd = null; rowlimit=0; written=0; log.logDetailed(toString(), "New database connection defined"); } /** * @return Returns the connection. */ public Connection getConnection() { return connection; } /** * Set the maximum number of records to retrieve from a query. * @param rows */ public void setQueryLimit(int rows) { rowlimit = rows; } /** * @return Returns the prepStatementInsert. */ public PreparedStatement getPrepStatementInsert() { return prepStatementInsert; } /** * @return Returns the prepStatementLookup. */ public PreparedStatement getPrepStatementLookup() { return prepStatementLookup; } /** * @return Returns the prepStatementUpdate. */ public PreparedStatement getPrepStatementUpdate() { return prepStatementUpdate; } /** * Open the database connection. * @throws KettleDatabaseException if something went wrong. */ public void connect() throws KettleDatabaseException { try { if (databaseMeta!=null) { connect(databaseMeta.getDriverClass()); log.logDetailed(toString(), "Connected to database."); } else { throw new KettleDatabaseException("No valid database connection defined!"); } } catch(Exception e) { throw new KettleDatabaseException("Error occured while trying to connect to the database", e); } } /** * Connect using the correct classname * @param classname for example "org.gjt.mm.mysql.Driver" * @return true if the connect was succesfull, false if something went wrong. */ private void connect(String classname) throws KettleDatabaseException { // Install and load the jdbc Driver try { Class.forName(classname); } catch(NoClassDefFoundError e) { throw new KettleDatabaseException("Exception while loading class", e); } catch(ClassNotFoundException e) { throw new KettleDatabaseException("Exception while loading class", e); } catch(Exception e) { throw new KettleDatabaseException("Exception while loading class", e); } try { String url = StringUtil.environmentSubstitute(databaseMeta.getURL()); String userName = StringUtil.environmentSubstitute(databaseMeta.getUsername()); String password = StringUtil.environmentSubstitute(databaseMeta.getPassword()); if (databaseMeta.supportsOptionsInURL()) { if (!Const.isEmpty(userName)) { connection = DriverManager.getConnection(url, userName, password); } else { // Perhaps the username is in the URL or no username is required... connection = DriverManager.getConnection(url); } } else { Properties properties = databaseMeta.getConnectionProperties(); if (!Const.isEmpty(userName)) properties.put("user", userName); if (!Const.isEmpty(password)) properties.put("password", password); connection = DriverManager.getConnection(url, properties); } } catch(SQLException e) { throw new KettleDatabaseException("Error connecting to database: (using class "+classname+")", e); } catch(Throwable e) { throw new KettleDatabaseException("Error connecting to database: (using class "+classname+")", e); } } /** * Disconnect from the database and close all open prepared statements. */ public void disconnect() { try { if (connection==null) return ; // Nothing to do... if (connection.isClosed()) return ; // Nothing to do... if (!isAutoCommit()) commit(); if (pstmt !=null) { pstmt.close(); pstmt=null; } if (prepStatementLookup!=null) { prepStatementLookup.close(); prepStatementLookup=null; } if (prepStatementInsert!=null) { prepStatementInsert.close(); prepStatementInsert=null; } if (prepStatementUpdate!=null) { prepStatementUpdate.close(); prepStatementUpdate=null; } if (pstmt_seq!=null) { pstmt_seq.close(); pstmt_seq=null; } if (connection !=null) { connection.close(); connection=null; } log.logDetailed(toString(), "Connection to database closed!"); } catch(SQLException ex) { log.logError(toString(), "Error disconnecting from database:"+Const.CR+ex.getMessage()); } catch(KettleDatabaseException dbe) { log.logError(toString(), "Error disconnecting from database:"+Const.CR+dbe.getMessage()); } } public void cancelQuery() throws KettleDatabaseException { try { if (pstmt !=null) { pstmt.cancel(); } if (sel_stmt !=null) { sel_stmt.cancel(); } log.logDetailed(toString(), "Open query canceled!"); } catch(SQLException ex) { throw new KettleDatabaseException("Error cancelling query", ex); } } /** * Specify after how many rows a commit needs to occur when inserting or updating values. * @param commsize The number of rows to wait before doing a commit on the connection. */ public void setCommit(int commsize) { commitsize=commsize; String onOff = (commitsize<=0?"on":"off"); try { connection.setAutoCommit(commitsize<=0); log.logDetailed(toString(), "Auto commit "+onOff); } catch(Exception e) { log.logError(toString(), "Can't turn auto commit "+onOff); } } /** * Perform a commit the connection if this is supported by the database */ public void commit() throws KettleDatabaseException { try { if (getDatabaseMetaData().supportsTransactions()) { connection.commit(); } else { log.logDetailed(toString(), "No commit possible on database connection ["+toString()+"]"); } } catch(Exception e) { if (databaseMeta.supportsEmptyTransactions()) throw new KettleDatabaseException("Error comitting connection", e); } } public void rollback() throws KettleDatabaseException { try { if (getDatabaseMetaData().supportsTransactions()) { connection.rollback(); } else { log.logDetailed(toString(), "No rollback possible on database connection ["+toString()+"]"); } } catch(SQLException e) { throw new KettleDatabaseException("Error performing rollback on connection", e); } } /** * Prepare inserting values into a table, using the fields & values in a Row * @param r The row to determine which values need to be inserted * @param table The name of the table in which we want to insert rows * @throws KettleDatabaseException if something went wrong. */ public void prepareInsert(Row r, String table) throws KettleDatabaseException { if (r.size()==0) { throw new KettleDatabaseException("No fields in row, can't insert!"); } String ins = getInsertStatement(table, r); log.logDetailed(toString(),"Preparing statement: "+Const.CR+ins); prepStatementInsert=prepareSQL(ins); } /** * Prepare a statement to be executed on the database. (does not return generated keys) * @param sql The SQL to be prepared * @return The PreparedStatement object. * @throws KettleDatabaseException */ public PreparedStatement prepareSQL(String sql) throws KettleDatabaseException { return prepareSQL(sql, false); } /** * Prepare a statement to be executed on the database. * @param sql The SQL to be prepared * @param returnKeys set to true if you want to return generated keys from an insert statement * @return The PreparedStatement object. * @throws KettleDatabaseException */ public PreparedStatement prepareSQL(String sql, boolean returnKeys) throws KettleDatabaseException { try { if (returnKeys) { return connection.prepareStatement(databaseMeta.stripCR(sql), Statement.RETURN_GENERATED_KEYS); } else { return connection.prepareStatement(databaseMeta.stripCR(sql)); } } catch(SQLException ex) { throw new KettleDatabaseException("Couldn't prepare statement:"+Const.CR+sql, ex); } } public void closeLookup() throws KettleDatabaseException { closePreparedStatement(pstmt); } public void closePreparedStatement(PreparedStatement ps) throws KettleDatabaseException { if (ps!=null) { try { ps.close(); } catch(SQLException e) { throw new KettleDatabaseException("Error closing prepared statement", e); } } } public void closeInsert() throws KettleDatabaseException { if (prepStatementInsert!=null) { try { prepStatementInsert.close(); prepStatementInsert = null; } catch(SQLException e) { throw new KettleDatabaseException("Error closing insert prepared statement.", e); } } } public void closeUpdate() throws KettleDatabaseException { if (prepStatementUpdate!=null) { try { prepStatementUpdate.close(); } catch(SQLException e) { throw new KettleDatabaseException("Error closing update prepared statement.", e); } } } public void setValues(Row r) throws KettleDatabaseException { setValues(r, pstmt); } public void setValuesInsert(Row r) throws KettleDatabaseException { setValues(r, prepStatementInsert); } public void setValuesUpdate(Row r) throws KettleDatabaseException { setValues(r, prepStatementUpdate); } public void setValuesLookup(Row r) throws KettleDatabaseException { setValues(r, prepStatementLookup); } public void setProcValues(Row r, int argnrs[], String argdir[], boolean result) throws KettleDatabaseException { int pos; if (result) pos=2; else pos=1; for (int i=0;i<argnrs.length;i++) { if (argdir[i].equalsIgnoreCase("IN") || argdir[i].equalsIgnoreCase("INOUT")) { Value v=r.getValue(argnrs[i]); setValue(cstmt, v, pos); pos++; } } } public void setValue(PreparedStatement ps, Value v, int pos) throws KettleDatabaseException { String debug = ""; try { switch(v.getType()) { case Value.VALUE_TYPE_BIGNUMBER: debug="BigNumber"; if (!v.isNull()) { ps.setBigDecimal(pos, v.getBigNumber()); } else { ps.setNull(pos, java.sql.Types.DECIMAL); } break; case Value.VALUE_TYPE_NUMBER : debug="Number"; if (!v.isNull()) { double num = v.getNumber(); if (databaseMeta.supportsFloatRoundingOnUpdate() && v.getPrecision()>=0) { num = Const.round(num, v.getPrecision()); } ps.setDouble(pos, num); } else { ps.setNull(pos, java.sql.Types.DOUBLE); } break; case Value.VALUE_TYPE_INTEGER: debug="Integer"; if (!v.isNull()) { if (databaseMeta.supportsSetLong()) { ps.setLong(pos, Math.round( v.getNumber() ) ); } else { if (databaseMeta.supportsFloatRoundingOnUpdate() && v.getPrecision()>=0) { ps.setDouble(pos, v.getNumber() ); } else { ps.setDouble(pos, Const.round( v.getNumber(), v.getPrecision() ) ); } } } else { ps.setNull(pos, java.sql.Types.BIGINT); } break; case Value.VALUE_TYPE_STRING : debug="String"; if (v.getLength()<DatabaseMeta.CLOB_LENGTH) { if (!v.isNull() && v.getString()!=null) { ps.setString(pos, v.getString()); } else { ps.setNull(pos, java.sql.Types.VARCHAR); } } else { if (!v.isNull()) { int maxlen = databaseMeta.getMaxTextFieldLength(); int len = v.getStringLength(); // Take the last maxlen characters of the string... int begin = len - maxlen; if (begin<0) begin=0; // Get the substring! String logging = v.getString().substring(begin); if (databaseMeta.supportsSetCharacterStream()) { StringReader sr = new StringReader(logging); ps.setCharacterStream(pos, sr, logging.length()); } else { ps.setString(pos, logging); } } else { ps.setNull(pos, java.sql.Types.VARCHAR); } } break; case Value.VALUE_TYPE_DATE : debug="Date"; if (!v.isNull() && v.getDate()!=null) { long dat = v.getDate().getTime(); if(v.getPrecision()==1 || !databaseMeta.supportsTimeStampToDateConversion()) { // Convert to DATE! java.sql.Date ddate = new java.sql.Date(dat); ps.setDate(pos, ddate); } else { java.sql.Timestamp sdate = new java.sql.Timestamp(dat); ps.setTimestamp(pos, sdate); } } else { if(v.getPrecision()==1 || !databaseMeta.supportsTimeStampToDateConversion()) { ps.setNull(pos, java.sql.Types.DATE); } else { ps.setNull(pos, java.sql.Types.TIMESTAMP); } } break; case Value.VALUE_TYPE_BOOLEAN: debug="Boolean"; if (databaseMeta.supportsBooleanDataType()) { if (!v.isNull()) { ps.setBoolean(pos, v.getBoolean()); } else { ps.setNull(pos, java.sql.Types.BOOLEAN); } } else { if (!v.isNull()) { ps.setString(pos, v.getBoolean()?"Y":"N"); } else { ps.setNull(pos, java.sql.Types.CHAR); } } break; default: debug="default"; // placeholder ps.setNull(pos, java.sql.Types.VARCHAR); break; } } catch(SQLException ex) { throw new KettleDatabaseException("Error setting value #"+pos+" ["+v.toString()+"] on prepared statement ("+debug+")"+Const.CR+ex.toString(), ex); } catch(Exception e) { throw new KettleDatabaseException("Error setting value #"+pos+" ["+(v==null?"NULL":v.toString())+"] on prepared statement ("+debug+")"+Const.CR+e.toString(), e); } } // Sets the values of the preparedStatement pstmt. public void setValues(Row r, PreparedStatement ps) throws KettleDatabaseException { int i; Value v; // now set the values in the row! for (i=0;i<r.size();i++) { v=r.getValue(i); try { //System.out.println("Setting value ["+v+"] on preparedStatement, position="+i); setValue(ps, v, i+1); } catch(KettleDatabaseException e) { throw new KettleDatabaseException("offending row : "+r, e); } } } public void setDimValues(Row r, Value dateval) throws KettleDatabaseException { setDimValues(r, dateval, prepStatementLookup); } // Sets the values of the preparedStatement pstmt. public void setDimValues(Row r, Value dateval, PreparedStatement ps) throws KettleDatabaseException { int i; Value v; long dat; // now set the values in the row! for (i=0;i<r.size();i++) { v=r.getValue(i); try { setValue(ps, v, i+1); } catch(KettleDatabaseException e) { throw new KettleDatabaseException("Unable to set value #"+i+" on dimension using row :"+r, e); } } if (dateval!=null && dateval.getDate()!=null && !dateval.isNull()) { dat = dateval.getDate().getTime(); } else { Calendar cal=Calendar.getInstance(); // use system date! dat = cal.getTime().getTime(); } java.sql.Timestamp sdate = new java.sql.Timestamp(dat); try { ps.setTimestamp(r.size()+1, sdate); // ? > date_from ps.setTimestamp(r.size()+2, sdate); // ? <= date_to } catch(SQLException ex) { throw new KettleDatabaseException("Unable to set timestamp on fromdate or todate", ex); } } public void dimUpdate(Row row, String table, String fieldlookup[], int fieldnrs[], String returnkey, Value dimkey ) throws KettleDatabaseException { int i; if (pstmt_dup==null) // first time: construct prepared statement { // Construct the SQL statement... /* * UPDATE d_customer * SET fieldlookup[] = row.getValue(fieldnrs) * WHERE returnkey = dimkey * ; */ String sql="UPDATE "+table+Const.CR+"SET "; for (i=0;i<fieldlookup.length;i++) { if (i>0) sql+=", "; else sql+=" "; sql+=fieldlookup[i]+" = ?"+Const.CR; } sql+="WHERE "+returnkey+" = ?"; try { log.logDebug(toString(), "Preparing statement: ["+sql+"]"); pstmt_dup=connection.prepareStatement(databaseMeta.stripCR(sql)); } catch(SQLException ex) { throw new KettleDatabaseException("Coudln't prepare statement :"+Const.CR+sql, ex); } } // Assemble information // New Row rupd=new Row(); for (i=0;i<fieldnrs.length;i++) { rupd.addValue( row.getValue(fieldnrs[i])); } rupd.addValue( dimkey ); setValues(rupd, pstmt_dup); insertRow(pstmt_dup); } // This inserts new record into dimension // Optionally, if the entry already exists, update date range from previous version // of the entry. public void dimInsert(Row row, String table, boolean newentry, String keyfield, boolean autoinc, Value technicalKey, String versionfield, Value val_version, String datefrom, Value val_datfrom, String dateto, Value val_datto, String fieldlookup[], int fieldnrs[], String key[], String keylookup[], int keynrs[] ) throws KettleDatabaseException { int i; if (prepStatementInsert==null && prepStatementUpdate==null) // first time: construct prepared statement { /* Construct the SQL statement... * * INSERT INTO * d_customer(keyfield, versionfield, datefrom, dateto, key[], fieldlookup[]) * VALUES (val_key ,val_version , val_datfrom, val_datto, keynrs[], fieldnrs[]) * ; */ String sql="INSERT INTO "+databaseMeta.quoteField(table)+"( "; if (!autoinc) sql+=databaseMeta.quoteField(keyfield)+", "; // NO AUTOINCREMENT else if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_INFORMIX) sql+="0, "; // placeholder on informix! sql+=databaseMeta.quoteField(versionfield)+", "+databaseMeta.quoteField(datefrom)+", "+databaseMeta.quoteField(dateto); for (i=0;i<keylookup.length;i++) { sql+=", "+databaseMeta.quoteField(keylookup[i]); } for (i=0;i<fieldlookup.length;i++) { sql+=", "+databaseMeta.quoteField(fieldlookup[i]); } sql+=") VALUES("; if (!autoinc) sql+="?, "; sql+="?, ?, ?"; for (i=0;i<keynrs.length;i++) { sql+=", ?"; } for (i=0;i<fieldnrs.length;i++) { sql+=", ?"; } sql+=" )"; try { if (keyfield==null) { log.logDetailed(toString(), "SQL w/ return keys=["+sql+"]"); prepStatementInsert=connection.prepareStatement(databaseMeta.stripCR(sql), Statement.RETURN_GENERATED_KEYS); } else { log.logDetailed(toString(), "SQL=["+sql+"]"); prepStatementInsert=connection.prepareStatement(databaseMeta.stripCR(sql)); } //pstmt=con.prepareStatement(sql, new String[] { "klant_tk" } ); } catch(SQLException ex) { throw new KettleDatabaseException("Unable to prepare dimension insert :"+Const.CR+sql, ex); } /* * UPDATE d_customer * SET dateto = val_datnow * WHERE keylookup[] = keynrs[] * AND versionfield = val_version - 1 * ; */ String sql_upd="UPDATE "+databaseMeta.quoteField(table)+Const.CR+"SET "+databaseMeta.quoteField(dateto)+" = ?"+Const.CR; sql_upd+="WHERE "; for (i=0;i<keylookup.length;i++) { if (i>0) sql_upd+="AND "; sql_upd+=databaseMeta.quoteField(keylookup[i])+" = ?"+Const.CR; } sql_upd+="AND "+databaseMeta.quoteField(versionfield)+" = ? "; try { log.logDetailed(toString(), "Preparing update: "+Const.CR+sql_upd+Const.CR); prepStatementUpdate=connection.prepareStatement(databaseMeta.stripCR(sql_upd)); } catch(SQLException ex) { throw new KettleDatabaseException("Unable to prepare dimension update :"+Const.CR+sql_upd, ex); } } Row rins=new Row(); if (!autoinc) rins.addValue(technicalKey); if (!newentry) { Value val_new_version = new Value(val_version); val_new_version.setValue( val_new_version.getNumber()+1 ); // determine next version rins.addValue(val_new_version); } else { rins.addValue(val_version); } rins.addValue(val_datfrom); rins.addValue(val_datto); for (i=0;i<keynrs.length;i++) { rins.addValue( row.getValue(keynrs[i])); } for (i=0;i<fieldnrs.length;i++) { Value val = row.getValue(fieldnrs[i]); rins.addValue( val ); } log.logDebug(toString(), "rins, size="+rins.size()+", values="+rins.toString()); // INSERT NEW VALUE! setValues(rins, prepStatementInsert); insertRow(prepStatementInsert); log.logDebug(toString(), "Row inserted!"); if (keyfield==null) { try { Row keys = getGeneratedKeys(prepStatementInsert); if (keys.size()>0) { technicalKey.setValue(keys.getValue(0).getInteger()); } else { throw new KettleDatabaseException("Unable to retrieve value of auto-generated technical key : no value found!"); } } catch(Exception e) { throw new KettleDatabaseException("Unable to retrieve value of auto-generated technical key : unexpected error: ", e); } } if (!newentry) // we have to update the previous version in the dimension! { /* * UPDATE d_customer * SET dateto = val_datfrom * WHERE keylookup[] = keynrs[] * AND versionfield = val_version - 1 * ; */ Row rupd = new Row(); rupd.addValue(val_datfrom); for (i=0;i<keynrs.length;i++) { rupd.addValue( row.getValue(keynrs[i])); } rupd.addValue(val_version); log.logRowlevel(toString(), "UPDATE using rupd="+rupd.toString()); // UPDATE VALUES setValues(rupd, prepStatementUpdate); // set values for update log.logDebug(toString(), "Values set for update ("+rupd.size()+")"); insertRow(prepStatementUpdate); // do the actual update log.logDebug(toString(), "Row updated!"); } } /** * @param ps The prepared insert statement to use * @return The generated keys in auto-increment fields * @throws KettleDatabaseException in case something goes wrong retrieving the keys. */ public Row getGeneratedKeys(PreparedStatement ps) throws KettleDatabaseException { ResultSet keys = null; try { keys=ps.getGeneratedKeys(); // 1 row of keys ResultSetMetaData resultSetMetaData = keys.getMetaData(); Row rowInfo = getRowInfo(resultSetMetaData); return getRow(keys, resultSetMetaData, rowInfo); } catch(Exception ex) { throw new KettleDatabaseException("Unable to retrieve key(s) from auto-increment field(s)", ex); } finally { if (keys!=null) { try { keys.close(); } catch(SQLException e) { throw new KettleDatabaseException("Unable to close resultset of auto-generated keys", e); } } } } // This updates all versions of a dimension entry. public void dimPunchThrough(Row row, String table, int fieldupdate[], String fieldlookup[], int fieldnrs[], String key[], String keylookup[], int keynrs[] ) throws KettleDatabaseException { int i; boolean first; if (pstmt_pun==null) // first time: construct prepared statement { /* * UPDATE table * SET punchv1 = fieldx, ... * WHERE keylookup[] = keynrs[] * ; */ String sql_upd="UPDATE "+table+Const.CR; sql_upd+="SET "; first=true; for (i=0;i<fieldlookup.length;i++) { if (fieldupdate[i]==DimensionLookupMeta.TYPE_UPDATE_DIM_PUNCHTHROUGH) { if (!first) sql_upd+=", "; else sql_upd+=" "; first=false; sql_upd+=fieldlookup[i]+" = ?"+Const.CR; } } sql_upd+="WHERE "; for (i=0;i<keylookup.length;i++) { if (i>0) sql_upd+="AND "; sql_upd+=keylookup[i]+" = ?"+Const.CR; } try { pstmt_pun=connection.prepareStatement(databaseMeta.stripCR(sql_upd)); } catch(SQLException ex) { throw new KettleDatabaseException("Unable to prepare dimension punchThrough update statement : "+Const.CR+sql_upd, ex); } } Row rupd=new Row(); for (i=0;i<fieldlookup.length;i++) { if (fieldupdate[i]==DimensionLookupMeta.TYPE_UPDATE_DIM_PUNCHTHROUGH) { rupd.addValue( row.getValue(fieldnrs[i])); } } for (i=0;i<keynrs.length;i++) { rupd.addValue( row.getValue(keynrs[i])); } // UPDATE VALUES setValues(rupd, pstmt_pun); // set values for update insertRow(pstmt_pun); // do the actual update } /** * This inserts new record into a junk dimension */ public void combiInsert( Row row, String table, String keyfield, boolean autoinc, Value val_key, String keylookup[], int keynrs[], boolean crc, String crcfield, Value val_crc ) throws KettleDatabaseException { String debug="Combination insert"; try { boolean comma; if (prepStatementInsert==null) // first time: construct prepared statement { debug="First: construct prepared statement"; /* Construct the SQL statement... * * INSERT INTO * d_test(keyfield, [crcfield,] keylookup[]) * VALUES(val_key, [val_crc], row values with keynrs[]) * ; */ StringBuffer sql = new StringBuffer(100); sql.append("INSERT INTO ").append(databaseMeta.quoteField(table)).append("( "); comma=false; if (!autoinc) // NO AUTOINCREMENT { sql.append(databaseMeta.quoteField(keyfield)); comma=true; } else if (databaseMeta.needsPlaceHolder()) { sql.append('0'); // placeholder on informix! Will be replaced in table by real autoinc value. comma=true; } if (crc) { if (comma) sql.append(", "); sql.append(databaseMeta.quoteField(crcfield)); comma=true; } for (int i=0;i<keylookup.length;i++) { if (comma) sql.append(", "); sql.append(databaseMeta.quoteField(keylookup[i])); comma=true; } sql.append(") VALUES ("); comma=false; if (keyfield!=null) { sql.append('?'); comma=true; } if (crc) { if (comma) sql.append(','); sql.append('?'); comma=true; } for (int i=0;i<keylookup.length;i++) { if (comma) sql.append(','); else comma=true; sql.append('?'); } sql.append(" )"); String sqlStatement = sql.toString(); try { debug="First: prepare statement"; if (keyfield==null) { log.logDetailed(toString(), "SQL with return keys: "+sqlStatement); prepStatementInsert=connection.prepareStatement(databaseMeta.stripCR(sqlStatement), Statement.RETURN_GENERATED_KEYS); } else { log.logDetailed(toString(), "SQL without return keys: "+sqlStatement); prepStatementInsert=connection.prepareStatement(databaseMeta.stripCR(sqlStatement)); } } catch(SQLException ex) { throw new KettleDatabaseException("Unable to prepare combi insert statement : "+Const.CR+sqlStatement, ex); } catch(Exception ex) { throw new KettleDatabaseException("Unable to prepare combi insert statement : "+Const.CR+sqlStatement, ex); } } debug="Create new insert row rins"; Row rins=new Row(); if (!autoinc) rins.addValue(val_key); if (crc) { rins.addValue(val_crc); } for (int i=0;i<keynrs.length;i++) { rins.addValue( row.getValue(keynrs[i])); } if (log.isRowLevel()) log.logRowlevel(toString(), "rins="+rins.toString()); debug="Set values on insert"; // INSERT NEW VALUE! setValues(rins, prepStatementInsert); debug="Insert row"; insertRow(prepStatementInsert); debug="Retrieve key"; if (keyfield==null) { ResultSet keys = null; try { keys=prepStatementInsert.getGeneratedKeys(); // 1 key if (keys.next()) val_key.setValue(keys.getDouble(1)); else { throw new KettleDatabaseException("Unable to retrieve auto-increment of combi insert key : "+keyfield+", no fields in resultset"); } } catch(SQLException ex) { throw new KettleDatabaseException("Unable to retrieve auto-increment of combi insert key : "+keyfield, ex); } finally { try { if ( keys != null ) keys.close(); } catch(SQLException ex) { throw new KettleDatabaseException("Unable to retrieve auto-increment of combi insert key : "+keyfield, ex); } } } } catch(Exception e) { log.logError(toString(), Const.getStackTracker(e)); throw new KettleDatabaseException("Unexpected error in combination insert in part ["+debug+"] : "+e.toString(), e); } } public Value getNextSequenceValue(String seq, String keyfield) throws KettleDatabaseException { Value retval=null; try { if (pstmt_seq==null) { pstmt_seq=connection.prepareStatement(databaseMeta.getSeqNextvalSQL(databaseMeta.stripCR(seq))); } ResultSet rs=null; try { rs = pstmt_seq.executeQuery(); if (rs.next()) { long next = rs.getLong(1); retval=new Value(keyfield, next); retval.setLength(9,0); } } finally { if ( rs != null ) rs.close(); } } catch(SQLException ex) { throw new KettleDatabaseException("Unable to get next value for sequence : "+seq, ex); } return retval; } public void insertRow(String tableName, Row fields) throws KettleDatabaseException { prepareInsert(fields, tableName); setValuesInsert(fields); insertRow(); closeInsert(); } public String getInsertStatement(String tableName, Row fields) { StringBuffer ins=new StringBuffer(128); ins.append("INSERT INTO ").append(databaseMeta.quoteField(tableName)).append("("); // now add the names in the row: for (int i=0;i<fields.size();i++) { if (i>0) ins.append(", "); String name = fields.getValue(i).getName(); ins.append(databaseMeta.quoteField(name)); } ins.append(") VALUES ("); // Add placeholders... for (int i=0;i<fields.size();i++) { if (i>0) ins.append(", "); ins.append(" ?"); } ins.append(")"); return ins.toString(); } public void insertRow() throws KettleDatabaseException { insertRow(prepStatementInsert); } public void insertRow(boolean batch) throws KettleDatabaseException { insertRow(prepStatementInsert, batch); } public void updateRow() throws KettleDatabaseException { insertRow(prepStatementUpdate); } public void insertRow(PreparedStatement ps) throws KettleDatabaseException { insertRow(ps, false); } /** * @param batchCounter The batchCounter to set. */ public void setBatchCounter(int batchCounter) { this.batchCounter = batchCounter; } /** * @return Returns the batchCounter. */ public int getBatchCounter() { return batchCounter; } private long testCounter = 0; /** * Insert a row into the database using a prepared statement that has all values set. * @param ps The prepared statement * @param batch True if you want to use batch inserts (size = commitsize) * @throws KettleDatabaseException */ public void insertRow(PreparedStatement ps, boolean batch) throws KettleDatabaseException { String debug="insertRow start"; try { boolean useBatchInsert = batch && getDatabaseMetaData().supportsBatchUpdates() && databaseMeta.supportsBatchUpdates(); // Add support for batch inserts... if (!isAutoCommit()) { if (useBatchInsert) { debug="insertRow add batch"; batchCounter++; ps.addBatch(); // Add the batch, but don't forget to run the batch testCounter++; // System.out.println("testCounter is at "+testCounter); } else { debug="insertRow exec update"; ps.executeUpdate(); } } else { ps.executeUpdate(); } written++; if (!isAutoCommit() && (written%commitsize)==0) { if (useBatchInsert) { debug="insertRow executeBatch commit"; ps.executeBatch(); commit(); ps.clearBatch(); // System.out.println("EXECUTE BATCH, testcounter is at "+testCounter); batchCounter=0; } else { debug="insertRow normal commit"; commit(); } } } catch(BatchUpdateException ex) { //System.out.println("Batch update exception "+ex.getMessage()); KettleDatabaseBatchException kdbe = new KettleDatabaseBatchException("Error updating batch", ex); kdbe.setUpdateCounts(ex.getUpdateCounts()); throw kdbe; } catch(SQLException ex) { log.logError(toString(), Const.getStackTracker(ex)); throw new KettleDatabaseException("Error inserting row", ex); } catch(Exception e) { // System.out.println("Unexpected exception in ["+debug+"] : "+e.getMessage()); throw new KettleDatabaseException("Unexpected error inserting row in part ["+debug+"]", e); } } /** * Clears batch of insert prepared statement * @deprecated * @throws KettleDatabaseException */ public void clearInsertBatch() throws KettleDatabaseException { clearBatch(prepStatementInsert); } public void clearBatch(PreparedStatement preparedStatement) throws KettleDatabaseException { try { preparedStatement.clearBatch(); } catch(SQLException e) { throw new KettleDatabaseException("Unable to clear batch for prepared statement", e); } } public void insertFinished(boolean batch) throws KettleDatabaseException { insertFinished(prepStatementInsert, batch); prepStatementInsert = null; } public void insertFinished(PreparedStatement ps, boolean batch) throws KettleDatabaseException { try { if (ps!=null) { if (!isAutoCommit()) { if (batch && getDatabaseMetaData().supportsBatchUpdates() && batchCounter>0) { //System.out.println("Executing batch with "+batchCounter+" elements..."); ps.executeBatch(); commit(); } else { commit(); } } ps.close(); } } catch(SQLException ex) { throw new KettleDatabaseException("Unable to commit connection after having inserted rows.", ex); } } /** * Execute an SQL statement on the database connection (has to be open) * @param sql The SQL to execute * @return a Result object indicating the number of lines read, deleted, inserted, updated, ... * @throws KettleDatabaseException in case anything goes wrong. */ public Result execStatement(String sql) throws KettleDatabaseException { return execStatement(sql, null); } public Result execStatement(String sql, Row params) throws KettleDatabaseException { Result result = new Result(); try { boolean resultSet; int count; if (params!=null) { PreparedStatement prep_stmt = connection.prepareStatement(databaseMeta.stripCR(sql)); setValues(params, prep_stmt); // set the parameters! resultSet = prep_stmt.execute(); count = prep_stmt.getUpdateCount(); prep_stmt.close(); } else { String sqlStripped = databaseMeta.stripCR(sql); // log.logDetailed(toString(), "Executing SQL Statement: ["+sqlStripped+"]"); Statement stmt = connection.createStatement(); resultSet = stmt.execute(sqlStripped); count = stmt.getUpdateCount(); stmt.close(); } if (resultSet) { // the result is a resultset, but we don't do anything with it! // You should have called something else! // log.logDetailed(toString(), "What to do with ResultSet??? (count="+count+")"); } else { if (count > 0) { if (sql.toUpperCase().startsWith("INSERT")) result.setNrLinesOutput((long) count); if (sql.toUpperCase().startsWith("UPDATE")) result.setNrLinesUpdated((long) count); if (sql.toUpperCase().startsWith("DELETE")) result.setNrLinesDeleted((long) count); } } // See if a cache needs to be cleared... if (sql.toUpperCase().startsWith("ALTER TABLE")) { DBCache.getInstance().clear(databaseMeta.getName()); } } catch(SQLException ex) { throw new KettleDatabaseException("Couldn't execute SQL: "+sql+Const.CR, ex); } catch(Exception e) { throw new KettleDatabaseException("Unexpected error executing SQL: "+Const.CR, e); } return result; } /** * Execute a series of SQL statements, separated by ; * * We are already connected... * Multiple statements have to be split into parts * We use the ";" to separate statements... * * We keep the results in Result object from Jobs * * @param script The SQL script to be execute * @throws KettleDatabaseException In case an error occurs * @return A result with counts of the number or records updates, inserted, deleted or read. */ public Result execStatements(String script) throws KettleDatabaseException { Result result = new Result(); String all = script; int from=0; int to=0; int length = all.length(); int nrstats = 0; while (to<length) { char c = all.charAt(to); if (c=='"') { to++; c=' '; while (to<length && c!='"') { c=all.charAt(to); to++; } } else if (c=='\'') // skip until next ' { to++; c=' '; while (to<length && c!='\'') { c=all.charAt(to); to++; } } else if (all.substring(to).startsWith("--")) // -- means: ignore comment until end of line... { to++; while (to<length && c!='\n' && c!='\r') { c=all.charAt(to); to++; } } if (c==';' || to>=length-1) // end of statement { if (to>=length-1) to++; // grab last char also! String stat; if (to<=length) stat = all.substring(from, to); else stat = all.substring(from); // If it ends with a ; remove that ; // Oracle for example can't stand it when this happens... if (stat.length()>0 && stat.charAt(stat.length()-1)==';') { stat = stat.substring(0,stat.length()-1); } if (!Const.onlySpaces(stat)) { String sql=Const.trim(stat); if (sql.toUpperCase().startsWith("SELECT")) { // A Query log.logDetailed(toString(), "launch SELECT statement: "+Const.CR+sql); nrstats++; ResultSet rs = null; try { rs = openQuery(sql); if (rs!=null) { Row r = getRow(rs); while (r!=null) { result.setNrLinesRead(result.getNrLinesRead()+1); log.logDetailed(toString(), r.toString()); r=getRow(rs); } } else { log.logDebug(toString(), "Error executing query: "+Const.CR+sql); } } finally { try { if ( rs != null ) rs.close(); } catch (SQLException ex ) { log.logDebug(toString(), "Error closing query: "+Const.CR+sql); } } } else // any kind of statement { log.logDetailed(toString(), "launch DDL statement: "+Const.CR+sql); // A DDL statement nrstats++; Result res = execStatement(sql); result.add(res); } } to++; from=to; } else { to++; } } log.logDetailed(toString(), nrstats+" statement"+(nrstats==1?"":"s")+" executed"); return result; } public ResultSet openQuery(String sql) throws KettleDatabaseException { return openQuery(sql, null); } /** * Open a query on the database with a set of parameters stored in a Kettle Row * @param sql The SQL to launch with question marks (?) as placeholders for the parameters * @param params The parameters or null if no parameters are used. * @return A JDBC ResultSet * @throws KettleDatabaseException when something goes wrong with the query. */ public ResultSet openQuery(String sql, Row params) throws KettleDatabaseException { return openQuery(sql, params, ResultSet.FETCH_FORWARD); } public ResultSet openQuery(String sql, Row params, int fetch_mode) throws KettleDatabaseException { ResultSet res; String debug = "Start"; // Create a Statement try { if (params!=null) { debug = "P create prepared statement (con==null? "+(connection==null)+")"; pstmt = connection.prepareStatement(databaseMeta.stripCR(sql), ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); debug = "P Set values"; setValues(params); // set the dates etc! if (canWeSetFetchSize(pstmt) ) { debug = "P Set fetchsize"; int fs = Const.FETCH_SIZE<=pstmt.getMaxRows()?pstmt.getMaxRows():Const.FETCH_SIZE; // System.out.println("Setting pstmt fetchsize to : "+fs); if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL) { pstmt.setFetchSize(Integer.MIN_VALUE); } else { pstmt.setFetchSize(fs); } debug = "P Set fetch direction"; pstmt.setFetchDirection(fetch_mode); } debug = "P Set max rows"; if (rowlimit>0) pstmt.setMaxRows(rowlimit); debug = "exec query"; res = pstmt.executeQuery(); } else { debug = "create statement"; sel_stmt = connection.createStatement(); if (canWeSetFetchSize(sel_stmt)) { debug = "Set fetchsize"; int fs = Const.FETCH_SIZE<=sel_stmt.getMaxRows()?sel_stmt.getMaxRows():Const.FETCH_SIZE; if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL) { sel_stmt.setFetchSize(Integer.MIN_VALUE); } else { sel_stmt.setFetchSize(fs); } debug = "Set fetch direction"; sel_stmt.setFetchDirection(fetch_mode); } debug = "Set max rows"; if (rowlimit>0) sel_stmt.setMaxRows(rowlimit); debug = "exec query"; res=sel_stmt.executeQuery(databaseMeta.stripCR(sql)); } debug = "openQuery : get rowinfo"; // MySQL Hack only. It seems too much for the cursor type of operation on MySQL, to have another cursor opened // to get the length of a String field. So, on MySQL, we ingore the length of Strings in result rows. rowinfo = getRowInfo(res.getMetaData(), databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL); } catch(SQLException ex) { log.logError(toString(), "ERROR executing ["+sql+"]"); log.logError(toString(), "ERROR in part: ["+debug+"]"); printSQLException(ex); throw new KettleDatabaseException("An error occurred executing SQL: "+Const.CR+sql, ex); } catch(Exception e) { log.logError(toString(), "ERROR executing query: "+e.toString()); log.logError(toString(), "ERROR in part: "+debug); throw new KettleDatabaseException("An error occurred executing SQL in part ["+debug+"]:"+Const.CR+sql, e); } return res; } private boolean canWeSetFetchSize(Statement statement) throws SQLException { return databaseMeta.isFetchSizeSupported() && ( statement.getMaxRows()>0 || databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_POSTGRES || databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_MYSQL); } public ResultSet openQuery(PreparedStatement ps, Row params) throws KettleDatabaseException { ResultSet res; String debug = "Start"; // Create a Statement try { debug = "OQ Set values"; setValues(params, ps); // set the parameters! if (canWeSetFetchSize(ps)) { debug = "OQ Set fetchsize"; int fs = Const.FETCH_SIZE<=ps.getMaxRows()?ps.getMaxRows():Const.FETCH_SIZE; if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL) { ps.setFetchSize(Integer.MIN_VALUE); } else { ps.setFetchSize(fs); } debug = "OQ Set fetch direction"; ps.setFetchDirection(ResultSet.FETCH_FORWARD); } debug = "OQ Set max rows"; if (rowlimit>0) ps.setMaxRows(rowlimit); debug = "OQ exec query"; res = ps.executeQuery(); debug = "OQ getRowInfo()"; rowinfo = getRowInfo(res.getMetaData()); } catch(SQLException ex) { throw new KettleDatabaseException("ERROR executing query in part["+debug+"]", ex); } catch(Exception e) { throw new KettleDatabaseException("ERROR executing query in part["+debug+"]", e); } return res; } public Row getTableFields(String tablename) throws KettleDatabaseException { return getQueryFields(databaseMeta.getSQLQueryFields(tablename), false); } public Row getQueryFields(String sql, boolean param) throws KettleDatabaseException { return getQueryFields(sql, param, null); } /** * See if the table specified exists by looking at the data dictionary! * @param tablename The name of the table to check. * @return true if the table exists, false if it doesn't. */ public boolean checkTableExists(String tablename) throws KettleDatabaseException { try { log.logDebug(toString(), "Checking if table ["+tablename+"] exists!"); if (getDatabaseMetaData()!=null) { ResultSet alltables = getDatabaseMetaData().getTables(null, null, "%" , new String[] { "TABLE", "VIEW", "SYNONYM" } ); boolean found = false; if (alltables!=null) { while (alltables.next() && !found) { String schemaName = alltables.getString("TABLE_SCHEM"); String name = alltables.getString("TABLE_NAME"); if ( tablename.equalsIgnoreCase(name) || ( schemaName!=null && tablename.equalsIgnoreCase( databaseMeta.getSchemaTableCombination(schemaName, name)) ) ) { log.logDebug(toString(), "table ["+tablename+"] was found!"); found=true; } } alltables.close(); return found; } else { throw new KettleDatabaseException("Unable to read table-names from the database meta-data."); } } else { throw new KettleDatabaseException("Unable to get database meta-data from the database."); } } catch(Exception e) { throw new KettleDatabaseException("Unable to check if table ["+tablename+"] exists on connection ["+databaseMeta.getName()+"]", e); } } /** * Check whether the sequence exists, Oracle only! * @param sequenceName The name of the sequence * @return true if the sequence exists. */ public boolean checkSequenceExists(String sequenceName) throws KettleDatabaseException { boolean retval=false; if (!databaseMeta.supportsSequences()) return retval; try { // Get the info from the data dictionary... String sql = databaseMeta.getSQLSequenceExists(sequenceName); ResultSet res = openQuery(sql); if (res!=null) { Row row = getRow(res); if (row!=null) { retval=true; } closeQuery(res); } } catch(Exception e) { throw new KettleDatabaseException("Unexpected error checking whether or not sequence ["+sequenceName+"] exists", e); } return retval; } /** * Check if an index on certain fields in a table exists. * @param tablename The table on which the index is checked * @param idx_fields The fields on which the indexe is checked * @return True if the index exists */ public boolean checkIndexExists(String tablename, String idx_fields[]) throws KettleDatabaseException { if (!checkTableExists(tablename)) return false; log.logDebug(toString(), "CheckIndexExists() tablename = "+tablename+" type = "+databaseMeta.getDatabaseTypeDesc()); boolean exists[] = new boolean[idx_fields.length]; for (int i=0;i<exists.length;i++) exists[i]=false; try { switch(databaseMeta.getDatabaseType()) { case DatabaseMeta.TYPE_DATABASE_MSSQL: { // Get the info from the data dictionary... StringBuffer sql = new StringBuffer(128); sql.append("select i.name table_name, c.name column_name "); sql.append("from sysindexes i, sysindexkeys k, syscolumns c "); sql.append("where i.name = '"+tablename+"' "); sql.append("AND i.id = k.id "); sql.append("AND i.id = c.id "); sql.append("AND k.colid = c.colid "); ResultSet res = null; try { res = openQuery(sql.toString()); if (res!=null) { Row row = getRow(res); while (row!=null) { String column = row.getString("column_name", ""); int idx = Const.indexOfString(column, idx_fields); if (idx>=0) exists[idx]=true; row = getRow(res); } } else { return false; } } finally { if ( res != null ) closeQuery(res); } } break; case DatabaseMeta.TYPE_DATABASE_ORACLE: { // Get the info from the data dictionary... String sql = "SELECT * FROM USER_IND_COLUMNS WHERE TABLE_NAME = '"+tablename.toUpperCase()+"'"; ResultSet res = null; try { res = openQuery(sql); if (res!=null) { Row row = getRow(res); while (row!=null) { String column = row.getString("COLUMN_NAME", ""); int idx = Const.indexOfString(column, idx_fields); if (idx>=0) { exists[idx]=true; } row = getRow(res); } } else { return false; } } finally { if ( res != null ) closeQuery(res); } } break; case DatabaseMeta.TYPE_DATABASE_ACCESS: { // Get a list of all the indexes for this table ResultSet indexList = null; try { indexList = getDatabaseMetaData().getIndexInfo(null,null,tablename,false,true); while (indexList.next()) { // String tablen = indexList.getString("TABLE_NAME"); // String indexn = indexList.getString("INDEX_NAME"); String column = indexList.getString("COLUMN_NAME"); // int pos = indexList.getShort("ORDINAL_POSITION"); // int type = indexList.getShort("TYPE"); int idx = Const.indexOfString(column, idx_fields); if (idx>=0) { exists[idx]=true; } } } finally { if ( indexList != null ) indexList.close(); } } break; default: { // Get a list of all the indexes for this table ResultSet indexList = null; try { indexList = getDatabaseMetaData().getIndexInfo(null,null,tablename,false,true); while (indexList.next()) { // String tablen = indexList.getString("TABLE_NAME"); // String indexn = indexList.getString("INDEX_NAME"); String column = indexList.getString("COLUMN_NAME"); // int pos = indexList.getShort("ORDINAL_POSITION"); // int type = indexList.getShort("TYPE"); int idx = Const.indexOfString(column, idx_fields); if (idx>=0) { exists[idx]=true; } } } finally { if ( indexList != null ) indexList.close(); } } break; } // See if all the fields are indexed... boolean all=true; for (int i=0;i<exists.length && all;i++) if (!exists[i]) all=false; return all; } catch(Exception e) { e.printStackTrace(); throw new KettleDatabaseException("Unable to determine if indexes exists on table ["+tablename+"]", e); } } public String getCreateIndexStatement(String tablename, String indexname, String idx_fields[], boolean tk, boolean unique, boolean bitmap, boolean semi_colon) { String cr_index=""; cr_index += "CREATE "; if (unique || ( tk && databaseMeta.getDatabaseType() == DatabaseMeta.TYPE_DATABASE_SYBASE)) cr_index += "UNIQUE "; if (bitmap && databaseMeta.supportsBitmapIndex()) cr_index += "BITMAP "; cr_index += "INDEX "+databaseMeta.quoteField(indexname)+Const.CR+" "; cr_index += "ON "+databaseMeta.quoteField(tablename)+Const.CR; cr_index += "( "+Const.CR; for (int i=0;i<idx_fields.length;i++) { if (i>0) cr_index+=", "; else cr_index+=" "; cr_index += databaseMeta.quoteField(idx_fields[i])+Const.CR; } cr_index+=")"+Const.CR; if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE && databaseMeta.getIndexTablespace()!=null && databaseMeta.getIndexTablespace().length()>0) { cr_index+="TABLESPACE "+databaseMeta.quoteField(databaseMeta.getIndexTablespace()); } if (semi_colon) { cr_index+=";"+Const.CR; } return cr_index; } public String getCreateSequenceStatement(String sequence, long start_at, long increment_by, long max_value, boolean semi_colon) { String cr_seq=""; if (sequence==null || sequence.length()==0) return cr_seq; if (databaseMeta.supportsSequences()) { cr_seq += "CREATE SEQUENCE "+databaseMeta.quoteField(sequence)+" "+Const.CR; // Works for both Oracle and PostgreSQL :-) cr_seq += "START WITH "+start_at+" "+Const.CR; cr_seq += "INCREMENT BY "+increment_by+" "+Const.CR; if (max_value>0) cr_seq += "MAXVALUE "+max_value+Const.CR; if (semi_colon) cr_seq+=";"+Const.CR; } return cr_seq; } public Row getQueryFields(String sql, boolean param, Row inform) throws KettleDatabaseException { Row fields; DBCache dbcache = DBCache.getInstance(); DBCacheEntry entry=null; // Check the cache first! if (dbcache!=null) { entry = new DBCacheEntry(databaseMeta.getName(), sql); fields = dbcache.get(entry); if (fields!=null) { return fields; } } if (connection==null) return null; // Cache test without connect. // No cache entry found String debug=""; try { if (inform==null) { debug="inform==null"; sel_stmt = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); debug="isFetchSizeSupported()"; if (databaseMeta.isFetchSizeSupported() && sel_stmt.getMaxRows()>=1) { debug = "Set fetchsize"; if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MYSQL) { sel_stmt.setFetchSize(Integer.MIN_VALUE); } else { sel_stmt.setFetchSize(1); } } debug = "Set max rows to 1"; sel_stmt.setMaxRows(1); debug = "exec query"; ResultSet r=sel_stmt.executeQuery(databaseMeta.stripCR(sql)); debug = "getQueryFields get row info"; fields = getRowInfo(r.getMetaData()); debug="close resultset"; r.close(); debug="close statement"; sel_stmt.close(); sel_stmt=null; } else { debug="prepareStatement"; PreparedStatement ps = connection.prepareStatement(databaseMeta.stripCR(sql)); if (param) { Row par = inform; debug="getParameterMetaData()"; if (par==null) par = getParameterMetaData(ps); debug="getParameterMetaData()"; if (par==null) par = getParameterMetaData(sql, inform); setValues(par, ps); } debug="executeQuery()"; ResultSet r = ps.executeQuery(); debug="getRowInfo"; fields=getRowInfo(ps.getMetaData()); debug="close resultset"; r.close(); debug="close preparedStatement"; ps.close(); } } catch(SQLException ex) { throw new KettleDatabaseException("Couldn't get field info from ["+sql+"]"+Const.CR+"Location: "+debug, ex); } catch(Exception e) { throw new KettleDatabaseException("Couldn't get field info in part ["+debug+"]", e); } // Store in cache!! if (dbcache!=null && entry!=null) { if (fields!=null) { dbcache.put(entry, fields); } } return fields; } public void closeQuery(ResultSet res) throws KettleDatabaseException { // close everything involved in the query! try { if (res!=null) res.close(); if (sel_stmt!=null) { sel_stmt.close(); sel_stmt=null; } if (pstmt!=null) { pstmt.close(); pstmt=null;} } catch(SQLException ex) { throw new KettleDatabaseException("Couldn't close query: resultset or prepared statements", ex); } } private Row getRowInfo(ResultSetMetaData rm) throws KettleDatabaseException { return getRowInfo(rm, false); } // Build the row using ResultSetMetaData rsmd private Row getRowInfo(ResultSetMetaData rm, boolean ignoreLength) throws KettleDatabaseException { int nrcols; int i; Value v; String name; int type, valtype; int precision; int length; if (rm==null) return null; rowinfo = new Row(); try { nrcols=rm.getColumnCount(); for (i=1;i<=nrcols;i++) { name=new String(rm.getColumnName(i)); type=rm.getColumnType(i); valtype=Value.VALUE_TYPE_NONE; length=-1; precision=-1; switch(type) { case java.sql.Types.CHAR: case java.sql.Types.VARCHAR: case java.sql.Types.LONGVARCHAR: // Character Large Object valtype=Value.VALUE_TYPE_STRING; if (!ignoreLength) length=rm.getColumnDisplaySize(i); // System.out.println("Display of "+name+" = "+precision); // System.out.println("Precision of "+name+" = "+rm.getPrecision(i)); // System.out.println("Scale of "+name+" = "+rm.getScale(i)); break; case java.sql.Types.CLOB: valtype=Value.VALUE_TYPE_STRING; length=DatabaseMeta.CLOB_LENGTH; break; case java.sql.Types.BIGINT: valtype=Value.VALUE_TYPE_INTEGER; precision=0; // Max 9.223.372.036.854.775.807 length=15; break; case java.sql.Types.INTEGER: valtype=Value.VALUE_TYPE_INTEGER; precision=0; // Max 2.147.483.647 length=9; break; case java.sql.Types.SMALLINT: valtype=Value.VALUE_TYPE_INTEGER; precision=0; // Max 32.767 length=4; break; case java.sql.Types.TINYINT: valtype=Value.VALUE_TYPE_INTEGER; precision=0; // Max 127 length=2; break; case java.sql.Types.DECIMAL: case java.sql.Types.DOUBLE: case java.sql.Types.FLOAT: case java.sql.Types.REAL: case java.sql.Types.NUMERIC: valtype=Value.VALUE_TYPE_NUMBER; length=rm.getPrecision(i); precision=rm.getScale(i); if (length >=126) length=-1; if (precision >=126) precision=-1; if (type==java.sql.Types.DOUBLE || type==java.sql.Types.FLOAT || type==java.sql.Types.REAL) { if (precision==0) { precision=-1; // precision is obviously incorrect if the type if Double/Float/Real } // If were dealing with Postgres and double precision types if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_POSTGRES && type==java.sql.Types.DOUBLE && precision==16 && length==16) { precision=-1; length=-1; } } else { if (precision==0 && length<18 && length>0) // Among others Oracle is affected here. { valtype=Value.VALUE_TYPE_INTEGER; } } if (length>18 || precision>18) valtype=Value.VALUE_TYPE_BIGNUMBER; if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE) { if (precision<=0 && length<=0) // undefined size: BIGNUMBER { valtype=Value.VALUE_TYPE_BIGNUMBER; length=-1; precision=-1; } } break; case java.sql.Types.DATE: case java.sql.Types.TIME: case java.sql.Types.TIMESTAMP: valtype=Value.VALUE_TYPE_DATE; break; case java.sql.Types.BOOLEAN: case java.sql.Types.BIT: valtype=Value.VALUE_TYPE_BOOLEAN; break; default: valtype=Value.VALUE_TYPE_STRING; length=rm.getPrecision(i); precision=rm.getScale(i); break; } // TODO: grab the comment as a description to the field, later // comment=rm.getColumnLabel(i); v=new Value(name, valtype); v.setLength(length, precision); rowinfo.addValue(v); } return rowinfo; } catch(SQLException ex) { throw new KettleDatabaseException("Error getting row information from database: ", ex); } } // Build the row using ResultSetMetaData rsmd /* private Row getRowInfo() throws KettleDatabaseException { return getRowInfo(rsmd); } */ public boolean absolute(ResultSet rs, int position) throws KettleDatabaseException { try { return rs.absolute(position); } catch(SQLException e) { throw new KettleDatabaseException("Unable to move resultset to position "+position, e); } } public boolean relative(ResultSet rs, int rows) throws KettleDatabaseException { try { return rs.relative(rows); } catch(SQLException e) { throw new KettleDatabaseException("Unable to move the resultset forward "+rows+" rows", e); } } public void afterLast(ResultSet rs) throws KettleDatabaseException { try { rs.afterLast(); } catch(SQLException e) { throw new KettleDatabaseException("Unable to move resultset to after the last position", e); } } public void first(ResultSet rs) throws KettleDatabaseException { try { rs.first(); } catch(SQLException e) { throw new KettleDatabaseException("Unable to move resultset to the first position", e); } } /** * Get a row from the resultset. * @param rs The resultset to get the row from * @return one row or null if no row was found on the resultset or if an error occurred. */ public Row getRow(ResultSet rs) throws KettleDatabaseException { ResultSetMetaData rsmd = null; try { rsmd = rs.getMetaData(); } catch(SQLException e) { throw new KettleDatabaseException("Unable to retrieve metadata from resultset", e); } if (rowinfo==null) { rowinfo = getRowInfo(rsmd); } return getRow(rs, rsmd, rowinfo); } /** * Get a row from the resultset. * @param rs The resultset to get the row from * @return one row or null if no row was found on the resultset or if an error occurred. */ public Row getRow(ResultSet rs, ResultSetMetaData resultSetMetaData, Row rowInfo) throws KettleDatabaseException { Row row; int nrcols, i; Value val; try { nrcols=resultSetMetaData.getColumnCount(); if (rs.next()) { row=new Row(); for (i=0;i<nrcols;i++) { val=new Value(rowInfo.getValue(i)); // copy info from meta-data. switch(val.getType()) { case Value.VALUE_TYPE_BOOLEAN : val.setValue( rs.getBoolean(i+1) ); break; case Value.VALUE_TYPE_NUMBER : val.setValue( rs.getDouble(i+1) ); break; case Value.VALUE_TYPE_BIGNUMBER : val.setValue( rs.getBigDecimal(i+1) ); break; case Value.VALUE_TYPE_INTEGER : val.setValue( rs.getLong(i+1) ); break; case Value.VALUE_TYPE_STRING : val.setValue( rs.getString(i+1) ); break; case Value.VALUE_TYPE_DATE : if (databaseMeta.supportsTimeStampToDateConversion()) { val.setValue( rs.getTimestamp(i+1) ); break; } else { val.setValue( rs.getDate(i+1) ); break; } default: break; } if (rs.wasNull()) val.setNull(); // null value! row.addValue(val); } } else { row=null; } return row; } catch(SQLException ex) { throw new KettleDatabaseException("Couldn't get row from result set", ex); } } public void printSQLException(SQLException ex) { log.logError(toString(), "==> SQLException: "); while (ex != null) { log.logError(toString(), "Message: " + ex.getMessage ()); log.logError(toString(), "SQLState: " + ex.getSQLState ()); log.logError(toString(), "ErrorCode: " + ex.getErrorCode ()); ex = ex.getNextException(); log.logError(toString(), ""); } } public void setLookup(String table, String codes[], String condition[], String gets[], String rename[], String orderby ) throws KettleDatabaseException { setLookup(table, codes, condition, gets, rename, orderby, false); } // Lookup certain fields in a table public void setLookup(String table, String codes[], String condition[], String gets[], String rename[], String orderby, boolean checkForMultipleResults) throws KettleDatabaseException { String sql = "SELECT "; for (int i=0;i<gets.length;i++) { if (i!=0) sql += ", "; sql += databaseMeta.quoteField(gets[i]); if (rename!=null && rename[i]!=null && !gets[i].equalsIgnoreCase(rename[i])) { sql+=" AS "+databaseMeta.quoteField(rename[i]); } } sql += " FROM "+databaseMeta.quoteField(table)+" WHERE "; for (int i=0;i<codes.length;i++) { if (i!=0) sql += " AND "; sql += databaseMeta.quoteField(codes[i]); if ("BETWEEN".equalsIgnoreCase(condition[i])) { sql+=" BETWEEN ? AND ? "; } else if ("IS NULL".equalsIgnoreCase(condition[i]) || "IS NOT NULL".equalsIgnoreCase(condition[i])) { sql+=" "+condition[i]+" "; } else { sql+=" "+condition[i]+" ? "; } } if (orderby!=null && orderby.length()!=0) { sql += " ORDER BY "+orderby; } try { log.logDetailed(toString(), "Setting preparedStatement to ["+sql+"]"); prepStatementLookup=connection.prepareStatement(databaseMeta.stripCR(sql)); if (!checkForMultipleResults) { prepStatementLookup.setMaxRows(1); // alywas get only 1 line back! } } catch(SQLException ex) { throw new KettleDatabaseException("Unable to prepare statement for update ["+sql+"]", ex); } } // Lookup certain fields in a table public boolean prepareUpdate(String table, String codes[], String condition[], String sets[]) { StringBuffer sql = new StringBuffer(128); int i; sql.append("UPDATE ").append(databaseMeta.quoteField(table)).append(Const.CR).append("SET "); for (i=0;i<sets.length;i++) { if (i!=0) sql.append(", "); sql.append(databaseMeta.quoteField(sets[i])); sql.append(" = ?").append(Const.CR); } sql.append("WHERE "); for (i=0;i<codes.length;i++) { if (i!=0) sql.append("AND "); sql.append(databaseMeta.quoteField(codes[i])); if ("BETWEEN".equalsIgnoreCase(condition[i])) { sql.append(" BETWEEN ? AND ? "); } else if ("IS NULL".equalsIgnoreCase(condition[i]) || "IS NOT NULL".equalsIgnoreCase(condition[i])) { sql.append(" ").append(condition[i]).append(" "); } else { sql.append(" ").append(condition[i]).append(" ? "); } } try { String s = sql.toString(); log.logDetailed(toString(), "Setting update preparedStatement to ["+s+"]"); prepStatementUpdate=connection.prepareStatement(databaseMeta.stripCR(s)); } catch(SQLException ex) { printSQLException(ex); return false; } return true; } /** * Prepare a delete statement by giving it the tablename, fields and conditions to work with. * @param table The table-name to delete in * @param codes * @param condition * @return */ public boolean prepareDelete(String table, String codes[], String condition[]) { String sql; int i; sql = "DELETE FROM "+table+Const.CR; sql+= "WHERE "; for (i=0;i<codes.length;i++) { if (i!=0) sql += "AND "; sql += codes[i]; if ("BETWEEN".equalsIgnoreCase(condition[i])) { sql+=" BETWEEN ? AND ? "; } else if ("IS NULL".equalsIgnoreCase(condition[i]) || "IS NOT NULL".equalsIgnoreCase(condition[i])) { sql+=" "+condition[i]+" "; } else { sql+=" "+condition[i]+" ? "; } } try { log.logDetailed(toString(), "Setting update preparedStatement to ["+sql+"]"); prepStatementUpdate=connection.prepareStatement(databaseMeta.stripCR(sql)); } catch(SQLException ex) { printSQLException(ex); return false; } return true; } public void setProcLookup(String proc, String arg[], String argdir[], int argtype[], String returnvalue, int returntype) throws KettleDatabaseException { String sql; int pos=0; int i; sql = "{ "; if (returnvalue!=null && returnvalue.length()!=0) { sql+="? = "; } sql+="call "+proc+" "; if (arg.length>0) sql+="("; for (i=0;i<arg.length;i++) { if (i!=0) sql += ", "; sql += " ?"; } if (arg.length>0) sql+=")"; sql+="}"; try { log.logDetailed(toString(), "DBA setting callableStatement to ["+sql+"]"); cstmt=connection.prepareCall(sql); pos=1; if (!Const.isEmpty(returnvalue)) { switch(returntype) { case Value.VALUE_TYPE_NUMBER : cstmt.registerOutParameter(pos, java.sql.Types.DOUBLE); break; case Value.VALUE_TYPE_BIGNUMBER : cstmt.registerOutParameter(pos, java.sql.Types.DECIMAL); break; case Value.VALUE_TYPE_INTEGER : cstmt.registerOutParameter(pos, java.sql.Types.BIGINT); break; case Value.VALUE_TYPE_STRING : cstmt.registerOutParameter(pos, java.sql.Types.VARCHAR); break; case Value.VALUE_TYPE_DATE : cstmt.registerOutParameter(pos, java.sql.Types.TIMESTAMP); break; case Value.VALUE_TYPE_BOOLEAN : cstmt.registerOutParameter(pos, java.sql.Types.BOOLEAN); break; default: break; } pos++; } for (i=0;i<arg.length;i++) { if (argdir[i].equalsIgnoreCase("OUT") || argdir[i].equalsIgnoreCase("INOUT")) { switch(argtype[i]) { case Value.VALUE_TYPE_NUMBER : cstmt.registerOutParameter(i+pos, java.sql.Types.DOUBLE); break; case Value.VALUE_TYPE_BIGNUMBER : cstmt.registerOutParameter(i+pos, java.sql.Types.DECIMAL); break; case Value.VALUE_TYPE_INTEGER : cstmt.registerOutParameter(i+pos, java.sql.Types.BIGINT); break; case Value.VALUE_TYPE_STRING : cstmt.registerOutParameter(i+pos, java.sql.Types.VARCHAR); break; case Value.VALUE_TYPE_DATE : cstmt.registerOutParameter(i+pos, java.sql.Types.TIMESTAMP); break; case Value.VALUE_TYPE_BOOLEAN : cstmt.registerOutParameter(i+pos, java.sql.Types.BOOLEAN); break; default: break; } } } } catch(SQLException ex) { throw new KettleDatabaseException("Unable to prepare database procedure call", ex); } } /* * table: dimension table * keys[]: which dim-fields do we use to look up key? * retval: name of the key to return * datefield: do we have a datefield? * datefrom, dateto: date-range, if any. */ public boolean setDimLookup(String table, String keys[], String tk, String version, String extra[], String extraRename[], String datefrom, String dateto ) throws KettleDatabaseException { String sql; int i; /* * SELECT <tk>, <version>, ... * FROM <table> * WHERE key1=keys[1] * AND key2=keys[2] ... * AND <datefield> BETWEEN <datefrom> AND <dateto> * ; * */ sql = "SELECT "+databaseMeta.quoteField(tk)+", "+databaseMeta.quoteField(version); if (extra!=null) { for (i=0;i<extra.length;i++) { if (extra[i]!=null && extra[i].length()!=0) { sql+=", "+databaseMeta.quoteField(extra[i]); if (extraRename[i]!=null && extraRename[i].length()>0 && !extra[i].equals(extraRename[i])) { sql+=" AS "+databaseMeta.quoteField(extraRename[i]); } } } } sql+= " FROM "+databaseMeta.quoteField(table)+" WHERE "; for (i=0;i<keys.length;i++) { if (i!=0) sql += " AND "; sql += databaseMeta.quoteField(keys[i])+" = ? "; } sql += " AND ? >= "+databaseMeta.quoteField(datefrom)+" AND ? < "+databaseMeta.quoteField(dateto); try { log.logDetailed(toString(), "Dimension Lookup setting preparedStatement to ["+sql+"]"); prepStatementLookup=connection.prepareStatement(databaseMeta.stripCR(sql)); prepStatementLookup.setMaxRows(1); // alywas get only 1 line back! log.logDetailed(toString(), "Finished preparing dimension lookup statement."); } catch(SQLException ex) { throw new KettleDatabaseException("Unable to prepare dimension lookup", ex); } return true; } /* CombinationLookup * table: dimension table * keys[]: which dim-fields do we use to look up key? * retval: name of the key to return */ public void setCombiLookup(String table, String keys[], String retval, boolean crc, String crcfield ) throws KettleDatabaseException { StringBuffer sql = new StringBuffer(100); int i; boolean comma; /* * SELECT <retval> * FROM <table> * WHERE ( ( <key1> = ? ) OR ( <key1> IS NULL AND ? IS NULL ) ) * AND ( ( <key2> = ? ) OR ( <key1> IS NULL AND ? IS NULL ) ) * ... * ; * * OR * * SELECT <retval> * FROM <table> * WHERE <crcfield> = ? * AND ( ( <key1> = ? ) OR ( <key1> IS NULL AND ? IS NULL ) ) * AND ( ( <key2> = ? ) OR ( <key1> IS NULL AND ? IS NULL ) ) * ... * ; * */ sql.append("SELECT ").append(databaseMeta.quoteField(retval)).append(Const.CR); sql.append("FROM ").append(databaseMeta.quoteField(table)).append(Const.CR); sql.append("WHERE "); comma=false; if (crc) { sql.append(databaseMeta.quoteField(crcfield)).append(" = ? ").append(Const.CR); comma=true; } else { sql.append("( ( "); } for (i=0;i<keys.length;i++) { if (comma) { sql.append(" AND ( ( "); } else { comma=true; } sql.append(databaseMeta.quoteField(keys[i])).append(" = ? ) OR ( ").append(databaseMeta.quoteField(keys[i])).append(" IS NULL AND ? IS NULL ) )").append(Const.CR); } try { String sqlStatement = sql.toString(); log.logDebug(toString(), "preparing combi-lookup statement:"+Const.CR+sqlStatement); prepStatementLookup=connection.prepareStatement(databaseMeta.stripCR(sqlStatement)); prepStatementLookup.setMaxRows(1); // alywas get only 1 line back! } catch(SQLException ex) { throw new KettleDatabaseException("Unable to prepare combi-lookup statement", ex); } } public Row callProcedure(String arg[], String argdir[], int argtype[], String resultname, int resulttype) throws KettleDatabaseException { Row ret; try { cstmt.execute(); ret=new Row(); int pos=1; if (resultname!=null && resultname.length()!=0) { Value v=new Value(resultname, Value.VALUE_TYPE_NONE); switch(resulttype) { case Value.VALUE_TYPE_BOOLEAN : v.setValue( cstmt.getBoolean(pos) ); break; case Value.VALUE_TYPE_NUMBER : v.setValue( cstmt.getDouble(pos) ); break; case Value.VALUE_TYPE_BIGNUMBER : v.setValue( cstmt.getBigDecimal(pos)); break; case Value.VALUE_TYPE_INTEGER : v.setValue( cstmt.getLong(pos) ); break; case Value.VALUE_TYPE_STRING : v.setValue( cstmt.getString(pos) ); break; case Value.VALUE_TYPE_DATE : v.setValue( cstmt.getTimestamp(pos) ); break; } ret.addValue(v); pos++; } for (int i=0;i<arg.length;i++) { if (argdir[i].equalsIgnoreCase("OUT") || argdir[i].equalsIgnoreCase("INOUT")) { Value v=new Value(arg[i], Value.VALUE_TYPE_NONE); switch(argtype[i]) { case Value.VALUE_TYPE_BOOLEAN : v.setValue( cstmt.getBoolean(pos+i) ); break; case Value.VALUE_TYPE_NUMBER : v.setValue( cstmt.getDouble(pos+i) ); break; case Value.VALUE_TYPE_BIGNUMBER : v.setValue( cstmt.getBigDecimal(pos+i)); break; case Value.VALUE_TYPE_INTEGER : v.setValue( cstmt.getLong(pos+i) ); break; case Value.VALUE_TYPE_STRING : v.setValue( cstmt.getString(pos+i) ); break; case Value.VALUE_TYPE_DATE : v.setValue( cstmt.getTimestamp(pos+i) ); break; } ret.addValue(v); } } return ret; } catch(SQLException ex) { throw new KettleDatabaseException("Unable to call procedure", ex); } } public Row getLookup() throws KettleDatabaseException { return getLookup(prepStatementLookup); } public Row getLookup(boolean failOnMultipleResults) throws KettleDatabaseException { return getLookup(prepStatementLookup, failOnMultipleResults); } public Row getLookup(PreparedStatement ps) throws KettleDatabaseException { return getLookup(ps, false); } public Row getLookup(PreparedStatement ps, boolean failOnMultipleResults) throws KettleDatabaseException { String debug = "start"; Row ret; try { debug = "pstmt.executeQuery()"; ResultSet res = ps.executeQuery(); debug = "getRowInfo()"; rowinfo = getRowInfo(res.getMetaData()); debug = "getRow(res)"; ret=getRow(res); if (failOnMultipleResults) { if (res.next()) { throw new KettleDatabaseException("Only 1 row was expected as a result of a lookup, and at least 2 were found!"); } } debug = "res.close()"; res.close(); // close resultset! return ret; } catch(SQLException ex) { throw new KettleDatabaseException("Error looking up row in database ("+debug+")", ex); } } public DatabaseMetaData getDatabaseMetaData() throws KettleDatabaseException { try { if (dbmd==null) dbmd = connection.getMetaData(); // Only get the metadata once! } catch(Exception e) { throw new KettleDatabaseException("Unable to get database metadata from this database connection", e); } return dbmd; } public String getDDL(String tablename, Row fields) throws KettleDatabaseException { return getDDL(tablename, fields, null, false, null, true); } public String getDDL(String tablename, Row fields, String tk, boolean use_autoinc, String pk) throws KettleDatabaseException { return getDDL(tablename, fields, tk, use_autoinc, pk, true); } public String getDDL(String tablename, Row fields, String tk, boolean use_autoinc, String pk, boolean semicolon) throws KettleDatabaseException { String retval; // First, check for reserved SQL in the input row r... databaseMeta.quoteReservedWords(fields); if (checkTableExists(tablename)) { retval=getAlterTableStatement(tablename, fields, tk, use_autoinc, pk, semicolon); } else { retval=getCreateTableStatement(tablename, fields, tk, use_autoinc, pk, semicolon); } return retval; } public String getCreateTableStatement(String tablename, Row fields, String tk, boolean use_autoinc, String pk, boolean semicolon) { String retval; retval = "CREATE TABLE "+databaseMeta.quoteField(tablename)+Const.CR; retval+= "("+Const.CR; for (int i=0;i<fields.size();i++) { if (i>0) retval+=", "; else retval+=" "; Value v=fields.getValue(i); retval+=databaseMeta.getFieldDefinition(v, tk, pk, use_autoinc); } // At the end, before the closing of the statement, we might need to add some constraints... // Technical keys if (tk!=null) { if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_CACHE) { retval+=", PRIMARY KEY ("+tk+")"+Const.CR; } } // Primary keys if (pk!=null) { if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE) { retval+=", PRIMARY KEY ("+pk+")"+Const.CR; } } retval+= ")"+Const.CR; if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_ORACLE && databaseMeta.getIndexTablespace()!=null && databaseMeta.getIndexTablespace().length()>0) { retval+="TABLESPACE "+databaseMeta.getDataTablespace(); } if (semicolon) retval+=";"; retval+=Const.CR; return retval; } public String getAlterTableStatement(String tablename, Row fields, String tk, boolean use_autoinc, String pk, boolean semicolon) throws KettleDatabaseException { String retval=""; String tableName = databaseMeta.quoteField(tablename); // Get the fields that are in the table now: Row tabFields = getTableFields(tablename); // Don't forget to quote these as well... databaseMeta.quoteReservedWords(tabFields); // Find the missing fields Row missing = new Row(); for (int i=0;i<fields.size();i++) { Value v = fields.getValue(i); // Not found? if (tabFields.searchValue( v.getName() )==null ) { missing.addValue(v); // nope --> Missing! } } if (missing.size()!=0) { for (int i=0;i<missing.size();i++) { Value v=missing.getValue(i); retval+=databaseMeta.getAddColumnStatement(tableName, v, tk, use_autoinc, pk, true); } } // Find the surplus fields Row surplus = new Row(); for (int i=0;i<tabFields.size();i++) { Value v = tabFields.getValue(i); // Found in table, not in input ? if (fields.searchValue( v.getName() )==null ) { surplus.addValue(v); // yes --> surplus! } } if (surplus.size()!=0) { for (int i=0;i<surplus.size();i++) { Value v=surplus.getValue(i); retval+=databaseMeta.getDropColumnStatement(tableName, v, tk, use_autoinc, pk, true); } } // OK, see if there are fields for wich we need to modify the type... (length, precision) Row modify = new Row(); for (int i=0;i<fields.size();i++) { Value desiredField = fields.getValue(i); Value currentField = tabFields.searchValue( desiredField.getName()); if (currentField!=null) { boolean mod = false; mod |= ( currentField.getLength() < desiredField.getLength() ) && desiredField.getLength()>0; mod |= ( currentField.getPrecision() < desiredField.getPrecision() ) && desiredField.getPrecision()>0; // Numeric values... mod |= ( currentField.getType() != desiredField.getType() ) && ( currentField.isNumber()^desiredField.isNumeric() ); if (mod) { // System.out.println("Desired field: ["+desiredField.toStringMeta()+"], current field: ["+currentField.toStringMeta()+"]"); modify.addValue(desiredField); } } } if (modify.size()>0) { for (int i=0;i<modify.size();i++) { Value v=modify.getValue(i); retval+=databaseMeta.getModifyColumnStatement(tableName, v, tk, use_autoinc, pk, true); } } return retval; } public void checkDimZero(String tablename, String tk, String version, boolean use_autoinc) throws KettleDatabaseException { int start_tk = databaseMeta.getNotFoundTK(use_autoinc); String sql = "SELECT count(*) FROM "+databaseMeta.quoteField(tablename)+" WHERE "+databaseMeta.quoteField(tk)+" = "+start_tk; ResultSet rs = openQuery(sql, null); Row r = getRow(rs); // One value: a number; Value count = r.getValue(0); if (count.getNumber() == 0) { try { Statement st = connection.createStatement(); String isql; if (!databaseMeta.supportsAutoinc() || !use_autoinc) { isql = isql = "insert into "+databaseMeta.quoteField(tablename)+"("+databaseMeta.quoteField(tk)+", "+databaseMeta.quoteField(version)+") values (0, 1)"; } else { switch(databaseMeta.getDatabaseType()) { case DatabaseMeta.TYPE_DATABASE_CACHE : case DatabaseMeta.TYPE_DATABASE_GUPTA : case DatabaseMeta.TYPE_DATABASE_ORACLE : isql = "insert into "+databaseMeta.quoteField(tablename)+"("+databaseMeta.quoteField(tk)+", "+databaseMeta.quoteField(version)+") values (0, 1)"; break; case DatabaseMeta.TYPE_DATABASE_INFORMIX : case DatabaseMeta.TYPE_DATABASE_MYSQL : isql = "insert into "+databaseMeta.quoteField(tablename)+"("+databaseMeta.quoteField(tk)+", "+databaseMeta.quoteField(version)+") values (1, 1)"; break; case DatabaseMeta.TYPE_DATABASE_MSSQL : case DatabaseMeta.TYPE_DATABASE_DB2 : case DatabaseMeta.TYPE_DATABASE_DBASE : case DatabaseMeta.TYPE_DATABASE_GENERIC : case DatabaseMeta.TYPE_DATABASE_SYBASE : case DatabaseMeta.TYPE_DATABASE_ACCESS : isql = "insert into "+databaseMeta.quoteField(tablename)+"("+databaseMeta.quoteField(version)+") values (1)"; break; default: isql = "insert into "+databaseMeta.quoteField(tablename)+"("+databaseMeta.quoteField(tk)+", "+databaseMeta.quoteField(version)+") values (0, 1)"; break; } } st.executeUpdate(databaseMeta.stripCR(isql)); } catch(SQLException e) { throw new KettleDatabaseException("Error inserting 'unknown' row in dimension ["+tablename+"] : "+sql, e); } } } public Value checkSequence(String seqname) throws KettleDatabaseException { String sql=null; if (databaseMeta.supportsSequences()) { sql = databaseMeta.getSQLCurrentSequenceValue(seqname); ResultSet rs = openQuery(sql, null); Row r = getRow(rs); // One value: a number; if (r!=null) { Value last = r.getValue(0); // errorstr="Sequence is at number: "+last.toString(); return last; } else { return null; } } else { throw new KettleDatabaseException("Sequences are only available for Oracle databases."); } } public void truncateTable(String tablename) throws KettleDatabaseException { execStatement(databaseMeta.getTruncateTableStatement(tablename)); } /** * Execute a query and return at most one row from the resultset * @param sql The SQL for the query * @return one Row with data or null if nothing was found. */ public Row getOneRow(String sql) throws KettleDatabaseException { ResultSet rs = openQuery(sql, null); if (rs!=null) { Row r = getRow(rs); // One row only; try { rs.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close resultset", e); } if (pstmt!=null) { try { pstmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement pstmt", e); } pstmt=null; } if (sel_stmt!=null) { try { sel_stmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement sel_stmt", e); } sel_stmt=null; } return r; } else { throw new KettleDatabaseException("error opening resultset for query: "+sql); } } public Row getOneRow(String sql, Row param) throws KettleDatabaseException { ResultSet rs = openQuery(sql, param); if (rs!=null) { Row r = getRow(rs); // One value: a number; try { rs.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close resultset", e); } if (pstmt!=null) { try { pstmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement pstmt", e); } pstmt=null; } if (sel_stmt!=null) { try { sel_stmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement sel_stmt", e); } sel_stmt=null; } rowinfo=null; return r; } else { return null; } } public Row getParameterMetaData(PreparedStatement ps) { Row par = new Row(); try { ParameterMetaData pmd = ps.getParameterMetaData(); for (int i=1;i<pmd.getParameterCount();i++) { String name = "par"+i; int sqltype = pmd.getParameterType(i); int length = pmd.getPrecision(i); int precision = pmd.getScale(i); Value val; switch(sqltype) { case java.sql.Types.CHAR: case java.sql.Types.VARCHAR: val=new Value(name, Value.VALUE_TYPE_STRING); break; case java.sql.Types.BIGINT: case java.sql.Types.INTEGER: case java.sql.Types.NUMERIC: case java.sql.Types.SMALLINT: case java.sql.Types.TINYINT: val=new Value(name, Value.VALUE_TYPE_INTEGER); break; case java.sql.Types.DECIMAL: case java.sql.Types.DOUBLE: case java.sql.Types.FLOAT: case java.sql.Types.REAL: val=new Value(name, Value.VALUE_TYPE_NUMBER); break; case java.sql.Types.DATE: case java.sql.Types.TIME: case java.sql.Types.TIMESTAMP: val=new Value(name, Value.VALUE_TYPE_DATE); break; case java.sql.Types.BOOLEAN: case java.sql.Types.BIT: val=new Value(name, Value.VALUE_TYPE_BOOLEAN); break; default: val=new Value(name, Value.VALUE_TYPE_NONE); break; } if (val.isNumeric() && ( length>18 || precision>18) ) { val = new Value(name, Value.VALUE_TYPE_BIGNUMBER); } val.setNull(); par.addValue(val); } } // Oops: probably the database or JDBC doesn't support it. catch(AbstractMethodError e) { return null; } catch(SQLException e) { return null; } catch(Exception e) { return null; } return par; } public int countParameters(String sql) { int q=0; boolean quote_opened=false; boolean dquote_opened=false; for (int x=0;x<sql.length();x++) { char c = sql.charAt(x); switch(c) { case '\'': quote_opened= !quote_opened; break; case '"' : dquote_opened=!dquote_opened; break; case '?' : if (!quote_opened && !dquote_opened) q++; break; } } return q; } // Get the fields back from an SQL query public Row getParameterMetaData(String sql, Row inform) { // The database coudln't handle it: try manually! int q=countParameters(sql); Row par=new Row(); if (inform!=null && q==inform.size()) { for (int i=0;i<q;i++) { Value inf=inform.getValue(i); Value v = new Value(inf); par.addValue(v); } } else { for (int i=0;i<q;i++) { Value v = new Value("name"+i, Value.VALUE_TYPE_NUMBER); v.setValue( 0.0 ); par.addValue(v); } } return par; } public static final Row getTransLogrecordFields(boolean use_batchid, boolean use_logfield) { Row r = new Row(); Value v; if (use_batchid) { v=new Value("ID_BATCH", Value.VALUE_TYPE_INTEGER); v.setLength(8,0); r.addValue(v); } v=new Value("TRANSNAME", Value.VALUE_TYPE_STRING ); v.setLength(50); r.addValue(v); v=new Value("STATUS", Value.VALUE_TYPE_STRING ); v.setLength(15); r.addValue(v); v=new Value("LINES_READ", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v); v=new Value("LINES_WRITTEN", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v); v=new Value("LINES_UPDATED", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v); v=new Value("LINES_INPUT", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v); v=new Value("LINES_OUTPUT", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v); v=new Value("ERRORS", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v); v=new Value("STARTDATE", Value.VALUE_TYPE_DATE ); r.addValue(v); v=new Value("ENDDATE", Value.VALUE_TYPE_DATE ); r.addValue(v); v=new Value("LOGDATE", Value.VALUE_TYPE_DATE ); r.addValue(v); v=new Value("DEPDATE", Value.VALUE_TYPE_DATE ); r.addValue(v); v=new Value("REPLAYDATE", Value.VALUE_TYPE_DATE ); r.addValue(v); if (use_logfield) { v=new Value("LOG_FIELD", Value.VALUE_TYPE_STRING); v.setLength(DatabaseMeta.CLOB_LENGTH,0); r.addValue(v); } return r; } public static final Row getJobLogrecordFields(boolean use_jobid, boolean use_logfield) { Row r = new Row(); Value v; if (use_jobid) { v=new Value("ID_JOB", Value.VALUE_TYPE_STRING); v.setLength(50); r.addValue(v); } v=new Value("JOBNAME", Value.VALUE_TYPE_STRING); v.setLength(50); r.addValue(v); v=new Value("STATUS", Value.VALUE_TYPE_STRING); v.setLength(15); r.addValue(v); v=new Value("LINES_READ", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v); v=new Value("LINES_WRITTEN", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v); v=new Value("LINES_UPDATED", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v); v=new Value("LINES_INPUT", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v); v=new Value("LINES_OUTPUT", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v); v=new Value("ERRORS", Value.VALUE_TYPE_INTEGER); v.setLength(10,0); r.addValue(v); v=new Value("STARTDATE", Value.VALUE_TYPE_DATE ); r.addValue(v); v=new Value("ENDDATE", Value.VALUE_TYPE_DATE ); r.addValue(v); v=new Value("LOGDATE", Value.VALUE_TYPE_DATE ); r.addValue(v); v=new Value("DEPDATE", Value.VALUE_TYPE_DATE ); r.addValue(v); v=new Value("REPLAYDATE", Value.VALUE_TYPE_DATE ); r.addValue(v); if (use_logfield) { v=new Value("LOG_FIELD", Value.VALUE_TYPE_STRING); v.setLength(DatabaseMeta.CLOB_LENGTH,0); r.addValue(v); } return r; } public void writeLogRecord( String logtable, boolean use_id, long id, boolean job, String name, String status, long read, long written, long updated, long input, long output, long errors, java.util.Date startdate, java.util.Date enddate, java.util.Date logdate, java.util.Date depdate, java.util.Date replayDate, String log_string ) throws KettleDatabaseException { if (use_id && log_string!=null && !status.equalsIgnoreCase("start")) { String sql = "UPDATE "+logtable+" SET STATUS=?, LINES_READ=?, LINES_WRITTEN=?, LINES_INPUT=?," + " LINES_OUTPUT=?, LINES_UPDATED=?, ERRORS=?, STARTDATE=?, ENDDATE=?, LOGDATE=?, DEPDATE=?, REPLAYDATE=?, LOG_FIELD=? " + "WHERE "; if (job) sql+="ID_JOB=?"; else sql+="ID_BATCH=?"; Row r = new Row(); r.addValue( new Value("STATUS", status )); r.addValue( new Value("LINES_READ", (long)read )); r.addValue( new Value("LINES_WRITTEN", (long)written)); r.addValue( new Value("LINES_INPUT", (long)input )); r.addValue( new Value("LINES_OUTPUT", (long)output )); r.addValue( new Value("LINES_UPDATED", (long)updated)); r.addValue( new Value("ERRORS", (long)errors )); r.addValue( new Value("STARTDATE", startdate )); r.addValue( new Value("ENDDATE", enddate )); r.addValue( new Value("LOGDATE", logdate )); r.addValue( new Value("DEPDATE", depdate )); r.addValue( new Value("REPLAYDATE", replayDate )); Value logfield = new Value("LOG_FIELD", log_string); logfield.setLength(DatabaseMeta.CLOB_LENGTH); r.addValue( logfield ); r.addValue( new Value("ID_BATCH", id )); execStatement(sql, r); } else { int parms; String sql = "INSERT INTO "+logtable+" ( "; if (job) { if (use_id) { sql+="ID_JOB, JOBNAME"; parms=14; } else { sql+="JOBNAME"; parms=13; } } else { if (use_id) { sql+="ID_BATCH, TRANSNAME"; parms=14; } else { sql+="TRANSNAME"; parms=13; } } sql+=", STATUS, LINES_READ, LINES_WRITTEN, LINES_UPDATED, LINES_INPUT, LINES_OUTPUT, ERRORS, STARTDATE, ENDDATE, LOGDATE, DEPDATE, REPLAYDATE"; if (log_string!=null && log_string.length()>0) sql+=", LOG_FIELD"; // This is possibly a CLOB! sql+=") VALUES("; for (int i=0;i<parms;i++) if (i==0) sql+="?"; else sql+=", ?"; if (log_string!=null && log_string.length()>0) sql+=", ?"; sql+=")"; try { pstmt = connection.prepareStatement(databaseMeta.stripCR(sql)); Row r = new Row(); if (job) { if (use_id) { r.addValue( new Value("ID_BATCH", id )); } r.addValue( new Value("TRANSNAME", name )); } else { if (use_id) { r.addValue( new Value("ID_JOB", id )); } r.addValue( new Value("JOBNAME", name )); } r.addValue( new Value("STATUS", status )); r.addValue( new Value("LINES_READ", (long)read )); r.addValue( new Value("LINES_WRITTEN", (long)written)); r.addValue( new Value("LINES_UPDATED", (long)updated)); r.addValue( new Value("LINES_INPUT", (long)input )); r.addValue( new Value("LINES_OUTPUT", (long)output )); r.addValue( new Value("ERRORS", (long)errors )); r.addValue( new Value("STARTDATE", startdate )); r.addValue( new Value("ENDDATE", enddate )); r.addValue( new Value("LOGDATE", logdate )); r.addValue( new Value("DEPDATE", depdate )); r.addValue( new Value("REPLAYDATE", replayDate )); if (log_string!=null && log_string.length()>0) { Value large = new Value("LOG_FIELD", log_string ); large.setLength(DatabaseMeta.CLOB_LENGTH); r.addValue( large ); } setValues(r); pstmt.executeUpdate(); pstmt.close(); pstmt=null; } catch(SQLException ex) { throw new KettleDatabaseException("Unable to write log record to log table "+logtable, ex); } } } public Row getLastLogDate( String logtable, String name, boolean job, String status ) throws KettleDatabaseException { Row row=null; String jobtrans = job?"JOBNAME":"TRANSNAME"; String sql = ""; sql+=" SELECT ENDDATE, DEPDATE, STARTDATE"; sql+=" FROM "+logtable; sql+=" WHERE ERRORS = 0"; sql+=" AND STATUS = 'end'"; sql+=" AND "+jobtrans+" = ?"; sql+=" ORDER BY LOGDATE DESC, ENDDATE DESC"; try { pstmt = connection.prepareStatement(databaseMeta.stripCR(sql)); Row r = new Row(); r.addValue( new Value("TRANSNAME", name )); setValues(r); ResultSet res = pstmt.executeQuery(); if (res!=null) { rowinfo = getRowInfo(res.getMetaData()); row = getRow(res); res.close(); } pstmt.close(); pstmt=null; } catch(SQLException ex) { throw new KettleDatabaseException("Unable to obtain last logdate from table "+logtable, ex); } return row; } public synchronized void getNextValue(Hashtable counters, String table, Value val_key) throws KettleDatabaseException { String lookup = databaseMeta.quoteField(table)+"."+databaseMeta.quoteField(val_key.getName()); // Try to find the previous sequence value... Counter counter = null; if (counters!=null) counter=(Counter)counters.get(lookup); if (counter==null) { Row r = getOneRow("SELECT MAX("+databaseMeta.quoteField(val_key.getName())+") FROM "+databaseMeta.quoteField(table)); if (r!=null) { counter = new Counter(r.getValue(0).getInteger()+1, 1); val_key.setValue(counter.next()); if (counters!=null) counters.put(lookup, counter); } else { throw new KettleDatabaseException("Couldn't find maximum key value from table "+table); } } else { val_key.setValue(counter.next()); } } public String toString() { if (databaseMeta!=null) return databaseMeta.getName(); else return "-"; } public boolean isSystemTable(String table_name) { if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_MSSQL) { if ( table_name.startsWith("sys")) return true; if ( table_name.equals("dtproperties")) return true; } else if (databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_GUPTA) { if ( table_name.startsWith("SYS")) return true; } return false; } /** Reads the result of an SQL query into an ArrayList * * @param sql The SQL to launch * @param limit <=0 means unlimited, otherwise this specifies the maximum number of rows read. * @return An ArrayList of rows. * @throws KettleDatabaseException if something goes wrong. */ public ArrayList getRows(String sql, int limit) throws KettleDatabaseException { return getRows(sql, limit, null); } /** Reads the result of an SQL query into an ArrayList * * @param sql The SQL to launch * @param limit <=0 means unlimited, otherwise this specifies the maximum number of rows read. * @param monitor The progress monitor to update while getting the rows. * @return An ArrayList of rows. * @throws KettleDatabaseException if something goes wrong. */ public ArrayList getRows(String sql, int limit, IProgressMonitor monitor) throws KettleDatabaseException { if (monitor!=null) monitor.setTaskName("Opening query..."); ResultSet rset = openQuery(sql); return getRows(rset, limit, monitor); } /** Reads the result of a ResultSet into an ArrayList * * @param rset the ResultSet to read out * @param limit <=0 means unlimited, otherwise this specifies the maximum number of rows read. * @param monitor The progress monitor to update while getting the rows. * @return An ArrayList of rows. * @throws KettleDatabaseException if something goes wrong. */ public ArrayList getRows(ResultSet rset, int limit, IProgressMonitor monitor) throws KettleDatabaseException { try { ArrayList result = new ArrayList(); boolean stop=false; int i=0; if (rset!=null) { if (monitor!=null && limit>0) monitor.beginTask("Reading rows...", limit); while ((limit<=0 || i<limit) && !stop) { Row row = getRow(rset); if (row!=null) { result.add(row); i++; } else { stop=true; } if (monitor!=null && limit>0) monitor.worked(1); } closeQuery(rset); if (monitor!=null) monitor.done(); } return result; } catch(Exception e) { throw new KettleDatabaseException("Unable to get list of rows from ResultSet : ", e); } } public ArrayList getFirstRows(String table_name, int limit) throws KettleDatabaseException { return getFirstRows(table_name, limit, null); } public ArrayList getFirstRows(String table_name, int limit, IProgressMonitor monitor) throws KettleDatabaseException { String sql = "SELECT * FROM "+databaseMeta.quoteField(table_name); if (limit>0) { sql+=databaseMeta.getLimitClause(limit); } return getRows(sql, limit, monitor); } public Row getReturnRow() { return rowinfo; } public String[] getTableTypes() throws KettleDatabaseException { try { ArrayList types = new ArrayList(); ResultSet rstt = getDatabaseMetaData().getTableTypes(); while(rstt.next()) { String ttype = rstt.getString("TABLE_TYPE"); types.add(ttype); } return (String[])types.toArray(new String[types.size()]); } catch(SQLException e) { throw new KettleDatabaseException("Unable to get table types from database!", e); } } public String[] getTablenames() throws KettleDatabaseException { String schemaname = null; if (databaseMeta.useSchemaNameForTableList()) schemaname = databaseMeta.getUsername().toUpperCase(); ArrayList names = new ArrayList(); ResultSet alltables=null; try { alltables = getDatabaseMetaData().getTables(null, schemaname, null, databaseMeta.getTableTypes() ); while (alltables.next()) { String table = alltables.getString("TABLE_NAME"); log.logRowlevel(toString(), "got table from meta-data: "+table); names.add(table); } } catch(SQLException e) { log.logError(toString(), "Error getting tablenames from schema ["+schemaname+"]"); } finally { try { if (alltables!=null) alltables.close(); } catch(SQLException e) { throw new KettleDatabaseException("Error closing resultset after getting views from schema ["+schemaname+"]", e); } } log.logDetailed(toString(), "read :"+names.size()+" table names from db meta-data."); return (String[])names.toArray(new String[names.size()]); } public String[] getViews() throws KettleDatabaseException { if (!databaseMeta.supportsViews()) return new String[] {}; String schemaname = null; if (databaseMeta.useSchemaNameForTableList()) schemaname=databaseMeta.getUsername().toUpperCase(); ArrayList names = new ArrayList(); ResultSet alltables=null; try { alltables = dbmd.getTables(null, schemaname, null, databaseMeta.getViewTypes() ); while (alltables.next()) { String table = alltables.getString("TABLE_NAME"); log.logRowlevel(toString(), "got view from meta-data: "+table); names.add(table); } } catch(SQLException e) { throw new KettleDatabaseException("Error getting views from schema ["+schemaname+"]", e); } finally { try { if (alltables!=null) alltables.close(); } catch(SQLException e) { throw new KettleDatabaseException("Error closing resultset after getting views from schema ["+schemaname+"]", e); } } log.logDetailed(toString(), "read :"+names.size()+" views from db meta-data."); return (String[])names.toArray(new String[names.size()]); } public String[] getSynonyms() throws KettleDatabaseException { if (!databaseMeta.supportsSynonyms()) return new String[] {}; String schemaname = null; if (databaseMeta.useSchemaNameForTableList()) schemaname=databaseMeta.getUsername().toUpperCase(); ArrayList names = new ArrayList(); ResultSet alltables=null; try { alltables = dbmd.getTables(null, schemaname, null, databaseMeta.getSynonymTypes() ); while (alltables.next()) { String table = alltables.getString("TABLE_NAME"); log.logRowlevel(toString(), "got view from meta-data: "+table); names.add(table); } } catch(SQLException e) { throw new KettleDatabaseException("Error getting synonyms from schema ["+schemaname+"]", e); } finally { try { if (alltables!=null) alltables.close(); } catch(SQLException e) { throw new KettleDatabaseException("Error closing resultset after getting synonyms from schema ["+schemaname+"]", e); } } log.logDetailed(toString(), "read :"+names.size()+" views from db meta-data."); return (String[])names.toArray(new String[names.size()]); } public String[] getProcedures() throws KettleDatabaseException { String sql = databaseMeta.getSQLListOfProcedures(); if (sql!=null) { //System.out.println("SQL= "+sql); ArrayList procs = getRows(sql, 1000); //System.out.println("Found "+procs.size()+" rows"); String[] str = new String[procs.size()]; for (int i=0;i<procs.size();i++) { str[i] = ((Row)procs.get(i)).getValue(0).getString(); } return str; } else { ResultSet rs = null; try { DatabaseMetaData dbmd = getDatabaseMetaData(); rs = dbmd.getProcedures(null, null, null); ArrayList rows = getRows(rs, 0, null); String result[] = new String[rows.size()]; for (int i=0;i<rows.size();i++) { Row row = (Row)rows.get(i); String procCatalog = row.getString("PROCEDURE_CAT", null); String procSchema = row.getString("PROCEDURE_SCHEMA", null); String procName = row.getString("PROCEDURE_NAME", ""); String name = ""; if (procCatalog!=null) name+=procCatalog+"."; else if (procSchema!=null) name+=procSchema+"."; name+=procName; result[i] = name; } return result; } catch(Exception e) { throw new KettleDatabaseException("Unable to get list of procedures from database meta-data: ", e); } finally { if (rs!=null) try { rs.close(); } catch(Exception e) {} } } } public boolean isAutoCommit() { return commitsize<=0; } /** * @return Returns the databaseMeta. */ public DatabaseMeta getDatabaseMeta() { return databaseMeta; } /** * Lock a tables in the database for write operations * @param tableNames The tables to lock * @throws KettleDatabaseException */ public void lockTables(String tableNames[]) throws KettleDatabaseException { String sql = databaseMeta.getSQLLockTables(tableNames); if (sql!=null) { execStatements(sql); } } /** * Unlock certain tables in the database for write operations * @param tableNames The tables to unlock * @throws KettleDatabaseException */ public void unlockTables(String tableNames[]) throws KettleDatabaseException { String sql = databaseMeta.getSQLUnlockTables(tableNames); if (sql!=null) { execStatement(sql); } } }
/* Open Source Software - may be modified and shared by FRC teams. The code */ /* the project. */ // FILE NAME: Autonomous.java (Team 339 - Kilroy) // ABSTRACT: // This file is where almost all code for Kilroy will be // written. All of these functions are functions that should // override methods in the base class (IterativeRobot). The // functions are as follows: // Init() - Initialization code for autonomous mode // should go here. Will be called each time the robot enters // autonomous mode. // Periodic() - Periodic code for autonomous mode should // go here. Will be called periodically at a regular rate while // the robot is in autonomous mode. // Team 339. package org.usfirst.frc.team339.robot; import org.usfirst.frc.team339.Hardware.Hardware; import org.usfirst.frc.team339.Utils.ErrorMessage; import org.usfirst.frc.team339.Utils.ManipulatorArm; import org.usfirst.frc.team339.Utils.ManipulatorArm.ArmPosition; import edu.wpi.first.wpilibj.DoubleSolenoid.Value; /** * This class contains all of the user code for the Autonomous part of the * match, namely, the Init and Periodic code * * @author Nathanial Lydick * @written Jan 13, 2015 */ /** * A new and improved Autonomous class. * The class <b>beautifully</b> uses state machines in order to periodically * execute instructions during the Autonomous period. * * TODO: "make it worky". * * @author Michael Andrzej Klaczynski * @written at the eleventh stroke of midnight, the 28th of January, * Year of our LORD 2016. Rewritten ever thereafter. * */ public class Autonomous { /** * The overarching states of autonomous mode. */ private static enum MainState { /** * The first state. * Initializes things if necessary, * though most things are initialized * in init(). */ INIT, // beginning, check conditions /** * Sets arm to head downward. */ BEGIN_LOWERING_ARM, /** * Moves at a low speed while lowering arm. * If it reaches the end of the distance, and the arm is not fully down, * skips to DONE. */ MOVE_TO_OUTER_WORKS, /** * Resets and starts delay timer. */ INIT_DELAY,// sets delay timer. /** * Waits. * Waits until the delay is up. */ DELAY, // waits, depending on settings. /** * This state checks to see if we are in lane 1. * If so, we go until we reach an encoder distance (set to distance to * alignment tape), * Else, we go until the sensors find the Alignment tape. */ FORWARDS_BASED_ON_ENCODERS_OR_IR, // decides based on lane whether to move // to tape based on encoders or IR /** * Go the distance over the outer works. */ FORWARDS_OVER_OUTER_WORKS, /** * Goes forward until it reaches the set distance to the Alignment tape. */ FORWARDS_TO_TAPE_BY_DISTANCE, // drives the distance required to the tape. /** * Goes forward until it senses the Alignment tape. */ FORWARDS_UNTIL_TAPE, // drives forwards until detection of the gaffers' // tape. /** * Drives up 16 inches to put the center of the robot over the Aline. */ CENTER_TO_TAPE, /** * Upon reaching the Alignment line, sometimes we must rotate. */ ROTATE_ON_ALIGNMENT_LINE, // rotates on the alignment line. /** * After reaching the A-line, or after rotating upon reaching it, drives * towards a position in front of the goal. */ FORWARDS_FROM_ALIGNMENT_LINE, // drives from the alignment line. /** * After reaching a spot in front of the goal, we turn to face it. */ TURN_TO_FACE_GOAL, // rotates toward the goal. /** * Once we are facing the goal, we may sometimes drive forwards. */ DRIVE_UP_TO_GOAL, // drives up the goal. /** * Once we are in the shooting position, we align based on the chimera. */ ALIGN_IN_FRONT_OF_GOAL, /** * We shoot the cannon ball. */ SHOOT, // adjusts its self (?) and fires the cannon ball. /** * Wait to close the solenoids. */ DELAY_AFTER_SHOOT, /** * Wait for the arm to come down before crossing the outer works. */ WAIT_FOR_ARM_DESCENT, /** * We stop, and do nothing else. */ DONE } /** * * States to run arm movements in parallel. * */ private static enum ArmState { /** * Begins moving the arm in a downwards/down-to-the-floor action fashion. */ INIT_DOWN, /** * Czecks to see if the arm is all the way down. */ MOVE_DOWN, /** * Begins moving the arm in a upwards/up-to-the-shooter action fashion. */ INIT_UP, /** * Czecks to see if the arm is all the way up. */ CHECK_UP, /** * Moves, and czecks to see if the arm is all the way up, so that we may * deposit. */ MOVE_UP_TO_DEPOSIT, /** * Begins spinning its wheels so as to spit out the cannon ball. */ INIT_DEPOSIT, /** * Have we spit out the cannon ball? If so, INIT_DOWN. */ DEPOSIT, /** * Hold the ball out of the way. */ HOLD, /** * Do nothing, but set armStatesOn to false. */ DONE } // AUTO STATES /** * The state to be executed periodically throughout Autonomous. */ private static MainState mainState = MainState.INIT; /** * Used to run arm movements in parallel to the main state machine. */ private static ArmState armState = ArmState.DONE; // VARIABLES /** * The boolean that decides whether or not we run autonomous. */ private static boolean autonomousEnabled; /** * Time to delay at beginning. 0-3 seconds */ private static double delay; // time to delay before beginning. /** * Number of our starting position, and path further on. */ private static int lane; /** * Run the arm state machine only when necessary (when true). */ private static boolean runArmStates = false; /** * Prints print that it prints prints while it prints true. */ private static boolean debug; // TUNEABLES /** * User-Initialization code for autonomous mode should go here. Will be * called once when the robot enters autonomous mode. * * @author Nathanial Lydick * * @written Jan 13, 2015 */ public static void init () { //check the Autonomous ENABLED/DISABLED switch. autonomousEnabled = Hardware.autonomousEnabled.isOn(); // set the delay time based on potentiometer. delay = initDelayTime(); // get the lane based off of startingPositionPotentiometer lane = getLane(); debug = DEBUGGING_DEFAULT; // Hardware.drive.setMaxSpeed(MAXIMUM_AUTONOMOUS_SPEED); // motor initialization Hardware.transmission.setFirstGearPercentage(1.0); Hardware.transmission.setGear(1); Hardware.transmission.setJoysticksAreReversed(true); Hardware.transmission.setJoystickDeadbandRange(0.0); // Encoder Initialization Hardware.leftRearEncoder.reset(); Hardware.rightRearEncoder.reset(); // Sets Resolution of camera Hardware.axisCamera .writeBrightness(Hardware.MINIMUM_AXIS_CAMERA_BRIGHTNESS); // turn the timer off and reset the counter // so that we can use it in autonomous Hardware.kilroyTimer.stop(); Hardware.kilroyTimer.reset(); Hardware.leftRearEncoder.reset(); Hardware.rightRearEncoder.reset(); Hardware.leftFrontMotor.set(0.0); Hardware.leftRearMotor.set(0.0); Hardware.rightFrontMotor.set(0.0); Hardware.rightRearMotor.set(0.0); Hardware.armMotor.set(0.0); Hardware.armIntakeMotor.set(0.0); Hardware.errorMessage.clearErrorlog(); } // end Init /** * User Periodic code for autonomous mode should go here. Will be called * periodically at a regular rate while the robot is in autonomous mode. * * @author Nathanial Lydick * @written Jan 13, 2015 */ public static void periodic () { // Checks the "enabled" switch. if (autonomousEnabled == true) { //runs the overarching state machine. runMainStateMachine(); } // Czecks if we are running any arm functions. if (runArmStates == true) //run the arm state machine. { runArmStates(); } else { Hardware.pickupArm.stopArmMotor(); } } // end Periodic /** * Sets the delay time in full seconds based on potentiometer. */ private static int initDelayTime () { return (int) (MAXIMUM_DELAY * Hardware.delayPot.get() / Hardware.DELAY_POT_DEGREES); } /** * Called periodically to run the overarching states. */ private static void runMainStateMachine () { if (debug == true) // print out states. { System.out.println("Main State: " + mainState); Teleop.printStatements(); Hardware.errorMessage.printError( "Main State: " + mainState, ErrorMessage.PrintsTo.roboRIO); // Hardware.errorMessage.printError( // "Left:" + Hardware.leftRearEncoder.getDistance(), // ErrorMessage.PrintsTo.roboRIO); // Hardware.errorMessage.printError( // "Right:" + Hardware.rightRearEncoder.getDistance(), // ErrorMessage.PrintsTo.roboRIO); // System.out.println("Time: " + Hardware.kilroyTimer.get()); } switch (mainState) { case INIT: // Doesn't do much. // Just a Platypus. mainInit(); if (lane == 1) // lower the arm to pass beneath the bar. { mainState = MainState.BEGIN_LOWERING_ARM; } else // lowering the arm would get in the way. Skip to delay. { mainState = MainState.INIT_DELAY; } break; case BEGIN_LOWERING_ARM: // starts the arm movement to the floor runArmStates = true; armState = ArmState.MOVE_DOWN; //TODO: Remove primitive stuff below. //Hardware.armMotor.set(1.0); // goes into initDelay mainState = MainState.INIT_DELAY; break; case MOVE_TO_OUTER_WORKS: // goes forwards to outer works. if ((Hardware.drive.driveStraightByInches( DriveInformation.DISTANCE_TO_OUTER_WORKS * LAB_SCALING_FACTOR, false, DriveInformation.MOTOR_RATIO_TO_OUTER_WORKS[lane], DriveInformation.MOTOR_RATIO_TO_OUTER_WORKS[lane])) == true) //continue over the outer works unless the arm is going to get in the way. { //continue over the Outer Works mainState = MainState.FORWARDS_OVER_OUTER_WORKS; resetEncoders(); //UNLESS... //When going under the low bar (lane 1), the arm must be down. if ((lane == 1) && (Hardware.pickupArm.isDown() == false)) //arm is not down in time. STOP. { mainState = MainState.WAIT_FOR_ARM_DESCENT; } } break; case INIT_DELAY: // reset and start timer initDelay(); // run DELAY state. mainState = MainState.DELAY; break; case DELAY: // check whether done or not until done. if (delayIsDone() == true) // go to move forwards while lowering arm when finished. { mainState = MainState.MOVE_TO_OUTER_WORKS; } break; case FORWARDS_OVER_OUTER_WORKS: //Drive over Outer Works. if (Hardware.drive.driveStraightByInches( DriveInformation.DISTANCE_OVER_OUTER_WORKS, false, DriveInformation.OUTER_WORKS_MOTOR_RATIO, DriveInformation.OUTER_WORKS_MOTOR_RATIO) == true) //put up all the things we had to put down under the low bar. //begin loading the catapult. { //put up camera. Hardware.cameraSolenoid.set(Value.kForward); //initiate the arm motion. runArmStates = true; armState = ArmState.HOLD; mainState = MainState.FORWARDS_BASED_ON_ENCODERS_OR_IR; } break; case WAIT_FOR_ARM_DESCENT: if (Hardware.pickupArm.moveToPosition( ManipulatorArm.ArmPosition.FULL_DOWN) == true) mainState = MainState.FORWARDS_OVER_OUTER_WORKS; break; case FORWARDS_BASED_ON_ENCODERS_OR_IR: // Check if we are in lane One. if (lane == 1) // If so, move forwards the distance to the A-tape. { mainState = MainState.FORWARDS_TO_TAPE_BY_DISTANCE; } else // If in another lane, move forwards until we detect the A-tape. { mainState = MainState.FORWARDS_UNTIL_TAPE; } break; case FORWARDS_TO_TAPE_BY_DISTANCE: // Drive the distance from outer works to A-Line. if ((Hardware.drive.driveStraightByInches( DriveInformation.DISTANCE_TO_TAPE * LAB_SCALING_FACTOR, false, DriveInformation.MOTOR_RATIO_TO_A_LINE[lane], DriveInformation.MOTOR_RATIO_TO_A_LINE[lane]) == true)) // when done, proceed from Alignment line. { //reset Encoders to prepare for next state. resetEncoders(); //We definitely don't need to rotate. mainState = MainState.CENTER_TO_TAPE; } break; case FORWARDS_UNTIL_TAPE: // Drive until IR sensors pick up tape. if (hasMovedToTape() == true) { //reset Encoders to prepare for next state. resetEncoders(); // When done, possibly rotate. mainState = MainState.CENTER_TO_TAPE; } break; case CENTER_TO_TAPE: //Drive up from front of the Alignment Line to put the pivoting center of the robot on the Line. if (Hardware.drive.driveStraightByInches( DriveInformation.DISTANCE_TO_CENTRE_OF_ROBOT, DriveInformation.BREAK_ON_ALIGNMENT_LINE[lane], DriveInformation.CENTRE_TO_ALIGNMENT_LINE_MOTOR_RATIO[lane], DriveInformation.CENTRE_TO_ALIGNMENT_LINE_MOTOR_RATIO[lane])) { mainState = MainState.ROTATE_ON_ALIGNMENT_LINE; } break; case ROTATE_ON_ALIGNMENT_LINE: //Rotates until we are pointed at the place from whence we want to shoot. if (hasTurnedBasedOnSign( DriveInformation.ROTATE_ON_ALIGNMENT_LINE_DISTANCE[lane] * LAB_SCALING_FACTOR) == true) { //reset Encoders to prepare for next state. resetEncoders(); //then move. mainState = MainState.FORWARDS_FROM_ALIGNMENT_LINE; } break; case FORWARDS_FROM_ALIGNMENT_LINE: //Drive until we reach the line normal to the goal. if (Hardware.drive.driveStraightByInches( DriveInformation.FORWARDS_FROM_ALIGNMENT_LINE_DISTANCE[lane] * LAB_SCALING_FACTOR, true, //breaking here is preferable. DriveInformation.FORWARDS_FROM_ALIGNMENT_LINE_MOTOR_RATIO[lane], DriveInformation.FORWARDS_FROM_ALIGNMENT_LINE_MOTOR_RATIO[lane]) == true) { //reset Encoders to prepare for next state. resetEncoders(); mainState = MainState.TURN_TO_FACE_GOAL; } break; case TURN_TO_FACE_GOAL: //Turns until we are facing the goal. if (hasTurnedBasedOnSign( DriveInformation.TURN_TO_FACE_GOAL_DEGREES[lane] * LAB_SCALING_FACTOR) == true) //when done move up to the batter. { //reset Encoders to prepare for next state resetEncoders(); //then drive. mainState = MainState.DRIVE_UP_TO_GOAL; } break; case DRIVE_UP_TO_GOAL: //Moves to goal. Stops to align. if (hasDrivenUpToGoal() == true) //Go to align. { //reset Encoders to prepare for next state. resetEncoders(); //go to shoot. //TODO:No longer using align. //go to align. mainState = MainState.SHOOT; } break; case ALIGN_IN_FRONT_OF_GOAL: //align based on the camera until we are facing the goal. head-on. if (Hardware.drive.alignByCamera() == true) //Once we are in position, we shoot! { mainState = MainState.SHOOT; } break; case SHOOT: //FIRE!!! shoot(); mainState = MainState.DELAY_AFTER_SHOOT; break; case DELAY_AFTER_SHOOT: //Check if enough time has passed for the air to have been released. if (hasShot() == true) { mainState = MainState.DONE; } default: case DONE: //clean everything up; //the blood of our enemies stains quickly. done(); break; } } private static void mainInit () { Hardware.kilroyTimer.reset(); Hardware.kilroyTimer.start(); } /** * Starts the delay timer. */ private static void initDelay () { Hardware.delayTimer.reset(); Hardware.delayTimer.start(); } /** * Waits. * One of the overarching states. */ private static boolean delayIsDone () { boolean done = false; // stop. Hardware.transmission.controls(0.0, 0.0); // check timer if (Hardware.delayTimer.get() > delay) // return true. stop and reset timer. { done = true; Hardware.delayTimer.stop(); Hardware.delayTimer.reset(); } if (Hardware.pickupArm.isDown() == true) { } return done; } /** * Drives, and * Checks to see if the IRSensors detect Alignment tape. * * @return true when it does. */ private static boolean hasMovedToTape () { //The stateness of being on the tape. boolean tapeness = false; // Move forwards. Hardware.drive.driveStraightContinuous(); // simply check if we have detected the tape on either side. if (Hardware.leftIR.isOn() || Hardware.rightIR.isOn()) // we are done here. { tapeness = true; } return tapeness; } /** * Drives to the final shooting position. * * @return true when complete. */ private static boolean hasDrivenUpToGoal () { boolean done = false; // Have we reached the distance according to drawings. // Have we seen if we have reached cleats of the tower according to IR? if ((Hardware.drive.driveStraightByInches( DriveInformation.DRIVE_UP_TO_GOAL[lane] * LAB_SCALING_FACTOR, true, DriveInformation.DRIVE_UP_TO_GOAL_MOTOR_RATIO[lane], DriveInformation.DRIVE_UP_TO_GOAL_MOTOR_RATIO[lane]) == true) || (Hardware.leftIR.isOn() || Hardware.rightIR.isOn())) // We are done here. { done = true; } // TEMPORARY PRINTS. // see if we have stopped based on IR or Encoders. if (done == true && (Hardware.leftIR.isOn() || Hardware.rightIR.isOn())) { System.out.println("Stopped by Sensors"); } else { System.out.println("Stopped by distance."); } return done; } /** * <b> FIRE!!! </b> * Shoots the ball. May want to add states/methods to align. * */ private static void shoot () { //Make sure the arm is out of the way. if (Hardware.pickupArm.isClearOfArm()) { //RELEASE THE KRACKEN! I mean, the pressurized air... Hardware.catapultSolenoid0.set(true); Hardware.catapultSolenoid1.set(true); Hardware.catapultSolenoid2.set(true); } //set a timer so that we know when to close the solenoids. Hardware.kilroyTimer.reset(); Hardware.kilroyTimer.start(); } /** * Wait a second... * Close the solenoids. * * @return true when delay is up. */ private static boolean hasShot () { //Check the time. if (Hardware.kilroyTimer.get() > DELAY_TIME_AFTER_SHOOT) //Close the airways, and finish. { Hardware.catapultSolenoid0.set(false); Hardware.catapultSolenoid1.set(false); Hardware.catapultSolenoid2.set(false); return true; } return false; } /** * Stop everything. */ private static void done () { autonomousEnabled = false; debug = false; Hardware.transmission.controls(0.0, 0.0); Hardware.armMotor.set(0.0); Hardware.delayTimer.stop(); } /** * A separate state machine, used to run arm movements in parallel. */ private static void runArmStates () { switch (armState) { case INIT_DOWN: //begin moving arm down Hardware.pickupArm.move(-1.0); //go to periodically check. armState = ArmState.MOVE_DOWN; break; case MOVE_DOWN: //check if down. if (Hardware.pickupArm .moveToPosition(ArmPosition.FULL_DOWN) == true) //stop. { Hardware.pickupArm.move(0.0); armState = ArmState.DONE; } break; case INIT_UP: //begin moving arm up. Hardware.pickupArm.move(1.0); //go to periodically check. armState = ArmState.CHECK_UP; break; case CHECK_UP: //check if up. if (Hardware.pickupArm.isUp() == true) { //stop. Hardware.pickupArm.move(0.0); armState = ArmState.DONE; } break; case MOVE_UP_TO_DEPOSIT: //check is in up position so that we may deposit the ball. if (Hardware.pickupArm .moveToPosition(ArmPosition.DEPOSIT) == true) //stop, and go to deposit. { Hardware.pickupArm.move(0.0); armState = ArmState.INIT_DEPOSIT; } break; case INIT_DEPOSIT: //spin wheels to release ball. Hardware.pickupArm.pushOutBall(); armState = ArmState.DEPOSIT; break; case DEPOSIT: //check if the ball is out. if (Hardware.pickupArm.ballIsOut()) //stop rollers, and move down. { Hardware.pickupArm.stopIntakeArms(); //get out of the way. armState = ArmState.INIT_DOWN; } break; case HOLD: Hardware.pickupArm.moveToPosition(ArmPosition.HOLD); break; default: case DONE: //stop running state machine. runArmStates = false; break; } } //TODO: Remove unecessary TODOs /** * Return the starting position based on 6-position switch on the robot. * * @return lane/starting position */ private static int getLane () { int position = Hardware.startingPositionDial.getPosition(); //-1 is returned when there is no signal. if (position == -1) //Go to lane 1 by default. { position = 0; } position++; return position; } /** * Reset left and right encoders. * To be called at the end of any state that uses Drive. */ private static void resetEncoders () { Hardware.leftRearEncoder.reset(); Hardware.rightRearEncoder.reset(); } /** * For turning in drive based on array of positive and negative values. * Use to turn a number of degrees * COUNTERCLOCKWISE. * Kilroy must turn along different paths. * You must use this to be versatile. */ private static boolean hasTurnedBasedOnSign (double degrees, double turnSpeed) { boolean done = false; if (degrees < 0) //Turn right. Make degrees positive. { done = Hardware.drive.turnRightDegrees(-degrees, false, turnSpeed, -turnSpeed); } else //Turn left the given number of degrees. { done = Hardware.drive.turnLeftDegrees(degrees, false, -turnSpeed, turnSpeed); } return done; } /** * For turning in drive based on array of positive and negative values. * Use to turn a number of degrees * COUNTERCLOCKWISE. * Kilroy must turn along different paths. * You must use this to be versatile. */ private static boolean hasTurnedBasedOnSign (double degrees) { return hasTurnedBasedOnSign(degrees, DriveInformation.DEFAULT_TURN_SPEED); } /** * Contains distances and speeds at which to drive. * * TODO: Figure out reasonable speeds, etc. */ private static final class DriveInformation { /** * For each lane, decides whether or not to break on the Alignment Line */ private static final boolean[] BREAK_ON_ALIGNMENT_LINE = { false, // A placeholder, allowing lane to line up with index. false, //lane 1 false, //lane 2 true, // lane 3 true, // lane 4 false // lane 5 }; /** * The motor controller values for moving to the outer works. * As these are initial speeds, keep them low, to go easy on the motors. * Lane is indicated by index. */ static final double[] MOTOR_RATIO_TO_OUTER_WORKS = { 0.0, // nothing. Not used. Arbitrary; makes it work. 0.40,//0.25, // lane 1, should be extra low. 1.0, // lane 2 0.4, // lane 3 0.4, // lane 4 0.4 // lane 5 }; /** * "Speeds" at which to drive from the Outer Works to the Alignment Line. */ static final double[] MOTOR_RATIO_TO_A_LINE = { 0.0, //PLACEHOLDER 0.5, //lane 1 0.6, //lane 2 0.4, //lane 3 0.4, //lane 4 0.6 //lane 5 }; /** * Distances to rotate upon reaching alignment line. * Lane is indicated by index. * Set to Zero for 1, 2, and 5. */ static final double[] ROTATE_ON_ALIGNMENT_LINE_DISTANCE = { 0.0, // nothing. Not used. Arbitrary; makes it work. 0.0, // lane 1 (not neccesary) 0.0, // lane 2 (not neccesary) -20, // lane 3 24.8, // lane 4 0.0 // lane 5 (not neccesary) }; /** * Distances to drive after reaching alignment tape. * Lane is indicated by index. * 16 inchworms added inevitably, to start from centre of robot. */ static final double[] FORWARDS_FROM_ALIGNMENT_LINE_DISTANCE = { 0.0, // nothing. Not used. Arbitrary; makes it work. 74.7,// lane 1 82.0,// lane 2 64.0, // lane 3 66.1,// lane 4 86.5 // lane 5 }; static final double[] CENTRE_TO_ALIGNMENT_LINE_MOTOR_RATIO = { 0.0, 1.0, 1.0, .25, .25, 1.0 }; /** * "Speeds" at which to drive from the A-Line to the imaginary line normal to * the goal. */ static final double[] FORWARDS_FROM_ALIGNMENT_LINE_MOTOR_RATIO = { 0.0, // nothing. A Placeholder. 0.4, //lane 1 0.4, //lane 2 0.3, //lane 3 0.3, //lane 4 0.4 //lane 5 }; /** * Distances to rotate to face goal. */ static final double[] TURN_TO_FACE_GOAL_DEGREES = { 0.0, // makes it so the indexes line up with the lane -60.0,// lane 1 -60.0,// lane 2 20.0,// lane 3 -24.85,// lane 4 60 // lane 5 }; /** * Distances to travel once facing the goal. * Not neccesary for lanes 3 and 4; set to zero. * Actually, we may not use this much at all, given that we will probably just * use the IR to sense the cleets at the bottom of the tower. */ static final double[] DRIVE_UP_TO_GOAL = { 0.0, // nothing. Not used. Arbitrary; makes it work. 62.7,// lane 1 52.9,// lane 2 0.0,// lane 3 (not neccesary) 0.0,// lane 4 (not neccesary) 12.0 // lane 5 }; /** * "Speeds" at which to drive to the Batter. */ static final double[] DRIVE_UP_TO_GOAL_MOTOR_RATIO = { 0.0, 0.35, 0.4, 0.4, 0.4, 0.4 }; /** * Distance from Outer Works checkpoint to Alignment Line. * The front of the robot will be touching the Lion. */ private static final double DISTANCE_TO_TAPE = 17.5; /** * Distance to get the front of the robot to the Outer Works. */ private static final double DISTANCE_TO_OUTER_WORKS = 22.75; /** * Distance to travel to get over the Outer Works. */ private static final double DISTANCE_OVER_OUTER_WORKS = 96.25; /** * Motor ratio at which we move over outer works. * TODO: possibly make into array. */ private static final double OUTER_WORKS_MOTOR_RATIO = 0.4; /** * The distance to the central pivot point from the front of the robot. * We will use this so that we may rotate around a desired point at the end of a * distance. */ private static final double DISTANCE_TO_CENTRE_OF_ROBOT = 16.0; /** * Speed at which to make turns by default. * TODO: figure out a reasonable speed. */ private static final double DEFAULT_TURN_SPEED = 0.28; } /** * Always 1.0. Do not change. The code depends on it. * TODO: Actually, we are not currently using this. */ private static final double MAXIMUM_AUTONOMOUS_SPEED = 1.0; /** * The maximum time to wait at the beginning of the match. * Used to scale the ratio given by the potentiometer. */ private static final double MAXIMUM_DELAY = 3.0; /** * Set to true to print out print statements. */ private static final boolean DEBUGGING_DEFAULT = true; /** * Factor by which to scale all distances for testing in our small lab space. */ private static final double LAB_SCALING_FACTOR = .5; /** * Time to wait after releasing the solenoids before closing them back up. */ private static final double DELAY_TIME_AFTER_SHOOT = 1.0; } // end class
/* Open Source Software - may be modified and shared by FRC teams. The code */ /* the project. */ // FILE NAME: Autonomous.java (Team 339 - Kilroy) // ABSTRACT: // This file is where almost all code for Kilroy will be // written. Some of these functions are functions that should // override methods in the base class (IterativeRobot). The // functions are as follows: // Init() - Initialization code for autonomous mode // should go here. Will be called each time the robot enters // autonomous mode. // Periodic() - Periodic code for autonomous mode should // go here. Will be called periodically at a regular rate while // the robot is in autonomous mode. // Team 339. package org.usfirst.frc.team339.robot; import org.usfirst.frc.team339.Hardware.Hardware; import org.usfirst.frc.team339.Utils.Drive; import org.usfirst.frc.team339.Utils.Drive.AlignReturnType; import org.usfirst.frc.team339.Utils.Shooter.turnReturn; import org.usfirst.frc.team339.Utils.Shooter.turnToGoalReturn; import edu.wpi.first.wpilibj.DriverStation.Alliance; import edu.wpi.first.wpilibj.Relay.Value; /** * An Autonomous class. * This class <b>beautifully</b> uses state machines in order to periodically * execute instructions during the Autonomous period. * * This class contains all of the user code for the Autonomous part * of the * match, namely, the Init and Periodic code * * * @author Michael Andrzej Klaczynski * @written at the eleventh stroke of midnight, the 28th of January, * Year of our LORD 2016. Rewritten ever thereafter. * * @author Nathanial Lydick * @written Jan 13, 2015 */ public class Autonomous { // AUTO STATES /** * The overarching states of autonomous mode. * Each state represents a set of instructions the robot must execute * periodically at a given time. * These states are mainly used in the runMainStateMachine() method * */ private static enum MainState { /** * Reset Encoder Values, determine alliance, determine delay time, * determine path */ INIT, /** * Delays anywhere between 0 and 5 seconds, controlled by a potentiometer on * the robot */ DELAY_BEFORE_START, /** * Accelerates so we don't jerk our encoders. */ ACCELERATE, /** * Drives up the the gear. */ DRIVE_FORWARD_TO_CENTER, /** * Drive to the side of the airship at normal speed. See * DRIVE_FORWARD_TO_CENTER. */ DRIVE_FORWARD_TO_SIDES, /** * Turn towards the peg deposit place on the airship */ TURN_TO_GEAR_PEG, /** * Align with the vision strips to deposit gear */ DRIVE_TO_GEAR_WITH_CAMERA, /** * Drive up to the gear peg when we don't see any blobs. */ DRIVE_CAREFULLY_TO_PEG, /** * Stops us moving up to the peg so we don't spear ourselves on it. */ BRAKE_UP_TO_PEG, TURN_TURRET_OUT_OF_THE_WAY, /** * Currently unused, may be used to regain vision targets, or make sure the * gear is on the spring. It's a bit of a wildcard at the moment. */ WIGGLE_WIGGLE, /** * We've got the gear on the peg (probably), but we're waiting for the human * player to pull the gear out of our thingy. */ WAIT_FOR_GEAR_EXODUS, /** * Wait after we detect the gear leaving our mechanism to make sure it's * clear before we try and drive back. */ DELAY_AFTER_GEAR_EXODUS, /** * Back away from whatever peg we're currently on. */ DRIVE_AWAY_FROM_PEG, /** * On paths where we go for the hopper, Turn so we're facing it */ TURN_TO_HOPPER, /** * On paths where we go for the hopper, drive until we slam into it. */ DRIVE_UP_TO_HOPPER, /** * Since we drive backwards to get into range, we need to turn around to * fire. */ TURN_TO_FACE_GOAL, /** * On paths where we fire, back away from the gear peg and towards the * boiler until we're in range to fire. */ DRIVE_TO_FIRERANGE, /** * Use the camera to figure out if we're in range of the top boiler */ DRIVE_INTO_RANGE_WITH_CAMERA, /** * Turn the turret so it's facing the boiler */ ALIGN_TO_FIRE, /** * Empty out the hopper or fire until time out */ FIRE, /** * Quit the path. */ DONE } private static enum AutoProgram { INIT, CENTER_GEAR_PLACEMENT, RIGHT_PATH, LEFT_PATH, DELAY_AFTER_GEAR_EXODUS, DONE } // VARIABLES private static Drive.AlignReturnType cameraState = Drive.AlignReturnType.NO_BLOBS; // TUNEABLES private static final double ALIGN_CORRECT_VAR = 50; private static final double ALIGN_DRIVE_SPEED = .3; private static final double ALIGN_DEADBAND = 10 // +/- pixels / Hardware.axisCamera.getHorizontalResolution(); private static final double ALIGN_ACCEPTED_CENTER = .5; // Relative coordinates private static final int ALIGN_DISTANCE_FROM_GOAL = 14; /** * User-Initialization code for autonomous mode should go here. Will be * called once when the robot enters autonomous mode. * * @author Nathanial Lydick * * @written Jan 13, 2015 */ public static void init () { // Sets the scaling factor and general ultrasonic stuff Hardware.rightUS.setScalingFactor(.13); Hardware.rightUS.setOffsetDistanceFromNearestBummper(3); Hardware.rightUS.setNumberOfItemsToCheckBackwardForValidity(3); Hardware.mecanumDrive.setFirstGearPercentage(1.0); Hardware.mecanumDrive.setGear(1); if (Hardware.isRunningOnKilroyXVIII) { robotSpeedScalar = KILROY_XVIII_DEFAULT_SPEED; } else { robotSpeedScalar = KILROY_XVII_DEFAULT_SPEED; } } // end Init /** * User Periodic code for autonomous mode should go here. Will be called * periodically at a regular rate while the robot is in autonomous mode. * * @author Nathanial Lydick * @written Jan 13, 2015 */ public static void periodic () { switch (autoPath) { case INIT: // get the auto program we want to run, get delay pot. if (Hardware.enableAutonomous.isOn()) { delayTime = Hardware.delayPot.get(0.0, 5.0); if (Hardware.driverStation .getAlliance() == Alliance.Red) { isRedAlliance = true; } if (Hardware.pathSelector.isOn()) { autoPath = AutoProgram.CENTER_GEAR_PLACEMENT; break; } if (Hardware.rightPath.isOn()) { autoPath = AutoProgram.RIGHT_PATH; break; } if (Hardware.leftPath.isOn()) { autoPath = AutoProgram.LEFT_PATH; break; } autoPath = AutoProgram.DONE; } else { autoPath = AutoProgram.DONE; } break; case CENTER_GEAR_PLACEMENT: if (placeCenterGearPath()) autoPath = AutoProgram.DONE; break; case RIGHT_PATH: if (rightSidePath()) autoPath = AutoProgram.DONE; break; case LEFT_PATH: if (leftSidePath()) autoPath = AutoProgram.DONE; break; case DONE: Hardware.leftRearMotor.set(0); Hardware.leftFrontMotor.set(0); Hardware.rightRearMotor.set(0); Hardware.rightFrontMotor.set(0); Hardware.ringlightRelay.set(Value.kOff); break; } } // end Periodic private static MainState currentState = MainState.INIT; private static MainState postAccelerateState = MainState.DONE; private static AutoProgram autoPath = AutoProgram.INIT; private static double delayTime = 5; private static boolean isRedAlliance = false; private static boolean goForFire = false; private static boolean goForHopper = false; private static boolean driveToTargetFirstStart = true; private static boolean placeCenterGearPath () { System.out.println("CurrentState = " + currentState); System.out.println("Right US: " + Hardware.rightUS.getDistanceFromNearestBumper()); System.out.println(Hardware.autoDrive.getAveragedEncoderValues()); System.out.println( "Gear " + Hardware.mecanumDrive.getCurrentGearPercentage()); switch (currentState) { case INIT: // zero out all the sensors, reset timers, etc. Hardware.autoStateTimer.start(); Hardware.ringlightRelay.set(Value.kOn); if (Hardware.backupOrFireOrHopper.isOn()) { goForFire = true; } currentState = MainState.DELAY_BEFORE_START; break; case DELAY_BEFORE_START: // stop all the motors to feed the watchdog Hardware.leftRearMotor.set(0); Hardware.leftFrontMotor.set(0); Hardware.rightRearMotor.set(0); Hardware.rightFrontMotor.set(0); // wait for timer to run out if (Hardware.autoStateTimer.get() >= delayTime) { // Hardware.axisCamera.saveImagesSafely(); currentState = MainState.ACCELERATE; postAccelerateState = MainState.DRIVE_FORWARD_TO_CENTER; Hardware.autoStateTimer.reset(); Hardware.autoStateTimer.start(); } break; case ACCELERATE: // TODO magic number cameraState = AlignReturnType.WAITING; if (Hardware.autoDrive.accelerate(getRealSpeed(.2), .1)) { currentState = postAccelerateState; Hardware.axisCamera.saveImagesSafely(); } Hardware.rightUS.getDistanceFromNearestBumper(); break; case DRIVE_FORWARD_TO_CENTER: // If we see blobs, hand over control to camera, otherwise, go // forward. Check to make sure we haven't gone too far. Hardware.imageProcessor.processImage(); System.out.println( "Number of blobs: " + Hardware.imageProcessor .getParticleAnalysisReports().length); if (Hardware.imageProcessor.getNthSizeBlob(1) != null) { currentState = MainState.DRIVE_TO_GEAR_WITH_CAMERA; } else currentState = MainState.DRIVE_CAREFULLY_TO_PEG; break; case DRIVE_TO_GEAR_WITH_CAMERA: // Get our return type from the strafe to gear. // NOTE: if the constructor for autoDrive uses a mecanum // transmission, // we will strafe. If it uses a four wheel transmission, it will // wiggle wiggle on it's way to the peg cameraState = Hardware.autoDrive.strafeToGear( getRealSpeed(ALIGN_DRIVE_SPEED), ALIGN_CORRECT_VAR, ALIGN_DEADBAND, ALIGN_ACCEPTED_CENTER, ALIGN_DISTANCE_FROM_GOAL); System.out.println( "Number of Blobs: " + Hardware.imageProcessor .getParticleAnalysisReports().length); System.out.println("strafeToGear state: " + cameraState); if (cameraState == AlignReturnType.NO_BLOBS) { // If we don't see anything, just drive forwards till we are // close enough currentState = MainState.DRIVE_CAREFULLY_TO_PEG; } if (cameraState == AlignReturnType.CLOSE_ENOUGH) { // If we are close enough to the wall, stop. currentState = MainState.BRAKE_UP_TO_PEG; } break; case DRIVE_CAREFULLY_TO_PEG: if (Hardware.imageProcessor.getNthSizeBlob(1) != null) { currentState = MainState.DRIVE_TO_GEAR_WITH_CAMERA; } else { if (Hardware.rightUS .getDistanceFromNearestBumper() >= 14) { Hardware.autoDrive.driveNoDeadband(.3, 0.0); } else { currentState = MainState.BRAKE_UP_TO_PEG; } } break; case BRAKE_UP_TO_PEG: if (Hardware.autoDrive.timeBrake(.3, .2)) { currentState = MainState.TURN_TURRET_OUT_OF_THE_WAY; } break; case TURN_TURRET_OUT_OF_THE_WAY: if (Hardware.shooter .turnToBearing(-17) == turnReturn.SUCCESS) { Hardware.shooter.stopGimbal(); currentState = MainState.WAIT_FOR_GEAR_EXODUS; Hardware.autoStateTimer.reset(); Hardware.autoStateTimer.start(); } break; case WAIT_FOR_GEAR_EXODUS: Hardware.ringlightRelay.set(Value.kOff); // if (Hardware.autoStateTimer.get() >= 1.25) // runWiggleWiggleSetup = true; // currentState = MainState.WIGGLE_WIGGLE; if (Hardware.gearLimitSwitch.isOn() == false) { Hardware.autoDrive.drive(0.0, 0.0); currentState = MainState.DELAY_AFTER_GEAR_EXODUS; Hardware.autoStateTimer.reset(); Hardware.autoStateTimer.start(); } break; case WIGGLE_WIGGLE: if (runWiggleWiggleSetup) { Hardware.autoStateTimer.reset(); Hardware.autoStateTimer.start(); runWiggleWiggleSetup = false; wiggleWiggleCount++; } if (wiggleWiggleCount == 1) { if (Hardware.autoStateTimer.get() >= .5) { Hardware.autoDrive.drive(.5, 90); } else { currentState = MainState.WAIT_FOR_GEAR_EXODUS; } } else if (wiggleWiggleCount == 2) { if (Hardware.autoStateTimer.get() >= .1) { Hardware.autoDrive.drive(.5, -90); } else { currentState = MainState.WAIT_FOR_GEAR_EXODUS; } } else { currentState = MainState.DELAY_AFTER_GEAR_EXODUS; } break; case DELAY_AFTER_GEAR_EXODUS: Hardware.leftRearMotor.set(0); Hardware.leftFrontMotor.set(0); Hardware.rightRearMotor.set(0); Hardware.rightFrontMotor.set(0); if (Hardware.autoStateTimer.get() >= 1.5) { Hardware.axisCamera.saveImagesSafely(); Hardware.autoDrive.resetEncoders(); if (goForFire) { currentState = MainState.DRIVE_AWAY_FROM_PEG; } else { currentState = MainState.DONE; } } break; case DRIVE_AWAY_FROM_PEG: if (Hardware.autoDrive.driveInches(36.0, getRealSpeed(-.5))) { currentState = MainState.DONE; } break; default: case DONE: Hardware.axisCamera.saveImagesSafely(); return true; } return false; } private static int wiggleWiggleCount = 0; private static boolean runWiggleWiggleSetup = true; private static boolean rightSidePath () { System.out.println("Current State = " + currentState); switch (currentState) { case INIT: Hardware.leftRearMotor.set(0); Hardware.leftFrontMotor.set(0); Hardware.rightRearMotor.set(0); Hardware.rightFrontMotor.set(0); Hardware.autoStateTimer.reset(); Hardware.autoStateTimer.start(); Hardware.ringlightRelay.set(Value.kOn); initializeDriveProgram(); currentState = MainState.DELAY_BEFORE_START; break; case DELAY_BEFORE_START: // stop all the motors to feed the watchdog Hardware.leftRearMotor.set(0); Hardware.leftFrontMotor.set(0); Hardware.rightRearMotor.set(0); Hardware.rightFrontMotor.set(0); // wait for timer to run out if (Hardware.autoStateTimer.get() >= delayTime) { Hardware.axisCamera.saveImagesSafely(); currentState = MainState.ACCELERATE; postAccelerateState = MainState.DRIVE_FORWARD_TO_SIDES; Hardware.autoStateTimer.reset(); Hardware.autoStateTimer.start(); } break; case ACCELERATE: System.out.println("right front motor accelerate: " + Hardware.rightFrontMotor.getSpeed()); System.out.println("left front motor accelerate: " + Hardware.leftFrontMotor.getSpeed()); if (Hardware.autoDrive.accelerate(.4, .3))// TODO magic num! { currentState = postAccelerateState; } break; case DRIVE_FORWARD_TO_SIDES: if (Hardware.autoDrive.getAveragedEncoderValues() <= 95.5) { Hardware.autoDrive.drive(.5, 0.0, 0.0); } else { currentState = MainState.TURN_TO_GEAR_PEG; } break; case TURN_TO_GEAR_PEG: // turn left on both red and blue Hardware.imageProcessor.processImage(); // If we're done turning if (Hardware.autoDrive.turnDegrees(-55, .4)) { // if we have the two blobs we need to correctly alighn if (Hardware.imageProcessor.getNthSizeBlob(1) != null) { // Drive up to the peg using the camera currentState = MainState.DRIVE_TO_GEAR_WITH_CAMERA; } // If we don't have the necessary blobs else { // Drive up to the peg going as straight as possible. Good // luck! currentState = MainState.DRIVE_CAREFULLY_TO_PEG; } Hardware.autoDrive.drive(0, 0, 0);// TODO use brake at some // point. Hardware.autoDrive.resetEncoders(); } // If we're not done turning else { // Keep Turning! currentState = MainState.TURN_TO_GEAR_PEG; } break; case DRIVE_TO_GEAR_WITH_CAMERA: System.out.println("in second drive to gear with camera"); Hardware.imageProcessor.processImage(); // If at any time we lose our target blob number if (Hardware.imageProcessor.getNthSizeBlob(1) == null) { // Drive to the peg straight from here currentState = MainState.DRIVE_CAREFULLY_TO_PEG; } else { currentState = MainState.DRIVE_TO_GEAR_WITH_CAMERA; // TODO magic numbers and need to be tuned. Hardware.autoDrive.alignToGear(0.0, .5, .1); } // TODO tune so we end here if (Hardware.rightUS.getDistanceFromNearestBumper() < 8) { Hardware.autoDrive.drive(0.0, 0.0, 0.0); currentState = MainState.WAIT_FOR_GEAR_EXODUS; } break; case DRIVE_CAREFULLY_TO_PEG: // TODO could cause issues, check in testing. Hardware.imageProcessor.processImage(); if (Hardware.rightUS.getDistanceFromNearestBumper() < 8) { if (Hardware.imageProcessor.getNthSizeBlob(1) != null) { currentState = MainState.DRIVE_TO_GEAR_WITH_CAMERA; } else { Hardware.autoDrive.drive(.4, 0.0, 0.0); } } else { currentState = MainState.WAIT_FOR_GEAR_EXODUS; Hardware.autoDrive.drive(0.0, 0.0, 0.0); } break; case WIGGLE_WIGGLE: currentState = MainState.WAIT_FOR_GEAR_EXODUS; break; case WAIT_FOR_GEAR_EXODUS: if (Hardware.gearLimitSwitch.isOn() == false) { Hardware.autoStateTimer.reset(); Hardware.autoStateTimer.start(); currentState = MainState.DELAY_AFTER_GEAR_EXODUS; } break; case DELAY_AFTER_GEAR_EXODUS: Hardware.leftRearMotor.set(0); Hardware.leftFrontMotor.set(0); Hardware.rightRearMotor.set(0); Hardware.rightFrontMotor.set(0); if (Hardware.autoStateTimer.get() >= 1.5)// TODO magic number { currentState = MainState.DRIVE_AWAY_FROM_PEG; } break; case DRIVE_AWAY_FROM_PEG: if (Hardware.autoDrive.driveInches(24, -.3)) { if (isRedAlliance && goForFire) { currentState = MainState.TURN_TO_FACE_GOAL; } if (!isRedAlliance && goForHopper) { currentState = MainState.TURN_TO_HOPPER; } else { currentState = MainState.DONE; } } break; case TURN_TO_FACE_GOAL: if (Hardware.autoDrive.turnDegrees(180)) { currentState = MainState.DRIVE_TO_FIRERANGE; } break; case DRIVE_TO_FIRERANGE: Hardware.imageProcessor.processImage(); if (Hardware.imageProcessor.getNthSizeBlob(1) != null) { currentState = MainState.DRIVE_INTO_RANGE_WITH_CAMERA; } else { // TODO random number I selected if (Hardware.autoDrive.driveInches(6, getRealSpeed(.6))) currentState = MainState.ALIGN_TO_FIRE; } break; case DRIVE_INTO_RANGE_WITH_CAMERA: Hardware.imageProcessor.processImage(); if (Hardware.imageProcessor.getNthSizeBlob(1) != null) { } break; case TURN_TO_HOPPER: // TODO random magic numbers I selected if (Hardware.autoDrive.turnDegrees(isRedAlliance ? 12 : 90)) { currentState = MainState.DRIVE_UP_TO_HOPPER; } break; case DRIVE_UP_TO_HOPPER: // TODO see above todo. // TODO comment terneries if (Hardware.autoDrive.driveInches(isRedAlliance ? 12 : 90, getRealSpeed(.6))) { currentState = MainState.DONE; } case ALIGN_TO_FIRE: if (Hardware.shooter .turnToGoal() == turnToGoalReturn.SUCCESS) { // align By camera, probably in a firemech currentState = MainState.FIRE; } else if (Hardware.shooter .turnToGoal() == turnToGoalReturn.NO_BLOBS) { currentState = MainState.DONE; } else if (Hardware.shooter .turnToGoal() == turnToGoalReturn.OUT_OF_GIMBALING_RANGE) { // TODO magic numbers if (Hardware.autoDrive.alignToGear(0, .4, .1) == Drive.AlignReturnType.ALIGNED) { // Will probably never reach this part. currentState = MainState.FIRE; } } break; case FIRE: if (Hardware.shooter.fire(0)) { fireCount++; } if (fireCount >= 10) { currentState = MainState.DONE; } break; default: currentState = MainState.DONE; case DONE: return true; } return false; } private static int fireCount = 0; private static boolean isDrivingByCamera = false; private static boolean leftSidePath () { System.out.println("Current State = " + currentState); switch (currentState) { case INIT: Hardware.leftRearMotor.set(0); Hardware.leftFrontMotor.set(0); Hardware.rightRearMotor.set(0); Hardware.rightFrontMotor.set(0); Hardware.autoStateTimer.reset(); Hardware.autoStateTimer.start(); Hardware.ringlightRelay.set(Value.kOn); initializeDriveProgram(); currentState = MainState.DELAY_BEFORE_START; break; case DELAY_BEFORE_START: // stop all the motors to feed the watchdog Hardware.leftRearMotor.set(0); Hardware.leftFrontMotor.set(0); Hardware.rightRearMotor.set(0); Hardware.rightFrontMotor.set(0); // wait for timer to run out if (Hardware.autoStateTimer.get() >= delayTime) { Hardware.axisCamera.saveImagesSafely(); currentState = MainState.ACCELERATE; postAccelerateState = MainState.DRIVE_FORWARD_TO_SIDES; Hardware.autoStateTimer.reset(); Hardware.autoStateTimer.start(); } break; case ACCELERATE: if (Hardware.autoDrive.accelerate(.5, .5))// TODO magic num! { currentState = postAccelerateState; } break; case DRIVE_FORWARD_TO_SIDES: if (Hardware.autoDrive.getAveragedEncoderValues() <= 95.5) { Hardware.autoDrive.drive(.5, 0.0, 0.0); } else { currentState = MainState.TURN_TO_GEAR_PEG; } break; case TURN_TO_GEAR_PEG: // turn right on both red and blue Hardware.imageProcessor.processImage(); // If we're done turning if (Hardware.autoDrive.turnDegrees(55, .4)) { // if we have the two blobs we need to correctly alighn if (Hardware.imageProcessor.getNthSizeBlob(1) != null) { // Drive up to the peg using the camera currentState = MainState.DRIVE_TO_GEAR_WITH_CAMERA; } // If we don't have the necessary blobs else { // Drive up to the peg going as straight as possible. Good // luck! currentState = MainState.DRIVE_CAREFULLY_TO_PEG; } Hardware.autoDrive.drive(0, 0, 0);// TODO use brake at some // point. Hardware.autoDrive.resetEncoders(); } // If we're not done turning else { // Keep Turning! currentState = MainState.TURN_TO_GEAR_PEG; } break; case DRIVE_TO_GEAR_WITH_CAMERA: Hardware.imageProcessor.processImage(); // If at any time we lose our target blob number if (Hardware.imageProcessor.getNthSizeBlob(1) == null) { // Drive to the peg straight from here currentState = MainState.DRIVE_CAREFULLY_TO_PEG; } else { currentState = MainState.DRIVE_TO_GEAR_WITH_CAMERA; // TODO magic numbers and need to be tuned. if (Hardware.autoDrive.strafeToGear(.4, 5, .1, 0.0, 20) == AlignReturnType.CLOSE_ENOUGH) { Hardware.autoDrive.drive(0.0, 0.0, 0.0); currentState = MainState.WAIT_FOR_GEAR_EXODUS; } } break; case DRIVE_CAREFULLY_TO_PEG: // TODO could cause issues, check in testing. Hardware.imageProcessor.processImage(); if (Hardware.rightUS.getDistanceFromNearestBumper() < 8) { if (Hardware.imageProcessor.getNthSizeBlob(1) != null) { currentState = MainState.DRIVE_TO_GEAR_WITH_CAMERA; } else { Hardware.autoDrive.drive(.4, 0.0, 0.0); } } else { currentState = MainState.WAIT_FOR_GEAR_EXODUS; Hardware.autoDrive.drive(0.0, 0.0, 0.0); } break; case WIGGLE_WIGGLE: currentState = MainState.WAIT_FOR_GEAR_EXODUS; break; case WAIT_FOR_GEAR_EXODUS: if (Hardware.gearLimitSwitch.isOn() == false) { Hardware.autoStateTimer.reset(); Hardware.autoStateTimer.start(); currentState = MainState.DELAY_AFTER_GEAR_EXODUS; } break; case DELAY_AFTER_GEAR_EXODUS: Hardware.leftRearMotor.set(0); Hardware.leftFrontMotor.set(0); Hardware.rightRearMotor.set(0); Hardware.rightFrontMotor.set(0); if (Hardware.autoStateTimer.get() >= 1.5)// TODO magic number { currentState = MainState.DRIVE_AWAY_FROM_PEG; } break; case DRIVE_AWAY_FROM_PEG: if (Hardware.autoDrive.driveInches(24, -.3)) { if (isRedAlliance && goForHopper) { currentState = MainState.TURN_TO_HOPPER; } if (!isRedAlliance && goForFire) { currentState = MainState.TURN_TO_FACE_GOAL; } else { currentState = MainState.DONE; } } break; case TURN_TO_FACE_GOAL: if (Hardware.autoDrive.turnDegrees(180)) { currentState = MainState.DRIVE_TO_FIRERANGE; } break; case DRIVE_TO_FIRERANGE: Hardware.imageProcessor.processImage(); if (Hardware.imageProcessor.getNthSizeBlob(1) != null) { currentState = MainState.DRIVE_INTO_RANGE_WITH_CAMERA; } else { // TODO random number I selected if (Hardware.autoDrive.driveInches(6, getRealSpeed(.6))) currentState = MainState.ALIGN_TO_FIRE; } break; case DRIVE_INTO_RANGE_WITH_CAMERA: Hardware.imageProcessor.processImage(); if (Hardware.imageProcessor.getNthSizeBlob(1) != null) { } break; case TURN_TO_HOPPER: // TODO random magic numbers I selected if (Hardware.autoDrive.turnDegrees(isRedAlliance ? 12 : 90)) { currentState = MainState.DRIVE_UP_TO_HOPPER; } break; case DRIVE_UP_TO_HOPPER: // TODO see above todo. // TODO comment terneries if (Hardware.autoDrive.driveInches(isRedAlliance ? 12 : 90, getRealSpeed(.6))) { currentState = MainState.DONE; } case ALIGN_TO_FIRE: if (Hardware.shooter .turnToGoal() == turnToGoalReturn.SUCCESS) { // align By camera, probably in a firemech currentState = MainState.FIRE; } else if (Hardware.shooter .turnToGoal() == turnToGoalReturn.NO_BLOBS) { currentState = MainState.DONE; } else if (Hardware.shooter .turnToGoal() == turnToGoalReturn.OUT_OF_GIMBALING_RANGE) { // TODO magic numbers if (Hardware.autoDrive.alignToGear(0, .4, .1) == Drive.AlignReturnType.ALIGNED) { // Will probably never reach this part. currentState = MainState.FIRE; } } break; case FIRE: if (Hardware.shooter.fire(0)) { fireCount++; } if (fireCount >= 10) { currentState = MainState.DONE; } break; default: currentState = MainState.DONE; case DONE: return true; } return false; } private static final double[] accelerationSpeeds = { getRealSpeed(.2), getRealSpeed(.4), getRealSpeed(.5) }; /** * reset all the sensors and timers, in preparation for an autonomous program. */ private static void initializeDriveProgram () { Hardware.autoStateTimer.stop(); Hardware.autoStateTimer.reset(); Hardware.driveGyro.calibrate(); Hardware.driveGyro.reset(); Hardware.autoDrive.resetEncoders(); Hardware.mecanumDrive.drive(0, 0, 0); } /** * Corrects the speed based on which robot we're using. Uses the * isRunningOnKilroyXVIII boolean to decide which speed scalar to use. * * @param fakeSpeed * The speed you want the robot to use, don't worry about it. * @return * The correct speed for whichever robot we're on. */ private static double getRealSpeed (double fakeSpeed) { return fakeSpeed * robotSpeedScalar; } private static double robotSpeedScalar = 1.0; private static final double KILROY_XVIII_DEFAULT_SPEED = 1.0; private static final double KILROY_XVII_DEFAULT_SPEED = .7; } // end class
package org.usfirst.frc.team3335.robot.subsystems; import edu.wpi.first.wpilibj.DoubleSolenoid; import edu.wpi.first.wpilibj.DoubleSolenoid.Value; import edu.wpi.first.wpilibj.Solenoid; import edu.wpi.first.wpilibj.command.Subsystem; @SuppressWarnings("unused") public class Dumper extends Subsystem implements LoggableSubsystem { private Value state; private DoubleSolenoid solenoid; //private Solenoid solenoid; public Dumper() { //solenoid = new Solenoid(3); solenoid = new DoubleSolenoid(2, 3); state = Value.kForward; solenoid.set(state); } public void switchPos() { switch (solenoid.get()) { case kOff: case kReverse: solenoid.set(Value.kForward); break; case kForward: solenoid.set(Value.kOff); break; } } @Override protected void initDefaultCommand() { } @Override public void log() { } }
package ca.cumulonimbus.pressurenetsdk; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.security.MessageDigest; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.PackageManager.NameNotFoundException; import android.database.Cursor; import android.database.sqlite.SQLiteDatabaseLockedException; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.location.Location; import android.net.ConnectivityManager; import android.os.AsyncTask; import android.os.BatteryManager; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.Messenger; import android.os.RemoteException; import android.preference.PreferenceManager; import android.provider.Settings.Secure; /** * Represent developer-facing pressureNET API Background task; manage and run * everything Handle Intents * * @author jacob * */ public class CbService extends Service { private CbDataCollector dataCollector; private CbLocationManager locationManager; private CbSettingsHandler settingsHandler; private CbDb db; public CbService service = this; private String mAppDir; IBinder mBinder; ReadingSender sender; Message recentMsg; String serverURL = CbConfiguration.SERVER_URL; public static String ACTION_SEND_MEASUREMENT = "SendMeasurement"; // Service Interaction API Messages public static final int MSG_OKAY = 0; public static final int MSG_STOP = 1; public static final int MSG_GET_BEST_LOCATION = 2; public static final int MSG_BEST_LOCATION = 3; public static final int MSG_GET_BEST_PRESSURE = 4; public static final int MSG_BEST_PRESSURE = 5; public static final int MSG_START_AUTOSUBMIT = 6; public static final int MSG_STOP_AUTOSUBMIT = 7; public static final int MSG_SET_SETTINGS = 8; public static final int MSG_GET_SETTINGS = 9; public static final int MSG_SETTINGS = 10; public static final int MSG_DATA_STREAM = 12; // pressureNET Live API public static final int MSG_GET_LOCAL_RECENTS = 14; public static final int MSG_LOCAL_RECENTS = 15; public static final int MSG_GET_API_RECENTS = 16; public static final int MSG_API_RECENTS = 17; public static final int MSG_MAKE_API_CALL = 18; public static final int MSG_API_RESULT_COUNT = 19; // pressureNET API Cache public static final int MSG_CLEAR_LOCAL_CACHE = 20; public static final int MSG_REMOVE_FROM_PRESSURENET = 21; public static final int MSG_CLEAR_API_CACHE = 22; // Current Conditions public static final int MSG_ADD_CURRENT_CONDITION = 23; public static final int MSG_GET_CURRENT_CONDITIONS = 24; public static final int MSG_CURRENT_CONDITIONS = 25; // Sending Data public static final int MSG_SEND_OBSERVATION = 26; public static final int MSG_SEND_CURRENT_CONDITION = 27; // Current Conditions API public static final int MSG_MAKE_CURRENT_CONDITIONS_API_CALL = 28; // Notifications public static final int MSG_CHANGE_NOTIFICATION = 31; // Data management public static final int MSG_COUNT_LOCAL_OBS = 32; public static final int MSG_COUNT_API_CACHE = 33; public static final int MSG_COUNT_LOCAL_OBS_TOTALS = 34; public static final int MSG_COUNT_API_CACHE_TOTALS = 35; // Graphing public static final int MSG_GET_API_RECENTS_FOR_GRAPH = 36; public static final int MSG_API_RECENTS_FOR_GRAPH = 37; // Success / Failure notification for data submission public static final int MSG_DATA_RESULT = 38; long lastAPICall = System.currentTimeMillis(); private CbObservation collectedObservation; private final Handler mHandler = new Handler(); Messenger mMessenger = new Messenger(new IncomingHandler()); ArrayList<CbObservation> offlineBuffer = new ArrayList<CbObservation>(); private long lastPressureChangeAlert = 0; private Messenger lastMessenger; private boolean fromUser = false; CbAlarm alarm = new CbAlarm(); double recentPressureReading = 0.0; int recentPressureAccuracy = 0; int batchReadingCount = 0; private long lastSubmit = 0; /** * Collect data from onboard sensors and store locally * * @author jacob * */ public class CbDataCollector implements SensorEventListener { private SensorManager sm; private final int TYPE_AMBIENT_TEMPERATURE = 13; private final int TYPE_RELATIVE_HUMIDITY = 12; private ArrayList<CbObservation> recentObservations = new ArrayList<CbObservation>(); public ArrayList<CbObservation> getRecentObservations() { return recentObservations; } /** * Access the database to fetch recent, locally-recorded observations * * @return */ public ArrayList<CbObservation> getRecentDatabaseObservations() { ArrayList<CbObservation> recentDbList = new ArrayList<CbObservation>(); CbDb db = new CbDb(getApplicationContext()); db.open(); Cursor c = db.fetchAllObservations(); while (c.moveToNext()) { CbObservation obs = new CbObservation(); Location location = new Location("network"); location.setLatitude(c.getDouble(1)); location.setLongitude(c.getDouble(2)); location.setAltitude(c.getDouble(3)); location.setAccuracy(c.getInt(4)); location.setProvider(c.getString(5)); obs.setLocation(location); obs.setObservationType(c.getString(6)); obs.setObservationUnit(c.getString(7)); obs.setObservationValue(c.getDouble(8)); obs.setSharing(c.getString(9)); obs.setTime(c.getInt(10)); obs.setTimeZoneOffset(c.getInt(11)); obs.setUser_id(c.getString(12)); recentDbList.add(obs); } db.close(); return recentDbList; } public void setRecentObservations( ArrayList<CbObservation> recentObservations) { this.recentObservations = recentObservations; } /** * Start collecting sensor data. * * @param m * @return */ public int startCollectingData() { batchReadingCount = 0; try { sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE); Sensor pressureSensor = sm .getDefaultSensor(Sensor.TYPE_PRESSURE); Sensor temperatureSensor = sm .getDefaultSensor(TYPE_AMBIENT_TEMPERATURE); Sensor humiditySensor = sm .getDefaultSensor(TYPE_RELATIVE_HUMIDITY); if (pressureSensor != null) { sm.registerListener(this, pressureSensor,SensorManager.SENSOR_DELAY_UI); } if (temperatureSensor != null) { //sm.registerListener(this, temperatureSensor, SensorManager.SENSOR_DELAY_UI); } if (humiditySensor != null) { //sm.registerListener(this, humiditySensor,SensorManager.SENSOR_DELAY_UI); } return 1; } catch (Exception e) { e.printStackTrace(); return -1; } } /** * Stop collecting sensor data */ public void stopCollectingData() { log("cbservice stop collecting data"); // sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE); if(sm!=null) { sm.unregisterListener(this); } } public CbDataCollector() { } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { if (sensor.getType() == Sensor.TYPE_PRESSURE) { recentPressureAccuracy = accuracy; log("cbservice accuracy changed, new barometer accuracy " + recentPressureAccuracy); } } @Override public void onSensorChanged(SensorEvent event) { if (event.sensor.getType() == Sensor.TYPE_PRESSURE) { if(event.values.length > 0) { if(event.values[0] >= 0) { log("cbservice sensor; new pressure reading " + event.values[0]); recentPressureReading = event.values[0]; } else { log("cbservice sensor; pressure reading is 0 or negative" + event.values[0]); } } else { log("cbservice sensor; no event values"); } } else if (event.sensor.getType() == TYPE_RELATIVE_HUMIDITY) { // recentHumidityReading = event.values[0]; } else if (event.sensor.getType() == TYPE_AMBIENT_TEMPERATURE) { // recentTemperatureReading = event.values[0]; } batchReadingCount++; if(batchReadingCount>10) { log("batch readings " + batchReadingCount + ", stopping"); stopCollectingData(); } else { log("batch readings " + batchReadingCount + ", not stopping"); } } } /** * Find all the data for an observation. * * Location, Measurement values, etc. * * @return */ public CbObservation collectNewObservation() { try { CbObservation pressureObservation = new CbObservation(); log("cb collecting new observation"); // Location values locationManager = new CbLocationManager(getApplicationContext()); locationManager.startGettingLocations(); // Measurement values pressureObservation = buildPressureObservation(); pressureObservation.setLocation(locationManager .getCurrentBestLocation()); // stop listening for locations LocationStopper stop = new LocationStopper(); mHandler.postDelayed(stop, 1000 * 3); log("returning pressure obs: " + pressureObservation.getObservationValue()); return pressureObservation; } catch (Exception e) { //e.printStackTrace(); return null; } } private class LocationStopper implements Runnable { @Override public void run() { try { //System.out.println("locationmanager stop getting locations"); locationManager.stopGettingLocations(); } catch (Exception e) { //e.printStackTrace(); } } } /** * Send a single reading. TODO: Combine with ReadingSender for less code duplication. * ReadingSender. Fix that. */ public class SingleReadingSender implements Runnable { @Override public void run() { if(settingsHandler == null) { log("single reading sender, loading settings from prefs"); loadSetttingsFromPreferences(); } log("collecting and submitting single " + settingsHandler.getServerURL()); dataCollector = new CbDataCollector(); dataCollector.startCollectingData(); CbObservation singleObservation = new CbObservation(); if (settingsHandler.isCollectingData()) { // Collect singleObservation = collectNewObservation(); if (singleObservation.getObservationValue() != 0.0) { // Store in database db.open(); long count = db.addObservation(singleObservation); db.close(); try { if (settingsHandler.isSharingData()) { // Send if we're online if (isNetworkAvailable()) { log("online and sending single"); singleObservation .setClientKey(CbConfiguration.API_KEY); fromUser = true; sendCbObservation(singleObservation); fromUser = false; // also check and send the offline buffer if (offlineBuffer.size() > 0) { log("sending " + offlineBuffer.size() + " offline buffered obs"); for (CbObservation singleOffline : offlineBuffer) { sendCbObservation(singleObservation); } offlineBuffer.clear(); } } else { log("didn't send, not sharing data; i.e., offline"); // / offline buffer variable // TODO: put this in the DB to survive longer offlineBuffer.add(singleObservation); } } } catch (Exception e) { //e.printStackTrace(); } } } } } /** * Put together all the information that defines * an observation and store it in a single object. * @return */ public CbObservation buildPressureObservation() { CbObservation pressureObservation = new CbObservation(); pressureObservation.setTime(System.currentTimeMillis()); pressureObservation.setTimeZoneOffset(Calendar.getInstance() .getTimeZone().getRawOffset()); pressureObservation.setUser_id(getID()); pressureObservation.setObservationType("pressure"); pressureObservation.setObservationValue(recentPressureReading); pressureObservation.setObservationUnit("mbar"); // pressureObservation.setSensor(sm.getSensorList(Sensor.TYPE_PRESSURE).get(0)); pressureObservation.setSharing(settingsHandler.getShareLevel()); pressureObservation.setVersionNumber(getSDKVersion()); log("cbservice buildobs, share level " + settingsHandler.getShareLevel() + " " + getID()); return pressureObservation; } /** * Return the version number of the SDK sending this reading * @return */ public String getSDKVersion() { String version = "-1.0"; try { version = getPackageManager() .getPackageInfo("ca.cumulonimbus.pressurenetsdk", 0).versionName; } catch (NameNotFoundException nnfe) { // TODO: this is not an okay return value // (Don't send error messages as version numbers) version = nnfe.getMessage(); } return version; } /** * Collect and send data in a different thread. This runs itself every * "settingsHandler.getDataCollectionFrequency()" milliseconds */ private class ReadingSender implements Runnable { public void run() { long now = System.currentTimeMillis(); if(now - lastSubmit < 2000) { log("too soon, bailing"); return; } // retrieve updated settings if(settingsHandler == null) { settingsHandler = new CbSettingsHandler(getApplicationContext()); settingsHandler = settingsHandler.getSettings(); } else { settingsHandler = settingsHandler.getSettings(); } if(dataCollector!=null) { dataCollector.startCollectingData(); } else { dataCollector = new CbDataCollector(); dataCollector.startCollectingData(); } log("collecting and submitting " + settingsHandler.getServerURL()); boolean okayToGo = true; // Check if we're supposed to be charging and if we are. // Bail if appropriate if (settingsHandler.isOnlyWhenCharging()) { if (!isCharging()) { okayToGo = false; } } if (okayToGo && settingsHandler.isCollectingData()) { // Collect CbObservation singleObservation = new CbObservation(); singleObservation = collectNewObservation(); if (singleObservation != null) { if (singleObservation.getObservationValue() != 0.0) { // Store in database db.open(); long count = db.addObservation(singleObservation); db.close(); try { if (settingsHandler.isSharingData()) { // Send if we're online if (isNetworkAvailable()) { lastSubmit = System.currentTimeMillis(); log("online and sending"); singleObservation .setClientKey(CbConfiguration.API_KEY); sendCbObservation(singleObservation); // also check and send the offline buffer if (offlineBuffer.size() > 0) { log("sending " + offlineBuffer.size() + " offline buffered obs"); for (CbObservation singleOffline : offlineBuffer) { sendCbObservation(singleObservation); } offlineBuffer.clear(); } } else { log("didn't send"); // / offline buffer variable // TODO: put this in the DB to survive // longer offlineBuffer.add(singleObservation); } } else { log("cbservice not sharing data, didn't send"); } // If notifications are enabled, log("is send notif " + settingsHandler.isSendNotifications()); if (settingsHandler.isSendNotifications()) { // check for pressure local trend changes and // notify // the client // ensure this only happens every once in a // while long rightNow = System.currentTimeMillis(); long sixHours = 1000 * 60 * 60 * 6; if (rightNow - lastPressureChangeAlert > (sixHours)) { long timeLength = 1000 * 60 * 60 * 3; db.open(); Cursor localCursor = db.runLocalAPICall( -90, 90, -180, 180, System.currentTimeMillis() - (timeLength), System.currentTimeMillis(), 1000); ArrayList<CbObservation> recents = new ArrayList<CbObservation>(); while (localCursor.moveToNext()) { // just need observation value, time, // and // location CbObservation obs = new CbObservation(); obs.setObservationValue(localCursor .getDouble(8)); obs.setTime(localCursor.getLong(10)); Location location = new Location( "network"); location.setLatitude(localCursor .getDouble(1)); location.setLongitude(localCursor .getDouble(2)); obs.setLocation(location); recents.add(obs); } String tendencyChange = CbScience .changeInTrend(recents); db.close(); log("cbservice tendency changes: " + tendencyChange); if (tendencyChange.contains(",") && (!tendencyChange.toLowerCase() .contains("unknown"))) { String[] tendencies = tendencyChange .split(","); if (!tendencies[0] .equals(tendencies[1])) { log("Trend change! " + tendencyChange); try { if (lastMessenger != null) { lastMessenger .send(Message .obtain(null, MSG_CHANGE_NOTIFICATION, tendencyChange)); } else { log("readingsender didn't send notif, no lastMessenger"); } } catch (Exception e) { //e.printStackTrace(); } lastPressureChangeAlert = rightNow; } else { log("tendency equal"); } } } else { // wait log("tendency; hasn't been 6h, min wait time yet"); } } } catch (Exception e) { //e.printStackTrace(); } } } else { log("singleobservation is null, not sending"); } } else { log("cbservice is not collecting data."); } } } /** * Check for network connection, return true * if we're online. * * @return */ public boolean isNetworkAvailable() { log("is net available?"); ConnectivityManager cm = (ConnectivityManager) this .getSystemService(Context.CONNECTIVITY_SERVICE); // test for connection if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isAvailable() && cm.getActiveNetworkInfo().isConnected()) { log("yes"); return true; } else { log("no"); return false; } } /** * Stop all listeners, active sensors, etc, and shut down. * */ public void stopAutoSubmit() { if (locationManager != null) { locationManager.stopGettingLocations(); } if (dataCollector != null) { dataCollector.stopCollectingData(); } log("cbservice stop autosubmit"); // alarm.cancelAlarm(getApplicationContext()); } /** * Send the observation to the server * * @param observation * @return */ public boolean sendCbObservation(CbObservation observation) { try { CbDataSender sender = new CbDataSender(getApplicationContext()); settingsHandler = settingsHandler.getSettings(); if(settingsHandler.getServerURL().equals("")) { log("settings are empty; defaults"); //loadSetttingsFromPreferences(); // settingsHandler = settingsHandler.getSettings(); } log("sendCbObservation with settings " + settingsHandler); sender.setSettings(settingsHandler, locationManager, lastMessenger, fromUser); sender.execute(observation.getObservationAsParams()); return true; } catch (Exception e) { return false; } } /** * Send a new account to the server * * @param account * @return */ public boolean sendCbAccount(CbAccount account) { try { CbDataSender sender = new CbDataSender(getApplicationContext()); sender.setSettings(settingsHandler, locationManager, null, true); sender.execute(account.getAccountAsParams()); fromUser = false; return true; } catch (Exception e) { return false; } } /** * Send the current condition to the server * * @param observation * @return */ public boolean sendCbCurrentCondition(CbCurrentCondition condition) { log("sending cbcurrent condition"); try { CbDataSender sender = new CbDataSender(getApplicationContext()); fromUser = true; sender.setSettings(settingsHandler, locationManager, lastMessenger, fromUser); sender.execute(condition.getCurrentConditionAsParams()); fromUser = false; return true; } catch (Exception e) { return false; } } /** * Start the periodic data collection. */ public void startSubmit() { log("CbService: Starting to auto-collect and submit data."); if (!alarm.isRepeating()) { log("cbservice alarm not repeating, starting alarm"); alarm.setAlarm(getApplicationContext(), settingsHandler.getDataCollectionFrequency()); } else { log("cbservice startsubmit, alarm is already repeating. restarting."); alarm.restartAlarm(getApplicationContext(), settingsHandler.getDataCollectionFrequency()); } } @Override public void onDestroy() { log("on destroy"); stopAutoSubmit(); super.onDestroy(); } @Override public void onCreate() { setUpFiles(); log("cb on create"); settingsHandler = new CbSettingsHandler(getApplicationContext()); settingsHandler.getSettings(); db = new CbDb(getApplicationContext()); super.onCreate(); } /** * Check charge state for preferences. * */ public boolean isCharging() { // Check battery and charging status IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); Intent batteryStatus = getApplicationContext().registerReceiver(null, ifilter); // Are we charging / charged? int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1); boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL; return isCharging; } /** * Start running background data collection methods. * */ @Override public int onStartCommand(Intent intent, int flags, int startId) { log("cb onstartcommand"); dataCollector = new CbDataCollector(); if (intent != null) { if (intent.getAction() != null) { if (intent.getAction().equals(ACTION_SEND_MEASUREMENT)) { // send just a single measurement log("sending single observation, request from intent"); sendSingleObs(); return START_NOT_STICKY; } } else if (intent.getBooleanExtra("alarm", false)) { // This runs when the service is started from the alarm. // Submit a data point log("cbservice alarm firing, sending data"); if(settingsHandler == null) { settingsHandler = new CbSettingsHandler(getApplicationContext()); settingsHandler.getSettings(); } else { settingsHandler.getSettings(); } if(settingsHandler.isSharingData()) { dataCollector = new CbDataCollector(); dataCollector.startCollectingData(); startWithIntent(intent, true); } else { log("cbservice not sharing data"); } LocationStopper stop = new LocationStopper(); mHandler.postDelayed(stop, 1000 * 3); return START_NOT_STICKY; } else { // Check the database log("starting service with db"); startWithDatabase(); return START_NOT_STICKY; } } super.onStartCommand(intent, flags, startId); return START_NOT_STICKY; } /** * Convert time ago text to ms. TODO: not this. values in xml. * * @param timeAgo * @return */ public static long stringTimeToLongHack(String timeAgo) { if (timeAgo.equals("1 minute")) { return 1000 * 60; } else if (timeAgo.equals("5 minutes")) { return 1000 * 60 * 5; } else if (timeAgo.equals("10 minutes")) { return 1000 * 60 * 10; } else if (timeAgo.equals("30 minutes")) { return 1000 * 60 * 30; } else if (timeAgo.equals("1 hour")) { return 1000 * 60 * 60; } else if(timeAgo.equals("6 hours")) { return 1000 * 60 * 60 * 6; } else if(timeAgo.equals("12 hours")) { return 1000 * 60 * 60 * 12; } return 1000 * 60 * 10; } public void loadSetttingsFromPreferences() { log("loading settings from prefs"); settingsHandler = new CbSettingsHandler(getApplicationContext()); settingsHandler.setServerURL(serverURL); settingsHandler.setAppID(getApplication().getPackageName()); SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(this); String preferenceCollectionFrequency = sharedPreferences.getString( "autofrequency", "10 minutes"); boolean preferenceShareData = sharedPreferences.getBoolean( "autoupdate", true); String preferenceShareLevel = sharedPreferences.getString( "sharing_preference", "Us, Researchers and Forecasters"); boolean preferenceSendNotifications = sharedPreferences.getBoolean( "send_notifications", false); settingsHandler .setDataCollectionFrequency(stringTimeToLongHack(preferenceCollectionFrequency)); settingsHandler.setSendNotifications(preferenceSendNotifications); boolean useGPS = sharedPreferences.getBoolean("use_gps", true); boolean onlyWhenCharging = sharedPreferences.getBoolean( "only_when_charging", false); settingsHandler.setUseGPS(useGPS); settingsHandler.setOnlyWhenCharging(onlyWhenCharging); settingsHandler.setSharingData(preferenceShareData); settingsHandler.setShareLevel(preferenceShareLevel); // Seems like new settings. Try adding to the db. settingsHandler.saveSettings(); } public void startWithIntent(Intent intent, boolean fromAlarm) { try { if (!fromAlarm) { // We arrived here from the user (i.e., not the alarm) // start/(update?) the alarm startSubmit(); } else { // alarm. Go! ReadingSender reading = new ReadingSender(); mHandler.post(reading); } } catch (Exception e) { for (StackTraceElement ste : e.getStackTrace()) { log(ste.getMethodName() + ste.getLineNumber()); } } } public void startWithDatabase() { try { db.open(); // Check the database for Settings initialization settingsHandler = new CbSettingsHandler(getApplicationContext()); Cursor allSettings = db.fetchSettingByApp(getPackageName()); log("cb intent null; checking db, size " + allSettings.getCount()); if (allSettings.moveToFirst()) { settingsHandler.setAppID(allSettings.getString(1)); settingsHandler.setDataCollectionFrequency(allSettings .getLong(2)); settingsHandler.setServerURL(serverURL); int sendNotifications = allSettings.getInt(4); int useGPS = allSettings.getInt(5); int onlyWhenCharging = allSettings.getInt(6); int sharingData = allSettings.getInt(7); settingsHandler.setShareLevel(allSettings.getString(9)); boolean boolCharging = (onlyWhenCharging > 0); boolean boolGPS = (useGPS > 0); boolean boolSendNotifications = (sendNotifications > 0); boolean boolSharingData = (sharingData > 0); log("only when charging processed " + boolCharging + " gps " + boolGPS); settingsHandler.setSendNotifications(boolSendNotifications); settingsHandler.setOnlyWhenCharging(boolCharging); settingsHandler.setUseGPS(boolGPS); settingsHandler.setSharingData(boolSharingData); settingsHandler.saveSettings(); } log("cbservice startwithdb, " + settingsHandler); ReadingSender reading = new ReadingSender(); mHandler.post(reading); startSubmit(); db.close(); } catch (Exception e) { for (StackTraceElement ste : e.getStackTrace()) { log(ste.getMethodName() + ste.getLineNumber()); } } } /** * Handler of incoming messages from clients. */ class IncomingHandler extends Handler { @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_STOP: log("message. bound service says stop"); try { alarm.cancelAlarm(getApplicationContext()); } catch(Exception e) { } break; case MSG_GET_BEST_LOCATION: log("message. bound service requesting location"); if (locationManager != null) { Location best = locationManager.getCurrentBestLocation(); try { log("service sending best location"); msg.replyTo.send(Message.obtain(null, MSG_BEST_LOCATION, best)); } catch (RemoteException re) { re.printStackTrace(); } } else { log("error: location null, not returning"); } break; case MSG_GET_BEST_PRESSURE: log("message. bound service requesting pressure. not responding"); break; case MSG_START_AUTOSUBMIT: // log("start autosubmit"); // startWithDatabase(); break; case MSG_STOP_AUTOSUBMIT: log("stop autosubmit"); stopAutoSubmit(); break; case MSG_GET_SETTINGS: log("get settings"); if(settingsHandler != null) { settingsHandler.getSettings(); } else { settingsHandler = new CbSettingsHandler(getApplicationContext()); settingsHandler.getSettings(); } try { msg.replyTo.send(Message.obtain(null, MSG_SETTINGS, settingsHandler)); } catch (RemoteException re) { re.printStackTrace(); } break; case MSG_DATA_STREAM: break; case MSG_SET_SETTINGS: log("set settings"); settingsHandler = (CbSettingsHandler) msg.obj; settingsHandler.saveSettings(); break; case MSG_GET_LOCAL_RECENTS: log("get local recents"); recentMsg = msg; CbApiCall apiCall = (CbApiCall) msg.obj; if (apiCall == null) { // log("apicall null, bailing"); break; } // run API call db.open(); Cursor cursor = db.runLocalAPICall(apiCall.getMinLat(), apiCall.getMaxLat(), apiCall.getMinLon(), apiCall.getMaxLon(), apiCall.getStartTime(), apiCall.getEndTime(), 2000); ArrayList<CbObservation> results = new ArrayList<CbObservation>(); while (cursor.moveToNext()) { // TODO: This is duplicated in CbDataCollector. Fix that CbObservation obs = new CbObservation(); Location location = new Location("network"); location.setLatitude(cursor.getDouble(1)); location.setLongitude(cursor.getDouble(2)); location.setAltitude(cursor.getDouble(3)); location.setAccuracy(cursor.getInt(4)); location.setProvider(cursor.getString(5)); obs.setLocation(location); obs.setObservationType(cursor.getString(6)); obs.setObservationUnit(cursor.getString(7)); obs.setObservationValue(cursor.getDouble(8)); obs.setSharing(cursor.getString(9)); obs.setTime(cursor.getLong(10)); obs.setTimeZoneOffset(cursor.getInt(11)); obs.setUser_id(cursor.getString(12)); obs.setTrend(cursor.getString(18)); results.add(obs); } db.close(); log("cbservice: " + results.size() + " local api results"); try { msg.replyTo.send(Message.obtain(null, MSG_LOCAL_RECENTS, results)); } catch (RemoteException re) { re.printStackTrace(); } break; case MSG_GET_API_RECENTS: CbApiCall apiCacheCall = (CbApiCall) msg.obj; log("get api recents " + apiCacheCall.toString()); // run API call try { db.open(); Cursor cacheCursor = db.runAPICacheCall( apiCacheCall.getMinLat(), apiCacheCall.getMaxLat(), apiCacheCall.getMinLon(), apiCacheCall.getMaxLon(), apiCacheCall.getStartTime(), apiCacheCall.getEndTime(), apiCacheCall.getLimit()); ArrayList<CbObservation> cacheResults = new ArrayList<CbObservation>(); while (cacheCursor.moveToNext()) { CbObservation obs = new CbObservation(); Location location = new Location("network"); location.setLatitude(cacheCursor.getDouble(1)); location.setLongitude(cacheCursor.getDouble(2)); obs.setLocation(location); obs.setObservationValue(cacheCursor.getDouble(3)); obs.setTime(cacheCursor.getLong(4)); cacheResults.add(obs); } db.close(); try { msg.replyTo.send(Message.obtain(null, MSG_API_RECENTS, cacheResults)); } catch (RemoteException re) { // re.printStackTrace(); } } catch (Exception e) { } break; case MSG_GET_API_RECENTS_FOR_GRAPH: // TODO: Put this in a method. It's a copy+paste from // GET_API_RECENTS CbApiCall apiCacheCallGraph = (CbApiCall) msg.obj; log("get api recents " + apiCacheCallGraph.toString()); // run API call db.open(); Cursor cacheCursorGraph = db.runAPICacheCall( apiCacheCallGraph.getMinLat(), apiCacheCallGraph.getMaxLat(), apiCacheCallGraph.getMinLon(), apiCacheCallGraph.getMaxLon(), apiCacheCallGraph.getStartTime(), apiCacheCallGraph.getEndTime(), apiCacheCallGraph.getLimit()); ArrayList<CbObservation> cacheResultsGraph = new ArrayList<CbObservation>(); while (cacheCursorGraph.moveToNext()) { CbObservation obs = new CbObservation(); Location location = new Location("network"); location.setLatitude(cacheCursorGraph.getDouble(1)); location.setLongitude(cacheCursorGraph.getDouble(2)); obs.setLocation(location); obs.setObservationValue(cacheCursorGraph.getDouble(3)); obs.setTime(cacheCursorGraph.getLong(4)); cacheResultsGraph.add(obs); } db.close(); try { msg.replyTo.send(Message.obtain(null, MSG_API_RECENTS_FOR_GRAPH, cacheResultsGraph)); } catch (RemoteException re) { re.printStackTrace(); } break; case MSG_MAKE_API_CALL: CbApi api = new CbApi(getApplicationContext()); CbApiCall liveApiCall = (CbApiCall) msg.obj; liveApiCall.setCallType("Readings"); long timeDiff = System.currentTimeMillis() - lastAPICall; deleteOldData(); lastAPICall = api.makeAPICall(liveApiCall, service, msg.replyTo, "Readings"); break; case MSG_MAKE_CURRENT_CONDITIONS_API_CALL: CbApi conditionApi = new CbApi(getApplicationContext()); CbApiCall conditionApiCall = (CbApiCall) msg.obj; conditionApiCall.setCallType("Conditions"); conditionApi.makeAPICall(conditionApiCall, service, msg.replyTo, "Conditions"); break; case MSG_CLEAR_LOCAL_CACHE: db.open(); db.clearLocalCache(); long count = db.getUserDataCount(); db.close(); try { msg.replyTo.send(Message.obtain(null, MSG_COUNT_LOCAL_OBS_TOTALS, (int) count, 0)); } catch (RemoteException re) { re.printStackTrace(); } break; case MSG_REMOVE_FROM_PRESSURENET: // TODO: Implement a secure system to remove user data break; case MSG_CLEAR_API_CACHE: db.open(); db.clearAPICache(); long countCache = db.getDataCacheCount(); db.close(); try { msg.replyTo.send(Message.obtain(null, MSG_COUNT_API_CACHE_TOTALS, (int) countCache, 0)); } catch (RemoteException re) { //re.printStackTrace(); } break; case MSG_ADD_CURRENT_CONDITION: CbCurrentCondition cc = (CbCurrentCondition) msg.obj; try { db.open(); db.addCondition(cc); db.close(); } catch(SQLiteDatabaseLockedException dble) { } break; case MSG_GET_CURRENT_CONDITIONS: recentMsg = msg; db.open(); CbApiCall currentConditionAPI = (CbApiCall) msg.obj; Cursor ccCursor = db.getCurrentConditions( currentConditionAPI.getMinLat(), currentConditionAPI.getMaxLat(), currentConditionAPI.getMinLon(), currentConditionAPI.getMaxLon(), currentConditionAPI.getStartTime(), currentConditionAPI.getEndTime(), 1000); ArrayList<CbCurrentCondition> conditions = new ArrayList<CbCurrentCondition>(); while (ccCursor.moveToNext()) { CbCurrentCondition cur = new CbCurrentCondition(); Location location = new Location("network"); location.setLatitude(ccCursor.getDouble(1)); location.setLongitude(ccCursor.getDouble(2)); location.setAltitude(ccCursor.getDouble(3)); location.setAccuracy(ccCursor.getInt(4)); location.setProvider(ccCursor.getString(5)); cur.setLocation(location); cur.setTime(ccCursor.getLong(6)); cur.setTime(ccCursor.getLong(7)); cur.setUser_id(ccCursor.getString(9)); cur.setGeneral_condition(ccCursor.getString(10)); cur.setWindy(ccCursor.getString(11)); cur.setFog_thickness(ccCursor.getString(12)); cur.setCloud_type(ccCursor.getString(13)); cur.setPrecipitation_type(ccCursor.getString(14)); cur.setPrecipitation_amount(ccCursor.getDouble(15)); cur.setPrecipitation_unit(ccCursor.getString(16)); cur.setThunderstorm_intensity(ccCursor.getString(17)); cur.setUser_comment(ccCursor.getString(18)); conditions.add(cur); } db.close(); try { msg.replyTo.send(Message.obtain(null, MSG_CURRENT_CONDITIONS, conditions)); } catch (RemoteException re) { re.printStackTrace(); } break; case MSG_SEND_CURRENT_CONDITION: CbCurrentCondition condition = (CbCurrentCondition) msg.obj; if (settingsHandler == null) { settingsHandler = new CbSettingsHandler( getApplicationContext()); settingsHandler.setServerURL(serverURL); settingsHandler .setAppID(getApplication().getPackageName()); } try { condition .setSharing_policy(settingsHandler.getShareLevel()); sendCbCurrentCondition(condition); } catch (Exception e) { //e.printStackTrace(); } break; case MSG_SEND_OBSERVATION: log("sending single observation, request from app"); sendSingleObs(); break; case MSG_COUNT_LOCAL_OBS: db.open(); long countLocalObsOnly = db.getUserDataCount(); db.close(); try { msg.replyTo.send(Message.obtain(null, MSG_COUNT_LOCAL_OBS_TOTALS, (int) countLocalObsOnly, 0)); } catch (RemoteException re) { re.printStackTrace(); } break; case MSG_COUNT_API_CACHE: db.open(); long countCacheOnly = db.getDataCacheCount(); db.close(); try { msg.replyTo.send(Message .obtain(null, MSG_COUNT_API_CACHE_TOTALS, (int) countCacheOnly, 0)); } catch (RemoteException re) { re.printStackTrace(); } break; case MSG_CHANGE_NOTIFICATION: if (msg.replyTo != null) { lastMessenger = msg.replyTo; } else { } break; default: super.handleMessage(msg); } } } public void sendSingleObs() { if (settingsHandler != null) { if (settingsHandler.getServerURL() == null) { settingsHandler.getSettings(); } } SingleReadingSender singleSender = new SingleReadingSender(); mHandler.post(singleSender); } /** * Remove older data from cache to keep the size reasonable * * @return */ public void deleteOldData() { log("deleting old data"); db.open(); db.deleteOldCacheData(); db.close(); } public boolean notifyAPIResult(Messenger reply, int count) { try { if (reply == null) { log("cannot notify, reply is null"); } else { reply.send(Message.obtain(null, MSG_API_RESULT_COUNT, count, 0)); } } catch (RemoteException re) { re.printStackTrace(); } catch (NullPointerException npe) { //npe.printStackTrace(); } return false; } public CbObservation recentPressureFromDatabase() { CbObservation obs = new CbObservation(); double pressure = 0.0; try { long rowId = db.fetchObservationMaxID(); Cursor c = db.fetchObservation(rowId); while (c.moveToNext()) { pressure = c.getDouble(8); } log(pressure + " pressure from db"); if (pressure == 0.0) { log("returning null"); return null; } obs.setObservationValue(pressure); return obs; } catch (Exception e) { obs.setObservationValue(pressure); return obs; } } /** * Get a hash'd device ID * * @return */ public String getID() { try { MessageDigest md = MessageDigest.getInstance("MD5"); String actual_id = Secure.getString(getApplicationContext() .getContentResolver(), Secure.ANDROID_ID); byte[] bytes = actual_id.getBytes(); byte[] digest = md.digest(bytes); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < digest.length; i++) { hexString.append(Integer.toHexString(0xFF & digest[i])); } return hexString.toString(); } catch (Exception e) { return " } } // Used to write a log to SD card. Not used unless logging enabled. public void setUpFiles() { try { File homeDirectory = getExternalFilesDir(null); if (homeDirectory != null) { mAppDir = homeDirectory.getAbsolutePath(); } } catch (Exception e) { //e.printStackTrace(); } } // Log data to SD card for debug purposes. // To enable logging, ensure the Manifest allows writing to SD card. public void logToFile(String text) { try { OutputStream output = new FileOutputStream(mAppDir + "/log.txt", true); String logString = (new Date()).toString() + ": " + text + "\n"; output.write(logString.getBytes()); output.close(); } catch (FileNotFoundException e) { //e.printStackTrace(); } catch (IOException ioe) { //ioe.printStackTrace(); } } @Override public IBinder onBind(Intent intent) { log("on bind"); return mMessenger.getBinder(); } @Override public void onRebind(Intent intent) { log("on rebind"); super.onRebind(intent); } public void log(String message) { if(CbConfiguration.DEBUG_MODE) { //logToFile(message); System.out.println(message); } } public CbDataCollector getDataCollector() { return dataCollector; } public void setDataCollector(CbDataCollector dataCollector) { this.dataCollector = dataCollector; } public CbLocationManager getLocationManager() { return locationManager; } public void setLocationManager(CbLocationManager locationManager) { this.locationManager = locationManager; } }
/* Open Source Software - may be modified and shared by FRC teams. The code */ /* the project. */ // FILE NAME: Autonomous.java (Team 339 - Kilroy) // ABSTRACT: // This file is where almost all code for Kilroy will be // written. All of these functions are functions that should // override methods in the base class (IterativeRobot). The // functions are as follows: // Init() - Initialization code for autonomous mode // should go here. Will be called each time the robot enters // autonomous mode. // Periodic() - Periodic code for autonomous mode should // go here. Will be called periodically at a regular rate while // the robot is in autonomous mode. // Team 339. package org.usfirst.frc.team339.robot; import org.usfirst.frc.team339.Hardware.Hardware; import org.usfirst.frc.team339.HardwareInterfaces.transmission.Transmission_old.debugStateValues; import org.usfirst.frc.team339.Utils.ManipulatorArm; import org.usfirst.frc.team339.Utils.ManipulatorArm.ArmPosition; import edu.wpi.first.wpilibj.DoubleSolenoid.Value; import edu.wpi.first.wpilibj.Relay; /** * This class contains all of the user code for the Autonomous part of the * match, namely, the Init and Periodic code * * @author Nathanial Lydick * @written Jan 13, 2015 */ /** * A new and improved Autonomous class. * The class <b>beautifully</b> uses state machines in order to periodically * execute instructions during the Autonomous period. * * TODO: "make it worky". * * @author Michael Andrzej Klaczynski * @written at the eleventh stroke of midnight, the 28th of January, * Year of our LORD 2016. Rewritten ever thereafter. * */ public class Autonomous { /** * The overarching states of autonomous mode. */ private static enum MainState { /** * The first state. * Initializes things if necessary, * though most things are initialized * in init(). */ INIT, // beginning, check conditions /** * Sets arm to head downward. */ BEGIN_LOWERING_ARM, /** * slowly increase speed from 0; */ ACCELERATE_FROM_ZERO, /** * Moves at a low speed while lowering arm. * If it reaches the end of the distance, and the arm is not fully down, * skips to DONE. */ MOVE_TO_OUTER_WORKS, /** * Resets and starts delay timer. */ INIT_DELAY,// sets delay timer. /** * Waits. * Waits until the delay is up. */ DELAY, // waits, depending on settings. /** * This state checks to see if we are in lane 1. * If so, we go until we reach an encoder distance (set to distance to * alignment tape), * Else, we go until the sensors find the Alignment tape. */ FORWARDS_BASED_ON_ENCODERS_OR_IR, // decides based on lane whether to move // to tape based on encoders or IR /** * Go the distance over the outer works. */ FORWARDS_OVER_OUTER_WORKS, /** * Goes forward until it reaches the set distance to the Alignment tape. */ FORWARDS_TO_TAPE_BY_DISTANCE, // drives the distance required to the tape. /** * Goes forward until it senses the Alignment tape. */ FORWARDS_UNTIL_TAPE, // drives forwards until detection of the gaffers' // tape. /** * Drives up 16 inches to put the center of the robot over the Aline. */ CENTER_TO_TAPE, /** * If we are in backup plan (lane 6), start a delay so that we can * reverse. */ DELAY_IF_REVERSE, /** * Upon reaching the Alignment line, sometimes we must rotate. */ ROTATE_ON_ALIGNMENT_LINE, // rotates on the alignment line. /** * After reaching the A-line, or after rotating upon reaching it, drives * towards a position in front of the goal. */ FORWARDS_FROM_ALIGNMENT_LINE, // drives from the alignment line. /** * After reaching a spot in front of the goal, we turn to face it. */ TURN_TO_FACE_GOAL, // rotates toward the goal. /** * Once we are facing the goal, we may sometimes drive forwards. */ DRIVE_UP_TO_GOAL, // drives up the goal. /** * Brakes once we are in front of the goal. */ STOP_IN_FRONT_OF_GOAL, /** * Once we are in the shooting position, we align based on the chimera. */ ALIGN_IN_FRONT_OF_GOAL, /** * We shoot the cannon ball. */ SHOOT, // adjusts its self (?) and fires the cannon ball. /** * Wait to close the solenoids. */ DELAY_AFTER_SHOOT, /** * Wait for the arm to come down before crossing the outer works. */ WAIT_FOR_ARM_DESCENT, /** * We stop, and do nothing else. */ DONE } /** * * States to run arm movements in parallel. * */ private static enum ArmState { /** * Begins moving the arm in a downwards/down-to-the-floor action * fashion. */ INIT_DOWN, /** * Czecks to see if the arm is all the way down. */ MOVE_DOWN, /** * Begins moving the arm in a upwards/up-to-the-shooter action fashion. */ INIT_UP, /** * Czecks to see if the arm is all the way up. */ CHECK_UP, /** * Moves, and czecks to see if the arm is all the way up, so that we may * deposit. */ MOVE_UP_TO_DEPOSIT, /** * Begins spinning its wheels so as to spit out the cannon ball. */ INIT_DEPOSIT, /** * Have we spit out the cannon ball? If so, INIT_DOWN. */ DEPOSIT, /** * Hold the ball out of the way. */ HOLD, /** * Do nothing, but set armStatesOn to false. */ DONE } // AUTO STATES /** * The state to be executed periodically throughout Autonomous. */ private static MainState mainState = MainState.INIT; /** * Used to run arm movements in parallel to the main state machine. */ private static ArmState armState = ArmState.DONE; // VARIABLES /** * The boolean that decides whether or not we run autonomous. */ private static boolean autonomousEnabled; /** * Time to delay at beginning. 0-3 seconds */ private static double delay; // time to delay before beginning. /** * Number of our starting position, and path further on. */ private static int lane; private static int accelerationStage = 0; private static double totalDistance = 0; /** * Run the arm state machine only when necessary (when true). */ private static boolean runArmStates = false; /** * Prints print that it prints prints while it prints true. */ private static boolean debug; // TUNEABLES /** * User-Initialization code for autonomous mode should go here. Will be * called once when the robot enters autonomous mode. * * @author Nathanial Lydick * * @written Jan 13, 2015 */ public static void init () { try { //check the Autonomous ENABLED/DISABLED switch. autonomousEnabled = Hardware.autonomousEnabled.isOn(); // set the delay time based on potentiometer. delay = initDelayTime(); // get the lane based off of startingPositionPotentiometer lane = getLane(); debug = DEBUGGING_DEFAULT; Hardware.transmission .setDebugState(debugStateValues.DEBUG_ALL); // Hardware.drive.setMaxSpeed(MAXIMUM_AUTONOMOUS_SPEED); // motor initialization Hardware.transmission.setFirstGearPercentage(1.0); Hardware.transmission.setGear(1); Hardware.transmission.setJoysticksAreReversed(true); Hardware.transmission.setJoystickDeadbandRange(0.0); // Encoder Initialization Hardware.leftRearEncoder.reset(); Hardware.rightRearEncoder.reset(); // Sets Resolution of camera Hardware.ringLightRelay.set(Relay.Value.kOff); Hardware.axisCamera .writeBrightness( Hardware.MINIMUM_AXIS_CAMERA_BRIGHTNESS); // turn the timer off and reset the counter // so that we can use it in autonomous Hardware.kilroyTimer.stop(); Hardware.kilroyTimer.reset(); Hardware.leftRearEncoder.reset(); Hardware.rightRearEncoder.reset(); Hardware.leftFrontMotor.set(0.0); Hardware.leftRearMotor.set(0.0); Hardware.rightFrontMotor.set(0.0); Hardware.rightRearMotor.set(0.0); Hardware.armMotor.set(0.0); Hardware.armIntakeMotor.set(0.0); try { Hardware.errorMessage.clearErrorlog(); } catch (Exception e) { System.out.println("clearing log is the problem"); } } catch (Exception e) { System.out.println("Auto init died"); } } // end Init /** * User Periodic code for autonomous mode should go here. Will be called * periodically at a regular rate while the robot is in autonomous mode. * * @author Nathanial Lydick * @written Jan 13, 2015 */ public static void periodic () { // Checks the "enabled" switch. if (autonomousEnabled == true) { //runs the overarching state machine. runMainStateMachine(); } // Czecks if we are running any arm functions. if (runArmStates == true) //run the arm state machine. { System.out.println("\t" + armState); runArmStates(); } else { Hardware.pickupArm.stopArmMotor(); } Teleop.printStatements(); } // end Periodic /** * Sets the delay time in full seconds based on potentiometer. */ private static int initDelayTime () { return (int) (MAXIMUM_DELAY * Hardware.delayPot.get() / Hardware.DELAY_POT_DEGREES); } /** * Called periodically to run the overarching states. */ private static void runMainStateMachine () { if (debug == true) // print out states. { System.out.println("Main State: " + mainState); // System.out.println("LeftIR: " + Hardware.leftIR.isOn()); // System.out.println("RightIR: " + Hardware.rightIR.isOn()); // if (Hardware.leftIR.isOn() || Hardware.rightIR.isOn()) //// Hardware.errorMessage.printError( //// (mainState + ": An IR has turned on."), PrintsTo.roboRIO, //// false); //System.out.println("Arm Pot: " + Hardware.armPot.get()); // Teleop.printStatements(); // Hardware.errorMessage.printError( // "Main State: " + mainState, // ErrorMessage.PrintsTo.roboRIO); // Hardware.errorMessage.printError( // "Left:" + Hardware.leftRearEncoder.getDistance(), // ErrorMessage.PrintsTo.roboRIO); // Hardware.errorMessage.printError( // "Right:" + Hardware.rightRearEncoder.getDistance(), // ErrorMessage.PrintsTo.roboRIO); // System.out.println("Time: " + Hardware.kilroyTimer.get()); } switch (mainState) { case INIT: // Doesn't do much. // Just a Platypus. mainInit(); if (lane == 1 || lane == 6) // lower the arm to pass beneath the bar. { mainState = MainState.BEGIN_LOWERING_ARM; } else // lowering the arm would get in the way. Skip to delay. { mainState = MainState.INIT_DELAY; } break; case BEGIN_LOWERING_ARM: // starts the arm movement to the floor runArmStates = true; armState = ArmState.MOVE_DOWN; // goes into initDelay mainState = MainState.INIT_DELAY; break; case ACCELERATE_FROM_ZERO: if (accelerationStage < DriveInformation.ACCELERATION_RATIOS.length) { Hardware.drive.driveStraightByInches(99999, false, DriveInformation.ACCELERATION_RATIOS[accelerationStage], DriveInformation.ACCELERATION_RATIOS[accelerationStage]); if (Hardware.delayTimer .get() > DriveInformation.ACCELERATION_TIMES[accelerationStage]) { accelerationStage++; } } else { Hardware.delayTimer.stop(); Hardware.delayTimer.reset(); mainState = MainState.MOVE_TO_OUTER_WORKS; } break; case MOVE_TO_OUTER_WORKS: // goes forwards to outer works. if ((Hardware.drive.driveStraightByInches( DriveInformation.DISTANCE_TO_OUTER_WORKS * labScalingFactor, false, DriveInformation.MOTOR_RATIO_TO_OUTER_WORKS[lane], DriveInformation.MOTOR_RATIO_TO_OUTER_WORKS[lane])) == true) //continue over the outer works unless the arm is going to get in the way. { Hardware.axisCamera.saveImagesSafely(); //Teleop.printStatements(); //continue over the Outer Works mainState = MainState.FORWARDS_OVER_OUTER_WORKS; resetEncoders(); //UNLESS... //When going under the low bar (lane 1), the arm must be down. if ((lane == 1 || lane == 6) && (Hardware.pickupArm.isDown() == false)) //arm is not down in time. STOP. { mainState = MainState.WAIT_FOR_ARM_DESCENT; } } break; case INIT_DELAY: // reset and start timer initDelay(); // run DELAY state. mainState = MainState.DELAY; break; case DELAY: // check whether done or not until done. if (delayIsDone() == true) // go to move forwards while lowering arm when finished. { mainState = MainState.ACCELERATE_FROM_ZERO; Hardware.delayTimer.reset(); Hardware.delayTimer.start(); } break; case FORWARDS_OVER_OUTER_WORKS: //Drive over Outer Works. if (Hardware.drive.driveStraightByInches( DriveInformation.DISTANCE_OVER_OUTER_WORKS * labScalingFactor, false, DriveInformation.DRIVE_OVER_OUTER_WORKS_MOTOR_RATIOS[lane], DriveInformation.DRIVE_OVER_OUTER_WORKS_MOTOR_RATIOS[lane]) == true) //put up all the things we had to put down under the low bar. //begin loading the catapult. { //put up camera. Hardware.cameraSolenoid.set(Value.kReverse); armState = ArmState.MOVE_UP_TO_DEPOSIT; //Teleop.printStatements(); resetEncoders(); //initiate the arm motion. runArmStates = true; mainState = MainState.FORWARDS_BASED_ON_ENCODERS_OR_IR; } break; case WAIT_FOR_ARM_DESCENT: Hardware.transmission.controls(0.0, 0.0); //System.out.println(Hardware.armPot.get()); if (Hardware.pickupArm.moveToPosition( ManipulatorArm.ArmPosition.FULL_DOWN) == true) mainState = MainState.FORWARDS_OVER_OUTER_WORKS; break; case FORWARDS_BASED_ON_ENCODERS_OR_IR: // Check if we are in lane One. if (lane == 1 || lane == 6) // If so, move forwards the distance to the A-tape. { mainState = MainState.FORWARDS_TO_TAPE_BY_DISTANCE; } else // If in another lane, move forwards until we detect the A-tape. { mainState = MainState.FORWARDS_UNTIL_TAPE; } break; case FORWARDS_TO_TAPE_BY_DISTANCE: // Drive the distance from outer works to A-Line. if ((Hardware.drive.driveStraightByInches( DriveInformation.DISTANCE_TO_TAPE * labScalingFactor, false, DriveInformation.MOTOR_RATIO_TO_A_LINE[lane], DriveInformation.MOTOR_RATIO_TO_A_LINE[lane]) == true)) // when done, proceed from Alignment line. { //Teleop.printStatements(); //reset Encoders to prepare for next state. resetEncoders(); //We definitely don't need to rotate. mainState = MainState.CENTER_TO_TAPE; } break; case FORWARDS_UNTIL_TAPE: // Drive until IR sensors pick up tape. if (hasMovedToTape() == true) { //reset Encoders to prepare for next state. resetEncoders(); // When done, possibly rotate. mainState = MainState.CENTER_TO_TAPE; } break; case CENTER_TO_TAPE: //Drive up from front of the Alignment Line to put the pivoting center of the robot on the Line. if (Hardware.drive.driveStraightByInches( DriveInformation.DISTANCE_TO_CENTRE_OF_ROBOT, DriveInformation.BREAK_ON_ALIGNMENT_LINE[lane], DriveInformation.CENTRE_TO_ALIGNMENT_LINE_MOTOR_RATIO[lane], DriveInformation.CENTRE_TO_ALIGNMENT_LINE_MOTOR_RATIO[lane])) { mainState = MainState.FORWARDS_FROM_ALIGNMENT_LINE; //Teleop.printStatements(); Hardware.delayTimer.reset(); Hardware.delayTimer.start(); } break; case DELAY_IF_REVERSE: if (Hardware.delayTimer .get() >= DriveInformation.DELAY_IF_REVERSE[lane]) { mainState = MainState.ROTATE_ON_ALIGNMENT_LINE; } break; case ROTATE_ON_ALIGNMENT_LINE: //Rotates until we are pointed at the place from whence we want to shoot. if (hasTurnedBasedOnSign( DriveInformation.ROTATE_ON_ALIGNMENT_LINE_DISTANCE[lane] * labScalingFactor) == true) { //reset Encoders to prepare for next state. resetEncoders(); //then move. mainState = MainState.FORWARDS_FROM_ALIGNMENT_LINE; } break; case FORWARDS_FROM_ALIGNMENT_LINE: //Drive until we reach the line normal to the goal. if (Hardware.drive.driveStraightByInches( DriveInformation.FORWARDS_FROM_ALIGNMENT_LINE_DISTANCE[lane] * labScalingFactor, false,//true, //breaking here is preferable. DriveInformation.FORWARDS_FROM_ALIGNMENT_LINE_MOTOR_RATIO[lane], DriveInformation.FORWARDS_FROM_ALIGNMENT_LINE_MOTOR_RATIO[lane]) == true) { //Teleop.printStatements(); //reset Encoders to prepare for next state. resetEncoders(); mainState = MainState.TURN_TO_FACE_GOAL; } break; case TURN_TO_FACE_GOAL: //Turns until we are facing the goal. if (hasTurnedBasedOnSign( DriveInformation.TURN_TO_FACE_GOAL_DEGREES[lane]) == true) //when done move up to the batter. { //Teleop.printStatements(); //reset Encoders to prepare for next state resetEncoders(); Hardware.ringLightRelay.set(Relay.Value.kOn); armState = ArmState.HOLD; //then drive. mainState = MainState.DONE; } break; case DRIVE_UP_TO_GOAL: //Moves to goal. Stops to align. if (((Hardware.drive.driveStraightByInches( DriveInformation.DRIVE_UP_TO_GOAL[lane] * labScalingFactor, false, DriveInformation.DRIVE_UP_TO_GOAL_MOTOR_RATIO[lane], DriveInformation.DRIVE_UP_TO_GOAL_MOTOR_RATIO[lane]) == true) || (Hardware.leftIR.isOn() || Hardware.rightIR.isOn()))) //Go to align. { //reset Encoders to prepare for next state. resetEncoders(); //go to align. mainState = MainState.ALIGN_IN_FRONT_OF_GOAL; } break; case STOP_IN_FRONT_OF_GOAL: //if (Hardware.drive.brake(.1) == true) { mainState = MainState.DONE;//MainState.SHOOT; } case ALIGN_IN_FRONT_OF_GOAL: //align based on the camera until we are facing the goal. head-on. //TODO: Demystify magic numbers if (Hardware.drive.alignByCamera(0.1, .4, 0.0, false) == true) //Once we are in position, we shoot! { mainState = MainState.SHOOT; } break; case SHOOT: //FIRE!!! shoot(); mainState = MainState.DELAY_AFTER_SHOOT; Hardware.axisCamera.saveImagesSafely(); break; case DELAY_AFTER_SHOOT: //Check if enough time has passed for the air to have been released. if (hasShot() == true) { mainState = MainState.DONE; } default: case DONE: //clean everything up; //the blood of our enemies stains quickly. done(); break; } } private static void mainInit () { Hardware.kilroyTimer.reset(); Hardware.kilroyTimer.start(); } /** * Starts the delay timer. */ private static void initDelay () { Hardware.delayTimer.reset(); Hardware.delayTimer.start(); } /** * Waits. * One of the overarching states. */ private static boolean delayIsDone () { boolean done = false; // stop. Hardware.transmission.controls(0.0, 0.0); // check timer if (Hardware.delayTimer.get() > delay) // return true. stop and reset timer. { done = true; Hardware.delayTimer.stop(); Hardware.delayTimer.reset(); } if (Hardware.pickupArm.isDown() == true) { } return done; } /** * Drives, and * Checks to see if the IRSensors detect Alignment tape. * * @return true when it does. */ private static boolean hasMovedToTape () { //The stateness of being on the tape. boolean tapeness = false; // Move forwards. Hardware.drive.driveStraightContinuous(); // simply check if we have detected the tape on either side. if (Hardware.leftIR.isOn() || Hardware.rightIR.isOn()) // we are done here. { tapeness = true; } return tapeness; } /** * Drives to the final shooting position. * * @return true when complete. */ private static boolean hasDrivenUpToGoal () { boolean done = false; // Have we reached the distance according to drawings. // Have we seen if we have reached cleats of the tower according to IR? if ((Hardware.drive.driveStraightByInches( DriveInformation.DRIVE_UP_TO_GOAL[lane] * labScalingFactor, false, DriveInformation.DRIVE_UP_TO_GOAL_MOTOR_RATIO[lane], DriveInformation.DRIVE_UP_TO_GOAL_MOTOR_RATIO[lane]) == true) || (Hardware.leftIR.isOn() || Hardware.rightIR.isOn())) // We are done here. { done = true; } // TEMPORARY PRINTS. // see if we have stopped based on IR or Encoders. // if (done == true // && (Hardware.leftIR.isOn() || Hardware.rightIR.isOn())) // System.out.println("Stopped by Sensors"); // else if (Hardware.leftRearEncoder // .getDistance() >= DriveInformation.DRIVE_UP_TO_GOAL[lane] || // Hardware.rightRearEncoder // .getDistance() >= DriveInformation.DRIVE_UP_TO_GOAL[lane]) // System.out.println("Stopped by distance."); return done; } /** * <b> FIRE!!! </b> * <p> * Shoots the ball. * */ private static void shoot () { //Make sure the arm is out of the way. if (Hardware.pickupArm.isClearOfArm()) { //RELEASE THE KRACKEN! I mean, the pressurized air... Hardware.catapultSolenoid0.set(true); Hardware.catapultSolenoid1.set(true); Hardware.catapultSolenoid2.set(true); } //set a timer so that we know when to close the solenoids. Hardware.kilroyTimer.reset(); Hardware.kilroyTimer.start(); } /** * Wait a second... * Close the solenoids. * * @return true when delay is up. */ private static boolean hasShot () { //Check the time. if (Hardware.kilroyTimer.get() > DELAY_TIME_AFTER_SHOOT) //Close the airways, and finish. { Hardware.catapultSolenoid0.set(false); Hardware.catapultSolenoid1.set(false); Hardware.catapultSolenoid2.set(false); return true; } return false; } /** * Stop everything. */ private static void done () { autonomousEnabled = false; debug = false; Hardware.transmission.controls(0.0, 0.0); Hardware.armMotor.set(0.0); Hardware.delayTimer.stop(); Hardware.delayTimer.reset(); Hardware.ringLightRelay.set(Relay.Value.kOff); armState = ArmState.DONE; System.out.println("Total Distance: " + totalDistance); } /** * A separate state machine, used to run arm movements in parallel. */ private static void runArmStates () { switch (armState) { case INIT_DOWN: //begin moving arm down Hardware.pickupArm.move(-1.0); //go to periodically check. armState = ArmState.MOVE_DOWN; break; case MOVE_DOWN: //check if down. if (Hardware.pickupArm .moveToPosition(ArmPosition.FULL_DOWN) == true) //stop. { Hardware.pickupArm.move(0.0); armState = ArmState.DONE; } break; case INIT_UP: //begin moving arm up. Hardware.pickupArm.move(1.0); //go to periodically check. armState = ArmState.CHECK_UP; break; case CHECK_UP: //check if up. if (Hardware.pickupArm.isUp() == true) { //stop. Hardware.pickupArm.move(0.0); armState = ArmState.DONE; } break; case MOVE_UP_TO_DEPOSIT: //check is in up position so that we may deposit the ball. if (Hardware.pickupArm .moveToPosition(ArmPosition.DEPOSIT) == true) //stop, and go to deposit. { Hardware.pickupArm.move(0.0); armState = ArmState.INIT_DEPOSIT; } break; case INIT_DEPOSIT: //spin wheels to release ball. Hardware.pickupArm.pullInBall(true); //armState = ArmState.DEPOSIT; break; case DEPOSIT: //check if the ball is out. if (Hardware.pickupArm.ballIsOut()) //stop rollers, and move down. { Hardware.pickupArm.stopIntakeArms(); //get out of the way. armState = ArmState.DONE; } break; case HOLD: Hardware.pickupArm.stopIntakeArms(); Hardware.pickupArm.moveToPosition(ArmPosition.HOLD); break; default: case DONE: //stop running state machine. runArmStates = false; break; } } //TODO: Remove unecessary TODOs /** * Return the starting position based on 6-position switch on the robot. * * @return lane/starting position */ private static int getLane () { int position = Hardware.startingPositionDial.getPosition(); //-1 is returned when there is no signal. if (position == -1) //Go to lane 1 by default. { position = 0; } position++; return position; } /** * Reset left and right encoders. * To be called at the end of any state that uses Drive. */ public static void resetEncoders () { totalDistance += (Hardware.leftRearEncoder.getDistance() + Hardware.rightRearEncoder.get()) / 2; Hardware.leftRearEncoder.reset(); Hardware.rightRearEncoder.reset(); } /** * For turning in drive based on array of positive and negative values. * Use to turn a number of degrees * COUNTERCLOCKWISE. * Kilroy must turn along different paths. * You must use this to be versatile. */ private static boolean hasTurnedBasedOnSign (double degrees, double turnSpeed) { boolean done = false; if (degrees < 0) //Turn right. Make degrees positive. { done = Hardware.drive.turnRightDegrees(-degrees, false, turnSpeed, -turnSpeed); } else //Turn left the given number of degrees. { done = Hardware.drive.turnLeftDegrees(degrees, false, -turnSpeed, turnSpeed); } return done; } /** * For turning in drive based on array of positive and negative values. * Use to turn a number of degrees * COUNTERCLOCKWISE. * Kilroy must turn along different paths. * You must use this to be versatile. */ private static boolean hasTurnedBasedOnSign (double degrees) { return hasTurnedBasedOnSign(degrees, DriveInformation.DEFAULT_TURN_SPEED); } /** * Contains distances and speeds at which to drive. * * TODO: Figure out reasonable speeds, etc. */ private static final class DriveInformation { private static final double[] ACCELERATION_RATIOS = { 0.1, 0.2, 0.3 }; private static final double[] ACCELERATION_TIMES = { 0.2, 0.4, 0.6 }; private static final double[] DRIVE_OVER_OUTER_WORKS_MOTOR_RATIOS = { 0.0, 0.4, 0.7, 0.7, 0.7, 0.7, 0.4 }; /** * For each lane, decides whether or not to break on the Alignment Line */ private static final boolean[] BREAK_ON_ALIGNMENT_LINE = { false, // A placeholder, allowing lane to line up with index. false, //lane 1 false, //lane 2 true, // lane 3 true, // lane 4 false, // lane 5 true //backup plan }; /** * The motor controller values for moving to the outer works. * As these are initial speeds, keep them low, to go easy on the motors. * Lane is indicated by index. */ static final double[] MOTOR_RATIO_TO_OUTER_WORKS = { 0.0, // nothing. Not used. Arbitrary; makes it work. 0.40,//0.25, // lane 1, should be extra low. 1.0, // lane 2 0.4, // lane 3 0.4, // lane 4 0.4, // lane 5 0.4 //backup plan }; /** * "Speeds" at which to drive from the Outer Works to the Alignment * Line. */ static final double[] MOTOR_RATIO_TO_A_LINE = { 0.0, //PLACEHOLDER 0.4, //lane 1 0.6, //lane 2 0.4, //lane 3 0.4, //lane 4 0.6, //lane 5 0.0 //backup plan }; /** * Distances to rotate upon reaching alignment line. * Lane is indicated by index. * Set to Zero for 1, 2, and 5. */ static final double[] ROTATE_ON_ALIGNMENT_LINE_DISTANCE = { 0.0, // nothing. Not used. Arbitrary; makes it work. 0.0, // lane 1 (not neccesary) 0.0, // lane 2 (not neccesary) -20, // lane 3 24.8, // lane 4 0.0, // lane 5 (not neccesary) 0.0 //backup plan }; /** * Distances to drive after reaching alignment tape. * Lane is indicated by index. * 16 inchworms added inevitably, to start from centre of robot. */ static final double[] FORWARDS_FROM_ALIGNMENT_LINE_DISTANCE = { 0.0, // nothing. Not used. Arbitrary; makes it work. 48.57,// lane 1 77.44,//68.0,// lane 2 64.0, // lane 3 66.1,// lane 4 86.5, // lane 5 -169.0 //backup plan }; static final double[] CENTRE_TO_ALIGNMENT_LINE_MOTOR_RATIO = { 0.0, 0.4, 0.4, .25, .25, 0.4, 0.25 //backup plan }; /** * "Speeds" at which to drive from the A-Line to the imaginary line * normal to * the goal. */ static final double[] FORWARDS_FROM_ALIGNMENT_LINE_MOTOR_RATIO = { 0.0, // nothing. A Placeholder. 0.4, //lane 1 0.4, //lane 2 0.3, //lane 3 0.3, //lane 4 0.4, //lane 5 -0.5 //backup plan }; /** * Distances to rotate to face goal. */ static final double[] TURN_TO_FACE_GOAL_DEGREES = { 0.0, // makes it so the indexes line up with the lane -60.0,// lane 1 -60.0,// lane 2 20.0,// lane 3 -24.85,// lane 4 60, // lane 5 -90.0 //backup plan }; /** * Distances to travel once facing the goal. * Not neccesary for lanes 3 and 4; set to zero. * Actually, we may not use this much at all, given that we will * probably just * use the IR to sense the cleets at the bottom of the tower. */ static final double[] DRIVE_UP_TO_GOAL = { 0.0, // nothing. Not used. Arbitrary; makes it work. 65.85,//previously 62.7,// lane 1 18.1,//52.9,// lane 2 0.0,// lane 3 (not neccesary) 0.0,// lane 4 (not neccesary) 12.0, // lane 5 0.0 //backup plan }; /** * "Speeds" at which to drive to the Batter. */ static final double[] DRIVE_UP_TO_GOAL_MOTOR_RATIO = { 0.0, 0.4, 0.4, 0.4, 0.4, 0.4, 0.0 }; /** * Time to delay at A-line. Only used if reversing. */ static final double[] DELAY_IF_REVERSE = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0 }; /** * Distance from Outer Works checkpoint to Alignment Line. * The front of the robot will be touching the Lion. */ private static final double DISTANCE_TO_TAPE = 27.5; /** * Distance to get the front of the robot to the Outer Works. */ private static final double DISTANCE_TO_OUTER_WORKS = 22.75; /** * Distance to travel to get over the Outer Works. */ private static final double DISTANCE_OVER_OUTER_WORKS = 98.86; /** * The distance to the central pivot point from the front of the robot. * We will use this so that we may rotate around a desired point at the * end of a * distance. */ private static final double DISTANCE_TO_CENTRE_OF_ROBOT = 16.0; /** * Speed at which to make turns by default. * TODO: figure out a reasonable speed. */ private static final double DEFAULT_TURN_SPEED = 0.4; //previously 0.28 } /** * Always 1.0. Do not change. The code depends on it. * TODO: Actually, we are not currently using this. */ private static final double MAXIMUM_AUTONOMOUS_SPEED = 1.0; /** * The maximum time to wait at the beginning of the match. * Used to scale the ratio given by the potentiometer. */ private static final double MAXIMUM_DELAY = 3.0; /** * Set to true to print out print statements. */ private static final boolean DEBUGGING_DEFAULT = true; /** * Factor by which to scale all distances for testing in our small lab * space. */ public static double labScalingFactor = 1.0; /** * Time to wait after releasing the solenoids before closing them back up. */ private static final double DELAY_TIME_AFTER_SHOOT = 1.0; } // end class
package org.usfirst.frc.team997.robot.subsystems; import edu.wpi.first.wpilibj.Counter; import edu.wpi.first.wpilibj.DigitalInput; import edu.wpi.first.wpilibj.Servo; import edu.wpi.first.wpilibj.VictorSP; import edu.wpi.first.wpilibj.command.Subsystem; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; public class Shooter extends Subsystem { private VictorSP shooterMotor; private Counter shooterCounter; private DigitalInput shooterSensor; private Servo shooterKickerFirst, shooterKickerSecond; public Shooter(int shootSensorPort, int shootMotorPort, int shootServoFirstPort, int shootServoSecondPort, int shootUpSource){ //shooterSensor detects when ball is fully in shooter grasp shooterSensor = new DigitalInput(shootSensorPort); //shooterMotor is the VictorSP that controls the shooter wheels shooterMotor = new VictorSP(shootMotorPort); //shooterServo is the Servo that controls the kicker shooterKickerFirst = new Servo(shootServoFirstPort); shooterKickerSecond = new Servo(shootServoSecondPort); //makes UpSource. the thing shooterCounter = new Counter(); shooterCounter.setUpSource(shootUpSource); //something involving units per time shooterCounter.setDistancePerPulse(1); //shooterCounter counts the rotation of the wheels (using reflective tape) shooterCounter = new Counter(); } private void setKickers(double d) { shooterKickerFirst.set(d); shooterKickerSecond.set(1 - d); } public void retractKicker(){ //moves kicker back to default position (.8) setKickers(.8); } public void kickKicker(){ //kicks out kicker to kicking position (.5) setKickers(.5); } public void speedUp(){ //causes shooterMotor (controlling the shooter wheels) to speed up shooterMotor.set(-.8); } public void slowDown(){ //causes shooterMotor (controlling the shooter wheels) to slow down to stop shooterMotor.set(0); } public void gatherBall(){ //gathers ball as long as the sensor is not activated if (shooterSensor.get()){ shooterMotor.set(0); } else { shooterMotor.set(.45); } } public boolean getshooterSensor() { //returns value of sensor (i'm guessing it's like 0 or 1 to indicate sensed or not?) return shooterSensor.get(); } public void smartDashboard() { SmartDashboard.putNumber("Shooter Rate", shooterCounter.getRate()); SmartDashboard.putNumber("Average Speed of Shooter", shooterCounter.getSamplesToAverage()); SmartDashboard.putNumber("Period", shooterCounter.getPeriod()); } // Put methods for controlling this subsystem // here. Call these from Commands. public void initDefaultCommand() { // Set the default command for a subsystem here. //setDefaultCommand(new MySpecialCommand()); } }
package ca.eandb.jdcp.worker; import java.rmi.RemoteException; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.UUID; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Executor; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import javax.jnlp.UnavailableServiceException; import org.apache.log4j.Logger; import ca.eandb.jdcp.job.TaskDescription; import ca.eandb.jdcp.job.TaskWorker; import ca.eandb.jdcp.remote.JobService; import ca.eandb.util.UnexpectedException; import ca.eandb.util.classloader.ClassLoaderStrategy; import ca.eandb.util.classloader.StrategyClassLoader; import ca.eandb.util.progress.ProgressMonitor; import ca.eandb.util.progress.ProgressMonitorFactory; import ca.eandb.util.rmi.Serialized; /** * A <code>Runnable</code> worker that processes tasks for a * <code>ParallelizableJob</code> from a remote <code>JobServiceMaster<code>. * This class may potentially use multiple threads to process tasks. * @author Brad Kimmel */ public final class ThreadServiceWorker implements Runnable { /** * Initializes the address of the master and the amount of time to idle * when no task is available. * @param masterHost The URL of the master. * @param idleTime The time (in seconds) to idle when no task is * available. * @param maxConcurrentWorkers The maximum number of concurrent worker * threads to allow. * @param executor The <code>Executor</code> to use to process tasks. * @param monitorFactory The <code>ProgressMonitorFactory</code> to use to * create <code>ProgressMonitor</code>s for worker tasks. */ public ThreadServiceWorker(JobServiceFactory serviceFactory, int maxConcurrentWorkers, Executor executor, ProgressMonitorFactory monitorFactory) { assert(maxConcurrentWorkers > 0); this.serviceFactory = serviceFactory; this.executor = executor; this.maxConcurrentWorkers = maxConcurrentWorkers; this.monitorFactory = monitorFactory; } /* (non-Javadoc) * @see java.lang.Runnable#run() */ public synchronized void run() { runThread = Thread.currentThread(); reconnectPending = true; this.initializeWorkers(maxConcurrentWorkers); while (!shutdownPending) { try { while (!Thread.interrupted()) { Worker worker = this.workerQueue.take(); if (reconnectPending) { this.initializeService(); reconnectPending = false; } this.executor.execute(worker); } } catch (InterruptedException e) { /* nothing to do. */ } } runThread = null; } /** * Shuts down the <code>Thread</code> currently processing this worker. */ public void shutdown() { synchronized (runThread) { if (runThread != null && !shutdownPending) { shutdownPending = true; runThread.interrupt(); } } } /** * Schedules a reconnection to the <code>JobService</code>. */ private void reconnect() { reconnectPending = true; } /** * Initializes the worker queue with the specified number of workers. * @param numWorkers The number of workers to create. * @param parentMonitor The <code>ProgressMonitor</code> to use to create * child <code>ProgressMonitor</code>s for each <code>Worker</code>. */ private void initializeWorkers(int numWorkers) { for (int i = 0; i < numWorkers; i++) { String title = String.format("Worker (%d)", i + 1); ProgressMonitor monitor = new ProgressMonitorWrapper(monitorFactory.createProgressMonitor(title)); workerQueue.add(new Worker(monitor)); } } /** * Attempt to initialize a connection to the master service. * @return A value indicating whether the operation succeeded. */ private void initializeService() { this.service = serviceFactory.connect(); } /** * An entry in the <code>TaskWorker</code> cache. * @author Brad Kimmel */ private static class WorkerCacheEntry { /** * Initializes the cache entry. * @param jobId The <code>UUID</code> of the job that the * <code>TaskWorker</code> processes tasks for. */ public WorkerCacheEntry(UUID jobId) { this.jobId = jobId; this.workerGuard.writeLock().lock(); } /** * Returns a value indicating if this <code>WorkerCacheEntry</code> * is to be used for the job with the specified <code>UUID</code>. * @param jobId The job's <code>UUID</code> to test. * @return A value indicating if this <code>WorkerCacheEntry</code> * applies to the specified job. */ public boolean matches(UUID jobId) { return this.jobId.equals(jobId); } /** * Sets the <code>TaskWorker</code> to use. This method may only be * called once. * @param worker The <code>TaskWorker</code> to use for matching * jobs. */ public synchronized void setWorker(TaskWorker worker) { /* Set the worker. */ this.worker = worker; /* Release the lock. */ this.workerGuard.writeLock().unlock(); } /** * Gets the <code>TaskWorker</code> to use to process tasks for the * matching job. This method will wait for <code>setWorker</code> * to be called if it has not yet been called. * @return The <code>TaskWorker</code> to use to process tasks for * the matching job. * @see {@link #setWorker(TaskWorker)}. */ public TaskWorker getWorker() { this.workerGuard.readLock().lock(); TaskWorker worker = this.worker; this.workerGuard.readLock().unlock(); return worker; } /** * The <code>UUID</code> of the job that the <code>TaskWorker</code> * processes tasks for. */ private final UUID jobId; /** * The cached <code>TaskWorker</code>. */ private TaskWorker worker; /** * The <code>ReadWriteLock</code> to use before reading from or writing * to the <code>worker</code> field. */ private final ReadWriteLock workerGuard = new ReentrantReadWriteLock(); } /** * Searches for the <code>WorkerCacheEntry</code> matching the job with the * specified <code>UUID</code>. * @param jobId The <code>UUID</code> of the job whose * <code>WorkerCacheEntry</code> to search for. * @return The <code>WorkerCacheEntry</code> corresponding to the job with * the specified <code>UUID</code>, or <code>null</code> if the * no such entry exists. */ private WorkerCacheEntry getCacheEntry(UUID jobId) { assert(jobId != null); synchronized (this.workerCache) { Iterator<WorkerCacheEntry> i = this.workerCache.iterator(); /* Search for the worker for the specified job. */ while (i.hasNext()) { WorkerCacheEntry entry = i.next(); if (entry.matches(jobId)) { /* Remove the entry and re-insert it at the end of the list. * This will ensure that when an item is removed from the list, * the item that is removed will always be the least recently * used. */ i.remove(); this.workerCache.add(entry); return entry; } } /* cache miss */ return null; } } /** * Removes the specified entry from the task worker cache. * @param entry The <code>WorkerCacheEntry</code> to remove. */ private void removeCacheEntry(WorkerCacheEntry entry) { assert(entry != null); synchronized (this.workerCache) { this.workerCache.remove(entry); } } /** * Removes least recently used entries from the task worker cache until * there are at most <code>this.maxCachedWorkers</code> entries. */ private void removeOldCacheEntries() { synchronized (this.workerCache) { /* If the cache has exceeded capacity, then remove the least * recently used entry. */ assert(this.maxCachedWorkers > 0); while (this.workerCache.size() > this.maxCachedWorkers) { this.workerCache.remove(0); } } } /** * Obtains the task worker to process tasks for the job with the specified * <code>UUID</code>. * @param jobId The <code>UUID</code> of the job to obtain the task worker * for. * @return The <code>TaskWorker</code> to process tasks for the job with * the specified <code>UUID</code>, or <code>null</code> if the job * is invalid or has already been completed. * @throws RemoteException * @throws ClassNotFoundException */ private TaskWorker getTaskWorker(UUID jobId) throws RemoteException, ClassNotFoundException { WorkerCacheEntry entry = null; boolean hit; synchronized (this.workerCache) { /* First try to get the worker from the cache. */ entry = this.getCacheEntry(jobId); hit = (entry != null); /* If there was no matching cache entry, then add a new entry to * the cache. */ if (!hit) { entry = new WorkerCacheEntry(jobId); this.workerCache.add(entry); } } if (hit) { /* We found a cache entry, so get the worker from that entry. */ return entry.getWorker(); } else { /* cache miss */ /* The task worker was not in the cache, so use the service to * obtain the task worker. */ Serialized<TaskWorker> envelope = this.service.getTaskWorker(jobId); ClassLoaderStrategy strategy; try { strategy = new PersistenceCachingJobServiceClassLoaderStrategy(service, jobId); } catch (UnavailableServiceException e) { strategy = new FileCachingJobServiceClassLoaderStrategy(service, jobId, "./worker"); } ClassLoader loader = new StrategyClassLoader(strategy, ThreadServiceWorker.class.getClassLoader()); TaskWorker worker = envelope.deserialize(loader); entry.setWorker(worker); /* If we couldn't get a worker from the service, then don't keep * the cache entry. */ if (worker == null) { this.removeCacheEntry(entry); } /* Clean up the cache. */ this.removeOldCacheEntries(); return worker; } } /** * Used to process tasks in threads. * @author Brad Kimmel */ private class Worker implements Runnable { /** * Initializes the progress monitor to report to. * @param monitor The <code>ProgressMonitor</code> to report * the progress of the task to. */ public Worker(ProgressMonitor monitor) { this.monitor = monitor; } /* (non-Javadoc) * @see java.lang.Runnable#run() */ public void run() { try { this.monitor.notifyIndeterminantProgress(); this.monitor.notifyStatusChanged("Requesting task..."); if (service != null) { TaskDescription taskDesc = service.requestTask(); UUID jobId = taskDesc.getJobId(); if (jobId != null) { this.monitor.notifyStatusChanged("Obtaining task worker..."); TaskWorker worker; try { worker = getTaskWorker(jobId); } catch (ClassNotFoundException e) { service.reportException(jobId, 0, e); worker = null; } if (worker == null) { this.monitor.notifyStatusChanged("Could not obtain worker..."); this.monitor.notifyCancelled(); return; } this.monitor.notifyStatusChanged("Performing task..."); ClassLoader loader = worker.getClass().getClassLoader(); Object results; try { Object task = taskDesc.getTask().deserialize(loader); results = worker.performTask(task, monitor); } catch (Exception e) { service.reportException(jobId, taskDesc.getTaskId(), e); results = null; } this.monitor.notifyStatusChanged("Submitting task results..."); if (results != null) { service.submitTaskResults(jobId, taskDesc.getTaskId(), new Serialized<Object>(results)); } } else { try { int seconds = (Integer) taskDesc.getTask().deserialize(); this.idle(seconds); } catch (ClassNotFoundException e) { throw new UnexpectedException(e); } } this.monitor.notifyComplete(); } } catch (RemoteException e) { logger.error("Could not communicate with master.", e); this.monitor.notifyStatusChanged("Failed to communicate with master."); reconnect(); this.monitor.notifyCancelled(); } finally { workerQueue.add(this); } } /** * Idles for the specified number of seconds. * @param seconds The number of seconds to idle for. */ private void idle(int seconds) { monitor.notifyStatusChanged("Idling..."); for (int i = 0; i < seconds; i++) { if (!monitor.notifyProgress(i, seconds)) { monitor.notifyCancelled(); } this.sleep(); } monitor.notifyProgress(seconds, seconds); monitor.notifyComplete(); } /** * Sleeps for one second. */ private void sleep() { try { Thread.sleep(1000); } catch (InterruptedException e) { logger.warn("Thread was interrupted", e); } } /** * The <code>ProgressMonitor</code> to report to. */ private final ProgressMonitor monitor; } /** * A <code>ProgressMonitor</code> that wraps another to signal cancellation * when the <code>ThreadServiceWorker</code> is shutting down. * @author Brad Kimmel */ private class ProgressMonitorWrapper implements ProgressMonitor { /** The <code>ProgressMonitor</code> to wrap. */ private final ProgressMonitor monitor; /** * Creates a new <code>ProgressMonitorWrapper</code>. * @param monitor The <code>ProgressMonitor</code> to wrap. */ public ProgressMonitorWrapper(ProgressMonitor monitor) { this.monitor = monitor; } /* (non-Javadoc) * @see ca.eandb.util.progress.ProgressMonitor#isCancelPending() */ @Override public boolean isCancelPending() { return shutdownPending; } /* (non-Javadoc) * @see ca.eandb.util.progress.ProgressMonitor#notifyCancelled() */ @Override public void notifyCancelled() { /* ignore. */ } /* (non-Javadoc) * @see ca.eandb.util.progress.ProgressMonitor#notifyComplete() */ @Override public void notifyComplete() { /* ignore. */ } /* (non-Javadoc) * @see ca.eandb.util.progress.ProgressMonitor#notifyIndeterminantProgress() */ @Override public boolean notifyIndeterminantProgress() { monitor.notifyIndeterminantProgress(); return !shutdownPending; } /* (non-Javadoc) * @see ca.eandb.util.progress.ProgressMonitor#notifyProgress(int, int) */ @Override public boolean notifyProgress(int value, int maximum) { monitor.notifyProgress(value, maximum); return !shutdownPending; } /* (non-Javadoc) * @see ca.eandb.util.progress.ProgressMonitor#notifyProgress(double) */ @Override public boolean notifyProgress(double progress) { monitor.notifyProgress(progress); return !shutdownPending; } /* (non-Javadoc) * @see ca.eandb.util.progress.ProgressMonitor#notifyStatusChanged(java.lang.String) */ @Override public void notifyStatusChanged(String status) { monitor.notifyStatusChanged(status); } } /** The <code>Logger</code> to write log messages to. */ private static final Logger logger = Logger.getLogger(ThreadServiceWorker.class); /** * The <code>JobServiceFactory</code> to use to connect to a * <code>JobService</code>. */ private final JobServiceFactory serviceFactory; /** The <code>Executor</code> to use to process tasks. */ private final Executor executor; /** * The <code>ProgressMonitorFactory</code> to use to create * <code>ProgressMonitor</code>s for worker tasks. */ private final ProgressMonitorFactory monitorFactory; /** * The <code>JobService</code> to obtain tasks from and submit * results to. */ private JobService service = null; /** * The <code>Thread</code> that is currently executing the {@link #run()} * method. */ private Thread runThread = null; /** A value indicating if thread is about to be shut down. */ private boolean shutdownPending = false; /** A value indicating if the worker should reconnect. */ private boolean reconnectPending; /** The maximum number of workers that may be executing simultaneously. */ private final int maxConcurrentWorkers; /** A queue containing the available workers. */ private final BlockingQueue<Worker> workerQueue = new LinkedBlockingQueue<Worker>(); /** * A list of recently used <code>TaskWorker</code>s and their associated * job's <code>UUID</code>s, in order from least recently used to most * recently used. */ private final List<WorkerCacheEntry> workerCache = new LinkedList<WorkerCacheEntry>(); /** * The maximum number of <code>TaskWorker</code>s to retain in the cache. */ private final int maxCachedWorkers = 5; }
package ca.kanoa.RodsTwo.Helpers; import ca.kanoa.RodsTwo.Objects.Rod; import ca.kanoa.RodsTwo.RodsTwo; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import java.io.File; import java.util.Arrays; public class CommandExecutor implements org.bukkit.command.CommandExecutor { private RodsTwo plugin; public CommandExecutor(RodsTwo plugin){ this.plugin = plugin; } public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { boolean isPlayer = sender instanceof Player; Player player = isPlayer ? (Player) sender : null; if(args.length > 0 && args[0].equalsIgnoreCase("spawn")){ if(args.length == 2 || args.length == 3){ if(isPlayer){ Rod rod = null; for(Rod r : plugin.getRods()) if(r.getName().equalsIgnoreCase(args[1])) rod = r; if(rod == null){ player.sendMessage("Couldn't find a rod with that name."); return true; } else{ int x = 1; try{ x = Integer.parseInt(args[2]); } catch(Exception e){ //Do nothing } ItemStack rodStack = new ItemStack(Material.getMaterial(rod.getRodID()), x); ItemMeta rodMeta = rodStack.getItemMeta(); rodMeta.setLore(Arrays.asList(new String[]{rod.getName()})); rodMeta.setDisplayName(rod.getName() + " Rod"); rodStack.setItemMeta(rodMeta); player.getInventory().addItem(rodStack); player.sendMessage(ChatColor.LIGHT_PURPLE + "Spawned a(n) " + rodStack.getItemMeta().getDisplayName()); return true; } } else{ sender.sendMessage("Player only command."); return true; } } else{ sender.sendMessage(ChatColor.RED + "Invalid arguments!"); return true; } } else if(args.length > 0 && args[0].equalsIgnoreCase("list")){ if(args.length == 1){ sender.sendMessage("" + ChatColor.DARK_PURPLE + ChatColor.BOLD + "Listing all loaded rods"); for(Rod rod : plugin.getRods()) sender.sendMessage(ChatColor.LIGHT_PURPLE + "Name: " + ChatColor.RED + rod.getName() + ChatColor.LIGHT_PURPLE + ", Cost: " + ChatColor.WHITE + rod.getCost() + ChatColor.LIGHT_PURPLE + ", ItemID: " + ChatColor.GREEN + rod.getRodID()); } else sender.sendMessage(ChatColor.RED + "Too many arguments!"); return true; } else if(args.length > 0 && args[0].equalsIgnoreCase("reload")){ if(args.length == 1){ sender.sendMessage(ChatColor.AQUA + "Reloading configuration..."); plugin.rodConfig = YamlConfiguration.loadConfiguration(new File(plugin.getDataFolder(), "rods.yml")); Utils.setRodVars(); plugin.getServer().resetRecipes(); Utils.addRecipes(); sender.sendMessage(ChatColor.AQUA + "Reload complete!"); } else sender.sendMessage(ChatColor.RED + "Too many arguments!"); return true; } else if(args.length > 0 && args[0].equalsIgnoreCase("overwrite")){ if(args.length == 1){ sender.sendMessage(ChatColor.AQUA + "Overwriting configuration..."); Utils.makeConfig(true); plugin.rodConfig = YamlConfiguration.loadConfiguration(new File(plugin.getDataFolder(), "rods.yml")); Utils.setRodVars(); plugin.getServer().resetRecipes(); Utils.addRecipes(); sender.sendMessage(ChatColor.AQUA + "Overwrite complete!"); } else sender.sendMessage(ChatColor.RED + "Too many arguments!"); return true; } return false; } }
package ca.mcgill.mcb.pcingola.bigDataScript; import ca.mcgill.mcb.pcingola.bigDataScript.util.Gpr; public class Zzz { public static void main(String[] args) throws Exception { Gpr.debug("PATH: " + System.getenv("PATH")); } }
package ch.deletescape.jterm.commandcontexts; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import ch.deletescape.jterm.CommandUtils; import ch.deletescape.jterm.JTerm; import ch.deletescape.jterm.Util; import ch.deletescape.jterm.io.Printer; public class Env implements CommandContext { private String getEnv(String cmd) { StringBuilder output = new StringBuilder(); String env = cmd; if (!"".equals(env)) { output.append(System.getenv(env) + "\n"); } else { System.getenv().forEach((s1, s2) -> output.append(s1 + "=" + s2 + "\n")); } Printer.out.println(output.toString()); return output.toString(); } private String exec(String cmd) throws IOException { Process proc = Runtime.getRuntime().exec(cmd); InputStream in = proc.getInputStream(); return Util.copyStream(in, Printer.out.getPrintStream()); } private Object exit() { Printer.out.println("Exiting"); JTerm.exit(); return null; } public static boolean run(String cmd) throws IOException { try { Path path = JTerm.getCurrPath().resolve(Util.makePathString(cmd)).toRealPath(); if (Files.isDirectory(path)) { Printer.err.println(path + " is a directory!"); } else { Path bak = JTerm.getCurrPath(); JTerm.setCurrPath(path.getParent()); try (BufferedReader in = Files.newBufferedReader(path)) { in.lines().forEach(CommandUtils::evaluateCommand); } JTerm.setCurrPath(bak); return true; } } catch (NoSuchFileException e) { Printer.out .println("Error: Path \"" + JTerm.getCurrPath().resolve(Util.makePathString(cmd)) + "\" couldn't be found!"); } return false; } private String os(String arg) { String name = System.getProperty("os.name"); String arch = System.getProperty("os.arch"); String version = System.getProperty("os.version"); StringBuilder sb = new StringBuilder(); switch (arg) { case "": sb.append("Name . . . . . : "); sb.append(name); sb.append('\n'); sb.append("Architecture . : "); sb.append(arch); sb.append('\n'); sb.append("Version. . . . : "); sb.append(version); sb.append('\n'); break; case "-n": case "--name": sb.append(name); break; case "-v": case "--version": sb.append(version); break; case "-a": case "--arch": sb.append(arch); break; default: String errTXT = "Unknown option: " + arg; Printer.err.println(errTXT); case "-h": case "--help": sb.append("Usage: os [-[nvah]]"); sb.append("\n\t-n / --name . . . : Prints os name"); sb.append("\n\t-a / --arch . . . : Prints os architecture"); sb.append("\n\t-v / --version. . : Prints os version"); sb.append("\n\t-h / --help . . . : Prints this usage information\n"); } Printer.out.println(sb.toString()); return sb.toString(); } private String alias(String cmd) { String str = cmd.trim(); String alias = str.split("=")[0].trim().replaceAll(" ", "_"); String original = str.split("=")[1].trim(); if (CommandUtils.COMMAND_LISTENERS.containsKey(alias)) { String errTxt = "Can't set alias \"" + alias + "\", a command with that name already exists!"; Printer.err.println(errTxt); return errTxt; } String successTxt = "Setting alias \"" + alias + "\" for command \"" + original + "\""; Printer.out.println(successTxt); CommandUtils.addListener(alias, (o) -> CommandUtils.evaluateCommand((original + " " + o).trim())); return successTxt; } @Override public void init() { CommandUtils.addListener("getEnv", this::getEnv); CommandUtils.addListener("exec", this::exec); CommandUtils.addListener("exit", o -> exit()); CommandUtils.addListener("bye", o -> exit()); CommandUtils.addListener("run", Env::run); CommandUtils.addListener("os", this::os); CommandUtils.addListener("alias", this::alias); } }
package algorithms.imageProcessing; import algorithms.compGeometry.LinesAndAngles; import algorithms.util.PairIntArray; import java.util.Arrays; /** * * @author nichole */ public class PartialShapeMatcher { /** * in sampling the boundaries of the shapes, one can * choose to use the same number for each (which can result * in very different spacings for different sized curves) * or one can choose a set distance between sampling * points. * dp is the set distance between sampling points. The authors use 3 as an example. */ protected int dp = 5; public void overrideSamplingDistance(int d) { this.dp = d; } /** * NOT READY FOR USE. * * the spacings used are equidistant, so note that any scale factor between p and q has to be applied to the data before using this method. * this method will return a score when completed. * * @param p * @param q */ public void match(PairIntArray p, PairIntArray q) { if (p.getN() > q.getN()) { throw new IllegalArgumentException( "q must be <= p in length."); } float[][][] md = createDifferenceMatrices(p, q); /* the matrices in md can be analyzed for best global solution and separately for best local solution. This method will return results for a local solution to create the point correspondence list. Note that the local best could be two different kinds of models, so might write two different methods for the results. (1) the assumption of same object but with some amount of occlusion, hence gaps in correspondence. (2) the assumption of same object but with some parts being differently oriented, for an example, the scissors opened versus closed. */ //printing out results for md[0] and md[-3] and +3 // to look at known test data while checking logic //print("md[0]", md[0]); //print("md[-3]", md[md.length - 1]); printBlocks("md[0]", md[0]); printBlocks("md[3]", md[3]); printBlocks("md[-3]", md[md.length - 1]); } protected float[][][] createDifferenceMatrices( PairIntArray p, PairIntArray q) { if (p.getN() > q.getN()) { throw new IllegalArgumentException( "q must be <= p in length."); } /* | a_1_1...a_1_N | | a_2_1...a_2_N | | a_N_1...a_N_N | elements on the diagonal are zero to shift to different first point as reference, can shift up k-1 rows and left k-1 columns. */ float[][] a1 = createDescriptorMatrix(p); float[][] a2 = createDescriptorMatrix(q); int n1 = a1.length; int n2 = a2.length; float[][][] md = new float[n2][][]; float[][] prevA2Shifted = null; for (int i = 0; i < n2; ++i) { float[][] shifted2; if (prevA2Shifted == null) { shifted2 = copy(a2); } else { // shifts by 1 to left and down by 1 rotate(prevA2Shifted); shifted2 = prevA2Shifted; } //M_D^n = A_1(1:M,1:M) - A_2(n:n+M-1,n:n+M-1) md[i] = subtract(a1, shifted2); prevA2Shifted = shifted2; } for (int i = 0; i < n2; ++i) { float[][] mdI = md[i]; // I(x,y)=i(x,y)+I(x-1,y)+I(x,y-1)-I(x-1,y-1)) for (int x = 0; x < mdI.length; ++x) { for (int y = 0; y < mdI[x].length; ++y) { if (x > 0 && y > 0) { mdI[x][y] += (mdI[x-1][y] + mdI[x][y-1] - mdI[x-1][y-1]); } else if (x > 0) { mdI[x][y] += mdI[x-1][y]; } else if (y > 0) { mdI[x][y] += mdI[x][y-1]; } } } } return md; } protected float[][] createDescriptorMatrix(PairIntArray p) { int n = (int)Math.ceil((double)p.getN()/dp); float[][] a = new float[n][]; for (int i = 0; i < n; ++i) { a[i] = new float[n]; } /* P1 Pmid P2 */ System.out.println("n=" + n); for (int i1 = 0; i1 < n; ++i1) { int start = i1 + 1 + dp; for (int ii = start; ii < (start + n - 1 - dp); ++ii) { int i2 = ii; int imid = i2 - dp; // wrap around if (imid > (n - 1)) { imid -= n; } // wrap around if (i2 > (n - 1)) { i2 -= n; } //System.out.println("i1=" + i1 + " imid=" + imid + " i2=" + i2); double angleA = LinesAndAngles.calcClockwiseAngle( p.getX(i1), p.getY(i1), p.getX(i2), p.getY(i2), p.getX(imid), p.getY(imid) ); /* String str = String.format( "[%d](%d,%d) [%d](%d,%d) [%d](%d,%d) a=%.4f", i1, p.getX(i1), p.getY(i1), i2, p.getX(i2), p.getY(i2), imid, p.getX(imid), p.getY(imid), (float) angleA * 180. / Math.PI); System.out.println(str); */ a[i1][i2] = (float)angleA; } } return a; } protected int distanceSqEucl(int x1, int y1, int x2, int y2) { int diffX = x1 - x2; int diffY = y1 - y2; return (diffX * diffX + diffY * diffY); } private float[][] copy(float[][] a) { float[][] a2 = new float[a.length][]; for (int i = 0; i < a2.length; ++i) { a2[i] = Arrays.copyOf(a[i], a[i].length); } return a2; } private void rotate(float[][] prevShifted) { // shift x left by 1 first for (int y = 0; y < prevShifted[0].length; ++y) { float tmp0 = prevShifted[0][y]; for (int x = 0; x < (prevShifted.length- 1); ++x){ prevShifted[x][y] = prevShifted[x + 1][y]; } prevShifted[prevShifted.length - 1][y] = tmp0; } // shift y down by 1 for (int x = 0; x < prevShifted.length; ++x) { float tmp0 = prevShifted[x][0]; for (int y = 0; y < (prevShifted[x].length - 1); ++y){ prevShifted[x][y] = prevShifted[x][y + 1]; } prevShifted[x][prevShifted[x].length - 1] = tmp0; } } private float[][] subtract(float[][] a1, float[][] a2) { assert(a1.length <= a2.length); assert(a1[0].length <= a2[0].length); float[][] output = new float[a1.length][]; for (int i = 0; i < a1.length; ++i) { output[i] = new float[a1[i].length]; for (int j = 0; j < a1[i].length; ++j) { output[i][j] = a1[i][j] - a2[i][j]; } } return output; } private void print(String label, float[][] a) { StringBuilder sb = new StringBuilder(label); sb.append("\n"); for (int j = 0; j < a[0].length; ++j) { sb.append(String.format("row: %3d", j)); for (int i = 0; i < a.length; ++i) { sb.append(String.format(" %.4f,", a[i][j])); } System.out.println(sb.toString()); sb.delete(0, sb.length()); } } private void printBlocks(String label, float[][] a) { System.out.println(label); /* Find quadratic sub-areas within reference and query descriptor matrices starting at main diagonal which are most similar. */ // try a set block size int r = 2; double c = (1./(r*r)); double prev = Double.MAX_VALUE; for (int i = r; i < a.length; i+=r) { double d; if ((i - r) > -1) { d = c * (a[i][i] - a[i - r][i - r] + a[i - r][i] + a[i][i - r]); System.out.println( String.format( " [%d,%d] %.4f, %.4f, %.4f, %.4f => %.4f", i, i, -a[i - r][i - r], a[i - r][i], a[i][i - r], a[i][i], d)); } else { d = c * a[i][i]; } /* d = a[i][i]; if (prev < Double.MAX_VALUE) { d -= prev; } prev = d; System.out.println( String.format(" [%d,%d]%.4f,", i, i, d)); */ } } }
package co.epitre.aelf_lectures; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.GregorianCalendar; import java.util.List; import android.accounts.Account; import android.accounts.AccountManager; import android.annotation.SuppressLint; import android.app.UiModeManager; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.os.AsyncTask; import android.os.Bundle; import android.provider.Settings.SettingNotFoundException; import android.support.v4.view.ViewPager; import android.support.v4.view.WindowCompat; import android.util.Log; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.ArrayAdapter; import android.widget.ProgressBar; import android.widget.RelativeLayout; import co.epitre.aelf_lectures.data.LectureItem; import co.epitre.aelf_lectures.data.LecturesController; import co.epitre.aelf_lectures.data.LecturesController.WHAT; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; class WhatWhen { public LecturesController.WHAT what; public GregorianCalendar when; public int position; public boolean useCache = true; } public class LecturesActivity extends SherlockFragmentActivity implements DatePickerFragment.CalendarDialogListener, ActionBar.OnNavigationListener { public static final String TAG = "AELFLecturesActivity"; public static final String PREFS_NAME = "aelf-prefs"; public static final long DATE_TODAY = 0; /** * The {@link android.support.v4.view.PagerAdapter} that will provide * fragments for each of the sections. We use a * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which * will keep every loaded fragment in memory. If this becomes too memory * intensive, it may be best to switch to a * {@link android.support.v4.app.FragmentStatePagerAdapter}. */ LecturesController lecturesCtrl = null; SectionsPagerAdapterFragment mSectionsPagerAdapter; WhatWhen whatwhen; Menu mMenu; List<LectureItem> networkError = new ArrayList<LectureItem>(1); /** * Sync account related vars */ // The authority for the sync adapter's content provider public static final String AUTHORITY = "co.epitre.aelf"; // DANGER: must be the same as the provider's in the manifest // An account type, in the form of a domain name public static final String ACCOUNT_TYPE = "epitre.co"; // The account name public static final String ACCOUNT = "www.aelf.org"; // Sync interval in s. ~ 1 Day public static final long SYNC_INTERVAL = 60L*60L*22L; // Instance fields Account mAccount; // action bar protected ActionBar actionBar; /** * The {@link ViewPager} that will host the section contents. */ ViewPager mViewPager; // TODO: detect first launch + trigger initial sync @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); int currentVersion, savedVersion; // current version PackageInfo packageInfo; try { packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0); } catch (NameNotFoundException e) { throw new RuntimeException("Could not determine current version"); } currentVersion = packageInfo.versionCode; // load saved version, if any SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); savedVersion = settings.getInt("version", -1); // upgrade logic, primitive at the moment... if(savedVersion != currentVersion) { if(savedVersion < 11) { // delete cache DB: needs to force regenerate getApplicationContext().deleteDatabase("aelf_cache.db"); } // update saved version SharedPreferences.Editor editor = settings.edit(); editor.putInt("version", currentVersion); editor.commit(); } // create dummy account for our background sync engine mAccount = CreateSyncAccount(this); // init the lecture controller lecturesCtrl = LecturesController.getInstance(this); // need restore state ? whatwhen = new WhatWhen(); if(savedInstanceState != null) { // Restore saved instance state. Especially useful on screen rotate on older phones whatwhen.what = WHAT.values()[savedInstanceState.getInt("what")]; whatwhen.position = savedInstanceState.getInt("position"); long timestamp = savedInstanceState.getLong("when"); whatwhen.when = new GregorianCalendar(); if(timestamp != DATE_TODAY) { whatwhen.when.setTimeInMillis(timestamp); } } else { // load the "lectures" for today whatwhen.when = new GregorianCalendar(); whatwhen.what = WHAT.MESSE; whatwhen.position = 0; // 1st lecture of the office } // error handler networkError.add(new LectureItem("Erreur Réseau", "<p>Connexion au serveur AELF impossible<br />Veuillez ré-essayer plus tard.</p>", "erreur")); // TODO: explore possible overlay action bar lifecycle //requestWindowFeature(WindowCompat.FEATURE_ACTION_BAR_OVERLAY); // some UI. Most UI init are done in the prev async task setContentView(R.layout.activity_lectures); // prevent phone sleep findViewById(android.R.id.content).setKeepScreenOn(true); // Spinner actionBar = getSupportActionBar(); Context context = actionBar.getThemedContext(); ArrayAdapter<CharSequence> list = ArrayAdapter.createFromResource(context, R.array.spinner, R.layout.sherlock_spinner_item); list.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item); actionBar.setDisplayShowTitleEnabled(false); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); actionBar.setListNavigationCallbacks(list, this); // restore active navigation item actionBar.setSelectedNavigationItem(whatwhen.what.getPosition()); // finally, turn on periodic lectures caching if(mAccount != null) { ContentResolver.setIsSyncable(mAccount, AUTHORITY, 1); ContentResolver.setSyncAutomatically(mAccount, AUTHORITY, true); ContentResolver.addPeriodicSync(mAccount, AUTHORITY, new Bundle(1), SYNC_INTERVAL); } } @SuppressLint("NewApi") public void prepare_fullscreen() { // Hide status (top) bar. Navigation bar (> 4.0) still visible. getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); if (android.os.Build.VERSION.SDK_INT < 14) // 4.0 min return; // Android 4.0+: make navigation bar 'discret' ('dots' instead of icons) int uiOptions = View.SYSTEM_UI_FLAG_LOW_PROFILE; // for android.os.Build.VERSION.SDK_INT >= 16 (4.1) // we should explore // - navbar workflow. --> hide with View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // - actionbar workflow. --> hide with View.SYSTEM_UI_FLAG_LAYOUT_STABLE // BUT: navbar shows automatically and dont hide :( // actionbar does not show. (actionBar.hide/show();) // an idea is to deal with scroll events on the UI. // Android 4.4+: hide navigation bar, make it accessible via edge scroll if (android.os.Build.VERSION.SDK_INT >= 19) { uiOptions |= View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION; } // apply settings View decorView = getWindow().getDecorView(); decorView.setSystemUiVisibility(uiOptions); // TODO: explore artificially reducing luminosity /*try { int brightness = android.provider.Settings.System.getInt( getContentResolver(), android.provider.Settings.System.SCREEN_BRIGHTNESS); Log.v(TAG, "brightness="+brightness); } catch (SettingNotFoundException e) { // don't care }*/ } @Override public void onWindowFocusChanged(boolean hasFocus) { // manage application's intrusiveness for different Android versions super.onWindowFocusChanged(hasFocus); if(hasFocus) prepare_fullscreen(); } private boolean isSameDay(GregorianCalendar when, GregorianCalendar other){ return (when.get(GregorianCalendar.ERA) == other.get(GregorianCalendar.ERA) && when.get(GregorianCalendar.YEAR) == other.get(GregorianCalendar.YEAR) && when.get(GregorianCalendar.DAY_OF_YEAR) == other.get(GregorianCalendar.DAY_OF_YEAR)); } private boolean isToday(GregorianCalendar when){ GregorianCalendar today = new GregorianCalendar(); return isSameDay(when, today); } @Override protected void onSaveInstanceState(Bundle outState) { // Save instance state. Especially useful on screen rotate on older phones // - what --> mass, tierce, ... ? (id) // - when --> date (timestamp) // - position --> active tab (id) super.onSaveInstanceState(outState); if(outState == null) return; int position = 0; // first slide by default int what = 0; // "Messe" by default long when = DATE_TODAY; if(whatwhen != null) { if(whatwhen.what != null) what = whatwhen.what.getPosition(); if(mViewPager != null) position = mViewPager.getCurrentItem(); if(whatwhen.when != null && !isToday(whatwhen.when)) { when = whatwhen.when.getTimeInMillis(); } } outState.putInt("what", what); outState.putInt("position", position); outState.putLong("when", when); } public boolean onAbout(MenuItem item) { AboutDialogFragment aboutDialog = new AboutDialogFragment(); aboutDialog.show(getSupportFragmentManager(), "aboutDialog"); return true; } public boolean onSyncPref(MenuItem item) { Intent intent = new Intent(this, SyncPrefActivity.class); startActivity(intent); return true; } public boolean onSyncDo(MenuItem item) { // Pass the settings flags by inserting them in a bundle Bundle settingsBundle = new Bundle(); settingsBundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true); settingsBundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true); // start sync ContentResolver.requestSync(mAccount, AUTHORITY, settingsBundle); // done return true; } public boolean onRefresh(MenuItem item) { whatwhen.useCache = false; whatwhen.position = mViewPager.getCurrentItem(); new DownloadXmlTask().execute(whatwhen); return true; } public boolean onCalendar(MenuItem item) { Bundle args = new Bundle(); args.putLong("time", whatwhen.when.getTimeInMillis()); DatePickerFragment calendarDialog = new DatePickerFragment(); calendarDialog.setArguments(args); calendarDialog.show(getSupportFragmentManager(), "datePicker"); return true; } @SuppressLint("SimpleDateFormat") // I know but currently French only public void onCalendarDialogPicked(int year, int month, int day) { GregorianCalendar date = new GregorianCalendar(year, month, day); // do not refresh if date did not change to avoid unnecessary flickering if(isSameDay(whatwhen.when, date)) return; whatwhen.when = date; whatwhen.position = mViewPager.getCurrentItem(); // keep on the same reading on date change new DownloadXmlTask().execute(whatwhen); // Update to date button with "this.date" MenuItem calendarItem = mMenu.findItem(R.id.action_calendar); SimpleDateFormat actionDateFormat = new SimpleDateFormat("E d MMM y"); //TODO: move str to cst calendarItem.setTitle(actionDateFormat.format(whatwhen.when.getTime())); } @Override public boolean onNavigationItemSelected(int position, long itemId) { // Are we actually *changing* ? --> maybe not if coming from state reload if(whatwhen.what != LecturesController.WHAT.values()[position]) { whatwhen.what = LecturesController.WHAT.values()[position]; whatwhen.position = 0; // on what change, move to 1st } new DownloadXmlTask().execute(whatwhen); return true; } @SuppressLint("SimpleDateFormat") // I know but currently French only @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar getSupportMenuInflater().inflate(R.menu.lectures, menu); // Update to date button with "this.date" MenuItem calendarItem = menu.findItem(R.id.action_calendar); SimpleDateFormat actionDateFormat = new SimpleDateFormat("E d MMM y"); //TODO: move str to cst calendarItem.setTitle(actionDateFormat.format(whatwhen.when.getTime())); mMenu = menu; return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_about: return onAbout(item); case R.id.action_sync_settings: return onSyncPref(item); case R.id.action_sync_do: return onSyncDo(item); case R.id.action_refresh: return onRefresh(item); case R.id.action_calendar: return onCalendar(item); } return true; } /** * Create a new dummy account for the sync adapter * * @param context The application context */ public static Account CreateSyncAccount(Context context) { // Create the account type and default account Account newAccount = new Account(ACCOUNT, ACCOUNT_TYPE); // Get an instance of the Android account manager AccountManager accountManager = (AccountManager) context.getSystemService(ACCOUNT_SERVICE); /* * Add the account and account type, no password or user data * If successful, return the Account object, otherwise report an error. */ if (accountManager.addAccountExplicitly(newAccount, null, null)) { return newAccount; } else { return accountManager.getAccountsByType(ACCOUNT_TYPE)[0]; } } protected void setLoading(final boolean loading) { final RelativeLayout loadingOverlay = (RelativeLayout)findViewById(R.id.loadingOverlay); final ProgressBar loadingIndicator = (ProgressBar)findViewById(R.id.loadingIndicator); loadingOverlay.post(new Runnable() { public void run() { if(loading) { loadingIndicator.getIndeterminateDrawable().setColorFilter(getResources().getColor(R.color.sepia_fg), android.graphics.PorterDuff.Mode.MULTIPLY); loadingOverlay.setVisibility(View.VISIBLE); } else { loadingOverlay.setVisibility(View.INVISIBLE); } } }); } // Async loader private class DownloadXmlTask extends AsyncTask<WhatWhen, Void, List<LectureItem>> { @Override protected List<LectureItem> doInBackground(WhatWhen... whatwhen) { WhatWhen ww = whatwhen[0]; try { if(ww.useCache) { // attempt to load from cache: skip loading indicator (avoids flickering) List<LectureItem> lectures = lecturesCtrl.getLecturesFromCache(ww.what, ww.when); if(lectures != null) return lectures; } // attempts to load from network, with loading indicator setLoading(true); return lecturesCtrl.getLecturesFromNetwork(ww.what, ww.when); } catch (IOException e) { Log.e(TAG, "I/O error while loading. AELF servers down ?"); setLoading(false); return null; } finally { // "useCache=false" is "fire and forget" ww.useCache = true; } } @Override protected void onPostExecute(final List<LectureItem> lectures) { // Fragment e{4a335af8} is not currently in the FragmentManager runOnUiThread(new Runnable() { public void run() { List<LectureItem> pager_data; if(lectures != null) { pager_data = lectures; } else { pager_data = networkError; } // Create the adapter that will return a fragment for each of the three // primary sections of the app. mSectionsPagerAdapter = new SectionsPagerAdapterFragment(getSupportFragmentManager(), pager_data); // Set up the ViewPager with the sections adapter. mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mSectionsPagerAdapter); mViewPager.setCurrentItem(whatwhen.position); setLoading(false); } }); } } }
package co.epitre.aelf_lectures; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.GregorianCalendar; import java.util.List; import android.accounts.Account; import android.accounts.AccountManager; import android.annotation.SuppressLint; import android.app.UiModeManager; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.os.AsyncTask; import android.os.Bundle; import android.provider.Settings.SettingNotFoundException; import android.support.v4.view.ViewPager; import android.support.v4.view.WindowCompat; import android.util.Log; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.ArrayAdapter; import android.widget.ProgressBar; import android.widget.RelativeLayout; import co.epitre.aelf_lectures.data.LectureItem; import co.epitre.aelf_lectures.data.LecturesController; import co.epitre.aelf_lectures.data.LecturesController.WHAT; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; class WhatWhen { public LecturesController.WHAT what; public GregorianCalendar when; public int position; public boolean useCache = true; } public class LecturesActivity extends SherlockFragmentActivity implements DatePickerFragment.CalendarDialogListener, ActionBar.OnNavigationListener { public static final String TAG = "AELFLecturesActivity"; public static final String PREFS_NAME = "aelf-prefs"; public static final long DATE_TODAY = 0; /** * The {@link android.support.v4.view.PagerAdapter} that will provide * fragments for each of the sections. We use a * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which * will keep every loaded fragment in memory. If this becomes too memory * intensive, it may be best to switch to a * {@link android.support.v4.app.FragmentStatePagerAdapter}. */ LecturesController lecturesCtrl = null; WhatWhen whatwhen; Menu mMenu; List<LectureItem> networkError = new ArrayList<LectureItem>(1); /** * Sync account related vars */ // The authority for the sync adapter's content provider public static final String AUTHORITY = "co.epitre.aelf"; // DANGER: must be the same as the provider's in the manifest // An account type, in the form of a domain name public static final String ACCOUNT_TYPE = "epitre.co"; // The account name public static final String ACCOUNT = "www.aelf.org"; // Sync interval in s. ~ 1 Day public static final long SYNC_INTERVAL = 60L*60L*22L; // Instance fields Account mAccount; // action bar protected ActionBar actionBar; /** * The {@link ViewPager} that will host the section contents. */ ViewPager mViewPager; // TODO: detect first launch + trigger initial sync @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); int currentVersion, savedVersion; // current version PackageInfo packageInfo; try { packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0); } catch (NameNotFoundException e) { throw new RuntimeException("Could not determine current version"); } currentVersion = packageInfo.versionCode; // load saved version, if any SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); savedVersion = settings.getInt("version", -1); // upgrade logic, primitive at the moment... if(savedVersion != currentVersion) { if(savedVersion < 11) { // delete cache DB: needs to force regenerate getApplicationContext().deleteDatabase("aelf_cache.db"); } // update saved version SharedPreferences.Editor editor = settings.edit(); editor.putInt("version", currentVersion); editor.commit(); } // create dummy account for our background sync engine mAccount = CreateSyncAccount(this); // init the lecture controller lecturesCtrl = LecturesController.getInstance(this); // need restore state ? whatwhen = new WhatWhen(); if(savedInstanceState != null) { // Restore saved instance state. Especially useful on screen rotate on older phones whatwhen.what = WHAT.values()[savedInstanceState.getInt("what")]; whatwhen.position = savedInstanceState.getInt("position"); long timestamp = savedInstanceState.getLong("when"); whatwhen.when = new GregorianCalendar(); if(timestamp != DATE_TODAY) { whatwhen.when.setTimeInMillis(timestamp); } } else { // load the "lectures" for today whatwhen.when = new GregorianCalendar(); whatwhen.what = WHAT.MESSE; whatwhen.position = 0; // 1st lecture of the office } // error handler networkError.add(new LectureItem("Erreur Réseau", "<p>Connexion au serveur AELF impossible<br />Veuillez ré-essayer plus tard.</p>", "erreur")); // TODO: explore possible overlay action bar lifecycle //requestWindowFeature(WindowCompat.FEATURE_ACTION_BAR_OVERLAY); // some UI. Most UI init are done in the prev async task setContentView(R.layout.activity_lectures); // prevent phone sleep findViewById(android.R.id.content).setKeepScreenOn(true); // Spinner actionBar = getSupportActionBar(); Context context = actionBar.getThemedContext(); ArrayAdapter<CharSequence> list = ArrayAdapter.createFromResource(context, R.array.spinner, R.layout.sherlock_spinner_item); list.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item); actionBar.setDisplayShowTitleEnabled(false); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); actionBar.setListNavigationCallbacks(list, this); // restore active navigation item actionBar.setSelectedNavigationItem(whatwhen.what.getPosition()); // finally, turn on periodic lectures caching if(mAccount != null) { ContentResolver.setIsSyncable(mAccount, AUTHORITY, 1); ContentResolver.setSyncAutomatically(mAccount, AUTHORITY, true); ContentResolver.addPeriodicSync(mAccount, AUTHORITY, new Bundle(1), SYNC_INTERVAL); } } @SuppressLint("NewApi") public void prepare_fullscreen() { // Hide status (top) bar. Navigation bar (> 4.0) still visible. getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); if (android.os.Build.VERSION.SDK_INT < 14) // 4.0 min return; // Android 4.0+: make navigation bar 'discret' ('dots' instead of icons) int uiOptions = View.SYSTEM_UI_FLAG_LOW_PROFILE; // for android.os.Build.VERSION.SDK_INT >= 16 (4.1) // we should explore // - navbar workflow. --> hide with View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // - actionbar workflow. --> hide with View.SYSTEM_UI_FLAG_LAYOUT_STABLE // BUT: navbar shows automatically and dont hide :( // actionbar does not show. (actionBar.hide/show();) // an idea is to deal with scroll events on the UI. // Android 4.4+: hide navigation bar, make it accessible via edge scroll if (android.os.Build.VERSION.SDK_INT >= 19) { uiOptions |= View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION; } // apply settings View decorView = getWindow().getDecorView(); decorView.setSystemUiVisibility(uiOptions); // TODO: explore artificially reducing luminosity /*try { int brightness = android.provider.Settings.System.getInt( getContentResolver(), android.provider.Settings.System.SCREEN_BRIGHTNESS); Log.v(TAG, "brightness="+brightness); } catch (SettingNotFoundException e) { // don't care }*/ } @Override public void onWindowFocusChanged(boolean hasFocus) { // manage application's intrusiveness for different Android versions super.onWindowFocusChanged(hasFocus); if(hasFocus) prepare_fullscreen(); } private boolean isSameDay(GregorianCalendar when, GregorianCalendar other){ return (when.get(GregorianCalendar.ERA) == other.get(GregorianCalendar.ERA) && when.get(GregorianCalendar.YEAR) == other.get(GregorianCalendar.YEAR) && when.get(GregorianCalendar.DAY_OF_YEAR) == other.get(GregorianCalendar.DAY_OF_YEAR)); } private boolean isToday(GregorianCalendar when){ GregorianCalendar today = new GregorianCalendar(); return isSameDay(when, today); } @Override protected void onSaveInstanceState(Bundle outState) { // Save instance state. Especially useful on screen rotate on older phones // - what --> mass, tierce, ... ? (id) // - when --> date (timestamp) // - position --> active tab (id) super.onSaveInstanceState(outState); if(outState == null) return; int position = 0; // first slide by default int what = 0; // "Messe" by default long when = DATE_TODAY; if(whatwhen != null) { if(whatwhen.what != null) what = whatwhen.what.getPosition(); if(mViewPager != null) position = mViewPager.getCurrentItem(); if(whatwhen.when != null && !isToday(whatwhen.when)) { when = whatwhen.when.getTimeInMillis(); } } outState.putInt("what", what); outState.putInt("position", position); outState.putLong("when", when); } public boolean onAbout(MenuItem item) { AboutDialogFragment aboutDialog = new AboutDialogFragment(); aboutDialog.show(getSupportFragmentManager(), "aboutDialog"); return true; } public boolean onSyncPref(MenuItem item) { Intent intent = new Intent(this, SyncPrefActivity.class); startActivity(intent); return true; } public boolean onSyncDo(MenuItem item) { // Pass the settings flags by inserting them in a bundle Bundle settingsBundle = new Bundle(); settingsBundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true); settingsBundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true); // start sync ContentResolver.requestSync(mAccount, AUTHORITY, settingsBundle); // done return true; } public boolean onRefresh(MenuItem item) { whatwhen.useCache = false; if(mViewPager != null) { whatwhen.position = mViewPager.getCurrentItem(); } else { whatwhen.position = 0; } new DownloadXmlTask().execute(whatwhen); return true; } public boolean onCalendar(MenuItem item) { Bundle args = new Bundle(); args.putLong("time", whatwhen.when.getTimeInMillis()); DatePickerFragment calendarDialog = new DatePickerFragment(); calendarDialog.setArguments(args); calendarDialog.show(getSupportFragmentManager(), "datePicker"); return true; } @SuppressLint("SimpleDateFormat") // I know but currently French only public void onCalendarDialogPicked(int year, int month, int day) { GregorianCalendar date = new GregorianCalendar(year, month, day); // do not refresh if date did not change to avoid unnecessary flickering if(isSameDay(whatwhen.when, date)) return; whatwhen.when = date; // keep on the same reading on date change if(mViewPager != null) { whatwhen.position = mViewPager.getCurrentItem(); } else { whatwhen.position = 0; } new DownloadXmlTask().execute(whatwhen); // Update to date button with "this.date" MenuItem calendarItem = mMenu.findItem(R.id.action_calendar); SimpleDateFormat actionDateFormat = new SimpleDateFormat("E d MMM y"); //TODO: move str to cst calendarItem.setTitle(actionDateFormat.format(whatwhen.when.getTime())); } @Override public boolean onNavigationItemSelected(int position, long itemId) { // Are we actually *changing* ? --> maybe not if coming from state reload if(whatwhen.what != LecturesController.WHAT.values()[position]) { whatwhen.what = LecturesController.WHAT.values()[position]; whatwhen.position = 0; // on what change, move to 1st } new DownloadXmlTask().execute(whatwhen); return true; } @SuppressLint("SimpleDateFormat") // I know but currently French only @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar getSupportMenuInflater().inflate(R.menu.lectures, menu); // Update to date button with "this.date" MenuItem calendarItem = menu.findItem(R.id.action_calendar); SimpleDateFormat actionDateFormat = new SimpleDateFormat("E d MMM y"); //TODO: move str to cst calendarItem.setTitle(actionDateFormat.format(whatwhen.when.getTime())); mMenu = menu; return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_about: return onAbout(item); case R.id.action_sync_settings: return onSyncPref(item); case R.id.action_sync_do: return onSyncDo(item); case R.id.action_refresh: return onRefresh(item); case R.id.action_calendar: return onCalendar(item); } return true; } /** * Create a new dummy account for the sync adapter * * @param context The application context */ public static Account CreateSyncAccount(Context context) { // Create the account type and default account Account newAccount = new Account(ACCOUNT, ACCOUNT_TYPE); // Get an instance of the Android account manager AccountManager accountManager = (AccountManager) context.getSystemService(ACCOUNT_SERVICE); /* * Add the account and account type, no password or user data * If successful, return the Account object, otherwise report an error. */ if (accountManager.addAccountExplicitly(newAccount, null, null)) { return newAccount; } else { return accountManager.getAccountsByType(ACCOUNT_TYPE)[0]; } } protected void setLoading(final boolean loading) { final RelativeLayout loadingOverlay = (RelativeLayout)findViewById(R.id.loadingOverlay); final ProgressBar loadingIndicator = (ProgressBar)findViewById(R.id.loadingIndicator); loadingOverlay.post(new Runnable() { public void run() { if(loading) { loadingIndicator.getIndeterminateDrawable().setColorFilter(getResources().getColor(R.color.sepia_fg), android.graphics.PorterDuff.Mode.MULTIPLY); loadingOverlay.setVisibility(View.VISIBLE); } else { loadingOverlay.setVisibility(View.INVISIBLE); } } }); } // Async loader private class DownloadXmlTask extends AsyncTask<WhatWhen, Void, List<LectureItem>> { LecturePagerAdapter mLecturesPager; @Override protected List<LectureItem> doInBackground(WhatWhen... whatwhen) { WhatWhen ww = whatwhen[0]; try { if(ww.useCache) { // attempt to load from cache: skip loading indicator (avoids flickering) List<LectureItem> lectures = lecturesCtrl.getLecturesFromCache(ww.what, ww.when); if(lectures != null) return lectures; } // attempts to load from network, with loading indicator setLoading(true); return lecturesCtrl.getLecturesFromNetwork(ww.what, ww.when); } catch (IOException e) { Log.e(TAG, "I/O error while loading. AELF servers down ?"); setLoading(false); return null; } finally { // "useCache=false" is "fire and forget" ww.useCache = true; } } @Override protected void onPostExecute(final List<LectureItem> lectures) { List<LectureItem> pager_data; if(lectures != null) { pager_data = lectures; } else { pager_data = networkError; } // 1 slide fragment <==> 1 lecture mLecturesPager= new LecturePagerAdapter(getSupportFragmentManager(), pager_data); // Set up the ViewPager with the sections adapter. try { mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mLecturesPager); mViewPager.setCurrentItem(whatwhen.position); setLoading(false); } catch(IllegalStateException e) { // Fragment manager has gone away, will reload anyway so silently give up } } } }
package com.akjava.lib.common.form; import java.util.ArrayList; import java.util.List; import com.akjava.lib.common.tag.LabelAndValue; import com.google.common.base.Joiner; import com.google.common.collect.Lists; public class FormFieldData { private String name; private String key; private int type; private FormData parent; public FormData getParent() { return parent; } public void setParent(FormData parent) { this.parent = parent; } public int getType() { return type; } public void setType(int type) { this.type = type; } private String defaultValue; public String getDefaultValue() { return defaultValue; } public void setDefaultValue(String defaultValue) { this.defaultValue = defaultValue; } private boolean createAuto; private List<LabelAndValue> optionValues=new ArrayList<LabelAndValue>(); private List<Validator> validators=new ArrayList<Validator>(); private List<Modifier> modifiers=new ArrayList<Modifier>(); public List<Modifier> getModifiers() { return modifiers; } public void setModifiers(List<Modifier> modifiers) { this.modifiers = modifiers; } private String placeHolder; private String comment; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public boolean isCreateAuto() { return createAuto; } public void setCreateAuto(boolean createAuto) { this.createAuto = createAuto; } private String optionText; public String getOptionText() { return optionText; } public void setOptionText(String optionText) { this.optionText = optionText; } public List<LabelAndValue> getOptionValues() { return optionValues; } public void setOptionValues(List<LabelAndValue> optionValues) { this.optionValues = optionValues; } public List<Validator> getValidators() { return validators; } public void setValidators(List<Validator> validators) { this.validators = validators; } public String getPlaceHolder() { return placeHolder; } public void setPlaceHolder(String placeHolder) { this.placeHolder = placeHolder; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public static final int TYPE_TEXT_SHORT=0; public static final int TYPE_TEXT_LONG=1; public static final int TYPE_ID=2; public static final int TYPE_CHECK=3; public static final int TYPE_SELECT_SINGLE=4; public static final int TYPE_SELECT_MULTI=5; public static final int TYPE_CREATE_DATE=6; public static final int TYPE_CREATE_USER=7; public static final int TYPE_MODIFIED_DATE=8; public static final int TYPE_MODIFIED_USER=9; public static final int TYPE_NUMBER=10; public static String getTypeByNumber(int value){ switch(value){ case TYPE_TEXT_LONG: return "text_long"; case TYPE_ID: return "id"; case TYPE_CHECK: return "check"; case TYPE_SELECT_SINGLE: return "select"; case TYPE_SELECT_MULTI: return "select_multi"; case TYPE_CREATE_DATE: return "create_date"; case TYPE_CREATE_USER: return "create_user"; case TYPE_MODIFIED_DATE: return "modified_date"; case TYPE_MODIFIED_USER: return "modified_user"; case TYPE_NUMBER: return "number"; default: return "text"; } } public static final List<String> TYPES=Lists.newArrayList("text","text_short","text_long","id","check","select","select_single","select_multi","create_date","create_user","modified_date","modified_user","number"); public static int getTypeByLabel(String v){ int type=0; if(v.equals("text")||v.equals("text_short")){ type=TYPE_TEXT_SHORT; }else if(v.equals("text_long")){ type=TYPE_TEXT_LONG; }else if(v.equals("id")){ type=TYPE_ID; }else if(v.equals("check")){ type=TYPE_CHECK; }else if(v.equals("select")||v.equals("select_single")){ type=TYPE_SELECT_SINGLE; }else if(v.equals("select_multi")){ type=TYPE_SELECT_MULTI; }else if(v.equals("create_date")){ type=TYPE_CREATE_DATE; }else if(v.equals("create_user")){ type=TYPE_CREATE_USER; }else if(v.equals("modified_date")){ type=TYPE_CREATE_DATE; }else if(v.equals("modified_user")){ type=TYPE_MODIFIED_USER; }else if(v.equals("number")){ type=TYPE_NUMBER; } return type; } public String toString(){ return Joiner.on(";").withKeyValueSeparator("=").useForNull("null").join(FormFieldDataDto.formDataToMap(this)); } }
package bitronix.tm.resource.jdbc; import bitronix.tm.internal.BitronixRollbackSystemException; import bitronix.tm.internal.BitronixSystemException; import bitronix.tm.resource.common.*; import bitronix.tm.resource.jdbc.lrc.LrcXADataSource; import bitronix.tm.utils.Decoder; import bitronix.tm.utils.ManagementRegistrar; import bitronix.tm.utils.Scheduler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.sql.XAConnection; import javax.transaction.SystemException; import javax.transaction.xa.XAResource; import java.lang.reflect.Method; import java.sql.*; import java.util.*; import java.util.Date; public class JdbcPooledConnection extends AbstractXAResourceHolder implements StateChangeListener, JdbcPooledConnectionMBean { private final static Logger log = LoggerFactory.getLogger(JdbcPooledConnection.class); private final static int DETECTION_TIMEOUT = 5; // seconds private XAConnection xaConnection; private Connection connection; private XAResource xaResource; private PoolingDataSource poolingDataSource; private LruStatementCache statementsCache; private List uncachedStatements; private int usageCount; /* management */ private String jmxName; private Date acquisitionDate; private Date lastReleaseDate; private int jdbcVersionDetected; private Method isValidMethod; public JdbcPooledConnection(PoolingDataSource poolingDataSource, XAConnection xaConnection) throws SQLException { this.poolingDataSource = poolingDataSource; this.xaConnection = xaConnection; this.xaResource = xaConnection.getXAResource(); this.statementsCache = new LruStatementCache(poolingDataSource.getPreparedStatementCacheSize()); this.uncachedStatements = Collections.synchronizedList(new ArrayList()); statementsCache.addEvictionListener(new LruEvictionListener() { public void onEviction(Object value) { PreparedStatement stmt = (PreparedStatement) value; try { stmt.close(); } catch (SQLException ex) { log.warn("error closing evicted statement", ex); } } }); connection = xaConnection.getConnection(); detectJdbcVersion(connection); addStateChangeEventListener(this); if (poolingDataSource.getClassName().equals(LrcXADataSource.class.getName())) { if (log.isDebugEnabled()) log.debug("emulating XA for resource " + poolingDataSource.getUniqueName() + " - changing twoPcOrderingPosition to ALWAYS_LAST_POSITION"); poolingDataSource.setTwoPcOrderingPosition(Scheduler.ALWAYS_LAST_POSITION); if (log.isDebugEnabled()) log.debug("emulating XA for resource " + poolingDataSource.getUniqueName() + " - changing deferConnectionRelease to true"); poolingDataSource.setDeferConnectionRelease(true); if (log.isDebugEnabled()) log.debug("emulating XA for resource " + poolingDataSource.getUniqueName() + " - changing useTmJoin to true"); poolingDataSource.setUseTmJoin(true); } this.jmxName = "bitronix.tm:type=JDBC,UniqueName=" + ManagementRegistrar.makeValidName(poolingDataSource.getUniqueName()) + ",Id=" + poolingDataSource.incCreatedResourcesCounter(); ManagementRegistrar.register(jmxName, this); } private synchronized void detectJdbcVersion(Connection connection) { if (jdbcVersionDetected > 0) return; try { isValidMethod = connection.getClass().getMethod("isValid", new Class[]{Integer.TYPE}); isValidMethod.invoke(connection, new Object[] {new Integer(DETECTION_TIMEOUT)}); // test invoke jdbcVersionDetected = 4; if (!poolingDataSource.isEnableJdbc4ConnectionTest()) { if (log.isDebugEnabled()) log.debug("dataSource is JDBC4 or newer and supports isValid(), but enableJdbc4ConnectionTest is not set or is false"); } } catch (Exception ex) { jdbcVersionDetected = 3; } catch (AbstractMethodError er) { // this happens if the driver implements JDBC 3 but runs on JDK 1.6+ (which embeds the JDBC 4 interfaces) jdbcVersionDetected = 3; } if (log.isDebugEnabled()) log.debug("detected JDBC connection class '" + connection.getClass() + "' is version " + jdbcVersionDetected + " type"); } private void applyIsolationLevel() throws SQLException { String isolationLevel = getPoolingDataSource().getIsolationLevel(); if (isolationLevel != null) { int level = translateIsolationLevel(isolationLevel); if (level < 0) { log.warn("invalid transaction isolation level '" + isolationLevel + "' configured, keeping the default isolation level."); } else { if (log.isDebugEnabled()) log.debug("setting connection's isolation level to " + isolationLevel); connection.setTransactionIsolation(level); } } } private static int translateIsolationLevel(String isolationLevelGuarantee) { if ("READ_COMMITTED".equals(isolationLevelGuarantee)) return Connection.TRANSACTION_READ_COMMITTED; if ("READ_UNCOMMITTED".equals(isolationLevelGuarantee)) return Connection.TRANSACTION_READ_UNCOMMITTED; if ("REPEATABLE_READ".equals(isolationLevelGuarantee)) return Connection.TRANSACTION_REPEATABLE_READ; if ("SERIALIZABLE".equals(isolationLevelGuarantee)) return Connection.TRANSACTION_SERIALIZABLE; return -1; } public void close() throws SQLException { // this should never happen, should we throw an exception or log at warn/error? if (usageCount > 0) { if (log.isDebugEnabled()) log.debug("close connection with usage count > 0, " + this); } setState(STATE_CLOSED); // cleanup of pooled resources statementsCache.clear(); ManagementRegistrar.unregister(jmxName); connection.close(); xaConnection.close(); } public RecoveryXAResourceHolder createRecoveryXAResourceHolder() { return new RecoveryXAResourceHolder(this); } private void testConnection(Connection connection) throws SQLException { if (poolingDataSource.isEnableJdbc4ConnectionTest() && jdbcVersionDetected >= 4) { Boolean isValid = null; try { if (log.isDebugEnabled()) log.debug("testing with JDBC4 isValid() method, connection of " + this); isValid = (Boolean) isValidMethod.invoke(connection, new Object[]{new Integer(poolingDataSource.getAcquisitionTimeout())}); } catch (Exception e) { log.warn("dysfunctional JDBC4 Connection.isValid() method, or negative acquisition timeout, in call to test connection of " + this + ". Falling back to test query."); jdbcVersionDetected = 3; } // if isValid is null, and exception was caught above and we fall through to the query test if (isValid != null) { if (isValid.booleanValue()) { if (log.isDebugEnabled()) log.debug("isValid successfully tested connection of " + this); return; } throw new SQLException("connection is no longer valid"); } } String query = poolingDataSource.getTestQuery(); if (query == null) { if (log.isDebugEnabled()) log.debug("no query to test connection of " + this + ", skipping test"); return; } // Throws a SQLException if the connection is dead if (log.isDebugEnabled()) log.debug("testing with query '" + query + "' connection of " + this); PreparedStatement stmt = connection.prepareStatement(query); ResultSet rs = stmt.executeQuery(); rs.close(); stmt.close(); if (log.isDebugEnabled()) log.debug("testQuery successfully tested connection of " + this); } protected void release() throws SQLException { if (log.isDebugEnabled()) log.debug("releasing to pool " + this); --usageCount; // delisting try { TransactionContextHelper.delistFromCurrentTransaction(this); } catch (BitronixRollbackSystemException ex) { throw (SQLException) new SQLException("unilateral rollback of " + this).initCause(ex); } catch (SystemException ex) { throw (SQLException) new SQLException("error delisting " + this).initCause(ex); } finally { // Only requeue a connection if it is no longer in use. In the case of non-shared connections, // usageCount will always be 0 here, so the default behavior is unchanged. if (usageCount == 0) { try { TransactionContextHelper.requeue(this, poolingDataSource); } catch (BitronixSystemException ex) { // Requeue failed, restore the usageCount to previous value (see testcase // NewJdbcStrangeUsageMockTest.testClosingSuspendedConnectionsInDifferentContext). // This can happen when a close is attempted while the connection is participating // in a global transaction. usageCount++; // this may hide the exception thrown by delistFromCurrentTransaction() but // an error requeuing must absolutely be reported as an exception. // Too bad if this happens... See DualSessionWrapper.close() as well. throw (SQLException) new SQLException("error requeuing " + this).initCause(ex); } if (log.isDebugEnabled()) log.debug("released to pool " + this); } else { if (log.isDebugEnabled()) log.debug("not releasing " + this + " to pool yet, connection is still shared"); } } // finally } public XAResource getXAResource() { return xaResource; } public ResourceBean getResourceBean() { return getPoolingDataSource(); } public PoolingDataSource getPoolingDataSource() { return poolingDataSource; } public List getXAResourceHolders() { List xaResourceHolders = new ArrayList(); xaResourceHolders.add(this); return xaResourceHolders; } public Object getConnectionHandle() throws Exception { if (log.isDebugEnabled()) log.debug("getting connection handle from " + this); int oldState = getState(); // Increment the usage count usageCount++; // Only transition to STATE_ACCESSIBLE on the first usage. If we're not sharing // connections (default behavior) usageCount is always 1 here, so this transition // will always occur (current behavior unchanged). If we _are_ sharing connections, // and this is _not_ the first usage, it is valid for the state to already be // STATE_ACCESSIBLE. Calling setState() with STATE_ACCESSIBLE when the state is // already STATE_ACCESSIBLE fails the sanity check in AbstractXAStatefulHolder. // Even if the connection is shared (usageCount > 1), if the state was STATE_NOT_ACCESSIBLE // we transition back to STATE_ACCESSIBLE. if (usageCount == 1 || oldState == STATE_NOT_ACCESSIBLE) { setState(STATE_ACCESSIBLE); } if (oldState == STATE_IN_POOL) { if (log.isDebugEnabled()) log.debug("connection " + xaConnection + " was in state IN_POOL, testing it"); testConnection(connection); applyIsolationLevel(); applyCursorHoldabilty(); if (TransactionContextHelper.currentTransaction() == null) { // it is safe to set the auto-commit flag outside of a global transaction applyLocalAutoCommit(); } } else { if (log.isDebugEnabled()) log.debug("connection " + xaConnection + " was in state " + Decoder.decodeXAStatefulHolderState(oldState) + ", no need to test it"); } if (log.isDebugEnabled()) log.debug("got connection handle from " + this); return new JdbcConnectionHandle(this, connection); } public void stateChanged(XAStatefulHolder source, int oldState, int newState) { if (newState == STATE_IN_POOL) { if (log.isDebugEnabled()) log.debug("requeued JDBC connection of " + poolingDataSource); lastReleaseDate = new Date(); } if (oldState == STATE_IN_POOL && newState == STATE_ACCESSIBLE) { acquisitionDate = new Date(); } if (oldState == STATE_NOT_ACCESSIBLE && newState == STATE_ACCESSIBLE) { TransactionContextHelper.recycle(this); } } public void stateChanging(XAStatefulHolder source, int currentState, int futureState) { if (futureState == STATE_IN_POOL) { if (usageCount > 0) { log.warn("usage count too high (" + usageCount + ") on connection returned to pool " + source); } } if (futureState == STATE_IN_POOL || futureState == STATE_NOT_ACCESSIBLE) { // close all uncached statements if (log.isDebugEnabled()) log.debug("closing " + uncachedStatements.size() + " dangling uncached statement(s)"); for (int i = 0; i < uncachedStatements.size(); i++) { Statement statement = (Statement) uncachedStatements.get(i); try { statement.close(); } catch (SQLException ex) { if (log.isDebugEnabled()) log.debug("error trying to close uncached statement " + statement, ex); } } uncachedStatements.clear(); // clear SQL warnings try { if (log.isDebugEnabled()) log.debug("clearing warnings of " + connection); connection.clearWarnings(); } catch (SQLException ex) { if (log.isDebugEnabled()) log.debug("error cleaning warnings of " + connection, ex); } } } /** * Get a PreparedStatement from cache. * @param stmt the key that has been used to cache the statement. * @return the cached statement corresponding to the key or null if no statement is cached under that key. */ protected JdbcPreparedStatementHandle getCachedStatement(JdbcPreparedStatementHandle stmt) { return statementsCache.get(stmt); } /** * Put a PreparedStatement in the cache. * @param stmt the statement to cache. * @return the cached statement. */ protected JdbcPreparedStatementHandle putCachedStatement(JdbcPreparedStatementHandle stmt) { return statementsCache.put(stmt); } /** * Register uncached statement so that it can be closed when the connection is put back in the pool. * * @param stmt the statement to register. * @return the registered statement. */ protected Statement registerUncachedStatement(Statement stmt) { uncachedStatements.add(stmt); return stmt; } protected void unregisterUncachedStatement(Statement stmt) { uncachedStatements.remove(stmt); } public String toString() { return "a JdbcPooledConnection from datasource " + poolingDataSource.getUniqueName() + " in state " + Decoder.decodeXAStatefulHolderState(getState()) + " with usage count " + usageCount + " wrapping " + xaConnection; } private void applyCursorHoldabilty() throws SQLException { String cursorHoldability = getPoolingDataSource().getCursorHoldability(); if (cursorHoldability != null) { int holdability = translateCursorHoldability(cursorHoldability); if (holdability < 0) { log.warn("invalid cursor holdability '" + cursorHoldability + "' configured, keeping the default cursor holdability."); } else { if (log.isDebugEnabled()) log.debug("setting connection's cursor holdability to " + cursorHoldability); connection.setHoldability(holdability); } } } private static int translateCursorHoldability(String cursorHoldability) { if ("CLOSE_CURSORS_AT_COMMIT".equals(cursorHoldability)) return ResultSet.CLOSE_CURSORS_AT_COMMIT; if ("HOLD_CURSORS_OVER_COMMIT".equals(cursorHoldability)) return ResultSet.HOLD_CURSORS_OVER_COMMIT; return -1; } private void applyLocalAutoCommit() throws SQLException { String localAutoCommit = getPoolingDataSource().getLocalAutoCommit(); if (localAutoCommit != null) { if (localAutoCommit.equalsIgnoreCase("true")) { if (log.isDebugEnabled()) log.debug("setting connection's auto commit to true"); connection.setAutoCommit(true); } else if (localAutoCommit.equalsIgnoreCase("false")) { if (log.isDebugEnabled()) log.debug("setting connection's auto commit to false"); connection.setAutoCommit(false); } else { log.warn("invalid auto commit '" + localAutoCommit + "' configured, keeping default auto commit"); } } } /* management */ public String getStateDescription() { return Decoder.decodeXAStatefulHolderState(getState()); } public Date getAcquisitionDate() { return acquisitionDate; } public Date getLastReleaseDate() { return lastReleaseDate; } public Collection getTransactionGtridsCurrentlyHoldingThis() { return getXAResourceHolderStateGtrids(); } }
package VASSAL.tools; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.SortedSet; import java.util.zip.CRC32; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import VASSAL.build.GameModule; import VASSAL.configure.DirectoryConfigurer; import VASSAL.launch.Launcher; import VASSAL.preferences.Prefs; import VASSAL.tools.IOUtils; import VASSAL.tools.filechooser.FileChooser; /** * An ArchiveWriter is a writeable DataArchive. New files may be added * with the {@link #addFile} and {@link #addImage} methods. */ public class ArchiveWriter extends DataArchive { private final Map<String,Object> images = new HashMap<String,Object>(); private final Map<String,Object> sounds = new HashMap<String,Object>(); private final Map<String,Object> files = new HashMap<String,Object>(); private String archiveName; private boolean closeWhenNotInUse; /** * Create a new writeable archive. * * @param zipName the name of the archive. If null, the user will be * prompted for a filename when saving. If not null, new entries will * be added to the named archive. If the file exists and is not a zip * archive, it will be overwritten. */ public ArchiveWriter(String zipName) { archiveName = zipName; closeWhenNotInUse = false; if (archiveName != null) { final File f = new File(archiveName); if (f.exists()) { try { archive = new ZipFile(f); } catch (IOException e) { // FIXME: This isn't quite right, e.g., in the case where the user intends // to overwrite the given file, but it isn't a zip file. How to distinguish // between that situation and a bona fide I/O error? ReadErrorDialog.error(e, archiveName); } } } } public ArchiveWriter(String zipName, boolean keepClosed) { this(zipName); closeWhenNotInUse(); } public ArchiveWriter(ZipFile archive) { this.archive = archive; archiveName = archive.getName(); } /** * Close the archive, but keep it available for reuse. Used for Preferences * files which must be shared between processes. */ public void closeWhenNotInUse() { closeWhenNotInUse = true; if (archive != null) { try { archive.close(); } catch (IOException e) { ReadErrorDialog.error(e, archive.getName()); } archive = null; } } /** * Add an image file to the archive. The file will be copied into an * "images" directory in the archive. Storing another image with the * same name will overwrite the previous image. * * @param path the full path of the image file on the user's filesystem * @param name the name under which to store the image in the archive */ public void addImage(String path, String name) { // check SVG for external references and pull them in if (name.toLowerCase().endsWith(".svg")) { for (String s : SVGImageUtils.getExternalReferences(path)) { final File f = new File(s); final String n = f.getName(); // ImageCache.remove(new SourceOp(n)); images.put(imageDir + n, f.getPath()); } } // otherwise just add what we were given else { // ImageCache.remove(new SourceOp(name)); images.put(IMAGE_DIR + name, path); } localImages = null; } public void addImage(String name, byte[] contents) { // ImageCache.remove(new SourceOp(name)); images.put(imageDir + name, contents); localImages = null; } public void addSound(String file, String name) { sounds.put(SOUNDS_DIR + name, file); } public boolean isImageAdded(String name) { return images.containsKey(name); } public void removeImage(String name) { // ImageCache.remove(new SourceOp(name)); images.remove(imageDir + name); localImages = null; } /** * Copy a file from the user's filesystem to the archive. * * @param path the full path of the file on the user's filesystem * @param fileName the name under which to store the file in the archive */ public void addFile(String path, String fileName) { files.put(fileName, path); } /** * Copy an <code>InputStream</code> into the archive * * @param fileName the name under which to store the contents of the stream * @param in the stream to copy */ public void addFile(String fileName, InputStream in) { try { files.put(fileName, IOUtils.getBytes(in)); } catch (IOException e) { ReadErrorDialog.error(e, fileName); } } public void addFile(String fileName, byte[] content) { files.put(fileName, content); } /** * Overrides {@link DataArchive#getFileStream} to return streams that have * been added to the archive but not yet written to disk. */ @Override public InputStream getFileStream(String fileName) throws IOException { if (closeWhenNotInUse && archive == null && archiveName != null) { archive = new ZipFile(archiveName); } InputStream in = getAddedStream(images, fileName); if (in != null) return in; in = getAddedStream(files, fileName); if (in != null) return in; in = getAddedStream(sounds, fileName); if (in != null) return in; if (archive != null) return super.getFileStream(fileName); throw new FileNotFoundException(fileName + " not found"); } private InputStream getAddedStream(Map<String,Object> table, String fileName) throws IOException { final Object file = table.get(fileName); if (file instanceof String) { return new FileInputStream((String) file); } else if (file instanceof byte[]) { return new ByteArrayInputStream((byte[]) file); } else { return null; } } public void saveAs() throws IOException { saveAs(false); } public void saveAs (boolean notifyModuleManager) throws IOException { archiveName = null; write(notifyModuleManager); } /** * If the ArchiveWriter was initialized with non-null file name, then * write the contents of the archive to the named archive. If it was * initialized with a null name, prompt the user to select a new file * into which to write archive. */ public void write() throws IOException { write(false); } public void write(boolean notifyModuleManager) throws IOException { if (archiveName == null) { final FileChooser fc = FileChooser.createFileChooser( GameModule.getGameModule().getFrame(), (DirectoryConfigurer) Prefs.getGlobalPrefs() .getOption(Prefs.MODULES_DIR_KEY)); if (fc.showSaveDialog() != FileChooser.APPROVE_OPTION) return; archiveName = fc.getSelectedFile().getPath(); } String temp = new File(archiveName).getParent(); temp = temp == null ? "temp" : temp + File.separator + "temp"; int n = 1; while ((new File(temp + n + ".zip")).exists()) { n++; } temp += n + ".zip"; ZipOutputStream out = null; try { out = new ZipOutputStream( new BufferedOutputStream( new FileOutputStream(temp))); out.setLevel(9); if (closeWhenNotInUse && archive == null && archiveName != null) { try { archive = new ZipFile(archiveName); } catch (IOException e) { // Not an error, either the archive doesn't exist yet, // or it isn't a ZIP file and we're going to overwrite it. // In the case that this is a bona fide I/O error, we'll // surely hit it again when we try to write later, so it // can be ignored here. } } if (archive != null) { // Copy old unmodified entries into temp file final byte[] buf = new byte[8192]; ZipInputStream in = null; try { in = new ZipInputStream( new BufferedInputStream( new FileInputStream(archive.getName()))); ZipEntry entry = null; while ((entry = in.getNextEntry()) != null) { // skip modified or new entries final String name = entry.getName(); if (images.containsKey(name) || sounds.containsKey(name) || files.containsKey(name)) continue; if (entry.getMethod() == ZipEntry.DEFLATED) { // we can't reuse entries for compressed files // because there's no way to reset the fields // to acceptable values entry = new ZipEntry(name); } // write out unmodified entries out.putNextEntry(entry); IOUtils.copy(in, out, buf); } in.close(); } finally { IOUtils.closeQuietly(in); } } // Write new entries into temp file writeEntries(images, ZipEntry.STORED, out); writeEntries(sounds, ZipEntry.STORED, out); writeEntries(files, ZipEntry.DEFLATED, out); out.close(); } finally { IOUtils.closeQuietly(out); } if (archive != null) { archive.close(); archive = null; } final File original = new File(archiveName); if (original.exists() && !original.delete()) { throw new IOException("Unable to overwrite " + archiveName + "\nData stored in " + temp); } final File f = new File(temp); if (!f.renameTo(original)) { throw new IOException("Unable to write to " + archiveName + "\nData stored in " + temp); } if (notifyModuleManager) { Launcher.getInstance().sendSaveCmd(original); } if (!closeWhenNotInUse) { archive = new ZipFile(archiveName); } } private void writeEntries(Map<String,Object> h, int method, ZipOutputStream out) throws IOException { for (String name : h.keySet()) { final Object o = h.get(name); final ZipEntry entry = new ZipEntry(name); entry.setMethod(method); if (o instanceof String && !name.toLowerCase().endsWith(".svg")) { FileInputStream in = null; try { // o is a filename in = new FileInputStream((String) o); final byte[] buf = new byte[8192]; if (method == ZipEntry.STORED) { // find the checksum final CRC32 checksum = new CRC32(); int count = 0; int n = 0; try { while ((n = in.read(buf)) > 0) { checksum.update(buf, 0, n); count += n; } in.close(); } finally { IOUtils.closeQuietly(in); } entry.setSize(count); entry.setCrc(checksum.getValue()); // reset the stream in = new FileInputStream((String) o); } out.putNextEntry(entry); IOUtils.copy(in, out, buf); in.close(); } finally { IOUtils.closeQuietly(in); } } else { byte[] contents; if (o instanceof String) { contents = SVGImageUtils.relativizeExternalReferences((String) o); } else if (o instanceof byte[]) { contents = (byte[]) o; } else { // unrecognized type try { throw new IllegalStateException( "Entry '" + name + "' is of an unrecognized type."); } catch (IllegalStateException e) { // Note: we catch here and continue becuase the user will // appreciate being able to save whatever he can. ErrorDialog.bug(e); } continue; } if (method == ZipEntry.STORED) { entry.setSize(contents.length); final CRC32 checksum = new CRC32(); checksum.update(contents); entry.setCrc(checksum.getValue()); } out.putNextEntry(entry); out.write(contents); } } } public SortedSet<String> getImageNameSet() { final SortedSet<String> s = super.getImageNameSet(); for (String name : images.keySet()) { if (name.startsWith(imageDir)) { s.add(name.substring(imageDir.length())); } } return s; } /** * Ensure the specified Zip archive exists. Create it and the specified * entry if it does not. * * @param archiveName Archive file * @param entryName Entry Name */ public static void ensureExists(File archiveFile, String entryName) throws IOException { if (archiveFile.exists()) return; ZipOutputStream out = null; try { out = new ZipOutputStream( new BufferedOutputStream(new FileOutputStream(archiveFile))); out.putNextEntry(new ZipEntry(entryName)); out.close(); } finally { IOUtils.closeQuietly(out); } } /** @deprecated Use {@link getImageNameSet()} instead. */ @Deprecated protected SortedSet<String> setOfImageNames() { final SortedSet<String> s = super.setOfImageNames(); for (String name : images.keySet()) { if (name.startsWith(imageDir)) { s.add(name.substring(imageDir.length())); } } return s; } /** @deprecated Use {@link #setofImageNames()} instead. */ @Deprecated @SuppressWarnings("unchecked") protected void listImageNames(Collection v) { v.addAll(setOfImageNames()); } }
package caris.framework.handlers; import caris.framework.basehandlers.Handler; import caris.framework.basereactions.MultiReaction; import caris.framework.basereactions.Reaction; import caris.framework.library.Constants; import caris.framework.library.Variables; import caris.framework.reactions.ReactionMessage; import caris.framework.reactions.ReactionUserStatusUpdate; import caris.framework.utilities.Logger; import sx.blah.discord.api.events.Event; import sx.blah.discord.handle.impl.events.user.PresenceUpdateEvent; import sx.blah.discord.handle.obj.IGuild; import sx.blah.discord.handle.obj.StatusType; public class PresenceUpdateHandler extends Handler { public PresenceUpdateHandler() { super("PresenceUpdate", false); } @Override protected boolean isTriggered(Event event) { if( !(event instanceof PresenceUpdateEvent) ) { return false; } PresenceUpdateEvent presenceUpdateEvent = (PresenceUpdateEvent) event; return presenceUpdateEvent.getNewPresence().getStatus().equals(StatusType.ONLINE) || presenceUpdateEvent.getNewPresence().getStatus().equals(StatusType.OFFLINE); } @Override protected Reaction process(Event event) { Logger.debug("PresenceUpdate detected", 2, true); PresenceUpdateEvent presenceUpdateEvent = (PresenceUpdateEvent) event; MultiReaction userOnline = new MultiReaction(-1); if( presenceUpdateEvent.getNewPresence().getStatus().equals(StatusType.OFFLINE) && !Variables.globalUserInfo.get(presenceUpdateEvent.getUser()).hasGoneOffline ) { userOnline.reactions.add(new ReactionUserStatusUpdate(presenceUpdateEvent.getUser(), true)); } else if( presenceUpdateEvent.getNewPresence().getStatus().equals(StatusType.ONLINE) && Variables.globalUserInfo.get(presenceUpdateEvent.getUser()).hasGoneOffline ) { Logger.print(" User [" + presenceUpdateEvent.getUser().getName() + "#" + presenceUpdateEvent.getUser().getDiscriminator() + "]" + "(" + presenceUpdateEvent.getUser().getLongID() + ") has come online.", true); userOnline.reactions.add(new ReactionUserStatusUpdate(presenceUpdateEvent.getUser(), false)); for( IGuild guild : Variables.guildIndex.keySet() ) { if( guild.getUsers().contains(presenceUpdateEvent.getUser()) ) { if( !Variables.guildIndex.get(guild).userIndex.get(presenceUpdateEvent.getUser()).mailbox.isEmpty() ) { userOnline.reactions.add(new ReactionMessage("Welcome back, " + presenceUpdateEvent.getUser().mention() + "! You have incoming mail!" + "\nType `" + Constants.INVOCATION_PREFIX + " mail check` to read it!", Variables.guildIndex.get(guild).getDefaultChannel())); } } } } Logger.debug("Reaction produced from " + name, 1, true); return userOnline; } }
package ch.unizh.ini.jaer.projects.rnnfilter; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.logging.Level; import javax.swing.ImageIcon; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.filechooser.FileFilter; import javax.swing.filechooser.FileNameExtensionFilter; import org.apache.commons.lang3.StringUtils; import org.jblas.FloatMatrix; import com.jogamp.opengl.GL; import com.jogamp.opengl.GL2; import com.jogamp.opengl.GLAutoDrawable; import ch.unizh.ini.jaer.chip.cochlea.BinauralCochleaEvent.Ear; import ch.unizh.ini.jaer.chip.cochlea.CochleaAMSEvent; import ch.unizh.ini.jaer.chip.cochlea.CochleaAMSEvent.FilterType; import ch.unizh.ini.jaer.chip.cochlea.RollingCochleaGramDisplayMethod; import net.sf.jaer.Description; import net.sf.jaer.DevelopmentStatus; import net.sf.jaer.chip.AEChip; import net.sf.jaer.event.BasicEvent; import net.sf.jaer.event.EventPacket; import net.sf.jaer.eventprocessing.EventFilter2D; import net.sf.jaer.graphics.FrameAnnotater; import net.sf.jaer.graphics.MultilineAnnotationTextRenderer; /** * Extracts binned spike features from CochleaAMS sensor and processes them through a recurrent network * * @author jithendar */ @Description("Extracts binned spike features from CochleaAMS sensor and processes them through a recurrent network") @DevelopmentStatus(DevelopmentStatus.Status.Experimental) public class RNNfilter extends EventFilter2D implements FrameAnnotater, PropertyChangeListener { /** * Chooses the time length for the bin, the current network is trained on 5ms data, hence the variable is * initialized appropriately */ private int binTimeLength = getPrefs().getInt("binTimeLength", 5000); // default value set to 5 ms /** * Choose whether to bin the data from both ears, when false the chooseEar variable chooses which ear to bin from */ private boolean useBothEars = getBoolean("useBothEars", false); /** * If data from only one ear is chosen, this variable gets the preference from the user */ private int chooseEar = getPrefs().getInt("chooseEar", 0); // 0 corresponds to left, 1 corresponds to right /** * Choose whether to bin the data from all the neurons, when false the chooseNeuron variable chooses the appropriate * neuron */ private boolean useAllNeurons = getBoolean("useAllNeurons", false); /** * If data from only one neuron is chosen, this variable gets the preference from the user */ private int chooseNeuron = getPrefs().getInt("chooseNeuron", 0); // choose a value between 0 and 3, otherwise a // random value will be chosen /** * Choose whether to bin data from both the filter types, when false the chooseFilterType chooses the appropriate * filter type */ private boolean useBothFilterTypes = getBoolean("useBothFilterTypes", false); /** * If data from only one filter type is to be binned, this variable gets the preference from the user */ private int chooseFilterType = getPrefs().getInt("chooseFilterType", 1); // 0 corresponds to LPF, 1 corresponds to // BPF /** * The XML file to load the RNN network from */ private String lastRNNXMLFile = getString("lastRNNXMLFile", "rnn_cochlea_v3b_jAER.xml"); /** * Choose whether to display activations or not */ private boolean displayActivations = getBoolean("displayActivations", true); /** * Choose whether to display the softmax probability of the prediction */ private boolean displayAccuracy = getBoolean("displayAccuracy", true); /** * If the filter saves the feature as an array list, then choose whether to display it once the feature is recorded */ private boolean displayFeature = getBoolean("displayFeature", true); /** * If true, the frame is annotated with the label prediction only if the softmax accuracy is more than 0.9 */ private boolean showPredictionOnlyIfGood = getBoolean("showPredictionOnlyIfGood", false); /** * True if the filter intends to process RNN only when you click a button, if false it is a continuous RNN * processing */ private boolean clickToProcess = getBoolean("clickToProcess", true); /** * If needed to click to process RNN, choose if the RNN process happens as a batch at the end or in a continuous * live setting */ private boolean batchRNNProcess = getBoolean("batchRNNProcess", false); /** * Is the filter binning the events */ private boolean processingEnabled = getBoolean("processingEnabled", true); /** * Boolean variable which checks if the filter is initialized */ private boolean isInitialized = false; /** * Number of channels (frequencies), when a user chooses a number other 64 an appropriately trained network has to * be initialized */ private int nChannels = 64; /** * Number of neurons for each neuron, default value of 4 */ private int nNeurons = 4; /** * Number of ears, default value of 2 */ private int nEars = 2; /** * Number of filter types, default value of 2 */ private int nFilterTypes = 2; /** * The last time when RNN was processed */ private int lastBinCompleteTime; /** * Array to store the binned data, this has the data from the latest bin */ private int[] binnedData = new int[this.getnChannels()]; /** * When not using continuous live recording, this array list holds the list of binned data at all previous times, * which is then given to an RNN network */ private ArrayList<int[]> binnedDataList; /** * RNN network for the filter */ protected RNNetwork rnnetwork; /** * Output of the network; */ private float[] networkOutput; /** * Corresponding label given the network output */ private int label = -1; /** * The ear to choose the events from, 0 for left and 1 for right */ private int whichEar; /** * The neuron to choose the events from, values in 0-3 */ private int whichNeuron; /** * The filter type to choose events from, 0 for LPF and 1 for BPF */ private int whichFilter; /** * Choose which type of function you want the filter to perform, 0 stands for continuous recording, 1 stands for * click and record continuous RNN processing, 2 stands for click and record batch RNN processing */ private int whichFunction = 3; private boolean isFirstEventDone = false; private int counter = 0; // counts total number of basic events private int counter1 = 0; // counts total number of processed events private int lastEventTime; private int firstEventTime; private ArrayList<Integer> rnnProcessTimeStampList; private ArrayList<float[]> rnnOutputList; private boolean addedDisplayMethodPropertyChangeListener = false; private boolean screenCleared = false; // set by RollingCochleaGramDisplayMethod // TestNumpyData testNumpyData; //debug // private String lastTestDataXMLFile = "ti_train_cochlea_data_nozeroslices_20_jAER_input.xml"; //debug public RNNfilter(AEChip chip) { super(chip); String xmlnetwork = "1. XML Network", function = "2. Filter function", parameters = "3. Parameter options", display = "4. Display"; setPropertyTooltip("loadFromXML", "Load an XML file containing the network in an appropriate format"); setPropertyTooltip("runRNN", "If clickToProcess is set to true, the filter will process events when this button is kept pressed, also the network will be reset when you press the button. So press the button and hold it, speak and release the button when you want the filter to stop processing."); setPropertyTooltip("toggleBinning", "If clickToProcess is set to true, this button will toggle the boolean variable - processingEnabled - which enables the events to be processed. So when processingEnabled is false, clicking on the button will make the filter start processing the events and when processingEnabled is true, clicking the button will make the filter stop processing events."); setPropertyTooltip(xmlnetwork, "lastRNNXMLFile", "The XML file containing an RNN network exported from keras/somewhere else"); setPropertyTooltip(parameters, "binTimeLength", "Choose the bin size (in micro seconds) for the binning of the data, choose a network appropriately"); setPropertyTooltip(parameters, "useBothEars", "Choose whether to use the events from both ears"); setPropertyTooltip(parameters, "chooseEar", "If processing events from only one ear, choose which ear to process them from, 0 for left and 1 for right"); setPropertyTooltip(parameters, "useAllNeurons", "Choose whether to process the events from all the neurons"); setPropertyTooltip(parameters, "chooseNeuron", "If events from all neurons are not to be processed, which neuron's events should be chosen, choose a value in {0,1,2,3}"); setPropertyTooltip(parameters, "useBothFilterTypes", "Choose whether to process the events from both the filter types"); setPropertyTooltip(parameters, "chooseFilterType", "If processing is to be done only on one filter type, which filter type should be chosen; 0 for low pass and 1 for band pass"); setPropertyTooltip(function, "clickToProcess", "True if the filter wants to only process the events when the RunRNN filter action is kept pressed; default: false"); setPropertyTooltip(function, "batchRNNProcess", "True if you want to save the sound feature and then process the RNN in one go when clickToProcess is true, false otherwise; default: false"); setPropertyTooltip(function, "displayActivations", "Choose whether to display the softmax activations as a bar chart"); setPropertyTooltip(function, "displayAccuracy", "Choose whether to display the softmax accuracy of the current prediction"); setPropertyTooltip(function, "displayFeature", "Choose whether to display any recorded feature once recording is completed"); setPropertyTooltip(function, "showPredictionOnlyIfGood", "Show the output prediction only if the prediction is good (>0.9)"); setPropertyTooltip("processingEnabled", "The boolean variable which enables the events to be processed"); initFilter(); } @Override synchronized public void annotate(GLAutoDrawable drawable) { GL2 gl = drawable.getGL().getGL2(); if (chip.getCanvas().getDisplayMethod() instanceof RollingCochleaGramDisplayMethod) { // what to display on rolling cochlea gram display return; } if ((this.rnnetwork != null) & (this.rnnetwork.netname != null)) { MultilineAnnotationTextRenderer.resetToYPositionPixels(chip.getSizeY() * .1f); MultilineAnnotationTextRenderer.setScale(.1f); if (this.isProcessingEnabled()) { int timeElapsed = this.lastEventTime - this.firstEventTime; timeElapsed = timeElapsed / 1000; MultilineAnnotationTextRenderer.renderMultilineString( StringUtils.join("", this.rnnetwork.netname, " ; ", "Time elapsed:", Float.toString(timeElapsed), "ms")); } else { MultilineAnnotationTextRenderer.renderMultilineString(this.rnnetwork.netname); } } if (this.networkOutput != null) { float tmpValue = RNNfilter.maxValue(this.networkOutput) * 100; tmpValue = ((int) tmpValue); tmpValue = tmpValue / 100; if (!this.isShowPredictionOnlyIfGood() | (this.isShowPredictionOnlyIfGood() & (tmpValue > 0.9))) { MultilineAnnotationTextRenderer.resetToYPositionPixels(chip.getSizeY() * 1f); MultilineAnnotationTextRenderer.setScale(.1f); if (this.isDisplayAccuracy()) { // MultilineAnnotationTextRenderer.renderMultilineString(String.join("", Integer.toString(this.label // + 1),";",Float.toString(tmpValue))); MultilineAnnotationTextRenderer .renderMultilineString(StringUtils.join("", Integer.toString(this.label), ";", Float.toString(tmpValue))); } else { // MultilineAnnotationTextRenderer.renderMultilineString(Integer.toString(this.label + 1)); MultilineAnnotationTextRenderer.renderMultilineString(Integer.toString(this.label)); } } } if ((this.networkOutput != null) & this.isDisplayActivations()) { this.showActivations(gl, chip.getSizeX(), chip.getSizeY()); } } @Override synchronized public EventPacket<?> filterPacket(EventPacket<?> in) { for (BasicEvent e : in) { this.counter++; try { if (!this.isInitialized) { initFilter(); } // making sure the filter is initialized CochleaAMSEvent cochleaAMSEvent = ((CochleaAMSEvent) e); // int tmpByte = e.getType(); int ear; if (cochleaAMSEvent.getEar() == Ear.LEFT) { ear = 0; } else { ear = 1; } // sets the ear variable to 0 if from left ear, 1 if right ear int filterType; if (cochleaAMSEvent.getFilterType() == FilterType.LPF) { filterType = 0; } else { filterType = 1; } // sets the filterType variable to 0 if from low pass, 1 if from band pass int neuron = cochleaAMSEvent.getThreshold(); // returns the index corresponding to the ganglion cell // threshold level int timeStamp = e.timestamp; // the timestamp of the event int channel = e.x; // the channel address (0-63) of the event if ((this.rnnetwork.initialized) & this.isProcessingEnabled()) { processEvent(timeStamp, channel, ear, neuron, filterType); } // updates the bin data and performs additional computation as and when required } catch (Exception e1) { log.log(Level.WARNING, "In for-loop in filterPacket caught exception {0}", e1); } } return in; } @Override public void resetFilter() { this.resetNetwork(); this.resetBins(); switch (this.getWhichFunction()) { case 2: this.setProcessingEnabled(false); break; case 1: this.setProcessingEnabled(false); break; case 0: this.setProcessingEnabled(true); break; default: break; } this.rnnProcessTimeStampList = new ArrayList<>(); this.rnnOutputList = new ArrayList<>(); this.binnedDataList = new ArrayList<>(); this.counter = 0; this.counter1 = 0; this.isFirstEventDone = false; this.firstEventTime = 0; this.lastEventTime = 0; } @Override public void initFilter() { this.rnnetwork = new RNNetwork(); // this.testNumpyData = new TestNumpyData(); //debug this.resetBins(); Arrays.fill(this.binnedData, 0); // initialized the bin data array to zero // if whichEar preference given by user is out of bounds, choose a random value if ((this.getChooseEar() > -1) & (this.getChooseEar() < this.getnEars())) { this.whichEar = this.getChooseEar(); } else { this.whichEar = (int) (Math.random() * (this.getnEars())); } // if whichNeuron preference given by user is out of bounds, choose a random value if ((this.getChooseNeuron() > -1) & (this.getChooseNeuron() < this.getnNeurons())) { this.whichNeuron = this.getChooseNeuron(); } else { this.whichNeuron = (int) (Math.random() * (this.getnNeurons())); } // if whichFilter preference given by user is out of bounds, choose a random value if ((this.getChooseFilterType() > -1) & (this.getChooseFilterType() < this.getnFilterTypes())) { this.whichFilter = this.getChooseFilterType(); } else { this.whichFilter = (int) (Math.random() * (this.getnFilterTypes())); } // initializes the function of the filter from the user preferences if (!this.clickToProcess) { this.whichFunction = 0; } else { if (this.isBatchRNNProcess()) { this.whichFunction = 2; } else { this.whichFunction = 1; } } // sets the binning variable to either start binning right away or wait for a signal from the GUI, depending on // the function switch (this.getWhichFunction()) { case 2: this.setProcessingEnabled(false); break; case 1: this.setProcessingEnabled(false); break; case 0: this.setProcessingEnabled(true); break; default: break; } // this.loadTestDataFromXML(); //debug // this.testNumpyData.testingNetwork(); //debug this.rnnProcessTimeStampList = new ArrayList<>(); this.rnnOutputList = new ArrayList<>(); this.binnedDataList = new ArrayList<>(); this.label = -1; this.isInitialized = true; this.isFirstEventDone = false; this.counter = 0; this.counter1 = 0; } synchronized public void loadFromXML() { this.setProcessingEnabled(false); JFileChooser c = new JFileChooser(this.getLastRNNXMLFile()); FileFilter filter = new FileNameExtensionFilter("XML File", "xml"); c.addChoosableFileFilter(filter); c.setFileFilter(filter); c.setSelectedFile(new File(this.getLastRNNXMLFile())); int ret = c.showOpenDialog(chip.getAeViewer()); if (ret != JFileChooser.APPROVE_OPTION) { return; } File f = c.getSelectedFile(); try { this.rnnetwork.loadFromXML(f); this.setLastRNNXMLFile(f.toString()); putString("lastRNNXMLFile", this.getLastRNNXMLFile()); // this.testNumpyData.rnnetwork.loadFromXML(c.getSelectedFile()); //debug } catch (Exception e) { log.log(Level.WARNING, "Couldn't upload the xml file, please check. Caught exception {0}", e); } this.resetFilter(); } /** * Updates the bin data and if the timeStamp is past the bin time length, either the RNN network is processed or the * bin is updated in the arraylist of bins * * @param timeStamp * - timestamp of the event * @param channel * - which channel is the event from * @param ear * - which ear is the event from * @param neuron * - which neuron is the event from * @param filterType * - which filter type is the event from */ public void processEvent(int timeStamp, int channel, int ear, int neuron, int filterType) throws IOException { // makes sure that the address is ok if (!isAddressOk(channel, ear, neuron, filterType)) { return; } this.counter1++; if (!this.isFirstEventDone) { this.ifFirstEventNotDone(timeStamp, channel); } if (timeStamp < this.lastBinCompleteTime) { switch (this.getWhichFunction()) { case 1: log.log(Level.SEVERE, "The present timestamp is less than a previous timestamp, this isn't supposed to happen"); this.resetFilter(); break; case 0: log.log(Level.SEVERE, "The present timestamp is less than a previous timestamp, this isn't supposed to happen"); this.resetFilter(); this.ifFirstEventNotDone(timeStamp, channel); this.updateBin(channel); break; case 2: log.log(Level.SEVERE, "The present timestamp is less than a previous timestamp, this isn't supposed to happen"); this.resetFilter(); break; default: break; } return; } else { this.lastEventTime = timeStamp; } // if the present spike's timestamp is within a binTimeLength of the last binned data, we update the bin if ((timeStamp > this.lastBinCompleteTime) & (timeStamp < (this.lastBinCompleteTime + this.getBinTimeLength()))) { this.updateBin(channel); } else if (timeStamp > (this.lastBinCompleteTime + this.getBinTimeLength())) { // if the timestamp is more than a binTimeLength, then reset the bins to zero switch (this.getWhichFunction()) { case 1: this.updateBinnedDataListNoReset(timeStamp); this.processRNN(timeStamp); break; case 0: this.processRNN(timeStamp); break; case 2: this.updateBinnedDataList(timeStamp); break; default: break; } this.binnedData[channel]++; } } /** * Increase the updateBin counter at the given channel * * @param channel */ public void updateBin(int channel) { this.binnedData[channel]++; } /** * Updates the binned data list, given the latest time stamp it even adds the necessary zeros to the network * * @param timeStamp */ public void updateBinnedDataList(int timeStamp) { this.binnedDataList.add(Arrays.copyOf(this.binnedData, this.getnChannels())); this.lastBinCompleteTime += this.getBinTimeLength(); this.resetBins(); while (timeStamp > (this.lastBinCompleteTime + this.getBinTimeLength())) { int[] tmpArr = new int[this.getnChannels()]; this.binnedDataList.add(tmpArr); this.lastBinCompleteTime += this.getBinTimeLength(); } } /** * Updates the binned data list, given the latest time stamp it even adds the necessary zeros to the network, but * does not reset the current bin data * * @param timeStamp */ public void updateBinnedDataListNoReset(int timeStamp) { this.binnedDataList.add(Arrays.copyOf(this.binnedData, this.getnChannels())); int tmpRNNTimeStamp = this.lastBinCompleteTime; tmpRNNTimeStamp += this.getBinTimeLength(); while (timeStamp > (tmpRNNTimeStamp + this.getBinTimeLength())) { int[] tmpArr = new int[this.getnChannels()]; this.binnedDataList.add(tmpArr); tmpRNNTimeStamp += this.getBinTimeLength(); } } /** * Removes the zero slices from the beginning and the ending and gives the resulting binned array list of arrays; * currently not used * * @return */ public ArrayList<int[]> processDataListSingleDigit() { // removes zero slices from the beginning and the ending if (this.binnedDataList.isEmpty()) { return this.binnedDataList; } boolean removeStart = true; ArrayList<int[]> tmpBinnedDataList = new ArrayList<>(); for (int[] currentList : this.binnedDataList) { int sum = RNNfilter.sumOfArray(currentList); if ((removeStart == true) & (sum != 0)) { removeStart = false; } if (!removeStart) { tmpBinnedDataList.add(currentList); } } // tmpBinnedDataList doesn't have zero frames at the beginning for (int i = tmpBinnedDataList.size() - 1; i > -1; i int sum = RNNfilter.sumOfArray(tmpBinnedDataList.get(i)); if (sum == 0) { tmpBinnedDataList.remove(i); } else { break; } } return tmpBinnedDataList; } public void resetBinnedDataList() { this.binnedDataList = new ArrayList<int[]>(); } /** * Process the RNN in a batch manner */ public void processRNNList() { if (this.binnedDataList.isEmpty()) { return; } FloatMatrix tempOutput; tempOutput = FloatMatrix.zeros(this.getnChannels()); for (int[] currentBinnedData : this.binnedDataList) { tempOutput = this.rnnetwork.output(RNNfilter.intToFloat(currentBinnedData)); } this.networkOutput = RNNfilter.DMToFloat(tempOutput); this.label = RNNfilter.indexOfMaxValue(this.networkOutput); } /** * Returns true if the channel, ear and neuron attributes of the event are ok * * @param channel1 * - frequency channel of the input event * @param ear1 * - the ear the input event is from * @param neuron1 * - the neuron the input event is from * @param filterType1 * - the filterType the input event is from * @return - true if all the inputs are not abnormal */ public boolean isAddressOk(int channel1, int ear1, int neuron1, int filterType1) { if ((channel1 < 0) | (channel1 > this.getnChannels())) { return false; } // making sure the channel value is not out of bounds if ((ear1 < 0) | (ear1 > this.getnEars())) { return false; } // making sure the ear value is out of bounds if ((neuron1 < 0) | (neuron1 > this.getnNeurons())) { return false; } // making sure the neuron value is not out of bounds if ((filterType1 < 0) | (filterType1 > this.getnFilterTypes())) { return false; } // making sure the filterType value is not out of bounds if (!this.isUseBothEars()) { if (ear1 != this.whichEar) { // if both ears are not to be used and the ear value is not what is asked for, // return false return false; } } if (!this.isUseAllNeurons()) { if (neuron1 != this.whichNeuron) { // if all neurons are not to be used and the neuron value is not what is // asked for, return false return false; } } if (!this.useBothFilterTypes) { if (filterType1 != this.whichFilter) { // if all filters are not to be used and the filter value is not what // was asked for, return false return false; } } return true; } /** * Processes the RNN network for continuous recording setting * * @param timeStamp * - the timestamp of the present event */ public void processRNN(int timeStamp) { long now = System.nanoTime(); FloatMatrix tempOutput = this.rnnetwork.output(RNNfilter.intToFloat(this.binnedData)); long dt = System.nanoTime() - now; // log.log(Level.INFO, String.format("%d nanoseconds for one frame computation", dt)); this.networkOutput = RNNfilter.DMToFloat(tempOutput); if (chip.getCanvas().getDisplayMethod() instanceof RollingCochleaGramDisplayMethod) { if (!addedDisplayMethodPropertyChangeListener) { chip.getCanvas().getDisplayMethod().getSupport().addPropertyChangeListener(this); addedDisplayMethodPropertyChangeListener = true; } // save outputs for rendering if (screenCleared) { // reset memory } // save results } this.label = RNNfilter.indexOfMaxValue(this.networkOutput); this.lastBinCompleteTime += this.getBinTimeLength(); this.resetBins(); // if the present timeStamp is very far from the last time RNN was processed, that means an appropriate number // of zero bins have to be sent to the network while (timeStamp > (this.lastBinCompleteTime + this.getBinTimeLength())) { tempOutput = this.rnnetwork.output(RNNfilter.intToFloat(this.binnedData)); this.networkOutput = RNNfilter.DMToFloat(tempOutput); this.rnnOutputList.add(this.networkOutput); this.label = RNNfilter.indexOfMaxValue(this.networkOutput); this.lastBinCompleteTime += this.getBinTimeLength(); } } /** * Resets the binnedData to zero */ public void resetBins() { Arrays.fill(this.binnedData, 0); // initialized the bin data array to zero } /** * Resets the internal states in the network */ public void resetNetwork() { this.rnnetwork.resetNetworkLayers(); } /** * Copies int array to a float array * * @param intArray * - 1 dimensional int array * @return floatArray - 1 dimensional float array */ public static float[] intToFloat(int[] intArray) { float[] floatArray = new float[intArray.length]; for (int i = 0; i < intArray.length; i++) { floatArray[i] = intArray[i]; } return floatArray; } /** * Copies a 1 dimensional FloatMatrix (jblas) into a 1 dimensional float array * * @param floatMatrix * - 1 dimensional float matrix, there is no check make sure the input is indeed 1 dimensional * @return 1 dimensional float array */ public static float[] DMToFloat(FloatMatrix floatMatrix) { int length = floatMatrix.length; float[] floatArray = new float[length]; for (int i = 0; i < length; i++) { floatArray[i] = floatMatrix.get(i); } return floatArray; } /** * Returns the index of the maximum value in the array * * @param input * @return */ public static int indexOfMaxValue(float[] input) { int index = 0; float tmpMax = input[0]; for (int i = 1; i < input.length; i++) { if (input[i] > tmpMax) { tmpMax = input[i]; index = i; } } return index; } /** * Returns the maximum value in the array * * @param input * @return */ public static float maxValue(float[] input) { float tmpMax = input[0]; for (int i = 1; i < input.length; i++) { if (input[i] > tmpMax) { tmpMax = input[i]; } } return tmpMax; } /** * Returns the maximum value in a 2D array * * @param input * @return */ public static int maxValueIn2DArray(int[][] input) { int output = 0; int xLength = input.length; int yLength = input[0].length; for (int x = 0; x < xLength; x++) { for (int y = 0; y < yLength; y++) { if (output < input[x][y]) { output = input[x][y]; } } } return output; } /** * Calculates the sum of elements in an integer array * * @param input * an integer array * @return sum of elements in input integer array */ public static int sumOfArray(int[] input) { int sum = 0; for (int i : input) { sum += i; } return sum; } /** * Returns an array with the sum of each array in an arraylist of arrays * * @param input * @return sum of array elements in arraylist */ public static int[] sumOfArrayList(ArrayList<int[]> input) { int size = input.size(); int[] output = new int[size]; for (int i = 0; i < size; i++) { output[i] = RNNfilter.sumOfArray(input.get(i)); } return output; } /** * Converts the arraylist holding the recorded features and prints it as an image in a new JFrame * * @param input * @throws IOException */ public void printDigit(ArrayList<int[]> input) throws IOException { if (input.isEmpty()) { return; } int xLength = input.size(); int yLength = input.get(0).length; int maxValue = 0; int[][] tmpImage = new int[xLength][yLength]; for (int i = 0; i < xLength; i++) { tmpImage[i] = input.get(i); } maxValue = RNNfilter.maxValueIn2DArray(tmpImage); int[][] tmpImageScaled = RNNfilter.rescale2DArray(tmpImage, 255 / maxValue); BufferedImage newImage = new BufferedImage(xLength, yLength, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < xLength; x++) { for (int y = 0; y < yLength; y++) { newImage.setRGB(x, y, tmpImageScaled[x][y]); } } ImageIcon icon = new ImageIcon(newImage); ScaledImagePanel scaledImage = new ScaledImagePanel(icon); JFrame frame = new JFrame(); frame.setSize(xLength, yLength); frame.add(scaledImage); frame.setVisible(true); } @Override public void propertyChange(PropertyChangeEvent pce) { if (pce.getPropertyName() == RollingCochleaGramDisplayMethod.EVENT_SCREEN_CLEARED) { screenCleared = true; } } /** * A class which helps scale the image to fit the size of the JFrame */ public class ScaledImagePanel extends JPanel { ImageIcon image; public ScaledImagePanel() { } public ScaledImagePanel(ImageIcon image1) { this.image = image1; } @Override protected void paintComponent(Graphics g) { BufferedImage scaledImage = getScaledImage(); super.paintComponent(g); g.drawImage(scaledImage, 0, 0, null); } private BufferedImage getScaledImage() { BufferedImage image = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D g2d = image.createGraphics(); g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY)); g2d.drawImage(this.image.getImage(), 0, 0, getWidth(), getHeight(), null); return image; } } /** * Rescales the values in an integer 2D array to an approximated integer 2D array * * @param input * @param scale * @return */ public static int[][] rescale2DArray(int[][] input, float scale) { int xLength = input.length; int yLength = input[0].length; int[][] output = new int[xLength][yLength]; for (int x = 0; x < xLength; x++) { for (int y = 0; y < yLength; y++) { output[x][y] = (int) scale * input[x][y]; } } return output; } /** * Annotates the frame with the activations of the softmax layer as a bar chart * * @param gl * @param width * @param height */ public void showActivations(GL2 gl, int width, int height) { if (this.networkOutput == null) { } else { float dx = (float) (width) / this.networkOutput.length; float dy = 0.8f * (height); gl.glBegin(GL.GL_LINE_STRIP); for (int i = 0; i < this.networkOutput.length; i++) { float tmpOutput = this.networkOutput[i]; float tmpOutputMax = RNNfilter.maxValue(this.networkOutput); float y_end = 1 + ((dy * tmpOutput) / tmpOutputMax); // draws the relative activations of the neurons in // the layer float x_start = 1 + (dx * i); float x_end = x_start + dx; gl.glVertex2f(x_start, 1); gl.glVertex2f(x_start, y_end); gl.glVertex2f(x_end, y_end); gl.glVertex2f(x_end, 1); } gl.glEnd(); } } /** * @return the nChannels */ public int getnChannels() { return nChannels; } /** * @return the nNeurons */ public int getnNeurons() { return nNeurons; } /** * @return the nEars */ public int getnEars() { return nEars; } /** * @return the binTimeLength */ public int getBinTimeLength() { return binTimeLength; } /** * @param binTimeLength1 * the binTimeLength to set */ public void setBinTimeLength(int binTimeLength1) { getPrefs().putInt("binTimeLength", binTimeLength1); getSupport().firePropertyChange("binTimeLength", this.binTimeLength, binTimeLength1); this.binTimeLength = binTimeLength1; } /** * @return the useBothEars */ public boolean isUseBothEars() { return useBothEars; } /** * @param useBothEars1 * the useBothEars to set */ public void setUseBothEars(boolean useBothEars1) { putBoolean("useBothEars", useBothEars1); this.useBothEars = useBothEars1; } /** * @return the chooseEar */ public int getChooseEar() { return chooseEar; } /** * @param chooseEar1 * the chooseEar to set */ public void setChooseEar(int chooseEar1) { getPrefs().putInt("chooseEar", chooseEar1); getSupport().firePropertyChange("chooseEar", this.chooseEar, chooseEar1); this.chooseEar = chooseEar1; if ((this.getChooseEar() > -1) & (this.getChooseEar() < this.getnEars())) { this.whichEar = this.getChooseEar(); } else { this.whichEar = (int) (Math.random() * (this.getnEars())); } } /** * @return the useAllNeurons */ public boolean isUseAllNeurons() { return useAllNeurons; } /** * @param useAllNeurons1 * the useAllNeurons to set */ public void setUseAllNeurons(boolean useAllNeurons1) { putBoolean("useAllNeurons", useAllNeurons1); this.useAllNeurons = useAllNeurons1; } /** * @return the chooseNeuron */ public int getChooseNeuron() { return chooseNeuron; } /** * @param chooseNeuron1 * the chooseNeuron to set */ public void setChooseNeuron(int chooseNeuron1) { getPrefs().putInt("chooseNeuron", chooseNeuron1); getSupport().firePropertyChange("chooseNeuron", this.chooseNeuron, chooseNeuron1); this.chooseNeuron = chooseNeuron1; if ((this.getChooseNeuron() > -1) & (this.getChooseNeuron() < this.getnNeurons())) { this.whichNeuron = this.getChooseNeuron(); } else { this.whichNeuron = (int) (Math.random() * (this.getnNeurons())); } } /** * @return the lastRNNXMLFile */ public String getLastRNNXMLFile() { return lastRNNXMLFile; } /** * @param lastRNNXMLFile1 * the lastRNNXMLFile to set */ public void setLastRNNXMLFile(String lastRNNXMLFile1) { putString("lastRNNXMLFile", lastRNNXMLFile1); this.lastRNNXMLFile = lastRNNXMLFile1; } /** * @return the binning */ public boolean isProcessingEnabled() { return processingEnabled; } /** * @param binning1 * the binning to set */ public void setProcessingEnabled(boolean binning1) { putBoolean("processingEnabled", binning1); boolean oldBinning = this.processingEnabled; this.processingEnabled = binning1; support.firePropertyChange("processingEnabled", oldBinning, binning1); } /** * @return the useBothFilterTypes */ public boolean isUseBothFilterTypes() { return useBothFilterTypes; } /** * @param useBothFilterTypes1 * the useBothFilterTypes to set */ public void setUseBothFilterTypes(boolean useBothFilterTypes1) { putBoolean("useBothFilterTypes", useBothFilterTypes1); this.useBothFilterTypes = useBothFilterTypes1; } /** * @return the chooseFilterType */ public int getChooseFilterType() { return chooseFilterType; } /** * @param chooseFilterType1 * the chooseFilterType to set */ public void setChooseFilterType(int chooseFilterType1) { getPrefs().putInt("chooseFilterType", chooseFilterType1); getSupport().firePropertyChange("chooseFilterType", this.chooseFilterType, chooseFilterType1); this.chooseFilterType = chooseFilterType1; if ((this.getChooseFilterType() > -1) & (this.getChooseFilterType() < this.getnFilterTypes())) { this.whichFilter = this.getChooseFilterType(); } else { this.whichFilter = (int) (Math.random() * (this.getnFilterTypes())); } } /** * @return the nFilterTypes */ public int getnFilterTypes() { return nFilterTypes; } /** * @return the whichFunction */ public int getWhichFunction() { return whichFunction; } public void ifFirstEventNotDone(int timeStamp, int channel) { this.firstEventTime = timeStamp; this.isFirstEventDone = true; this.lastBinCompleteTime = timeStamp; this.updateBin(channel); this.lastEventTime = timeStamp; } /** * @return the displayActivations */ public boolean isDisplayActivations() { return displayActivations; } /** * @param displayActivations * the displayActivations to set */ public void setDisplayActivations(boolean displayActivations) { putBoolean("displayActivations", displayActivations); this.displayActivations = displayActivations; } /** * @return the displayAccuracy */ public boolean isDisplayAccuracy() { return displayAccuracy; } /** * @param displayAccuracy * the displayAccuracy to set */ public void setDisplayAccuracy(boolean displayAccuracy) { putBoolean("displayAccuracy", displayAccuracy); this.displayAccuracy = displayAccuracy; } /** * @return the displayFeature */ public boolean isDisplayFeature() { return displayFeature; } /** * @param displayFeature * the displayFeature to set */ public void setDisplayFeature(boolean displayFeature) { putBoolean("displayFeature", displayFeature); this.displayFeature = displayFeature; } /** * @return the showPredictionOnlyIfGood */ public boolean isShowPredictionOnlyIfGood() { return showPredictionOnlyIfGood; } /** * @param showPredictionOnlyIfGood * the showPredictionOnlyIfGood to set */ public void setShowPredictionOnlyIfGood(boolean showPredictionOnlyIfGood) { putBoolean("showPredictionOnlyIfGood", showPredictionOnlyIfGood); this.showPredictionOnlyIfGood = showPredictionOnlyIfGood; } /** * @return the singleDigits */ public boolean isClickToProcess() { return clickToProcess; } /** * @param singleDigits * the singleDigits to set */ public void setClickToProcess(boolean clickToProcess) { putBoolean("clickToProcess", clickToProcess); this.clickToProcess = clickToProcess; if (!clickToProcess) { this.whichFunction = 0; } else { if (this.isBatchRNNProcess()) { this.whichFunction = 2; } else { this.whichFunction = 1; } } this.resetFilter(); } /** * @return the batchRNNProcess */ public boolean isBatchRNNProcess() { return batchRNNProcess; } /** * @param batchRNNProcess * the batchRNNProcess to set */ public void setBatchRNNProcess(boolean batchRNNProcess) { putBoolean("batchRNNProcess", batchRNNProcess); this.batchRNNProcess = batchRNNProcess; if (this.clickToProcess) { if (batchRNNProcess) { this.whichFunction = 2; } else { this.whichFunction = 1; } } this.resetFilter(); } /** * Implements a toggleBinning function which would be used to build the button with the same name * * @throws IOException */ synchronized public void toggleBinning() throws IOException { if ((this.getWhichFunction() == 2) & (this.isProcessingEnabled() == false)) { this.resetNetwork(); this.setProcessingEnabled(true); } else if ((this.getWhichFunction() == 2) & (this.isProcessingEnabled() == true)) { // if the filter was binning // the events before, then // stop binning and process // the digit recorded this.setProcessingEnabled(false); if (this.displayFeature) { this.printDigit(binnedDataList); } this.processRNNList(); this.resetBins(); this.rnnProcessTimeStampList = new ArrayList<>(); this.rnnOutputList = new ArrayList<>(); this.binnedDataList = new ArrayList<>(); this.counter = 0; this.counter1 = 0; this.isFirstEventDone = false; } if ((this.getWhichFunction() == 1) & (this.isProcessingEnabled() == false)) { this.resetNetwork(); this.setProcessingEnabled(true); } else if ((this.getWhichFunction() == 1) & (this.isProcessingEnabled() == true)) { this.setProcessingEnabled(false); if (this.displayFeature) { this.printDigit(binnedDataList); } this.resetBins(); this.rnnProcessTimeStampList = new ArrayList<>(); this.rnnOutputList = new ArrayList<>(); this.binnedDataList = new ArrayList<>(); this.counter = 0; this.counter1 = 0; this.isFirstEventDone = false; } } /** * Implements the toggleBinning button, runs the toggleBinning function * * @throws IOException */ public void doToggleBinning() throws IOException { this.toggleBinning(); } /** * Implements the function which would run when the RunRNN button is pressed; as suggested by Prof. Tobi */ public void doPressRunRNN() { log.info("RunRNN button pressed"); if ((this.getWhichFunction() == 1) | (this.getWhichFunction() == 2)) { this.resetNetwork(); this.setProcessingEnabled(true); } } /** * Implements the function which would run when the RunRNN button is released; as suggested by Prof. Tobi * * @throws IOException */ public void doReleaseRunRNN() throws IOException { log.info("RunRNN button released"); if ((this.getWhichFunction() == 1) | (this.getWhichFunction() == 2)) { this.setProcessingEnabled(false); if (this.displayFeature) { this.printDigit(binnedDataList); } if (this.getWhichFunction() == 2) { this.processRNNList(); } this.resetBins(); this.rnnProcessTimeStampList = new ArrayList<>(); this.rnnOutputList = new ArrayList<>(); this.binnedDataList = new ArrayList<>(); this.counter = 0; this.counter1 = 0; this.isFirstEventDone = false; } } /** * Implements the loadFromXML function as a button */ public void doLoadFromXML() { this.loadFromXML(); } }