answer stringlengths 17 10.2M |
|---|
package de.lmu.ifi.dbs.elki.application.visualization;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.SpinnerModel;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.apache.batik.util.SVGConstants;
import org.w3c.dom.Element;
import de.lmu.ifi.dbs.elki.application.AbstractApplication;
import de.lmu.ifi.dbs.elki.data.ClassLabel;
import de.lmu.ifi.dbs.elki.data.DoubleVector;
import de.lmu.ifi.dbs.elki.data.NumberVector;
import de.lmu.ifi.dbs.elki.data.VectorUtil;
import de.lmu.ifi.dbs.elki.database.AssociationID;
import de.lmu.ifi.dbs.elki.database.Database;
import de.lmu.ifi.dbs.elki.database.DistanceResultPair;
import de.lmu.ifi.dbs.elki.database.connection.DatabaseConnection;
import de.lmu.ifi.dbs.elki.database.connection.FileBasedDatabaseConnection;
import de.lmu.ifi.dbs.elki.distance.DoubleDistance;
import de.lmu.ifi.dbs.elki.distance.NumberDistance;
import de.lmu.ifi.dbs.elki.distance.distancefunction.DistanceFunction;
import de.lmu.ifi.dbs.elki.distance.distancefunction.EuclideanDistanceFunction;
import de.lmu.ifi.dbs.elki.logging.AbstractLoggable;
import de.lmu.ifi.dbs.elki.math.DoubleMinMax;
import de.lmu.ifi.dbs.elki.normalization.Normalization;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.ClassParameter;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.OptionID;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.ParameterException;
import de.lmu.ifi.dbs.elki.visualization.batikutil.JSVGSynchronizedCanvas;
import de.lmu.ifi.dbs.elki.visualization.batikutil.LazyCanvasResizer;
import de.lmu.ifi.dbs.elki.visualization.batikutil.NodeReplacer;
import de.lmu.ifi.dbs.elki.visualization.css.CSSClassManager.CSSNamingConflict;
import de.lmu.ifi.dbs.elki.visualization.savedialog.SVGSaveDialog;
import de.lmu.ifi.dbs.elki.visualization.scales.LinearScale;
import de.lmu.ifi.dbs.elki.visualization.style.PropertiesBasedStyleLibrary;
import de.lmu.ifi.dbs.elki.visualization.style.StyleLibrary;
import de.lmu.ifi.dbs.elki.visualization.svg.SVGPath;
import de.lmu.ifi.dbs.elki.visualization.svg.SVGPlot;
import de.lmu.ifi.dbs.elki.visualization.svg.SVGSimpleLinearAxis;
import de.lmu.ifi.dbs.elki.visualization.svg.SVGUtil;
/**
* User application to explore the k Nearest Neighbors for a given data set and
* distance function. When selecting one or more data entries, the nearest
* neighbors each are determined and visualized.
*
* <p>
* Reference:<br/>
*
* Elke Achtert, Thomas Bernecker, Hans-Peter Kriegel, Erich Schubert, Arthur
* Zimek:<br/>
*
* ELKI in Time: ELKI 0.2 for the Performance Evaluation of Distance Measures
* for Time Series.<br/>
*
* In Proc. 11th International Symposium on Spatial and Temporal Databases (SSTD
* 2009), Aalborg, Denmark, 2009.
* </p>
*
* <h3>Usage example:</h3>
*
* <p>
* Main invocation:<br/>
*
* <code>java -cp elki.jar de.lmu.ifi.dbs.elki.visualization.KNNExplorer</code>
* </p>
*
* <p>
* The application supports the usual parametrization, in particular parameters
* <code>-dbc.in</code> and <code>-explorer.distancefunction</code> to select an
* input file and the distance function to explore.
* </p>
*
* @author Erich Schubert
*
* @param <O> Object type
*/
public class KNNExplorer<O extends NumberVector<?, ?>, N extends NumberDistance<N, D>, D extends Number> extends AbstractApplication {
/**
* Parameter to specify the database connection to be used, must extend
* {@link de.lmu.ifi.dbs.elki.database.connection.DatabaseConnection}.
* <p>
* Key: {@code -dbc}
* </p>
* <p>
* Default value: {@link FileBasedDatabaseConnection}
* </p>
*/
private final ClassParameter<DatabaseConnection<O>> DATABASE_CONNECTION_PARAM = new ClassParameter<DatabaseConnection<O>>(OptionID.DATABASE_CONNECTION, DatabaseConnection.class, FileBasedDatabaseConnection.class.getName());
/**
* Optional Parameter to specify a normalization in order to use a database
* with normalized values.
* <p>
* Key: {@code -norm}
* </p>
*/
private final ClassParameter<Normalization<O>> NORMALIZATION_PARAM = new ClassParameter<Normalization<O>>(OptionID.NORMALIZATION, Normalization.class, true);
/**
* OptionID for {@link #DISTANCE_FUNCTION_PARAM}
*/
public static final OptionID DISTANCE_FUNCTION_ID = OptionID.getOrCreateOptionID("explorer.distancefunction", "Distance function to determine the distance between database objects.");
/**
* Parameter to specify the distance function to determine the distance
* between database objects, must extend
* {@link de.lmu.ifi.dbs.elki.distance.distancefunction.DistanceFunction}.
* <p>
* Key: {@code -explorer.distancefunction}
* </p>
* <p>
* Default value:
* {@link de.lmu.ifi.dbs.elki.distance.distancefunction.EuclideanDistanceFunction}
* </p>
*/
protected final ClassParameter<DistanceFunction<O, N>> DISTANCE_FUNCTION_PARAM = new ClassParameter<DistanceFunction<O, N>>(DISTANCE_FUNCTION_ID, DistanceFunction.class, EuclideanDistanceFunction.class.getName());
/**
* Holds the database connection to have the algorithm run with.
*/
private DatabaseConnection<O> databaseConnection;
/**
* Holds the instance of the distance function specified by
* {@link #DISTANCE_FUNCTION_PARAM}.
*/
private DistanceFunction<O, N> distanceFunction;
/**
* A normalization - per default no normalization is used.
*/
private Normalization<O> normalization = null;
/**
* KNN Explorer wrapper.
*/
public KNNExplorer() {
super();
// parameter database connection
addOption(DATABASE_CONNECTION_PARAM);
// Distance function
addOption(DISTANCE_FUNCTION_PARAM);
// parameter normalization
addOption(NORMALIZATION_PARAM);
}
/**
* @see de.lmu.ifi.dbs.elki.utilities.optionhandling.AbstractParameterizable#setParameters
*/
@Override
public List<String> setParameters(List<String> args) throws ParameterException {
List<String> remainingParameters = super.setParameters(args);
// database connection
databaseConnection = DATABASE_CONNECTION_PARAM.instantiateClass();
addParameterizable(databaseConnection);
remainingParameters = databaseConnection.setParameters(remainingParameters);
// instantiate distance function.
distanceFunction = DISTANCE_FUNCTION_PARAM.instantiateClass();
addParameterizable(distanceFunction);
remainingParameters = distanceFunction.setParameters(remainingParameters);
// normalization
if(NORMALIZATION_PARAM.isSet()) {
normalization = NORMALIZATION_PARAM.instantiateClass();
addParameterizable(normalization);
remainingParameters = normalization.setParameters(remainingParameters);
}
rememberParametersExcept(args, remainingParameters);
return remainingParameters;
}
@Override
public void run() throws IllegalStateException {
Database<O> db = databaseConnection.getDatabase(normalization);
(new ExplorerWindow()).run(db, distanceFunction);
}
/**
* Main method to run this wrapper.
*
* @param args the arguments to run this wrapper
*/
public static void main(String[] args) {
new KNNExplorer<DoubleVector, DoubleDistance, Double>().runCLIApplication(args);
}
/**
* Main window of KNN Explorer.
*
* @author Erich Schubert
*/
class ExplorerWindow extends AbstractLoggable {
/**
* Default Window Title
*/
private static final String WINDOW_TITLE_BASE = "ELKI k Nearest Neighbors Explorer";
/**
* Maximum resolution for plotted lines to improve performance for long time
* series.
*/
private static final int MAXRESOLUTION = 1000;
/**
* SVG graph object ID (for replacing)
*/
private static final String SERIESID = "series";
// The frame.
protected JFrame frame = new JFrame(WINDOW_TITLE_BASE);
// The spinner
protected JSpinner spinner;
// The list of series
private JList seriesList = new JList();
// The "Quit" button, to close the application.
protected JButton quitButton = new JButton("Quit");
// The "Export" button, to save the image
protected JButton saveButton = new JButton("Export");
// The SVG canvas.
protected JSVGSynchronizedCanvas svgCanvas = new JSVGSynchronizedCanvas();
// The plot
SVGPlot plot;
// Viewport
Element viewport;
// Dimensionality
protected int dim;
protected int k = 20;
// Scale
protected LinearScale s;
// The current database
protected Database<O> db;
// Distance cache
protected HashMap<Integer, Double> distancecache = new HashMap<Integer, Double>();
// Canvas scaling ratio
protected double ratio;
/**
* Holds the instance of the distance function specified by
* {@link #DISTANCE_FUNCTION_PARAM}.
*/
private DistanceFunction<O, N> distanceFunction;
/**
* Constructor.
*/
public ExplorerWindow() {
super(false);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// Create a panel and add the button, status label and the SVG canvas.
final JPanel bigpanel = new JPanel(new BorderLayout());
// set up spinner
SpinnerModel model = new SpinnerNumberModel(k, 1, 1000, 1);
spinner = new JSpinner(model);
JPanel spinnerPanel = new JPanel(new BorderLayout());
spinnerPanel.add(BorderLayout.WEST, new JLabel("k"));
spinnerPanel.add(BorderLayout.EAST, spinner);
// button panel
JPanel buttonPanel = new JPanel(new BorderLayout());
buttonPanel.add(BorderLayout.WEST, saveButton);
buttonPanel.add(BorderLayout.EAST, quitButton);
// set up cell renderer
seriesList.setCellRenderer(new SeriesLabelRenderer());
JPanel sidepanel = new JPanel(new BorderLayout());
sidepanel.add(BorderLayout.NORTH, spinnerPanel);
sidepanel.add(BorderLayout.CENTER, new JScrollPane(seriesList));
sidepanel.add(BorderLayout.SOUTH, buttonPanel);
bigpanel.add(BorderLayout.WEST, sidepanel);
bigpanel.add(BorderLayout.CENTER, svgCanvas);
frame.getContentPane().add(bigpanel);
spinner.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(@SuppressWarnings("unused") ChangeEvent e) {
k = (Integer) (spinner.getValue());
updateSelection();
}
});
seriesList.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
if(!e.getValueIsAdjusting()) {
updateSelection();
}
}
});
saveButton.addActionListener(new ActionListener() {
public void actionPerformed(@SuppressWarnings("unused") ActionEvent ae) {
SVGSaveDialog.showSaveDialog(plot, 512, 512);
}
});
quitButton.addActionListener(new ActionListener() {
public void actionPerformed(@SuppressWarnings("unused") ActionEvent e) {
frame.setVisible(false);
frame.dispose();
}
});
// display
frame.setSize(600, 600);
// resize listener
LazyCanvasResizer listener = new LazyCanvasResizer(frame) {
@Override
public void executeResize(double newratio) {
ratio = newratio;
updateSize();
updateSelection();
}
};
ratio = listener.getActiveRatio();
frame.addComponentListener(listener);
}
/**
* Update the SVG plot size.
*/
public void updateSize() {
SVGUtil.setAtt(plot.getRoot(), SVGConstants.SVG_VIEW_BOX_ATTRIBUTE, "0 0 " + ratio + " 1");
SVGUtil.setAtt(viewport, SVGConstants.SVG_WIDTH_ATTRIBUTE, ratio);
SVGUtil.setAtt(viewport, SVGConstants.SVG_HEIGHT_ATTRIBUTE, "1");
SVGUtil.setAtt(viewport, SVGConstants.SVG_VIEW_BOX_ATTRIBUTE, "-0.1 -0.1 " + (ratio + 0.2) + " 1.2");
}
/**
* Process the given Database and distance function.
*
* @param db Database
* @param distanceFunction Distance function
*/
public void run(Database<O> db, DistanceFunction<O, N> distanceFunction) {
this.db = db;
this.dim = db.dimensionality();
this.distanceFunction = distanceFunction;
this.distanceFunction.setDatabase(this.db, false, false);
double min = Double.MAX_VALUE;
double max = Double.MIN_VALUE;
for(Integer objID : db) {
O vec = db.get(objID);
DoubleMinMax mm = VectorUtil.getRangeDouble(vec);
min = Math.min(min, mm.getMin());
max = Math.max(max, mm.getMax());
}
this.s = new LinearScale(min, max);
this.frame.setTitle(distanceFunction.getClass().getSimpleName() + " - " + WINDOW_TITLE_BASE);
plot = new SVGPlot();
viewport = plot.svgElement(SVGConstants.SVG_SVG_TAG);
plot.getRoot().appendChild(viewport);
updateSize();
try {
StyleLibrary style = new PropertiesBasedStyleLibrary();
SVGSimpleLinearAxis.drawAxis(plot, viewport, this.s, 0.0, 1.0, 0.0, 0.0, true, false, style);
}
catch(CSSNamingConflict e) {
logger.exception(e);
}
plot.updateStyleElement();
// insert the actual data series.
Element egroup = plot.svgElement(SVGConstants.SVG_G_TAG);
SVGUtil.setAtt(egroup, SVGConstants.SVG_ID_ATTRIBUTE, SERIESID);
viewport.appendChild(egroup);
plot.putIdElement(SERIESID, egroup);
svgCanvas.setPlot(plot);
DefaultListModel m = new DefaultListModel();
for(Integer dbid : db) {
m.addElement(dbid);
}
seriesList.setModel(m);
frame.setVisible(true);
}
/**
* Process the users new selection.
*/
protected void updateSelection() {
Object[] sel = seriesList.getSelectedValues();
// prepare replacement tag.
Element newe = plot.svgElement(SVGConstants.SVG_G_TAG);
SVGUtil.setAtt(newe, SVGConstants.SVG_ID_ATTRIBUTE, SERIESID);
distancecache.clear();
for(Object o : sel) {
int idx = (Integer) o;
List<DistanceResultPair<N>> knn = db.kNNQueryForID(idx, k, distanceFunction);
double maxdist = knn.get(knn.size() - 1).getDistance().doubleValue();
// avoid division by zero.
if(maxdist == 0) {
maxdist = 1;
}
for(ListIterator<DistanceResultPair<N>> iter = knn.listIterator(knn.size()); iter.hasPrevious();) {
DistanceResultPair<N> pair = iter.previous();
Element line = plotSeries(pair.getID(), MAXRESOLUTION);
double dist = pair.getDistance().doubleValue() / maxdist;
Color color = getColor(dist);
String colstr = "#" + Integer.toHexString(color.getRGB()).substring(2);
String width = (pair.getID() == idx) ? "0.5%" : "0.2%";
SVGUtil.setStyle(line, "stroke: " + colstr + "; stroke-width: " + width + "; fill: none");
newe.appendChild(line);
// put into cache
Double known = distancecache.get(pair.getID());
if(known == null || dist < known) {
distancecache.put(pair.getID(), dist);
}
}
}
plot.scheduleUpdate(new NodeReplacer(newe, plot, SERIESID));
seriesList.repaint();
}
/**
* Get the appropriate color for the given distance.
*
* @param dist Distance
* @return Color
*/
Color getColor(double dist) {
Color color = new Color((int) (255 * dist), 0, (int) (255 * (1.0 - dist)));
return color;
}
/**
* Plot a single time series.
*
* @param idx Object index
* @param resolution Maximum number of steps to plot
* @return SVG element
*/
private Element plotSeries(int idx, int resolution) {
O series = db.get(idx);
double step = 1.0;
if(resolution < dim) {
step = (double) dim / (double) resolution;
}
SVGPath path = new SVGPath();
for(double id = 0; id < dim; id += step) {
int i = (int) Math.floor(id);
path.drawTo(ratio * (((double) i) / (dim - 1)), 1.0 - s.getScaled(series.doubleValue(i + 1)));
}
Element p = path.makeElement(plot);
return p;
}
/**
* Renderer for the labels, with coloring as in the plot.
*
* @author Erich Schubert
*/
private class SeriesLabelRenderer extends DefaultListCellRenderer {
/**
* Serial version
*/
private static final long serialVersionUID = 1L;
/**
* Constructor.
*/
public SeriesLabelRenderer() {
super();
}
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
String label = null;
if(label == null || label == "") {
label = db.getAssociation(AssociationID.LABEL, (Integer) value);
}
if(label == null || label == "") {
ClassLabel cls = db.getAssociation(AssociationID.CLASS, (Integer) value);
if(cls != null) {
label = cls.toString();
}
}
if(label == null || label == "") {
label = Integer.toString((Integer) value);
}
// setText(label);
Component renderer = super.getListCellRendererComponent(list, label, index, isSelected, cellHasFocus);
Double known = distancecache.get(value);
if(known != null) {
setBackground(getColor(known));
}
return renderer;
}
}
}
} |
package io.hentitydb.entity;
import com.google.common.base.Throwables;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import io.hentitydb.serialization.ByteBufferCodec;
import io.hentitydb.serialization.ClassCodec;
import io.hentitydb.serialization.ReadBuffer;
import io.hentitydb.serialization.WriteBuffer;
import io.hentitydb.store.AbstractFilter;
import io.hentitydb.store.Column;
import io.hentitydb.store.Filter;
import io.hentitydb.store.KeyColumn;
import io.hentitydb.store.TableName;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import static com.google.common.base.Preconditions.checkNotNull;
public class EntityFilter<K> extends AbstractFilter<K, byte[]> {
final static ByteBufferCodec BYTE_BUFFER_CODEC = new ByteBufferCodec(true);
final static ClassCodec CLASS_CODEC = new ClassCodec();
protected TableName tableName = null;
protected int limit = 0;
protected int numComponents;
protected ByteBuffer start;
protected ByteBuffer end;
protected QueryPredicate queryPredicate;
private transient KeyColumn<K, byte[]> previous = null;
private transient Map<String, Column<byte[]>> current = Maps.newHashMap();
private transient int count = 0;
private transient boolean done = false;
private final static boolean debug = false;
final static Maps.EntryTransformer<String, Column<byte[]>, ByteBuffer> COLUMN_TRANSFORMER =
(key, value) -> value != null ? ByteBuffer.wrap(value.getBytes()) : null;
final static Maps.EntryTransformer<String, IndexedColumn<byte[]>, ByteBuffer> INDEXED_COLUMN_TRANSFORMER =
(key, value) -> value != null ? ByteBuffer.wrap(value.getColumn().getBytes()) : null;
// Required for serialization
public EntityFilter() {
}
public EntityFilter(int numComponents, ByteBuffer start, ByteBuffer end,
QueryPredicate queryPredicate, int limit) {
this.numComponents = numComponents;
this.start = checkNotNull(start);
this.end = checkNotNull(end);
this.queryPredicate = queryPredicate;
this.limit = limit;
}
public EntityFilter(int numComponents, QueryPredicate queryPredicate, int limit) {
this.numComponents = numComponents;
this.start = ByteBuffer.allocate(0);
this.end = ByteBuffer.allocate(0);
this.queryPredicate = queryPredicate;
this.limit = limit;
}
protected EntityFilter(int numComponents, ByteBuffer start, ByteBuffer end,
QueryPredicate queryPredicate, int limit,
TableName tableName) {
this.tableName = tableName;
this.numComponents = numComponents;
this.start = checkNotNull(start);
this.end = checkNotNull(end);
this.queryPredicate = queryPredicate;
this.limit = limit;
}
protected EntityFilter(int numComponents, QueryPredicate queryPredicate, int limit,
TableName tableName) {
this.tableName = tableName;
this.numComponents = numComponents;
this.start = ByteBuffer.allocate(0);
this.end = ByteBuffer.allocate(0);
this.queryPredicate = queryPredicate;
this.limit = limit;
}
protected int getLimit() {
return limit;
}
protected int getCount() {
return count;
}
protected int getNumComponents() {
return numComponents;
}
protected KeyColumn<K, byte[]> getPreviousKeyColumn() {
return previous;
}
protected boolean isDone() {
return done;
}
protected void setDone(boolean done) {
this.done = done;
}
@Override
public void reset() {
previous = null;
current.clear();
count = 0;
done = false;
}
@Override
public boolean ignoreRemainingRow() {
return done;
}
@Override
public boolean filterKeyColumn(KeyColumn<K, byte[]> keyColumn) {
return filterKeyColumn(keyColumn, Optional.empty());
}
protected boolean filterKeyColumn(KeyColumn<K, byte[]> keyColumn, Optional<Boolean> matchesPrevious) {
final String methodName = "filterKeyColumn";
ByteBuffer columnName = ByteBuffer.wrap(keyColumn.getColumn().getRawName());
if (start.remaining() != 0 && compare(start, columnName) > 0) {
return false;
} else if (end.remaining() != 0 && compare(end, columnName) < 0) {
// we could have an optimization here to set done = true if
// all the element IDs are of fixed length (such as Long or Integer)
// which would allow element IDs to be comparable;
// however, most use cases use start and limit to get the next page
return false;
}
boolean filter = true;
//noinspection StatementWithEmptyBody
if (previous == null ||
(matchesPrevious.isPresent() && matchesPrevious.get()) ||
(previous.getColumn().getFamily().equals(keyColumn.getColumn().getFamily()) &&
compare(ByteBuffer.wrap(previous.getColumn().getRawName()), columnName) == 0)) {
// noop
} else {
if (checkColumns(current)) {
count++;
if (limit > 0 && count >= limit) {
done = true;
filter = false;
}
}
current.clear();
}
String valueName = getValueName(columnName);
// We may get a duplicate as filterKeyColumn will be called for multiple hfiles
// In that case keep the more recent one
// NOTE: this assumes columns are traversed in descending timestamp order
Column<byte[]> old = current.get(valueName);
if (old == null) {
current.put(valueName, keyColumn.getColumn());
}
previous = keyColumn;
return filter;
}
@Override
public boolean hasFilterRow() {
return queryPredicate != null;
}
@Override
public Set<Integer> filterRow(List<KeyColumn<K, byte[]>> columns) {
final String methodName = "filterRow";
Set<Integer> toKeepIndexes = Sets.newHashSetWithExpectedSize(columns.size());
// first group columns
Map<String, IndexedColumn<byte[]>> groupedColumns = Maps.newHashMap();
KeyColumn<K, byte[]> previous = null;
int count = 0;
int index = 0;
for (KeyColumn<K, byte[]> keyColumn : columns) {
ByteBuffer columnName = ByteBuffer.wrap(keyColumn.getColumn().getRawName());
//noinspection StatementWithEmptyBody
if (previous == null ||
(previous.getColumn().getFamily().equals(keyColumn.getColumn().getFamily()) &&
compare(ByteBuffer.wrap(previous.getColumn().getRawName()), columnName) == 0)) {
// noop
} else {
if (checkGroupedColumns(groupedColumns)) {
count++;
for (IndexedColumn<byte[]> indexedColumn : groupedColumns.values()) {
toKeepIndexes.add(indexedColumn.getIndex());
}
}
groupedColumns.clear();
}
String valueName = getValueName(columnName);
IndexedColumn<byte[]> old = groupedColumns.get(valueName);
if (old == null) {
groupedColumns.put(valueName, new IndexedColumn<>(index, keyColumn.getColumn()));
}
previous = keyColumn;
index++;
}
if (checkGroupedColumns(groupedColumns)) {
count++;
for (IndexedColumn<byte[]> indexedColumn : groupedColumns.values()) {
toKeepIndexes.add(indexedColumn.getIndex());
}
}
if (getLimit() > 0 && getCount() >= getLimit()) {
if (getCount() != count) {
if (debug) {
StringBuilder sb = new StringBuilder();
sb.append("WARNING: ");
sb.append(getKeyString(previous));
sb.append(" count mismatch, initial = ").append(getCount());
sb.append(", final = ").append(count);
System.out.println(sb.toString());
}
}
}
return toKeepIndexes;
}
private boolean checkColumns(Map<String, Column<byte[]>> columns) {
if (columns.isEmpty()) return false;
return queryPredicate == null || queryPredicate.evaluate(Maps.transformEntries(columns, COLUMN_TRANSFORMER));
}
private boolean checkGroupedColumns(Map<String, IndexedColumn<byte[]>> groupedColumns) {
if (groupedColumns.isEmpty()) return false;
return queryPredicate == null || queryPredicate.evaluate(Maps.transformEntries(groupedColumns, INDEXED_COLUMN_TRANSFORMER));
}
static class IndexedColumn<C> {
private final int index;
private final Column<C> column;
public IndexedColumn(int index, Column<C> column) {
this.index = index;
this.column = column;
}
public int getIndex() {
return index;
}
public Column<C> getColumn() {
return column;
}
}
@Override
public void encode(Filter<K, byte[]> value, WriteBuffer buffer) {
buffer.writeVarInt(numComponents);
buffer.writeVarInt(limit);
BYTE_BUFFER_CODEC.encode(start, buffer);
BYTE_BUFFER_CODEC.encode(end, buffer);
buffer.writeByte(queryPredicate != null ? 1 : 0);
if (queryPredicate != null) {
CLASS_CODEC.encode(queryPredicate.getClass(), buffer);
queryPredicate.encode(buffer);
}
}
@Override
public Filter<K, byte[]> decode(ReadBuffer buffer) {
try {
int numComponents = buffer.readVarInt();
int limit = buffer.readVarInt();
ByteBuffer start = BYTE_BUFFER_CODEC.decode(buffer);
ByteBuffer end = BYTE_BUFFER_CODEC.decode(buffer);
QueryPredicate queryPredicate = null;
if (buffer.readByte() == 1) {
final Class predicateClass = CLASS_CODEC.decode(buffer);
queryPredicate = (QueryPredicate) predicateClass.newInstance();
queryPredicate = queryPredicate.decode(buffer);
}
return new EntityFilter<>(numComponents, start, end, queryPredicate, limit);
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
public int compare(ByteBuffer o1, ByteBuffer o2) {
return EntityMapper.compare(numComponents, o1, o2);
}
public String getValueName(ByteBuffer columnName) {
return EntityMapper.getValueName(numComponents, columnName);
}
private String getKeyString(KeyColumn<K, byte[]> keyColumn) {
String tableString = tableName != null ? tableName.toString() : "";
String keyString = "N/A";
if (keyColumn != null) {
K key = keyColumn.getKey();
if (key != null) {
keyString = key.toString();
}
}
return "(" + tableString + ", " + keyString + ")";
}
} |
package io.kamax.mxisd.config;
import io.kamax.matrix.json.GsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ViewConfig {
private transient final Logger log = LoggerFactory.getLogger(ViewConfig.class);
public static class Session {
public static class Paths {
private String failure;
private String success;
public String getFailure() {
return failure;
}
public void setFailure(String failure) {
this.failure = failure;
}
public String getSuccess() {
return success;
}
public void setSuccess(String success) {
this.success = success;
}
}
public static class Local {
private Paths onTokenSubmit = new Paths();
public Paths getOnTokenSubmit() {
return onTokenSubmit;
}
public void setOnTokenSubmit(Paths onTokenSubmit) {
this.onTokenSubmit = onTokenSubmit;
}
}
public static class Remote {
private Paths onRequest = new Paths();
private Paths onCheck = new Paths();
public Paths getOnRequest() {
return onRequest;
}
public void setOnRequest(Paths onRequest) {
this.onRequest = onRequest;
}
public Paths getOnCheck() {
return onCheck;
}
public void setOnCheck(Paths onCheck) {
this.onCheck = onCheck;
}
}
private Local local = new Local();
private Local localRemote = new Local();
private Remote remote = new Remote();
public Session() {
local.onTokenSubmit.success = "classpath:/session/local/tokenSubmitSuccess.html";
local.onTokenSubmit.failure = "classpath:/session/local/tokenSubmitFailure.html";
localRemote.onTokenSubmit.success = "classpath:/session/localRemote/tokenSubmitSuccess.html";
localRemote.onTokenSubmit.failure = "classpath:/session/local/tokenSubmitFailure.html";
remote.onRequest.success = "classpath:/session/remote/requestSuccess.html";
remote.onRequest.failure = "classpath:/session/remote/requestFailure.html";
remote.onCheck.success = "classpath:/session/remote/checkSuccess.html";
remote.onCheck.failure = "classpath:/session/remote/checkFailure.html";
}
public Local getLocal() {
return local;
}
public void setLocal(Local local) {
this.local = local;
}
public Local getLocalRemote() {
return localRemote;
}
public void setLocalRemote(Local localRemote) {
this.localRemote = localRemote;
}
public Remote getRemote() {
return remote;
}
public void setRemote(Remote remote) {
this.remote = remote;
}
}
private Session session = new Session();
public Session getSession() {
return session;
}
public void setSession(Session session) {
this.session = session;
}
public void build() {
log.info("
log.info("Session: {}", GsonUtil.get().toJson(session));
}
} |
package io.outbound.sdk;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Set;
/**
* The PushNotification represents one notification send from Outbound to the device. A PushNotification
* is passed into the overridable methods of {@link OutboundService} allowing you to implement your own
* logic around notifications.
*/
public class PushNotification implements Parcelable {
private final static String TAG = BuildConfig.APPLICATION_ID;
private final static String SILENT_FIELD = "_oq";
private final static String UNINSTALL_TRACKER_FIELD = "_ogp";
private final static String TEST_FIELD = "_otm";
private final static String ID_FIELD = "_onid";
private final static String INSTANCE_ID_FIELD = "_oid";
private final static String LINK_FIELD = "_odl";
private final static String SOUND_FILE_FIELD = "_sf";
private final static String SOUND_FOLDER_FIELD = "_sfo";
private final static String SOUND_SILENT = "_silent";
private final static String SOUND_DEFAULT = "_soundDefault";
private final static String TITLE_FIELD = "title";
private final static String BODY_FIELD = "body";
private final static String CATEGORY_FIELD = "category";
private final static String PAYLOAD_FIELD = "payload";
private final static String LG_NOTIF_IMG_FIELD = "_lni";
private final static String LG_NOTIF_FOLDER_FIELD = "_lnf";
private final static String SM_NOTIF_IMG_FIELD = "_sni";
private final static String SM_NOTIF_FOLDER_FIELD = "_snf";
private boolean uninstallTracker;
private boolean test;
private boolean silent;
private boolean linkHandled = false;
private boolean mainActivityLaunched = false;
private int id;
private String instanceId;
private String link;
private String title;
private String body;
private String category;
private String lgNotifFolder;
private String lgNotifImage;
private String smNotifFolder;
private String smNotifImage;
private Boolean soundSilent = false;
private Boolean soundDefault = false;
private String soundFile;
private String soundFolder;
private JSONObject payload;
/** Required methods to implement {@link android.os.Parcelable} */
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public PushNotification createFromParcel(Parcel in) {
return new PushNotification(in);
}
public PushNotification[] newArray(int size) {
return new PushNotification[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
Bundle data = new Bundle();
data.putString(SILENT_FIELD, silent ? "true" : "false");
data.putString(UNINSTALL_TRACKER_FIELD, uninstallTracker ? "true" : "false");
data.putString(TEST_FIELD, test ? "true" : "false");
data.putString(ID_FIELD, id + "");
data.putString(INSTANCE_ID_FIELD, instanceId);
data.putString(TITLE_FIELD, title);
data.putString(BODY_FIELD, body);
data.putString(CATEGORY_FIELD, category);
data.putString(LINK_FIELD, link);
data.putString(LG_NOTIF_FOLDER_FIELD, lgNotifFolder);
data.putString(LG_NOTIF_IMG_FIELD, lgNotifImage);
data.putString(SM_NOTIF_FOLDER_FIELD, smNotifFolder);
data.putString(SM_NOTIF_IMG_FIELD, smNotifImage);
data.putString(SOUND_DEFAULT, soundDefault ? "true" : "false");
data.putString(SOUND_SILENT, soundSilent ? "true" : "false");
data.putString(SOUND_FILE_FIELD, soundFile);
data.putString(SOUND_FOLDER_FIELD, soundFolder);
if (payload != null) {
data.putString(PAYLOAD_FIELD, payload.toString());
}
dest.writeBundle(data);
}
public PushNotification(Parcel in) {
this(in.readBundle());
}
public PushNotification(Bundle data) {
Set<String> keys = data.keySet();
for(String key : keys) {
switch (key) {
case INSTANCE_ID_FIELD:
this.instanceId = data.getString(key);
break;
case SILENT_FIELD:
this.silent = keyIsTrue(data, key);
break;
case LINK_FIELD:
this.link = data.getString(key);
break;
case ID_FIELD:
this.id = Integer.parseInt(data.getString(key));
break;
case UNINSTALL_TRACKER_FIELD:
this.uninstallTracker = keyIsTrue(data, key);
break;
case TEST_FIELD:
this.test = keyIsTrue(data, key);
break;
case TITLE_FIELD:
this.title = data.getString(key);
break;
case BODY_FIELD:
this.body = data.getString(key);
break;
case CATEGORY_FIELD:
this.category = data.getString(key);
break;
case LG_NOTIF_FOLDER_FIELD:
this.lgNotifFolder = data.getString(key);
break;
case LG_NOTIF_IMG_FIELD:
this.lgNotifImage = data.getString(key);
break;
case SM_NOTIF_FOLDER_FIELD:
this.smNotifFolder = data.getString(key);
break;
case SM_NOTIF_IMG_FIELD:
this.smNotifImage = data.getString(key);
break;
case SOUND_SILENT:
this.soundSilent = keyIsTrue(data, key);
break;
case SOUND_DEFAULT:
this.soundDefault = keyIsTrue(data, key);
break;
case SOUND_FILE_FIELD:
this.soundFile = data.getString(key);
break;
case SOUND_FOLDER_FIELD:
this.soundFolder = data.getString(key);
break;
case PAYLOAD_FIELD:
try {
this.payload = new JSONObject(data.getString(key));
} catch (JSONException e) {
Log.e(TAG, "Exception processing notification payload.", e);
}
break;
}
}
}
public boolean isSilent() {
return silent;
}
public boolean isUninstallTracker() {
return uninstallTracker;
}
public boolean isTestMessage() {
return test;
}
public int getId() {
return id;
}
public String getInstanceId() {
return instanceId;
}
/**
* Get the deeplink sent with the notification if any.
*
* @return the URL or null
*/
public String getDeeplink() {
return link;
}
public String getTitle() {
return title;
}
public String getBody() {
return body;
}
public String getCategory() {
return category;
}
public JSONObject getPayload() {
return payload;
}
public String getLgNotifFolder() { return lgNotifFolder; }
public String getLgNotifImage() { return lgNotifImage; }
public String getSmNotifFolder() { return smNotifFolder; }
public String getSmNotifImage() { return smNotifImage; }
public Boolean getSoundSilent() { return soundSilent; }
public Boolean getSoundDefault() { return soundDefault; }
public String getSoundFile() { return soundFile; }
public String getSoundFolder() { return soundFolder; }
/**
* Determine if the deeplink in the notification (if any) has been handled by the SDK or not.
*
* @return
*/
public boolean linkHasBeenHandled() {
return linkHandled;
}
public void setLinkHandled() {
this.linkHandled = true;
}
public void setMainActivityLaunched() {
this.mainActivityLaunched = true;
}
/**
* Determine if the SDK fell back to the main activity when the notification was opened or not.
*
* @return
*/
public boolean wasMainActivityLaunched() {
return mainActivityLaunched;
}
/**
* Creates a {@link NotificationCompat.Builder} constructed with the customization provided by Outbound.
* @param context
* @return
*/
public NotificationCompat.Builder createNotificationBuilder(Context context) {
Resources resources = context.getResources();
PackageManager pm = context.getPackageManager();
ApplicationInfo appInfo = null;
try {
appInfo = pm.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
} catch (PackageManager.NameNotFoundException e) {
// since we are using context.getPackageName() this should never happen.
Log.e(TAG, "Tried to access app that doesn't exist.");
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
NotificationCompat.Builder builder;
String notificationChannelId = OutboundClient.getInstance().getNotificationChannelId();
if (notificationChannelId != null) {
builder = new NotificationCompat.Builder(context, notificationChannelId);
} else {
builder = new NotificationCompat.Builder(context);
}
if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) && (notificationChannelId == null)) {
// Warning: Notifications may not be delivered for Android 8+ (Oreo+) clients
Log.w(TAG, "Did you forget to provide a notification channel id? Notifications may not be delivered on sdk26+");
}
builder
.setAutoCancel(true)
.setStyle(new NotificationCompat.BigTextStyle().bigText(this.getBody() == null ? "" : this.getBody()))
.setContentText(this.getBody() == null ? "" : this.getBody())
.setContentTitle(this.getTitle() == null ? "" : this.getTitle());
try {
String image = this.getSmNotifImage();
String folder = this.getSmNotifFolder();
if (!TextUtils.isEmpty(image) && !TextUtils.isEmpty(folder)) {
int resId = resources.getIdentifier(image, folder, context.getPackageName());
if (resId != 0) {
builder.setSmallIcon(resId);
}
}
} catch (Exception e) {
Log.e(TAG, "Small icon doesn't exist");
if (appInfo != null) {
builder.setSmallIcon(appInfo.icon);
}
}
try {
String image = this.getLgNotifImage();
String folder = this.getLgNotifFolder();
Resources rs = pm.getResourcesForApplication(context.getPackageName());
if (!TextUtils.isEmpty(image) && !TextUtils.isEmpty(folder)) {
int resId = resources.getIdentifier(image, folder, context.getPackageName());
if (resId != 0) {
builder.setLargeIcon(BitmapFactory.decodeResource(rs, resId));
}
}
} catch (Exception e) {
Log.e(TAG, "Large icon doesn't exist");
}
try {
Uri media = null;
if (!this.getSoundSilent().equals(true)) {
if (this.getSoundDefault().equals(true)) {
media = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
} else {
int resId = resources.getIdentifier(this.getSoundFile(), this.getSoundFolder(), context.getPackageName());
if (resId != 0) {
media = Uri.parse("android.resource://" + context.getPackageName() + "/" + resId);
}
}
}
if (media != null) {
builder.setSound(media);
}
} catch (Exception e) {
Log.e(TAG, "Music asset does not exist");
}
// we set local only since the server already sends to all device tokens registered.
// until we investigate how this works it is better safe than sorry.
builder.setLocalOnly(true);
Intent intentToOpen = new Intent(context.getPackageName() + OutboundService.ACTION_OPEN_NOTIF);
intentToOpen.setPackage(context.getPackageName());
intentToOpen.putExtra(OutboundService.EXTRA_NOTIFICATION, this);
PendingIntent pIntent = PendingIntent.getService(context, 0, intentToOpen, PendingIntent.FLAG_ONE_SHOT);
builder.setContentIntent(pIntent);
if (this.getCategory() != null) {
builder.setCategory(this.getCategory());
}
return builder;
}
private boolean keyIsTrue(Bundle data, String key) {
if (data.containsKey(key)) {
String dataValue = data.getString(key);
return dataValue != null && dataValue.equals("true");
}
return false;
}
} |
package javax.time.calendar;
/**
* Strategy for resolving an invalid year-month-day to a valid one.
* <p>
* DateResolver is an interface and must be implemented with care
* to ensure other classes in the framework operate correctly.
* All implementations must be final, immutable and thread-safe.
*
* @author Michael Nascimento Santos
* @author Stephen Colebourne
*/
public interface DateResolver {
/**
* Resolves the combination of year, month and day into a date.
* <p>
* The purpose of resolution is to avoid invalid dates. Each of the three
* fields are individually valid. However, the day-of-month may not be
* valid for the associated month and year.
*
* @param year the year that was input, from MIN_YEAR to MAX_YEAR
* @param monthOfYear the month-of-year, not null
* @param dayOfMonth the proposed day-of-month, from 1 to 31
* @return the resolved date, never null
* @throws InvalidCalendarFieldException if the date cannot be resolved
*/
LocalDate resolveDate(int year, MonthOfYear monthOfYear, int dayOfMonth);
} |
package mcjty.rftools;
import cpw.mods.fml.common.eventhandler.Event;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import mcjty.rftools.blocks.blockprotector.BlockProtectorTileEntity;
import mcjty.rftools.blocks.blockprotector.BlockProtectors;
import mcjty.rftools.blocks.dimlets.DimletConfiguration;
import mcjty.rftools.blocks.environmental.PeacefulAreaManager;
import mcjty.rftools.dimension.DimensionInformation;
import mcjty.rftools.dimension.DimensionStorage;
import mcjty.rftools.dimension.RfToolsDimensionManager;
import mcjty.varia.Coordinate;
import mcjty.varia.GlobalCoordinate;
import net.minecraft.block.Block;
import net.minecraft.block.BlockBed;
import net.minecraft.entity.monster.IMob;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.Vec3;
import net.minecraft.world.ChunkPosition;
import net.minecraft.world.Explosion;
import net.minecraft.world.World;
import net.minecraftforge.event.entity.EntityEvent;
import net.minecraftforge.event.entity.living.LivingFallEvent;
import net.minecraftforge.event.entity.living.LivingSpawnEvent;
import net.minecraftforge.event.entity.player.AttackEntityEvent;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.event.world.BlockEvent;
import net.minecraftforge.event.world.ExplosionEvent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class ForgeEventHandlers {
@SubscribeEvent
public void onBlockBreakEvent(BlockEvent.BreakEvent event) {
int id = event.world.provider.dimensionId;
BlockProtectors blockProtectors = BlockProtectors.getProtectors(event.world);
Collection<GlobalCoordinate> protectors = blockProtectors.findProtectors(event.x, event.y, event.z, id, 2);
for (GlobalCoordinate protector : protectors) {
int cx = protector.getCoordinate().getX();
int cy = protector.getCoordinate().getY();
int cz = protector.getCoordinate().getZ();
TileEntity te = event.world.getTileEntity(cx, cy, cz);
if (te instanceof BlockProtectorTileEntity) {
BlockProtectorTileEntity blockProtectorTileEntity = (BlockProtectorTileEntity) te;
Coordinate relative = blockProtectorTileEntity.absoluteToRelative(event.x, event.y, event.z);
boolean b = blockProtectorTileEntity.isProtected(relative);
if (b) {
if (blockProtectorTileEntity.attemptHarvestProtection()) {
event.setCanceled(true);
} else {
blockProtectorTileEntity.removeProtection(relative);
}
return;
}
}
}
}
@SubscribeEvent
public void onDetonate(ExplosionEvent.Detonate event) {
int id = event.world.provider.dimensionId;
BlockProtectors blockProtectors = BlockProtectors.getProtectors(event.world);
Explosion explosion = event.explosion;
Collection<GlobalCoordinate> protectors = blockProtectors.findProtectors((int) explosion.explosionX, (int) explosion.explosionY, (int) explosion.explosionZ, id, (int) explosion.explosionSize);
if (protectors.isEmpty()) {
return;
}
List<ChunkPosition> affectedBlocks = event.getAffectedBlocks();
List<ChunkPosition> toremove = new ArrayList<ChunkPosition>();
Vec3 explosionVector = Vec3.createVectorHelper(explosion.explosionX, explosion.explosionY, explosion.explosionZ);
int rf = 0;
for (GlobalCoordinate protector : protectors) {
int cx = protector.getCoordinate().getX();
int cy = protector.getCoordinate().getY();
int cz = protector.getCoordinate().getZ();
TileEntity te = event.world.getTileEntity(cx, cy, cz);
if (te instanceof BlockProtectorTileEntity) {
BlockProtectorTileEntity blockProtectorTileEntity = (BlockProtectorTileEntity) te;
for (ChunkPosition block : affectedBlocks) {
Coordinate relative = blockProtectorTileEntity.absoluteToRelative(block.chunkPosX, block.chunkPosY, block.chunkPosZ);
boolean b = blockProtectorTileEntity.isProtected(relative);
if (b) {
Vec3 blockVector = Vec3.createVectorHelper(block.chunkPosX, block.chunkPosY, block.chunkPosZ);
double distanceTo = explosionVector.distanceTo(blockVector);
int rfneeded = blockProtectorTileEntity.attemptExplosionProtection((float) (distanceTo / explosion.explosionSize), explosion.explosionSize);
if (rfneeded > 0) {
toremove.add(block);
rf += rfneeded;
} else {
blockProtectorTileEntity.removeProtection(relative);
}
}
}
}
}
for (ChunkPosition block : toremove) {
affectedBlocks.remove(block);
}
RFTools.logDebug("RF Needed for one explosion:" + rf);
}
@SubscribeEvent
public void onAttackEntityEvent(AttackEntityEvent event) {
World world = event.entityPlayer.getEntityWorld();
int id = world.provider.dimensionId;
RfToolsDimensionManager dimensionManager = RfToolsDimensionManager.getDimensionManager(world);
if (dimensionManager.getDimensionInformation(id) != null) {
// RFTools dimension.
DimensionStorage storage = DimensionStorage.getDimensionStorage(world);
int energy = storage.getEnergyLevel(id);
if (energy <= 0) {
event.setCanceled(true);
}
}
}
@SubscribeEvent
public void onEntityConstructingEvent(EntityEvent.EntityConstructing event) {
if (event.entity instanceof EntityPlayer) {
PlayerExtendedProperties properties = new PlayerExtendedProperties();
event.entity.registerExtendedProperties(PlayerExtendedProperties.ID, properties);
}
}
@SubscribeEvent
public void onPlayerInterractEvent(PlayerInteractEvent event) {
if (event.action == PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK) {
World world = event.world;
if (!world.isRemote) {
Block block = world.getBlock(event.x, event.y, event.z);
if (block instanceof BlockBed) {
RfToolsDimensionManager dimensionManager = RfToolsDimensionManager.getDimensionManager(world);
if (dimensionManager.getDimensionInformation(world.provider.dimensionId) != null) {
// We are in an RFTools dimension.
switch (DimletConfiguration.bedBehaviour) {
case 0:
event.setCanceled(true);
RFTools.message(event.entityPlayer, "You cannot sleep in this dimension!");
break;
case 1:
// Just do the usual thing (this typically mean explosion).
break;
case 2:
event.setCanceled(true);
int meta = BedControl.getBedMeta(world, event.x, event.y, event.z);
if (meta != -1) {
BedControl.trySleep(world, event.entityPlayer, event.x, event.y, event.z, meta);
}
break;
}
}
}
}
}
}
@SubscribeEvent
public void onEntitySpawnEvent(LivingSpawnEvent.CheckSpawn event) {
World world = event.world;
int id = world.provider.dimensionId;
DimensionInformation dimensionInformation = null;
if (DimletConfiguration.preventSpawnUnpowered) {
RfToolsDimensionManager dimensionManager = RfToolsDimensionManager.getDimensionManager(world);
dimensionInformation = dimensionManager.getDimensionInformation(id);
if (dimensionInformation != null) {
// RFTools dimension.
DimensionStorage storage = DimensionStorage.getDimensionStorage(world);
int energy = storage.getEnergyLevel(id);
if (energy <= 0) {
event.setResult(Event.Result.DENY);
RFTools.logDebug("Dimension power low: Prevented a spawn of " + event.entity.getClass().getName());
}
}
}
if (event.entity instanceof IMob) {
Coordinate coordinate = new Coordinate((int) event.entity.posX, (int) event.entity.posY, (int) event.entity.posZ);
if (PeacefulAreaManager.isPeaceful(new GlobalCoordinate(coordinate, id))) {
event.setResult(Event.Result.DENY);
RFTools.logDebug("Peaceful manager: Prevented a spawn of " + event.entity.getClass().getName());
} else if (dimensionInformation != null && dimensionInformation.isPeaceful()) {
// RFTools dimension.
event.setResult(Event.Result.DENY);
RFTools.logDebug("Peaceful dimension: Prevented a spawn of " + event.entity.getClass().getName());
}
}
}
@SubscribeEvent
public void onLivingFallEvent(LivingFallEvent event) {
if (event.entity instanceof EntityPlayer) {
EntityPlayer player = (EntityPlayer) event.entity;
PlayerExtendedProperties playerExtendedProperties = PlayerExtendedProperties.getProperties(player);
if (!player.worldObj.isRemote) {
if (playerExtendedProperties.hasBuff(PlayerBuff.BUFF_FEATHERFALLING)) {
event.distance /= 2.0f;
} else if (playerExtendedProperties.hasBuff(PlayerBuff.BUFF_FEATHERFALLINGPLUS)) {
event.distance /= 8.0f;
}
}
}
}
} |
package org.anddev.andengine.engine.camera;
import org.anddev.andengine.input.touch.TouchEvent;
/**
* @author Nicolas Gramlich
* @since 15:48:11 - 24.06.2010
* TODO min/max(X/Y) values could be cached and only updated once the zoomfactor/center changed.
*/
public class ZoomCamera extends Camera {
// Constants
// Fields
private float mZoomFactor = 1.0f;
// Constructors
public ZoomCamera(final float pX, final float pY, final float pWidth, final float pHeight) {
super(pX, pY, pWidth, pHeight);
}
// Getter & Setter
public float getZoomFactor() {
return this.mZoomFactor;
}
public void setZoomFactor(final float pZoomFactor) {
this.mZoomFactor = pZoomFactor;
}
// Methods for/from SuperClass/Interfaces
@Override
public float getMinX() {
if(this.mZoomFactor == 1.0f) {
return super.getMinX();
} else {
final float centerX = this.getCenterX();
return centerX - (centerX - super.getMinX()) / this.mZoomFactor;
}
}
@Override
public float getMaxX() {
if(this.mZoomFactor == 1.0f) {
return super.getMaxX();
} else {
final float centerX = this.getCenterX();
return centerX + (super.getMaxX() - centerX) / this.mZoomFactor;
}
}
@Override
public float getMinY() {
if(this.mZoomFactor == 1.0f) {
return super.getMinY();
} else {
final float centerY = this.getCenterY();
return centerY - (centerY - super.getMinY()) / this.mZoomFactor;
}
}
@Override
public float getMaxY() {
if(this.mZoomFactor == 1.0f) {
return super.getMaxY();
} else {
final float centerY = this.getCenterY();
return centerY + (super.getMaxY() - centerY) / this.mZoomFactor;
}
}
@Override
public float getWidth() {
return super.getWidth() / this.mZoomFactor;
}
@Override
public float getHeight() {
return super.getHeight() / this.mZoomFactor;
}
@Override
public void convertSceneToHUDTouchEvent(final TouchEvent pSceneTouchEvent) {
final float x = (pSceneTouchEvent.getX() - this.getMinX()) * this.getZoomFactor();
final float y = (pSceneTouchEvent.getY() - this.getMinY()) * this.getZoomFactor();
pSceneTouchEvent.set(x, y);
}
@Override
public void convertHUDToSceneTouchEvent(final TouchEvent pHUDTouchEvent) {
final float x = pHUDTouchEvent.getX() / this.getZoomFactor() + this.getMinX();
final float y = pHUDTouchEvent.getY() / this.getZoomFactor() + this.getMinY();
pHUDTouchEvent.set(x, y);
}
// Methods
// Inner and Anonymous Classes
} |
package name.kevinross.tool;
import android.app.ActivityThread;
import android.content.Context;
import android.os.Debug;
import java.util.List;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import name.kevinross.tool.debuggable.DebuggableToolHelpers;
/**
* Abstract class that facilitates debugging of non-android-app java code. Extend this and
* implement AbstractTool#run(String[]) or AbstractTool#run(OptionSet) as the entry point for tool
* code. You must not have a default constructor: this particular mechanism means anything done in
* the default ctor app-side won't have any use on the tool-side as they will be different instances
* in different processes.
*
* To run your code, instantiate your class and call any of the runTool(*) methods.
*
* new YourTool().runTool("hello", "world");
* new YourTool().runTool("--flag", "param");
*
* To debug your code, a "builder" mechanism is used:
*
* new YourTool().setWaitForDebugger(true).runTool("hello", "world");
*
*/
public abstract class AbstractTool {
private boolean willWaitForDebugger = false;
private String[] args = new String[]{};
private ActivityThread thisActivityThread = null;
private Context thisContext = null;
protected OptionSet parsedArgs = null;
/**
* Get the context obtained via PackageManager inspecting the containing package
* @return
*/
protected Context getContext() {
return thisContext;
}
/**
* Get the activity thread for the current process
* @return
*/
protected ActivityThread getActivityThread() {
return thisActivityThread;
}
/**
* In client code, instantiate the class and call #runTool(*) or #runSuTool(*) to run code.
*/
public AbstractTool() {
}
private String getCommandLine(String... args) {
return DebuggableToolHelpers.getCommandLineForMainClass(this.getClass(), willWaitForDebugger, args);
}
/**
* Run the tool in a separate process with the given arguments
* @param args
* @return
*/
public List<String> runTool(String... args) {
return DebuggableToolHelpers.runCommand(false, getCommandLine(args));
}
public Thread runService(String... args) {
return DebuggableToolHelpers.runCommandInBackground(false, getCommandLine(args));
}
/**
* Run the tool in a separate process with the given arguments and context
* @param ctx
* @param args
* @return
*/
public List<String> runTool(Context ctx, String... args) {
return DebuggableToolHelpers.runCommand(false, ctx, getCommandLine(args));
}
public Thread runService(Context ctx, String... args) {
return DebuggableToolHelpers.runCommandInBackground(false, ctx, getCommandLine(args));
}
/**
* Run the tool in a separate process with the given arguments
* @param su run as root
* @param args
* @return
*/
public List<String> runTool(boolean su, String... args) {
return DebuggableToolHelpers.runCommand(su, getCommandLine(args));
}
public Thread runService(boolean su, String... args) {
return DebuggableToolHelpers.runCommandInBackground(su, getCommandLine(args));
}
/**
* Run the tool as root with the given context and arguments
* @param su run as root
* @param ctx
* @param args
* @return
*/
public List<String> runTool(boolean su, Context ctx, String... args) {
return DebuggableToolHelpers.runCommand(su, ctx, DebuggableToolHelpers.getCommandLineForMainClass(this.getClass(), willWaitForDebugger, args));
}
public Thread runService(boolean su, Context ctx, String... args) {
return DebuggableToolHelpers.runCommandInBackground(su, ctx, getCommandLine(args));
}
/**
* Run the tool as $uid with the given arguments (requires root to obtain $uid)
* @param uid
* @param args
* @return
*/
public List<String> runTool(int uid, String... args) {
return DebuggableToolHelpers.runCommand(true, uid, DebuggableToolHelpers.getCommandLineForMainClass(this.getClass(), willWaitForDebugger, args));
}
public Thread runService(int uid, String... args) {
return DebuggableToolHelpers.runCommandInBackground(true, uid, getCommandLine(args));
}
/**
* Run the tool as $uid with the given context and arguments (requires root to obtain $uid)
* @param uid
* @param ctx
* @param args
* @return
*/
public List<String> runTool(int uid, Context ctx, String... args) {
return DebuggableToolHelpers.runCommand(true, uid, ctx, DebuggableToolHelpers.getCommandLineForMainClass(this.getClass(), willWaitForDebugger, args));
}
public Thread runService(int uid, Context ctx, String... args) {
return DebuggableToolHelpers.runCommandInBackground(true, uid, ctx, getCommandLine(args));
}
/**
* Wait for the debugger to attach before running the tool's #run() method
* @param willWait
* @return
*/
public <I extends AbstractTool> I setWaitForDebugger(boolean willWait) {
willWaitForDebugger = willWait;
return (I)this;
}
public void setArgs(String[] args) {
this.args = args;
this.parsedArgs = getArgParser().parse(args);
}
protected String[] getArgs() {
return args;
}
public void setContext(Context ctx) {
thisContext = ctx;
}
public void setActivityThread(ActivityThread thread) {thisActivityThread = thread;}
public void start() {
if (willWaitForDebugger) {
Debug.waitForDebugger();
}
run(parsedArgs);
}
/**
* Implement this in client code as the main entry point
* @param parser
*/
protected abstract void run(OptionSet parser);
/**
* Implementing this to allow for validating parameters
* @return
*/
protected OptionParser getArgParser() {
return new OptionParser();
}
/**
* Implement this to override the process namd
* @return
*/
public String getAppName() {
return getClass().getName();
}
} |
package net.caseif.crosstitles;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* An API for sending titles to players.
*/
public class TitleUtil {
private static final String VERSION_STRING;
private static final boolean TITLE_SUPPORT;
// fields
private static Field entityPlayer_playerConnection;
// constructors
private static Constructor<?> packetPlayOutTitle_init_LL;
private static Constructor<?> packetPlayOutTitle_init_III;
// methods
private static Method chatSerializer_a;
private static Method craftPlayer_getHandle;
private static Method playerConnection_sendPacket;
// enum values
private static Object enumTitleAction_subtitle;
private static Object enumTitleAction_title;
static {
String[] array = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",");
VERSION_STRING = array.length == 4 ? array[3] + "." : "";
boolean titleSupport = true;
try {
// for specifying title type
@SuppressWarnings("unchecked")
Class<? extends Enum> enumTitleAction = (Class<? extends Enum>)getNmsClass("EnumTitleAction");
enumTitleAction_title = Enum.valueOf(enumTitleAction, "TITLE");
enumTitleAction_subtitle = Enum.valueOf(enumTitleAction, "SUBTITLE");
// constructors for the packet
Class<?> packetPlayOutTitle = getNmsClass("PacketPlayOutTitle");
packetPlayOutTitle_init_LL =
packetPlayOutTitle.getConstructor(enumTitleAction, getNmsClass("IChatBaseComponent"));
packetPlayOutTitle_init_III = packetPlayOutTitle.getConstructor(int.class, int.class, int.class);
// for getting an IChatBaseComponent from a String
chatSerializer_a = getNmsClass("ChatSerializer").getDeclaredMethod("a", String.class);
// for sending packets
craftPlayer_getHandle = getCraftClass("entity.CraftPlayer").getMethod("getHandle");
entityPlayer_playerConnection = getNmsClass("EntityPlayer").getDeclaredField("playerConnection");
playerConnection_sendPacket =
getNmsClass("PlayerConnection").getMethod("sendPacket", getNmsClass("Packet"));
}
catch (ClassNotFoundException ex) {
titleSupport = false;
}
catch (NoSuchFieldException ex) {
titleSupport = false;
}
catch (NoSuchMethodException ex) {
titleSupport = false;
}
TITLE_SUPPORT = titleSupport;
}
/**
* Returns whether titles are supported on the current server.
* @return whether titles are supported on the current server
*/
public static boolean areTitlesSupported() {
return TITLE_SUPPORT;
}
private static void sendTitle(Player player, String title, ChatColor color, boolean sub) {
if (TITLE_SUPPORT) {
String json = "{text:\"" + title + "\"";
if (color != null) { // append color info
json += ",color:\"" + color.name().toLowerCase() + "\"";
}
json += "}";
try {
Object packet = packetPlayOutTitle_init_LL.newInstance(
// the type of information contained by the packet
sub ? enumTitleAction_subtitle : enumTitleAction_title,
// the serialized JSON to send via the packet
chatSerializer_a.invoke(null, json)
);
Object vanillaPlayer = craftPlayer_getHandle.invoke(player);
Object playerConnection = entityPlayer_playerConnection.get(vanillaPlayer);
playerConnection_sendPacket.invoke(playerConnection, packet);
}
catch (IllegalAccessException ex) {
ex.printStackTrace();
}
catch (InstantiationException ex) {
ex.printStackTrace();
}
catch (InvocationTargetException ex) {
ex.printStackTrace();
}
}
}
/**
* Sends a title to a player.
* @param player the player to send the title to
* @param title the content of the title
* @param color the color of the title
*/
public static void sendTitle(Player player, String title, ChatColor color) {
sendTitle(player, title, color, false);
}
/**
* Sends a subtitle to a player if one is already displaying; otherwise sets
* the subtitle to display when a title is next sent.
* @param player the player to send the subtitle to
* @param subtitle the content of the subtitle
* @param color the color of the subtitle
*/
public static void sendSubtitle(Player player, String subtitle, ChatColor color) {
sendTitle(player, subtitle, color, true);
}
/**
* Sets the timing for the current title if one is displayinmg; otherwise
* sets the timing for the next title sent.
* @param player the player to set title timing for
* @param fadeIn the time in ticks the title should fade in over (default
* 20)
* @param stay the time in ticks the title should remain on the screen for
* between fades (default 60)
* @param fadeOut the time in ticks the title should fade out over (default
* 20)
*/
public static void sendTimes(Player player, int fadeIn, int stay, int fadeOut) {
if (TITLE_SUPPORT) {
try {
Object packet = packetPlayOutTitle_init_III.newInstance(fadeIn, stay, fadeOut);
Object vanillaPlayer = craftPlayer_getHandle.invoke(player);
Object playerConnection = entityPlayer_playerConnection.get(vanillaPlayer);
playerConnection_sendPacket.invoke(playerConnection, packet);
}
catch (IllegalAccessException ex) {
ex.printStackTrace();
}
catch (InstantiationException ex) {
ex.printStackTrace();
}
catch (InvocationTargetException ex) {
ex.printStackTrace();
}
}
}
/**
* Sends a title and subtitle to a player.
* @param player the player to send the title to
* @param title the content of the title
* @param titleColor the color of the title
* @param subtitle the content of the subtitle
* @param subColor the color of the subtitle
*/
public static void sendTitle(Player player,
String title, ChatColor titleColor,
String subtitle, ChatColor subColor) {
sendSubtitle(player, subtitle, subColor);
sendTitle(player, title, titleColor);
}
/**
* Sends a title and subtitle with the given timing to a player.
* @param player the player to send the title to
* @param title the content of the title
* @param titleColor the color of the title
* @param subtitle the content of the subtitle
* @param subColor the color of the subtitle
* @param fadeIn the time in ticks the title should fade in over (default
* 20)
* @param stay the time in ticks the title should remain on the screen for
* between fades (default 60)
* @param fadeOut the time in ticks the title should fade out over (default
* 20)
*/
public static void sendTitle(Player player,
String title, ChatColor titleColor,
String subtitle, ChatColor subColor,
int fadeIn, int stay, int fadeOut) {
sendTimes(player, fadeIn, stay, fadeOut);
sendSubtitle(player, subtitle, subColor);
sendTitle(player, title, titleColor);
}
/**
* Sends a title and subtitle with the given timing to a player.
* @param player the player to send the title to
* @param title the content of the title
* @param titleColor the color of the title
* @param fadeIn the time in ticks the title should fade in over (default
* 20)
* @param stay the time in ticks the title should remain on the screen for
* between fades (default 60)
* @param fadeOut the time in ticks the title should fade out over (default
* 20)
*/
public static void sendTitle(Player player,
String title, ChatColor titleColor,
int fadeIn, int stay, int fadeOut) {
sendTimes(player, fadeIn, stay, fadeOut);
sendTitle(player, title, titleColor);
}
/**
* Retrieves a class by the given name from the package
* <code>net.minecraft.server</code>.
*
* @param name the class to retrieve
* @return the class object from the package
* <code>net.minecraft.server</code>
* @throws ClassNotFoundException if the class does not exist in the
* package
*/
private static Class<?> getNmsClass(String name) throws ClassNotFoundException {
String className = "net.minecraft.server." + VERSION_STRING + name;
return Class.forName(className);
}
/**
* Retrieves a class by the given name from the package
* <code>org.bukkit.craftbukkit</code>.
*
* @param name the class to retrieve
* @return the class object from the package
* <code>org.bukkit.craftbukkit</code>
* @throws ClassNotFoundException if the class does not exist in the
* package
*/
private static Class<?> getCraftClass(String name) throws ClassNotFoundException {
String className = "org.bukkit.craftbukkit." + VERSION_STRING + name;
return Class.forName(className);
}
} |
package net.dean.jraw.http;
import java.io.IOException;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.Proxy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.Authenticator;
import okhttp3.Credentials;
import okhttp3.HttpUrl;
import okhttp3.JavaNetCookieJar;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Route;
import okio.BufferedSink;
/**
* Provides a concrete HttpAdapter implementation using Square's OkHttp
*/
public final class OkHttpAdapter implements HttpAdapter<OkHttpClient> {
private static final Protocol DEFAULT_PROTOCOL = Protocol.SPDY_3;
private static final Protocol FALLBACK_PROTOCOL = Protocol.HTTP_1_1;
private static OkHttpClient newOkHttpClient() {
TimeUnit unit = TimeUnit.SECONDS;
int timeout = 10;
return new OkHttpClient.Builder()
.connectTimeout(timeout, unit)
.readTimeout(timeout, unit)
.writeTimeout(timeout, unit)
.build();
}
private OkHttpClient http;
private CookieManager cookieManager;
private Map<String, String> defaultHeaders;
private boolean isRawJson;
public OkHttpAdapter() {
this(DEFAULT_PROTOCOL);
}
public OkHttpAdapter(Protocol protocol) {
this(newOkHttpClient(), protocol);
}
public OkHttpAdapter(OkHttpClient httpClient, Protocol protocol) {
this.http = httpClient;
this.cookieManager = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
this.defaultHeaders = new HashMap<>();
List<Protocol> protocolList = new ArrayList<>();
protocolList.add(FALLBACK_PROTOCOL);
if (FALLBACK_PROTOCOL != protocol) {
protocolList.add(protocol);
}
http = http.newBuilder()
.protocols(protocolList)
.cookieJar(new JavaNetCookieJar(cookieManager))
.build();
}
@Override
public RestResponse execute(HttpRequest request) throws IOException {
OkHttpClient perRequestClient = http;
if (request.isUsingBasicAuth()) {
BasicAuthenticator authenticator = new BasicAuthenticator(request.getBasicAuthData());
perRequestClient = http.newBuilder().authenticator(authenticator).build();
}
HttpUrl url = HttpUrl.get(request.getUrl());
if (isRawJson) {
HttpUrl.Builder urlBuilder = HttpUrl.get(request.getUrl()).newBuilder();
urlBuilder.addQueryParameter("raw_json", "1");
url = urlBuilder.build();
}
Request.Builder builder = new Request.Builder()
.method(request.getMethod(), request.getBody() == null ? null : new OkHttpRequestBody(request.getBody()))
.url(url)
.headers(request.getHeaders());
Response response = perRequestClient.newCall(builder.build()).execute();
return new RestResponse(request,
response.body().string(),
response.headers(),
response.code(),
response.message(),
response.protocol().toString().toUpperCase());
}
@Override
public int getConnectTimeout() {
return http.connectTimeoutMillis();
}
@Override
public void setConnectTimeout(long timeout, TimeUnit unit) {
http = http.newBuilder().connectTimeout(timeout, unit).build();
}
@Override
public int getReadTimeout() {
return http.readTimeoutMillis();
}
@Override
public void setReadTimeout(long timeout, TimeUnit unit) {
http = http.newBuilder().readTimeout(timeout, unit).build();
}
@Override
public int getWriteTimeout() {
return http.writeTimeoutMillis();
}
@Override
public void setWriteTimeout(long timeout, TimeUnit unit) {
http = http.newBuilder().writeTimeout(timeout, unit).build();
}
@Override
public boolean isFollowingRedirects() {
return http.followRedirects();
}
@Override
public void setFollowRedirects(boolean flag) {
http = http.newBuilder().followRedirects(flag).build();
}
@Override
public Proxy getProxy() {
return http.proxy();
}
@Override
public void setProxy(Proxy proxy) {
http = http.newBuilder().proxy(proxy).build();
}
@Override
public CookieManager getCookieManager() {
return cookieManager;
}
@Override
public void setCookieManager(CookieManager manager) {
this.cookieManager = manager;
http = http.newBuilder().cookieJar(new JavaNetCookieJar(cookieManager)).build();
}
@Override
public Map<String, String> getDefaultHeaders() {
return defaultHeaders;
}
@Override
public OkHttpClient getNativeClient() {
return http;
}
/**
* Response body encoding: For legacy reasons, all reddit JSON response bodies currently have
* <, >, and & replaced with &lt;, &gt;, and &amp;, respectively.
*
* @param rawJson True to have JSON body characters <, >, and & replaced with
* &lt;, &gt;, and &amp;, respectively. False to use encoded
* characters in JSON bodies
*/
public void setRawJson(boolean rawJson) {
isRawJson = rawJson;
}
/** Mirrors a JRAW RequestBody to an OkHttp RequestBody */
private static class OkHttpRequestBody extends okhttp3.RequestBody {
private RequestBody mirror;
private MediaType contentType = null; // Lazily initialized
public OkHttpRequestBody(RequestBody mirror) {
this.mirror = mirror;
}
@Override
public MediaType contentType() {
if (mirror.contentType() == null)
return null;
if (contentType != null)
return contentType;
contentType = MediaType.parse(mirror.contentType().toString());
return contentType;
}
@Override
public long contentLength() {
return mirror.contentLength();
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
mirror.writeTo(sink);
}
}
private static class BasicAuthenticator implements Authenticator {
private final BasicAuthData data;
public BasicAuthenticator(BasicAuthData data) {
this.data = data;
}
@Override
public Request authenticate(Route route, Response response) throws IOException {
String credential = Credentials.basic(data.getUsername(), data.getPassword());
String header = response.code() == 407 ? "Proxy-Authorization" : "Authorization";
return response.request().newBuilder().header(header, credential).build();
}
}
} |
package org.appwork.utils.swing.dialog;
import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.HashMap;
import javax.swing.AbstractAction;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.KeyStroke;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import net.miginfocom.swing.MigLayout;
import org.appwork.storage.JSonStorage;
import org.appwork.utils.BinaryLogic;
import org.appwork.utils.locale.APPWORKUTILS;
import org.appwork.utils.logging.Log;
import org.appwork.utils.swing.LockPanel;
import org.appwork.utils.swing.SwingUtils;
public abstract class AbstractDialog<T> extends TimerDialog implements ActionListener, WindowListener {
private static final long serialVersionUID = 1831761858087385862L;
private static final HashMap<String, Integer> SESSION_DONTSHOW_AGAIN = new HashMap<String, Integer>();
/**
* @return
*/
private static Integer getSessionDontShowAgainValue(final String key) {
final Integer ret = AbstractDialog.SESSION_DONTSHOW_AGAIN.get(key);
if (ret == null) { return -1; }
return ret;
}
public static void resetDialogInformations() {
try {
AbstractDialog.SESSION_DONTSHOW_AGAIN.clear();
JSonStorage.getStorage("Dialogs").clear();
} catch (final Exception e) {
Log.exception(e);
}
}
protected JButton cancelButton;
private final String cancelOption;
private JPanel defaultButtons;
private JCheckBox dontshowagain;
protected int flagMask;
private final ImageIcon icon;
private boolean initialized = false;
protected JButton okButton;
private final String okOption;
protected JComponent panel;
private int returnBitMask = 0;
public AbstractDialog(final int flag, final String title, final ImageIcon icon, final String okOption, final String cancelOption) {
super(Dialog.getInstance().getParentOwner());
this.flagMask = flag;
this.setTitle(title);
this.icon = BinaryLogic.containsAll(flag, Dialog.STYLE_HIDE_ICON) ? null : icon;
this.okOption = okOption == null ? APPWORKUTILS.ABSTRACTDIALOG_BUTTON_OK.s() : okOption;
this.cancelOption = cancelOption == null ? APPWORKUTILS.ABSTRACTDIALOG_BUTTON_CANCEL.s() : cancelOption;
}
/* this function will init and show the dialog */
private void _init() {
dont: if (BinaryLogic.containsAll(this.flagMask, Dialog.STYLE_SHOW_DO_NOT_DISPLAY_AGAIN)) {
try {
final int i = BinaryLogic.containsAll(this.flagMask, Dialog.LOGIC_DONT_SHOW_AGAIN_DELETE_ON_EXIT) ? AbstractDialog.getSessionDontShowAgainValue(this.getDontShowAgainKey()) : JSonStorage.getStorage("Dialogs").get(this.getDontShowAgainKey(), -1);
if (i >= 0) {
// filter saved return value
int ret = i & (Dialog.RETURN_OK | Dialog.RETURN_CANCEL);
// add flags
ret |= Dialog.RETURN_DONT_SHOW_AGAIN | Dialog.RETURN_SKIPPED_BY_DONT_SHOW;
/*
* if LOGIC_DONT_SHOW_AGAIN_IGNORES_CANCEL or
* LOGIC_DONT_SHOW_AGAIN_IGNORES_OK are used, we check here
* if we should handle the dont show again feature
*/
if (BinaryLogic.containsAll(this.flagMask, Dialog.LOGIC_DONT_SHOW_AGAIN_IGNORES_CANCEL) && BinaryLogic.containsAll(ret, Dialog.RETURN_CANCEL)) {
break dont;
}
if (BinaryLogic.containsAll(this.flagMask, Dialog.LOGIC_DONT_SHOW_AGAIN_IGNORES_OK) && BinaryLogic.containsAll(ret, Dialog.RETURN_OK)) {
break dont;
}
this.returnBitMask = ret;
return;
}
} catch (final Exception e) {
Log.exception(e);
}
}
try {
if (Dialog.getInstance().getParentOwner() != null) {
LockPanel.create(Dialog.getInstance().getParentOwner()).lock(500);
}
} catch (final Exception e) {
}
if (Dialog.getInstance().getParentOwner() == null || !Dialog.getInstance().getParentOwner().isShowing()) {
this.setAlwaysOnTop(true);
}
// The Dialog Modal
this.setModal(true);
// Layout manager
this.setLayout(new MigLayout("ins 5", "[]", "[fill,grow][]"));
// Dispose dialog on close
this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
this.addWindowListener(this);
// create panel for the dialog's buttons
this.defaultButtons = this.getDefaultButtonPanel();
this.okButton = new JButton(this.okOption);
/*
* We set the focus on the ok button. if no ok button is shown, we set
* the focus on cancel button
*/
JButton focus = this.okButton;
this.cancelButton = new JButton(this.cancelOption);
// add listeners here
this.okButton.addActionListener(this);
this.cancelButton.addActionListener(this);
// add icon if available
if (this.icon != null) {
this.add(new JLabel(this.icon), "split 2,alignx left,aligny center,shrinkx,gapright 10");
}
// Layout the dialog content and add it to the contentpane
this.panel = this.layoutDialogContent();
this.add(this.panel, "pushx,growx,pushy,growy,spanx,aligny center,wrap");
// add the countdown timer
this.add(this.timerLbl, "split 3,growx,hidemode 2");
if (BinaryLogic.containsAll(this.flagMask, Dialog.STYLE_SHOW_DO_NOT_DISPLAY_AGAIN)) {
this.dontshowagain = new JCheckBox(APPWORKUTILS.ABSTRACTDIALOG_STYLE_SHOW_DO_NOT_DISPLAY_AGAIN.s());
this.dontshowagain.setHorizontalAlignment(SwingConstants.TRAILING);
this.dontshowagain.setHorizontalTextPosition(SwingConstants.LEADING);
this.add(this.dontshowagain, "growx,pushx,alignx right,gapleft 20");
} else {
this.add(Box.createHorizontalGlue(), "growx,pushx,alignx right,gapleft 20");
}
this.add(this.defaultButtons, "alignx right,shrinkx");
if ((this.flagMask & Dialog.BUTTONS_HIDE_OK) == 0) {
// Set OK as defaultbutton
this.getRootPane().setDefaultButton(this.okButton);
this.okButton.addHierarchyListener(new HierarchyListener() {
public void hierarchyChanged(final HierarchyEvent e) {
if ((e.getChangeFlags() & HierarchyEvent.PARENT_CHANGED) != 0) {
final JButton defaultButton = (JButton) e.getComponent();
final JRootPane root = SwingUtilities.getRootPane(defaultButton);
if (root != null) {
root.setDefaultButton(defaultButton);
}
}
}
});
focus = this.okButton;
this.defaultButtons.add(this.okButton, "alignx right,tag ok,sizegroup confirms");
}
if (!BinaryLogic.containsAll(this.flagMask, Dialog.BUTTONS_HIDE_CANCEL)) {
this.defaultButtons.add(this.cancelButton, "alignx right,tag cancel,sizegroup confirms");
if (BinaryLogic.containsAll(this.flagMask, Dialog.BUTTONS_HIDE_OK)) {
this.getRootPane().setDefaultButton(this.cancelButton);
this.cancelButton.requestFocusInWindow();
// focus is on cancel if OK is hidden
focus = this.cancelButton;
}
}
this.addButtons(this.defaultButtons);
if (BinaryLogic.containsAll(this.flagMask, Dialog.LOGIC_COUNTDOWN)) {
// show timer
this.initTimer(Dialog.getInstance().getCoundownTime());
} else {
this.timerLbl.setVisible(false);
}
// pack dialog
this.invalidate();
// this.setMinimumSize(this.getPreferredSize());
this.pack();
this.setResizable(true);
this.setMinimumSize(this.getPreferredSize());
this.toFront();
if (this.getDesiredSize() != null) {
this.setSize(this.getDesiredSize());
}
if (Dialog.getInstance().getParentOwner() == null || !Dialog.getInstance().getParentOwner().isDisplayable() || !Dialog.getInstance().getParentOwner().isVisible()) {
final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation(new Point((int) (screenSize.getWidth() - this.getWidth()) / 2, (int) (screenSize.getHeight() - this.getHeight()) / 2));
} else if (Dialog.getInstance().getParentOwner().getExtendedState() == Frame.ICONIFIED) {
// dock dialog at bottom right if mainframe is not visible
final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation(new Point((int) (screenSize.getWidth() - this.getWidth() - 20), (int) (screenSize.getHeight() - this.getHeight() - 60)));
} else {
this.setLocation(SwingUtils.getCenter(Dialog.getInstance().getParentOwner(), this));
}
// register an escape listener to cancel the dialog
final KeyStroke ks = KeyStroke.getKeyStroke("ESCAPE");
focus.getInputMap().put(ks, "ESCAPE");
focus.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(ks, "ESCAPE");
focus.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(ks, "ESCAPE");
focus.getActionMap().put("ESCAPE", new AbstractAction() {
private static final long serialVersionUID = -6666144330707394562L;
public void actionPerformed(final ActionEvent e) {
Log.L.fine("Answer: Key<ESCAPE>");
AbstractDialog.this.dispose();
}
});
focus.requestFocus();
this.packed();
this.setVisible(true);
/*
* workaround a javabug that forces the parentframe to stay always on
* top
*/
if (Dialog.getInstance().getParentOwner() != null) {
Dialog.getInstance().getParentOwner().setAlwaysOnTop(true);
Dialog.getInstance().getParentOwner().setAlwaysOnTop(false);
}
}
/*
* (non-Javadoc)
*
* @seeorg.appwork.utils.event.Event.ActionListener#actionPerformed(com.
* rapidshare.utils.event.Event.ActionEvent)
*/
public void actionPerformed(final ActionEvent e) {
if (e.getSource() == this.okButton) {
Log.L.fine("Answer: Button<OK:" + this.okButton.getText() + ">");
this.setReturnmask(true);
} else if (e.getSource() == this.cancelButton) {
Log.L.fine("Answer: Button<CANCEL:" + this.cancelButton.getText() + ">");
this.setReturnmask(false);
}
this.dispose();
}
/**
* Overwrite this method to add additional buttons
*/
protected void addButtons(final JPanel buttonBar) {
}
/**
* called when user closes the window
*
* @return <code>true</code>, if and only if the dialog should be closeable
**/
public boolean closeAllowed() {
return true;
}
protected abstract T createReturnValue();
/**
* This method has to be called to display the dialog. make sure that all
* settings have beens et before, becvause this call very likly display a
* dialog that blocks the rest of the gui until it is closed
*/
public AbstractDialog<T> displayDialog() {
if (this.initialized) { return this; }
this.initialized = true;
this._init();
return this;
}
@Override
public void dispose() {
if (!this.initialized) { throw new IllegalStateException("Dialog has not been initialized yet. call displayDialog()"); }
try {
if (Dialog.getInstance().getParentOwner() != null) {
LockPanel.create(Dialog.getInstance().getParentOwner()).unlock(300);
}
} catch (final AWTException e1) {
}
super.dispose();
}
/**
* @return
*/
protected JPanel getDefaultButtonPanel() {
return new JPanel(new MigLayout("ins 0", "[fill,grow]", "[fill,grow]"));
}
/**
* should be overwritten and return a Dimension of the dialog should have a
* special size
*
* @return
*/
protected Dimension getDesiredSize() {
return null;
}
/**
* Create the key to save the don't showmagain state in database. should be
* overwritten in same dialogs. by default, the dialogs get differed by
* their title and their classname
*
* @return
*/
protected String getDontShowAgainKey() {
return "ABSTRACTDIALOG_DONT_SHOW_AGAIN_" + this.getClass().getSimpleName() + "_" + this.toString();
}
/**
* Return the returnbitmask
*
* @return
*/
public int getReturnmask() {
if (!this.initialized) { throw new IllegalStateException("Dialog has not been initialized yet. call displayDialog()"); }
return this.returnBitMask;
}
public T getReturnValue() {
if (!this.initialized) { throw new IllegalStateException("Dialog has not been initialized yet. call displayDialog()"); }
return this.createReturnValue();
}
/**
* This method has to be overwritten to implement custom content
*
* @return musst return a JComponent
*/
abstract public JComponent layoutDialogContent();
/**
* Handle timeout
*/
@Override
protected void onTimeout() {
this.setReturnmask(false);
this.returnBitMask |= Dialog.RETURN_TIMEOUT;
this.dispose();
}
/**
* may be overwritten to set focus to special components etc.
*/
protected void packed() {
}
/**
* Sets the returnvalue and saves the don't show again states to the
* database
*
* @param b
*/
protected void setReturnmask(final boolean b) {
this.returnBitMask = b ? Dialog.RETURN_OK : Dialog.RETURN_CANCEL;
if (BinaryLogic.containsAll(this.flagMask, Dialog.STYLE_SHOW_DO_NOT_DISPLAY_AGAIN)) {
if (this.dontshowagain.isSelected() && this.dontshowagain.isEnabled()) {
this.returnBitMask |= Dialog.RETURN_DONT_SHOW_AGAIN;
try {
if (BinaryLogic.containsAll(this.flagMask, Dialog.LOGIC_DONT_SHOW_AGAIN_DELETE_ON_EXIT)) {
AbstractDialog.SESSION_DONTSHOW_AGAIN.put(this.getDontShowAgainKey(), this.returnBitMask);
} else {
JSonStorage.getStorage("Dialogs").put(this.getDontShowAgainKey(), this.returnBitMask);
}
} catch (final Exception e) {
Log.exception(e);
}
}
}
}
/**
* Returns an id of the dialog based on it's title;
*/
@Override
public String toString() {
return ("dialog-" + this.getTitle()).replaceAll("\\W", "_");
}
public void windowActivated(final WindowEvent arg0) {
}
public void windowClosed(final WindowEvent arg0) {
}
public void windowClosing(final WindowEvent arg0) {
if (this.closeAllowed()) {
Log.L.fine("Answer: Button<[X]>");
this.returnBitMask |= Dialog.RETURN_CLOSED;
this.dispose();
} else {
Log.L.fine("(Answer: Tried [X] bot not allowed)");
}
}
public void windowDeactivated(final WindowEvent arg0) {
}
public void windowDeiconified(final WindowEvent arg0) {
}
public void windowIconified(final WindowEvent arg0) {
}
public void windowOpened(final WindowEvent arg0) {
}
} |
package net.jforum.view.forum;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import net.jforum.Command;
import net.jforum.ControllerUtils;
import net.jforum.JForumExecutionContext;
import net.jforum.SessionFacade;
import net.jforum.context.RequestContext;
import net.jforum.dao.BanlistDAO;
import net.jforum.dao.DataAccessDriver;
import net.jforum.dao.UserDAO;
import net.jforum.dao.UserSessionDAO;
import net.jforum.entities.Banlist;
import net.jforum.entities.Bookmark;
import net.jforum.entities.User;
import net.jforum.entities.UserSession;
import net.jforum.repository.BanlistRepository;
import net.jforum.repository.ForumRepository;
import net.jforum.repository.RankingRepository;
import net.jforum.repository.SecurityRepository;
import net.jforum.security.SecurityConstants;
import net.jforum.security.StopForumSpam;
import net.jforum.util.I18n;
import net.jforum.util.Hash;
import net.jforum.util.concurrent.Executor;
import net.jforum.util.mail.ActivationKeySpammer;
import net.jforum.util.mail.EmailSenderTask;
import net.jforum.util.mail.LostPasswordSpammer;
import net.jforum.util.preferences.ConfigKeys;
import net.jforum.util.preferences.SystemGlobals;
import net.jforum.util.preferences.TemplateKeys;
import net.jforum.view.forum.common.Stats;
import net.jforum.view.forum.common.UserCommon;
import net.jforum.view.forum.common.ViewCommon;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
/**
* @author Rafael Steil
* @version $Id$
*/
public class UserAction extends Command
{
private static final Logger LOGGER = Logger.getLogger(UserAction.class);
private static final String USERNAME = "username";
private static final String USER_ID = "user_id";
private static final String PAGE_TITLE = "pageTitle";
private static final String MESSAGE = "message";
private static final String EMAIL = "email";
private final UserDAO userDao = DataAccessDriver.getInstance().newUserDAO();
private final UserSessionDAO userSessionDao = DataAccessDriver.getInstance().newUserSessionDAO();
private boolean canEdit()
{
final int tmpId = SessionFacade.getUserSession().getUserId();
final boolean canEdit = SessionFacade.isLogged() && tmpId == this.request.getIntParameter(USER_ID);
if (!canEdit) {
this.profile();
}
return canEdit;
}
public void edit()
{
if (this.canEdit()) {
final int userId = this.request.getIntParameter(USER_ID);
final User user = userDao.selectById(userId);
this.context.put("u", user);
this.context.put("action", "editSave");
this.context.put(PAGE_TITLE, I18n.getMessage("UserProfile.profileFor") + " " + user.getUsername());
this.context.put("avatarAllowExternalUrl", SystemGlobals.getBoolValue(ConfigKeys.AVATAR_ALLOW_EXTERNAL_URL));
this.context.put("avatarPath", SystemGlobals.getValue(ConfigKeys.AVATAR_IMAGE_DIR));
this.setTemplateName(TemplateKeys.USER_EDIT);
}
}
public void editDone()
{
this.context.put("editDone", true);
this.edit();
}
public void editSave()
{
if (this.canEdit()) {
final int userId = this.request.getIntParameter(USER_ID);
final List<String> warns = UserCommon.saveUser(userId);
if (!warns.isEmpty()) {
this.context.put("warns", warns);
this.edit();
}
else {
JForumExecutionContext.setRedirect(this.request.getContextPath()
+ "/user/editDone/" + userId
+ SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION));
}
}
}
private void registrationDisabled()
{
this.setTemplateName(TemplateKeys.USER_REGISTRATION_DISABLED);
this.context.put(MESSAGE, I18n.getMessage("User.registrationDisabled"));
}
private void insert(final boolean hasErrors)
{
final int userId = SessionFacade.getUserSession().getUserId();
if ((!SystemGlobals.getBoolValue(ConfigKeys.REGISTRATION_ENABLED)
&& !SecurityRepository.get(userId).canAccess(SecurityConstants.PERM_ADMINISTRATION))
|| ConfigKeys.TYPE_SSO.equals(SystemGlobals.getValue(ConfigKeys.AUTHENTICATION_TYPE))) {
this.registrationDisabled();
return;
}
if (!hasErrors && SystemGlobals.getBoolValue(ConfigKeys.AGREEMENT_SHOW) && !this.agreementAccepted()) {
this.setTemplateName(TemplateKeys.AGREEMENT_LIST);
this.context.put("agreementContents", this.agreementContents());
return;
}
this.setTemplateName(TemplateKeys.USER_INSERT);
this.context.put("action", "insertSave");
this.context.put(USERNAME, this.request.getParameter(USERNAME));
this.context.put(EMAIL, this.request.getParameter(EMAIL));
this.context.put(PAGE_TITLE, I18n.getMessage("ForumBase.register"));
if (SystemGlobals.getBoolValue(ConfigKeys.CAPTCHA_REGISTRATION)){
this.context.put("captcha_reg", true);
}
SessionFacade.removeAttribute(ConfigKeys.AGREEMENT_ACCEPTED);
}
public void insert()
{
this.insert(false);
}
public void acceptAgreement()
{
SessionFacade.setAttribute(ConfigKeys.AGREEMENT_ACCEPTED, "1");
JForumExecutionContext.setRedirect(this.request.getContextPath()
+ "/user/insert"
+ SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION));
}
private String agreementContents()
{
StringBuilder contents = new StringBuilder();
try {
String directory = new StringBuilder()
.append(SystemGlobals.getApplicationPath())
.append(SystemGlobals.getValue(ConfigKeys.AGREEMENT_FILES_PATH))
.append('/')
.toString();
String filename = "terms_" + I18n.getUserLanguage() + ".txt";
File file = new File(directory + filename);
if (!file.exists()) {
filename = SystemGlobals.getValue(ConfigKeys.AGREEMENT_DEFAULT_FILE);
file = new File(directory + filename);
if (!file.exists()) {
throw new FileNotFoundException("Could not locate any terms agreement file");
}
}
contents.append(FileUtils.readFileToString(file, SystemGlobals.getValue(ConfigKeys.ENCODING)));
}
catch (Exception e) {
LOGGER.warn("Failed to read agreement data: " + e, e);
contents = new StringBuilder(I18n.getMessage("User.agreement.noAgreement"));
}
return contents.toString();
}
private boolean agreementAccepted()
{
return "1".equals(SessionFacade.getAttribute(ConfigKeys.AGREEMENT_ACCEPTED));
}
public void insertSave()
{
UserSession userSession = SessionFacade.getUserSession();
int userId = userSession.getUserId();
if ((!SystemGlobals.getBoolValue(ConfigKeys.REGISTRATION_ENABLED)
&& !SecurityRepository.get(userId).canAccess(SecurityConstants.PERM_ADMINISTRATION))
|| ConfigKeys.TYPE_SSO.equals(SystemGlobals.getValue(ConfigKeys.AUTHENTICATION_TYPE))) {
this.registrationDisabled();
return;
}
User user = new User();
String username = this.request.getParameter(USERNAME);
String password = this.request.getParameter("password");
String email = this.request.getParameter(EMAIL);
String captchaResponse = this.request.getParameter("captchaResponse");
String ip = this.request.getRemoteAddr();
boolean error = false;
if (StringUtils.isBlank(username)
|| StringUtils.isBlank(password)) {
this.context.put("error", I18n.getMessage("UsernamePasswordCannotBeNull"));
error = true;
}
if (username != null) {
username = username.trim();
}
if (!error && username != null && username.length() > SystemGlobals.getIntValue(ConfigKeys.USERNAME_MAX_LENGTH)) {
this.context.put("error", I18n.getMessage("User.usernameTooBig"));
error = true;
}
if (!error && username != null && (username.indexOf('<') > -1 || username.indexOf('>') > -1)) {
this.context.put("error", I18n.getMessage("User.usernameInvalidChars"));
error = true;
}
if (!error && userDao.isUsernameRegistered(username)) {
this.context.put("error", I18n.getMessage("UsernameExists"));
error = true;
}
if (!error && userDao.findByEmail(email) != null) {
this.context.put("error", I18n.getMessage("User.emailExists", new String[] { email }));
error = true;
}
if (!error && !userSession.validateCaptchaResponse(captchaResponse)){
this.context.put("error", I18n.getMessage("CaptchaResponseFails"));
error = true;
}
final BanlistDAO banlistDao = DataAccessDriver.getInstance().newBanlistDAO();
boolean stopForumSpamEnabled = SystemGlobals.getBoolValue(ConfigKeys.STOPFORUMSPAM_API_ENABLED);
if (stopForumSpamEnabled && StopForumSpam.checkIp(ip)) {
LOGGER.info("Forum Spam found! Block it: " + ip);
final Banlist banlist = new Banlist();
banlist.setIp(ip);
if (!BanlistRepository.shouldBan(banlist)) {
banlistDao.insert(banlist);
BanlistRepository.add(banlist);
}
error = true;
} else if (stopForumSpamEnabled && StopForumSpam.checkEmail(email)) {
LOGGER.info("Forum Spam found! Block it: " + email);
final Banlist banlist = new Banlist();
banlist.setEmail(email);
if (!BanlistRepository.shouldBan(banlist)) {
banlistDao.insert(banlist);
BanlistRepository.add(banlist);
} else { // email already exists, block source ip now
LOGGER.info("Forum Spam found! Block it: " + ip);
final Banlist banlist2 = new Banlist();
banlist2.setIp(ip);
banlistDao.insert(banlist2);
BanlistRepository.add(banlist2);
}
error = true;
}
if (error) {
this.insert(true);
return;
}
user.setUsername(username);
user.setPassword(Hash.sha512(password));
user.setEmail(email);
boolean needMailActivation = SystemGlobals.getBoolValue(ConfigKeys.MAIL_USER_EMAIL_AUTH);
if (needMailActivation) {
user.setActivationKey(Hash.md5(username + System.currentTimeMillis()));
}
int newUserId = userDao.addNew(user);
if (needMailActivation) {
Executor.execute(new EmailSenderTask(new ActivationKeySpammer(user)));
this.setTemplateName(TemplateKeys.USER_INSERT_ACTIVATE_MAIL);
this.context.put(MESSAGE, I18n.getMessage("User.GoActivateAccountMessage"));
}
else if(SecurityRepository.get(userId).canAccess(SecurityConstants.PERM_ADMINISTRATION)) {
JForumExecutionContext.setRedirect(this.request.getContextPath()
+ "/adminUsers/list"
+ SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION));
}
else {
this.logNewRegisteredUserIn(newUserId, user);
}
if (!needMailActivation) {
userDao.writeUserActive(newUserId);
}
}
public void activateAccount()
{
String hash = this.request.getParameter("hash");
int userId = Integer.parseInt(this.request.getParameter(USER_ID));
User user = userDao.selectById(userId);
boolean isValid = userDao.validateActivationKeyHash(userId, hash);
if (isValid) {
// Activate the account
userDao.writeUserActive(userId);
this.logNewRegisteredUserIn(userId, user);
}
else {
this.setTemplateName(TemplateKeys.USER_INVALID_ACTIVATION);
this.context.put(MESSAGE, I18n.getMessage("User.invalidActivationKey",
new Object[] { this.request.getContextPath()
+ "/user/activateManual"
+ SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION)
}
));
}
}
public void activateManual()
{
this.setTemplateName(TemplateKeys.ACTIVATE_ACCOUNT_MANUAL);
}
private void logNewRegisteredUserIn(final int userId, final User user)
{
UserSession userSession = SessionFacade.getUserSession();
SessionFacade.remove(userSession.getSessionId());
userSession.setAutoLogin(true);
userSession.setUserId(userId);
userSession.setUsername(user.getUsername());
userSession.setLastVisit(new Date(System.currentTimeMillis()));
userSession.setStartTime(new Date(System.currentTimeMillis()));
SessionFacade.makeLogged();
SessionFacade.add(userSession);
// Finalizing.. show the user the congratulations page
JForumExecutionContext.setRedirect(this.request.getContextPath()
+ "/user/registrationComplete"
+ SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION));
}
public void registrationComplete()
{
int userId = SessionFacade.getUserSession().getUserId();
// prevent increment total users through directly type in url
if (userId <= ForumRepository.lastRegisteredUser().getId()) {
JForumExecutionContext.setRedirect(this.request.getContextPath()
+ "/forums/list"
+ SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION));
return;
}
ForumRepository.setLastRegisteredUser(userDao.selectById(userId));
ForumRepository.incrementTotalUsers();
String profilePage = JForumExecutionContext.getForumContext().encodeURL("/user/edit/" + userId);
String homePage = JForumExecutionContext.getForumContext().encodeURL("/forums/list");
String message = I18n.getMessage("User.RegistrationCompleteMessage",
new Object[] { profilePage, homePage });
this.context.put(MESSAGE, message);
this.setTemplateName(TemplateKeys.USER_REGISTRATION_COMPLETE);
}
public void validateLogin()
{
String password;
String username;
if (parseBasicAuthentication()) {
username = (String)this.request.getAttribute(USERNAME);
password = (String)this.request.getAttribute("password");
}
else {
username = this.request.getParameter(USERNAME);
password = this.request.getParameter("password");
}
boolean validInfo = false;
if (password.length() > 0) {
User user = this.validateLogin(username, password);
if (user != null) {
// Note: here we only want to set the redirect location if it hasn't already been
// set. This will give the LoginAuthenticator a chance to set the redirect location.
this.buildSucessfulLoginRedirect();
SessionFacade.makeLogged();
String sessionId = SessionFacade.isUserInSession(user.getId());
UserSession userSession = new UserSession(SessionFacade.getUserSession());
// Remove the "guest" session
SessionFacade.remove(userSession.getSessionId());
userSession.dataToUser(user);
UserSession currentUs = SessionFacade.getUserSession(sessionId);
// Check if the user is returning to the system
// before its last session has expired ( hypothesis )
UserSession tmpUs;
if (sessionId != null && currentUs != null) {
// Write its old session data
SessionFacade.storeSessionData(sessionId, JForumExecutionContext.getConnection());
tmpUs = new UserSession(currentUs);
SessionFacade.remove(sessionId);
}
else {
tmpUs = userSessionDao.selectById(userSession, JForumExecutionContext.getConnection());
}
I18n.load(user.getLang());
// Autologin
if (this.request.getParameter("autologin") != null
&& SystemGlobals.getBoolValue(ConfigKeys.AUTO_LOGIN_ENABLED)) {
userSession.setAutoLogin(true);
// Generate the user-specific hash
String systemHash = Hash.md5(SystemGlobals.getValue(ConfigKeys.USER_HASH_SEQUENCE) + user.getId());
String userHash = Hash.md5(System.currentTimeMillis() + systemHash);
// Persist the user hash
userDao.saveUserAuthHash(user.getId(), userHash);
systemHash = Hash.md5(userHash);
ControllerUtils.addCookie(SystemGlobals.getValue(ConfigKeys.COOKIE_AUTO_LOGIN), "1");
ControllerUtils.addCookie(SystemGlobals.getValue(ConfigKeys.COOKIE_USER_HASH), systemHash);
}
else {
// Remove cookies for safety
ControllerUtils.addCookie(SystemGlobals.getValue(ConfigKeys.COOKIE_USER_HASH), null);
ControllerUtils.addCookie(SystemGlobals.getValue(ConfigKeys.COOKIE_AUTO_LOGIN), null);
}
if (tmpUs == null) {
userSession.setLastVisit(new Date(System.currentTimeMillis()));
}
else {
// Update last visit and session start time
userSession.setLastVisit(new Date(tmpUs.getStartTime().getTime() + tmpUs.getSessionTime()));
}
SessionFacade.add(userSession);
SessionFacade.setAttribute(ConfigKeys.TOPICS_READ_TIME, new HashMap<Integer, Long>());
ControllerUtils.addCookie(SystemGlobals.getValue(ConfigKeys.COOKIE_NAME_DATA),
Integer.toString(user.getId()));
SecurityRepository.load(user.getId(), true);
validInfo = true;
}
}
// Invalid login
if (!validInfo) {
this.context.put("invalidLogin", "1");
this.setTemplateName(TemplateKeys.USER_VALIDATE_LOGIN);
if (isValidReturnPath()) {
this.context.put("returnPath", this.request.getParameter("returnPath"));
}
}
else if (isValidReturnPath()) {
JForumExecutionContext.setRedirect(this.request.getParameter("returnPath"));
}
}
private void buildSucessfulLoginRedirect()
{
if (JForumExecutionContext.getRedirectTo() == null) {
String forwaredHost = request.getHeader("X-Forwarded-Host");
if (forwaredHost == null
|| SystemGlobals.getBoolValue(ConfigKeys.LOGIN_IGNORE_XFORWARDEDHOST)) {
JForumExecutionContext.setRedirect(this.request.getContextPath()
+ "/forums/list"
+ SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION));
}
else {
JForumExecutionContext.setRedirect(this.request.getScheme()
+ ":
+ forwaredHost
+ this.request.getContextPath()
+ "/forums/list"
+ SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION));
}
}
}
public void validateLogin(final RequestContext request) {
this.request = request;
validateLogin();
}
public static boolean hasBasicAuthentication(final RequestContext request) {
String auth = request.getHeader("Authorization");
return (auth != null && auth.startsWith("Basic "));
}
private boolean parseBasicAuthentication()
{
if (hasBasicAuthentication(request)) {
String auth = request.getHeader("Authorization");
String decoded;
decoded = String.valueOf(new Base64().decode(auth.substring(6)));
int p = decoded.indexOf(':');
if (p != -1) {
request.setAttribute(USERNAME, decoded.substring(0, p));
request.setAttribute("password", decoded.substring(p + 1));
return true;
}
}
return false;
}
private User validateLogin(final String name, final String password)
{
return userDao.validateLogin(name, password);
}
public void profile()
{
DataAccessDriver da = DataAccessDriver.getInstance();
User user = userDao.selectById(this.request.getIntParameter(USER_ID));
if (user.getId() == 0) {
this.userNotFound();
}
else {
this.setTemplateName(TemplateKeys.USER_PROFILE);
this.context.put("karmaEnabled", SecurityRepository.canAccess(SecurityConstants.PERM_KARMA_ENABLED));
this.context.put("rank", new RankingRepository());
this.context.put("u", user);
this.context.put("avatarAllowExternalUrl", SystemGlobals.getBoolValue(ConfigKeys.AVATAR_ALLOW_EXTERNAL_URL));
this.context.put("avatarPath", SystemGlobals.getValue(ConfigKeys.AVATAR_IMAGE_DIR));
this.context.put("showAvatar", SystemGlobals.getBoolValue(ConfigKeys.AVATAR_SHOW));
this.context.put("showKarma", SystemGlobals.getBoolValue(ConfigKeys.KARMA_SHOW));
int loggedId = SessionFacade.getUserSession().getUserId();
int count = 0;
List<Bookmark> bookmarks = da.newBookmarkDAO().selectByUser(user.getId());
for (Iterator<Bookmark> iter = bookmarks.iterator(); iter.hasNext(); ) {
Bookmark bookmark = iter.next();
if (bookmark.isPublicVisible() || loggedId == user.getId()) {
count++;
}
}
this.context.put(PAGE_TITLE, I18n.getMessage("UserProfile.allAbout")+" "+user.getUsername());
this.context.put("nbookmarks", Integer.valueOf(count));
this.context.put("ntopics", Integer.valueOf(da.newTopicDAO().countUserTopics(user.getId())));
this.context.put("nposts", Integer.valueOf(da.newPostDAO().countUserPosts(user.getId())));
this.context.put("rssEnabled", SystemGlobals.getBoolValue(ConfigKeys.RSS_ENABLED));
Stats.record("User profile page", request.getRequestURL());
}
}
private void userNotFound()
{
this.context.put(MESSAGE, I18n.getMessage("User.notFound"));
this.setTemplateName(TemplateKeys.USER_NOT_FOUND);
}
public void logout()
{
JForumExecutionContext.setRedirect(this.request.getContextPath()
+ "/forums/list"
+ SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION));
UserSession userSession = SessionFacade.getUserSession();
SessionFacade.storeSessionData(userSession.getSessionId(), JForumExecutionContext.getConnection());
SessionFacade.makeUnlogged();
SessionFacade.remove(userSession.getSessionId());
// Disable auto login
userSession.setAutoLogin(false);
userSession.makeAnonymous();
SessionFacade.add(userSession);
}
public void login()
{
if (ConfigKeys.TYPE_SSO.equals(SystemGlobals.getValue(ConfigKeys.AUTHENTICATION_TYPE))) {
this.registrationDisabled();
return;
}
if (isValidReturnPath()) {
this.context.put("returnPath", this.request.getParameter("returnPath"));
}
else if (!SystemGlobals.getBoolValue(ConfigKeys.LOGIN_IGNORE_REFERER)) {
String referer = this.request.getHeader("Referer");
if (referer != null) {
this.context.put("returnPath", referer);
}
}
this.context.put(PAGE_TITLE, I18n.getMessage("ForumBase.login"));
this.setTemplateName(TemplateKeys.USER_LOGIN);
}
// Lost password form
public void lostPassword()
{
this.setTemplateName(TemplateKeys.USER_LOSTPASSWORD);
this.context.put(PAGE_TITLE, I18n.getMessage("PasswordRecovery.title"));
}
public User prepareLostPassword(String origUsername, final String email)
{
String username = origUsername;
User user = null;
if (email != null && !email.trim().equals("")) {
username = userDao.getUsernameByEmail(email);
}
if (username != null && !username.trim().equals("")) {
List<User> l = userDao.findByName(username, true);
if (!l.isEmpty()) {
user = l.get(0);
}
}
if (user == null) {
return null;
}
String hash = Hash.md5(user.getEmail()
+ System.currentTimeMillis()
+ SystemGlobals.getValue(ConfigKeys.USER_HASH_SEQUENCE)
+ new Random().nextInt(999999));
userDao.writeLostPasswordHash(user.getEmail(), hash);
user.setActivationKey(hash);
return user;
}
// Send lost password email
public void lostPasswordSend()
{
String email = this.request.getParameter(EMAIL);
String username = this.request.getParameter(USERNAME);
User user = this.prepareLostPassword(username, email);
if (user == null) {
// user could not be found
this.context.put(MESSAGE,
I18n.getMessage("PasswordRecovery.invalidUserEmail"));
this.lostPassword();
return;
}
Executor.execute(new EmailSenderTask(
new LostPasswordSpammer(user,
SystemGlobals.getValue(ConfigKeys.MAIL_LOST_PASSWORD_SUBJECT))));
this.setTemplateName(TemplateKeys.USER_LOSTPASSWORD_SEND);
this.context.put(MESSAGE, I18n.getMessage(
"PasswordRecovery.emailSent",
new String[] {
this.request.getContextPath()
+ "/user/login"
+ SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION)
}));
}
// Recover user password ( aka, ask him a new one )
public void recoverPassword()
{
String hash = this.request.getParameter("hash");
this.setTemplateName(TemplateKeys.USER_RECOVERPASSWORD);
this.context.put("recoverHash", hash);
}
public void recoverPasswordValidate()
{
String hash = this.request.getParameter("recoverHash");
String email = this.request.getParameter(EMAIL);
String message;
boolean isOk = userDao.validateLostPasswordHash(email, hash);
if (isOk) {
String password = this.request.getParameter("newPassword");
userDao.saveNewPassword(Hash.sha512(password), email);
message = I18n.getMessage("PasswordRecovery.ok",
new String[] { this.request.getContextPath()
+ "/user/login"
+ SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION) });
}
else {
message = I18n.getMessage("PasswordRecovery.invalidData");
}
this.setTemplateName(TemplateKeys.USER_RECOVERPASSWORD_VALIDATE);
this.context.put(MESSAGE, message);
}
public void list()
{
int start = this.preparePagination(userDao.getTotalUsers());
int usersPerPage = SystemGlobals.getIntValue(ConfigKeys.USERS_PER_PAGE);
List<User> users = userDao.selectAll(start ,usersPerPage);
this.context.put("users", users);
this.context.put(PAGE_TITLE, I18n.getMessage("ForumBase.usersList"));
this.setTemplateName(TemplateKeys.USER_LIST);
}
public void listGroup()
{
int groupId = this.request.getIntParameter("group_id");
int start = this.preparePagination(userDao.getTotalUsersByGroup(groupId));
int usersPerPage = SystemGlobals.getIntValue(ConfigKeys.USERS_PER_PAGE);
List<User> users = userDao.selectAllByGroup(groupId, start ,usersPerPage);
this.context.put("users", users);
this.setTemplateName(TemplateKeys.USER_LIST);
}
/**
* @deprecated probably will be removed. Use KarmaAction to load Karma
*/
public void searchKarma()
{
int start = this.preparePagination(userDao.getTotalUsers());
int usersPerPage = SystemGlobals.getIntValue(ConfigKeys.USERS_PER_PAGE);
//Load all users with your karma
List<User> users = userDao.selectAllWithKarma(start ,usersPerPage);
this.context.put("users", users);
this.setTemplateName(TemplateKeys.USER_SEARCH_KARMA);
}
private int preparePagination(int totalUsers)
{
int start = ViewCommon.getStartPage();
int usersPerPage = SystemGlobals.getIntValue(ConfigKeys.USERS_PER_PAGE);
ViewCommon.contextToPagination(start, totalUsers, usersPerPage);
return start;
}
private boolean isValidReturnPath() {
if (request.getParameter("returnPath") != null) {
return request.getParameter("returnPath").startsWith(SystemGlobals.getValue(ConfigKeys.FORUM_LINK));
} else {
return false;
}
}
} |
package net.onrc.onos.datastore;
import java.io.File;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import edu.stanford.ramcloud.JRamCloud;
public class RCClient {
private static final String DB_CONFIG_FILE = "conf/ramcloud.conf";
public static final Configuration config = getConfiguration();
// Value taken from RAMCloud's Status.h
// FIXME These constants should be defined by JRamCloud
public static final int STATUS_OK = 0;
// FIXME come up with a proper way to retrieve configuration
public static final int MAX_MULTI_READS = Math.max(1, Integer
.valueOf(System.getProperty("ramcloud.max_multi_reads", "400")));
public static final int MAX_MULTI_WRITES = Math.max(1, Integer
.valueOf(System.getProperty("ramcloud.max_multi_writes", "800")));
private static final ThreadLocal<JRamCloud> tlsRCClient = new ThreadLocal<JRamCloud>() {
@Override
protected JRamCloud initialValue() {
return new JRamCloud(getCoordinatorUrl(config));
}
};
/**
* @return JRamCloud instance intended to be used only within the
* SameThread.
* @note Do not store the returned instance in a member variable, etc. which
* may be accessed later by another thread.
*/
static JRamCloud getClient() {
return tlsRCClient.get();
}
public static final Configuration getConfiguration() {
final File configFile = new File(System.getProperty("ramcloud.config.path", DB_CONFIG_FILE));
return getConfiguration(configFile);
}
public static final Configuration getConfiguration(final File configFile) {
if (configFile == null) {
throw new IllegalArgumentException("Need to specify a configuration file or storage directory");
}
if (!configFile.isFile()) {
throw new IllegalArgumentException("Location of configuration must be a file");
}
try {
return new PropertiesConfiguration(configFile);
} catch (ConfigurationException e) {
throw new IllegalArgumentException("Could not load configuration at: " + configFile, e);
}
}
public static String getCoordinatorUrl(final Configuration configuration) {
final String coordinatorIp = configuration.getString("ramcloud.coordinatorIp", "fast+udp:host=127.0.0.1");
final String coordinatorPort = configuration.getString("ramcloud.coordinatorPort", "port=12246");
final String coordinatorURL = coordinatorIp + "," + coordinatorPort;
return coordinatorURL;
}
} |
package org.callimachusproject.management;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.management.ManagementFactory;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import javax.mail.MessagingException;
import org.apache.http.HttpHost;
import org.apache.http.client.utils.URIUtils;
import org.callimachusproject.Version;
import org.callimachusproject.auth.AuthorizationService;
import org.callimachusproject.client.HTTPObjectClient;
import org.callimachusproject.io.FileUtil;
import org.callimachusproject.logging.LoggingProperties;
import org.callimachusproject.repository.CalliRepository;
import org.callimachusproject.server.WebServer;
import org.callimachusproject.setup.SetupOrigin;
import org.callimachusproject.setup.SetupTool;
import org.callimachusproject.util.CallimachusConf;
import org.callimachusproject.util.ConfigTemplate;
import org.callimachusproject.util.MailProperties;
import org.openrdf.OpenRDFException;
import org.openrdf.model.URI;
import org.openrdf.model.ValueFactory;
import org.openrdf.model.vocabulary.RDF;
import org.openrdf.repository.Repository;
import org.openrdf.repository.RepositoryConnection;
import org.openrdf.repository.RepositoryException;
import org.openrdf.repository.config.RepositoryConfig;
import org.openrdf.repository.config.RepositoryConfigException;
import org.openrdf.repository.manager.LocalRepositoryManager;
import org.openrdf.repository.manager.SystemRepository;
import org.openrdf.repository.object.ObjectRepository;
import org.openrdf.store.blob.BlobStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CalliServer implements CalliServerMXBean {
private static final String CHANGES_PATH = "../changes/";
private static final String ERROR_XPL_PATH = "pipelines/error.xpl";
private static final String SCHEMA_GRAPH = "types/SchemaGraph";
private static final String IDENTITY_PATH = "/diverted;";
private static final String ORIGIN = "http://callimachusproject.org/rdf/2009/framework#Origin";
private static final String REPOSITORY_TYPES = "META-INF/templates/repository-types.properties";
private static final ThreadFactory THREADFACTORY = new ThreadFactory() {
public Thread newThread(Runnable r) {
String name = CalliServer.class.getSimpleName() + "-"
+ Integer.toHexString(r.hashCode());
Thread t = new Thread(r, name);
t.setDaemon(true);
return t;
}
};
public static interface ServerListener {
void repositoryInitialized(String repositoryID, CalliRepository repository);
void repositoryShutDown(String repositoryID);
void webServiceStarted(WebServer server);
void webServiceStopping(WebServer server);
}
private final Logger logger = LoggerFactory.getLogger(CalliServer.class);
private final ExecutorService executor = Executors
.newSingleThreadScheduledExecutor(THREADFACTORY);
private final CallimachusConf conf;
private final ServerListener listener;
private final File serverCacheDir;
private volatile int starting;
private volatile boolean running;
private volatile boolean stopping;
private int processing;
private Exception exception;
WebServer server;
private final LocalRepositoryManager manager;
private final Map<String, CalliRepository> repositories = new LinkedHashMap<String, CalliRepository>();
public CalliServer(CallimachusConf conf, LocalRepositoryManager manager,
ServerListener listener) throws OpenRDFException, IOException {
this.conf = conf;
this.listener = listener;
this.manager = manager;
String tmpDirStr = System.getProperty("java.io.tmpdir");
if (tmpDirStr == null) {
tmpDirStr = "tmp";
}
File tmpDir = new File(tmpDirStr);
if (!tmpDir.exists()) {
tmpDir.mkdirs();
}
File cacheDir = new File(tmpDir, "cache");
File in = new File(cacheDir, "client");
FileUtil.deleteOnExit(cacheDir);
HTTPObjectClient.setCacheDirectory(in);
serverCacheDir = new File(cacheDir, "server");
}
public String toString() {
return manager.getBaseDir().toString();
}
public boolean isRunning() {
return running;
}
public synchronized void init() throws OpenRDFException, IOException {
if (isWebServiceRunning()) {
stopWebServiceNow();
}
try {
if (isThereAnOriginSetup()) {
server = createServer();
} else {
logger.warn("No Web origin is setup on this server");
}
} catch (IOException e) {
logger.error(e.toString(), e);
} catch (OpenRDFException e) {
logger.error(e.toString(), e);
} catch (GeneralSecurityException e) {
logger.error(e.toString(), e);
} finally {
if (server == null) {
shutDownRepositories();
}
}
}
public synchronized void start() throws IOException, OpenRDFException {
running = true;
notifyAll();
if (server != null) {
try {
logger.info("Callimachus is binding to {}", toString());
for (SetupOrigin origin : getOrigins()) {
HttpHost host = URIUtils.extractHost(java.net.URI.create(origin.getRoot()));
HTTPObjectClient.getInstance().setProxy(host, server);
}
for (CalliRepository repository : repositories.values()) {
repository.setCompileRepository(true);
}
server.start();
System.gc();
Thread.yield();
long uptime = ManagementFactory.getRuntimeMXBean().getUptime();
logger.info("Callimachus started after {} seconds", uptime / 1000.0);
if (listener != null) {
listener.webServiceStarted(server);
}
} catch (IOException e) {
logger.error(e.toString(), e);
} catch (OpenRDFException e) {
logger.error(e.toString(), e);
}
}
}
public synchronized void stop() throws IOException, OpenRDFException {
running = false;
if (isWebServiceRunning()) {
stopWebServiceNow();
}
notifyAll();
}
public synchronized void destroy() throws IOException, OpenRDFException {
stop();
shutDownRepositories();
manager.shutDown();
notifyAll();
}
@Override
public String getServerName() throws IOException {
String name = conf.getServerName();
if (name == null || name.length() == 0)
return Version.getInstance().getVersion();
return name;
}
@Override
public void setServerName(String name) throws IOException {
if (name == null || name.length() == 0 || name.equals(Version.getInstance().getVersion())) {
conf.setServerName(null);
} else {
conf.setServerName(name);
}
if (server != null) {
server.setName(getServerName());
}
}
public String getPorts() throws IOException {
int[] ports = getPortArray();
StringBuilder sb = new StringBuilder();
for (int i=0; i<ports.length; i++) {
sb.append(ports[i]);
if (i <ports.length - 1) {
sb.append(' ');
}
}
return sb.toString();
}
public void setPorts(String portStr) throws IOException {
int[] ports = new int[0];
if (portStr != null && portStr.trim().length() > 0) {
String[] values = portStr.trim().split("\\s+");
ports = new int[values.length];
for (int i = 0; i < values.length; i++) {
ports[i] = Integer.parseInt(values[i]);
}
}
conf.setPorts(ports);
if (server != null) {
server.listen(getPortArray(), getSSLPortArray());
}
}
public String getSSLPorts() throws IOException {
int[] ports = getSSLPortArray();
StringBuilder sb = new StringBuilder();
for (int i=0; i<ports.length; i++) {
sb.append(ports[i]);
if (i <ports.length - 1) {
sb.append(' ');
}
}
return sb.toString();
}
public void setSSLPorts(String portStr) throws IOException {
int[] ports = new int[0];
if (portStr != null && portStr.trim().length() > 0) {
String[] values = portStr.trim().split("\\s+");
ports = new int[values.length];
for (int i = 0; i < values.length; i++) {
ports[i] = Integer.parseInt(values[i]);
}
}
conf.setSslPorts(ports);
if (server != null) {
server.listen(getPortArray(), getSSLPortArray());
}
}
public boolean isStartingInProgress() {
return starting > 0;
}
public boolean isStoppingInProgress() {
return stopping;
}
public boolean isWebServiceRunning() {
return server != null && server.isRunning();
}
public synchronized void startWebService() throws Exception {
if (isWebServiceRunning())
return;
final int start = ++starting;
submit(new Callable<Void>() {
public Void call() throws Exception {
startWebServiceNow(start);
return null;
}
});
}
public void restartWebService() throws Exception {
final int start = ++starting;
submit(new Callable<Void>() {
public Void call() throws Exception {
stopWebServiceNow();
startWebServiceNow(start);
return null;
}
});
}
public void stopWebService() throws Exception {
if (stopping || !isWebServiceRunning())
return;
submit(new Callable<Void>() {
public Void call() throws Exception {
stopWebServiceNow();
return null;
}
});
}
@Override
public Map<String, String> getMailProperties() throws IOException {
return MailProperties.getInstance().getMailProperties();
}
@Override
public void setMailProperties(Map<String, String> lines)
throws IOException, MessagingException {
MailProperties.getInstance().setMailProperties(lines);
}
@Override
public Map<String, String> getLoggingProperties() throws IOException {
return LoggingProperties.getInstance().getLoggingProperties();
}
@Override
public void setLoggingProperties(Map<String, String> lines)
throws IOException, MessagingException {
LoggingProperties.getInstance().setLoggingProperties(lines);
}
@Override
public String[] getRepositoryIDs() throws OpenRDFException {
Set<String> set = manager.getRepositoryIDs();
set = new LinkedHashSet<String>(set);
set.remove(SystemRepository.ID);
return set.toArray(new String[0]);
}
public Map<String,String> getRepositoryProperties() throws IOException, OpenRDFException {
Map<String, String> map = getAllRepositoryProperties();
map = new LinkedHashMap<String, String>(map);
Iterator<String> iter = map.keySet().iterator();
while (iter.hasNext()) {
if (iter.next().contains("password")) {
iter.remove();
}
}
return map;
}
public String[] getAvailableRepositoryTypes() throws IOException {
List<String> list = new ArrayList<String>();
ClassLoader cl = this.getClass().getClassLoader();
Enumeration<URL> types = cl.getResources(REPOSITORY_TYPES);
while (types.hasMoreElements()) {
Properties properties = new Properties();
InputStream in = types.nextElement().openStream();
try {
properties.load(in);
} finally {
in.close();
}
Enumeration<?> names = properties.propertyNames();
while (names.hasMoreElements()) {
list.add((String) names.nextElement());
}
}
return list.toArray(new String[list.size()]);
}
public synchronized void setRepositoryProperties(Map<String,String> parameters)
throws IOException, OpenRDFException {
Map<String, Map<String, String>> params;
Map<String, String> combined;
combined = getAllRepositoryProperties();
combined = new LinkedHashMap<String, String>(combined);
combined.putAll(parameters);
params = groupBeforePeriod(combined);
Set<String> removed = new LinkedHashSet<String>(params.keySet());
removed.removeAll(groupBeforePeriod(parameters).keySet());
for (String repositoryID : removed) {
if (manager.removeRepository(repositoryID)) {
logger.warn("Removed repository {}", repositoryID);
}
}
combined = getAllRepositoryProperties();
combined = new LinkedHashMap<String, String>(combined);
combined.putAll(parameters);
params = groupBeforePeriod(combined);
for (String repositoryID : params.keySet()) {
Map<String, String> pmap = params.get(repositoryID);
String type = pmap.get(null);
ClassLoader cl = this.getClass().getClassLoader();
Enumeration<URL> types = cl.getResources(REPOSITORY_TYPES);
while (types.hasMoreElements()) {
Properties properties = new Properties();
InputStream in = types.nextElement().openStream();
try {
properties.load(in);
} finally {
in.close();
}
if (!properties.containsKey(type))
continue;
String path = properties.getProperty(type);
Enumeration<URL> configs = cl.getResources(path);
while (configs.hasMoreElements()) {
URL url = configs.nextElement();
ConfigTemplate temp = new ConfigTemplate(url);
RepositoryConfig config = temp.render(pmap);
if (config == null)
throw new RepositoryConfigException("Missing parameters for " + repositoryID);
if (manager.hasRepositoryConfig(repositoryID)) {
RepositoryConfig oldConfig = manager.getRepositoryConfig(repositoryID);
if (temp.getParameters(config).equals(temp.getParameters(oldConfig)))
continue;
config.validate();
logger.info("Replacing repository configuration {}", repositoryID);
manager.addRepositoryConfig(config);
} else {
config.validate();
logger.info("Creating repository {}", repositoryID);
manager.addRepositoryConfig(config);
}
if (manager.getInitializedRepositoryIDs().contains(repositoryID)) {
manager.getRepository(repositoryID).shutDown();
}
try {
Repository repo = manager.getRepository(repositoryID);
RepositoryConnection conn = repo.getConnection();
try {
// just check that we can access the repository
conn.hasStatement(null, null, null, false);
} finally {
conn.close();
}
} catch (OpenRDFException e) {
logger.error(e.toString(), e);
throw new RepositoryConfigException(e.toString());
}
}
}
}
}
public synchronized void checkForErrors() throws Exception {
try {
if (exception != null)
throw exception;
} finally {
exception = null;
}
}
public synchronized boolean isSetupInProgress() {
return processing > 0;
}
public String[] getWebappOrigins() throws IOException {
return conf.getWebappOrigins();
}
@Override
public void setupWebappOrigin(final String webappOrigin,
final String repositoryID) throws Exception {
submit(new Callable<Void>() {
public Void call() throws Exception {
CalliRepository repository = getInitializedRepository(repositoryID);
Repository repo = manager.getRepository(repositoryID);
File dataDir = manager.getRepositoryDir(repositoryID);
if (repository == null) {
repository = new CalliRepository(repo, dataDir);
String changes = repository.getCallimachusUrl(webappOrigin, CHANGES_PATH);
if (changes != null) {
repository.setChangeFolder(changes);
}
} else {
BlobStore blobs = repository.getBlobStore();
String changes = repository.getChangeFolder();
repository = new CalliRepository(repo, dataDir);
if (changes != null) {
repository.setChangeFolder(changes);
}
if (blobs != null) {
repository.setBlobStore(blobs);
}
}
SetupTool tool = new SetupTool(repositoryID, repository, conf);
tool.setupWebappOrigin(webappOrigin);
refreshRepository(repositoryID);
if (isWebServiceRunning()) {
server.addOrigin(webappOrigin, getRepository(repositoryID));
server.setIdentityPrefix(getIdentityPrefixes());
HttpHost host = URIUtils.extractHost(java.net.URI.create(webappOrigin + "/"));
HTTPObjectClient.getInstance().setProxy(host, server);
}
return null;
}
});
}
@Override
public void ignoreWebappOrigin(String webappOrigin) throws Exception {
List<String> list = new ArrayList<String>(Arrays.asList(conf.getWebappOrigins()));
list.remove(webappOrigin);
for (SetupOrigin origin : getOrigins()) {
if (webappOrigin.equals(origin.getWebappOrigin())) {
list.remove(origin.getRoot().replaceAll("/$", ""));
}
}
conf.setWebappOrigins(list.toArray(new String[list.size()]));
}
public SetupOrigin[] getOrigins() throws IOException, OpenRDFException {
List<SetupOrigin> list = new ArrayList<SetupOrigin>();
Set<String> webapps = new LinkedHashSet<String>(Arrays.asList(getWebappOrigins()));
Map<String, String> map = conf.getOriginRepositoryIDs();
for (String repositoryID : new LinkedHashSet<String>(map.values())) {
CalliRepository repository = getRepository(repositoryID);
SetupTool tool = new SetupTool(repositoryID, repository, conf);
SetupOrigin[] origins = tool.getOrigins();
for (SetupOrigin origin : origins) {
webapps.remove(origin.getWebappOrigin());
}
list.addAll(Arrays.asList(origins));
}
for (String webappOrigin : webapps) {
// this webapp are not yet setup in the store
String id = map.get(webappOrigin);
list.add(new SetupOrigin(webappOrigin, id));
}
return list.toArray(new SetupOrigin[list.size()]);
}
public void setupResolvableOrigin(final String origin, final String webappOrigin)
throws Exception {
submit(new Callable<Void>() {
public Void call() throws Exception {
SetupTool tool = getSetupTool(webappOrigin);
tool.setupResolvableOrigin(origin, webappOrigin);
if (isWebServiceRunning()) {
server.addOrigin(origin, getRepository(tool.getRepositoryID()));
server.setIdentityPrefix(getIdentityPrefixes());
HttpHost host = URIUtils.extractHost(java.net.URI.create(origin + "/"));
HTTPObjectClient.getInstance().setProxy(host, server);
}
return null;
}
});
}
public void setupRootRealm(final String realm, final String webappOrigin)
throws Exception {
submit(new Callable<Void>() {
public Void call() throws Exception {
getSetupTool(webappOrigin).setupRootRealm(realm, webappOrigin);
return null;
}
});
}
public String[] getDigestEmailAddresses(String webappOrigin)
throws OpenRDFException, IOException {
return getSetupTool(webappOrigin).getDigestEmailAddresses(webappOrigin);
}
public void inviteAdminUser(final String email, final String username,
final String label, final String comment, final String subject,
final String body, final String webappOrigin) throws Exception {
submit(new Callable<Void>() {
public Void call() throws Exception {
SetupTool tool = getSetupTool(webappOrigin);
tool.inviteAdminUser(email, username, label, comment, subject,
body, webappOrigin);
String repositoryID = tool.getRepositoryID();
CalliRepository repository = getRepository(repositoryID);
ObjectRepository object = repository.getDelegate();
AuthorizationService.getInstance().get(object).resetCache();
return null;
}
});
}
public boolean changeDigestUserPassword(String email, String password,
String webappOrigin) throws OpenRDFException, IOException {
return getSetupTool(webappOrigin).changeDigestUserPassword(email,
password, webappOrigin);
}
synchronized void saveError(Exception exc) {
exception = exc;
}
synchronized void begin() {
processing++;
}
synchronized void end() {
processing
notifyAll();
}
protected void submit(final Callable<Void> task)
throws Exception {
checkForErrors();
executor.submit(new Runnable() {
public void run() {
begin();
try {
task.call();
} catch (Exception exc) {
saveError(exc);
} finally {
end();
}
}
});
Thread.yield();
}
SetupTool getSetupTool(String webappOrigin) throws OpenRDFException, IOException {
String repositoryID = conf.getOriginRepositoryIDs().get(webappOrigin);
CalliRepository repository = getRepository(repositoryID);
return new SetupTool(repositoryID, repository, conf);
}
private Map<String, String> getAllRepositoryProperties()
throws IOException, OpenRDFException {
Map<String, String> map = new LinkedHashMap<String, String>();
ClassLoader cl = this.getClass().getClassLoader();
Enumeration<URL> types = cl.getResources(REPOSITORY_TYPES);
while (types.hasMoreElements()) {
Properties properties = new Properties();
InputStream in = types.nextElement().openStream();
try {
properties.load(in);
} finally {
in.close();
}
Enumeration<?> names = properties.propertyNames();
while (names.hasMoreElements()) {
String type = (String) names.nextElement();
String path = properties.getProperty(type);
Enumeration<URL> configs = cl.getResources(path);
while (configs.hasMoreElements()) {
URL url = configs.nextElement();
ConfigTemplate temp = new ConfigTemplate(url);
for (String id : manager.getRepositoryIDs()) {
if (id.equals(SystemRepository.ID))
continue;
RepositoryConfig cfg = manager.getRepositoryConfig(id);
Map<String, String> params = temp.getParameters(cfg);
if (params == null || id.indexOf('.') >= 0)
continue;
for (Map.Entry<String, String> e : params.entrySet()) {
map.put(id + '.' + e.getKey(), e.getValue());
}
map.put(id, type);
}
}
}
}
return map;
}
private Map<String, Map<String, String>> groupBeforePeriod(
Map<String, String> parameters) {
Map<String, Map<String, String>> params = new LinkedHashMap<String, Map<String,String>>();
for (Map.Entry<String, String> e : parameters.entrySet()) {
String id, key;
int idx = e.getKey().indexOf('.');
if (idx < 0) {
id = e.getKey();
key = null;
} else {
id = e.getKey().substring(0, idx);
key = e.getKey().substring(idx + 1);
}
String value = e.getValue();
Map<String, String> map = params.get(id);
if (map == null) {
params.put(id, map = new LinkedHashMap<String, String>());
}
map.put(key, value);
}
return params;
}
synchronized void startWebServiceNow(int start) {
if (start != starting)
return;
try {
if (isWebServiceRunning()) {
stopWebServiceNow();
}
try {
if (getPortArray().length == 0 && getSSLPortArray().length == 0)
throw new IllegalStateException("No TCP port defined for server");
if (!isThereAnOriginSetup())
throw new IllegalStateException("Repository origin is not setup");
if (server == null) {
server = createServer();
}
} finally {
if (server == null) {
shutDownRepositories();
}
}
server.start();
if (listener != null) {
listener.webServiceStarted(server);
}
} catch (IOException e) {
logger.error(e.toString(), e);
} catch (OpenRDFException e) {
logger.error(e.toString(), e);
} catch (GeneralSecurityException e) {
logger.error(e.toString(), e);
} finally {
starting = 0;
notifyAll();
}
}
synchronized boolean stopWebServiceNow() throws OpenRDFException {
stopping = true;
try {
if (server == null) {
shutDownRepositories();
return false;
} else {
if (listener != null) {
listener.webServiceStopping(server);
}
server.stop();
shutDownRepositories();
server.destroy();
for (SetupOrigin origin : getOrigins()) {
HttpHost host = URIUtils.extractHost(java.net.URI.create(origin.getRoot()));
HTTPObjectClient.getInstance().removeProxy(host, server);
}
return true;
}
} catch (IOException e) {
logger.error(e.toString(), e);
return false;
} finally {
stopping = false;
notifyAll();
server = null;
shutDownRepositories();
}
}
private boolean isThereAnOriginSetup() throws RepositoryException,
RepositoryConfigException, IOException {
Map<String, String> map = conf.getOriginRepositoryIDs();
for (String repositoryID : new LinkedHashSet<String>(map.values())) {
if (!manager.hasRepositoryConfig(repositoryID))
continue;
Repository repository = manager.getRepository(repositoryID);
RepositoryConnection conn = repository.getConnection();
try {
ValueFactory vf = conn.getValueFactory();
URI Origin = vf.createURI(ORIGIN);
for (String origin : map.keySet()) {
if (!repositoryID.equals(map.get(origin)))
continue;
URI subj = vf.createURI(origin + "/");
if (conn.hasStatement(subj, RDF.TYPE, Origin, false))
return true; // at least one origin is setup
}
return getPortArray().length > 0
|| getSSLPortArray().length > 0;
} finally {
conn.close();
}
}
return false;
}
private synchronized WebServer createServer() throws OpenRDFException,
IOException, NoSuchAlgorithmException {
WebServer server = new WebServer(serverCacheDir);
for (SetupOrigin so : getOrigins()) {
boolean first = repositories.isEmpty();
if (so.isResolvable()) {
String origin = so.getRoot().replaceAll("/$", "");
server.addOrigin(origin, getRepository(so.getRepositoryID()));
server.setIdentityPrefix(getIdentityPrefixes());
HttpHost host = URIUtils.extractHost(java.net.URI.create(so.getRoot()));
HTTPObjectClient.getInstance().setProxy(host, server);
if (first) {
CalliRepository repo = getRepository(so.getRepositoryID());
String pipe = repo.getCallimachusUrl(so.getWebappOrigin(), ERROR_XPL_PATH);
if (pipe == null)
throw new IllegalArgumentException(
"Callimachus webapp not setup on: " + so.getWebappOrigin());
server.setErrorPipe(pipe);
}
}
}
server.setName(getServerName());
server.listen(getPortArray(), getSSLPortArray());
return server;
}
CalliRepository getRepository(String repositoryID)
throws IOException, OpenRDFException {
Map<String, String> map = conf.getOriginRepositoryIDs();
List<String> origins = new ArrayList<String>(map.size());
for (Map.Entry<String, String> e : map.entrySet()) {
if (repositoryID.equals(e.getValue())) {
origins.add(e.getKey());
}
}
CalliRepository repository = repositories.get(repositoryID);
if (repository != null && repository.isInitialized())
return repository;
if (origins.isEmpty())
return null;
Repository repo = manager.getRepository(repositoryID);
File dataDir = manager.getRepositoryDir(repositoryID);
repository = new CalliRepository(repo, dataDir);
String changes = repository.getCallimachusUrl(origins.get(0), CHANGES_PATH);
if (changes != null) {
repository.setChangeFolder(changes);
}
for (String origin : origins) {
String schema = repository.getCallimachusUrl(origin, SCHEMA_GRAPH);
if (schema != null) {
repository.addSchemaGraphType(schema);
}
}
repository.setCompileRepository(true);
if (listener != null && repositories.containsKey(repositoryID)) {
listener.repositoryShutDown(repositoryID);
}
repositories.put(repositoryID, repository);
if (listener != null) {
listener.repositoryInitialized(repositoryID, repository);
}
return repository;
}
synchronized CalliRepository getInitializedRepository(String repositoryID) {
CalliRepository repository = repositories.get(repositoryID);
if (repository == null || !repository.isInitialized())
return null;
return repository;
}
synchronized void refreshRepository(String repositoryID) {
repositories.remove(repositoryID);
}
private synchronized void shutDownRepositories() throws OpenRDFException {
for (Map.Entry<String, CalliRepository> e : repositories.entrySet()) {
e.getValue().shutDown();
if (listener != null) {
listener.repositoryShutDown(e.getKey());
}
}
manager.refresh();
repositories.clear();
}
private int[] getPortArray() throws IOException {
return conf.getPorts();
}
private int[] getSSLPortArray() throws IOException {
return conf.getSslPorts();
}
private String[] getIdentityPrefixes() throws IOException, OpenRDFException {
Map<String, String> map = new LinkedHashMap<String, String>();
for (SetupOrigin origin : getOrigins()) {
String key = origin.getRepositoryID();
if (origin.isResolvable() && map.containsKey(key)) {
map.put(key, null);
} else {
map.put(key, origin.getWebappOrigin());
}
}
List<String> identities = new ArrayList<String>(map.size());
for (String origin : map.values()) {
if (origin != null) {
identities.add(origin + IDENTITY_PATH);
}
}
return identities.toArray(new String[identities.size()]);
}
} |
// Clase Principal
import javax.swing.*;
import java.awt.*;
import java.lang.*;
import java.awt.event.*;
class Raya extends JFrame implements ActionListener
{
int turno=0;
boolean fin;
boolean dosJugadores;
boolean pulsado;
//botones
JButton boton[][]=new JButton[7][7];
//menus
JMenuBar Barra=new JMenuBar();
JMenu Archivo=new JMenu("Archivo");
JMenu Opciones=new JMenu("Opciones");
JMenuItem Nuevo=new JMenuItem("Nuevo");
JMenuItem Salir=new JMenuItem("Salir");
JMenuItem M1Jugador=new JMenuItem("1 Jugador");
JMenuItem M2Jugador=new JMenuItem("2 Jugadores");
JLabel Nombre=new JLabel("http://todojava.awardspace.com",JLabel.CENTER);
//imagenes
ImageIcon foto1;
ImageIcon foto2;
Raya()
{
//Cargar imagenes
foto1=new ImageIcon("foto1.gif");
foto2=new ImageIcon("foto2.gif");
//menu
Nuevo.addActionListener(this);
Archivo.add(Nuevo);
Archivo.addSeparator();
Salir.addActionListener(this);
Archivo.add(Salir);
M1Jugador.addActionListener(this);
Opciones.add(M1Jugador);
M2Jugador.addActionListener(this);
Opciones.add(M2Jugador);
Barra.add(Archivo);
Barra.add(Opciones);
setJMenuBar(Barra);
//Panel Principal
JPanel Principal=new JPanel();
Principal.setLayout(new GridLayout(7,7));
//Colocar Botones
for(int i=0;i<7;i++)
{
for(int j=0;j<7;j++)
{
boton[i][j]=new JButton();
boton[i][j].addActionListener(this);
boton[i][j].setBackground(Color.BLACK);
Principal.add(boton[i][j]);
}
Nombre.setForeground(Color.BLUE);
add(Nombre,"North");
add(Principal,"Center");
}
//Para cerrar la Ventana
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
//tamao frame
setLocation(170,25);
setSize (600,600);
setResizable(false);
setTitle("CONECTA 4 v 1.0 http://todojava.awardspace.com/");
setVisible(true);
}
void ganar(int x,int y)
{
/*
* x fila
* y columna
*/
fin=false;
//Quien gana en? horizontal
int ganar1=0;
int ganar2=0;
for(int j=0;j<7;j++)
{
if(boton[y][j].getIcon()!=null)
{
if(boton[y][j].getIcon().equals(foto1))
{
ganar1++;
}
else ganar1=0;
if(ganar1==4)
{
JOptionPane.showMessageDialog(this,"Gana Jugador Rojo","Conecta 4",JOptionPane.INFORMATION_MESSAGE,foto1);
VolverEmpezar();
fin=true;
}
if(fin!=true)
{
if(boton[y][j].getIcon().equals(foto2))
{
ganar2++;
}
else ganar2=0;
if(ganar2==4)
{
JOptionPane.showMessageDialog(this,"Gana Jugador Verde","Conecta 4",JOptionPane.INFORMATION_MESSAGE,foto2);
VolverEmpezar();
}
}
}
else
{
ganar1=0;
ganar2=0;
}
}
// Quien gana en? vertical
ganar1=0;
ganar2=0;
for(int i=0;i<7;i++)
{
if(boton[i][x].getIcon()!=null)
{
if(boton[i][x].getIcon().equals(foto1))
{
ganar1++;
}
else ganar1=0;
if(ganar1==4)
{
JOptionPane.showMessageDialog(this,"Gana Jugador Rojo","Conecta 4",JOptionPane.INFORMATION_MESSAGE,foto1);
VolverEmpezar();
fin=true;
}
if(fin!=true)
{
if(boton[i][x].getIcon().equals(foto2))
{
ganar2++;
}
else ganar2=0;
if(ganar2==4)
{
JOptionPane.showMessageDialog(this,"Gana Jugador Verde","Conecta 4",JOptionPane.INFORMATION_MESSAGE,foto2);
VolverEmpezar();
}
}
}
}
// Quien gana en Oblicuo 1 Posicion De izquierda a derecha
ganar1=0;
ganar2=0;
int a=y;
int b=x;
while(b>0 && a>0)
{
a
b
}
while(b<7 && a<7)
{
if(boton[a][b].getIcon()!=null)
{
if(boton[a][b].getIcon().equals(foto1))
{
ganar1++;
}
else ganar1=0;
if(ganar1==4)
{
JOptionPane.showMessageDialog(this,"Gana Jugador Rojo","Conecta 4",JOptionPane.INFORMATION_MESSAGE,foto1);
VolverEmpezar();
fin=true;
}
if(fin!=true)
{
if(boton[a][b].getIcon().equals(foto2))
{
ganar2++;
}
else ganar2=0;
if(ganar2==4)
{
JOptionPane.showMessageDialog(this,"Gana Jugador Verde","Conecta 4",JOptionPane.INFORMATION_MESSAGE,foto2);
VolverEmpezar();
}
}
}
else
{
ganar1=0;
ganar2=0;
}
a++;
b++;
}
// Quien gana en oblicuo? 2 Posicion de derecha a izquierda
ganar1=0;
ganar2=0;
a=y;
b=x;
//buscar posicin de la esquina
while(b<6 && a>0)
{
a
b++;
}
while(b>-1 && a<7 )
{
if(boton[a][b].getIcon()!=null)
{
if(boton[a][b].getIcon().equals(foto1))
{
ganar1++;
}
else ganar1=0;
if(ganar1==4)
{
JOptionPane.showMessageDialog(this,"Gana Jugador Rojo","Conecta 4",JOptionPane.INFORMATION_MESSAGE,foto1);
VolverEmpezar();
fin=true;
}
if(fin!=true)
{
if(boton[a][b].getIcon().equals(foto2))
{
ganar2++;
}
else ganar2=0;
if(ganar2==4)
{
JOptionPane.showMessageDialog(this,"Gana Jugador Verde","Conecta 4",JOptionPane.INFORMATION_MESSAGE,foto2);
VolverEmpezar();
}
}
}
else
{
ganar1=0;
ganar2=0;
}
a++;
b
}
}
// Volver el programa al estado inicial
void VolverEmpezar()
{
for(int i=0;i<7;i++)
{
for(int j=0;j<7;j++)
{
boton[i][j].setIcon(null);
}
}
turno=0;
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==M1Jugador)
{
dosJugadores=false;
VolverEmpezar();
}
if(ae.getSource()==M2Jugador)
{
dosJugadores=true;
VolverEmpezar();
}
if(ae.getSource()==Salir)
{
dispose();
}
if(ae.getSource()==Nuevo)
{
VolverEmpezar();
}
int x=0;
int y=0;
for(int i=0;i<7;i++)
{
for(int j=0;j<7;j++)
{
if (ae.getSource()==boton[i][j])
{
//Ir hasta la ultima posicion
int k=7;
do
{
k
}
while(boton[k][j].getIcon()!=null & k!=0);
//Pintar Ficha
if(boton[k][j].getIcon()==null)
{
if(dosJugadores) //Si es modo un jugador o dos
{ //Dos Jugadores
if(turno %2==0)boton[k][j].setIcon(foto1);
else boton[k][j].setIcon(foto2);
turno++;
x=j;
y=k;
}
else
{ //Un Jugador
boton[k][j].setIcon(foto1);
turno++;
pulsado=true;
x=j;
y=k;
}
}
}
}
}
ganar(x,y);
if(pulsado)
{
if(!dosJugadores) juegaMaquina(x,y);
}
//Empate!!!
if(turno==49)
{
JOptionPane.showMessageDialog(this,"Has Empatado","Conecta 4",JOptionPane.INFORMATION_MESSAGE);
VolverEmpezar();
}
fin=false;
}
void juegaMaquina(int x,int y)
{
boolean Cubrir_izquierda=false;
int ganarVert=0;
int ganarHorz=0;
int posicion=0;
posicion=GenerarAleatorio(x); //Generar Aleatorio por defecto
ganarHorz=0;
for(int i=0;i<7;i++) //buscamos en todo el tablero
{
for(int j=0;j<7;j++)
{
if(boton[i][j].getIcon()!=null)
{
if(boton[i][j].getIcon().equals(foto2))
{
ganarHorz++;
}
else ganarHorz=0;
if(ganarHorz==3)
{
posicion=j;
if(posicion!=6)
{
if(boton[y][j+1].getIcon()==null) posicion++;
else if(j>=3 && boton[y][j-3].getIcon()==null)posicion=posicion-3;
System.out.println("Por la derecha");
}
}
}
}
ganarHorz=0;
}
ganarHorz=0;
for(int j=6;j>=0;j
{
if(boton[y][j].getIcon()!=null)
{
if(boton[y][j].getIcon().equals(foto1))
{
ganarHorz++;
}
else ganarHorz=0;
if(ganarHorz==3 && j!=0)
{
posicion=j;
if(boton[y][j-1].getIcon()==null)
{
posicion
Cubrir_izquierda=true;
}
//System.out.println("Por la izquierda");
}
}
}
ganarHorz=0;
if(!Cubrir_izquierda)
{
for(int j=0;j<7;j++)
{
if(boton[y][j].getIcon()!=null)
{
if(boton[y][j].getIcon().equals(foto1))
{
ganarHorz++;
}
else ganarHorz=0;
if(ganarHorz==3)
{
posicion=j;
if(posicion!=6)
{
if(boton[y][j+1].getIcon()==null) posicion++;
//System.out.println("Por la derecha");
}
}
}
}
}
for(int i=0;i<7;i++)
{
if(boton[i][x].getIcon()!=null)
{
if(boton[i][x].getIcon().equals(foto1))
{
ganarVert++;
}
else ganarVert=0;
if(ganarVert==3)
{
posicion=x; //obtiene la columna en la que se puede ganar;
//System.out.println("Por la arriba");
}
}
}
ganarVert=0;
for(int i=0;i<7;i++) //buscamos en todo el tablero
{
for(int j=0;j<7;j++)
{
if(boton[j][i].getIcon()!=null)
{
if(boton[j][i].getIcon().equals(foto2))
{
ganarVert++;
}
else ganarVert=0;
if(ganarVert==3 && j!=0) //si en alguna columna hay 3 fichas seguidas de la mquina
{
posicion=i; //obtiene la columna en la que se puede ganar;
}
}
}
ganarVert=0;
}
if(boton[0][posicion].getIcon()!=null) //si no se pude poner ficha en la columna (columna llena)
{
posicion=GenerarAleatorio(posicion); //Genera posicin aleatoria
}
int k=7;
//Ir a la ltima posicin de la columna
do
{
k
}
while(boton[k][posicion].getIcon()!=null & k!=0);
//Pintar Ficha
boton[k][posicion].setIcon(foto2);
ganar(posicion,k);
pulsado=false;
Cubrir_izquierda=false;
}
int GenerarAleatorio(int posicion)
{
//Buscar columna en la que se puede poner
double aleatorio=0;
do
{
aleatorio=Math.random()*7;
posicion=(int)aleatorio;
}
while(boton[0][posicion].getIcon()!=null); //posicion 0: para q busque las columnas q no esten llenas
return posicion;
}
public static void main (String [] args)
{
new Raya();
}
} |
package gov.nih.nci.calab.service.workflow;
import gov.nih.nci.calab.db.DataAccessProxy;
import gov.nih.nci.calab.db.IDataAccess;
import gov.nih.nci.calab.domain.Aliquot;
import gov.nih.nci.calab.domain.Assay;
import gov.nih.nci.calab.domain.AssayType;
import gov.nih.nci.calab.domain.InputFile;
import gov.nih.nci.calab.domain.OutputFile;
import gov.nih.nci.calab.domain.Run;
import gov.nih.nci.calab.domain.RunSampleContainer;
import gov.nih.nci.calab.domain.StorageElement;
import gov.nih.nci.calab.dto.administration.AliquotBean;
import gov.nih.nci.calab.dto.administration.ContainerBean;
import gov.nih.nci.calab.dto.administration.StorageLocation;
import gov.nih.nci.calab.dto.workflow.AssayBean;
import gov.nih.nci.calab.dto.workflow.ExecuteWorkflowBean;
import gov.nih.nci.calab.dto.workflow.FileBean;
import gov.nih.nci.calab.dto.workflow.RunBean;
import gov.nih.nci.calab.service.util.CalabComparators;
import gov.nih.nci.calab.service.util.CalabConstants;
import gov.nih.nci.calab.service.util.StringUtils;
import gov.nih.nci.calab.service.util.file.FileNameConvertor;
import gov.nih.nci.calab.service.util.file.HttpUploadedFileData;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import org.apache.log4j.Logger;
public class ExecuteWorkflowService {
private static Logger logger = Logger.getLogger(ExecuteWorkflowService.class);
/**
* Save the aliquot IDs to be associated with the given run ID.
*
* @param runId
* @param aliquotIds
* @throws Exception
*/
public void saveRunAliquots(String runId, String[] aliquotIds,
String comments, String creator, String creationDate) throws Exception {
IDataAccess ida = (new DataAccessProxy()).getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
//load run object
logger.debug("ExecuteWorkflowService.saveRunAliquots(): run id = " + runId);
Run doRun = (Run)ida.load(Run.class, StringUtils.convertToLong(runId));
// Create RunSampleContainer collection
for (int i=0;i<aliquotIds.length;i++) {
// check if the aliquot has been assigned to the run, if it is, skip it
String hqlString ="select count(runcontainer.id) from RunSampleContainer runcontainer where runcontainer.run.id='" + runId +
"' and runcontainer.sampleContainer.id='" + aliquotIds[i] + "'";
List results = ida.search(hqlString);
if (((Integer)results.get(0)).intValue() > 0)
{
logger.debug("The aliquot id " + aliquotIds[i] + " is already assigned to this run, continue .... " );
continue;
}
RunSampleContainer doRunSC = new RunSampleContainer();
doRunSC.setComments(comments);
doRunSC.setRun(doRun);
logger.debug("ExecuteWorkflowService.saveRunAliquots(): aliquot id = " + aliquotIds[i]);
Aliquot doAliquot = (Aliquot)ida.load(Aliquot.class, StringUtils.convertToLong(aliquotIds[i]));
logger.debug("ExecuteWorkflowService.saveRunAliquots(): doAliquot = " + doAliquot);
doRunSC.setSampleContainer(doAliquot);
doRunSC.setCreatedBy(creator);
doRunSC.setCreatedDate(StringUtils.convertToDate(creationDate, CalabConstants.DATE_FORMAT));
ida.createObject(doRunSC);
}
ida.close();
} catch (Exception e) {
ida.rollback();
logger.error("Error in saving Run Aliquot ", e);
throw new RuntimeException("Error in saving Run Aliquot ");
}finally {
ida.close();
}
}
public AliquotBean getAliquot(String aliquotId) throws Exception {
AliquotBean aliquotBean = new AliquotBean();
IDataAccess ida = (new DataAccessProxy()).getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
String hqlString = "from Aliquot aliquot where aliquot.id ='" + aliquotId+ "'";
List results = ida.search(hqlString);
for (Object obj : results) {
Aliquot doAliquot = (Aliquot) obj;
aliquotBean.setAliquotId(aliquotId); // name
aliquotBean.setAliquotName(doAliquot.getName());
aliquotBean.setCreationDate(StringUtils.convertDateToString(doAliquot.getCreatedDate(), CalabConstants.DATE_FORMAT));
aliquotBean.setCreator(doAliquot.getCreatedBy());
aliquotBean.setHowCreated(doAliquot.getCreatedMethod());
String maskStatus = (doAliquot.getDataStatus() == null)?CalabConstants.ACTIVE_STATUS:CalabConstants.MASK_STATUS;
aliquotBean.setMaskStatus(maskStatus);
// ContainerBean
ContainerBean containerBean = new ContainerBean();
if (doAliquot.getConcentration() != null){
containerBean.setConcentration(doAliquot.getConcentration().toString());
containerBean.setConcentrationUnit(doAliquot.getConcentrationUnit());
}
containerBean.setContainerComments(doAliquot.getComments());
containerBean.setContainerType(doAliquot.getContainerType());
if (doAliquot.getQuantity() != null) {
containerBean.setQuantity(doAliquot.getQuantity().toString());
containerBean.setQuantityUnit(doAliquot.getQuantityUnit());
}
containerBean.setSafetyPrecaution(doAliquot.getSafetyPrecaution());
containerBean.setSolvent(doAliquot.getDiluentsSolvent());
containerBean.setStorageCondition(doAliquot.getStorageCondition());
if (doAliquot.getVolume() != null) {
containerBean.setVolume(doAliquot.getVolume().toString());
containerBean.setVolumeUnit(doAliquot.getVolumeUnit());
}
// containerBean.setStorageLocationStr();
StorageLocation location = new StorageLocation();
Set storageElements = (Set)doAliquot.getStorageElementCollection();
for(Object storageObj: storageElements) {
StorageElement element = (StorageElement)storageObj;
if (element.getType().equals(CalabConstants.STORAGE_ROOM)) {
location.setRoom(element.getLocation());
} else if (element.getType().equals(CalabConstants.STORAGE_FREEZER)) {
location.setFreezer(element.getLocation());
} else if (element.getType().equals(CalabConstants.STORAGE_SHELF)) {
location.setShelf(element.getLocation());
} else if (element.getType().equals(CalabConstants.STORAGE_BOX)) {
location.setBox(element.getLocation());
} else if (element.getType().equals(CalabConstants.STORAGE_RACK)) {
location.setRack(element.getLocation());
} else if (element.getType().equals(CalabConstants.STORAGE_LAB)) {
location.setLab(element.getLocation());
}
}
containerBean.setStorageLocation(location);
aliquotBean.setContainer(containerBean);
}
} catch (Exception e) {
logger.error("Error in retrieving aliquot information with id -- " + aliquotId, e);
throw new RuntimeException("Error in retrieving aliquot information with name -- " + aliquotId);
} finally {
ida.close();
}
if (aliquotBean.getAliquotId().length()==0) {
return null;
}
return aliquotBean;
}
/**
* Save the aliquot IDs to be associated with the given run ID.
* @param assayId
* @param runBy
* @param runDate
* @param createdBy
* @param createdDate
* @throws Exception
*/
public String saveRun(String assayId, String runBy, String runDate,String createdBy, String createdDate ) throws Exception {
// Details of Saving to RUN Table
Long runId; // Run Id is the primary key of the saved Run
IDataAccess ida = (new DataAccessProxy()).getInstance(IDataAccess.HIBERNATE);
logger.debug("ExecuteWorkflowService.saveRun(): assayId = " + assayId);
try {
ida.open();
Run doRun = new Run();
// Retrieve the max sequence number for assay run
String runName = CalabConstants.RUN + (getLastAssayRunNum(ida,assayId)+1);
logger.debug("ExecuteWorkflowService.saveRun(): new run name = " + runName);
doRun.setName(runName);
doRun.setCreatedBy(createdBy);
doRun.setCreatedDate(StringUtils.convertToDate(createdDate, CalabConstants.DATE_FORMAT));
doRun.setRunBy(runBy);
doRun.setRunDate(StringUtils.convertToDate(runDate, CalabConstants.DATE_FORMAT));
doRun.setAssay((Assay)ida.load(Assay.class, StringUtils.convertToLong(assayId)));
runId = (Long)ida.createObject(doRun);
} catch (Exception e) {
e.printStackTrace();
ida.rollback();
logger.error("Error in creating Run for assay. ", e);
throw new RuntimeException("Error in creating Run for assay. ");
} finally {
ida.close();
}
return runId.toString();
}
private int getLastAssayRunNum(IDataAccess ida, String assayId) {
int runNum = 0;
try {
String hqlString = "select run.name from Run run join run.assay assay where assay.id='" + assayId + "'";
List results = ida.search(hqlString);
for (Object obj : results) {
String runName = (String)obj;
int runSeqNum = Integer.parseInt(runName.substring(CalabConstants.RUN.length()).trim());
if (runSeqNum > runNum) {
runNum = runSeqNum;
}
}
} catch (Exception e) {
logger.error("Error in retrieving the last aliquot child aliquot number",e);
throw new RuntimeException(
"Error in retrieving the last aliquot child aliquot number");
}
return runNum;
}
public ExecuteWorkflowBean getExecuteWorkflowBean() throws Exception {
IDataAccess ida = (new DataAccessProxy()).getInstance(IDataAccess.HIBERNATE);
ExecuteWorkflowBean workflowBean = new ExecuteWorkflowBean();
int assayTypeCount = 0;
int assayCount= 0;
int runCount = 0;
int aliquotCount = 0;
int inputFileCount = 0;
try {
ida.open();
HashMap<String, List<AssayBean>> typedAssayBeans = new HashMap<String, List<AssayBean>>();
// Get all assay for AssayType
String hqlString = "from AssayType assayType order by assayType.executeOrder";
List results = ida.search(hqlString);
assayTypeCount = results.size();
for (Object obj: results) {
String assayTypeName = ((AssayType)obj).getName();
List<AssayBean> assays = new ArrayList<AssayBean>();
try {
hqlString = "from Assay assay where assay.assayType ='" + assayTypeName +"'";
List assayResults = ida.search(hqlString);
assayCount = assayCount + assayResults.size();
for (Object assay: assayResults){
Assay doAssay = (Assay)assay;
AssayBean assayBean = new AssayBean();
assayBean.setAssayId(doAssay.getId().toString());
assayBean.setAssayName(doAssay.getName());
assayBean.setAssayType(doAssay.getAssayType());
Set runs = (Set)doAssay.getRunCollection();
runCount = runCount + runs.size();
List<RunBean> runBeans = new ArrayList<RunBean>();
for (Object run: runs) {
Run doRun = (Run)run;
RunBean runBean = new RunBean();
runBean.setId(doRun.getId().toString());
runBean.setName(doRun.getName());
runBean.setAssayBean(assayBean);
Set runAliquots = (Set)doRun.getRunSampleContainerCollection();
aliquotCount = aliquotCount + runAliquots.size();
List<AliquotBean> aliquotBeans= new ArrayList<AliquotBean>();
for(Object runAliquot: runAliquots){
RunSampleContainer doRunAliquot = (RunSampleContainer)runAliquot;
// Have to load the class to get away the classcastexception (Cast Lazy loaded SampleContainer to Aliquot)
Aliquot container = (Aliquot)ida.load(Aliquot.class, doRunAliquot.getSampleContainer().getId());
// System.out.println("container class type = " + container.getClass().getName());
// TODO: suppose no need to check instanceof, since run only association with Aliquot
if (container instanceof Aliquot) {
Aliquot doAliquot = (Aliquot)container;
String maskStatus=(doAliquot.getDataStatus()==null)?CalabConstants.ACTIVE_STATUS:doAliquot.getDataStatus().getStatus();
AliquotBean aliquotBean = new AliquotBean(doAliquot.getId().toString(), doAliquot.getName(), maskStatus);;
aliquotBeans.add(aliquotBean);
}
}
//sort aliquots by name
Collections.sort(aliquotBeans, new CalabComparators.AliquotBeanComparator());
runBean.setAliquotBeans(aliquotBeans);
Set inputFiles = (Set)doRun.getInputFileCollection();
inputFileCount = inputFileCount + inputFiles.size();
List<FileBean> inputFileBeans = new ArrayList<FileBean>();
for (Object infile: inputFiles) {
InputFile doInputFile = (InputFile)infile;
FileBean infileBean = new FileBean();
infileBean.setId(doInputFile.getId().toString());
infileBean.setPath(doInputFile.getPath());
infileBean.setCreatedDate(doInputFile.getCreatedDate());
infileBean.setShortFilename(doInputFile.getFilename());
infileBean.setInoutType(CalabConstants.INPUT);
if (doInputFile.getDataStatus() == null) {
infileBean.setFileMaskStatus(CalabConstants.ACTIVE_STATUS);
} else {
infileBean.setFileMaskStatus(CalabConstants.MASK_STATUS);
}
inputFileBeans.add(infileBean);
}
runBean.setInputFileBeans(inputFileBeans);
Set outputFiles = (Set)doRun.getOutputFileCollection();
List<FileBean> outputFileBeans = new ArrayList<FileBean>();
for (Object outfile: outputFiles) {
OutputFile doOutputFile = (OutputFile)outfile;
FileBean outfileBean = new FileBean();
outfileBean.setId(doOutputFile.getId().toString());
outfileBean.setPath(doOutputFile.getPath());
outfileBean.setCreatedDate(doOutputFile.getCreatedDate());
outfileBean.setShortFilename(doOutputFile.getFilename());
outfileBean.setInoutType(CalabConstants.OUTPUT);
if (doOutputFile.getDataStatus() == null) {
outfileBean.setFileMaskStatus(CalabConstants.ACTIVE_STATUS);
} else {
outfileBean.setFileMaskStatus(CalabConstants.MASK_STATUS);
}
outputFileBeans.add(outfileBean);
}
runBean.setOutputFileBeans(outputFileBeans);
runBeans.add(runBean);
}
//sort runBeans by runNumber
Collections.sort(runBeans, new CalabComparators.RunBeanComparator());
assayBean.setRunBeans(runBeans);
assays.add(assayBean);
}
} catch (Exception e) {
logger.error("Error in retrieving assay by assayType -- " + assayTypeName, e);
throw new Exception("Error in retrieving assay by assayType -- " + assayTypeName);
}
// sort assayBeans by type, prefix and number
CalabComparators.AssayBeanComparator assayBeanComparator = new CalabComparators.AssayBeanComparator();
Collections.sort(assays, assayBeanComparator);
typedAssayBeans.put(assayTypeName, assays);
}
// Get all count
workflowBean.setAssayTypeCount(assayTypeCount);
workflowBean.setAssayCount(assayCount);
workflowBean.setRunCount(runCount);
workflowBean.setAliquotCount(aliquotCount);
workflowBean.setInputFileCount(inputFileCount);
workflowBean.setAssayBeanMap(typedAssayBeans);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Error in retriving execute workflow objects ");
} finally {
ida.close();
}
return workflowBean;
}
/**
* Save the aliquot IDs to be associated with the given run ID.
* @param fileURI
* @param fileName
* @param runId
* @throws Exception
*/
public void saveFile(List<HttpUploadedFileData> fileList, String filepath, String runId, String inout, String creator) throws Exception {
// fileList is a list of HttpUploadedFileData
Date date = Calendar.getInstance().getTime();
IDataAccess ida = (new DataAccessProxy()).getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
// TODO: only one run should be returned
Run doRun = (Run)ida.load(Run.class, StringUtils.convertToLong(runId));
// String assayName = doRun.getAssay().getName();
// String assayType = doRun.getAssay().getAssayType();
for (HttpUploadedFileData fileData: fileList) {
if (inout.equalsIgnoreCase(CalabConstants.INPUT)) {
InputFile doInputFile = new InputFile();
doInputFile.setRun(doRun);
doInputFile.setCreatedBy(creator);
doInputFile.setCreatedDate(date);
FileNameConvertor fconvertor = new FileNameConvertor();
String filename = fconvertor.getConvertedFileName(fileData.getFileName());
doInputFile.setPath(filepath + CalabConstants.URI_SEPERATOR + filename);
doInputFile.setFilename(getShortFilename(filename));
ida.store(doInputFile);
// logger.info("Object object retruned from inputfile = " + object);
} else if (inout.equalsIgnoreCase(CalabConstants.OUTPUT)) {
OutputFile doOutputFile = new OutputFile();
doOutputFile.setRun(doRun);
doOutputFile.setCreatedBy(creator);
doOutputFile.setCreatedDate(date);
System.out.println("ExecuteWorkflowService.saveFile(): output file created Date = " + date);
FileNameConvertor fconvertor = new FileNameConvertor();
String filename = fconvertor.getConvertedFileName(fileData.getFileName());
doOutputFile.setPath(filepath + CalabConstants.URI_SEPERATOR + fconvertor.getConvertedFileName(fileData.getFileName()));
doOutputFile.setFilename(getShortFilename(filename));
ida.store(doOutputFile);
}
}
} catch (Exception e) {
ida.rollback();
e.printStackTrace();
throw new RuntimeException("Error in persist File information for run -> " + runId + " | " + inout);
} finally {
ida.close();
}
}
public RunBean getAssayInfoByRun(ExecuteWorkflowBean workflowBean, String runId)
{
if (workflowBean != null) {
Collection<List<AssayBean>> typedAssayBeans = workflowBean.getAssayBeanMap().values();
for (List<AssayBean> assayBeans: typedAssayBeans) {
for (AssayBean assayBean: assayBeans) {
for (RunBean runBean: assayBean.getRunBeans()) {
if (runBean.getId().equals(runId)) {
return runBean;
}
}
}
}
logger.debug("Could not find Run's assay info for Run ID = " + runId);
return null;
} else {
return null;
}
}
public List<FileBean> getLastesFileListByRun(String runId, String type) throws Exception {
IDataAccess ida = (new DataAccessProxy()).getInstance(IDataAccess.HIBERNATE);
List<FileBean> fileBeans = new ArrayList<FileBean>();
try {
ida.open();
// Run doRun = (Run)ida.load(Run.class, StringUtils.convertToLong(runId));
Run doRun = null;
String hqlString = "from Run run where run.id='" + runId + "'";
List results = ida.search(hqlString);
for (Object obj: results) {
doRun = (Run)obj;
}
if (doRun == null) {
return fileBeans;
}
if (type.equalsIgnoreCase("input")) {
Set inputFiles = (Set)doRun.getInputFileCollection();
for (Object infile: inputFiles) {
InputFile doInputFile = (InputFile)infile;
FileBean infileBean = new FileBean();
infileBean.setId(doInputFile.getId().toString());
infileBean.setPath(doInputFile.getPath());
infileBean.setCreatedDate(doInputFile.getCreatedDate());
fileBeans.add(infileBean);
}
} else if (type.equalsIgnoreCase("output")) {
Set outputFiles = (Set)doRun.getOutputFileCollection();
for (Object outfile: outputFiles) {
OutputFile doOutputFile = (OutputFile)outfile;
FileBean outfileBean = new FileBean();
outfileBean.setId(doOutputFile.getId().toString());
outfileBean.setPath(doOutputFile.getPath());
outfileBean.setCreatedDate(doOutputFile.getCreatedDate());
fileBeans.add(outfileBean);
}
}
} catch (Exception e) {
e.printStackTrace();
ida.rollback();
logger.error("Error in retrieving updated file list. ", e);
throw new RuntimeException("Error in retrieving updated file list. ");
} finally {
ida.close();
}
return fileBeans;
}
private String getShortFilename(String longName) {
String shortname = "";
String[] tokens = longName.split("_");
//longname format as 20060419_15-16-42-557_filename.ext
int timeStampLength = (tokens[0].length()+tokens[1].length()+2);
shortname = longName.substring(timeStampLength);
return shortname;
}
public RunBean getRunBeanById(String runId) throws Exception {
IDataAccess ida = (new DataAccessProxy()).getInstance(IDataAccess.HIBERNATE);
RunBean runBean = new RunBean();
try {
ida.open();
String hqlString = "select run.name, assay.name, assay.assayType from Run run join run.assay assay where run.id='" + runId + "'";
List results = ida.search(hqlString);
for(Object obj: results){
Object[] values = (Object[])obj;
runBean.setName(StringUtils.convertToString(values[0]));
AssayBean assayBean = new AssayBean(StringUtils.convertToString(values[1]),StringUtils.convertToString(values[2]));
runBean.setAssayBean(assayBean);
break;
}
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
ida.close();
}
return runBean;
}
} |
package org.jmist.framework.services;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.UUID;
import org.jmist.framework.IJob;
import org.jmist.framework.IProgressMonitor;
import org.jmist.framework.ITaskWorker;
import org.jmist.framework.TaskDescription;
/**
* A job that submits a parallelizable job to a remote
* <code>JobServiceMaster<code>.
* @author bkimmel
*/
public final class ServiceWorkerJob implements IJob {
/**
* 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 milliseconds) to idle when no task is
* available.
*/
public ServiceWorkerJob(String masterHost, long idleTime) {
this.masterHost = masterHost;
this.idleTime = idleTime;
}
/* (non-Javadoc)
* @see org.jmist.framework.IJob#go(org.jmist.framework.IProgressMonitor)
*/
@Override
public void go(IProgressMonitor monitor) {
try {
monitor.notifyIndeterminantProgress();
monitor.notifyStatusChanged("Looking up master...");
Registry registry = LocateRegistry.getRegistry(this.masterHost);
IJobMasterService service = (IJobMasterService) registry.lookup("IJobMasterService");
ITaskWorker worker = null;
UUID jobId = new UUID(0, 0);
while (monitor.notifyIndeterminantProgress()) {
monitor.notifyStatusChanged("Requesting task...");
TaskDescription taskDesc = service.requestTask();
if (taskDesc != null) {
if (jobId != taskDesc.getJobId()) {
worker = service.getTaskWorker(taskDesc.getJobId());
jobId = taskDesc.getJobId();
}
assert(worker != null);
monitor.notifyStatusChanged("Performing task...");
Object results = worker.performTask(taskDesc.getTask(), monitor);
monitor.notifyStatusChanged("Submitting task results...");
service.submitTaskResults(jobId, taskDesc.getTaskId(), results);
} else { /* taskDesc == null */
monitor.notifyStatusChanged("Idling...");
try {
Thread.sleep(this.idleTime);
} catch (InterruptedException e) {
// continue.
}
}
}
monitor.notifyStatusChanged("Cancelled.");
} catch (Exception e) {
monitor.notifyStatusChanged("Exception: " + e.toString());
System.err.println("Client exception: " + e.toString());
e.printStackTrace();
} finally {
monitor.notifyCancelled();
}
}
/** The URL of the master. */
private final String masterHost;
/**
* The amount of time (in milliseconds) to idle when no task is available.
*/
private final long idleTime;
} |
package net.xprova.xprova;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import net.xprova.dot.GraphDotPrinter;
import net.xprova.graph.Graph;
import net.xprova.netlist.GateLibrary;
import net.xprova.netlist.Netlist;
import net.xprova.netlistgraph.Generator;
import net.xprova.netlistgraph.NetlistGraph;
import net.xprova.netlistgraph.NetlistGraphDotFormatter;
import net.xprova.netlistgraph.Vertex;
import net.xprova.piccolo.Command;
import net.xprova.piccolo.Console;
import net.xprova.propertylanguage.Property;
import net.xprova.propertylanguage.PropertyParser;
import net.xprova.simulations.CodeGenerator;
import net.xprova.verilogparser.VerilogParser;
public class ConsoleHandler {
private GateLibrary lib = null;
private NetlistGraph graph = null;
private PrintStream out = null;
private HashMap<String, FlipFlop> defsFF = null;
private ArrayList<Property> assumptions = null;
private ArrayList<Property> assertions = null;
public ConsoleHandler(PrintStream ps) {
out = ps;
defsFF = new HashMap<String, FlipFlop>();
assumptions = new ArrayList<Property>();
assertions = new ArrayList<Property>();
}
@Command(aliases = { "load_lib" }, description = "load a cell library")
public void loadLibrary(String libFile) throws Exception {
ArrayList<Netlist> libMods = VerilogParser.parseFile(libFile, new GateLibrary());
lib = new GateLibrary(libMods);
out.printf("Loaded %d modules from library %s\n", libMods.size(), libFile);
}
@Command(aliases = { "list_modules" }, description = "list the contents of the loaded cell library")
public void reportLibrary() {
if (lib == null) {
out.println("No library is currently loaded");
} else {
lib.printModules();
}
}
@Command(aliases = { "read_verilog" }, description = "read a gate-level verilog netlist")
public void readVerilogFile(String args[]) throws Exception {
// parse command input
Option optModule = Option.builder("m").desc("name of module").hasArg().argName("MODULE").required(false)
.build();
Options options = new Options();
options.addOption(optModule);
CommandLineParser parser = new DefaultParser();
CommandLine line;
line = parser.parse(options, args);
if (line.getArgList().isEmpty())
throw new Exception("no file specified");
// use first non-empty argument as file name
String verilogFile = "";
for (String str : line.getArgList())
if (!str.isEmpty())
verilogFile = str.trim();
Netlist selNetlist = null;
// read verilog file
if (lib == null) {
out.println("No library is current loaded");
} else {
ArrayList<Netlist> nls = VerilogParser.parseFile(verilogFile, lib);
String moduleName = line.getOptionValue("m", nls.get(0).name);
for (Netlist nl : nls) {
if (nl.name.equals(moduleName)) {
selNetlist = nl;
break;
}
}
if (selNetlist == null)
throw new Exception(String.format("Cannot find module <%s> in file <%s>", moduleName, verilogFile));
graph = new NetlistGraph(selNetlist);
out.printf("Loaded design <%s>\n", selNetlist.name);
}
}
@Command(aliases = { "write_verilog" }, description = "export current design as a verilog netlist")
public void writeVerilogFile(String args[]) throws Exception {
if (args.length != 1)
throw new Exception("requires one argument: filename");
String outputVerilogFile = args[0];
Generator.generateFile(graph, outputVerilogFile);
}
@Command(aliases = {
"export_dot" }, description = "export a graph representation of the loaded design in DOT format")
public void exportDotFile(String[] args) throws Exception {
// parse command input
Option optIgnoreEdges = Option.builder().desc("list of edges to ignore").hasArg().argName("IGNORE_EDGES")
.required(false).longOpt("ignore-edges").build();
Option optIgnoreVertices = Option.builder().desc("list of vertices to ignore").hasArg()
.argName("IGNORE_VERTICES").required(false).longOpt("ignore-vertices").build();
Option optType = Option.builder("t").longOpt("type").hasArg().desc("graph elements: ([n]ets|[g]ates|[f]lops)")
.build();
Option optTo = Option.builder().longOpt("to").hasArg().desc("destination flip-flop").build();
Option optCombine = Option.builder().longOpt("combine").hasArg().desc("list of vertex prefixes to combine")
.build();
Options options = new Options();
options.addOption(optIgnoreEdges);
options.addOption(optIgnoreVertices);
options.addOption(optType);
options.addOption(optTo);
options.addOption(optCombine);
CommandLineParser parser = new DefaultParser();
CommandLine line = parser.parse(options, args);
if (line.getArgList().isEmpty())
throw new Exception("no file specified");
// use first non-empty argument as file name
String dotFile = "";
for (String str : line.getArgList())
if (!str.isEmpty())
dotFile = str.trim();
// produce graph
if (graph == null) {
out.println("No design is currently loaded");
return;
}
NetlistGraph effectiveNetlist;
if (line.hasOption("to")) {
String vName = line.getOptionValue("to");
Vertex flop = graph.getVertex(vName);
if (flop == null) {
throw new Exception(
String.format("netlist <%s> does not contain flip-flip <%s>", graph.getName(), vName));
}
HashSet<Vertex> flipflops = graph.getModulesByTypes(defsFF.keySet());
HashSet<Vertex> flopInputVertices = graph.bfs(flop, flipflops, true);
Graph<Vertex> flopGraph = graph.reduce(flipflops);
flopInputVertices.add(flop);
flopInputVertices.addAll(flopGraph.getSources(flop));
effectiveNetlist = graph.getSubGraph(flopInputVertices);
} else {
effectiveNetlist = graph;
}
HashSet<Vertex> selectedVertices;
if (!line.hasOption('t')) {
// no type specified, include all vertex types (net, gate,
// flip-flop)
selectedVertices = effectiveNetlist.getVertices();
} else {
// vertex types were specified
String vTypes = line.getOptionValue('t');
selectedVertices = new HashSet<Vertex>();
HashSet<Vertex> flipflops = graph.getModulesByTypes(defsFF.keySet());
// are flipflops are flipflops2 the same?
HashSet<Vertex> gates = effectiveNetlist.getModules();
gates.removeAll(flipflops);
if (vTypes.contains("n"))
selectedVertices.addAll(effectiveNetlist.getNets());
if (vTypes.contains("f"))
selectedVertices.addAll(flipflops);
if (vTypes.contains("g"))
selectedVertices.addAll(gates);
}
Graph<Vertex> sg = effectiveNetlist.reduce(selectedVertices);
if (line.hasOption("combine")) {
for (String s : line.getOptionValue("combine").split(","))
combineVertices(s, selectedVertices, effectiveNetlist, sg);
}
NetlistGraphDotFormatter formatter = new NetlistGraphDotFormatter(graph);
if (line.hasOption("ignore-edges")) {
formatter.setIgnoredEdges(line.getOptionValue("ignore-edges").split(","));
}
if (line.hasOption("ignore-vertices")) {
formatter.setIgnoredVertices(line.getOptionValue("ignore-vertices").split(","));
}
GraphDotPrinter.printGraph(dotFile, sg, formatter, selectedVertices);
}
private void combineVertices(String prefix, HashSet<Vertex> selectedVertices, NetlistGraph effectiveNetlist,
Graph<Vertex> sg) throws Exception {
HashSet<Vertex> grp1 = new HashSet<Vertex>();
HashSet<String> grp1_types = new HashSet<String>();
Vertex comb = null;
int n = prefix.length();
for (Vertex v : selectedVertices) {
String upToNCharacters = v.name.substring(0, Math.min(v.name.length(), n));
if (upToNCharacters.equals(prefix)) {
grp1.add(v);
grp1_types.add(v.subtype);
comb = v;
}
}
if (!grp1.isEmpty()) {
grp1.remove(comb);
selectedVertices.removeAll(grp1);
comb.name = prefix;
if (grp1_types.size() > 1) {
comb.subtype = "BLOCK";
}
sg.combineVertices(comb, grp1);
}
}
@Command(aliases = {
"augment_netlist", }, description = "add metastable flip-flop models and associated connections")
public void augmentNetlist() throws Exception {
if (graph == null) {
out.println("No design is currently loaded");
} else {
Transformer t1 = new Transformer(graph, defsFF);
t1.transformCDC();
}
}
@Command(aliases = { "clear_ff_defs" }, description = "clear flip-flop definitions")
public void clearDefsFF(String[] args) {
// specify flip-flop modules
defsFF.clear();
}
@Command(aliases = { "def_ff" }, description = "define and specify the ports of a flip-flop cell")
public void addDefFF(String modName, String clkPort, String rstPort, String dPort) throws Exception {
if (defsFF.containsKey(modName)) {
throw new Exception(String.format("definition already exists for flip-flop <%s> ", modName));
} else {
FlipFlop ff = new FlipFlop(modName, clkPort, rstPort, dPort);
defsFF.put(modName, ff);
out.printf("defined flip-flop <%s>\n", modName);
}
}
@Command(aliases = { "list_ff" }, description = "list flip-flop definitions")
public void listDefFF() {
String strFormat = "%20s %14s %14s %14s\n";
out.print(String.format(strFormat, "Flip-flip Module", "Clock Port", "Reset Port", "Data Port"));
out.print(String.format(strFormat, "
for (FlipFlop f : defsFF.values()) {
out.print(String.format(strFormat, f.moduleName, f.clkPort, f.rstPort, f.dPort));
}
}
@Command(aliases = { "report_domains" }, description = "print list of clock domains in current design")
public void reportClockDomains() throws Exception {
Transformer t1 = new Transformer(graph, defsFF);
HashSet<Vertex> clks = t1.getClocks();
String strFormat = "%20s %14s\n";
out.printf("Found %d clock domain(s):\n\n", clks.size());
out.print(String.format(strFormat, "Clock Domain Net", " FFs"));
out.print(String.format(strFormat, "
for (Vertex clk : clks) {
int count = t1.getDomainFlops(clk).size();
out.print(String.format(strFormat, clk, count));
}
}
@Command(aliases = { "report_xpaths" }, description = "print list of crossover paths in current design")
public void reportCrossoverPaths() {
String strFormat = "%20s -> %20s";
ArrayList<String> paths = new ArrayList<String>();
HashSet<Vertex> flops = graph.getModulesByTypes(defsFF.keySet());
Graph<Vertex> ffGraph = graph.reduce(flops);
for (Vertex src : flops) {
for (Vertex dst : ffGraph.getDestinations(src)) {
Vertex clk1 = graph.getNet(src, defsFF.get(src.subtype).clkPort);
Vertex clk2 = graph.getNet(dst, defsFF.get(dst.subtype).clkPort);
if (clk1 != clk2)
paths.add(String.format(strFormat, src, dst));
}
}
Collections.sort(paths);
// output
out.printf("Found %d crossover paths:\n\n", paths.size());
for (String p : paths) {
out.println(p);
}
}
@Command(aliases = { "rename_modules" }, description = "rename modules according to their types")
public void renameModules(String args[]) throws ParseException {
// rename modules
final String modStr = "%s%d";
// parse input
Option optIgnore = Option.builder().desc("list of nets to ignore").hasArg().argName("IGNORE_NETS")
.required(false).longOpt("ignore").build();
Options options = new Options();
options.addOption(optIgnore);
CommandLineParser parser = new DefaultParser();
CommandLine line = parser.parse(options, args);
String ignoreStr = line.getOptionValue("ignore", "");
HashSet<String> ignored = new HashSet<String>(Arrays.asList(ignoreStr.split(",")));
List<Vertex> sortedMods = new ArrayList<Vertex>(graph.getModules());
Collections.sort(sortedMods, new Comparator<Vertex>() {
@Override
public int compare(Vertex arg0, Vertex arg1) {
return arg0.name.compareTo(arg1.name);
}
});
HashMap<String, Integer> modCounts = new HashMap<String, Integer>();
for (Vertex v : sortedMods) {
if (!ignored.contains(v.name)) {
String lowerMod = v.subtype.toLowerCase();
Integer c = modCounts.get(lowerMod);
c = (c == null) ? 1 : c + 1;
v.name = String.format(modStr, lowerMod, c);
modCounts.put(lowerMod, c);
}
}
}
@Command(aliases = { "rename_nets" }, description = "rename nets as n1, n2 ...")
public void renameNets(String args[]) throws ParseException {
// renames internal (i.e. non-port) nets
// parse input
Option optIgnore = Option.builder().desc("list of nets to ignore").hasArg().argName("IGNORE_NETS")
.required(false).longOpt("ignore").build();
Option optFormat = Option.builder().desc("net naming format").hasArg().argName("FORMAT").required(false)
.longOpt("format").build();
Options options = new Options();
options.addOption(optIgnore);
options.addOption(optFormat);
CommandLineParser parser = new DefaultParser();
CommandLine line = parser.parse(options, args);
String ignoreStr = line.getOptionValue("ignore", "");
HashSet<String> ignored = new HashSet<String>(Arrays.asList(ignoreStr.split(",")));
String netStr = line.getOptionValue("format", "n%d");
// rename nets
int netCount = 0;
HashSet<Vertex> nonIO = graph.getNets();
nonIO.removeAll(graph.getIONets());
List<Vertex> nonIOList = new ArrayList<Vertex>(nonIO);
Collections.sort(nonIOList, new Comparator<Vertex>() {
@Override
public int compare(Vertex arg0, Vertex arg1) {
return arg0.name.compareTo(arg1.name);
}
});
for (Vertex n : nonIOList) {
if (!ignored.contains(n.name)) {
String jNetName = n.name;
// to obtain a Java-friendly variable name,
// replace all non-word chars with underscores
jNetName = jNetName.replaceAll("[\\W]+", "_");
netCount += 1;
String nn = netStr;
nn = nn.replace("%d", "" + netCount);
nn = nn.replace("%s", "" + jNetName);
n.name = nn;
}
}
}
@Command(aliases = { "prove" }, description = "attempt to prove defined assertions")
public void proveAssertions(String args[]) throws Exception {
// options:
// --printcode
// --norun
// parse command input
Option optPrintCode = Option.builder().desc("print generated code").required(false).longOpt("printcode")
.build();
Option optNoRun = Option.builder().desc("do not execute generated code").required(false).longOpt("norun")
.build();
Option optNoCounter = Option.builder().desc("do not print counter-example (if found)").required(false)
.longOpt("nocounter").build();
Options options = new Options();
options.addOption(optPrintCode);
options.addOption(optNoRun);
options.addOption(optNoCounter);
CommandLineParser parser = new DefaultParser();
CommandLine line = parser.parse(options, args);
// code:
if (graph == null)
throw new Exception("no design is loaded");
String invokeArgs = line.hasOption("nocounter") ? "" : "gen-counter-example";
String templateResourceFile = "template1.j";
String javaFileStr = "CodeSimulator.java";
String classFileStr = "CodeSimulator";
File tempDir = new File(System.getProperty("java.io.tmpdir"));
File javaFile = new File(tempDir, javaFileStr);
String cmd = "javac " + javaFile.getAbsolutePath();
String cmd2 = String.format("java -classpath %s %s %s", tempDir.getAbsolutePath(), classFileStr, invokeArgs);
// generate code
String templateCode = loadResourceString(templateResourceFile);
CodeGenerator cg = new CodeGenerator(graph, assumptions, assertions);
ArrayList<String> lines = cg.generate(templateCode);
if (line.hasOption("printcode")) {
for (String l : lines)
out.println(l);
}
if (!line.hasOption("norun")) {
out.println("Saving code to " + javaFile.getAbsolutePath() + " ...");
PrintStream fout = new PrintStream(javaFile);
for (String l : lines)
fout.println(l);
fout.close();
// compile using javac
out.println("Compiling ...");
final Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(cmd);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
String s;
while ((s = stdError.readLine()) != null)
out.println(s);
while ((s = stdInput.readLine()) != null)
out.println(s);
stdInput.close();
stdError.close();
proc.waitFor();
if (proc.exitValue() != 0) {
throw new Exception("Compilation failed");
}
// run code
out.println("Executing compiled code ...");
Process proc2 = rt.exec(cmd2);
proc.waitFor();
BufferedReader stdInput2 = new BufferedReader(new InputStreamReader(proc2.getInputStream()));
BufferedReader stdError2 = new BufferedReader(new InputStreamReader(proc2.getErrorStream()));
while ((s = stdError2.readLine()) != null)
out.println(s);
while ((s = stdInput2.readLine()) != null)
out.println(s);
}
}
private static String loadResourceString(String file) {
Scanner s = null;
String bannerFileContent;
try {
final InputStream stream;
stream = Console.class.getClassLoader().getResourceAsStream(file);
s = new Scanner(stream);
bannerFileContent = s.useDelimiter("\\Z").next();
} catch (Exception e) {
bannerFileContent = "<could not load internal file>\n";
} finally {
if (s != null)
s.close();
}
return bannerFileContent;
}
@Command(aliases = { "ungroup_nets" }, description = "split arrays into individual nets")
public void ungroupNets(String args[]) {
String netNameFormat = args.length == 0 ? "%s_%d_" : String.join(" ", args);
for (Vertex v : graph.getNets()) {
int k1 = v.name.indexOf("[");
int k2 = v.name.indexOf("]");
String name = v.name;
int bit = 0;
if (k1 != -1 && k2 != -1) {
name = v.name.substring(0, k1);
bit = Integer.valueOf(v.name.substring(k1 + 1, k2));
v.name = String.format(netNameFormat, name, bit);
}
}
}
@Command(aliases = { "synth_verilog" }, description = "synthesize behavioral verilog design using yosys")
public void synthBehavioralDesign(String args[]) throws Exception {
// TODO: implement the following switches
// -v : verbose mode, show output of yosys
// --lib myfile.lib: specify custom library for yosys
String behavioralDesign = args[0];
String synthDesign = args[1];
(new SynthesisEngine()).synthesis(behavioralDesign, synthDesign, out);
}
@Command(description = "add an assumption for formal verification")
public void assume(String args[]) {
String pStr = String.join(" ", args);
PropertyParser pp = new PropertyParser();
assumptions.add(pp.parse(pStr));
}
@Command(aliases = { "assert" }, description = "add an assertion for formal verification")
public void assertp(String args[]) {
String pStr = String.join(" ", args);
PropertyParser pp = new PropertyParser();
assertions.add(pp.parse(pStr));
}
@Command(description = "print a list of design properties (assumptions and assertions)")
public void list_properties(String args[]) throws Exception {
System.out.println("Properties:");
for (Property p : assumptions)
System.out.println("* assumption : " + p);
for (Property p : assertions)
System.out.println("* assertion : " + p);
}
} |
package gov.nih.nci.ncicb.cadsr.loader.validator;
import gov.nih.nci.ncicb.cadsr.domain.Concept;
import gov.nih.nci.ncicb.cadsr.domain.DomainObjectFactory;
import gov.nih.nci.ncicb.cadsr.loader.ElementsLists;
import gov.nih.nci.ncicb.cadsr.loader.event.ProgressEvent;
import gov.nih.nci.ncicb.cadsr.loader.event.ProgressListener;
import gov.nih.nci.ncicb.cadsr.loader.ext.EvsModule;
import gov.nih.nci.ncicb.cadsr.loader.ext.EvsResult;
import gov.nih.nci.ncicb.cadsr.loader.util.PropertyAccessor;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
public class ConceptValidator implements Validator
{
private ValidationItems items = ValidationItems.getInstance();
private EvsModule module = new EvsModule();
private ProgressListener progressListener;
public ConceptValidator()
{
}
public void addProgressListener(ProgressListener l) {
progressListener = l;
}
public ValidationItems validate() {
List<Concept> concepts = ElementsLists.getInstance().
getElements(DomainObjectFactory.newConcept());
final ExecutorService executor = Executors.newFixedThreadPool(10);
final BlockingQueue<Future> futures = new LinkedBlockingQueue<Future>();
final Map<Future,Concept> futureConceptMap = new HashMap<Future,Concept>();
for(final Concept concept : concepts)
{
Future<ValidatedConcept> future = executor.submit(new Callable<ValidatedConcept>() {
public ValidatedConcept call() throws Exception {
EvsResult result = module.findByConceptCode(concept.getPreferredName(), false);
Collection<EvsResult> nameResult =
module.findByPreferredName(concept.getLongName(), false);
return new ValidatedConcept(concept, nameResult, result);
}
});
futures.add(future);
futureConceptMap.put(future, concept);
}
int pStatus = 0;
// wait for each future to complete
for(Future<ValidatedConcept> future : futures) {
final Concept con = futureConceptMap.get(future);
if(progressListener != null) {
ProgressEvent event = new ProgressEvent();
event.setMessage("Validating " + con.getLongName());
event.setStatus(pStatus++);
progressListener.newProgressEvent(event);
}
ValidatedConcept vc = null;
try {
// block until the future is ready
vc = future.get();
}
catch (Exception e) {
e.printStackTrace();
}
EvsResult result = vc.getResult();
if(result != null) {
if(con.getLongName() == null ||
!con.getLongName().equals(result.getConcept().getLongName())) {
items.addItem(new ValidationError(
PropertyAccessor.getProperty(
"mismatch.name.by.code", con.getLongName()),
new ConceptMismatchWrapper(1,result.getConcept(),con)));
//highlightDifferentNameByCode.add(result.getConcept());
//errorList.put(con, result.getConcept());
}
if(con.getPreferredDefinition() == null ||
!con.getPreferredDefinition().trim().equals(
result.getConcept().getPreferredDefinition().trim())) {
items.addItem(new MismatchDefByCodeError(
PropertyAccessor.getProperty(
"mismatch.def.by.code", con.getLongName()),new ConceptMismatchWrapper(2,result.getConcept(),con)));
//highlightDifferentDefByCode.add(result.getConcept());
//errorList.put(con, result.getConcept());
}
}
Collection<EvsResult> nameResult = vc.getNameResult();
if(nameResult != null && nameResult.size() == 1)
{
for(EvsResult name : nameResult) {
if(con.getPreferredName() == null ||
!con.getPreferredName().equals(
name.getConcept().getPreferredName())) {
items.addItem(new ValidationError(
PropertyAccessor.getProperty(
"mismatch.code.by.name", con.getLongName()),
new ConceptMismatchWrapper(3,name.getConcept(),con)));
//highlightDifferentCodeByName.add(name.getConcept());
//errorNameList.put(con, name.getConcept());
}
if(con.getPreferredDefinition() == null ||
!con.getPreferredDefinition().trim().equals(
name.getConcept().getPreferredDefinition().trim())) {
items.addItem(new ValidationError(
PropertyAccessor.getProperty(
"mismatch.def.by.name", con.getLongName()),
new ConceptMismatchWrapper(4,name.getConcept(),con)));
//highlightDifferentDefByName.add(name.getConcept());
//errorNameList.put(con, name.getConcept());
}
}
}
// a slight delay so that we can see the progress in the UI, since the
// futures tend to complete in batches
try {
Thread.sleep(20);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
return items;
}
/**
* These are the EVS query results for a given concept.
*/
public class ValidatedConcept {
private Concept concept;
private Collection<EvsResult> nameResult;
private EvsResult result;
public ValidatedConcept(Concept concept, Collection<EvsResult> nameResult, EvsResult result) {
this.concept = concept;
this.nameResult = nameResult;
this.result = result;
}
public Concept getConcept() {
return concept;
}
public Collection<EvsResult> getNameResult() {
return nameResult;
}
public EvsResult getResult() {
return result;
}
}
} |
package org.missionassetfund.apps.android.models;
import com.parse.ParseClassName;
import com.parse.ParseUser;
@ParseClassName("_User")
public class User extends ParseUser {
public static final String NAME_KEY = "name";
public static final String PHONE_NUMBER_KEY = "phoneNumber";
public static final String TOTAL_CASH_KEY = "totalCash";
public static final String SETUP_KEY = "setup";
public User() {
super();
}
public String getName() {
return getString(NAME_KEY);
}
public void setName(String name) {
put(NAME_KEY, name);
}
public String getPhoneNumber() {
return getString(PHONE_NUMBER_KEY);
}
public void setPhoneNumber(String phoneNumber) {
put(PHONE_NUMBER_KEY, phoneNumber);
}
public Double getTotalCash() {
return getDouble(TOTAL_CASH_KEY);
}
public void setTotalCash(Double liquidAsset) {
put(TOTAL_CASH_KEY, liquidAsset);
}
public boolean isSetup() {
return getBoolean(SETUP_KEY);
}
public void setSetup(boolean setup) {
put(SETUP_KEY, setup);
}
} |
package org.animotron.operator.query;
import static org.neo4j.graphdb.Direction.OUTGOING;
import static org.neo4j.graphdb.traversal.Evaluation.*;
import static org.animotron.graph.RelationshipTypes.REF;
import java.util.Set;
import javolution.util.FastSet;
import org.animotron.Executor;
import org.animotron.Statement;
import org.animotron.Statements;
import org.animotron.graph.AnimoGraph;
import org.animotron.graph.GraphOperation;
import org.animotron.io.PipedInput;
import org.animotron.manipulator.Evaluator;
import org.animotron.manipulator.OnQuestion;
import org.animotron.manipulator.PFlow;
import org.animotron.operator.AbstractOperator;
import org.animotron.operator.Cachable;
import org.animotron.operator.Evaluable;
import org.animotron.operator.IC;
import org.animotron.operator.Query;
import org.animotron.operator.Utils;
import org.animotron.operator.relation.HAVE;
import org.animotron.operator.relation.IS;
import org.jetlang.channels.Subscribable;
import org.jetlang.core.DisposingExecutor;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Path;
import org.neo4j.graphdb.PropertyContainer;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.traversal.Evaluation;
import org.neo4j.graphdb.traversal.TraversalDescription;
import org.neo4j.kernel.Traversal;
import org.neo4j.kernel.Uniqueness;
/**
* Query operator 'Get'. Return 'have' relations on provided context.
*
* @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a>
* @author <a href="mailto:gazdovsky@gmail.com">Evgeny Gazdovsky</a>
*/
public class GET extends AbstractOperator implements Evaluable, Query, Cachable {
public static final GET _ = new GET();
private GET() { super("get", "animo/query/extract"); }
private static TraversalDescription td_eval =
Traversal.description().
breadthFirst().
relationships(HAVE._.relationshipType(), OUTGOING);
//.evaluator(Evaluators.excludeStartPosition());
private static TraversalDescription td_eval_ic =
Traversal.description().
breadthFirst().
relationships(IS._.relationshipType(), OUTGOING).
relationships(IC._.relationshipType(), OUTGOING);
public OnQuestion onCalcQuestion() {
return question;
}
public static Relationship getHaveAtPFlow(PFlow pf, String name) {
final Path pflow = pf.getFlowPath();
//XXX: remove when getFlowPath fixed
if (pflow == null)
return null;
for (Relationship p : pflow.relationships()) {
if (p.getType().name().equals(HAVE._.rType) && _.name(p).equals(name)) {
return p;
}
}
return null;
}
private OnQuestion question = new OnQuestion() {
@Override
public void onMessage(final PFlow pf) {
final Relationship op = pf.getOP();
final Node node = op.getEndNode();
final String name = name(op);
final Relationship underHAVE = getHaveAtPFlow(pf, name);
System.out.println("GET '"+name(op));
//check, maybe, result was already calculated
if (!Utils.results(node, pf)) {
//no pre-calculated result, calculate it
Subscribable<Relationship> onContext = new Subscribable<Relationship>() {
@Override
public void onMessage(Relationship context) {
System.out.println("GET message ["+name+"] context "+context);
if (context == null) {
pf.sendAnswer(null);
return;
}
Set<Relationship> res = getByTraversal(underHAVE, op, context, name); //get(context.getEndNode(), name);
if (!res.isEmpty()) {
for (Relationship r : res)
pf.sendAnswer(r);
return;
}
PipedInput in;
try {
in = Evaluator._.execute(pf.getStartOP(), context.getEndNode());
for (Object n : in) {
Relationship r = get(((Relationship)n).getEndNode(), name);
if (r != null)
pf.sendAnswer(createResult(node, r));
}
} catch (Exception e) {
//XXX: what to do?
e.printStackTrace();
}
}
@Override
public DisposingExecutor getQueue() {
return Executor.getFiber();
}
};
pf.answer.subscribe(onContext);
if (haveContext(pf)) {
pf.addContextPoint(op);
super.onMessage(pf);
} else {
System.out.println("P-FLOW is context for GET!");
Set<Relationship> res = getByTraversal(underHAVE, op, pf.getStartOP(), name); //get(context.getEndNode(), name);
if (!res.isEmpty())
for (Relationship r : res)
pf.sendAnswer(r);
// Relationship res = null;
// boolean answered = false;
// for (Relationship stack : pf.stack()) {
// System.out.println("stack "+stack);
// res = get(stack.getEndNode(), name);
// if (res != null) {
// pf.sendAnswer(createResultInMemory(node, res));
// answered = true;
// } else {
// answered = goDownStack(pf, answered, name, node, stack);
// if (answered) break;
}
}
pf.done();
}
};
// private boolean goDownStack(PFlow pf, boolean answered, String name, Node node, Relationship pos) {
// Relationship res = null;
// //go by REF first
// System.out.println("go by REF");
// for (Relationship context : pf.getStackContext(pos, true)) {
// System.out.println(context);
// res = get(context.getEndNode(), name);
// if (res != null) {
// pf.sendAnswer(createResultInMemory(node, res));
// answered = true;
// if (!answered) {
// for (Relationship context : pf.getStackContext(pos, true)) {
// answered = answered || goDownStack(pf, answered, name, node, context);
// if (!answered) {
// //go by AN (references)
// System.out.println("go by AN");
// for (Relationship context : pf.getStackContext(pos, false)) {
// System.out.println(context);
// res = get(context.getEndNode(), name);
// if (res != null) {
// pf.sendAnswer(createResultInMemory(node, res));
// answered = true;
// if (!answered) {
// for (Relationship context : pf.getStackContext(pos, false)) {
// answered = answered || goDownStack(pf, answered, name, node, context);
// return answered;
public Relationship get(Node context, final String name) {
System.out.println("GET get context = "+context);
//search for local 'HAVE'
Relationship have = getByHave(context, name);
if (have != null) return have;
Relationship instance = context.getSingleRelationship(REF, OUTGOING);
if (instance != null) {
//change context to the-instance by REF
context = instance.getEndNode();
//search for have
have = getByHave(context, name);
if (have != null) return have;
}
Relationship prevTHE = null;
//search 'IC' by 'IS' topology
for (Relationship tdR : td_eval_ic.traverse(context).relationships()) {
Statement st = Statements.relationshipType( tdR.getType() );
if (st instanceof IS) {
System.out.println("GET IC -> IS "+tdR);
if (prevTHE != null) {
//search for have
have = getByHave(prevTHE.getEndNode(), name);
if (have != null) return have;
}
prevTHE = tdR;
} else if (st instanceof IC) {
System.out.print("GET IC -> "+tdR);
if (name.equals(name(tdR))) {
System.out.println(" MATCH");
//store
final Node sNode = context;
final Relationship r = tdR;
return AnimoGraph.execute(new GraphOperation<Relationship>() {
@Override
public Relationship execute() {
Relationship res = sNode.createRelationshipTo(r.getEndNode(), HAVE._.relationshipType());
//RID.set(res, r.getId());
return res;
}
});
//in-memory
//Relationship res = new InMemoryRelationship(context, tdR.getEndNode(), HAVE._.relationshipType());
//RID.set(res, tdR.getId());
//return res;
//as it
//return tdR;
}
System.out.println();
}
}
if (prevTHE != null) {
//search for have
have = getByHave(prevTHE.getEndNode(), name);
if (have != null) return have;
}
return null;
}
private Relationship getByHave(Node context, final String name) {
for (Relationship tdR : td_eval.traverse(context).relationships()) {
System.out.println("GET check = "+tdR);
if (name.equals(name(tdR)))
return tdR;
}
return null;
}
public Set<Relationship> getByTraversal(final Relationship underHAVE, final Relationship start_op, final PropertyContainer context, final String name) {
TraversalDescription td;
if (context instanceof Relationship) {
td = Traversal.description().depthFirst().
uniqueness(Uniqueness.RELATIONSHIP_PATH).
evaluator(new org.neo4j.graphdb.traversal.Evaluator(){
@Override
public Evaluation evaluate(Path path) {
if (path.length() > 0) {
Relationship r = path.lastRelationship();
if (r.getStartNode().equals(path.endNode())) {
if (r.equals(context)) {
return INCLUDE_AND_PRUNE;
}
// String rType = r.getType().name();
//second must be REF
// or it can be IS ! so, REF and HAVE after IS
// if (path.length() == 1 && !(rType.equals(RelationshipTypes.REF.name()) || rType.equals(IS._.rType)) ) {
// return EXCLUDE_AND_PRUNE;
// } else if (path.length() == 2 && !(rType.equals(HAVE._.rType) || rType.equals(IC._.rType))) {
// return EXCLUDE_AND_PRUNE;
return EXCLUDE_AND_CONTINUE;
//Allow ...<-IS->...
} if (path.length() > 2 && r.getType().name().equals(IS._.rType)) {
return EXCLUDE_AND_CONTINUE;
}
return EXCLUDE_AND_PRUNE;
}
return EXCLUDE_AND_CONTINUE;
}
});
} else {
//TODO: merge with prev. one
td = Traversal.description().depthFirst().
uniqueness(Uniqueness.RELATIONSHIP_PATH).
evaluator(new org.neo4j.graphdb.traversal.Evaluator(){
@Override
public Evaluation evaluate(Path path) {
if (path.length() > 0) {
Relationship r = path.lastRelationship();
if (r.getStartNode().equals(path.endNode())) {
if (r.getEndNode().equals(context)) {
return INCLUDE_AND_PRUNE;
}
return EXCLUDE_AND_CONTINUE;
}
return EXCLUDE_AND_PRUNE;
}
return EXCLUDE_AND_CONTINUE;
}
});
}
System.out.println("context = "+context+" start_op = "+start_op);
Node node = Utils.getByREF(start_op.getEndNode());
// for (Path path : td.traverse(node)) {
// System.out.println("path = "+path);
int deep = Integer.MAX_VALUE;
Set<Relationship> result = new FastSet<Relationship>();
Relationship thisResult = null;
int thisDeep = 0;
for (Path path : td.traverse(node)) {
System.out.println("path = "+path);
boolean foundIS = false;
boolean foundBackIS = false;
Relationship foundIC = null;
Node lastNode = null;
thisDeep = 0;
int step = 0;
boolean REFcase = false;
for (Relationship r : path.relationships()) {
step++;
String type = r.getType().name();
if (thisDeep > 0) {
if (type.equals(IS._.relationshipType().name()) && r.getStartNode().equals(lastNode)) {
lastNode = r.getEndNode();
foundBackIS = true;
} else {
lastNode = r.getStartNode();
}
thisDeep++;
continue;
}
if (step == 1 && type.equals(REF.name())) {
REFcase = true;
} else if (REFcase && step == 2 && !(type.equals(HAVE._.rType) || type.equals(IC._.rType))) {
break;
}
lastNode = r.getStartNode();
if (type.equals(IS._.relationshipType().name())) {
if (name.equals(IS._.name(r))) {
foundIS = true;
continue;
}
if (foundIC != null) {
thisResult = ICresult(context, foundIC);
thisDeep++;
continue;
}
} else if (type.equals(HAVE._.relationshipType().name()) && (name.equals(HAVE._.name(r)) || foundIS)) {
//ignore empty have
if (!Utils.haveContext(r.getEndNode()))
break;
//cycle detection
if (underHAVE != null && r.equals(underHAVE))
break;
thisResult = r;
thisDeep++;
} else if (type.equals(IC._.relationshipType().name()) && (name.equals(IC._.name(r)) || foundIS)) {
if (foundIS) {
thisResult = ICresult(context, r);
thisDeep++;
} else {
foundIC = r;
}
}
}
if (thisDeep == 0)
;
else if (thisDeep == deep && !foundBackIS) {
result.add(thisResult);
} else if (thisDeep < deep) {
result.clear();
result.add(thisResult);
deep = thisDeep;
}
}
return result;
}
private Relationship ICresult(PropertyContainer context, Relationship r) {
//store
final Node sNode;
if (context instanceof Relationship) {
sNode = ((Relationship)context).getEndNode();
} else {
sNode = (Node)context;
}
final Node eNode = r.getEndNode();
//avoid duplicate
for (Relationship h : sNode.getRelationships(HAVE._.relationshipType(), OUTGOING)) {
if (h.getEndNode().equals(eNode))
return h;
}
return AnimoGraph.execute(new GraphOperation<Relationship>() {
@Override
public Relationship execute() {
Relationship res = sNode.createRelationshipTo(eNode, HAVE._.relationshipType());
//RID.set(res, r.getId());
return res;
}
});
}
} |
// $Id: SpotSceneDirector.java,v 1.9 2001/12/16 22:09:17 mdb Exp $
package com.threerings.whirled.spot.client;
import java.util.Iterator;
import com.samskivert.util.StringUtil;
import com.threerings.presents.dobj.DObject;
import com.threerings.presents.dobj.DObjectManager;
import com.threerings.presents.dobj.ObjectAccessException;
import com.threerings.presents.dobj.Subscriber;
import com.threerings.crowd.chat.ChatDirector;
import com.threerings.crowd.client.LocationAdapter;
import com.threerings.crowd.client.LocationDirector;
import com.threerings.crowd.data.PlaceObject;
import com.threerings.whirled.client.SceneDirector;
import com.threerings.whirled.data.SceneModel;
import com.threerings.whirled.util.WhirledContext;
import com.threerings.whirled.spot.Log;
import com.threerings.whirled.spot.data.Location;
import com.threerings.whirled.spot.data.Portal;
/**
* Extends the standard scene director with facilities to move between
* locations within a scene.
*/
public class SpotSceneDirector
implements SpotCodes, Subscriber
{
/**
* This is used to communicate back to the caller of {@link
* #changeLocation}.
*/
public static interface ChangeObserver
{
/**
* Indicates that the requested location change succeeded.
*/
public void locationChangeSucceeded (int locationId);
/**
* Indicates that the requested location change failed and
* provides a reason code explaining the failure.
*/
public void locationChangeFailed (int locationId, String reason);
}
/**
* Creates a new spot scene director with the specified context and
* which will cooperate with the supplied scene director.
*
* @param ctx the active client context.
* @param locdir the location director with which we will be
* cooperating.
* @param scdir the scene director with which we will be cooperating.
*/
public SpotSceneDirector (WhirledContext ctx, LocationDirector locdir,
SceneDirector scdir)
{
_ctx = ctx;
_scdir = scdir;
// wire ourselves up to hear about leave place notifications
locdir.addLocationObserver(new LocationAdapter() {
public void locationDidChange (PlaceObject place) {
// we need to clear some things out when we leave a place
handleDeparture();
}
});
}
/**
* Configures this spot scene director with a chat director, with
* which it will coordinate to implement cluster chatting.
*/
public void setChatDirector (ChatDirector chatdir)
{
_chatdir = chatdir;
}
/**
* Requests that this client move to the location specified by the
* supplied portal id. A request will be made and when the response is
* received, the location observers will be notified of success or
* failure.
*/
public void traversePortal (int portalId)
{
// look up the destination scene and location
DisplaySpotScene scene = (DisplaySpotScene)_scdir.getScene();
if (scene == null) {
Log.warning("Requested to traverse portal when we have " +
"no scene [portalId=" + portalId + "].");
return;
}
// find the portal they're talking about
int targetSceneId = -1, targetLocId = -1;
Iterator portals = scene.getPortals().iterator();
while (portals.hasNext()) {
Portal portal = (Portal)portals.next();
if (portal.locationId == portalId) {
targetSceneId = portal.targetSceneId;
targetLocId = portal.targetLocId;
}
}
// make sure we found the portal
if (targetSceneId == -1) {
portals = scene.getPortals().iterator();
Log.warning("Requested to traverse non-existent portal " +
"[portalId=" + portalId +
", portals=" + StringUtil.toString(portals) + "].");
}
// prepare to move to this scene (sets up pending data)
if (!_scdir.prepareMoveTo(targetSceneId)) {
return;
}
// check the version of our cached copy of the scene to which
// we're requesting to move; if we were unable to load it, assume
// a cached version of zero
int sceneVer = 0;
SceneModel pendingModel = _scdir.getPendingModel();
if (pendingModel != null) {
sceneVer = pendingModel.version;
}
// issue a traversePortal request
SpotService.traversePortal(
_ctx.getClient(), scene.getId(), portalId, sceneVer, _scdir);
}
/**
* Issues a request to change our location within the scene to the
* location identified by the specified id. Most client entities find
* out about location changes via changes to the occupant info data,
* but the initiator of a location change request can be notified of
* its success or failure, primarily so that it can act in
* anticipation of a successful location change (like by starting a
* sprite moving toward the new location), but backtrack if it finds
* out that the location change failed.
*/
public void changeLocation (int locationId, ChangeObserver obs)
{
// refuse if there's a pending location change
if (_pendingLocId != -1) {
return;
}
// make sure we're currently in a scene
DisplaySpotScene scene = (DisplaySpotScene)_scdir.getScene();
if (scene == null) {
Log.warning("Requested to change locations, but we're not " +
"currently in any scene [locId=" + locationId + "].");
return;
}
// make sure the specified location is in the current scene
Location loc = scene.getLocation(locationId);
if (loc == null) {
Log.warning("Requested to change to a location that's not " +
"in the current scene [locs=" + StringUtil.toString(
scene.getLocations().iterator()) +
", locId=" + locationId + "].");
return;
}
// make a note that we're changing to this location
_pendingLocId = locationId;
_changeObserver = obs;
// and send the location change request
SpotService.changeLoc(_ctx.getClient(), scene.getId(),
locationId, this);
}
/**
* Sends a chat message to the other users in the cluster to which the
* location that we currently occupy belongs.
*
* @return true if a cluster speak message was delivered, false if we
* are not in a valid cluster and refused to deliver the request.
*/
public boolean requestClusterSpeak (String message)
{
// make sure we're currently in a scene
DisplaySpotScene scene = (DisplaySpotScene)_scdir.getScene();
if (scene == null) {
Log.warning("Requested to speak to cluster, but we're not " +
"currently in any scene [message=" + message + "].");
return false;
}
// make sure we're in a location
Location loc = scene.getLocation(_locationId);
if (loc == null) {
Log.info("Ignoring cluster speak as we're not in a valid " +
"location [locId=" + _locationId + "].");
return false;
}
// make sure the location has an associated cluster
if (loc.clusterIndex == -1) {
Log.info("Ignoring cluster speak as our location has no " +
"cluster [loc=" + loc + "].");
return false;
}
// we're all clear to go
SpotService.clusterSpeak(
_ctx.getClient(), scene.getId(), _locationId, message, this);
return true;
}
/**
* Called in response to a successful <code>changeLoc</code> request.
*/
public void handleChangeLocSucceeded (int invid, int clusterOid)
{
ChangeObserver obs = _changeObserver;
_locationId = _pendingLocId;
// clear out our pending location info
_pendingLocId = -1;
_changeObserver = null;
// determine if our cluster oid changed (which we only care about
// if we're doing cluster chat)
if (_chatdir != null) {
int oldOid = (_clobj == null) ? -1 : _clobj.getOid();
if (clusterOid != oldOid) {
DObjectManager omgr = _ctx.getDObjectManager();
// remove our old subscription if necessary
if (_clobj != null) {
_chatdir.removeAuxilliarySource(_clobj);
// unsubscribe from our old object
omgr.unsubscribeFromObject(_clobj.getOid(), this);
_clobj = null;
}
// create a new subscription (we'll wire it up to the chat
// director when the subscription completes
omgr.subscribeToObject(clusterOid, this);
}
}
// if we had an observer, let them know things went well
if (obs != null) {
obs.locationChangeSucceeded(_locationId);
}
}
/**
* Called in response to a failed <code>changeLoc</code> request.
*/
public void handleChangeLocFailed (int invid, String reason)
{
ChangeObserver obs = _changeObserver;
int locId = _pendingLocId;
// clear out our pending location info
_pendingLocId = -1;
_changeObserver = null;
// if we had an observer, let them know things went well
if (obs != null) {
obs.locationChangeFailed(locId, reason);
}
}
// documentation inherited
public void objectAvailable (DObject object)
{
// we've got our cluster chat object, configure the chat director
// with it and keep a reference ourselves
if (_chatdir != null) {
_chatdir.addAuxilliarySource(CLUSTER_CHAT_TYPE, object);
_clobj = object;
}
}
// documentation inherited
public void requestFailed (int oid, ObjectAccessException cause)
{
Log.warning("Unable to subscribe to cluster chat object " +
"[oid=" + oid + ",, cause=" + cause + "].");
}
/**
* Clean up after a few things when we depart from a scene.
*/
protected void handleDeparture ()
{
// clear out our last known location id
_locationId = -1;
// unwire and clear out our cluster chat object if we've got one
if (_chatdir != null && _clobj != null) {
// unwire the auxilliary chat object
_chatdir.removeAuxilliarySource(_clobj);
// unsubscribe as well
DObjectManager omgr = _ctx.getDObjectManager();
omgr.unsubscribeFromObject(_clobj.getOid(), this);
_clobj = null;
}
}
/** The active client context. */
protected WhirledContext _ctx;
/** The scene director with which we are cooperating. */
protected SceneDirector _scdir;
/** A reference to the chat director with which we coordinate. */
protected ChatDirector _chatdir;
/** The location id of the location we currently occupy. */
protected int _locationId = -1;
/** The location id on which we have an outstanding change location
* request. */
protected int _pendingLocId = -1;
/** The cluster chat object for the cluster we currently occupy. */
protected DObject _clobj;
/** An entity that wants to know if a requested location change
* succeded or failed. */
protected ChangeObserver _changeObserver;
} |
package org.u_compare.gui.control;
import java.awt.Container;
import java.util.ArrayList;
import org.u_compare.gui.component.ComponentPanel;
import org.u_compare.gui.model.AbstractAggregateComponent.InvalidPositionException;
import org.u_compare.gui.model.AbstractComponent.MinimizedStatusEnum;
import org.u_compare.gui.model.AggregateComponent;
import org.u_compare.gui.model.Component;
/**
*
* Controller responsible for handling user input directed at a specific
* component/workflow.
*
* @author Luke McCrohon
*
*/
public class ComponentController implements
DragAndDropController.DragController {
// The model corresponding to this class
protected Component component;
// The view corresponding to this class
protected ComponentPanel componentView;
// The parent controller of this object if it exists
private ComponentController parent;
private ArrayList<ComponentController> subControllers = new ArrayList<ComponentController>();
private ArrayList<DropTargetController> dropTargets = new ArrayList<DropTargetController>();
private ArrayList<ParameterController> parameterControllers = new ArrayList<ParameterController>();
protected final boolean allowEditing;
protected ComponentController(boolean allowEditing) {
this.allowEditing = allowEditing;
}
/**
* Create a controller object for the specified component.
*
* @param componentModel
* @throws NullPointerException
*/
public ComponentController(Component component, boolean allowEditing) {
this.allowEditing = allowEditing;
this.component = component;
this.componentView = new ComponentPanel(component, this);
if (allowEditing) {
DragAndDropController.registerDragSource(componentView, this);
}
}
private void setParent(ComponentController parent) {
this.parent = parent;
}
/**
* Needed so the constructor can collect subviews to pass to view
* constructor.
*
* @return
*/
public ComponentPanel getView() {
return this.componentView;
}
public void addFirstDropTarget(DropTargetController control) {
assert (dropTargets.size() == 0);
addDropTarget(control);
}
/**
* Called by componentView to set relevant controllers.
*
* @param param
*/
public void addParamaterController(ParameterController param) {
parameterControllers.add(param);
}
public void insert(ComponentController component,
DropTargetController following) {
addSubComponent(component);
addDropTarget(following);
}
/**
* For use during building view. Where possible use the insert method for
* adding a component and its following drop target.
*
* @param controller
*/
private void addDropTarget(DropTargetController control) {
dropTargets.add(control);
// special formatting for intermediate drop targets
if (dropTargets.size() > 2) {
dropTargets.get(dropTargets.size() - 2).setIntermediate();
} else if (dropTargets.size() == 2) {
dropTargets.get(0).clearSolitaryDropTarget();
}
}
private void addSubComponent(ComponentController subComponent) {
subControllers.add(subComponent);
subComponent.setParent(this);
}
public void resetSubComponents() {
dropTargets = new ArrayList<DropTargetController>();
subControllers = new ArrayList<ComponentController>();
// TODO do i need to reset subComponents parents?
}
public boolean isLocked() {
return component.getLockedStatus();
}
public void setLocked(boolean lockedStatus) {
if (lockedStatus) {
component.setLocked();
} else {
component.setUnlocked();
}
}
public void toggleLocked() {
setLocked(!isLocked());
}
public void toggleMinimized() {
switch (component.getMinimizedStatus()) {
case MINIMIZED:
component.setMinimizedStatus(MinimizedStatusEnum.PARTIAL);
break;
case PARTIAL:
component.setMinimizedStatus(MinimizedStatusEnum.MAXIMIZED);
break;
case MAXIMIZED:
component.setMinimizedStatus(MinimizedStatusEnum.MINIMIZED);
break;
}
}
/**
* Checks if the specified sub component can be added at the specified
* position. Needed to update graphics when dragging.
*
* @return true if it can be added at this location
*/
public boolean canAddSubComponent(ComponentController newControl,
int position) {
if (!newControl.canRemove() // check if newControl is able to be moved
// from current location
|| isLocked() // check if this component is locked.
|| !component.isAggregate() // make sure this component is an
// aggregate
|| isAnscestor(newControl) // Prohibit dropping of anscestors
) {
return false;
}
if (!subControllers.contains(newControl)) {
return ((AggregateComponent) component).canAddSubComponent(
newControl.component, position);
} else {
return ((AggregateComponent) component).canReorderSubComponent(
newControl.component, position);
}
}
/**
* Check whether the specified components is an anscestor of this component.
*
* @param comp
* @return
*/
private boolean isAnscestor(ComponentController comp) {
if (this == comp) {
return true;
}
if (parent == null) {
return false;
} else {
return parent.isAnscestor(comp);
}
}
/**
* Check whether this component can be removed from its current position.
*/
public boolean canRemove() {
if (parent != null) {
return parent.canRemoveSubComponent(this);
} else {
return !component.isWorkflow();// if a non-workflow component
// corresponds to not being in a
// postion
}
}
/**
* Checks whether the specified subComponent can be removed or not.
*
* @param toRemove
* @return True if it can be removed, false otherwise.
*/
public boolean canRemoveSubComponent(ComponentController toRemove) {
if (!isLocked() && component.isAggregate()) {
return ((AggregateComponent) component)
.canRemoveSubComponent(toRemove.component);
} else {
return false;
}
}
/**
* Called when a component is dragged from either another position in the
* workflow or from the component library.
*
* @param component
* @param position
* @throws InvalidSubComponentException
*/
public void addSubComponent(ComponentController subComponentController,
int position) throws InvalidSubComponentException {
if (canAddSubComponent(subComponentController, position)) {
// TODO this method is adding too many copies of the
// subComponentController
// Doesn't seem to have any negative affects, but likely to leave
// dangling memory references
// System.out.println("start " + subControllers.size());
try {
if (!subControllers.contains(subComponentController)) {
// System.out.println("mid1 " + subControllers.size());
subComponentController.removeComponent();
// System.out.println("mid2 " + subControllers.size());
// here
// This seems to be doing an add, which it shouldn't...
((AggregateComponent) component).addSubComponent(position,
subComponentController.component);
// /System.out.println("mid3 " + subControllers.size());
subComponentController.setParent(this);
// System.out.println("mid4 " + subControllers.size());
// and here
subControllers.add(subComponentController);
// System.out.println("mid5 " + subControllers.size());
} else {
((AggregateComponent) component).reorderSubComponent(
subComponentController.component, position);
}
} catch (InvalidPositionException e) {
// TODO this should never happen
}
} else {
throw new InvalidSubComponentException(
"Cannot add component here\nAggregate: "
+ component.isAggregate());
}
// System.out.println("End " + subControllers.size());
}
/**
* Removes this component from its current position in the model and
* controller.
*/
public void removeComponent() {
// Should never be called on the top level workflow component
assert (parent != null);
if (canRemove()) {
if (parent != null) {// If it has a parent already, remove it
parent.removeSubComponent(this);
}
}
}
/**
* Removes a child component from its current position in the workflow in
* both controller and model.
*/
public void removeSubComponent(ComponentController toRemove) {
if (!subControllers.contains(toRemove)) {
System.err
.println("ERROR: trying to remove non existing component.");
Thread.dumpStack();
return;
}
// Remove from controller
toRemove.setParent(null);
subControllers.remove(toRemove);
// Remove from model
((AggregateComponent) component).removeSubComponent(toRemove.component);
}
public void dropTargetRemoved(DropTargetController dropTargetController) {
for (int i = 0; i < dropTargets.size(); i++) {
if (dropTargets.get(i).equals(dropTargetController)) {
dropTargets.remove(i);
break;
}
}
}
/**
* Responds to a descendant drop target having the currently dragged
* component dropped on it.
*
* @param position
* The target where the component was dropped.
*/
public void somethingDroppedOnChild(DropTargetController position) {
if (!droppableOnChild(position)) {// Ignore drop
return;
}
int index = dropTargetToPosition(position);
try {
addSubComponent(getCurrentlyDragged(), index);
} catch (InvalidSubComponentException e) {
System.out.println("Invalid Sub Component Exception");
e.printStackTrace();
}
}
/**
* Used for dropping on New Workflow tab
*/
public void somethingDroppedOnTop() {
somethingDroppedOnChild(dropTargets.get(0));
}
/**
* Is it possible to drop the currently dragged component at the specified
* position?
*
* (Used for determining mouse over highlighting when dragging)
*
* @param position
* location to drop at.
* @return True if currently dragged component can be dropped there.
*/
public boolean droppableOnChild(DropTargetController position) {
return canAddSubComponent(getCurrentlyDragged(),
dropTargetToPosition(position));
}
@Override
public void setDragged() {
componentView.requestFocusInWindow();
DragAndDropController.getController().setDragged(this);
}
/**
* Converts a drop target controller to its position index.
*
* @param position
* @return The index of the specified position.
*/
private int dropTargetToPosition(DropTargetController position) {
for (int i = 0; i < dropTargets.size(); i++) {
if (dropTargets.get(i).equals(position)) {
return i;
}
}
return -1;
}
/**
* Gets the controller for the currently dragged component.
*
* @return Currently dragged component.
*/
private ComponentController getCurrentlyDragged() {
return DragAndDropController.getController().getDraggedComponent();
}
/**
* Validation needs to be handled at a level higher than the component that
* is being added/removed from.
*/
public void validateWorkflow() {
if (parent != null) {
parent.validateWorkflow();
} else {
Container parent = componentView.getParent();
if (parent != null) {
parent.validate();
} else {
System.out
.println("Component Controller: Validate changes failed as view's parent is null. Should not occur in full system, but may occur during unittests.");
}
}
}
public void setName(String title) {
component.setName(title);
}
public void setDescription(String descriptionText) {
component.setDescription(descriptionText);
}
/**
* Used only at construction time
*
* @return
*/
public boolean allowEditing() {
return allowEditing;
}
} |
package org.usfirst.frc.team2854.robot.commands;
import org.usfirst.frc.team2854.robot.oi.Axis;
import org.usfirst.frc.team2854.robot.subsystems.DriveTrain;
import edu.wpi.first.wpilibj.command.Command;
/**
* @author Richard Huang
*/
public class Drive extends Command{
private DriveTrain driveTrain;
private Axis leftTrigger,rightTrigger;
public Drive(DriveTrain pDriveTrain,Axis LT,Axis RT){
driveTrain=pDriveTrain;
leftTrigger=LT;
rightTrigger=RT;
}
// Called just before this Command runs the first time
protected void initialize(){
System.out.println("Initialized drive command");
requires(driveTrain);
}
// Called repeatedly when this Command is scheduled to run
protected void execute(){
driveTrain.tankDrive(sigmoid(leftTrigger.deadbandGet()),sigmoid(rightTrigger.deadbandGet()));
}
//smooth over driving with sigmoid function
private double sigmoid(double i){
return 2/(1+Math.pow(Math.E,-7*Math.pow(i,3)))-1;
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished(){
return false;
}
// Called once after isFinished returns true
protected void end(){
driveTrain.stop();
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted(){
driveTrain.stop();
}
} |
package org.apache.velocity.runtime.resource;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Map;
import org.apache.velocity.Template;
import org.apache.velocity.runtime.Runtime;
import org.apache.velocity.runtime.configuration.Configuration;
import org.apache.velocity.runtime.resource.ResourceFactory;
import org.apache.velocity.runtime.resource.loader.ResourceLoader;
import org.apache.velocity.runtime.resource.loader.ResourceLoaderFactory;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.exception.ParseErrorException;
/**
* Class to manage the text resource for the Velocity
* Runtime.
*
* @author <a href="mailto:jvanzyl@periapt.com">Jason van Zyl</a>
* @version $Id: ResourceManager.java,v 1.12 2001/03/04 00:40:02 jvanzyl Exp $
*/
public class ResourceManager
{
/**
* A template resources.
*/
public static final int RESOURCE_TEMPLATE = 1;
/**
* A static content resource.
*/
public static final int RESOURCE_CONTENT = 2;
/**
* Hashtable used to store templates that have been
* processed. Our simple caching mechanism.
*/
private static Hashtable globalCache = new Hashtable();
/**
* The List of templateLoaders that the Runtime will
* use to locate the InputStream source of a template.
*/
private static ArrayList resourceLoaders = new ArrayList();
/**
* This is a list of the template stream source
* initializers, basically properties for a particular
* template stream source. The order in this list
* reflects numbering of the properties i.e.
* template.loader.1.<property> = <value>
* template.loader.2.<property> = <value>
*/
private static ArrayList sourceInitializerList = new ArrayList();
/**
* This is a map of public name of the template
* stream source to it's initializer. This is so
* that clients of velocity can set properties of
* a template source stream with its public name.
* So for example, a client could set the
* File.resource.path property and this would
* change the resource.path property for the
* file template stream source.
*/
private static Hashtable sourceInitializerMap = new Hashtable();
/**
* Each loader needs a configuration object for
* its initialization, this flags keeps track of whether
* or not the configuration objects have been created
* for the resource loaders.
*/
private static boolean resourceLoaderInitializersActive = false;
/**
* Initialize the ResourceManager. It is assumed
* that assembleSourceInitializers() has been
* called before this is run.
*/
public static void initialize() throws Exception
{
ResourceLoader resourceLoader;
assembleResourceLoaderInitializers();
for (int i = 0; i < sourceInitializerList.size(); i++)
{
Configuration configuration = (Configuration) sourceInitializerList.get(i);
String loaderClass = configuration.getString("class");
resourceLoader = ResourceLoaderFactory.getLoader(loaderClass);
resourceLoader.commonInit(configuration);
resourceLoader.init(configuration);
resourceLoaders.add(resourceLoader);
}
}
/**
* This will produce a List of Hashtables, each
* hashtable contains the intialization info for
* a particular resource loader. This Hastable
* will be passed in when initializing the
* the template loader.
*/
private static void assembleResourceLoaderInitializers()
{
if (resourceLoaderInitializersActive)
{
return;
}
for (int i = 1; i < 10; i++)
{
String loaderID = "resource.loader." + new Integer(i).toString();
/*
* Create a resources class specifically for
* the loader if we have a valid subset of
* resources. VelocityResources.subset(prefix)
* will return null if we do not have a valid
* subset of resources.
*/
if (Runtime.getConfiguration().subset(loaderID) == null)
{
continue;
}
Configuration loaderConfiguration = new Configuration(
Runtime.getConfiguration().subset(loaderID));
/*
* Add resources to the list of resource loader
* initializers.
*/
sourceInitializerList.add(loaderConfiguration);
/*
* Make a Map of the public names for the sources
* to the sources property identifier so that external
* clients can set source properties. For example:
* File.resource.path would get translated into
* template.loader.1.resource.path and the translated
* name would be used to set the property.
*/
sourceInitializerMap.put(
loaderConfiguration.getString("public.name").toLowerCase(),
loaderConfiguration);
}
resourceLoaderInitializersActive = true;
}
/**
* Gets the named resource. Returned class type corresponds to specified type
* (i.e. <code>Template</code> to <code>RESOURCE_TEMPLATE</code>).
*
* @param resourceName The name of the resource to retrieve.
* @param resourceType The type of resource (<code>RESOURCE_TEMPLATE</code>,
* <code>RESOURCE_CONTENT</code>, etc.).
* @return Resource with the template parsed and ready.
* @throws ResourceNotFoundException if template not found
* from any available source.
* @throws ParseErrorException if template cannot be parsed due
* to syntax (or other) error.
* @throws Exception if a problem in parse
*/
public static Resource getResource(String resourceName, int resourceType)
throws ResourceNotFoundException, ParseErrorException, Exception
{
Resource resource = null;
ResourceLoader resourceLoader = null;
/*
* Check to see if the resource was placed in the cache.
* If it was placed in the cache then we will use
* the cached version of the resource. If not we
* will load it.
*/
if (globalCache.containsKey(resourceName))
{
resource = (Resource) globalCache.get(resourceName);
/*
* The resource knows whether it needs to be checked
* or not, and the resource's loader can check to
* see if the source has been modified. If both
* these conditions are true then we must reload
* the input stream and parse it to make a new
* AST for the resource.
*/
if ( resource.requiresChecking() )
{
/*
* touch() the resource to reset the counters
*/
resource.touch();
if( resource.isSourceModified() )
{
try
{
/*
* read in the fresh stream and parse
*/
resource.process();
/*
* now set the modification info and reset
* the modification check counters
*/
resource.setLastModified(
resourceLoader.getLastModified( resource ));
}
catch( ResourceNotFoundException rnfe )
{
Runtime.error("ResourceManager.getResource() exception: " + rnfe);
throw rnfe;
}
catch( ParseErrorException pee )
{
Runtime.error("ResourceManager.getResource() exception: " + pee);
throw pee;
}
catch( Exception eee )
{
Runtime.error("ResourceManager.getResource() exception: " + eee);
throw eee;
}
}
}
return resource;
}
else
{
/*
* it's not in the cache
*/
try
{
resource = ResourceFactory.getResource(resourceName, resourceType);
resource.setName(resourceName);
/*
* Now we have to try to find the appropriate
* loader for this resource. We have to cycle through
* the list of available resource loaders and see
* which one gives us a stream that we can use to
* make a resource with.
*/
//! Bug this is being run more then once!
for (int i = 0; i < resourceLoaders.size(); i++)
{
resourceLoader = (ResourceLoader) resourceLoaders.get(i);
resource.setResourceLoader(resourceLoader);
Runtime.info("Attempting to find " + resourceName +
" with " + resourceLoader.getClassName());
if (resource.process())
break;
}
/*
* Return null if we can't find a resource.
*/
if (resource.getData() == null)
throw new ResourceNotFoundException("Can't find " + resourceName + "!");
resource.setLastModified(resourceLoader.getLastModified(resource));
resource.setModificationCheckInterval(
resourceLoader.getModificationCheckInterval());
resource.touch();
/*
* Place the resource in the cache if the resource
* loader says to.
*/
if (resourceLoader.isCachingOn())
globalCache.put(resourceName, resource);
}
catch( ParseErrorException pee )
{
Runtime.error("ResourceManager.getResource() parse exception: " + pee);
throw pee;
}
catch( Exception ee )
{
Runtime.error("ResourceManager.getResource() exception: " + ee);
throw ee;
}
}
return resource;
}
/**
* Allow clients of Velocity to set a template stream
* source property before the template source streams
* are initialized. This would for example allow clients
* to set the template path that would be used by the
* file template stream source. Right now these properties
* have to be set before the template stream source is
* initialized. Maybe we should allow these properties
* to be changed on the fly.
*
* It is assumed that the initializers have been
* assembled.
*/
public static void setSourceProperty(String key, String value)
{
if (resourceLoaderInitializersActive == false)
{
assembleResourceLoaderInitializers();
}
String publicName = key.substring(0, key.indexOf("."));
String property = key.substring(key.indexOf(".") + 1);
Configuration loaderConfiguration = (Configuration)
sourceInitializerMap.get(publicName.toLowerCase());
loaderConfiguration.setProperty(property, value);
}
} |
package org.basex.gui.view.tree;
import static org.basex.gui.GUIConstants.*;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Transparency;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.image.BufferedImage;
import java.util.LinkedList;
import java.util.ListIterator;
import javax.swing.SwingUtilities;
import org.basex.core.Context;
import org.basex.data.Data;
import org.basex.data.Nodes;
import org.basex.gui.GUIConstants;
import org.basex.gui.GUIProp;
import org.basex.gui.layout.BaseXLayout;
import org.basex.gui.layout.BaseXPopup;
import org.basex.gui.view.View;
import org.basex.gui.view.ViewData;
import org.basex.gui.view.ViewNotifier;
import org.basex.gui.view.ViewRect;
import org.basex.util.IntList;
import org.basex.util.Token;
public final class TreeView extends View implements TreeViewOptions {
/** TreeBorders Object, contains cached pre values and borders. */
private TreeSubtree sub;
/** TreeRects Object, contains cached rectangles. */
private TreeRects tr;
/** Current font height. */
private int fontHeight;
/** Current mouse position x. */
private int mousePosX = -1;
/** Current mouse position y. */
private int mousePosY = -1;
/** Window width. */
private int wwidth = -1;
/** Window height. */
private int wheight = -1;
/** Current Image of visualization. */
private BufferedImage treeImage;
/** Notified focus flag. */
private boolean refreshedFocus;
/** Distance between the levels. */
private int levelDistance;
/** Image of the current marked nodes. */
private BufferedImage markedImage;
/** If something is selected. */
private boolean selection;
/** The selection rectangle. */
private ViewRect selectRect;
/** The node height. */
private int nodeHeight;
/** Top margin. */
private int topMargin;
/** Distance between multiple trees. */
private double treedist;
/** Currently focused rectangle. */
private TreeRect frect;
/** Level of currently focused rectangle. */
private int flv = -1;
/** Focused root number. */
private int frn;
/** Focused pre. */
private int fpre;
/** New tree initialization. */
private byte paintType;
/** Array with current root nodes. */
private int[] roots;
/** Real big rectangle. */
private boolean rbr;
/** If something is in focus. */
private boolean inFocus;
/**
* Default constructor.
* @param man view manager
*/
public TreeView(final ViewNotifier man) {
super(TREEVIEW, null, man);
new BaseXPopup(this, GUIConstants.POPUP);
}
@Override
public void refreshContext(final boolean more, final boolean quick) {
paintType = PAINT_NEW_CONTEXT;
repaint();
}
@Override
public void refreshFocus() {
refreshedFocus = true;
repaint();
}
@Override
public void refreshInit() {
if(!visible()) return;
paintType = PAINT_NEW_INIT;
repaint();
}
@Override
public void refreshLayout() {
paintType = PAINT_NEW_WINDOW_SIZE;
repaint();
}
@Override
public void refreshMark() {
markNodes();
repaint();
}
@Override
public void refreshUpdate() {
paintType = PAINT_NEW_INIT;
repaint();
}
@Override
public boolean visible() {
final boolean v = gui.prop.is(GUIProp.SHOWTREE);
if(!v) {
sub = null;
tr = null;
paintType = PAINT_NEW_INIT;
}
return v;
}
@Override
public void visible(final boolean v) {
gui.prop.set(GUIProp.SHOWTREE, v);
}
@Override
protected boolean db() {
return true;
}
@Override
public void paintComponent(final Graphics g) {
final Context c = gui.context;
final Data data = c.data;
if(data == null) return;
super.paintComponent(g);
gui.painting = true;
roots = gui.context.current.nodes;
if(roots.length == 0) return;
smooth(g);
g.setFont(font);
fontHeight = g.getFontMetrics().getHeight();
// timer
// final Performance perf = new Performance();
// perf.initTimer();
// initializes sizes
if(paintType == PAINT_NEW_INIT) {
sub = new TreeSubtree(data);
tr = new TreeRects(gui.prop);
}
if(paintType == PAINT_NEW_INIT || paintType == PAINT_NEW_CONTEXT)
sub.generateBorders(c);
if(paintType == PAINT_NEW_INIT || paintType == PAINT_NEW_CONTEXT
|| paintType == PAINT_NEW_WINDOW_SIZE || paintType == -1
&& windowSizeChanged()) {
treedist = tr.generateRects(sub, g, c, wwidth);
rbr = treedist == -1;
markedImage = null;
setLevelDistance();
createNewMainImage();
if(gui.context.marked.size() > 0) markNodes();
}
g.drawImage(treeImage, 0, 0, wwidth, wheight, this);
if(selection) {
if(selectRect != null) {
// draw selection
final int x = selectRect.w < 0 ? selectRect.x + selectRect.w
: selectRect.x;
final int y = selectRect.h < 0 ? selectRect.y + selectRect.h
: selectRect.y;
final int w = Math.abs(selectRect.w);
final int h = Math.abs(selectRect.h);
g.setColor(colormark1);
g.drawRect(x, y, w, h);
}
markNodes();
}
if(markedImage != null) g.drawImage(markedImage, 0, 0, wwidth,
wheight, this);
// highlights the focused node
inFocus = paintType < 0 ? focus() : false;
if(inFocus) {
int focused = gui.context.focused;
if(rbr) {
highlightRealBigRect(g, frn, flv, fpre);
} else {
if(tr.isBigRectangle(sub, frn, flv)) {
final int f = getMostSizedNode(data, frn, flv, frect, focused);
if(f >= 0) focused = f;
}
highlightNode(g, frn, flv, frect, focused, -1, DRAW_HIGHLIGHT);
}
if(SHOW_EXTRA_INFO) {
g.setColor(new Color(0xeeeeee));
g.fillRect(0, wheight - fontHeight - 6, wwidth, fontHeight + 6);
final Data d = gui.context.data;
final int k = d.kind(focused);
final int s = d.size(focused, k);
final int as = d.attSize(focused, k);
g.setColor(Color.BLACK);
g.drawString("pre: " + focused + " level: " + flv + " level-size: "
+ sub.getLevelSize(frn, flv) + " node-size: " + (s - as)
+ " node: " + Token.string(ViewData.tag(gui.prop, d, focused)), 2,
wheight - 6);
}
}
paintType = -1;
gui.painting = false;
}
/**
* Creates new image and draws rectangles in it.
*/
private void createNewMainImage() {
treeImage = createImage();
final Graphics tg = treeImage.getGraphics();
final int rl = roots.length;
tg.setFont(font);
smooth(tg);
if(!rbr) {
for(int rn = 0; rn < rl; ++rn) {
final int h = sub.getSubtreeHeight(rn);
for(int lv = 0; lv < h; ++lv) {
final boolean br = tr.isBigRectangle(sub, rn, lv);
final TreeRect[] lr = tr.getTreeRectsPerLevel(rn, lv);
for(int i = 0; i < lr.length; ++i) {
final TreeRect r = lr[i];
final int pre = sub.getPrePerIndex(rn, lv, i);
drawRectangle(tg, rn, lv, r, pre, DRAW_RECTANGLE);
}
if(br) {
final TreeRect r = lr[0];
final int ww = r.x + r.w - 1;
final int x = r.x + 1;
drawBigRectSquares(tg, lv, x, ww, 4);
}
}
if(SHOW_CONN_MI) {
final TreeRect rr = tr.getTreeRectPerIndex(rn, 0, 0);
highlightDescendants(tg, rn, 0, rr, roots[rn], getRectCenter(rr),
DRAW_CONN);
}
}
} else {
final int w = wwidth;
tg.setColor(getColorPerLevel(0, false));
tg.drawRect(0, getYperLevel(0), w, nodeHeight);
drawBigRectSquares(tg, 0, 0, w - 1, 4);
System.out.println(w);
for(int px = 0; px < w; px += 2) {
drawRealBigRectangle(tg, -1, 0, -1, px, DRAW_CONN);
}
}
}
/**
* Returns subtree-height of real big rectangles.
* @param px pixel position
* @return height
*/
private int getRealBigRectangleHeightNode(final int px) {
final int[] r = getRealBigRectangleNodeRange(px);
final int pp = r[0];
final int ppp = r[1];
int maxHeight = 0;
int n = -1;
for(int i = pp; i <= ppp; ++i) {
final int h = sub.getSubtreeHeight(i);
if(h >= maxHeight) {
maxHeight = h;
n = i;
}
}
return n;
}
/**
* Return real big rectangle range.
* @param px pixel position
* @return range
*/
private int[] getRealBigRectangleNodeRange(final int px) {
int w = wwidth;
w = w % 2 == 0 ? w / 2 : w / 2 - 1;
final int l = roots.length;
final int pp = px / 2 * l / w;
// final int overflow = l % w;
// final double perc = 2 / (double) w;
// final int overflow = l % w;
// final int pp = (int) (px / 2 * perc * l);
// System.out.println("w " + w + " l " + l +" pp " + pp + " ov " + overflow);
int p = 0; // overflow >= px / 2 ? 1 : 0;
return new int[] { pp, pp + p};
}
/**
* Draws real big rectangles.
* @param g graphics reference
* @param rn root
* @param lv level
* @param pre pre
* @param px pixel position
* @param t type
*/
private void drawRealBigRectangle(final Graphics g, final int rn,
final int lv, final int pre, final int px, final byte t) {
final Color hColor = COLORS[8];
if(t == DRAW_HIGHLIGHT) {
final int y = getYperLevel(0);
g.setColor(hColor);
g.drawLine(px, y, px, y + nodeHeight);
drawThumbnails(g, rn, lv, pre, new TreeRect(0, 10), lv == 0);
}
final int nh = getRealBigRectangleHeightNode(px);
// System.out.println("nh: " +nh+" px: " + px + " rn"+rn + " " + lv);
final int maxHeight = sub.getSubtreeHeight(nh);
for(int i = 1; i < maxHeight; ++i) {
final int y = getYperLevel(i);
if(t == DRAW_CONN) {
g.setColor(getColorPerLevel(i, false));
} else {
g.setColor(hColor);
}
g.drawLine(px, y, px, y + nodeHeight);
// draws line connection
final int yy = getYperLevel(i - 1);
final Color c = getConnectionColor(t);
g.setColor(c);
g.drawLine(px, yy + nodeHeight, px, y);
}
}
/**
* Highlights real big rects.
* @param g Graphics reference
* @param rn root
* @param lv level
* @param pre pre
*/
private void highlightRealBigRect(final Graphics g, final int rn,
final int lv, final int pre) {
drawRealBigRectangle(g, rn, lv, pre, mousePosX, DRAW_HIGHLIGHT);
}
/**
* Draws the squares inside big rectangles.
* @param g graphics reference
* @param lv level
* @param x x-coordinate
* @param w width
* @param ss square-size
*/
private void drawBigRectSquares(final Graphics g, final int lv, final int x,
final int w, final int ss) {
int xx = x;
final int y = getYperLevel(lv);
int nh = nodeHeight;
g.setColor(GUIConstants.back);
while(nh > 0) {
nh -= ss;
if(nh < 0) nh = 0;
g.drawLine(xx, y + nh, w, y + nh);
}
while(xx < w) {
xx = xx + ss - 1 < w ? xx + ss : xx + ss - 1;
g.drawLine(xx, y, xx, y + nodeHeight);
}
}
/**
* Return boolean if position is marked or not.
* @param x x-coordinate
* @param y y-coordinate
* @return position is marked or not
*/
private boolean isMarked(final int x, final int y) {
if(markedImage != null) {
final int h = markedImage.getHeight();
final int w = markedImage.getWidth();
if(y > h || y < 0 || x > w || x < 0) return false;
final int marc = markedImage.getRGB(x, y);
return colormark1.getRGB() == marc || colormarkA.getRGB() == marc;
}
return false;
}
/**
* Draws Rectangles.
* @param g graphics reference
* @param rn root
* @param lv level
* @param r rectangle
* @param pre pre
* @param t type
*/
private void drawRectangle(final Graphics g, final int rn, final int lv,
final TreeRect r, final int pre, final byte t) {
final int y = getYperLevel(lv);
final int h = nodeHeight;
final boolean br = tr.isBigRectangle(sub, rn, lv);
boolean txt = !br && fontHeight <= h;
boolean fill = false;
boolean border = false;
final int xx = r.x;
final int ww = r.w;
final boolean marked = isMarked(xx, y);
Color borderColor = null;
Color fillColor = null;
Color textColor = Color.BLACK;
switch(t) {
case DRAW_RECTANGLE:
borderColor = getColorPerLevel(lv, false);
fillColor = getColorPerLevel(lv, true);
txt = txt & DRAW_NODE_TEXT;
border = BORDER_RECTANGLES;
fill = FILL_RECTANGLES;
break;
case DRAW_HIGHLIGHT:
borderColor = color6;
final int alpha = 0xDD000000;
final int rgb = GUIConstants.COLORCELL.getRGB();
fillColor = new Color(rgb + alpha, true);
if(h > 4) border = true;
fill = !br && !marked;
break;
case DRAW_MARK:
borderColor = h > 2 && r.w > 4 ? colormarkA : colormark1;
fillColor = colormark1;
border = true;
fill = true;
break;
case DRAW_DESCENDANTS:
final int alphaD = 0xDD000000;
final int rgbD = COLORS[6].getRGB();
fillColor = new Color(rgbD + alphaD, true);
borderColor = COLORS[8];
textColor = Color.WHITE;
fill = !marked;
border = true;
if(h < 4) {
fillColor = SMALL_SPACE_COLOR;
borderColor = fillColor;
txt = false;
}
break;
case DRAW_PARENT:
fillColor = COLORS[6];
textColor = Color.WHITE;
fill = !br && !marked;
border = !br;
if(h < 4) {
fillColor = SMALL_SPACE_COLOR;
borderColor = COLORS[8];
txt = false;
}
break;
}
if(border) {
g.setColor(borderColor);
g.drawRect(xx, y, ww, h);
}
if(fill) {
g.setColor(fillColor);
g.fillRect(xx + 1, y + 1, ww - 1, h - 1);
}
if(txt && (fill || !FILL_RECTANGLES)) {
g.setColor(textColor);
drawRectangleText(g, rn, lv, r, pre);
}
}
/**
* Draws text into rectangle.
* @param g graphics reference
* @param rn root
* @param lv level
* @param r rectangle
* @param pre pre
*/
private void drawRectangleText(final Graphics g, final int rn, final int lv,
final TreeRect r, final int pre) {
String s = Token.string(tr.getText(gui.context, rn, pre)).trim();
if(r.w < BaseXLayout.width(g, s)
&& r.w < BaseXLayout.width(g, "..".concat(s.substring(s.length() - 1)))
+ MIN_TXT_SPACE) return;
final int x = r.x;
final int y = getYperLevel(lv);
final int rm = x + (int) (r.w / 2f);
int tw = BaseXLayout.width(g, s);
if(tw > r.w) {
s = s.concat("..");
while((tw = BaseXLayout.width(g, s)) + MIN_TXT_SPACE > r.w
&& s.length() > 3) {
s = s.substring(0, (s.length() - 2) / 2).concat("..");
}
}
final int yy = (int) (y + (nodeHeight + fontHeight - 4) / 2d);
g.drawString(s, (int) (rm - tw / 2d + BORDER_PADDING), yy);
}
/**
* Returns draw Color.
* @param l the current level
* @param fill if true it returns fill color, rectangle color else
* @return draw color
*/
private Color getColorPerLevel(final int l, final boolean fill) {
final int till = l < CHANGE_COLOR_TILL ? l : CHANGE_COLOR_TILL;
return fill ? COLORS[till] : COLORS[till + 2];
}
/**
* Marks nodes inside the dragged selection.
*/
private void markSelektedNodes() {
final int x = selectRect.w < 0 ? selectRect.x + selectRect.w : selectRect.x;
final int y = selectRect.h < 0 ? selectRect.y + selectRect.h : selectRect.y;
final int w = Math.abs(selectRect.w);
final int h = Math.abs(selectRect.h);
final int t = y + h;
final int size = sub.getMaxSubtreeHeight();
final IntList list = new IntList();
for(int r = 0; r < roots.length; ++r) {
for(int i = 0; i < size; ++i) {
final int yL = getYperLevel(i);
if(i < sub.getSubtreeHeight(r) && (yL >= y || yL + nodeHeight >= y)
&& (yL <= t || yL + nodeHeight <= t)) {
final TreeRect[] rlv = tr.getTreeRectsPerLevel(r, i);
final int s = sub.getLevelSize(r, i);
if(tr.isBigRectangle(sub, r, i)) {
final TreeRect mRect = rlv[0];
int sPrePos = (int) (s * x / (double) mRect.w);
int ePrePos = (int) (s * (x + w) / (double) mRect.w);
// System.out.println("s" + sPrePos + " w " +mRect.w);
if(sPrePos < 0) sPrePos = 0;
if(ePrePos >= s) ePrePos = s - 1;
while(sPrePos++ < ePrePos)
list.add(sub.getPrePerIndex(r, i, sPrePos));
} else {
for(int j = 0; j < s; ++j) {
final TreeRect rect = rlv[j];
if(rect.contains(x, w)) list.add(sub.getPrePerIndex(r, i, j));
}
}
}
}
}
gui.notify.mark(new Nodes(list.toArray(), gui.context.data), this);
}
/**
* Creates a new translucent BufferedImage.
* @return new translucent BufferedImage
*/
private BufferedImage createImage() {
return new BufferedImage(Math.max(1, wwidth), Math.max(1, wheight),
Transparency.TRANSLUCENT);
}
/**
* Highlights the marked nodes.
*/
private void markNodes() {
markedImage = createImage();
final Graphics mg = markedImage.getGraphics();
smooth(mg);
mg.setFont(font);
final int[] mark = gui.context.marked.nodes;
if(mark.length == 0) return;
int rn = 0;
while(rn < roots.length) {
final LinkedList<Integer> marklink = new LinkedList<Integer>();
for(int i = 0; i < mark.length; ++i)
marklink.add(i, mark[i]);
for(int lv = 0; lv < sub.getSubtreeHeight(rn); ++lv) {
final int y = getYperLevel(lv);
final ListIterator<Integer> li = marklink.listIterator();
if(rbr) {
while(li.hasNext()) {
final int pre = li.next();
final int ix = sub.getPreIndex(rn, lv, pre);
if(ix > -1) {
li.remove();
//TODO
}
}
return;
}
if(tr.isBigRectangle(sub, rn, lv)) {
while(li.hasNext()) {
final int pre = li.next();
final TreeRect rect = tr.searchRect(sub, rn, lv, pre);
final int ix = sub.getPreIndex(rn, lv, pre);
if(ix > -1) {
li.remove();
final int x = (int) (rect.w * ix / (double) sub.getLevelSize(rn,
lv));
mg.setColor(colormark1);
mg.fillRect(rect.x + x, y, 2, nodeHeight + 1);
}
}
} else {
while(li.hasNext()) {
final int pre = li.next();
final TreeRect rect = tr.searchRect(sub, rn, lv, pre);
if(rect != null) {
li.remove();
drawRectangle(mg, rn, lv, rect, pre, DRAW_MARK);
}
}
}
}
++rn;
}
}
/**
* Returns position inside big rectangle.
* @param rn root
* @param lv level
* @param pre pre
* @param r rectangle
* @return position
*/
private int getBigRectPosition(final int rn, final int lv, final int pre,
final TreeRect r) {
final int idx = sub.getPreIndex(rn, lv, pre);
final double ratio = idx / (double) sub.getLevelSize(rn, lv);
return r.x + (int) Math.round((r.w - 1) * ratio) + 1;
}
/**
* Draws node inside big rectangle.
* @param g the graphics reference
* @param rn root
* @param lv level
* @param r rectangle
* @param pre pre
* @return node center
*/
private int drawNodeInBigRectangle(final Graphics g, final int rn,
final int lv, final TreeRect r, final int pre) {
final int y = getYperLevel(lv);
final int np = getBigRectPosition(rn, lv, pre, r);
g.setColor(nodeHeight < 4 ? SMALL_SPACE_COLOR : COLORS[7]);
g.drawLine(np, y, np, y + nodeHeight);
return np;
}
/**
* Draws parent connection.
* @param g the graphics reference
* @param lv level
* @param r rectangle
* @param px parent x
* @param brx bigrect x
*/
private void drawParentConnection(final Graphics g, final int lv,
final TreeRect r, final int px, final int brx) {
final int y = getYperLevel(lv);
g.setColor(COLORS[7]);
g.drawLine(px, getYperLevel(lv + 1) - 1, brx == -1 ? (2 * r.x + r.w) / 2
: brx, y + nodeHeight + 1);
}
/**
* Highlights nodes.
* @param g the graphics reference
* @param rn root
* @param pre pre
* @param r rectangle to highlight
* @param lv level
* @param px parent's x value
* @param t highlight type
*/
private void highlightNode(final Graphics g, final int rn, final int lv,
final TreeRect r, final int pre, final int px, final byte t) {
if(lv == -1) return;
final boolean br = tr.isBigRectangle(sub, rn, lv);
final boolean isRoot = roots[rn] == pre;
final int height = sub.getSubtreeHeight(rn);
final Data d = gui.context.data;
final int k = d.kind(pre);
final int size = d.size(pre, k);
// rectangle center
int rc = -1;
if(br) {
rc = drawNodeInBigRectangle(g, rn, lv, r, pre);
} else {
drawRectangle(g, rn, lv, r, pre, t);
rc = getRectCenter(r);
}
// draw parent node connection
if(px > -1 && MIN_NODE_DIST_CONN <= levelDistance) drawParentConnection(g,
lv, r, px, rc);
// if there are ancestors draw them
if(!isRoot) {
final int par = d.parent(pre, k);
final int lvp = lv - 1;
final TreeRect parRect = tr.searchRect(sub, rn, lvp, par);
if(parRect == null) return;
highlightNode(g, rn, lvp, parRect, par, rc, DRAW_PARENT);
}
// if there are descendants draw them
if((t == DRAW_CONN || t == DRAW_HIGHLIGHT) && size > 1 && lv + 1 < height)
highlightDescendants(
g, rn, lv, r, pre, rc, t);
// draws node text
if(t == DRAW_HIGHLIGHT) drawThumbnails(g, rn, lv, pre, r, isRoot);
}
/**
* Draws thumbnails.
* @param g the graphics reference
* @param rn root
* @param lv level
* @param pre pre
* @param r rect
* @param isRoot is root node?
*/
private void drawThumbnails(final Graphics g, final int rn, final int lv,
final int pre, final TreeRect r, final boolean isRoot) {
final int x = r.x;
final int y = getYperLevel(lv);
final int h = nodeHeight;
final String s = Token.string(tr.getText(gui.context, rn, pre));
final int w = BaseXLayout.width(g, s);
g.setColor(COLORS[8]);
if(isRoot) {
g.fillRect(x, y + h, w + 2, fontHeight + 2);
g.setColor(COLORS[6]);
g.drawRect(x - 1, y + h + 1, w + 3, fontHeight + 1);
g.setColor(Color.WHITE);
g.drawString(s, r.x + 1, (int) (y + h + (float) fontHeight) - 2);
} else {
g.fillRect(r.x, y - fontHeight, w + 2, fontHeight);
g.setColor(COLORS[6]);
g.drawRect(r.x - 1, y - fontHeight - 1, w + 3, fontHeight + 1);
g.setColor(Color.WHITE);
g.drawString(s, r.x + 1, (int) (y - h / (float) fontHeight) - 2);
}
}
/**
* Highlights descendants.
* @param g the graphics reference
* @param rn root
* @param lv level
* @param r rectangle to highlight
* @param pre pre
* @param px parent's x value
* @param t highlight type
*/
private void highlightDescendants(final Graphics g, final int rn,
final int lv, final TreeRect r, final int pre, final int px,
final byte t) {
final Data d = gui.context.current.data;
final boolean br = tr.isBigRectangle(sub, rn, lv);
if(!br && t != DRAW_CONN) drawRectangle(g, rn, lv, r, pre, t);
final int lvd = lv + 1;
final TreeBorder[] sbo = sub.subtree(d, pre);
if(sub.getSubtreeHeight(rn) >= lvd && sbo.length >= 2) {
final boolean brd = tr.isBigRectangle(sub, rn, lvd);
if(brd) {
drawBigRectDescendants(g, rn, lvd, sbo, px, t);
} else {
final TreeBorder bo = sbo[1];
final TreeBorder bos = sub.getTreeBorder(rn, lvd);
final int start = bo.start >= bos.start ? bo.start - bos.start
: bo.start;
for(int j = 0; j < bo.size; ++j) {
final int dp = sub.getPrePerIndex(rn, lvd, j + start);
final TreeRect dr = tr.getTreeRectPerIndex(rn, lvd, j + start);
if(SHOW_DESCENDANTS_CONN && levelDistance >= MIN_NODE_DIST_CONN)
drawDescendantsConn(
g, lvd, dr, px, t);
highlightDescendants(g, rn, lvd, dr, dp, getRectCenter(dr),
t == DRAW_CONN ? DRAW_CONN : DRAW_DESCENDANTS);
}
}
}
// private void highlightDescendants(final Graphics g, final int rn,
// final int pre, final TreeRect r, final int l,
// final int px, final byte t) {
// final Data d = gui.context.current.data;
// if(!cache.isBigRectangle(rn, l) && t != DRAW_CONN) drawRectangle(g, rn,
// r, pre, t);
// final int lv = l + 1;
// final TreeBorder[] sbo = cache.generateSubtreeBorders(d, pre);
// if(cache.getHeight(rn) <= lv || sbo.length < 2) return;
// final int parc = px == -1 ? (2 * r.x + r.w) / 2 : px;
// if(cache.isBigRectangle(rn, lv)) {
// drawBigRectDescendants(g, rn, lv, sbo, parc, t);
// } else {
// final TreeBorder bo = sbo[1];
// final TreeBorder bos = cache.getTreeBorder(rn, lv);
// for(int j = 0; j < bo.size; ++j) {
// final int pi = cache.getPrePerIndex(bo, j);
// // if(gui.context.current.nodes[0] > 0) Util.outln("rn:" + rn
// // + " lv:" + lv + " bo-size:" + bo.size + " bo-start:" + (bo.start)
// // + " bos-start:" + bos.start);
// final int start = bo.start >= bos.start ? bo.start - bos.start
// : bo.start;
// final TreeRect sr = cache.getTreeRectPerIndex(rn, lv, j + start);
// if(SHOW_DESCENDANTS_CONN && levelDistance >= MIN_NODE_DIST_CONN) {
// drawDescendantsConn(g, lv, sr, parc, t);
// highlightDescendants(g, rn, pi, sr, lv, -1, t == DRAW_CONN ? DRAW_CONN
// : DRAW_DESCENDANTS);
}
/**
* Returns rectangle center.
* @param r TreeRect
* @return center
*/
private int getRectCenter(final TreeRect r) {
return (2 * r.x + r.w) / 2;
}
/**
* Draws descendants for big rectangles.
* @param g graphics reference
* @param rn root
* @param lv level
* @param subt subtree
* @param parc parent center
* @param t type
*/
private void drawBigRectDescendants(final Graphics g, final int rn,
final int lv, final TreeBorder[] subt, final int parc, final byte t) {
int lvv = lv;
int cen = parc;
int i;
for(i = 1; i < subt.length && tr.isBigRectangle(sub, rn, lvv); ++i) {
final TreeBorder bos = sub.getTreeBorder(rn, lvv);
final TreeBorder bo = subt[i];
final TreeRect r = tr.getTreeRectPerIndex(rn, lvv, 0);
final int start = bo.start - bos.start;
final double sti = start / (double) bos.size;
final double eni = (start + bo.size) / (double) bos.size;
final int df = r.x + (int) (r.w * sti);
final int dt = r.x + (int) (r.w * eni);
final int ww = Math.max(dt - df, 2);
if(MIN_NODE_DIST_CONN <= levelDistance) drawDescendantsConn(g, lvv,
new TreeRect(df, ww), cen, t);
cen = (2 * df + ww) / 2;
switch(t) {
case DRAW_CONN:
break;
default:
final int rgb = COLORS[7].getRGB();
final int alpha = 0x33000000;
g.setColor(nodeHeight < 4 ? SMALL_SPACE_COLOR : new Color(
rgb + alpha, false));
if(nodeHeight > 2) {
g.drawRect(df, getYperLevel(lvv) + 1, ww, nodeHeight - 2);
} else {
g.drawRect(df, getYperLevel(lvv), ww, nodeHeight);
}
}
if(lvv + 1 < sub.getSubtreeHeight(rn)
&& !tr.isBigRectangle(sub, rn, lvv + 1)) {
final Data d = gui.context.current.data;
for(int j = start; j < start + bo.size; ++j) {
final int pre = sub.getPrePerIndex(rn, lvv, j);
final int pos = getBigRectPosition(rn, lvv, pre, r);
final int k = d.kind(pre);
final int s = d.size(pre, k);
if(s > 1) highlightDescendants(g, rn, lvv, r, pre, pos,
t == DRAW_HIGHLIGHT || t == DRAW_DESCENDANTS ? DRAW_DESCENDANTS
: DRAW_CONN);
}
}
++lvv;
}
}
/**
* Returns connection color.
* @param t type
* @return color
*/
private Color getConnectionColor(final byte t) {
int alpha;
int rgb;
Color c;
switch(t) {
case DRAW_CONN:
alpha = 0x20000000;
rgb = COLORS[4].getRGB();
c = new Color(rgb + alpha, true);
break;
default:
case DRAW_DESCENDANTS:
alpha = 0x60000000;
rgb = COLORS[8].getRGB();
c = new Color(rgb + alpha, true);
break;
}
return c;
}
/**
* Draws descendants connection.
* @param g graphics reference
* @param lv level
* @param r TreeRect
* @param parc parent center
* @param t type
*/
private void drawDescendantsConn(final Graphics g, final int lv,
final TreeRect r, final int parc, final byte t) {
final int pary = getYperLevel(lv - 1) + nodeHeight;
final int prey = getYperLevel(lv) - 1;
final int boRight = r.x + r.w + BORDER_PADDING - 2;
final int boLeft = r.x + BORDER_PADDING;
final int boTop = prey + 1;
final Color c = getConnectionColor(t);
if(SHOW_3D_CONN) {
final int boBottom = prey + nodeHeight + 1;
final int parmx = r.x + (int) ((boRight - boLeft) / 2d);
final int dis = 0x111111;
final int alpha = 0x20000000;
final int rgb = COLORS[4].getRGB();
final Color ca = new Color(rgb + alpha - dis, false);
final Color cb = new Color(rgb + alpha + dis, false);
// g.setColor(new Color(0x444444, false));
g.setColor(cb);
// g.setColor(new Color(0x666666, false));
g.drawPolygon(new int[] { parc, boRight, boRight}, new int[] { pary,
boBottom, boTop}, 3);
// g.setColor(new Color(0x666666, false));
g.drawPolygon(new int[] { parc, boLeft, boLeft}, new int[] { pary,
boBottom, boTop}, 3);
g.setColor(c);
// g.setColor(new Color(0x555555, false));
g.drawPolygon(new int[] { parc, boLeft, boRight}, new int[] { pary,
boTop, boTop}, 3);
g.setColor(Color.BLACK);
if(parmx < parc) g.drawLine(boRight, boBottom, parc, pary);
else if(parmx > parc) g.drawLine(boLeft, boBottom, parc, pary);
// g.setColor(cb);
// // g.setColor(new Color(0x666666, false));
// g.drawLine(boRight, boTop, parc, pary);
// g.drawLine(boLeft, boTop, parc, pary);
} else {
g.setColor(c);
if(boRight - boLeft > 2) {
g.fillPolygon(new int[] { parc, boRight, boLeft}, new int[] { pary,
boTop, boTop}, 3);
} else {
g.drawLine((boRight + boLeft) / 2, boTop, parc, pary);
}
}
}
/**
* Finds rectangle at cursor position.
* @return focused rectangle
*/
private boolean focus() {
if(refreshedFocus) {
final int pre = gui.context.focused;
if(rbr) {
for(int r = 0; r < roots.length; ++r) {
for(int i = 0; i < sub.getSubtreeHeight(r); ++i) {
final int index = sub.getPreIndex(r, i, pre);
if(index > -1) {
frn = r;
flv = i;
fpre = pre;
refreshedFocus = false;
return true;
}
}
}
return false;
}
for(int r = 0; r < roots.length; ++r) {
for(int i = 0; i < sub.getSubtreeHeight(r); ++i) {
if(tr.isBigRectangle(sub, r, i)) {
final int index = sub.getPreIndex(r, i, pre);
if(index > -1) {
frn = r;
frect = tr.getTreeRectsPerLevel(r, i)[0];
flv = i;
refreshedFocus = false;
return true;
}
} else {
final TreeRect rect = tr.searchRect(sub, r, i, pre);
if(rect != null) {
frn = r;
frect = rect;
flv = i;
refreshedFocus = false;
return true;
}
}
}
}
} else {
final int lv = getLevelPerY(mousePosY);
if(lv < 0) return false;
final int mx = mousePosX;
if(rbr) {
final int max = getRealBigRectangleHeightNode(mx);
if(max < 0) return false;
if(lv == 0) {
frn = getRealBigRectangleHeightNode(mx);
flv = lv;
fpre = roots[(int) ((mx / (double) wwidth) * roots.length)];
gui.notify.focus(fpre, this);
return true;
}
final int maxlv = sub.getSubtreeHeight(max);
if(mx % 2 > 0 || lv >= maxlv) return false;
frn = max;
flv = lv;
fpre = sub.getPrePerIndex(max, lv, 0);
gui.notify.focus(fpre, this);
return true;
}
final int rn = frn = getTreePerX(mx);
final int h = sub.getSubtreeHeight(rn);
if(h < 0 || lv >= h) return false;
final TreeRect[] rL = tr.getTreeRectsPerLevel(rn, lv);
for(int i = 0; i < rL.length; ++i) {
final TreeRect r = rL[i];
if(r.contains(mx)) {
frect = r;
flv = lv;
int pre = -1;
// if multiple pre values, then approximate pre value
if(tr.isBigRectangle(sub, rn, lv)) {
pre = tr.getPrePerXPos(sub, rn, lv, mx);
} else {
pre = sub.getPrePerIndex(rn, lv, i);
}
fpre = pre;
gui.notify.focus(pre, this);
refreshedFocus = false;
return true;
}
}
}
refreshedFocus = false;
return false;
}
/**
* Returns the y-axis value for a given level.
* @param level the level
* @return the y-axis value
*/
private int getYperLevel(final int level) {
return level * nodeHeight + level * levelDistance + topMargin;
}
/**
* Determines tree number.
* @param x x-axis value
* @return tree number
*/
private int getTreePerX(final int x) {
return (int) (x / treedist);
}
/**
* Determines the level of a y-axis value.
* @param y the y-axis value
* @return the level if inside a node rectangle, -1 else
*/
private int getLevelPerY(final int y) {
final double f = (y - topMargin) / ((float) levelDistance + nodeHeight);
final double b = nodeHeight / (float) (levelDistance + nodeHeight);
return f <= (int) f + b ? (int) f : -1;
}
/**
* Sets optimal distance between levels.
*/
private void setLevelDistance() {
final int h = wheight - BOTTOM_MARGIN;
int lvs = 0;
for(int i = 0; i < roots.length; ++i) {
final int th = sub.getSubtreeHeight(i);
if(th > lvs) lvs = th;
}
nodeHeight = MAX_NODE_HEIGHT;
int lD;
while((lD = (int) ((h - lvs * nodeHeight) / (double) (lvs - 1)))
< (nodeHeight <= BEST_NODE_HEIGHT ? MIN_LEVEL_DISTANCE
: BEST_LEVEL_DISTANCE)
&& nodeHeight >= MIN_NODE_HEIGHT)
nodeHeight
levelDistance = lD < MIN_LEVEL_DISTANCE ? MIN_LEVEL_DISTANCE
: lD > MAX_LEVEL_DISTANCE ? MAX_LEVEL_DISTANCE : lD;
final int ih = (int) ((h - (levelDistance * (lvs - 1) + lvs *
nodeHeight)) / 2d);
topMargin = ih < TOP_MARGIN ? TOP_MARGIN : ih;
}
/**
* Returns true if window-size has changed.
* @return window-size has changed
*/
private boolean windowSizeChanged() {
if(wwidth > -1 && wheight > -1 && getHeight() == wheight
&& getWidth() == wwidth) return false;
wheight = getHeight();
wwidth = getWidth();
return true;
}
/**
* Returns number of hit nodes.
* @param rn root
* @param lv level
* @param r rectangle
* @return size
*/
private int getHitBigRectNodesNum(final int rn, final int lv,
final TreeRect r) {
final int w = r.w;
final int ls = sub.getLevelSize(rn, lv);
return Math.max(ls / Math.max(w, 1), 1);
}
/**
* Returns most sized node.
* @param d the data reference
* @param rn root
* @param lv level
* @param r rectangle
* @param p pre
* @return deepest node pre
*/
private int getMostSizedNode(final Data d, final int rn, final int lv,
final TreeRect r, final int p) {
final int size = getHitBigRectNodesNum(rn, lv, r);
final int idx = sub.getPreIndex(rn, lv, p);
if(idx < 0) return -1;
int dpre = -1;
int si = 0;
for(int i = 0; i < size; ++i) {
final int pre = sub.getPrePerIndex(rn, lv, i + idx);
final int k = d.kind(pre);
final int s = d.size(pre, k);
if(s > si) {
si = s;
dpre = pre;
}
}
return dpre;
}
@Override
public void mouseMoved(final MouseEvent e) {
if(gui.updating) return;
super.mouseMoved(e);
// refresh mouse focus
mousePosX = e.getX();
mousePosY = e.getY();
repaint();
}
@Override
public void mouseClicked(final MouseEvent e) {
final boolean left = SwingUtilities.isLeftMouseButton(e);
final boolean right = !left;
if(!right && !left || frect == null) return;
// System.out.println("clicked");
if(left && inFocus) {
if(rbr) {
// final Nodes ns = new Nodes(gui.context.data);
// final int [] range = getRealBigRectangleNodeRange(mousePosX);
// final int l = range.length;
// final int [] m = new int[l];
// final int st = range[0];
// final int en = range[1];
// int c = 0;
// for(int i = st; i <= en; ++i){
gui.notify.mark(0, null);
} else {
if(flv >= sub.getSubtreeHeight(frn)) return;
if(tr.isBigRectangle(sub, frn, flv)) {
final Nodes ns = new Nodes(gui.context.data);
final int sum = getHitBigRectNodesNum(frn, flv, frect);
final int fix = sub.getPreIndex(frn, flv, fpre);
final int[] m = new int[sum];
for(int i = 0; i < sum; ++i) {
final int pre = sub.getPrePerIndex(frn, flv, i + fix);
if(pre == -1) break;
m[i] = pre;
}
ns.union(m);
gui.notify.mark(ns, null);
} else {
gui.notify.mark(0, null);
}
}
if(e.getClickCount() > 1) {
gui.notify.context(gui.context.marked, false, this);
refreshContext(false, false);
}
}
}
@Override
public void mouseWheelMoved(final MouseWheelEvent e) {
if(gui.updating || gui.context.focused == -1) return;
if(e.getWheelRotation() > 0) gui.notify.context(new Nodes(
gui.context.focused, gui.context.data), false, null);
else gui.notify.hist(false);
}
@Override
public void mouseDragged(final MouseEvent e) {
if(gui.updating || e.isShiftDown() || rbr) return;
if(!selection) {
selection = true;
selectRect = new ViewRect();
selectRect.x = e.getX();
selectRect.y = e.getY();
selectRect.h = 1;
selectRect.w = 1;
} else {
final int x = e.getX();
final int y = e.getY();
selectRect.w = x - selectRect.x;
selectRect.h = y - selectRect.y;
}
markSelektedNodes();
repaint();
}
@Override
public void mouseReleased(final MouseEvent e) {
if(gui.updating || gui.painting) return;
selection = false;
repaint();
}
} |
package edu.wustl.query.bizlogic;
import junit.framework.Test;
import junit.framework.TestSuite;
public class QueryTestAll extends TestSuite
{
/**
* @param args arg
*/
public static void main(String[] args)
{
try
{
junit.swingui.TestRunner.run(QueryTestAll.class);
}
catch(Exception e)
{
e.printStackTrace();
}
}
/**
* @return test
*/
public static Test suite()
{
TestSuite suite = new TestSuite("Test suite for QUERY business logic");
// For testing FAMEWORK for Query testing
// suite.addTestSuite(XQueryGeneratorTestCase.class);
// For testing ASynchronous Queries
// suite.addTestSuite(ASynchronousQueriesTestCases.class);
//For testing WorkflowBizLogic
suite.addTestSuite(WorkflowBizLogicTestCases.class);
return suite;
}
} |
package org.broad.igv.track;
import htsjdk.tribble.Feature;
import htsjdk.tribble.TribbleException;
import org.apache.log4j.Logger;
import org.broad.igv.Globals;
import org.broad.igv.event.DataLoadedEvent;
import org.broad.igv.event.IGVEventBus;
import org.broad.igv.event.IGVEventObserver;
import org.broad.igv.feature.*;
import org.broad.igv.feature.genome.Genome;
import org.broad.igv.feature.genome.GenomeManager;
import org.broad.igv.prefs.Constants;
import org.broad.igv.prefs.PreferencesManager;
import org.broad.igv.renderer.*;
import org.broad.igv.tools.motiffinder.MotifFinderSource;
import org.broad.igv.ui.IGV;
import org.broad.igv.ui.UIConstants;
import org.broad.igv.ui.panel.ReferenceFrame;
import org.broad.igv.ui.util.MessageUtils;
import org.broad.igv.util.BrowserLauncher;
import org.broad.igv.util.ResourceLocator;
import org.broad.igv.util.StringUtils;
import org.broad.igv.variant.VariantTrack;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.util.List;
import java.util.*;
/**
* Track which displays features, typically showing regions of the genome
* in a qualitative way. Features are rendered using the specified FeatureRenderer.
* The gene track is an example of a feature track.
*
* @author jrobinso
*/
public class FeatureTrack extends AbstractTrack implements IGVEventObserver {
private static Logger log = Logger.getLogger(FeatureTrack.class);
public static final int MINIMUM_FEATURE_SPACING = 5;
public static final int DEFAULT_MARGIN = 5;
public static final int NO_FEATURE_ROW_SELECTED = -1;
private static final Color SELECTED_FEATURE_ROW_COLOR = new Color(100, 100, 100, 30);
private static final int DEFAULT_EXPANDED_HEIGHT = 35;
private static final int DEFAULT_SQUISHED_HEIGHT = 12;
public FeatureSource source;
private String trackLine = null;
private static boolean drawBorder = true;
private int expandedRowHeight = DEFAULT_EXPANDED_HEIGHT;
private int squishedRowHeight = DEFAULT_SQUISHED_HEIGHT;
private int margin = DEFAULT_MARGIN;
private boolean fatalLoadError = false;
private Track.DisplayMode lastFeatureMode = null; // Keeps track of the feature display mode before an auto-switch to COLLAPSE
private boolean alternateExonColor = false;
private boolean showFeatures = true; // true == features, false = coverage
protected Renderer renderer;
private DataRenderer coverageRenderer;
// TODO -- this is a memory leak, this cache needs cleared when the reference frame collection (gene list) changes
/**
* Map of reference frame name -> packed features
*/
protected Map<String, PackedFeatures<IGVFeature>> packedFeaturesMap = Collections.synchronizedMap(new HashMap<>());
private List<Rectangle> levelRects = new ArrayList<>();
//track which row of the expanded track is selected by the user. Selection goes away if tracks are collpased
private int selectedFeatureRowIndex = NO_FEATURE_ROW_SELECTED;
//Feature selected by the user. This is repopulated on each handleDataClick() call.
protected IGVFeature selectedFeature = null;
/**
* The "real" constructor, all other constructors call this one.
* @param id
* @param name
* @param locator
* @param source
*/
public FeatureTrack(String id, String name, ResourceLocator locator, FeatureSource source) {
super(id, name, locator);
init(source, locator);
setSortable(false);
}
/**
* Construct with no feature source. Currently this is only used for the BlatTrack subclass.
*/
public FeatureTrack(String id, String name) {
this(id, name, null, null);
}
public FeatureTrack(String id, String name, ResourceLocator locator) {
this(id, name, locator, null);
}
/**
* Constructor with no ResourceLocator. Note: tracks using this constructor will not be recorded in the
* "Resources" section of session files. Used for the default gene track and computed tracks.
*/
public FeatureTrack(String id, String name, FeatureSource source) {
this(id, name, null, source);
}
public FeatureTrack(ResourceLocator locator, FeatureSource source) {
this(locator.getPath(), locator.getTrackName(), locator, source);
}
public FeatureTrack(String id, ResourceLocator locator, FeatureSource source) {
this(id, locator.getTrackName(), locator, source);
}
/**
* Create a new track which is a shallow copy of this one
*
* @param featureTrack
*/
public FeatureTrack(FeatureTrack featureTrack) {
this(featureTrack.getId(), featureTrack.getName(), featureTrack.getResourceLocator(), featureTrack.source);
}
protected void init(FeatureSource source, ResourceLocator locator) {
setMinimumHeight(10);
setColor(Color.blue.darker());
if(source != null) {
this.source = source;
coverageRenderer = new BarChartRenderer();
int sourceFeatureWindowSize = source.getFeatureWindowSize();
if (sourceFeatureWindowSize > 0) { // Only apply a default if the feature source supports visibility window.
int defVisibilityWindow = PreferencesManager.getPreferences().getAsInt(Constants.DEFAULT_VISIBILITY_WINDOW);
if (defVisibilityWindow > 0) {
setVisibilityWindow(defVisibilityWindow * 1000);
} else {
visibilityWindow = sourceFeatureWindowSize;
}
}
}
if(locator != null) {
String path = locator.getPath();
this.renderer = path != null && path.endsWith("junctions.bed") ?
new SpliceJunctionRenderer() : new IGVFeatureRenderer();
}
IGVEventBus.getInstance().subscribe(DataLoadedEvent.class, this);
}
@Override
public void dispose() {
super.dispose();
if (source != null) {
source.dispose();
source = null;
}
}
/**
* Called after features are finished loading, which can be asynchronous
*/
public void receiveEvent(Object e) {
if (e instanceof DataLoadedEvent) {
// DataLoadedEvent event = (DataLoadedEvent) e;
// if (IGV.hasInstance()) {
// // TODO -- WHY IS THIS HERE????
// //TODO Assuming this is necessary, there can be many data loaded events in succession,
// //don't want to layout for each one
// IGV.getInstance().layoutMainPanel();
} else {
log.info("Unknown event type: " + e.getClass());
}
}
@Override
public boolean isFilterable() {
return false; // Don't filter "feature" tracks
}
@Override
public int getHeight() {
if (!isVisible()) {
return 0;
}
int rowHeight = getDisplayMode() == DisplayMode.SQUISHED ? squishedRowHeight : expandedRowHeight;
int minHeight = margin + rowHeight * Math.max(1, getNumberOfFeatureLevels());
return Math.max(minHeight, super.getHeight());
}
public int getExpandedRowHeight() {
return expandedRowHeight;
}
public void setExpandedRowHeight(int expandedRowHeight) {
this.expandedRowHeight = expandedRowHeight;
}
public int getSquishedRowHeight() {
return squishedRowHeight;
}
public void setSquishedRowHeight(int squishedRowHeight) {
this.squishedRowHeight = squishedRowHeight;
}
public int getFeatureWindowSize() {
return source.getFeatureWindowSize();
}
public void setRendererClass(Class rc) {
try {
renderer = (Renderer) rc.newInstance();
} catch (Exception ex) {
log.error("Error instatiating renderer ", ex);
}
}
public void setMargin(int margin) {
this.margin = margin;
}
@Override
public void setProperties(TrackProperties trackProperties) {
super.setProperties(trackProperties);
if (trackProperties.getFeatureVisibilityWindow() >= 0) {
setVisibilityWindow(trackProperties.getFeatureVisibilityWindow());
}
alternateExonColor = trackProperties.isAlternateExonColor();
}
public void setWindowFunction(WindowFunction type) {
// Ignored for feature tracks
}
/**
* Return the maximum number of features for any panel in this track. In whole genome view there is a single panel,
* but there are multiple in gene list view (one for each gene list).
*
* @return
*/
public int getNumberOfFeatureLevels() {
if (areFeaturesStacked() && packedFeaturesMap.size() > 0) {
int n = 0;
synchronized (packedFeaturesMap) {
for (PackedFeatures pf : packedFeaturesMap.values()) {
//dhmay adding null check. To my mind this shouldn't be necessary, but we're encountering
//it intermittently. Food for future thought
if (pf != null) {
n = Math.max(n, pf.getRowCount());
}
}
}
return n;
}
return 1;
}
/**
* @return Whether features are displayed stacked on top of one another, rather than overlapping
*/
protected boolean areFeaturesStacked() {
return getDisplayMode() != DisplayMode.COLLAPSED;
}
/**
* Return a score over the interval. This is required by the track interface to support sorting.
*/
public float getRegionScore(String chr, int start, int end, int zoom, RegionScoreType scoreType, String frameName) {
try {
Iterator<Feature> features = source.getFeatures(chr, start, end);
if (features != null) {
if (scoreType == RegionScoreType.MUTATION_COUNT && this.getTrackType() == TrackType.MUTATION) {
int count = 0;
while (features.hasNext()) {
Feature f = features.next();
if (f.getStart() > end) {
break;
}
if (f.getEnd() >= start) {
count++;
}
}
return count;
} else if (scoreType == RegionScoreType.SCORE) {
// Average score of features in region. Note: Should the score be weighted by genomic size?
float regionScore = 0;
int nValues = 0;
while (features.hasNext()) {
Feature f = features.next();
if (f instanceof IGVFeature) {
if ((f.getEnd() >= start) && (f.getStart() <= end)) {
float value = ((IGVFeature) f).getScore();
regionScore += value;
nValues++;
}
}
}
if (nValues == 0) {
// No scores in interval
return -Float.MAX_VALUE;
} else {
return regionScore / nValues;
}
}
}
} catch (IOException e) {
log.error("Error counting features.", e);
}
return -Float.MAX_VALUE;
}
public Renderer getRenderer() {
if (renderer == null) {
setRendererClass(IGVFeatureRenderer.class);
}
return renderer;
}
/**
* Return a string for popup text.
*
* @param chr
* @param position in genomic coordinates
* @param mouseX
* @return
*/
public String getValueStringAt(String chr, double position, int mouseX, int mouseY, ReferenceFrame frame) {
if (showFeatures) {
List<Feature> allFeatures = getAllFeatureAt(position, mouseY, frame);
if (allFeatures == null) {
return null;
}
StringBuffer buf = new StringBuffer();
boolean firstFeature = true;
int maxNumber = 10;
int n = 1;
for (Feature feature : allFeatures) {
if (feature != null && feature instanceof IGVFeature) {
if (!firstFeature) {
buf.append("<hr><br>");
}
IGVFeature igvFeature = (IGVFeature) feature;
String vs = igvFeature.getValueString(position, mouseX, null);
buf.append(vs);
if (IGV.getInstance().isShowDetailsOnClick()) {
// URL
String url = getFeatureURL(igvFeature);
if (url != null) {
buf.append("<br/><a href=\"" + url + "\">" + url + "</a>");
}
}
firstFeature = false;
if (n > maxNumber) {
buf.append("...");
break;
}
}
n++;
}
return buf.toString();
} else {
int zoom = Math.max(0, frame.getZoom());
if (source == null) {
return null;
}
List<LocusScore> scores = source.getCoverageScores(chr, (int) position - 10, (int) position + 10, zoom);
if (scores == null) {
return "";
} else {
// give a +/- 2 pixel buffer, otherwise very narrow features will be missed.
double bpPerPixel = frame.getScale();
int minWidth = (int) (2 * bpPerPixel);
LocusScore score = (LocusScore) FeatureUtils.getFeatureAt(position, minWidth, scores);
return score == null ? null : "Mean count: " + score.getScore();
}
}
}
private String getFeatureURL(IGVFeature igvFeature) {
String url = igvFeature.getURL();
if (url == null) {
String trackURL = getUrl();
if (trackURL != null && igvFeature.getIdentifier() != null) {
String encodedID = StringUtils.encodeURL(igvFeature.getIdentifier());
url = trackURL.replaceAll("\\$\\$", encodedID);
}
}
return url;
}
/**
* Get all features which overlap the specified locus
*
* @return
*/
public List<Feature> getFeatures(String chr, int start, int end) {
List<Feature> features = new ArrayList<Feature>();
try {
Iterator<Feature> iter = source.getFeatures(chr, start, end);
while (iter.hasNext()) {
features.add(iter.next());
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return features;
}
/**
* @param position in genomic coordinates
* @param y pixel location in panel coordinates. // TODO offset by track origin before getting here?
* @param frame
* @return
*/
protected List<Feature> getAllFeatureAt(double position, int y, ReferenceFrame frame) {
// Determine the level number (for expanded tracks)
int featureRow = getFeatureRow(y);
return getFeaturesAtPositionInFeatureRow(position, featureRow, frame);
}
/**
* Determine which row the user clicked in and return the appropriate feature
*
* @param y
* @return
*/
private int getFeatureRow(int y) {
int rowHeight;
DisplayMode mode = getDisplayMode();
switch (mode) {
case SQUISHED:
rowHeight = getSquishedRowHeight();
break;
case EXPANDED:
rowHeight = getExpandedRowHeight();
break;
default:
rowHeight = getHeight();
}
return Math.max(0, Math.min(levelRects.size() - 1, (int) ((y - this.getY() - this.margin) / rowHeight)));
}
/**
* Knowing the feature row, figure out which feature is at {@code position}. If not expanded,
* featureRow is ignored
*
* @param position
* @param featureRow
* @param frame
* @return
*/
public List<Feature> getFeaturesAtPositionInFeatureRow(double position, int featureRow, ReferenceFrame frame) {
PackedFeatures<IGVFeature> packedFeatures = packedFeaturesMap.get(frame.getName());
if (packedFeatures == null) {
return null;
}
//If features are stacked we look at only the row.
//If they are collapsed on top of each other, we get all features in all rows
int nLevels = areFeaturesStacked() ? packedFeatures.getRowCount() : 1;
List<IGVFeature> possFeatures = null;
if ((nLevels > 1) && (featureRow < nLevels)) {
possFeatures = packedFeatures.getRows().get(featureRow).getFeatures();
} else {
possFeatures = packedFeatures.getFeatures();
}
List<Feature> featureList = null;
if (possFeatures != null) {
// give a minum 2 pixel or 1/2 bp window, otherwise very narrow features will be missed.
double bpPerPixel = frame.getScale();
double minWidth = Math.max(0.5, MINIMUM_FEATURE_SPACING * bpPerPixel);
int maxFeatureLength = packedFeatures.getMaxFeatureLength();
featureList = FeatureUtils.getAllFeaturesAt(position, maxFeatureLength, minWidth, possFeatures);
}
return featureList;
}
public WindowFunction getWindowFunction() {
return WindowFunction.count;
}
@Override
public boolean handleDataClick(TrackClickEvent te) {
MouseEvent e = te.getMouseEvent();
//Selection of an expanded feature row
if (areFeaturesStacked()) {
if (levelRects != null) {
for (int i = 0; i < levelRects.size(); i++) {
Rectangle rect = levelRects.get(i);
if (rect.contains(e.getPoint())) {
if (i == selectedFeatureRowIndex)
setSelectedFeatureRowIndex(FeatureTrack.NO_FEATURE_ROW_SELECTED);
else {
//make this track selected
setSelected(true);
//select the appropriate row
setSelectedFeatureRowIndex(i);
}
IGV.getInstance().repaint();
break;
}
}
}
}
//For feature selection
selectedFeature = null;
Feature f = getFeatureAtMousePosition(te);
if (f != null && f instanceof IGVFeature) {
IGVFeature igvFeature = (IGVFeature) f;
if (selectedFeature != null && igvFeature.contains(selectedFeature) && (selectedFeature.contains(igvFeature))) {
//If something already selected, then if it's the same as this feature, deselect, otherwise, select
//this feature.
//todo: contains() might not do everything I want it to.
selectedFeature = null;
} else {
//if nothing already selected, or something else selected,
// select this feature
selectedFeature = igvFeature;
}
if (IGV.getInstance().isShowDetailsOnClick()) {
openTooltipWindow(te);
} else {
String url = getFeatureURL(igvFeature);
if (url != null) {
try {
BrowserLauncher.openURL(url);
} catch (IOException e1) {
log.error("Error launching url: " + url);
}
e.consume();
return true;
}
}
}
return false;
}
public Feature getFeatureAtMousePosition(TrackClickEvent te) {
MouseEvent e = te.getMouseEvent();
final ReferenceFrame referenceFrame = te.getFrame();
if (referenceFrame != null) {
double location = referenceFrame.getChromosomePosition(e.getX());
List<Feature> features = getAllFeatureAt(location, e.getY(), referenceFrame);
return (features != null && features.size() > 0) ? features.get(0) : null;
} else {
return null;
}
}
/**
* Required by the interface, really not applicable to feature tracks
*/
public boolean isLogNormalized() {
return true;
}
public void overlay(RenderContext context, Rectangle rect) {
renderFeatures(context, rect);
}
@Override
public void setDisplayMode(DisplayMode mode) {
// Explicity setting the display mode overrides the automatic switch
lastFeatureMode = null;
super.setDisplayMode(mode);
}
@Override
public boolean isReadyToPaint(ReferenceFrame frame) {
if (!isShowFeatures(frame)) {
return true; // Ready by definition (nothing to paint)
} else {
PackedFeatures packedFeatures = packedFeaturesMap.get(frame.getName());
String chr = frame.getChrName();
int start = (int) frame.getOrigin();
int end = (int) frame.getEnd();
return (packedFeatures != null && packedFeatures.containsInterval(chr, start, end));
}
}
public void load(ReferenceFrame frame) {
loadFeatures(frame.getChrName(), (int) frame.getOrigin(), (int) frame.getEnd(), frame);
}
/**
* Loads and segregates features into rows such that they do not overlap.
*
* @param chr
* @param start
* @param end
*/
protected void loadFeatures(final String chr, final int start, final int end, final ReferenceFrame frame) {
try {
int delta = (end - start) / 2;
int expandedStart = start - delta;
int expandedEnd = end + delta;
//Make sure we are only querying within the chromosome we allow for somewhat pathological cases of start
//being negative and end being outside, but only if directly queried. Our expansion should not
//set start < 0 or end > chromosomeLength
if (start >= 0) {
expandedStart = Math.max(0, expandedStart);
}
Genome genome = GenomeManager.getInstance().getCurrentGenome();
if (genome != null) {
Chromosome c = genome.getChromosome(chr);
if (c != null && end < c.getLength()) expandedEnd = Math.min(c.getLength(), expandedEnd);
}
Iterator<Feature> iter = source.getFeatures(chr, expandedStart, expandedEnd);
if (iter == null) {
PackedFeatures pf = new PackedFeatures(chr, expandedStart, expandedEnd);
packedFeaturesMap.put(frame.getName(), pf);
} else {
PackedFeatures pf = new PackedFeatures(chr, expandedStart, expandedEnd, iter, getName());
packedFeaturesMap.put(frame.getName(), pf);
//log.info("Loaded " + chr + " " + expandedStart + "-" + expandedEnd);
}
} catch (Exception e) {
// Mark the interval with an empty feature list to prevent an endless loop of load attempts.
PackedFeatures pf = new PackedFeatures(chr, start, end);
packedFeaturesMap.put(frame.getName(), pf);
String msg = "Error loading features for interval: " + chr + ":" + start + "-" + end + " <br>" + e.toString();
MessageUtils.showMessage(msg);
log.error(msg, e);
}
}
@Override
public void render(RenderContext context, Rectangle rect) {
Rectangle renderRect = new Rectangle(rect);
renderRect.y = renderRect.y + margin;
renderRect.height -= margin;
showFeatures = isShowFeatures(context.getReferenceFrame());
if (showFeatures) {
if (lastFeatureMode != null) {
super.setDisplayMode(lastFeatureMode);
lastFeatureMode = null;
}
renderFeatures(context, renderRect);
} else {
if (getDisplayMode() != DisplayMode.COLLAPSED) {
// An ugly hack, but we want to prevent this for vcf tracks
if (!(this instanceof VariantTrack)) {
lastFeatureMode = getDisplayMode();
super.setDisplayMode(DisplayMode.COLLAPSED);
}
}
renderCoverage(context, renderRect);
}
if (FeatureTrack.drawBorder) {
Graphics2D borderGraphics = context.getGraphic2DForColor(UIConstants.TRACK_BORDER_GRAY);
borderGraphics.drawLine(rect.x, rect.y, rect.x + rect.width, rect.y);
//TODO Fix height for variant track
borderGraphics.drawLine(rect.x, rect.y + rect.height, rect.x + rect.width, rect.y + rect.height);
}
}
protected boolean isShowFeatures(ReferenceFrame frame) {
if (frame.getChrName().equals(Globals.CHR_ALL)) {
return false;
} else {
double windowSize = frame.getEnd() - frame.getOrigin();
int vw = getVisibilityWindow();
return (vw <= 0 || windowSize <= vw);
}
}
protected void renderCoverage(RenderContext context, Rectangle inputRect) {
final String chr = context.getChr();
List<LocusScore> scores = (source != null && chr.equals(Globals.CHR_ALL)) ?
source.getCoverageScores(chr, (int) context.getOrigin(),
(int) context.getEndLocation(), context.getZoom()) :
null;
if (scores == null) {
Graphics2D g = context.getGraphic2DForColor(Color.gray);
Rectangle textRect = new Rectangle(inputRect);
// Keep text near the top of the track rectangle
textRect.height = Math.min(inputRect.height, 20);
String message = getZoomInMessage(chr);
GraphicUtils.drawCenteredText(message, textRect, g);
} else {
float max = getMaxEstimate(scores);
ContinuousColorScale cs = getColorScale();
if (cs != null) {
cs.setPosEnd(max);
}
if (this.dataRange == null) {
setDataRange(new DataRange(0, 0, max));
} else {
this.dataRange.maximum = max;
}
coverageRenderer.render(scores, context, inputRect, this);
}
}
protected String getZoomInMessage(String chr) {
return chr.equals(Globals.CHR_ALL) ? "Zoom in to see features." :
"Zoom in to see features, or right-click to increase Feature Visibility Window.";
}
private float getMaxEstimate(List<LocusScore> scores) {
float max = 0;
int n = Math.min(200, scores.size());
for (int i = 0; i < n; i++) {
max = Math.max(max, scores.get(i).getScore());
}
return max;
}
/**
* Render features in the given input rectangle.
*
* @param context
* @param inputRect
*/
protected void renderFeatures(RenderContext context, Rectangle inputRect) {
if (log.isTraceEnabled()) {
String msg = String.format("renderFeatures: %s frame: %s", getName(), context.getReferenceFrame().getName());
log.trace(msg);
}
PackedFeatures packedFeatures = packedFeaturesMap.get(context.getReferenceFrame().getName());
if (packedFeatures == null || !packedFeatures.overlapsInterval(context.getChr(), (int) context.getOrigin(), (int) context.getEndLocation() + 1)) {
return;
}
try {
renderFeatureImpl(context, inputRect, packedFeatures);
} catch (TribbleException e) {
log.error("Tribble error", e);
//Error loading features. We'll let the user decide if this is "fatal" or not.
if (!fatalLoadError) {
fatalLoadError = true;
boolean unload = MessageUtils.confirm("<html> Error loading features: " + e.getMessage() +
"<br>Unload track " + getName() + "?");
if (unload) {
Collection<Track> tmp = Arrays.asList((Track) this);
IGV.getInstance().removeTracks(tmp);
IGV.getInstance().repaint();
} else {
fatalLoadError = false;
}
}
}
}
protected void renderFeatureImpl(RenderContext context, Rectangle inputRect, PackedFeatures packedFeatures) {
Renderer renderer = getRenderer();
if (areFeaturesStacked()) {
List<PackedFeatures.FeatureRow> rows = packedFeatures.getRows();
if (rows != null && rows.size() > 0) {
int nLevels = rows.size();
synchronized (levelRects) {
levelRects.clear();
// Divide rectangle into equal height levels
double h = getDisplayMode() == DisplayMode.SQUISHED ? squishedRowHeight : expandedRowHeight;
Rectangle rect = new Rectangle(inputRect.x, inputRect.y, inputRect.width, (int) h);
int i = 0;
if (renderer instanceof FeatureRenderer) ((FeatureRenderer) renderer).reset();
for (PackedFeatures.FeatureRow row : rows) {
levelRects.add(new Rectangle(rect));
renderer.render(row.features, context, levelRects.get(i), this);
if (selectedFeatureRowIndex == i) {
Graphics2D fontGraphics = context.getGraphic2DForColor(SELECTED_FEATURE_ROW_COLOR);
fontGraphics.fillRect(rect.x, rect.y, rect.width, rect.height);
}
rect.y += h;
i++;
}
}
}
} else {
List<Feature> features = packedFeatures.getFeatures();
if (features != null) {
renderer.render(features, context, inputRect, this);
}
}
}
/**
* Return the nextLine or previous feature relative to the center location.
* TODO -- investigate delegating this method to FeatureSource, where it might be possible to simplify the implementation
*
* @param chr
* @param center
* @param forward
* @return
* @throws IOException
*/
public Feature nextFeature(String chr, double center, boolean forward, ReferenceFrame frame) throws IOException {
Feature f = null;
boolean canScroll = (forward && !frame.windowAtEnd()) || (!forward && frame.getOrigin() > 0);
PackedFeatures packedFeatures = packedFeaturesMap.get(frame.getName());
if (packedFeatures != null && packedFeatures.containsInterval(chr, (int) center - 1, (int) center + 1)) {
if (packedFeatures.getFeatures().size() > 0 && canScroll) {
f = (forward ? FeatureUtils.getFeatureAfter(center + 1, packedFeatures.getFeatures()) :
FeatureUtils.getFeatureBefore(center - 1, packedFeatures.getFeatures()));
}
if (f == null) {
FeatureSource rawSource = source;
if (source instanceof CachingFeatureSource) {
rawSource = ((CachingFeatureSource) source).getSource();
}
f = FeatureTrackUtils.nextFeature(rawSource, chr, packedFeatures.getStart(), packedFeatures.getEnd(), forward);
}
}
return f;
}
public void setVisibilityWindow(int windowSize) {
super.setVisibilityWindow(windowSize);
packedFeaturesMap.clear();
source.setFeatureWindowSize(visibilityWindow);
}
public int getSelectedFeatureRowIndex() {
return selectedFeatureRowIndex;
}
public void setSelectedFeatureRowIndex(int selectedFeatureRowIndex) {
this.selectedFeatureRowIndex = selectedFeatureRowIndex;
}
public IGVFeature getSelectedFeature() {
return selectedFeature;
}
public static boolean isDrawBorder() {
return drawBorder;
}
public static void setDrawBorder(boolean drawBorder) {
FeatureTrack.drawBorder = drawBorder;
}
public boolean isAlternateExonColor() {
return alternateExonColor;
}
/**
* This method exists for Plugin tracks. When restoring a session there is no guarantee of track
* order, so arguments referring to other tracks may fail to resolve. We update those references
* here after all tracks have been processed
*
* @param allTracks
*/
public void updateTrackReferences(List<Track> allTracks) {
}
/**
* Features are packed upon loading, effectively a cache.
* This clears that cache. Used to force a refresh
*/
public void clearPackedFeatures() {
this.packedFeaturesMap.clear();
}
/**
* Return currently loaded features. Used to export features to a file.
*
* @param frame
* @return
*/
public List<Feature> getVisibleFeatures(ReferenceFrame frame) {
PackedFeatures packedFeatures = packedFeaturesMap.get(frame.getName());
return (packedFeatures == null) ? Collections.emptyList() : packedFeatures.getFeatures();
}
public void setTrackLine(String trackLine) {
this.trackLine = trackLine;
}
/**
* Return "track" line information for exporting features to a file. Default is null, subclasses may override.
*
* @return
*/
public String getExportTrackLine() {
return trackLine;
}
@Override
public void unmarshalXML(Element element, Integer version) {
super.unmarshalXML(element, version);
NodeList tmp = element.getElementsByTagName("SequenceMatchSource");
if (tmp.getLength() > 0) {
Element sourceElement = (Element) tmp.item(0);
MotifFinderSource source = new MotifFinderSource();
source.unmarshalXML(sourceElement, version);
this.source = source;
}
}
} |
package org.opentdc.resources.opencrx;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;
import javax.jdo.PersistenceManager;
import javax.jmi.reflect.DuplicateException;
import javax.naming.NamingException;
import javax.servlet.ServletContext;
import org.opencrx.kernel.account1.cci2.ContactQuery;
import org.opencrx.kernel.account1.jmi1.Contact;
import org.opencrx.kernel.activity1.cci2.ResourceQuery;
import org.opencrx.kernel.activity1.jmi1.Resource;
import org.opencrx.kernel.utils.Utils;
import org.openmdx.base.exception.ServiceException;
import org.openmdx.base.persistence.cci.Queries;
import org.openmdx.base.rest.spi.Facades;
import org.openmdx.base.rest.spi.Query_2Facade;
import org.opentdc.opencrx.AbstractOpencrxServiceProvider;
import org.opentdc.opencrx.ActivitiesHelper;
import org.opentdc.resources.ResourceModel;
import org.opentdc.resources.ServiceProvider;
import org.opentdc.service.exception.InternalServerErrorException;
import org.opentdc.service.exception.NotFoundException;
/**
* OpencrxServiceProvider
*
*/
public class OpencrxServiceProvider extends AbstractOpencrxServiceProvider implements ServiceProvider {
protected static final Logger logger = Logger.getLogger(OpencrxServiceProvider.class.getName());
/**
* Constructor.
*
* @param context
* @param prefix
* @throws ServiceException
* @throws NamingException
*/
public OpencrxServiceProvider(
ServletContext context,
String prefix
) throws ServiceException, NamingException {
super(context, prefix);
}
/**
* Map resource to resource model.
*
* @param resource
* @return
*/
protected ResourceModel newResourceModel(
Resource resource
) {
ResourceModel _r = new ResourceModel();
_r.setName(resource.getName());
if(resource.getContact() != null) {
_r.setFirstName(resource.getContact().getFirstName());
_r.setLastName(resource.getContact().getLastName());
}
return _r;
}
/* (non-Javadoc)
* @see org.opentdc.resources.ServiceProvider#listResources(java.lang.String, java.lang.String, long, long)
*/
@Override
public List<ResourceModel> listResources(
String queryType,
String query,
int position,
int size
) {
try {
PersistenceManager pm = this.getPersistenceManager();
org.opencrx.kernel.activity1.jmi1.Segment activitySegment = this.getActivitySegment();
Query_2Facade resourcesQueryFacade = Facades.newQuery(null);
resourcesQueryFacade.setQueryType(
queryType == null || queryType.isEmpty()
? "org:opencrx:kernel:activity1:Resource"
: queryType
);
if(query != null && !query.isEmpty()) {
resourcesQueryFacade.setQuery(query);
}
ResourceQuery resourcesQuery = (ResourceQuery)pm.newQuery(
Queries.QUERY_LANGUAGE,
resourcesQueryFacade.getDelegate()
);
resourcesQuery.forAllDisabled().isFalse();
resourcesQuery.orderByName().ascending();
resourcesQuery.thereExistsCategory().equalTo(ActivitiesHelper.RESOURCE_CATEGORY_PROJECT);
List<Resource> resources = activitySegment.getResource(resourcesQuery);
List<ResourceModel> result = new ArrayList<ResourceModel>();
int count = 0;
for(Iterator<Resource> i = resources.listIterator(position); i.hasNext(); ) {
Resource resource = i.next();
result.add(this.newResourceModel(resource));
count++;
if(count > size) {
break;
}
}
return result;
} catch(ServiceException e) {
e.log();
throw new InternalServerErrorException(e.getMessage());
}
}
/* (non-Javadoc)
* @see org.opentdc.resources.ServiceProvider#createResource(org.opentdc.resources.ResourceModel)
*/
@Override
public ResourceModel createResource(
ResourceModel r
) throws DuplicateException {
org.opencrx.kernel.activity1.jmi1.Segment activitySegment = this.getActivitySegment();
org.opencrx.kernel.account1.jmi1.Segment accountSegment = this.getAccountSegment();
if(r.getId() != null) {
Resource resource = null;
try {
resource = activitySegment.getResource(r.getId());
} catch(Exception ignore) {}
if(resource != null) {
throw new org.opentdc.service.exception.DuplicateException();
}
}
PersistenceManager pm = this.getPersistenceManager();
Contact contact = null;
// Find contact matching firstName, lastName
{
ContactQuery contactQuery = (ContactQuery)pm.newQuery(Contact.class);
contactQuery.thereExistsLastName().equalTo(r.getLastName());
contactQuery.thereExistsFirstName().equalTo(r.getFirstName());
contactQuery.forAllDisabled().isFalse();
List<Contact> contacts = accountSegment.getAccount(contactQuery);
if(contacts.isEmpty()) {
contact = pm.newInstance(Contact.class);
contact.setFirstName(r.getFirstName());
contact.setLastName(r.getLastName());
try {
pm.currentTransaction().begin();
accountSegment.addAccount(
Utils.getUidAsString(),
contact
);
pm.currentTransaction().commit();
} catch(Exception e) {
new ServiceException(e).log();
try {
pm.currentTransaction().rollback();
} catch(Exception ignore) {}
}
} else {
contact = contacts.iterator().next();
}
}
// Create resource
Resource resource = null;
{
resource = pm.newInstance(Resource.class);
if(r.getName() == null || r.getName().isEmpty()) {
if(contact == null) {
resource.setName(r.getLastName() + ", " + r.getFirstName());
} else {
resource.setName(contact.getFullName());
}
} else {
resource.setName(r.getName());
}
resource.setContact(contact);
resource.getCategory().add(ActivitiesHelper.RESOURCE_CATEGORY_PROJECT);
try {
pm.currentTransaction().begin();
activitySegment.addResource(
Utils.getUidAsString(),
resource
);
pm.currentTransaction().commit();
} catch(Exception e) {
new ServiceException(e).log();
try {
pm.currentTransaction().rollback();
} catch(Exception ignore) {}
throw new InternalServerErrorException("Unable to create resource");
}
}
return this.newResourceModel(resource);
}
/* (non-Javadoc)
* @see org.opentdc.resources.ServiceProvider#readResource(java.lang.String)
*/
@Override
public ResourceModel readResource(
String id
) throws NotFoundException {
org.opencrx.kernel.activity1.jmi1.Segment activitySegment = this.getActivitySegment();
Resource resource = null;
try {
resource = activitySegment.getResource(id);
} catch(Exception ignore) {}
if(resource == null) {
throw new org.opentdc.service.exception.NotFoundException(id);
} else {
return this.newResourceModel(resource);
}
}
/* (non-Javadoc)
* @see org.opentdc.resources.ServiceProvider#updateResource(java.lang.String, org.opentdc.resources.ResourceModel)
*/
@Override
public ResourceModel updateResource(
String id,
ResourceModel r
) throws NotFoundException {
PersistenceManager pm = this.getPersistenceManager();
org.opencrx.kernel.activity1.jmi1.Segment activitySegment = this.getActivitySegment();
Resource resource = activitySegment.getResource(id);
if(resource == null) {
throw new org.opentdc.service.exception.NotFoundException(id);
} else {
try {
pm.currentTransaction().begin();
resource.setName(r.getName());
pm.currentTransaction().commit();
} catch(Exception e) {
new ServiceException(e).log();
try {
pm.currentTransaction().rollback();
} catch(Exception ignore) {}
throw new InternalServerErrorException("Unable to update resource");
}
return this.newResourceModel(resource);
}
}
/* (non-Javadoc)
* @see org.opentdc.resources.ServiceProvider#deleteResource(java.lang.String)
*/
@Override
public void deleteResource(
String id
) throws NotFoundException {
PersistenceManager pm = this.getPersistenceManager();
org.opencrx.kernel.activity1.jmi1.Segment activitySegment = this.getActivitySegment();
Resource resource = null;
try {
resource = activitySegment.getResource(id);
} catch(Exception ignore) {}
if(resource == null || Boolean.TRUE.equals(resource.isDisabled())) {
throw new org.opentdc.service.exception.NotFoundException(id);
} else {
try {
pm.currentTransaction().begin();
resource.setDisabled(true);
pm.currentTransaction().commit();
} catch(Exception e) {
new ServiceException(e).log();
try {
pm.currentTransaction().rollback();
} catch(Exception ignore) {}
throw new InternalServerErrorException("Unable to delete resource");
}
}
}
/* (non-Javadoc)
* @see org.opentdc.resources.ServiceProvider#countResources()
*/
@Override
public int countResources(
) {
return this.listResources(
null, // queryType
null, // query
0, // position
Integer.MAX_VALUE // size
).size();
}
} |
package org.concord.energy3d.scene;
import java.awt.EventQueue;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import javax.imageio.ImageIO;
import javax.swing.JOptionPane;
import org.concord.energy3d.gui.EnergyPanel;
import org.concord.energy3d.gui.MainFrame;
import org.concord.energy3d.gui.MainPanel;
import org.concord.energy3d.logger.SnapshotLogger;
import org.concord.energy3d.model.Door;
import org.concord.energy3d.model.Floor;
import org.concord.energy3d.model.Foundation;
import org.concord.energy3d.model.HousePart;
import org.concord.energy3d.model.Human;
import org.concord.energy3d.model.Mirror;
import org.concord.energy3d.model.Rack;
import org.concord.energy3d.model.Roof;
import org.concord.energy3d.model.Sensor;
import org.concord.energy3d.model.Snap;
import org.concord.energy3d.model.SolarPanel;
import org.concord.energy3d.model.Thermalizable;
import org.concord.energy3d.model.Tree;
import org.concord.energy3d.model.Wall;
import org.concord.energy3d.model.Window;
import org.concord.energy3d.scene.SceneManager.ViewMode;
import org.concord.energy3d.shapes.Heliodon;
import org.concord.energy3d.simulation.Atmosphere;
import org.concord.energy3d.simulation.DesignSpecs;
import org.concord.energy3d.simulation.Ground;
import org.concord.energy3d.simulation.UtilityBill;
import org.concord.energy3d.undo.AddMultiplePartsCommand;
import org.concord.energy3d.undo.LockAllCommand;
import org.concord.energy3d.undo.PastePartCommand;
import org.concord.energy3d.undo.RemoveMultiplePartsCommand;
import org.concord.energy3d.undo.RemoveMultipleShuttersCommand;
import org.concord.energy3d.undo.SaveCommand;
import org.concord.energy3d.util.Config;
import org.concord.energy3d.util.Util;
import org.concord.energy3d.util.WallVisitor;
import com.ardor3d.image.Texture.MinificationFilter;
import com.ardor3d.image.Texture2D;
import com.ardor3d.image.util.awt.AWTImageLoader;
import com.ardor3d.math.ColorRGBA;
import com.ardor3d.math.Vector3;
import com.ardor3d.math.type.ReadOnlyColorRGBA;
import com.ardor3d.math.type.ReadOnlyVector3;
import com.ardor3d.renderer.Camera;
import com.ardor3d.renderer.state.TextureState;
import com.ardor3d.scenegraph.Mesh;
import com.ardor3d.scenegraph.Node;
import com.ardor3d.util.TextureKey;
public class Scene implements Serializable {
public static final ReadOnlyColorRGBA WHITE = ColorRGBA.WHITE;
public static final ReadOnlyColorRGBA GRAY = ColorRGBA.LIGHT_GRAY;
public static final int CLOUDY_SKY_THEME = 0;
public static final int DESERT_THEME = 1;
public static final int GRASSLAND_THEME = 2;
public static final int FOREST_THEME = 3;
private static final long serialVersionUID = 1L;
private static final Node root = new Node("House Root");
private static final Node originalHouseRoot = new Node("Original House Root");
private static final Node notReceivingShadowRoot = new Node("Trees Root");
private static final int currentVersion = 1;
private static Scene instance;
private static URL url = null;
private static boolean redrawAll = false;
private static boolean drawThickness = false;
private static boolean drawAnnotationsInside = false;
private Unit unit = Unit.InternationalSystemOfUnits;
private transient boolean edited = false;
private final List<HousePart> parts = new ArrayList<HousePart>();
private final Calendar calendar = Calendar.getInstance();
private TextureMode textureMode = TextureMode.Full;
private ReadOnlyVector3 cameraLocation;
private ReadOnlyVector3 cameraDirection;
private ReadOnlyColorRGBA landColor = new ColorRGBA(0, 1, 0, 0.5f);
private ReadOnlyColorRGBA foundationColor;
private ReadOnlyColorRGBA wallColor;
private ReadOnlyColorRGBA doorColor;
private ReadOnlyColorRGBA floorColor;
private ReadOnlyColorRGBA roofColor;
private double annotationScale = 0.2;
private int version = currentVersion;
private boolean isAnnotationsVisible = true;
private long idCounter;
private boolean studentMode;
private String projectName;
private String city;
private int latitude;
private boolean isHeliodonVisible;
private String note;
private int solarContrast;
private boolean hideAxes;
private boolean hideLightBeams;
private boolean showSunAngles;
private boolean showBuildingLabels;
private boolean cleanup;
private double heatVectorLength = 2000;
private boolean alwaysComputeHeatFluxVectors;
private boolean fullEnergyInSolarMap = true;
private boolean onlyReflectedEnergyInMirrorSolarMap;
private boolean noSolarMapForLand;
private boolean disallowFoundationOverlap;
private Ground ground = new Ground();
private Atmosphere atmosphere = new Atmosphere();
private DesignSpecs designSpecs = new DesignSpecs();
private HousePart copyBuffer, originalCopy;
private boolean dashedlineOnRoofs = true;
private boolean onlySolarAnalysis;
private UtilityBill utilityBill;
private int theme;
private transient BufferedImage mapImage;
private transient boolean avoidSavingMapImage;
private double mapScale;
private boolean hideMap;
private double heatFluxGridSize = 2;
/* the following parameters specify the resolution of discretization for a simulation */
// increment of time in minutes
private int timeStep = 15;
// number of points in x and y directions when a plate (e.g., mirrors and solar panels) is discretized into a grid
// used in both radiation calculation and heat map visualization for mirrors
// used in heat map visualization for solar panels (for radiation calculation, solar panels use the underlying solar cell layout, e.g., 6x10, as the discretization)
// to meet the need of texture, these numbers must be power of 2
private int plateNx = 4, plateNy = 4;
// the step length of the discretized grid on any part that is not a plate
private double solarStep = 2.0;
public static enum Unit {
InternationalSystemOfUnits, USCustomaryUnits
};
public static enum TextureMode {
None, Simple, Full
};
public static Scene getInstance() {
if (instance == null) {
try {
open(null);
} catch (final Exception e) {
e.printStackTrace();
}
}
return instance;
}
public static void newFile() {
newFile(80, 60); // by default, the foundation is 16 meters x 12 meters (192 square meters seem right for a house)
}
private static void newFile(final double xLength, final double yLength) {
try {
open(null);
} catch (final Exception e) {
e.printStackTrace();
}
SceneManager.getTaskManager().update(new Callable<Object>() {
@Override
public Object call() throws Exception {
instance.add(new Human(Human.JACK, 1));
instance.add(new Foundation(xLength, yLength), true);
return null;
}
});
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
EnergyPanel.getInstance().update();
EnergyPanel.getInstance().clearAllGraphs();
}
});
}
public static void open(final URL file) throws Exception {
openNow(file);
synchronized (SceneManager.getInstance()) {
EnergyPanel.getInstance().clearRadiationHeatMap();
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
final EnergyPanel e = EnergyPanel.getInstance();
e.update();
e.clearAllGraphs();
if (MainFrame.getInstance().getTopViewCheckBoxMenuItem().isSelected()) { // make sure we exist the 2D top view
MainFrame.getInstance().getTopViewCheckBoxMenuItem().setSelected(false);
SceneManager.getInstance().resetCamera(ViewMode.NORMAL);
loadCameraLocation();
}
final HousePart p = SceneManager.getInstance().getSelectedPart();
if (p instanceof Foundation) {
final Foundation f = (Foundation) p;
switch (f.getSupportingType()) {
case Foundation.BUILDING:
e.getConstructionCostGraph().addGraph(f);
e.getBuildingDailyEnergyGraph().clearData();
e.getBuildingDailyEnergyGraph().addGraph(f);
e.validate();
break;
case Foundation.PV_STATION:
e.getPvStationDailyEnergyGraph().clearData();
e.getPvStationDailyEnergyGraph().addGraph(f);
e.validate();
break;
case Foundation.CSP_STATION:
e.getCspStationDailyEnergyGraph().clearData();
e.getCspStationDailyEnergyGraph().addGraph(f);
e.validate();
break;
}
}
}
});
}
}
public static void openNow(final URL file) throws Exception {
if (PrintController.getInstance().isPrintPreview()) {
MainPanel.getInstance().getPreviewButton().setSelected(false);
while (!PrintController.getInstance().isFinished()) {
Thread.yield();
}
}
synchronized (SceneManager.getInstance()) {
Scene.url = file;
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
MainPanel.getInstance().getHeliodonButton().setSelected(false);
MainPanel.getInstance().getSunAnimationButton().setSelected(false);
}
});
SceneManager.getInstance().setSolarHeatMapWithoutUpdate(false);
Wall.resetDefaultWallHeight();
if (instance != null) {
instance.deleteAll();
}
if (url == null) {
instance = new Scene();
System.out.println("done");
} else {
System.out.print("Opening..." + file + "...");
final ObjectInputStream in = new ObjectInputStream(file.openStream());
instance = (Scene) in.readObject();
in.close();
for (final HousePart part : instance.parts) {
part.getRoot();
}
instance.upgradeSceneToNewVersion();
instance.cleanup();
loadCameraLocation();
}
instance.applyMap();
SceneManager.getInstance().hideAllEditPoints();
final CameraControl cameraControl = SceneManager.getInstance().getCameraControl();
if (cameraControl != null) {
cameraControl.reset();
}
int count = 0;
Foundation first = null;
for (final HousePart p : Scene.getInstance().getParts()) {
if (p instanceof Foundation && !p.isFrozen()) {
if (count == 0) {
first = (Foundation) p;
}
count++;
}
}
if (count == 1) {
SceneManager.getInstance().setSelectedPart(first);
}
instance.init();
instance.redrawAllNow(); // needed in case Heliodon is on and needs to be drawn with correct size
SceneManager.getInstance().updateHeliodonAndAnnotationSize();
}
EventQueue.invokeLater(new Runnable() { // update GUI must be called in Event Queue to prevent possible deadlocks
@Override
public void run() {
if (instance.textureMode == TextureMode.None) {
MainFrame.getInstance().getNoTextureMenuItem().setSelected(true);
} else if (instance.textureMode == TextureMode.Simple) {
MainFrame.getInstance().getSimpleTextureMenuItem().setSelected(true);
} else {
MainFrame.getInstance().getFullTextureMenuItem().setSelected(true);
}
MainPanel.getInstance().getAnnotationButton().setSelected(instance.isAnnotationsVisible);
MainFrame.getInstance().updateTitleBar();
}
});
}
private void init() {
root.detachAllChildren();
originalHouseRoot.detachAllChildren();
notReceivingShadowRoot.detachAllChildren();
root.attachChild(originalHouseRoot);
root.attachChild(notReceivingShadowRoot);
if (url != null) {
for (final HousePart p : parts) {
final boolean b = p instanceof Tree || p instanceof Human;
(b ? notReceivingShadowRoot : originalHouseRoot).attachChild(p.getRoot());
}
System.out.println("initSceneNow done");
/* must redraw now so that heliodon can be initialized to right size if it is to be visible */
// redrawAllNow();
}
root.updateWorldBound(true);
SceneManager.getInstance().updateHeliodonAndAnnotationSize();
SceneManager.getInstance().setAxesVisible(!hideAxes);
SceneManager.getInstance().setBuildingLabelsVisible(showBuildingLabels);
SceneManager.getInstance().getSolarLand().setVisible(!noSolarMapForLand);
setTheme(theme);
SceneManager.getInstance().getLand().setDefaultColor(landColor != null ? landColor : new ColorRGBA(0, 1, 0, 0.5f));
final EnergyPanel energyPanel = EnergyPanel.getInstance();
if (calendar != null) {
final Date time = calendar.getTime();
Heliodon.getInstance().setDate(time);
Heliodon.getInstance().setTime(time);
Util.setSilently(energyPanel.getDateSpinner(), time);
Util.setSilently(energyPanel.getTimeSpinner(), time);
if ("Boston".equals(city) || city == null || "".equals(city)) {
city = "Boston, MA";
latitude = 42;
}
energyPanel.setLatitude(latitude); // already silent
Util.selectSilently(energyPanel.getCityComboBox(), city);
Scene.getInstance().setTreeLeaves();
MainPanel.getInstance().getHeliodonButton().setSelected(isHeliodonVisible);
Heliodon.getInstance().drawSun();
SceneManager.getInstance().changeSkyTexture();
SceneManager.getInstance().setShading(Heliodon.getInstance().isNightTime());
}
// previous versions do not have the following classes
if (designSpecs == null) {
designSpecs = new DesignSpecs();
} else {
designSpecs.setDefaultValues();
}
if (ground == null) {
ground = new Ground();
}
if (atmosphere == null) {
atmosphere = new Atmosphere();
}
if (unit == null) {
unit = Unit.InternationalSystemOfUnits;
}
// restore the default values
if (Util.isZero(heatVectorLength)) {
heatVectorLength = 5000;
}
if (Util.isZero(heatFluxGridSize)) {
heatFluxGridSize = 2;
}
if (Util.isZero(solarStep)) {
solarStep = 2;
}
if (Util.isZero(timeStep)) {
timeStep = 15;
}
if (Util.isZero(plateNx)) {
plateNx = 4;
}
if (Util.isZero(plateNy)) {
plateNy = 4;
}
if (Util.isZero(solarContrast)) {
solarContrast = 50;
}
setEdited(false);
setCopyBuffer(null);
Util.setSilently(energyPanel.getColorMapSlider(), solarContrast);
Util.setSilently(MainPanel.getInstance().getNoteTextArea(), note == null ? "" : note); // need to do this to avoid logging
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
energyPanel.updateThermostat();
MainPanel.getInstance().setNoteVisible(MainPanel.getInstance().isNoteVisible()); // necessary for the scroll bars to show up appropriately
MainPanel.getInstance().getEnergyViewButton().setSelected(false); // moved from OpenNow to here to avoid triggering EnergyComputer -> RedrawAllNow before open is completed
SceneManager.getInstance().getUndoManager().die();
}
});
}
public static double parsePropertyString(final String s) {
final int indexOfSpace = s.indexOf(' ');
return Double.parseDouble(s.substring(0, indexOfSpace != -1 ? indexOfSpace : s.length()));
}
public static void loadCameraLocation() {
final Camera camera = SceneManager.getInstance().getCamera();
if (instance.getCameraLocation() != null && instance.getCameraDirection() != null) {
camera.setLocation(instance.getCameraLocation());
camera.lookAt(instance.getCameraLocation().add(instance.getCameraDirection(), null), Vector3.UNIT_Z);
}
SceneManager.getInstance().getCameraNode().updateFromCamera();
Scene.getInstance().updateEditShapes();
}
public static void importFile(final URL url) throws Exception {
if (PrintController.getInstance().isPrintPreview()) {
MainPanel.getInstance().getPreviewButton().setSelected(false);
while (!PrintController.getInstance().isFinished()) {
Thread.yield();
}
}
if (url != null) {
long max = -1;
for (final HousePart x : Scene.getInstance().parts) {
if (x.getId() > max) {
max = x.getId();
}
}
if (max < 0) {
max = 0;
}
System.out.print("Opening..." + url + "...");
final ObjectInputStream in = new ObjectInputStream(url.openStream());
final Scene instance = (Scene) in.readObject();
in.close();
// instance.cleanup();
instance.upgradeSceneToNewVersion();
if (url != null) {
final AddMultiplePartsCommand cmd = new AddMultiplePartsCommand(new ArrayList<HousePart>(instance.getParts()), url);
synchronized (SceneManager.getInstance()) {
double cx = 0;
double cy = 0;
int count = 0;
for (final HousePart p : instance.getParts()) {
p.setId(max + p.getId());
Scene.getInstance().parts.add(p);
originalHouseRoot.attachChild(p.getRoot());
if (p instanceof Foundation || p instanceof Tree || p instanceof Human) {
final Vector3 c = p.getAbsCenter();
cx += c.getX();
cy += c.getY();
count++;
}
}
final Vector3 position = SceneManager.getInstance().getPickedLocationOnLand();
if (position != null) {
final Vector3 shift = position.subtractLocal(count == 0 ? new Vector3(0, 0, 0) : new Vector3(cx / count, cy / count, 0));
for (final HousePart p : instance.getParts()) {
if (p instanceof Foundation || p instanceof Tree || p instanceof Human) {
for (int i = 0; i < p.getPoints().size(); i++) {
p.getPoints().get(i).addLocal(shift);
}
}
}
}
}
redrawAll = true;
SceneManager.getInstance().getUndoManager().addEdit(cmd);
}
root.updateWorldBound(true);
SceneManager.getInstance().updateHeliodonAndAnnotationSize();
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
// SceneManager.getInstance().getUndoManager().die();
// MainFrame.getInstance().refreshUndoRedo();
MainPanel.getInstance().getEnergyViewButton().setSelected(false);
}
});
} else {
JOptionPane.showMessageDialog(MainFrame.getInstance(), "URL doesn't exist.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
/** This can be used by the user to fix problems that are caused by bugs based on our observations. This is different than cleanup() as the latter cannot be used to remove undrawables. */
public void fixProblems() {
// remove all undrawables
final ArrayList<HousePart> a = new ArrayList<HousePart>();
for (final HousePart p : parts) {
if (!p.isDrawable()) {
a.add(p);
}
}
for (final HousePart p : a) {
remove(p, false);
}
a.clear();
cleanup();
redrawAll(true);
}
private void deleteAll() {
for (final HousePart p : parts) {
p.delete();
}
}
private void cleanup() {
// fix if roof and wall are not linked from each other
for (final HousePart p : parts) {
if (p instanceof Roof) {
final Roof r = (Roof) p;
final HousePart c = r.getContainer();
if (c != null && !c.getChildren().contains(r)) {
c.getChildren().add(r);
}
}
}
final ArrayList<HousePart> toBeRemoved = new ArrayList<HousePart>();
for (final HousePart p : parts) {
// remove all invalid parts or orphan parts without a top container
if (!p.isValid() || ((p instanceof Roof || p instanceof Window || p instanceof Door || p instanceof SolarPanel || p instanceof Floor) && p.getContainer() == null)) {
toBeRemoved.add(p);
}
// remove walls that are at the same position
if (p instanceof Wall) {
if (((Wall) p).isAtSamePlaceAsAnotherPart()) {
toBeRemoved.add(p);
}
}
}
for (final HousePart p : toBeRemoved) {
remove(p, false);
}
// remove children with multiple parents
toBeRemoved.clear();
for (final HousePart p : parts) {
for (final HousePart child : p.getChildren()) {
if (child.getContainer() != p && !toBeRemoved.contains(child)) {
toBeRemoved.add(child);
}
}
}
for (final HousePart p : toBeRemoved) {
remove(p, false);
}
// remove from remaining parents
for (final HousePart p : parts) {
for (final HousePart r : toBeRemoved) {
p.getChildren().remove(r);
}
}
// remove all the children that are not in parts
toBeRemoved.clear();
for (final HousePart p : parts) {
for (final HousePart child : p.getChildren()) {
if (!parts.contains(child) && !toBeRemoved.contains(child)) {
toBeRemoved.add(child);
}
}
}
for (final HousePart p : toBeRemoved) {
remove(p, false);
}
// complete all non-completed parts
for (final HousePart p : parts) {
if (!p.isDrawCompleted()) {
p.complete();
}
}
}
private void upgradeSceneToNewVersion() {
if (textureMode == null) {
textureMode = TextureMode.Full;
for (final HousePart p : parts) {
if (p instanceof Roof) {
((Roof) p).setOverhangLength(0.2);
}
}
}
if (version < 1) {
for (final HousePart part : parts) {
if (part instanceof Foundation) {
((Foundation) part).scaleHouseForNewVersion(10);
}
}
cameraLocation = cameraLocation.multiply(10, null);
setAnnotationScale(1.0);
}
version = currentVersion;
}
public void connectWalls() {
for (final HousePart part : parts) {
if (part instanceof Wall) {
part.reset();
}
}
for (final HousePart part : parts) {
if (part instanceof Wall) {
((Wall) part).connectedWalls();
}
}
for (final HousePart part : parts) {
if (part instanceof Wall) {
((Wall) part).computeInsideDirectionOfAttachedWalls(false);
}
}
}
public static void save(final URL url, final boolean setAsCurrentFile) throws Exception {
save(url, setAsCurrentFile, true, false);
}
public static void save(final URL url, final boolean setAsCurrentFile, final boolean notifyUndoManager, final boolean logger) throws Exception {
SceneManager.getTaskManager().update(new Callable<Object>() {
@Override
public Object call() throws Exception {
if (logger) {
instance.storeMapImageData();
}
if (notifyUndoManager) {
instance.cleanup();
}
// save camera to file
if (SceneManager.getInstance().getViewMode() == ViewMode.NORMAL) {
saveCameraLocation();
}
instance.hideAxes = !SceneManager.getInstance().areAxesVisible();
instance.showBuildingLabels = SceneManager.getInstance().areBuildingLabelsVisible();
instance.calendar.setTime(Heliodon.getInstance().getCalendar().getTime());
instance.latitude = (int) Math.toDegrees(Heliodon.getInstance().getLatitude());
instance.city = (String) EnergyPanel.getInstance().getCityComboBox().getSelectedItem();
instance.isHeliodonVisible = Heliodon.getInstance().isVisible();
instance.note = MainPanel.getInstance().getNoteTextArea().getText().trim();
instance.solarContrast = EnergyPanel.getInstance().getColorMapSlider().getValue();
if (setAsCurrentFile) {
Scene.url = url;
}
System.out.print("Saving " + url + "...");
ObjectOutputStream out;
out = new ObjectOutputStream(new FileOutputStream(url.toURI().getPath()));
out.writeObject(instance);
out.close();
if (notifyUndoManager) {
SceneManager.getInstance().getUndoManager().addEdit(new SaveCommand());
}
if (logger) {
instance.restoreMapImageData();
}
System.out.println("done");
return null;
}
});
}
public static void saveCameraLocation() {
final Camera camera = SceneManager.getInstance().getCamera();
instance.setCameraLocation(camera.getLocation().clone());
instance.setCameraDirection(SceneManager.getInstance().getCamera().getDirection().clone());
}
public static Node getRoot() {
return root;
}
private Scene() {
}
public void add(final HousePart housePart, final boolean redraw) {
final HousePart container = housePart.getContainer();
if (container != null) {
container.getChildren().add(housePart);
}
add(housePart);
if (redraw) {
redrawAll();
}
}
private void add(final HousePart housePart) {
System.out.println("Adding: " + housePart);
if (housePart instanceof Tree || housePart instanceof Human) {
notReceivingShadowRoot.attachChild(housePart.getRoot());
} else {
originalHouseRoot.attachChild(housePart.getRoot());
}
parts.add(housePart);
for (final HousePart child : housePart.getChildren()) {
add(child);
}
}
public void remove(final HousePart housePart, final boolean redraw) {
if (housePart == null) {
return;
}
housePart.setGridsVisible(false);
final HousePart container = housePart.getContainer();
if (container != null) {
container.getChildren().remove(housePart);
}
removeChildren(housePart);
if (redraw) {
redrawAll();
}
}
private void removeChildren(final HousePart housePart) {
System.out.println("Removing: " + housePart);
parts.remove(housePart); // this must happen before call to wall.delete()
for (final HousePart child : housePart.getChildren()) {
removeChildren(child);
}
// originalHouseRoot.detachChild(housePart.getRoot());
housePart.getRoot().removeFromParent();
housePart.delete();
}
private static void setIdOfChildren(final HousePart p) {
final ArrayList<HousePart> children = p.getChildren();
for (final HousePart c : children) {
c.setId(Scene.getInstance().nextID());
if (!c.getChildren().isEmpty()) {
setIdOfChildren(c);
}
}
}
public void setCopyBuffer(final HousePart p) {
EnergyPanel.getInstance().clearRadiationHeatMap();
// exclude the following types of house parts
if (p instanceof Roof || p instanceof Floor || p instanceof Sensor) {
return;
}
copyBuffer = p;
originalCopy = p;
}
public HousePart getCopyBuffer() {
return copyBuffer;
}
public HousePart getOriginalCopy() {
return originalCopy;
}
public void paste() {
if (copyBuffer == null) {
return;
}
if (copyBuffer instanceof Foundation) {
return;
}
EnergyPanel.getInstance().clearRadiationHeatMap();
final HousePart c = copyBuffer.copy(true);
if (c == null) {
return;
}
add(c, true);
copyBuffer = c;
SceneManager.getInstance().getUndoManager().addEdit(new PastePartCommand(c));
EnergyPanel.getInstance().clearRadiationHeatMap();
EnergyPanel.getInstance().update();
}
public void pasteToPickedLocationOnLand() {
EnergyPanel.getInstance().clearRadiationHeatMap();
if (copyBuffer == null) {
return;
}
final HousePart c = copyBuffer.copy(false);
if (c == null) {
return;
}
final Vector3 position = SceneManager.getInstance().getPickedLocationOnLand();
if (position == null) {
return;
}
if (c instanceof Tree || c instanceof Human) {
c.getPoints().set(0, position);
add(c, true);
copyBuffer = c;
SceneManager.getInstance().getUndoManager().addEdit(new PastePartCommand(c));
} else if (c instanceof Foundation) { // pasting a foundation also clones the building above it
final Vector3 shift = position.subtractLocal(c.getAbsCenter()).multiplyLocal(1, 1, 0);
final int n = c.getPoints().size();
for (int i = 0; i < n; i++) {
c.getPoints().get(i).addLocal(shift);
}
add(c, true);
// copy gable info, too
final Foundation oldFoundation = (Foundation) copyBuffer;
final Foundation newFoundation = (Foundation) c;
final List<Roof> oldRoofs = oldFoundation.getRoofs();
final List<Roof> newRoofs = newFoundation.getRoofs();
if (!oldRoofs.isEmpty() && !newRoofs.isEmpty()) {
for (int i = 0; i < newRoofs.size(); i++) {
final Map<Integer, List<Wall>> oldMap = oldRoofs.get(i).getGableEditPointToWallMap();
if (oldMap == null || oldMap.isEmpty()) {
continue;
}
final Map<Integer, List<Wall>> newMap = new HashMap<Integer, List<Wall>>();
for (final Integer key : oldMap.keySet()) {
final List<Wall> oldWalls = oldMap.get(key);
final List<Wall> newWalls = new ArrayList<Wall>();
for (final Wall w : oldWalls) {
newWalls.add(getCopiedWall(w, oldFoundation, newFoundation));
}
newMap.put(key, newWalls);
}
newRoofs.get(i).setGableEditPointToWallMap(newMap);
}
}
copyBuffer = c;
setIdOfChildren(c);
SceneManager.getInstance().getUndoManager().addEdit(new PastePartCommand(c));
}
}
private Wall getCopiedWall(final Wall oldWall, final Foundation oldFoundation, final Foundation newFoundation) {
final ArrayList<HousePart> oldWalls = oldFoundation.getChildren();
final ArrayList<HousePart> newWalls = newFoundation.getChildren();
final int index = oldWalls.indexOf(oldWall);
if (index < 0) {
return null;
}
return (Wall) newWalls.get(index);
}
public void pasteToPickedLocationOnWall() {
EnergyPanel.getInstance().clearRadiationHeatMap();
final HousePart selectedPart = SceneManager.getInstance().getSelectedPart();
if (!(selectedPart instanceof Wall)) {
return;
}
if (copyBuffer == null) {
return;
}
if (copyBuffer instanceof Foundation) {
return;
}
final HousePart c = copyBuffer.copy(false);
if (c == null) {
return;
}
Vector3 position = SceneManager.getInstance().getPickedLocationOnWall();
if (position == null) {
return;
}
final Wall wall = (Wall) selectedPart;
if (wall != c.getContainer()) { // windows and solar panels can be pasted to a different wall
if (c instanceof Window) {
((Window) c).moveTo(wall);
} else if (c instanceof SolarPanel) {
((SolarPanel) c).moveTo(wall);
}
}
position = c.toRelative(position.subtractLocal(c.getContainer().getAbsPoint(0)));
final Vector3 center = c.toRelative(c.getAbsCenter().subtractLocal(c.getContainer().getAbsPoint(0)));
position = position.subtractLocal(center);
final int n = c.getPoints().size();
for (int i = 0; i < n; i++) {
final Vector3 v = c.getPoints().get(i);
v.addLocal(position);
}
// out of boundary check
final List<Vector3> polygon = wall.getWallPolygonPoints();
final List<Vector3> relativePolygon = new ArrayList<Vector3>();
for (final Vector3 p : polygon) {
relativePolygon.add(c.toRelative(p));
}
for (final Vector3 p : relativePolygon) {
final double y = p.getY();
p.setY(p.getZ());
p.setZ(y);
}
for (int i = 0; i < n; i++) {
final Vector3 v = c.getPoints().get(i);
if (!Util.insidePolygon(new Vector3(v.getX(), v.getZ(), v.getY()), relativePolygon)) {
return;
}
}
add(c, true);
copyBuffer = c;
SceneManager.getInstance().getUndoManager().addEdit(new PastePartCommand(c));
}
public void pasteToPickedLocationOnRoof() {
EnergyPanel.getInstance().clearRadiationHeatMap();
if (copyBuffer == null) {
return;
}
if (copyBuffer instanceof Foundation) {
return;
}
final HousePart selectedPart = SceneManager.getInstance().getSelectedPart();
if (!(selectedPart instanceof Roof)) {
return;
}
final HousePart c = copyBuffer.copy(false);
if (c == null) {
return;
}
Vector3 position = SceneManager.getInstance().getPickedLocationOnRoof();
if (position == null) {
return;
}
if (selectedPart != c.getContainer()) { // solar panels and racks can be pasted to a different parent
if (c instanceof SolarPanel) {
((SolarPanel) c).moveTo(selectedPart);
} else if (c instanceof Rack) {
((Rack) c).moveTo(selectedPart);
}
}
position = c.toRelative(position.subtractLocal(c.getContainer().getAbsPoint(0)));
final Vector3 center = c.toRelative(c.getAbsCenter().subtractLocal(c.getContainer().getAbsPoint(0)));
position = position.subtractLocal(center);
final int n = c.getPoints().size();
for (int i = 0; i < n; i++) {
final Vector3 v = c.getPoints().get(i);
v.addLocal(position);
}
if (c instanceof Rack) {
((Rack) c).moveSolarPanels(position);
}
add(c, true);
copyBuffer = c;
SceneManager.getInstance().getUndoManager().addEdit(new PastePartCommand(c));
}
public void pasteToPickedLocationOnRack() {
final HousePart selectedPart = SceneManager.getInstance().getSelectedPart();
if (!(selectedPart instanceof Rack)) {
return;
}
if (!(copyBuffer instanceof SolarPanel)) {
return;
}
EnergyPanel.getInstance().clearRadiationHeatMap();
final HousePart c = copyBuffer.copy(false);
if (c == null) {
return;
}
Vector3 position = SceneManager.getInstance().getPickedLocationOnRack();
if (position == null) {
return;
}
if (selectedPart != c.getContainer()) {
((SolarPanel) c).moveTo(selectedPart);
}
position = c.toRelative(position.subtractLocal(c.getContainer().getAbsPoint(0)));
final Vector3 center = c.toRelative(c.getAbsCenter().subtractLocal(c.getContainer().getAbsPoint(0)));
position = position.subtractLocal(center);
final int n = c.getPoints().size();
for (int i = 0; i < n; i++) {
final Vector3 v = c.getPoints().get(i);
v.addLocal(position);
}
add(c, true);
copyBuffer = c;
SceneManager.getInstance().getUndoManager().addEdit(new PastePartCommand(c));
}
public void pasteToPickedLocationOnFoundation() {
EnergyPanel.getInstance().clearRadiationHeatMap();
final HousePart selectedPart = SceneManager.getInstance().getSelectedPart();
if (!(selectedPart instanceof Foundation)) {
return;
}
if (copyBuffer == null) {
return;
}
final HousePart c = copyBuffer.copy(false);
if (c == null) {
return;
}
Vector3 position = SceneManager.getInstance().getPickedLocationOnFoundation();
if (position == null) {
return;
}
c.setContainer(selectedPart); // move to this foundation
position = c.toRelative(position.subtractLocal(c.getContainer().getAbsPoint(0)));
final Vector3 center = c.toRelative(c.getAbsCenter().subtractLocal(c.getContainer().getAbsPoint(0)));
position = position.subtractLocal(center);
final int n = c.getPoints().size();
for (int i = 0; i < n; i++) {
final Vector3 v = c.getPoints().get(i);
v.addLocal(position);
}
if (c instanceof Rack) {
((Rack) c).moveSolarPanels(position);
}
add(c, true);
copyBuffer = c;
SceneManager.getInstance().getUndoManager().addEdit(new PastePartCommand(c));
}
public List<HousePart> getParts() {
return parts;
}
public HousePart getPart(final long id) {
for (final HousePart p : parts) {
if (id == p.getId()) {
return p;
}
}
return null;
}
public void drawResizeBounds() {
for (final HousePart part : parts) {
if (part instanceof Foundation) {
part.draw();
}
}
}
public static Node getOriginalHouseRoot() {
return originalHouseRoot;
}
public static Node getNotReceivingShadowRoot() {
return notReceivingShadowRoot;
}
public static URL getURL() {
return url;
}
public static boolean isTemplate() {
if (Config.isEclipse()) {
return url != null && url.toString().indexOf("/energy3d/target/classes") != -1;
}
return url != null && url.toString().indexOf(".jar!") != -1;
}
public void setAnnotationsVisible(final boolean visible) {
isAnnotationsVisible = visible;
for (final HousePart part : parts) {
part.setAnnotationsVisible(visible);
}
if (PrintController.getInstance().isPrintPreview()) {
for (final HousePart part : PrintController.getInstance().getPrintParts()) {
part.setAnnotationsVisible(visible);
}
}
if (PrintController.getInstance().isPrintPreview()) {
PrintController.getInstance().restartAnimation();
} else {
SceneManager.getInstance().refresh();
}
}
public void setTextureMode(final TextureMode textureMode) {
this.textureMode = textureMode;
redrawAll();
Scene.getInstance().updateRoofDashLinesColor();
}
public TextureMode getTextureMode() {
return textureMode;
}
public void setDrawThickness(final boolean draw) {
drawThickness = draw;
redrawAll = true;
}
public boolean isDrawThickness() {
return drawThickness;
}
public static boolean isDrawAnnotationsInside() {
return drawAnnotationsInside;
}
public static void setDrawAnnotationsInside(final boolean drawAnnotationsInside) {
Scene.drawAnnotationsInside = drawAnnotationsInside;
synchronized (SceneManager.getInstance()) {
for (final HousePart part : instance.getParts()) {
part.drawAnnotations();
}
}
if (PrintController.getInstance().getPrintParts() != null) {
for (final HousePart part : PrintController.getInstance().getPrintParts()) {
part.drawAnnotations();
}
}
}
public void redrawAll() {
redrawAll(false);
}
public void redrawAll(final boolean cleanup) {
this.cleanup = cleanup;
if (PrintController.getInstance().isPrintPreview()) {
PrintController.getInstance().restartAnimation();
} else {
redrawAll = true;
}
}
public void redrawAllNow() {
System.out.println("redrawAllNow()");
synchronized (SceneManager.getInstance()) {
final long t = System.nanoTime();
if (cleanup) {
cleanup();
cleanup = false;
}
connectWalls();
Snap.clearAnnotationDrawn();
for (final HousePart part : parts) {
if (part instanceof Roof) {
part.draw();
}
}
for (final HousePart part : parts) {
if (!(part instanceof Roof)) {
part.draw();
}
}
// need to draw roof again because roof holes depend on drawn windows
for (final HousePart part : parts) {
if (part instanceof Roof) {
part.draw();
// System.out.println(((Roof) part).getIntersectionCache().size());
}
}
System.out.println("Time = " + (System.nanoTime() - t) / 1000000000.0);
}
// no need for redrawing print parts because they will be regenerated from original parts anyways
redrawAll = false;
}
public void updateAllTextures() {
System.out.println("updateAllTextures()");
for (final HousePart part : parts) {
part.updateTextureAndColor();
}
SceneManager.getInstance().refresh();
}
public void setUnit(final Unit unit) {
this.unit = unit;
redrawAll = true;
}
public Unit getUnit() {
if (unit == null) {
unit = Unit.InternationalSystemOfUnits;
}
return unit;
}
public void setAnnotationScale(final double scale) {
annotationScale = scale;
}
public double getAnnotationScale() {
if (annotationScale == 0) {
annotationScale = 10;
}
return annotationScale;
}
public void updateRoofDashLinesColor() {
for (final HousePart part : parts) {
if (part instanceof Roof) {
((Roof) part).updateDashLinesColor();
}
}
if (PrintController.getInstance().getPrintParts() != null) {
for (final HousePart part : PrintController.getInstance().getPrintParts()) {
if (part instanceof Roof) {
((Roof) part).updateDashLinesColor();
}
}
}
}
public void removeAllTrees() {
final ArrayList<HousePart> trees = new ArrayList<HousePart>();
for (final HousePart part : parts) {
if (part instanceof Tree && !part.isFrozen()) {
trees.add(part);
}
}
if (trees.isEmpty()) {
JOptionPane.showMessageDialog(MainFrame.getInstance(), "There is no tree to remove.", "No Tree", JOptionPane.INFORMATION_MESSAGE);
return;
}
if (JOptionPane.showConfirmDialog(MainFrame.getInstance(), "Do you really want to remove all " + trees.size() + " trees?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) != JOptionPane.YES_OPTION) {
return;
}
final RemoveMultiplePartsCommand c = new RemoveMultiplePartsCommand(trees);
for (final HousePart part : trees) {
remove(part, false);
}
redrawAll();
SceneManager.getInstance().getUndoManager().addEdit(c);
edited = true;
}
public void removeAllHumans() {
final ArrayList<HousePart> humans = new ArrayList<HousePart>();
for (final HousePart part : parts) {
if (part instanceof Human) {
humans.add(part);
}
}
if (humans.isEmpty()) {
JOptionPane.showMessageDialog(MainFrame.getInstance(), "There is no human to remove.", "No Human", JOptionPane.INFORMATION_MESSAGE);
return;
}
if (JOptionPane.showConfirmDialog(MainFrame.getInstance(), "Do you really want to remove all " + humans.size() + " humans?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) != JOptionPane.YES_OPTION) {
return;
}
final RemoveMultiplePartsCommand c = new RemoveMultiplePartsCommand(humans);
for (final HousePart part : humans) {
remove(part, false);
}
redrawAll();
SceneManager.getInstance().getUndoManager().addEdit(c);
edited = true;
}
public void removeAllRoofs() {
final ArrayList<HousePart> roofs = new ArrayList<HousePart>();
for (final HousePart part : parts) {
if (part instanceof Roof && !part.isFrozen()) {
roofs.add(part);
}
}
if (roofs.isEmpty()) {
JOptionPane.showMessageDialog(MainFrame.getInstance(), "There is no roof to remove.", "No Roof", JOptionPane.INFORMATION_MESSAGE);
return;
}
if (JOptionPane.showConfirmDialog(MainFrame.getInstance(), "Do you really want to remove all " + roofs.size() + " roofs?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) != JOptionPane.YES_OPTION) {
return;
}
final RemoveMultiplePartsCommand c = new RemoveMultiplePartsCommand(roofs);
for (final HousePart part : roofs) {
remove(part, false);
}
redrawAll();
SceneManager.getInstance().getUndoManager().addEdit(c);
edited = true;
}
public void removeAllFloors() {
final ArrayList<HousePart> floors = new ArrayList<HousePart>();
for (final HousePart part : parts) {
if (part instanceof Floor && !part.isFrozen()) {
floors.add(part);
}
}
if (floors.isEmpty()) {
JOptionPane.showMessageDialog(MainFrame.getInstance(), "There is no floor to remove.", "No Floor", JOptionPane.INFORMATION_MESSAGE);
return;
}
if (JOptionPane.showConfirmDialog(MainFrame.getInstance(), "Do you really want to remove all " + floors.size() + " floors?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) != JOptionPane.YES_OPTION) {
return;
}
final RemoveMultiplePartsCommand c = new RemoveMultiplePartsCommand(floors);
for (final HousePart part : floors) {
remove(part, false);
}
redrawAll();
SceneManager.getInstance().getUndoManager().addEdit(c);
edited = true;
}
public void removeAllSolarPanels(List<SolarPanel> panels) {
final HousePart selectedPart = SceneManager.getInstance().getSelectedPart();
if (panels == null) {
panels = new ArrayList<SolarPanel>();
if (selectedPart != null) {
if (selectedPart instanceof Rack) {
for (final HousePart part : selectedPart.getChildren()) {
if (part instanceof SolarPanel) {
panels.add((SolarPanel) part);
}
}
} else {
final Foundation foundation = selectedPart instanceof Foundation ? (Foundation) selectedPart : selectedPart.getTopContainer();
for (final HousePart part : parts) {
if (part instanceof SolarPanel && !part.isFrozen() && part.getTopContainer() == foundation) {
panels.add((SolarPanel) part);
}
}
}
} else {
for (final HousePart part : parts) {
if (part instanceof SolarPanel && !part.isFrozen()) {
panels.add((SolarPanel) part);
}
}
}
}
if (panels.isEmpty()) {
JOptionPane.showMessageDialog(MainFrame.getInstance(), "There is no solar panel to remove.", "No Solar Panel", JOptionPane.INFORMATION_MESSAGE);
return;
}
if (JOptionPane.showConfirmDialog(MainFrame.getInstance(), "Do you really want to remove all " + panels.size() + " solar panels" + (selectedPart != null ? " of the selected building" : "") + "?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) != JOptionPane.YES_OPTION) {
return;
}
final RemoveMultiplePartsCommand c = new RemoveMultiplePartsCommand(new ArrayList<HousePart>(panels));
for (final HousePart part : panels) {
remove(part, false);
}
redrawAll();
SceneManager.getInstance().getUndoManager().addEdit(c);
edited = true;
}
public void removeAllMirrors() {
final ArrayList<HousePart> mirrors = new ArrayList<HousePart>();
final HousePart selectedPart = SceneManager.getInstance().getSelectedPart();
if (selectedPart != null) {
final Foundation foundation = selectedPart instanceof Foundation ? (Foundation) selectedPart : selectedPart.getTopContainer();
for (final HousePart part : parts) {
if (part instanceof Mirror && !part.isFrozen() && part.getTopContainer() == foundation) {
mirrors.add(part);
}
}
} else {
for (final HousePart part : parts) {
if (part instanceof Mirror && !part.isFrozen()) {
mirrors.add(part);
}
}
}
if (mirrors.isEmpty()) {
JOptionPane.showMessageDialog(MainFrame.getInstance(), "There is no mirror to remove.", "No Mirror", JOptionPane.INFORMATION_MESSAGE);
return;
}
if (JOptionPane.showConfirmDialog(MainFrame.getInstance(), "Do you really want to remove all " + mirrors.size() + " mirrors" + (selectedPart != null ? " on the selected foundation" : "") + "?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) != JOptionPane.YES_OPTION) {
return;
}
final RemoveMultiplePartsCommand c = new RemoveMultiplePartsCommand(mirrors);
for (final HousePart part : mirrors) {
remove(part, false);
}
redrawAll();
SceneManager.getInstance().getUndoManager().addEdit(c);
edited = true;
}
public void removeAllWindows() {
final ArrayList<HousePart> windows = new ArrayList<HousePart>();
final HousePart selectedPart = SceneManager.getInstance().getSelectedPart();
if (selectedPart != null) {
final Foundation foundation = selectedPart instanceof Foundation ? (Foundation) selectedPart : selectedPart.getTopContainer();
for (final HousePart part : parts) {
if (part instanceof Window && !part.isFrozen() && part.getTopContainer() == foundation) {
windows.add(part);
}
}
} else {
for (final HousePart part : parts) {
if (part instanceof Window && !part.isFrozen()) {
windows.add(part);
}
}
}
if (windows.isEmpty()) {
JOptionPane.showMessageDialog(MainFrame.getInstance(), "There is no window to remove.", "No Window", JOptionPane.INFORMATION_MESSAGE);
return;
}
if (JOptionPane.showConfirmDialog(MainFrame.getInstance(), "Do you really want to remove all " + windows.size() + " windows" + (selectedPart != null ? " of the selected building" : "") + "?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) != JOptionPane.YES_OPTION) {
return;
}
final RemoveMultiplePartsCommand c = new RemoveMultiplePartsCommand(windows);
for (final HousePart part : windows) {
remove(part, false);
}
redrawAll();
SceneManager.getInstance().getUndoManager().addEdit(c);
edited = true;
}
public void removeAllWindowShutters() {
final ArrayList<Window> windows = new ArrayList<Window>();
final HousePart selectedPart = SceneManager.getInstance().getSelectedPart();
if (selectedPart != null) {
final Foundation foundation = selectedPart instanceof Foundation ? (Foundation) selectedPart : selectedPart.getTopContainer();
for (final HousePart part : parts) {
if (part instanceof Window && !part.isFrozen() && part.getTopContainer() == foundation) {
final Window w = (Window) part;
if (w.getLeftShutter() || w.getRightShutter()) {
windows.add(w);
}
}
}
} else {
for (final HousePart part : parts) {
if (part instanceof Window && !part.isFrozen()) {
final Window w = (Window) part;
if (w.getLeftShutter() || w.getRightShutter()) {
windows.add(w);
}
}
}
}
if (windows.isEmpty()) {
JOptionPane.showMessageDialog(MainFrame.getInstance(), "There is no window shutter to remove.", "No Shutter", JOptionPane.INFORMATION_MESSAGE);
return;
}
if (JOptionPane.showConfirmDialog(MainFrame.getInstance(), "Do you really want to remove all " + windows.size() + " window shutters" + (selectedPart != null ? " of the selected building" : "") + "?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) != JOptionPane.YES_OPTION) {
return;
}
final RemoveMultipleShuttersCommand c = new RemoveMultipleShuttersCommand(windows);
for (final HousePart part : windows) {
final Window w = (Window) part;
w.setLeftShutter(false);
w.setRightShutter(false);
}
redrawAll();
SceneManager.getInstance().getUndoManager().addEdit(c);
edited = true;
}
public void removeAllFoundations() {
final ArrayList<HousePart> foundations = new ArrayList<HousePart>();
for (final HousePart part : parts) {
if (part instanceof Foundation && !part.isFrozen()) {
foundations.add(part);
}
}
if (foundations.isEmpty()) {
JOptionPane.showMessageDialog(MainFrame.getInstance(), "There is no activated foundation to remove.", "No Foundation", JOptionPane.INFORMATION_MESSAGE);
return;
}
if (JOptionPane.showConfirmDialog(MainFrame.getInstance(), "Do you really want to remove all " + foundations.size() + " foundations?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) != JOptionPane.YES_OPTION) {
return;
}
final RemoveMultiplePartsCommand c = new RemoveMultiplePartsCommand(foundations);
for (final HousePart part : foundations) {
remove(part, false);
}
redrawAll();
SceneManager.getInstance().getUndoManager().addEdit(c);
edited = true;
}
public void removeAllChildren(final HousePart parent) {
final List<HousePart> children = parent.getChildren();
final String s = parent.getClass().getSimpleName();
final List<HousePart> copy = new ArrayList<HousePart>(); // make a copy to avoid ConcurrentModificationException
for (final HousePart p : children) {
if (p instanceof Roof) {
continue; // make an exception of roof (it is a child of a wall)
}
copy.add(p);
}
if (copy.isEmpty()) {
JOptionPane.showMessageDialog(MainFrame.getInstance(), "There is no element to remove from " + s + ".", "No Element", JOptionPane.INFORMATION_MESSAGE);
return;
}
if (JOptionPane.showConfirmDialog(MainFrame.getInstance(), "Do you really want to remove all " + copy.size() + " elements of " + s + "?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.NO_OPTION) {
return;
}
final RemoveMultiplePartsCommand c = new RemoveMultiplePartsCommand(copy);
for (final HousePart p : copy) {
remove(p, false);
}
redrawAll();
SceneManager.getInstance().getUndoManager().addEdit(c);
edited = true;
}
public void lockAll(final boolean freeze) {
if (parts.isEmpty()) {
return;
}
int lockCount = 0;
for (final HousePart part : parts) {
if (part.isFrozen()) {
lockCount++;
}
}
if (!freeze) {
if (lockCount > 0) {
if (JOptionPane.showConfirmDialog(MainFrame.getInstance(), "<html>A lock prevents a component from being edited.<br>Do you really want to remove all the existing " + lockCount + " locks?</html>", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) != JOptionPane.YES_OPTION) {
return;
}
} else {
JOptionPane.showMessageDialog(MainFrame.getInstance(), "<html>A lock prevents a component from being edited.<br>There is no lock to remove.</html>");
return;
}
}
SceneManager.getInstance().getUndoManager().addEdit(new LockAllCommand());
for (final HousePart part : parts) {
part.setFreeze(freeze);
}
if (freeze) {
SceneManager.getInstance().hideAllEditPoints();
}
redrawAll();
edited = true;
}
public static boolean isRedrawAll() {
return redrawAll;
}
public boolean areAnnotationsVisible() {
return isAnnotationsVisible;
}
public ReadOnlyVector3 getCameraLocation() {
return cameraLocation;
}
public void setCameraLocation(final ReadOnlyVector3 cameraLocation) {
this.cameraLocation = cameraLocation;
}
public ReadOnlyVector3 getCameraDirection() {
return cameraDirection;
}
public void setCameraDirection(final ReadOnlyVector3 cameraDirection) {
this.cameraDirection = cameraDirection;
}
public void removeAllGables() {
for (final HousePart part : parts) {
if (part instanceof Roof) {
((Roof) part).removeAllGables();
}
}
}
public ReadOnlyColorRGBA getLandColor() {
return landColor;
}
public void setLandColor(final ReadOnlyColorRGBA c) {
landColor = c;
SceneManager.getInstance().getLand().setDefaultColor(landColor);
}
/** get the default color for foundations */
public ReadOnlyColorRGBA getFoundationColor() {
if (foundationColor == null) {
return WHITE;
}
return foundationColor;
}
/** set the default color for foundations */
public void setFoundationColor(final ReadOnlyColorRGBA foundationColor) {
this.foundationColor = foundationColor;
}
/** get the default color for walls */
public ReadOnlyColorRGBA getWallColor() {
if (wallColor == null) {
return GRAY;
}
return wallColor;
}
/** set the default color for walls */
public void setWallColor(final ReadOnlyColorRGBA wallColor) {
this.wallColor = wallColor;
}
/** get the default color for doors */
public ReadOnlyColorRGBA getDoorColor() {
if (doorColor == null) {
return WHITE;
}
return doorColor;
}
/** set the default color for doors */
public void setDoorColor(final ReadOnlyColorRGBA doorColor) {
this.doorColor = doorColor;
}
/** get the default color for floors */
public ReadOnlyColorRGBA getFloorColor() {
if (floorColor == null) {
return WHITE;
}
return floorColor;
}
/** set the default color for floors */
public void setFloorColor(final ReadOnlyColorRGBA floorColor) {
this.floorColor = floorColor;
}
/** get the default color for roofs */
public ReadOnlyColorRGBA getRoofColor() {
if (roofColor == null) {
return WHITE;
}
return roofColor;
}
/** set the default color for roofs */
public void setRoofColor(final ReadOnlyColorRGBA roofColor) {
this.roofColor = roofColor;
}
public void setWindowColorInContainer(final HousePart container, final ColorRGBA c, final boolean shutter) {
for (final HousePart p : parts) {
if (p instanceof Window && p.getContainer() == container) {
final Window w = (Window) p;
if (shutter) {
w.setShutterColor(c);
} else {
w.setColor(c);
}
w.draw();
}
}
}
public void setShutterLengthInContainer(final HousePart container, final double length) {
for (final HousePart p : parts) {
if (p instanceof Window && p.getContainer() == container) {
final Window w = (Window) p;
w.setShutterLength(length);
w.draw();
}
}
}
public void setShutterColorOfBuilding(final HousePart part, final ReadOnlyColorRGBA color) {
if (part instanceof Foundation) {
return;
}
for (final HousePart p : parts) {
if (p instanceof Window && p.getTopContainer() == part.getTopContainer()) {
final Window w = (Window) p;
w.setShutterColor(color);
w.draw();
}
}
}
public void setShutterLengthOfBuilding(final HousePart part, final double length) {
if (part instanceof Foundation) {
return;
}
for (final HousePart p : parts) {
if (p instanceof Window && p.getTopContainer() == part.getTopContainer()) {
final Window w = (Window) p;
w.setShutterLength(length);
w.draw();
}
}
}
public void setPartColorOfBuilding(final HousePart part, final ReadOnlyColorRGBA color) {
if (part instanceof Foundation) {
part.setColor(color);
} else {
for (final HousePart p : parts) {
if (p.getTopContainer() == part.getTopContainer() && p.getClass().equals(part.getClass())) {
p.setColor(color);
}
}
}
}
public void setColorOfAllPartsOfSameType(final HousePart part, final ReadOnlyColorRGBA color) {
for (final HousePart p : parts) {
if (p.getClass().equals(part.getClass())) {
p.setColor(color);
}
}
}
public List<HousePart> getPartsOfSameTypeInBuilding(final HousePart x) {
final List<HousePart> list = new ArrayList<HousePart>();
if (x instanceof Foundation) {
list.add(x);
} else {
for (final HousePart p : parts) {
if (p.getClass().equals(x.getClass()) && p.getTopContainer() == x.getTopContainer()) {
list.add(p);
}
}
}
return list;
}
public List<HousePart> getAllPartsOfSameType(final HousePart x) {
final List<HousePart> list = new ArrayList<HousePart>();
for (final HousePart p : parts) {
if (p.getClass().equals(x.getClass())) {
list.add(p);
}
}
return list;
}
public void setUValuesOfSameTypeInBuilding(final HousePart x, final double uValue) {
if (x instanceof Thermalizable) {
if (x instanceof Foundation) {
((Foundation) x).setUValue(uValue);
} else {
for (final HousePart p : parts) {
if (p.getClass().equals(x.getClass()) && p.getTopContainer() == x.getTopContainer()) {
((Thermalizable) p).setUValue(uValue);
}
}
}
}
}
public List<Window> getWindowsOnContainer(final HousePart container) {
final List<Window> list = new ArrayList<Window>();
for (final HousePart p : parts) {
if (p instanceof Window && p.getContainer() == container) {
list.add((Window) p);
}
}
return list;
}
public void setWindowShgcInContainer(final HousePart container, final double shgc) {
for (final HousePart p : parts) {
if (p instanceof Window && p.getContainer() == container) {
((Window) p).setSolarHeatGainCoefficient(shgc);
}
}
}
public List<Window> getWindowsOfBuilding(final Foundation foundation) {
final List<Window> list = new ArrayList<Window>();
for (final HousePart p : parts) {
if (p instanceof Window && p.getTopContainer() == foundation) {
list.add((Window) p);
}
}
return list;
}
public void setWindowShgcOfBuilding(final Foundation foundation, final double shgc) {
for (final HousePart p : parts) {
if (p instanceof Window && p.getTopContainer() == foundation) {
((Window) p).setSolarHeatGainCoefficient(shgc);
}
}
}
public List<SolarPanel> getAllSolarPanels() {
final List<SolarPanel> list = new ArrayList<SolarPanel>();
for (final HousePart p : parts) {
if (p instanceof SolarPanel) {
list.add((SolarPanel) p);
}
}
return list;
}
public void setTiltAngleForSolarPanelsOnFoundation(final Foundation foundation, final double angle) {
for (final HousePart p : parts) {
if (p instanceof SolarPanel && p.getTopContainer() == foundation) {
((SolarPanel) p).setTiltAngle(angle);
p.draw();
}
}
SceneManager.getInstance().refresh();
}
public void setTiltAngleForAllSolarPanels(final double angle) {
for (final HousePart p : parts) {
if (p instanceof SolarPanel) {
((SolarPanel) p).setTiltAngle(angle);
p.draw();
}
}
SceneManager.getInstance().refresh();
}
public void setAzimuthForSolarPanelsOnFoundation(final Foundation foundation, final double angle) {
for (final HousePart p : parts) {
if (p instanceof SolarPanel && p.getTopContainer() == foundation) {
((SolarPanel) p).setRelativeAzimuth(angle);
p.draw();
}
}
SceneManager.getInstance().refresh();
}
public void setAzimuthForAllSolarPanels(final double angle) {
for (final HousePart p : parts) {
if (p instanceof SolarPanel) {
((SolarPanel) p).setRelativeAzimuth(angle);
p.draw();
}
}
SceneManager.getInstance().refresh();
}
public void setBaseHeightForSolarPanelsOnFoundation(final Foundation foundation, final double baseHeight) {
for (final HousePart p : parts) {
if (p instanceof SolarPanel && p.getTopContainer() == foundation) {
((SolarPanel) p).setBaseHeight(baseHeight);
p.draw();
}
}
SceneManager.getInstance().refresh();
}
public void setBaseHeightForAllSolarPanels(final double baseHeight) {
for (final HousePart p : parts) {
if (p instanceof SolarPanel) {
((SolarPanel) p).setBaseHeight(baseHeight);
p.draw();
}
}
SceneManager.getInstance().refresh();
}
public void setTrackerForSolarPanelsOnFoundation(final Foundation foundation, final int tracker) {
for (final HousePart p : parts) {
if (p instanceof SolarPanel && p.getTopContainer() == foundation) {
((SolarPanel) p).setTracker(tracker);
p.draw();
}
}
SceneManager.getInstance().refresh();
}
public void setTrackerForAllSolarPanels(final int tracker) {
for (final HousePart p : parts) {
if (p instanceof SolarPanel) {
((SolarPanel) p).setTracker(tracker);
p.draw();
}
}
SceneManager.getInstance().refresh();
}
public void setShadeToleranceForSolarPanelsOnFoundation(final Foundation foundation, final int cellWiring) {
for (final HousePart p : parts) {
if (p instanceof SolarPanel && p.getTopContainer() == foundation) {
((SolarPanel) p).setShadeTolerance(cellWiring);
}
}
}
public void setShadeToleranceForAllSolarPanels(final int cellWiring) {
for (final HousePart p : parts) {
if (p instanceof SolarPanel) {
((SolarPanel) p).setShadeTolerance(cellWiring);
}
}
}
public void setSolarCellEfficiencyOnFoundation(final Foundation foundation, final double eff) {
for (final HousePart p : parts) {
if (p instanceof SolarPanel && p.getTopContainer() == foundation) {
((SolarPanel) p).setCellEfficiency(eff);
}
}
}
public void setSolarCellEfficiencyForAll(final double eff) {
for (final HousePart p : parts) {
if (p instanceof SolarPanel) {
((SolarPanel) p).setCellEfficiency(eff);
}
}
}
public void setTemperatureCoefficientPmaxOnFoundation(final Foundation foundation, final double tcPmax) {
for (final HousePart p : parts) {
if (p instanceof SolarPanel && p.getTopContainer() == foundation) {
((SolarPanel) p).setTemperatureCoefficientPmax(tcPmax);
}
}
}
public void setTemperatureCoefficientPmaxForAll(final double tcPmax) {
for (final HousePart p : parts) {
if (p instanceof SolarPanel) {
((SolarPanel) p).setTemperatureCoefficientPmax(tcPmax);
}
}
}
public void setSolarPanelInverterEfficiencyOnFoundation(final Foundation foundation, final double eff) {
for (final HousePart p : parts) {
if (p instanceof SolarPanel && p.getTopContainer() == foundation) {
((SolarPanel) p).setInverterEfficiency(eff);
}
}
}
public void setSolarPanelInverterEfficiencyForAll(final double eff) {
for (final HousePart p : parts) {
if (p instanceof SolarPanel) {
((SolarPanel) p).setInverterEfficiency(eff);
}
}
}
public List<Rack> getAllRacks() {
final List<Rack> list = new ArrayList<Rack>();
for (final HousePart p : parts) {
if (p instanceof Rack) {
list.add((Rack) p);
}
}
return list;
}
public void setTiltAngleForRacksOnFoundation(final Foundation foundation, final double angle) {
for (final HousePart p : parts) {
if (p instanceof Rack && p.getTopContainer() == foundation) {
((Rack) p).setTiltAngle(angle);
p.draw();
}
}
SceneManager.getInstance().refresh();
}
public void setTiltAngleForAllRacks(final double angle) {
for (final HousePart p : parts) {
if (p instanceof Rack) {
((Rack) p).setTiltAngle(angle);
p.draw();
}
}
SceneManager.getInstance().refresh();
}
public void setAzimuthForRacksOnFoundation(final Foundation foundation, final double angle) {
for (final HousePart p : parts) {
if (p instanceof Rack && p.getTopContainer() == foundation) {
((Rack) p).setRelativeAzimuth(angle);
p.draw();
}
}
SceneManager.getInstance().refresh();
}
public void setAzimuthForAllRacks(final double angle) {
for (final HousePart p : parts) {
if (p instanceof Rack) {
((Rack) p).setRelativeAzimuth(angle);
p.draw();
}
}
SceneManager.getInstance().refresh();
}
public void setBaseHeightForRacksOnFoundation(final Foundation foundation, final double baseHeight) {
for (final HousePart p : parts) {
if (p instanceof Rack && p.getTopContainer() == foundation) {
((Rack) p).setBaseHeight(baseHeight);
p.draw();
}
}
SceneManager.getInstance().refresh();
}
public void setBaseHeightForAllRacks(final double baseHeight) {
for (final HousePart p : parts) {
if (p instanceof Rack) {
((Rack) p).setBaseHeight(baseHeight);
p.draw();
}
}
SceneManager.getInstance().refresh();
}
public void setSizeForRacksOnFoundation(final Foundation foundation, final double width, final double height) {
for (final HousePart p : parts) {
if (p instanceof Rack && p.getTopContainer() == foundation) {
((Rack) p).setRackWidth(width);
((Rack) p).setRackHeight(height);
p.draw();
}
}
SceneManager.getInstance().refresh();
}
public void setSizeForAllRacks(final double width, final double height) {
for (final HousePart p : parts) {
if (p instanceof Rack) {
((Rack) p).setRackWidth(width);
((Rack) p).setRackHeight(height);
p.draw();
}
}
SceneManager.getInstance().refresh();
}
public void setPoleSpacingForRacksOnFoundation(final Foundation foundation, final double dx, final double dy) {
for (final HousePart p : parts) {
if (p instanceof Rack && p.getTopContainer() == foundation) {
((Rack) p).setPoleDistanceX(dx);
((Rack) p).setPoleDistanceY(dy);
p.draw();
}
}
SceneManager.getInstance().refresh();
}
public void setPoleSpacingForAllRacks(final double dx, final double dy) {
for (final HousePart p : parts) {
if (p instanceof Rack) {
((Rack) p).setPoleDistanceX(dx);
((Rack) p).setPoleDistanceY(dy);
p.draw();
}
}
SceneManager.getInstance().refresh();
}
public List<Mirror> getAllMirrors() {
final List<Mirror> list = new ArrayList<Mirror>();
for (final HousePart p : parts) {
if (p instanceof Mirror) {
list.add((Mirror) p);
}
}
return list;
}
public void setZenithAngleForMirrorsOfFoundation(final Foundation foundation, final double angle) {
for (final HousePart p : parts) {
if (p instanceof Mirror && p.getTopContainer() == foundation) {
((Mirror) p).setTiltAngle(angle);
p.draw();
}
}
SceneManager.getInstance().refresh();
}
public void setTiltAngleForAllMirrors(final double angle) {
for (final HousePart p : parts) {
if (p instanceof Mirror) {
((Mirror) p).setTiltAngle(angle);
p.draw();
}
}
SceneManager.getInstance().refresh();
}
public void setAzimuthForMirrorsOnFoundation(final Foundation foundation, final double angle) {
for (final HousePart p : parts) {
if (p instanceof Mirror && p.getTopContainer() == foundation) {
((Mirror) p).setRelativeAzimuth(angle);
p.draw();
}
}
SceneManager.getInstance().refresh();
}
public void setAzimuthForAllMirrors(final double angle) {
for (final HousePart p : parts) {
if (p instanceof Mirror) {
((Mirror) p).setRelativeAzimuth(angle);
p.draw();
}
}
SceneManager.getInstance().refresh();
}
public void setReflectivityForMirrorsOnFoundation(final Foundation foundation, final double reflectivity) {
for (final HousePart p : parts) {
if (p instanceof Mirror && p.getTopContainer() == foundation) {
((Mirror) p).setReflectivity(reflectivity);
}
}
}
public void setReflectivityForAllMirrors(final double reflectivity) {
for (final HousePart p : parts) {
if (p instanceof Mirror) {
((Mirror) p).setReflectivity(reflectivity);
}
}
}
public void setTargetForMirrorsOnFoundation(final Foundation foundation, final Foundation target) {
final List<Foundation> oldTargets = new ArrayList<Foundation>();
for (final HousePart p : parts) {
if (p instanceof Mirror && p.getTopContainer() == foundation) {
final Mirror m = (Mirror) p;
final Foundation t = m.getHeliostatTarget();
if (t != null && !oldTargets.contains(t)) {
oldTargets.add(t);
}
m.setHeliostatTarget(target);
p.draw();
}
}
if (target != null) {
target.drawSolarReceiver();
}
if (!oldTargets.isEmpty()) {
for (final Foundation t : oldTargets) {
t.drawSolarReceiver();
}
}
SceneManager.getInstance().refresh();
}
public void setTargetForAllMirrors(final Foundation target) {
final List<Foundation> oldTargets = new ArrayList<Foundation>();
for (final HousePart p : parts) {
if (p instanceof Mirror) {
final Mirror m = (Mirror) p;
final Foundation t = m.getHeliostatTarget();
if (t != null && !oldTargets.contains(t)) {
oldTargets.add(t);
}
m.setHeliostatTarget(target);
p.draw();
}
}
if (target != null) {
target.drawSolarReceiver();
}
if (!oldTargets.isEmpty()) {
for (final Foundation t : oldTargets) {
t.drawSolarReceiver();
}
}
SceneManager.getInstance().refresh();
}
public void setBaseHeightForMirrorsOnFoundation(final Foundation foundation, final double baseHeight) {
for (final HousePart p : parts) {
if (p instanceof Mirror && p.getTopContainer() == foundation) {
((Mirror) p).setBaseHeight(baseHeight);
p.draw();
}
}
SceneManager.getInstance().refresh();
}
public void setBaseHeightForAllMirrors(final double baseHeight) {
for (final HousePart p : parts) {
if (p instanceof Mirror) {
((Mirror) p).setBaseHeight(baseHeight);
p.draw();
}
}
SceneManager.getInstance().refresh();
}
public void setSizeForMirrorsOnFoundation(final Foundation foundation, final double width, final double height) {
for (final HousePart p : parts) {
if (p instanceof Mirror && p.getTopContainer() == foundation) {
((Mirror) p).setMirrorWidth(width);
((Mirror) p).setMirrorHeight(height);
p.draw();
}
}
SceneManager.getInstance().refresh();
}
public void setSizeForAllMirrors(final double width, final double height) {
for (final HousePart p : parts) {
if (p instanceof Mirror) {
((Mirror) p).setMirrorWidth(width);
((Mirror) p).setMirrorHeight(height);
p.draw();
}
}
SceneManager.getInstance().refresh();
}
public void setThicknessOfWallsOnFoundation(final Foundation foundation, final double thickness) {
for (final HousePart p : parts) {
if (p instanceof Wall && p.getTopContainer() == foundation) {
((Wall) p).setThickness(thickness);
p.draw();
}
}
SceneManager.getInstance().refresh();
}
public void setThicknessForAllWalls(final double thickness) {
for (final HousePart p : parts) {
if (p instanceof Wall) {
((Wall) p).setThickness(thickness);
p.draw();
}
}
SceneManager.getInstance().refresh();
}
public void setHeightOfConnectedWalls(final Wall w, final double height) {
w.visitNeighbors(new WallVisitor() {
@Override
public void visit(final Wall currentWall, final Snap prev, final Snap next) {
currentWall.setHeight(height, true);
currentWall.draw();
}
});
SceneManager.getInstance().refresh();
}
public void setHeightOfWallsOnFoundation(final Foundation foundation, final double height) {
for (final HousePart p : parts) {
if (p instanceof Wall && p.getTopContainer() == foundation) {
((Wall) p).setHeight(height, true);
p.draw();
}
}
SceneManager.getInstance().refresh();
}
public void setHeightForAllWalls(final double height) {
for (final HousePart p : parts) {
if (p instanceof Wall) {
((Wall) p).setHeight(height, true);
p.draw();
}
}
SceneManager.getInstance().refresh();
}
public void setColorOfConnectedWalls(final Wall w, final ColorRGBA color) {
w.visitNeighbors(new WallVisitor() {
@Override
public void visit(final Wall currentWall, final Snap prev, final Snap next) {
currentWall.setColor(color);
currentWall.draw();
}
});
SceneManager.getInstance().refresh();
}
public boolean isEdited() {
return edited;
}
public void setEdited(final boolean edited) {
setEdited(edited, true);
}
public void setEdited(final boolean edited, final boolean recomputeEnergy) {
if (edited) {
SnapshotLogger.getInstance().setSceneEdited(true);
}
this.edited = edited;
MainFrame.getInstance().updateTitleBar();
}
public void updateEditShapes() {
for (final HousePart part : parts) {
part.updateEditShapes();
}
}
public long nextID() {
return ++idCounter;
}
public boolean hasSensor() {
for (final HousePart housePart : parts) {
if (housePart instanceof Sensor) {
return true;
}
}
return false;
}
public void setProjectName(final String projectName) {
this.projectName = projectName;
}
public String getProjectName() {
return projectName;
}
public void setStudentMode(final boolean b) {
studentMode = b;
}
public boolean isStudentMode() {
return studentMode;
}
public void setCity(final String city) {
this.city = city;
}
public String getCity() {
return city;
}
public void setDate(final Date date) {
if (calendar != null) {
calendar.setTime(date);
}
}
public Date getDate() {
if (calendar != null) {
return calendar.getTime();
}
return Heliodon.getInstance().getCalendar().getTime();
}
public void setHeatVectorLength(final double heatVectorLength) {
this.heatVectorLength = heatVectorLength;
}
public double getHeatVectorLength() {
return heatVectorLength;
}
public void setHeatFluxGridSize(final double heatFluxGridSize) {
this.heatFluxGridSize = heatFluxGridSize;
}
public double getHeatVectorGridSize() {
return heatFluxGridSize;
}
public boolean getAlwaysComputeHeatFluxVectors() {
return alwaysComputeHeatFluxVectors;
}
public void setAlwaysComputeHeatFluxVectors(final boolean alwaysComputeHeatFluxVectors) {
this.alwaysComputeHeatFluxVectors = alwaysComputeHeatFluxVectors;
for (final HousePart part : Scene.getInstance().getParts()) {
part.updateHeatFluxVisibility();
}
}
public boolean getOnlyAbsorptionInSolarMap() {
return !fullEnergyInSolarMap;
}
public void setOnlyAbsorptionInSolarMap(final boolean onlyAbsorptionInSolarMap) {
fullEnergyInSolarMap = !onlyAbsorptionInSolarMap;
}
public boolean getOnlyReflectedEnergyInMirrorSolarMap() {
return onlyReflectedEnergyInMirrorSolarMap;
}
public void setOnlyReflectedEnergyInMirrorSolarMap(final boolean onlyReflectedEnergyInMirrorSolarMap) {
this.onlyReflectedEnergyInMirrorSolarMap = onlyReflectedEnergyInMirrorSolarMap;
}
public void setSolarMapForLand(final boolean showSolarMapForLand) {
noSolarMapForLand = !showSolarMapForLand;
}
public boolean getSolarMapForLand() {
return !noSolarMapForLand;
}
public void setDisallowFoundationOverlap(final boolean disallowFoundationOverlap) {
this.disallowFoundationOverlap = disallowFoundationOverlap;
}
public boolean getDisallowFoundationOverlap() {
return disallowFoundationOverlap;
}
public void setSolarHeatMapColorContrast(final int solarContrast) {
this.solarContrast = solarContrast;
}
public int getSolarHeatMapColorContrast() {
return solarContrast;
}
public int getNumberOfSolarPanels() {
int count = 0;
for (final HousePart p : parts) {
if (p instanceof SolarPanel) {
count++;
}
}
return count;
}
public int getNumberOfMirrors() {
int count = 0;
for (final HousePart p : parts) {
if (p instanceof Mirror) {
count++;
}
}
return count;
}
// XIE: This needs to be called for trees to change texture when the month changes
public void setTreeLeaves() {
SceneManager.getTaskManager().update(new Callable<Object>() {
@Override
public Object call() throws Exception {
for (final HousePart p : parts) {
if (p instanceof Tree) {
p.updateTextureAndColor();
}
}
return null;
}
});
}
public void updateMirrors() {
SceneManager.getTaskManager().update(new Callable<Object>() {
@Override
public Object call() throws Exception {
final boolean night = Heliodon.getInstance().isNightTime();
for (final HousePart part : parts) {
if (part instanceof Mirror) {
final Mirror m = (Mirror) part;
if (night) {
m.drawLightBeams(); // call this so that the light beams can be set invisible
} else {
m.draw();
}
}
}
return null;
}
});
}
public void updateSolarPanels() {
SceneManager.getTaskManager().update(new Callable<Object>() {
@Override
public Object call() throws Exception {
final boolean night = Heliodon.getInstance().isNightTime();
for (final HousePart part : parts) {
if (part instanceof SolarPanel) {
final SolarPanel sp = (SolarPanel) part;
if (night) {
sp.drawSunBeam();
} else {
sp.draw();
}
}
}
return null;
}
});
}
public Ground getGround() {
return ground;
}
public Atmosphere getAtmosphere() {
return atmosphere;
}
public DesignSpecs getDesignSpecs() {
return designSpecs;
}
public void setDashedLinesOnRoofShown(final boolean dashedLineOnRoofs) {
this.dashedlineOnRoofs = dashedLineOnRoofs;
}
public boolean areDashedLinesOnRoofShown() {
return dashedlineOnRoofs;
}
public void setOnlySolarAnalysis(final boolean onlySolarAnalysis) {
this.onlySolarAnalysis = onlySolarAnalysis;
}
public boolean getOnlySolarAnalysis() {
return onlySolarAnalysis;
}
public void setUtilityBill(final UtilityBill utilityBill) {
this.utilityBill = utilityBill;
}
public UtilityBill getUtilityBill() {
return utilityBill;
}
public void setTheme(final int theme) {
this.theme = theme;
ReadOnlyColorRGBA c;
switch (theme) {
case DESERT_THEME:
c = new ColorRGBA(1, 1, 1, 0.5f);
break;
case GRASSLAND_THEME:
c = new ColorRGBA(0, 1, 0, 0.5f);
break;
case FOREST_THEME:
c = new ColorRGBA(0, 1, 0.2f, 0.5f);
break;
default:
c = new ColorRGBA(0, 1, 0, 0.5f);
}
setLandColor(c);
SceneManager.getInstance().changeSkyTexture();
}
public int getTheme() {
return theme;
}
public void setLightBeamsVisible(final boolean showLightBeams) {
hideLightBeams = !showLightBeams;
}
public boolean areLightBeamsVisible() {
return !hideLightBeams;
}
public void setSunAnglesVisible(final boolean showSunAngles) {
this.showSunAngles = showSunAngles;
}
public boolean areSunAnglesVisible() {
return showSunAngles;
}
public void setPlateNx(final int plateNx) {
this.plateNx = plateNx;
}
public int getPlateNx() {
return plateNx;
}
public void setPlateNy(final int plateNy) {
this.plateNy = plateNy;
}
public int getPlateNy() {
return plateNy;
}
public void setSolarStep(final double solarStep) {
this.solarStep = solarStep;
}
public double getSolarStep() {
return solarStep;
}
public void setTimeStep(final int timeStep) {
this.timeStep = timeStep;
}
public int getTimeStep() {
return timeStep;
}
public void setMap(final BufferedImage mapImage, final double mapScale) {
this.mapImage = mapImage;
this.mapScale = mapScale;
applyMap();
}
public boolean isMapEnabled() {
return mapImage != null;
}
private void applyMap() {
if (mapImage == null) {
SceneManager.getInstance().getMapLand().setVisible(false);
setFoundationsVisible(true);
} else {
SceneManager.getInstance().resizeMapLand(mapScale);
final Texture2D texture = new Texture2D();
texture.setTextureKey(TextureKey.getRTTKey(MinificationFilter.NearestNeighborNoMipMaps));
texture.setImage(AWTImageLoader.makeArdor3dImage(mapImage, true));
final TextureState textureState = new TextureState();
textureState.setTexture(texture);
final Mesh mesh = SceneManager.getInstance().getMapLand();
mesh.setRenderState(textureState);
mesh.setVisible(!hideMap);
setFoundationsVisible(false);
}
}
private void setFoundationsVisible(final boolean visible) {
for (final HousePart part : Scene.getInstance().getParts()) {
if (part instanceof Foundation) {
part.getMesh().setVisible(visible);
}
}
SceneManager.getInstance().refresh();
}
public void setShowMap(final boolean showMap) {
hideMap = !showMap;
}
public boolean getShowMap() {
return !hideMap;
}
/** used by SnapshotLogger */
private void storeMapImageData() {
avoidSavingMapImage = true;
}
/** used by SnapshotLogger */
private void restoreMapImageData() {
avoidSavingMapImage = false;
}
private void writeObject(final ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
if (mapImage != null && !avoidSavingMapImage) {
ImageIO.write(mapImage, "jpg", out);
}
}
private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
mapImage = ImageIO.read(in);
}
} |
package plugin.importer;
import model.*;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import plugin.OperationNameIcon;
import plugin.PluginsSettings;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Vector;
import static plugin.importer.DiderotProjectImporter.decodeNewLine;
public class DefaultDiderotProjectImporter extends DefaultHandler implements DiderotProjectImporter
{
private Route rootRoute;
private Project project;
private JFrame parent;
static private HashMap<String, OperationNameIcon> availableOperations = new HashMap<>();
static
{
availableOperations.put("New project", new OperationNameIcon("createProject", "new"));
availableOperations.put("Open project", new OperationNameIcon("importProject", "open"));
}
@Override
public HashMap<String, OperationNameIcon> getAvailableImportingOperations()
{
return availableOperations;
}
@Override
public String getPluginName()
{
return "Diderot default project importer";
}
@Override
public String getPluginAuthor()
{
return "Joseph Caillet";
}
@Override
public String getPluginContactInformation()
{
return "https://github.com/JosephCaillet/Diderot";
}
@Override
public String getPluginVersion()
{
return "1.0";
}
@Override
public String getPluginDescription()
{
return "This default plugin is used to provide diderot project opening.";
}
@Override
public void setDiderotData(Route rootRoute, Project project)
{
this.rootRoute = rootRoute;
this.project = project;
}
@Override
public void setParentFrame(JFrame parent)
{
this.parent = parent;
}
public void createProject()
{
project.clear();
project.addResponseFormat("HTML");
project.addResponseFormat("JSON");
project.addResponseFormat("XML");
project.addResponseFormat("CSS");
project.addResponseFormat("CSV");
project.addResponseFormat("Plain text");
project.setDefaultResponseFormat("JSON");
project.addUserRouteProperty("Status", "implemented");
Project.UserDefinedRouteProperty udp = project.getUserRouteProperty("Status");
udp.add("beta");
udp.add("depreciated");
udp.setNewValuesDisabled(true);
project.setName("New Project");
project.setDomain("newProject.com");
project.setAuthors(System.getProperty("user.name"));
rootRoute.clear();
rootRoute.setName("newProject.com");
PluginsSettings.clear();
}
public void importProject()
{
//Todo: remove "." to start in home directory of user
JFileChooser fileChooser = new JFileChooser(".");
fileChooser.setFileFilter(new FileNameExtensionFilter("Diderot project file", "dip"));
if(JFileChooser.APPROVE_OPTION != fileChooser.showOpenDialog(parent))
{
return;
}
try
{
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Element diderotProject = documentBuilder.parse(fileChooser.getSelectedFile()).getDocumentElement();
project.clear();
rootRoute.clear();
PluginsSettings.clear();
loadProject(diderotProject);
loadPluginsProperties(diderotProject);
loadResponsesOutputFormat(diderotProject);
loadUserDefinedProperties(diderotProject);
loadRoutes(diderotProject.getElementsByTagName("route").item(0));
project.setOpenedStatus(true);
PluginsSettings.setPropertyValue("Diderot default project exporter" + "projectFileName", fileChooser.getSelectedFile().getAbsolutePath());
}
catch(SAXException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
catch(ParserConfigurationException e)
{
e.printStackTrace();
}
}
private void loadProject(Element projectElement)
{
project.setName(projectElement.getAttribute("name"));
project.setCompany(projectElement.getAttribute("company"));
project.setAuthors(projectElement.getAttribute("authors"));
project.setContact(projectElement.getAttribute("contact"));
Node description = projectElement.getElementsByTagName("description").item(0).getFirstChild();
if(description != null)
{
project.setDescription(decodeNewLine(description.getTextContent()));
}
}
private void loadPluginsProperties(Element projectElement)
{
Node pluginsProperties = projectElement.getElementsByTagName("pluginsProperties").item(0);
if(pluginsProperties == null)
{
return;
}
NodeList nodeList = pluginsProperties.getChildNodes();
for(int i = 0; i < nodeList.getLength(); i++)
{
Node node = nodeList.item(i);
if(node.getNodeType() == Node.TEXT_NODE)
{
continue;
}
PluginsSettings.setPropertyValue(node.getAttributes().getNamedItem("property").getTextContent(), node.getTextContent());
}
}
private void loadResponsesOutputFormat(Element projectElement)
{
//TODO fix typo in: responseOutputFormat
Node responsesOutputFormat = projectElement.getElementsByTagName("responseOutputFormat").item(0);
NodeList nodeList = responsesOutputFormat.getChildNodes();
for(int i = 0; i < nodeList.getLength(); i++)
{
if(nodeList.item(i).getNodeType() == Node.TEXT_NODE)
{
continue;
}
project.addResponseFormat(nodeList.item(i).getTextContent());
}
}
private void loadUserDefinedProperties(Element projectElement)
{
Node userDefinedProperties = projectElement.getElementsByTagName("userDefinedProperties").item(0);
NodeList nodeList = userDefinedProperties.getChildNodes();
for(int i = 0; i < nodeList.getLength(); i++)
{
if(nodeList.item(i).getNodeType() == Node.TEXT_NODE)
{
continue;
}
NamedNodeMap propAtr = nodeList.item(i).getAttributes();
Vector<String> values = new Vector<>();
String defaultVal = "";
NodeList valuesList = nodeList.item(i).getChildNodes();
for(int j = 0; j< valuesList.getLength(); j++)
{
Node value = valuesList.item(j);
if(value.getNodeType() == Node.TEXT_NODE)
{
continue;
}
String valueText = value.getTextContent();
if(value.getAttributes().getNamedItem("default") != null)
{
defaultVal = valueText;
}
values.add(valueText);
}
project.addUserRouteProperty(propAtr.getNamedItem("name").getTextContent(), defaultVal);
Project.UserDefinedRouteProperty userDefinedRouteProperty = project.getUserRouteProperty(propAtr.getNamedItem("name").getTextContent());
userDefinedRouteProperty.setValuesMemorized(Boolean.parseBoolean(propAtr.getNamedItem("memorize").getTextContent()));
userDefinedRouteProperty.setNewValuesDisabled((Boolean.parseBoolean(propAtr.getNamedItem("disallow").getTextContent())));
}
}
private void loadRoutes(Node routeNode)
{
String routeName = routeNode.getAttributes().getNamedItem("name").getTextContent();
project.setDomain(routeName);
rootRoute.setName(routeName);
loadRoutes(routeNode, rootRoute);
}
private void loadRoutes(Node routeNode, Route route)
{
NodeList routeChildren = routeNode.getChildNodes();
for(int i = 0; i < routeChildren.getLength(); i++)
{
if(routeChildren.item(i).getNodeType() == Node.TEXT_NODE)
{
continue;
}
String nodeName = routeChildren.item(i).getNodeName();
if("description".equals(nodeName))
{
route.setDescription(decodeNewLine(routeChildren.item(i).getTextContent()));
}
else if("methods".equals(nodeName))
{
NodeList methods = routeChildren.item(i).getChildNodes();
for(int j = 0; j < methods.getLength(); j++)
{
if(methods.item(j).getNodeType() == Node.TEXT_NODE)
{
continue;
}
String name = methods.item(j).getAttributes().getNamedItem("name").getTextContent();
HttpMethod newHttpMethod = new HttpMethod();
route.addHttpMethod(name, newHttpMethod);
NodeList methodsChildren = methods.item(j).getChildNodes();
for(int k = 0; k < methodsChildren.getLength(); k++)
{
if(methodsChildren.item(k).getNodeType() == Node.TEXT_NODE)
{
continue;
}
nodeName = methodsChildren.item(k).getNodeName();
if("description".equals(nodeName))
{
newHttpMethod.setDescription(decodeNewLine(methodsChildren.item(k).getTextContent()));
}
else if("parameters".equals(nodeName))
{
NodeList params = methodsChildren.item(k).getChildNodes();
for(int l = 0; l < params.getLength(); l++)
{
if(params.item(l).getNodeType() == Node.TEXT_NODE)
{
continue;
}
NamedNodeMap attributes = params.item(l).getAttributes();
Boolean isRequired = Boolean.valueOf(attributes.getNamedItem("required").getTextContent());
Parameter newParam = new Parameter(isRequired, attributes.getNamedItem("description").getTextContent());
newHttpMethod.addParameter(attributes.getNamedItem("name").getTextContent(), newParam);
}
}
else if("responses".equals(nodeName))
{
NodeList responses = methodsChildren.item(k).getChildNodes();
for(int l = 0; l < responses.getLength(); l++)
{
if(responses.item(l).getNodeType() == Node.TEXT_NODE)
{
continue;
}
nodeName = responses.item(l).getNodeName();
for(int m = 0; m < responses.getLength(); m++)
{
if(responses.item(m).getNodeType() == Node.TEXT_NODE)
{
continue;
}
Response response = new Response();
NamedNodeMap attributes = responses.item(m).getAttributes();
response.setOutputType(attributes.getNamedItem("outputFormat").getTextContent());
NodeList responseChildren = responses.item(m).getChildNodes();
for(int n = 0; n < responseChildren.getLength(); n++)
{
if(responseChildren.item(n).getNodeType() == Node.TEXT_NODE)
{
continue;
}
nodeName = responseChildren.item(n).getNodeName();
if("description".equals(nodeName))
{
response.setDescription(decodeNewLine(responseChildren.item(n).getTextContent()));
}
else if("outputSchema".equals(nodeName))
{
response.setSchema(decodeNewLine(responseChildren.item(n).getTextContent()));
}
}
newHttpMethod.addResponse(attributes.getNamedItem("name").getTextContent(), response);
}
}
}
else if("userDefinedProperties".equals(nodeName))
{
NodeList values = methodsChildren.item(k).getChildNodes();
for(int l = 0; l < values.getLength(); l++)
{
if(values.item(l).getNodeType() == Node.TEXT_NODE)
{
continue;
}
String property = values.item(l).getAttributes().getNamedItem("property").getTextContent();
String value = values.item(l).getTextContent();
newHttpMethod.setUserProperty(property, value);
}
}
}
}
}
else if("routes".equals(nodeName))
{
NodeList childRoutes = routeChildren.item(i).getChildNodes();
for(int j = 0; j < childRoutes.getLength(); j++)
{
if(childRoutes.item(j).getNodeType() == Node.TEXT_NODE)
{
continue;
}
String name = childRoutes.item(j).getAttributes().getNamedItem("name").getTextContent();
Route newRoute = new Route(name);
route.addRoute(name, newRoute);
loadRoutes(childRoutes.item(j), newRoute);
}
}
}
}
} |
package jp.mironal.java.aws.app.glacier;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import jp.mironal.java.aws.app.glacier.JobRestoreParam.Builder;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.ObjectMapper;
import com.amazonaws.AmazonClientException;
import com.amazonaws.auth.policy.Policy;
import com.amazonaws.auth.policy.Principal;
import com.amazonaws.auth.policy.Resource;
import com.amazonaws.auth.policy.Statement;
import com.amazonaws.auth.policy.Statement.Effect;
import com.amazonaws.auth.policy.actions.SQSActions;
import com.amazonaws.services.glacier.AmazonGlacierClient;
import com.amazonaws.services.glacier.model.DescribeJobRequest;
import com.amazonaws.services.glacier.model.DescribeJobResult;
import com.amazonaws.services.glacier.model.GetJobOutputRequest;
import com.amazonaws.services.glacier.model.GetJobOutputResult;
import com.amazonaws.services.glacier.model.GlacierJobDescription;
import com.amazonaws.services.glacier.model.InitiateJobRequest;
import com.amazonaws.services.glacier.model.InitiateJobResult;
import com.amazonaws.services.glacier.model.JobParameters;
import com.amazonaws.services.glacier.model.ListJobsRequest;
import com.amazonaws.services.glacier.model.ListJobsResult;
import com.amazonaws.services.sns.AmazonSNSClient;
import com.amazonaws.services.sns.model.CreateTopicRequest;
import com.amazonaws.services.sns.model.CreateTopicResult;
import com.amazonaws.services.sns.model.DeleteTopicRequest;
import com.amazonaws.services.sns.model.SubscribeRequest;
import com.amazonaws.services.sns.model.SubscribeResult;
import com.amazonaws.services.sns.model.UnsubscribeRequest;
import com.amazonaws.services.sqs.AmazonSQSClient;
import com.amazonaws.services.sqs.model.CreateQueueRequest;
import com.amazonaws.services.sqs.model.CreateQueueResult;
import com.amazonaws.services.sqs.model.DeleteQueueRequest;
import com.amazonaws.services.sqs.model.GetQueueAttributesRequest;
import com.amazonaws.services.sqs.model.GetQueueAttributesResult;
import com.amazonaws.services.sqs.model.Message;
import com.amazonaws.services.sqs.model.ReceiveMessageRequest;
import com.amazonaws.services.sqs.model.SetQueueAttributesRequest;
/**
* .<br>
*
*
* @author yama
*/
public class LowLevelArchiveController extends GlacierTools {
class SqsSetupResult {
private final String queueUrl;
private final String queueArn;
public SqsSetupResult(String sqsQueueUrl, String sqsQueueArn) {
this.queueUrl = sqsQueueUrl;
this.queueArn = sqsQueueArn;
}
}
class SnsSetupResult {
private final String topicArn;
private final String subscriptionArn;
public SnsSetupResult(String snsTopicArn, String snsSubscriptionArn) {
this.topicArn = snsTopicArn;
this.subscriptionArn = snsSubscriptionArn;
}
}
/**
* @param jobId
* @param sqsQueueUrl
* @param sqsClient
* @return
* @throws JsonParseException
* @throws IOException
*/
public static CheckJobResult checkJobToComplete(String jobId, String sqsQueueUrl,
AmazonSQSClient sqsClient) throws JsonParseException, IOException {
ObjectMapper mapper = new ObjectMapper();
JsonFactory factory = mapper.getJsonFactory();
ReceiveMessageRequest messageRequest = new ReceiveMessageRequest(sqsQueueUrl)
.withMaxNumberOfMessages(10);
List<Message> msgs = sqsClient.receiveMessage(messageRequest).getMessages();
System.out.println("get message : msg.size=" + msgs.size());
boolean messageFound = false;
boolean jobSuccessful = false;
if (msgs.size() > 0) {
for (Message m : msgs) {
JsonParser jpMessage = factory.createJsonParser(m.getBody());
JsonNode JobmessageNode = mapper.readTree(jpMessage);
String jobMessage = JobmessageNode.get("Message").getTextValue();
JsonParser jpDesc = factory.createJsonParser(jobMessage);
JsonNode jobDescNode = mapper.readTree(jpDesc);
String retrievedJobId = jobDescNode.get("JobId").getTextValue();
String statusCode = jobDescNode.get("StatusCode").getTextValue();
System.out.println("retrievedJobId=" + retrievedJobId);
System.out.println("StatusCode=" + statusCode);
if (retrievedJobId.equals(jobId)) {
messageFound = true;
if (statusCode.equals("Succeeded")) {
jobSuccessful = true;
}
}
}
}
return new CheckJobResult(messageFound, jobSuccessful);
}
/**
* Job.
*
* @param jobId
* @param vaultName
* @param saveFile
* @param client
*/
public static void downloadJobOutput(String jobId, String vaultName, File saveFile,
AmazonGlacierClient client) {
GetJobOutputRequest getJobOutputRequest = new GetJobOutputRequest()
.withVaultName(vaultName).withJobId(jobId);
GetJobOutputResult getJobOutputResult = client.getJobOutput(getJobOutputRequest);
InputStream in = new BufferedInputStream(getJobOutputResult.getBody());
OutputStream out = null;
try {
out = new BufferedOutputStream(new FileOutputStream(saveFile));
byte[] buffer = new byte[1024 * 1024];
int byteRead = 0;
do {
byteRead = in.read(buffer);
if (byteRead <= 0) {
break;
}
out.write(buffer, 0, byteRead);
} while (byteRead > 0);
} catch (IOException e) {
throw new AmazonClientException("Unable to save archive", e);
} finally {
try {
in.close();
} catch (IOException ignore) {
}
if (out != null) {
try {
out.close();
} catch (IOException ignore) {
}
}
}
}
private AmazonSQSClient sqsClient;
private AmazonSNSClient snsClient;
private boolean alreadyInitiate = false;
private SqsSetupResult sqsSetupResult;
private SnsSetupResult snsSetupResult;
private String jobId;
private String vaultName;
private String archiveId;
private void setVaultNameAndArchiveId(String vaultName, String archiveId) {
if (vaultName == null) {
throw new NullPointerException("vaultName is null.");
}
if (archiveId == null) {
throw new NullPointerException("archiveId is null.");
}
this.vaultName = vaultName;
this.archiveId = archiveId;
}
public LowLevelArchiveController() throws IOException {
super();
}
public LowLevelArchiveController(Region endpoint, File awsProperties) throws IOException {
super(endpoint, awsProperties);
sqsClient = new AmazonSQSClient(credentials);
sqsClient.setEndpoint(GlacierTools.makeUrl(AwsService.Sqs, endpoint));
snsClient = new AmazonSNSClient(credentials);
snsClient.setEndpoint(GlacierTools.makeUrl(AwsService.Sns, endpoint));
}
/**
* Job.
*
* @return Instance of JobRestoreParam.
*/
public JobRestoreParam getJobRestoreParam() {
Builder builder = new Builder();
builder.setVaultName(this.vaultName).setJobId(this.jobId)
.setSnsSubscriptionArn(snsSetupResult.subscriptionArn)
.setSnsTopicArn(snsSetupResult.topicArn).setSqsQueueUrl(sqsSetupResult.queueUrl);
return builder.build();
}
/**
* Job.
*
* @param param
*/
public void restoreJob(JobRestoreParam param) {
if (param == null) {
throw new NullPointerException("param is null.");
}
this.vaultName = param.getVaultName();
this.jobId = param.getJobId();
this.snsSetupResult = new SnsSetupResult(param.getSnsTopicArn(),
param.getSnsSubscriptionArn());
this.sqsSetupResult = new SqsSetupResult(param.getSqsQueueUrl(), "");
}
/**
* inventory-retrievalJob.<br>
* inventory-retrievalVaultJob
*
* @param vaultName Vault.
* @return jobId
*/
public String initiateInventoryJob(String vaultName) {
setVaultNameAndArchiveId(vaultName, "");
// setup the SQS and SNS
setupJob();
JobParameters jobParameters = new JobParameters().withType("inventory-retrieval")
.withDescription("inventory-retrieval_job").withFormat("JSON")
.withSNSTopic(snsSetupResult.topicArn);
return executeInitiateJob(jobParameters);
}
/**
* archive-retrievalJob.<br>
* archive-retrievalVaultArchiveJob.
*
* @param vaultName ArchiveVault
* @param archiveId ArchiveID
* @return jobId
*/
public String initiateArchiveJob(String vaultName, String archiveId) {
setVaultNameAndArchiveId(vaultName, archiveId);
// setup the SQS and SNS
setupJob();
JobParameters jobParameters = new JobParameters().withType("archive-retrieval")
.withArchiveId(archiveId).withSNSTopic(snsSetupResult.topicArn);
return executeInitiateJob(jobParameters);
}
/**
* Job.<br>
* SQSJob.<br>
* Job.
*
* @return JobCheckJobResult
* @throws JsonParseException
* @throws IOException
*/
public CheckJobResult checkJobToComplete() throws JsonParseException, IOException {
// Job
if (!alreadyInitiate) {
throw new IllegalStateException("Job has not yet started");
}
return LowLevelArchiveController.checkJobToComplete(this.jobId, sqsSetupResult.queueUrl,
sqsClient);
}
/**
* Job.
*
* @return
* @throws JsonParseException
* @throws IOException
* @throws InterruptedException
*/
public boolean waitForJobToComplete() throws JsonParseException, IOException,
InterruptedException {
CheckJobResult result = null;
do {
System.out.println("loop");
Thread.sleep(1000 * 60 * 30);
result = checkJobToComplete();
System.out.println(result.toString());
} while (!result.isMessageFound());
System.out.println("exit loop");
return result.isJobSuccessful();
}
public void printJobOutput() throws JsonParseException, IOException {
GetJobOutputRequest getJobOutputRequest = new GetJobOutputRequest()
.withVaultName(vaultName).withJobId(jobId);
GetJobOutputResult getJobOutputResult = client.getJobOutput(getJobOutputRequest);
BufferedReader br = new BufferedReader(new InputStreamReader(getJobOutputResult.getBody()));
try {
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
throw new AmazonClientException("Unable to save archive", e);
} finally {
try {
br.close();
} catch (IOException ignore) {
}
}
}
public InventoryRetrievalResult getInveInventoryJobOutput() throws JsonParseException,
IOException, ParseException {
GetJobOutputRequest getJobOutputRequest = new GetJobOutputRequest()
.withAccountId(vaultName).withJobId(jobId);
GetJobOutputResult result = client.getJobOutput(getJobOutputRequest);
return new InventoryRetrievalResult(result.getBody());
}
public void downloadJobOutput(File saveFile) {
LowLevelArchiveController.downloadJobOutput(this.jobId, this.vaultName, saveFile,
this.client);
}
public void cleanUp() {
snsClient.unsubscribe(new UnsubscribeRequest(snsSetupResult.subscriptionArn));
snsClient.deleteTopic(new DeleteTopicRequest(snsSetupResult.topicArn));
sqsClient.deleteQueue(new DeleteQueueRequest(sqsSetupResult.queueUrl));
}
/**
* SQS.
*
* @param queueName
* @return SetupSqsResult
*/
private SqsSetupResult setupSQS(String queueName) {
CreateQueueRequest request = new CreateQueueRequest().withQueueName(queueName);
CreateQueueResult result = sqsClient.createQueue(request);
String sqsQueueUrl = result.getQueueUrl();
GetQueueAttributesRequest qRequest = new GetQueueAttributesRequest().withQueueUrl(
sqsQueueUrl).withAttributeNames("QueueArn");
GetQueueAttributesResult qResult = sqsClient.getQueueAttributes(qRequest);
String sqsQueueArn = qResult.getAttributes().get("QueueArn");
Policy sqsPolicy = new Policy().withStatements(new Statement(Effect.Allow)
.withPrincipals(Principal.AllUsers).withActions(SQSActions.SendMessage)
.withResources(new Resource(sqsQueueArn)));
Map<String, String> queueAttributes = new HashMap<String, String>();
queueAttributes.put("Policy", sqsPolicy.toJson());
sqsClient.setQueueAttributes(new SetQueueAttributesRequest(sqsQueueUrl, queueAttributes));
return new SqsSetupResult(sqsQueueUrl, sqsQueueArn);
}
/**
* @param snsTopicName
* @param sqsQueueArn
* @return SetupSnsResult
*/
private SnsSetupResult setupSNS(String snsTopicName, String sqsQueueArn) {
CreateTopicRequest request = new CreateTopicRequest().withName(snsTopicName);
CreateTopicResult result = snsClient.createTopic(request);
String snsTopicArn = result.getTopicArn();
SubscribeRequest subscribeRequest = new SubscribeRequest().withTopicArn(snsTopicArn)
.withEndpoint(sqsQueueArn).withProtocol("sqs");
SubscribeResult subscribeResult = snsClient.subscribe(subscribeRequest);
return new SnsSetupResult(snsTopicArn, subscribeResult.getSubscriptionArn());
}
/**
* Amazon Glacier
*
* @param jobParameters
* @return jobId
*/
private String executeInitiateJob(JobParameters jobParameters) {
InitiateJobRequest request = new InitiateJobRequest().withVaultName(vaultName)
.withJobParameters(jobParameters);
InitiateJobResult result = client.initiateJob(request);
this.jobId = result.getJobId();
return jobId;
}
/**
* SQSSNS.
*/
private void setupJob() {
if (alreadyInitiate) {
throw new IllegalStateException("initiate job request is already node.");
}
alreadyInitiate = true;
String sqsQueueName = "initiate-job_sqs";
sqsSetupResult = setupSQS(sqsQueueName);
String snsTopicName = "initiate-job_sns";
snsSetupResult = setupSNS(snsTopicName, sqsSetupResult.queueArn);
}
} |
package org.embulk.input;
import com.google.common.base.Optional;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import org.apache.http.Header;
import org.apache.http.NameValuePair;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.embulk.config.*;
import org.embulk.spi.BufferAllocator;
import org.embulk.spi.Exec;
import org.embulk.spi.FileInputPlugin;
import org.embulk.spi.TransactionalFileInput;
import org.embulk.spi.util.InputStreamFileInput;
import org.embulk.spi.util.RetryExecutor;
import org.slf4j.Logger;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
public class HttpInputPlugin implements FileInputPlugin {
private final Logger logger = Exec.getLogger(getClass());
public interface PluginTask extends Task {
@Config("url")
public String getUrl();
@Config("charset")
@ConfigDefault("\"utf-8\"")
public String getCharset();
@Config("method")
@ConfigDefault("\"get\"")
public String getMethod();
@Config("user_agent")
@ConfigDefault("\"Embulk::Input::HttpInputPlugin\"")
public String getUserAgent();
@Config("open_timeout")
@ConfigDefault("2000")
public int getOpenTimeout();
@Config("read_timeout")
@ConfigDefault("10000")
public int getReadTimeout();
@Config("max_retries")
@ConfigDefault("5")
public int getMaxRetries();
@Config("retry_interval")
@ConfigDefault("10000")
public int getRetryInterval();
@Config("sleep_before_request")
@ConfigDefault("0")
public int getSleepBeforeRequest();
public void setSleepBeforeRequest(int sleepBeforeRequest);
@Config("params")
@ConfigDefault("null")
public Optional<ParamsConfig> getParams();
@Config("basic_auth")
@ConfigDefault("null")
public Optional<BasicAuthConfig> getBasicAuth();
@ConfigInject
public BufferAllocator getBufferAllocator();
public List<List<QueryConfig.Query>> getQueries();
public void setQueries(List<List<QueryConfig.Query>> queries);
public HttpMethod getHttpMethod();
public void setHttpMethod(HttpMethod httpMethod);
}
public enum HttpMethod {
POST,
GET
}
@Override
public ConfigDiff transaction(ConfigSource config, FileInputPlugin.Control control) {
PluginTask task = config.loadConfig(PluginTask.class);
int numOfThreads = 1;
if (task.getParams().isPresent()) {
List<List<QueryConfig.Query>> expandedQueries = task.getParams().get().expandQueries();
task.setQueries(expandedQueries);
numOfThreads = expandedQueries.size();
} else {
task.setQueries(Lists.<List<QueryConfig.Query>>newArrayList());
}
if (numOfThreads == 1) {
task.setSleepBeforeRequest(0);
}
switch (task.getMethod().toUpperCase()) {
case "GET":
task.setHttpMethod(HttpMethod.GET);
break;
case "POST":
task.setHttpMethod(HttpMethod.POST);
break;
default:
throw new ConfigException(String.format("Unsupported http method %s", task.getMethod()));
}
return resume(task.dump(), numOfThreads, control);
}
@Override
public ConfigDiff resume(TaskSource taskSource,
int taskCount,
FileInputPlugin.Control control) {
control.run(taskSource, taskCount);
return Exec.newConfigDiff();
}
@Override
public void cleanup(TaskSource taskSource,
int taskCount,
List<CommitReport> successCommitReports) {
}
@Override
public TransactionalFileInput open(TaskSource taskSource, int taskIndex) {
PluginTask task = taskSource.loadTask(PluginTask.class);
HttpRequestBase request;
try {
request = makeRequest(task, taskIndex);
} catch (URISyntaxException | UnsupportedEncodingException e) {
throw Throwables.propagate(e);
}
HttpClientBuilder builder = HttpClientBuilder.create()
.disableAutomaticRetries()
.setDefaultRequestConfig(makeRequestConfig(task))
.setDefaultHeaders(makeHeaders(task));
if (task.getBasicAuth().isPresent()) {
builder.setDefaultCredentialsProvider(makeCredentialsProvider(task.getBasicAuth().get(),
request));
}
HttpClient client = builder.build();
logger.info(String.format("%s \"%s\"", task.getMethod().toUpperCase(),
request.getURI().toString()));
RetryableHandler retryable = new RetryableHandler(client, request);
try {
if (task.getSleepBeforeRequest() > 0) {
logger.info(String.format("wait %d msec before request", task.getSleepBeforeRequest()));
Thread.sleep(task.getSleepBeforeRequest());
}
RetryExecutor.retryExecutor().
withRetryLimit(task.getMaxRetries()).
withInitialRetryWait(task.getRetryInterval()).
withMaxRetryWait(30 * 60 * 1000).
runInterruptible(retryable);
InputStream stream = retryable.getResponse().getEntity().getContent();
PluginFileInput input = new PluginFileInput(task, stream);
stream = null;
return input;
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
private CredentialsProvider makeCredentialsProvider(BasicAuthConfig config, HttpRequestBase scopeRequest) {
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
final AuthScope authScope = new AuthScope(scopeRequest.getURI().getHost(),
scopeRequest.getURI().getPort());
credentialsProvider.setCredentials(authScope,
new UsernamePasswordCredentials(config.getUser(), config.getPassword()));
return credentialsProvider;
}
private HttpRequestBase makeRequest(PluginTask task, int taskIndex)
throws URISyntaxException, UnsupportedEncodingException {
final List<QueryConfig.Query> queries = (task.getQueries().isEmpty()) ?
null : task.getQueries().get(taskIndex);
if (task.getHttpMethod() == HttpMethod.GET) {
HttpGet request = new HttpGet(task.getUrl());
if (queries != null) {
URIBuilder builder = new URIBuilder(request.getURI());
for (QueryConfig.Query q : queries) {
for (String v : q.getValues()) {
builder.addParameter(q.getName(), v);
}
}
request.setURI(builder.build());
}
return request;
} else if (task.getHttpMethod() == HttpMethod.POST) {
HttpPost request = new HttpPost(task.getUrl());
if (queries != null) {
List<NameValuePair> pairs = new ArrayList<>();
for (QueryConfig.Query q : queries) {
for (String v : q.getValues()) {
pairs.add(new BasicNameValuePair(q.getName(), v));
}
}
request.setEntity(new UrlEncodedFormEntity(pairs));
}
return request;
}
throw new IllegalArgumentException(String.format("Unsupported http method %s", task.getMethod()));
}
private List<Header> makeHeaders(PluginTask task) {
List<Header> headers = new ArrayList<>();
headers.add(new BasicHeader("Accept", "*/*"));
headers.add(new BasicHeader("Accept-Charset", task.getCharset()));
headers.add(new BasicHeader("Accept-Encoding", "gzip, deflate"));
headers.add(new BasicHeader("Accept-Language", "en-us,en;q=0.5"));
headers.add(new BasicHeader("User-Agent", task.getUserAgent()));
return headers;
}
private RequestConfig makeRequestConfig(PluginTask task) {
return RequestConfig.custom()
.setCircularRedirectsAllowed(true)
.setMaxRedirects(10)
.setRedirectsEnabled(true)
.setConnectTimeout(task.getOpenTimeout())
.setSocketTimeout(task.getReadTimeout())
.build();
}
public static class PluginFileInput extends InputStreamFileInput
implements TransactionalFileInput {
private static class SingleFileProvider
implements InputStreamFileInput.Provider {
private InputStream stream;
private boolean opened = false;
public SingleFileProvider(InputStream stream) {
this.stream = stream;
}
@Override
public InputStream openNext() throws IOException {
if (opened) {
return null;
}
opened = true;
return stream;
}
@Override
public void close() throws IOException {
if (!opened) {
stream.close();
}
}
}
public PluginFileInput(PluginTask task, InputStream stream) {
super(task.getBufferAllocator(), new SingleFileProvider(stream));
}
public void abort() {
}
public CommitReport commit() {
return Exec.newCommitReport();
}
@Override
public void close() {
}
}
} |
package org.gbif.ws.client;
import org.gbif.ws.json.JacksonJsonObjectMapperProvider;
import org.gbif.ws.security.Md5EncodeService;
import org.gbif.ws.security.Md5EncodeServiceImpl;
import org.gbif.ws.security.SecretKeySigningService;
import org.gbif.ws.security.SigningService;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Objects;
import com.fasterxml.jackson.databind.ObjectMapper;
import feign.Contract;
import feign.Feign;
import feign.InvocationHandlerFactory;
import feign.RequestInterceptor;
import feign.codec.Decoder;
import feign.codec.Encoder;
import feign.codec.ErrorDecoder;
import feign.httpclient.ApacheHttpClient;
import io.github.resilience4j.core.IntervalFunction;
import io.github.resilience4j.feign.FeignDecorators;
import io.github.resilience4j.feign.Resilience4jFeign;
import io.github.resilience4j.retry.Retry;
import io.github.resilience4j.retry.RetryConfig;
import io.github.resilience4j.retry.RetryRegistry;
import lombok.Builder;
import lombok.Data;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.ConnectionConfig;
import org.apache.http.config.SocketConfig;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* ClientBuilder used to create Feign Clients.
* This builders support retry using exponential backoff and multithreaded http client.
*/
public class ClientBuilder {
private static final String HTTP_PROTOCOL = "http";
private static final String HTTPS_PROTOCOL = "https";
private static final RetryRegistry RETRY_REGISTRY = RetryRegistry.ofDefaults();
private static final Logger LOG = LoggerFactory.getLogger(ClientBuilder.class);
private String url;
private RequestInterceptor requestInterceptor;
private Decoder decoder;
private Encoder encoder;
private ConnectionPoolConfig connectionPoolConfig;
private RetryConfig retryConfig;
private ObjectMapper objectMapper;
private final ErrorDecoder errorDecoder = new ClientErrorDecoder();
private final Contract contract = new ClientContract();
private final InvocationHandlerFactory invocationHandlerFactory = new ClientInvocationHandlerFactory();
/**
* Creates a builder instance, by default uses the GBIF Jackson ObjectMapper.
*/
public ClientBuilder() {
withObjectMapper(JacksonJsonObjectMapperProvider.getObjectMapper());
}
/**
* Exponential backoff retry configuration.
*/
public ClientBuilder withExponentialBackoffRetry(Duration initialInterval, double multiplier, int maxAttempts) {
retryConfig = RetryConfig.custom()
.maxAttempts(maxAttempts)
.intervalFunction(IntervalFunction.ofExponentialBackoff(initialInterval, multiplier))
.build();
return this;
}
/**
* Target base url.
*/
public ClientBuilder withUrl(String url) {
this.url = url;
return this;
}
/**
* Simple base credentials.
*/
public ClientBuilder withCredentials(String username, String password) {
this.requestInterceptor = new SimpleUserAuthRequestInterceptor(username, password);
return this;
}
/**
* Custom AppKey credentials.
*/
public ClientBuilder withAppKeyCredentials(String username, String appKey, String secretKey) {
this.requestInterceptor =
new GbifAuthRequestInterceptor(username, appKey, secretKey, new SecretKeySigningService(),
new Md5EncodeServiceImpl(objectMapper));
return this;
}
/**
* Connection pool configuration to create a multithreaded client.
*/
public ClientBuilder withConnectionPoolConfig(ConnectionPoolConfig connectionPoolConfig) {
this.connectionPoolConfig = connectionPoolConfig;
return this;
}
/**
* Jakcson ObjectMapper used to serialize JSON data.
*/
public ClientBuilder withObjectMapper(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
this.encoder = new ClientEncoder(objectMapper);
this.decoder = new ClientDecoder(objectMapper);
return this;
}
/**
* Custom GBIF authentication.
*/
public ClientBuilder withCustomGbifAuth(String username,
String appKey,
String secretKey,
SigningService signingService,
Md5EncodeService md5EncodeService) {
this.requestInterceptor =
new GbifAuthRequestInterceptor(username, appKey, secretKey, signingService, md5EncodeService);
return this;
}
/**
* Creates a new client instance.
*/
public <T> T build(Class<T> clazz) {
Feign.Builder builder = Feign.builder();
if (Objects.nonNull(retryConfig)) {
Retry retry = RETRY_REGISTRY.retry(clazz.getName(), retryConfig);
//logging
retry.getEventPublisher().onError(event -> LOG.error(event.toString()));
FeignDecorators decorators = FeignDecorators
.builder()
.withRetry(retry)
.build();
builder = Resilience4jFeign.builder(decorators);
} else {
//Feign builder do not support invocation handler
builder.invocationHandlerFactory(invocationHandlerFactory);
}
builder
.encoder(encoder)
.decoder(decoder)
.errorDecoder(errorDecoder)
.contract(contract)
.decode404();
if (requestInterceptor != null) {
builder.requestInterceptor(requestInterceptor);
}
if (connectionPoolConfig != null) {
builder.client(new ApacheHttpClient(newMultithreadedClient(connectionPoolConfig)));
}
return builder.target(clazz, url);
}
/**
* Creates a Http multithreaded client.
*/
private static HttpClient newMultithreadedClient(ConnectionPoolConfig connectionPoolConfig) {
return HttpClients.custom()
.setMaxConnTotal(connectionPoolConfig.getMaxConnections())
.setMaxConnPerRoute(connectionPoolConfig.getMaxPerRoute())
.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(connectionPoolConfig.getTimeout()).build())
.setDefaultConnectionConfig(ConnectionConfig.custom().setCharset(Charset.forName(StandardCharsets.UTF_8.name())).build())
.setDefaultRequestConfig(RequestConfig.custom().setConnectTimeout(connectionPoolConfig.getTimeout())
.setConnectionRequestTimeout(connectionPoolConfig.getTimeout()).build())
.build();
}
@Data
@Builder
public static class ConnectionPoolConfig {
private final Integer timeout;
private final Integer maxConnections;
private final Integer maxPerRoute;
}
} |
package org.hcjf.io.net.http;
import org.hcjf.log.Log;
import org.hcjf.properties.SystemProperties;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;
/**
* This particular kind of package contains the request information.
* @author javaito
*/
public class HttpRequest extends HttpPackage {
private static final int METHOD_INDEX = 0;
private static final int REQUEST_PATH_INDEX = 1;
private static final int VERSION_INDEX = 2;
private String path;
private String context;
private HttpMethod method;
private final Map<String, String> parameters;
private final List<String> pathParts;
public HttpRequest(String requestPath, HttpMethod method) {
this.path = requestPath;
this.method = method;
this.parameters = new HashMap<>();
this.pathParts = new ArrayList<>();
}
protected HttpRequest(HttpRequest httpRequest) {
super(httpRequest);
this.path = httpRequest.path;
this.method = httpRequest.method;
this.parameters = httpRequest.parameters;
this.pathParts = httpRequest.pathParts;
}
public HttpRequest() {
this(null, null);
}
/**
* Return the request path
* @return Request path.
*/
public String getPath() {
return path;
}
/**
* Set the request path.
* @param path Request path.
*/
public void setPath(String path) {
this.path = path;
}
/**
* Return the request context.
* @return Request context.
*/
public String getContext() {
return context;
}
/**
* Set the request context.
* @param context Request context.
*/
public void setContext(String context) {
this.context = context;
this.path = context;
}
/**
* Return the request method.
* @return Request method.
*/
public HttpMethod getMethod() {
return method;
}
/**
* Set the request method.
* @param method Request method.
*/
public void setMethod(HttpMethod method) {
this.method = method;
}
/**
* Return the request parameters.
* @return Request parameters.
*/
public Map<String, String> getParameters() {
return Collections.unmodifiableMap(parameters);
}
/**
* Return the parameter indexed by the argument name.
* @param parameterName Name of the founding parameter.
* @return Return the parameter.
*/
public String getParameter(String parameterName) {
return parameters.get(parameterName);
}
/**
* Add parameter.
* @param parameterName Parameter name.
* @param parameterValue Parameter value.
*/
public void addHttpParameter(String parameterName, String parameterValue) {
parameters.put(parameterName, parameterValue);
}
/**
* Return a list with all the parts of the request path.
* If the path is /path1/path2/pathN, then the method response with
* a list ad [path1,path2,pathN]
* @return List with all the parts of the request path.
*/
public List<String> getPathParts() {
return pathParts;
}
/**
* This method process the body of the complete request.
* @param body Body of the request.
*/
@Override
protected void processBody(byte[] body) {
HttpHeader contentType = getHeader(HttpHeader.CONTENT_TYPE);
if(contentType != null &&
contentType.getHeaderValue().startsWith(HttpHeader.APPLICATION_X_WWW_FORM_URLENCODED)) {
parseHttpParameters(new String(body));
}
}
/**
* Process the first line of the request.
* @param firstLine First line of the request.
*/
@Override
protected void processFirstLine(String firstLine) {
String[] parts = firstLine.split(LINE_FIELD_SEPARATOR);
method = HttpMethod.valueOf(parts[METHOD_INDEX]);
path = parts[REQUEST_PATH_INDEX];
setHttpVersion(parts[VERSION_INDEX]);
//Check if there are parameters into request
if(path.indexOf(HTTP_FIELD_START) >= 0) {
context = path.substring(0, path.indexOf(HTTP_FIELD_START));
parseHttpParameters(path.substring(path.indexOf(HTTP_FIELD_START) + 1));
} else {
context = path;
}
for(String pathPart : context.split(HTTP_CONTEXT_SEPARATOR)) {
if(!pathPart.isEmpty()) {
pathParts.add(pathPart);
}
}
}
/**
*
* @param parametersBody
*/
private void parseHttpParameters(String parametersBody) {
String[] params = parametersBody.split(HTTP_FIELD_SEPARATOR);
String charset = null;
HttpHeader contentType = getHeader(HttpHeader.CONTENT_TYPE);
if(contentType != null) {
//The content-type header should not have more than one group
//In this case we use the first group.
charset = contentType.getParameter(
contentType.getGroups().iterator().next(), HttpHeader.PARAM_CHARSET);
}
if(charset == null) {
charset = SystemProperties.getDefaultCharset();
}
String key;
String value;
for(String param : params) {
if(param.indexOf(HTTP_FIELD_ASSIGNATION) < 0) {
key = param;
value = null;
} else {
String[] keyValue = param.split(HTTP_FIELD_ASSIGNATION);
key = keyValue[0];
value = keyValue.length==2 ? keyValue[1] : null;
}
try {
parameters.put(URLDecoder.decode(key, charset), value == null ? null : URLDecoder.decode(value, charset));
} catch (UnsupportedEncodingException e) {
Log.w(HttpServer.HTTP_SERVER_LOG_TAG, "Unable to decode http parameter, %s:%s", key, value);
parameters.put(key, value);
}
}
}
/**
* Return the string that represent the protocol of the package.
* @return Protocol description.
*/
private String toStringProtocolHeader() {
StringBuilder builder = new StringBuilder();
builder.append(getMethod().toString()).append(LINE_FIELD_SEPARATOR).
append(getPath()).append(LINE_FIELD_SEPARATOR).
append(getHttpVersion()).append(STRING_LINE_SEPARATOR);
for(HttpHeader header : getHeaders()) {
builder.append(header).append(STRING_LINE_SEPARATOR);
}
builder.append(STRING_LINE_SEPARATOR);
return builder.toString();
}
/**
* Return the bytes that represent the string of the protocol name.
* @return Protocol name bytes.
*/
@Override
public final byte[] getProtocolHeader() {
return toStringProtocolHeader().getBytes();
}
/**
* Creates the string representation of the package.
* @return String representation of the package.
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(toStringProtocolHeader());
if(getBody() != null) {
int maxLength = SystemProperties.getInteger(SystemProperties.Net.Http.INPUT_LOG_BODY_MAX_LENGTH);
if(maxLength > 0) {
if (getBody().length > maxLength) {
builder.append(new String(getBody(), 0, maxLength));
builder.append(" ... [").append(getBody().length - maxLength).append(" more]");
} else {
builder.append(new String(getBody()));
}
}
}
return builder.toString();
}
} |
package org.junit.matchers;
import org.hamcrest.Matcher;
import org.junit.internal.matchers.CombinableMatcher;
import org.junit.internal.matchers.Each;
import org.junit.internal.matchers.IsCollectionContaining;
import org.junit.internal.matchers.StringContains;
/**
* Convenience import class: these are useful matchers for use with the assertThat method, but they are
* not currently included in the basic CoreMatchers class from hamcrest.
*/
public class JUnitMatchers {
/**
* @param element
* @return A matcher matching any collection containing element
*/
public static <T> org.hamcrest.Matcher<java.lang.Iterable<T>> hasItem(T element) {
return IsCollectionContaining.hasItem(element);
}
/**
* @param elementMatcher
* @return A matcher matching any collection containing an element matching elementMatcher
*/
public static <T> org.hamcrest.Matcher<java.lang.Iterable<T>> hasItem(org.hamcrest.Matcher<? extends T> elementMatcher) {
return IsCollectionContaining.hasItem(elementMatcher);
}
/**
* @param element
* @return A matcher matching any collection containing every element in elements
*/
public static <T> org.hamcrest.Matcher<java.lang.Iterable<T>> hasItems(T... elements) {
return IsCollectionContaining.hasItems(elements);
}
/**
* @param elementMatchers
* @return A matcher matching any collection containing at least one element that matches
* each matcher in elementMatcher (this may be one element matching all matchers,
* or different elements matching each matcher)
*/
public static <T> org.hamcrest.Matcher<java.lang.Iterable<T>> hasItems(org.hamcrest.Matcher<? extends T>... elementMatchers) {
return IsCollectionContaining.hasItems(elementMatchers);
}
/**
* @param elementMatcher
* @return A matcher matching any collection in which every element matches elementMatcher
*/
public static <T> Matcher<Iterable<T>> everyItem(final Matcher<T> elementMatcher) {
return Each.each(elementMatcher);
}
/**
* @param substring
* @return a matcher matching any string that contains substring
*/
public static org.hamcrest.Matcher<java.lang.String> containsString(java.lang.String substring) {
return StringContains.containsString(substring);
}
/**
* This is useful for fluently combining matchers that must both pass. For example:
* <pre>
* assertThat(string, both(containsString("a")).and(containsString("b")));
* </pre>
*/
public static <T> CombinableMatcher<T> both(Matcher<T> matcher) {
return new CombinableMatcher<T>(matcher);
}
/**
* This is useful for fluently combining matchers where either may pass, for example:
* <pre>
* assertThat(string, both(containsString("a")).and(containsString("b")));
* </pre>
*/
public static <T> CombinableMatcher<T> either(Matcher<T> matcher) {
return new CombinableMatcher<T>(matcher);
}
} |
package VASSAL.build.module;
import static java.lang.Math.round;
import java.awt.AWTEventMulticaster;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Component;
import java.awt.Composite;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Window;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragSource;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.awt.event.HierarchyEvent;
import java.awt.event.HierarchyListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.AffineTransform;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;
import javax.swing.OverlayLayout;
import javax.swing.RootPaneContainer;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import net.miginfocom.swing.MigLayout;
import org.apache.commons.lang3.SystemUtils;
import org.jdesktop.animation.timing.Animator;
import org.jdesktop.animation.timing.TimingTargetAdapter;
import org.w3c.dom.Element;
import VASSAL.build.AbstractBuildable;
import VASSAL.build.AbstractConfigurable;
import VASSAL.build.AbstractToolbarItem;
import VASSAL.build.AutoConfigurable;
import VASSAL.build.Buildable;
import VASSAL.build.Configurable;
import VASSAL.build.GameModule;
import VASSAL.build.IllegalBuildException;
import VASSAL.build.module.documentation.HelpFile;
import VASSAL.build.module.map.BoardPicker;
import VASSAL.build.module.map.CounterDetailViewer;
import VASSAL.build.module.map.DefaultPieceCollection;
import VASSAL.build.module.map.DrawPile;
import VASSAL.build.module.map.Drawable;
import VASSAL.build.module.map.Flare;
import VASSAL.build.module.map.ForwardToChatter;
import VASSAL.build.module.map.ForwardToKeyBuffer;
import VASSAL.build.module.map.GlobalMap;
import VASSAL.build.module.map.HidePiecesButton;
import VASSAL.build.module.map.HighlightLastMoved;
import VASSAL.build.module.map.ImageSaver;
import VASSAL.build.module.map.KeyBufferer;
import VASSAL.build.module.map.LOS_Thread;
import VASSAL.build.module.map.LayeredPieceCollection;
import VASSAL.build.module.map.MapCenterer;
import VASSAL.build.module.map.MapShader;
import VASSAL.build.module.map.MassKeyCommand;
import VASSAL.build.module.map.MenuDisplayer;
import VASSAL.build.module.map.PieceCollection;
import VASSAL.build.module.map.PieceMover;
import VASSAL.build.module.map.PieceRecenterer;
import VASSAL.build.module.map.Scroller;
import VASSAL.build.module.map.SelectionHighlighters;
import VASSAL.build.module.map.SetupStack;
import VASSAL.build.module.map.StackExpander;
import VASSAL.build.module.map.StackMetrics;
import VASSAL.build.module.map.TextSaver;
import VASSAL.build.module.map.Zoomer;
import VASSAL.build.module.map.boardPicker.Board;
import VASSAL.build.module.map.boardPicker.board.MapGrid;
import VASSAL.build.module.map.boardPicker.board.Region;
import VASSAL.build.module.map.boardPicker.board.RegionGrid;
import VASSAL.build.module.map.boardPicker.board.ZonedGrid;
import VASSAL.build.module.map.boardPicker.board.HexGrid;
import VASSAL.build.module.map.boardPicker.board.SquareGrid;
import VASSAL.build.module.map.boardPicker.board.mapgrid.Zone;
import VASSAL.build.module.properties.ChangePropertyCommandEncoder;
import VASSAL.build.module.properties.GlobalProperties;
import VASSAL.build.module.properties.MutablePropertiesContainer;
import VASSAL.build.module.properties.MutableProperty;
import VASSAL.build.module.properties.PropertySource;
import VASSAL.build.widget.MapWidget;
import VASSAL.command.AddPiece;
import VASSAL.command.Command;
import VASSAL.command.MoveTracker;
import VASSAL.configure.AutoConfigurer;
import VASSAL.configure.BooleanConfigurer;
import VASSAL.configure.ColorConfigurer;
import VASSAL.configure.CompoundValidityChecker;
import VASSAL.configure.Configurer;
import VASSAL.configure.ConfigurerFactory;
import VASSAL.configure.ConfigureTree;
import VASSAL.configure.IconConfigurer;
import VASSAL.configure.IntConfigurer;
import VASSAL.configure.MandatoryComponent;
import VASSAL.configure.NamedHotKeyConfigurer;
import VASSAL.configure.PlayerIdFormattedStringConfigurer;
import VASSAL.configure.VisibilityCondition;
import VASSAL.counters.ColoredBorder;
import VASSAL.counters.Deck;
import VASSAL.counters.DeckVisitor;
import VASSAL.counters.DeckVisitorDispatcher;
import VASSAL.counters.DragBuffer;
import VASSAL.counters.GamePiece;
import VASSAL.counters.GlobalCommand;
import VASSAL.counters.Highlighter;
import VASSAL.counters.KeyBuffer;
import VASSAL.counters.PieceFinder;
import VASSAL.counters.PieceVisitorDispatcher;
import VASSAL.counters.Properties;
import VASSAL.counters.ReportState;
import VASSAL.counters.Stack;
import VASSAL.i18n.Resources;
import VASSAL.i18n.TranslatableConfigurerFactory;
import VASSAL.preferences.PositionOption;
import VASSAL.preferences.Prefs;
import VASSAL.search.HTMLImageFinder;
import VASSAL.tools.AdjustableSpeedScrollPane;
import VASSAL.tools.ComponentSplitter;
import VASSAL.tools.KeyStrokeSource;
import VASSAL.tools.LaunchButton;
import VASSAL.tools.NamedKeyStroke;
import VASSAL.tools.ProblemDialog;
import VASSAL.tools.ToolBarComponent;
import VASSAL.tools.UniqueIdManager;
import VASSAL.tools.WrapLayout;
import VASSAL.tools.menu.MenuManager;
import VASSAL.tools.swing.SplitPane;
import VASSAL.tools.swing.SwingUtils;
import static VASSAL.preferences.Prefs.MAIN_WINDOW_HEIGHT;
import static VASSAL.preferences.Prefs.MAIN_WINDOW_REMEMBER;
/**
* The Map is the main component for displaying and containing {@link GamePiece}s during play. Pieces are displayed on
* the map's {@link Board}(s) and moved by clicking and dragging. Keyboard events are forwarded to selected pieces. Multiple
* map windows are supported in a single game, with dragging between windows allowed.
*
* To a map's {@link Board} subcomponent(s), various forms of grid can be added: ({@link ZonedGrid} (aka Multi-zone Grid),
* {@link HexGrid}, {@link SquareGrid} (aka Rectangular Grid), and {@link RegionGrid} (aka Irregular Grid). These can be used
* to determine where pieces are allowed to move, and also for filling properties (e.g. LocationName, CurrentZone, CurrentBoard,
* CurrentMap) to allow the module to keep track of pieces and react to their movements.
*
* A Map may contain many different {@link Buildable} subcomponents. Components which are addable <i>uniquely</i> to a Map are
* contained in the <code>VASSAL.build.module.map</code> package. Some of the most common Map subcomponents include
* {@link Zoomer} for Zoom Capability, {@link CounterDetailViewer} aka Mouse-over Stack Viewer, {@link HidePiecesButton},
* and {@link SelectionHighlighters}.
*
* Map also contain several critical subcomponents which are automatically added and are not configurable at the module level.
* These include {@link PieceMover} which handles dragging and dropping of pieces, {@link KeyBufferer} which tracks which pieces
* are currently "selected" and forwards key commands to them, {@link MenuDisplayer} which listens for "right clicks" and provides
* "context menu" services, and {@link StackMetrics} which handles the "stacking" of game pieces.
*/
public class Map extends AbstractToolbarItem implements GameComponent, MouseListener, MouseMotionListener, DropTargetListener, Configurable,
UniqueIdManager.Identifyable, ToolBarComponent, MutablePropertiesContainer, PropertySource, PlayerRoster.SideChangeListener {
protected static boolean changeReportingEnabled = true;
protected String mapID = ""; //$NON-NLS-1$
protected String mapName = ""; //$NON-NLS-1$
protected static final UniqueIdManager idMgr = new UniqueIdManager("Map"); //$NON-NLS-1$
protected JPanel theMap; // Our main visual interface component
protected ArrayList<Drawable> drawComponents = new ArrayList<>(); //NOPMD
protected JLayeredPane layeredPane = new JLayeredPane();
protected JScrollPane scroll;
@Deprecated(since = "2020-11-05", forRemoval = true)
protected ComponentSplitter.SplitPane mainWindowDock;
protected SplitPane splitPane;
protected BoardPicker picker;
protected JToolBar toolBar = new JToolBar();
protected Zoomer zoom;
protected StackMetrics metrics;
protected Dimension edgeBuffer = new Dimension(0, 0);
protected Color bgColor = Color.white;
protected LaunchButton launchButton; // Legacy for binary signature
protected boolean useLaunchButton = false;
protected boolean useLaunchButtonEdit = false;
protected String markMovedOption = GlobalOptions.ALWAYS;
protected String markUnmovedIcon = "/images/unmoved.gif"; //$NON-NLS-1$
protected String markUnmovedText = ""; //$NON-NLS-1$
protected String markUnmovedTooltip = Resources.getString("Map.mark_unmoved"); //$NON-NLS-1$
protected MouseListener multicaster = null;
protected ArrayList<MouseListener> mouseListenerStack = new ArrayList<>(); //NOPMD
protected List<Board> boards = new CopyOnWriteArrayList<>();
protected int[][] boardWidths; // Cache of board widths by row/column
protected int[][] boardHeights; // Cache of board heights by row/column
protected PieceCollection pieces = new DefaultPieceCollection(); // All the pieces on the map, but sorted into visual layers. Will be replaced by a LayeredPieceCollection if Map has a "Game Piece Layers" Component.
protected Highlighter highlighter = new ColoredBorder();
protected ArrayList<Highlighter> highlighters = new ArrayList<>(); //NOPMD
protected boolean clearFirst = false; // Whether to clear the display before
// drawing the map
protected boolean hideCounters = false; // Option to hide counters to see
// map
protected float pieceOpacity = 1.0f;
protected boolean allowMultiple = false;
protected VisibilityCondition visibilityCondition;
protected DragGestureListener dragGestureListener;
protected String moveWithinFormat;
protected String moveToFormat;
protected String createFormat;
protected String changeFormat = "$" + MESSAGE + "$"; //$NON-NLS-1$ //$NON-NLS-2$
protected NamedKeyStroke moveKey;
protected String tooltip = ""; //$NON-NLS-1$
protected MutablePropertiesContainer propsContainer = new MutablePropertiesContainer.Impl();
protected PropertyChangeListener repaintOnPropertyChange = evt -> repaint();
protected PieceMover pieceMover;
protected KeyListener[] saveKeyListeners = null;
private IntConfigurer preferredScrollConfig;
public Map() {
getView();
theMap.addMouseListener(this);
if (shouldDockIntoMainWindow()) {
final String constraints =
(SystemUtils.IS_OS_MAC_OSX ? "ins 1 0 1 0" : "ins 0") + //NON-NLS
",gapx 0,hidemode 3"; //NON-NLS
toolBar.setLayout(new MigLayout(constraints));
}
else {
toolBar.setLayout(new WrapLayout(WrapLayout.LEFT, 0, 0));
}
toolBar.setAlignmentX(0.0F);
toolBar.setFloatable(false);
}
/**
* @return Map's main visual interface swing component (its JPanel)
*/
@Override
public Component getComponent() {
return theMap;
}
/**
* Global Change Reporting control - used by Global Key Commands (see {@link GlobalCommand}) to
* temporarily disable reporting while they run, if their "Suppress individual reports" option is selected.
* @param b true to turn global change reporting on, false to turn it off.
*/
public static void setChangeReportingEnabled(boolean b) {
changeReportingEnabled = b;
}
/**
* @return true if change reporting is currently enabled, false if it is presently being suppressed by a Global Key Command.
*/
public static boolean isChangeReportingEnabled() {
return changeReportingEnabled;
}
public static final String NAME = "mapName"; //$NON-NLS-1$
public static final String MARK_MOVED = "markMoved"; //$NON-NLS-1$
public static final String MARK_UNMOVED_ICON = "markUnmovedIcon"; //$NON-NLS-1$
public static final String MARK_UNMOVED_TEXT = "markUnmovedText"; //$NON-NLS-1$
public static final String MARK_UNMOVED_TOOLTIP = "markUnmovedTooltip"; //$NON-NLS-1$
public static final String EDGE_WIDTH = "edgeWidth"; //$NON-NLS-1$
public static final String EDGE_HEIGHT = "edgeHeight"; //$NON-NLS-1$
public static final String BACKGROUND_COLOR = "backgroundcolor"; //NON-NLS
public static final String HIGHLIGHT_COLOR = "color"; //$NON-NLS-1$
public static final String HIGHLIGHT_THICKNESS = "thickness"; //$NON-NLS-1$
public static final String ALLOW_MULTIPLE = "allowMultiple"; //$NON-NLS-1$
public static final String USE_LAUNCH_BUTTON = "launch"; //$NON-NLS-1$
public static final String BUTTON_NAME = "buttonName"; //$NON-NLS-1$
public static final String TOOLTIP = "tooltip"; //$NON-NLS-1$
public static final String ICON = "icon"; //$NON-NLS-1$
public static final String HOTKEY = "hotkey"; //$NON-NLS-1$
public static final String SUPPRESS_AUTO = "suppressAuto"; //$NON-NLS-1$
public static final String MOVE_WITHIN_FORMAT = "moveWithinFormat"; //$NON-NLS-1$
public static final String MOVE_TO_FORMAT = "moveToFormat"; //$NON-NLS-1$
public static final String CREATE_FORMAT = "createFormat"; //$NON-NLS-1$
public static final String CHANGE_FORMAT = "changeFormat"; //$NON-NLS-1$
public static final String MOVE_KEY = "moveKey"; //$NON-NLS-1$
public static final String MOVING_STACKS_PICKUP_UNITS = "movingStacksPickupUnits"; //$NON-NLS-1$
/**
* Sets a buildFile (XML) attribute value for this component.
* @param key the name of the attribute. Will be one of those listed in {@link #getAttributeNames}
* @param value If the <code>value</code> parameter is a String, it will be the value returned by {@link #getAttributeValueString} for the same
* <code>key</code>. Since Map extends {@link AbstractConfigurable}, then <code>value</code> can also be an instance of
* the corresponding Class listed in {@link #getAttributeTypes}.
*/
@Override
public void setAttribute(String key, Object value) {
if (NAME.equals(key)) {
setMapName((String) value);
}
else if (MARK_MOVED.equals(key)) {
markMovedOption = (String) value;
}
else if (MARK_UNMOVED_ICON.equals(key)) {
markUnmovedIcon = (String) value;
if (pieceMover != null) {
pieceMover.setAttribute(key, value);
}
}
else if (MARK_UNMOVED_TEXT.equals(key)) {
markUnmovedText = (String) value;
if (pieceMover != null) {
pieceMover.setAttribute(key, value);
}
}
else if (MARK_UNMOVED_TOOLTIP.equals(key)) {
markUnmovedTooltip = (String) value;
}
else if ("edge".equals(key)) { // Backward-compatible //$NON-NLS-1$
final String s = (String) value;
final int i = s.indexOf(','); //$NON-NLS-1$
if (i > 0) {
edgeBuffer = new Dimension(Integer.parseInt(s.substring(0, i)), Integer.parseInt(s.substring(i + 1)));
}
}
else if (EDGE_WIDTH.equals(key)) {
if (value instanceof String) {
value = Integer.valueOf((String) value);
}
try {
edgeBuffer = new Dimension((Integer) value, edgeBuffer.height);
}
catch (NumberFormatException ex) {
throw new IllegalBuildException(ex);
}
}
else if (EDGE_HEIGHT.equals(key)) {
if (value instanceof String) {
value = Integer.valueOf((String) value);
}
try {
edgeBuffer = new Dimension(edgeBuffer.width, (Integer) value);
}
catch (NumberFormatException ex) {
throw new IllegalBuildException(ex);
}
}
else if (BACKGROUND_COLOR.equals(key)) {
if (value instanceof String) {
value = ColorConfigurer.stringToColor((String)value);
}
bgColor = (Color)value;
}
else if (ALLOW_MULTIPLE.equals(key)) {
if (value instanceof String) {
value = Boolean.valueOf((String) value);
}
allowMultiple = (Boolean) value;
if (picker != null) {
picker.setAllowMultiple(allowMultiple);
}
}
else if (HIGHLIGHT_COLOR.equals(key)) {
if (value instanceof String) {
value = ColorConfigurer.stringToColor((String) value);
}
if (value != null) {
((ColoredBorder) highlighter).setColor((Color) value);
}
}
else if (HIGHLIGHT_THICKNESS.equals(key)) {
if (value instanceof String) {
value = Integer.valueOf((String) value);
}
if (highlighter instanceof ColoredBorder) {
((ColoredBorder) highlighter).setThickness((Integer) value);
}
}
else if (USE_LAUNCH_BUTTON.equals(key)) {
if (value instanceof String) {
value = Boolean.valueOf((String) value);
}
useLaunchButtonEdit = (Boolean) value;
getLaunchButton().setVisible(useLaunchButton);
}
else if (SUPPRESS_AUTO.equals(key)) {
if (value instanceof String) {
value = Boolean.valueOf((String) value);
}
if (Boolean.TRUE.equals(value)) {
moveWithinFormat = ""; //$NON-NLS-1$
}
}
else if (MOVE_WITHIN_FORMAT.equals(key)) {
moveWithinFormat = (String) value;
}
else if (MOVE_TO_FORMAT.equals(key)) {
moveToFormat = (String) value;
}
else if (CREATE_FORMAT.equals(key)) {
createFormat = (String) value;
}
else if (CHANGE_FORMAT.equals(key)) {
changeFormat = (String) value;
}
else if (MOVE_KEY.equals(key)) {
if (value instanceof String) {
value = NamedHotKeyConfigurer.decode((String) value);
}
moveKey = (NamedKeyStroke) value;
}
else if (TOOLTIP.equals(key)) {
tooltip = (String) value;
getLaunchButton().setAttribute(key, value);
}
else {
super.setAttribute(key, value);
}
}
/**
* @return a String representation of the XML buildFile attribute with the given name. When initializing a module,
* this String value will loaded from the XML and passed to {@link #setAttribute}. It is also frequently used for
* checking the current value of an attribute.
*
* @param key the name of the attribute. Will be one of those listed in {@link #getAttributeNames}
*/
@Override
public String getAttributeValueString(String key) {
if (NAME.equals(key)) {
return getMapName();
}
else if (MARK_MOVED.equals(key)) {
return markMovedOption;
}
else if (MARK_UNMOVED_ICON.equals(key)) {
return markUnmovedIcon;
}
else if (MARK_UNMOVED_TEXT.equals(key)) {
return markUnmovedText;
}
else if (MARK_UNMOVED_TOOLTIP.equals(key)) {
return markUnmovedTooltip;
}
else if (EDGE_WIDTH.equals(key)) {
return String.valueOf(edgeBuffer.width); //$NON-NLS-1$
}
else if (EDGE_HEIGHT.equals(key)) {
return String.valueOf(edgeBuffer.height); //$NON-NLS-1$
}
else if (BACKGROUND_COLOR.equals(key)) {
return ColorConfigurer.colorToString(bgColor);
}
else if (ALLOW_MULTIPLE.equals(key)) {
return String.valueOf(picker.isAllowMultiple()); //$NON-NLS-1$
}
else if (HIGHLIGHT_COLOR.equals(key)) {
if (highlighter instanceof ColoredBorder) {
return ColorConfigurer.colorToString(
((ColoredBorder) highlighter).getColor());
}
else {
return null;
}
}
else if (HIGHLIGHT_THICKNESS.equals(key)) {
if (highlighter instanceof ColoredBorder) {
return String.valueOf(
((ColoredBorder) highlighter).getThickness()); //$NON-NLS-1$
}
else {
return null;
}
}
else if (USE_LAUNCH_BUTTON.equals(key)) {
return String.valueOf(useLaunchButtonEdit);
}
else if (MOVE_WITHIN_FORMAT.equals(key)) {
return getMoveWithinFormat();
}
else if (MOVE_TO_FORMAT.equals(key)) {
return getMoveToFormat();
}
else if (CREATE_FORMAT.equals(key)) {
return getCreateFormat();
}
else if (CHANGE_FORMAT.equals(key)) {
return getChangeFormat();
}
else if (MOVE_KEY.equals(key)) {
return NamedHotKeyConfigurer.encode(moveKey);
}
else if (TOOLTIP.equals(key)) {
return (tooltip == null || tooltip.length() == 0)
? getLaunchButton().getAttributeValueString(name) : tooltip;
}
else {
return super.getAttributeValueString(key);
}
}
/**
* Builds the map's component hierarchy from a given XML element, or a null one is given initializes
* a brand new default "new map" hierarchy.
* @param e XML element to build from, or null to build the default hierarchy for a brand new Map
*/
@Override
public void build(Element e) {
setButtonTextKey(BUTTON_NAME); // Uses non-standard "button text" key
launchButton = makeLaunchButton(
"", //NON-NLS
Resources.getString("Editor.Map.map"), //NON-NLS
"/images/map.gif", //NON-NLS
evt -> {
if (splitPane == null && getLaunchButton().isEnabled()) {
final Container tla = theMap.getTopLevelAncestor();
if (tla != null) {
tla.setVisible(!tla.isVisible());
}
}
}
);
getLaunchButton().setEnabled(false);
getLaunchButton().setVisible(false);
if (e != null) {
super.build(e);
getBoardPicker();
getStackMetrics();
}
else {
getBoardPicker();
getStackMetrics();
addChild(new ForwardToKeyBuffer());
addChild(new Scroller());
addChild(new ForwardToChatter());
addChild(new MenuDisplayer());
addChild(new MapCenterer());
addChild(new StackExpander());
addChild(new PieceMover());
addChild(new KeyBufferer());
addChild(new ImageSaver());
addChild(new CounterDetailViewer());
addChild(new Flare());
setMapName(Resources.getString("Map.main_map"));
}
if (getComponentsOf(GlobalProperties.class).isEmpty()) {
addChild(new GlobalProperties());
}
if (getComponentsOf(SelectionHighlighters.class).isEmpty()) {
addChild(new SelectionHighlighters());
}
if (getComponentsOf(HighlightLastMoved.class).isEmpty()) {
addChild(new HighlightLastMoved());
}
if (getComponentsOf(Flare.class).isEmpty()) {
addChild(new Flare());
}
setup(false);
}
/**
* Adds a child component to this map. Used by {@link #build} to create "default components" for a new map object
* @param b {@link Buildable} component to add
*/
private void addChild(Buildable b) {
add(b);
b.addTo(this);
}
/**
* Every map must include a single {@link BoardPicker} as one of its build components. This will contain
* the map's {@link Board} (or Boards), which will in turn contain any grids, zones, and location
* information.
* @param picker BoardPicker to register to the map. This method unregisters any previous BoardPicker.
*/
public void setBoardPicker(BoardPicker picker) {
if (this.picker != null) {
GameModule.getGameModule().removeCommandEncoder(picker);
GameModule.getGameModule().getGameState().addGameComponent(picker);
}
this.picker = picker;
if (picker != null) {
picker.setAllowMultiple(allowMultiple);
GameModule.getGameModule().addCommandEncoder(picker);
GameModule.getGameModule().getGameState().addGameComponent(picker);
}
}
/**
* Every map must include a {@link BoardPicker} as one of its build components. This contains
* the map's {@link Board} (or Boards), which will in turn contain any grids, zones, and location
* information.
* @return the BoardPicker for this map (if none exist, this method will add one and return it)
*/
public BoardPicker getBoardPicker() {
if (picker == null) {
picker = new BoardPicker();
picker.build(null);
add(picker);
picker.addTo(this);
}
return picker;
}
/**
* A map may include a single {@link Zoomer} as one of its build components. This adds zoom in/out capability to the map.
* @param z {@link Zoomer} to register
*/
public void setZoomer(Zoomer z) {
zoom = z;
}
/**
* A map may include a {@link Zoomer} as one of its build components. This adds zoom in/out capability to the map.
* @return the Zoomer for this map, if one is registered, or null if none.
*/
public Zoomer getZoomer() {
return zoom;
}
/**
* If the map has a {@link Zoomer} (see {@link #setZoomer}), then returns the Zoomer's current zoom factor. If no
* Zoomer exists, returns 1.0 as the zoom factor.
* @return the current zoom factor for the map
*/
public double getZoom() {
return zoom == null ? 1.0 : zoom.getZoomFactor();
}
/**
* Every map must include a single {@link StackMetrics} as one of its build components, which governs the visuals
* of stacking of GamePieces on the map.
* @param sm {@link StackMetrics} component to register
*/
public void setStackMetrics(StackMetrics sm) {
metrics = sm;
}
/**
* Every map must include a single {@link StackMetrics} object as one of its build
* components, which governs the visuals of stacking of GamePieces on the map
*
* @return the StackMetrics for this map
*/
public StackMetrics getStackMetrics() {
if (metrics == null) {
metrics = new StackMetrics();
metrics.build(null);
add(metrics);
metrics.addTo(this);
}
return metrics;
}
/**
* Every map must include a single {@link PieceMover} component as one of its build
* components, which handles drag-and-drop behavior for the map.
* @param mover {@link PieceMover} component to register
*/
public void setPieceMover(PieceMover mover) {
pieceMover = mover;
}
/**
* Every map window has a toolbar, and this method returns swing toolbar component for this map.
* @return the swing toolbar component ({@link JToolBar} for this map's window.
*/
@Override
public JToolBar getToolBar() {
return toolBar;
}
/**
* Registers a {@link Drawable} component to this map. Components can implement the {@link Drawable} interface (and register
* themselves here) if they have a graphical component that should be drawn whenever the Map is drawn. Standard examples
* include {@link CounterDetailViewer}s (aka Mouse-over Stack Viewers), {@link GlobalMap}s (aka Overview Maps), {@link LOS_Thread}s,
* {@link MapShader}s, and the {@link KeyBufferer} (to show which pieces are selected).
*/
public void addDrawComponent(Drawable theComponent) {
drawComponents.add(theComponent);
}
/**
* Unregister a {@link Drawable} component from this map
*/
public void removeDrawComponent(Drawable theComponent) {
drawComponents.remove(theComponent);
}
/**
* Registers this Map as a child of another buildable component, usually the {@link GameModule}. Determines a unique id for
* this Map. Registers itself as {@link KeyStrokeSource}. Registers itself as a {@link GameComponent}. Registers itself as
* a drop target and drag source. If the map is to be removed or otherwise shutdown, it can be deregistered, reversing this
* process, by {@link #removeFrom}
*
* @see #getId
* @see DragBuffer
*/
@Override
public void addTo(Buildable b) {
useLaunchButton = useLaunchButtonEdit;
idMgr.add(this);
final GameModule g = GameModule.getGameModule();
g.addCommandEncoder(new ChangePropertyCommandEncoder(this));
validator = new CompoundValidityChecker(
new MandatoryComponent(this, BoardPicker.class),
new MandatoryComponent(this, StackMetrics.class)).append(idMgr);
final DragGestureListener dgl = dge -> {
if (dragGestureListener != null &&
mouseListenerStack.isEmpty() &&
SwingUtils.isDragTrigger(dge)) {
dragGestureListener.dragGestureRecognized(dge);
}
};
DragSource.getDefaultDragSource().createDefaultDragGestureRecognizer(
theMap, DnDConstants.ACTION_MOVE, dgl);
theMap.setDropTarget(PieceMover.DragHandler.makeDropTarget(
theMap, DnDConstants.ACTION_MOVE, this));
g.getGameState().addGameComponent(this);
g.getToolBar().add(getLaunchButton());
if (shouldDockIntoMainWindow()) {
final Component controlPanel = g.getControlPanel();
final Container cppar = controlPanel.getParent();
final int i = SwingUtils.getIndexInParent(controlPanel, cppar);
splitPane = new SplitPane(SplitPane.VERTICAL_SPLIT, controlPanel, layeredPane);
splitPane.setResizeWeight(0.0);
controlPanel.setMinimumSize(new Dimension(0, 0));
layeredPane.setMinimumSize(new Dimension(0, 0));
cppar.add(splitPane, i);
g.addKeyStrokeSource(new KeyStrokeSource(theMap, JComponent.WHEN_FOCUSED));
}
else {
g.addKeyStrokeSource(
new KeyStrokeSource(theMap, JComponent.WHEN_IN_FOCUSED_WINDOW));
}
// Fix for bug 1630993: toolbar buttons not appearing
toolBar.addHierarchyListener(new HierarchyListener() {
@Override
public void hierarchyChanged(HierarchyEvent e) {
final Window w;
if ((w = SwingUtilities.getWindowAncestor(toolBar)) != null) {
w.validate();
}
if (toolBar.getSize().width > 0) {
toolBar.removeHierarchyListener(this);
}
}
});
g.getPrefs().addOption(
Resources.getString("Prefs.general_tab"), //$NON-NLS-1$
new IntConfigurer(
PREFERRED_EDGE_DELAY,
Resources.getString("Map.scroll_delay_preference"), //$NON-NLS-1$
PREFERRED_EDGE_SCROLL_DELAY
)
);
g.addSideChangeListenerToPlayerRoster(this);
// Create the Configurer for the Pref
preferredScrollConfig = new IntConfigurer(
PREFERRED_SCROLL_ZONE,
Resources.getString("Map.scroll_zone_preference"), //$NON-NLS-1$
SCROLL_ZONE
);
// Register the Pref, which copies any existing pref value into the configurer
g.getPrefs().addOption(
Resources.getString("Prefs.general_tab"), //$NON-NLS-1$
preferredScrollConfig
);
// Read the current value of the pref
SCROLL_ZONE = preferredScrollConfig.getIntValue(60);
// Listen for any changes to the pref
preferredScrollConfig.addPropertyChangeListener(evt -> SCROLL_ZONE = preferredScrollConfig.getIntValue(60));
g.getPrefs().addOption(
Resources.getString("Prefs.compatibility_tab"), //$NON-NLS-1$
new BooleanConfigurer(
MOVING_STACKS_PICKUP_UNITS,
Resources.getString("Map.moving_stacks_preference"), //$NON-NLS-1$
Boolean.FALSE
)
);
}
/**
* Unregisters this Map from its {@link Buildable} parent (usually a {@link GameModule}), reversing
* the process of {@link #addTo}.
* @param b parent {@link Buildable} to deregister from
*/
@Override
public void removeFrom(Buildable b) {
final GameModule g = GameModule.getGameModule();
g.getGameState().removeGameComponent(this);
final Window w = SwingUtilities.getWindowAncestor(theMap);
if (w != null) {
w.dispose();
}
g.getToolBar().remove(getLaunchButton());
idMgr.remove(this);
if (picker != null) {
g.removeCommandEncoder(picker);
g.getGameState().addGameComponent(picker);
}
PlayerRoster.removeSideChangeListener(this);
}
/**
* Takes action when the local player has switched sides. Because Map implements {@link PlayerRoster.SideChangeListener},
* this method will automatically be called whenever the local player switches sides.
* @param oldSide side the local player is switching away from
* @param newSide side the local player is switching to
*/
@Override
public void sideChanged(String oldSide, String newSide) {
repaint();
}
/**
* Set the boards for this map. Each map may contain more than one
* {@link Board}.
* @param c Collection of Boards to be used.
*/
public synchronized void setBoards(Collection<Board> c) {
boards.clear();
for (final Board b : c) {
b.setMap(this);
boards.add(b);
}
setBoardBoundaries();
}
/**
* Set the boards for this map. Each map may contain more than one
* {@link Board}.
* @deprecated Use {@link #setBoards(Collection)} instead.
*/
@Deprecated(since = "2020-08-05", forRemoval = true)
public synchronized void setBoards(Enumeration<Board> boardList) {
ProblemDialog.showDeprecated("2020-08-05"); //NON-NLS
setBoards(Collections.list(boardList));
}
/**
* Since a map can have multiple boards in use at once (laid out above and beside each other), this
* method accepts a {@link Point} in the map's coordinate space and will return the {@link Board} which
* contains that point, or null if none.
* @return the {@link Board} on this map containing the argument point
*/
public Board findBoard(Point p) {
for (final Board b : boards) {
if (b.bounds().contains(p)) {
return b;
}
}
return null;
}
/**
* If the given point in the map's coordinate space is within a {@link Zone} on a board with a
* {@link ZonedGrid} (aka Multi-zoned Grid), returns the Zone. Otherwise returns null.
* @return the {@link Zone} on this map containing the argument point
*/
public Zone findZone(Point p) {
final Board b = findBoard(p);
if (b != null) {
final MapGrid grid = b.getGrid();
if (grid instanceof ZonedGrid) {
final Rectangle r = b.bounds();
final Point pos = new Point(p);
pos.translate(-r.x, -r.y); // Translate to Board co-ords
return ((ZonedGrid) grid).findZone(pos);
}
}
return null;
}
/**
* Search on all boards for a Zone with the given name
* @param name Zone Name
* @return Located zone, or null if not found
*/
public Zone findZone(String name) {
for (final Board b : boards) {
for (final ZonedGrid zg : b.getAllDescendantComponentsOf(ZonedGrid.class)) {
final Zone z = zg.findZone(name);
if (z != null) {
return z;
}
}
}
return null;
}
/**
* Search on all boards for a Region (location on an Irregular Grid) with the given name
* @param name Region name
* @return Located region, or null if none
*/
public Region findRegion(String name) {
for (final Board b : boards) {
for (final RegionGrid rg : b.getAllDescendantComponentsOf(RegionGrid.class)) {
final Region r = rg.findRegion(name);
if (r != null) {
return r;
}
}
}
return null;
}
/**
* Searches our list of boards for one with the given name
* @param name Board Name
* @return located board, or null if no such board found
*/
public Board getBoardByName(String name) {
if (name != null) {
for (final Board b : boards) {
if (name.equals(b.getName())) {
return b;
}
}
}
return null;
}
/**
* @return Dimension for map window's "preferred size"
*/
public Dimension getPreferredSize() {
final Dimension size = mapSize();
size.width *= getZoom();
size.height *= getZoom();
return size;
}
/**
* @return the size of the map in pixels at 100% zoom,
* including the edge buffer
*/
// FIXME: why synchronized?
public synchronized Dimension mapSize() {
final Rectangle r = new Rectangle(0, 0);
for (final Board b : boards) r.add(b.bounds());
r.width += edgeBuffer.width;
r.height += edgeBuffer.height;
return r.getSize();
}
public boolean isLocationRestricted(Point p) {
final Board b = findBoard(p);
if (b != null) {
final Rectangle r = b.bounds();
final Point snap = new Point(p);
snap.translate(-r.x, -r.y);
return b.isLocationRestricted(snap);
}
else {
return false;
}
}
/**
* @return the nearest allowable point according to the {@link VASSAL.build.module.map.boardPicker.board.MapGrid} on
* the {@link Board} at this point
*
* @see Board#snapTo
* @see VASSAL.build.module.map.boardPicker.board.MapGrid#snapTo
*/
public Point snapTo(Point p) {
Point snap = new Point(p);
final Board b = findBoard(p);
if (b == null) return snap;
final Rectangle r = b.bounds();
snap.translate(-r.x, -r.y);
snap = b.snapTo(snap);
snap.translate(r.x, r.y);
//CC bugfix13409
// If we snapped to a point outside the board b, call sanpTo again with the board we landed into
final Board bSnappedTo = findBoard(snap);
if (bSnappedTo != null && !b.equals(bSnappedTo)) {
final Rectangle rSnappedTo = bSnappedTo.bounds();
snap.translate(-rSnappedTo.x, -rSnappedTo.y);
snap = bSnappedTo.snapTo(snap);
snap.translate(rSnappedTo.x, rSnappedTo.y);
}
// RFE 882378
// If we have snapped to a point 1 pixel off the edge of the map, move
// back
// onto the map.
if (findBoard(snap) == null) {
snap.translate(-r.x, -r.y);
if (snap.x == r.width) {
snap.x = r.width - 1;
}
else if (snap.x == -1) {
snap.x = 0;
}
if (snap.y == r.height) {
snap.y = r.height - 1;
}
else if (snap.y == -1) {
snap.y = 0;
}
snap.translate(r.x, r.y);
}
return snap;
}
/**
* @return The buffer of empty space around the boards in the Map window,
* in component coordinates at 100% zoom
*/
public Dimension getEdgeBuffer() {
return new Dimension(edgeBuffer);
}
/**
* Translate a point from component coordinates (i.e., x,y position on
* the JPanel) to map coordinates (i.e., accounting for zoom factor).
*
* @see #componentCoordinates
* @deprecated Use {@link #componentToMap(Point)}
*/
@Deprecated(since = "2020-08-05", forRemoval = true)
public Point mapCoordinates(Point p) {
ProblemDialog.showDeprecated("2020-08-05"); //NON-NLS
return componentToMap(p);
}
/** @deprecated Use {@link #componentToMap(Rectangle)} */
@Deprecated(since = "2020-08-05", forRemoval = true)
public Rectangle mapRectangle(Rectangle r) {
ProblemDialog.showDeprecated("2020-08-05"); //NON-NLS
return componentToMap(r);
}
/**
* Translate a point from map coordinates to component coordinates
*
* @see #mapCoordinates
* @deprecated {@link #mapToComponent(Point)}
*/
@Deprecated(since = "2020-08-05", forRemoval = true)
public Point componentCoordinates(Point p) {
ProblemDialog.showDeprecated("2020-08-05"); //NON-NLS
return mapToComponent(p);
}
/** @deprecated Use {@link #mapToComponent(Rectangle)} */
@Deprecated(since = "2020-08-05", forRemoval = true)
public Rectangle componentRectangle(Rectangle r) {
ProblemDialog.showDeprecated("2020-08-05"); //NON-NLS
return mapToComponent(r);
}
/**
* Scales an integer value to a zoom factor
* @param c value to be scaled
* @param zoom zoom factor
* @return scaled value result
*/
protected int scale(int c, double zoom) {
return (int)(c * zoom);
}
/**
* Scales a point to a zoom factor
* @param p point to be scaled
* @param zoom zoom factor
* @return scaled point result
*/
protected Point scale(Point p, double zoom) {
return new Point((int)(p.x * zoom), (int)(p.y * zoom));
}
/**
* Scales a Rectangle to a zoom factor
* @param r Rectangle to be zoomed
* @param zoom zoom factor
* @return scaled Rectangle result
*/
protected Rectangle scale(Rectangle r, double zoom) {
return new Rectangle(
(int)(r.x * zoom),
(int)(r.y * zoom),
(int)(r.width * zoom),
(int)(r.height * zoom)
);
}
/**
* Converts an integer value from the Map's coordinate system to Drawing coordinates for rendering. Takes into
* account the operating system's scale factor (needed to deal with HiDPI monitors) as well as the Map's zoom
* factor. Although Drawing coordinates may <i>sometimes</i> have the traditional 1-to-1 relationship with component
* coordinates, on HiDPI monitors it will not.
*
* Examples: Drawing a line between two points on a map (see {@link LOS_Thread#draw}. Drawing a piece on the map
* (see {@link StackMetrics#draw}.
*
* @param c value in Map coordinate space to be scaled
* @param os_scale Operating system's scale factor, (obtained from {@link Graphics2D#getDeviceConfiguration().getDefaultTransform().getScaleX()})
* @return scaled value in Drawing coordinate space
*/
public int mapToDrawing(int c, double os_scale) {
return scale(c, getZoom() * os_scale);
}
/**
* Converts a point from the Map's coordinate system to Drawing coordinates for rendering. Takes into
* account the operating system's scale factor (needed to deal with HiDPI monitors) as well as the Map's zoom
* factor. Although Drawing coordinates may <i>sometimes</i> have the traditional 1-to-1 relationship with component
* coordinates, on HiDPI monitors it will not.
*
* Examples: Drawing a line between two points on a map (see {@link LOS_Thread#draw}. Drawing a piece on the map
* (see {@link StackMetrics#draw}.
*
* @param p point in Map coordinates to be scaled
* @param os_scale Operating system's scale factor, (obtained from {@link Graphics2D#getDeviceConfiguration().getDefaultTransform().getScaleX()})
* @return scaled point in Drawing coordinates
*/
public Point mapToDrawing(Point p, double os_scale) {
return scale(p, getZoom() * os_scale);
}
/**
* Converts a rectangle from the Map's coordinate system to Drawing coordinates for rendering. Takes into
* account the operating system's scale factor (needed to deal with HiDPI monitors) as well as the Map's zoom
* factor. Although Drawing coordinates may <i>sometimes</i> have the traditional 1-to-1 relationship with component
* coordinates, on HiDPI monitors it will not.
*
* Examples: Drawing a line between two points on a map (see {@link LOS_Thread#draw}. Drawing a piece on the map
* (see {@link StackMetrics#draw}.
*
* @param r rectangle in Map coordinates to be scaled
* @param os_scale Operating system's scale factor, (obtained from {@link Graphics2D#getDeviceConfiguration().getDefaultTransform().getScaleX()})
* @return scaled rectangle in Drawing coordinates
*/
public Rectangle mapToDrawing(Rectangle r, double os_scale) {
return scale(r, getZoom() * os_scale);
}
/**
* Converts an integer value from the Map's coordinate system to Component coordinates used for interactions between
* swing components. Basically this scales by the map's zoom factor. Note that although drawing coordinates may
* sometimes have the traditional 1-to-1 relationship with component coordinates, on HiDPI monitors it will not.
*
* Examples: activating a popup menu at a piece's location on a map (see MenuDisplayer#maybePopup). Drag and
* drop operations (see dragGestureRecognizedPrep in {@link PieceMover}).
*
* @param c value in Map coordinate system to scale
* @return scaled value in Component coordinate system
*/
public int mapToComponent(int c) {
return scale(c, getZoom());
}
/**
* Converts a Point from the Map's coordinate system to Component coordinates used for interactions between
* swing components. Basically this scales by the map's zoom factor. Note that although drawing coordinates may
* sometimes have the traditional 1-to-1 relationship with component coordinates, on HiDPI monitors it will not.
*
* Examples: activating a popup menu at a piece's location on a map (see MenuDisplayer#maybePopup). Drag and
* drop operations (see dragGestureRecognizedPrep in {@link PieceMover}).
*
* @param p Point in Map coordinates to scale
* @return scaled Point in Component coordinates
*/
public Point mapToComponent(Point p) {
return scale(p, getZoom());
}
/**
* Converts a Rectangle from the Map's coordinate system to Component coordinates used for interactions between
* swing components. Basically this scales by the map's zoom factor. Note that although drawing coordinates may
* sometimes have the traditional 1-to-1 relationship with component coordinates, on HiDPI monitors it will not.
*
* Examples: activating a popup menu at a piece's location on a map (see MenuDisplayer#maybePopup). Drag and
* drop operations (see dragGestureRecognizedPrep in {@link PieceMover}).
*
* @param r Rectangle in Map coordinates to scale
* @return scaled Rectangle in Component coordinates
*/
public Rectangle mapToComponent(Rectangle r) {
return scale(r, getZoom());
}
/**
* Converts an integer value from Component coordinates system to Drawing coordinates for rendering. Takes into
* account the operating system's scale factor (needed to deal with HiDPI monitors), which accounts entirely for
* the difference in these two coordinate systems. Although Drawing coordinates may <i>sometimes</i> have the
* traditional 1-to-1 relationship with Component coordinates, on HiDPI monitors it will not.
*
* Examples: see {@link VASSAL.counters.Footprint#draw} - checking a map component's "visible" clipping rect, and
* using it in the context of drawing move trails.
*
* @param c value in Component coordinate space to be scaled
* @param os_scale Operating system's scale factor, (obtained from {@link Graphics2D#getDeviceConfiguration().getDefaultTransform().getScaleX()})
* @return scaled value in Drawing coordinate space
*/
public int componentToDrawing(int c, double os_scale) {
return scale(c, os_scale);
}
/**
* Converts a Point from Component coordinates to Drawing coordinates for rendering. Takes into
* account the operating system's scale factor (needed to deal with HiDPI monitors), which accounts entirely for
* the difference in these two coordinate systems. Although Drawing coordinates may <i>sometimes</i> have the
* traditional 1-to-1 relationship with Component coordinates, on HiDPI monitors it will not.
*
* Examples: see {@link VASSAL.counters.Footprint#draw} - checking a map component's "visible" clipping rect, and
* using it in the context of drawing move trails.
*
* @param p Point in Component coordinate space to be scaled
* @param os_scale Operating system's scale factor, (obtained from {@link Graphics2D#getDeviceConfiguration().getDefaultTransform().getScaleX()})
* @return scaled Point in Drawing coordinate space
*/
public Point componentToDrawing(Point p, double os_scale) {
return scale(p, os_scale);
}
/**
* Converts a Rectangle from Component coordinates to Drawing coordinates for rendering. Takes into
* account the operating system's scale factor (needed to deal with HiDPI monitors), which accounts entirely for
* the difference in these two coordinate systems. Although Drawing coordinates may <i>sometimes</i> have the
* traditional 1-to-1 relationship with Component coordinates, on HiDPI monitors it will not.
*
* Examples: see {@link VASSAL.counters.Footprint#draw} - checking a map component's "visible" clipping rect, and
* using it in the context of drawing move trails.
*
* @param r Rectangle in Component coordinate space to be scaled
* @param os_scale Operating system's scale factor, (obtained from {@link Graphics2D#getDeviceConfiguration().getDefaultTransform().getScaleX()})
* @return scaled Rectangle in Drawing coordinate space
*/
public Rectangle componentToDrawing(Rectangle r, double os_scale) {
return scale(r, os_scale);
}
/**
* Converts an integer value from swing Component coordinates to the Map's coordinate system. Basically this scales by the
* inverse of the map's zoom factor. Note that although drawing coordinates may sometimes have the traditional 1-to-1 relationship
* with component coordinates, on HiDPI monitors it will not.
*
* Examples: Checking if the mouse is currently overlapping a game piece {@link KeyBufferer#mouseReleased(MouseEvent)},
* CounterDetailViewer#getDisplayablePieces.
*
* @param c value in Component coordinates to scale
* @return scaled value in Map coordinates
*/
public int componentToMap(int c) {
return scale(c, 1.0 / getZoom());
}
/**
* Converts a Point from swing Component coordinates to the Map's coordinate system. Basically this scales by the
* inverse of the map's zoom factor. Note that although drawing coordinates may sometimes have the traditional 1-to-1 relationship
* with component coordinates, on HiDPI monitors it will not.
*
* Examples: Checking if the mouse is currently overlapping a game piece {@link KeyBufferer#mouseReleased(MouseEvent)},
* CounterDetailViewer#getDisplayablePieces.
*
* @param p Point in Component coordinates to scale
* @return scaled Point in Map coordinates
*/
public Point componentToMap(Point p) {
return scale(p, 1.0 / getZoom());
}
/**
* Converts a Rectangle from swing Component coordinates to the Map's coordinate system. Basically this scales by the
* inverse of the map's zoom factor. Note that although drawing coordinates may sometimes have the traditional 1-to-1 relationship
* with component coordinates, on HiDPI monitors it will not.
*
* Examples: Checking if the mouse is currently overlapping a game piece {@link KeyBufferer#mouseReleased(MouseEvent)},
* CounterDetailViewer#getDisplayablePieces.
*
* @param r Rectangle in Component coordinates to scale
* @return scaled Rectangle in Map coordinates
*/
public Rectangle componentToMap(Rectangle r) {
return scale(r, 1.0 / getZoom());
}
/**
* Converts an integer value from Drawing coordinates to the Map's coordinate system. Takes into
* account the operating system's scale factor (needed to deal with HiDPI monitors) as well as the Map's zoom
* factor, scaling by the inverse of both of these scale factors. Although Drawing coordinates may <i>sometimes</i>
* have the traditional 1-to-1 relationship with component coordinates, on HiDPI monitors it will not.
*
* @param c value in Drawing coordinate space to be scaled
* @param os_scale Operating system's scale factor, (obtained from {@link Graphics2D#getDeviceConfiguration().getDefaultTransform().getScaleX()})
* @return scaled value in Map coordinates
*/
@SuppressWarnings("unused")
public int drawingToMap(int c, double os_scale) {
return scale(c, 1.0 / (getZoom() * os_scale));
}
/**
* Converts a Point from Drawing coordinates to the Map's coordinate system. Takes into
* account the operating system's scale factor (needed to deal with HiDPI monitors) as well as the Map's zoom
* factor, scaling by the inverse of both of these scale factors. Although Drawing coordinates may <i>sometimes</i>
* have the traditional 1-to-1 relationship with component coordinates, on HiDPI monitors it will not.
*
* @param p Point in Drawing coordinate space to be scaled
* @param os_scale Operating system's scale factor, (obtained from {@link Graphics2D#getDeviceConfiguration().getDefaultTransform().getScaleX()})
* @return scaled point in Map coordinates
*/
public Point drawingToMap(Point p, double os_scale) {
return scale(p, 1.0 / (getZoom() * os_scale));
}
/**
* Converts a Rectangle from Drawing coordinates to the Map's coordinate system. Takes into
* account the operating system's scale factor (needed to deal with HiDPI monitors) as well as the Map's zoom
* factor, scaling by the inverse of both of these scale factors. Although Drawing coordinates may <i>sometimes</i>
* have the traditional 1-to-1 relationship with component coordinates, on HiDPI monitors it will not.
*
* @param r Rectangle in Drawing coordinate space to be scaled
* @param os_scale Operating system's scale factor, (obtained from {@link Graphics2D#getDeviceConfiguration().getDefaultTransform().getScaleX()})
* @return scaled Rectangle in Map coordinates
*/
public Rectangle drawingToMap(Rectangle r, double os_scale) {
return scale(r, 1.0 / (getZoom() * os_scale));
}
/**
* Converts an integer value from Drawing coordinates to swing Component coordinates. Takes into account the inverse
* of the operating system's scale factor (needed to deal with HiDPI monitors), which accounts entirely for the
* difference in these two coordinate systems. Although Drawing coordinates may <i>sometimes</i> have the traditional
* 1-to-1 relationship with Component coordinates, on HiDPI monitors it will not.
*
* @param c value in Drawing coordinates
* @param os_scale Operating system's scale factor, (obtained from {@link Graphics2D#getDeviceConfiguration().getDefaultTransform().getScaleX()})
* @return scaled value in Component coordinates
*/
public int drawingToComponent(int c, double os_scale) {
return scale(c, 1.0 / os_scale);
}
/**
* Converts a Point from Drawing coordinates to swing Component coordinates. Takes into account the inverse
* of the operating system's scale factor (needed to deal with HiDPI monitors), which accounts entirely for the
* difference in these two coordinate systems. Although Drawing coordinates may <i>sometimes</i> have the traditional
* 1-to-1 relationship with Component coordinates, on HiDPI monitors it will not.
*
* @param p Point in Drawing coordinates
* @param os_scale Operating system's scale factor, (obtained from {@link Graphics2D#getDeviceConfiguration().getDefaultTransform().getScaleX()})
* @return scaled Point in Component coordinates
*/
public Point drawingToComponent(Point p, double os_scale) {
return scale(p, 1.0 / os_scale);
}
/**
* Converts a Rectangle from Drawing coordinates to swing Component coordinates. Takes into account the inverse
* of the operating system's scale factor (needed to deal with HiDPI monitors), which accounts entirely for the
* difference in these two coordinate systems. Although Drawing coordinates may <i>sometimes</i> have the traditional
* 1-to-1 relationship with Component coordinates, on HiDPI monitors it will not.
*
* @param r Rectangle in Drawing coordinates
* @param os_scale Operating system's scale factor, (obtained from {@link Graphics2D#getDeviceConfiguration().getDefaultTransform().getScaleX()})
* @return scaled Rectangle in Component coordinates
*/
public Rectangle drawingToComponent(Rectangle r, double os_scale) {
return scale(r, 1.0 / os_scale);
}
/**
* @return a String name for the given location on the map. Checks first for a {@link Deck}, then for a {@link Board} that
* is able to provide a name from one of its grids. If no matches, returns "offboard" string.
*
* @see Board#locationName
*/
public String locationName(Point p) {
String loc = getDeckNameAt(p);
if (loc == null) {
final Board b = findBoard(p);
if (b != null) {
loc = b.locationName(new Point(p.x - b.bounds().x, p.y - b.bounds().y));
}
}
if (loc == null) {
loc = Resources.getString("Map.offboard"); //$NON-NLS-1$
}
return loc;
}
/**
* @return a translated-if-available String name for the given location on the map. Checks first for a {@link Deck},
* then for a {@link Board} that is able to provide a name from one of its grids. If no matches, returns "offboard" string.
*
* @see Board#locationName
*/
public String localizedLocationName(Point p) {
String loc = getLocalizedDeckNameAt(p);
if (loc == null) {
final Board b = findBoard(p);
if (b != null) {
loc = b.localizedLocationName(new Point(p.x - b.bounds().x, p.y - b.bounds().y));
}
}
if (loc == null) {
loc = Resources.getString("Map.offboard"); //$NON-NLS-1$
}
return loc;
}
/**
* Is this map visible to all players?
* @return true if this map either (a) isn't a {@link PrivateMap} or (b) does have its visible-to-all flag set
*/
@SuppressWarnings("unused")
public boolean isVisibleToAll() {
return !(this instanceof PrivateMap) || getAttributeValueString(PrivateMap.VISIBLE).equals("true"); //$NON-NLS-1$
}
/**
* @return the name of the {@link Deck} whose bounding box contains point p
*/
@SuppressWarnings("unused")
public String getDeckNameContaining(Point p) {
String deck = null;
if (p != null) {
for (final DrawPile d : getComponentsOf(DrawPile.class)) {
final Rectangle box = d.boundingBox();
if (box != null && box.contains(p)) {
deck = d.getConfigureName();
break;
}
}
}
return deck;
}
/**
* Return the name of the {@link Deck} whose position is precisely p
*
* @param p Point to look for Deck
* @return Name of {@link Deck whose position is precisely p
*/
public String getDeckNameAt(Point p) {
String deck = null;
if (p != null) {
for (final DrawPile d : getComponentsOf(DrawPile.class)) {
if (d.getPosition().equals(p)) {
deck = d.getConfigureName();
break;
}
}
}
return deck;
}
/**
* Return the localized name of the {@link Deck} whose position is precisely p
*
* @param p Point to look for Deck
* @return Name of {@link Deck whose position is precisely p
*/
public String getLocalizedDeckNameAt(Point p) {
String deck = null;
if (p != null) {
for (final DrawPile d : getComponentsOf(DrawPile.class)) {
if (d.getPosition().equals(p)) {
deck = d.getLocalizedConfigureName();
break;
}
}
}
return deck;
}
/**
* Because MouseEvents are received in Component coordinates, it is
* inconvenient for MouseListeners on the map to have to translate to Map
* coordinates. MouseListeners added with this method will receive mouse
* events with points already translated into Map coordinates.
* addLocalMouseListenerFirst inserts the new listener at the start of the
* chain.
* @param l MouseListener to add
*/
public void addLocalMouseListener(MouseListener l) {
multicaster = AWTEventMulticaster.add(multicaster, l);
}
/**
* Because MouseEvents are received in Component coordinates, it is
* inconvenient for MouseListeners on the map to have to translate to Map
* coordinates. MouseListeners added with this method will receive mouse
* events with points already translated into Map coordinates.
* addLocalMouseListenerFirst inserts the new listener at the start of the
* chain.
* @param l MouseListener to add
*/
public void addLocalMouseListenerFirst(MouseListener l) {
multicaster = AWTEventMulticaster.add(l, multicaster);
}
/**
* Because MouseEvents are received in Component coordinates, it is
* inconvenient for MouseListeners on the map to have to translate to Map
* coordinates. MouseListeners added with this method will receive mouse
* events with points already translated into Map coordinates.
* addLocalMouseListenerFirst inserts the new listener at the start of the
* chain.
* @param l MouseListener to add
*/
public void removeLocalMouseListener(MouseListener l) {
multicaster = AWTEventMulticaster.remove(multicaster, l);
}
/**
* MouseListeners on a map may be pushed and popped onto a stack.
* Only the top listener on the stack receives mouse events.
* @param l MouseListener to push onto stack.
*/
public void pushMouseListener(MouseListener l) {
mouseListenerStack.add(l);
}
/**
* MouseListeners on a map may be pushed and popped onto a stack. Only the top listener on the stack receives mouse
* events. The pop method removes the most recently pushed mouse listener.
*/
public void popMouseListener() {
mouseListenerStack.remove(mouseListenerStack.size() - 1);
}
/**
* @param e MouseEvent
*/
@Override
public void mouseEntered(MouseEvent e) {
}
/**
* @param e MouseEvent
*/
@Override
public void mouseExited(MouseEvent e) {
}
/**
* Because MouseEvents are received in Component coordinates, it is
* inconvenient for MouseListeners on the map to have to translate to Map
* coordinates. MouseListeners added with this method will receive mouse
* events with points already translated into Map coordinates.
* addLocalMouseListenerFirst inserts the new listener at the start of the
* chain.
* @param e MouseEvent in Component coordinates
* @return MouseEvent translated into Map coordinates
*/
public MouseEvent translateEvent(MouseEvent e) {
// don't write over Java's mouse event
final MouseEvent mapEvent = new MouseEvent(
e.getComponent(), e.getID(), e.getWhen(), e.getModifiersEx(),
e.getX(), e.getY(), e.getXOnScreen(), e.getYOnScreen(),
e.getClickCount(), e.isPopupTrigger(), e.getButton()
);
final Point p = componentToMap(mapEvent.getPoint());
mapEvent.translatePoint(p.x - mapEvent.getX(), p.y - mapEvent.getY());
return mapEvent;
}
/**
* Mouse events are first translated into map coordinates. Then the event is forwarded to the top MouseListener in the
* stack, if any, otherwise forwarded to all LocalMouseListeners
* @param e MouseEvent from system
*
* @see #pushMouseListener
* @see #popMouseListener
* @see #addLocalMouseListener
*/
@Override
public void mouseClicked(MouseEvent e) {
if (!mouseListenerStack.isEmpty()) {
mouseListenerStack.get(mouseListenerStack.size() - 1).mouseClicked(translateEvent(e));
}
else if (multicaster != null) {
multicaster.mouseClicked(translateEvent(e));
}
}
public static Map activeMap = null;
/**
* Marks an ActiveMap for certain drag and drop operations, so that the map can be repainted when the operation is
* complete.
* @param m Map to be considered active.
*/
public static void setActiveMap(Map m) {
activeMap = m;
}
/**
* Repaints the current ActiveMap (see {@link #setActiveMap}) and unmarks it.
*/
public static void clearActiveMap() {
if (activeMap != null) {
activeMap.repaint();
setActiveMap(null);
}
}
/**
* Mouse events are first translated into map coordinates. Then the event is forwarded to the top MouseListener in the
* stack, if any, otherwise forwarded to all LocalMouseListeners
* @param e MouseEvent from system
*
* @see #pushMouseListener
* @see #popMouseListener
* @see #addLocalMouseListener
*/
@Override
public void mousePressed(MouseEvent e) {
// Deselect any counters on the last Map with focus
if (!this.equals(activeMap)) {
boolean dirty = false;
final KeyBuffer kbuf = KeyBuffer.getBuffer();
final ArrayList<GamePiece> l = new ArrayList<>(kbuf.asList());
for (final GamePiece p : l) {
if (p.getMap() == activeMap) {
kbuf.remove(p);
dirty = true;
}
}
if (dirty && activeMap != null) {
activeMap.repaint();
}
}
setActiveMap(this);
if (!mouseListenerStack.isEmpty()) {
mouseListenerStack.get(mouseListenerStack.size() - 1).mousePressed(translateEvent(e));
}
else if (multicaster != null) {
multicaster.mousePressed(translateEvent(e));
}
}
/**
* Mouse events are first translated into map coordinates. Then the event is forwarded to the top MouseListener in the
* stack, if any, otherwise forwarded to all LocalMouseListeners
* @param e MouseEvent from system
*
* @see #pushMouseListener
* @see #popMouseListener
* @see #addLocalMouseListener
*/
@Override
public void mouseReleased(MouseEvent e) {
// don't write over Java's mouse event
final Point p = e.getPoint();
p.translate(theMap.getX(), theMap.getY());
if (theMap.getBounds().contains(p)) {
if (!mouseListenerStack.isEmpty()) {
mouseListenerStack.get(mouseListenerStack.size() - 1).mouseReleased(translateEvent(e));
}
else if (multicaster != null) {
multicaster.mouseReleased(translateEvent(e));
}
// Request Focus so that keyboard input will be recognized
theMap.requestFocus();
}
// Clicking with mouse always repaints the map
clearFirst = true;
theMap.repaint();
activeMap = this;
}
/**
* Save all current Key Listeners and remove them from the
* map. Used by Traits that need to prevent Key Commands
* at certain times.
*/
public void enableKeyListeners() {
if (saveKeyListeners == null) return;
for (final KeyListener kl : saveKeyListeners) {
theMap.addKeyListener(kl);
}
saveKeyListeners = null;
}
/**
* Restore the previously disabled KeyListeners
*/
public void disableKeyListeners() {
if (saveKeyListeners != null) return;
saveKeyListeners = theMap.getKeyListeners();
for (final KeyListener kl : saveKeyListeners) {
theMap.removeKeyListener(kl);
}
}
/**
* This listener will be notified when a drag event is initiated, assuming
* that no MouseListeners are on the stack.
*
* @see #pushMouseListener
* @param dragGestureListener Listener
*/
public void setDragGestureListener(DragGestureListener dragGestureListener) {
this.dragGestureListener = dragGestureListener;
}
/**
* @return current dragGestureListener that handles normal drag events (assuming no MouseListeners are on the stack)
* @see #pushMouseListener
*/
public DragGestureListener getDragGestureListener() {
return dragGestureListener;
}
/**
* @param dtde DropTargetDragEvent
*/
@Override
public void dragEnter(DropTargetDragEvent dtde) {
}
/**
* Handles scrolling when dragging an gamepiece to the edge of the window
* @param dtde DropTargetDragEvent
*/
@Override
public void dragOver(DropTargetDragEvent dtde) {
scrollAtEdge(dtde.getLocation(), SCROLL_ZONE);
}
/**
* @param dtde DropTargetDragEvent
*/
@Override
public void dropActionChanged(DropTargetDragEvent dtde) {
}
/*
* Cancel final scroll and repaint map
* @param dtde DropTargetDragEvent
*/
@Override
public void dragExit(DropTargetEvent dte) {
if (scroller.isRunning()) scroller.stop();
repaint();
}
/**
* We put the "drop" in drag-n-drop!
* @param dtde DropTargetDragEvent
*/
@Override
public void drop(DropTargetDropEvent dtde) {
if (dtde.getDropTargetContext().getComponent() == theMap) {
final MouseEvent evt = new MouseEvent(
theMap,
MouseEvent.MOUSE_RELEASED,
System.currentTimeMillis(),
0,
dtde.getLocation().x,
dtde.getLocation().y,
1,
false,
MouseEvent.NOBUTTON
);
theMap.dispatchEvent(evt);
dtde.dropComplete(true);
}
if (scroller.isRunning()) scroller.stop();
}
/**
* Mouse motion events are not forwarded to LocalMouseListeners or to listeners on the stack
* @param e MouseEvent from system
*/
@Override
public void mouseMoved(MouseEvent e) {
}
/**
* Mouse motion events are not forwarded to LocalMouseListeners or to
* listeners on the stack.
*
* The map scrolls when dragging the mouse near the edge.
* @param e MouseEvent from system
*/
@Override
public void mouseDragged(MouseEvent e) {
if (!SwingUtils.isContextMouseButtonDown(e)) {
scrollAtEdge(e.getPoint(), SCROLL_ZONE);
}
else {
if (scroller.isRunning()) scroller.stop();
}
}
/*
* Delay before starting scroll at edge
*/
public static final int PREFERRED_EDGE_SCROLL_DELAY = 200;
public static final String PREFERRED_EDGE_DELAY = "PreferredEdgeDelay"; //$NON-NLS-1$
/** The width of the hot zone for triggering autoscrolling. */
public static int SCROLL_ZONE = 60;
public static final String PREFERRED_SCROLL_ZONE = "PreferredScrollZone"; //$NON-NLS-1$
/** The horizontal component of the autoscrolling vector, -1, 0, or 1. */
protected int sx;
/** The vertical component of the autoscrolling vector, -1, 0, or 1. */
protected int sy;
protected int dx, dy;
/**
* Begin autoscrolling the map if the given point is within the given
* distance from a viewport edge.
*
* @param evtPt Point to check
* @param dist Distance to check
*/
public void scrollAtEdge(Point evtPt, int dist) {
final Rectangle vrect = scroll.getViewport().getViewRect();
final int px = evtPt.x - vrect.x;
final int py = evtPt.y - vrect.y;
// determine scroll vector
sx = 0;
if (px < dist && px >= 0) {
sx = -1;
dx = dist - px;
}
else if (px < vrect.width && px >= vrect.width - dist) {
sx = 1;
dx = dist - (vrect.width - px);
}
sy = 0;
if (py < dist && py >= 0) {
sy = -1;
dy = dist - py;
}
else if (py < vrect.height && py >= vrect.height - dist) {
sy = 1;
dy = dist - (vrect.height - py);
}
dx /= 2;
dy /= 2;
// start autoscrolling if we have a nonzero scroll vector
if (sx != 0 || sy != 0) {
if (!scroller.isRunning()) {
scroller.setStartDelay((Integer)
GameModule.getGameModule().getPrefs().getValue(PREFERRED_EDGE_DELAY));
scroller.start();
}
}
else {
if (scroller.isRunning()) scroller.stop();
}
}
/** The animator which controls autoscrolling. */
protected Animator scroller = new Animator(Animator.INFINITE,
new TimingTargetAdapter() {
private long t0;
/**
* Continue to scroll the map as animator instructs us
* @param fraction not used
*/
@Override
public void timingEvent(float fraction) {
// Constant velocity along each axis, 0.5px/ms
final long t1 = System.currentTimeMillis();
final int dt = (int)((t1 - t0) / 2);
t0 = t1;
scroll(sx * dt, sy * dt);
// Check whether we have hit an edge
final Rectangle vrect = scroll.getViewport().getViewRect();
if ((sx == -1 && vrect.x == 0) ||
(sx == 1 && vrect.x + vrect.width >= theMap.getWidth())) sx = 0;
if ((sy == -1 && vrect.y == 0) ||
(sy == 1 && vrect.y + vrect.height >= theMap.getHeight())) sy = 0;
// Stop if the scroll vector is zero
if (sx == 0 && sy == 0) scroller.stop();
}
/**
* Get ready to scroll
*/
@Override
public void begin() {
t0 = System.currentTimeMillis();
}
}
);
/**
* Repaints the map. Accepts parameter about whether to clear the display first.
* @param cf true if display should be cleared before drawing the map
*/
public void repaint(boolean cf) {
clearFirst = cf;
theMap.repaint();
}
/**
* Repaints the map.
*/
public void repaint() {
theMap.repaint();
}
/**
* Paints a specific region of the map, denoted by a Rectangle.
* @param g Graphics object where map should be painted
* @param visibleRect region of map to repaint
*/
public void paintRegion(Graphics g, Rectangle visibleRect) {
paintRegion(g, visibleRect, theMap);
}
/**
* Paints a specific region of the map, denoted by a Rectangle.
* @param g Graphics object where map should be painted
* @param visibleRect region of map to repaint
* @param c observer component
*/
public void paintRegion(Graphics g, Rectangle visibleRect, Component c) {
clearMapBorder(g); // To avoid ghost pieces around the edge
drawBoardsInRegion(g, visibleRect, c);
drawDrawable(g, false);
drawPiecesInRegion(g, visibleRect, c);
drawDrawable(g, true);
}
/**
* For each Board overlapping the given region, update the appropriate section of the board image.
* @param g Graphics object where map should be painted
* @param visibleRect region of map to repaint
* @param c observer component
*/
public void drawBoardsInRegion(Graphics g,
Rectangle visibleRect,
Component c) {
final Graphics2D g2d = (Graphics2D) g;
final double os_scale = g2d.getDeviceConfiguration().getDefaultTransform().getScaleX();
final double dzoom = getZoom() * os_scale;
for (final Board b : boards) {
b.drawRegion(g, getLocation(b, dzoom), visibleRect, dzoom, c);
}
}
/**
* For each Board overlapping the given region, update the appropriate section of the board image.
* @param g Graphics object where map should be painted
* @param visibleRect region of map to repaint
*/
public void drawBoardsInRegion(Graphics g, Rectangle visibleRect) {
drawBoardsInRegion(g, visibleRect, theMap);
}
/**
* Draws all pieces visible in a rectangular area of the map
* @param g Graphics object where map should be painted
* @param visibleRect region of map to repaint
* @param c observer component
*/
public void drawPiecesInRegion(Graphics g,
Rectangle visibleRect,
Component c) {
if (hideCounters) {
return;
}
final Graphics2D g2d = (Graphics2D) g;
final double os_scale = g2d.getDeviceConfiguration().getDefaultTransform().getScaleX();
final double dzoom = getZoom() * os_scale;
final Composite oldComposite = g2d.getComposite();
g2d.setComposite(
AlphaComposite.getInstance(AlphaComposite.SRC_OVER, pieceOpacity));
final GamePiece[] stack = pieces.getPieces(); // Gets map pieces, sorted by visual layer
for (final GamePiece gamePiece : stack) {
final Point pt = mapToDrawing(gamePiece.getPosition(), os_scale);
if (gamePiece.getClass() == Stack.class) {
getStackMetrics().draw(
(Stack) gamePiece, pt, g, this, dzoom, visibleRect
);
}
else {
gamePiece.draw(g, pt.x, pt.y, c, dzoom);
if (Boolean.TRUE.equals(gamePiece.getProperty(Properties.SELECTED))) {
highlighter.draw(gamePiece, g, pt.x, pt.y, c, dzoom);
}
}
/*
// draw bounding box for debugging
final Rectangle bb = stack[i].boundingBox();
g.drawRect(pt.x + bb.x, pt.y + bb.y, bb.width, bb.height);
*/
}
g2d.setComposite(oldComposite);
}
/**
* Draws all pieces visible in a rectangular area of the map
* @param g Graphics object where map should be painted
* @param visibleRect region of map to repaint
*/
public void drawPiecesInRegion(Graphics g, Rectangle visibleRect) {
drawPiecesInRegion(g, visibleRect, theMap);
}
/**
* Draws the map pieces at a given offset
* @param g Target graphics object
* @param xOffset x offset
* @param yOffset y offset
*/
public void drawPieces(Graphics g, int xOffset, int yOffset) {
if (hideCounters) {
return;
}
final Graphics2D g2d = (Graphics2D) g;
final double os_scale = g2d.getDeviceConfiguration().getDefaultTransform().getScaleX();
final Composite oldComposite = g2d.getComposite();
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, pieceOpacity));
final GamePiece[] stack = pieces.getPieces(); // Gets map pieces, sorted by visual layer
for (final GamePiece gamePiece : stack) {
final Point pt = mapToDrawing(gamePiece.getPosition(), os_scale);
gamePiece.draw(g, pt.x + xOffset, pt.y + yOffset, theMap, getZoom());
if (Boolean.TRUE.equals(gamePiece.getProperty(Properties.SELECTED))) {
highlighter.draw(gamePiece, g, pt.x - xOffset, pt.y - yOffset, theMap, getZoom());
}
}
g2d.setComposite(oldComposite);
}
/**
* Draws all of our "Drawable" components. Standard examples include {@link CounterDetailViewer}s (aka Mouse-over Stack Viewers),
* {@link GlobalMap}s (aka Overview Maps), {@link LOS_Thread}s, {@link MapShader}s, and the {@link KeyBufferer} (to show which
* pieces are selected).
* @param g target graphics object
* @param aboveCounters true means we should draw only the drawables that go above the counters; false means we should draw only the ones that go below
*/
public void drawDrawable(Graphics g, boolean aboveCounters) {
for (final Drawable drawable : drawComponents) {
if (aboveCounters == drawable.drawAboveCounters()) {
drawable.draw(g, this);
}
}
}
/**
* @return Current selection highlighter
*/
public Highlighter getHighlighter() {
return highlighter;
}
/**
* @param h selection highlighter to set active
*/
public void setHighlighter(Highlighter h) {
highlighter = h;
}
/**
* @param h selection highlighter to add to our list
*/
public void addHighlighter(Highlighter h) {
highlighters.add(h);
}
/**
* @param h selection highlighter to remove from our list
*/
public void removeHighlighter(Highlighter h) {
highlighters.remove(h);
}
/**
* @return an Iterator for all of our highlighters
*/
public Iterator<Highlighter> getHighlighters() {
return highlighters.iterator();
}
/**
* @return a Collection of all {@link Board}s on the Map
*/
public Collection<Board> getBoards() {
return Collections.unmodifiableCollection(boards);
}
/**
* @return an Enumeration of all {@link Board}s on the map
* @deprecated Use {@link #getBoards()} instead.
*/
@Deprecated(since = "2020-08-05", forRemoval = true)
public Enumeration<Board> getAllBoards() {
ProblemDialog.showDeprecated("2020-08-05"); //NON-NLS
return Collections.enumeration(boards);
}
/**
* @return number of Boards on this map
*/
public int getBoardCount() {
return boards.size();
}
/**
* @return the boundingBox of a GamePiece accounting for the offset of a piece within its parent stack. Return null if
* this piece is not on the map
*
* @see GamePiece#boundingBox
*/
public Rectangle boundingBoxOf(GamePiece p) {
Rectangle r = null;
if (p.getMap() == this) {
r = p.boundingBox();
final Point pos = p.getPosition();
r.translate(pos.x, pos.y);
if (Boolean.TRUE.equals(p.getProperty(Properties.SELECTED))) {
r.add(highlighter.boundingBox(p));
for (final Iterator<Highlighter> i = getHighlighters(); i.hasNext();) {
r.add(i.next().boundingBox(p));
}
}
if (p.getParent() != null) {
final Point pt = getStackMetrics().relativePosition(p.getParent(), p);
r.translate(pt.x, pt.y);
}
}
return r;
}
/**
* @return the selection bounding box of a GamePiece accounting for the offset of a piece within a stack
*
* @see GamePiece#getShape
*/
public Rectangle selectionBoundsOf(GamePiece p) {
if (p.getMap() != this) {
throw new IllegalArgumentException(
Resources.getString("Map.piece_not_on_map")); //$NON-NLS-1$
}
final Rectangle r = p.getShape().getBounds();
r.translate(p.getPosition().x, p.getPosition().y);
if (p.getParent() != null) {
final Point pt = getStackMetrics().relativePosition(p.getParent(), p);
r.translate(pt.x, pt.y);
}
return r;
}
/**
* @return the position of a GamePiece accounting for the offset within a parent stack, if any
*/
public Point positionOf(GamePiece p) {
if (p.getMap() != this) {
throw new IllegalArgumentException(
Resources.getString("Map.piece_not_on_map")); //$NON-NLS-1$
}
final Point point = p.getPosition();
if (p.getParent() != null) {
final Point pt = getStackMetrics().relativePosition(p.getParent(), p);
point.translate(pt.x, pt.y);
}
return point;
}
/**
* @return an array of all GamePieces on the map, subject to visibility, and sorted in order of
* visual layers. This is a read-only copy. Altering the array does not alter the pieces on the map.
*/
public GamePiece[] getPieces() {
return pieces.getPieces();
}
/**
* @return an array of all GamePieces on the map, regardless of visibility, and sorted
* in order of visual layer. This is a read-only copy. Altering the array does not alter
* the pieces on the map.
*/
public GamePiece[] getAllPieces() {
return pieces.getAllPieces();
}
/**
* @param pieces Sets the PieceCollection for this map (usually a LayeredPieceCollection a/k/a "Game Piece Layer Control"), which keeps the pieces/stacks/decks sorted by visual layer, and within each layer by back-to-front draw order
*/
public void setPieceCollection(PieceCollection pieces) {
this.pieces = pieces;
}
/**
* @return piece collection for this map (a/k/a its LayeredPieceCollection or "Game Piece Layer Control"), which maintains a list of all the pieces/stacks/decks on the map sorted by visual layer, and within each layer by back-to-front draw order
*/
public PieceCollection getPieceCollection() {
return pieces;
}
/**
* Clears the map border region, if any. If the {@link #clearFirst} flag is set, wipe the map image too.
* @param g target graphics object
*/
protected void clearMapBorder(Graphics g) {
final Graphics2D g2d = (Graphics2D) g.create();
final double os_scale = g2d.getDeviceConfiguration().getDefaultTransform().getScaleX();
if (clearFirst || boards.isEmpty()) {
g.setColor(bgColor);
g.fillRect(
0,
0,
componentToDrawing(theMap.getWidth(), os_scale),
componentToDrawing(theMap.getHeight(), os_scale)
);
clearFirst = false;
}
else {
final int mw = componentToDrawing(theMap.getWidth(), os_scale);
final int mh = componentToDrawing(theMap.getHeight(), os_scale);
final int ew = mapToDrawing(edgeBuffer.width, os_scale);
final int eh = mapToDrawing(edgeBuffer.height, os_scale);
g.setColor(bgColor);
g.fillRect(0, 0, ew, mh);
g.fillRect(0, 0, mw, eh);
g.fillRect(mw - ew, 0, ew, mh);
g.fillRect(0, mh - eh, mw, eh);
}
}
/**
* Adjusts the bounds() rectangle to account for the Board's relative
* position to other boards. In other words, if Board A is N pixels wide
* and Board B is to the right of Board A, then the origin of Board B
* will be adjusted N pixels to the right.
*/
protected void setBoardBoundaries() {
int maxX = 0;
int maxY = 0;
for (final Board b : boards) {
final Point relPos = b.relativePosition();
maxX = Math.max(maxX, relPos.x);
maxY = Math.max(maxY, relPos.y);
}
boardWidths = new int[maxX + 1][maxY + 1];
boardHeights = new int[maxX + 1][maxY + 1];
for (final Board b : boards) {
final Point relPos = b.relativePosition();
boardWidths[relPos.x][relPos.y] = b.bounds().width;
boardHeights[relPos.x][relPos.y] = b.bounds().height;
}
final Point offset = new Point(edgeBuffer.width, edgeBuffer.height);
for (final Board b : boards) {
final Point relPos = b.relativePosition();
final Point location = getLocation(relPos.x, relPos.y, 1.0);
b.setLocation(location.x, location.y);
b.translate(offset.x, offset.y);
}
theMap.revalidate();
}
/**
* Gets the location of a board in Map space, based on a passed zoom factor
* @param b Board to find location
* @param zoom zoom factor to use
* @return Relative position of the board at given scale
*/
protected Point getLocation(Board b, double zoom) {
final Point p;
if (zoom == 1.0) {
p = b.bounds().getLocation();
}
else {
final Point relPos = b.relativePosition();
p = getLocation(relPos.x, relPos.y, zoom);
p.translate((int) (zoom * edgeBuffer.width), (int) (zoom * edgeBuffer.height));
}
return p;
}
/**
* Finds the location of a board (in Map space) at a particular
* column and row, based on passed zoom factor
* @param column number of board to find
* @param row number of board to find
* @param zoom zoom factor to use
* @return location of the board in Map space
*/
protected Point getLocation(int column, int row, double zoom) {
final Point p = new Point();
for (int x = 0; x < column; ++x) {
p.translate((int) Math.floor(zoom * boardWidths[x][row]), 0);
}
for (int y = 0; y < row; ++y) {
p.translate(0, (int) Math.floor(zoom * boardHeights[column][y]));
}
return p;
}
/**
* Draw the boards of the map at the given point and zoom factor onto
* the given Graphics object
* @param g target Graphics object
* @param xoffset x offset to draw at
* @param yoffset y offset to draw at
* @param zoom zoom factor for drawing the boards
* @param obs observer Component
*/
public void drawBoards(Graphics g, int xoffset, int yoffset, double zoom, Component obs) {
for (final Board b : boards) {
final Point p = getLocation(b, zoom);
p.translate(xoffset, yoffset);
b.draw(g, p.x, p.y, zoom, obs);
}
}
/**
* Repaint the given area, specified in map coordinates
* @param r Rectangle specifying region to repaint in map coordinates
*/
public void repaint(Rectangle r) {
r.setLocation(mapToComponent(new Point(r.x, r.y)));
r.setSize((int) (r.width * getZoom()), (int) (r.height * getZoom()));
theMap.repaint(r.x, r.y, r.width, r.height);
}
/**
* @param show if true, enable drawing of {@link GamePiece}s. If false, don't draw any {@link GamePiece}s when painting the map
*/
public void setPiecesVisible(boolean show) {
hideCounters = !show;
}
/**
* @return true if {@link GamePiece}s should be drawn when painting the map
*/
public boolean isPiecesVisible() {
return !hideCounters && pieceOpacity != 0;
}
/**
* @return current pieceOpacity for drawing
*/
public float getPieceOpacity() {
return pieceOpacity;
}
/**
* @param pieceOpacity sets opacity for piece drawing, 0 to 1.0
*/
public void setPieceOpacity(float pieceOpacity) {
this.pieceOpacity = pieceOpacity;
}
/**
* Gets the value of a map-level global property. If a "Global Property" entry is not found at the map
* level, then module-level properties are checked, which includes identification information for the
* local player.
* @param key identifies the global property to be returned
* @return value of designated global property
*/
@Override
public Object getProperty(Object key) {
final Object value;
final MutableProperty p = propsContainer.getMutableProperty(String.valueOf(key));
if (p != null) {
value = p.getPropertyValue();
}
else {
value = GameModule.getGameModule().getProperty(key);
}
return value;
}
/**
* Gets the value of map-level global property, or a module-level one if a map-level one is not found.
* The localized aspect presently only applies to permanent module-level objects which can be localized (e.g. player sides)
* @param key Name of the property to get the value of
* @return Localized/translated name of the named property, if one is available, otherwise returns the non-localized name
*/
@Override
public Object getLocalizedProperty(Object key) {
Object value = null;
final MutableProperty p = propsContainer.getMutableProperty(String.valueOf(key));
if (p != null) {
value = p.getPropertyValue();
}
if (value == null) {
value = GameModule.getGameModule().getLocalizedProperty(key);
}
return value;
}
/**
* Return the apply-on-move key. It may be named, so just return
* the allocated KeyStroke.
* @return apply-on-move keystroke
*/
public KeyStroke getMoveKey() {
return moveKey == null ? null : moveKey.getKeyStroke();
}
/**
* Creates the top-level window for this map. Could be a JDialog or a JFrame depending on whether we are set to
* use a single window or have our own window.
* @return the top-level window containing this map
*/
protected Window createParentFrame() {
if (GlobalOptions.getInstance().isUseSingleWindow()) {
final JDialog d = new JDialog(GameModule.getGameModule().getPlayerWindow());
d.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
d.setTitle(getDefaultWindowTitle());
return d;
}
else {
final JFrame d = new JFrame();
d.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
d.setTitle(getDefaultWindowTitle());
d.setJMenuBar(MenuManager.getInstance().getMenuBarFor(d));
return d;
}
}
/**
* If this map shows with its own special button, it does not dock into the main window. Likewise if we have
* no combined window setting. Otherwise the *first* non-button-launched map we find will be the one we dock.
* @return whether this map should dock into the main window
*/
public boolean shouldDockIntoMainWindow() {
// set to show via a button, or no combined window at all, don't dock
if (useLaunchButton || !GlobalOptions.getInstance().isUseSingleWindow()) {
return false;
}
// otherwise dock if this map is the first not to show via a button
for (final Map m : GameModule.getGameModule().getComponentsOf(Map.class)) {
if (m == this) {
return true;
}
else if (m.shouldDockIntoMainWindow()) {
return false;
}
}
// Module isn't fully built yet, and/or no maps at all in module yet (perhaps THIS map will soon be the first one)
return true;
}
/**
* When a game is started, create a top-level window, if none exists.
* When a game is ended, remove all boards from the map.
* @param show true if a game is starting, false if a game is ending
*
* @see GameComponent
*/
@Override
public void setup(boolean show) {
final GameModule g = GameModule.getGameModule();
if (show) {
if (shouldDockIntoMainWindow()) {
if (splitPane != null) {
final Dimension d = g.getPlayerWindow().getSize();
final Prefs p = Prefs.getGlobalPrefs();
if (Boolean.TRUE.equals(p.getOption(MAIN_WINDOW_REMEMBER).getValue())) {
final int h = (Integer) p.getOption(MAIN_WINDOW_HEIGHT).getValue();
if (h > 0) {
g.getPlayerWindow().setSize(d.width, h);
}
}
else {
g.getPlayerWindow().setSize(d.width, d.height * 3);
}
splitPane.showBottom();
}
if (toolBar.getParent() == null) {
g.getToolBar().addSeparator();
g.getToolBar().add(toolBar);
}
toolBar.setVisible(true);
}
else {
if (SwingUtilities.getWindowAncestor(theMap) == null) {
final Window topWindow = createParentFrame();
topWindow.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
if (useLaunchButton) {
topWindow.setVisible(false);
}
else {
g.getGameState().setup(false);
}
}
});
((RootPaneContainer) topWindow).getContentPane().add("North", getToolBar()); //$NON-NLS-1$
((RootPaneContainer) topWindow).getContentPane().add("Center", layeredPane); //$NON-NLS-1$
topWindow.setSize(600, 400);
final PositionOption option =
new PositionOption(PositionOption.key + getIdentifier(), topWindow);
g.getPrefs().addOption(option);
}
theMap.getTopLevelAncestor().setVisible(!useLaunchButton);
theMap.revalidate();
}
}
else {
pieces.clear();
boards.clear();
if (shouldDockIntoMainWindow()) {
if (splitPane != null) {
splitPane.hideBottom();
final Dimension d = g.getPlayerWindow().getSize();
final Prefs p = Prefs.getGlobalPrefs();
if (Boolean.TRUE.equals(p.getOption(MAIN_WINDOW_REMEMBER).getValue())) {
final int h = (Integer) p.getOption(MAIN_WINDOW_HEIGHT).getValue();
if (h > 0) {
g.getPlayerWindow().setSize(d.width, h / 3);
}
}
else {
g.getPlayerWindow().setSize(d.width, d.height / 3);
}
}
toolBar.setVisible(false);
}
else if (theMap.getTopLevelAncestor() != null) {
theMap.getTopLevelAncestor().setVisible(false);
}
}
getLaunchButton().setEnabled(show);
getLaunchButton().setVisible(useLaunchButton);
}
/**
* As a {@link GameComponent}, Map does not have any action inherently needing to be taken for "restoring" itself for load/save and
* network play purposes (the locations of pieces, etc, are stored in the pieces, and are restored from {@link GameState} in its
* {@link GameState#getRestorePiecesCommand} method, which creates an AddPiece command for each piece). Map's interest in GameComponent
* is entirely for game start/stop purposes (see {@link #setup}, above).
* @return null since no restore command needed.
*/
@Override
public Command getRestoreCommand() {
return null;
}
/**
* @deprecated use {@link #updateTitleBar()}
* @param s String to append to title
*/
@Deprecated(since = "2020-09-16", forRemoval = true)
@SuppressWarnings("unused")
public void appendToTitle(String s) {
// replaced by updateTitleBar()
}
/**
* Updates the title bar of the current window
*/
public void updateTitleBar() {
if (splitPane != null) {
return;
}
final Component c = theMap.getTopLevelAncestor();
if (c instanceof JFrame) {
((JFrame) c).setTitle(getDefaultWindowTitle());
}
if (c instanceof JDialog) {
((JDialog) c).setTitle(getDefaultWindowTitle());
}
}
/**
* @return The correct current default window title
*/
protected String getDefaultWindowTitle() {
if (getLocalizedMapName().length() > 0) {
return GameModule.getGameModule().getWindowTitleString("Map.window_named", getLocalizedMapName()); //$NON-NLS-1$
}
else {
return GameModule.getGameModule().getWindowTitleString("Map.window", GameModule.getGameModule().getLocalizedGameName()); //$NON-NLS-1$
}
}
/**
* Use the provided {@link PieceFinder} instance to locate a visible piece at the given location
* @param pt Point at which to find visible pieces
* @param finder PieceFinder to use
* @return a visible piece at the given location, or null if none.
*/
public GamePiece findPiece(Point pt, PieceFinder finder) {
final GamePiece[] stack = pieces.getPieces();
for (int i = stack.length - 1; i >= 0; --i) {
final GamePiece p = finder.select(this, stack[i], pt);
if (p != null) {
return p;
}
}
return null;
}
/**
* Use the provided {@link PieceFinder} instance to locate any piece at the given location, regardless of whether it
* is visible or not.
* @param pt Point at which to find pieces
* @param finder PieceFinder to use
* @return a piece at the given location, regardless of visibility, or null if none.
*/
public GamePiece findAnyPiece(Point pt, PieceFinder finder) {
final GamePiece[] stack = pieces.getAllPieces();
// Our piece collection is provided to us in "draw order", in other words "back-to-front", which means
// that we need to iterate backwards to prioritize checking pieces that are visually "in front of" others.
for (int i = stack.length - 1; i >= 0; --i) {
final GamePiece p = finder.select(this, stack[i], pt);
if (p != null) {
return p;
}
}
return null;
}
/**
* Place a piece at the destination point. If necessary, remove the piece from its parent Stack or Map
* @param piece GamePiece to place
* @param pt location to place the piece
*
* @return a {@link Command} that reproduces this action
*/
public Command placeAt(GamePiece piece, Point pt) {
final Command c;
if (GameModule.getGameModule().getGameState().getPieceForId(piece.getId()) == null) {
piece.setPosition(pt);
addPiece(piece);
GameModule.getGameModule().getGameState().addPiece(piece);
c = new AddPiece(piece);
}
else {
final MoveTracker tracker = new MoveTracker(piece);
piece.setPosition(pt);
addPiece(piece);
c = tracker.getMoveCommand();
}
return c;
}
/**
* Attempts to apply the provided {@link PieceVisitorDispatcher} to all pieces on this map, until it finds one
* that returns a non-null Command.
* @return the first non-null {@link Command} returned by <code>commandFactory</code>
*
* @param commandFactory The PieceVisitorDispatcher to apply
*/
public Command apply(PieceVisitorDispatcher commandFactory) {
final GamePiece[] stack = pieces.getPieces();
Command c = null;
for (int i = 0; i < stack.length && c == null; ++i) {
c = (Command) commandFactory.accept(stack[i]);
}
return c;
}
/**
* Move a piece to the destination point. If a piece is at the point (i.e. has a location exactly equal to it), merge
* into a {@link Stack} with the piece by forwarding to {@link StackMetrics#merge}. Otherwise, place by forwarding to placeAt()
* @param p GamePiece to place/merge
* @param pt Point location on the map to place/merge the piece.
* @return a {@link Command} that will duplicate this action on other clients
*
* @see StackMetrics#merge
*/
public Command placeOrMerge(final GamePiece p, final Point pt) {
Command c = apply(new DeckVisitorDispatcher(new Merger(this, pt, p)));
if (c == null || c.isNull()) {
c = placeAt(p, pt);
// If no piece at destination and this is a stacking piece, create
// a new Stack containing the piece
if (!(p instanceof Stack) &&
!Boolean.TRUE.equals(p.getProperty(Properties.NO_STACK))) {
final Stack parent = getStackMetrics().createStack(p);
if (parent != null) {
c = c.append(placeAt(parent, pt));
}
}
}
return c;
}
/**
* Adds a GamePiece to this map's list of pieces. Removes the piece from its parent Stack and from its current map, if different from
* this map.
* @param p Game Piece to add
*/
public void addPiece(GamePiece p) {
if (indexOf(p) < 0) {
if (p.getParent() != null) {
p.getParent().remove(p);
p.setParent(null);
}
if (p.getMap() != null && p.getMap() != this) {
p.getMap().removePiece(p);
}
pieces.add(p);
p.setMap(this);
theMap.repaint();
}
}
/**
* Reorder the argument GamePiece to the new index. When painting the map, pieces are drawn in order of index
*
* @deprecated use {@link PieceCollection#moveToFront}
*/
@SuppressWarnings("unused")
@Deprecated(since = "2020-08-05", forRemoval = true)
public void reposition(GamePiece s, int pos) {
ProblemDialog.showDeprecated("2020-08-05"); //NON-NLS
}
/**
* Returns the index of a piece. When painting the map, pieces are drawn in order of index Return -1 if the piece is
* not on this map
* @param s GamePiece to find the index of
* @return index of the piece on the map, or -1 if the piece is not on this map
*/
public int indexOf(GamePiece s) {
return pieces.indexOf(s);
}
/**
* Removes a piece from the map
* @param p GamePiece to remove from map
*/
public void removePiece(GamePiece p) {
pieces.remove(p);
theMap.repaint();
}
/**
* Center the map at given map coordinates within its JScrollPane container
* @param p Point to center
*/
public void centerAt(Point p) {
centerAt(p, 0, 0);
}
/**
* Center the map at the given map coordinates, if the point is not
* already within (dx,dy) of the center.
* @param p point to center
* @param dx x tolerance for nearness to center
* @param dy y tolerance for nearness to center
*/
public void centerAt(Point p, int dx, int dy) {
if (scroll != null) {
p = mapToComponent(p);
final Rectangle r = theMap.getVisibleRect();
r.x = p.x - r.width / 2;
r.y = p.y - r.height / 2;
final Dimension d = getPreferredSize();
if (r.x + r.width > d.width) r.x = d.width - r.width;
if (r.y + r.height > d.height) r.y = d.height - r.height;
r.width = dx > r.width ? 0 : r.width - dx;
r.height = dy > r.height ? 0 : r.height - dy;
theMap.scrollRectToVisible(r);
}
}
/**
* Ensure that the given region (in map coordinates) is visible. Uses player preference
* to determine how sensitive to be about when to re-center.
* @param r Rectangle demarking region to ensure is visible
*/
public void ensureVisible(Rectangle r) {
if (scroll != null) {
final boolean bTriggerRecenter;
final Point p = mapToComponent(r.getLocation());
final Rectangle rCurrent = theMap.getVisibleRect();
final Rectangle rNorecenter = new Rectangle(0, 0);
// If r is already visible decide if unit is close enough to
// border to justify a recenter
// Close enough means a strip of the window along the edges whose
// width is a % of the edge to center of the window
// The % is defined in GlobalOptions.CENTER_ON_MOVE_SENSITIVITY
final double noRecenterPct = (100.0 - GlobalOptions.getInstance().centerOnOpponentsMoveSensitivity()) / 100.0;
// if r is within a band of n%width/height of border, trigger recenter
rNorecenter.width = (int) round(rCurrent.width * noRecenterPct);
rNorecenter.height = (int) round(rCurrent.height * noRecenterPct);
rNorecenter.x = rCurrent.x + round(rCurrent.width - rNorecenter.width) / 2;
rNorecenter.y = rCurrent.y + round(rCurrent.height - rNorecenter.height) / 2;
bTriggerRecenter = p.x < rNorecenter.x || p.x > (rNorecenter.x + rNorecenter.width) ||
p.y < rNorecenter.y || p.y > (rNorecenter.y + rNorecenter.height);
if (bTriggerRecenter) {
r.x = p.x - rCurrent.width / 2;
r.y = p.y - rCurrent.height / 2;
r.width = rCurrent.width;
r.height = rCurrent.height;
final Dimension d = getPreferredSize();
if (r.x + r.width > d.width) r.x = d.width - r.width;
if (r.y + r.height > d.height) r.y = d.height - r.height;
theMap.scrollRectToVisible(r);
}
}
}
/**
* Scrolls the map in the containing JScrollPane.
*
* @param dx number of pixels to scroll horizontally
* @param dy number of pixels to scroll vertically
*/
public void scroll(int dx, int dy) {
Rectangle r = scroll.getViewport().getViewRect();
r.translate(dx, dy);
r = r.intersection(new Rectangle(getPreferredSize()));
theMap.scrollRectToVisible(r);
}
/**
* Gets the generic name for this type of class across all instances of it. Appears
* in the Editor window in [..] as e.g. [Map], [Prototype], etc.
* @return The generic name for this kind of component, i.e. the part appearing [In Brackets] in the Editor's {@link ConfigureTree}.
*/
public static String getConfigureTypeName() {
return Resources.getString("Editor.Map.component_type"); //$NON-NLS-1$
}
/**
* @return the name of this map, for internal purposes
*/
public String getMapName() {
return getConfigureName();
}
/**
* @return the localized name of this map, for display purposes
*/
public String getLocalizedMapName() {
return getLocalizedConfigureName();
}
/**
* @param s Sets the name of the map.
*/
public void setMapName(String s) {
mapName = s;
setConfigureName(mapName);
if (tooltip == null || tooltip.length() == 0) {
getLaunchButton().setToolTipText(s != null ? Resources.getString("Map.show_hide", s) : Resources.getString("Map.show_hide", Resources.getString("Map.map"))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
}
/**
* @return a HelpFile describing how to use and configure this component
*/
@Override
public HelpFile getHelpFile() {
return HelpFile.getReferenceManualPage("Map.html"); //$NON-NLS-1$
}
/**
* @return an array of Strings describing the buildFile (XML) attributes of this component. These strings are used as prompts in the
* Properties window for this object, when the component is configured in the Editor. The order of descriptions should
* be the same as the order of names in {@link AbstractBuildable#getAttributeNames}
* @see AbstractConfigurable
*/
@Override
public String[] getAttributeDescriptions() {
return new String[] {
Resources.getString("Editor.Map.map_name"), //$NON-NLS-1$
Resources.getString("Editor.Map.mark_pieces_moved"), //$NON-NLS-1$
Resources.getString("Editor.Map.mark_unmoved_button_text"), //$NON-NLS-1$
Resources.getString("Editor.Map.mark_unmoved_tooltip_text"), //$NON-NLS-1$
Resources.getString("Editor.Map.mark_unmoved_button_icon"), //$NON-NLS-1$
Resources.getString("Editor.Map.horizontal"), //$NON-NLS-1$
Resources.getString("Editor.Map.vertical"), //$NON-NLS-1$
Resources.getString("Editor.Map.bkgdcolor"), //$NON-NLS-1$
Resources.getString("Editor.Map.multiboard"), //$NON-NLS-1$
Resources.getString("Editor.Map.bc_selected_counter"), //$NON-NLS-1$
Resources.getString("Editor.Map.bt_selected_counter"), //$NON-NLS-1$
Resources.getString("Editor.Map.show_hide"), //$NON-NLS-1$
Resources.getString(Resources.BUTTON_TEXT),
Resources.getString(Resources.TOOLTIP_TEXT),
Resources.getString(Resources.BUTTON_ICON),
Resources.getString(Resources.HOTKEY_LABEL),
Resources.getString("Editor.Map.report_move_within"), //$NON-NLS-1$
Resources.getString("Editor.Map.report_move_to"), //$NON-NLS-1$
Resources.getString("Editor.Map.report_created"), //$NON-NLS-1$
Resources.getString("Editor.Map.report_modified"), //$NON-NLS-1$
Resources.getString("Editor.Map.key_applied_all") //$NON-NLS-1$
};
}
/**
* Lists all the buildFile (XML) attribute names for this component.
* If this component is ALSO an {@link AbstractConfigurable}, then this list of attributes determines the appropriate
* attribute order for {@link AbstractConfigurable#getAttributeDescriptions()} and {@link AbstractConfigurable#getAttributeTypes()}.
* @return a list of all buildFile (XML) attribute names for this component
* @see AbstractBuildable
*/
@Override
public String[] getAttributeNames() {
return new String[] {
NAME,
MARK_MOVED,
MARK_UNMOVED_TEXT,
MARK_UNMOVED_TOOLTIP,
MARK_UNMOVED_ICON,
EDGE_WIDTH,
EDGE_HEIGHT,
BACKGROUND_COLOR,
ALLOW_MULTIPLE,
HIGHLIGHT_COLOR,
HIGHLIGHT_THICKNESS,
USE_LAUNCH_BUTTON,
BUTTON_NAME,
TOOLTIP,
ICON,
HOTKEY,
MOVE_WITHIN_FORMAT,
MOVE_TO_FORMAT,
CREATE_FORMAT,
CHANGE_FORMAT,
MOVE_KEY
};
}
/**
* @return the Class for the buildFile (XML) attributes of this component. Valid classes include: String, Integer, Double, Boolean, Image,
* Color, and KeyStroke, along with any class for which a Configurer exists in VASSAL.configure. The class determines, among other things,
* which type of {@link AutoConfigurer} will be used to configure the attribute when the object is configured in the Editor.
*
* The order of classes should be the same as the order of names in {@link AbstractBuildable#getAttributeNames}
* @see AbstractConfigurable
*/
@Override
public Class<?>[] getAttributeTypes() {
return new Class<?>[] {
String.class,
GlobalOptions.Prompt.class,
String.class,
String.class,
UnmovedIconConfig.class,
Integer.class,
Integer.class,
Color.class,
Boolean.class,
Color.class,
Integer.class,
Boolean.class,
String.class,
String.class,
IconConfig.class,
NamedKeyStroke.class,
MoveWithinFormatConfig.class,
MoveToFormatConfig.class,
CreateFormatConfig.class,
ChangeFormatConfig.class,
NamedKeyStroke.class
};
}
public static final String LOCATION = "location"; //$NON-NLS-1$
public static final String OLD_LOCATION = "previousLocation"; //$NON-NLS-1$
public static final String OLD_MAP = "previousMap"; //$NON-NLS-1$
public static final String MAP_NAME = "mapName"; //$NON-NLS-1$
public static final String PIECE_NAME = "pieceName"; //$NON-NLS-1$
public static final String MESSAGE = "message"; //$NON-NLS-1$
/**
* Autoconfigurer for map's icon used on its launch button
*/
public static class IconConfig implements ConfigurerFactory {
@Override
public Configurer getConfigurer(AutoConfigurable c, String key, String name) {
return new IconConfigurer(key, name, "/images/map.gif"); //$NON-NLS-1$
}
}
/**
* Autoconfigurer for mark-unmoved icon
*/
public static class UnmovedIconConfig implements ConfigurerFactory {
@Override
public Configurer getConfigurer(AutoConfigurable c, String key, String name) {
return new IconConfigurer(key, name, "/images/unmoved.gif"); //$NON-NLS-1$
}
}
/**
* Report format configurer for "moved within map"
*/
public static class MoveWithinFormatConfig implements TranslatableConfigurerFactory {
@Override
public Configurer getConfigurer(AutoConfigurable c, String key, String name) {
return new PlayerIdFormattedStringConfigurer(key, name, new String[] { PIECE_NAME, LOCATION, MAP_NAME, OLD_LOCATION });
}
}
/**
* Report format configurer for "moved to map"
*/
public static class MoveToFormatConfig implements TranslatableConfigurerFactory {
@Override
public Configurer getConfigurer(AutoConfigurable c, String key, String name) {
return new PlayerIdFormattedStringConfigurer(key, name, new String[] { PIECE_NAME, LOCATION, OLD_MAP, MAP_NAME, OLD_LOCATION });
}
}
public static class CreateFormatConfig implements TranslatableConfigurerFactory {
@Override
public Configurer getConfigurer(AutoConfigurable c, String key, String name) {
return new PlayerIdFormattedStringConfigurer(key, name, new String[] { PIECE_NAME, MAP_NAME, LOCATION });
}
}
public static class ChangeFormatConfig implements TranslatableConfigurerFactory {
@Override
public Configurer getConfigurer(AutoConfigurable c, String key, String name) {
return new PlayerIdFormattedStringConfigurer(key, name, new String[] {
MESSAGE,
ReportState.COMMAND_NAME,
ReportState.OLD_UNIT_NAME,
ReportState.NEW_UNIT_NAME,
ReportState.MAP_NAME,
ReportState.LOCATION_NAME });
}
}
public String getCreateFormat() {
if (createFormat != null) {
return createFormat;
}
else {
String val = Resources.getString("Editor.Map.report_created_in_default");
if (!boards.isEmpty()) {
final Board b = boards.get(0);
if (b.getGrid() == null || b.getGrid().getGridNumbering() == null) {
val = ""; //$NON-NLS-1$
}
}
return val;
}
}
/**
* @return "changed on map" format string
*/
public String getChangeFormat() {
return isChangeReportingEnabled() ? changeFormat : "";
}
/**
* @return "moved to map" format string
*/
public String getMoveToFormat() {
if (moveToFormat != null) {
return moveToFormat;
}
else {
String val = Resources.getString("Editor.Map.report_move_to_default");
if (!boards.isEmpty()) {
final Board b = boards.get(0);
if (b.getGrid() == null || b.getGrid().getGridNumbering() != null) {
val = ""; //$NON-NLS-1$
}
}
return val;
}
}
/**
* @return "moved within map" format string
*/
public String getMoveWithinFormat() {
if (moveWithinFormat != null) {
return moveWithinFormat;
}
else {
String val = Resources.getString("Editor.Map.report_move_within_default");
if (!boards.isEmpty()) {
final Board b = boards.get(0);
if (b.getGrid() == null) {
val = ""; //$NON-NLS-1$
}
}
return val;
}
}
/**
* List of subcomponents which can be added to a Map.
*
* @return a list of valid sub-component Classes. If a Class
* appears in this list, then instances of that class may be added
* to this component from the Editor's {@link ConfigureTree} window by
* right-clicking on the component and selecting the appropriate "Add"
* option.
* @see Configurable
*/
@Override
public Class<?>[] getAllowableConfigureComponents() {
return new Class<?>[]{ GlobalMap.class, LOS_Thread.class, ToolbarMenu.class, MultiActionButton.class, HidePiecesButton.class, Zoomer.class,
CounterDetailViewer.class, HighlightLastMoved.class, LayeredPieceCollection.class, ImageSaver.class, TextSaver.class, DrawPile.class, SetupStack.class,
MassKeyCommand.class, MapShader.class, PieceRecenterer.class, Flare.class };
}
/**
* @param name Name (key) of one of this component's attributes
* @return Visibility condition for the corresponding component
*/
@Override
public VisibilityCondition getAttributeVisibility(String name) {
if (visibilityCondition == null) {
visibilityCondition = () -> useLaunchButton;
}
if (List.of(HOTKEY, BUTTON_NAME, TOOLTIP, ICON).contains(name)) {
return visibilityCondition;
}
else if (List.of(MARK_UNMOVED_TEXT, MARK_UNMOVED_ICON, MARK_UNMOVED_TOOLTIP).contains(name)) {
return () -> !GlobalOptions.NEVER.equals(markMovedOption);
}
else {
return super.getAttributeVisibility(name);
}
}
/**
* Each Map must have a unique String id
*
* Sets our unique ID (among Maps), so that e.g. commands sent to different maps don't inadvertently get confused when
* we send commands to other clients.
* @param id Sets our unique ID
*/
@Override
public void setId(String id) {
mapID = id;
}
/**
* Each Map must have a unique String id
*
* @return the id for this map
*/
@Override
public String getId() {
return mapID;
}
/**
* Find the map that corresponds to a known unique id
* @param id unique id of the map to find
* @return Map object corresponding to that unique id
*/
public static Map getMapById(String id) {
return (Map) idMgr.findInstance(id);
}
/**
* Utility method to return a {@link List} of all map components (on all maps!) in the
* module.
*
* @return the list of <code>Map</code>s components
*/
public static List<Map> getMapList() {
final GameModule g = GameModule.getGameModule();
final List<Map> l = g.getComponentsOf(Map.class);
for (final ChartWindow cw : g.getComponentsOf(ChartWindow.class)) {
for (final MapWidget mw : cw.getAllDescendantComponentsOf(MapWidget.class)) {
l.add(mw.getMap());
}
}
return l;
}
/**
* Utility method to return a list of all map components in the module
*
* @return Iterator over all maps
* @deprecated Use {@link #getMapList()} instead.
*/
@Deprecated(since = "2020-08-05", forRemoval = true)
public static Iterator<Map> getAllMaps() {
ProblemDialog.showDeprecated("2020-08-05"); //NON-NLS
return getMapList().iterator();
}
/**
* Find a contained Global Property (variable) by name. Does NOT search at the Module level.
* @param name Name of Global Property to find
* @return Mutable property corresponding to the name given
*/
@Override
public MutableProperty getMutableProperty(String name) {
return propsContainer.getMutableProperty(name);
}
/**
* Adds a new Global Property to this map.
* @param key Name of the new property
* @param p The property object to add
*/
@Override
public void addMutableProperty(String key, MutableProperty p) {
propsContainer.addMutableProperty(key, p);
p.addMutablePropertyChangeListener(repaintOnPropertyChange);
}
/**
* Removes a new Global Property from this map.
* @param key Name of the property to be removed
* @return the object just removed
*/
@Override
public MutableProperty removeMutableProperty(String key) {
final MutableProperty p = propsContainer.removeMutableProperty(key);
if (p != null) {
p.removeMutablePropertyChangeListener(repaintOnPropertyChange);
}
return p;
}
/**
* @return The container ID for map-level Global Properties on this object (just uses the map name)
*/
@Override
public String getMutablePropertiesContainerId() {
return getMapName();
}
/**
* Make a best guess for a unique identifier for the target. Use
* {@link VASSAL.tools.UniqueIdManager.Identifyable#getConfigureName} if non-null, otherwise use
* {@link VASSAL.tools.UniqueIdManager.Identifyable#getId}
*
* @return Unique Identifier
*/
public String getIdentifier() {
return UniqueIdManager.getIdentifier(this);
}
/** @return the Swing component representing the map */
public JComponent getView() {
if (theMap == null) {
theMap = new View(this);
scroll = new AdjustableSpeedScrollPane(
theMap,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll.unregisterKeyboardAction(
KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, 0));
scroll.unregisterKeyboardAction(
KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, 0));
scroll.setAlignmentX(0.0f);
scroll.setAlignmentY(0.0f);
layeredPane.setLayout(new InsetLayout(layeredPane, scroll));
layeredPane.add(scroll, JLayeredPane.DEFAULT_LAYER);
}
return theMap;
}
/** @return the JLayeredPane holding map insets */
public JLayeredPane getLayeredPane() {
return layeredPane;
}
/**
* The Layout responsible for arranging insets which overlay the Map
* InsetLayout currently is responsible for keeping the {@link GlobalMap}
* in the upper-left corner of the {@link Map.View}.
*/
public static class InsetLayout extends OverlayLayout {
private static final long serialVersionUID = 1L;
private final JScrollPane base;
/**
* @param target Component we are to lay out
* @param base JScrollPane for it
*/
public InsetLayout(Container target, JScrollPane base) {
super(target);
this.base = base;
}
/**
* @param target Component to lay out
*/
@Override
public void layoutContainer(Container target) {
super.layoutContainer(target);
base.getLayout().layoutContainer(base);
final Dimension viewSize = base.getViewport().getSize();
final Insets insets = base.getInsets();
viewSize.width += insets.left;
viewSize.height += insets.top;
// prevent non-base components from overlapping the base's scrollbars
final int n = target.getComponentCount();
for (int i = 0; i < n; ++i) {
final Component c = target.getComponent(i);
if (c != base && c.isVisible()) {
final Rectangle b = c.getBounds();
b.width = Math.min(b.width, viewSize.width);
b.height = Math.min(b.height, viewSize.height);
c.setBounds(b);
}
}
}
}
/**
* Implements default logic for merging pieces (into a {@link Stack} or {@link Deck}}
* at a given location within a map Returns a {@link Command} that merges the input
* {@link GamePiece} with an existing piece at the input position, provided the pieces
* are stackable, visible, in the same layer, etc.
*/
public static class Merger implements DeckVisitor {
private final Point pt;
private final Map map;
private final GamePiece p;
/**
* Constructor for a Merger. This is passed the map, location, and piece we are going to be merging into something.
* @param map map
* @param pt point
* @param p piece
*/
public Merger(Map map, Point pt, GamePiece p) {
this.map = map;
this.pt = pt;
this.p = p;
}
/**
* Returns a command that merges our piece into the specified deck, provided that
* the Deck shares the location of our merger point provided in the constructor.
* @param d Deck to consider merging into
* @return A command to merge our piece into the specified deck, or null if deck isn't in correct position
*/
@Override
public Object visitDeck(Deck d) {
if (d.getPosition().equals(pt)) {
return map.getStackMetrics().merge(d, p);
}
else {
return null;
}
}
/**
* Returns a command to merge our piece into the specified stack, provided that the stack is in the precise
* map location specified, the map allows stacking, our piece allows stacking, and our stack & piece are in the
* same layer.
* @param s Stack to consider merging with
* @return Command to merge into the stack, or null if any of the necessary conditions weren't met
*/
@Override
public Object visitStack(Stack s) {
if (s.getPosition().equals(pt) && map.getStackMetrics().isStackingEnabled() && !Boolean.TRUE.equals(p.getProperty(Properties.NO_STACK))
&& s.topPiece() != null && map.getPieceCollection().canMerge(s, p)) { //NOTE: topPiece() returns the top VISIBLE piece (not hidden by Invisible trait)
return map.getStackMetrics().merge(s, p);
}
else {
return null;
}
}
/**
* @return a command to form a new stack with a piece found at the our location, provided all of the conditions to form a
* stack are met. Returns null if the necessary conditions aren't met.
* @param piece piece to consider forming a new stack with.
*/
@Override
public Object visitDefault(GamePiece piece) {
if (piece.getPosition().equals(pt) && map.getStackMetrics().isStackingEnabled() && !Boolean.TRUE.equals(p.getProperty(Properties.NO_STACK))
&& !Boolean.TRUE.equals(piece.getProperty(Properties.INVISIBLE_TO_ME)) && !Boolean.TRUE.equals(piece.getProperty(Properties.NO_STACK))
&& map.getPieceCollection().canMerge(piece, p)) {
return map.getStackMetrics().merge(piece, p);
}
else {
return null;
}
}
}
/**
* The (JPanel-extending) component that represents the map itself
*/
public static class View extends JPanel {
private static final long serialVersionUID = 1L;
protected Map map;
/**
* Create our view
* @param m lets us know what Map we represent
*/
public View(Map m) {
setFocusTraversalKeysEnabled(false);
map = m;
}
/**
* Draw our graphics to the graphics object
* @param g target graphics object
*/
@Override
public void paint(Graphics g) {
// Don't draw the map until the game is updated.
if (GameModule.getGameModule().getGameState().isUpdating()) {
return;
}
final Graphics2D g2d = (Graphics2D) g;
g2d.addRenderingHints(SwingUtils.FONT_HINTS);
final double os_scale = g2d.getDeviceConfiguration().getDefaultTransform().getScaleX();
// HDPI: We may get a transform where scale != 1. This means we
// are running on an HDPI system. We want to draw at the effective
// scale factor to prevent poor quality upscaling, so reset the
// transform to scale of 1 and multiply the map zoom by the OS scaling.
final AffineTransform orig_t = g2d.getTransform();
g2d.setTransform(SwingUtils.descaleTransform(orig_t));
final Rectangle r = map.componentToDrawing(getVisibleRect(), os_scale);
g2d.setColor(map.bgColor);
g2d.fillRect(r.x, r.y, r.width, r.height);
map.paintRegion(g2d, r);
g2d.setTransform(orig_t);
}
/**
* Update our panel (by painting it)
* @param g target graphics object
*/
@Override
public void update(Graphics g) {
// To avoid flicker, don't clear the display first
paint(g);
}
/**
* @return our preferred size will be that of the map.
*/
@Override
public Dimension getPreferredSize() {
return map.getPreferredSize();
}
/** returns the map we're assigned to */
public Map getMap() {
return map;
}
}
/**
* {@link VASSAL.search.SearchTarget}
* @return a list of any Message Format strings referenced in the Configurable, if any (for search)
*/
@Override
public List<String> getFormattedStringList() {
return List.of(moveWithinFormat, moveToFormat, createFormat, changeFormat);
}
/**
* {@link VASSAL.search.SearchTarget}
* @return a list of any Menu/Button/Tooltip Text strings referenced in the Configurable, if any (for search)
*/
@Override
public List<String> getMenuTextList() {
final List<String> l = new ArrayList<>();
if (!GlobalOptions.NEVER.equals(markMovedOption)) {
l.add(markUnmovedText);
l.add(markUnmovedTooltip);
}
if (useLaunchButtonEdit) {
l.add(getAttributeValueString(BUTTON_NAME));
l.add(getAttributeValueString(TOOLTIP));
}
return l;
}
/**
* {@link VASSAL.search.SearchTarget}
* @return a list of any Named KeyStrokes referenced in the Configurable, if any (for search)
*/
@Override
public List<NamedKeyStroke> getNamedKeyStrokeList() {
return Arrays.asList(NamedHotKeyConfigurer.decode(getAttributeValueString(HOTKEY)), moveKey);
}
/**
* In case reports use HTML and refer to any image files
* @param s Collection to add image names to
*/
@Override
public void addLocalImageNames(Collection<String> s) {
HTMLImageFinder h;
h = new HTMLImageFinder(moveWithinFormat);
h.addImageNames(s);
h = new HTMLImageFinder(moveToFormat);
h.addImageNames(s);
h = new HTMLImageFinder(createFormat);
h.addImageNames(s);
h = new HTMLImageFinder(changeFormat);
h.addImageNames(s);
String string;
if (!GlobalOptions.NEVER.equals(markMovedOption)) {
string = getAttributeValueString(MARK_UNMOVED_ICON);
if (string != null) { // Launch buttons sometimes have null icon attributes - yay
s.add(string);
}
}
if (useLaunchButtonEdit) {
string = getLaunchButton().getAttributeValueString(getLaunchButton().getIconAttribute());
if (string != null) { // Launch buttons sometimes have null icon attributes - yay
s.add(string);
}
}
}
} |
package org.shipkit.internal.gradle.git;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.logging.Logger;
import org.gradle.api.logging.Logging;
import org.shipkit.gradle.configuration.ShipkitConfiguration;
import org.shipkit.internal.gradle.configuration.ShipkitConfigurationPlugin;
import java.text.MessageFormat;
/**
* This plugin is used for internal purposes, it does not add any user-visible, public behavior.
* It identifies GitHub repository url and keeps it in the field on this plugin.
* Applies plugins:
* <ul>
* <li>{@link ShipkitConfigurationPlugin}</li>
* </ul>
*/
public class GitAuthPlugin implements Plugin<Project> {
private GitAuth gitAuth;
@Override
public void apply(Project project) {
ShipkitConfiguration conf = project.getPlugins().apply(ShipkitConfigurationPlugin.class).getConfiguration();
String writeToken = conf.getLenient().getGitHub().getWriteAuthToken();
String url = getGitHubUrl(conf.getGitHub().getRepository(), conf);
gitAuth = new GitAuth(url, writeToken);
}
static String getGitHubUrl(String ghRepo, ShipkitConfiguration conf) {
String ghUser = conf.getGitHub().getWriteAuthUser();
String writeToken = conf.getLenient().getGitHub().getWriteAuthToken();
if(writeToken != null) {
return MessageFormat.format("https://{0}:{1}@github.com/{2}.git", ghUser, writeToken, ghRepo);
} else{
return MessageFormat.format("https://github.com/{0}.git", ghRepo);
}
}
public GitAuth getGitAuth(){
return gitAuth;
}
public static class GitAuth{
private final String repositoryUrl;
private final String secretValue;
GitAuth(String repositoryUrl, String secretValue) {
this.repositoryUrl = repositoryUrl;
this.secretValue = secretValue;
}
/**
* Secret value to replace in {@link #repositoryUrl}.
* It may be null if {@link ShipkitConfiguration.GitHub#getWriteAuthToken()} is not specified.
*/
public String getSecretValue() {
return secretValue;
}
public String getRepositoryUrl() {
return repositoryUrl;
}
}
} |
package org.myrobotlab.service;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.alicebot.ab.AIMLMap;
import org.alicebot.ab.AIMLSet;
import org.alicebot.ab.Bot;
import org.alicebot.ab.Category;
import org.alicebot.ab.Chat;
import org.alicebot.ab.MagicBooleans;
import org.alicebot.ab.Predicates;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.ServiceType;
import org.myrobotlab.framework.interfaces.Attachable;
import org.myrobotlab.io.FileIO;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.programab.ChatData;
import org.myrobotlab.programab.MrlSraixHandler;
import org.myrobotlab.programab.OOBPayload;
import org.myrobotlab.service.data.Locale;
import org.myrobotlab.service.interfaces.LocaleProvider;
import org.myrobotlab.service.interfaces.SearchPublisher;
import org.myrobotlab.service.interfaces.SpeechSynthesis;
import org.myrobotlab.service.interfaces.TextListener;
import org.myrobotlab.service.interfaces.TextPublisher;
import org.slf4j.Logger;
public class ProgramAB extends Service implements TextListener, TextPublisher, LocaleProvider {
// Internal class for the program ab response.
public static class Response {
// FIXME - timestamps are usually longs System.currentTimeMillis()
public Date timestamp;
public String botName;
public String userName;
public String msg;
public List<OOBPayload> payloads;
public Response(String userName, String botName, String msg, List<OOBPayload> payloads, Date timestamp) {
this.botName = botName;
this.userName = userName;
this.msg = msg;
this.payloads = payloads;
this.timestamp = timestamp;
}
public String toString() {
StringBuilder str = new StringBuilder();
str.append("[");
str.append("Time:" + timestamp.getTime() + ", ");
str.append("Bot:" + botName + ", ");
str.append("User:" + userName + ", ");
str.append("Msg:" + msg + ", ");
str.append("Payloads:[");
if (payloads != null) {
for (OOBPayload payload : payloads) {
str.append(payload.toString() + ", ");
}
}
str.append("]]");
return str.toString();
}
}
static final long serialVersionUID = 1L;
transient public final static Logger log = LoggerFactory.getLogger(ProgramAB.class);
// TODO: this path is really specific to each bot that is loaded.
// right now there is a requirement that all active bots are loaded from the
// same directory. (defaulting to ProgramAB)
private String path = "ProgramAB";
// bots map is keyed off the lower case version of the bot name.
private transient HashMap<String, Bot> bots = new HashMap<String, Bot>();
// Mapping a bot to a username and chat session
private transient HashMap<String, HashMap<String, ChatData>> sessions = new HashMap<String, HashMap<String, ChatData>>();
// TODO: ProgramAB default bot should be Alice-en_US we should name the rest
// of the language specific default bots.
// initial default values for the current bot/and user
private String currentBotName = "en-US";
// This is the default username that is chatting with the bot.
private String currentUserName = "default";
public int savePredicatesInterval = 300000; // every 5 minutes
// TODO: move the implementation from the gui to this class so it can be used
// across web and swing gui properly.
boolean visualDebug = true;
// TODO: if true, AIML is written back to disk on shutdown of this service.
public boolean writeOnExit = true;
/**
* list of available bots - populated on startup
*/
HashSet<String> availableBots = new HashSet<>();
boolean peerSearch = true;
private Locale locale;
/**
* Default constructor for the program ab service.
*
*
* @param n
* - service name
* @param id
* - process id
*/
public ProgramAB(String n, String id) {
super(n, id);
availableBots = getBots();
addTask("savePredicates", savePredicatesInterval, 0, "savePredicates");
}
public void addOOBTextListener(TextListener service) {
addListener("publishOOBText", service.getName(), "onOOBText");
}
public void addResponseListener(Service service) {
addListener("publishResponse", service.getName(), "onResponse");
}
@Deprecated /* use standard attachTextListener */
public void addTextListener(TextListener service) {
attachTextListener(service);
}
public void addTextListener(SpeechSynthesis service) {
addListener("publishText", service.getName(), "onText");
}
public void addTextPublisher(TextPublisher service) {
subscribe(service.getName(), "publishText");
}
private String createSessionPredicateFilename(String username, String botName) {
// TODO: sanitize the session label so it can be safely used as a filename
String predicatePath = getPath() + File.separator + "bots" + File.separator + botName + File.separator + "config";
// just in case the directory doesn't exist.. make it.
File predDir = new File(predicatePath);
if (!predDir.exists()) {
predDir.mkdirs();
}
predicatePath += File.separator + username + ".predicates.txt";
return predicatePath;
}
public int getMaxConversationDelay() {
return sessions.get(getCurrentBotName()).get(getCurrentUserName()).maxConversationDelay;
}
/**
* This is the main method that will ask for the current bot's chat session to
* respond to It returns a Response object.
*
* @param text
* @return
* @throws IOException
*/
public Response getResponse(String text) throws IOException {
return getResponse(getCurrentUserName(), text);
}
/**
* This method has the side effect of switching which bot your are currently
* chatting with.
*
* @param username
* - the query string to the bot brain
* @param text
* - the user that is sending the query
* @return the response for a user from a bot given the input text.
* @throws IOException
*/
public Response getResponse(String username, String text) throws IOException {
return getResponse(username, getCurrentBotName(), text);
}
/**
* Full get response method . Using this method will update the current
* user/bot name if different from the current session.
*
* @param userName
* @param botName
* @param text
* @return
* @throws IOException
*/
public Response getResponse(String userName, String botName, String text) throws IOException {
return getResponse(userName, botName, text, true);
}
/**
* Gets a response and optionally update if this is the current bot session
* that's active globally.
*
* @param userName
* @param botName
* @param text
* @param updateCurrentSession
* (specify if the currentbot/currentuser name should be updated in
* the programab service.)
* @return
* @throws IOException
*/
public Response getResponse(String userName, String botName, String text, boolean updateCurrentSession) throws IOException {
// error check the input.
log.info("Get Response for : user {} bot {} : {}", userName, botName, text);
if (userName == null || botName == null || text == null) {
String error = "ERROR: Username , botName or text was null. no response.";
error(error);
return new Response(userName, botName, error, null, new Date());
}
// update the current session if we want to change which bot is at
// attention.
if (updateCurrentSession) {
updateCurrentSession(userName, botName);
}
Bot bot = bots.get(botName.toLowerCase());
if (bot == null) {
String error = "ERROR: Core not loaded, please load core before chatting.";
error(error);
return new Response(userName, botName, error, null, new Date());
}
// Auto start a new session from the current path that the programAB service
// is operating out of.
if (!sessions.containsKey(botName) || !sessions.get(botName).containsKey(userName)) {
startSession(getPath(), userName, botName);
}
ChatData chatData = sessions.get(botName).get(userName);
// Get the actual bots aiml based response.
String res = getChat(userName, botName).multisentenceRespond(text);
// grab and update the time when this response came in.
chatData.lastResponseTime = new Date();
// Check the AIML response to see if there is OOB (out of band data)
// If so, process those oob messages.
List<OOBPayload> payloads = null;
if (chatData.processOOB) {
payloads = processOOB(res);
}
// OOB text should not be published as part of the response text.
if (payloads != null) {
res = OOBPayload.removeOOBFromString(res).trim();
}
// create the response object to return
Response response = new Response(userName, botName, res, payloads, chatData.lastResponseTime);
// Now that we've said something, lets create a timer task to wait for N
// seconds
// and if nothing has been said.. try say something else.
// TODO: trigger a task to respond with something again
// if the humans get bored
if (chatData.enableAutoConversation) {
// schedule one future reply. (always get the last word in..)
// int numExecutions = 1;
// TODO: we need a way for the task to just execute one time
// it'd be good to have access to the timer here, but it's transient
addTask("getResponse", chatData.maxConversationDelay, 0, "getResponse", userName, text);
}
// EEK! clean up the API!
invoke("publishRequest", text); // publisher used by uis
invoke("publishResponse", response);
invoke("publishResponseText", response);
invoke("publishText", response.msg);
info("to: {} - {}", userName, res);
return response;
}
private void updateCurrentSession(String userName, String botName) {
// update the current user/bot name..
if (!botName.equals(getCurrentBotName())) {
// update which bot is in the front.. and honestly. we should also set
// which userName is currently talking to the bot.
log.info("Setting {} as the current bot.", botName);
this.setCurrentBotName(botName);
}
if (!userName.equals(getCurrentUserName())) {
// update which bot is in the front.. and honestly. we should also set
// which userName is currently talking to the bot.
log.info("Setting {} user as the currnt user.", userName);
this.setCurrentUserName(userName);
}
}
/**
* This method specifics how many times the robot will respond with the same
* thing before forcing a different (default?) response instead.
*
* @param val
*/
public void repetitionCount(int val) {
org.alicebot.ab.MagicNumbers.repetition_count = val;
}
public Chat getChat(String userName, String botName) {
if (sessions.containsKey(botName) && sessions.get(botName).containsKey(userName)) {
return sessions.get(botName).get(userName).chat;
} else {
warn("%s %S session does not exist", botName, userName);
return null;
}
}
public void removePredicate(String userName, String predicateName) {
removePredicate(userName, getCurrentBotName(), predicateName);
}
public void removePredicate(String userName, String botName, String predicateName) {
Predicates preds = getChat(userName, botName).predicates;
preds.remove(predicateName);
}
/**
* Add a value to a set for the current session
*
* @param setName
* @param setValue
*/
public void addToSet(String setName, String setValue) {
// add to the set for the bot.
Bot bot = bots.get(getCurrentBotName().toLowerCase());
AIMLSet updateSet = bot.setMap.get(setName);
setValue = setValue.toUpperCase().trim();
if (updateSet != null) {
updateSet.add(setValue);
// persist to disk.
updateSet.writeAIMLSet();
} else {
log.info("Unknown AIML set: {}. A new set will be created. ", setName);
// TODO: should we create a new set ? or just log this warning?
// The AIML Set doesn't exist. Lets create a new one
AIMLSet newSet = new AIMLSet(setName, bot);
newSet.add(setValue);
newSet.writeAIMLSet();
}
}
/**
* Add a map / value for the current session
*
* @param mapName
* - the map name
* @param key
* - the key
* @param value
* - the value
*/
public void addToMap(String mapName, String key, String value) {
// add an entry to the map.
Bot bot = bots.get(getCurrentBotName().toLowerCase());
AIMLMap updateMap = bot.mapMap.get(mapName);
key = key.toUpperCase().trim();
if (updateMap != null) {
updateMap.put(key, value);
// persist to disk!
updateMap.writeAIMLMap();
} else {
log.info("Unknown AIML map: {}. A new MAP will be created. ", mapName);
// dynamically create new maps?!
AIMLMap newMap = new AIMLMap(mapName, bot);
newMap.put(key, value);
newMap.writeAIMLMap();
}
}
public void setPredicate(String predicateName, String predicateValue) {
setPredicate(getCurrentUserName(), predicateName, predicateValue);
}
public void setPredicate(String username, String predicateName, String predicateValue) {
setPredicate(username, getCurrentBotName(), predicateName, predicateValue);
}
public void setPredicate(String username, String botName, String predicateName, String predicateValue) {
Predicates preds = getChat(username, botName).predicates;
preds.put(predicateName, predicateValue);
}
@Deprecated
public void unsetPredicate(String username, String predicateName) {
removePredicate(username, getCurrentBotName(), predicateName);
}
public String getPredicate(String predicateName) {
return getPredicate(getCurrentUserName(), predicateName);
}
public String getPredicate(String username, String predicateName) {
return getPredicate(username, getCurrentBotName(), predicateName);
}
public String getPredicate(String username, String botName, String predicateName) {
Predicates preds = getChat(username, botName).predicates;
return preds.get(predicateName);
}
/**
* Only respond if the last response was longer than delay ms ago
*
* @param userName
* - current username
* @param text
* - text to get a response
* @param delay
* - min amount of time that must have transpired since the last
* @return the response
* @throws IOException
*/
public Response getResponse(String userName, String text, Long delay) throws IOException {
ChatData chatData = sessions.get(getCurrentBotName()).get(userName);
long delta = System.currentTimeMillis() - chatData.lastResponseTime.getTime();
if (delta > delay) {
return getResponse(userName, text);
} else {
log.info("Skipping response, minimum delay since previous response not reached.");
return null;
}
}
public boolean isEnableAutoConversation() {
return sessions.get(getCurrentBotName()).get(getCurrentUserName()).enableAutoConversation;
}
public boolean isProcessOOB() {
return sessions.get(getCurrentBotName()).get(getCurrentUserName()).processOOB;
}
/**
* Return a list of all patterns that the current AIML Bot knows to match
* against.
*
* @param botName
* the bots name from which to return it's patterns.
* @return a list of all patterns loaded into the aiml brain
*/
public ArrayList<String> listPatterns(String botName) {
ArrayList<String> patterns = new ArrayList<String>();
Bot bot = bots.get(botName.toLowerCase());
for (Category c : bot.brain.getCategories()) {
patterns.add(c.getPattern());
}
return patterns;
}
/**
* Return the number of milliseconds since the last response was given -1 if a
* response has never been given.
*
* @return milliseconds
*/
public long millisecondsSinceLastResponse() {
ChatData chatData = sessions.get(getCurrentBotName()).get(getCurrentUserName());
if (chatData.lastResponseTime == null) {
return -1;
}
long delta = System.currentTimeMillis() - chatData.lastResponseTime.getTime();
return delta;
}
@Override
public void onText(String text) throws IOException {
getResponse(text);
// TODO: should we publish the response here?
}
private List<OOBPayload> processOOB(String text) {
// Find any oob tags
ArrayList<OOBPayload> payloads = OOBPayload.extractOOBPayloads(text, this);
// invoke them all.
for (OOBPayload payload : payloads) {
// assumption is this is non blocking invoking!
boolean oobRes = OOBPayload.invokeOOBPayload(payload, getName(), false);
if (!oobRes) {
// there was a failure invoking
log.warn("Failed to invoke OOB/MRL tag : {}", OOBPayload.asOOBTag(payload));
}
}
if (payloads.size() > 0) {
return payloads;
} else {
return null;
}
}
/*
* If a response comes back that has an OOB Message, publish that separately
*/
public String publishOOBText(String oobText) {
return oobText;
}
/**
* publish a response generated from a session in the programAB service.
*
* @param response
* @return
*/
public Response publishResponse(Response response) {
return response;
}
/**
* Test only publishing point - for simple consumers
*/
public String publishResponseText(Response response) {
return response.msg;
}
@Override
public String publishText(String text) {
// TODO: this should not be done here.
// clean up whitespaces & cariage return
text = text.replaceAll("\\n", " ");
text = text.replaceAll("\\r", " ");
text = text.replaceAll("\\s{2,}", " ");
return text;
}
public String publishRequest(String text) {
return text;
}
public void reloadSession(String userName, String botName) throws IOException {
reloadSession(getPath(), userName, botName);
}
/**
* This method will close the current bot, and reload it from AIML It then
* will then re-establish only the session associated with userName.
*
* @param path
* @param userName
* @param botName
* @throws IOException
*/
public void reloadSession(String path, String userName, String botName) throws IOException {
if (sessions.containsKey(botName) && sessions.get(botName).containsKey(userName)) {
// TODO: will garbage collection clean up the bot now ?
// Or are there other handles to it?
sessions.get(botName).remove(userName);
log.info("{} session removed", sessions);
}
// reloading a session means to remove restart the bot and then start the
// session.
bots.remove(botName.toLowerCase());
startSession(path, userName, botName);
// Set<String> userSessions = sessions.get(botName).keySet();
// TODO: we should make sure we keep the same path as before.
// for (String user : userSessions ) {
// startSession(path, user, getCurrentBotName());
}
/**
* Persist the predicates for all known sessions in the robot.
*
*/
public void savePredicates() throws IOException {
for (String botName : sessions.keySet()) {
// TODO: gael is seeing an exception here.. only was is if botName doesn't
// have any sessions.
if (sessions.containsKey(botName)) {
for (String userName : sessions.get(botName).keySet()) {
savePredicates(botName, userName);
}
} else {
log.warn("Bot {} had no sessions to save predicates for.", botName);
}
}
log.info("Done saving predicates.");
}
private void savePredicates(String botName, String userName) throws IOException {
String sessionPredicateFilename = createSessionPredicateFilename(userName, botName);
log.info("Bot : {} User : {} Predicates Filename : {} ", botName, userName, sessionPredicateFilename);
File sessionPredFile = new File(sessionPredicateFilename);
// if the file doesn't exist.. we should create it.. (and make the
// directories for it.)
if (!sessionPredFile.getParentFile().exists()) {
// create the directory.
log.info("Creating the directory {}", sessionPredFile.getParentFile());
sessionPredFile.getParentFile().mkdirs();
}
Chat chat = getChat(userName, botName);
// overwrite the original file , this should always be a full set.
log.info("Writing predicate file for session {} {}", botName, userName);
StringBuilder sb = new StringBuilder();
for (String predicate : chat.predicates.keySet()) {
String value = chat.predicates.get(predicate);
sb.append(predicate + ":" + value + "\n");
}
FileWriter predWriter = new FileWriter(sessionPredFile, false);
BufferedWriter bw = new BufferedWriter(predWriter);
bw.write(sb.toString());
bw.close();
log.info("Saved predicates to file {}", sessionPredFile.getAbsolutePath());
}
public void setEnableAutoConversation(boolean enableAutoConversation) {
sessions.get(getCurrentBotName()).get(getCurrentUserName()).enableAutoConversation = enableAutoConversation;
}
public void setMaxConversationDelay(int maxConversationDelay) {
sessions.get(getCurrentBotName()).get(getCurrentUserName()).maxConversationDelay = maxConversationDelay;
}
public void setProcessOOB(boolean processOOB) {
sessions.get(getCurrentBotName()).get(getCurrentUserName()).processOOB = processOOB;
}
public void startSession() throws IOException {
startSession(currentUserName);
}
public void startSession(String username) throws IOException {
startSession(username, getCurrentBotName());
}
public void startSession(String username, String botName) throws IOException {
startSession(getPath(), username, botName);
}
public void startSession(String path, String userName, String botName) throws IOException {
startSession(path, userName, botName, MagicBooleans.defaultLocale);
}
/**
* Load the AIML 2.0 Bot config and start a chat session. This must be called
* after the service is created.
*
* @param path
* - he path to the ProgramAB directory where the bots aiml resides
* @param userName
* - The new user name
* @param botName
* - The name of the bot to load. (example: alice2)
* @param locale
* - The locale of the bot to ensure the aiml is loaded (mostly for
* Japanese support)
* @throws IOException
*/
public void startSession(String path, String userName, String botName, java.util.Locale locale) throws IOException {
// if update the current user/bot name globally. (bring this bot/user
// session to attention.)
log.info("Start Session Path: {} User: {} Bot: {} Locale: {}", path, userName, botName, locale);
File check = new File(path + fs + "bots" + fs + botName);
if (!check.exists() || !check.isDirectory()) {
String invalid = String.format("%s could not load aiml. %s is not a valid bot directory", getName(), check.getAbsolutePath());
error(invalid);
throw new IOException(invalid);
}
updateCurrentSession(userName, botName);
// Session is between a user and a bot. key is compound.
if (sessions.containsKey(botName) && sessions.get(botName).containsKey(userName)) {
info("Session %s %s already created", botName, userName);
return;
}
setReady(false);
info("Starting chat session path: %s username: %s botname: %s", path, userName, botName);
setPath(path);
setCurrentBotName(botName);
setCurrentUserName(userName);
// check if we've already started this bot.
Bot bot = bots.get(botName.toLowerCase());
if (bot == null) {
// create a new bot if we haven't started it yet.
bot = new Bot(botName, path, locale);
// Hijack all the SRAIX requests and implement them as a synchronous call
// a service to return a string response for programab...
bot.setSraixHandler(new MrlSraixHandler(this));
// put the bot into the bots map/cache referenced by it's lowercase
// botName.
bots.put(botName.toLowerCase(), bot);
}
// create a chat session from the bot.
Chat chat = new Chat(bot);
// load session specific predicates, these override the default ones.
String sessionPredicateFilename = createSessionPredicateFilename(userName, botName);
chat.predicates.getPredicateDefaults(sessionPredicateFilename);
if (!sessions.containsKey(botName)) {
// initialize the sessions for this bot
HashMap<String, ChatData> newSet = new HashMap<String, ChatData>();
sessions.put(botName, newSet);
}
// put the current user session in the sessions map (overwrite if it was
// already there.
sessions.get(botName).put(userName, new ChatData(chat));
initializeChatSession(userName, botName, chat);
// this.currentBotName = botName;
log.info("Started session for bot name:{} , username:{}", botName, userName);
setReady(true);
}
private void initializeChatSession(String userName, String botName, Chat chat) {
// lets test if the robot knows the name of the person in the session
String name = chat.predicates.get("name").trim();
// TODO: this implies that the default value for "name" is default
// "Friend"
if (name == null || "Friend".equalsIgnoreCase(name) || "unknown".equalsIgnoreCase(name)) {
// TODO: find another interface that's simpler to use for this
// create a string that represents the predicates file
String inputPredicateStream = "name:" + userName;
// load those predicates
chat.predicates.getPredicateDefaultsFromInputStream(FileIO.toInputStream(inputPredicateStream));
}
// TODO move this inside high level :
// it is used to know the last username...
if (sessions.get(botName).containsKey("default") && !userName.equals("default")) {
setPredicate("default", "lastUsername", userName);
// robot surname is stored inside default.predicates, not inside
// system.prop
setPredicate(userName, "botname", getPredicate("default", "botname"));
try {
savePredicates();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void addCategory(Category c) {
Bot bot = bots.get(getCurrentBotName().toLowerCase());
bot.brain.addCategory(c);
}
public void addCategory(String pattern, String template, String that) {
log.info("Adding category {} to respond with {} for the that context {}", pattern, template, that);
// TODO: expose that / topic / filename?!
int activationCnt = 0;
String topic = "*";
// TODO: what is this used for? can we tell the bot to only write out
// certain aiml files and leave the rest as
// immutable
String filename = "mrl_added.aiml";
// clean the pattern
pattern = pattern.trim().toUpperCase();
Category c = new Category(activationCnt, pattern, that, topic, template, filename);
addCategory(c);
}
public void addCategory(String pattern, String template) {
addCategory(pattern, template, "*");
}
/**
* Use startSession instead.
* @throws IOException
*/
@Deprecated
public boolean setUsername(String username) throws IOException {
startSession(getPath(), username, getCurrentBotName());
return true;
}
public void writeAIML() {
// TODO: revisit this method to make sure
for (Bot bot : bots.values()) {
if (bot != null) {
bot.writeAIMLFiles();
}
}
}
/**
* writeAndQuit will write brain to disk For learn.aiml is concerned
*/
public void writeAndQuit() {
// write out all bots aiml & save all predicates for all sessions?
for (Bot bot : bots.values()) {
if (bot == null) {
log.info("no bot - don't need to write and quit");
continue;
}
try {
savePredicates();
// important to save learnf.aiml
writeAIML();
} catch (IOException e1) {
log.error("saving predicates threw", e1);
}
bot.writeQuit();
}
}
public String setPath(String path) {
if (path != null && !path.equals(this.path)) {
this.path = path;
broadcastState();
}
return this.path;
}
public void setCurrentBotName(String currentBotName) {
this.currentBotName = currentBotName;
broadcastState();
}
public void setVisualDebug(Boolean visualDebug) {
this.visualDebug = visualDebug;
broadcastState();
}
public Boolean getVisualDebug() {
return visualDebug;
}
public void setCurrentUserName(String currentUserName) {
this.currentUserName = currentUserName;
broadcastState();
}
public String getPath() {
return path;
}
public String getCurrentUserName() {
return currentUserName;
}
public String getCurrentBotName() {
return currentBotName;
}
/**
* @return the sessions
*/
public HashMap<String, HashMap<String, ChatData>> getSessions() {
return sessions;
}
/**
* This method can be used to get a listing of all bots available in the bots
* directory.
*
* @return
*/
public HashSet<String> getBots() {
HashSet<String> availableBots = new HashSet<String>();
File programAbDir = new File(String.format("%s%sbots", getPath(), File.separator));
if (!programAbDir.exists() || !programAbDir.isDirectory()) {
log.info("%s does not exist !!!");
} else {
File[] listOfFiles = programAbDir.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
} else if (listOfFiles[i].isDirectory()) {
availableBots.add(listOfFiles[i].getName());
}
}
}
return availableBots;
}
public void attach(Attachable attachable) {
if (attachable instanceof TextPublisher) {
addTextPublisher((TextPublisher) attachable);
} else if (attachable instanceof TextListener) {
addListener("publishText", attachable.getName(), "onText");
} else {
log.error("don't know how to attach a {}", attachable.getName());
}
}
@Override
public void stopService() {
if (writeOnExit) {
writeAndQuit();
}
super.stopService();
}
public boolean setPeerSearch(boolean b) {
peerSearch = b;
return peerSearch;
}
@Override
public void startService() {
super.startService();
if (peerSearch) {
startPeer("search");
}
}
/**
* This static method returns all the details of the class without it having
* to be constructed. It has description, categories, dependencies, and peer
* definitions.
*
* @return ServiceType - returns all the data
*
*/
static public ServiceType getMetaData() {
ServiceType meta = new ServiceType(ProgramAB.class.getCanonicalName());
meta.addDescription("AIML 2.0 Reference interpreter based on Program AB");
meta.addCategory("intelligence");
// FIXME - add Wikipedia local search !!
meta.addPeer("search", "GoogleSearch", "replacement for handling pannous sriax requests");
// TODO: renamed the bots in the program-ab-data folder to prefix them so we
// know they are different than the inmoov bots.
// each bot should have their own name, it's confusing that the inmoov bots
// are named en-US and so are the program ab bots.
meta.addDependency("program-ab", "program-ab-data", "1.1", "zip");
meta.addDependency("program-ab", "program-ab-kw", "0.0.8.4");
meta.addDependency("org.json", "json", "20090211");
// used by FileIO
meta.addDependency("commons-io", "commons-io", "2.5");
// TODO: This is for CJK support in ProgramAB move this into the published
// POM for ProgramAB so they are pulled in transiently.
meta.addDependency("org.apache.lucene", "lucene-analyzers-common", "8.4.1");
meta.addDependency("org.apache.lucene", "lucene-analyzers-kuromoji", "8.4.1");
meta.addCategory("ai", "control");
return meta;
}
public static void main(String args[]) {
LoggingFactory.init("INFO");
Runtime.start("gui", "SwingGui");
Runtime.start("brain", "ProgramAB");
WebGui webgui = (WebGui) Runtime.create("webgui", "WebGui");
webgui.autoStartBrowser(false);
webgui.startService();
}
@Override /* FIXME - just do this once in abstract */
public void attachTextListener(TextListener service) {
if (service == null) {
log.warn("{}.attachTextListener(null)");
return;
}
addListener("publishText", service.getName());
}
@Override
public void attachTextPublisher(TextPublisher service) {
if (service == null) {
log.warn("{}.attachTextPublisher(null)");
return;
}
subscribe(service.getName(), "publishText");
}
public SearchPublisher getSearch() {
return (SearchPublisher)getPeer("search");
}
@Override
public void setLocale(String code) {
this.locale = new Locale(code);
}
@Override
public String getLanguage() {
return locale.getLanguage();
}
@Override
public Locale getLocale() {
return locale;
}
@Override
public Map<String, Locale> getLocales() {
return Locale.getLocaleMap("en-US", "fr-FR", "es-ES", "de-DE", "nl-NL", "ru-RU", "hi-IN","it-IT", "fi-FI","pt-PT");
}
} |
package HxCKDMS.XEnchants.hooks;
import java.lang.reflect.Field;
import java.util.List;
import HxCKDMS.XEnchants.XEnchants;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.effect.EntityLightningBolt;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.entity.projectile.EntityArrow;
import net.minecraft.item.ItemStack;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.DamageSource;
import net.minecraftforge.event.entity.EntityEvent;
import net.minecraftforge.event.entity.living.LivingAttackEvent;
import net.minecraftforge.event.entity.player.ArrowLooseEvent;
public class ArrowEventHookContainer
{
boolean isExplosive = false;
boolean isHoming = false;
boolean isGodly = false;
int explosiveAmount;
int homingAmount;
int godlyAmount;
EntityLiving target;
@SubscribeEvent
public void ArrowLooseEvent(ArrowLooseEvent event){
ItemStack stack = event.bow;
isExplosive = false;
isHoming = false;
isGodly = false;
godlyAmount = EnchantmentHelper.getEnchantmentLevel(XEnchants.ArrowLightning.effectId, stack);
homingAmount = EnchantmentHelper.getEnchantmentLevel(XEnchants.ArrowSeeking.effectId, stack);
explosiveAmount = EnchantmentHelper.getEnchantmentLevel(XEnchants.ArrowExplosive.effectId, stack);
if(explosiveAmount > 0){
isExplosive = true;
}if(homingAmount > 0){
isHoming = true;
}if(godlyAmount > 0){
isGodly = true;
}
}
@SubscribeEvent
public void entityAttacked(LivingAttackEvent event)
{
if(event.entityLiving instanceof EntityLiving){
EntityLiving ent = (EntityLiving) event.entityLiving;
if (event.source.isProjectile() && isExplosive) {
ent.worldObj.createExplosion(ent, ent.posX, ent.posY, ent.posZ, 2.0F * explosiveAmount, true);
} else if (event.source.isProjectile() && isHoming) {
float damage = 6;
ent.attackEntityFrom(DamageSource.generic, damage);
} else if (event.source.isProjectile() && isGodly) {
ent.worldObj.spawnEntityInWorld(new EntityLightningBolt(ent.worldObj, ent.posX, ent.posY, ent.posZ));
}
}
}
@SubscribeEvent
public void arrowInAir(EntityEvent event)
{
if (event.entity instanceof EntityArrow){
EntityArrow arrow = (EntityArrow) event.entity;
if(isHoming) {
if(target == null || target.velocityChanged || !target.canEntityBeSeen(arrow)) {
double posX = arrow.posX;
double posY = arrow.posY;
double posZ = arrow.posZ;
double size = 6 * homingAmount;
double d = -1D;
EntityLiving entityliving = null;
List list = arrow.worldObj.getEntitiesWithinAABB(net.minecraft.entity.EntityLiving.class, arrow.boundingBox.expand(size, size, size));
for (Object aList : list) {
EntityLiving tempEnt = (EntityLiving) aList;
if (tempEnt == arrow.shootingEntity) {
continue;
}
double distance = tempEnt.getDistance(posX, posY, posZ);
if ((size < 0.0D || distance < size * size) && (d == -1D || distance < d) && tempEnt.canEntityBeSeen(arrow)) {
d = distance;
entityliving = tempEnt;
}
}
target = entityliving;
}
if(target != null ){
if(target instanceof EntityLiving) {
double dirX = target.posX - arrow.posX;
double dirY = target.boundingBox.minY + (double) (target.height / 2.0F) - (arrow.posY + (double) (arrow.height / 2.0F));
double dirZ = target.posZ - arrow.posZ;
arrow.setThrowableHeading(dirX, dirY, dirZ, 1.5F, 0.0F);
arrow.setVelocity(dirX*10, dirY*10, dirZ*10);
}
}
}
}
}
} |
package StevenDimDoors.mod_pocketDim.ticking;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.block.BlockContainer;
import net.minecraft.world.ChunkCoordIntPair;
import net.minecraft.world.World;
import net.minecraftforge.common.DimensionManager;
import StevenDimDoors.mod_pocketDim.DDProperties;
/**
* Provides methods for applying Limbo decay. Limbo decay refers to the effect that most blocks placed in Limbo
* naturally change into stone, then cobble, then gravel, and finally Unraveled Fabric as time passes.
*/
public class LimboDecay implements IRegularTickReceiver {
private static final int MAX_DECAY_SPREAD_CHANCE = 100;
private static final int DECAY_SPREAD_CHANCE = 50;
private static final int CHUNK_SIZE = 16;
private static final int SECTION_HEIGHT = 16;
private static final int LIMBO_DECAY_INTERVAL = 10; //Apply spread decay every 10 ticks
//Provides a reversed list of the block IDs that blocks cycle through during decay.
private final int[] decaySequence;
private final Random random;
private final DDProperties properties;
private final int[] blocksImmuneToDecay;
public LimboDecay(IRegularTickSender tickSender, DDProperties properties)
{
decaySequence = new int[] {
properties.LimboBlockID,
Block.gravel.blockID,
Block.cobblestone.blockID,
Block.stone.blockID
};
blocksImmuneToDecay = new int[] {
properties.LimboBlockID,
properties.PermaFabricBlockID,
properties.TransientDoorID,
properties.DimensionalDoorID,
properties.WarpDoorID,
properties.RiftBlockID,
properties.UnstableDoorID,
properties.GoldenDoorID,
properties.GoldenDimensionalDoorID
};
this.properties = properties;
this.random = new Random();
tickSender.registerForTicking(this, LIMBO_DECAY_INTERVAL, false);
}
/**
* Applies fast Limbo decay periodically.
*/
@Override
public void notifyTick()
{
applyRandomFastDecay();
}
/**
* Checks the blocks orthogonally around a given location (presumably the location of an Unraveled Fabric block)
* and applies Limbo decay to them. This gives the impression that decay spreads outward from Unraveled Fabric.
*/
public void applySpreadDecay(World world, int x, int y, int z)
{
//Check if we randomly apply decay spread or not. This can be used to moderate the frequency of
//full spread decay checks, which can also shift its performance impact on the game.
if (random.nextInt(MAX_DECAY_SPREAD_CHANCE) < DECAY_SPREAD_CHANCE)
{
//Apply decay to the blocks above, below, and on all four sides.
//World.getBlockId() implements bounds checking, so we don't have to worry about reaching out of the world
decayBlock(world, x - 1, y, z);
decayBlock(world, x + 1, y, z);
decayBlock(world, x, y, z - 1);
decayBlock(world, x, y, z + 1);
decayBlock(world, x, y - 1, z);
decayBlock(world, x, y + 1, z);
}
}
/**
* Picks random blocks from each active chunk in Limbo and, if decay is applicable, converts them directly to Unraveled Fabric.
* This decay method is designed to stop players from avoiding Limbo decay by building floating structures.
*/
private void applyRandomFastDecay()
{
int x, y, z;
int sectionY;
int limboHeight;
World limbo = DimensionManager.getWorld(properties.LimboDimensionID);
if (limbo != null)
{
limboHeight = limbo.getHeight();
//Obtain the coordinates of active chunks in Limbo. For each section of each chunk,
//pick a random block and try to apply fast decay.
for (Object coordObject : limbo.activeChunkSet)
{
ChunkCoordIntPair chunkCoord = (ChunkCoordIntPair) coordObject;
//Loop through each chunk section and fast-decay a random block
//Apply the changes using the world object instead of directly to the chunk so that clients are always notified.
for (sectionY = 0; sectionY < limboHeight; sectionY += SECTION_HEIGHT)
{
x = chunkCoord.chunkXPos * CHUNK_SIZE + random.nextInt(CHUNK_SIZE);
z = chunkCoord.chunkZPos * CHUNK_SIZE + random.nextInt(CHUNK_SIZE);
y = sectionY + random.nextInt(SECTION_HEIGHT);
decayBlockFast(limbo, x, y, z);
}
}
}
}
/**
* Checks if a block can be decayed and, if so, changes it directly into Unraveled Fabric.
*/
private boolean decayBlockFast(World world, int x, int y, int z)
{
int blockID = world.getBlockId(x, y, z);
if (canDecayBlock(blockID))
{
world.setBlock(x, y, z, properties.LimboBlockID);
return true;
}
return false;
}
/**
* Checks if a block can be decayed and, if so, changes it to the next block ID along the decay sequence.
*/
private boolean decayBlock(World world, int x, int y, int z)
{
int index;
int blockID = world.getBlockId(x, y, z);
if (canDecayBlock(blockID))
{
//Loop over the block IDs that decay can go through.
//Find an index matching the current blockID, if any.
for (index = 0; index < decaySequence.length; index++)
{
if (decaySequence[index] == blockID)
{
break;
}
}
//Since the decay sequence is a reversed list, the block ID in the index before our match
//is the block ID we should change this block into. A trick in this approach is that if
//we loop over the array without finding a match, then (index - 1) will contain the
//last ID in the array, which is the first one that all blocks decay into.
//We assume that Unraveled Fabric is NOT decayable. Otherwise, this will go out of bounds!
world.setBlock(x, y, z, decaySequence[index - 1]);
return true;
}
return false;
}
/**
* Checks if a block can decay. We will not decay air, certain DD blocks, or containers.
*/
private boolean canDecayBlock(int blockID)
{
if (blockID == 0)
{
return false;
}
for (int k = 0; k < blocksImmuneToDecay.length; k++)
{
if (blockID == blocksImmuneToDecay[k])
{
return false;
}
}
Block block = Block.blocksList[blockID];
return (block == null || !(block instanceof BlockContainer));
}
} |
import com.licel.jcardsim.base.Simulator;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Date;
import javacard.framework.AID;
import javacard.framework.Util;
import javax.smartcardio.CommandAPDU;
import javax.smartcardio.ResponseAPDU;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.ASN1OutputStream;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERBitString;
import org.bouncycastle.asn1.DERNull;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.pkcs.RSAPublicKey;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.Certificate;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.asn1.x509.Time;
import org.bouncycastle.asn1.x509.V1TBSCertificateGenerator;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.asn1.x509.TBSCertificate;
import org.bouncycastle.asn1.x9.X9ObjectIdentifiers;
import org.cryptonit.CryptonitApplet;
/**
* @author Mathias Brossard
*/
class piv {
private static String toHex(String prefix, byte[] bytes) {
StringBuilder sb = new StringBuilder();
sb.append(prefix);
for (int i = 0; i < bytes.length; i++) {
sb.append(String.format("%02x ", bytes[i]));
}
return sb.toString();
}
private static TBSCertificate createTBS(ByteArrayOutputStream bOut, SubjectPublicKeyInfo ski, AlgorithmIdentifier algo) throws IOException {
TBSCertificate tbs = null;
V1TBSCertificateGenerator tbsGen = new V1TBSCertificateGenerator();
tbsGen.setSerialNumber(new ASN1Integer(0x1));
tbsGen.setStartDate(new Time(new Date(100, 01, 01, 00, 00, 00)));
tbsGen.setEndDate(new Time(new Date(130, 12, 31, 23, 59, 59)));
tbsGen.setIssuer(new X500Name("CN=Cryptonit"));
tbsGen.setSubject(new X500Name("CN=Cryptonit"));
tbsGen.setSignature(algo);
tbsGen.setSubjectPublicKeyInfo(ski);
tbs = tbsGen.generateTBSCertificate();
ASN1OutputStream aOut = new ASN1OutputStream(bOut);
aOut.writeObject(tbs);
System.out.println("Build TBS");
System.out.println(toHex(bOut.toByteArray()));
Base64.encode(bOut.toByteArray(), System.out);
System.out.println();
return tbs;
}
private static ResponseAPDU sendAPDU(Simulator simulator, CommandAPDU command) {
ResponseAPDU response;
System.out.println(toHex(" > ", command.getBytes()));
response = new ResponseAPDU(simulator.transmitCommand(command.getBytes()));
System.out.println(toHex(" < ", response.getData())
+ String.format("[sw=%04X l=%d]", response.getSW(), response.getData().length));
return response;
}
public static void main(String[] args) {
ResponseAPDU response;
Simulator simulator = new Simulator();
byte[] arg;
byte[] appletAIDBytes = new byte[]{
(byte) 0xA0, (byte) 0x00, (byte) 0x00, (byte) 0x03,
(byte) 0x08, (byte) 0x00, (byte) 0x00, (byte) 0x10,
(byte) 0x00
};
short sw, le;
AID appletAID = new AID(appletAIDBytes, (short) 0, (byte) appletAIDBytes.length);
simulator.installApplet(appletAID, CryptonitApplet.class);
System.out.println("Select Applet");
response = sendAPDU(simulator, new CommandAPDU(0x00, 0xA4, 0x04, 0x00, new byte[]{
(byte) 0xA0, (byte) 0x00, (byte) 0x00, (byte) 0x03, (byte) 0x08
}));
System.out.println("Management key authentication (part 1)");
response = sendAPDU(simulator, new CommandAPDU(0x00, 0x87, 0x03, 0x9B, new byte[]{
(byte) 0x7C, (byte) 0x02, (byte) 0x80, (byte) 0x00
}));
arg = new byte[]{
(byte) 0x7C, (byte) 0x14,
(byte) 0x80, (byte) 0x08,
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x81, (byte) 0x08,
(byte) 0x2B, (byte) 0x65, (byte) 0x4B, (byte) 0x22, (byte) 0xB2, (byte) 0x2D, (byte) 0x99, (byte) 0x7F
};
SecretKey key = new SecretKeySpec(new byte[]{
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08
}, "DESede");
try {
Cipher cipher = Cipher.getInstance("DESede/ECB/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, key);
cipher.doFinal(response.getData(), 4, 8, arg, 4);
} catch (Exception ex) {
ex.printStackTrace(System.out);
}
System.out.println("Management key authentication (part 2)");
response = sendAPDU(simulator, new CommandAPDU(0x00, 0x87, 0x03, 0x9B, arg));
System.out.println("Generate RSA key (9A)");
response = sendAPDU(simulator, new CommandAPDU(0x00, 0x47, 0x00, 0x9A, new byte[]{
(byte) 0xAC, (byte) 0x03, (byte) 0x80, (byte) 0x01, (byte) 0x07
}));
arg = response.getData();
if (arg.length < 9 || arg[7] != 0x1 || arg[8] != 0x0) {
System.err.println("Error modulus");
return;
}
byte[] n = new byte[257];
byte[] e = new byte[3];
short s = (short) (arg.length - 9);
Util.arrayCopy(arg, (short) 9, n, (short) 1, s);
sw = (short) response.getSW();
le = (short) (sw & 0xFF);
System.out.println("Call GET RESPONSE");
response = sendAPDU(simulator, new CommandAPDU(0x00, 0xC0, 0x00, 0x00, new byte[]{}, le));
arg = response.getData();
if(arg.length < (256 - s)) {
System.err.println("Error remaining modulus");
return;
}
Util.arrayCopy(arg, (short) 0, n, (short) (s + 1), (short) (256 - s));
s = (short) (256 - s);
if (arg[s] != (byte) 0x82 || arg[s + 1] != (byte) 0x3) {
System.err.println("Error exponent");
return;
}
Util.arrayCopy(arg, (short) (s + 2), e, (short) 0, (short) 3);
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
TBSCertificate tbs;
try {
RSAPublicKey rsa_pub = new RSAPublicKey(new BigInteger(n), new BigInteger(e));
AlgorithmIdentifier palgo = new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE),
salgo = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha256WithRSAEncryption, DERNull.INSTANCE);
tbs = createTBS(bOut, new SubjectPublicKeyInfo(palgo, rsa_pub), salgo);
} catch (Exception ex) {
ex.printStackTrace(System.err);
return;
}
byte[] digest = null;
try {
MessageDigest md;
md = MessageDigest.getInstance("SHA-256");
md.update(bOut.toByteArray());
digest = md.digest();
} catch (Exception ex) {
ex.printStackTrace(System.err);
return;
}
System.out.println("Verify PIN");
response = sendAPDU(simulator, new CommandAPDU(0x00, 0x20, 0x00, 0x80, new byte[]{
0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38
}));
/* RSA signature request */
byte[] sig_request = new byte[266], sig_prefix = new byte[]{
(byte) 0x7C, (byte) 0x82, (byte) 0x01, (byte) 0x06,
(byte) 0x82, (byte) 0x00,
(byte) 0x81, (byte) 0x82, (byte) 0x01, (byte) 0x00,
(byte) 0x00, (byte) 0x01
};
Util.arrayFillNonAtomic(sig_request, (short) 0, (short) sig_request.length, (byte) 0xFF);
Util.arrayCopy(sig_prefix, (short) 0, sig_request, (short) 0, (short) sig_prefix.length);
sig_request[sig_request.length - digest.length - 1] = 0x0;
Util.arrayCopy(digest, (short) 0, sig_request, (short) (sig_request.length - digest.length), (short) (digest.length));
System.out.println("RSA signature file (chained APDUs) first command");
arg = Arrays.copyOfRange(sig_request, 0, 255);
response = sendAPDU(simulator, new CommandAPDU(0x10, 0x87, 0x07, 0x9A, arg));
System.out.println("RSA signature file (chained APDUs) second command");
arg = Arrays.copyOfRange(sig_request, 255, sig_request.length);
response = sendAPDU(simulator, new CommandAPDU(0x00, 0x87, 0x07, 0x9A, arg));
arg = response.getData();
byte[] sig = new byte[256];
if (arg.length > 8 && arg[6] == 0x1 && arg[7] == 0x0) {
s = (short) (arg.length - 8);
Util.arrayCopy(arg, (short) 8, sig, (short) 0, s);
} else {
System.err.println("Error in signature");
return;
}
sw = (short) response.getSW();
le = (short) (sw & 0xFF);
System.out.println("Call GET RESPONSE");
response = sendAPDU(simulator, new CommandAPDU(0x00, 0xC0, 0x00, 0x00, new byte[]{}, le));
arg = response.getData();
Util.arrayCopy(arg, (short) 0, sig, s, (short) (256 - s));
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(tbs);
v.add(new AlgorithmIdentifier(PKCSObjectIdentifiers.sha256WithRSAEncryption, DERNull.INSTANCE));
v.add(new DERBitString(sig));
byte [] crt = null;
try {
Certificate c = Certificate.getInstance(new DERSequence(v));
crt = c.getEncoded();
} catch (Exception ex) {
ex.printStackTrace(System.out);
}
byte[] prefix = new byte[]{
(byte) 0x5C, (byte) 0x03, (byte) 0x5F, (byte) 0xC1, (byte) 0x05,
(byte) 0x53, (byte) 0x82
}, postfix = new byte[]{
(byte) 0x71, (byte) 0x01, (byte) 0x00, (byte) 0xFE, (byte) 0x00
};
short len = (short) (prefix.length + crt.length + 6 + postfix.length);
byte[] buffer = new byte[len];
Util.arrayCopy(prefix, (short) 0, buffer, (short) 0, (short) prefix.length);
int off = prefix.length;
buffer[off++] = (byte) (((crt.length + postfix.length + 4) >> 8) & 0xFF);
buffer[off++] = (byte) ((crt.length + postfix.length + 4) & 0xFF);
buffer[off++] = (byte) 0x70;
buffer[off++] = (byte) 0x82;
buffer[off++] = (byte) ((crt.length >> 8) & 0xFF);
buffer[off++] = (byte) (crt.length & 0xFF);
Util.arrayCopy(crt, (short) 0, buffer, (short) off, (short) crt.length);
off += crt.length;
Util.arrayCopy(postfix, (short) 0, buffer, (short) off, (short) postfix.length);
int i = 1, left = buffer.length, sent = 0;
while(left > 0) {
System.out.println(String.format("Uploading certificate part %d", i++));
int cla = (left <= 255) ? 0x00 : 0x10;
int sending = (left <= 255) ? left : 255;
arg = Arrays.copyOfRange(buffer, sent, sent + sending);
response = sendAPDU(simulator, new CommandAPDU(cla, 0xDB, 0x3F, 0xFF, arg));
sent += sending;
left -= sending;
}
System.out.println("Read 0x5FC105 file");
response = sendAPDU(simulator, new CommandAPDU(0x00, 0xCB, 0x3F, 0xFF, new byte[]{
(byte) 0x5C, (byte) 0x03, (byte) 0x5F, (byte) 0xC1, (byte) 0x05
}));
while (((sw = (short) response.getSW()) & 0xFF00) == 0x6100) {
le = (short) (sw & 0xFF);
System.out.println("Call GET RESPONSE");
response = sendAPDU(simulator, new CommandAPDU(0x00, 0xC0, 0x00, 0x00, new byte[]{}, le));
}
System.out.println("Generate EC P256 key (9C)");
response = sendAPDU(simulator, new CommandAPDU(0x00, 0x47, 0x00, 0x9C, new byte[]{
(byte) 0xAC, (byte) 0x03, (byte) 0x80, (byte) 0x01, (byte) 0x11
}));
arg = response.getData();
if (arg.length < 9 || arg[3] != (byte) 0x86 || arg[4] != 0x41) {
System.err.println("Error EC Public key");
return;
}
prefix = new byte[]{
(byte) 0x30, (byte) 0x59, (byte) 0x30, (byte) 0x13, (byte) 0x06,
(byte) 0x07, (byte) 0x2A, (byte) 0x86, (byte) 0x48, (byte) 0xCE,
(byte) 0x3D, (byte) 0x02, (byte) 0x01, (byte) 0x06, (byte) 0x08,
(byte) 0x2A, (byte) 0x86, (byte) 0x48, (byte) 0xCE, (byte) 0x3D,
(byte) 0x03, (byte) 0x01, (byte) 0x07, (byte) 0x03, (byte) 0x42,
(byte) 0x00
};
buffer = new byte[prefix.length + 65];
Util.arrayCopy(prefix, (short) 0, buffer, (short) 0, (short) prefix.length);
Util.arrayCopy(arg, (short) 5, buffer, (short) prefix.length, (short) 65);
bOut = new ByteArrayOutputStream();
try {
ASN1InputStream aIn = new ASN1InputStream(buffer);
ASN1Sequence aSeq = (ASN1Sequence) aIn.readObject();
AlgorithmIdentifier palgo = new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE),
salgo = new AlgorithmIdentifier(X9ObjectIdentifiers.ecdsa_with_SHA1, DERNull.INSTANCE);
tbs = createTBS(bOut, new SubjectPublicKeyInfo(aSeq), salgo);
} catch (Exception ex) {
ex.printStackTrace(System.err);
return;
}
digest = null;
try {
MessageDigest md;
md = MessageDigest.getInstance("SHA1");
md.update(bOut.toByteArray());
digest = md.digest();
} catch (Exception ex) {
ex.printStackTrace(System.err);
return;
}
/* ECDSA signature request */
sig_prefix = new byte[]{
(byte) 0x7C, (byte) 0x18,
(byte) 0x82, (byte) 0x00,
(byte) 0x81, (byte) 0x14,
};
sig_request = new byte[sig_prefix.length + 20];
Util.arrayCopy(sig_prefix, (short) 0, sig_request, (short) 0, (short) sig_prefix.length);
Util.arrayCopy(digest, (short) 0, sig_request, (short) (sig_prefix.length), (short) (digest.length));
System.out.println("EC (9C) signature");
response = sendAPDU(simulator, new CommandAPDU(0x00, 0x87, 0x07, 0x9C, sig_request));
arg = response.getData();
sig = Arrays.copyOfRange(arg, 4, arg.length);
v = new ASN1EncodableVector();
v.add(tbs);
v.add(new AlgorithmIdentifier(X9ObjectIdentifiers.ecdsa_with_SHA1, DERNull.INSTANCE));
v.add(new DERBitString(sig));
crt = null;
try {
Certificate c = Certificate.getInstance(new DERSequence(v));
crt = c.getEncoded();
} catch (Exception ex) {
ex.printStackTrace(System.out);
}
// Writing now to 5FC10A
prefix = new byte[]{
(byte) 0x5C, (byte) 0x03, (byte) 0x5F, (byte) 0xC1, (byte) 0x0A,
(byte) 0x53, (byte) 0x82
};
len = (short) (prefix.length + crt.length + 6 + postfix.length);
buffer = new byte[len];
Util.arrayCopy(prefix, (short) 0, buffer, (short) 0, (short) prefix.length);
off = prefix.length;
buffer[off++] = (byte) (((crt.length + postfix.length + 4) >> 8) & 0xFF);
buffer[off++] = (byte) ((crt.length + postfix.length + 4) & 0xFF);
buffer[off++] = (byte) 0x70;
buffer[off++] = (byte) 0x82;
buffer[off++] = (byte) ((crt.length >> 8) & 0xFF);
buffer[off++] = (byte) (crt.length & 0xFF);
Util.arrayCopy(crt, (short) 0, buffer, (short) off, (short) crt.length);
off += crt.length;
Util.arrayCopy(postfix, (short) 0, buffer, (short) off, (short) postfix.length);
i = 1; left = buffer.length; sent = 0;
while(left > 0) {
System.out.println(String.format("Uploading certificate part %d", i++));
int cla = (left <= 255) ? 0x00 : 0x10;
int sending = (left <= 255) ? left : 255;
arg = Arrays.copyOfRange(buffer, sent, sent + sending);
response = sendAPDU(simulator, new CommandAPDU(cla, 0xDB, 0x3F, 0xFF, arg));
sent += sending;
left -= sending;
}
System.out.println("Read 0x5FC10A file");
response = sendAPDU(simulator, new CommandAPDU(0x00, 0xCB, 0x3F, 0xFF, new byte[]{
(byte) 0x5C, (byte) 0x03, (byte) 0x5F, (byte) 0xC1, (byte) 0x0A
}));
while (((sw = (short) response.getSW()) & 0xFF00) == 0x6100) {
le = (short) (sw & 0xFF);
System.out.println("Call GET RESPONSE");
response = sendAPDU(simulator, new CommandAPDU(0x00, 0xC0, 0x00, 0x00, new byte[]{}, le));
}
System.out.println("Set Card Capabilities Container");
response = sendAPDU(simulator, new CommandAPDU(0x00, 0xDB, 0x3F, 0xFF, new byte[]{
(byte) 0x5C, (byte) 0x03, (byte) 0x5F, (byte) 0xC1, (byte) 0x07,
(byte) 0x53, (byte) 0x33, (byte) 0xF0, (byte) 0x15, (byte) 0xA0,
(byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0x16, (byte) 0xFF,
(byte) 0x02, (byte) 0x30, (byte) 0x1D, (byte) 0x9C, (byte) 0x5D,
(byte) 0xB7, (byte) 0xA3, (byte) 0x87, (byte) 0xF1, (byte) 0xBE,
(byte) 0x25, (byte) 0x1F, (byte) 0xB9, (byte) 0xFB, (byte) 0x1A,
(byte) 0xF1, (byte) 0x01, (byte) 0x21, (byte) 0xF2, (byte) 0x01,
(byte) 0x21, (byte) 0xF3, (byte) 0x00, (byte) 0xF4, (byte) 0x01,
(byte) 0x00, (byte) 0xF5, (byte) 0x01, (byte) 0x10, (byte) 0xF6,
(byte) 0x00, (byte) 0xF7, (byte) 0x00, (byte) 0xFA, (byte) 0x00,
(byte) 0xFB, (byte) 0x00, (byte) 0xFC, (byte) 0x00, (byte) 0xFD,
(byte) 0x00, (byte) 0xFE, (byte) 0x00
}));
System.out.println("Set CHUID");
response = sendAPDU(simulator, new CommandAPDU(0x00, 0xDB, 0x3F, 0xFF, new byte[]{
(byte) 0x5C, (byte) 0x03, (byte) 0x5F, (byte) 0xC1, (byte) 0x02,
(byte) 0x53, (byte) 0x3B, (byte) 0x30, (byte) 0x19, (byte) 0xD4,
(byte) 0xE7, (byte) 0x39, (byte) 0xDA, (byte) 0x73, (byte) 0x9C,
(byte) 0xED, (byte) 0x39, (byte) 0xCE, (byte) 0x73, (byte) 0x9D,
(byte) 0x83, (byte) 0x68, (byte) 0x58, (byte) 0x21, (byte) 0x08,
(byte) 0x42, (byte) 0x10, (byte) 0x84, (byte) 0x21, (byte) 0x38,
(byte) 0x42, (byte) 0x10, (byte) 0xC3, (byte) 0xF5, (byte) 0x34,
(byte) 0x10, (byte) 0xFB, (byte) 0x0C, (byte) 0xB0, (byte) 0x46,
(byte) 0x75, (byte) 0x85, (byte) 0xD3, (byte) 0x8D, (byte) 0xE2,
(byte) 0xA4, (byte) 0x96, (byte) 0x83, (byte) 0x5E, (byte) 0x0D,
(byte) 0xA7, (byte) 0x78, (byte) 0x35, (byte) 0x08, (byte) 0x32,
(byte) 0x30, (byte) 0x33, (byte) 0x30, (byte) 0x30, (byte) 0x31,
(byte) 0x30, (byte) 0x31, (byte) 0x3E, (byte) 0x00, (byte) 0xFE,
(byte) 0x00
}));
}
} |
package org.owasp.dependencycheck;
import java.util.EnumMap;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.owasp.dependencycheck.analyzer.AnalysisException;
import org.owasp.dependencycheck.analyzer.AnalysisPhase;
import org.owasp.dependencycheck.analyzer.Analyzer;
import org.owasp.dependencycheck.analyzer.AnalyzerService;
import org.owasp.dependencycheck.data.CachedWebDataSource;
import org.owasp.dependencycheck.data.UpdateException;
import org.owasp.dependencycheck.data.UpdateService;
import org.owasp.dependencycheck.dependency.Dependency;
import org.owasp.dependencycheck.utils.FileUtils;
/**
* Scans files, directories, etc. for Dependencies. Analyzers are loaded and
* used to process the files found by the scan, if a file is encountered and an
* Analyzer is associated with the file type then the file is turned into a
* dependency.
*
* @author Jeremy Long (jeremy.long@gmail.com)
*/
public class Engine {
/**
* The list of dependencies.
*/
private List<Dependency> dependencies = new ArrayList<Dependency>();
/**
* A Map of analyzers grouped by Analysis phase.
*/
private EnumMap<AnalysisPhase, List<Analyzer>> analyzers =
new EnumMap<AnalysisPhase, List<Analyzer>>(AnalysisPhase.class);
/**
* A set of extensions supported by the analyzers.
*/
private Set<String> extensions = new HashSet<String>();
/**
* Creates a new Engine.
*/
public Engine() {
doUpdates();
loadAnalyzers();
}
/**
* Creates a new Engine.
*
* @param autoUpdate indicates whether or not data should be updated from
* the Internet.
*/
public Engine(boolean autoUpdate) {
if (autoUpdate) {
doUpdates();
}
loadAnalyzers();
}
/**
* Loads the analyzers specified in the configuration file (or system
* properties).
*/
private void loadAnalyzers() {
for (AnalysisPhase phase : AnalysisPhase.values()) {
analyzers.put(phase, new ArrayList<Analyzer>());
}
final AnalyzerService service = AnalyzerService.getInstance();
final Iterator<Analyzer> iterator = service.getAnalyzers();
while (iterator.hasNext()) {
final Analyzer a = iterator.next();
analyzers.get(a.getAnalysisPhase()).add(a);
if (a.getSupportedExtensions() != null) {
extensions.addAll(a.getSupportedExtensions());
}
}
}
/**
* Get the List of the analyzers for a specific phase of analysis.
*
* @param phase the phase to get the configured analyzers.
* @return the analyzers loaded
*/
public List<Analyzer> getAnalyzers(AnalysisPhase phase) {
return analyzers.get(phase);
}
/**
* Get the dependencies identified.
*
* @return the dependencies identified
*/
public List<Dependency> getDependencies() {
return dependencies;
}
/**
* Scans a given file or directory. If a directory is specified, it will be
* scanned recursively. Any dependencies identified are added to the
* dependency collection.
*
* @param path the path to a file or directory to be analyzed.
*/
public void scan(String path) {
final File file = new File(path);
if (file.exists()) {
if (file.isDirectory()) {
scanDirectory(file);
} else {
scanFile(file);
}
}
}
/**
* Recursively scans files and directories. Any dependencies identified are
* added to the dependency collection.
*
* @param dir the directory to scan.
*/
protected void scanDirectory(File dir) {
final File[] files = dir.listFiles();
for (File f : files) {
if (f.isDirectory()) {
scanDirectory(f);
} else {
scanFile(f);
}
}
}
/**
* Scans a specified file. If a dependency is identified it is added to the
* dependency collection.
*
* @param file The file to scan.
*/
protected void scanFile(File file) {
if (!file.isFile()) {
final String msg = String.format("Path passed to scanFile(File) is not a file: %s.", file.toString());
Logger.getLogger(Engine.class.getName()).log(Level.WARNING, msg);
}
final String fileName = file.getName();
final String extension = FileUtils.getFileExtension(fileName);
if (extension != null) {
if (extensions.contains(extension)) {
final Dependency dependency = new Dependency(file);
dependencies.add(dependency);
}
} else {
final String msg = String.format("No file extension found on file '%s'. The file was not analyzed.",
file.toString());
Logger.getLogger(Engine.class.getName()).log(Level.FINEST, msg);
}
}
/**
* Runs the analyzers against all of the dependencies.
*/
public void analyzeDependencies() {
//phase one initialize
for (AnalysisPhase phase : AnalysisPhase.values()) {
final List<Analyzer> analyzerList = analyzers.get(phase);
for (Analyzer a : analyzerList) {
try {
a.initialize();
} catch (Exception ex) {
Logger.getLogger(Engine.class.getName()).log(Level.SEVERE,
"Exception occurred initializing " + a.getName() + ".", ex);
try {
a.close();
} catch (Exception ex1) {
Logger.getLogger(Engine.class.getName()).log(Level.FINER, null, ex1);
}
}
}
}
// analysis phases
for (AnalysisPhase phase : AnalysisPhase.values()) {
final List<Analyzer> analyzerList = analyzers.get(phase);
for (Analyzer a : analyzerList) {
//need to create a copy of the collection because some of the
// analyzers may modify it. This prevents ConcurrentModificationExceptions.
final Set<Dependency> dependencySet = new HashSet<Dependency>();
dependencySet.addAll(dependencies);
for (Dependency d : dependencySet) {
if (a.supportsExtension(d.getFileExtension())) {
try {
a.analyze(d, this);
} catch (AnalysisException ex) {
d.addAnalysisException(ex);
}
}
}
}
}
//close/cleanup
for (AnalysisPhase phase : AnalysisPhase.values()) {
final List<Analyzer> analyzerList = analyzers.get(phase);
for (Analyzer a : analyzerList) {
try {
a.close();
} catch (Exception ex) {
Logger.getLogger(Engine.class.getName()).log(Level.WARNING, null, ex);
}
}
}
}
/**
* Cycles through the cached web data sources and calls update on all of them.
*/
private void doUpdates() {
final UpdateService service = UpdateService.getInstance();
final Iterator<CachedWebDataSource> iterator = service.getDataSources();
while (iterator.hasNext()) {
final CachedWebDataSource source = iterator.next();
try {
source.update();
} catch (UpdateException ex) {
Logger.getLogger(Engine.class.getName()).log(Level.WARNING,
"Unable to update " + source.getClass().getName());
Logger.getLogger(Engine.class.getName()).log(Level.INFO,
"Unable to update details for " + source.getClass().getName(), ex);
}
}
}
/**
* Returns a full list of all of the analyzers. This is useful
* for reporting which analyzers where used.
* @return a list of Analyzers
*/
public List<Analyzer> getAnalyzers() {
final List<Analyzer> ret = new ArrayList<Analyzer>();
for (AnalysisPhase phase : AnalysisPhase.values()) {
final List<Analyzer> analyzerList = analyzers.get(phase);
ret.addAll(analyzerList);
}
return ret;
}
} |
package br.com.rb.marsexpress.model;
public class AcaoMoverParaFrente implements Acao{
@Override
public Posicao executar(Posicao posicao) {
int x = posicao.getX();
int y = posicao.getY();
Direcao direcao = posicao.getDirecao();
if(direcao.equals(Direcao.N)){
y+=1;
}
else if(direcao.equals(Direcao.S)) {
y-=1;
}
else if(direcao.equals(Direcao.E)) {
x+=1;
}
else if(direcao.equals(Direcao.W)) {
x-=1;
}
return new Posicao(x, y, direcao);
}
} |
package ch.rasc.musicsearch.web;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletResponse;
import org.apache.lucene.document.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import ch.rasc.musicsearch.service.IndexService;
@Controller
public class DownloadMusicController {
@Autowired
private Environment environement;
@Autowired
private IndexService indexService;
private boolean xSendFile;
@PostConstruct
public void init() {
Boolean xSendFileProperty = environement.getProperty("xSendFile", Boolean.class);
if (xSendFileProperty != null) {
xSendFile = xSendFileProperty;
} else {
xSendFile = false;
}
}
@RequestMapping("/downloadMusic")
public void download(@RequestParam(value = "docId", required = true) int docId, HttpServletResponse response)
throws IOException {
Document doc = indexService.getIndexSearcher().doc(docId);
if (doc != null) {
Path musicFile = Paths.get(environement.getProperty("musicDir"), doc.get("directory"), doc.get("fileName"));
String contentType = Files.probeContentType(musicFile);
response.setContentType(contentType);
if (xSendFile) {
String redirectUrl = environement.getProperty("xSendFileContext") + "/" + doc.get("directory") + "/" + doc.get("fileName");
response.setHeader("X-Accel-Redirect", redirectUrl);
} else {
response.setContentLength((int) Files.size(musicFile));
try (OutputStream out = response.getOutputStream()) {
Files.copy(musicFile, out);
}
}
}
}
} |
package cn.momia.wap.web.ctrl.subject;
import cn.momia.common.api.http.MomiaHttpResponse;
import cn.momia.wap.web.ctrl.AbstractController;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
@Controller
public class SubjectController extends AbstractController {
@RequestMapping(value = "/subjectdetail", method = RequestMethod.GET)
public ModelAndView subject(@RequestParam long id) {
MomiaHttpResponse resp = get("/v2/subject?id=" + id);
return new ModelAndView("subject/subject", "subject", resp.getData());
}
@RequestMapping(value = "/subject/placeorder", method = RequestMethod.GET)
public ModelAndView placeorder(HttpServletRequest request, @RequestParam long id, @RequestParam(required = false, value = "coid", defaultValue = "0") long courseId) {
String utoken = getUtoken(request);
if (StringUtils.isBlank(utoken)) {
String referer = request.getHeader("Referer");
StringBuffer url = request.getRequestURL().append("?").append(request.getQueryString());
return new ModelAndView("redirect:/auth/login?ref=" + URLEncoder.encode(url.toString()) + "&back=" + URLEncoder.encode(referer));
}
MomiaHttpResponse resp = get("/v2/subject/sku?utoken=" + utoken + "&id=" + id + (courseId > 0 ? "&coid=" + courseId : ""));
JSONObject params = (JSONObject) resp.getData();
if (courseId > 0) params.put("courseOrder", true);
return new ModelAndView("subject/placeorder", "params", params);
}
} |
package org.testng.internal;
import org.testng.ITestClass;
import org.testng.ITestNGMethod;
import org.testng.annotations.ITestAnnotation;
import org.testng.internal.annotations.AnnotationHelper;
import org.testng.internal.annotations.IAnnotationFinder;
import org.testng.xml.XmlClass;
import org.testng.xml.XmlInclude;
import org.testng.xml.XmlTest;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* This class represents a test method.
*
* @author Cedric Beust, May 3, 2004
* @author <a href = "mailto:the_mindstorm@evolva.ro">Alexandru Popescu</a>
*/
public class TestNGMethod extends BaseTestMethod implements Serializable {
private static final long serialVersionUID = -1742868891986775307L;
private int m_threadPoolSize = 0;
private int m_invocationCount = 1;
private int m_successPercentage = 100;
/**
* Constructs a <code>TestNGMethod</code>
*
* @param method
* @param finder
*/
public TestNGMethod(Method method, IAnnotationFinder finder, XmlTest xmlTest, Object instance) {
this(method, finder, true, xmlTest, instance);
}
private TestNGMethod(Method method, IAnnotationFinder finder, boolean initialize,
XmlTest xmlTest, Object instance) {
super(method, finder, instance);
if(initialize) {
init(xmlTest);
}
}
/**
* {@inheritDoc}
*/
@Override
public int getInvocationCount() {
return m_invocationCount;
}
/**
* {@inheritDoc}
*/
@Override
public int getSuccessPercentage() {
return m_successPercentage;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isTest() {
return true;
}
private void ppp(String s) {
System.out.println("[TestNGMethod] " + s);
}
private void init(XmlTest xmlTest) {
setXmlTest(xmlTest);
setInvocationNumbers(xmlTest.getInvocationNumbers(
m_method.getDeclaringClass().getName() + "." + m_method.getName()));
{
ITestAnnotation testAnnotation =
AnnotationHelper.findTest(getAnnotationFinder(), m_method.getMethod());
if (testAnnotation == null) {
// Try on the class
testAnnotation = AnnotationHelper.findTest(getAnnotationFinder(), m_method.getDeclaringClass());
}
if (null != testAnnotation) {
setTimeOut(testAnnotation.getTimeOut());
m_successPercentage = testAnnotation.getSuccessPercentage();
setInvocationCount(testAnnotation.getInvocationCount());
setThreadPoolSize(testAnnotation.getThreadPoolSize());
setAlwaysRun(testAnnotation.getAlwaysRun());
setDescription(findDescription(testAnnotation, xmlTest));
setEnabled(testAnnotation.getEnabled());
setRetryAnalyzer(testAnnotation.getRetryAnalyzer());
setSkipFailedInvocations(testAnnotation.skipFailedInvocations());
setInvocationTimeOut(testAnnotation.invocationTimeOut());
setIgnoreMissingDependencies(testAnnotation.ignoreMissingDependencies());
setPriority(testAnnotation.getPriority());
}
// Groups
{
initGroups(ITestAnnotation.class);
}
}
}
private String findDescription(ITestAnnotation testAnnotation, XmlTest xmlTest) {
String result = testAnnotation.getDescription();
if (result == null) {
List<XmlClass> classes = xmlTest.getXmlClasses();
for (XmlClass c : classes) {
if (c.getName().equals(m_method.getMethod().getDeclaringClass().getName())) {
for (XmlInclude include : c.getIncludedMethods()) {
if (include.getName().equals(m_method.getName())) {
result = include.getDescription();
if (result != null) {
break;
}
}
}
}
}
}
return result;
}
/**
* {@inheritDoc}
*/
@Override
public int getThreadPoolSize() {
return m_threadPoolSize;
}
/**
* Sets the number of threads on which this method should be invoked.
*/
@Override
public void setThreadPoolSize(int threadPoolSize) {
m_threadPoolSize = threadPoolSize;
}
/**
* Sets the number of invocations for this method.
*/
@Override
public void setInvocationCount(int counter) {
m_invocationCount= counter;
}
/**
* Clones the current <code>TestNGMethod</code> and its @BeforeMethod and @AfterMethod methods.
* @see org.testng.internal.BaseTestMethod#clone()
*/
@Override
public BaseTestMethod clone() {
TestNGMethod clone= new TestNGMethod(getMethod(), getAnnotationFinder(), false, getXmlTest(),
getInstance());
ITestClass tc= getTestClass();
NoOpTestClass testClass= new NoOpTestClass(tc);
testClass.setBeforeTestMethods(clone(tc.getBeforeTestMethods()));
testClass.setAfterTestMethod(clone(tc.getAfterTestMethods()));
clone.m_testClass= testClass;
clone.setDate(getDate());
clone.setGroups(getGroups());
clone.setGroupsDependedUpon(getGroupsDependedUpon(), Collections.<String>emptyList());
clone.setMethodsDependedUpon(getMethodsDependedUpon());
clone.setAlwaysRun(isAlwaysRun());
clone.m_beforeGroups= getBeforeGroups();
clone.m_afterGroups= getAfterGroups();
clone.m_currentInvocationCount= m_currentInvocationCount;
clone.setMissingGroup(getMissingGroup());
clone.setThreadPoolSize(getThreadPoolSize());
clone.setDescription(getDescription());
clone.setEnabled(getEnabled());
clone.setParameterInvocationCount(getParameterInvocationCount());
clone.setInvocationCount(getInvocationCount());
clone.m_successPercentage = getSuccessPercentage();
clone.setTimeOut(getTimeOut());
clone.setRetryAnalyzer(getRetryAnalyzer());
clone.setSkipFailedInvocations(skipFailedInvocations());
clone.setInvocationNumbers(getInvocationNumbers());
clone.setPriority(getPriority());
return clone;
}
private ITestNGMethod[] clone(ITestNGMethod[] sources) {
ITestNGMethod[] clones= new ITestNGMethod[sources.length];
for(int i= 0; i < sources.length; i++) {
clones[i]= sources[i].clone();
}
return clones;
}
/** Sorts ITestNGMethod by Class name. */
public static final Comparator<ITestNGMethod> SORT_BY_CLASS =
new Comparator<ITestNGMethod>() {
@Override
public int compare(ITestNGMethod o1, ITestNGMethod o2) {
String c1 = o1.getTestClass().getName();
String c2 = o2.getTestClass().getName();
return c1.compareTo(c2);
}
};
} |
package com.azcltd.fluffycommons.texts;
import android.content.Context;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.style.ClickableSpan;
import android.text.style.MetricAffectingSpan;
import android.util.TypedValue;
import android.view.View;
import com.azcltd.fluffycommons.utils.AppContext;
/**
* SpannableStringBuilder wrapper that allows applying various text styles to single TextView.
* <p/>
* Usage example:<br/>
* <pre>
* CharSequence text = new SpannableBuilder(this)
* .createStyle().setFont("fonts/blessed-day.otf").setColor(Color.RED).setSize(25).apply()
* .append("Part1 ")
* .currentStyle().setColor(Color.GREEN).setUnderline(true).apply()
* .append("Part2 ")
* .createStyle().setColor(Color.BLUE).apply()
* .append("Part3").build();
*
* textView.setText(text);
* </pre>
* <p/>
* In this example: Part1 will use custom font, red color and 25sp font size;
* Part2 will use custom font, green color, 25sp font size and underline;
* Part3 will use blue color only.
*/
public class SpannableBuilder {
private final SpannableStringBuilder mBuilder = new SpannableStringBuilder();
private final Context mAppContext;
private final OnSpanClickListener mClickListener;
private Style mCurrentStyle;
public SpannableBuilder() {
this(AppContext.get());
}
public SpannableBuilder(Context appContext) {
this(appContext, null);
}
public SpannableBuilder(Context appContext, OnSpanClickListener clickListener) {
mAppContext = appContext.getApplicationContext();
mClickListener = clickListener;
}
public Style currentStyle() {
return mCurrentStyle;
}
public Style createStyle() {
return new Style(mAppContext, this);
}
public SpannableBuilder clearStyle() {
mCurrentStyle = null;
return this;
}
public SpannableBuilder append(int stringId) {
return append(stringId, null);
}
public SpannableBuilder append(int stringId, Object clickObject) {
return append(mAppContext.getString(stringId), clickObject);
}
public SpannableBuilder append(CharSequence text) {
return append(text, null);
}
public SpannableBuilder append(CharSequence str, final Object clickObject) {
if (str == null || str.length() == 0) return this;
int length = mBuilder.length();
mBuilder.append(str);
if (clickObject != null && mClickListener != null) {
ClickableSpan clickSpan = new ClickableSpan() {
@Override
public void onClick(View widget) {
mClickListener.onSpanClicked(clickObject);
}
};
mBuilder.setSpan(clickSpan, length, length + str.length(), SpannableStringBuilder.SPAN_INCLUSIVE_EXCLUSIVE);
}
if (mCurrentStyle != null) {
Span span = new Span(mCurrentStyle);
mBuilder.setSpan(span, length, length + str.length(), SpannableStringBuilder.SPAN_INCLUSIVE_EXCLUSIVE);
}
return this;
}
public CharSequence build() {
return mBuilder;
}
private static class Span extends MetricAffectingSpan {
private final Style mStyle;
public Span(Style style) {
mStyle = style.clone();
}
@Override
public void updateDrawState(TextPaint ds) {
apply(ds);
}
@Override
public void updateMeasureState(TextPaint paint) {
apply(paint);
}
private void apply(Paint paint) {
if (mStyle.typeface != null) paint.setTypeface(mStyle.typeface);
if (mStyle.color != Style.NO_COLOR) paint.setColor(mStyle.color);
if (mStyle.size != Style.NO_SIZE) paint.setTextSize(mStyle.size);
paint.setUnderlineText(mStyle.underline);
}
}
public static class Style implements Cloneable {
private static final int NO_COLOR = Integer.MIN_VALUE;
private static final float NO_SIZE = Float.MIN_VALUE;
// Note: will be null for cloned object
private final Context context;
private final SpannableBuilder parent;
private Typeface typeface;
private int color = NO_COLOR;
private float size = NO_SIZE;
private boolean underline;
private Style(Context context, SpannableBuilder builer) {
this.context = context;
this.parent = builer;
}
public Style setFont(Typeface typeface) {
this.typeface = typeface;
return this;
}
/**
* For more details see {@link com.azcltd.fluffycommons.texts.Fonts}
*/
public Style setFont(String fontPath) {
return setFont(Fonts.getTypeface(fontPath, context.getAssets()));
}
/**
* For more details see {@link com.azcltd.fluffycommons.texts.Fonts}
*/
public Style setFont(int fontStringId) {
return setFont(context.getString(fontStringId));
}
public Style setColor(int color) {
this.color = color;
return this;
}
public Style setColorResId(int colorResId) {
return setColor(context.getResources().getColor(colorResId));
}
public Style setSize(int unit, float value) {
size = TypedValue.applyDimension(unit, value, context.getResources().getDisplayMetrics());
return this;
}
/**
* Setting size as scaled pixels (SP)
*/
public Style setSize(float value) {
return setSize(TypedValue.COMPLEX_UNIT_SP, value);
}
public Style setUnderline(boolean underline) {
this.underline = underline;
return this;
}
public SpannableBuilder apply() {
parent.mCurrentStyle = this;
return parent;
}
@Override
protected Style clone() {
Style style = new Style(null, null);
style.typeface = this.typeface;
style.color = this.color;
style.size = this.size;
style.underline = this.underline;
return style;
}
}
public interface OnSpanClickListener {
void onSpanClicked(Object clickObject);
}
} |
/**
* La clase {@code Tema}
*
* @author jdleiva
* @version %I% %G%
*/
public class Tema {
private String id;
private String nombre;
/**
* Instantiates a new Tema.
*
* @param id the id
* @param nombre the nombre
*/
public Tema(String id, String nombre) {
this.id = id;
this.nombre = nombre;
}
/**
* Gets id.
*
* @return the id
*/
public String getId() {
return id;
}
/**
* Sets id.
*
* @param id the id
*/
public void setId(String id) {
this.id = id;
}
/**
* Gets nombre.
*
* @return the nombre
*/
public String getNombre() {
return nombre;
}
/**
* Sets nombre.
*
* @param nombre the nombre
*/
public void setNombre(String nombre) {
this.nombre = nombre;
}
@Override
public String toString() {
return "Tema";
}
} |
package com.carlosefonseca.common.utils;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import com.carlosefonseca.common.R;
import org.jetbrains.annotations.Nullable;
/**
* Creates a View.OnClickListener that starts a new activity.
* <p/>
* Sample usage:<br/>
* {@code button.setOnClickListener(new OpenNewActivity(this, NewActivity.class);}
* <p/>
* It can also be used inside other code by calling<br/>
* {@code new OpenNewActivity(this, NewActivity.class).go();} or start() or finishAndStart()
*/
@SuppressWarnings("UnusedDeclaration")
public class OpenNewActivity implements View.OnClickListener {
private static final String TAG = CodeUtils.getTag(OpenNewActivity.class);
private Integer flags;
public enum TransitionAnimation {
/**
* The system transition.
*/
DEFAULT,
/**
* A fade in/out transition.
*/
FADE,
/**
* Don't use this. It's the internal indication for using custom enter/exit animations.
*/
CUSTOM
}
private Context context;
private Activity activity;
private final Class aClass;
private final Test test;
private final boolean finish;
private final TransitionAnimation animation;
private int enterAnim;
private int exitAnim;
public interface Test {
boolean isValid(@Nullable View view);
}
/** A convenience method for just opening an activity, quick and simple. */
public static void start(Class aClass) {
new OpenNewActivity(null, aClass, null).go(null);
}
/** A convenience method for just opening an activity, quick and simple, and finishing the current one. */
public static void finishAndStart(Activity activityToFinish, Class aClass) {
new OpenNewActivity(activityToFinish, aClass, true).go(null);
}
/**
* Creates a View.OnClickListener that starts a new activity.
* <p/>
* Uses the default system transition and doesn't finish the current activity.
*
* @param aClass The class of the new activity.
*/
public OpenNewActivity(Class aClass) {
this(null, aClass, null);
}
/**
* Creates a View.OnClickListener that starts a new activity.
* <p/>
* Uses the default system transition and doesn't finish the current activity.
*
* @param aClass The class of the new activity.
*/
public OpenNewActivity(Class aClass, Test test) {
this(null, aClass, test);
}
/**
* Creates a View.OnClickListener that starts a new activity.
* <p/>
* Uses the default system transition and doesn't finish the current activity.
* <p/>
* You can use #OpenNewActivity(Class class) instead of this.
*
* @param activity The current activity.
* @param aClass The class of the new activity.
*/
public OpenNewActivity(Activity activity, Class aClass) {
this(activity, aClass, null);
}
/**
* Creates a View.OnClickListener that starts a new activity.
* <p/>
* Uses the default system transition and doesn't finish the current activity.
* <p/>
* You can use #OpenNewActivity(Class class) instead of this.
*
* @param activity The current activity.
* @param aClass The class of the new activity.
*/
public OpenNewActivity(@Nullable Activity activity, Class aClass, @Nullable Test test) {
this.activity = activity;
this.aClass = aClass;
this.test = test;
this.animation = TransitionAnimation.DEFAULT;
this.finish = false;
}
/**
* Creates a View.OnClickListener that starts a new activity.
* <p/>
* Uses the default system transition. The current activity can be automatically finished for you.
*
* @param activity The current activity.
* @param aClass The class of the new activity.
* @param finish Whether to finish the current activity or not.
*/
public OpenNewActivity(Activity activity, Class aClass, boolean finish) {
this.activity = activity;
this.aClass = aClass;
this.finish = finish;
this.animation = TransitionAnimation.DEFAULT;
test = null;
}
/**
* Creates a View.OnClickListener that starts a new activity.
* <p/>
* A built-in transition animation can be specified. The current activity can be automatically finished for you.
*
* @param activity The current activity.
* @param aClass The class of the new activity.
* @param finish Whether to finish the current activity or not.
* @param animation A built-in transition.
* @see TransitionAnimation
*/
public OpenNewActivity(Activity activity, Class aClass, boolean finish, TransitionAnimation animation) {
this.activity = activity;
this.aClass = aClass;
this.finish = finish;
this.animation = animation;
test = null;
}
/**
* Creates a View.OnClickListener that starts a new activity.
* <p/>
* A custom transition animation can be specified. The current activity can be automatically finished for you.
*
* @param activity The current activity.
* @param aClass The class of the new activity.
* @param finish Whether to finish the current activity or not.
* @param enterAnim The {@code anim} resource file to use for the enter animation.
* @param exitAnim The {@code anim} resource file to use for the exit animation.
* @see TransitionAnimation
*/
public OpenNewActivity(Activity activity, Class aClass, boolean finish, int enterAnim, int exitAnim) {
this.activity = activity;
this.aClass = aClass;
this.finish = finish;
this.enterAnim = enterAnim;
this.exitAnim = exitAnim;
this.animation = TransitionAnimation.CUSTOM;
test = null;
}
public OpenNewActivity flags(int flags) {
this.flags = flags;
return this;
}
@Override
public void onClick(@Nullable View view) {
if (activity == null && view != null && view.getContext() != null) {
context = view.getContext();
} else {
context = activity;
}
go(view);
}
/**
* Simpler way to immediately run the transition.
* Performs the same as the {@link #onClick(android.view.View)}, it's just smaller.
* @param view
*/
public void go(@Nullable View view) {
if (context == null && activity == null) Log.e(TAG, "No context!");
if (context == null) context = activity;
if (test != null && !test.isValid(view)) {
Log.i(TAG, "Test failed");
return;
}
Intent intent = new Intent(context, aClass);
if (flags != null) intent.addFlags(flags);
context.startActivity(intent);
if (activity != null) {
switch (animation) {
case FADE:
activity.overridePendingTransition(R.anim.fadein, R.anim.fadeout);
break;
case CUSTOM:
activity.overridePendingTransition(enterAnim, exitAnim);
break;
case DEFAULT:
default:
}
if (finish) activity.finish();
}
}
public static final View.OnClickListener back = new View.OnClickListener() {
@Override
public void onClick(View v) {
if (v.getContext() != null) {
((Activity) v.getContext()).onBackPressed();
}
}
};
} |
package se.comhem.web.test.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import se.comhem.web.test.domain.Hero;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* This class is utility class for
* File operations
* @author Prashant Pathania
*
*/
public class FileUtil {
/**
* Method to return file object
* @param filePath - refers to filePath
* @return - File object
*/
public static File getFile(String filePath) {
return new File(filePath);
}
/**
* This method read the file and returns the
* data in String format
* @param file - represents the file object
* @return - string data from file
*/
public static String getFileContent(File file) throws FileNotFoundException, IOException {
StringBuilder fileContent = new StringBuilder();
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(file);
int content;
while ((content = fileInputStream.read()) != -1) {
// convert to char and display it
fileContent.append((char) content);
}
} finally {
if (fileInputStream != null) {
fileInputStream.close();
}
}
return fileContent.toString();
}
/**
* This method converts object to json and writes
* to a file
* @param object - a data holding object
* @param targetFile - represents file to write
*/
public static void convertAndWriteJsonToFile(List<Hero> heroList, File targetFile) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.writeValue(targetFile, heroList);
}
/**
* This method clears the content of the file
* @param targetFile - refers to the file path
*/
public static void clearFileContent(File targetFile) throws IOException {
PrintWriter writer = null;
try {
writer = new PrintWriter(targetFile);
writer.print("");
} finally {
if (writer != null) {
writer.close();
}
}
}
} |
package seedu.task.model.util;
import java.util.Calendar;
import seedu.task.commons.exceptions.IllegalValueException;
public class DateParser {
public static final String DATE_STRING_ILLEGAL_FORMAT =
"String given to the DateParser must be of the form YYYY/MM/DD HHMM";
private static final int DEFAULT_SECONDS = 0;
private static final String DATE_STRING_VALIDATION_REGEX = "[0-9]{4}/[0-1][0-9]/[0-3][0-9] [0-2][0-9][0-5][0-9]";
public static Calendar parse(String date) throws IllegalValueException {
if (!isValidDateString(date)) {
throw new IllegalValueException(DATE_STRING_ILLEGAL_FORMAT);
}
Calendar cal = Calendar.getInstance();
int year = getYear(date);
int month = getMonth(date);
int day = getDay(date);
int hour = getHour(date);
int minute = getMinute(date);
cal.set(year, month, day, hour, minute, DEFAULT_SECONDS);
return cal;
}
public static String toString(Calendar date) {
String dateString;
int year = date.get(Calendar.YEAR);
int month = date.get(Calendar.MONTH);
int day = date.get(Calendar.DATE);
int hour = date.get(Calendar.HOUR_OF_DAY);
int minute = date.get(Calendar.MINUTE);
dateString = String.format("%4d/%02d/%02d %02d:%02d", year, month + 1, day, hour, minute);
return dateString;
}
public static boolean isValidDateString(String test) {
return test.matches(DATE_STRING_VALIDATION_REGEX);
}
private static int getYear(String date) {
return Integer.parseInt(date.substring(0, 4));
}
private static int getMonth(String date) {
return Integer.parseInt(date.substring(5, 7)) - 1;
}
private static int getDay(String date) {
return Integer.parseInt(date.substring(8, 10));
}
private static int getHour(String date) {
return Integer.parseInt(date.substring(11, 13));
}
private static int getMinute(String date) {
return Integer.parseInt(date.substring(13));
}
} |
package com.comandante.creeper.merchant;
import com.comandante.creeper.Items.Loot;
import com.comandante.creeper.managers.GameManager;
import com.comandante.creeper.server.Color;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import static com.comandante.creeper.server.Color.BOLD_ON;
public class Rogueshop extends Merchant {
private final static long phraseIntervalMs = 300000;
private final static String NAME = "blackbeard";
private final static String welcomeMessage = "Welcome to Blackbeard's Rogue Shop.\r\n";
private final static Set<String> validTriggers = new HashSet<String>(Arrays.asList(new String[]
{"blackbeard", "b", "rogue", "r", NAME}
));
private final static String colorName = BOLD_ON + Color.CYAN + NAME + Color.RESET ;
public Rogueshop(GameManager gameManager, Loot loot, Map<Integer, MerchantItemForSale> merchantItemForSales) {
super(gameManager, NAME, colorName, validTriggers, merchantItemForSales, welcomeMessage);
}
} |
package com.devotedmc.ExilePearl.listener;
import static vg.civcraft.mc.civmodcore.util.TextUtil.msg;
import java.util.HashSet;
import java.util.Set;
import org.bukkit.Material;
import org.bukkit.block.Dispenser;
import org.bukkit.block.Dropper;
import org.bukkit.block.Hopper;
import org.bukkit.entity.EnderPearl;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockIgniteEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.block.BlockIgniteEvent.IgniteCause;
import org.bukkit.event.enchantment.EnchantItemEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.LingeringPotionSplashEvent;
import org.bukkit.event.entity.PotionSplashEvent;
import org.bukkit.event.entity.ProjectileLaunchEvent;
import org.bukkit.event.inventory.InventoryAction;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.PlayerBedEnterEvent;
import org.bukkit.event.player.PlayerBucketEmptyEvent;
import org.bukkit.event.player.PlayerBucketFillEvent;
import org.bukkit.event.player.PlayerExpChangeEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerItemConsumeEvent;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import com.devotedmc.ExilePearl.ExilePearlApi;
import com.devotedmc.ExilePearl.ExileRule;
import com.devotedmc.ExilePearl.Lang;
import com.devotedmc.ExilePearl.config.PearlConfig;
import com.devotedmc.ExilePearl.config.Configurable;
import com.devotedmc.ExilePearl.event.PlayerPearledEvent;
/**
* Listener for disallowing certain actions of exiled players
* @author Gordon
*
* Loss of privileges (for Devoted) when exiled, each of these needs to be toggleable in the config:
* Cannot break reinforced blocks. (Citadel can stop damage, use that)
* Cannot break bastions by placing blocks. (Might need bastion change)
* Cannot throw ender pearls at all.
* Cannot enter a bastion field they are not on. Same teleport back feature as world border.
* Cannot do damage to other players.
* Cannot light fires.
* Cannot light TNT.
* Cannot chat in local chat. Given a message suggesting chatting in a group chat in Citadel.
* Cannot use water or lava buckets.
* Cannot use any potions.
* Cannot set a bed.
* Cannot enter within 1k of their ExilePearl. Same teleport back feature as world border.
* Can use a /suicide command after a 180 second timeout. (In case they get stuck in a reinforced box).
* Cannot place snitch or note-block.
* Exiled players can still play, mine, enchant, trade, grind, and explore.
*
*/
public class ExileListener extends RuleListener implements Configurable {
private Set<String> protectedAnimals = new HashSet<String>();
/**
* Creates a new ExileListener instance
* @param logger The logger instance
* @param pearls The pearl manger
* @param config The plugin configuration
*/
public ExileListener(final ExilePearlApi pearlApi) {
super(pearlApi);
}
/**
* Clears the bed of newly exiled players
* @param e The event
*/
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlayerPearled(PlayerPearledEvent e) {
if (config.canPerform(ExileRule.USE_BED)) {
return;
}
Player p = e.getPearl().getPlayer();
if (p != null && p.isOnline()) {
e.getPearl().getPlayer().setBedSpawnLocation(null, true);
}
}
/**
* Prevent exiled players from using a bed
* @param e The event
*/
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onPlayerEnterBed(PlayerBedEnterEvent e) {
checkAndCancelRule(ExileRule.USE_BED, e, e.getPlayer());
}
/**
* Prevent exiled players from throwing ender pearls
* @param e The event
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPearlThrow(ProjectileLaunchEvent e) {
if (e.getEntity() instanceof EnderPearl) {
checkAndCancelRule(ExileRule.THROW_PEARL, e, (Player)e.getEntity().getShooter());
}
}
/**
* Prevent exiled players from using buckets
* @param e The event
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPlayerFillBucket(PlayerBucketFillEvent e) {
checkAndCancelRule(ExileRule.USE_BUCKET, e, e.getPlayer());
}
/**
* Prevent exiled players from using buckets
* @param e The event
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPlayerEmptyBucket(PlayerBucketEmptyEvent e) {
checkAndCancelRule(ExileRule.USE_BUCKET, e, e.getPlayer());
}
/**
* Prevent exiled players from using certain blocks
* @param e The event
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPlayerInteract(PlayerInteractEvent e) {
if (e.hasBlock()) {
Material type = e.getClickedBlock().getType();
if (type == Material.BREWING_STAND) {
checkAndCancelRule(ExileRule.BREW, e, e.getPlayer());
} else if (type == Material.ANVIL) {
checkAndCancelRule(ExileRule.USE_ANVIL, e, e.getPlayer());
}
}
}
/**
* Prevent exiled players from enchanting
* @param e The event
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPlayerEnchant(EnchantItemEvent e) {
checkAndCancelRule(ExileRule.ENCHANT, e, e.getEnchanter());
}
/**
* Prevent exiled players from pvping and killing pets and protected mobs
* @param e The event
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPlayerDamage(EntityDamageByEntityEvent e) {
if (!(e.getDamager() instanceof Player)) {
return;
}
Player player = (Player)e.getDamager();
if (e.getEntity() instanceof Player) {
checkAndCancelRule(ExileRule.PVP, e, player);
return;
}
if (!(e.getEntity() instanceof LivingEntity)) {
return;
}
LivingEntity living = (LivingEntity)e.getEntity();
String name = living.getCustomName();
if (name != null && name != "") {
checkAndCancelRule(ExileRule.KILL_PETS, e, player);
return;
}
if (!isRuleActive(ExileRule.KILL_MOBS, player.getUniqueId())) {
return;
}
for(String animal : protectedAnimals) {
Class<?> clazz = null;
try {
clazz = Class.forName("org.bukkit.entity." + animal);
} catch (Exception ex) {
continue;
}
if (clazz != null && clazz.isInstance(living)) {
checkAndCancelRule(ExileRule.KILL_MOBS, e, player);
return;
}
}
}
/**
* Prevent exiled players from drinking potions
* @param e The event
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPlayerDrinkPotion(PlayerItemConsumeEvent e) {
if(e.getItem().getType() == Material.POTION) {
checkAndCancelRule(ExileRule.USE_POTIONS, e, e.getPlayer());
}
}
/**
* Prevent exiled players from using splash potions
* @param e The event
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPlayerThrowPotion(PotionSplashEvent e) {
if(e.getEntity() != null && e.getEntity().getShooter() instanceof Player) {
checkAndCancelRule(ExileRule.USE_POTIONS, e, (Player)e.getEntity().getShooter());
}
}
/**
* Prevent exiled players from using lingering splash potions
* @param e The event
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPlayerThrowLingeringPotion(LingeringPotionSplashEvent e) {
if(e.getEntity() != null && e.getEntity().getShooter() instanceof Player) {
checkAndCancelRule(ExileRule.USE_POTIONS, e, (Player)e.getEntity().getShooter());
}
}
/**
* Prevents exiled players from breaking blocks
* @param e The event
*/
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPlayerIgnite(BlockIgniteEvent e) {
if (e.getCause() == IgniteCause.FLINT_AND_STEEL) {
checkAndCancelRule(ExileRule.IGNITE, e, e.getPlayer());
}
}
/**
* Prevents exiled players from breaking blocks
* @param e The event
*/
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onBlockBreak(BlockBreakEvent e) {
checkAndCancelRule(ExileRule.MINE, e, e.getPlayer());
}
/**
* Prevents exiled players from collecting xp
* @param e The event
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onCollectXp(PlayerExpChangeEvent e) {
if (isRuleActive(ExileRule.COLLECT_XP, e.getPlayer().getUniqueId())) {
e.setAmount(0);
msg(e.getPlayer(), Lang.ruleCantDoThat, ExileRule.COLLECT_XP.getActionString());
}
}
/**
* Prevents exiled players from placing certain blocks
* @param e The event
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockPlaced(BlockPlaceEvent e) {
Material m = e.getBlockPlaced().getType();
if (m == Material.TNT) {
checkAndCancelRule(ExileRule.PLACE_TNT, e, e.getPlayer());
}
}
/**
* Prevents exiled players from moving restricted items like lava and TNT
* into dispensers, hoppers, and droppers
* @param e The event
*/
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH)
public void onInventoryClick(InventoryClickEvent e) {
Player player = (Player) e.getWhoClicked();
InventoryAction action = e.getAction();
ItemStack item;
InventoryHolder holder = null;
if(action == InventoryAction.PLACE_ALL
|| action == InventoryAction.PLACE_SOME
|| action == InventoryAction.PLACE_ONE) {
item = e.getCursor();
boolean clickedTop = e.getView().convertSlot(e.getRawSlot()) == e.getRawSlot();
if (item == null || !clickedTop) {
return;
}
holder = e.getView().getTopInventory().getHolder();
} else if(action == InventoryAction.MOVE_TO_OTHER_INVENTORY) {
item = e.getCurrentItem();
boolean clickedTop = e.getView().convertSlot(e.getRawSlot()) == e.getRawSlot();
if (item == null || !clickedTop) {
return;
}
holder = e.getView().getTopInventory().getHolder();
} else {
return;
}
if (item == null || holder == null) {
return;
}
if (!(holder instanceof Dispenser || holder instanceof Dropper || holder instanceof Hopper)) {
return;
}
Material m = item.getType();
if (m == Material.TNT) {
checkAndCancelRule(ExileRule.PLACE_TNT, e, player, false);
}
else if (m == Material.LAVA_BUCKET || m == Material.WATER_BUCKET) {
checkAndCancelRule(ExileRule.USE_BUCKET, e, player, false);
}
if (e.isCancelled()) {
msg(player, Lang.ruleCantDoThat, "do that");
}
}
@Override
public void loadConfig(PearlConfig config) {
protectedAnimals.addAll(config.getProtectedAnimals());
}
} |
package tigase.xmpp.impl;
import java.util.Queue;
import java.util.Map;
import java.util.logging.Logger;
import java.util.logging.Level;
import tigase.db.NonAuthUserRepository;
import tigase.server.Command;
import tigase.server.Packet;
import tigase.xml.Element;
import tigase.xmpp.Authorization;
import tigase.xmpp.NotAuthorizedException;
import tigase.xmpp.XMPPProcessor;
import tigase.xmpp.XMPPProcessorIfc;
import tigase.xmpp.XMPPResourceConnection;
import tigase.xmpp.XMPPException;
import tigase.util.JIDUtils;
/**
* Describe class JabberIqCommand here.
*
*
* Created: Mon Jan 22 22:41:17 2007
*
* @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a>
* @version $Rev$
*/
public class JabberIqCommand extends XMPPProcessor implements XMPPProcessorIfc {
private static final Logger log =
Logger.getLogger("tigase.xmpp.impl.JabberIqCommand");
private static final String XMLNS = Command.XMLNS;
private static final String ID = XMLNS;
private static final String[] ELEMENTS =
{"command"};
private static final String[] XMLNSS =
{Command.XMLNS};
private static final Element[] DISCO_FEATURES =
{new Element("feature", new String[] {"var"}, new String[] {XMLNS})};
@Override
public String id() { return ID; }
@Override
public String[] supElements()
{ return ELEMENTS; }
@Override
public String[] supNamespaces()
{ return XMLNSS; }
@Override
public Element[] supDiscoFeatures(final XMPPResourceConnection session)
{ return DISCO_FEATURES; }
@Override
public void process(final Packet packet, final XMPPResourceConnection session,
final NonAuthUserRepository repo, final Queue<Packet> results,
final Map<String, Object> settings)
throws XMPPException {
if (session == null) { return; }
// Processing only commands (that should be quaranteed by name space)
// and only unknown commands. All known commands are processed elsewhere
// if (!packet.isCommand() || packet.getCommand() != Command.OTHER) {
// return;
try {
if (log.isLoggable(Level.FINEST)) {
log.finest("Received packet: " + packet.getStringData());
}
// Not needed anymore. Packet filter does it for all stanzas.
// // For all messages coming from the owner of this account set
// // proper 'from' attribute. This is actually needed for the case
// // when the user sends a message to himself.
// if (packet.getFrom().equals(session.getConnectionId())) {
// packet.getElement().setAttribute("from", session.getJID());
// } // end of if (packet.getFrom().equals(session.getConnectionId()))
if (packet.getElemTo() == null) {
packet.getElement().setAttribute("to", session.getSMComponentId());
packet.initVars();
}
String id = JIDUtils.getNodeID(packet.getElemTo());
if (id.equals(session.getUserId())) {
// Yes this is message to 'this' client
Element elem = packet.getElement().clone();
Packet result = new Packet(elem);
result.setTo(session.getConnectionId(packet.getElemTo()));
result.setFrom(packet.getTo());
results.offer(result);
} else {
// This is message to some other client
Element result = packet.getElement().clone();
results.offer(new Packet(result));
} // end of else
} catch (NotAuthorizedException e) {
log.warning("NotAuthorizedException for packet: " + packet.getStringData());
results.offer(Authorization.NOT_AUTHORIZED.getResponseMessage(packet,
"You must authorize session first.", true));
} // end of try-catch
}
} |
package com.ezardlabs.lostsector.objects.menus;
import com.ezardlabs.dethsquare.GameObject;
import com.ezardlabs.dethsquare.Input;
import com.ezardlabs.dethsquare.Input.KeyCode;
import com.ezardlabs.dethsquare.LevelManager;
import com.ezardlabs.dethsquare.Screen;
import com.ezardlabs.dethsquare.Vector2;
public class MainMenu extends Menu {
private GameObject settingsMenu;
@Override
public void start() {
super.start();
settingsMenu = GameObject.instantiate(
new GameObject("Settings Menu", new SettingsMenu(menu -> {
menu.gameObject.setActive(false);
open();
})),
new Vector2(960 - 600, 540 - 500));
settingsMenu.setActive(false);
open();
Screen.setCursorVisible(true);
}
@Override
public void update() {
if (Input.getKeyDown(KeyCode.ESCAPE) && settingsMenu.isActiveSelf()) {
settingsMenu.setActive(false);
open();
}
super.update();
}
@Override
protected String[] getOptions() {
return new String[]{
"Play",
"Settings",
"Quit"
};
}
@Override
protected MenuAction[] getActions() {
return new MenuAction[]{
(menu, index, text) -> LevelManager.loadLevel("defense"),
(menu, index, text) -> {
close();
settingsMenu.setActive(true);
},
(menu, index, text) -> System.exit(0)
};
}
} |
package uk.co.jemos.podam.api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.concurrent.ThreadLocalRandom;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Set;
/**
* PODAM Utilities class.
*
* @author mtedone
*
* @since 1.0.0
*
*/
public abstract class PodamUtils {
/** An array of valid String characters */
public static final char[] NICE_ASCII_CHARACTERS = new char[] { 'a', 'b',
'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B',
'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1',
'2', '3', '4', '5', '6', '7', '8', '9', '_' };
/** The application logger. */
private static final Logger LOG = LoggerFactory.getLogger(PodamUtils.class);
/**
* It returns a {@link Field} matching the attribute name or null if a field
* was not found.
*
* @param pojoClass
* The class supposed to contain the field
* @param attributeName
* The field name
*
* @return a {@link Field} matching the attribute name or null if a field
* was not found.
*/
public static Field getField(Class<?> pojoClass, String attributeName) {
Class<?> clazz = pojoClass;
while (clazz != null) {
try {
return clazz.getDeclaredField(attributeName);
} catch (NoSuchFieldException e) {
clazz = clazz.getSuperclass();
}
}
LOG.warn("A field could not be found for attribute '{}[{}]'",
pojoClass, attributeName);
return null;
}
/**
* It returns an value for a {@link Field} matching the attribute
* name or null if a field was not found.
*
* @param <T>
* The type of field to be returned
* @param pojo
* The class supposed to contain the field
* @param attributeName
* The field name
*
* @return an instance of {@link Field} matching the attribute name or
* null if a field was not found.
*/
public static <T> T getFieldValue(Object pojo, String attributeName) {
T retValue = null;
try {
Field field = PodamUtils.getField(pojo.getClass(), attributeName);
if (field != null) {
// It allows to invoke Field.get on private fields
field.setAccessible(true);
@SuppressWarnings("unchecked")
T t = (T) field.get(pojo);
retValue = t;
} else {
LOG.info("The field {}[{}] didn't exist.", pojo.getClass(), attributeName);
}
} catch (Exception e) {
LOG.warn("We couldn't get default value for {}[{}]",
pojo.getClass(), attributeName, e);
}
return retValue;
}
/**
* Searches among set of a class'es methods and selects the one defined in
* the most specific descend of the hierarchy tree
*
* @param methods a set of methods to choose from
* @return the selected method
*/
public static Method selectLatestMethod(Set<Method> methods) {
/* We want to find a method defined the latest */
Method selected = null;
for (Method method : methods) {
if (selected == null || selected.getDeclaringClass().isAssignableFrom(method.getDeclaringClass())) {
selected = method;
}
}
return selected;
}
/**
* Given the attribute and setter it combines annotations from them
* or an empty collection if no custom annotations were found
*
* @param attribute
* The class attribute
* @param methods
* List of setters and getter to check annotations
* @return all annotations for the attribute
*/
public static List<Annotation> getAttributeAnnotations(final Field attribute,
final Method... methods) {
List<Annotation> retValue = new ArrayList<Annotation>();
if (null != attribute) {
for (Annotation annotation : attribute.getAnnotations()) {
retValue.add(annotation);
}
}
for (Method method : methods) {
Annotation[][] paramAnnotations = method.getParameterAnnotations();
if (paramAnnotations.length > 0) {
for (Annotation annotation : paramAnnotations[0]) {
retValue.add(annotation);
}
} else {
for (Annotation annotation : method.getAnnotations()) {
retValue.add(annotation);
}
}
}
return retValue;
}
/**
* Generates random character from set valid for identifiers in Java language
*
* @return random character suitable for identifier
*/
public static Character getNiceCharacter() {
int randomCharIdx = getIntegerInRange(0, NICE_ASCII_CHARACTERS.length - 1);
return NICE_ASCII_CHARACTERS[randomCharIdx];
}
/**
* It returns a long/Long value between min and max value (included).
*
* @param minValue
* The minimum value for the returned value
* @param maxValue
* The maximum value for the returned value
* @return A long/Long value between min and max value (included).
*/
public static long getLongInRange(long minValue, long maxValue) {
return (long) (getDoubleInRange(minValue - 0.5, maxValue + 0.5 - (1 / Long.MAX_VALUE)) + 0.5);
}
/**
* It returns a random int/Integer value between min and max value (included).
*
* @param minValue
* The minimum value for the returned value
* @param maxValue
* The maximum value for the returned value
* @return An int/Integer value between min and max value (included).
*/
public static int getIntegerInRange(int minValue, int maxValue) {
return (int) getLongInRange(minValue, maxValue);
}
/**
* It returns a double/Double value between min and max value (included).
*
* @param minValue
* The minimum value for the returned value
* @param maxValue
* The maximum value for the returned value
* @return A double/Double value between min and max value (included)
*/
public static double getDoubleInRange(double minValue, double maxValue) {
// This can happen. It's a way to specify a precise value
if (minValue == maxValue) {
return minValue;
}
double retValue;
double margin = (maxValue - minValue + 0.1);
Random random = ThreadLocalRandom.current();
do {
retValue = minValue + random.nextDouble() * margin;
} while (retValue > maxValue);
return retValue;
}
/**
* Finds boxed type for a primitive type
*
* @param primitiveType
* Primitive type to find boxed type for
* @return A boxed type or the same type, if original type was not primitive
*/
public static Class<?> primitiveToBoxedType(Class<?> primitiveType) {
if (int.class.equals(primitiveType)) {
return Integer.class;
} else if (double.class.equals(primitiveType)) {
return Double.class;
} else if (long.class.equals(primitiveType)) {
return Long.class;
} else if (byte.class.equals(primitiveType)) {
return Byte.class;
} else if (float.class.equals(primitiveType)) {
return Float.class;
} else if (char.class.equals(primitiveType)) {
return Character.class;
} else if (short.class.equals(primitiveType)) {
return Short.class;
} else {
return primitiveType;
}
}
} |
package wy2boogie.core;
import wybs.lang.CompilationUnit;
import wybs.util.AbstractCompilationUnit;
import wyfs.lang.Content;
import wyfs.lang.Path;
import java.io.*;
import java.util.*;
public class BoogieExampleFile extends AbstractCompilationUnit {
// Content Type
/**
* Records the name-value relationships of one Boogie counter-example.
*
*
*/
public static class BoogieModel {
/**
* This map-of-maps records all the mappings in the Boogie counter-example.
* For example:
* <pre>
* toInt -> {
* T@WVal!val!2 -> 0
* T@WVal!val!3 -> 8855
* else -> 0
* }
* </pre>
* will add the key "toInt" as a key, with its value being a map
* that maps "T@WVal!val!2" to "0" ... and "else" to "0".
* In addition to these "to..." maps, we also use the "is..." maps
* to decide which map each symbolic name should belong to (see the isType method).
*
* Note that globals are put into a map whose names is "".
*
* These maps are later used (see getValue) to 'concretise' symbolic names into concrete values.
* For example, to rewrite "T@WVal!val!2" to "0".
*/
private final Map<String, Map<String, String>> maps;
private Map<String, String> currentMap;
private Map<String, String> toFieldName;
private String currentMapName;
public static final String[] ATOM_TYPES = {"Int", "Bool", "Null", "Ref"};
private Set<String> ignoredGlobals;
// , "Array", "Record", "Function", "Method"};
public BoogieModel() {
ignoredGlobals = new HashSet<>();
ignoredGlobals.add("null");
ignoredGlobals.add("empty__record");
ignoredGlobals.add("undef__field");
maps = new LinkedHashMap<>();
currentMap = new LinkedHashMap<>(); // we preserve name order
toFieldName = new LinkedHashMap<>(); // preserve name order
currentMapName = "";
maps.put(currentMapName, currentMap); // we start with the global map, whose name is the empty string.
}
/**
* Start a new named map in this model.
*
* @param name
*/
public void startMap(String name) {
currentMap = new HashMap<>();
if (maps.containsKey(name)) {
throw new RuntimeException("Duplicate map: " + name);
}
currentMapName = name;
maps.put(currentMapName, currentMap);
}
/**
* Add one key-value pair to the current map.
* @param key
* @param value
*/
public void addEntry(String key, String value) {
// System.out.printf("DEBUG: %s += %s -> %s\n", currentMapName, key, value);
currentMap.put(key, value);
}
public Set<String> getGlobals() {
return maps.get("").keySet();
}
/**
* Get the value of a key in a given map.
*
* @param mapName the name of a map, which must exist. The 'global' map is called "".
* @param key the name of a key in that map.
* @return null if the key is not in the map.
*/
public String getValue(String mapName, String key) {
Map<String, String> map1 = maps.get(mapName);
if (map1 == null) {
throw new IllegalArgumentException("missing map " + mapName + " while looking for key " + key
+ "maps=" + maps);
}
return map1.get(key);
}
/**
* Find out if a value has a given type.
* @param map a WVal type name like "Int", "Bool", "Method", "Ref", "Array", "Record", etc.
* @param value the name of an abstract value, like "T@WVal!val!3"
* @return true if the value belongs to the given type.
*/
public boolean isType(String map, String value) {
Map<String, String> typed = maps.get("is" + map);
if (typed != null) {
String truth = typed.get(value);
if (truth != null && "true".equals(truth)) {
return true;
}
// TODO: check "else" ...
}
return false;
}
/**
* Unfolds abstract values to concrete Whiley values.
* Leaves unknown values unchanged.
*
* @param value
* @return
*/
public String concretise(String value) {
String result = null;
if (isType("Null", value)) {
// We handle the "Null" type specially, because it has only a single value.
// And the .beg files do not have any "toNull" map.
result = "null";
} else {
for (String typ : ATOM_TYPES) {
if (isType(typ, value)) {
result = getValue("to" + typ, value);
}
}
}
if (result == null) {
result = value;
}
return result;
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
for (String g : getGlobals()) {
if (ignoredGlobals.contains(g) || g.startsWith("%lbl%")) {
// ignore labels for now
continue;
}
String value = getValue("", g);
if (isType("Array", value)) {
stringifyArray(result, g, value);
} else if (isType("Record", value)) {
stringifyRecord(result, g, value);
} else {
result.append(String.format(" %30s := %s\n", g, concretise(value)));
}
}
return result.toString();
}
private void stringifyArray(StringBuilder result, String g, String value) {
String len = getValue("arraylen", value);
String array = getValue( "toArray", value);
result.append(String.format(" %31s == %s\n", "|" + g + "|", concretise(len)));
if (array != null) {
Map<String, String> aMap = maps.get("Select_[$int]WVal");
for (String k : aMap.keySet()) {
if (k.startsWith(array + " ")) {
String[] kk = k.split(" ");
String index = kk[1];
String indexVal = aMap.get(k);
result.append(String.format(" %30s[%s] := %s\n", g, index, concretise(indexVal)));
}
}
}
}
/**
* TODO: sort field names
* @param result
* @param g
* @param value
*/
private void stringifyRecord(StringBuilder result, String g, String value) {
String rec = getValue( "toRecord", value);
if (rec != null) {
Map<String, String> aMap = maps.get("Select_[WField]WVal");
for (String k : aMap.keySet()) {
if (k.startsWith(rec + " ")) {
String[] kk = k.split(" ");
String field = kk[1].trim();
if (this.toFieldName.containsKey(field)) {
field = this.toFieldName.get(field);
}
String indexVal = aMap.get(k);
result.append(String.format(" %30s.%s == %s\n", g, field, concretise(indexVal)));
}
}
}
}
}
/**
* List of the counter-example models.
*/
private final List<BoogieModel> models = new ArrayList<>();
/**
* Responsible for identifying and writing Whiley counter-example models.
* The normal extension is ".wyeg" for Whiley counter-examples.
*/
public static final Content.Type<BoogieExampleFile> ContentType = new Content.Type<BoogieExampleFile>() {
public Path.Entry<BoogieExampleFile> accept(Path.Entry<?> e) {
if (e.contentType() == this) {
return (Path.Entry<BoogieExampleFile>) e;
}
return null;
}
public static final String ARROW = " -> ";
@Override
public BoogieExampleFile read(Path.Entry<BoogieExampleFile> e, InputStream input) throws IOException {
BoogieExampleFile result = new BoogieExampleFile(e);
try (BufferedReader reader = new BufferedReader(new InputStreamReader(input))) {
BoogieModel model = null;
String line = reader.readLine();
while (line != null) {
if (line.equals("*** MODEL")) {
if (model != null) {
result.models.add(model);
}
model = new BoogieModel();
} else if (line.endsWith(" -> {")) {
// start new map
model.startMap(line.split(ARROW)[0].trim());
} else if (line.contains(ARROW)) {
// add to current map
String[] words = line.split(ARROW);
String lhs = words[0].trim();
String rhs = words[1].trim();
if (lhs.startsWith("$")) {
// this is a field name, so we need the reverse mapping
model.toFieldName.put(rhs, lhs.substring(1));
} else {
model.addEntry(lhs, rhs);
}
} else if (line.equals("}")) {
// end of current map
} else if (line.equals("*** END_MODEL")) {
// end of this model
} else {
System.err.println("WARNING: unknown line:" + line + ".");
}
line = reader.readLine();
}
if (model == null) {
throw new IOException("No models found in " + e.location());
} else {
result.models.add(model);
}
}
return result;
}
@Override
public void write(OutputStream output, BoogieExampleFile jf) {
throw new UnsupportedOperationException();
}
@Override
public String toString() {
return "Content-Type: Boogie counter-examples";
}
@Override
public String getSuffix() {
return "beg";
}
};
public BoogieExampleFile(Path.Entry<? extends CompilationUnit> entry) {
super(entry);
}
public List<BoogieModel> getModels() {
return models;
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
int num = 1;
for (BoogieModel model : getModels()) {
result.append("*** Model " + num + "\n");
result.append(model.toString());
result.append("\n");
num++;
}
return result.toString();
}
} |
package xyz.cques.rangefun;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.PrimitiveIterator;
class RangeIterator implements PrimitiveIterator.OfInt {
private boolean backwardsIteration;
private final int step;
private final int end;
private int current;
RangeIterator(int start, int end, int step) {
this.current = start;
this.end = end;
if (isBackwardsIteration(start, end)) {
backwardsIteration = true;
this.step = negative(step);
} else {
this.step = step;
}
}
private boolean isBackwardsIteration(int start, int end) {
return start > end;
}
private int negative(int number) {
int newNumber = number;
if (newNumber > 0) {
newNumber = -newNumber;
}
return newNumber;
}
/**
* Returns the next {@code int} element in the range.
*
* @return the next {@code int} element in the range
* @throws NoSuchElementException if the end of the range has been reached
*/
@Override
public int nextInt() {
if (hasNext()) {
int oldCurrent = current;
current = current + step;
return oldCurrent;
} else {
throw new NoSuchElementException(
"the end of the range has been reached"
);
}
}
/**
* Returns {@code true} if the iteration has more elements.
* (In other words, returns {@code true} if {@link #next} would
* return an element rather than throwing an exception.)
*
* @return {@code true} if the iteration has more elements
*/
@Override
public boolean hasNext() {
if (backwardsIteration) {
return current >= end;
}
return current <= end;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
RangeIterator other = (RangeIterator) o;
return backwardsIteration == other.backwardsIteration &&
step == other.step &&
end == other.end &&
current == other.current;
}
@Override
public int hashCode() {
return Objects.hash(backwardsIteration,
step,
end,
current);
}
} |
package com.gmail.nossr50.commands.skills;
import com.gmail.nossr50.commands.SkillCommand;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.SkillType;
import com.gmail.nossr50.locale.LocaleLoader;
public class TamingCommand extends SkillCommand {
private String goreChance;
private boolean canBeastLore;
private boolean canGore;
private boolean canSharpenedClaws;
private boolean canEnvironmentallyAware;
private boolean canThickFur;
private boolean canShockProof;
private boolean canCallWild;
private boolean canFastFood;
public TamingCommand() {
super(SkillType.TAMING);
}
@Override
protected void dataCalculations() {
if (skillValue >= 1000) {
goreChance = "100.00%";
}
else {
goreChance = percent.format(skillValue / 1000);
} }
@Override
protected void permissionsCheck() {
canBeastLore = permInstance.beastLore(player);
canCallWild = permInstance.callOfTheWild(player);
canEnvironmentallyAware = permInstance.environmentallyAware(player);
canFastFood = permInstance.fastFoodService(player);
canGore = permInstance.gore(player);
canSharpenedClaws = permInstance.sharpenedClaws(player);
canShockProof = permInstance.shockProof(player);
canThickFur = permInstance.thickFur(player);
}
@Override
protected boolean effectsHeaderPermissions() {
return canBeastLore || canCallWild || canEnvironmentallyAware || canFastFood || canGore || canSharpenedClaws || canShockProof || canThickFur;
}
@Override
protected void effectsDisplay() {
Config configInstance = Config.getInstance();
if (canBeastLore) {
player.sendMessage(LocaleLoader.getString("Effects.Template", new Object[] { LocaleLoader.getString("Taming.Effect.0"), LocaleLoader.getString("Taming.Effect.1") }));
}
if (canGore) {
player.sendMessage(LocaleLoader.getString("Effects.Template", new Object[] { LocaleLoader.getString("Taming.Effect.2"), LocaleLoader.getString("Taming.Effect.3") }));
}
if (canSharpenedClaws) {
player.sendMessage(LocaleLoader.getString("Effects.Template", new Object[] { LocaleLoader.getString("Taming.Effect.4"), LocaleLoader.getString("Taming.Effect.5") }));
}
if (canEnvironmentallyAware) {
player.sendMessage(LocaleLoader.getString("Effects.Template", new Object[] { LocaleLoader.getString("Taming.Effect.6"), LocaleLoader.getString("Taming.Effect.7") }));
}
if (canThickFur) {
player.sendMessage(LocaleLoader.getString("Effects.Template", new Object[] { LocaleLoader.getString("Taming.Effect.8"), LocaleLoader.getString("Taming.Effect.9") }));
}
if (canShockProof) {
player.sendMessage(LocaleLoader.getString("Effects.Template", new Object[] { LocaleLoader.getString("Taming.Effect.10"), LocaleLoader.getString("Taming.Effect.11") }));
}
if (canFastFood) {
player.sendMessage(LocaleLoader.getString("Effects.Template", new Object[] { LocaleLoader.getString("Taming.Effect.16"), LocaleLoader.getString("Taming.Effect.17") }));
}
if (canCallWild) {
player.sendMessage(LocaleLoader.getString("Effects.Template", new Object[] { LocaleLoader.getString("Taming.Effect.12"), LocaleLoader.getString("Taming.Effect.13") }));
player.sendMessage(LocaleLoader.getString("Taming.Effect.14", new Object[] { configInstance.getTamingCOTWOcelotCost() }));
player.sendMessage(LocaleLoader.getString("Taming.Effect.15", new Object[] { configInstance.getTamingCOTWWolfCost() }));
}
}
@Override
protected boolean statsHeaderPermissions() {
return canEnvironmentallyAware || canFastFood || canGore || canSharpenedClaws || canShockProof || canThickFur;
}
@Override
protected void statsDisplay() {
if (canFastFood) {
if (skillValue < 50) {
player.sendMessage(LocaleLoader.getString("Ability.Generic.Template.Lock", new Object[] { LocaleLoader.getString("Taming.Ability.Locked.4") }));
}
else {
player.sendMessage(LocaleLoader.getString("Ability.Generic.Template", new Object[] { LocaleLoader.getString("Taming.Ability.Bonus.8"), LocaleLoader.getString("Taming.Ability.Bonus.9") }));
}
}
if (canEnvironmentallyAware) {
if (skillValue < 100) {
player.sendMessage(LocaleLoader.getString("Ability.Generic.Template.Lock", new Object[] { LocaleLoader.getString("Taming.Ability.Locked.0") }));
}
else {
player.sendMessage(LocaleLoader.getString("Ability.Generic.Template", new Object[] { LocaleLoader.getString("Taming.Ability.Bonus.0"), LocaleLoader.getString("Taming.Ability.Bonus.1") }));
}
}
if (canThickFur) {
if (skillValue < 250) {
player.sendMessage(LocaleLoader.getString("Ability.Generic.Template.Lock", new Object[] { LocaleLoader.getString("Taming.Ability.Locked.1") }));
}
else {
player.sendMessage(LocaleLoader.getString("Ability.Generic.Template", new Object[] { LocaleLoader.getString("Taming.Ability.Bonus.2"), LocaleLoader.getString("Taming.Ability.Bonus.3") }));
}
}
if (canShockProof) {
if (skillValue < 500) {
player.sendMessage(LocaleLoader.getString("Ability.Generic.Template.Lock", new Object[] { LocaleLoader.getString("Taming.Ability.Locked.2") }));
}
else {
player.sendMessage(LocaleLoader.getString("Ability.Generic.Template", new Object[] { LocaleLoader.getString("Taming.Ability.Bonus.4"), LocaleLoader.getString("Taming.Ability.Bonus.5") }));
}
}
if (canSharpenedClaws) {
if (skillValue < 750) {
player.sendMessage(LocaleLoader.getString("Ability.Generic.Template.Lock", new Object[] { LocaleLoader.getString("Taming.Ability.Locked.3") }));
}
else {
player.sendMessage(LocaleLoader.getString("Ability.Generic.Template", new Object[] { LocaleLoader.getString("Taming.Ability.Bonus.6"), LocaleLoader.getString("Taming.Ability.Bonus.7") }));
}
}
if (canGore) {
player.sendMessage(LocaleLoader.getString("Taming.Combat.Chance.Gore", new Object[] { goreChance }));
}
}
} |
// C l e f I n t e r //
// <editor-fold defaultstate="collapsed" desc="hdr">
// This program is free software: you can redistribute it and/or modify it under the terms of the
// </editor-fold>
package org.audiveris.omr.sig.inter;
import org.audiveris.omr.glyph.Glyph;
import org.audiveris.omr.glyph.Shape;
import org.audiveris.omr.sheet.Staff;
import org.audiveris.omr.sheet.rhythm.MeasureStack;
import org.audiveris.omrdataset.api.OmrShape;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.awt.Point;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "clef")
public class ClefInter
extends AbstractPitchedInter
{
private static final Logger logger = LoggerFactory.getLogger(ClefInter.class);
/** A dummy default clef to be used when no current clef is defined. */
private static final ClefInter defaultClef = new ClefInter(
null,
Shape.G_CLEF,
1,
null,
+2.0,
ClefKind.TREBLE);
/** Kind of the clef. */
@XmlAttribute
private ClefKind kind;
/**
* Creates a <b>ghost</b> ClefInter object.
*
* @param shape the possible shape
* @param grade the interpretation quality
*/
public ClefInter (Shape shape,
double grade)
{
this(null, shape, grade, null, null, null);
}
/**
* Creates a new ClefInter object.
*
* @param glyph the glyph to interpret
* @param shape the possible shape
* @param grade the interpretation quality
* @param staff the related staff
* @param pitch pitch position
* @param kind clef kind
*/
private ClefInter (Glyph glyph,
Shape shape,
double grade,
Staff staff,
Double pitch,
ClefKind kind)
{
super(glyph, null, shape, grade, staff, pitch);
this.kind = kind;
}
/**
* No-arg constructor needed for JAXB.
*/
private ClefInter ()
{
super(null, null, null, null, null, null);
}
// absolutePitchOf //
/**
* Report an absolute pitch value, using the current clef if any,
* otherwise using the default clef (G_CLEF)
*
* @param clef the provided current clef
* @param pitchPosition the pitch position of the provided note
* @return the corresponding absolute
*/
public static int absolutePitchOf (ClefInter clef,
int pitchPosition)
{
if (clef == null) {
return defaultClef.absolutePitchOf(pitchPosition);
} else {
return clef.absolutePitchOf(pitchPosition);
}
}
// added //
@Override
public void added ()
{
super.added();
// Add it to containing measure stack
MeasureStack stack = sig.getSystem().getStackAt(getCenter());
if (stack != null) {
stack.addInter(this);
if (kind == null) {
kind = kindOf(getCenter(), shape, staff);
pitch = Double.valueOf(kind.pitch);
}
}
}
// accept //
@Override
public void accept (InterVisitor visitor)
{
visitor.visit(this);
}
// getKind //
/**
* @return the kind
*/
public ClefKind getKind ()
{
return kind;
}
// remove //
/**
* Remove it from containing measure.
*
* @param extensive true for non-manual removals only
* @see #added()
*/
@Override
public void remove (boolean extensive)
{
MeasureStack stack = sig.getSystem().getStackAt(getCenter());
if (stack != null) {
stack.removeInter(this);
}
super.remove(extensive);
}
// replicate //
/**
* Replicate this clef in a target staff.
*
* @param targetStaff the target staff
* @return the replicated clef, whose bounds may need an update
*/
public ClefInter replicate (Staff targetStaff)
{
return new ClefInter(null, shape, 0, targetStaff, pitch, kind);
}
// internals //
@Override
protected String internals ()
{
return super.internals() + " " + kind;
}
// absolutePitchOf //
/**
* Report the absolute pitch corresponding to a note at the provided pitch position,
* assuming we are governed by this clef
*
* @param intPitch the pitch position of the note
* @return the corresponding absolute pitch
*/
private int absolutePitchOf (int intPitch)
{
switch (shape) {
case G_CLEF:
case G_CLEF_SMALL:
return 34 - intPitch;
case G_CLEF_8VA:
return 34 + 7 - intPitch;
case G_CLEF_8VB:
return 34 - 7 - intPitch;
case C_CLEF:
// Depending on precise clef position, we can have
// an Alto C-clef (pp=0) or a Tenor C-clef (pp=-2) [or other stuff]
return 28 - (int) Math.rint(this.pitch) - intPitch;
case F_CLEF:
case F_CLEF_SMALL:
return 22 - intPitch;
case F_CLEF_8VA:
return 22 + 7 - intPitch;
case F_CLEF_8VB:
return 22 - 7 - intPitch;
case PERCUSSION_CLEF:
return 0;
default:
logger.error("No absolute note pitch defined for {}", this);
return 0; // To keep compiler happy
}
}
// noteStepOf //
/**
* Report the note step corresponding to a note at the provided pitch position,
* assuming we are governed by this clef
*
* @param pitch the pitch position of the note
* @return the corresponding note step
*/
private HeadInter.Step noteStepOf (int pitch)
{
switch (shape) {
case G_CLEF:
case G_CLEF_SMALL:
case G_CLEF_8VA:
case G_CLEF_8VB:
return HeadInter.Step.values()[(71 - pitch) % 7];
case C_CLEF:
// Depending on precise clef position, we can have
// an Alto C-clef (pp=0) or a Tenor C-clef (pp=-2) [or other stuff]
return HeadInter.Step.values()[(72 + (int) Math.rint(this.pitch) - pitch) % 7];
case F_CLEF:
case F_CLEF_SMALL:
case F_CLEF_8VA:
case F_CLEF_8VB:
return HeadInter.Step.values()[(73 - pitch) % 7];
case PERCUSSION_CLEF:
return null;
default:
logger.error("No note step defined for {}", this);
return null; // To keep compiler happy
}
}
// octaveOf //
/**
* Report the octave corresponding to a note at the provided pitch position,
* assuming we are governed by this clef
*
* @param pitchPosition the pitch position of the note
* @return the corresponding octave
*/
private int octaveOf (double pitchPosition)
{
int intPitch = (int) Math.rint(pitchPosition);
switch (shape) {
case G_CLEF:
case G_CLEF_SMALL:
return (34 - intPitch) / 7;
case G_CLEF_8VA:
return ((34 - intPitch) / 7) + 1;
case G_CLEF_8VB:
return ((34 - intPitch) / 7) - 1;
case C_CLEF:
// Depending on precise clef position, we can have
// an Alto C-clef (pp=0) or a Tenor C-clef (pp=-2) [or other stuff]
return (28 + (int) Math.rint(this.pitch) - intPitch) / 7;
case F_CLEF:
case F_CLEF_SMALL:
return (22 - intPitch) / 7;
case F_CLEF_8VA:
return ((22 - intPitch) / 7) + 1;
case F_CLEF_8VB:
return ((22 - intPitch) / 7) - 1;
case PERCUSSION_CLEF:
return 0;
default:
logger.error("No note octave defined for {}", this);
return 0; // To keep compiler happy
}
}
// create //
/**
* Create a Clef inter.
*
* @param glyph underlying glyph
* @param shape precise shape
* @param grade evaluation value
* @param staff related staff
* @return the created instance or null if failed
*/
public static ClefInter create (Glyph glyph,
Shape shape,
double grade,
Staff staff)
{
switch (shape) {
case G_CLEF:
case G_CLEF_SMALL:
case G_CLEF_8VA:
case G_CLEF_8VB:
return new ClefInter(glyph, shape, grade, staff, 2.0, ClefKind.TREBLE);
case C_CLEF:
// Depending on precise clef position, we can have
// an Alto C-clef (pp=0) or a Tenor C-clef (pp=-2)
Point center = glyph.getCenter();
double pp = Math.rint(staff.pitchPositionOf(center));
ClefKind kind = (pp >= -1) ? ClefKind.ALTO : ClefKind.TENOR;
return new ClefInter(glyph, shape, grade, staff, pp, kind);
case F_CLEF:
case F_CLEF_SMALL:
case F_CLEF_8VA:
case F_CLEF_8VB:
return new ClefInter(glyph, shape, grade, staff, -2.0, ClefKind.BASS);
case PERCUSSION_CLEF:
return new ClefInter(glyph, shape, grade, staff, 0.0, ClefKind.PERCUSSION);
default:
return null;
}
}
// kindOf //
/**
* Guess the clef kind, based on shape and location.
*
* @param center area center of the clef
* @param shape clef shape
* @param staff the containing shape
* @return the precise clef kind
*/
public static ClefKind kindOf (Point center,
Shape shape,
Staff staff)
{
switch (shape) {
case G_CLEF:
case G_CLEF_SMALL:
case G_CLEF_8VA:
case G_CLEF_8VB:
return ClefKind.TREBLE;
case C_CLEF:
// Disambiguate between Alto C-clef (pp=0) and Tenor C-clef (pp=-2)
int pp = (int) Math.rint(staff.pitchPositionOf(center));
return (pp >= -1) ? ClefKind.ALTO : ClefKind.TENOR;
case F_CLEF:
case F_CLEF_SMALL:
case F_CLEF_8VA:
case F_CLEF_8VB:
return ClefKind.BASS;
case PERCUSSION_CLEF:
return ClefKind.PERCUSSION;
default:
return null;
}
}
// kindOf //
public static ClefKind kindOf (OmrShape omrShape)
{
switch (omrShape) {
case gClef:
case gClef8vb:
case gClef8va:
case gClef15mb:
case gClef15ma:
return ClefKind.TREBLE;
case cClefAlto:
return ClefKind.ALTO;
case cClefTenor:
return ClefKind.TENOR;
case fClef:
case fClef8vb:
case fClef8va:
case fClef15mb:
case fClef15ma:
return ClefKind.BASS;
case unpitchedPercussionClef1:
return ClefKind.PERCUSSION;
}
throw new IllegalArgumentException("No ClefKind for " + omrShape);
}
// noteStepOf //
/**
* Report the note step that corresponds to a note in the provided pitch position,
* using the current clef if any, otherwise using the default clef (G_CLEF)
*
* @param clef the provided current clef
* @param pitchPosition the pitch position of the provided note
* @return the corresponding note step
*/
public static HeadInter.Step noteStepOf (ClefInter clef,
int pitchPosition)
{
if (clef == null) {
return defaultClef.noteStepOf(pitchPosition);
} else {
return clef.noteStepOf(pitchPosition);
}
}
// octaveOf //
/**
* Report the octave corresponding to a note at the provided pitch position,
* assuming we are governed by the provided clef, otherwise (if clef is null)
* we use the default clef (G_CLEF)
*
* @param clef the current clef if any
* @param pitch the pitch position of the note
* @return the corresponding octave
*/
public static int octaveOf (ClefInter clef,
double pitch)
{
if (clef == null) {
return defaultClef.octaveOf(pitch);
} else {
return clef.octaveOf(pitch);
}
}
/**
* Clef kind, based on shape and pitch.
*/
public static enum ClefKind
{
TREBLE(Shape.G_CLEF, 2),
BASS(Shape.F_CLEF, -2),
ALTO(Shape.C_CLEF, 0),
TENOR(Shape.C_CLEF, -2),
PERCUSSION(Shape.PERCUSSION_CLEF, 0);
/** Symbol shape class. (regardless of ottava mark if any) */
public final Shape shape;
/** Pitch of reference line. */
public final int pitch;
ClefKind (Shape shape,
int pitch)
{
this.shape = shape;
this.pitch = pitch;
}
}
} |
package com.herokuapp.directto.client;
import java.util.*;
/**
* @author Ryan Brainard
*/
public final class EventSubscription {
public static enum Event {
DEPLOY_PRE_VERIFICATION_START,
DEPLOY_PRE_VERIFICATION_END,
DEPLOY_START,
UPLOAD_START,
UPLOAD_END,
POLL,
DEPLOY_END
}
public static interface Subscriber {
void handle(Event event);
}
private final Map<Event, Set<Subscriber>> subscribers = new EnumMap<Event, Set<Subscriber>>(Event.class);
void announce(Event event) {
if (subscribers.containsKey(event)) {
for (Subscriber subscriber : subscribers.get(event)) {
subscriber.handle(event);
}
}
}
public EventSubscription subscribe(Event event, Subscriber subscriber) {
return subscribe(EnumSet.of(event), subscriber);
}
public EventSubscription subscribe(EnumSet<Event> events, Subscriber subscriber) {
for (Event event : events) {
if (!subscribers.containsKey(event)) {
subscribers.put(event, new HashSet<Subscriber>());
}
subscribers.get(event).add(subscriber);
}
return this;
}
} |
package com.hyperfresh.mchyperchat;
import java.util.Collection;
/**
* Event entry methods for HyperChat.
*
* When implementing a server API, redirect all their events to this class.
*/
public class HyperChatEventPoster
{
public static User lastSpoke = null;
/**
* Executes when a player has said something.
*
* @param spoke
* @param said
*/
public static void onPlayerChat(Player spoke, String said)
{
Collection<Player> players = HyperChat.getPlayers();
spoke.setLastMessage(said);
if(spoke != lastSpoke)
{
if(lastSpoke != null) //print the last player's footer
{
players.stream().forEach
(
p ->
{
String footerFormat = p.getTheme().getChatFooterFormat();
if(footerFormat != null)
{
p.sendMessage(HyperChat.processDynamicFields(footerFormat, lastSpoke));
}
}
);
}
//print this player's header
players.stream().forEach
(
p ->
{
String headerFormat = spoke.getTheme().getChatHeaderFormat();
if(headerFormat != null)
{
p.sendMessage(HyperChat.processDynamicFields(headerFormat, spoke));
}
}
);
}
//print this player's message
players.stream().forEach
(
p ->
{
String messageFormat = spoke.getTheme().getChatMessageFormat();
if(messageFormat != null)
{
p.sendMessage(HyperChat.processDynamicFields(messageFormat, spoke));
}
}
);
lastSpoke = spoke;
}
/**
* Executes only when a console has run the "say" command.
* Everything <b>after</b> "say" should be included in the {@code said} argument.
*
* @param said what the console said.
*/
public static void onConsoleChat(String said)
{
HyperChat.getConsole().setLastMessage(said);
}
} |
package com.impossibl.postgres.jdbc;
import static com.impossibl.postgres.jdbc.Exceptions.NOT_ALLOWED_ON_PREP_STMT;
import static com.impossibl.postgres.jdbc.Exceptions.NOT_IMPLEMENTED;
import static com.impossibl.postgres.jdbc.Exceptions.PARAMETER_INDEX_OUT_OF_BOUNDS;
import static com.impossibl.postgres.jdbc.SQLTypeUtils.coerce;
import static java.nio.charset.StandardCharsets.US_ASCII;
import static java.nio.charset.StandardCharsets.UTF_8;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.Array;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Date;
import java.sql.NClob;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.Ref;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.RowId;
import java.sql.SQLException;
import java.sql.SQLXML;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import com.google.common.io.ByteStreams;
import com.google.common.io.CharStreams;
import com.impossibl.postgres.protocol.ResultField;
import com.impossibl.postgres.types.Type;
class PGPreparedStatement extends PGStatement implements PreparedStatement {
List<Type> parameterTypes;
List<Object> parameterValues;
boolean wantsGeneratedKeys;
PGPreparedStatement(PGConnection connection, int type, int concurrency, int holdability, String name, List<Type> parameterTypes, List<ResultField> resultFields) {
super(connection, type, concurrency, holdability, name, resultFields);
this.parameterTypes = parameterTypes;
this.parameterValues = Arrays.asList(new Object[parameterTypes.size()]);
}
public boolean getWantsGeneratedKeys() {
return wantsGeneratedKeys;
}
public void setWantsGeneratedKeys(boolean wantsGeneratedKeys) {
this.wantsGeneratedKeys = wantsGeneratedKeys;
}
/**
* Ensure the given parameter index is valid for this statement
*
* @throws SQLException
* If the parameter index is out of bounds
*/
void checkParameterIndex(int idx) throws SQLException {
if(idx < 1 || idx > parameterValues.size())
throw PARAMETER_INDEX_OUT_OF_BOUNDS;
}
void set(int parameterIdx, Object val) throws SQLException {
checkClosed();
checkParameterIndex(parameterIdx);
parameterIdx -= 1;
Type paramType = parameterTypes.get(parameterIdx);
parameterValues.set(parameterIdx, coerce(val, paramType, connection.getTypeMap(), connection));
}
void internalClose() throws SQLException {
super.internalClose();
parameterTypes = null;
parameterValues = null;
}
@Override
public boolean execute() throws SQLException {
boolean res = super.executeStatement(name, parameterTypes, parameterValues);
if(wantsGeneratedKeys) {
generatedKeysResultSet = getResultSet();
}
return res;
}
@Override
public PGResultSet executeQuery() throws SQLException {
execute();
return getResultSet();
}
@Override
public int executeUpdate() throws SQLException {
execute();
if(wantsGeneratedKeys) {
generatedKeysResultSet = getResultSet();
}
return getUpdateCount();
}
@Override
public void clearBatch() throws SQLException {
checkClosed();
throw NOT_IMPLEMENTED;
}
@Override
public int[] executeBatch() throws SQLException {
checkClosed();
throw NOT_IMPLEMENTED;
}
@Override
public void addBatch() throws SQLException {
checkClosed();
throw NOT_IMPLEMENTED;
}
@Override
public void clearParameters() throws SQLException {
checkClosed();
for (int c = 0; c < parameterValues.size(); ++c) {
parameterValues.set(c, null);
}
}
@Override
public ParameterMetaData getParameterMetaData() throws SQLException {
checkClosed();
return new PGParameterMetaData(parameterTypes);
}
@Override
public ResultSetMetaData getMetaData() throws SQLException {
checkClosed();
return new PGResultSetMetaData(connection, resultFields);
}
@Override
public void setNull(int parameterIndex, int sqlType) throws SQLException {
set(parameterIndex, null);
}
@Override
public void setBoolean(int parameterIndex, boolean x) throws SQLException {
set(parameterIndex, x);
}
@Override
public void setByte(int parameterIndex, byte x) throws SQLException {
set(parameterIndex, x);
}
@Override
public void setShort(int parameterIndex, short x) throws SQLException {
set(parameterIndex, x);
}
@Override
public void setInt(int parameterIndex, int x) throws SQLException {
set(parameterIndex, x);
}
@Override
public void setLong(int parameterIndex, long x) throws SQLException {
set(parameterIndex, x);
}
@Override
public void setFloat(int parameterIndex, float x) throws SQLException {
set(parameterIndex, x);
}
@Override
public void setDouble(int parameterIndex, double x) throws SQLException {
set(parameterIndex, x);
}
@Override
public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException {
set(parameterIndex, x);
}
@Override
public void setString(int parameterIndex, String x) throws SQLException {
set(parameterIndex, x);
}
@Override
public void setBytes(int parameterIndex, byte[] x) throws SQLException {
set(parameterIndex, x);
}
@Override
public void setDate(int parameterIndex, Date x) throws SQLException {
set(parameterIndex, x);
}
@Override
public void setTime(int parameterIndex, Time x) throws SQLException {
set(parameterIndex, x);
}
@Override
public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException {
set(parameterIndex, x);
}
@Override
public void setBinaryStream(int parameterIndex, InputStream x) throws SQLException {
setBinaryStream(parameterIndex, x, (long) -1);
}
@Override
public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException {
setBinaryStream(parameterIndex, x, (long) length);
}
@Override
public void setBinaryStream(int parameterIndex, InputStream x, long length) throws SQLException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
ByteStreams.copy(x, out);
}
catch(IOException e) {
throw new SQLException(e);
}
set(parameterIndex, out.toByteArray());
}
@Override
public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException {
InputStreamReader reader = new InputStreamReader(x, UTF_8);
setCharacterStream(parameterIndex, reader, length);
}
@Override
public void setAsciiStream(int parameterIndex, InputStream x) throws SQLException {
setAsciiStream(parameterIndex, x, (long) -1);
}
@Override
public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException {
setAsciiStream(parameterIndex, x, (long) length);
}
@Override
public void setAsciiStream(int parameterIndex, InputStream x, long length) throws SQLException {
InputStreamReader reader = new InputStreamReader(x, US_ASCII);
setCharacterStream(parameterIndex, reader, length);
}
@Override
public void setCharacterStream(int parameterIndex, Reader reader) throws SQLException {
setCharacterStream(parameterIndex, reader, (long) -1);
}
@Override
public void setCharacterStream(int parameterIndex, Reader reader, int length) throws SQLException {
setCharacterStream(parameterIndex, reader, (long) length);
}
@Override
public void setCharacterStream(int parameterIndex, Reader reader, long length) throws SQLException {
StringWriter writer = new StringWriter();
try {
CharStreams.copy(reader, writer);
}
catch(IOException e) {
throw new SQLException(e);
}
set(parameterIndex, writer.toString());
}
@Override
public void setObject(int parameterIndex, Object x) throws SQLException {
set(parameterIndex, x);
}
@Override
public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException {
checkClosed();
setObject(parameterIndex, x, targetSqlType, 0);
}
@Override
public void setObject(int parameterIndex, Object x, int targetSqlType, int scaleOrLength) throws SQLException {
checkClosed();
checkParameterIndex(parameterIndex);
if(SQLTypeMetaData.getSQLType(parameterTypes.get(parameterIndex-1)) != targetSqlType) {
throw new SQLException("Invalid target SQL type");
}
set(parameterIndex, x);
}
@Override
public void setBlob(int parameterIndex, Blob x) throws SQLException {
set(parameterIndex, x);
}
@Override
public void setBlob(int parameterIndex, InputStream inputStream, long length) throws SQLException {
setBlob(parameterIndex, ByteStreams.limit(inputStream, length));
}
@Override
public void setBlob(int parameterIndex, InputStream inputStream) throws SQLException {
Blob blob = connection.createBlob();
try {
ByteStreams.copy(inputStream, blob.setBinaryStream(0));
}
catch(IOException e) {
throw new SQLException(e);
}
set(parameterIndex, blob);
}
@Override
public void setArray(int parameterIndex, Array x) throws SQLException {
set(parameterIndex, x);
}
@Override
public void setDate(int parameterIndex, Date x, Calendar cal) throws SQLException {
checkClosed();
throw NOT_IMPLEMENTED;
}
@Override
public void setTime(int parameterIndex, Time x, Calendar cal) throws SQLException {
checkClosed();
throw NOT_IMPLEMENTED;
}
@Override
public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException {
checkClosed();
throw NOT_IMPLEMENTED;
}
@Override
public void setNull(int parameterIndex, int sqlType, String typeName) throws SQLException {
set(parameterIndex, null);
}
@Override
public void setURL(int parameterIndex, URL x) throws SQLException {
set(parameterIndex, x);
}
@Override
public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException {
checkClosed();
throw NOT_IMPLEMENTED;
}
@Override
public void setRowId(int parameterIndex, RowId x) throws SQLException {
checkClosed();
throw NOT_IMPLEMENTED;
}
@Override
public void setRef(int parameterIndex, Ref x) throws SQLException {
checkClosed();
throw NOT_IMPLEMENTED;
}
@Override
public void setNString(int parameterIndex, String value) throws SQLException {
checkClosed();
throw NOT_IMPLEMENTED;
}
@Override
public void setClob(int parameterIndex, Clob x) throws SQLException {
checkClosed();
throw NOT_IMPLEMENTED;
}
@Override
public void setNClob(int parameterIndex, NClob value) throws SQLException {
checkClosed();
throw NOT_IMPLEMENTED;
}
@Override
public void setClob(int parameterIndex, Reader reader, long length) throws SQLException {
checkClosed();
throw NOT_IMPLEMENTED;
}
@Override
public void setNClob(int parameterIndex, Reader reader, long length) throws SQLException {
checkClosed();
throw NOT_IMPLEMENTED;
}
@Override
public void setClob(int parameterIndex, Reader reader) throws SQLException {
checkClosed();
throw NOT_IMPLEMENTED;
}
@Override
public void setNClob(int parameterIndex, Reader reader) throws SQLException {
checkClosed();
throw NOT_IMPLEMENTED;
}
@Override
public void setNCharacterStream(int parameterIndex, Reader value) throws SQLException {
checkClosed();
throw NOT_IMPLEMENTED;
}
@Override
public void setNCharacterStream(int parameterIndex, Reader value, long length) throws SQLException {
checkClosed();
throw NOT_IMPLEMENTED;
}
@Override
public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException {
throw NOT_ALLOWED_ON_PREP_STMT;
}
@Override
public int executeUpdate(String sql, int[] columnIndexes) throws SQLException {
throw NOT_ALLOWED_ON_PREP_STMT;
}
@Override
public int executeUpdate(String sql, String[] columnNames) throws SQLException {
throw NOT_ALLOWED_ON_PREP_STMT;
}
@Override
public boolean execute(String sql, int autoGeneratedKeys) throws SQLException {
throw NOT_ALLOWED_ON_PREP_STMT;
}
@Override
public boolean execute(String sql, int[] columnIndexes) throws SQLException {
throw NOT_ALLOWED_ON_PREP_STMT;
}
@Override
public boolean execute(String sql, String[] columnNames) throws SQLException {
throw NOT_ALLOWED_ON_PREP_STMT;
}
@Override
public boolean execute(String sql) throws SQLException {
throw NOT_ALLOWED_ON_PREP_STMT;
}
@Override
public ResultSet executeQuery(String sql) throws SQLException {
throw NOT_ALLOWED_ON_PREP_STMT;
}
@Override
public int executeUpdate(String sql) throws SQLException {
throw NOT_ALLOWED_ON_PREP_STMT;
}
@Override
public void addBatch(String sql) throws SQLException {
throw NOT_ALLOWED_ON_PREP_STMT;
}
} |
package com.jarvis.cache.redis;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jarvis.cache.AbstractCacheManager;
import com.jarvis.cache.exception.CacheCenterConnectionException;
import com.jarvis.cache.script.AbstractScriptParser;
import com.jarvis.cache.serializer.ISerializer;
import com.jarvis.cache.serializer.StringSerializer;
import com.jarvis.cache.to.AutoLoadConfig;
import com.jarvis.cache.to.CacheKeyTO;
import com.jarvis.cache.to.CacheWrapper;
import redis.clients.jedis.JedisCluster;
/**
* Redis
* @author jiayu.qiu
*/
public class JedisClusterCacheManager extends AbstractCacheManager {
private static final Logger logger=LoggerFactory.getLogger(JedisClusterCacheManager.class);
private static final StringSerializer keySerializer=new StringSerializer();
private JedisCluster jedisCluster;
/**
* Hash00;hashExpire0@Cacheexpire-1
*/
private int hashExpire=-1;
/**
* Hash
*/
private boolean hashExpireByScript=true;
public JedisClusterCacheManager(AutoLoadConfig config, ISerializer<Object> serializer, AbstractScriptParser scriptParser, JedisCluster jedisCluster) {
super(config, serializer, scriptParser);
this.jedisCluster=jedisCluster;
}
public void setJedisCluster(JedisCluster jedisCluster) {
this.jedisCluster=jedisCluster;
}
@Override
public void setCache(final CacheKeyTO cacheKeyTO, final CacheWrapper<Object> result, final Method method, final Object args[]) throws CacheCenterConnectionException {
if(null == jedisCluster || null == cacheKeyTO) {
return;
}
String cacheKey=cacheKeyTO.getCacheKey();
if(null == cacheKey || cacheKey.length() == 0) {
return;
}
try {
int expire=result.getExpire();
String hfield=cacheKeyTO.getHfield();
if(null == hfield || hfield.length() == 0) {
if(expire == 0) {
jedisCluster.set(keySerializer.serialize(cacheKey), getSerializer().serialize(result));
} else if(expire > 0) {
jedisCluster.setex(keySerializer.serialize(cacheKey), expire, getSerializer().serialize(result));
}
} else {
hashSet(cacheKey, hfield, result);
}
} catch(Exception ex) {
logger.error(ex.getMessage(), ex);
} finally {
}
}
private static byte[] hashSetScript;
static {
try {
String tmpScript="redis.call('HSET', KEYS[1], ARGV[1], ARGV[2]);\nredis.call('EXPIRE', KEYS[1], tonumber(ARGV[3]));";
hashSetScript=tmpScript.getBytes("UTF-8");
} catch(UnsupportedEncodingException ex) {
logger.error(ex.getMessage(), ex);
}
}
private void hashSet(String cacheKey, String hfield, CacheWrapper<Object> result) throws Exception {
byte[] key=keySerializer.serialize(cacheKey);
byte[] field=keySerializer.serialize(hfield);
byte[] val=getSerializer().serialize(result);
int hExpire;
if(hashExpire < 0) {
hExpire=result.getExpire();
} else {
hExpire=hashExpire;
}
if(hExpire == 0) {
jedisCluster.hset(key, field, val);
} else if(hExpire > 0) {
if(hashExpireByScript) {
List<byte[]> keys=new ArrayList<byte[]>();
keys.add(key);
List<byte[]> args=new ArrayList<byte[]>();
args.add(field);
args.add(val);
args.add(keySerializer.serialize(String.valueOf(hExpire)));
jedisCluster.eval(hashSetScript, keys, args);
} else {
jedisCluster.hset(key, field, val);
jedisCluster.expire(key, hExpire);
}
}
}
@SuppressWarnings("unchecked")
@Override
public CacheWrapper<Object> get(final CacheKeyTO cacheKeyTO, final Method method, final Object args[]) throws CacheCenterConnectionException {
if(null == jedisCluster || null == cacheKeyTO) {
return null;
}
String cacheKey=cacheKeyTO.getCacheKey();
if(null == cacheKey || cacheKey.length() == 0) {
return null;
}
CacheWrapper<Object> res=null;
try {
byte bytes[]=null;
String hfield=cacheKeyTO.getHfield();
if(null == hfield || hfield.length() == 0) {
bytes=jedisCluster.get(keySerializer.serialize(cacheKey));
} else {
bytes=jedisCluster.hget(keySerializer.serialize(cacheKey), keySerializer.serialize(hfield));
}
Type returnType=method.getGenericReturnType();
res=(CacheWrapper<Object>)getSerializer().deserialize(bytes, returnType);
} catch(Exception ex) {
logger.error(ex.getMessage(), ex);
} finally {
}
return res;
}
/**
* Key
* @param cacheKeyTO Key
*/
@Override
public void delete(CacheKeyTO cacheKeyTO) throws CacheCenterConnectionException {
if(null == jedisCluster || null == cacheKeyTO) {
return;
}
String cacheKey=cacheKeyTO.getCacheKey();
if(null == cacheKey || cacheKey.length() == 0) {
return;
}
logger.debug("delete cache:" + cacheKey);
try {
String hfield=cacheKeyTO.getHfield();
if(null == hfield || hfield.length() == 0) {
jedisCluster.del(keySerializer.serialize(cacheKey));
} else {
jedisCluster.hdel(keySerializer.serialize(cacheKey), keySerializer.serialize(hfield));
}
this.getAutoLoadHandler().resetAutoLoadLastLoadTime(cacheKeyTO);
} catch(Exception ex) {
logger.error(ex.getMessage(), ex);
} finally {
}
}
public JedisCluster getJedisCluster() {
return jedisCluster;
}
public int getHashExpire() {
return hashExpire;
}
public void setHashExpire(int hashExpire) {
if(hashExpire < 0) {
return;
}
this.hashExpire=hashExpire;
}
public boolean isHashExpireByScript() {
return hashExpireByScript;
}
public void setHashExpireByScript(boolean hashExpireByScript) {
this.hashExpireByScript=hashExpireByScript;
}
} |
package whelk.history;
import whelk.Document;
import whelk.JsonLd;
import java.time.Instant;
import java.time.ZonedDateTime;
import java.util.*;
public class History {
// Most-recent-ownership for each part of the record
private final HashMap<List<Object>, Ownership> m_pathOwnership;
// A (json) summary of changes or "change sets" for the history of this record, version for version.
public Map m_changeSetsMap;
// The last version added to this history, needed for diffing the next one against.
private DocumentVersion m_lastVersion;
private final JsonLd m_jsonLd;
/**
* Reconstruct a records history given a list of versions of said record
*/
public History(List<DocumentVersion> versions, JsonLd jsonLd) {
m_jsonLd = jsonLd;
m_pathOwnership = new HashMap<>();
m_changeSetsMap = new HashMap();
m_changeSetsMap.put("@id", versions.get(0).doc.getCompleteId() + "/changesets");
m_changeSetsMap.put("changeSets", new ArrayList<>());
// The list we get is sorted chronologically, oldest first.
for (int i = 0; i < versions.size(); ++i) {
DocumentVersion version = versions.get(i);
Map changeSet = new HashMap();
changeSet.put("@type", "ChangeSet");
Map versionLink = new HashMap();
versionLink.put("@id", version.doc.getCompleteId() + "/data?version=" + i);
changeSet.put("version", versionLink);
changeSet.put("addedPaths", new ArrayList<>());
changeSet.put("modifiedPaths", new ArrayList<>());
changeSet.put("removedPaths", new ArrayList<>());
changeSet.put("agent", version.changedBy);
List changeSets = (List) m_changeSetsMap.get("changeSets");
Map agent = new HashMap();
agent.put("@id", changedByToUri(version.changedBy));
changeSet.put("agent", agent);
if (wasScriptEdit(version)) {
changeSet.put("date", version.doc.getGenerationDate());
Map tool = new HashMap();
tool.put("@id", "https://id.kb.se/generator/globalchanges");
changeSet.put("tool", tool);
} else if (version.changedIn.equals("APIX")) {
changeSet.put("date", version.doc.getModified());
Map tool = new HashMap();
tool.put("@id", "https://id.kb.se/generator/apix");
changeSet.put("tool", tool);
} else if (version.changedIn.equals("batch import")) {
changeSet.put("date", version.doc.getModified());
Map tool = new HashMap();
tool.put("@id", "https://id.kb.se/generator/batchimport");
changeSet.put("tool", tool);
} else if (version.changedIn.equals("vcopy")) {
changeSet.put("date", version.doc.getModified());
Map tool = new HashMap();
tool.put("@id", "https://id.kb.se/generator/voyager");
changeSet.put("tool", tool);
} else if (version.changedBy.equals("WhelkCopier")) {
changeSet.put("date", version.doc.getModified());
Map tool = new HashMap();
tool.put("@id", "https://id.kb.se/generator/whelkcopier");
changeSet.put("tool", tool);
} else if (version.changedIn.equals("xl")) { // Must be last in list!
changeSet.put("date", version.doc.getModified());
Map tool = new HashMap();
tool.put("@id", "https://id.kb.se/generator/crud");
changeSet.put("tool", tool);
}
changeSets.add(changeSet);
addVersion(version, changeSet);
// Clean up empty fields
if ( ((List) changeSet.get("addedPaths")).isEmpty() )
changeSet.remove("addedPaths");
if ( ((List) changeSet.get("removedPaths")).isEmpty() )
changeSet.remove("removedPaths");
if ( ((List) changeSet.get("modifiedPaths")).isEmpty() )
changeSet.remove("modifiedPaths");
}
}
public void addVersion(DocumentVersion version, Map changeSetToBuild) {
if (m_lastVersion == null) {
m_pathOwnership.put( new ArrayList<>(), new Ownership(version, null) );
} else {
examineDiff(new ArrayList<>(), version, version.doc.data, m_lastVersion.doc.data, null, changeSetToBuild);
}
m_lastVersion = version;
}
public Ownership getOwnership(List<Object> path) {
List<Object> temp = new ArrayList<>(path);
while (!temp.isEmpty()) {
Ownership value = m_pathOwnership.get(temp);
if (value != null)
return value;
temp.remove(temp.size()-1);
}
return m_pathOwnership.get(new ArrayList<>()); // The root (first) owner
}
/**
* Get the set of owners for path and everything under it.
*/
public Set<Ownership> getSubtreeOwnerships(List<Object> path) {
Set<Ownership> owners = new HashSet<>();
for (Object keyObject : m_pathOwnership.keySet()) {
List<Object> key = (List<Object>) keyObject;
if (key.size() >= path.size() && key.subList(0, path.size()).equals(path)) { // A path below (more specific) than 'path'
owners.add(m_pathOwnership.get(key));
}
}
return owners;
}
/**
* Examine differences between (what would presumably be) the same entity
* in two versions of a record.
*
* 'version' is the new version (whole Record),
* 'previousVersion' is the old one (whole Record),
* 'path' is where in the record(s) we are,
* 'examining' is the object (entity?) being compared,
* 'correspondingPrevious' is the "same" object in the old version
* 'compositePath' is null or a (shorter/higher) path to the latest
* found enclosing "composite object", such as for example a Title,
* which is considered _one value_ even though it is structured and
* has subcomponents. The point of this is that changing (for example)
* a subTitle should result in ownership of the whole title (not just
* the subtitle).
* 'changeSet' is a map in which this function will be building a summary
* of changes this version has.
*/
private void examineDiff(List<Object> path,
DocumentVersion version,
Object examining, Object correspondingPrevious,
List<Object> compositePath,
Map changeSet) {
if (examining instanceof Map) {
if (! (correspondingPrevious instanceof Map) ) {
setOwnership(path, compositePath, version);
return;
}
Set k1 = ((Map) examining).keySet();
Set k2 = ((Map) correspondingPrevious).keySet();
// Is this a composite object ?
Object type = ((Map)examining).get("@type");
if ( type instanceof String &&
( m_jsonLd.isSubClassOf( (String) type, "StructuredValue") ||
m_jsonLd.isSubClassOf( (String) type, "QualifiedRole") ) ) {
compositePath = new ArrayList<>(path);
}
// Key added!
if (!k2.containsAll(k1)) {
Set newKeys = new HashSet(k1);
newKeys.removeAll(k2);
for (Object key : newKeys) {
List<Object> newPath = new ArrayList(path);
newPath.add(key);
setOwnership(newPath, compositePath, version);
((List) changeSet.get("addedPaths")).add(newPath);
}
}
// Key removed!
if (!k1.containsAll(k2)) {
Set removedKeys = new HashSet(k2);
removedKeys.removeAll(k1);
for (Object key : removedKeys) {
List<Object> removedPath = new ArrayList(path);
removedPath.add(key);
clearOwnership(removedPath);
((List) changeSet.get("removedPaths")).add(removedPath);
}
}
}
if (examining instanceof List) {
if (! (correspondingPrevious instanceof List) ) {
setOwnership(path, compositePath, version);
((List) changeSet.get("modifiedPaths")).add(path);
return;
}
}
if (examining instanceof String ||
examining instanceof Float || examining instanceof Boolean) {
if (!examining.equals(correspondingPrevious)) {
setOwnership(path, compositePath, version);
((List) changeSet.get("modifiedPaths")).add(path);
return;
}
}
// Keep scanning
if (examining instanceof List) {
// Create copies of the two lists (so that they can be manipulated)
// and remove from them any elements that _have an identical copy_ in the
// other list.
// This way, only elements that differ somehow remain to be checked, and
// they remain in their relative order to one another.
// Without this, removal or addition of a list element results in every
// _following_ element being compared with the wrong element in the other list.
List tempNew = new LinkedList((List) examining);
List tempOld = new LinkedList((List) correspondingPrevious);
for (int i = 0; i < tempNew.size(); ++i) {
for (int j = 0; j < tempOld.size(); ++j) {
if (tempNew.get(i).equals(tempOld.get(j))) { // Equals will recursively check the entire subtree!
tempNew.remove(i);
tempOld.remove(j);
--i;
--j;
break;
}
}
}
for (int i = 0; i < tempNew.size(); ++i) {
List<Object> childPath = new ArrayList(path);
if ( tempOld.size() > i ) {
childPath.add(Integer.valueOf(i));
examineDiff(childPath, version,
tempNew.get(i), tempOld.get(i),
compositePath, changeSet);
}
}
} else if (examining instanceof Map) {
for (Object key : ((Map) examining).keySet() ) {
List<Object> childPath = new ArrayList(path);
if ( ((Map)correspondingPrevious).get(key) != null ) {
childPath.add(key);
examineDiff(childPath, version,
((Map) examining).get(key), ((Map) correspondingPrevious).get(key),
compositePath, changeSet);
}
}
}
}
private void setOwnership(List<Object> newPath, List<Object> compositePath,
DocumentVersion version) {
List<Object> path;
if (compositePath != null) {
path = compositePath;
} else {
path = newPath;
}
m_pathOwnership.put( path, new Ownership(version, m_pathOwnership.get(path)) );
}
private void clearOwnership(List<Object> removedPath) {
Iterator<List<Object>> it = m_pathOwnership.keySet().iterator();
while (it.hasNext()) {
List<Object> keyPath = it.next();
if (keyPath.size() >= removedPath.size() && keyPath.subList(0, removedPath.size()).equals(removedPath)) {
// removedPath is a more general version of keyPath.
// For example, keyPath might be @graph,1,hasTitle,subTitle
// and the removed path @graph,1,hasTitle
// Therefore, keyPath must be cleared.
it.remove();
}
}
}
/**
* What was put into the changedBy column has varied a bit over XLs history. This
* tries to make sense of the different variants.
*/
private String changedByToUri(String changedBy) {
if (changedBy == null)
return "https://libris.kb.se/library/SEK";
if (changedBy.startsWith("http"))
return changedBy;
if (changedBy.equals("")) // This was the case for script changes for a brief period (early global changes)
return "https://libris.kb.se/library/SEK";
if (changedBy.endsWith(".groovy"))
return "https://libris.kb.se/library/SEK";
if (changedBy.equals("Libriskörning, globala ändringar"))
return "https://libris.kb.se/library/SEK";
if (changedBy.equals("WhelkCopier"))
return "https://libris.kb.se/library/SEK";
else return "https://libris.kb.se/library/" + changedBy;
}
public static boolean wasScriptEdit(DocumentVersion version) {
Instant modifiedInstant = ZonedDateTime.parse(version.doc.getModified()).toInstant();
Instant generatedInstant = ZonedDateTime.parse(version.doc.getGenerationDate()).toInstant();
if (generatedInstant != null && generatedInstant.isAfter( modifiedInstant )) {
return true;
}
return false;
}
// DEBUG CODE BELOW THIS POINT
public String toString() {
StringBuilder b = new StringBuilder();
toString(b, m_lastVersion.doc.data, 0, new ArrayList<>());
return b.toString();
}
private void toString(StringBuilder b, Object current, int indent, List<Object> path) {
if (current instanceof List) {
for (int i = 0; i < ((List) current).size(); ++i) {
beginLine(b, indent, path);
b.append("[\n");
List<Object> childPath = new ArrayList(path);
childPath.add(Integer.valueOf(i));
toString(b, ((List)current).get(i), indent + 1, childPath);
b.setLength(b.length()-1); // drop newline
b.append(",\n");
beginLine(b, indent, path);
b.append("]\n");
}
} else if (current instanceof Map) {
beginLine(b, indent, path);
b.append("{\n");
for (Object key : ((Map) current).keySet() ) {
List<Object> childPath = new ArrayList(path);
childPath.add(key);
beginLine(b, indent+1, childPath);
b.append( "\"" + key + "\"" + " : \n");
toString(b, ((Map) current).get(key), indent + 1, childPath);
b.setLength(b.length()-1); // drop newline
b.append(",\n");
}
beginLine(b, indent, path);
b.append("}\n");
} else {
// Bool, string, number
beginLine(b, indent, path);
b.append("\"");
b.append(current.toString());
b.append("\"");
}
}
private void beginLine(StringBuilder b, int indent, List<Object> path) {
Formatter formatter = new Formatter(b);
formatter.format("%1$-50s| ", getOwnership(path));
for (int i = 0; i < indent; ++i) {
b.append(" ");
}
}
} |
package com.jvpichowski.jme3.states.view;
import com.jme3.app.Application;
import com.jme3.app.state.BaseAppState;
import com.jme3.asset.AssetManager;
import com.jme3.material.Material;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import com.simsilica.es.Entity;
import com.simsilica.es.EntityData;
import com.simsilica.es.EntitySet;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
/**
* Must be attached before ESBulletState
*/
public final class ShapeViewState extends BaseAppState {
private final EntityData entityData;
private final Node rootNode;
private Node sceneRoot;
private List<SpatialContainer> containers;
private EntitySet unshadedEntities;
private EntitySet shadedEntities;
private EntitySet locatedEntities;
private EntitySet rotatedEntities;
private AssetManager assetManager;
public ShapeViewState(EntityData entityData, Node rootNode){
this.rootNode = rootNode;
this.entityData = entityData;
}
@Override
protected void initialize(Application app) {
sceneRoot = new Node("Shapes");
assetManager = app.getAssetManager();
containers = new ArrayList<>(4);
containers.add(new BoxView.Container(entityData, app.getAssetManager(), sceneRoot));
containers.add(new CylinderView.Container(entityData, app.getAssetManager(), sceneRoot));
containers.add(new SphereView.Container(entityData, app.getAssetManager(), sceneRoot));
containers.add(new CapsuleView.Container(entityData, app.getAssetManager(), sceneRoot));
containers.forEach(SpatialContainer::start);
shadedEntities = entityData.getEntities(ShadedColor.class);
unshadedEntities = entityData.getEntities(UnshadedColor.class);
locatedEntities = entityData.getEntities(ViewLocation.class);
rotatedEntities = entityData.getEntities(ViewRotation.class);
}
@Override
protected void cleanup(Application app) {
shadedEntities.release();
unshadedEntities.release();
locatedEntities.release();
rotatedEntities.release();
containers.forEach(SpatialContainer::stop);
containers.forEach(SpatialContainer::destroy);
sceneRoot = null;
}
@Override
protected void onEnable() {
rootNode.attachChild(sceneRoot);
}
@Override
protected void onDisable() {
sceneRoot.removeFromParent();
}
@Override
public void update(float tpf) {
if(!isEnabled()) return;
containers.forEach(SpatialContainer::update);
shadedEntities.applyChanges();
match(containers, shadedEntities.getAddedEntities(),
((entity, spatial) -> ShapeViewState.applyShadedMat(entity, spatial, assetManager)));
match(containers, shadedEntities.getChangedEntities(),
((entity, spatial) -> ShapeViewState.applyShadedMat(entity, spatial, assetManager)));
unshadedEntities.applyChanges();
match(containers, unshadedEntities.getAddedEntities(),
((entity, spatial) -> ShapeViewState.applyUnshadedMat(entity, spatial, assetManager)));
match(containers, unshadedEntities.getChangedEntities(),
((entity, spatial) -> ShapeViewState.applyUnshadedMat(entity, spatial, assetManager)));
locatedEntities.applyChanges();
match(containers, locatedEntities.getAddedEntities(), ShapeViewState::applyViewLocation);
match(containers, locatedEntities.getChangedEntities(), ShapeViewState::applyViewLocation);
rotatedEntities.applyChanges();
match(containers, rotatedEntities.getAddedEntities(), ShapeViewState::applyViewRotation);
match(containers, rotatedEntities.getChangedEntities(), ShapeViewState::applyViewRotation);
}
private static void applyShadedMat(Entity entity, Spatial spatial, AssetManager assetManager){
Material mat = new Material(assetManager, "Common/MatDefs/Light/Lighting.j3md");
mat.setBoolean("UseMaterialColors",true);
mat.setColor("Diffuse", entity.get(ShadedColor.class).getDiffuse());
spatial.setMaterial(mat);
}
private static void applyUnshadedMat(Entity entity, Spatial spatial, AssetManager assetManager){
Material mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
mat.setColor("Color", entity.get(UnshadedColor.class).getColor());
spatial.setMaterial(mat);
}
private static void applyViewRotation(Entity entity, Spatial spatial){
spatial.setLocalRotation(entity.get(ViewRotation.class).getRotation());
}
private static void applyViewLocation(Entity entity, Spatial spatial){
spatial.setLocalTranslation(entity.get(ViewLocation.class).getLocation());
}
/**
* Searches the pair of entity and spatial which are in both structures and applies the consumer to it.
*
* @param containers
* @param entities
* @param consumer
*/
private static void match(List<SpatialContainer> containers, Set<Entity> entities, BiConsumer<Entity, Spatial> consumer){
entities.forEach(entity -> containers.stream().map(c -> c.getObject(entity.getId())).filter(
c -> c != null).forEach(spatial -> consumer.accept(entity, spatial)));
}
} |
package com.lothrazar.samscontent.event;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import org.apache.logging.log4j.Logger;
import com.lothrazar.samscontent.ItemRegistry;
import com.lothrazar.samscontent.ModMain;
import com.lothrazar.samscontent.SpellRegistry;
import com.lothrazar.samscontent.SpellRegistry.EnumSpellType;
import com.lothrazar.samscontent.command.CommandSimpleWaypoints;
import com.lothrazar.samscontent.command.CommandTodoList;
import com.lothrazar.samscontent.potion.PotionRegistry;
import com.lothrazar.util.Location;
import com.lothrazar.util.Reference;
import com.lothrazar.util.Util;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.WorldRenderer;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.client.resources.model.IBakedModel;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.MathHelper;
import net.minecraft.village.Village;
import net.minecraft.world.GameRules;
import net.minecraft.world.World;
import net.minecraft.world.biome.BiomeGenBase;
import net.minecraft.world.chunk.Chunk;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.passive.EntityHorse;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.DimensionManager;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.fml.client.event.ConfigChangedEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.Mod.Instance;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.event.FMLServerStartingEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
public class DebugScreenText
{
public Date addDays(Date baseDate, int daysToAdd)
{
Calendar calendar = Calendar.getInstance();
calendar.setTime(baseDate);
calendar.add(Calendar.DAY_OF_YEAR, daysToAdd);
return calendar.getTime();
}
private static void renderItemAt(ItemStack stack, int x, int y)
{
int height = 16, width = 16;
IBakedModel iBakedModel = Minecraft.getMinecraft().getRenderItem().getItemModelMesher().getItemModel(stack);
TextureAtlasSprite textureAtlasSprite = Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite(iBakedModel.getTexture().getIconName());
renderTexture( textureAtlasSprite, x, y);
}
public static void renderBlockAt(Block block, int x, int y)
{
TextureAtlasSprite textureAtlasSprite = Minecraft.getMinecraft().getBlockRendererDispatcher().getBlockModelShapes().getTexture(block.getDefaultState());
renderTexture( textureAtlasSprite, x, y);
}
private static void renderTexture( TextureAtlasSprite textureAtlasSprite , int x, int y)
{
Minecraft.getMinecraft().getTextureManager().bindTexture(TextureMap.locationBlocksTexture);
Tessellator tessellator = Tessellator.getInstance();
int height = 16, width = 16;
WorldRenderer worldrenderer = tessellator.getWorldRenderer();
worldrenderer.startDrawingQuads();
worldrenderer.addVertexWithUV((double)(x), (double)(y + height), 0.0, (double)textureAtlasSprite.getMinU(), (double)textureAtlasSprite.getMaxV());
worldrenderer.addVertexWithUV((double)(x + width), (double)(y + height), 0.0, (double)textureAtlasSprite.getMaxU(), (double)textureAtlasSprite.getMaxV());
worldrenderer.addVertexWithUV((double)(x + width), (double)(y), 0.0, (double)textureAtlasSprite.getMaxU(), (double)textureAtlasSprite.getMinV());
worldrenderer.addVertexWithUV((double)(x), (double)(y), 0.0, (double)textureAtlasSprite.getMinU(), (double)textureAtlasSprite.getMinV());
tessellator.draw();
}
@SubscribeEvent
public void onRenderTextOverlay(RenderGameOverlayEvent.Text event)
{
EntityPlayerSP player = Minecraft.getMinecraft().thePlayer;
if(Minecraft.getMinecraft().gameSettings.showDebugInfo == false)
{
//EnumChatFormatting.GREEN +
event.left.add(SpellRegistry.getPlayerCurrentSpell(player).name());
int x = 12, y = 15;
EnumSpellType spell = SpellRegistry.getPlayerCurrentSpell(player);
switch(spell)
{
case chest:
//renderBlockAt(Blocks.tripwire_hook,x,y);
//doing it the way below crashes
//renderItemAt(new ItemStack(Item.getItemFromBlock(Blocks.chest)),x,y);
renderItemAt(new ItemStack(ItemRegistry.itemChestSack),x,y);
break;
//TODO: spell clock/compass
case harvest:
renderItemAt(new ItemStack(Items.wheat),x,y);
break;
case firebolt:
renderItemAt(new ItemStack(Items.fire_charge),x,y);
break;
case frostbolt:
renderItemAt(new ItemStack(Items.snowball),x,y);
break;
case ghost:
renderItemAt(new ItemStack(Items.ghast_tear),x,y);
break;
case jump:
renderItemAt(new ItemStack(Items.slime_ball),x,y);
break;
case lightningbolt:
//renderItemAt(new ItemStack(Items.skull,1,Reference.skull_creeper),x,y);
renderItemAt(new ItemStack(Items.gunpowder),x,y);
break;
case pearl:
renderItemAt(new ItemStack(Items.ender_pearl),x,y);
break;
case phase:
renderItemAt(new ItemStack(Items.bed),x,y);
break;
case slowfall:
renderItemAt(new ItemStack(Items.feather),x,y);
break;
case waterwalk:
renderItemAt(new ItemStack(Items.chainmail_boots),x,y);
break;
default:
//System.out.println("unknown spell");
//next = EnumSpellType.chest;//default
break;
}
return;
}
World world = Minecraft.getMinecraft().getIntegratedServer().getEntityWorld();
if(ModMain.cfg.reducedDebugImproved &&
world.getGameRules().getGameRuleBooleanValue(Reference.gamerule.reducedDebugInfo) )
{
//then replace all existing text with just this
event.right.clear();
event.left.clear();
int blockLight = world.getLightFromNeighbors(player.getPosition()) + 1;
String firstLine = Util.lang("debug.biome")+" "+world.getBiomeGenForCoords(player.getPosition()).biomeName;
String light = Util.lang("debug.light")+" "+blockLight;
// +" "+world.getLight(player.getPosition(), true)
// +" "+world.getLightBrightness(player.getPosition())
if(player.isSneaking()) // L for light
firstLine = firstLine +" "+light;
//Minecraft.getMinecraft().getDebugFPS()
event.left.add(firstLine);
}
addDateTimeInfo(event, world);
if(ModMain.cfg.debugSlime && player.dimension == Reference.Dimension.overworld)
{
addSlimeChunkInfo(event, player, world);
}
if(ModMain.cfg.debugVillageInfo && world.villageCollectionObj != null)
{
addVillageInfo(event, player, world);
}
if(ModMain.cfg.debugHorseInfo && player.ridingEntity != null && player.ridingEntity instanceof EntityHorse)
{
addHorseInfo(event, player);
}
CommandSimpleWaypoints.AddWaypointInfo(event);
addTodoCommandInfo(event, player);
if(Util.isShiftKeyDown() && ModMain.cfg.debugGameruleInfo)
{
addGameruleInfo(event, world);
}
//TESTING OUT PLAYER COMPASS CLOCKS PELLS
//System.out.println("width"+ Minecraft.getMinecraft().displayWidth);
int xMiddle = Minecraft.getMinecraft().displayWidth/4;
//System.out.println(" xMiddle "+ xMiddle);
renderItemAt(new ItemStack(Items.compass),xMiddle,16);
renderItemAt(new ItemStack(Items.clock),xMiddle,35);
}
private void addTodoCommandInfo(RenderGameOverlayEvent.Text event, EntityPlayerSP player)
{
String todoCurrent = CommandTodoList.GetTodoForPlayer(player);
if(todoCurrent != null && todoCurrent.isEmpty() == false)
{
event.right.add(todoCurrent);
}
}
private void addGameruleInfo(RenderGameOverlayEvent.Text event, World world)
{
event.right.add("");
GameRules rules = world.getWorldInfo().getGameRulesInstance();
ArrayList<String> ruleNames = new ArrayList<String>();
ruleNames.add(Reference.gamerule.commandBlockOutput);
ruleNames.add(Reference.gamerule.doDaylightCycle);
ruleNames.add(Reference.gamerule.doEntityDrops);
ruleNames.add(Reference.gamerule.doFireTick);
ruleNames.add(Reference.gamerule.doMobLoot);
ruleNames.add(Reference.gamerule.doMobSpawning);
ruleNames.add(Reference.gamerule.doTileDrops);
ruleNames.add(Reference.gamerule.keepInventory);
ruleNames.add(Reference.gamerule.mobGriefing);
ruleNames.add(Reference.gamerule.naturalRegeneration);
ruleNames.add(Reference.gamerule.reducedDebugInfo);
ruleNames.add(Reference.gamerule.sendCommandFeedback);
ruleNames.add(Reference.gamerule.showDeathMessages);
String name;
for(int i = 0; i < ruleNames.size(); i++)
{
name = ruleNames.get(i);
if(rules.getGameRuleBooleanValue(name))
{
event.right.add(EnumChatFormatting.GREEN + name);
}
else
{
event.right.add(EnumChatFormatting.RED + name);
}
}
}
private void addHorseInfo(RenderGameOverlayEvent.Text event, EntityPlayerSP player)
{
EntityHorse horse = (EntityHorse)player.ridingEntity;
double speed = horse.getEntityAttribute(SharedMonsterAttributes.movementSpeed).getAttributeValue() ;
double jump = horse.getHorseJumpStrength() ;
//convert from scale factor to blocks
double jumpHeight = 0;
double gravity = 0.98;
while (jump > 0)
{
jumpHeight += jump;
jump -= 0.08;
jump *= gravity;
}
//http://minecraft.gamepedia.com/Item_id#Horse_Variants
String variant = "";
int var = horse.getHorseVariant();
String spots = null;
if(var >= 1024) spots = "Black Dots ";
else if(var >= 768) spots = "White Dots";
else if(var >= 512) spots = "White Field";
else if(var >= 256) spots = "White Patches";
while(var - 256 > 0)
{
var -= 256;
}
switch( var )
{
case Reference.horse.variant_white: variant = "White";break;
case Reference.horse.variant_creamy: variant = "Creamy";break;
case Reference.horse.variant_chestnut: variant = "Chestnut";break;
case Reference.horse.variant_brown: variant = "Brown";break;
case Reference.horse.variant_black: variant = "Black";break;
case Reference.horse.variant_gray: variant = "Gray";break;
case Reference.horse.variant_brown_dark: variant = "Dark Brown";break;
}
//if its not a horse, variant wont matter
String type = "";
switch( horse.getHorseType())
{
case Reference.horse.type_standard: type = variant + " Horse";break;
case Reference.horse.type_donkey: type = "Donkey";break;
case Reference.horse.type_mule: type = "Mule";break;
case Reference.horse.type_zombie: type = "Zombie Horse";break;
case Reference.horse.type_skeleton: type = "Skeleton Horse";break;
}
if(spots != null) type += " ("+spots+")";
//event.left.add("");
event.left.add(Util.lang("debug.horsetype")+" "+type);
DecimalFormat df = new DecimalFormat("0.0000");
event.left.add(Util.lang("debug.horsespeed")+" "+ df.format(speed) );
df = new DecimalFormat("0.0");
event.left.add(Util.lang("debug.horsejump") +" "+ df.format(jumpHeight) );
}
private void addVillageInfo(RenderGameOverlayEvent.Text event, EntityPlayerSP player, World world)
{
int playerX = MathHelper.floor_double(player.posX);
int playerY = MathHelper.floor_double(player.posY);
int playerZ = MathHelper.floor_double(player.posZ);
int dX,dZ;
int range = 10;
Village closest = world.villageCollectionObj.getNearestVillage(player.getPosition(), range);
if(closest != null)
{
int doors = closest.getNumVillageDoors();
int villagers = closest.getNumVillagers();
int rep = closest.getReputationForPlayer(player.getName());
event.left.add(Util.lang("debug.villagepop")+" "+String.format("%d",villagers));
event.left.add(Util.lang("debug.villagerep")+" "+String.format("%d",rep));
event.left.add(Util.lang("debug.villagedoors")+" "+String.format("%d",doors));
dX = playerX - closest.getCenter().getX();
dZ = playerZ - closest.getCenter().getZ();
int dist = MathHelper.floor_double(Math.sqrt( dX*dX + dZ*dZ));
event.left.add(Util.lang("debug.villagedistcenter")+" "+String.format("%d", dist));
}
}
private void addSlimeChunkInfo(RenderGameOverlayEvent.Text event, EntityPlayerSP player, World world)
{
long seed = world.getSeed();
Chunk in = world.getChunkFromBlockCoords(player.getPosition());
Random rnd = new Random(seed +
(long) (in.xPosition * in.xPosition * 0x4c1906) +
(long) (in.xPosition * 0x5ac0db) +
(long) (in.zPosition * in.zPosition) * 0x4307a7L +
(long) (in.zPosition * 0x5f24f) ^ 0x3ad8025f);
boolean isSlimeChunk = (rnd.nextInt(10) == 0);
if(isSlimeChunk)
{
event.left.add(Util.lang("debug.slimechunk"));
}
}
private void addDateTimeInfo(RenderGameOverlayEvent.Text event, World world)
{
long time = world.getWorldTime();
int days = MathHelper.floor_double( time / Reference.ticksPerDay);
long remainder = time % Reference.ticksPerDay;
String detail = "";
if(remainder < 5000) detail = Util.lang("debug.morning");
else if(remainder < 7000) detail = Util.lang("debug.midday");//midd ay is exactly 6k, so go one on each side
else if(remainder < 12000) detail = Util.lang("debug.afternoon");
else detail = Util.lang("debug.moonphase") + " " + world.getMoonPhase();
// a 365 day calendar. Day Zero is January 1st of year zero?``
//event.left.add("Day "+days +" ("+detail+")");
SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy");
Calendar c1 = Calendar.getInstance(); // TODAY AD
c1.set(Calendar.YEAR, 0); // August 16th, 0 AD
c1.set(Calendar.DAY_OF_YEAR, 1); // January 1st, 0 AD
c1.set(Calendar.YEAR, 1000); // January 1st, 2001 AD
Date start = c1.getTime(); // prints the expected date
Date curr = addDays(start,days);
event.left.add(Util.lang("debug.days") + days +", "+detail);
event.left.add(sdf.format(curr));
}
} |
package com.lyubenblagoev.postfixrest.entity;
import java.util.Date;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@MappedSuperclass
public class BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private boolean enabled;
@Temporal(TemporalType.TIMESTAMP)
private Date created;
@Temporal(TemporalType.TIMESTAMP)
private Date updated;
@PrePersist
public void onPrePersist() {
this.created = new Date();
}
@PreUpdate
public void onPreUpdate() {
this.updated = new Date();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getUpdated() {
return updated;
}
public void setUpdated(Date updated) {
this.updated = updated;
}
} |
package com.profiler.common.mapping.code;
import com.profiler.common.mapping.ApiMappingTable;
import com.profiler.common.mapping.ClassMapping;
import com.profiler.common.mapping.MethodMapping;
import com.profiler.common.mapping.Register;
public class ServerRegister implements Register {
public static final int TomcatStandardHostValveCode = 5000;
private static final ClassMapping TomcatStandardHostValve = new ClassMapping(TomcatStandardHostValveCode, "org.apache.catalina.core.StandardHostValve",
new MethodMapping("invoke", new String[] { "org.apache.catalina.connector.Request", "org.apache.catalina.connector.Response" }, new String[] { "request", "response" })
);
public static final int BlocHttpHandlerCode = 5010;
private static final ClassMapping BlocHttpHandler = new ClassMapping(BlocHttpHandlerCode, "com.nhncorp.lucy.bloc.handler.HTTPHandler$BlocAdapter",
new MethodMapping("execute", new String[] { "external.org.apache.coyote.Request", "external.org.apache.coyote.Response" }, new String[] { "request", "response" })
);
public static final int SpringServletHandlerCode = 5020;
private static final ClassMapping FrameworkServlet = new ClassMapping(SpringServletHandlerCode, "org.springframework.web.servlet.FrameworkServlet",
new MethodMapping("doDelete", new String[] { "javax.servlet.http.HttpServletRequest", "javax.servlet.http.HttpServletResponse" }, new String[]{"request", "response"}),
new MethodMapping("doGet", new String[] { "javax.servlet.http.HttpServletRequest", "javax.servlet.http.HttpServletResponse" }, new String[] { "request", "response" }),
new MethodMapping("doPost", new String[] { "javax.servlet.http.HttpServletRequest", "javax.servlet.http.HttpServletResponse" }, new String[] { "request", "response" }),
new MethodMapping("doPut", new String[] { "javax.servlet.http.HttpServletRequest", "javax.servlet.http.HttpServletResponse" }, new String[] { "request", "response" })
);
public static final int HttpServletHandlerCode = 5030;
private static final ClassMapping HttpServlet = new ClassMapping(HttpServletHandlerCode, "javax.servlet.http.HttpServlet",
new MethodMapping("doDelete", new String[] { "javax.servlet.http.HttpServletRequest", "javax.servlet.http.HttpServletResponse" }, new String[] { "request", "response" }),
new MethodMapping("doGet", new String[] { "javax.servlet.http.HttpServletRequest", "javax.servlet.http.HttpServletResponse" }, new String[] { "request", "response" }),
new MethodMapping("doHead", new String[] { "javax.servlet.http.HttpServletRequest", "javax.servlet.http.HttpServletResponse" }, new String[] { "request", "response" }),
new MethodMapping("doOptions", new String[] { "javax.servlet.http.HttpServletRequest", "javax.servlet.http.HttpServletResponse" }, new String[] { "request", "response" }),
new MethodMapping("doPost", new String[] { "javax.servlet.http.HttpServletRequest", "javax.servlet.http.HttpServletResponse" }, new String[] { "request", "response" }),
new MethodMapping("doPut", new String[] { "javax.servlet.http.HttpServletRequest", "javax.servlet.http.HttpServletResponse" }, new String[] { "request", "response" }),
new MethodMapping("doTrace", new String[] { "javax.servlet.http.HttpServletRequest", "javax.servlet.http.HttpServletResponse" }, new String[] { "request", "response" })
);
@Override
public void register(ApiMappingTable apiMappingTable, int startRange, int endRange) {
apiMappingTable.put(TomcatStandardHostValve);
apiMappingTable.put(BlocHttpHandler);
apiMappingTable.put(FrameworkServlet);
apiMappingTable.put(HttpServlet);
}
} |
package com.rarchives.ripme.ripper.rippers;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import com.rarchives.ripme.ripper.AlbumRipper;
import com.rarchives.ripme.utils.Utils;
public class TumblrRipper extends AlbumRipper {
private static final String DOMAIN = "tumblr.com",
HOST = "tumblr";
private static final Logger logger = Logger.getLogger(TumblrRipper.class);
private enum ALBUM_TYPE {
SUBDOMAIN,
TAG,
POST
}
private ALBUM_TYPE albumType;
private String subdomain, tagName, postNumber;
private final String API_KEY;
public TumblrRipper(URL url) throws IOException {
super(url);
API_KEY = Utils.getConfigString("tumblr.auth", null);
if (API_KEY == null) {
throw new IOException("Could not find tumblr authentication key in configuration");
}
}
@Override
public boolean canRip(URL url) {
return url.getHost().endsWith(DOMAIN);
}
@Override
public URL sanitizeURL(URL url) throws MalformedURLException {
return url;
}
@Override
public void rip() throws IOException {
String[] mediaTypes;
if (albumType == ALBUM_TYPE.POST) {
mediaTypes = new String[] { "post" };
} else {
mediaTypes = new String[] { "photo", "video" };
}
int offset;
for (String mediaType : mediaTypes) {
offset = 0;
while (true) {
String apiURL = getTumblrApiURL(mediaType, offset);
logger.info(" Retrieving " + apiURL);
Document doc = Jsoup.connect(apiURL)
.ignoreContentType(true)
.timeout(10 * 1000)
.header("User-agent", USER_AGENT)
.get();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
logger.error("[!] Interrupted while waiting to load next album:", e);
break;
}
String jsonString = doc.body().html().replaceAll(""", "\"");
if (!handleJSON(jsonString)) {
// Returns false if an error occurs and we should stop.
break;
}
offset += 20;
}
}
waitForThreads();
}
private boolean handleJSON(String jsonString) {
JSONObject json = new JSONObject(jsonString);
if (json == null || !json.has("response")) {
logger.error("[!] JSON response from tumblr was invalid: " + jsonString);
return false;
}
JSONArray posts, photos;
JSONObject post, photo;
URL fileURL;
posts = json.getJSONObject("response").getJSONArray("posts");
if (posts.length() == 0) {
logger.info(" Zero posts returned.");
return false;
}
for (int i = 0; i < posts.length(); i++) {
post = posts.getJSONObject(i);
if (post.has("photos")) {
photos = post.getJSONArray("photos");
for (int j = 0; j < photos.length(); j++) {
photo = photos.getJSONObject(j);
try {
fileURL = new URL(photo.getJSONObject("original_size").getString("url"));
addURLToDownload(fileURL);
} catch (Exception e) {
logger.error("[!] Error while parsing photo in " + photo, e);
continue;
}
}
} else if (post.has("video_url")) {
try {
fileURL = new URL(post.getString("video_url"));
addURLToDownload(fileURL);
} catch (Exception e) {
logger.error("[!] Error while parsing video in " + post, e);
return true;
}
}
if (albumType == ALBUM_TYPE.POST) {
return false;
}
}
return true;
}
private String getTumblrApiURL(String mediaType, int offset) {
StringBuilder sb = new StringBuilder();
if (albumType == ALBUM_TYPE.POST) {
sb.append("http://api.tumblr.com/v2/blog/")
.append(subdomain)
.append(".tumblr.com/posts?id=")
.append(postNumber)
.append("&api_key=")
.append(API_KEY);
return sb.toString();
}
sb.append("http://api.tumblr.com/v2/blog/")
.append(subdomain)
.append(".tumblr.com/posts/")
.append(mediaType)
.append("?api_key=")
.append(API_KEY)
.append("&offset=")
.append(offset);
if (albumType == ALBUM_TYPE.TAG) {
sb.append("&tag=")
.append(tagName);
}
return sb.toString();
}
@Override
public String getHost() {
return HOST;
}
@Override
public String getGID(URL url) throws MalformedURLException {
Pattern p;
Matcher m;
// Tagged URL
p = Pattern.compile("^https?://([a-zA-Z0-9\\-]{1,})\\.tumblr\\.com/tagged/([a-zA-Z0-9\\-%]{1,}).*$");
m = p.matcher(url.toExternalForm());
if (m.matches()) {
this.albumType = ALBUM_TYPE.TAG;
this.subdomain = m.group(1);
this.tagName = m.group(2);
this.tagName = this.tagName.replace('-', '+').replace("_", "%20");
return this.subdomain + "_tag_" + this.tagName.replace("%20", " ");
}
// Post URL
p = Pattern.compile("^https?://([a-zA-Z0-9\\-]{1,})\\.tumblr\\.com/post/([0-9]{1,}).*$");
m = p.matcher(url.toExternalForm());
if (m.matches()) {
this.albumType = ALBUM_TYPE.POST;
this.subdomain = m.group(1);
this.postNumber = m.group(2);
return this.subdomain + "_post_" + this.postNumber;
}
// Subdomain-level URL
p = Pattern.compile("^https?://([a-zA-Z0-9\\-]{1,})\\.tumblr\\.com/?.*$");
m = p.matcher(url.toExternalForm());
if (m.matches()) {
this.albumType = ALBUM_TYPE.SUBDOMAIN;
this.subdomain = m.group(1);
return this.subdomain;
}
// TODO support non-tumblr.com domains
throw new MalformedURLException("Expected format: http://user.tumblr.com[/tagged/tag|/post/postno]");
}
} |
package wcanalysis.heuristic.model;
import gov.nasa.jpf.symbc.numeric.PCChoiceGenerator;
import gov.nasa.jpf.symbc.numeric.PathCondition;
import gov.nasa.jpf.vm.ChoiceGenerator;
import gov.nasa.jpf.vm.Instruction;
import gov.nasa.jpf.vm.ThreadInfo;
import gov.nasa.jpf.vm.VM;
/**
* @author Kasper Luckow
*
*/
public final class DepthState extends State {
public final static class DepthStateBuilder extends StateBuilderAdapter {
private int depth = 0;
private long instrExecuted = 0;
public DepthStateBuilder() { }
private DepthStateBuilder(int depth, long instrExecuted) {
this.depth = depth;
this.instrExecuted = instrExecuted;
}
@Override
public void handleChoiceGeneratorAdvanced(VM vm, ChoiceGenerator<?> currentCG) {
if(currentCG instanceof PCChoiceGenerator)
this.depth++;
}
@Override
public void handleInstructionExecuted(VM vm, ThreadInfo currentThread, Instruction nextInstruction,
Instruction executedInstruction) {
this.instrExecuted++;
}
@Override
public StateBuilder copy() {
return new DepthStateBuilder(this.depth, this.instrExecuted);
}
@Override
public State build(PathCondition resultingPC) {
return new DepthState(resultingPC, this.depth, this.instrExecuted);
}
}
private final int depth;
private final long instrExecuted;
DepthState(PathCondition pc, int depth, long instrExecuted) {
super(pc);
this.depth = depth;
this.instrExecuted = instrExecuted;
}
public int getDepth() {
return depth;
}
public long getInstrExecuted() {
return instrExecuted;
}
@Override
public double getWC() {
return getDepth();
}
@Override
public int compareTo(State o) {
if(!(o instanceof DepthState)) {
throw new IllegalStateException("Expected state of type " + DepthState.class.getName());
}
return (int)(this.depth - ((DepthState)o).depth);
}
@Override
public String getCSVHeader() {
return "wcDepth,wcInstrExec";
}
@Override
public String getCSV() {
return this.depth + "," + this.instrExecuted;
}
} |
package com.s24.redjob.channel.command;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.s24.redjob.queue.QueueWorker;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import static java.util.Collections.emptyList;
/**
* Command to shutdown queue workers.
*/
@JsonTypeName
public class PauseQueueWorker {
/**
* Pause (true) or unpause (false) workers?.
*/
private boolean pause;
/**
* Workers of which queues should be paused.
* If empty, all workers will be paused.
*/
private Set<String> queues = new HashSet<>();
/**
* Hidden default constructor for Jackson.
*/
@JsonCreator
PauseQueueWorker() {
}
/**
* Constructor to pause/unpause all workers.
*/
public PauseQueueWorker(boolean pause) {
this(pause, emptyList());
}
/**
* Constructor to pause/unpause workers processing the given queues.
*
* @param pause
* Pause (true) or unpause (false)?
* @param queues
* Queues to select workers. If empty, select all workers.
*/
public PauseQueueWorker(boolean pause, String... queues) {
this(pause, Arrays.asList(queues));
}
/**
* Constructor to pause/unpause workers processing the given queues.
*
* @param pause
* Pause (true) or unpause (false)?
* @param queues
* Queues to select workers. If empty, select all workers.
*/
public PauseQueueWorker(boolean pause, Collection<String> queues) {
this.pause = pause;
this.queues.addAll(queues);
}
/**
* Pause (true) or unpause (false) workers?.
*/
public boolean isPause() {
return pause;
}
/**
* Workers of which queues should be paused.
* If empty, all workers will be paused.
*/
public Set<String> getQueues() {
return queues;
}
/**
* Does the worker match the selectors of the job?.
*/
protected boolean matches(QueueWorker worker) {
return queues.isEmpty() || worker.getQueues().stream().anyMatch(queues::contains);
}
} |
package com.techcavern.wavetact.commands.utils;
import com.techcavern.wavetact.annot.CMD;
import com.techcavern.wavetact.annot.GenCMD;
import com.techcavern.wavetact.utils.GeneralUtils;
import com.techcavern.wavetact.utils.IRCUtils;
import com.techcavern.wavetact.utils.objects.GenericCommand;
import org.pircbotx.Channel;
import org.pircbotx.PircBotX;
import org.pircbotx.User;
import java.net.InetAddress;
import java.net.Socket;
@CMD
@GenCMD
public class PingTime extends GenericCommand {
public PingTime() {
super(GeneralUtils.toArray("pingtime checkping chping ptime"), 0, "pingtime [website] (port)"," checks pingtime to a certain domain/address/ip/etc (IPv6 NOT supported)");
}
@Override
public void onCommand(User user, PircBotX Bot, Channel channel, boolean isPrivate, int UserPermLevel, String... args) throws Exception {
int port;
if (args.length < 2) {
port = 80;
} else {
port = Integer.parseInt(args[1]);
}
Long time = System.currentTimeMillis();
Socket socket = new Socket(GeneralUtils.getIP(args[0], Bot), port);
socket.close();
time = System.currentTimeMillis() - time;
IRCUtils.SendMessage(user, channel, "Ping Time: " + time + " milliseconds", isPrivate);
}
} |
package com.tlswe.awsmock.ec2.control;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import com.tlswe.awsmock.common.exception.AwsMockException;
import com.tlswe.awsmock.ec2.cxf_generated.InstanceStateChangeType;
import com.tlswe.awsmock.ec2.cxf_generated.InstanceStateType;
import com.tlswe.awsmock.ec2.exception.BadEc2RequestException;
import com.tlswe.awsmock.ec2.model.AbstractMockEc2Instance;
import com.tlswe.awsmock.ec2.model.AbstractMockEc2Instance.InstanceType;
/**
* Factory class providing static methods for managing life cycle of mock ec2 instances. The current implementations
* can:
* <ul>
* <li>run</li>
* <li>stop</li>
* <li>terminate</li>
* <li>describe</li>
* </ul>
* mock ec2 instances only. <br>
*
*
* @author xma
*
*/
public final class MockEc2Controller {
/**
* Singleton instance of MockEc2Controller.
*/
private static MockEc2Controller singletonMockEc2Controller = null;
/**
* Max allowed number of mock instances to run at a time (a single request).
*/
private static final int MAX_RUN_INSTANCE_COUNT_AT_A_TIME = 10000;
// private static final Random _random = new Random();
/**
* A map of all the mock ec2 instances, instanceID as key and {@link AbstractMockEc2Instance} as value.
*/
private final Map<String, AbstractMockEc2Instance> allMockEc2Instances =
new ConcurrentHashMap<String, AbstractMockEc2Instance>();
/**
* Internal timer for cleaning up terminated mock ec2 instances.
*/
private ScheduledExecutorService cleanupTerminatedInstancesTimer = null;
/**
* The result of scheduling a task with a {@link ScheduledExecutorService}.
*/
private ScheduledFuture cleanupTerminatedInstancesScheduledFuture = null;
/**
* Constructor of MockEc2Controller is made private and only called once by {@link #getInstance()}.
*/
private MockEc2Controller() {
}
/**
*
* @return singleton instance of {@link MockEc2Controller}
*/
public static MockEc2Controller getInstance() {
if (null == singletonMockEc2Controller) {
// "double lock lazy loading" for singleton instance loading on first time usage
synchronized (MockEc2Controller.class) {
if (null == singletonMockEc2Controller) {
singletonMockEc2Controller = new MockEc2Controller();
}
}
}
return singletonMockEc2Controller;
}
/**
* List mock ec2 instances in current aws-mock.
*
* @param instanceIDs
* a filter of specified instance IDs for the target instance to describe
* @return a collection of {@link AbstractMockEc2Instance} with specified instance IDs, or all of the mock ec2
* instances if no instance IDs as filtered
*/
public Collection<AbstractMockEc2Instance> describeInstances(final Set<String> instanceIDs) {
if (null == instanceIDs || instanceIDs.size() == 0) {
return allMockEc2Instances.values();
} else {
return getInstances(instanceIDs);
}
}
/**
* List mock ec2 instance IDs in current aws-mock.
*
* @param instanceIDs
* a filter of specified instance IDs for the target instance to describe
* @return a collection of IDs with specified instance IDs, or all of the mock ec2 instanceIDs if not filtered
*/
public List<String> listInstanceIDs(final Set<String> instanceIDs) {
Set<String> allInstanceIDs = allMockEc2Instances.keySet();
if (null == instanceIDs || instanceIDs.size() == 0) {
return new ArrayList<String>(allInstanceIDs);
} else {
List<String> filteredInstanceIDs = new ArrayList<String>();
for (String id : allInstanceIDs) {
if (null != id && instanceIDs.contains(id)) {
filteredInstanceIDs.add(id);
}
}
return filteredInstanceIDs;
}
}
/**
*
* Create and run mock ec2 instances.
*
* @param <T>
* The template type of class as concrete type of mock ec2 instance to run as, should extend
* {@link AbstractMockEc2Instance}, matching the clazz parameter
* @param clazz
* class as concrete type of mock ec2 instance to run as, should extend {@link AbstractMockEc2Instance}
* @param imageId
* AMI of new mock ec2 instance(s)
* @param instanceTypeName
* type(scale) name of new mock ec2 instance(s)
* @param minCount
* max count of instances to run (but limited to {@link #MAX_RUN_INSTANCE_COUNT_AT_A_TIME})
* @param maxCount
* min count of instances to run (should larger than 0)
* @return a list of objects of clazz as started new mock ec2 instances
*
*/
public <T extends AbstractMockEc2Instance> List<T> runInstances(final Class<? extends T> clazz,
final String imageId, final String instanceTypeName,
final int minCount, final int maxCount) {
// EC2 Query Request action name
final String action = "runInstances";
/*-
* throws an exception in case of error parsing for a correct request conformed to EC2 QUERY API which
* should be built by AWS client tool correctly
*/
InstanceType instanceType = InstanceType.getByName(instanceTypeName);
if (null == instanceType) {
throw new BadEc2RequestException(action, "illegal instance type: " + instanceTypeName);
}
if (maxCount > MAX_RUN_INSTANCE_COUNT_AT_A_TIME) {
throw new BadEc2RequestException(action, "you can not request to run more than "
+ MAX_RUN_INSTANCE_COUNT_AT_A_TIME
+ " instances at a time!");
}
if (minCount < 1) {
throw new BadEc2RequestException(action, "you should request to run at least 1 instance!");
}
if (minCount > maxCount) {
throw new BadEc2RequestException(action, "minCount should not be greater than maxCount!");
}
List<T> ret = new ArrayList<T>();
/*-
* startup as much instances as possible
*/
for (int i = 0; i < maxCount; i++) {
T inst = null;
try {
inst = clazz.newInstance();
} catch (InstantiationException e) {
throw new AwsMockException("failed to instantiate class " + clazz.getName()
+ ", please make sure sure this class extends com.tlswe.awsmock.ec2.model.MockEc2Instance "
+ "and has a public constructor with no parameters. ", e);
} catch (IllegalAccessException e) {
throw new AwsMockException("failed to access constructor of " + clazz.getName()
+ ", please make sure the constructor with no parameters is public. ", e);
}
inst.setImageId(imageId);
inst.setInstanceType(instanceType);
// inst.setSecurityGroups(securityGroups);
inst.start();
// internal timer should be initialized once right after mock ec2
// instance is created and run
inst.initializeInternalTimer();
ret.add(inst);
allMockEc2Instances.put(inst.getInstanceID(), inst);
}
return ret;
}
/**
* Start one or more existing mock ec2 instances.
*
* @param instanceIDs
* a set of instance IDs for those instances to start
* @return a list of state change messages (typically stopped to running)
*/
public List<InstanceStateChangeType> startInstances(final Set<String> instanceIDs) {
List<InstanceStateChangeType> ret = new ArrayList<InstanceStateChangeType>();
Collection<AbstractMockEc2Instance> instances = getInstances(instanceIDs);
for (AbstractMockEc2Instance instance : instances) {
if (null != instance) {
InstanceStateChangeType stateChange = new InstanceStateChangeType();
stateChange.setInstanceId(instance.getInstanceID());
InstanceStateType previousState = new InstanceStateType();
previousState.setCode(instance.getInstanceState().getCode());
previousState.setName(instance.getInstanceState().getName());
stateChange.setPreviousState(previousState);
instance.start();
InstanceStateType newState = new InstanceStateType();
newState.setCode(instance.getInstanceState().getCode());
newState.setName(instance.getInstanceState().getName());
stateChange.setCurrentState(newState);
ret.add(stateChange);
}
}
return ret;
}
/**
* Stop one or more existing mock ec2 instances.
*
* @param instanceIDs
* a set of instance IDs for those instances to stop
* @return a list of state change messages (typically running to stopping)
*/
public List<InstanceStateChangeType> stopInstances(final Set<String> instanceIDs) {
List<InstanceStateChangeType> ret = new ArrayList<InstanceStateChangeType>();
Collection<AbstractMockEc2Instance> instances = getInstances(instanceIDs);
for (AbstractMockEc2Instance instance : instances) {
if (null != instance) {
InstanceStateChangeType stateChange = new InstanceStateChangeType();
stateChange.setInstanceId(instance.getInstanceID());
InstanceStateType previousState = new InstanceStateType();
previousState.setCode(instance.getInstanceState().getCode());
previousState.setName(instance.getInstanceState().getName());
stateChange.setPreviousState(previousState);
instance.stop();
InstanceStateType newState = new InstanceStateType();
newState.setCode(instance.getInstanceState().getCode());
newState.setName(instance.getInstanceState().getName());
stateChange.setCurrentState(newState);
ret.add(stateChange);
}
}
return ret;
}
/**
* Terminate one or more existing mock ec2 instances.
*
* @param instanceIDs
* a set of instance IDs for those instances to terminate
* @return a list of state change messages (typically running/stopped to terminated)
*/
public List<InstanceStateChangeType> terminateInstances(final Set<String> instanceIDs) {
List<InstanceStateChangeType> ret = new ArrayList<InstanceStateChangeType>();
Collection<AbstractMockEc2Instance> instances = getInstances(instanceIDs);
for (AbstractMockEc2Instance instance : instances) {
if (null != instance) {
InstanceStateChangeType stateChange = new InstanceStateChangeType();
stateChange.setInstanceId(instance.getInstanceID());
InstanceStateType previousState = new InstanceStateType();
previousState.setCode(instance.getInstanceState().getCode());
previousState.setName(instance.getInstanceState().getName());
stateChange.setPreviousState(previousState);
instance.terminate();
InstanceStateType newState = new InstanceStateType();
newState.setCode(instance.getInstanceState().getCode());
newState.setName(instance.getInstanceState().getName());
stateChange.setCurrentState(newState);
ret.add(stateChange);
}
}
return ret;
}
/**
* List all mock ec2 instances within aws-mock.
*
* @return a collection of all the mock ec2 instances
*/
public Collection<AbstractMockEc2Instance> getAllMockEc2Instances() {
return allMockEc2Instances.values();
}
/**
* Get mock ec2 instance by instance ID.
*
* @param instanceID
* ID of the mock ec2 instance to get
* @return the mock ec2 instance object
*/
public AbstractMockEc2Instance getMockEc2Instance(final String instanceID) {
return allMockEc2Instances.get(instanceID);
}
/**
* Get mock ec2 instances by instance IDs.
*
* @param instanceIDs
* IDs of the mock ec2 instances to get
* @return the mock ec2 instances object
*/
private Collection<AbstractMockEc2Instance> getInstances(final Set<String> instanceIDs) {
Collection<AbstractMockEc2Instance> ret = new ArrayList<AbstractMockEc2Instance>();
for (String instanceID : instanceIDs) {
ret.add(getMockEc2Instance(instanceID));
}
return ret;
}
/**
* Clear {@link #allMockEc2Instances} and restore it from given a collection of instances.
*
* @param instances
* collection of {@link #getMockEc2Instance(String)} to restore
*/
public void restoreAllMockEc2Instances(final Collection<AbstractMockEc2Instance> instances) {
allMockEc2Instances.clear();
if (null != instances) {
for (AbstractMockEc2Instance instance : instances) {
allMockEc2Instances.put(instance.getInstanceID(), instance);
// re-initialize the internal timer
instance.initializeInternalTimer();
}
}
}
/**
* Clean up terminated mock instances after a pre-defined period. Period is defined in aws-mock.properties (or if
* not overridden, as defined in aws-mock-default.properties)
*
* @param period
* time period to clean up terminated instances
*/
public void cleanupTerminatedInstances(final long period) {
Runnable cleanupTerminatedInstancesTask = new Runnable() {
/**
* this method is triggered every pre-defined period
*/
private String terminatedState = AbstractMockEc2Instance.InstanceState.TERMINATED.getName();
@Override
public void run() {
// traverse the map allMockEc2Instances and clean up the terminated ones
for (AbstractMockEc2Instance instance : allMockEc2Instances.values()) {
if (terminatedState.equals(instance.getInstanceState().getName())) {
allMockEc2Instances.remove(instance.getInstanceID());
}
}
}
};
cleanupTerminatedInstancesTimer = Executors.newSingleThreadScheduledExecutor();
cleanupTerminatedInstancesScheduledFuture = cleanupTerminatedInstancesTimer.
scheduleAtFixedRate(cleanupTerminatedInstancesTask, 0L, period, TimeUnit.SECONDS);
}
/**
* Cancel the internal timer of cleaning up terminated mock ec2 instances.
*/
public void destroyCleanupTerminatedInstanceTimer() {
cleanupTerminatedInstancesScheduledFuture.cancel(true);
cleanupTerminatedInstancesScheduledFuture = null;
cleanupTerminatedInstancesTimer.shutdown();
cleanupTerminatedInstancesTimer = null;
}
} |
package com.vaguehope.onosendai.images;
import java.util.concurrent.Executor;
import android.app.Activity;
import android.graphics.Bitmap;
public final class ImageLoaderUtils {
private ImageLoaderUtils () {
throw new AssertionError();
}
public static ImageLoader fromActivity (final Activity activity) {
if (!(activity instanceof ImageLoader)) throw new IllegalArgumentException("Activity is not an ImageLoader: " + activity);
return (ImageLoader) activity;
}
public static void loadImage (final HybridBitmapCache cache, final ImageLoadRequest req) {
loadImage(cache, req, null);
}
public static void loadImage (final HybridBitmapCache cache, final ImageLoadRequest req, final Executor exec) {
final Bitmap bmp = cache.quickGet(req.getUrl());
if (bmp != null) {
req.setImageBitmap(bmp);
}
else {
req.setImagePending();
final ImageFetcherTask task = new ImageFetcherTask(cache);
if (exec != null) {
task.executeOnExecutor(exec, req);
}
else {
task.execute(req);
}
}
}
} |
package com.yahoo.sketches.theta;
import static com.yahoo.sketches.Util.DEFAULT_NOMINAL_ENTRIES;
import static com.yahoo.sketches.Util.DEFAULT_UPDATE_SEED;
import static com.yahoo.sketches.Util.LS;
import static com.yahoo.sketches.Util.MAX_LG_NOM_LONGS;
import static com.yahoo.sketches.Util.MIN_LG_NOM_LONGS;
import static com.yahoo.sketches.Util.TAB;
import static com.yahoo.sketches.Util.ceilingPowerOf2;
import com.yahoo.memory.WritableMemory;
import com.yahoo.sketches.SketchesArgumentException;
import com.yahoo.sketches.SketchesStateException;
/**
* For building concurrent buffers and shared theta sketch
*
* @author Lee Rhodes
*/
public class ConcurrentThetaBuilder {
private int bLgNomLongs;
private long bSeed;
private int bCacheLimit;
private boolean bPropagateOrderedCompact;
private int bPoolThreads;
private ConcurrentDirectThetaSketch bShared;
/**
* Constructor for building concurrent buffers and the shared theta sketch.
* The shared theta sketch must be built first.
*
*/
public ConcurrentThetaBuilder() {
bLgNomLongs = Integer.numberOfTrailingZeros(DEFAULT_NOMINAL_ENTRIES);
bSeed = DEFAULT_UPDATE_SEED;
bCacheLimit = 1;
bPropagateOrderedCompact = true;
bPoolThreads = 3;
bShared = null;
}
/**
* Returns a ConcurrentHeapThetaBuffer with the current configuration of this Builder,
* which must include a valid ConcurrentDirectThetaSketch.
* @return an ConcurrentHeapThetaBuffer
*/
public ConcurrentHeapThetaBuffer build() {
if (bShared == null) {
throw new SketchesStateException("The ConcurrentDirectThetaSketch must be build first.");
}
return new ConcurrentHeapThetaBuffer(
bLgNomLongs, bSeed, bCacheLimit, bShared, bPropagateOrderedCompact);
}
/**
* Returns a ConcurrentDirectThetaSketch with the current configuration of the Builder
* and the given destination WritableMemory.
* @param dstMem the given WritableMemory
* @return a ConcurrentDirectThetaSketch with the current configuration of the Builder
* and the given destination WritableMemory.
*/
public ConcurrentDirectThetaSketch build(final WritableMemory dstMem) {
if (dstMem == null) {
throw new SketchesArgumentException("Destination WritableMemory cannot be null.");
}
bShared = ConcurrentDirectThetaSketch.initNewDirectInstance(
bLgNomLongs, bSeed, dstMem, bPoolThreads);
return bShared;
}
/**
* Sets the Nominal Entries for this sketch. The minimum value is 16 and the maximum value is
* 67,108,864, which is 2^26. Be aware that sketches as large as this maximum value have not
* been thoroughly tested or characterized for performance.
* @param nomEntries <a href="{@docRoot}/resources/dictionary.html#nomEntries">Nominal Entres</a>
* This will become the ceiling power of 2 if it is not.
* @return this ConcurrentThetaBuilder
*/
public ConcurrentThetaBuilder setNominalEntries(final int nomEntries) {
bLgNomLongs = Integer.numberOfTrailingZeros(ceilingPowerOf2(nomEntries));
if ((bLgNomLongs > MAX_LG_NOM_LONGS) || (bLgNomLongs < MIN_LG_NOM_LONGS)) {
throw new SketchesArgumentException("Nominal Entries must be >= 16 and <= 67108864: "
+ nomEntries);
}
return this;
}
/**
* Returns Log-base 2 Nominal Entries
* @return Log-base 2 Nominal Entries
*/
public int getLgNominalEntries() {
return bLgNomLongs;
}
/**
* Sets the long seed value that is required by the hashing function.
* @param seed <a href="{@docRoot}/resources/dictionary.html#seed">See seed</a>
* @return this ConcurrentThetaBuilder
*/
public ConcurrentThetaBuilder setSeed(final long seed) {
bSeed = seed;
return this;
}
/**
* Returns the seed
* @return the seed
*/
public long getSeed() {
return bSeed;
}
/**
* Sets the number of ExecutorService, Executors.newWorkStealingPool poolThreads.
* @param poolThreads the given poolThreads
* @return this ConcurrentThetaBuilder
*/
public ConcurrentThetaBuilder setPoolThreads(final int poolThreads) {
bPoolThreads = poolThreads;
return this;
}
/**
* Gets the number of ExecutorService, Executors.newWorkStealingPool poolThreads.
* @return the number of ExecutorService, Executors.newWorkStealingPool poolThreads.
*/
public int getPoolThreads() {
return bPoolThreads;
}
/**
* Sets the cache limit size for the ConcurrentHeapThetaBuffer.
* @param cacheLimit the given cacheLimit
* @return this ConcurrentThetaBuilder
*/
public ConcurrentThetaBuilder setCacheLimit(final int cacheLimit) {
bCacheLimit = cacheLimit;
return this;
}
/**
* Gets the cache limit size for the ConcurrentHeapThetaBuffer.
* @return the cache limit size for the ConcurrentHeapThetaBuffer.
*/
public int getCacheLimit() {
return bCacheLimit;
}
/**
* Gets the shared ConcurrentDirectThetaSketch or null if not set.
* @return the shared ConcurrentDirectThetaSketch or null if not set.
*/
public ConcurrentDirectThetaSketch getSharedSketch() {
return bShared;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("ConcurrentThetaBuilder configuration:").append(LS);
sb.append("LgK:").append(TAB).append(bLgNomLongs).append(LS);
sb.append("K:").append(TAB).append(1 << bLgNomLongs).append(LS);
sb.append("Seed:").append(TAB).append(bSeed).append(LS);
sb.append("Pool Threads:").append(TAB).append(bPoolThreads).append(LS);
sb.append("Cache Limit:").append(TAB).append(bCacheLimit).append(LS);
final String str = (bShared != null) ? bShared.getClass().getSimpleName() : "null";
sb.append("Shared Sketch:").append(TAB).append(str).append(LS);
return sb.toString();
}
} |
package de.unibremen.opensores.controller;
import de.unibremen.opensores.util.DateUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.commons.io.FileUtils;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;
import org.mindrot.jbcrypt.BCrypt;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import de.unibremen.opensores.util.tme.Parser;
import de.unibremen.opensores.util.tme.TMEObject;
import de.unibremen.opensores.util.tme.TMEArray;
import de.unibremen.opensores.model.User;
import de.unibremen.opensores.model.Group;
import de.unibremen.opensores.model.Course;
import de.unibremen.opensores.model.Student;
import de.unibremen.opensores.model.Tutorial;
import de.unibremen.opensores.model.Semester;
import de.unibremen.opensores.model.GlobalRole;
import de.unibremen.opensores.model.PrivilegedUser;
import de.unibremen.opensores.model.ParticipationType;
import de.unibremen.opensores.service.UserService;
import de.unibremen.opensores.service.GroupService;
import de.unibremen.opensores.service.CourseService;
import de.unibremen.opensores.service.StudentService;
import de.unibremen.opensores.service.TutorialService;
import de.unibremen.opensores.service.SemesterService;
import de.unibremen.opensores.service.PrivilegedUserService;
import de.unibremen.opensores.exception.TmeException;
import de.unibremen.opensores.exception.SemesterFormatException;
import java.util.Map;
import java.util.HashMap;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.text.ParseException;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.context.ExternalContext;
import javax.faces.bean.ViewScoped;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ResourceBundle;
@ManagedBean
@ViewScoped
public class TmeController implements Serializable {
/**
* Unique serial version uid.
*/
private static final long serialVersionUID = -126631593355925099L;
/**
* The log4j logger.
*/
private Logger log = LogManager.getLogger(TmeController.class);
/**
* User service for connecting to the database.
*/
@EJB
private transient UserService userService;
/**
* Course service for connecting to the database.
*/
@EJB
private transient CourseService courseService;
/**
* Semester service for connecting to the database.
*/
@EJB
private transient SemesterService semesterService;
/**
* Tutorial service for connecting to the database.
*/
@EJB
private transient TutorialService tutorialService;
/**
* PrivilegedUser service for connecting to the database.
*/
@EJB
private transient PrivilegedUserService privilegedUserService;
/**
* Student service for connecting to the database.
*/
@EJB
private transient StudentService studentService;
/**
* Group service for connecting to the database.
*/
@EJB
private transient GroupService groupService;
/**
* List of uploaded files by the user.
*/
@SuppressFBWarnings(value = "SE_TRANSIENT_FIELD_NOT_RESTORED",
justification = "actually findbugs is right this needs to be "
+ "serializable but I am too lazy to fix it")
private transient List<UploadedFile> files = new ArrayList<>();
/**
* Maps TME ids to JPA entities.
*/
private HashMap<Integer, Object> entityMap = new HashMap<>();
/**
* Maps TME ids to TME objects.
*/
private HashMap<Integer, TMEObject> nodeMap = new HashMap<>();
/**
* Handles file upload events.
*/
public void handleFileUpload(FileUploadEvent event) {
FacesContext facesContext = FacesContext.getCurrentInstance();
ResourceBundle bundle = ResourceBundle.getBundle("messages",
facesContext.getViewRoot().getLocale());
UploadedFile file = event.getFile();
if (file == null) {
facesContext.addMessage(null, new FacesMessage(FacesMessage
.SEVERITY_FATAL, bundle.getString("common.error"),
bundle.getString("courses.create.uploadFail")));
return;
}
files.add(file);
}
/**
* Uploads all files to the temporary folder.
*
* @return List of successfully uploaded files.
* @throws IOException If uploading an individual file failed.
*/
private List<File> uploadFiles() throws IOException {
List<File> uploadedFiles = new ArrayList<>();
for (UploadedFile file : files) {
Path fp = Files.createTempFile("exmatrikulator", file.getFileName());
Files.copy(file.getInputstream(), fp,
StandardCopyOption.REPLACE_EXISTING);
uploadedFiles.add(fp.toFile());
}
return uploadedFiles;
}
/**
* Imports the uploaded files.
*/
public void importFiles() {
FacesContext facesContext = FacesContext.getCurrentInstance();
ResourceBundle bundle = ResourceBundle.getBundle("messages",
facesContext.getViewRoot().getLocale());
List<File> uploaded = null;
try {
uploaded = uploadFiles();
} catch (IOException e) {
log.error(e);
facesContext.addMessage(null, new FacesMessage(FacesMessage
.SEVERITY_ERROR, bundle.getString("common.error"),
bundle.getString("courses.create.storeError")));
return;
}
List<TMEObject> objs = new ArrayList<>();
for (File file : uploaded) {
try {
String data = FileUtils.readFileToString(file);
objs.addAll(new Parser(data).getTMEObjects());
} catch (InterruptedException | IOException e) {
log.fatal(e);
return;
} catch (ParseException e) {
log.error(e);
facesContext.addMessage(null, new FacesMessage(FacesMessage
.SEVERITY_ERROR, bundle.getString("common.error"),
e.getMessage()));
}
if (!file.delete()) {
log.debug("failed to delte temporary upload file");
}
}
try {
importObjects(objs);
} catch (TmeException e) {
log.error(e);
facesContext.addMessage(null, new FacesMessage(FacesMessage
.SEVERITY_ERROR, bundle.getString("common.error"),
e.getMessage()));
return;
}
facesContext.addMessage(null, new FacesMessage(FacesMessage
.SEVERITY_INFO, bundle.getString("common.success"),
bundle.getString("import.success")));
}
/**
* Imports the given list of TMEObjects.
*
* @param objs TMEObject to import.
* @throws TmeException On a failed import.
*/
private void importObjects(List<TMEObject> objs)
throws TmeException {
for (TMEObject obj : objs) {
int id = obj.getId();
if (nodeMap.containsKey(id)) {
throw new TmeException("Duplicated id " + id);
} else {
nodeMap.put(id, obj);
}
}
for (TMEObject obj : objs) {
String[] splited = obj.getName().split("\\.");
if (splited.length <= 0) {
throw new TmeException("Invalid node key");
}
String key = splited[splited.length - 1];
switch (key) {
case "Course":
createCourse(obj);
break;
case "Teacher":
case "StudentData":
createUser(obj);
break;
default:
log.debug("Didn't _directly_ recongize key " + key);
}
}
}
/**
* Imports a course and associated TME objects.
*
* @param node Course TME object.
* @return Imported Course.
* @throws TmeException On a failed import.
*/
private Course createCourse(TMEObject node) throws TmeException {
Object obj = entityMap.get(node.getId());
if (obj != null) {
return (Course) obj;
}
Course course = new Course();
course.setName(node.getString("name"));
course.setDefaultSws(node.getString("wochenstunden"));
course.setDefaultCreditPoints(node.getInt("cp"));
course.setRequiresConfirmation(false);
course.setStudentsCanSeeFormula(true);
//super safe identifier collisionhandling
String randomIdentifier;
do {
randomIdentifier = RandomStringUtils.randomAlphabetic(4);
} while (courseService.findCourseByIdentifier(randomIdentifier) != null);
course.setIdentifier(randomIdentifier);
ParticipationType type = new ParticipationType();
type.setName(node.getString("studyArea"));
type.setGroupPerformance(node.getBoolean("groupPerformance"));
type.setRestricted(false);
type.setSws(null);
type.setCreditPoints(null);
type.setIsDefaultParttype(true);
type.setCourse(course);
course.getParticipationTypes().add(type);
Semester semester = createSemester(node.getString("zeitraum"));
course.setSemester(semester);
List<String> vaks = new ArrayList<>();
vaks.add(node.getString("nummer"));
course.setNumbers(vaks);
if (node.getBoolean("finished")) {
course.setLastFinalization(new Date());
} else {
course.setLastFinalization(null);
}
course.setMinGroupSize(node.getInt("minimaleGruppenGroesse"));
course.setMaxGroupSize(node.getInt("maximaleGruppenGroesse"));
courseService.persist(course);
createGroups(node.getArray("groups"), course);
course = courseService.update(course);
log.debug("Persisted course " + course.getName());
entityMap.put(node.getId(), course);
return course;
}
/**
* Returns a semester object form the given string.
*
* @param str String to use to create semester object.
* @return Semester object.
* @throws TmeException On invalid string format.
*/
private Semester createSemester(String str) throws TmeException {
Semester semester = null;
try {
semester = Semester.valueOf(str);
} catch (SemesterFormatException e) {
throw new TmeException("Invalid semester string format");
}
Semester sem = semesterService.findSemester(
semester.getSemesterYear(), semester.isWinter());
if (sem != null) {
return sem;
}
semesterService.persist(semester);
log.debug("Persist semester " + semester.toString());
return semester;
}
/**
* Creates all groups from the given TMEArray.
*
* @param array TMEArray to create groups from.
* @param course Course tho groups belong to.
* @return List of created group entities.
* @throws TmeException On a failed creation.
*/
private List<Group> createGroups(TMEArray array, Course course)
throws TmeException {
List<Group> groups = new ArrayList<>();
for (int i = 0; i < array.size(); i++) {
int id = array.getInt(i);
TMEObject node = findNode("jgradebook.data.Group", id);
if (node == null) {
throw new TmeException("non-existend group " + id);
}
Group group = createGroup(node, course);
groups.add(group);
}
return groups;
}
/**
* Creates a group from the given TME object in the given course.
*
* @param node TME group object.
* @param course Course the group belongs to.
* @return Created group entity.
* @throws TmeException On a failed creation.
*/
private Group createGroup(TMEObject node, Course course)
throws TmeException {
Object obj = entityMap.get(node.getId());
if (obj != null) {
return (Group) obj;
}
int tutorialId = node.getInt("tutorial");
TMEObject tutorialNode = findNode("jgradebook.data.Tutorial", tutorialId);
if (tutorialNode == null) {
throw new TmeException("non-existend tutorial " + tutorialId);
}
Tutorial tutorial = createTutorial(tutorialNode, course);
Group group = new Group();
group.setName(node.getString("name"));
group.setTutorial(tutorial);
groupService.persist(group);
tutorial.getGroups().add(group);
List<Student> students = createStudents(node.getArray("students"),
group, course);
group.setStudents(students);
course.getStudents().addAll(students);
course = courseService.update(course);
group = groupService.update(group);
log.debug("Created group " + group.getName());
entityMap.put(node.getId(), group);
return group;
}
/**
* Creates all students from the given TMEArray.
*
* @param array TMEArray to create students from.
* @param group Group the students belong to.
* @param course Course the students belong to.
* @return List of created student entities.
* @throws TmeException On a failed creation.
*/
private List<Student> createStudents(TMEArray array, Group group, Course course)
throws TmeException {
List<Student> students = new ArrayList<>();
for (int i = 0; i < array.size(); i++) {
int id = array.getInt(i);
TMEObject node = findNode("jgradebook.data.Student", id);
if (node == null) {
throw new TmeException("non-existend student " + id);
}
Student student = createStudent(node, group, course);
students.add(student);
}
return students;
}
/**
* Creates a student from the given TME object in the given group.
*
* @param node TME student object.
* @param group Group the student belongs to.
* @param course Course the student belongs to.
* @return Created Student entity.
* @throws TmeException On a failed creation.
*/
private Student createStudent(TMEObject node, Group group, Course course)
throws TmeException {
Object obj = entityMap.get(node.getId());
if (obj != null) {
return (Student) obj;
}
int id = node.getInt("studentData");
TMEObject studentData = findNode("jgradebook.data.StudentData", id);
if (studentData == null) {
throw new TmeException("non-existend studentData " + id);
}
User user = createUser(studentData);
Student student = new Student();
student.setGroup(group);
student.setCourse(course);
student.setTutorial(group.getTutorial());
student.setUser(user);
student.setDeleted(false);
student.setHidden(false);
student.setTries(0);
if (node.getString("status") == "CONFIRMED") {
student.setAcceptedInvitation(true);
student.setConfirmed(true);
} else {
student.setAcceptedInvitation(false);
student.setConfirmed(false);
}
student.setPaboGrade(null);
student.setPublicComment(null);
if (node.has("comment")) {
student.setPrivateComment(node.getString("comment"));
} else {
student.setPrivateComment(null);
}
studentService.persist(student);
log.debug("Persisted student " + student.getUser());
entityMap.put(node.getId(), student);
return student;
}
/**
* Creates a tutorial from the given TME object in the given course.
*
* @param node TME tutorial object.
* @param course Course the tutorial belongs to.
* @return Created tutorial entity.
* @throws TmeException On a failed creation.
*/
private Tutorial createTutorial(TMEObject node, Course course)
throws TmeException {
Object obj = entityMap.get(node.getId());
if (obj != null) {
return (Tutorial) obj;
}
int tutorId = node.getInt("tutor");
TMEObject tutorNode = findNode("jgradebook.data.Teacher", tutorId);
if (tutorNode == null) {
throw new TmeException("non-existend tutor " + tutorId);
}
Tutorial tutorial = new Tutorial();
tutorial.setCourse(course);
tutorial.setName("jgradebook Tutorial " + node.getId());
User user = createUser(tutorNode);
PrivilegedUser tutor = privilegedUserService.findPrivUserInCourse(
user, course);
if (tutor == null) {
tutor = new PrivilegedUser();
tutor.setCourse(course);
tutor.setSecretary(false);
tutor.setUser(user);
tutor.setHidden(false);
tutor.setDeleted(false);
course.getTutors().add(tutor);
tutor.getTutorials().add(tutorial);
privilegedUserService.persist(tutor);
}
course.getTutorials().add(tutorial);
tutorial.getTutors().add(tutor);
tutorialService.persist(tutorial);
course = courseService.update(course);
log.debug("Persisted tutorial " + tutorial.getName());
entityMap.put(node.getId(), tutorial);
return tutorial;
}
/**
* Returns a user entity from the given TME object.
*
* @param node StudentData or Teacher TME object.
* @return User entity.
*/
private User createUser(TMEObject node) {
Object obj = entityMap.get(node.getId());
if (obj != null) {
return (User) obj;
}
String email = node.getString("email");
User user = userService.findByEmail(email);
if (user != null) {
entityMap.put(node.getId(), user);
return user;
}
User newUser = new User();
newUser.setEmail(email);
newUser.setFirstName(node.getString("firstname"));
newUser.setLastName(node.getString("lastname"));
newUser.setLastActivity(DateUtil.getDateTime());
// Teachers don't have a marticulation number
if (node.has("matriculationNumber")) {
newUser.setMatriculationNumber(node.getString("matriculationNumber"));
} else {
newUser.setMatriculationNumber(null);
}
String plainPasswd = node.getString("password");
newUser.setPassword(BCrypt.hashpw(plainPasswd, BCrypt.gensalt()));
newUser.addRole(GlobalRole.USER);
if (node.has("superuser") && node.getBoolean("superuser")) {
newUser.addRole(GlobalRole.ADMIN);
}
userService.persist(newUser);
log.debug(String.format("Persisted new user '%s' (%s)",
newUser.toString(), newUser.getEmail()));
entityMap.put(node.getId(), newUser);
return newUser;
}
/**
* Finds the node with the given name and id in the TME objects list.
*
* @param name Node name.
* @param id Node id.
* @return Associated node or null.
*/
private TMEObject findNode(String name, int id) {
TMEObject node = nodeMap.get(id);
if (node == null) {
return null;
}
return (node.getName().equals(name)) ? node : null;
}
/**
* Converts a filesize from simple long to human readable display-value.
*
* @param fsize long value representing a filesize in bytes
* @return Human readable string representation
*/
public String getHumanReadableFileSize(long fsize) {
return FileUtils.byteCountToDisplaySize(fsize);
}
public List<UploadedFile> getFiles() {
return files;
}
public void setFiles(List<UploadedFile> files) {
this.files = files;
}
} |
package edu.virginia.psyc.pi.controller;
import edu.virginia.psyc.pi.domain.Participant;
import edu.virginia.psyc.pi.persistence.ParticipantDAO;
import edu.virginia.psyc.pi.persistence.ParticipantRepository;
import edu.virginia.psyc.pi.service.EmailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import javax.validation.Valid;
import java.security.Principal;
@Controller
@RequestMapping("/admin")
public class AdminController {
private ParticipantRepository participantRepository;
private static final Logger LOG = LoggerFactory.getLogger(AdminController.class);
private static final int PER_PAGE=10; // Number of users to display per page.
@Autowired
private EmailService emailService;
/**
* Spring automatically configures this object.
* You can modify the location of this database by editing the application.properties file.
*/
@Autowired
public AdminController(ParticipantRepository repository) {
this.participantRepository = repository;
}
@RequestMapping(method = RequestMethod.GET)
public String listUsers(ModelMap model,
final @RequestParam(value = "search", required = false, defaultValue = "") String search,
final @RequestParam(value = "page", required = false, defaultValue = "0") String pageParam) {
Page<ParticipantDAO> participants;
PageRequest pageRequest;
int page = Integer.parseInt(pageParam);
pageRequest = new PageRequest(page, PER_PAGE);
if(search.isEmpty()) {
participants = participantRepository.findAll(pageRequest);
} else {
participants = participantRepository.search(search, pageRequest);
}
model.addAttribute("participants", participants);
model.addAttribute("search", search);
return "admin";
}
@RequestMapping(value="/participant/{id}", method=RequestMethod.GET)
public String showForm(ModelMap model,
@PathVariable("id") long id) {
Participant p;
p = participantRepository.entityToDomain(participantRepository.findOne(id));
model.addAttribute("participant", p);
return "participant_form";
}
@RequestMapping(value="/participant/{id}", method=RequestMethod.POST)
public String checkParticipantInfo(ModelMap model,
@PathVariable("id") long id,
@Valid Participant participant,
BindingResult bindingResult) {
ParticipantDAO dao;
dao = participantRepository.findOne(id);
if (bindingResult.hasErrors()) {
LOG.error("Invalid participant:" + bindingResult.getAllErrors());
model.addAttribute("participant", participant);
return "participant_form";
} else {
participantRepository.domainToEntity(participant, dao);
participantRepository.save(dao);
}
return "redirect:/admin";
}
@RequestMapping(value="/sendEmail/{type}")
public String sendEmail(ModelMap model, Principal principal,
@PathVariable("type") EmailService.TYPE type) throws Exception {
Participant p;
p = participantRepository.entityToDomain(participantRepository.findByEmail(principal.getName()).get(0));
this.emailService.sendSimpleMail(p, type);
return "redirect:/admin";
}
} |
package net.formula97.andorid.car_kei_bo;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
* @author kazutoshi
* DB
*
* Cursor
* Cursor#close()
* # Cursor!!....
*
*/
public class DbManager extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "fuel_mileage.db";
private static final int DB_VERSION = 1;
private static final String LUB_MASTER = "LUB_MASTER";
private static final String COSTS_MASTER = "COSTS_MASTER";
private static final String CAR_MASTER = "CAR_MASTER";
public DbManager(Context context) {
super(context, DATABASE_NAME, null, DB_VERSION);
// TODO
}
/**
* DBDDL
* @see android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite.SQLiteDatabase)
* @param db SQLiteDatabaseDB
*/
@Override
public void onCreate(SQLiteDatabase db) {
String create_lub_master;
String create_costs_master;
String create_car_master;
// DDL
// LUB_MASTER
create_lub_master = "CREATE TABLE IF NOT EXISTS LUB_MASTER " +
"(RECORD_ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
"REFUEL_DATE REAL, " +
"CAR_ID INTEGER, " +
"LUB_AMOUNT REAL DEFAULT 0, " +
"UNIT_PRICE REAL DEFAULT 0, " +
"ODOMETER INTEGER, " +
"COMMENTS TEXT);";
// COSTS_MASTER
create_costs_master = "CREATE TABLE IF NOT EXISTS COSTS_MASTER " +
"(RECORD_ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
"REFUEL_DATE REAL, " +
"RUNNING_COST REAL DEFAULT 0);";
// CAR_MASTER
create_car_master = "CREATE TABLE IF NOT EXISTS CAR_MASTER " +
"(CAR_ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
"CAR_NAME TEXT, " +
"DEFAULT_FLAG INTEGER DEFAULT 0, " +
"CURRENT_FUEL_MILEAGE INTEGER DEFAULT 0, " +
"CURRENT_RUNNING_COST INTEGER DEFAULT 0, " +
"PRICEUNIT TEXT, " +
"DISTANCEUNIT TEXT, " +
"VOLUMEUNIT TEXT, " +
"FUELMILEAGE_LABEL TEXT, " +
"RUNNINGCOST_LABEL TEXT);";
// DDLexecSQL
db.execSQL(create_lub_master);
db.execSQL(create_costs_master);
db.execSQL(create_car_master);
}
/**
* DBDB
*
*
*
* @see android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite.SQLiteDatabase, int, int)
* @param db SQLiteDatabaseDB
* @param oldVersion intDB
* @param newVersion intDB
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO
// ALTER TABLE
Log.w("Car-Kei-Bo", "Updating database, which will destroy all old data.(for testing)");
db.execSQL("DROP TABLE IF EXISTS LUB_MASTER;");
db.execSQL("DROP TABLE IF EXISTS COSTS_MASTER;");
db.execSQL("DROP TABLE IF EXISTS CAR_MASTER;");
// onCreate()
onCreate(db);
}
/**
*
* ....(^^;)
* @param db SQLiteDatabaseDB
* @param carName String
* @param isDefaultCar boolean
* @param priceUnit String
* @param distanceUnit String
* @param volumeUnit String
* @return longinsertrowId-1SQLException
*/
protected long addNewCar(SQLiteDatabase db, String carName, boolean isDefaultCar,
String priceUnit, String distanceUnit, String volumeUnit) {
// insertOrThrow()0
long result = 0;
ContentValues value = new ContentValues();
value.put("CAR_NAME", carName);
// defaultCartrue10put
if (isDefaultCar == true) {
value.put("DEFAULT_FLAG", 1);
} else {
value.put("DEFAULT_FLAG", 0);
}
value.put("PRICEUNIT", priceUnit);
value.put("DISTANCEUNIT", distanceUnit);
value.put("VOLUMEUNIT", volumeUnit);
value.put("FUELMILEAGE_LABEL", distanceUnit + "/" + volumeUnit);
value.put("RUNNINGCOST_LABEL", priceUnit + "/" + distanceUnit);
db.beginTransaction();
try {
// insertOrThrowINSERT
result = db.insertOrThrow(CAR_MASTER, null, value);
db.setTransactionSuccessful();
} catch (SQLException e) {
Log.e(DATABASE_NAME, "Car record insert failed, ");
} finally {
// INSERTendTransaction()
db.endTransaction();
}
return result;
}
/**
*
*
* @param db SQLiteDatabaseDB
* @param carName String
* @return booleantruefalse
*/
protected boolean isExistSameNameCar(SQLiteDatabase db, String carName) {
Cursor q;
String[] columns = {"CAR_NAME"};
String where = "CAR_NAME = ?";
String[] args = {carName};
q = db.query(CAR_MASTER, columns, where, args, null, null, null);
q.moveToFirst();
int count = q.getCount();
q.close();
// 0falsetrue
if (count == 0) {
return false;
} else {
return true;
}
}
/**
*
*
* @param db SQLiteDatabaseDB
* @return booleantruefalse
*/
protected boolean isExistDefaultCarFlag(SQLiteDatabase db) {
Cursor q;
//String[] columns = {"DEFAULT_FLAG"};
String where = "DEFAULT_FLAG = ?";
String[] args = {"1"};
q = db.query(CAR_MASTER, null, where, args, null, null, null);
q.moveToFirst();
int defaultFlag = q.getCount();
q.close();
if (defaultFlag == 0) {
return false;
} else {
return true;
}
}
/**
*
*
* @param db SQLiteDatabaseDB
* @param carId intcarId
* @return booleantruefalse
*/
protected boolean isExistDefaultCarFlag(SQLiteDatabase db, int carId) {
Cursor q;
String[] columns = {"DEFAULT_FLAG"};
String where = "CAR_ID = ?";
// CAR_IDintquery()String[]valueOf()String
String[] args = {String.valueOf(carId)};
q = db.query(CAR_MASTER, columns, where, args, null, null, null);
q.moveToFirst();
int defaultFlag = q.getInt(0);
q.close();
if (defaultFlag == 0) {
return false;
} else {
return true;
}
}
/**
* CAR_ID
* @param db SQLiteDatabaseDB
* @param carName String
* @return intcarId
*/
protected int getCarId(SQLiteDatabase db, String carName) {
int iRet;
Cursor q;
String[] columns = {"CAR_ID"};
String where = "CAR_NAME = ?";
String[] args = {carName};
q = db.query(CAR_MASTER, columns, where, args, null, null, null);
q.moveToFirst();
iRet = q.getInt(0);
q.close();
return iRet;
}
/**
* CAR_IDCAR_NAME
* @param db SQLiteDatabaseDB
* @param carId intcarId
* @return StringcarId
*/
protected String getCarName(SQLiteDatabase db, int carId) {
String sRet;
Cursor q;
String[] columns = {"CAR_NAME"};
String where = "CAR_ID = ?";
// CAR_IDintquery()String[]valueOf()String
String[] args = {String.valueOf(carId)};
q = db.query(CAR_MASTER, columns, where, args, null, null, null);
q.moveToFirst();
sRet = q.getString(0);
q.close();
return sRet;
}
/**
* CAR_NAME
* @param db SQLiteDatabaseDB
* @return String
*/
protected String getDefaultCarName(SQLiteDatabase db) {
String sRet;
Cursor q;
String[] columns = {"CAR_NAME"};
String where = "DEFAULT_FLAG = ?";
// DEFAULT_FLAG=1query()String[]valueOf()String
String[] args = {String.valueOf(1)};
q = db.query(CAR_MASTER, columns, where, args, null, null, null);
q.moveToFirst();
sRet = q.getString(0);
Log.i(CAR_MASTER, "Found default car : " + sRet);
q.close();
return sRet;
}
/**
* CAR_ID
* @param db SQLiteDatabaseDB
* @return intcarId
*/
protected int getDefaultCarId(SQLiteDatabase db) {
int iRet;
Cursor q;
String[] columns = {"CAR_ID"};
String where = "DEFAULT_FLAG = ?";
// DEFAULT_FLAG=1query()String[]valueOf()String
String[] args = {String.valueOf(1)};
q = db.query(CAR_MASTER, columns, where, args, null, null, null);
q.moveToFirst();
iRet = q.getInt(0);
return iRet;
}
/**
*
* @param db SQLiteDatabaseDB
* @return CursorCursorCursor#close()
*/
protected Cursor getCarList(SQLiteDatabase db) {
Cursor q;
String[] columns = {"CAR_ID AS _id", "CAR_NAME", "CURRENT_FUEL_MILEAGE", "FUELMILEAGE_LABEL", "CURRENT_RUNNING_COST", "RUNNINGCOST_LABEL"};
//String where = "CAR_ID = ?";
//String[] args = {String.valueOf(1)};
//String groupBy = ""
//String having = ""
String orderBy = "CAR_ID";
q = db.query(CAR_MASTER, columns, null, null, null, null, orderBy);
q.moveToFirst();
return q;
}
/**
*
* @param db SQLiteDatabaseDB
* @param carId intcarId
* @return intUpdate
*/
protected int changeDefaultCar(SQLiteDatabase db, int carId) {
ContentValues cv = new ContentValues();
String where = "CAR_ID = ?";
String[] args = {String.valueOf(carId)};
int result;
db.beginTransaction();
try {
cv.put("DEFAULT_FLAG", 0);
result = db.update(CAR_MASTER, cv, null, null);
// carId
cv.clear();
cv.put("DEFAULT_FLAG", 1);
result = db.update(CAR_MASTER, cv, where, args);
db.setTransactionSuccessful();
} finally {
// setTransactionSuccessful()
// endTransaction()
db.endTransaction();
}
return result;
}
/**
*
* @param db SQLiteDatabaseDB
* @return intUpdate
*/
protected int clearAllDefaultFlags(SQLiteDatabase db) {
ContentValues cv = new ContentValues();
int result;
db.beginTransaction();
try {
cv.put("DEFAULT_FLAG", 0);
result = db.update(CAR_MASTER, cv, null, null);
db.setTransactionSuccessful();
} finally {
// setTransactionSuccessful()
// endTransaction()
db.endTransaction();
}
return result;
}
/**
* CAR_MASTER
* (^^;
* @param db SQLiteDatabaseDB
* @return booleantruefalse
*/
protected boolean hasCarRecords(SQLiteDatabase db) {
// getCount()
int iRet;
Cursor q;
q = db.query(CAR_MASTER, null, null, null, null, null, null);
q.moveToFirst();
iRet = q.getCount();
q.close();
if (iRet == 0) {
return false;
} else {
return true;
}
}
/**
* LUB_MASTER
* (^^;
* @param db SQLiteDatabaseDB
* @return booleantruefalse
*/
protected boolean hasLubRecords(SQLiteDatabase db) {
// getCount()
int iRet;
Cursor q;
q = db.query(LUB_MASTER, null, null, null, null, null, null);
q.moveToFirst();
iRet = q.getCount();
q.close();
if (iRet == 0) {
return false;
} else {
return true;
}
}
/**
* COSTS_MASTER
* (^^;
* @param db SQLiteDatabaseDB
* @return booleantruefalse
*/
protected boolean hasCostsRecords(SQLiteDatabase db) {
// getCount()
int iRet;
Cursor q;
q = db.query(COSTS_MASTER, null, null, null, null, null, null);
q.moveToFirst();
iRet = q.getCount();
q.close();
if (iRet == 0) {
return false;
} else {
return true;
}
}
} |
package edu.virginia.uvacluster.internal;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
import org.cytoscape.application.CyApplicationManager;
import org.cytoscape.application.swing.CySwingApplication;
import org.cytoscape.application.swing.CytoPanelComponent;
import org.cytoscape.application.swing.CytoPanelName;
import org.cytoscape.model.CyColumn;
import org.cytoscape.model.CyEdge;
import org.cytoscape.model.CyNetwork;
import org.cytoscape.model.CyNode;
import org.cytoscape.model.CyTable;
import org.cytoscape.model.subnetwork.CySubNetwork;
import org.cytoscape.service.util.CyServiceRegistrar;
import org.cytoscape.work.TaskIterator;
import org.cytoscape.work.swing.DialogTaskManager;
import org.cytoscape.work.util.ListSingleSelection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MyControlPanel extends JPanel implements CytoPanelComponent {
private static final long serialVersionUID = 8292806967891823933L;
private JPanel searchPanel;
private JPanel trainPanel;
private JPanel evaluatePanel;
private JPanel advancedTrainPanel;
private JPanel advancedSearchPanel;
private JPanel outerSearchPanel;
private JPanel outerTrainPanel;
private JButton analyzeButton;
private JComboBox chooser;
private JComboBox proteinGraph;
private JComboBox inputGraphChooser;
private JTextField checkNumNeighbors;
private JCheckBox useSelectedForSeeds;
private File useSelectedForSeedsFile;
private JButton useSelectedForSeedsButton;
private JPanel useSelectedForSeedsPanel;
private JTextField numSeeds;
private JTextField searchLimit;
private JTextField initTemp;
private JTextField tempScalingFactor;
private JTextField overlapLimit;
private JTextField minScoreThreshold;
private JTextField minSize;
private JTextField numResults;
private JLabel chooserLabel;
private JLabel proteinGraphLabel;
private JLabel checkNumNeighborsLabel;
private JLabel useSelectedForSeedsLabel;
private JLabel numSeedsLabel;
private JLabel searchLimitLabel;
private JLabel initTempLabel;
private JLabel tempScalingFactorLabel;
private JLabel overlapLimitLabel;
private JLabel minScoreThresholdLabel;
private JLabel minSizeLabel;
private JLabel numResultsLabel;
private JCheckBox trainNewModel;
private JComboBox existingModel;
private JComboBox bayesModel;
private JPanel customModelPanel;
private JComboBox weightName;
private JTextField clusterPrior;
private JTextField negativeExamples;
private JCheckBox ignoreMissing;
private File trainingFile;
private JButton trainingFileButton;
private JLabel trainingFileLabel;
/* NEW */
private JRadioButton useTrainedModel;
private JRadioButton trainDefaultModel;
private JRadioButton trainCustomModel;
private JComboBox model;
private JPanel trainingOptionPanel;
private File resultFile;
private JLabel useTrainedModelLabel;
private JLabel trainDefaultModelLabel;
private JLabel trainCustomModelLabel;
private JLabel resultFileLabel;
/* SCORING */
Double minScore = null;
private JPanel scorePanel;
private JRadioButton weightScoreOption;
private JRadioButton learningScoreOption;
private JLabel trainNewModelLabel;
private JLabel existingModelLabel;
private JLabel customModelLabel;
private JLabel bayesModelLabel;
private JLabel weightNameLabel;
private JLabel clusterPriorLabel;
private JLabel negativeExamplesLabel;
private JLabel ignoreMissingLabel;
SupervisedComplexTaskFactory clusterFactory;
private ArrayList<Cluster> searchResults;
private JTextField p;
private File evaluationFile;
private JButton evaluationFileButton;
private JButton evaluateButton;
private JLabel pLabel;
private JLabel evaluationFileLabel;
private final CySwingApplication swingApplication;
private final CyServiceRegistrar registrar;
private final CyApplicationManager appManager;
private final Logger logger;
public MyControlPanel(final CySwingApplication swingApplication, final CyServiceRegistrar registrar, final CyApplicationManager appManager) {
logger = LoggerFactory.getLogger(getClass());
this.swingApplication = swingApplication;
this.registrar = registrar;
this.appManager = appManager;
analyzeButton = new JButton("Analyze Network");
analyzeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
analyzeButtonPressed();
}
} );
evaluateButton = new JButton("Evaluate Results");
evaluateButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
evaluateButtonPressed(evaluationFile);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
final GroupLayout layout = new GroupLayout(this);
final JPanel outerPanel = new JPanel();
// Set up search panel
outerSearchPanel = new JPanel();
outerSearchPanel.setLayout(new BoxLayout(outerSearchPanel, BoxLayout.Y_AXIS));
outerSearchPanel.add(createSearchPanel());
advancedSearchPanel = new CollapsiblePanel("> Advanced Search Parameters", createAdvancedSearchParams());
outerSearchPanel.add(advancedSearchPanel);
TitledBorder search = BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.blue), "Searching for Complexes");
search.setTitleColor(Color.blue);
outerSearchPanel.setBorder(search);
// Set up train panel
outerTrainPanel = new JPanel();
outerTrainPanel.setLayout(new BoxLayout(outerTrainPanel, BoxLayout.Y_AXIS));
outerTrainPanel.add(createTrainPanel());
advancedTrainPanel = new CollapsiblePanel("> Advanced Training Parameters", createAdvancedTrainParams());
outerTrainPanel.add(advancedTrainPanel);
TitledBorder train = BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.blue), "Training the Bayesian Network");
train.setTitleColor(Color.blue);
outerTrainPanel.setBorder(train);
// Set up score panel
scorePanel = createScorePanel();
TitledBorder score = BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.blue), "Scoring Complexes");
score.setTitleColor(Color.blue);
scorePanel.setBorder(score);
// Set up evaluation panel
evaluatePanel = createEvaluatePanel();
evaluatePanel.setBorder(null);
// Button to save the results to file
// resultFileLabel = new JLabel("Save Results to File");
JButton resultFileButton = new JButton("Save Results To File");
resultFileButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
JFileChooser resultChooser = new JFileChooser();
int result = resultChooser.showOpenDialog(MyControlPanel.this);
if (result == JFileChooser.APPROVE_OPTION) {
resultFile = resultChooser.getSelectedFile();
try {
writeResultsToFile(resultFile);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
});
// Wrap all panels in an outer panel
outerPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(0,0,15,15);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weighty = 1.0;
gbc.weightx = 1.0;
gbc.gridy = 0;
outerPanel.add(outerSearchPanel, gbc);
gbc.gridy = 1;
outerPanel.add(scorePanel, gbc);
gbc.gridy = 2;
outerPanel.add(analyzeButton, gbc);
gbc.gridy = 3;
outerPanel.add(resultFileButton, gbc);
gbc.gridy = 4;
outerPanel.add(evaluatePanel, gbc);
gbc.gridy = 5;
outerPanel.add(evaluateButton, gbc);
// Add the outer panel to a JScrollPanel to make it
// vertically scrollable
final JScrollPane scrollablePanel = new JScrollPane(outerPanel);
scrollablePanel.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollablePanel.setBorder(null);
setLayout(layout);
layout.setAutoCreateContainerGaps(true);
layout.setAutoCreateGaps(true);
layout.setHorizontalGroup(layout.createParallelGroup(Alignment.CENTER, true)
.addComponent(scrollablePanel)
);
layout.setVerticalGroup(layout.createParallelGroup(Alignment.CENTER, true)
.addComponent(scrollablePanel)
);
}
public JPanel createAdvancedSearchParams() {
if (searchPanel != null) {
if (advancedSearchPanel == null) {
advancedSearchPanel = new JPanel();
final GroupLayout layout = new GroupLayout(advancedSearchPanel);
advancedSearchPanel.setLayout(layout);
layout.setAutoCreateContainerGaps(true);
layout.setAutoCreateGaps(true);
layout.setHorizontalGroup(
layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(searchLimitLabel)
.addComponent(initTempLabel)
.addComponent(tempScalingFactorLabel)
.addComponent(overlapLimitLabel)
.addComponent(minSizeLabel)
.addComponent(useSelectedForSeedsLabel)
.addComponent(numSeedsLabel)
.addComponent(numResultsLabel))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(searchLimit)
.addComponent(initTemp)
.addComponent(tempScalingFactor)
.addComponent(overlapLimit)
.addComponent(minSize)
.addComponent(useSelectedForSeedsPanel)
.addComponent(numSeeds)
.addComponent(numResults))
);
layout.setVerticalGroup(
layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(searchLimitLabel)
.addComponent(searchLimit))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(initTempLabel)
.addComponent(initTemp))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(tempScalingFactorLabel)
.addComponent(tempScalingFactor))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(overlapLimitLabel)
.addComponent(overlapLimit))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(minSizeLabel)
.addComponent(minSize))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(useSelectedForSeedsLabel)
.addComponent(useSelectedForSeedsPanel))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(numSeedsLabel)
.addComponent(numSeeds))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(numResultsLabel)
.addComponent(numResults))
);
}
}
return advancedSearchPanel;
}
public JPanel createAdvancedTrainParams() {
if (trainPanel != null) {
if (advancedTrainPanel == null) {
advancedTrainPanel = new JPanel();
final GroupLayout layout = new GroupLayout(advancedTrainPanel);
advancedTrainPanel.setLayout(layout);
layout.setAutoCreateContainerGaps(true);
layout.setAutoCreateGaps(true);
layout.setHorizontalGroup(
layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(minScoreThresholdLabel)
.addComponent(clusterPriorLabel)
.addComponent(negativeExamplesLabel)
.addComponent(ignoreMissingLabel))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(minScoreThreshold)
.addComponent(clusterPrior)
.addComponent(negativeExamples)
.addComponent(ignoreMissing))
);
layout.setVerticalGroup(
layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(minScoreThresholdLabel)
.addComponent(minScoreThreshold))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(clusterPriorLabel)
.addComponent(clusterPrior))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(negativeExamplesLabel)
.addComponent(negativeExamples))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(ignoreMissingLabel)
.addComponent(ignoreMissing))
);
}
}
return advancedTrainPanel;
}
public JPanel createSearchPanel() {
if (searchPanel == null) {
searchPanel = new JPanel();
final GroupLayout layout = new GroupLayout(searchPanel);
searchPanel.setLayout(layout);
layout.setAutoCreateContainerGaps(true);
layout.setAutoCreateGaps(true);
String[] variants = { "ISA", "Greedy ISA", "Sorted-Neighbor ISA" };
chooser = new JComboBox(variants);
chooser.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
String searchVariant = (String) chooser.getSelectedItem();
if (searchVariant == "Sorted-Neighbor ISA") {
checkNumNeighbors.setVisible(true);
checkNumNeighborsLabel.setVisible(true);
} else {
checkNumNeighbors.setVisible(false);
checkNumNeighborsLabel.setVisible(false);
}
}
}
);
chooserLabel = new JLabel("Search Variant");
// Select protein graph
ArrayList<String> networkNames = new ArrayList<String>();
networkNames.add(" - Select Network - ");
networkNames.addAll(getNetworkNames());
proteinGraph = new JComboBox(networkNames.toArray());
proteinGraphLabel = new JLabel("Protein graph");
proteinGraph.addActionListener(
// Automatically set the number of starting seeds to be 1/8 the number of nodes in the graph
new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (! proteinGraph.getSelectedItem().equals(" - Select Network - ")) {
for (CyNetwork network: CyActivator.networkManager.getNetworkSet()) {
if (network.getRow(network).get(CyNetwork.NAME, String.class).equals(proteinGraph.getSelectedItem())) {
int numNodes = network.getNodeCount();
numSeeds.setText(Integer.toString(numNodes / 8));
}
}
}
}
}
);
// Name of column containing weights
weightName = new JComboBox(getEdgeColumnNames().toArray());
weightNameLabel = new JLabel("Weight column in graph");
// Number of neighbors to consider
checkNumNeighbors = new JTextField("5");
checkNumNeighborsLabel = new JLabel("Neighbors to consider");
checkNumNeighbors.setVisible(false);
checkNumNeighborsLabel.setVisible(false);
// Number of Seeds
numSeeds = new JTextField("10");
numSeedsLabel = new JLabel("Number of Random Seeds");
// Search Limit
searchLimit = new JTextField("20");
searchLimitLabel = new JLabel("Search Limit");
// Initial Temperature
initTemp = new JTextField("1.8");
initTempLabel = new JLabel("Initial Temperature");
// Temperature scaling factor (Rate of change of temperature)
tempScalingFactor = new JTextField("0.88");
tempScalingFactorLabel = new JLabel("Temperature Scaling Factor");
// Permissible amount of overlap between complexes
overlapLimit = new JTextField("0.75");
overlapLimitLabel = new JLabel("Overlap Limit");
// Minimum acceptable complex size
minSize = new JTextField("3");
minSizeLabel = new JLabel("Minimum Complex Size");
// Selecting seeds from file
useSelectedForSeedsButton = new JButton("Seed File (.tab, .tsv)");
useSelectedForSeedsButton.setEnabled(false);
useSelectedForSeeds = new JCheckBox();
useSelectedForSeedsLabel = new JLabel("Use Seeds From File");
useSelectedForSeeds.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(useSelectedForSeeds.isEnabled() && useSelectedForSeeds.isSelected()) {
useSelectedForSeedsButton.setEnabled(true);
numSeeds.setVisible(false);
numSeedsLabel.setVisible(false);
} else {
useSelectedForSeedsButton.setEnabled(false);
numSeeds.setVisible(true);
numSeedsLabel.setVisible(true);
}
}
}
);
useSelectedForSeedsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0)); // Container for checkbox and button
((FlowLayout)useSelectedForSeedsPanel.getLayout()).setHgap(0);
useSelectedForSeedsPanel.add(useSelectedForSeeds);
useSelectedForSeedsPanel.add(useSelectedForSeedsButton);
useSelectedForSeedsButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
if (useSelectedForSeedsButton.getText().equals("Seed File (.tab, .tsv)")) {
JFileChooser seedsChooser = new JFileChooser();
int result = seedsChooser.showOpenDialog(MyControlPanel.this);
if (result == JFileChooser.APPROVE_OPTION) {
useSelectedForSeedsFile = seedsChooser.getSelectedFile();
if (useSelectedForSeedsFile == null) {
useSelectedForSeeds.setSelected(false);
numSeeds.setVisible(true);
numSeedsLabel.setVisible(true);
} else {
useSelectedForSeeds.setSelected(true);
useSelectedForSeedsLabel.setText(useSelectedForSeedsFile.getName());
useSelectedForSeedsButton.setText("Remove File");
numSeeds.setVisible(false);
numSeedsLabel.setVisible(false);
}
}
} else {
useSelectedForSeeds.setSelected(false);
useSelectedForSeedsLabel.setText("Use Seeds From File");
useSelectedForSeedsButton.setText("Seed File (.tab, .tsv)");
numSeeds.setVisible(true);
numSeedsLabel.setVisible(true);
}
}
});
// Number of results to save to file
numResults = new JTextField("10");
numResultsLabel = new JLabel("Number of results to display");
chooser.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
String searchVariant = (String) chooser.getSelectedItem();
if (searchVariant == "Sorted-Neighbor ISA") {
checkNumNeighbors.setVisible(true);
checkNumNeighborsLabel.setVisible(true);
} else {
checkNumNeighbors.setVisible(false);
checkNumNeighborsLabel.setVisible(false);
}
}
}
);
// Add search components to layout
layout.setHorizontalGroup(
layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(proteinGraphLabel)
.addComponent(chooserLabel)
.addComponent(checkNumNeighborsLabel))
// .addComponent(resultFileLabel))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(proteinGraph)
.addComponent(chooser)
.addComponent(checkNumNeighbors))
// .addComponent(resultFileButton))
);
layout.setVerticalGroup(
layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(proteinGraphLabel)
.addComponent(proteinGraph))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(chooserLabel)
.addComponent(chooser))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(checkNumNeighborsLabel)
.addComponent(checkNumNeighbors))
// .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
// .addComponent(resultFileLabel)
// .addComponent(resultFileButton))
);
}
return searchPanel;
}
public JPanel createScorePanel() {
if (scorePanel == null) {
scorePanel = new JPanel();
final ButtonGroup scoringButtons = new ButtonGroup();
/* For the simple search without learning: */
/* Calculate the mean of the edge weights in the input graph (if it has weights)
* in order to auto-set the min score threshold */
weightScoreOption = new JRadioButton("Use only edge information (no learning)");
weightScoreOption.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
if (weightScoreOption.isSelected()) {
outerTrainPanel.setVisible(false);
minScore = minScoreThreshold();
if (minScore < 0) {
// User needs to select a protein graph
scoringButtons.clearSelection();
} else {
minScoreThreshold.setText(Double.toString(minScore));
}
}
}
});
learningScoreOption = new JRadioButton("Use supervised learning with a Bayesian model");
learningScoreOption.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
if (learningScoreOption.isSelected()) {
outerTrainPanel.setVisible(true);
minScoreThreshold.setText("0");
}
}
});
scorePanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(0,0,15,15);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weighty = 1.0;
gbc.weightx = 1.0;
gbc.gridy = 0;
scorePanel.add(weightScoreOption, gbc);
gbc.gridy = 1;
scorePanel.add(learningScoreOption, gbc);
gbc.gridy = 2;
outerTrainPanel.setVisible(false);
scorePanel.add(outerTrainPanel, gbc);
scoringButtons.add(weightScoreOption);
scoringButtons.add(learningScoreOption);
}
return scorePanel;
}
public JPanel createTrainPanel() {
if (trainPanel == null) {
final JPanel modelPanel = new JPanel();
final JPanel trainingFilePanel = new JPanel();
trainPanel = new JPanel();
trainPanel.setLayout(new BoxLayout(trainPanel, BoxLayout.Y_AXIS));
// By Default, the model selection and training file buttons should be disabled
// until an option is selected
modelPanel.setVisible(false);
trainingFilePanel.setVisible(false);
// Use Trained Model?
useTrainedModel = new JRadioButton("Provide a trained model");
useTrainedModel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
if (useTrainedModel.isSelected()) {
modelPanel.setVisible(true);
trainingFilePanel.setVisible(false);
clusterPrior.setEnabled(false);
negativeExamples.setEnabled(false);
ignoreMissing.setEnabled(false);
}
}
});
// Train the Default (Built-in) Model?
trainDefaultModel = new JRadioButton("Train the built-in model");
trainDefaultModel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
if (trainDefaultModel.isSelected()) {
modelPanel.setVisible(false);
trainingFilePanel.setVisible(true);
clusterPrior.setEnabled(true);
negativeExamples.setEnabled(true);
ignoreMissing.setEnabled(true);
}
}
});
// Train a Custom Model?
trainCustomModel = new JRadioButton("Train a custom model");
trainCustomModel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
if (trainCustomModel.isSelected()) {
modelPanel.setVisible(true);
trainingFilePanel.setVisible(true);
clusterPrior.setEnabled(true);
negativeExamples.setEnabled(true);
ignoreMissing.setEnabled(true);
}
}
});
// Options for training: train built-in model, train a custom model,
// or provide an already-trained model. Radio buttons controlling these
// options are in one ButtonGroup (only one can be selected at a time
ButtonGroup trainingButtons = new ButtonGroup();
trainingButtons.add(useTrainedModel);
trainingButtons.add(trainDefaultModel);
trainingButtons.add(trainCustomModel);
// Create the panel holding radio buttons for training options
trainingOptionPanel = new JPanel();
trainingOptionPanel.setLayout(new BoxLayout(trainingOptionPanel, BoxLayout.Y_AXIS));
trainingOptionPanel.add(trainDefaultModel);
trainingOptionPanel.add(useTrainedModel);
trainingOptionPanel.add(trainCustomModel);
TitledBorder border = new TitledBorder("Select a Training Option:");
border.setTitleJustification(TitledBorder.CENTER);
border.setTitlePosition(TitledBorder.TOP);
trainingOptionPanel.setBorder(border);
model = new JComboBox(getNetworkNames().toArray());
JLabel modelLabel = new JLabel("Select Model");
modelPanel.add(modelLabel);
modelPanel.add(model);
// Minimum acceptable score
minScoreThreshold = new JTextField("0");
minScoreThresholdLabel = new JLabel("Minimum Complex Score");
clusterPrior = new JTextField("1E-4");
clusterPriorLabel = new JLabel("Cluster Probability Prior");
negativeExamples = new JTextField("2000");
negativeExamplesLabel = new JLabel("Generate # of Negative Examples");
trainingFileButton = new JButton("Training File (.tab, .tsv)");
trainingFileLabel = new JLabel("Positive Training Data");
trainingFileButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
JFileChooser trainingChooser = new JFileChooser();
int result = trainingChooser.showOpenDialog(MyControlPanel.this);
if (result == JFileChooser.APPROVE_OPTION) {
trainingFile = trainingChooser.getSelectedFile();
trainingFileLabel.setText(trainingFile.getName());
// Get number of positive training examples in order to set number of negative training examples
LineNumberReader lnr;
try {
lnr = new LineNumberReader(new FileReader(trainingFile));
lnr.skip(Long.MAX_VALUE);
negativeExamples.setText(Integer.toString(lnr.getLineNumber() + 1));
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
});
trainingFilePanel.add(trainingFileLabel);
trainingFilePanel.add(trainingFileButton);
ignoreMissing = new JCheckBox();
ignoreMissing.setSelected(true);
ignoreMissingLabel = new JLabel("Ignore Missing Nodes");
// Set the alignment on the panels to be left-justified
trainingOptionPanel.setAlignmentX( Component.CENTER_ALIGNMENT );
modelPanel.setAlignmentX( Component.CENTER_ALIGNMENT );
trainingFilePanel.setAlignmentX( Component.CENTER_ALIGNMENT );
trainPanel.add(trainingOptionPanel);
trainPanel.add(modelPanel);
trainPanel.add(trainingFilePanel);
}
return trainPanel;
}
public JPanel createEvaluatePanel() {
if (evaluatePanel == null) {
evaluatePanel = new JPanel();
final GroupLayout layout = new GroupLayout(evaluatePanel);
evaluatePanel.setLayout(layout);
layout.setAutoCreateContainerGaps(true);
layout.setAutoCreateGaps(true);
TitledBorder eval = BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.blue), "Evaluate Results");
evaluatePanel.setBorder(eval);
p = new JTextField("0.5");
pLabel = new JLabel("p");
evaluationFileLabel = new JLabel("File of Testing Complexes");
evaluationFileButton = new JButton("Select Evaluation File");
evaluationFileButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
JFileChooser evaluationChooser = new JFileChooser();
int evaluation = evaluationChooser.showOpenDialog(MyControlPanel.this);
if (evaluation == JFileChooser.APPROVE_OPTION) {
evaluationFile = evaluationChooser.getSelectedFile();
evaluationFileLabel.setText(evaluationFile.getName());
}
}
});
layout.setHorizontalGroup(
layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(pLabel)
.addComponent(evaluationFileLabel))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(p)
.addComponent(evaluationFileButton))
);
layout.setVerticalGroup(
layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(pLabel)
.addComponent(p))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(evaluationFileLabel)
.addComponent(evaluationFileButton))
);
Component[] components = evaluatePanel.getComponents();
for(int i = 0; i < components.length; i++) {
components[i].setVisible(false);
}
evaluateButton.setVisible(false);
}
return evaluatePanel;
}
public Component getComponent() {
return this;
}
public CytoPanelName getCytoPanelName() {
return CytoPanelName.WEST;
}
public String getTitle() {
return "";
}
public Icon getIcon() {
ImageIcon icon = new ImageIcon(MyControlPanel.class.getResource("/images/SCODElogo2.png"));
return icon;
}
private List<String> getNetworkNames() {
List<String> names = new ArrayList<String>();
for (CyNetwork network: CyActivator.networkManager.getNetworkSet()) {
names.add(network.getRow(network).get(CyNetwork.NAME, String.class));
}
return names;
}
private List<String> getEdgeColumnNames() {
List<String> names = new ArrayList<String>();
names.add("- Select Column -");
for (CyNetwork network: CyActivator.networkManager.getNetworkSet()) {
for (CyColumn col: network.getDefaultEdgeTable().getColumns()) {
if (!names.contains(col.getName()) && (!col.getName().equals("SUID")) &&
((col.getType() == Double.class) || (col.getType() == Integer.class) || (col.getType() == Long.class)))
names.add(col.getName());
}
}
return names;
}
private void analyzeButtonPressed() {
Integer inputValidation = validateInput();
if (inputValidation == 1) {
InputTask inputTask = createInputTask();
clusterFactory = new SupervisedComplexTaskFactory(inputTask, appManager);
DialogTaskManager dialogTaskManager = registrar.getService(DialogTaskManager.class);
TaskIterator taskIter = clusterFactory.createTaskIterator();
dialogTaskManager.execute(taskIter);
Component[] evalComponents = evaluatePanel.getComponents();
for(int i = 0; i < evalComponents.length; i++) {
evalComponents[i].setVisible(true);
}
evaluatePanel.setVisible(true);
evaluateButton.setVisible(true);
TitledBorder eval = BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.blue), "Evaluate Results");
eval.setTitleColor(Color.blue);
evaluatePanel.setBorder(eval);
} else if (inputValidation == 2) {
JOptionPane.showMessageDialog(this, "Please select a training option");
} else if (inputValidation == 3) {
JOptionPane.showMessageDialog(this, "Please load a positive training file");
} else if (inputValidation == 4) {
JOptionPane.showMessageDialog(this, "Please select a scoring option");
} else if (inputValidation == 5) {
JOptionPane.showMessageDialog(this, "Please load a seed file, or uncheck 'Use Starting Seeds From File' under the advanced search parameters.");
} else if (inputValidation == 6) {
JOptionPane.showMessageDialog(this, "Please select the protein graph under 'Search'");
}
}
private void printResults() {
searchResults = clusterFactory.getSearchTask().getResults();
for (Cluster network : searchResults) {
CySubNetwork result = network.getSubNetwork();
List<CyNode> nodes = result.getNodeList();
List<CyEdge> edges = result.getEdgeList();
System.out.println(result.getRow(result).get(CyNetwork.NAME, String.class) + ": " + nodes.size() + " nodes and " + edges.size() + " edges.");
}
}
private void writeResultsToFile(File resultFile) throws IOException {
if (clusterFactory == null || clusterFactory.getSearchTask() == null) {
JOptionPane.showMessageDialog(this, "You have not performed search yet.");
} else if (clusterFactory.getSearchTask().getResults().size() == 0) {
JOptionPane.showMessageDialog(this, "Search has not returned any results.");
} else {
searchResults = clusterFactory.getSearchTask().getResults();
if (! resultFile.exists()) { resultFile.createNewFile(); }
FileWriter writer = new FileWriter(resultFile);
String fileContents = "";
int counter = 1;
int resultsBound = Math.min(Integer.valueOf(numResults.getText()), Integer.valueOf(searchResults.size()));
List<Cluster> limitedResults = searchResults.subList(0, resultsBound);
for (Cluster network : limitedResults) {
CySubNetwork result = network.getSubNetwork();
List<CyNode> nodes = result.getNodeList();
String complexName = (result.getRow(result).get(CyNetwork.NAME, String.class) == null) ?
"Complex #" + counter
: result.getRow(result).get(CyNetwork.NAME, String.class);
fileContents = fileContents + counter +"\t" + complexName + "\t";
for (CyNode n : nodes) {
CyNetwork nodeNetwork = getNetworkPointer(); // The network pointer is set in SearchTask.java
fileContents = fileContents + " " + (nodeNetwork.getDefaultNodeTable().getRow(n.getSUID()).get("shared name", String.class));
}
fileContents = fileContents + "\n";
counter++;
}
writer.write(fileContents);
writer.close();
JOptionPane.showMessageDialog(this, "Results written to file '" + resultFile.getName() + "'");
}
}
private void evaluateButtonPressed(File evaluateFile) throws IOException {
if (evaluateFile == null) {
JOptionPane.showMessageDialog(this, "You must provide an evaluation file.");
} else {
ArrayList< Set<String> > resultComplexes = new ArrayList< Set<String> >();
ArrayList< Set<String> > evalComplexes = new ArrayList< Set<String> >();
searchResults = clusterFactory.getSearchTask().getResults();
List<Cluster> limitedResults = searchResults.subList(0, Integer.valueOf(numResults.getText()));
for (Cluster network : limitedResults) {
CySubNetwork result = network.getSubNetwork();
System.out.print("Printing a complex:");
List<CyNode> nodes = result.getNodeList();
Set<String> nodeNames = new HashSet<String>();
for (CyNode n : nodes) {
CyNetwork nodeNetwork = getNetworkPointer();
nodeNames.add(nodeNetwork.getDefaultNodeTable().getRow(n.getSUID()).get("shared name", String.class));
System.out.print(" " + nodeNetwork.getDefaultNodeTable().getRow(n.getSUID()).get("shared name", String.class));
}
System.out.println("");
resultComplexes.add(nodeNames);
}
System.out.println("");
System.out.println("");
FileReader evalfileReader = new FileReader(evaluateFile);
BufferedReader evalbufferedReader = new BufferedReader(evalfileReader);
String line = null ;
while((line = evalbufferedReader.readLine()) != null) {
String[] l = line.split("\t");
if (l.length == 3) {
System.out.println("Line: " + line);
String complexes_string = l[2];
HashSet eval_complexes = new HashSet(Arrays.asList(complexes_string.split(" ")));
evalComplexes.add(eval_complexes);
}
}
evalbufferedReader.close();
System.out.println("");
System.out.println("");
int countPredicted = 0;
int countKnown = 0;
for (Set<String> predicted : resultComplexes) {
for (Set<String> known : evalComplexes) {
Set<String> intersection = new HashSet<String>(predicted);
intersection.retainAll(known);
double C = intersection.size() ;
double A = predicted.size() - C ;
double B = known.size() - C ;
float pVal = Float.parseFloat(p.getText());
if ( ((C / (A + C)) > pVal) && ((C / (B + C)) > pVal) ) {
countPredicted++;
}
}
}
for (Set<String> known : evalComplexes) {
for (Set<String> predicted : resultComplexes) {
Set<String> intersection = new HashSet<String>(known);
intersection.retainAll(predicted);
double C = intersection.size() ;
double A = predicted.size() - C ;
double B = known.size() - C ;
float pVal = Float.parseFloat(p.getText());
if ( ((C / (A + C)) > pVal) && ((C / (B + C)) > pVal) ) {
countKnown++;
}
}
}
double recall = (double) countKnown / (double) evalComplexes.size() ;
double precision = (double) countPredicted / (double) resultComplexes.size() ;
JOptionPane.showMessageDialog(this, "Recall: " + recall + "\nPrecision: " + precision, "Evaluation Scoring", JOptionPane.INFORMATION_MESSAGE);
}
}
private Double minScoreThreshold() {
if (proteinGraph.getSelectedItem().toString().equals(" - Select Network - ")) {
JOptionPane.showMessageDialog(this, "Please select a protein graph under 'Search'");
} else {
CyNetwork nw = null;
for (CyNetwork network: CyActivator.networkManager.getNetworkSet()) {
if (network.getRow(network).get(CyNetwork.NAME, String.class).equals(proteinGraph.getSelectedItem().toString())) {
nw = network;
break;
}
}
CyTable nodeTable = nw.getDefaultEdgeTable();
if(nodeTable.getColumn("weight") != null) {
// Network has weight column
CyColumn column = nodeTable.getColumn("weight");
List<Double> values = column.getValues(Double.class);
Double avgWeight = 0.0;
for (Double value : values) {
avgWeight += value;
}
avgWeight = avgWeight / values.size();
return avgWeight * Integer.valueOf(minSize.getText()) / 10;
} else {
// No weight column
return 0.5;
}
}
return -1.0;
}
private InputTask createInputTask() {
InputTask inputTask = new InputTask();
inputTask.graphName = proteinGraph.getSelectedItem().toString();
ListSingleSelection<String> inputChooser = new ListSingleSelection<String>("ISA","Greedy ISA", "Sorted-Neighbor ISA");
inputChooser.setSelectedValue(chooser.getSelectedItem().toString());
inputTask.chooser = inputChooser;
int inputCheckNumNeighbors = Integer.parseInt(checkNumNeighbors.getText());
inputTask.checkNumNeighbors = inputCheckNumNeighbors;
boolean inputUseSelectedForSeeds = useSelectedForSeeds.isSelected();
inputTask.useSelectedForSeeds = inputUseSelectedForSeeds;
int inputNumSeeds = Integer.parseInt(numSeeds.getText());
inputTask.numSeeds = inputNumSeeds;
int inputSearchLimit = Integer.parseInt(searchLimit.getText());
inputTask.searchLimit = inputSearchLimit;
double inputInitTemp = Double.parseDouble(initTemp.getText());
inputTask.initTemp = inputInitTemp;
double inputTempScalingFactor = Double.parseDouble(tempScalingFactor.getText());
inputTask.tempScalingFactor = inputTempScalingFactor;
double inputOverlapLimit = Double.parseDouble(overlapLimit.getText());
inputTask.overlapLimit = inputOverlapLimit;
double inputMinScoreThreshold = Double.parseDouble(minScoreThreshold.getText());
inputTask.minScoreThreshold = inputMinScoreThreshold;
int inputMinSize = Integer.parseInt(minSize.getText());
inputTask.minSize = inputMinSize;
boolean inputTrainNewModel = trainCustomModel.isSelected() || trainDefaultModel.isSelected();
inputTask.trainNewModel = inputTrainNewModel;
ListSingleSelection<String> inputExistingModel = new ListSingleSelection<String>(getNetworkNames());
inputExistingModel.setSelectedValue(model.getSelectedItem().toString());
inputTask.existingModel = inputExistingModel;
boolean inputCustomModel = trainCustomModel.isSelected();
inputTask.customModel = inputCustomModel;
ListSingleSelection<String> inputBayesModel = new ListSingleSelection<String>(getNetworkNames());
inputBayesModel.setSelectedValue(model.getSelectedItem().toString());
inputTask.bayesModel = inputBayesModel;
ListSingleSelection<String> inputWeightName = new ListSingleSelection<String>(getEdgeColumnNames());
// inputWeightName.setSelectedValue(weightName.getSelectedItem().toString());
inputWeightName.setSelectedValue("weight");
inputTask.weightName = inputWeightName;
double inputClusterPrior = Double.parseDouble(clusterPrior.getText());
inputTask.clusterPrior = inputClusterPrior;
int inputNegativeExamples = Integer.parseInt(negativeExamples.getText());
inputTask.negativeExamples = inputNegativeExamples;
inputTask.trainingFile = trainingFile;
boolean inputIgnoreMissing = ignoreMissing.isSelected();
inputTask.ignoreMissing = inputIgnoreMissing;
inputTask.resultFile = resultFile;
inputTask.selectedSeedFile = useSelectedForSeedsFile;
inputTask.supervisedLearning = learningScoreOption.isSelected();
inputTask.numResults = Integer.parseInt((numResults.getText()));
return inputTask;
}
private Integer validateInput() {
if (learningScoreOption.isSelected() && !useTrainedModel.isSelected() && !trainDefaultModel.isSelected() && !trainCustomModel.isSelected()) {
// User has not selected a training option
return 2;
}
else if ( learningScoreOption.isSelected() && (trainDefaultModel.isSelected() || trainCustomModel.isSelected() ) && trainingFile == null ) {
// User has not provided a positive training file for one of the training options
return 3;
}
else if (proteinGraph.getSelectedItem().equals(" - Select Network - ")) {
// User has not selected a protein graph
return 6;
}
else if (!weightScoreOption.isSelected() && !learningScoreOption.isSelected()) {
// User has not selected a scoring option
return 4;
}
else if (useSelectedForSeeds.isSelected() && (useSelectedForSeedsFile == null)) {
// User has not provided a seed file
return 5;
}
return 1;
}
private CyNetwork getNetworkPointer() {
CyNetwork networkptr = null;
for (CyNetwork network: CyActivator.networkManager.getNetworkSet()) {
if (network.getRow(network).get(CyNetwork.NAME, String.class).equals(proteinGraph.getSelectedItem().toString())) {
networkptr = network;
}
}
return networkptr;
}
} |
package net.maizegenetics.baseplugins;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import net.maizegenetics.pal.alignment.Alignment;
import net.maizegenetics.pal.alignment.AlignmentMask;
import net.maizegenetics.pal.alignment.ExportUtils;
import net.maizegenetics.pal.alignment.Phenotype;
import net.maizegenetics.pal.alignment.PhenotypeUtils;
import net.maizegenetics.plugindef.AbstractPlugin;
import net.maizegenetics.plugindef.DataSet;
import net.maizegenetics.plugindef.Datum;
import net.maizegenetics.prefs.TasselPrefs;
import net.maizegenetics.pal.report.Report;
import net.maizegenetics.pal.report.TableReport;
import net.maizegenetics.pal.report.TableReportUtils;
import net.maizegenetics.gui.DialogUtils;
import net.maizegenetics.util.ExceptionUtils;
import net.maizegenetics.util.Utils;
import net.maizegenetics.pal.distance.DistanceMatrix;
import net.maizegenetics.pal.distance.WriteDistanceMatrix;
import net.maizegenetics.tassel.TASSELMainFrame;
import javax.swing.*;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.net.URL;
import javax.swing.tree.DefaultMutableTreeNode;
import org.apache.log4j.Logger;
/**
*
* @author terry
*/
public class ExportPlugin extends AbstractPlugin {
private static final Logger myLogger = Logger.getLogger(ExportPlugin.class);
private FileLoadPlugin.TasselFileType myFileType = FileLoadPlugin.TasselFileType.Hapmap;
private String mySaveFile = null;
private boolean myIsDiploid = false;
/**
* Creates a new instance of ExportPlugin
*/
public ExportPlugin(Frame parentFrame, boolean isInteractive) {
super(parentFrame, isInteractive);
}
public DataSet performFunction(DataSet input) {
try {
if (input.getSize() != 1) {
String message = "Please select one and only one item.";
if (isInteractive()) {
JOptionPane.showMessageDialog(getParentFrame(), message);
} else {
myLogger.error("performFunction: " + message);
}
return null;
}
String filename = mySaveFile;
try {
Object data = input.getData(0).getData();
if (data instanceof Alignment) {
filename = performFunctionForAlignment((Alignment) data);
} else if (data instanceof Phenotype) {
filename = performFunctionForPhenotype((Phenotype) data);
} else if (data instanceof DistanceMatrix) {
filename = performFunctionForDistanceMatrix((DistanceMatrix) data);
} else if (data instanceof TableReport) {
filename = performFunctionForTableReport((TableReport) data);
} else if (data instanceof Report) {
filename = performFunctionForReport((Report) data);
} else {
String message = "Don't know how to export data type: " + data.getClass().getName();
if (isInteractive()) {
JOptionPane.showMessageDialog(getParentFrame(), message);
} else {
myLogger.error("performFunction: " + message);
}
return null;
}
} catch (Exception e) {
e.printStackTrace();
StringBuilder builder = new StringBuilder();
builder.append(Utils.shortenStrLineLen(ExceptionUtils.getExceptionCauses(e), 50));
String str = builder.toString();
if (isInteractive()) {
DialogUtils.showError(str, getParentFrame());
} else {
myLogger.error(str);
}
return null;
}
if (filename != null) {
myLogger.info("performFunction: wrote dataset: " + input.getData(0).getName() + " to file: " + filename);
return new DataSet(new Datum("Filename", filename, null), this);
} else {
return null;
}
} finally {
fireProgress(100);
}
}
public String performFunctionForDistanceMatrix(DistanceMatrix input) {
if (isInteractive()) {
setSaveFile(getFileByChooser());
}
if ((mySaveFile == null) || (mySaveFile.length() == 0)) {
return null;
}
try {
File theFile = new File(Utils.addSuffixIfNeeded(mySaveFile, ".txt"));
WriteDistanceMatrix.saveDelimitedDistanceMatrix(input, theFile);
return theFile.getCanonicalPath();
} catch (Exception e) {
e.printStackTrace();
throw new IllegalStateException("ExportPlugin: performFunctionForDistanceMatrix: Problem writing file: " + mySaveFile);
}
}
public String performFunctionForTableReport(TableReport input) {
if (isInteractive()) {
setSaveFile(getFileByChooser());
}
if ((mySaveFile == null) || (mySaveFile.length() == 0)) {
return null;
}
try {
File theFile = new File(Utils.addSuffixIfNeeded(mySaveFile, ".txt"));
TableReportUtils.saveDelimitedTableReport(input, "\t", theFile);
return theFile.getCanonicalPath();
} catch (Exception e) {
e.printStackTrace();
throw new IllegalStateException("ExportPlugin: performFunctionForTableReport: Problem writing file: " + mySaveFile);
}
}
public String performFunctionForPhenotype(Phenotype input) {
if (isInteractive()) {
setSaveFile(getFileByChooser());
}
if ((mySaveFile == null) || (mySaveFile.length() == 0)) {
return null;
}
File theFile = null;
FileWriter fw = null;
PrintWriter pw = null;
try {
theFile = new File(Utils.addSuffixIfNeeded(mySaveFile, ".txt"));
fw = new FileWriter(theFile);
pw = new PrintWriter(fw);
PhenotypeUtils.saveAs(input, pw);
return theFile.getCanonicalPath();
} catch (Exception e) {
e.printStackTrace();
throw new IllegalStateException("ExportPlugin: performFunctionForPhenotype: Problem writing file: " + mySaveFile);
} finally {
try {
pw.close();
fw.close();
} catch (Exception e) {
// do nothing
}
}
}
public String performFunctionForAlignment(Alignment inputAlignment) {
if (isInteractive()) {
ExportPluginDialog theDialog = new ExportPluginDialog();
theDialog.setLocationRelativeTo(getParentFrame());
theDialog.setVisible(true);
if (theDialog.isCancel()) {
return null;
}
myFileType = theDialog.getTasselFileType();
theDialog.dispose();
setSaveFile(getFileByChooser());
}
if ((mySaveFile == null) || (mySaveFile.length() == 0)) {
return null;
}
String resultFile = mySaveFile;
if ((myFileType == FileLoadPlugin.TasselFileType.Hapmap) || (myFileType == FileLoadPlugin.TasselFileType.HapmapDiploid)) {
int n = 0;
DefaultMutableTreeNode node = null;
if (isInteractive()) {
DiploidOptionDialog diploidDialog = new DiploidOptionDialog();
diploidDialog.setLocationRelativeTo(getParentFrame());
diploidDialog.setVisible(true);
myIsDiploid = diploidDialog.getDiploid();
node = (DefaultMutableTreeNode) ((TASSELMainFrame) this.getParentFrame()).getDataTreePanel().getTree().getLastSelectedPathComponent();
n = node.getChildCount();
} else {
if (myFileType == FileLoadPlugin.TasselFileType.Hapmap) {
myIsDiploid = false;
} else if (myFileType == FileLoadPlugin.TasselFileType.HapmapDiploid) {
myIsDiploid = true;
}
}
boolean foundImputed = false;
if ((n == 0) || (!isInteractive())) {
resultFile = ExportUtils.writeToHapmap(inputAlignment, myIsDiploid, mySaveFile, '\t', this);
} else {
int i = 0;
while (i < n && !foundImputed) {
DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode) node.getChildAt(i);
Datum currentDatum = (Datum) currentNode.getUserObject();
Object currentMask = currentDatum.getData();
if (currentMask instanceof AlignmentMask) {
AlignmentMask.MaskType maskType = ((AlignmentMask) currentMask).getMaskType();
if (maskType == AlignmentMask.MaskType.imputed) {
ImputeDisplayOptionDialog imputeOptionDialog = new ImputeDisplayOptionDialog();
imputeOptionDialog.setLocationRelativeTo(getParentFrame());
imputeOptionDialog.setVisible(true);
if (imputeOptionDialog.getDisplayImputed()) {
resultFile = ExportUtils.writeToHapmap(inputAlignment, (AlignmentMask) currentMask, myIsDiploid, mySaveFile, '\t', this);
foundImputed = true;
} else if (i == (n - 1)) {
resultFile = ExportUtils.writeToHapmap(inputAlignment, myIsDiploid, mySaveFile, '\t', this);
}
}
}
i++;
}
}
} else if (myFileType == FileLoadPlugin.TasselFileType.Plink) {
resultFile = ExportUtils.writeToPlink(inputAlignment, mySaveFile, '\t');
} else if (myFileType == FileLoadPlugin.TasselFileType.Flapjack) {
resultFile = ExportUtils.writeToFlapjack(inputAlignment, mySaveFile, '\t');
} else if (myFileType == FileLoadPlugin.TasselFileType.Phylip_Seq) {
PrintWriter out = null;
try {
resultFile = Utils.addSuffixIfNeeded(mySaveFile, ".phy");
out = new PrintWriter(new FileWriter(resultFile));
ExportUtils.printSequential(inputAlignment, out);
} catch (Exception e) {
throw new IllegalStateException("ExportPlugin: performFunction: Problem writing file: " + mySaveFile);
} finally {
out.flush();
out.close();
}
} else if (myFileType == FileLoadPlugin.TasselFileType.Phylip_Inter) {
PrintWriter out = null;
try {
resultFile = Utils.addSuffixIfNeeded(mySaveFile, ".phy");
out = new PrintWriter(new FileWriter(resultFile));
ExportUtils.printInterleaved(inputAlignment, out);
} catch (Exception e) {
throw new IllegalStateException("ExportPlugin: performFunction: Problem writing file: " + mySaveFile);
} finally {
out.flush();
out.close();
}
} else if (myFileType == FileLoadPlugin.TasselFileType.Table) {
resultFile = ExportUtils.saveDelimitedAlignment(inputAlignment, "\t", mySaveFile);
} else if (myFileType == FileLoadPlugin.TasselFileType.Serial) {
resultFile = ExportUtils.writeAlignmentToSerialGZ(inputAlignment, mySaveFile);
} else {
throw new IllegalStateException("ExportPlugin: performFunction: Unknown Alignment File Format: " + myFileType);
}
return resultFile;
}
public String performFunctionForReport(Report input) {
if (isInteractive()) {
ReportOptionDialog theDialog = new ReportOptionDialog();
theDialog.setLocationRelativeTo(getParentFrame());
theDialog.setVisible(true);
if (theDialog.isCancel()) {
return null;
}
myFileType = theDialog.getTasselFileType();
theDialog.dispose();
setSaveFile(getFileByChooser());
}
if ((mySaveFile == null) || (mySaveFile.length() == 0)) {
return null;
}
String resultFile = Utils.addSuffixIfNeeded(mySaveFile, ".txt");
if (myFileType == FileLoadPlugin.TasselFileType.Text) {
BufferedWriter writer = Utils.getBufferedWriter(resultFile);
try {
writer.append(input.toString());
} catch (Exception e) {
e.printStackTrace();
throw new IllegalStateException("ExportPlugin: performFunctionForReport: Problem writing file: " + resultFile);
} finally {
try {
writer.close();
} catch (Exception e) {
// do nothing
}
}
} else {
PrintWriter writer = null;
try {
writer = new PrintWriter(resultFile);
input.report(writer);
} catch (Exception e) {
e.printStackTrace();
throw new IllegalStateException("ExportPlugin: performFunctionForReport: Problem writing file: " + resultFile);
} finally {
try {
writer.close();
} catch (Exception e) {
// do nothing
}
}
}
return resultFile;
}
/**
* Icon for this plugin to be used in buttons, etc.
*
* @return ImageIcon
*/
public ImageIcon getIcon() {
URL imageURL = ExportPlugin.class.getResource("images/Export16.gif");
if (imageURL == null) {
return null;
} else {
return new ImageIcon(imageURL);
}
}
/**
* Button name for this plugin to be used in buttons, etc.
*
* @return String
*/
public String getButtonName() {
return "Export";
}
/**
* Tool Tip Text for this plugin
*
* @return String
*/
public String getToolTipText() {
return "Export data to files on your computer.";
}
public String getSaveFile() {
return mySaveFile;
}
public void setSaveFile(String saveFile) {
mySaveFile = saveFile;
}
public void setSaveFile(File saveFile) {
if (saveFile == null) {
mySaveFile = null;
} else {
mySaveFile = saveFile.getPath();
}
}
public void setAlignmentFileType(FileLoadPlugin.TasselFileType type) {
myFileType = type;
}
public void setIsDiploid(boolean isDiploid) {
myIsDiploid = isDiploid;
}
private File getFileByChooser() {
JFileChooser fileSave = new JFileChooser(TasselPrefs.getSaveDir());
fileSave.setMultiSelectionEnabled(false);
File result = null;
int returnVal = fileSave.showSaveDialog(getParentFrame());
if (returnVal == JFileChooser.SAVE_DIALOG || returnVal == JFileChooser.APPROVE_OPTION) {
result = fileSave.getSelectedFile();
TasselPrefs.putSaveDir(fileSave.getCurrentDirectory().getPath());
}
return result;
}
class ExportPluginDialog extends JDialog {
private boolean myIsCancel = true;
private ButtonGroup myButtonGroup = new ButtonGroup();
private JRadioButton myHapMapRadioButton = new JRadioButton("Write Hapmap");
private JRadioButton myPlinkRadioButton = new JRadioButton("Write Plink");
private JRadioButton myFlapjackRadioButton = new JRadioButton("Write Flapjack");
private JRadioButton myPhylipRadioButton = new JRadioButton("Write Phylip (Sequential)");
private JRadioButton myPhylipInterRadioButton = new JRadioButton("Write Phylip (Interleaved)");
private JRadioButton myTabTableRadioButton = new JRadioButton("Write Tab Delimited");
public ExportPluginDialog() {
super((Frame) null, "Export...", true);
try {
jbInit();
pack();
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void jbInit() throws Exception {
setTitle("Export...");
setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
setUndecorated(false);
getRootPane().setWindowDecorationStyle(JRootPane.NONE);
Container contentPane = getContentPane();
BoxLayout layout = new BoxLayout(contentPane, BoxLayout.Y_AXIS);
contentPane.setLayout(layout);
JPanel main = getMain();
contentPane.add(main);
pack();
setResizable(false);
myButtonGroup.add(myHapMapRadioButton);
myButtonGroup.add(myPlinkRadioButton);
myButtonGroup.add(myFlapjackRadioButton);
myButtonGroup.add(myPhylipRadioButton);
myButtonGroup.add(myPhylipInterRadioButton);
myButtonGroup.add(myTabTableRadioButton);
myHapMapRadioButton.setSelected(true);
}
private JPanel getMain() {
JPanel inputs = new JPanel();
BoxLayout layout = new BoxLayout(inputs, BoxLayout.Y_AXIS);
inputs.setLayout(layout);
inputs.setAlignmentX(JPanel.CENTER_ALIGNMENT);
inputs.add(Box.createRigidArea(new Dimension(1, 10)));
inputs.add(getLabel());
inputs.add(Box.createRigidArea(new Dimension(1, 10)));
inputs.add(getOptionPanel());
inputs.add(Box.createRigidArea(new Dimension(1, 10)));
inputs.add(getButtons());
inputs.add(Box.createRigidArea(new Dimension(1, 10)));
return inputs;
}
private JPanel getLabel() {
JPanel result = new JPanel();
BoxLayout layout = new BoxLayout(result, BoxLayout.Y_AXIS);
result.setLayout(layout);
result.setAlignmentX(JPanel.CENTER_ALIGNMENT);
JLabel jLabel1 = new JLabel("Choose File Type to Export.");
jLabel1.setFont(new Font("Dialog", Font.BOLD, 18));
result.add(jLabel1);
return result;
}
private JPanel getOptionPanel() {
JPanel result = new JPanel();
BoxLayout layout = new BoxLayout(result, BoxLayout.Y_AXIS);
result.setLayout(layout);
result.setAlignmentX(JPanel.CENTER_ALIGNMENT);
result.setBorder(BorderFactory.createEtchedBorder());
result.add(myHapMapRadioButton);
result.add(myPlinkRadioButton);
result.add(myFlapjackRadioButton);
result.add(myPhylipRadioButton);
result.add(myPhylipInterRadioButton);
result.add(myTabTableRadioButton);
result.add(Box.createRigidArea(new Dimension(1, 20)));
return result;
}
private JPanel getButtons() {
JButton okButton = new JButton();
JButton cancelButton = new JButton();
cancelButton.setText("Cancel");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cancelButton_actionPerformed(e);
}
});
okButton.setText("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
okButton_actionPerformed(e);
}
});
JPanel result = new JPanel(new FlowLayout(FlowLayout.CENTER));
result.add(okButton);
result.add(cancelButton);
return result;
}
public FileLoadPlugin.TasselFileType getTasselFileType() {
if (myHapMapRadioButton.isSelected()) {
return FileLoadPlugin.TasselFileType.Hapmap;
}
if (myPlinkRadioButton.isSelected()) {
return FileLoadPlugin.TasselFileType.Plink;
}
if (myFlapjackRadioButton.isSelected()) {
return FileLoadPlugin.TasselFileType.Flapjack;
}
if (myPhylipRadioButton.isSelected()) {
return FileLoadPlugin.TasselFileType.Phylip_Seq;
}
if (myPhylipInterRadioButton.isSelected()) {
return FileLoadPlugin.TasselFileType.Phylip_Inter;
}
if (myTabTableRadioButton.isSelected()) {
return FileLoadPlugin.TasselFileType.Table;
}
return null;
}
private void okButton_actionPerformed(ActionEvent e) {
myIsCancel = false;
setVisible(false);
}
private void cancelButton_actionPerformed(ActionEvent e) {
myIsCancel = true;
setVisible(false);
}
public boolean isCancel() {
return myIsCancel;
}
}
}
class ImputeDisplayOptionDialog extends JDialog {
boolean displayImputed = true;
private JPanel mainPanel = new JPanel();
private JLabel lbl = new JLabel();
private JButton yesButton = new JButton();
private JButton noButton = new JButton();
private GridBagLayout gridBagLayout = new GridBagLayout();
public ImputeDisplayOptionDialog() {
super((Frame) null, "File Loader", true);
try {
initUI();
pack();
} catch (Exception ex) {
ex.printStackTrace();
}
}
void initUI() throws Exception {
lbl.setFont(new java.awt.Font("Dialog", 1, 12));
lbl.setText("Would you like Imputed data to be exported in lower case?");
mainPanel.setMinimumSize(new Dimension(480, 150));
mainPanel.setPreferredSize(new Dimension(480, 150));
mainPanel.setLayout(gridBagLayout);
yesButton.setMaximumSize(new Dimension(63, 27));
yesButton.setMinimumSize(new Dimension(63, 27));
yesButton.setText("Yes");
yesButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
yesButton_actionPerformed(e);
}
});
noButton.setMaximumSize(new Dimension(63, 27));
noButton.setMinimumSize(new Dimension(63, 27));
noButton.setText("No");
noButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
noButton_actionPerformed(e);
}
});
JPanel buttonPanel = new JPanel();
buttonPanel.add(yesButton);
buttonPanel.add(noButton);
mainPanel.add(lbl, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 0, 5, 0), 0, 0));
mainPanel.add(buttonPanel, new GridBagConstraints(0, 1, 1, 1, 1.0, 1.0, GridBagConstraints.PAGE_END, GridBagConstraints.NONE, new Insets(5, 0, 5, 0), 0, 0));
this.add(mainPanel, BorderLayout.CENTER);
}
private void yesButton_actionPerformed(ActionEvent e) {
displayImputed = true;
setVisible(false);
}
private void noButton_actionPerformed(ActionEvent e) {
displayImputed = false;
setVisible(false);
}
public boolean getDisplayImputed() {
return displayImputed;
}
}
class DiploidOptionDialog extends JDialog {
boolean displayDiploid = true;
private JPanel mainPanel = new JPanel();
private JLabel lbl = new JLabel();
private JButton yesButton = new JButton();
private JButton noButton = new JButton();
private GridBagLayout gridBagLayout = new GridBagLayout();
public DiploidOptionDialog() {
super((Frame) null, "File Loader", true);
try {
initUI();
pack();
} catch (Exception ex) {
ex.printStackTrace();
}
}
void initUI() throws Exception {
lbl.setFont(new java.awt.Font("Dialog", 1, 12));
lbl.setText("Would you like SNPs to be exported as Diploids?");
mainPanel.setMinimumSize(new Dimension(480, 150));
mainPanel.setPreferredSize(new Dimension(480, 150));
mainPanel.setLayout(gridBagLayout);
yesButton.setMaximumSize(new Dimension(63, 27));
yesButton.setMinimumSize(new Dimension(63, 27));
yesButton.setText("Yes");
yesButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
yesButton_actionPerformed(e);
}
});
noButton.setMaximumSize(new Dimension(63, 27));
noButton.setMinimumSize(new Dimension(63, 27));
noButton.setText("No");
noButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
noButton_actionPerformed(e);
}
});
JPanel buttonPanel = new JPanel();
buttonPanel.add(yesButton);
buttonPanel.add(noButton);
mainPanel.add(lbl, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 0, 5, 0), 0, 0));
mainPanel.add(buttonPanel, new GridBagConstraints(0, 1, 1, 1, 1.0, 1.0, GridBagConstraints.PAGE_END, GridBagConstraints.NONE, new Insets(5, 0, 5, 0), 0, 0));
this.add(mainPanel, BorderLayout.CENTER);
}
private void yesButton_actionPerformed(ActionEvent e) {
displayDiploid = true;
setVisible(false);
}
private void noButton_actionPerformed(ActionEvent e) {
displayDiploid = false;
setVisible(false);
}
public boolean getDiploid() {
return displayDiploid;
}
}
class ReportOptionDialog extends JDialog {
private boolean myIsCancel = true;
private ButtonGroup myButtonGroup = new ButtonGroup();
private JRadioButton myReportRadioButton = new JRadioButton("Write As Report");
private JRadioButton myTextRadioButton = new JRadioButton("Write As Text");
public ReportOptionDialog() {
super((Frame) null, "Export Report...", true);
try {
jbInit();
pack();
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void jbInit() throws Exception {
setTitle("Export Report...");
setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
setUndecorated(false);
getRootPane().setWindowDecorationStyle(JRootPane.NONE);
Container contentPane = getContentPane();
BoxLayout layout = new BoxLayout(contentPane, BoxLayout.Y_AXIS);
contentPane.setLayout(layout);
JPanel main = getMain();
contentPane.add(main);
pack();
setResizable(false);
myButtonGroup.add(myReportRadioButton);
myButtonGroup.add(myTextRadioButton);
myReportRadioButton.setSelected(true);
}
private JPanel getMain() {
JPanel inputs = new JPanel();
BoxLayout layout = new BoxLayout(inputs, BoxLayout.Y_AXIS);
inputs.setLayout(layout);
inputs.setAlignmentX(JPanel.CENTER_ALIGNMENT);
inputs.add(Box.createRigidArea(new Dimension(1, 10)));
inputs.add(getLabel());
inputs.add(Box.createRigidArea(new Dimension(1, 10)));
inputs.add(getOptionPanel());
inputs.add(Box.createRigidArea(new Dimension(1, 10)));
inputs.add(getButtons());
inputs.add(Box.createRigidArea(new Dimension(1, 10)));
return inputs;
}
private JPanel getLabel() {
JPanel result = new JPanel();
BoxLayout layout = new BoxLayout(result, BoxLayout.Y_AXIS);
result.setLayout(layout);
result.setAlignmentX(JPanel.CENTER_ALIGNMENT);
JLabel jLabel1 = new JLabel("Choose File Type to Export.");
jLabel1.setFont(new Font("Dialog", Font.BOLD, 18));
result.add(jLabel1);
return result;
}
private JPanel getOptionPanel() {
JPanel result = new JPanel();
BoxLayout layout = new BoxLayout(result, BoxLayout.Y_AXIS);
result.setLayout(layout);
result.setAlignmentX(JPanel.CENTER_ALIGNMENT);
result.setBorder(BorderFactory.createEtchedBorder());
result.add(myReportRadioButton);
result.add(myTextRadioButton);
result.add(Box.createRigidArea(new Dimension(1, 20)));
return result;
}
private JPanel getButtons() {
JButton okButton = new JButton();
JButton cancelButton = new JButton();
cancelButton.setText("Cancel");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cancelButton_actionPerformed(e);
}
});
okButton.setText("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
okButton_actionPerformed(e);
}
});
JPanel result = new JPanel(new FlowLayout(FlowLayout.CENTER));
result.add(okButton);
result.add(cancelButton);
return result;
}
public FileLoadPlugin.TasselFileType getTasselFileType() {
if (myTextRadioButton.isSelected()) {
return FileLoadPlugin.TasselFileType.Text;
}
return null;
}
private void okButton_actionPerformed(ActionEvent e) {
myIsCancel = false;
setVisible(false);
}
private void cancelButton_actionPerformed(ActionEvent e) {
myIsCancel = true;
setVisible(false);
}
public boolean isCancel() {
return myIsCancel;
}
} |
package eu.lp0.cursus.ui.component;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.persistence.PersistenceException;
import javax.swing.AbstractCellEditor;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import eu.lp0.cursus.db.DatabaseSession;
import eu.lp0.cursus.db.dao.EntityDAO;
import eu.lp0.cursus.db.data.Entity;
import eu.lp0.cursus.i18n.Messages;
import eu.lp0.cursus.util.Constants;
import eu.lp0.cursus.util.DatabaseError;
public abstract class DeleteDatabaseColumn<T extends Entity> extends DatabaseColumn<T, String> {
private final Logger log = LoggerFactory.getLogger(getClass());
private final EntityDAO<T> dao;
private final String action;
private final HeaderRenderer headerRenderer_;
private final JButton stdButton = new JButton("M"); //$NON-NLS-1$
private JTable table;
private JTableHeader header;
private DatabaseTableModel<T> model;
public DeleteDatabaseColumn(DatabaseWindow win, EntityDAO<T> dao, String action) {
super(null, win, dao);
this.dao = dao;
this.action = action;
headerRenderer = headerRenderer_ = new HeaderRenderer();
cellRenderer = new CellRenderer();
cellEditor = new CellEditor();
}
@Override
public int getMinWidth() {
return getPreferredWidth();
}
@Override
public int getMaxWidth() {
return getPreferredWidth();
}
@Override
public int getPreferredWidth() {
return stdButton.getPreferredSize().height;
}
@Override
public void setupModel(JTable table, DatabaseTableModel<T> model, TableRowSorter<? super TableModel> sorter) {
super.setupModel(table, model, sorter);
this.table = table;
this.header = table.getTableHeader();
this.model = model;
header.addMouseListener(headerRenderer_);
header.addMouseMotionListener(headerRenderer_);
header.addKeyListener(headerRenderer_);
sorter.setSortable(getModelIndex(), false);
}
protected abstract T newRow();
public void addRow() {
assert (SwingUtilities.isEventDispatchThread());
T row = null;
win.getDatabase().startSession();
try {
DatabaseSession.begin();
row = newRow();
dao.persist(row);
DatabaseSession.commit();
} catch (PersistenceException e) {
if (row != null) {
log.error(String.format("Unable to save row: %s#%d", row.getClass().getSimpleName(), row.getId()), e); //$NON-NLS-1$
}
DatabaseError.errorSaving(win.getFrame(), Constants.APP_NAME, e);
} finally {
win.getDatabase().endSession();
}
int mRow = model.getRowCount();
model.addRow(row);
int vRow = table.convertRowIndexToView(mRow);
table.getSelectionModel().setSelectionInterval(vRow, vRow);
table.scrollRectToVisible(table.getCellRect(mRow, table.convertColumnIndexToView(getModelIndex()), true));
}
protected boolean confirmDelete(T row) {
String value = getValue(row, false);
switch (JOptionPane.showConfirmDialog(win.getFrame(), Messages.getString(action + ".confirm", value), //$NON-NLS-1$
Messages.getString(action) + Constants.EN_DASH + value, JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE)) {
case JOptionPane.YES_OPTION:
return true;
case JOptionPane.NO_OPTION:
case JOptionPane.CLOSED_OPTION:
default:
return false;
}
}
protected boolean deleteRow(T row) {
assert (SwingUtilities.isEventDispatchThread());
win.getDatabase().startSession();
try {
DatabaseSession.begin();
T item = dao.get(row);
dao.remove(item);
DatabaseSession.commit();
return true;
} catch (PersistenceException e) {
log.error(String.format("Unable to delete row: row=%s#%d", row.getClass().getSimpleName(), row.getId()), e); //$NON-NLS-1$
DatabaseError.errorSaving(win.getFrame(), Constants.APP_NAME, e);
return false;
} finally {
win.getDatabase().endSession();
}
}
private class HeaderRenderer extends DefaultTableCellRenderer implements ActionListener, MouseListener, MouseMotionListener, KeyListener {
private final CellJButton button = new CellJButton("+"); //$NON-NLS-1$
public HeaderRenderer() {
button.addActionListener(this);
}
@Override
@SuppressWarnings("hiding")
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int vRow, int vCol) {
button.setSelected(isSelected);
button.setFocus(hasFocus);
return button;
}
@Override
public void actionPerformed(ActionEvent ae) {
addRow();
}
private boolean ourColumn(MouseEvent me) {
return table.isEnabled() && getModelIndex() == table.convertColumnIndexToModel(header.columnAtPoint(me.getPoint()));
}
@Override
public void mouseEntered(MouseEvent me) {
// If the mouse moves onto the header, do nothing as the mouseMoved event will be triggered
}
@Override
public void mousePressed(MouseEvent me) {
if (me.isConsumed()) {
return;
}
// Only depress the button if the mouse is over our column
if (ourColumn(me)) {
button.getModel().setArmed(true);
button.getModel().setPressed(true);
me.consume();
}
}
@Override
public void mouseReleased(MouseEvent me) {
if (me.isConsumed()) {
return;
}
// Always depress the button as the mouse may now be over another column
button.getModel().setPressed(false);
me.consume();
}
@Override
public void mouseClicked(MouseEvent me) {
// Do nothing as the button should have been successfully pressed while armed
}
@Override
public void mouseExited(MouseEvent me) {
if (me.isConsumed()) {
return;
}
// If the mouse moves off the header, disarm the button
button.getModel().setArmed(false);
me.consume();
}
@Override
public void mouseDragged(MouseEvent me) {
if (me.isConsumed()) {
return;
}
// Can't check the column here:
// it would work for the original location,
// but also for the new location... so it'd
// be clicked on column moves
button.getModel().setArmed(false);
me.consume();
}
@Override
public void mouseMoved(MouseEvent me) {
if (me.isConsumed()) {
return;
}
// If the mouse moves over our column, arm the button
if (ourColumn(me)) {
button.getModel().setArmed(true);
} else {
button.getModel().setArmed(false);
}
me.consume();
}
@Override
public void keyTyped(KeyEvent ke) {
if (table.isEnabled() && button.hasFakeFocus()) {
button.dispatchEvent(ke);
}
}
@Override
public void keyPressed(KeyEvent ke) {
// There's a side effect here in that the button won't
// get the key press that was used to change focus
if (table.isEnabled() && button.hasFakeFocus()) {
// This works but the button's not really visible
// so there's no visual feedback when activated
button.dispatchEvent(ke);
}
}
@Override
public void keyReleased(KeyEvent ke) {
// There's a side effect here in that the button won't
// get the key release that was used to change focus
if (table.isEnabled() && button.hasFakeFocus()) {
button.dispatchEvent(ke);
}
}
}
@Override
public TableCellRenderer getCellRenderer() {
return new CellRenderer();
}
private class CellJButton extends JButton {
private boolean focus;
private boolean painting;
public CellJButton(String text) {
super(text);
setMargin(new Insets(0, 0, 0, 0));
}
public void setFocus(boolean focus) {
this.focus = focus;
}
public boolean hasFakeFocus() {
return focus;
}
@Override
public void paint(Graphics g) {
painting = true;
super.paint(g);
painting = false;
}
@Override
public boolean isFocusOwner() {
return painting && focus || (isFocusable() && super.isFocusOwner());
}
@Override
public void revalidate() {
}
@Override
public void validate() {
}
}
private class CellRenderer extends DefaultTableCellRenderer {
private final CellJButton button = new CellJButton("-"); //$NON-NLS-1$
public CellRenderer() {
setOpaque(true);
button.setFocusable(false);
}
@Override
@SuppressWarnings("hiding")
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int vRow, int vCol) {
button.setFocus(hasFocus);
return button;
}
}
@Override
protected boolean setValue(T row, String value) {
throw new UnsupportedOperationException();
}
private class CellEditor extends AbstractCellEditor implements TableCellEditor, ActionListener {
private final CellJButton button = new CellJButton("-"); //$NON-NLS-1$
private Integer mRow;
private T mVal;
public CellEditor() {
button.setFocus(true);
button.addActionListener(this);
}
@Override
@SuppressWarnings("unchecked")
public Component getTableCellEditorComponent(@SuppressWarnings("hiding") JTable table, Object value, boolean isSelected, int vRow, int vCol) {
mRow = table.convertRowIndexToModel(vRow);
mVal = (T)value;
return button;
}
@Override
public Object getCellEditorValue() {
return mVal;
}
@Override
public void actionPerformed(ActionEvent ae) {
if (confirmDelete(mVal)) {
if (deleteRow(mVal)) {
super.stopCellEditing();
model.deleteRow(mRow);
}
}
}
@Override
public void cancelCellEditing() {
super.cancelCellEditing();
model = null;
mRow = null;
mVal = null;
}
@Override
public boolean stopCellEditing() {
try {
return super.stopCellEditing();
} finally {
model = null;
mRow = null;
mVal = null;
}
}
}
} |
package br.com.projeto.model;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
/**
*
* @author Daylton
*/
public class Teste {
public static void main(String[] args) {
Time t1 = new Time("Palmeiras", new ImageIcon("src/br/com/projeto/image/palmeiras_60x60.png"),12,12,12);
Time t2 = new Time("Chapecoense", new ImageIcon("src/br/com/projeto/image/chapecoense_60x60.png"),20,30,65);
Jogo jogo1 = new Jogo(t1, t2);
System.out.println("Coeficiente do Time 1: " + t1.getCoeficienteTime() + "\n");
System.out.println("Coeficiente do Time 2: " + t2.getCoeficienteTime() + "\n");
System.out.println("Posse de Bola T1: " + jogo1.getPosseDeBolaTime1() + "\n");
System.out.println("Posse de Bola T2: " + jogo1.getPosseDeBolaTime2() + "\n");
System.out.println("Finalizações T1: " + jogo1.getFinalizacaoTime1() + "\n");
System.out.println("Finalizações T2: " + jogo1.getFinalizacaoTime2() + "\n");
System.out.println("Gols T1: " + jogo1.getGolTime1() + "\n");
System.out.println("Gols T2: " + jogo1.getGolTime2() + "\n");
Font f = new Font("Consolas", Font.BOLD, 32);
JPanel painel = new JPanel();
GridLayout meuLayout = new GridLayout(4, 3, 5, 5);
JLabel escudo1 = new JLabel(jogo1.getTime1().getEscudo());
escudo1.setFont(f);
escudo1.setHorizontalAlignment(SwingConstants.CENTER);
escudo1.setVerticalAlignment(SwingConstants.CENTER);
JLabel escudo2 = new JLabel(jogo1.getTime2().getEscudo());
escudo2.setFont(f);
escudo2.setHorizontalAlignment(SwingConstants.CENTER);
escudo2.setVerticalAlignment(SwingConstants.CENTER);
JLabel gols1 = new JLabel(String.valueOf(jogo1.getGolTime1()));
gols1.setFont(f);
gols1.setHorizontalAlignment(SwingConstants.CENTER);
gols1.setVerticalAlignment(SwingConstants.CENTER);
JLabel gols2 = new JLabel(String.valueOf(jogo1.getGolTime2()));
gols2.setFont(f);
gols2.setHorizontalAlignment(SwingConstants.CENTER);
gols2.setVerticalAlignment(SwingConstants.CENTER);
JLabel finalizacoes1 = new JLabel(String.valueOf(jogo1.getFinalizacaoTime1()));
finalizacoes1.setFont(f);
finalizacoes1.setHorizontalAlignment(SwingConstants.CENTER);
finalizacoes1.setVerticalAlignment(SwingConstants.CENTER);
JLabel finalizacoes2 = new JLabel(String.valueOf(jogo1.getFinalizacaoTime2()));
finalizacoes2.setFont(f);
finalizacoes2.setHorizontalAlignment(SwingConstants.CENTER);
finalizacoes2.setVerticalAlignment(SwingConstants.CENTER);
JLabel posse1 = new JLabel((int)jogo1.getPosseDeBolaTime1() + "%");
posse1.setFont(f);
posse1.setHorizontalAlignment(SwingConstants.CENTER);
posse1.setVerticalAlignment(SwingConstants.CENTER);
JLabel posse2 = new JLabel((int)jogo1.getPosseDeBolaTime2() + "%");
posse2.setFont(f);
posse2.setHorizontalAlignment(SwingConstants.CENTER);
posse2.setVerticalAlignment(SwingConstants.CENTER);
JLabel textoTime = new JLabel("Time");
textoTime.setFont(f);
textoTime.setHorizontalAlignment(SwingConstants.CENTER);
textoTime.setVerticalAlignment(SwingConstants.CENTER);
JLabel textoGols = new JLabel("Gols");
textoGols.setFont(f);
textoGols.setHorizontalAlignment(SwingConstants.CENTER);
textoGols.setVerticalAlignment(SwingConstants.CENTER);
JLabel textoFinalizacoes = new JLabel("Finalizações");
textoFinalizacoes.setFont(f);
textoFinalizacoes.setHorizontalAlignment(SwingConstants.CENTER);
textoFinalizacoes.setVerticalAlignment(SwingConstants.CENTER);
JLabel textoPosse = new JLabel("Posse de Bola");
textoPosse.setFont(f);
textoPosse.setHorizontalAlignment(SwingConstants.CENTER);
textoPosse.setVerticalAlignment(SwingConstants.CENTER);
painel.setLayout(meuLayout);
painel.setBackground(Color.WHITE);
painel.add(textoTime);
painel.add(escudo1);
painel.add(escudo2);
painel.add(textoGols);
painel.add(gols1);
painel.add(gols2);
painel.add(textoFinalizacoes);
painel.add(finalizacoes1);
painel.add(finalizacoes2);
painel.add(textoPosse);
painel.add(posse1);
painel.add(posse2);
JOptionPane.showMessageDialog(null, painel, "Info Jogo", JOptionPane.PLAIN_MESSAGE);
}
} |
package info.faceland.strife.menus;
import com.tealcube.minecraft.bukkit.facecore.shade.amp.ampmenus.events.ItemClickEvent;
import com.tealcube.minecraft.bukkit.facecore.shade.amp.ampmenus.items.MenuItem;
import info.faceland.strife.StrifePlugin;
import info.faceland.strife.attributes.StrifeAttribute;
import info.faceland.strife.data.Champion;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class StatsDefenseMenuItem extends MenuItem {
private final StrifePlugin plugin;
private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("
private static final DecimalFormat REDUCER_FORMAT = new DecimalFormat("
public StatsDefenseMenuItem(StrifePlugin plugin) {
super(ChatColor.WHITE + "Defensive Stats", new ItemStack(Material.IRON_CHESTPLATE));
this.plugin = plugin;
}
@Override
public ItemStack getFinalIcon(Player player) {
Champion champion = plugin.getChampionManager().getChampion(player.getUniqueId());
Map<StrifeAttribute, Double> valueMap = champion.getAttributeValues();
ItemStack itemStack = new ItemStack(Material.IRON_CHESTPLATE);
ItemMeta itemMeta = Bukkit.getItemFactory().getItemMeta(itemStack.getType());
itemMeta.setDisplayName(getDisplayName());
List<String> lore = new ArrayList<>(getLore());
lore.add(ChatColor.BLUE + "Hitpoints: " + ChatColor.WHITE + DECIMAL_FORMAT.format(valueMap.get(StrifeAttribute.HEALTH)));
if (valueMap.get(StrifeAttribute.REGENERATION) > 1) {
lore.add(ChatColor.BLUE + "Regeneration: " + ChatColor.WHITE + valueMap.get(StrifeAttribute.REGENERATION));
}
if (valueMap.get(StrifeAttribute.ARMOR) > 0.35) {
double highArmor = 100 * (500/(500+Math.pow(((valueMap.get(StrifeAttribute.ARMOR) * 100) * (1 - valueMap.get(StrifeAttribute.ARMOR))), 1.7)));
lore.add(ChatColor.BLUE + "Armor: " + ChatColor.WHITE + DECIMAL_FORMAT
.format(100 * valueMap.get(StrifeAttribute.ARMOR)) + ChatColor.GRAY + " (" + REDUCER_FORMAT.format(highArmor) + "%)");
} else {
double lowArmor = 100 * (valueMap.get(StrifeAttribute.ARMOR) * (1 + (0.71-valueMap.get(StrifeAttribute.ARMOR))));
lore.add(ChatColor.BLUE + "Armor: " + ChatColor.WHITE + DECIMAL_FORMAT
.format(100 * valueMap.get(StrifeAttribute.ARMOR)) + ChatColor.GRAY + " (" + REDUCER_FORMAT.format(lowArmor) + "%)");
}
if (valueMap.get(StrifeAttribute.EVASION) > 0) {
double evasion = 100 * (1-(100/(100 + (Math.pow((valueMap.get(StrifeAttribute.EVASION) * 100), 1.25)))));
lore.add(ChatColor.BLUE + "Evasion: " + ChatColor.WHITE + DECIMAL_FORMAT.format(100 * valueMap
.get(StrifeAttribute.EVASION)) + ChatColor.GRAY + " (" + REDUCER_FORMAT.format(evasion) + "%)" );
}
if (valueMap.get(StrifeAttribute.RESISTANCE) > 0) {
lore.add(
ChatColor.BLUE + "Resistance: " + ChatColor.WHITE + DECIMAL_FORMAT.format(100*valueMap.get(StrifeAttribute.RESISTANCE)) + "%");
}
itemMeta.setLore(lore);
itemStack.setItemMeta(itemMeta);
return itemStack;
}
@Override
public void onItemClick(ItemClickEvent event) {
super.onItemClick(event);
}
} |
package com.promenadevt;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.sql.Date;
import java.util.concurrent.ExecutionException;
import org.apache.commons.io.IOUtils;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.OpenableColumns;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ViewSwitcher;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.DeleteObjectRequest;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.ResponseHeaderOverrides;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectInputStream;
import com.promenadevt.android.R;
import com.promenadevt.library.Constants;
import com.promenadevt.library.UserFunctions;
public class EditActivity extends Activity
{
EditText inputName;
Button btnChangeName;
Button btnTakePhoto;
Button btnAddConnection;
Button btnViewRoom;
Button btnDelete;
Button btnDeleteYes;
Button btnDeleteNo;
ViewSwitcher switcher;
ImageView roomImage;
UserFunctions userFunctions;
private static String username;
private static String roomName;
private static String dbID;
private static String propID;
private static String addr;
private static String roomURL;
int CAMERA_PIC_REQUEST = 1337;
private static final int PHOTO_SELECTED = 1;
Constants Constants;
private AmazonS3Client s3Client = new AmazonS3Client(
new BasicAWSCredentials(Constants.ACCESS_KEY_ID,
Constants.SECRET_KEY));
/*Intent res = new Intent();
String mPackage = "com.google.android.gallery3d";
String mClass = "com.google.android.apps.lightcycle.ProtectedPanoramaCaptureActivity";
res.setComponent(new ComponentName(mPackage,mClass));
startActivityForResult(res,CAMERA_PIC_REQUEST);
}*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if( requestCode == CAMERA_PIC_REQUEST){
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
roomImage.setImageBitmap(thumbnail);
}
else if(requestCode == PHOTO_SELECTED){
if (resultCode == RESULT_OK) {
Uri selectedImage = data.getData();
//Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
roomImage.setImageURI(selectedImage);
new S3PutObjectTask().execute(selectedImage);
userFunctions.changeURL(dbID, "https://s3-us-west-2.amazonaws.com/promenadevt-1/room"+dbID);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK ) {
// do something on back.
//DatabaseHandler db = new DatabaseHandler(getApplicationContext());
Intent rooms = new Intent(getApplicationContext(), RoomsActivity.class);
//HashMap<String, String> loginInfo = db.getUserDetails();
rooms.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
rooms.putExtra("user", username);
rooms.putExtra("id",propID);
rooms.putExtra("addr", addr);
startActivity(rooms);
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_room);
s3Client.setRegion(Region.getRegion(Regions.US_WEST_2));
//new S3GeneratePresignedUrlTask().execute();
// may need to account for newly registered user here
Intent intent = getIntent();
// pull info from previous page
username = intent.getStringExtra("user");
roomName = intent.getStringExtra("name");
propID = intent.getStringExtra("propID");
addr = intent.getStringExtra("addr");
inputName = (EditText) findViewById(R.id.nameRoom);
inputName.setText(roomName);
dbID = intent.getStringExtra("id");
roomURL = "https://s3-us-west-2.amazonaws.com/promenadevt-1/room"+dbID;
Constants = new Constants(propID,dbID);
btnChangeName = (Button) findViewById(R.id.btnUpdateR);
btnTakePhoto = (Button) findViewById(R.id.btnPhoto);
btnAddConnection = (Button) findViewById(R.id.btnConnection);
btnViewRoom = (Button) findViewById(R.id.btnView);
btnDelete = (Button) findViewById(R.id.btnDelete);
btnDeleteYes = (Button) findViewById(R.id.btnDeleteRoomYes);
btnDeleteNo = (Button) findViewById(R.id.btnDeleteRoomNo);
switcher = (ViewSwitcher) findViewById(R.id.editRoomsSwitch);
roomImage =(ImageView) findViewById(R.id.PhotoCaptured);
userFunctions = new UserFunctions();
if(roomURL != null){
try {
Bitmap bitmap = new S3GetObjectTask().execute().get();
roomImage.setImageBitmap(bitmap);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
btnChangeName.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View arg0) {
// change room name in database
UserFunctions userFunction = new UserFunctions();
String newName = inputName.getText().toString();
userFunction.renameRoom(dbID,newName);
}
});
btnTakePhoto.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View arg0) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT); |
package io.github.cloudiator.rest.model;
import java.util.Objects;
import io.swagger.annotations.ApiModel;
import javax.validation.Valid;
import javax.validation.constraints.*;
/**
* Platzhalter
*/
@ApiModel(description = "Platzhalter")
public class LoginCredential {
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
return true;
}
@Override
public int hashCode() {
return Objects.hash();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class LoginCredential {\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
} |
package io.github.elytra.copo.tile;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import com.google.common.base.Objects;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Lists;
import com.google.common.collect.Multiset;
import com.google.common.collect.Sets;
import com.google.common.primitives.Ints;
import cofh.api.energy.IEnergyReceiver;
import gnu.trove.set.hash.TCustomHashSet;
import gnu.trove.strategy.HashingStrategy;
import io.github.elytra.copo.CoPo;
import io.github.elytra.copo.block.BlockController;
import io.github.elytra.copo.block.BlockController.State;
import io.github.elytra.copo.helper.DriveComparator;
import io.github.elytra.copo.item.ItemDrive;
import io.github.elytra.copo.item.ItemMemory;
import io.github.elytra.copo.storage.IDigitalStorage;
import net.darkhax.tesla.api.ITeslaConsumer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ITickable;
import net.minecraft.util.math.BlockPos;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.energy.CapabilityEnergy;
import net.minecraftforge.energy.IEnergyStorage;
import net.minecraftforge.fml.common.Optional;
@Optional.Interface(iface="cofh.api.energy.IEnergyReceiver",modid="CoFHAPI|energy")
public class TileEntityController extends TileEntityNetworkMember implements IEnergyReceiver, ITickable, IDigitalStorage, IEnergyStorage {
public boolean error = false;
public boolean booting = true;
public String errorReason;
private long consumedPerTick = CoPo.inst.controllerRfUsage;
private long energyCapacity = CoPo.inst.controllerCapacity;
public int bootTicks = 0;
private int totalScanned = 0;
private transient Set<BlockPos> networkMemberLocations = Sets.newHashSet();
private transient List<TileEntityInterface> interfaces = Lists.newArrayList();
private transient List<TileEntityWirelessReceiver> receivers = Lists.newArrayList();
private transient List<TileEntityDriveBay> driveBays = Lists.newArrayList();
private transient List<TileEntityMemoryBay> memoryBays = Lists.newArrayList();
private transient List<ItemStack> drives = Lists.newArrayList();
private transient Set<ItemStack> prototypes;
private transient Multiset<Class<? extends TileEntityNetworkMember>> memberTypes = HashMultiset.create(7);
public int changeId = 0;
private boolean checkingInfiniteLoop = false;
private long maxMemory = 0;
// Measured in Teslas, also accepts RF and CapabilityEnergy
private long energy;
public TileEntityController() {
prototypes = new TCustomHashSet<>(new HashingStrategy<ItemStack>() {
private static final long serialVersionUID = 7782704091709458883L;
@Override
public int computeHashCode(ItemStack is) {
// intentionally excludes quantity
// excludes capabilities, due to there being no good way to get
// a capability hashcode - it'll have to collide and get
// resolved in equals. oh well.
if (is == null) return 0;
int res = 1;
if (is.hasTagCompound()) {
res = (31 * res) + is.getTagCompound().hashCode();
} else {
res *= 31;
}
res = (31 * res) + is.getItem().hashCode();
res = (31 * res) + is.getMetadata();
return res;
}
@Override
public boolean equals(ItemStack o1, ItemStack o2) {
// also intentionally excludes quantity
if (o1 == o2) return true;
if (o1 == null || o2 == null) return false;
if (o1.hasTagCompound() != o2.hasTagCompound()) return false;
if (o1.getItem() != o2.getItem()) return false;
if (o1.getMetadata() != o2.getMetadata()) return false;
if (!Objects.equal(o1.getTagCompound(), o2.getTagCompound())) return false;
if (!o1.areCapsCompatible(o2)) return false;
return true;
}
});
}
@Override
public void readFromNBT(NBTTagCompound compound) {
super.readFromNBT(compound);
energy = compound.getLong("Energy");
if (energy > energyCapacity) energy = energyCapacity;
}
@Override
public NBTTagCompound writeToNBT(NBTTagCompound compound) {
super.writeToNBT(compound);
compound.setLong("Energy", energy);
return compound;
}
@Override
public boolean canConnectEnergy(EnumFacing from) {
return true;
}
@Override
public void update() {
if (!hasWorldObj() || getWorld().isRemote) return;
if (bootTicks > 100 && booting) {
/*
* The booting delay is meant to deal with people avoiding the
* system's passive power drain by just shutting it off when it's
* not in use. Without this, I'd expect a common setup to be hooking
* up some sort of RF toggle to a pressure plate, so the system is
* only online when someone is actively using it. This makes such a
* minmax setup inconvenient.
*/
booting = false;
scanNetwork();
}
if (isPowered()) {
modifyEnergyStored(-getEnergyConsumedPerTick());
bootTicks++;
} else {
energy = 0;
}
if (getTotalUsedMemory() > maxMemory) {
error = true;
errorReason = "out_of_memory";
} else if ("out_of_memory".equals(errorReason)) {
error = false;
errorReason = null;
bootTicks = 0;
booting = true;
}
updateState();
}
@Override
public long getEnergyConsumedPerTick() {
return consumedPerTick;
}
@Override
public boolean hasStorage() {
return true;
}
@Override
public TileEntityController getStorage() {
return this;
}
@Override
public void setController(TileEntityController controller) {}
public void scanNetwork() {
if (!hasWorldObj()) return;
if (worldObj.isRemote) return;
if (booting) return;
Set<BlockPos> seen = Sets.newHashSet();
List<TileEntityNetworkMember> members = Lists.newArrayList();
List<BlockPos> queue = Lists.newArrayList(getPos());
boolean foundOtherController = false;
for (BlockPos pos : networkMemberLocations) {
TileEntity te = worldObj.getTileEntity(pos);
if (te instanceof TileEntityNetworkMember) {
((TileEntityNetworkMember)te).setController(null);
}
}
totalScanned = 0;
networkMemberLocations.clear();
driveBays.clear();
memoryBays.clear();
receivers.clear();
interfaces.clear();
prototypes.clear();
int itr = 0;
while (!queue.isEmpty()) {
if (itr > 100) {
error = true;
errorReason = "network_too_big";
consumedPerTick = CoPo.inst.controllerErrorUsage_NetworkTooBig;
return;
}
BlockPos pos = queue.remove(0);
seen.add(pos);
TileEntity te = getWorld().getTileEntity(pos);
if (te instanceof TileEntityNetworkMember) {
for (EnumFacing ef : EnumFacing.VALUES) {
BlockPos p = pos.offset(ef);
if (seen.contains(p)) continue;
seen.add(p);
if (worldObj.getTileEntity(p) == null) {
continue;
}
queue.add(p);
}
if (te != this) {
if (te instanceof TileEntityController) {
error = true;
((TileEntityController) te).error = true;
CoPo.log.debug("Found other controller");
foundOtherController = true;
}
if (!members.contains(te)) {
TileEntityNetworkMember tenm = (TileEntityNetworkMember) te;
members.add(tenm);
if (te instanceof TileEntityDriveBay) {
driveBays.add((TileEntityDriveBay)te);
} else if (te instanceof TileEntityInterface) {
interfaces.add((TileEntityInterface)te);
} else if (te instanceof TileEntityWirelessReceiver) {
receivers.add((TileEntityWirelessReceiver)te);
} else if (te instanceof TileEntityMemoryBay) {
memoryBays.add((TileEntityMemoryBay)te);
}
networkMemberLocations.add(pos);
memberTypes.add(tenm.getClass());
consumedPerTick += tenm.getEnergyConsumedPerTick();
}
}
}
itr++;
}
if (foundOtherController) {
error = true;
errorReason = "multiple_controllers";
consumedPerTick = CoPo.inst.controllerErrorUsage_MultipleControllers;
} else {
error = false;
errorReason = null;
}
checkInfiniteLoop();
for (TileEntityNetworkMember te : members) {
te.setController(this);
}
totalScanned = itr;
long energyUsage = CoPo.inst.controllerRfUsage;
for (TileEntityNetworkMember tenm : members) {
energyUsage += tenm.getEnergyConsumedPerTick();
}
consumedPerTick = energyUsage;
if (consumedPerTick > CoPo.inst.controllerCap) {
error = true;
errorReason = "too_much_power";
}
updateDrivesCache();
updateMemoryCache();
booting = false;
CoPo.log.debug("Found "+members.size()+" network members");
}
public void checkInfiniteLoop() {
checkingInfiniteLoop = true;
for (TileEntityWirelessReceiver r : receivers) {
TileEntityController cont = r.getTransmitterController();
if (cont != null && cont.isLinkedTo(this, 0)) {
error = true;
errorReason = "infinite_loop";
receivers.clear();
checkingInfiniteLoop = false;
return;
}
}
if (error && "infinite_loop".equals(errorReason)) {
error = false;
errorReason = null;
}
checkingInfiniteLoop = false;
}
public boolean isCheckingInfiniteLoop() {
return checkingInfiniteLoop;
}
public boolean isLinkedTo(TileEntityController tec, int depth) {
// bail out now in case our infinite loop checking is causing infinite recursion
if (depth > 50) return true;
if (tec.equals(this)) return true;
for (TileEntityWirelessReceiver r : receivers) {
TileEntityController cont = r.getTransmitterController();
if (cont != null && cont.isLinkedTo(tec, depth + 1)) {
return true;
}
}
return false;
}
private void updateState() {
if (!hasWorldObj()) return;
if (worldObj.isRemote) return;
State old = worldObj.getBlockState(getPos()).getValue(BlockController.state);
State nw;
if (isPowered()) {
if (old == State.OFF) {
booting = true;
bootTicks = -200;
}
if (booting) {
nw = State.BOOTING;
} else if (error) {
nw = State.ERROR;
} else {
nw = State.POWERED;
}
} else {
nw = State.OFF;
}
if (old != nw) {
worldObj.setBlockState(getPos(), worldObj.getBlockState(getPos())
.withProperty(BlockController.state, nw));
}
}
@Override
public boolean isPowered() {
return energy >= getEnergyConsumedPerTick();
}
/** assumes the network cache is also up to date, if it's not, call scanNetwork */
public void updateDrivesCache() {
if (hasWorldObj() && worldObj.isRemote) return;
drives.clear();
prototypes.clear();
for (TileEntityDriveBay tedb : driveBays) {
if (tedb.isInvalid()) continue;
for (ItemStack is : tedb) {
drives.add(is);
ItemDrive id = (ItemDrive)is.getItem();
prototypes.addAll(id.getPrototypes(is));
}
}
Collections.sort(drives, new DriveComparator());
}
public void updateMemoryCache() {
if (!hasWorldObj() || worldObj.isRemote) return;
maxMemory = 0;
for (TileEntityMemoryBay temb : memoryBays) {
if (temb.isInvalid()) continue;
for (int i = 0; i < 12; i++) {
if (temb.hasMemoryInSlot(i)) {
ItemStack stack = temb.getMemoryInSlot(i);
if (stack.getItem() instanceof ItemMemory) {
maxMemory += ((ItemMemory)stack.getItem()).getMaxBits(stack);
}
}
}
}
bootTicks = 0;
booting = true;
}
public void updateConsumptionRate(long change) {
consumedPerTick += change;
if (consumedPerTick > CoPo.inst.controllerCap) {
error = true;
errorReason = "too_much_power";
} else {
if (error && "too_much_power".equals(errorReason)) {
error = false;
errorReason = null;
}
}
}
@Override
public ItemStack addItemToNetwork(ItemStack stack) {
if (error) return stack;
if (stack == null) return null;
if (!prototypes.contains(stack) && getTotalUsedMemory()+getMemoryUsage(stack) > getMaxMemory()) {
return stack;
}
for (ItemStack drive : drives) {
// both these conditions should always be true, but might as well be safe
if (drive != null && drive.getItem() instanceof ItemDrive) {
int oldSize = stack.stackSize;
ItemDrive itemDrive = ((ItemDrive)drive.getItem());
itemDrive.addItem(drive, stack);
if (stack.stackSize < oldSize && !prototypes.contains(stack)) {
prototypes.add(stack.copy());
}
if (stack.stackSize <= 0) break;
}
}
for (TileEntityWirelessReceiver r : receivers) {
TileEntityController cont = r.getTransmitterController();
if (cont != null) {
cont.addItemToNetwork(stack);
}
if (stack.stackSize <= 0) break;
}
changeId++;
return stack.stackSize <= 0 ? null : stack;
}
@Override
public ItemStack removeItemsFromNetwork(ItemStack prototype, int amount, boolean checkInterfaces) {
if (error) return null;
if (prototype == null) return null;
ItemStack stack = prototype.copy();
stack.stackSize = 0;
if (checkInterfaces) {
for (TileEntityInterface in : interfaces) {
for (int i = 9; i <= 17; i++) {
ItemStack is = in.getStackInSlot(i);
if (is != null && ItemStack.areItemsEqual(is, prototype) && ItemStack.areItemStackTagsEqual(is, prototype)) {
int amountWanted = amount-stack.stackSize;
int amountTaken = Math.min(is.stackSize, amountWanted);
is.stackSize -= amountTaken;
stack.stackSize += amountTaken;
if (is.stackSize <= 0) {
in.setInventorySlotContents(i, null);
}
if (stack.stackSize >= amount) break;
}
}
}
}
boolean anyDriveStillHasItem = false;
for (ItemStack drive : drives) {
// both these conditions should always be true, but might as well be safe
if (drive != null && drive.getItem() instanceof ItemDrive) {
ItemDrive itemDrive = ((ItemDrive)drive.getItem());
int amountWanted = amount-stack.stackSize;
itemDrive.removeItems(drive, stack, amountWanted);
if (!anyDriveStillHasItem && itemDrive.getAmountStored(drive, stack) > 0) {
anyDriveStillHasItem = true;
}
if (stack.stackSize >= amount) break;
}
}
for (TileEntityWirelessReceiver r : receivers) {
TileEntityController cont = r.getTransmitterController();
if (cont != null) {
ItemStack remote = cont.removeItemsFromNetwork(prototype, amount-stack.stackSize, checkInterfaces);
if (remote != null) {
stack.stackSize += remote.stackSize;
}
}
if (stack.stackSize >= amount) break;
}
if (!anyDriveStillHasItem) {
prototypes.remove(prototype);
}
changeId++;
return stack.stackSize <= 0 ? null : stack;
}
@Override
public int getKilobitsStorageFree() {
int accum = 0;
for (ItemStack drive : drives) {
if (drive != null && drive.getItem() instanceof ItemDrive) {
accum += ((ItemDrive)drive.getItem()).getKilobitsFree(drive);
}
}
return accum;
}
private long getMemoryUsage(ItemStack is) {
return (8L + ItemDrive.getNBTComplexity(is.getTagCompound()));
}
public long getUsedTypeMemory() {
long count = 0;
for (ItemStack is : prototypes) {
count += getMemoryUsage(is);
}
return count;
}
public long getUsedNetworkMemory() {
return totalScanned * 6L;
}
public long getUsedWirelessMemory() {
return (memberTypes.count(TileEntityWirelessReceiver.class) * 16L) + (memberTypes.count(TileEntityWirelessTransmitter.class) * 32L);
}
public long getTotalUsedMemory() {
return getUsedTypeMemory()+getUsedNetworkMemory()+getUsedWirelessMemory();
}
public long getBitsMemoryFree() {
return getMaxMemory()-getTotalUsedMemory();
}
public long getMaxMemory() {
return maxMemory;
}
@Override
public List<ItemStack> getTypes() {
List<ItemStack> li = Lists.newArrayList();
for (ItemStack drive : drives) {
if (drive != null && drive.getItem() instanceof ItemDrive) {
li.addAll(((ItemDrive)drive.getItem()).getTypes(drive));
}
}
for (TileEntityInterface in : interfaces) {
for (int i = 9; i <= 17; i++) {
ItemStack ifaceStack = in.getStackInSlot(i);
if (ifaceStack != null) {
boolean added = false;
for (ItemStack cur : li) {
if (ItemStack.areItemsEqual(ifaceStack, cur) && ItemStack.areItemStackTagsEqual(ifaceStack, cur)) {
cur.stackSize += ifaceStack.stackSize;
added = true;
break;
}
}
if (!added) {
li.add(ifaceStack.copy());
}
}
}
}
for (TileEntityWirelessReceiver r : receivers) {
TileEntityController cont = r.getTransmitterController();
if (cont != null) {
li.addAll(cont.getTypes());
}
}
return li;
}
public void onNetworkPatched(TileEntityNetworkMember tenm) {
if (totalScanned == 0) return;
if (tenm instanceof TileEntityDriveBay) {
if (!driveBays.contains(tenm)) {
driveBays.add((TileEntityDriveBay)tenm);
updateDrivesCache();
changeId++;
}
} else if (tenm instanceof TileEntityInterface) {
if (!interfaces.contains(tenm)) {
interfaces.add((TileEntityInterface)tenm);
changeId++;
}
} else if (tenm instanceof TileEntityWirelessReceiver) {
if (!receivers.contains(tenm)) {
receivers.add((TileEntityWirelessReceiver)tenm);
checkInfiniteLoop();
changeId++;
}
} else if (tenm instanceof TileEntityMemoryBay) {
if (!memoryBays.contains(tenm)) {
memoryBays.add((TileEntityMemoryBay)tenm);
updateMemoryCache();
changeId++;
}
}
if (networkMemberLocations.add(tenm.getPos())) {
totalScanned++;
if (totalScanned > 100) {
error = true;
errorReason = "network_too_big";
consumedPerTick = CoPo.inst.controllerErrorUsage_NetworkTooBig;
}
}
}
public boolean knowsOfMemberAt(BlockPos pos) {
return networkMemberLocations.contains(pos);
}
@Override
public int getChangeId() {
return changeId;
}
public void modifyEnergyStored(long energy) {
this.energy += energy;
if (this.energy > energyCapacity) {
this.energy = energyCapacity;
} else if (this.energy < 0) {
this.energy = 0;
}
}
public long receiveEnergy(long maxReceive, boolean simulate) {
long energyReceived = Math.min(energyCapacity - energy,
Math.min(CoPo.inst.controllerCap+1, maxReceive));
if (!simulate) {
energy += energyReceived;
}
return energyReceived;
}
@Override
public int getEnergyStored(EnumFacing from) {
return Ints.saturatedCast(energy);
}
@Override
public int getMaxEnergyStored(EnumFacing from) {
return Ints.saturatedCast(energyCapacity);
}
@Override
public int receiveEnergy(EnumFacing from, int maxReceive, boolean simulate) {
return Ints.saturatedCast(receiveEnergy(maxReceive, simulate));
}
@Override
public int receiveEnergy(int maxReceive, boolean simulate) {
return Ints.saturatedCast(receiveEnergy((long)maxReceive, simulate));
}
@Override
public int extractEnergy(int maxExtract, boolean simulate) {
return 0;
}
@Override
public int getEnergyStored() {
return Ints.saturatedCast(energy);
}
@Override
public int getMaxEnergyStored() {
return Ints.saturatedCast(energyCapacity);
}
@Override
public boolean canExtract() {
return false;
}
@Override
public boolean canReceive() {
return true;
}
private Object teslaConsumer;
@Override
public <T> T getCapability(Capability<T> capability, EnumFacing facing) {
if (capability == null) return null;
if (capability == CapabilityEnergy.ENERGY) {
return (T)this;
} else if (capability == CoPo.TESLA_CONSUMER) {
if (teslaConsumer == null) {
teslaConsumer = new TeslaConsumer();
}
return (T)teslaConsumer;
}
return super.getCapability(capability, facing);
}
@Override
public boolean hasCapability(Capability<?> capability, EnumFacing facing) {
if (capability == null) return false;
if (capability == CapabilityEnergy.ENERGY) {
return true;
} else if (capability == CoPo.TESLA_CONSUMER) {
return true;
}
return super.hasCapability(capability, facing);
}
public class TeslaConsumer implements ITeslaConsumer {
@Override
public long givePower(long power, boolean simulated) {
return receiveEnergy(power, simulated);
}
}
} |
package mcjty.rftools.dimension;
import mcjty.rftools.RFTools;
import mcjty.rftools.dimension.description.DimensionDescriptor;
import mcjty.rftools.dimension.network.PacketCheckDimletConfig;
import mcjty.rftools.dimension.network.PacketSyncDimensionInfo;
import mcjty.rftools.dimension.world.GenericWorldProvider;
import mcjty.rftools.items.dimlets.DimletKey;
import mcjty.rftools.items.dimlets.DimletMapping;
import mcjty.rftools.items.dimlets.KnownDimletConfiguration;
import mcjty.rftools.network.PacketHandler;
import mcjty.rftools.network.PacketRegisterDimensions;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.World;
import net.minecraft.world.WorldSavedData;
import net.minecraft.world.WorldServer;
import net.minecraft.world.gen.ChunkProviderServer;
import net.minecraftforge.common.DimensionManager;
import net.minecraftforge.common.util.Constants;
import java.util.*;
public class RfToolsDimensionManager extends WorldSavedData {
public static final String DIMMANAGER_NAME = "RFToolsDimensionManager";
private static RfToolsDimensionManager instance = null;
private final Map<Integer, DimensionDescriptor> dimensions = new HashMap<Integer, DimensionDescriptor>();
private final Map<DimensionDescriptor, Integer> dimensionToID = new HashMap<DimensionDescriptor, Integer>();
private final Map<Integer, DimensionInformation> dimensionInformation = new HashMap<Integer, DimensionInformation>();
private final Set<Integer> reclaimedIds = new HashSet<Integer>();
public void syncFromServer(Map<Integer, DimensionDescriptor> dims, Map<Integer, DimensionInformation> dimInfo) {
RFTools.log("RfToolsDimensionManager.syncFromServer");
if (dims.isEmpty() || dimInfo.isEmpty()) {
RFTools.log("Dimension information from server is empty.");
}
for (Map.Entry<Integer, DimensionDescriptor> entry : dims.entrySet()) {
int id = entry.getKey();
DimensionDescriptor descriptor = entry.getValue();
if (dimensions.containsKey(id)) {
dimensionToID.remove(dimensions.get(id));
}
dimensions.put(id, descriptor);
dimensionToID.put(descriptor, id);
}
for (Map.Entry<Integer, DimensionInformation> entry : dimInfo.entrySet()) {
int id = entry.getKey();
DimensionInformation info = entry.getValue();
dimensionInformation.put(id, info);
}
}
public RfToolsDimensionManager(String identifier) {
super(identifier);
}
public static void clearInstance() {
if (instance != null) {
instance.dimensions.clear();
instance.dimensionToID.clear();
instance.dimensionInformation.clear();
instance.reclaimedIds.clear();
instance = null;
}
}
public static void cleanupDimensionInformation() {
if (instance != null) {
RFTools.log("Cleaning up RFTools dimensions");
unregisterDimensions();
instance.getDimensions().clear();
instance.dimensionToID.clear();
instance.dimensionInformation.clear();
instance.reclaimedIds.clear();
instance = null;
}
}
public static void unregisterDimensions() {
for (Map.Entry<Integer, DimensionDescriptor> me : instance.getDimensions().entrySet()) {
int id = me.getKey();
if (DimensionManager.isDimensionRegistered(id)) {
RFTools.log(" Unregister dimension: " + id);
try {
DimensionManager.unregisterDimension(id);
} catch (Exception e) {
// We ignore this error.
RFTools.log(" Could not unregister dimension: " + id);
}
try {
DimensionManager.unregisterProviderType(id);
} catch (Exception e) {
// We ignore this error.
RFTools.log(" Could not unregister provider: " + id);
}
} else {
RFTools.log(" Already unregistered! Dimension: " + id);
}
}
}
public void save(World world) {
world.mapStorage.setData(DIMMANAGER_NAME, this);
markDirty();
syncDimInfoToClients(world);
}
public void reclaimId(int id) {
reclaimedIds.add(id);
}
/**
* Check if the client dimlet id's match with the server.
* This is executed on the server to the clients.
*/
public void checkDimletConfig(EntityPlayer player) {
if (!player.getEntityWorld().isRemote) {
// Send over dimlet configuration to the client so that the client can check that the id's match.
RFTools.log("Send validation data to the client");
DimletMapping mapping = DimletMapping.getDimletMapping(player.getEntityWorld());
Map<Integer, DimletKey> dimlets = new HashMap<Integer, DimletKey>();
for (Integer id : mapping.getIds()) {
dimlets.put(id, mapping.getKey(id));
}
PacketHandler.INSTANCE.sendTo(new PacketCheckDimletConfig(dimlets), (EntityPlayerMP) player);
}
}
/**
* Here the information from the server arrives. This code is executed on the client.
*/
public void checkDimletConfigFromServer(Map<Integer, DimletKey> dimlets, World world) {
RFTools.log("Getting dimlet mapping from server");
DimletMapping mapping = DimletMapping.getDimletMapping(world);
mapping.overrideServerMapping(dimlets);
KnownDimletConfiguration.init(world, false);
KnownDimletConfiguration.initCrafting(world);
}
public void syncDimInfoToClients(World world) {
if (!world.isRemote) {
// Sync to clients.
RFTools.log("Sync dimension info to clients!");
PacketHandler.INSTANCE.sendToAll(new PacketSyncDimensionInfo(dimensions, dimensionInformation));
}
}
public Map<Integer, DimensionDescriptor> getDimensions() {
return dimensions;
}
public void registerDimensions() {
RFTools.log("Registering RFTools dimensions");
for (Map.Entry<Integer, DimensionDescriptor> me : dimensions.entrySet()) {
int id = me.getKey();
RFTools.log(" Dimension: " + id);
registerDimensionToServerAndClient(id);
}
}
private void registerDimensionToServerAndClient(int id) {
DimensionManager.registerProviderType(id, GenericWorldProvider.class, false);
DimensionManager.registerDimension(id, id);
PacketHandler.INSTANCE.sendToAll(new PacketRegisterDimensions(id));
}
public static RfToolsDimensionManager getDimensionManager(World world) {
if (instance != null) {
return instance;
}
instance = (RfToolsDimensionManager) world.mapStorage.loadData(RfToolsDimensionManager.class, DIMMANAGER_NAME);
if (instance == null) {
instance = new RfToolsDimensionManager(DIMMANAGER_NAME);
}
return instance;
}
public DimensionDescriptor getDimensionDescriptor(int id) {
return dimensions.get(id);
}
public Integer getDimensionID(DimensionDescriptor descriptor) {
return dimensionToID.get(descriptor);
}
public DimensionInformation getDimensionInformation(int id) {
return dimensionInformation.get(id);
}
/**
* Get a world for a dimension, possibly loading it from the configuration manager.
*/
public static World getWorldForDimension(int id) {
World w = DimensionManager.getWorld(id);
if (w == null) {
w = MinecraftServer.getServer().getConfigurationManager().getServerInstance().worldServerForDimension(id);
}
return w;
}
public void removeDimension(int id) {
DimensionDescriptor descriptor = dimensions.get(id);
dimensions.remove(id);
dimensionToID.remove(descriptor);
dimensionInformation.remove(id);
if (DimensionManager.isDimensionRegistered(id)) {
DimensionManager.unregisterDimension(id);
}
DimensionManager.unregisterProviderType(id);
}
public void recoverDimension(World world, int id, DimensionDescriptor descriptor, String name) {
if (!DimensionManager.isDimensionRegistered(id)) {
registerDimensionToServerAndClient(id);
}
DimensionInformation dimensionInfo = new DimensionInformation(name, descriptor, world);
dimensions.put(id, descriptor);
dimensionToID.put(descriptor, id);
dimensionInformation.put(id, dimensionInfo);
save(world);
touchSpawnChunk(id);
}
public int createNewDimension(World world, DimensionDescriptor descriptor, String name) {
int id = 0;
while (!reclaimedIds.isEmpty()) {
int rid = reclaimedIds.iterator().next();
reclaimedIds.remove(rid);
if (!DimensionManager.isDimensionRegistered(rid)) {
id = rid;
break;
}
}
if (id == 0) {
id = DimensionManager.getNextFreeDimId();
}
registerDimensionToServerAndClient(id);
RFTools.log("id = " + id + " for " + name + ", descriptor = " + descriptor.getDescriptionString());
dimensions.put(id, descriptor);
dimensionToID.put(descriptor, id);
DimensionInformation dimensionInfo = new DimensionInformation(name, descriptor, world);
dimensionInformation.put(id, dimensionInfo);
save(world);
touchSpawnChunk(id);
return id;
}
private void touchSpawnChunk(int id) {
// Make sure world generation kicks in for at least one chunk so that our matter receiver
// is generated and registered.
WorldServer worldServerForDimension = MinecraftServer.getServer().worldServerForDimension(id);
ChunkProviderServer providerServer = worldServerForDimension.theChunkProviderServer;
if (!providerServer.chunkExists(0, 0)) {
try {
providerServer.loadChunk(0, 0);
providerServer.populate(providerServer, 0, 0);
providerServer.unloadChunksIfNotNearSpawn(0, 0);
} catch (Exception e) {
RFTools.logError("Something went wrong during creation of the dimension!");
e.printStackTrace();
// We catch this exception to make sure our dimension tab is at least ok.
}
}
}
@Override
public void readFromNBT(NBTTagCompound tagCompound) {
dimensions.clear();
dimensionToID.clear();
dimensionInformation.clear();
reclaimedIds.clear();
NBTTagList lst = tagCompound.getTagList("dimensions", Constants.NBT.TAG_COMPOUND);
for (int i = 0 ; i < lst.tagCount() ; i++) {
NBTTagCompound tc = lst.getCompoundTagAt(i);
int id = tc.getInteger("id");
DimensionDescriptor descriptor = new DimensionDescriptor(tc);
dimensions.put(id, descriptor);
dimensionToID.put(descriptor, id);
DimensionInformation dimensionInfo = new DimensionInformation(descriptor, tc);
dimensionInformation.put(id, dimensionInfo);
}
int[] lstIds = tagCompound.getIntArray("reclaimedIds");
for (int id : lstIds) {
reclaimedIds.add(id);
}
}
@Override
public void writeToNBT(NBTTagCompound tagCompound) {
NBTTagList lst = new NBTTagList();
for (Map.Entry<Integer,DimensionDescriptor> me : dimensions.entrySet()) {
NBTTagCompound tc = new NBTTagCompound();
Integer id = me.getKey();
tc.setInteger("id", id);
me.getValue().writeToNBT(tc);
DimensionInformation dimensionInfo = dimensionInformation.get(id);
dimensionInfo.writeToNBT(tc);
lst.appendTag(tc);
}
tagCompound.setTag("dimensions", lst);
List<Integer> ids = new ArrayList<Integer>(reclaimedIds);
int[] lstIds = new int[ids.size()];
for (int i = 0 ; i < ids.size() ; i++) {
lstIds[i] = ids.get(i);
}
tagCompound.setIntArray("reclaimedIds", lstIds);
}
} |
package me.ferrybig.javacoding.teamspeakconnector;
/**
*
* @author Fernando
*/
public class Group extends UnresolvedGroup {
private final int icon;
private final boolean savedb;
private final String name;
private final int memberRemovePrivilege;
private final int memberAddPrivilege;
private final int modifyPrivilege;
private final int namemode;
private final Type type;
public Group(TeamspeakConnection con, int serverGroupId, int icon, boolean savedb, String name, int memberRemovePrivilege, int memberAddPrivilege, int modifyPrivilege, int namemode, Type type) {
super(con, serverGroupId);
this.icon = icon;
this.savedb = savedb;
this.name = name;
this.memberRemovePrivilege = memberRemovePrivilege;
this.memberAddPrivilege = memberAddPrivilege;
this.modifyPrivilege = modifyPrivilege;
this.namemode = namemode;
this.type = type;
}
@Override
public boolean isResolved() {
return true;
}
public int getIcon() {
return icon;
}
public boolean isSavedb() {
return savedb;
}
public String getName() {
return name;
}
public int getMemberRemovePrivilege() {
return memberRemovePrivilege;
}
public int getMemberAddPrivilege() {
return memberAddPrivilege;
}
public int getModifyPrivilege() {
return modifyPrivilege;
}
public int getNamemode() {
return namemode;
}
public Type getType() {
return type;
}
@Override
public String toString() {
return "Group{" + "serverGroupId=" + getServerGroupId() + ", icon=" + icon + ", savedb=" + savedb + ", name=" + name + ", memberRemovePrivilege=" + memberRemovePrivilege + ", memberAddPrivilege=" + memberAddPrivilege + ", modifyPrivilege=" + modifyPrivilege + ", namemode=" + namemode + ", type=" + type + '}';
}
public enum Type {
/**
* 0: template group (used for new virtual servers)
*/
TEMPLATE(0),
/**
* 1: regular group (used for regular clients)
*/
REGULAR(1),
/**
* 2: global query group (used for ServerQuery clients)
*/
SERVERQUERY(2);
private final int id;
private Type(int id) {
this.id = id;
}
public int getId() {
return id;
}
};
} |
package opensesim.gui.AssetEditor;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JDialog;
import javax.swing.JPanel;
import opensesim.AbstractAsset;
import opensesim.gui.Globals;
import opensesim.gui.util.JTextFieldLimit;
import opensesim.gui.util.Json.Export;
import opensesim.gui.util.Json.Import;
/**
*
* @author 7u83 <7u83@mail.ru>
*/
public class AssetEditorPanel extends javax.swing.JPanel {
ArrayList<Class<AbstractAsset>> asset_types;
/**
* Creates new form AssetEditor
*/
public AssetEditorPanel() {
super();
asset_types = Globals.getAvailableAssetsTypes(true);
initComponents();
symField.setLimit(Globals.MAX.SYMLEN);
nameField.setLimit(Globals.MAX.NAMELEN);
}
void initFields(AbstractAsset asset) {
if (asset == null) {
return;
}
symField.setText(asset.getSymbol());
nameField.setText(asset.getName());
decimalsField.getModel().setValue(asset.getDecimals());
}
public String getNameField() {
return nameField.getText();
}
public String getSymField() {
return symField.getText();
}
public void putType(String type) {
System.out.printf("Here we have a type: %s\n", type);
}
public JDialog dialog;
ComboBoxModel getComboBoxModel() {
ArrayList vector = new ArrayList();
int i;
for (i = 0; i < asset_types.size(); i++) {
AbstractAsset ait;
Class<AbstractAsset> asset_type = asset_types.get(i);
try {
ait = asset_type.newInstance();
vector.add(i, ait.getTypeName());
} catch (InstantiationException | IllegalAccessException | ClassCastException ex) {
Logger.getLogger(AssetEditorPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
return new DefaultComboBoxModel(vector.toArray());
}
/**
* 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() {
jLabel1 = new javax.swing.JLabel();
assetTypesComboBox = new javax.swing.JComboBox<>();
jLabel2 = new javax.swing.JLabel();
symField = new opensesim.gui.util.JTextFieldLimit();
jLabel3 = new javax.swing.JLabel();
nameField = new opensesim.gui.util.JTextFieldLimit();
jLabel4 = new javax.swing.JLabel();
decimalsField = new javax.swing.JSpinner();
guiPanel = new javax.swing.JPanel();
defaultGuiPanel = new javax.swing.JPanel();
jLabel1.setText("Symbol:");
assetTypesComboBox.setModel(getComboBoxModel());
assetTypesComboBox.setEnabled(false);
assetTypesComboBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
assetTypesComboBoxActionPerformed(evt);
}
});
jLabel2.setText("Type:");
symField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
symFieldActionPerformed(evt);
}
});
jLabel3.setText("Name:");
jLabel4.setText("Decimals:");
decimalsField.setModel(new javax.swing.SpinnerNumberModel(0, 0, 8, 1));
guiPanel.setLayout(new java.awt.BorderLayout());
defaultGuiPanel.setMinimumSize(new java.awt.Dimension(360, 25));
javax.swing.GroupLayout defaultGuiPanelLayout = new javax.swing.GroupLayout(defaultGuiPanel);
defaultGuiPanel.setLayout(defaultGuiPanelLayout);
defaultGuiPanelLayout.setHorizontalGroup(
defaultGuiPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 360, Short.MAX_VALUE)
);
defaultGuiPanelLayout.setVerticalGroup(
defaultGuiPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 25, Short.MAX_VALUE)
);
guiPanel.add(defaultGuiPanel, java.awt.BorderLayout.CENTER);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(guiPanel, 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(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 67, Short.MAX_VALUE))
.addGap(12, 12, 12)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(symField, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(assetTypesComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(nameField, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(decimalsField, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(assetTypesComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1)
.addComponent(symField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(nameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(decimalsField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(guiPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
}// </editor-fold>//GEN-END:initComponents
@Import("type")
public void setType(String type) {
Class<AbstractAsset> ac = (Class<AbstractAsset>) Globals.getClassByName(type);
if (ac == null) {
return;
}
AbstractAsset a;
try {
try {
a = ac.getConstructor().newInstance();
} catch (NoSuchMethodException | SecurityException ex) {
Logger.getLogger(AssetEditorPanel.class.getName()).log(Level.SEVERE, null, ex);
return;
}
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
Logger.getLogger(AssetEditorPanel.class.getName()).log(Level.SEVERE, null, ex);
return;
}
JPanel gui = a.getEditGui();
guiPanel.removeAll();
if (gui != null) {
guiPanel.add(gui, java.awt.BorderLayout.CENTER);
gui.setVisible(true);
} else {
guiPanel.add(defaultGuiPanel, java.awt.BorderLayout.CENTER);
}
for (int i = 0; i < asset_types.size(); i++) {
if (asset_types.get(i).getName().equals(type)) {
assetTypesComboBox.setSelectedIndex(i);
}
}
}
private void assetTypesComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_assetTypesComboBoxActionPerformed
int i = this.assetTypesComboBox.getSelectedIndex();
setType(asset_types.get(i).getName());
//this.pack();
revalidate();
repaint();
return;
}//GEN-LAST:event_assetTypesComboBoxActionPerformed
private void symFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_symFieldActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_symFieldActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
public javax.swing.JComboBox<String> assetTypesComboBox;
public javax.swing.JSpinner decimalsField;
private javax.swing.JPanel defaultGuiPanel;
private javax.swing.JPanel guiPanel;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
@Import("name")
@Export("name")
public opensesim.gui.util.JTextFieldLimit nameField;
@Export("symbol")
@Import("symbol")
public opensesim.gui.util.JTextFieldLimit symField;
// End of variables declaration//GEN-END:variables
} |
package me.zp4rker.discord.jitters.lstnr;
import me.zp4rker.discord.jitters.Jitters;
import me.zp4rker.discord.core.exception.ExceptionHandler;
import me.zp4rker.discord.jitters.util.JSONUtil;
import net.dv8tion.jda.core.EmbedBuilder;
import net.dv8tion.jda.core.entities.MessageEmbed;
import net.dv8tion.jda.core.entities.TextChannel;
import net.dv8tion.jda.core.entities.User;
import net.dv8tion.jda.core.events.message.guild.GuildMessageDeleteEvent;
import net.dv8tion.jda.core.hooks.SubscribeEvent;
import org.json.JSONArray;
import org.json.JSONObject;
import java.awt.*;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
/**
* @author ZP4RKER
*/
public class DeleteListener {
public static List<String> bypass = new ArrayList<>();
@SubscribeEvent
public void onDelete(GuildMessageDeleteEvent event) {
if (event.getChannel().getId().equals("314654582183821312")) return;
TextChannel channel = event.getChannel();
String id = event.getMessageId();
try {
JSONObject file = JSONUtil.readFile(MessageListener.getFile(channel));
JSONArray messagesArray = file.getJSONArray("messages");
int index = searchForMessage(messagesArray, id);
if (index < 0) return;
JSONObject data = messagesArray.getJSONObject(index);
if (!bypass.contains(event.getMessageId())) sendLog(data);
messagesArray.remove(index);
file.put("messages", messagesArray);
JSONUtil.writeFile(file.toString(2), MessageListener.getFile(channel));
} catch (Exception e) {
ExceptionHandler.handleException(e);
}
}
private int searchForMessage(JSONArray array, String id) {
for (int i = 0; i < array.length(); i++) {
if (array.getJSONObject(i).getString("id").equals(id)) return i;
}
return -1;
}
private void sendLog(JSONObject data) {
User user = Jitters.jda.getUserById(data.getString("author"));
if (user == null) return;
TextChannel channel = Jitters.jda.getTextChannelById(data.getString("channel"));
MessageEmbed embed = new EmbedBuilder()
.setAuthor(user.getName() + "#" + user.getDiscriminator(), null, user.getEffectiveAvatarUrl())
.setDescription("**Message from " + user.getAsMention() + " deleted in **" + channel.getAsMention()
+ "\n" + data.getString("content"))
.setFooter("ID: " + data.getString("id"), null)
.setTimestamp(Instant.now())
.setColor(new Color(240, 71, 71)).build();
Jitters.jda.getTextChannelById(314654582183821312L).sendMessage(embed).queue();
}
} |
package net.joelinn.quartz.jobstore;
import org.quartz.JobKey;
import org.quartz.TriggerKey;
import java.util.Arrays;
import java.util.List;
/**
* Joe Linn
* 7/14/2014
*/
public class RedisJobStoreSchema {
protected static final String DEFAULT_DELIMITER = ":";
protected static final String JOBS_SET = "jobs";
protected static final String JOB_GROUPS_SET = "job_groups";
protected static final String LOCK = "lock";
protected final String prefix;
protected final String delimiter;
public RedisJobStoreSchema(){
this("");
}
/**
* @param prefix the prefix to be prepended to all redis keys
*/
public RedisJobStoreSchema(String prefix){
this(prefix, DEFAULT_DELIMITER);
}
/**
* @param prefix the prefix to be prepended to all redis keys
* @param delimiter the delimiter to be used to separate key segments
*/
public RedisJobStoreSchema(String prefix, String delimiter) {
this.prefix = prefix;
this.delimiter = delimiter;
}
/**
*
* @return the redis key used for locking
*/
public String lockKey(){
return addPrefix(LOCK);
}
/**
* @return the redis key for the set containing all job keys
*/
public String jobsSet(){
return addPrefix(JOBS_SET);
}
/**
* @return the redis key for the set containing all job group keys
*/
public String jobGroupsSet(){
return addPrefix(JOB_GROUPS_SET);
}
/**
*
* @param jobKey
* @return the redis key associated with the given {@link org.quartz.JobKey}
*/
public String jobHashKey(final JobKey jobKey){
return addPrefix("job" + delimiter + jobKey.getGroup() + delimiter + jobKey.getName());
}
/**
*
* @param jobKey
* @return the redis key associated with the job data for the given {@link org.quartz.JobKey}
*/
public String jobDataMapHashKey(final JobKey jobKey){
return addPrefix("job_data_map" + delimiter + jobKey.getGroup() + delimiter + jobKey.getName());
}
/**
*
* @param jobKey
* @return the key associated with the group set for the given {@link org.quartz.JobKey}
*/
public String jobGroupSetKey(final JobKey jobKey){
return addPrefix("job_group" + delimiter + jobKey.getGroup());
}
/**
*
* @param jobHashKey the hash key for a job
* @return the {@link org.quartz.JobKey} object describing the job
*/
public JobKey jobKey(final String jobHashKey){
final List<String> hashParts = split(jobHashKey);
return new JobKey(hashParts.get(2), hashParts.get(1));
}
/**
*
* @param jobGroupSetKey the redis key for a job group set
* @return the name of the job group
*/
public String jobGroup(final String jobGroupSetKey){
return split(jobGroupSetKey).get(1);
}
/**
* @param jobKey the job key for which to get a trigger set key
* @return the key associated with the set of triggers for the given {@link org.quartz.JobKey}
*/
public String jobTriggersSetKey(final JobKey jobKey){
return addPrefix("job_triggers" + delimiter + jobKey.getGroup() + delimiter + jobKey.getName());
}
/**
* @return the key associated with the set of blocked jobs
*/
public String blockedJobsSet(){
return addPrefix("blocked_jobs");
}
/**
*
* @param triggerKey a trigger key
* @return the redis key associated with the given {@link org.quartz.TriggerKey}
*/
public String triggerHashKey(final TriggerKey triggerKey){
return addPrefix("trigger" + delimiter + triggerKey.getGroup() + delimiter + triggerKey.getName());
}
/**
*
* @param triggerHashKey the hash key for a trigger
* @return the {@link org.quartz.TriggerKey} object describing the desired trigger
*/
public TriggerKey triggerKey(final String triggerHashKey){
final List<String> hashParts = split(triggerHashKey);
return new TriggerKey(hashParts.get(2), hashParts.get(1));
}
/**
*
* @param triggerGroupSetKey the redis key for a trigger group set
* @return the name of the trigger group represented by the given redis key
*/
public String triggerGroup(final String triggerGroupSetKey){
return split(triggerGroupSetKey).get(1);
}
/**
* @param triggerKey a trigger key
* @return the redis key associated with the group of the given {@link org.quartz.TriggerKey}
*/
public String triggerGroupSetKey(final TriggerKey triggerKey){
return addPrefix("trigger_group" + delimiter + triggerKey.getGroup());
}
/**
* @return the key of the set containing all trigger keys
*/
public String triggersSet(){
return addPrefix("triggers");
}
/**
* @return the key of the set containing all trigger group keys
*/
public String triggerGroupsSet(){
return addPrefix("trigger_groups");
}
/**
* @return the key of the set containing paused trigger group keys
*/
public String pausedTriggerGroupsSet(){
return addPrefix("paused_trigger_groups");
}
/**
* @param state a {@link net.joelinn.quartz.jobstore.RedisTriggerState}
* @return the key of a set containing the keys of triggers which are in the given state
*/
public String triggerStateKey(final RedisTriggerState state){
return addPrefix(state.getKey());
}
/**
*
* @param triggerKey the key of the trigger for which to retrieve a lock key
* @return the redis key for the lock state of the given trigger
*/
public String triggerLockKey(final TriggerKey triggerKey){
return addPrefix("trigger_lock" + delimiter + triggerKey.getGroup() + delimiter + triggerKey.getName());
}
/**
*
* @param jobKey the key of the job for which to retrieve a block key
* @return the redis key for the blocked state of the given job
*/
public String jobBlockedKey(final JobKey jobKey){
return addPrefix("job_blocked" + delimiter + jobKey.getGroup() + delimiter + jobKey.getName());
}
/**
* @return the key which holds the time at which triggers were last released
*/
public String lastTriggerReleaseTime(){
return addPrefix("last_triggers_release_time");
}
/**
* @return the key of the set containing paused job groups
*/
public String pausedJobGroupsSet(){
return addPrefix("paused_job_groups");
}
/**
* @param calendarName the name of the calendar for which to retrieve a key
* @return the redis key for the set containing trigger keys for the given calendar name
*/
public String calendarTriggersSetKey(final String calendarName){
return addPrefix("calendar_triggers" + delimiter + calendarName);
}
/**
* @param calendarName the name of the calendar for which to retrieve a key
* @return the redis key for the calendar with the given name
*/
public String calendarHashKey(final String calendarName){
return addPrefix("calendar" + delimiter + calendarName);
}
/**
*
* @param calendarHashKey the redis key for a calendar
* @return the name of the calendar represented by the given key
*/
public String calendarName(final String calendarHashKey){
return split(calendarHashKey).get(1);
}
/**
* @return the key of the set containing all calendar keys
*/
public String calendarsSet(){
return addPrefix("calendars");
}
/**
* Add the configured prefix string to the given key
* @param key the key to which the prefix should be prepended
* @return a prefixed key
*/
protected String addPrefix(String key){
return prefix + key;
}
/**
* Split a string on the configured delimiter
* @param string the string to split
* @return a list comprised of the split parts of the given string
*/
protected List<String> split(final String string){
if (null!=prefix){
//remove prefix before split
return Arrays.asList(string.substring(prefix.length()).split(delimiter));
}else{
return Arrays.asList(string.split(delimiter));
}
}
} |
package net.openhft.chronicle.network2.event;
import net.openhft.lang.thread.LightPauser;
import static java.util.concurrent.TimeUnit.*;
import static net.openhft.chronicle.network2.event.References.or;
public class EventGroup implements EventLoop {
static final long MONITOR_INTERVAL = NANOSECONDS.convert(100, MILLISECONDS);
public static boolean IS_DEBUG = java.lang.management.ManagementFactory.getRuntimeMXBean().
getInputArguments().toString().indexOf("jdwp") >= 0;
final EventLoop monitor = new MonitorEventLoop(this, new LightPauser(LightPauser.NO_BUSY_PERIOD, NANOSECONDS.convert(1, SECONDS)));
final VanillaEventLoop core = new VanillaEventLoop(this, "core",
new LightPauser(NANOSECONDS.convert(20, MICROSECONDS), NANOSECONDS.convert(200, MICROSECONDS)),
NANOSECONDS.convert(100, MICROSECONDS));
final BlockingEventLoop blocking = new BlockingEventLoop(this, "blocking");
public void addHandler(EventHandler handler) {
switch (or(handler.priority(), HandlerPriority.BLOCKING)) {
case HIGH:
case MEDIUM:
case TIMER:
case DAEMON:
core.addHandler(handler);
break;
case MONITOR:
monitor.addHandler(handler);
break;
case BLOCKING:
blocking.addHandler(handler);
break;
default:
throw new IllegalArgumentException("Unknown priority " + handler.priority());
}
}
@Override
public void start() {
core.start();
monitor.start();
monitor.addHandler(new LoopBlockMonitor());
}
@Override
public void stop() {
monitor.stop();
core.stop();
}
class LoopBlockMonitor implements EventHandler {
long lastInterval = 1;
@Override
public boolean runOnce() {
long blockingTime = System.nanoTime() - core.loopStartNS();
long blockingInterval = blockingTime / (MONITOR_INTERVAL / 2);
if (blockingInterval > lastInterval && !IS_DEBUG) {
core.dumpRunningState(core.name() + " thread has blocked for " + MILLISECONDS.convert(blockingTime, NANOSECONDS) + " ms.");
} else {
lastInterval = Math.max(1, blockingInterval);
}
return false;
}
}
} |
package org.ambraproject.rhino.config;
import com.google.common.base.MoreObjects;
import com.google.common.collect.ImmutableSet;
import java.net.URI;
import java.net.URL;
import java.time.LocalDate;
import java.time.Month;
import java.util.List;
import java.util.Objects;
import java.util.Set;
/**
* Configuration for the server.
*/
public class YamlConfiguration implements RuntimeConfiguration {
// TODO add a validate function that can check for
// * required values and throw meaning errors when they are not present
// * supply meaning default values
private final Input input;
public YamlConfiguration(Input input) {
// if the yaml file doesn't contain anything, UserFields object will be null
if (input == null) {
this.input = new Input();
} else {
this.input = input;
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean prettyPrintJson() {
return input.prettyPrintJson;
}
private transient MultiBucketContentRepoEndpoint corpusStorageView;
@Override
public MultiBucketContentRepoEndpoint getCorpusStorage() {
if (corpusStorageView != null) return corpusStorageView;
if (input.contentRepo == null || input.contentRepo.corpus == null) {
throw new RuntimeException("contentRepo.corpus must be configured");
}
return corpusStorageView = parseCorpusStorage(input.contentRepo.corpus);
}
/**
* For corpus storage, unlike for editorial storage, enforce non-null values and set up collection of all buckets.
*/
private static MultiBucketContentRepoEndpoint parseCorpusStorage(MultibucketContentRepoEndpointInput corpus) {
URI address = corpus.address;
if (address == null) {
throw new RuntimeException("contentRepo.corpus.address must be configured");
}
String defaultBucket = corpus.bucket;
if (defaultBucket == null) {
throw new RuntimeException("contentRepo.corpus.bucket must be configured");
}
ImmutableSet<String> allBuckets = ImmutableSet.<String>builder()
.add(defaultBucket)
.addAll(MoreObjects.firstNonNull(corpus.secondaryBuckets, ImmutableSet.of()))
.build();
ImmutableSet<String> secondaryBuckets =
ImmutableSet.copyOf(MoreObjects.firstNonNull(corpus.secondaryBuckets, ImmutableSet.of()));
return new MultiBucketContentRepoEndpoint() {
@Override
public URI getAddress() {
return address;
}
@Override
public String getDefaultBucket() {
return defaultBucket;
}
@Override
public ImmutableSet<String> getAllBuckets() {
return allBuckets;
}
@Override
public ImmutableSet<String> getSecondaryBuckets() {
return secondaryBuckets;
}
};
}
private static final ContentRepoEndpoint NULL_CONTENT_REPO_ENDPOINT = new ContentRepoEndpoint() {
@Override
public URI getAddress() {
return null;
}
@Override
public String getDefaultBucket() {
return null;
}
};
private transient ContentRepoEndpoint editorialStorageView;
@Override
public ContentRepoEndpoint getEditorialStorage() {
return (editorialStorageView != null) ? editorialStorageView
: (input.contentRepo == null) ? NULL_CONTENT_REPO_ENDPOINT
: (input.contentRepo.editorial == null) ? NULL_CONTENT_REPO_ENDPOINT
: (editorialStorageView = new ContentRepoEndpoint() {
@Override
public URI getAddress() {
return input.contentRepo.editorial.address;
}
@Override
public String getDefaultBucket() {
return input.contentRepo.editorial.bucket;
}
});
}
private final HttpConnectionPoolConfiguration httpConnectionPoolConfiguration = new HttpConnectionPoolConfiguration() {
@Override
public Integer getMaxTotal() {
return (input.httpConnectionPool == null) ? null : input.httpConnectionPool.maxTotal;
}
@Override
public Integer getDefaultMaxPerRoute() {
return (input.httpConnectionPool == null) ? null : input.httpConnectionPool.defaultMaxPerRoute;
}
};
@Override
public HttpConnectionPoolConfiguration getHttpConnectionPoolConfiguration() {
return httpConnectionPoolConfiguration;
}
private final TaxonomyConfiguration taxonomyConfiguration = new TaxonomyConfiguration() {
private ImmutableSet<String> categoryBlacklist;
@Override
public URL getServer() {
return (input.taxonomy == null) ? null : input.taxonomy.server;
}
@Override
public String getThesaurus() {
return (input.taxonomy == null) ? null : input.taxonomy.thesaurus;
}
@Override
public Set<String> getCategoryBlacklist() {
if (categoryBlacklist != null) return categoryBlacklist;
if (input.taxonomy.categoryBlacklist == null) return categoryBlacklist = ImmutableSet.of();
return categoryBlacklist = ImmutableSet.copyOf(input.taxonomy.categoryBlacklist);
}
};
@Override
public TaxonomyConfiguration getTaxonomyConfiguration() {
return taxonomyConfiguration;
}
private static class UserApiConfigurationObject implements UserApiConfiguration {
// Must have real instance variables so that ConfigurationReadController.readNedConfig can serialize it
private final URL server;
private final String authorizationAppName;
private final String authorizationPassword;
private UserApiConfigurationObject(Input input) {
server = (input.userApi == null) ? null : input.userApi.server;
authorizationAppName = (input.userApi == null) ? null : input.userApi.authorizationAppName;
authorizationPassword = (input.userApi == null) ? null : input.userApi.authorizationPassword;
}
@Override
public URL getServer() {
return server;
}
@Override
public String getAuthorizationAppName() {
return authorizationAppName;
}
@Override
public String getAuthorizationPassword() {
return authorizationPassword;
}
}
private transient UserApiConfigurationObject userApiConfigurationObject;
@Override
public UserApiConfiguration getNedConfiguration() {
return (userApiConfigurationObject != null) ? userApiConfigurationObject
: (userApiConfigurationObject = new UserApiConfigurationObject(input));
}
@Override
public LocalDate getCompetingInterestPolicyStart() {
return (input.competingInterestPolicyStart == null) ? DEFAULT_COMPETING_INTEREST_POLICY_START
: LocalDate.parse(input.competingInterestPolicyStart);
}
/**
* The date at which the relevant software upgrade was deployed on PLOS's Ambra system, which was the only extant
* Ambra system at the time. Because no other systems will have older comments, it should never be necessary to
* override this default except in test environments.
*/
private static final LocalDate DEFAULT_COMPETING_INTEREST_POLICY_START = LocalDate.of(2009, Month.MARCH, 20);
private transient QueueConfiguration queueConfiguration;
@Override
public QueueConfiguration getQueueConfiguration() {
return (queueConfiguration != null) ? queueConfiguration : (queueConfiguration = new QueueConfiguration() {
private static final String DEFAULT_BROKER_URL = "tcp://localhost:61616";
private static final int DEFAULT_SYNDICATION_RANGE = 30;
@Override
public String getBrokerUrl() {
return input.queue != null && input.queue.brokerUrl != null ? input.queue.brokerUrl : DEFAULT_BROKER_URL;
}
@Override
public String getSolrUpdate() {
return input.queue != null ? input.queue.solrUpdate : null;
}
@Override
public String getLiteSolrUpdate() {
return input.queue != null ? input.queue.liteSolrUpdate : null;
}
@Override
public String getSolrDelete() {
return input.queue != null ? input.queue.solrDelete : null;
}
@Override
public int getSyndicationRange() {
return input.queue != null && input.queue.syndicationRange != null ? input.queue.syndicationRange : DEFAULT_SYNDICATION_RANGE;
}
});
}
@Override
public String getManuscriptCustomMetaName(ManuscriptCustomMetaAttribute attribute) {
Objects.requireNonNull(attribute);
if (input.manuscriptCustomMeta == null) return null;
switch (attribute) {
case REVISION_DATE:
return input.manuscriptCustomMeta.revisionDate;
case PUBLICATION_STAGE:
return input.manuscriptCustomMeta.publicationStage;
default:
throw new AssertionError();
}
}
public static class Input {
private boolean prettyPrintJson = true; // the default value should be true
private ContentRepoInput contentRepo;
private HttpConnectionPoolConfigurationInput httpConnectionPool;
private TaxonomyConfigurationInput taxonomy;
private UserApiConfigurationInput userApi;
private String competingInterestPolicyStart;
private QueueConfigurationInput queue;
private ManuscriptCustomMetaInput manuscriptCustomMeta;
/**
* @deprecated For reflective access by SnakeYAML only
*/
@Deprecated
public void setPrettyPrintJson(boolean prettyPrintJson) {
this.prettyPrintJson = prettyPrintJson;
}
/**
* @deprecated For reflective access by SnakeYAML only
*/
@Deprecated
public void setContentRepo(ContentRepoInput contentRepo) {
this.contentRepo = contentRepo;
}
/**
* @deprecated For reflective access by SnakeYAML only
*/
@Deprecated
public void setHttpConnectionPool(HttpConnectionPoolConfigurationInput httpConnectionPool) {
this.httpConnectionPool = httpConnectionPool;
}
/**
* @deprecated For reflective access by SnakeYAML only
*/
@Deprecated
public void setTaxonomy(TaxonomyConfigurationInput taxonomy) {
this.taxonomy = taxonomy;
}
/**
* @deprecated For reflective access by SnakeYAML only
*/
@Deprecated
public void setUserApi(UserApiConfigurationInput userApi) {
this.userApi = userApi;
}
/**
* @deprecated For reflective access by SnakeYAML only
*/
@Deprecated
public void setCompetingInterestPolicyStart(String competingInterestPolicyStart) {
this.competingInterestPolicyStart = competingInterestPolicyStart;
}
/**
* @deprecated For reflective access by SnakeYAML only
*/
@Deprecated
public void setQueue(QueueConfigurationInput queue) {
this.queue = queue;
}
/**
* @deprecated For reflective access by SnakeYAML only
*/
@Deprecated
public void setManuscriptCustomMeta(ManuscriptCustomMetaInput manuscriptCustomMeta) {
this.manuscriptCustomMeta = manuscriptCustomMeta;
}
}
public static class ContentRepoInput {
private ContentRepoEndpointInput editorial; // upstairs
private MultibucketContentRepoEndpointInput corpus; // downstairs
/**
* @deprecated For reflective access by SnakeYAML only
*/
@Deprecated
public void setEditorial(ContentRepoEndpointInput editorial) {
this.editorial = editorial;
}
/**
* @deprecated For reflective access by SnakeYAML only
*/
@Deprecated
public void setCorpus(MultibucketContentRepoEndpointInput corpus) {
this.corpus = corpus;
}
}
public static class ContentRepoEndpointInput {
protected URI address;
protected String bucket;
/**
* @deprecated For reflective access by SnakeYAML only
*/
@Deprecated
public void setAddress(URI address) {
this.address = address;
}
/**
* @deprecated For reflective access by SnakeYAML only
*/
@Deprecated
public void setBucket(String bucket) {
this.bucket = bucket;
}
}
public static class MultibucketContentRepoEndpointInput extends ContentRepoEndpointInput {
private List<String> secondaryBuckets;
/**
* @deprecated For reflective access by SnakeYAML only
*/
@Deprecated
public void setSecondaryBuckets(List<String> secondaryBuckets) {
this.secondaryBuckets = secondaryBuckets;
}
}
public static class HttpConnectionPoolConfigurationInput {
private Integer maxTotal;
private Integer defaultMaxPerRoute;
@Deprecated
public void setMaxTotal(Integer maxTotal) {
this.maxTotal = maxTotal;
}
@Deprecated
public void setDefaultMaxPerRoute(Integer defaultMaxPerRoute) {
this.defaultMaxPerRoute = defaultMaxPerRoute;
}
}
public static class TaxonomyConfigurationInput {
private URL server;
private String thesaurus;
private List<String> categoryBlacklist;
@Deprecated
public void setServer(URL server) {
this.server = server;
}
@Deprecated
public void setThesaurus(String thesaurus) {
this.thesaurus = thesaurus;
}
@Deprecated
public void setCategoryBlacklist(List<String> categoryBlacklist) {
this.categoryBlacklist = categoryBlacklist;
}
}
public static class UserApiConfigurationInput {
private URL server;
private String authorizationAppName;
private String authorizationPassword;
@Deprecated
public void setServer(URL server) {
this.server = server;
}
@Deprecated
public void setAuthorizationAppName(String authorizationAppName) {
this.authorizationAppName = authorizationAppName;
}
@Deprecated
public void setAuthorizationPassword(String authorizationPassword) {
this.authorizationPassword = authorizationPassword;
}
}
public static class QueueConfigurationInput {
private String brokerUrl;
private String solrUpdate;
private String liteSolrUpdate;
private String solrDelete;
private Integer syndicationRange;
@Deprecated
public void setBrokerUrl(String brokerUrl) {
this.brokerUrl = brokerUrl;
}
@Deprecated
public void setSolrUpdate(String solrUpdate) {
this.solrUpdate = solrUpdate;
}
@Deprecated
public void setLiteSolrUpdate(String liteSolrUpdate) {
this.liteSolrUpdate = liteSolrUpdate;
}
@Deprecated
public void setSolrDelete(String solrDelete) {
this.solrDelete = solrDelete;
}
@Deprecated
public void setSyndicationRange(Integer syndicationRange) {
this.syndicationRange = syndicationRange;
}
}
public static class ManuscriptCustomMetaInput {
private String revisionDate;
private String publicationStage;
@Deprecated
public void setRevisionDate(String revisionDate) {
this.revisionDate = revisionDate;
}
@Deprecated
public void setPublicationStage(String publicationStage) {
this.publicationStage = publicationStage;
}
}
} |
package org.apache.xerces.dom;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import java.util.Vector;
/**
* The Document interface represents the entire HTML or XML document.
* Conceptually, it is the root of the document tree, and provides the
* primary access to the document's data.
* <P>
* Since elements, text nodes, comments, processing instructions,
* etc. cannot exist outside the context of a Document, the Document
* interface also contains the factory methods needed to create these
* objects. The Node objects created have a ownerDocument attribute
* which associates them with the Document within whose context they
* were created.
*
* @version $Id$
* @since PR-DOM-Level-1-19980818.
*/
public class DeferredDocumentImpl
extends DocumentImpl
implements DeferredNode {
// Constants
/** Serialization version. */
static final long serialVersionUID = 5186323580749626857L;
// debugging
/** To include code for printing the ref count tables. */
private static final boolean DEBUG_PRINT_REF_COUNTS = false;
/** To include code for printing the internal tables. */
private static final boolean DEBUG_PRINT_TABLES = false;
/** To debug identifiers set to true and recompile. */
private static final boolean DEBUG_IDS = false;
// protected
/** Chunk shift. */
protected static final int CHUNK_SHIFT = 11; // 2^11 = 2k
/** Chunk size. */
protected static final int CHUNK_SIZE = (1 << CHUNK_SHIFT);
/** Chunk mask. */
protected static final int CHUNK_MASK = CHUNK_SIZE - 1;
/** Initial chunk size. */
protected static final int INITIAL_CHUNK_COUNT = (1 << (16 - CHUNK_SHIFT)); // 2^16 = 64k
// Data
// lazy-eval information
// To maximize memory consumption the actual semantic of these fields vary
// depending on the node type.
/** Node count. */
protected transient int fNodeCount = 0;
/** Node types. */
protected transient int fNodeType[][];
/** Node names. */
protected transient Object fNodeName[][];
/** Node values. */
protected transient Object fNodeValue[][];
/** Node parents. */
protected transient int fNodeParent[][];
/** Node first children. */
protected transient int fNodeLastChild[][];
/** Node prev siblings. */
protected transient int fNodePrevSib[][];
/** Node namespace URI. */
protected transient Object fNodeURI[][];
/** Extra data. */
protected transient int fNodeExtra[][];
/** Identifier count. */
protected transient int fIdCount;
/** Identifier name indexes. */
protected transient String fIdName[];
/** Identifier element indexes. */
protected transient int fIdElement[];
/** DOM2: For namespace support in the deferred case.
*/
// Implementation Note: The deferred element and attribute must know how to
// interpret the int representing the qname.
protected boolean fNamespacesEnabled = false;
// private data
private transient final StringBuffer fBufferStr = new StringBuffer();
private transient final Vector fStrChunks = new Vector();
// Constructors
/**
* NON-DOM: Actually creating a Document is outside the DOM's spec,
* since it has to operate in terms of a particular implementation.
*/
public DeferredDocumentImpl() {
this(false);
} // <init>()
/**
* NON-DOM: Actually creating a Document is outside the DOM's spec,
* since it has to operate in terms of a particular implementation.
*/
public DeferredDocumentImpl(boolean namespacesEnabled) {
this(namespacesEnabled, false);
} // <init>(boolean)
/** Experimental constructor. */
public DeferredDocumentImpl(boolean namespaces, boolean grammarAccess) {
super(grammarAccess);
needsSyncData(true);
needsSyncChildren(true);
fNamespacesEnabled = namespaces;
} // <init>(boolean,boolean)
// Public methods
/** Returns the cached parser.getNamespaces() value.*/
boolean getNamespacesEnabled() {
return fNamespacesEnabled;
}
void setNamespacesEnabled(boolean enable) {
fNamespacesEnabled = enable;
}
// internal factory methods
/** Creates a document node in the table. */
public int createDeferredDocument() {
int nodeIndex = createNode(Node.DOCUMENT_NODE);
return nodeIndex;
}
/** Creates a doctype. */
public int createDeferredDocumentType(String rootElementName,
String publicId, String systemId) {
// create node
int nodeIndex = createNode(Node.DOCUMENT_TYPE_NODE);
int chunk = nodeIndex >> CHUNK_SHIFT;
int index = nodeIndex & CHUNK_MASK;
// save name, public id, system id
setChunkValue(fNodeName, rootElementName, chunk, index);
setChunkValue(fNodeValue, publicId, chunk, index);
setChunkValue(fNodeURI, systemId, chunk, index);
// return node index
return nodeIndex;
} // createDeferredDocumentType(String,String,String):int
public void setInternalSubset(int doctypeIndex, String subset) {
int chunk = doctypeIndex >> CHUNK_SHIFT;
int index = doctypeIndex & CHUNK_MASK;
// create extra data node to store internal subset
int extraDataIndex = createNode(Node.DOCUMENT_TYPE_NODE);
int echunk = extraDataIndex >> CHUNK_SHIFT;
int eindex = extraDataIndex & CHUNK_MASK;
setChunkIndex(fNodeExtra, extraDataIndex, chunk, index);
setChunkValue(fNodeValue, subset, echunk, eindex);
}
/** Creates a notation in the table. */
public int createDeferredNotation(String notationName,
String publicId, String systemId, String baseURI) {
// create node
int nodeIndex = createNode(Node.NOTATION_NODE);
int chunk = nodeIndex >> CHUNK_SHIFT;
int index = nodeIndex & CHUNK_MASK;
// create extra data node
int extraDataIndex = createNode(Node.NOTATION_NODE);
int echunk = extraDataIndex >> CHUNK_SHIFT;
int eindex = extraDataIndex & CHUNK_MASK;
// save name, public id, system id, and notation name
setChunkValue(fNodeName, notationName, chunk, index);
setChunkValue(fNodeValue, publicId, chunk, index);
setChunkValue(fNodeURI, systemId, chunk, index);
// in extra data node set baseURI value
setChunkIndex(fNodeExtra, extraDataIndex, chunk, index);
setChunkValue(fNodeName, baseURI, echunk, eindex);
// return node index
return nodeIndex;
} // createDeferredNotation(String,String,String):int
/** Creates an entity in the table. */
public int createDeferredEntity(String entityName, String publicId,
String systemId, String notationName,
String baseURI) {
// create node
int nodeIndex = createNode(Node.ENTITY_NODE);
int chunk = nodeIndex >> CHUNK_SHIFT;
int index = nodeIndex & CHUNK_MASK;
// create extra data node
int extraDataIndex = createNode(Node.ENTITY_NODE);
int echunk = extraDataIndex >> CHUNK_SHIFT;
int eindex = extraDataIndex & CHUNK_MASK;
// save name, public id, system id, and notation name
setChunkValue(fNodeName, entityName, chunk, index);
setChunkValue(fNodeValue, publicId, chunk, index);
setChunkValue(fNodeURI, systemId, chunk, index);
setChunkIndex(fNodeExtra, extraDataIndex, chunk, index);
// set other values in the extra chunk
// notation
setChunkValue(fNodeName, notationName, echunk, eindex);
// version L3
setChunkValue(fNodeValue, null, echunk, eindex);
// encoding L3
setChunkValue(fNodeURI, null, echunk, eindex);
int extraDataIndex2 = createNode(Node.ENTITY_NODE);
int echunk2 = extraDataIndex2 >> CHUNK_SHIFT;
int eindex2 = extraDataIndex2 & CHUNK_MASK;
setChunkIndex(fNodeExtra, extraDataIndex2, echunk, eindex);
// baseURI
setChunkValue(fNodeName, baseURI, echunk2, eindex2);
// return node index
return nodeIndex;
} // createDeferredEntity(String,String,String,String):int
public String getDeferredEntityBaseURI (int entityIndex){
if (entityIndex != -1) {
int extraDataIndex = getNodeExtra(entityIndex, false);
extraDataIndex = getNodeExtra(extraDataIndex, false);
return getNodeName (extraDataIndex, false);
}
return null;
}
// DOM Level 3: setting encoding and version
public void setEntityInfo(int currentEntityDecl,
String version, String encoding){
int eNodeIndex = getNodeExtra(currentEntityDecl, false);
if (eNodeIndex !=-1) {
int echunk = eNodeIndex >> CHUNK_SHIFT;
int eindex = eNodeIndex & CHUNK_MASK;
setChunkValue(fNodeValue, version, echunk, eindex);
setChunkValue(fNodeURI, encoding, echunk, eindex);
}
}
// DOM Level 3
// setting actual encoding
public void setActualEncoding(int currentEntityDecl, String value){
// get first extra data chunk
int nodeIndex = getNodeExtra(currentEntityDecl, false);
// get second extra data chunk
int extraDataIndex = getNodeExtra(nodeIndex, false);
int echunk = extraDataIndex >> CHUNK_SHIFT;
int eindex = extraDataIndex & CHUNK_MASK;
setChunkValue(fNodeValue, value, echunk, eindex);
}
/** Creates an entity reference node in the table. */
public int createDeferredEntityReference(String name, String baseURI) {
// create node
int nodeIndex = createNode(Node.ENTITY_REFERENCE_NODE);
int chunk = nodeIndex >> CHUNK_SHIFT;
int index = nodeIndex & CHUNK_MASK;
setChunkValue(fNodeName, name, chunk, index);
setChunkValue(fNodeValue, baseURI, chunk, index);
// return node index
return nodeIndex;
} // createDeferredEntityReference(String):int
/** Creates an element node with a URI in the table and type information. */
public int createDeferredElement(String elementURI, String elementName,
Object type) {
// create node
int elementNodeIndex = createNode(Node.ELEMENT_NODE);
int elementChunk = elementNodeIndex >> CHUNK_SHIFT;
int elementIndex = elementNodeIndex & CHUNK_MASK;
setChunkValue(fNodeName, elementName, elementChunk, elementIndex);
setChunkValue(fNodeURI, elementURI, elementChunk, elementIndex);
setChunkValue(fNodeValue, type, elementChunk, elementIndex);
// return node index
return elementNodeIndex;
} // createDeferredElement(String,String):int
/** @deprecated. Creates an element node in the table. */
public int createDeferredElement(String elementName) {
return createDeferredElement(null, elementName);
}
/** @deprecated. Creates an element node with a URI in the table. */
public int createDeferredElement(String elementURI, String elementName) {
// create node
int elementNodeIndex = createNode(Node.ELEMENT_NODE);
int elementChunk = elementNodeIndex >> CHUNK_SHIFT;
int elementIndex = elementNodeIndex & CHUNK_MASK;
setChunkValue(fNodeName, elementName, elementChunk, elementIndex);
setChunkValue(fNodeURI, elementURI, elementChunk, elementIndex);
// return node index
return elementNodeIndex;
} // createDeferredElement(String,String):int
/**
* This method is used by the DOMParser to create attributes.
* @param elementNodeIndex
* @param attrName
* @param attrURI
* @param attrValue
* @param specified
* @param id
* @param type
* @return int
*/
public int setDeferredAttribute(int elementNodeIndex,
String attrName,
String attrURI,
String attrValue,
boolean specified,
boolean id,
Object type) {
// create attribute
int attrNodeIndex = createDeferredAttribute(attrName, attrURI, attrValue, specified);
int attrChunk = attrNodeIndex >> CHUNK_SHIFT;
int attrIndex = attrNodeIndex & CHUNK_MASK;
// set attribute's parent to element
setChunkIndex(fNodeParent, elementNodeIndex, attrChunk, attrIndex);
int elementChunk = elementNodeIndex >> CHUNK_SHIFT;
int elementIndex = elementNodeIndex & CHUNK_MASK;
// get element's last attribute
int lastAttrNodeIndex = getChunkIndex(fNodeExtra, elementChunk, elementIndex);
if (lastAttrNodeIndex != 0) {
int lastAttrChunk = lastAttrNodeIndex >> CHUNK_SHIFT;
int lastAttrIndex = lastAttrNodeIndex & CHUNK_MASK;
// add link from new attribute to last attribute
setChunkIndex(fNodePrevSib, lastAttrNodeIndex, attrChunk, attrIndex);
}
// add link from element to new last attribute
setChunkIndex(fNodeExtra, attrNodeIndex, elementChunk, elementIndex);
int extra = getChunkIndex(fNodeExtra, attrChunk, attrIndex);
if (id) {
extra = extra | ID;
setChunkIndex(fNodeExtra, extra, attrChunk, attrIndex);
String value = getChunkValue(fNodeValue, attrChunk, attrIndex);
putIdentifier(value, elementNodeIndex);
}
// store type information
if (type != null) {
int extraDataIndex = createNode(DeferredNode.TYPE_NODE);
int echunk = extraDataIndex >> CHUNK_SHIFT;
int eindex = extraDataIndex & CHUNK_MASK;
setChunkIndex(fNodeLastChild, extraDataIndex, attrChunk, attrIndex);
setChunkValue(fNodeValue, type, echunk, eindex);
}
// return node index
return attrNodeIndex;
}
/** @deprecated. Sets an attribute on an element node.*/
public int setDeferredAttribute(int elementNodeIndex,
String attrName, String attrURI,
String attrValue, boolean specified) {
// create attribute
int attrNodeIndex = createDeferredAttribute(attrName, attrURI,
attrValue, specified);
int attrChunk = attrNodeIndex >> CHUNK_SHIFT;
int attrIndex = attrNodeIndex & CHUNK_MASK;
// set attribute's parent to element
setChunkIndex(fNodeParent, elementNodeIndex, attrChunk, attrIndex);
int elementChunk = elementNodeIndex >> CHUNK_SHIFT;
int elementIndex = elementNodeIndex & CHUNK_MASK;
// get element's last attribute
int lastAttrNodeIndex = getChunkIndex(fNodeExtra,
elementChunk, elementIndex);
if (lastAttrNodeIndex != 0) {
int lastAttrChunk = lastAttrNodeIndex >> CHUNK_SHIFT;
int lastAttrIndex = lastAttrNodeIndex & CHUNK_MASK;
// add link from new attribute to last attribute
setChunkIndex(fNodePrevSib, lastAttrNodeIndex,
attrChunk, attrIndex);
}
// add link from element to new last attribute
setChunkIndex(fNodeExtra, attrNodeIndex,
elementChunk, elementIndex);
// return node index
return attrNodeIndex;
} // setDeferredAttribute(int,String,String,String,boolean):int
/** Creates an attribute in the table. */
public int createDeferredAttribute(String attrName, String attrValue,
boolean specified) {
return createDeferredAttribute(attrName, null, attrValue, specified);
}
/** Creates an attribute with a URI in the table. */
public int createDeferredAttribute(String attrName, String attrURI,
String attrValue, boolean specified) {
// create node
int nodeIndex = createNode(NodeImpl.ATTRIBUTE_NODE);
int chunk = nodeIndex >> CHUNK_SHIFT;
int index = nodeIndex & CHUNK_MASK;
setChunkValue(fNodeName, attrName, chunk, index);
setChunkValue(fNodeURI, attrURI, chunk, index);
setChunkValue(fNodeValue, attrValue, chunk, index);
int extra = specified ? SPECIFIED : 0;
setChunkIndex(fNodeExtra, extra, chunk, index);
// return node index
return nodeIndex;
} // createDeferredAttribute(String,String,String,boolean):int
/** Creates an element definition in the table.*/
public int createDeferredElementDefinition(String elementName) {
// create node
int nodeIndex = createNode(NodeImpl.ELEMENT_DEFINITION_NODE);
int chunk = nodeIndex >> CHUNK_SHIFT;
int index = nodeIndex & CHUNK_MASK;
setChunkValue(fNodeName, elementName, chunk, index);
// return node index
return nodeIndex;
} // createDeferredElementDefinition(String):int
/** Creates a text node in the table. */
public int createDeferredTextNode(String data,
boolean ignorableWhitespace) {
// create node
int nodeIndex = createNode(Node.TEXT_NODE);
int chunk = nodeIndex >> CHUNK_SHIFT;
int index = nodeIndex & CHUNK_MASK;
setChunkValue(fNodeValue, data, chunk, index);
// use extra to store ignorableWhitespace info
setChunkIndex(fNodeExtra, ignorableWhitespace ? 1 : 0, chunk, index);
// return node index
return nodeIndex;
} // createDeferredTextNode(String,boolean):int
/** Creates a CDATA section node in the table. */
public int createDeferredCDATASection(String data) {
// create node
int nodeIndex = createNode(Node.CDATA_SECTION_NODE);
int chunk = nodeIndex >> CHUNK_SHIFT;
int index = nodeIndex & CHUNK_MASK;
setChunkValue(fNodeValue, data, chunk, index);
// return node index
return nodeIndex;
} // createDeferredCDATASection(String):int
/** Creates a processing instruction node in the table. */
public int createDeferredProcessingInstruction(String target,
String data) {
// create node
int nodeIndex = createNode(Node.PROCESSING_INSTRUCTION_NODE);
int chunk = nodeIndex >> CHUNK_SHIFT;
int index = nodeIndex & CHUNK_MASK;
setChunkValue(fNodeName, target, chunk, index);
setChunkValue(fNodeValue, data, chunk, index);
// return node index
return nodeIndex;
} // createDeferredProcessingInstruction(String,String):int
/** Creates a comment node in the table. */
public int createDeferredComment(String data) {
// create node
int nodeIndex = createNode(Node.COMMENT_NODE);
int chunk = nodeIndex >> CHUNK_SHIFT;
int index = nodeIndex & CHUNK_MASK;
setChunkValue(fNodeValue, data, chunk, index);
// return node index
return nodeIndex;
} // createDeferredComment(String):int
/** Creates a clone of the specified node. */
public int cloneNode(int nodeIndex, boolean deep) {
// clone immediate node
int nchunk = nodeIndex >> CHUNK_SHIFT;
int nindex = nodeIndex & CHUNK_MASK;
int nodeType = fNodeType[nchunk][nindex];
int cloneIndex = createNode((short)nodeType);
int cchunk = cloneIndex >> CHUNK_SHIFT;
int cindex = cloneIndex & CHUNK_MASK;
setChunkValue(fNodeName, fNodeName[nchunk][nindex], cchunk, cindex);
setChunkValue(fNodeValue, fNodeValue[nchunk][nindex], cchunk, cindex);
setChunkValue(fNodeURI, fNodeURI[nchunk][nindex], cchunk, cindex);
int extraIndex = fNodeExtra[nchunk][nindex];
if (extraIndex != -1) {
if (nodeType != Node.ATTRIBUTE_NODE && nodeType != Node.TEXT_NODE) {
extraIndex = cloneNode(extraIndex, false);
}
setChunkIndex(fNodeExtra, extraIndex, cchunk, cindex);
}
// clone and attach children
if (deep) {
int prevIndex = -1;
int childIndex = getLastChild(nodeIndex, false);
while (childIndex != -1) {
int clonedChildIndex = cloneNode(childIndex, deep);
insertBefore(cloneIndex, clonedChildIndex, prevIndex);
prevIndex = clonedChildIndex;
childIndex = getRealPrevSibling(childIndex, false);
}
}
// return cloned node index
return cloneIndex;
} // cloneNode(int,boolean):int
/** Appends a child to the specified parent in the table. */
public void appendChild(int parentIndex, int childIndex) {
// append parent index
int pchunk = parentIndex >> CHUNK_SHIFT;
int pindex = parentIndex & CHUNK_MASK;
int cchunk = childIndex >> CHUNK_SHIFT;
int cindex = childIndex & CHUNK_MASK;
setChunkIndex(fNodeParent, parentIndex, cchunk, cindex);
// set previous sibling of new child
int olast = getChunkIndex(fNodeLastChild, pchunk, pindex);
setChunkIndex(fNodePrevSib, olast, cchunk, cindex);
// update parent's last child
setChunkIndex(fNodeLastChild, childIndex, pchunk, pindex);
} // appendChild(int,int)
/** Adds an attribute node to the specified element. */
public int setAttributeNode(int elemIndex, int attrIndex) {
int echunk = elemIndex >> CHUNK_SHIFT;
int eindex = elemIndex & CHUNK_MASK;
int achunk = attrIndex >> CHUNK_SHIFT;
int aindex = attrIndex & CHUNK_MASK;
// see if this attribute is already here
String attrName = getChunkValue(fNodeName, achunk, aindex);
int oldAttrIndex = getChunkIndex(fNodeExtra, echunk, eindex);
int nextIndex = -1;
int oachunk = -1;
int oaindex = -1;
while (oldAttrIndex != -1) {
oachunk = oldAttrIndex >> CHUNK_SHIFT;
oaindex = oldAttrIndex & CHUNK_MASK;
String oldAttrName = getChunkValue(fNodeName, oachunk, oaindex);
if (oldAttrName.equals(attrName)) {
break;
}
nextIndex = oldAttrIndex;
oldAttrIndex = getChunkIndex(fNodePrevSib, oachunk, oaindex);
}
// remove old attribute
if (oldAttrIndex != -1) {
// patch links
int prevIndex = getChunkIndex(fNodePrevSib, oachunk, oaindex);
if (nextIndex == -1) {
setChunkIndex(fNodeExtra, prevIndex, echunk, eindex);
}
else {
int pchunk = nextIndex >> CHUNK_SHIFT;
int pindex = nextIndex & CHUNK_MASK;
setChunkIndex(fNodePrevSib, prevIndex, pchunk, pindex);
}
// remove connections to siblings
clearChunkIndex(fNodeType, oachunk, oaindex);
clearChunkValue(fNodeName, oachunk, oaindex);
clearChunkValue(fNodeValue, oachunk, oaindex);
clearChunkIndex(fNodeParent, oachunk, oaindex);
clearChunkIndex(fNodePrevSib, oachunk, oaindex);
int attrTextIndex =
clearChunkIndex(fNodeLastChild, oachunk, oaindex);
int atchunk = attrTextIndex >> CHUNK_SHIFT;
int atindex = attrTextIndex & CHUNK_MASK;
clearChunkIndex(fNodeType, atchunk, atindex);
clearChunkValue(fNodeValue, atchunk, atindex);
clearChunkIndex(fNodeParent, atchunk, atindex);
clearChunkIndex(fNodeLastChild, atchunk, atindex);
}
// add new attribute
int prevIndex = getChunkIndex(fNodeExtra, echunk, eindex);
setChunkIndex(fNodeExtra, attrIndex, echunk, eindex);
setChunkIndex(fNodePrevSib, prevIndex, achunk, aindex);
// return
return oldAttrIndex;
} // setAttributeNode(int,int):int
/** Adds an attribute node to the specified element. */
public void setIdAttributeNode(int elemIndex, int attrIndex) {
int chunk = attrIndex >> CHUNK_SHIFT;
int index = attrIndex & CHUNK_MASK;
int extra = getChunkIndex(fNodeExtra, chunk, index);
extra = extra | ID;
setChunkIndex(fNodeExtra, extra, chunk, index);
String value = getChunkValue(fNodeValue, chunk, index);
putIdentifier(value, elemIndex);
}
/** Sets type of attribute */
public void setIdAttribute(int attrIndex) {
int chunk = attrIndex >> CHUNK_SHIFT;
int index = attrIndex & CHUNK_MASK;
int extra = getChunkIndex(fNodeExtra, chunk, index);
extra = extra | ID;
setChunkIndex(fNodeExtra, extra, chunk, index);
}
/** Inserts a child before the specified node in the table. */
public int insertBefore(int parentIndex, int newChildIndex, int refChildIndex) {
if (refChildIndex == -1) {
appendChild(parentIndex, newChildIndex);
return newChildIndex;
}
int nchunk = newChildIndex >> CHUNK_SHIFT;
int nindex = newChildIndex & CHUNK_MASK;
int rchunk = refChildIndex >> CHUNK_SHIFT;
int rindex = refChildIndex & CHUNK_MASK;
int previousIndex = getChunkIndex(fNodePrevSib, rchunk, rindex);
setChunkIndex(fNodePrevSib, newChildIndex, rchunk, rindex);
setChunkIndex(fNodePrevSib, previousIndex, nchunk, nindex);
return newChildIndex;
} // insertBefore(int,int,int):int
/** Sets the last child of the parentIndex to childIndex. */
public void setAsLastChild(int parentIndex, int childIndex) {
int pchunk = parentIndex >> CHUNK_SHIFT;
int pindex = parentIndex & CHUNK_MASK;
int chunk = childIndex >> CHUNK_SHIFT;
int index = childIndex & CHUNK_MASK;
setChunkIndex(fNodeLastChild, childIndex, pchunk, pindex);
} // setAsLastChild(int,int)
/**
* Returns the parent node of the given node.
* <em>Calling this method does not free the parent index.</em>
*/
public int getParentNode(int nodeIndex) {
return getParentNode(nodeIndex, false);
}
/**
* Returns the parent node of the given node.
* @param free True to free parent node.
*/
public int getParentNode(int nodeIndex, boolean free) {
if (nodeIndex == -1) {
return -1;
}
int chunk = nodeIndex >> CHUNK_SHIFT;
int index = nodeIndex & CHUNK_MASK;
return free ? clearChunkIndex(fNodeParent, chunk, index)
: getChunkIndex(fNodeParent, chunk, index);
} // getParentNode(int):int
/** Returns the last child of the given node. */
public int getLastChild(int nodeIndex) {
return getLastChild(nodeIndex, true);
}
/**
* Returns the last child of the given node.
* @param free True to free child index.
*/
public int getLastChild(int nodeIndex, boolean free) {
if (nodeIndex == -1) {
return -1;
}
int chunk = nodeIndex >> CHUNK_SHIFT;
int index = nodeIndex & CHUNK_MASK;
return free ? clearChunkIndex(fNodeLastChild, chunk, index)
: getChunkIndex(fNodeLastChild, chunk, index);
} // getLastChild(int,boolean):int
/**
* Returns the prev sibling of the given node.
* This is post-normalization of Text Nodes.
*/
public int getPrevSibling(int nodeIndex) {
return getPrevSibling(nodeIndex, true);
}
/**
* Returns the prev sibling of the given node.
* @param free True to free sibling index.
*/
public int getPrevSibling(int nodeIndex, boolean free) {
if (nodeIndex == -1) {
return -1;
}
int chunk = nodeIndex >> CHUNK_SHIFT;
int index = nodeIndex & CHUNK_MASK;
int type = getChunkIndex(fNodeType, chunk, index);
if (type == Node.TEXT_NODE) {
do {
nodeIndex = getChunkIndex(fNodePrevSib, chunk, index);
if (nodeIndex == -1) {
break;
}
chunk = nodeIndex >> CHUNK_SHIFT;
index = nodeIndex & CHUNK_MASK;
type = getChunkIndex(fNodeType, chunk, index);
} while (type == Node.TEXT_NODE);
}
else {
nodeIndex = getChunkIndex(fNodePrevSib, chunk, index);
}
return nodeIndex;
} // getPrevSibling(int,boolean):int
/**
* Returns the <i>real</i> prev sibling of the given node,
* directly from the data structures. Used by TextImpl#getNodeValue()
* to normalize values.
*/
public int getRealPrevSibling(int nodeIndex) {
return getRealPrevSibling(nodeIndex, true);
}
/**
* Returns the <i>real</i> prev sibling of the given node.
* @param free True to free sibling index.
*/
public int getRealPrevSibling(int nodeIndex, boolean free) {
if (nodeIndex == -1) {
return -1;
}
int chunk = nodeIndex >> CHUNK_SHIFT;
int index = nodeIndex & CHUNK_MASK;
return free ? clearChunkIndex(fNodePrevSib, chunk, index)
: getChunkIndex(fNodePrevSib, chunk, index);
} // getReadPrevSibling(int,boolean):int
/**
* Returns the index of the element definition in the table
* with the specified name index, or -1 if no such definition
* exists.
*/
public int lookupElementDefinition(String elementName) {
if (fNodeCount > 1) {
// find doctype
int docTypeIndex = -1;
int nchunk = 0;
int nindex = 0;
for (int index = getChunkIndex(fNodeLastChild, nchunk, nindex);
index != -1;
index = getChunkIndex(fNodePrevSib, nchunk, nindex)) {
nchunk = index >> CHUNK_SHIFT;
nindex = index & CHUNK_MASK;
if (getChunkIndex(fNodeType, nchunk, nindex) == Node.DOCUMENT_TYPE_NODE) {
docTypeIndex = index;
break;
}
}
// find element definition
if (docTypeIndex == -1) {
return -1;
}
nchunk = docTypeIndex >> CHUNK_SHIFT;
nindex = docTypeIndex & CHUNK_MASK;
for (int index = getChunkIndex(fNodeLastChild, nchunk, nindex);
index != -1;
index = getChunkIndex(fNodePrevSib, nchunk, nindex)) {
nchunk = index >> CHUNK_SHIFT;
nindex = index & CHUNK_MASK;
if (getChunkIndex(fNodeType, nchunk, nindex) ==
NodeImpl.ELEMENT_DEFINITION_NODE
&& getChunkValue(fNodeName, nchunk, nindex) == elementName) {
return index;
}
}
}
return -1;
} // lookupElementDefinition(String):int
/** Instantiates the requested node object. */
public DeferredNode getNodeObject(int nodeIndex) {
// is there anything to do?
if (nodeIndex == -1) {
return null;
}
// get node type
int chunk = nodeIndex >> CHUNK_SHIFT;
int index = nodeIndex & CHUNK_MASK;
int type = getChunkIndex(fNodeType, chunk, index);
if (type != Node.TEXT_NODE && type != Node.CDATA_SECTION_NODE) {
clearChunkIndex(fNodeType, chunk, index);
}
// create new node
DeferredNode node = null;
switch (type) {
// Standard DOM node types
case Node.ATTRIBUTE_NODE: {
if (fNamespacesEnabled) {
node = new DeferredAttrNSImpl(this, nodeIndex);
} else {
node = new DeferredAttrImpl(this, nodeIndex);
}
break;
}
case Node.CDATA_SECTION_NODE: {
node = new DeferredCDATASectionImpl(this, nodeIndex);
break;
}
case Node.COMMENT_NODE: {
node = new DeferredCommentImpl(this, nodeIndex);
break;
}
// NOTE: Document fragments can never be "fast".
// The parser will never ask to create a document
// fragment during the parse. Document fragments
// are used by the application *after* the parse.
// case Node.DOCUMENT_FRAGMENT_NODE: { break; }
case Node.DOCUMENT_NODE: {
// this node is never "fast"
node = this;
break;
}
case Node.DOCUMENT_TYPE_NODE: {
node = new DeferredDocumentTypeImpl(this, nodeIndex);
// save the doctype node
docType = (DocumentTypeImpl)node;
break;
}
case Node.ELEMENT_NODE: {
if (DEBUG_IDS) {
System.out.println("getNodeObject(ELEMENT_NODE): "+nodeIndex);
}
// create node
if (fNamespacesEnabled) {
node = new DeferredElementNSImpl(this, nodeIndex);
} else {
node = new DeferredElementImpl(this, nodeIndex);
}
// save the document element node
if (docElement == null) {
docElement = (ElementImpl)node;
}
// check to see if this element needs to be
// registered for its ID attributes
if (fIdElement != null) {
int idIndex = binarySearch(fIdElement, 0,
fIdCount-1, nodeIndex);
while (idIndex != -1) {
if (DEBUG_IDS) {
System.out.println(" id index: "+idIndex);
System.out.println(" fIdName["+idIndex+
"]: "+fIdName[idIndex]);
}
// register ID
String name = fIdName[idIndex];
if (name != null) {
if (DEBUG_IDS) {
System.out.println(" name: "+name);
System.out.print("getNodeObject()
}
putIdentifier0(name, (Element)node);
fIdName[idIndex] = null;
}
// continue if there are more IDs for
// this element
if (idIndex + 1 < fIdCount &&
fIdElement[idIndex + 1] == nodeIndex) {
idIndex++;
}
else {
idIndex = -1;
}
}
}
break;
}
case Node.ENTITY_NODE: {
node = new DeferredEntityImpl(this, nodeIndex);
break;
}
case Node.ENTITY_REFERENCE_NODE: {
node = new DeferredEntityReferenceImpl(this, nodeIndex);
break;
}
case Node.NOTATION_NODE: {
node = new DeferredNotationImpl(this, nodeIndex);
break;
}
case Node.PROCESSING_INSTRUCTION_NODE: {
node = new DeferredProcessingInstructionImpl(this, nodeIndex);
break;
}
case Node.TEXT_NODE: {
node = new DeferredTextImpl(this, nodeIndex);
break;
}
// non-standard DOM node types
case NodeImpl.ELEMENT_DEFINITION_NODE: {
node = new DeferredElementDefinitionImpl(this, nodeIndex);
break;
}
default: {
throw new IllegalArgumentException("type: "+type);
}
} // switch node type
// store and return
if (node != null) {
return node;
}
// error
throw new IllegalArgumentException();
} // createNodeObject(int):Node
/** Returns the name of the given node. */
public String getNodeName(int nodeIndex) {
return getNodeName(nodeIndex, true);
} // getNodeNameString(int):String
/**
* Returns the name of the given node.
* @param free True to free the string index.
*/
public String getNodeName(int nodeIndex, boolean free) {
if (nodeIndex == -1) {
return null;
}
int chunk = nodeIndex >> CHUNK_SHIFT;
int index = nodeIndex & CHUNK_MASK;
return free ? clearChunkValue(fNodeName, chunk, index)
: getChunkValue(fNodeName, chunk, index);
} // getNodeName(int,boolean):String
/** Returns the real value of the given node. */
public String getNodeValueString(int nodeIndex) {
return getNodeValueString(nodeIndex, true);
} // getNodeValueString(int):String
/**
* Returns the real value of the given node.
* @param free True to free the string index.
*/
public String getNodeValueString(int nodeIndex, boolean free) {
if (nodeIndex == -1) {
return null;
}
int chunk = nodeIndex >> CHUNK_SHIFT;
int index = nodeIndex & CHUNK_MASK;
String value = free ? clearChunkValue(fNodeValue, chunk, index)
: getChunkValue(fNodeValue, chunk, index);
if (value == null) {
return null;
}
int type = getChunkIndex(fNodeType, chunk, index);
if (type == Node.TEXT_NODE) {
int prevSib = getRealPrevSibling(nodeIndex);
if (prevSib != -1 &&
getNodeType(prevSib, false) == Node.TEXT_NODE) {
// append data that is stored in fNodeValue
// REVISIT: for text nodes it works differently than for CDATA
// nodes.
fStrChunks.addElement(value);
do {
// go in reverse order: find last child, then
// its previous sibling, etc
chunk = prevSib >> CHUNK_SHIFT;
index = prevSib & CHUNK_MASK;
value = getChunkValue(fNodeValue, chunk, index);
fStrChunks.addElement(value);
prevSib = getChunkIndex(fNodePrevSib, chunk, index);
if (prevSib == -1) {
break;
}
} while (getNodeType(prevSib, false) == Node.TEXT_NODE);
int chunkCount = fStrChunks.size();
// add to the buffer in the correct order.
for (int i = chunkCount - 1; i >= 0; i
fBufferStr.append((String)fStrChunks.elementAt(i));
}
value = fBufferStr.toString();
fStrChunks.removeAllElements();
fBufferStr.setLength(0);
return value;
}
}
else if (type == Node.CDATA_SECTION_NODE) {
// find if any other data stored in children
int child = getLastChild(nodeIndex, false);
if (child !=-1) {
// append data that is stored in fNodeValue
fBufferStr.append(value);
while (child !=-1) {
// go in reverse order: find last child, then
// its previous sibling, etc
chunk = child >> CHUNK_SHIFT;
index = child & CHUNK_MASK;
value = getChunkValue(fNodeValue, chunk, index);
fStrChunks.addElement(value);
child = getChunkIndex(fNodePrevSib, chunk, index);
}
// add to the buffer in the correct order.
for (int i=fStrChunks.size()-1; i>=0; i
fBufferStr.append((String)fStrChunks.elementAt(i));
}
value = fBufferStr.toString();
fStrChunks.setSize(0);
fBufferStr.setLength(0);
return value;
}
}
return value;
} // getNodeValueString(int,boolean):String
/**
* Returns the value of the given node.
*/
public String getNodeValue(int nodeIndex) {
return getNodeValue(nodeIndex, true);
}
/**
* Clears the type info that is stored in the fNodeValue array
* @param nodeIndex
* @return Object - type information for the attribute/element node
*/
public Object getTypeInfo(int nodeIndex) {
if (nodeIndex == -1) {
return null;
}
int chunk = nodeIndex >> CHUNK_SHIFT;
int index = nodeIndex & CHUNK_MASK;
Object value = fNodeValue[chunk] != null ? fNodeValue[chunk][index] : null;
if (value != null) {
fNodeValue[chunk][index] = null;
RefCount c = (RefCount) fNodeValue[chunk][CHUNK_SIZE];
c.fCount
if (c.fCount == 0) {
fNodeValue[chunk] = null;
}
}
return value;
}
/**
* Returns the value of the given node.
* @param free True to free the value index.
*/
public String getNodeValue(int nodeIndex, boolean free) {
if (nodeIndex == -1) {
return null;
}
int chunk = nodeIndex >> CHUNK_SHIFT;
int index = nodeIndex & CHUNK_MASK;
return free ? clearChunkValue(fNodeValue, chunk, index)
: getChunkValue(fNodeValue, chunk, index);
} // getNodeValue(int,boolean):String
/**
* Returns the extra info of the given node.
* Used by AttrImpl to store specified value (1 == true).
*/
public int getNodeExtra(int nodeIndex) {
return getNodeExtra(nodeIndex, true);
}
/**
* Returns the extra info of the given node.
* @param free True to free the value index.
*/
public int getNodeExtra(int nodeIndex, boolean free) {
if (nodeIndex == -1) {
return -1;
}
int chunk = nodeIndex >> CHUNK_SHIFT;
int index = nodeIndex & CHUNK_MASK;
return free ? clearChunkIndex(fNodeExtra, chunk, index)
: getChunkIndex(fNodeExtra, chunk, index);
} // getNodeExtra(int,boolean):int
/** Returns the type of the given node. */
public short getNodeType(int nodeIndex) {
return getNodeType(nodeIndex, true);
}
/**
* Returns the type of the given node.
* @param free True to free type index.
*/
public short getNodeType(int nodeIndex, boolean free) {
if (nodeIndex == -1) {
return -1;
}
int chunk = nodeIndex >> CHUNK_SHIFT;
int index = nodeIndex & CHUNK_MASK;
return free ? (short)clearChunkIndex(fNodeType, chunk, index)
: (short)getChunkIndex(fNodeType, chunk, index);
} // getNodeType(int):int
/** Returns the attribute value of the given name. */
public String getAttribute(int elemIndex, String name) {
if (elemIndex == -1 || name == null) {
return null;
}
int echunk = elemIndex >> CHUNK_SHIFT;
int eindex = elemIndex & CHUNK_MASK;
int attrIndex = getChunkIndex(fNodeExtra, echunk, eindex);
while (attrIndex != -1) {
int achunk = attrIndex >> CHUNK_SHIFT;
int aindex = attrIndex & CHUNK_MASK;
if (getChunkValue(fNodeName, achunk, aindex) == name) {
return getChunkValue(fNodeValue, achunk, aindex);
}
attrIndex = getChunkIndex(fNodePrevSib, achunk, aindex);
}
return null;
}
/** Returns the URI of the given node. */
public String getNodeURI(int nodeIndex) {
return getNodeURI(nodeIndex, true);
}
/**
* Returns the URI of the given node.
* @param free True to free URI index.
*/
public String getNodeURI(int nodeIndex, boolean free) {
if (nodeIndex == -1) {
return null;
}
int chunk = nodeIndex >> CHUNK_SHIFT;
int index = nodeIndex & CHUNK_MASK;
return free ? clearChunkValue(fNodeURI, chunk, index)
: getChunkValue(fNodeURI, chunk, index);
} // getNodeURI(int,int):String
// identifier maintenance
/** Registers an identifier name with a specified element node. */
public void putIdentifier(String name, int elementNodeIndex) {
if (DEBUG_IDS) {
System.out.println("putIdentifier(" + name + ", "
+ elementNodeIndex + ')' + "
getChunkValue(fNodeName,
elementNodeIndex >> CHUNK_SHIFT,
elementNodeIndex & CHUNK_MASK));
}
// initialize arrays
if (fIdName == null) {
fIdName = new String[64];
fIdElement = new int[64];
}
// resize arrays
if (fIdCount == fIdName.length) {
String idName[] = new String[fIdCount * 2];
System.arraycopy(fIdName, 0, idName, 0, fIdCount);
fIdName = idName;
int idElement[] = new int[idName.length];
System.arraycopy(fIdElement, 0, idElement, 0, fIdCount);
fIdElement = idElement;
}
// store identifier
fIdName[fIdCount] = name;
fIdElement[fIdCount] = elementNodeIndex;
fIdCount++;
} // putIdentifier(String,int)
// DEBUG
/** Prints out the tables. */
public void print() {
if (DEBUG_PRINT_REF_COUNTS) {
System.out.print("num\t");
System.out.print("type\t");
System.out.print("name\t");
System.out.print("val\t");
System.out.print("par\t");
System.out.print("lch\t");
System.out.print("psib");
System.out.println();
for (int i = 0; i < fNodeType.length; i++) {
if (fNodeType[i] != null) {
// separator
System.out.print("
System.out.print("
System.out.print("
System.out.print("
System.out.print("
System.out.print("
System.out.print("
System.out.println();
// ref count
System.out.print(i);
System.out.print('\t');
switch (fNodeType[i][CHUNK_SIZE]) {
case DocumentImpl.ELEMENT_DEFINITION_NODE: { System.out.print("EDef"); break; }
case Node.DOCUMENT_NODE: { System.out.print("Doc"); break; }
case Node.DOCUMENT_TYPE_NODE: { System.out.print("DType"); break; }
case Node.COMMENT_NODE: { System.out.print("Com"); break; }
case Node.PROCESSING_INSTRUCTION_NODE: { System.out.print("PI"); break; }
case Node.ELEMENT_NODE: { System.out.print("Elem"); break; }
case Node.ENTITY_NODE: { System.out.print("Ent"); break; }
case Node.ENTITY_REFERENCE_NODE: { System.out.print("ERef"); break; }
case Node.TEXT_NODE: { System.out.print("Text"); break; }
case Node.ATTRIBUTE_NODE: { System.out.print("Attr"); break; }
case DeferredNode.TYPE_NODE: { System.out.print("TypeInfo"); break; }
default: { System.out.print("?"+fNodeType[i][CHUNK_SIZE]); }
}
System.out.print('\t');
System.out.print(fNodeName[i][CHUNK_SIZE]);
System.out.print('\t');
System.out.print(fNodeValue[i][CHUNK_SIZE]);
System.out.print('\t');
System.out.print(fNodeURI[i][CHUNK_SIZE]);
System.out.print('\t');
System.out.print(fNodeParent[i][CHUNK_SIZE]);
System.out.print('\t');
System.out.print(fNodeLastChild[i][CHUNK_SIZE]);
System.out.print('\t');
System.out.print(fNodePrevSib[i][CHUNK_SIZE]);
System.out.print('\t');
System.out.print(fNodeExtra[i][CHUNK_SIZE]);
System.out.println();
}
}
}
if (DEBUG_PRINT_TABLES) {
// This assumes that the document is small
System.out.println("# start table");
for (int i = 0; i < fNodeCount; i++) {
int chunk = i >> CHUNK_SHIFT;
int index = i & CHUNK_MASK;
if (i % 10 == 0) {
System.out.print("num\t");
System.out.print("type\t");
System.out.print("name\t");
System.out.print("val\t");
System.out.print("uri\t");
System.out.print("par\t");
System.out.print("lch\t");
System.out.print("psib\t");
System.out.print("xtra");
System.out.println();
}
System.out.print(i);
System.out.print('\t');
switch (getChunkIndex(fNodeType, chunk, index)) {
case DocumentImpl.ELEMENT_DEFINITION_NODE: { System.out.print("EDef"); break; }
case Node.DOCUMENT_NODE: { System.out.print("Doc"); break; }
case Node.DOCUMENT_TYPE_NODE: { System.out.print("DType"); break; }
case Node.COMMENT_NODE: { System.out.print("Com"); break; }
case Node.PROCESSING_INSTRUCTION_NODE: { System.out.print("PI"); break; }
case Node.ELEMENT_NODE: { System.out.print("Elem"); break; }
case Node.ENTITY_NODE: { System.out.print("Ent"); break; }
case Node.ENTITY_REFERENCE_NODE: { System.out.print("ERef"); break; }
case Node.TEXT_NODE: { System.out.print("Text"); break; }
case Node.ATTRIBUTE_NODE: { System.out.print("Attr"); break; }
case DeferredNode.TYPE_NODE: { System.out.print("TypeInfo"); break; }
default: { System.out.print("?"+getChunkIndex(fNodeType, chunk, index)); }
}
System.out.print('\t');
System.out.print(getChunkValue(fNodeName, chunk, index));
System.out.print('\t');
System.out.print(getNodeValue(chunk, index));
System.out.print('\t');
System.out.print(getChunkValue(fNodeURI, chunk, index));
System.out.print('\t');
System.out.print(getChunkIndex(fNodeParent, chunk, index));
System.out.print('\t');
System.out.print(getChunkIndex(fNodeLastChild, chunk, index));
System.out.print('\t');
System.out.print(getChunkIndex(fNodePrevSib, chunk, index));
System.out.print('\t');
System.out.print(getChunkIndex(fNodeExtra, chunk, index));
System.out.println();
}
System.out.println("# end table");
}
} // print()
// DeferredNode methods
/** Returns the node index. */
public int getNodeIndex() {
return 0;
}
// Protected methods
/** Synchronizes the node's data. */
protected void synchronizeData() {
// no need to sync in the future
needsSyncData(false);
// fluff up enough nodes to fill identifiers hash
if (fIdElement != null) {
// REVISIT: There has to be a more efficient way of
// doing this. But keep in mind that the
// tree can have been altered and re-ordered
// before all of the element nodes with ID
// attributes have been registered. For now
// this is reasonable and safe. -Ac
IntVector path = new IntVector();
for (int i = 0; i < fIdCount; i++) {
// ignore if it's already been registered
int elementNodeIndex = fIdElement[i];
String idName = fIdName[i];
if (idName == null) {
continue;
}
// find path from this element to the root
path.removeAllElements();
int index = elementNodeIndex;
do {
path.addElement(index);
int pchunk = index >> CHUNK_SHIFT;
int pindex = index & CHUNK_MASK;
index = getChunkIndex(fNodeParent, pchunk, pindex);
} while (index != -1);
// Traverse path (backwards), fluffing the elements
// along the way. When this loop finishes, "place"
// will contain the reference to the element node
// we're interested in. -Ac
Node place = this;
for (int j = path.size() - 2; j >= 0; j
index = path.elementAt(j);
Node child = place.getLastChild();
while (child != null) {
if (child instanceof DeferredNode) {
int nodeIndex =
((DeferredNode)child).getNodeIndex();
if (nodeIndex == index) {
place = child;
break;
}
}
child = child.getPreviousSibling();
}
}
// register the element
Element element = (Element)place;
putIdentifier0(idName, element);
fIdName[i] = null;
// see if there are more IDs on this element
while (i + 1 < fIdCount &&
fIdElement[i + 1] == elementNodeIndex) {
idName = fIdName[++i];
if (idName == null) {
continue;
}
putIdentifier0(idName, element);
}
}
} // if identifiers
} // synchronizeData()
/**
* Synchronizes the node's children with the internal structure.
* Fluffing the children at once solves a lot of work to keep
* the two structures in sync. The problem gets worse when
* editing the tree -- this makes it a lot easier.
*/
protected void synchronizeChildren() {
if (needsSyncData()) {
synchronizeData();
/*
* when we have elements with IDs this method is being recursively
* called from synchronizeData, in which case we've already gone
* through the following and we can now simply stop here.
*/
if (!needsSyncChildren()) {
return;
}
}
// we don't want to generate any event for this so turn them off
boolean orig = mutationEvents;
mutationEvents = false;
// no need to sync in the future
needsSyncChildren(false);
getNodeType(0);
// create children and link them as siblings
ChildNode first = null;
ChildNode last = null;
for (int index = getLastChild(0);
index != -1;
index = getPrevSibling(index)) {
ChildNode node = (ChildNode)getNodeObject(index);
if (last == null) {
last = node;
}
else {
first.previousSibling = node;
}
node.ownerNode = this;
node.isOwned(true);
node.nextSibling = first;
first = node;
// save doctype and document type
int type = node.getNodeType();
if (type == Node.ELEMENT_NODE) {
docElement = (ElementImpl)node;
}
else if (type == Node.DOCUMENT_TYPE_NODE) {
docType = (DocumentTypeImpl)node;
}
}
if (first != null) {
firstChild = first;
first.isFirstChild(true);
lastChild(last);
}
// set mutation events flag back to its original value
mutationEvents = orig;
} // synchronizeChildren()
/**
* Synchronizes the node's children with the internal structure.
* Fluffing the children at once solves a lot of work to keep
* the two structures in sync. The problem gets worse when
* editing the tree -- this makes it a lot easier.
* This is not directly used in this class but this method is
* here so that it can be shared by all deferred subclasses of AttrImpl.
*/
protected final void synchronizeChildren(AttrImpl a, int nodeIndex) {
// we don't want to generate any event for this so turn them off
boolean orig = getMutationEvents();
setMutationEvents(false);
// no need to sync in the future
a.needsSyncChildren(false);
// create children and link them as siblings or simply store the value
// as a String if all we have is one piece of text
int last = getLastChild(nodeIndex);
int prev = getPrevSibling(last);
if (prev == -1) {
a.value = getNodeValueString(nodeIndex);
a.hasStringValue(true);
}
else {
ChildNode firstNode = null;
ChildNode lastNode = null;
for (int index = last; index != -1;
index = getPrevSibling(index)) {
ChildNode node = (ChildNode) getNodeObject(index);
if (lastNode == null) {
lastNode = node;
}
else {
firstNode.previousSibling = node;
}
node.ownerNode = a;
node.isOwned(true);
node.nextSibling = firstNode;
firstNode = node;
}
if (lastNode != null) {
a.value = firstNode; // firstChild = firstNode
firstNode.isFirstChild(true);
a.lastChild(lastNode);
}
a.hasStringValue(false);
}
// set mutation events flag back to its original value
setMutationEvents(orig);
} // synchronizeChildren(AttrImpl,int):void
/**
* Synchronizes the node's children with the internal structure.
* Fluffing the children at once solves a lot of work to keep
* the two structures in sync. The problem gets worse when
* editing the tree -- this makes it a lot easier.
* This is not directly used in this class but this method is
* here so that it can be shared by all deferred subclasses of ParentNode.
*/
protected final void synchronizeChildren(ParentNode p, int nodeIndex) {
// we don't want to generate any event for this so turn them off
boolean orig = getMutationEvents();
setMutationEvents(false);
// no need to sync in the future
p.needsSyncChildren(false);
// create children and link them as siblings
ChildNode firstNode = null;
ChildNode lastNode = null;
for (int index = getLastChild(nodeIndex);
index != -1;
index = getPrevSibling(index)) {
ChildNode node = (ChildNode) getNodeObject(index);
if (lastNode == null) {
lastNode = node;
}
else {
firstNode.previousSibling = node;
}
node.ownerNode = p;
node.isOwned(true);
node.nextSibling = firstNode;
firstNode = node;
}
if (lastNode != null) {
p.firstChild = firstNode;
firstNode.isFirstChild(true);
p.lastChild(lastNode);
}
// set mutation events flag back to its original value
setMutationEvents(orig);
} // synchronizeChildren(ParentNode,int):void
// utility methods
/** Ensures that the internal tables are large enough. */
protected void ensureCapacity(int chunk) {
if (fNodeType == null) {
// create buffers
fNodeType = new int[INITIAL_CHUNK_COUNT][];
fNodeName = new Object[INITIAL_CHUNK_COUNT][];
fNodeValue = new Object[INITIAL_CHUNK_COUNT][];
fNodeParent = new int[INITIAL_CHUNK_COUNT][];
fNodeLastChild = new int[INITIAL_CHUNK_COUNT][];
fNodePrevSib = new int[INITIAL_CHUNK_COUNT][];
fNodeURI = new Object[INITIAL_CHUNK_COUNT][];
fNodeExtra = new int[INITIAL_CHUNK_COUNT][];
}
else if (fNodeType.length <= chunk) {
// resize the tables
int newsize = chunk * 2;
int[][] newArray = new int[newsize][];
System.arraycopy(fNodeType, 0, newArray, 0, chunk);
fNodeType = newArray;
Object[][] newStrArray = new Object[newsize][];
System.arraycopy(fNodeName, 0, newStrArray, 0, chunk);
fNodeName = newStrArray;
newStrArray = new Object[newsize][];
System.arraycopy(fNodeValue, 0, newStrArray, 0, chunk);
fNodeValue = newStrArray;
newArray = new int[newsize][];
System.arraycopy(fNodeParent, 0, newArray, 0, chunk);
fNodeParent = newArray;
newArray = new int[newsize][];
System.arraycopy(fNodeLastChild, 0, newArray, 0, chunk);
fNodeLastChild = newArray;
newArray = new int[newsize][];
System.arraycopy(fNodePrevSib, 0, newArray, 0, chunk);
fNodePrevSib = newArray;
newStrArray = new Object[newsize][];
System.arraycopy(fNodeURI, 0, newStrArray, 0, chunk);
fNodeURI = newStrArray;
newArray = new int[newsize][];
System.arraycopy(fNodeExtra, 0, newArray, 0, chunk);
fNodeExtra = newArray;
}
else if (fNodeType[chunk] != null) {
// Done - there's sufficient capacity
return;
}
// create new chunks
createChunk(fNodeType, chunk);
createChunk(fNodeName, chunk);
createChunk(fNodeValue, chunk);
createChunk(fNodeParent, chunk);
createChunk(fNodeLastChild, chunk);
createChunk(fNodePrevSib, chunk);
createChunk(fNodeURI, chunk);
createChunk(fNodeExtra, chunk);
// Done
return;
} // ensureCapacity(int,int)
/** Creates a node of the specified type. */
protected int createNode(short nodeType) {
// ensure tables are large enough
int chunk = fNodeCount >> CHUNK_SHIFT;
int index = fNodeCount & CHUNK_MASK;
ensureCapacity(chunk);
// initialize node
setChunkIndex(fNodeType, nodeType, chunk, index);
// return node index number
return fNodeCount++;
} // createNode(short):int
/**
* Performs a binary search for a target value in an array of
* values. The array of values must be in ascending sorted order
* before calling this method and all array values must be
* non-negative.
*
* @param values The array of values to search.
* @param start The starting offset of the search.
* @param end The ending offset of the search.
* @param target The target value.
*
* @return This function will return the <i>first</i> occurrence
* of the target value, or -1 if the target value cannot
* be found.
*/
protected static int binarySearch(final int values[],
int start, int end, int target) {
if (DEBUG_IDS) {
System.out.println("binarySearch(), target: "+target);
}
// look for target value
while (start <= end) {
// is this the one we're looking for?
int middle = (start + end) / 2;
int value = values[middle];
if (DEBUG_IDS) {
System.out.print(" value: "+value+", target: "+target+"
print(values, start, end, middle, target);
}
if (value == target) {
while (middle > 0 && values[middle - 1] == target) {
middle
}
if (DEBUG_IDS) {
System.out.println("FOUND AT "+middle);
}
return middle;
}
// is this point higher or lower?
if (value > target) {
end = middle - 1;
}
else {
start = middle + 1;
}
} // while
// not found
if (DEBUG_IDS) {
System.out.println("NOT FOUND!");
}
return -1;
} // binarySearch(int[],int,int,int):int
// Private methods
private static final int[] INIT_ARRAY = new int[CHUNK_SIZE + 1];
static {
for (int i = 0; i < CHUNK_SIZE; i++) {
INIT_ARRAY[i] = -1;
}
}
/** Creates the specified chunk in the given array of chunks. */
private final void createChunk(int data[][], int chunk) {
data[chunk] = new int[CHUNK_SIZE + 1];
System.arraycopy(INIT_ARRAY, 0, data[chunk], 0, CHUNK_SIZE);
}
class RefCount {
int fCount;
}
private final void createChunk(Object data[][], int chunk) {
data[chunk] = new Object[CHUNK_SIZE + 1];
data[chunk][CHUNK_SIZE] = new RefCount();
}
/**
* Sets the specified value in the given of data at the chunk and index.
*
* @return Returns the old value.
*/
private final int setChunkIndex(int data[][], int value,
int chunk, int index) {
if (value == -1) {
return clearChunkIndex(data, chunk, index);
}
int ovalue = data[chunk][index];
if (ovalue == -1) {
data[chunk][CHUNK_SIZE]++;
}
data[chunk][index] = value;
return ovalue;
}
private final String setChunkValue(Object data[][], Object value,
int chunk, int index) {
if (value == null) {
return clearChunkValue(data, chunk, index);
}
String ovalue = (String) data[chunk][index];
if (ovalue == null) {
RefCount c = (RefCount) data[chunk][CHUNK_SIZE];
c.fCount++;
}
data[chunk][index] = value;
return ovalue;
}
/**
* Returns the specified value in the given data at the chunk and index.
*/
private final int getChunkIndex(int data[][], int chunk, int index) {
return data[chunk] != null ? data[chunk][index] : -1;
}
private final String getChunkValue(Object data[][], int chunk, int index) {
return data[chunk] != null ? (String) data[chunk][index] : null;
}
private final String getNodeValue(int chunk, int index) {
Object data = fNodeValue[chunk][index];
if (data == null){
return null;
}
else if (data instanceof String){
return (String)data;
}
else {
// type information
return data.toString();
}
}
/**
* Clears the specified value in the given data at the chunk and index.
* Note that this method will clear the given chunk if the reference
* count becomes zero.
*
* @return Returns the old value.
*/
private final int clearChunkIndex(int data[][], int chunk, int index) {
int value = data[chunk] != null ? data[chunk][index] : -1;
if (value != -1) {
data[chunk][CHUNK_SIZE]
data[chunk][index] = -1;
if (data[chunk][CHUNK_SIZE] == 0) {
data[chunk] = null;
}
}
return value;
}
private final String clearChunkValue(Object data[][],
int chunk, int index) {
String value = data[chunk] != null ? (String)data[chunk][index] : null;
if (value != null) {
data[chunk][index] = null;
RefCount c = (RefCount) data[chunk][CHUNK_SIZE];
c.fCount
if (c.fCount == 0) {
data[chunk] = null;
}
}
return value;
}
/**
* This version of putIdentifier is needed to avoid fluffing
* all of the paths to ID attributes when a node object is
* created that contains an ID attribute.
*/
private final void putIdentifier0(String idName, Element element) {
if (DEBUG_IDS) {
System.out.println("putIdentifier0("+
idName+", "+
element+')');
}
// create hashtable
if (identifiers == null) {
identifiers = new java.util.Hashtable();
}
// save ID and its associated element
identifiers.put(idName, element);
} // putIdentifier0(String,Element)
/** Prints the ID array. */
private static void print(int values[], int start, int end,
int middle, int target) {
if (DEBUG_IDS) {
System.out.print(start);
System.out.print(" [");
for (int i = start; i < end; i++) {
if (middle == i) {
System.out.print("!");
}
System.out.print(values[i]);
if (values[i] == target) {
System.out.print("*");
}
if (i < end - 1) {
System.out.print(" ");
}
}
System.out.println("] "+end);
}
} // print(int[],int,int,int,int)
// Classes
/**
* A simple integer vector.
*/
static class IntVector {
// Data
/** Data. */
private int data[];
/** Size. */
private int size;
// Public methods
/** Returns the length of this vector. */
public int size() {
return size;
}
/** Returns the element at the specified index. */
public int elementAt(int index) {
return data[index];
}
/** Appends an element to the end of the vector. */
public void addElement(int element) {
ensureCapacity(size + 1);
data[size++] = element;
}
/** Clears the vector. */
public void removeAllElements() {
size = 0;
}
// Private methods
/** Makes sure that there is enough storage. */
private void ensureCapacity(int newsize) {
if (data == null) {
data = new int[newsize + 15];
}
else if (newsize > data.length) {
int newdata[] = new int[newsize + 15];
System.arraycopy(data, 0, newdata, 0, data.length);
data = newdata;
}
} // ensureCapacity(int)
} // class IntVector
} // class DeferredDocumentImpl |
package org.andrey_bayev.htb_configurator.htb;
import java.util.Arrays;
/**
* This class allows you to change class bandwidth during the day or
* week
*/
public class TimeRange
{
private boolean daysOfWeak[];
private boolean always;//if you don't use daysOfWeak
private String time;
private Bandwidth rate;
private Bandwidth ceil;
private SpeedInBytes burst;
private SpeedInBytes cburst;
private String comment;
public TimeRange(String timeRange, String comment)
{
// todo: regex again!
this.comment = comment;
daysOfWeak = new boolean[7];
String parts[] = timeRange.split(";");
String timePart = parts[0];
String bandWidthPart = parts[1];
if (timePart.charAt(2) == ':')
{
always = true;
time = timePart;
} else
{
parts = timePart.split("/");
int days = Integer.parseInt(parts[0]);
while (days > 0)
{
daysOfWeak[days % 10] = true;
days /= 10;
}
time = parts[1];
}
parts = bandWidthPart.split(",");
String partOfTimeWithRate = parts[0];
String partOfTimeWithCeil = (parts.length == 2) ? parts[1] : "";
String rat[] = partOfTimeWithRate.split("/");
rate = new Bandwidth(rat[0]);
if (rat.length == 2)
{
burst = Transformations.fromStringToSpeedInBytes(rat[1]);
} else
{
burst.setSpeed(0);
burst.setUnit(Unit.BPS);
}
if (partOfTimeWithCeil != "")
{
String partsOfCeil[] = partOfTimeWithCeil.split("/");
ceil = new Bandwidth(partsOfCeil[0]);
if (partsOfCeil.length == 2)
{
cburst = Transformations.fromStringToSpeedInBytes(partsOfCeil[1]);
} else
{
cburst.setSpeed(0);
cburst.setUnit(Unit.BPS);
}
} else
{
ceil = null;
cburst.setSpeed(0);
cburst.setUnit(Unit.BPS);
}
}
public boolean[] getDaysOfWeak()
{
return daysOfWeak;
}
public void setDaysOfWeak(boolean[] daysOfWeak)
{
this.daysOfWeak = daysOfWeak;
}
public String getTime()
{
return time;
}
public void setTime(String time)
{
this.time = time;
}
public Bandwidth getRate()
{
return rate;
}
public void setRate(Bandwidth rate)
{
this.rate = rate;
}
public Bandwidth getCeil()
{
return ceil;
}
public void setCeil(Bandwidth ceil)
{
this.ceil = ceil;
}
public SpeedInBytes getBurst()
{
return burst;
}
public void setBurst(SpeedInBytes burst)
{
this.burst = burst;
}
public SpeedInBytes getCburst()
{
return cburst;
}
public void setCburst(SpeedInBytes cburst)
{
this.cburst = cburst;
}
public boolean isAlways()
{
return always;
}
public void setAlways(boolean always)
{
this.always = always;
}
public String getComment()
{
return comment;
}
public void setComment(String comment)
{
this.comment = comment;
}
public String toString()
{
String t = "";
if (!always)
{
for (int i = 0; i <= 6; i++)
{
if (daysOfWeak[i]) t += i;
}
t = t + '/';
}
t += time + ';';
t += rate.getSpeed() + Transformations.fromUnitToString(rate.getUnit());
if (burst.getSpeed() != 0)
{
t += '/' + Transformations.fromSpeedInBytesToString(burst);
}
if (ceil != null)
{
t += ',' + ceil.getSpeed() + Transformations.fromUnitToString(ceil.getUnit());
if (cburst.getSpeed() != 0)
{
t += '/' + Transformations.fromSpeedInBytesToString(cburst);
}
}
return t;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TimeRange timeRange = (TimeRange) o;
if (always != timeRange.always) return false;
if (burst != null ? !burst.equals(timeRange.burst) : timeRange.burst != null) return false;
if (cburst != null ? !cburst.equals(timeRange.cburst) : timeRange.cburst != null) return false;
if (ceil != null ? !ceil.equals(timeRange.ceil) : timeRange.ceil != null) return false;
if (!Arrays.equals(daysOfWeak, timeRange.daysOfWeak)) return false;
if (rate != null ? !rate.equals(timeRange.rate) : timeRange.rate != null) return false;
if (time != null ? !time.equals(timeRange.time) : timeRange.time != null) return false;
return true;
}
@Override
public int hashCode() {
int result = daysOfWeak != null ? Arrays.hashCode(daysOfWeak) : 0;
result = 31 * result + (always ? 1 : 0);
result = 31 * result + (time != null ? time.hashCode() : 0);
result = 31 * result + (rate != null ? rate.hashCode() : 0);
result = 31 * result + (ceil != null ? ceil.hashCode() : 0);
result = 31 * result + (burst != null ? burst.hashCode() : 0);
result = 31 * result + (cburst != null ? cburst.hashCode() : 0);
return result;
}
} |
package org.bouncycastle.crypto.digests;
import org.bouncycastle.crypto.ExtendedDigest;
import org.bouncycastle.util.Arrays;
public class SHA3Digest
implements ExtendedDigest
{
private static long[] KeccakRoundConstants = keccakInitializeRoundConstants();
private static int[] KeccakRhoOffsets = keccakInitializeRhoOffsets();
private static long[] keccakInitializeRoundConstants()
{
long[] keccakRoundConstants = new long[24];
byte[] LFSRstate = new byte[1];
LFSRstate[0] = 0x01;
int i, j, bitPosition;
for (i = 0; i < 24; i++)
{
keccakRoundConstants[i] = 0;
for (j = 0; j < 7; j++)
{
bitPosition = (1 << j) - 1;
if (LFSR86540(LFSRstate))
{
keccakRoundConstants[i] ^= 1L << bitPosition;
}
}
}
return keccakRoundConstants;
}
private static boolean LFSR86540(byte[] LFSR)
{
boolean result = (((LFSR[0]) & 0x01) != 0);
if (((LFSR[0]) & 0x80) != 0)
{
LFSR[0] = (byte)(((LFSR[0]) << 1) ^ 0x71);
}
else
{
LFSR[0] <<= 1;
}
return result;
}
private static int[] keccakInitializeRhoOffsets()
{
int[] keccakRhoOffsets = new int[25];
int x, y, t, newX, newY;
keccakRhoOffsets[(((0) % 5) + 5 * ((0) % 5))] = 0;
x = 1;
y = 0;
for (t = 0; t < 24; t++)
{
keccakRhoOffsets[(((x) % 5) + 5 * ((y) % 5))] = ((t + 1) * (t + 2) / 2) % 64;
newX = (0 * x + 1 * y) % 5;
newY = (2 * x + 3 * y) % 5;
x = newX;
y = newY;
}
return keccakRhoOffsets;
}
private byte[] state = new byte[(1600 / 8)];
private byte[] dataQueue = new byte[(1536 / 8)];
private int rate;
private int capacity;
private int bitsInQueue;
private int fixedOutputLength;
private boolean squeezing;
private int bitsAvailableForSqueezing;
private byte[] chunk;
private byte[] oneByte;
private void clearDataQueueSection(int off, int len)
{
for (int i = off; i != off + len; i++)
{
dataQueue[i] = 0;
}
}
public SHA3Digest()
{
init(0);
}
public SHA3Digest(int bitLength)
{
init(bitLength);
}
public String getAlgorithmName()
{
return "SHA3-" + fixedOutputLength;
}
public int getDigestSize()
{
return fixedOutputLength / 8;
}
public void update(byte in)
{
oneByte[0] = in;
doUpdate(oneByte, 0, 8L);
}
public void update(byte[] in, int inOff, int len)
{
doUpdate(in, inOff, len * 8L);
}
public int doFinal(byte[] out, int outOff)
{
doFinal(out);
reset();
return getDigestSize();
}
public void reset()
{
init(fixedOutputLength);
}
/**
* Return the size of block that the compression function is applied to in bytes.
*
* @return internal byte length of a block.
*/
public int getByteLength()
{
return rate / 8;
}
private void init(int bitLength)
{
switch (bitLength)
{
case 0:
case 288:
initSponge(1024, 576);
break;
case 224:
initSponge(1152, 448);
break;
case 256:
initSponge(1088, 512);
break;
case 384:
initSponge(832, 768);
break;
case 512:
initSponge(576, 1024);
break;
default:
throw new IllegalArgumentException("bitLength must be one of 224, 256, 384, or 512.");
}
}
private void doUpdate(byte[] data, int off, long databitlen)
{
if ((databitlen % 8) == 0)
{
absorb(data, off, databitlen);
}
else
{
absorb(data, off, databitlen - (databitlen % 8));
byte[] lastByte = new byte[1];
lastByte[0] = (byte)(data[off + (int)(databitlen / 8)] >> (8 - (databitlen % 8)));
absorb(lastByte, off, databitlen % 8);
}
}
private void doFinal(byte[] hashval)
{
squeeze(hashval, fixedOutputLength);
}
private void initSponge(int rate, int capacity)
{
if (rate + capacity != 1600)
{
throw new IllegalStateException("rate + capacity != 1600");
}
if ((rate <= 0) || (rate >= 1600) || ((rate % 64) != 0))
{
throw new IllegalStateException("invalid rate value");
}
this.rate = rate;
this.capacity = capacity;
this.fixedOutputLength = 0;
Arrays.fill(this.state, (byte)0);
Arrays.fill(this.dataQueue, (byte)0);
this.bitsInQueue = 0;
this.squeezing = false;
this.bitsAvailableForSqueezing = 0;
this.fixedOutputLength = capacity / 2;
this.chunk = new byte[rate / 8];
this.oneByte = new byte[1];
}
private void absorbQueue()
{
KeccakAbsorb(state, dataQueue, rate / 8);
bitsInQueue = 0;
}
private void absorb(byte[] data, int off, long databitlen)
{
long i, j, wholeBlocks;
if ((bitsInQueue % 8) != 0)
{
throw new IllegalStateException("attempt to absorb with odd length queue.");
}
if (squeezing)
{
throw new IllegalStateException("attempt to absorb while squeezing.");
}
i = 0;
while (i < databitlen)
{
if ((bitsInQueue == 0) && (databitlen >= rate) && (i <= (databitlen - rate)))
{
wholeBlocks = (databitlen - i) / rate;
for (j = 0; j < wholeBlocks; j++)
{
System.arraycopy(data, (int)(off + (i / 8) + (j * chunk.length)), chunk, 0, chunk.length);
// displayIntermediateValues.displayBytes(1, "Block to be absorbed", curData, rate / 8);
KeccakAbsorb(state, chunk, chunk.length);
}
i += wholeBlocks * rate;
}
else
{
int partialBlock = (int)(databitlen - i);
if (partialBlock + bitsInQueue > rate)
{
partialBlock = rate - bitsInQueue;
}
int partialByte = partialBlock % 8;
partialBlock -= partialByte;
System.arraycopy(data, off + (int)(i / 8), dataQueue, bitsInQueue / 8, partialBlock / 8);
bitsInQueue += partialBlock;
i += partialBlock;
if (bitsInQueue == rate)
{
absorbQueue();
}
if (partialByte > 0)
{
int mask = (1 << partialByte) - 1;
dataQueue[bitsInQueue / 8] = (byte)(data[off + ((int)(i / 8))] & mask);
bitsInQueue += partialByte;
i += partialByte;
}
}
}
}
private void padAndSwitchToSqueezingPhase()
{
if (bitsInQueue + 1 == rate)
{
dataQueue[bitsInQueue / 8] |= 1 << (bitsInQueue % 8);
absorbQueue();
clearDataQueueSection(0, rate / 8);
}
else
{
clearDataQueueSection((bitsInQueue + 7) / 8, rate / 8 - (bitsInQueue + 7) / 8);
dataQueue[bitsInQueue / 8] |= 1 << (bitsInQueue % 8);
}
dataQueue[(rate - 1) / 8] |= 1 << ((rate - 1) % 8);
absorbQueue();
if (rate == 1024)
{
KeccakExtract1024bits(state, dataQueue);
bitsAvailableForSqueezing = 1024;
}
else
{
KeccakExtract(state, dataQueue, rate / 64);
bitsAvailableForSqueezing = rate;
}
// displayIntermediateValues.displayBytes(1, "Block available for squeezing", dataQueue, bitsAvailableForSqueezing / 8);
squeezing = true;
}
private void squeeze(byte[] output, long outputLength)
{
long i;
int partialBlock;
if (!squeezing)
{
padAndSwitchToSqueezingPhase();
}
if ((outputLength % 8) != 0)
{
throw new IllegalStateException("outputLength not a multiple of 8");
}
i = 0;
while (i < outputLength)
{
if (bitsAvailableForSqueezing == 0)
{
keccakPermutation(state);
if (rate == 1024)
{
KeccakExtract1024bits(state, dataQueue);
bitsAvailableForSqueezing = 1024;
}
else
{
KeccakExtract(state, dataQueue, rate / 64);
bitsAvailableForSqueezing = rate;
}
// displayIntermediateValues.displayBytes(1, "Block available for squeezing", dataQueue, bitsAvailableForSqueezing / 8);
}
partialBlock = bitsAvailableForSqueezing;
if ((long)partialBlock > outputLength - i)
{
partialBlock = (int)(outputLength - i);
}
System.arraycopy(dataQueue, (rate - bitsAvailableForSqueezing) / 8, output, (int)(i / 8), partialBlock / 8);
bitsAvailableForSqueezing -= partialBlock;
i += partialBlock;
}
}
private void fromBytesToWords(long[] stateAsWords, byte[] state)
{
for (int i = 0; i < (1600 / 64); i++)
{
stateAsWords[i] = 0;
int index = i * (64 / 8);
for (int j = 0; j < (64 / 8); j++)
{
stateAsWords[i] |= ((long)state[index + j] & 0xff) << ((8 * j));
}
}
}
private void fromWordsToBytes(byte[] state, long[] stateAsWords)
{
for (int i = 0; i < (1600 / 64); i++)
{
int index = i * (64 / 8);
for (int j = 0; j < (64 / 8); j++)
{
state[index + j] = (byte)((stateAsWords[i] >>> ((8 * j))) & 0xFF);
}
}
}
private void keccakPermutation(byte[] state)
{
long[] longState = new long[state.length / 8];
fromBytesToWords(longState, state);
// displayIntermediateValues.displayStateAsBytes(1, "Input of permutation", longState);
keccakPermutationOnWords(longState);
// displayIntermediateValues.displayStateAsBytes(1, "State after permutation", longState);
fromWordsToBytes(state, longState);
}
private void keccakPermutationAfterXor(byte[] state, byte[] data, int dataLengthInBytes)
{
int i;
for (i = 0; i < dataLengthInBytes; i++)
{
state[i] ^= data[i];
}
keccakPermutation(state);
}
private void keccakPermutationOnWords(long[] state)
{
int i;
// displayIntermediateValues.displayStateAs64bitWords(3, "Same, with lanes as 64-bit words", state);
for (i = 0; i < 24; i++)
{
// displayIntermediateValues.displayRoundNumber(3, i);
theta(state);
// displayIntermediateValues.displayStateAs64bitWords(3, "After theta", state);
rho(state);
// displayIntermediateValues.displayStateAs64bitWords(3, "After rho", state);
pi(state);
// displayIntermediateValues.displayStateAs64bitWords(3, "After pi", state);
chi(state);
// displayIntermediateValues.displayStateAs64bitWords(3, "After chi", state);
iota(state, i);
// displayIntermediateValues.displayStateAs64bitWords(3, "After iota", state);
}
}
long[] C = new long[5];
private void theta(long[] A)
{
for (int x = 0; x < 5; x++)
{
C[x] = 0;
for (int y = 0; y < 5; y++)
{
C[x] ^= A[x + 5 * y];
}
}
for (int x = 0; x < 5; x++)
{
long dX = ((((C[(x + 1) % 5]) << 1) ^ ((C[(x + 1) % 5]) >>> (64 - 1)))) ^ C[(x + 4) % 5];
for (int y = 0; y < 5; y++)
{
A[x + 5 * y] ^= dX;
}
}
}
private void rho(long[] A)
{
for (int x = 0; x < 5; x++)
{
for (int y = 0; y < 5; y++)
{
int index = x + 5 * y;
A[index] = ((KeccakRhoOffsets[index] != 0) ? (((A[index]) << KeccakRhoOffsets[index]) ^ ((A[index]) >>> (64 - KeccakRhoOffsets[index]))) : A[index]);
}
}
}
long[] tempA = new long[25];
private void pi(long[] A)
{
System.arraycopy(A, 0, tempA, 0, tempA.length);
for (int x = 0; x < 5; x++)
{
for (int y = 0; y < 5; y++)
{
A[y + 5 * ((2 * x + 3 * y) % 5)] = tempA[x + 5 * y];
}
}
}
long[] chiC = new long[5];
private void chi(long[] A)
{
for (int y = 0; y < 5; y++)
{
for (int x = 0; x < 5; x++)
{
chiC[x] = A[x + 5 * y] ^ ((~A[(((x + 1) % 5) + 5 * y)]) & A[(((x + 2) % 5) + 5 * y)]);
}
for (int x = 0; x < 5; x++)
{
A[x + 5 * y] = chiC[x];
}
}
}
private void iota(long[] A, int indexRound)
{
A[(((0) % 5) + 5 * ((0) % 5))] ^= KeccakRoundConstants[indexRound];
}
private void KeccakAbsorb(byte[] state, byte[] data, int dataInBytes)
{
keccakPermutationAfterXor(state, data, dataInBytes);
}
private void KeccakExtract1024bits(byte[] state, byte[] data)
{
System.arraycopy(state, 0, data, 0, 128);
}
private void KeccakExtract(byte[] state, byte[] data, int laneCount)
{
System.arraycopy(state, 0, data, 0, laneCount * 8);
}
} |
package org.bouncycastle.crypto.tls;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.Enumeration;
import java.util.Hashtable;
import org.bouncycastle.util.Integers;
public class DTLSProtocolHandler {
private static final Integer EXT_RenegotiationInfo = Integers
.valueOf(ExtensionType.renegotiation_info);
private static final byte[] EMPTY_BYTES = new byte[0];
private final SecureRandom secureRandom;
public DTLSProtocolHandler(SecureRandom secureRandom) {
if (secureRandom == null)
throw new IllegalArgumentException("'secureRandom' cannot be null");
this.secureRandom = secureRandom;
}
public DTLSTransport connect(TlsClient client, DatagramTransport transport) throws IOException {
if (client == null)
throw new IllegalArgumentException("'client' cannot be null");
if (transport == null)
throw new IllegalArgumentException("'transport' cannot be null");
TlsClientContextImpl clientContext = createClientContext();
client.init(clientContext);
DTLSRecordLayer recordLayer = new DTLSRecordLayer(transport, clientContext,
ContentType.handshake);
DTLSReliableHandshake handshake = new DTLSReliableHandshake(recordLayer);
byte[] clientHello = generateClientHello(clientContext, client);
handshake.sendMessage(HandshakeType.client_hello, clientHello);
DTLSReliableHandshake.Message serverHello = handshake.receiveMessage();
// NOTE: After receiving a record from the server, we discover the version it chose
ProtocolVersion server_version = recordLayer.getDiscoveredServerVersion();
if (server_version.getFullVersion() < clientContext.getClientVersion().getFullVersion()) {
// TODO Alert
}
clientContext.setServerVersion(server_version);
client.notifyServerVersion(server_version);
if (serverHello.getType() == HandshakeType.hello_verify_request) {
byte[] cookie = parseHelloVerifyRequest(clientContext, serverHello.getBody());
byte[] patched = patchClientHelloWithCookie(clientHello, cookie);
handshake.sendMessage(HandshakeType.client_hello, patched);
serverHello = handshake.receiveMessage();
}
if (serverHello.getType() != HandshakeType.server_hello) {
// TODO Alert
}
// TODO Lots more handshake messages...
handshake.finish();
// TODO Needs to be attached to the record layer using ContentType.application_data
return new DTLSTransport(recordLayer);
}
private void assertEmpty(ByteArrayInputStream is) throws IOException {
if (is.available() > 0) {
// throw new TlsFatalAlert(AlertDescription.decode_error);
// TODO ALert
}
}
private TlsClientContextImpl createClientContext() {
SecurityParameters securityParameters = new SecurityParameters();
securityParameters.clientRandom = new byte[32];
secureRandom.nextBytes(securityParameters.clientRandom);
TlsUtils.writeGMTUnixTime(securityParameters.clientRandom, 0);
return new TlsClientContextImpl(secureRandom, securityParameters);
}
private byte[] generateClientHello(TlsClientContextImpl clientContext, TlsClient client)
throws IOException {
ByteArrayOutputStream buf = new ByteArrayOutputStream();
ProtocolVersion client_version = client.getClientVersion();
if (!client_version.isDTLS()) {
// TODO Alert
}
clientContext.setClientVersion(client_version);
TlsUtils.writeVersion(client_version, buf);
buf.write(clientContext.getSecurityParameters().getClientRandom());
// Length of Session id
TlsUtils.writeUint8((short) 0, buf);
// Length of cookie
TlsUtils.writeUint8((short) 0, buf);
/*
* Cipher suites
*/
int[] offeredCipherSuites = client.getCipherSuites();
for (int cipherSuite : offeredCipherSuites) {
switch (cipherSuite) {
case CipherSuite.TLS_RSA_EXPORT_WITH_RC4_40_MD5:
case CipherSuite.TLS_RSA_WITH_RC4_128_MD5:
case CipherSuite.TLS_RSA_WITH_RC4_128_SHA:
case CipherSuite.TLS_DH_anon_EXPORT_WITH_RC4_40_MD5:
case CipherSuite.TLS_DH_anon_WITH_RC4_128_MD5:
case CipherSuite.TLS_PSK_WITH_RC4_128_SHA:
case CipherSuite.TLS_DHE_PSK_WITH_RC4_128_SHA:
case CipherSuite.TLS_RSA_PSK_WITH_RC4_128_SHA:
case CipherSuite.TLS_ECDH_ECDSA_WITH_RC4_128_SHA:
case CipherSuite.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA:
case CipherSuite.TLS_ECDH_RSA_WITH_RC4_128_SHA:
case CipherSuite.TLS_ECDHE_RSA_WITH_RC4_128_SHA:
case CipherSuite.TLS_ECDH_anon_WITH_RC4_128_SHA:
// TODO Alert
throw new IllegalStateException(
"Client offered an RC4 cipher suite: RC4 MUST NOT be used with DTLS");
}
}
// Integer -> byte[]
Hashtable clientExtensions = client.getClientExtensions();
// Cipher Suites (and SCSV)
{
/*
* RFC 5746 3.4. The client MUST include either an empty "renegotiation_info" extension,
* or the TLS_EMPTY_RENEGOTIATION_INFO_SCSV signaling cipher suite value in the
* ClientHello. Including both is NOT RECOMMENDED.
*/
boolean noRenegExt = clientExtensions == null
|| clientExtensions.get(EXT_RenegotiationInfo) == null;
int count = offeredCipherSuites.length;
if (noRenegExt) {
// Note: 1 extra slot for TLS_EMPTY_RENEGOTIATION_INFO_SCSV
++count;
}
TlsUtils.writeUint16(2 * count, buf);
TlsUtils.writeUint16Array(offeredCipherSuites, buf);
if (noRenegExt) {
TlsUtils.writeUint16(CipherSuite.TLS_EMPTY_RENEGOTIATION_INFO_SCSV, buf);
}
}
// Compression methods
short[] offeredCompressionMethods = client.getCompressionMethods();
TlsUtils.writeUint8((short) offeredCompressionMethods.length, buf);
TlsUtils.writeUint8Array(offeredCompressionMethods, buf);
// Extensions
if (clientExtensions != null) {
ByteArrayOutputStream ext = new ByteArrayOutputStream();
Enumeration keys = clientExtensions.keys();
while (keys.hasMoreElements()) {
Integer extType = (Integer) keys.nextElement();
TlsProtocolHandler.writeExtension(ext, extType,
(byte[]) clientExtensions.get(extType));
}
TlsUtils.writeOpaque16(ext.toByteArray(), buf);
}
return buf.toByteArray();
}
private byte[] parseHelloVerifyRequest(TlsClientContextImpl clientContext, byte[] body)
throws IOException {
ByteArrayInputStream buf = new ByteArrayInputStream(body);
ProtocolVersion server_version = TlsUtils.readVersion(buf);
if (!server_version.equals(clientContext.getServerVersion())) {
// TODO Alert
}
byte[] cookie = TlsUtils.readOpaque8(buf);
assertEmpty(buf);
if (cookie.length < 1 || cookie.length > 32) {
// TODO Alert
}
return cookie;
}
private byte[] patchClientHelloWithCookie(byte[] clientHello, byte[] cookie) throws IOException {
int sessionIDPos = 34;
int sessionIDLength = TlsUtils.readUint8(clientHello, sessionIDPos);
int cookieLengthPos = sessionIDPos + 1 + sessionIDLength;
int cookiePos = cookieLengthPos + 1;
byte[] patched = new byte[clientHello.length + cookie.length];
System.arraycopy(clientHello, 0, patched, 0, cookieLengthPos);
TlsUtils.writeUint8((short) cookie.length, patched, cookieLengthPos);
System.arraycopy(cookie, 0, patched, cookiePos, cookie.length);
System.arraycopy(clientHello, cookiePos, patched, cookiePos + cookie.length,
clientHello.length - cookiePos);
return patched;
}
} |
package org.exist.xquery.functions.util;
import org.exist.dom.QName;
import org.exist.xquery.AbstractInternalModule;
import org.exist.xquery.FunctionDef;
import org.exist.xquery.XPathException;
import org.exist.xquery.functions.inspect.InspectFunction;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* Module function definitions for util module.
*
* @author Wolfgang Meier (wolfgang@exist-db.org)
* @author ljo
* @author Andrzej Taramina (andrzej@chaeron.com)
*/
public class UtilModule extends AbstractInternalModule
{
public final static String NAMESPACE_URI = "http://exist-db.org/xquery/util";
public final static String PREFIX = "util";
public final static String INCLUSION_DATE = "2004-09-12";
public final static String RELEASED_IN_VERSION = "pre eXist-1.0";
public final static FunctionDef[] functions = {
new FunctionDef( BuiltinFunctions.signatures[0], BuiltinFunctions.class ),
new FunctionDef( BuiltinFunctions.signatures[1], BuiltinFunctions.class ),
new FunctionDef( BuiltinFunctions.signatures[2], BuiltinFunctions.class ),
new FunctionDef( BuiltinFunctions.signatures[3], BuiltinFunctions.class ),
new FunctionDef( BuiltinFunctions.signatures[4], BuiltinFunctions.class ),
new FunctionDef(InspectFunction.SIGNATURE_DEPRECATED, InspectFunction.class),
new FunctionDef( ModuleInfo.moduleDescriptionSig, ModuleInfo.class ),
new FunctionDef( ModuleInfo.registeredModuleSig, ModuleInfo.class ),
new FunctionDef( ModuleInfo.registeredModulesSig, ModuleInfo.class ),
new FunctionDef( ModuleInfo.mapModuleSig, ModuleInfo.class ),
new FunctionDef( ModuleInfo.unmapModuleSig, ModuleInfo.class ),
new FunctionDef( ModuleInfo.mappedModuleSig, ModuleInfo.class ),
new FunctionDef( ModuleInfo.mappedModulesSig, ModuleInfo.class ),
new FunctionDef( ModuleInfo.moduleInfoSig, ModuleInfo.class ),
new FunctionDef( ModuleInfo.moduleInfoWithURISig, ModuleInfo.class ),
new FunctionDef( Expand.signatures[0], Expand.class ),
new FunctionDef( Expand.signatures[1], Expand.class ),
new FunctionDef( DescribeFunction.signature, DescribeFunction.class ),
new FunctionDef( FunDoctype.signature, FunDoctype.class ),
new FunctionDef( Eval.signatures[0], Eval.class ),
new FunctionDef( Eval.signatures[1], Eval.class ),
new FunctionDef( Eval.signatures[2], Eval.class ),
new FunctionDef( Eval.signatures[3], Eval.class ),
new FunctionDef( Eval.signatures[4], Eval.class ),
new FunctionDef( Eval.signatures[5], Eval.class ),
new FunctionDef( Eval.signatures[6], Eval.class ),
new FunctionDef( Eval.signatures[7], Eval.class ),
new FunctionDef( Compile.signatures[0], Compile.class ),
new FunctionDef( Compile.signatures[1], Compile.class ),
new FunctionDef( Compile.signatures[2], Compile.class ),
new FunctionDef( DocumentNameOrId.docIdSignature, DocumentNameOrId.class ),
new FunctionDef( DocumentNameOrId.docNameSignature, DocumentNameOrId.class ),
new FunctionDef( DocumentNameOrId.absoluteResourceIdSignature, DocumentNameOrId.class ),
new FunctionDef( DocumentNameOrId.resourceByAbsoluteIdSignature, DocumentNameOrId.class ),
new FunctionDef( CollectionName.signature, CollectionName.class ),
new FunctionDef( LogFunction.signatures[0], LogFunction.class ),
new FunctionDef( LogFunction.signatures[1], LogFunction.class ),
new FunctionDef( LogFunction.signatures[2], LogFunction.class ),
new FunctionDef( LogFunction.signatures[3], LogFunction.class ),
new FunctionDef( CatchFunction.signature, CatchFunction.class ),
new FunctionDef( ExclusiveLockFunction.signature, ExclusiveLockFunction.class ),
new FunctionDef( SharedLockFunction.signature, SharedLockFunction.class ),
new FunctionDef( Collations.signature, Collations.class ),
new FunctionDef( SystemProperty.signature, SystemProperty.class ),
new FunctionDef( FunctionFunction.signature, FunctionFunction.class ),
new FunctionDef( CallFunction.signature, CallFunction.class ),
new FunctionDef( NodeId.signature, NodeId.class ),
new FunctionDef( GetNodeById.signature, GetNodeById.class ),
new FunctionDef( IndexKeys.signatures[0], IndexKeys.class ),
new FunctionDef( IndexKeys.signatures[1], IndexKeys.class ),
new FunctionDef( IndexKeys.signatures[2], IndexKeys.class ),
new FunctionDef( IndexKeyOccurrences.signatures[0], IndexKeyOccurrences.class ),
new FunctionDef( IndexKeyOccurrences.signatures[1], IndexKeyOccurrences.class ),
new FunctionDef( IndexKeyDocuments.signatures[0], IndexKeyDocuments.class ),
new FunctionDef( IndexKeyDocuments.signatures[1], IndexKeyDocuments.class ),
new FunctionDef( IndexType.signature, IndexType.class ),
new FunctionDef( QNameIndexLookup.signature, QNameIndexLookup.class ),
new FunctionDef( Serialize.signatures[0], Serialize.class ),
new FunctionDef( Serialize.signatures[1], Serialize.class ),
new FunctionDef( BinaryDoc.signatures[0], BinaryDoc.class ),
new FunctionDef( BinaryDoc.signatures[1], BinaryDoc.class ),
new FunctionDef( BinaryDoc.signatures[2], BinaryDoc.class ),
new FunctionDef( BinaryToString.signatures[0], BinaryToString.class ),
new FunctionDef( BinaryToString.signatures[1], BinaryToString.class ),
new FunctionDef( BinaryToString.signatures[2], BinaryToString.class ),
new FunctionDef( BinaryToString.signatures[3], BinaryToString.class ),
new FunctionDef( Profile.signatures[0], Profile.class ),
new FunctionDef( Profile.signatures[1], Profile.class ),
new FunctionDef( PrologFunctions.signatures[0], PrologFunctions.class ),
new FunctionDef( PrologFunctions.signatures[1], PrologFunctions.class ),
new FunctionDef( PrologFunctions.signatures[2], PrologFunctions.class ),
new FunctionDef( PrologFunctions.signatures[3], PrologFunctions.class ),
new FunctionDef( SystemTime.signatures[0], SystemTime.class ),
new FunctionDef( SystemTime.signatures[1], SystemTime.class ),
new FunctionDef( SystemTime.signatures[2], SystemTime.class ),
new FunctionDef( RandomFunction.signatures[0], RandomFunction.class ),
new FunctionDef( RandomFunction.signatures[1], RandomFunction.class ),
new FunctionDef( RandomFunction.signatures[2], RandomFunction.class ),
new FunctionDef( FunUnEscapeURI.signature, FunUnEscapeURI.class ),
new FunctionDef( UUID.signatures[0], UUID.class ),
new FunctionDef( UUID.signatures[1], UUID.class ),
new FunctionDef( DeepCopyFunction.signature, DeepCopyFunction.class ),
new FunctionDef( GetSequenceType.signature, GetSequenceType.class ),
new FunctionDef( Parse.signatures[0], Parse.class ),
new FunctionDef( Parse.signatures[1], Parse.class ),
new FunctionDef( NodeXPath.signature, NodeXPath.class ),
new FunctionDef( Hash.signatures[0], Hash.class ),
new FunctionDef( Hash.signatures[1], Hash.class ),
new FunctionDef( GetFragmentBetween.signature, GetFragmentBetween.class ),
new FunctionDef( BaseConverter.signatures[0], BaseConverter.class ),
new FunctionDef( BaseConverter.signatures[1], BaseConverter.class ),
new FunctionDef( Wait.signatures[0], Wait.class ),
new FunctionDef( Base64Functions.signatures[0], Base64Functions.class ),
new FunctionDef( Base64Functions.signatures[1], Base64Functions.class ),
new FunctionDef( Base64Functions.signatures[2], Base64Functions.class )
};
static {
Arrays.sort( functions, new FunctionComparator() );
}
public final static QName EXCEPTION_QNAME = new QName( "exception", UtilModule.NAMESPACE_URI, UtilModule.PREFIX );
public final static QName EXCEPTION_MESSAGE_QNAME = new QName( "exception-message", UtilModule.NAMESPACE_URI, UtilModule.PREFIX );
public UtilModule(Map<String, List<? extends Object>> parameters) throws XPathException
{
super( functions, parameters, true );
declareVariable( EXCEPTION_QNAME, null );
declareVariable( EXCEPTION_MESSAGE_QNAME, null );
}
/* (non-Javadoc)
* @see org.exist.xquery.Module#getDescription()
*/
public String getDescription()
{
return( "A module for various utility extension functions." );
}
/* (non-Javadoc)
* @see org.exist.xquery.Module#getNamespaceURI()
*/
public String getNamespaceURI()
{
return( NAMESPACE_URI );
}
/* (non-Javadoc)
* @see org.exist.xquery.Module#getDefaultPrefix()
*/
public String getDefaultPrefix()
{
return( PREFIX );
}
public String getReleaseVersion()
{
return( RELEASED_IN_VERSION );
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.