answer stringlengths 17 10.2M |
|---|
package org.embulk.filter.join_file;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Maps;
import org.embulk.config.Config;
import org.embulk.config.ConfigDefault;
import org.embulk.config.ConfigSource;
import org.embulk.config.Task;
import org.embulk.config.TaskSource;
import org.embulk.spi.Column;
import org.embulk.spi.ColumnConfig;
import org.embulk.spi.Exec;
import org.embulk.spi.FilterPlugin;
import org.embulk.spi.PageOutput;
import org.embulk.spi.Schema;
import org.embulk.spi.time.TimestampParser;
import org.embulk.spi.type.Types;
import org.joda.time.DateTimeZone;
import org.slf4j.Logger;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class JoinFileFilterPlugin
implements FilterPlugin
{
private static final Logger logger = Exec.getLogger(JoinFileFilterPlugin.class);
public interface PluginTask
extends Task, TimestampParser.Task
{
@Config("base_column")
ColumnConfig getBaseColumn();
@Config("counter_column")
@ConfigDefault("{name: id, type: long}")
ColumnConfig getCounterColumn();
@Config("joined_column_prefix")
@ConfigDefault("\"_joined_by_embulk_\"")
String getJoinedColumnPrefix();
@Config("file_path")
String getFilePath();
@Config("file_format")
String getFileFormat();
@Config("columns")
List<ColumnConfig> getColumns();
@Config("time_zone")
@ConfigDefault("\"UTC\"")
String getTimeZone();
HashMap<String, HashMap<String, String>> getTable();
void setTable(HashMap<String, HashMap<String, String>> jsonTable);
}
@Override
public void transaction(ConfigSource config, Schema inputSchema,
FilterPlugin.Control control)
{
PluginTask task = config.loadConfig(PluginTask.class);
try {
TableBuilder tableBuilder = new TableBuilder(
task.getFilePath(),
task.getFileFormat(),
task.getColumns(),
task.getCounterColumn().getName(),
task.getJoinedColumnPrefix());
task.setTable(tableBuilder.build());
}
catch (IOException e) {
logger.error(e.getMessage());
throw new RuntimeException(e);
}
Schema outputSchema = buildOutputSchema(inputSchema, task.getColumns(), task.getJoinedColumnPrefix());
logger.info("output schema: {}", outputSchema);
control.run(task.dump(), outputSchema);
}
@Override
public PageOutput open(TaskSource taskSource, Schema inputSchema,
Schema outputSchema, PageOutput output)
{
PluginTask task = taskSource.loadTask(PluginTask.class);
// create joinColumns/baseColumn
final List<Column> outputColumns = outputSchema.getColumns();
final List<Column> inputColumns = inputSchema.getColumns();
Map<String, Column> inputColumnMap = Maps.newHashMap();
final List<Column> joinColumns = new ArrayList<>();
for (Column column : outputColumns) {
if (!inputColumns.contains(column)) {
joinColumns.add(column);
} else {
inputColumnMap.put(column.getName(), column);
}
}
final Column baseColumn = inputColumnMap.get(task.getBaseColumn().getName());
final HashMap<String, TimestampParser> timestampParserMap = buildTimestampParserMap(
task.getColumns(),
task.getJoinedColumnPrefix(),
task.getTimeZone());
return new JoinFilePageOutput(inputSchema, outputSchema, baseColumn, task.getTable(), joinColumns, timestampParserMap, output);
}
private Schema buildOutputSchema(Schema inputSchema, List<ColumnConfig> columns, String joinedColumnPrefix)
{
ImmutableList.Builder<Column> builder = ImmutableList.builder();
int i = 0; // columns index
for (Column inputColumn: inputSchema.getColumns()) {
Column outputColumn = new Column(i++, inputColumn.getName(), inputColumn.getType());
builder.add(outputColumn);
}
for (ColumnConfig columnConfig: columns) {
String columnName = joinedColumnPrefix + columnConfig.getName();
builder.add(new Column(i++, columnName, columnConfig.getType()));
}
return new Schema(builder.build());
}
private static interface ParserIntlTask extends Task, TimestampParser.Task {}
private static interface ParserIntlColumnOption extends Task, TimestampParser.TimestampColumnOption {}
private HashMap<String, TimestampParser> buildTimestampParserMap(List<ColumnConfig> columns, String joinedColumnPrefix, String timeZone)
{
final HashMap<String, TimestampParser> timestampParserMap = Maps.newHashMap();
for (ColumnConfig columnConfig: columns) {
if (Types.TIMESTAMP.equals(columnConfig.getType())) {
String format = columnConfig.getOption().get(String.class, "format");
DateTimeZone timezone = DateTimeZone.forID(timeZone);
// TODO: Switch to a newer TimestampParser constructor after a reasonable interval.
// Traditional constructor is used here for compatibility.
final ConfigSource configSource = Exec.newConfigSource();
configSource.set("format", format);
configSource.set("timezone", timezone);
TimestampParser parser = new TimestampParser(
Exec.newConfigSource().loadConfig(ParserIntlTask.class),
configSource.loadConfig(ParserIntlColumnOption.class));
String columnName = joinedColumnPrefix + columnConfig.getName();
timestampParserMap.put(columnName, parser);
}
}
return timestampParserMap;
}
} |
package org.jboss.qa.arquillian.container;
import java.io.InputStream;
import org.jboss.arquillian.container.spi.client.container.DeployableContainer;
import org.jboss.arquillian.container.spi.client.container.DeploymentException;
import org.jboss.arquillian.container.spi.client.container.LifecycleException;
import org.jboss.arquillian.container.spi.client.protocol.ProtocolDescription;
import org.jboss.arquillian.container.spi.client.protocol.metadata.ProtocolMetaData;
import org.jboss.arquillian.container.spi.context.annotation.ContainerScoped;
import org.jboss.arquillian.container.spi.context.annotation.DeploymentScoped;
import org.jboss.arquillian.core.api.InstanceProducer;
import org.jboss.arquillian.core.api.annotation.Inject;
import org.jboss.qa.arquillian.container.configuration.SrampConfiguration;
import org.jboss.qa.arquillian.container.service.SrampService;
import org.jboss.qa.arquillian.container.service.SrampServiceImpl;
import org.jboss.resteasy.logging.Logger;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.exporter.ZipExporter;
import org.jboss.shrinkwrap.api.spec.EnterpriseArchive;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.descriptor.api.Descriptor;
import org.oasis_open.docs.s_ramp.ns.s_ramp_v1.BaseArtifactType;
/**
* Implementation of Arquillian container to support S-RAMP as a remote
* deployment target.
*
* @author sbunciak
* @since 1.0.0
*/
public class SrampContainer implements DeployableContainer<SrampConfiguration> {
@Inject
@DeploymentScoped
private InstanceProducer<BaseArtifactType> artifactProd;
@Inject
@ContainerScoped
private InstanceProducer<SrampConfiguration> confProd;
private Logger log = Logger.getLogger(SrampContainer.class);
private SrampConfiguration config = null;
private SrampService srampService = null;
public Class<SrampConfiguration> getConfigurationClass() {
return SrampConfiguration.class;
}
public void setup(SrampConfiguration configuration) {
this.config = configuration;
confProd.set(configuration);
}
public void start() throws LifecycleException {
// In the case of remote container adapters, this is ideally the place
// to verify if the container is running, along with any other necessary
// validations.
try {
srampService = new SrampServiceImpl(config);
} catch (Exception e) {
log.error("Exception occured connecting to S-RAMP: ", e);
throw new LifecycleException(
"Exception occured connecting to S-RAMP: ", e);
}
if (srampService != null) {
log.info("Connection to S-RAMP established.");
}
}
public void stop() throws LifecycleException {
// Any cleanup operations can be performed in this method.
}
public ProtocolDescription getDefaultProtocol() {
return new ProtocolDescription("Local");
}
public ProtocolMetaData deploy(Archive<?> archive)
throws DeploymentException {
String applicationType = "";
// Deploying war
if (archive instanceof WebArchive) {
applicationType = "JavaWebApplication";
}
// Deploying jar
if (archive instanceof JavaArchive) {
// default archive type
applicationType = "JavaArchive";
// SwitchYardApplication if it contains switchyard.xml
if (archive.contains("META-INF/switchyard.xml")) {
applicationType = "SwitchYardApplication";
}
// TeiidVdb if it contains vdb.xml
if (archive.contains("META-INF/vdb.xml")) {
applicationType = "TeiidVdb";
}
// KieJarArchive if it contains kmodule.xml
if (archive.contains("META-INF/kmodule.xml")) {
applicationType = "KieJarArchive";
}
}
// Deploying ear
if (archive instanceof EnterpriseArchive) {
applicationType = "JavaEnterpriseApplication";
}
log.debug("Deploying " + applicationType + ": " + archive.getName());
// export SkrinkWrap archive as InputStream
InputStream in = archive.as(ZipExporter.class).exportAsInputStream();
// deploy archive to S-RAMP
BaseArtifactType artifact = srampService.deployArchive(
archive.getName(), applicationType, in);
// save the deployed archive to injection point
artifactProd.set(artifact);
log.info("Deployed " + applicationType + ": " + archive.getName());
// Return empty meta-data of no use
return new ProtocolMetaData();
}
public void undeploy(Archive<?> archive) throws DeploymentException {
try {
srampService.undeployArchives();
log.info("Undeployed " + archive.getName());
} catch (Exception e) {
log.error(
"Error occured during undeployment of " + archive.getName(),
e);
throw new DeploymentException("Error occured during undeployment",
e);
}
}
public void deploy(Descriptor descriptor) throws DeploymentException {
throw new UnsupportedOperationException(
"Descriptor-based deployment not implemented.");
}
public void undeploy(Descriptor descriptor) throws DeploymentException {
throw new UnsupportedOperationException(
"Descriptor-based deployment not implemented.");
}
} |
package org.jfree.chart.renderer.xy;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.ui.RectangleEdge;
import org.jfree.chart.ui.TextAnchor;
import org.jfree.chart.entity.EntityCollection;
import org.jfree.chart.event.RendererChangeEvent;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.labels.XYItemLabelGenerator;
import org.jfree.chart.plot.CrosshairState;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.PlotRenderingInfo;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.Range;
import org.jfree.data.general.DatasetUtilities;
import org.jfree.data.xy.IntervalXYDataset;
import org.jfree.data.xy.TableXYDataset;
import org.jfree.data.xy.XYDataset;
/**
* A bar renderer that displays the series items stacked.
* The dataset used together with this renderer must be a
* {@link org.jfree.data.xy.IntervalXYDataset} and a
* {@link org.jfree.data.xy.TableXYDataset}. For example, the
* dataset class {@link org.jfree.data.xy.CategoryTableXYDataset}
* implements both interfaces.
*
* The example shown here is generated by the
* <code>StackedXYBarChartDemo2.java</code> program included in the
* JFreeChart demo collection:
* <br><br>
* <img src="../../../../../images/StackedXYBarRendererSample.png"
* alt="StackedXYBarRendererSample.png">
*/
public class StackedXYBarRenderer extends XYBarRenderer {
/** For serialization. */
private static final long serialVersionUID = -7049101055533436444L;
/** A flag that controls whether the bars display values or percentages. */
private boolean renderAsPercentages;
/**
* Creates a new renderer.
*/
public StackedXYBarRenderer() {
this(0.0);
}
/**
* Creates a new renderer.
*
* @param margin the percentual amount of the bars that are cut away.
*/
public StackedXYBarRenderer(double margin) {
super(margin);
this.renderAsPercentages = false;
// set the default item label positions, which will only be used if
// the user requests visible item labels...
ItemLabelPosition p = new ItemLabelPosition(ItemLabelAnchor.CENTER,
TextAnchor.CENTER);
setDefaultPositiveItemLabelPosition(p);
setDefaultNegativeItemLabelPosition(p);
setPositiveItemLabelPositionFallback(null);
setNegativeItemLabelPositionFallback(null);
}
/**
* Returns <code>true</code> if the renderer displays each item value as
* a percentage (so that the stacked bars add to 100%), and
* <code>false</code> otherwise.
*
* @return A boolean.
*
* @see #setRenderAsPercentages(boolean)
*
* @since 1.0.5
*/
public boolean getRenderAsPercentages() {
return this.renderAsPercentages;
}
/**
* Sets the flag that controls whether the renderer displays each item
* value as a percentage (so that the stacked bars add to 100%), and sends
* a {@link RendererChangeEvent} to all registered listeners.
*
* @param asPercentages the flag.
*
* @see #getRenderAsPercentages()
*
* @since 1.0.5
*/
public void setRenderAsPercentages(boolean asPercentages) {
this.renderAsPercentages = asPercentages;
fireChangeEvent();
}
/**
* Returns <code>3</code> to indicate that this renderer requires three
* passes for drawing (shadows are drawn in the first pass, the bars in the
* second, and item labels are drawn in the third pass so that
* they always appear in front of all the bars).
*
* @return <code>2</code>.
*/
@Override
public int getPassCount() {
return 3;
}
/**
* Initialises the renderer and returns a state object that should be
* passed to all subsequent calls to the drawItem() method. Here there is
* nothing to do.
*
* @param g2 the graphics device.
* @param dataArea the area inside the axes.
* @param plot the plot.
* @param data the data.
* @param info an optional info collection object to return data back to
* the caller.
*
* @return A state object.
*/
@Override
public XYItemRendererState initialise(Graphics2D g2,
Rectangle2D dataArea,
XYPlot plot,
XYDataset data,
PlotRenderingInfo info) {
return new XYBarRendererState(info);
}
/**
* Returns the range of values the renderer requires to display all the
* items from the specified dataset.
*
* @param dataset the dataset (<code>null</code> permitted).
*
* @return The range (<code>null</code> if the dataset is <code>null</code>
* or empty).
*/
@Override
public Range findRangeBounds(XYDataset dataset) {
if (dataset != null) {
if (this.renderAsPercentages) {
return new Range(0.0, 1.0);
}
else {
return DatasetUtilities.findStackedRangeBounds(
(TableXYDataset) dataset);
}
}
else {
return null;
}
}
/**
* Draws the visual representation of a single data item.
*
* @param g2 the graphics device.
* @param state the renderer state.
* @param dataArea the area within which the plot is being drawn.
* @param info collects information about the drawing.
* @param plot the plot (can be used to obtain standard color information
* etc).
* @param domainAxis the domain axis.
* @param rangeAxis the range axis.
* @param dataset the dataset.
* @param series the series index (zero-based).
* @param item the item index (zero-based).
* @param crosshairState crosshair information for the plot
* (<code>null</code> permitted).
* @param pass the pass index.
*/
@Override
public void drawItem(Graphics2D g2,
XYItemRendererState state,
Rectangle2D dataArea,
PlotRenderingInfo info,
XYPlot plot,
ValueAxis domainAxis,
ValueAxis rangeAxis,
XYDataset dataset,
int series,
int item,
CrosshairState crosshairState,
int pass) {
if (!getItemVisible(series, item)) {
return;
}
if (!(dataset instanceof IntervalXYDataset
&& dataset instanceof TableXYDataset)) {
String message = "dataset (type " + dataset.getClass().getName()
+ ") has wrong type:";
boolean and = false;
if (!IntervalXYDataset.class.isAssignableFrom(dataset.getClass())) {
message += " it is no IntervalXYDataset";
and = true;
}
if (!TableXYDataset.class.isAssignableFrom(dataset.getClass())) {
if (and) {
message += " and";
}
message += " it is no TableXYDataset";
}
throw new IllegalArgumentException(message);
}
IntervalXYDataset intervalDataset = (IntervalXYDataset) dataset;
double value = intervalDataset.getYValue(series, item);
if (Double.isNaN(value)) {
return;
}
// if we are rendering the values as percentages, we need to calculate
// the total for the current item. Unfortunately here we end up
// repeating the calculation more times than is strictly necessary -
// hopefully I'll come back to this and find a way to add the
// total(s) to the renderer state. The other problem is we implicitly
// assume the dataset has no negative values...perhaps that can be
// fixed too.
double total = 0.0;
if (this.renderAsPercentages) {
total = DatasetUtilities.calculateStackTotal(
(TableXYDataset) dataset, item);
value = value / total;
}
double positiveBase = 0.0;
double negativeBase = 0.0;
for (int i = 0; i < series; i++) {
double v = dataset.getYValue(i, item);
if (!Double.isNaN(v) && isSeriesVisible(i)) {
if (this.renderAsPercentages) {
v = v / total;
}
if (v > 0) {
positiveBase = positiveBase + v;
}
else {
negativeBase = negativeBase + v;
}
}
}
double translatedBase;
double translatedValue;
RectangleEdge edgeR = plot.getRangeAxisEdge();
if (value > 0.0) {
translatedBase = rangeAxis.valueToJava2D(positiveBase, dataArea,
edgeR);
translatedValue = rangeAxis.valueToJava2D(positiveBase + value,
dataArea, edgeR);
}
else {
translatedBase = rangeAxis.valueToJava2D(negativeBase, dataArea,
edgeR);
translatedValue = rangeAxis.valueToJava2D(negativeBase + value,
dataArea, edgeR);
}
RectangleEdge edgeD = plot.getDomainAxisEdge();
double startX = intervalDataset.getStartXValue(series, item);
if (Double.isNaN(startX)) {
return;
}
double translatedStartX = domainAxis.valueToJava2D(startX, dataArea,
edgeD);
double endX = intervalDataset.getEndXValue(series, item);
if (Double.isNaN(endX)) {
return;
}
double translatedEndX = domainAxis.valueToJava2D(endX, dataArea, edgeD);
double translatedWidth = Math.max(1, Math.abs(translatedEndX
- translatedStartX));
double translatedHeight = Math.abs(translatedValue - translatedBase);
if (getMargin() > 0.0) {
double cut = translatedWidth * getMargin();
translatedWidth = translatedWidth - cut;
translatedStartX = translatedStartX + cut / 2;
}
Rectangle2D bar = null;
PlotOrientation orientation = plot.getOrientation();
if (orientation == PlotOrientation.HORIZONTAL) {
bar = new Rectangle2D.Double(Math.min(translatedBase,
translatedValue), Math.min(translatedEndX,
translatedStartX), translatedHeight, translatedWidth);
}
else if (orientation == PlotOrientation.VERTICAL) {
bar = new Rectangle2D.Double(Math.min(translatedStartX,
translatedEndX), Math.min(translatedBase, translatedValue),
translatedWidth, translatedHeight);
}
boolean positive = (value > 0.0);
boolean inverted = rangeAxis.isInverted();
RectangleEdge barBase;
if (orientation == PlotOrientation.HORIZONTAL) {
if (positive && inverted || !positive && !inverted) {
barBase = RectangleEdge.RIGHT;
}
else {
barBase = RectangleEdge.LEFT;
}
}
else {
if (positive && !inverted || !positive && inverted) {
barBase = RectangleEdge.BOTTOM;
}
else {
barBase = RectangleEdge.TOP;
}
}
if (pass == 0) {
if (getShadowsVisible()) {
getBarPainter().paintBarShadow(g2, this, series, item, bar,
barBase, false);
}
}
else if (pass == 1) {
getBarPainter().paintBar(g2, this, series, item, bar, barBase);
// add an entity for the item...
if (info != null) {
EntityCollection entities = info.getOwner()
.getEntityCollection();
if (entities != null) {
addEntity(entities, bar, dataset, series, item,
bar.getCenterX(), bar.getCenterY());
}
}
}
else if (pass == 2) {
// handle item label drawing, now that we know all the bars have
// been drawn...
if (isItemLabelVisible(series, item)) {
XYItemLabelGenerator generator = getItemLabelGenerator(series,
item);
drawItemLabel(g2, dataset, series, item, plot, generator, bar,
value < 0.0);
}
}
}
/**
* Tests this renderer for equality with an arbitrary object.
*
* @param obj the object (<code>null</code> permitted).
*
* @return A boolean.
*/
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof StackedXYBarRenderer)) {
return false;
}
StackedXYBarRenderer that = (StackedXYBarRenderer) obj;
if (this.renderAsPercentages != that.renderAsPercentages) {
return false;
}
return super.equals(obj);
}
/**
* Returns a hash code for this instance.
*
* @return A hash code.
*/
@Override
public int hashCode() {
int result = super.hashCode();
result = result * 37 + (this.renderAsPercentages ? 1 : 0);
return result;
}
} |
package org.lightmare.utils.serialization;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.lightmare.utils.ObjectUtils;
import org.lightmare.utils.RpcUtils;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
/**
* Reads write java objects from {@link Byte} array or {@link String} with java
* JSON serialization vendor specific JSON library
*
* @author Levan
*
*/
public abstract class JsonSerializer {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static boolean mapperConfigured;
// Lock for initializing ObjectMapper instance
private static final Lock LOCK = new ReentrantLock();
private static void configureMapper() {
LOCK.lock();
try {
if (ObjectUtils.notTrue(mapperConfigured)) {
MAPPER.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapperConfigured = Boolean.TRUE;
}
} finally {
LOCK.unlock();
}
}
/**
* Configures {@link ObjectMapper} if {@link RpcUtils#mapperConfigured} is
* <code>false</code>
*
* @return {@link ObjectMapper}
*/
public static ObjectMapper getMapper() {
if (ObjectUtils.notTrue(mapperConfigured)) {
configureMapper();
}
return MAPPER;
}
public static String write(Object value) throws IOException {
String data;
try {
data = getMapper().writeValueAsString(value);
} catch (JsonGenerationException ex) {
throw new IOException(ex);
} catch (JsonMappingException ex) {
throw new IOException(ex);
} catch (IOException ex) {
throw new IOException(ex);
}
return data;
}
public static <T> T read(String data, Class<T> valueClass)
throws IOException {
T value;
try {
value = getMapper().readValue(data, valueClass);
} catch (JsonGenerationException ex) {
throw new IOException(ex);
} catch (JsonMappingException ex) {
throw new IOException(ex);
} catch (IOException ex) {
throw new IOException(ex);
}
return value;
}
public static <T> T read(InputStream stream, Class<T> valueClass)
throws IOException {
T value = getMapper().readValue(stream, valueClass);
return value;
}
public static <T> T read(byte[] bytes, Class<T> valueClass)
throws IOException {
T value = getMapper().readValue(bytes, valueClass);
return value;
}
} |
package org.monarchinitiative.ppk.model.meta;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
/**
* An association connects an entity (for example, disease, person or variant) with either
* another entity, or with some kind of descriptor (for example, phenotype).
*
* All pieces of evidences are attached to associations
*
* @author cjm
*
*/
public abstract class Association {
@JsonProperty("entity")
private String entity;
@JsonProperty("evidence_list")
@JsonPropertyDescription("Any Association can have any number of pieces of evidence attached")
private List<Evidence> evidenceList;
/**
* @return the entity
*/
public String getEntity() {
return entity;
}
/**
* @param entity the entity to set
*/
public void setEntity(String entity) {
this.entity = entity;
}
/**
* @return the evidenceList
*/
public List<Evidence> getEvidenceList() {
return evidenceList;
}
/**
* @param evidenceList the evidenceList to set
*/
public void setEvidenceList(List<Evidence> evidenceList) {
this.evidenceList = evidenceList;
}
} |
package org.osiam.shell.command.update;
import java.io.IOException;
import org.osiam.client.OsiamConnector;
import org.osiam.client.oauth.AccessToken;
import org.osiam.resources.scim.UpdateUser;
import org.osiam.resources.scim.User;
import org.osiam.shell.command.OsiamAccessCommand;
import org.osiam.shell.command.update.user.UpdateUserBuilder;
import de.raysha.lib.jsimpleshell.Shell;
import de.raysha.lib.jsimpleshell.ShellBuilder;
import de.raysha.lib.jsimpleshell.ShellDependent;
import de.raysha.lib.jsimpleshell.annotation.Command;
import de.raysha.lib.jsimpleshell.annotation.Param;
import de.raysha.lib.jsimpleshell.io.OutputBuilder;
import de.raysha.lib.jsimpleshell.io.OutputDependent;
/**
* This class contains commands which can update users.
*
* @author rainu
*/
public class UpdateUserCommand extends OsiamAccessCommand implements ShellDependent, OutputDependent {
private Shell shell;
private OutputBuilder output;
public UpdateUserCommand(AccessToken at, OsiamConnector connector) {
super(at, connector);
}
@Override
public void cliSetShell(Shell theShell) {
this.shell = theShell;
}
@Override
public void cliSetOutput(OutputBuilder output) {
this.output = output;
}
@Command(description = "Update the current logged-in user.")
public Object updateMe() throws IOException{
String userName = connector.getCurrentUserBasic(accessToken).getUserName();
return updateUser(userName);
}
@Command(description = "Update the given user.")
public Object updateUser(
@Param(name = "userName", description = "The name of the user.")
String userName) throws IOException{
final User user = getUser(userName);
if(user == null) return "There is no user with the name \"" + userName + "\"!";
final UpdateUserBuilder builder = new UpdateUserBuilder(user);
final Shell subShell = ShellBuilder.subshell("update-user[" + userName + "]", shell)
.disableExitCommand()
.addHandler(builder)
.build();
output.out()
.normal("In this subshell you can edit the user. Leave this sub shell via \"commit\" to persist the changes.")
.println();
subShell.commandLoop();
final UpdateUser update = builder.build();
if(update == null) return null;
return connector.updateUser(user.getId(), update, accessToken);
}
} |
package org.smoothbuild.db.values.marshal;
import static com.google.common.base.Preconditions.checkNotNull;
import org.smoothbuild.db.hashed.HashedDb;
import org.smoothbuild.db.hashed.Marshaller;
import org.smoothbuild.db.hashed.Unmarshaller;
import org.smoothbuild.lang.value.Blob;
import org.smoothbuild.lang.value.SFile;
import org.smoothbuild.lang.value.SString;
import com.google.common.hash.HashCode;
public class FileMarshaller implements ValueMarshaller<SFile> {
private final HashedDb hashedDb;
public FileMarshaller(HashedDb hashedDb) {
this.hashedDb = checkNotNull(hashedDb);
}
public SFile write(SString path, Blob content) {
Marshaller marshaller = new Marshaller();
marshaller.write(path.hash());
marshaller.write(content.hash());
byte[] bytes = marshaller.getBytes();
HashCode hash = hashedDb.write(bytes);
return new SFile(hash, path, content);
}
@Override
public SFile read(HashCode hash) {
try (Unmarshaller unmarshaller = new Unmarshaller(hashedDb, hash)) {
SString path = new StringMarshaller(hashedDb).read(unmarshaller.readHash());
Blob blob = new BlobMarshaller(hashedDb).read(unmarshaller.readHash());
return new SFile(hash, path, blob);
}
}
} |
package org.spongepowered.common.scheduler;
import com.google.common.base.MoreObjects;
import org.spongepowered.common.relocate.co.aikar.timings.SpongeTimings;
import co.aikar.timings.Timing;
import org.spongepowered.api.plugin.PluginContainer;
import org.spongepowered.api.scheduler.Task;
import java.util.UUID;
import java.util.function.Consumer;
import java.util.concurrent.TimeUnit;
public class ScheduledTask implements Task {
final long offset; //nanoseconds or ticks
final long period; //nanoseconds or ticks
final boolean delayIsTicks;
final boolean intervalIsTicks;
private final PluginContainer owner;
private final Consumer<Task> consumer;
private long timestamp;
private ScheduledTaskState state;
private final UUID id;
private final String name;
private final TaskSynchronicity syncType;
private final String stringRepresentation;
private Timing taskTimer;
// Internal Task state. Not for user-service use.
public enum ScheduledTaskState {
/**
* Never ran before, waiting for the offset to pass.
*/
WAITING(false),
/**
* In the process of switching to the running state.
*/
SWITCHING(true),
/**
* Has ran, and will continue to unless removed from the task map.
*/
RUNNING(true),
/**
* Task cancelled, scheduled to be removed from the task map.
*/
CANCELED(false);
public final boolean isActive;
ScheduledTaskState(boolean active) {
this.isActive = active;
}
}
ScheduledTask(TaskSynchronicity syncType, Consumer<Task> task, String taskName, long delay, boolean delayIsTicks, long interval,
boolean intervalIsTicks, PluginContainer pluginContainer) {
// All tasks begin waiting.
this.setState(ScheduledTaskState.WAITING);
this.offset = delay;
this.delayIsTicks = delayIsTicks;
this.period = interval;
this.intervalIsTicks = intervalIsTicks;
this.owner = pluginContainer;
this.consumer = task;
this.id = UUID.randomUUID();
this.name = taskName;
this.syncType = syncType;
this.stringRepresentation = MoreObjects.toStringHelper(this)
.add("name", this.name)
.add("delay", this.offset)
.add("interval", this.period)
.add("owner", this.owner)
.add("id", this.id)
.add("isAsync", this.isAsynchronous())
.toString();
}
@Override
public PluginContainer getOwner() {
return this.owner;
}
@Override
public long getDelay() {
if (this.delayIsTicks) {
return this.offset;
}
return TimeUnit.NANOSECONDS.toMillis(this.offset);
}
@Override
public long getInterval() {
if (this.intervalIsTicks) {
return this.period;
}
return TimeUnit.NANOSECONDS.toMillis(this.period);
}
@Override
public boolean cancel() {
boolean success = false;
if (this.getState() != ScheduledTask.ScheduledTaskState.RUNNING) {
success = true;
}
this.setState(ScheduledTask.ScheduledTaskState.CANCELED);
return success;
}
@Override
public Consumer<Task> getConsumer() {
return this.consumer;
}
@Override
public UUID getUniqueId() {
return this.id;
}
@Override
public String getName() {
return this.name;
}
@Override
public boolean isAsynchronous() {
return this.syncType == TaskSynchronicity.ASYNCHRONOUS;
}
long getTimestamp() {
return this.timestamp;
}
/**
* Returns a timestamp after which the next execution will take place.
* Should only be compared to
* {@link SchedulerBase#getTimestamp(ScheduledTask)}.
*
* @return The next execution timestamp
*/
long nextExecutionTimestamp() {
if (this.state.isActive) {
return this.timestamp + this.period;
}
return this.timestamp + this.offset;
}
void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
ScheduledTaskState getState() {
return this.state;
}
void setState(ScheduledTaskState state) {
if (this.state != ScheduledTaskState.CANCELED) {
this.state = state;
}
}
@Override
public String toString() {
return this.stringRepresentation;
}
public enum TaskSynchronicity {
SYNCHRONOUS,
ASYNCHRONOUS
}
public Timing getTimingsHandler() {
if (this.taskTimer == null) {
this.taskTimer = SpongeTimings.getPluginSchedulerTimings(this.owner);
}
return this.taskTimer;
}
} |
package org.threadly.concurrent;
import java.util.concurrent.Callable;
import org.threadly.concurrent.future.ListenableFuture;
import org.threadly.concurrent.future.RunnableFuture;
import org.threadly.concurrent.lock.NativeLockFactory;
import org.threadly.concurrent.lock.StripedLock;
/**
* This is a class which is more full featured than {@link TaskExecutorDistributor},
* but it does require a scheduler implementation in order to be able to perform scheduling.
*
* @author jent - Mike Jensen
*/
public class TaskSchedulerDistributor extends TaskExecutorDistributor {
private final SimpleSchedulerInterface scheduler;
/**
* Constructor which creates scheduler based off provided values. This is a more full
* featured task distributor, it allows scheduling and recurring tasks
*
* @param expectedParallism Expected number of keys that will be used in parallel
* @param maxThreadCount Max thread count (limits the qty of keys which are handled in parallel)
*/
public TaskSchedulerDistributor(int expectedParallism, int maxThreadCount) {
this(new PriorityScheduledExecutor(expectedParallism,
maxThreadCount,
DEFAULT_THREAD_KEEPALIVE_TIME,
TaskPriority.High,
PriorityScheduledExecutor.DEFAULT_LOW_PRIORITY_MAX_WAIT_IN_MS),
new StripedLock(expectedParallism, new NativeLockFactory()));
}
/**
* Constructor to use a provided executor implementation for running tasks.
*
* @param scheduler A multi-threaded scheduler to distribute tasks to.
* Ideally has as many possible threads as keys that
* will be used in parallel.
*/
public TaskSchedulerDistributor(SimpleSchedulerInterface scheduler) {
this(DEFAULT_LOCK_PARALISM, scheduler);
}
/**
* Constructor to use a provided scheduler implementation for running tasks.
*
* @param expectedParallism level of expected qty of threads adding tasks in parallel
* @param scheduler A multi-threaded scheduler to distribute tasks to.
* Ideally has as many possible threads as keys that
* will be used in parallel.
*/
public TaskSchedulerDistributor(int expectedParallism, SimpleSchedulerInterface scheduler) {
this(scheduler, new StripedLock(expectedParallism, new NativeLockFactory()));
}
/**
* Constructor to be used in unit tests. This allows you to provide a StripedLock
* that provides a {@link org.threadly.test.concurrent.lock.TestableLockFactory} so
* that this class can be used with the
* {@link org.threadly.test.concurrent.TestablePriorityScheduler}.
*
* @param scheduler scheduler to be used for task worker execution
* @param sLock lock to be used for controlling access to workers
*/
public TaskSchedulerDistributor(SimpleSchedulerInterface scheduler,
StripedLock sLock) {
super(scheduler, sLock);
this.scheduler = scheduler;
}
/**
* Returns a scheduler implementation where all tasks submitted
* on this scheduler will run on the provided key.
*
* @param threadKey object key where hashCode will be used to determine execution thread
* @return scheduler which will only execute based on the provided key
*/
public SubmitterSchedulerInterface getSubmitterSchedulerForKey(Object threadKey) {
if (threadKey == null) {
throw new IllegalArgumentException("Must provide thread key");
}
return new KeyBasedScheduler(threadKey);
}
/**
* Schedule a one time task with a given delay that will not run concurrently
* based off the thread key.
*
* @param threadKey object key where hashCode will be used to determine execution thread
* @param task Task to execute
* @param delayInMs Time to wait to execute task
*/
public void schedule(Object threadKey,
Runnable task,
long delayInMs) {
if (threadKey == null) {
throw new IllegalArgumentException("Must provide a threadKey");
} else if (task == null) {
throw new IllegalArgumentException("Must provide a task");
} else if (delayInMs < 0) {
throw new IllegalArgumentException("delayInMs must be >= 0");
}
if (delayInMs == 0) {
addTask(threadKey, task);
} else {
scheduler.schedule(new AddTask(threadKey, task),
delayInMs);
}
}
/**
* Schedule a recurring task to run. The recurring delay time will be
* from the point where execution finished. This task will not run concurrently
* based off the thread key.
*
* @param threadKey object key where hashCode will be used to determine execution thread
* @param task Task to be executed.
* @param initialDelay Delay in milliseconds until first run.
* @param recurringDelay Delay in milliseconds for running task after last finish.
*/
public void scheduleWithFixedDelay(Object threadKey,
Runnable task,
long initialDelay,
long recurringDelay) {
if (threadKey == null) {
throw new IllegalArgumentException("Must provide a threadKey");
} else if (task == null) {
throw new IllegalArgumentException("Must provide a task");
} else if (initialDelay < 0) {
throw new IllegalArgumentException("initialDelay must be >= 0");
} else if (recurringDelay < 0) {
throw new IllegalArgumentException("recurringDelay must be >= 0");
}
scheduler.schedule(new AddTask(threadKey,
new RecrringTask(threadKey, task,
recurringDelay)),
initialDelay);
}
/**
* Submit a task to run as soon as possible. There is a
* slight increase in load when using submit over execute.
* So this should only be used when the future is necessary.
*
* The future .get() method will return null once the runnable has completed.
*
* @param threadKey key which hash will be used to determine which thread to run
* @param task runnable to be executed
* @return a future to know when the task has completed
*/
public ListenableFuture<?> submit(Object threadKey, Runnable task) {
return submit(threadKey, task, null);
}
/**
* Submit a task to run as soon as possible. There is a
* slight increase in load when using submit over execute.
* So this should only be used when the future is necessary.
*
* The future .get() method will return null once the runnable has completed.
*
* @param threadKey key which hash will be used to determine which thread to run
* @param task runnable to be executed
* @param result result to be returned from resulting future .get() when runnable completes
* @return a future to know when the task has completed
*/
public <T> ListenableFuture<T> submit(Object threadKey, Runnable task, T result) {
return submitScheduled(threadKey, task, result, 0);
}
/**
* Submit a {@link Callable} to run as soon as possible for a given key.
* This is needed when a result needs to be consumed from the callable.
*
* @param threadKey key which hash will be used to determine which thread to run
* @param task callable to be executed
* @return a future to know when the task has completed and get the result of the callable
*/
public <T> ListenableFuture<T> submit(Object threadKey, Callable<T> task) {
return submitScheduled(threadKey, task, 0);
}
/**
* Schedule a task with a given delay. There is a slight
* increase in load when using submitScheduled over schedule. So
* this should only be used when the future is necessary.
*
* The future .get() method will return null once the runnable has completed.
*
* @param threadKey key which hash will be used to determine which thread to run
* @param task runnable to execute
* @param delayInMs time in milliseconds to wait to execute task
* @return a future to know when the task has completed
*/
public ListenableFuture<?> submitScheduled(Object threadKey, Runnable task, long delayInMs) {
return submitScheduled(threadKey, task, null, delayInMs);
}
/**
* Schedule a task with a given delay. There is a slight
* increase in load when using submitScheduled over schedule. So
* this should only be used when the future is necessary.
*
* The future .get() method will return null once the runnable has completed.
*
* @param threadKey key which hash will be used to determine which thread to run
* @param task runnable to execute
* @param result result to be returned from resulting future .get() when runnable completes
* @param delayInMs time in milliseconds to wait to execute task
* @return a future to know when the task has completed
*/
public <T> ListenableFuture<T> submitScheduled(Object threadKey, Runnable task, T result, long delayInMs) {
if (threadKey == null) {
throw new IllegalArgumentException("Must provide a threadKey");
} else if (task == null) {
throw new IllegalArgumentException("Must provide a task");
} else if (delayInMs < 0) {
throw new IllegalArgumentException("delayInMs must be >= 0");
}
RunnableFuture<T> rf = new RunnableFuture<T>(task, result);
if (delayInMs == 0) {
addTask(threadKey, rf);
} else {
scheduler.schedule(new AddTask(threadKey, rf),
delayInMs);
}
return rf;
}
/**
* Schedule a {@link Callable} with a given delay. This is
* needed when a result needs to be consumed from the
* callable.
*
* @param threadKey key which hash will be used to determine which thread to run
* @param task callable to be executed
* @param delayInMs time in milliseconds to wait to execute task
* @return a future to know when the task has completed and get the result of the callable
*/
public <T> ListenableFuture<T> submitScheduled(Object threadKey, Callable<T> task, long delayInMs) {
if (threadKey == null) {
throw new IllegalArgumentException("Must provide a threadKey");
} else if (task == null) {
throw new IllegalArgumentException("Must provide a task");
} else if (delayInMs < 0) {
throw new IllegalArgumentException("delayInMs must be >= 0");
}
RunnableFuture<T> rf = new RunnableFuture<T>(task);
if (delayInMs == 0) {
addTask(threadKey, rf);
} else {
scheduler.schedule(new AddTask(threadKey, rf),
delayInMs);
}
return rf;
}
/**
* Task which will run delayed to add a task into the queue when ready.
*
* @author jent - Mike Jensen
*/
protected class AddTask extends VirtualRunnable {
private final Object key;
private final Runnable task;
protected AddTask(Object key, Runnable task) {
this.key = key;
this.task = task;
}
@Override
public void run() {
addTask(key, task);
}
}
/**
* Repeating task container.
*
* @author jent - Mike Jensen
*/
protected class RecrringTask extends VirtualRunnable {
private final Object key;
private final Runnable task;
private final long recurringDelay;
protected RecrringTask(Object key, Runnable task, long recurringDelay) {
this.key = key;
this.task = task;
this.recurringDelay = recurringDelay;
}
@Override
public void run() {
try {
if (factory != null && task instanceof VirtualRunnable) {
((VirtualRunnable)task).run(factory);
} else {
task.run();
}
} finally {
if (! scheduler.isShutdown()) {
scheduler.schedule(new AddTask(key, this), recurringDelay);
}
}
}
}
/**
* Simple simple scheduler implementation that runs all executions and
* scheduling on a given key.
*
* @author jent - Mike Jensen
*/
protected class KeyBasedScheduler extends KeyBasedExecutor
implements SubmitterSchedulerInterface {
protected KeyBasedScheduler(Object threadKey) {
super(threadKey);
}
@Override
public void schedule(Runnable task, long delayInMs) {
TaskSchedulerDistributor.this.schedule(threadKey, task,
delayInMs);
}
@Override
public void scheduleWithFixedDelay(Runnable task, long initialDelay, long recurringDelay) {
TaskSchedulerDistributor.this.scheduleWithFixedDelay(threadKey, task,
initialDelay,
recurringDelay);
}
@Override
public ListenableFuture<?> submit(Runnable task) {
return submit(task, null);
}
@Override
public <T> ListenableFuture<T> submit(Runnable task, T result) {
return submitScheduled(task, result, 0);
}
@Override
public <T> ListenableFuture<T> submit(Callable<T> task) {
return submitScheduled(task, 0);
}
@Override
public ListenableFuture<?> submitScheduled(Runnable task, long delayInMs) {
return submitScheduled(task, null, delayInMs);
}
@Override
public <T> ListenableFuture<T> submitScheduled(Runnable task, T result, long delayInMs) {
return TaskSchedulerDistributor.this.submitScheduled(threadKey, task, result, delayInMs);
}
@Override
public <T> ListenableFuture<T> submitScheduled(Callable<T> task, long delayInMs) {
return TaskSchedulerDistributor.this.submitScheduled(threadKey, task, delayInMs);
}
@Override
public boolean isShutdown() {
return scheduler.isShutdown();
}
}
} |
package org.thymoljs.thymol.test.webapp;
import java.io.IOException;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.VariablesMap;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.expression.Calendars;
import org.thymeleaf.expression.Dates;
import org.thymeleaf.standard.expression.TextLiteralExpression;
import org.thymeleaf.templateresolver.ITemplateResolver;
import org.thymeleaf.templateresolver.TemplateResolver;
public class ThymolTestFilter implements Filter {
public static final String UPDATE_PREFIX_URI = "ThymolTestFilter-updatePrefix";
private Locale locale = null;
private static TemplateEngine templateEngine;
static {
templateEngine = ThymolTestApplication.initializeTemplateEngine();
}
public ThymolTestFilter() {
super();
}
public void doFilter( final ServletRequest request, final ServletResponse response, final FilterChain chain ) throws IOException, ServletException {
process( ( HttpServletRequest )request, ( HttpServletResponse )response, ( ( HttpServletRequest )request ).getSession( true ).getServletContext(), templateEngine );
}
@Override
public void destroy() {
}
@Override
public void init( FilterConfig arg0 ) throws ServletException {
}
private void process( final HttpServletRequest request, final HttpServletResponse response, final ServletContext servletContext, final TemplateEngine templateEngine ) throws IOException {
WebContext ctx = new WebContext( request, response, servletContext );
String template = getRequestPath( request );
if( UPDATE_PREFIX_URI.equals( template ) ) {
String localeIndx = ( String )request.getParameter( "locale" );
if( localeIndx != null ) {
int indx = Integer.parseInt(localeIndx);
Locale[] all = Locale.getAvailableLocales();
locale = all[indx];
}
else {
locale = null;
}
String prefix = ( String )request.getParameter( "prefix" );
if( prefix != null ) {
addPrefix( prefix, locale );
}
response.setContentType("text/html");
}
else {
if( template.length() > 0 && !"favicon".equalsIgnoreCase( template ) ) { // Work around selenium defect 2883 - ignore any requests for favicon from selenium
if( locale != null) {
ctx.setLocale(locale);
locale = null;
}
processParameters( request, ctx );
injectVars( ctx );
response.setCharacterEncoding( "UTF-8" );
templateEngine.process( template, ctx, response.getWriter() );
}
}
}
private String getRequestPath( final HttpServletRequest request ) {
final String requestURI = request.getRequestURI();
if( !requestURI.contains( UPDATE_PREFIX_URI ) ) {
final String contextPath = request.getContextPath();
if( requestURI.startsWith( contextPath ) ) {
String uri = requestURI.substring( contextPath.length() + 1 );
if( uri.endsWith( ".html" ) ) {
uri = uri.substring( 0, uri.length() - 5 );
}
else {
uri = "";
}
// int dotPos = uri.lastIndexOf( '.' );
// if( dotPos > 0 ) {
// uri = uri.substring( 0, dotPos );
return uri;
}
}
return requestURI.substring( 1 );
}
public void processParameters( final HttpServletRequest request, WebContext ctx ) {
@SuppressWarnings( "unchecked" )
Map< String, Object > params = request.getParameterMap();
for( String key: params.keySet() ) {
Object objectValue = params.get( key );
if( objectValue != null ) {
if( objectValue instanceof String[] ) {
String[] stringValueArray = ( String[] )objectValue;
String valueString = stringValueArray[ 0 ];
valueString = ( new TextLiteralExpression( valueString ) ).getValue().getValue();
ctx.setVariable( key, valueString );
}
}
}
}
public static void addPrefix( String prefix, Locale locale ) {
Set< ITemplateResolver > resolvers = templateEngine.getTemplateResolvers();
TemplateResolver prefixResolver = null;
for( ITemplateResolver resolver: resolvers ) {
ThymolTestApplication.ThymolServletContextTemplateResolver tr = ( ThymolTestApplication.ThymolServletContextTemplateResolver )resolver;
if( tr.getPrefix().equals( prefix ) && tr.getLocale().toString().equals(locale.toString()) ) {
prefixResolver = tr;
break;
}
}
if( prefixResolver == null ) {
templateEngine = ThymolTestApplication.initializeTemplateEngine( prefix, locale ); //TODO
}
}
private void injectVars( WebContext ctx ) {
Map< String, String > testVar = new LinkedHashMap< String, String >();
testVar.put( "text", "Hi there!" );
ctx.setVariable( "test", testVar );
// ["product", "#{ 'name': 'Lettuce', 'prices': { 'euros': 9.00, 'dollars': 12.00 } }"]
Map< String, String > pricesVar = new LinkedHashMap< String, String >();
pricesVar.put( "euros", "9" );
pricesVar.put( "dollars", "12" );
Map< String, Object > productVar = new LinkedHashMap< String, Object >();
productVar.put( "name", "Lettuce" );
productVar.put( "prices", pricesVar );
ctx.setVariable( "product", productVar );
//user = #{ 'name': 'Jack Melon', 'role': 'finance' }
Map< String, Object > userVar = new LinkedHashMap< String, Object >();
userVar.put( "name", "Jack Melon" );
userVar.put( "role", "finance" );
userVar.put( "age", Integer.valueOf(24) );
ctx.setVariable( "user", userVar );
Map< String, String > subscribeVar = new LinkedHashMap< String, String >();
testVar.put( "submit", "Subscribe me please!" );
ctx.setVariable( "subscribe", subscribeVar );
ctx.setVariable( "identifier", new Integer(32) );
ctx.setVariable( "sel", Boolean.TRUE );
ctx.setVariable( "value01", Boolean.FALSE );
ctx.setVariable( "value02", Boolean.TRUE );
ctx.setVariable( "value03", Integer.valueOf(0) );
ctx.setVariable( "value04", Integer.valueOf(1) );
ctx.setVariable( "value05", Integer.valueOf(-1) );
ctx.setVariable( "value06", Integer.valueOf(2) );
ctx.setVariable( "value07", "true" );
ctx.setVariable( "value08", "false" );
ctx.setVariable( "value09", "yes" );
ctx.setVariable( "value10", "no" );
ctx.setVariable( "value11", "YES" );
ctx.setVariable( "value12", "NO" );
ctx.setVariable( "value13", "YeS" );
ctx.setVariable( "value14", "YeS" );
ctx.setVariable( "value15", "No" );
ctx.setVariable( "value16", "nO" );
ctx.setVariable( "value17", "whatever" );
ctx.setVariable( "value18", "Y" );
ctx.setVariable( "value19", "N" );
ctx.setVariable( "value20", "T" );
ctx.setVariable( "value21", "F" );
ctx.setVariable( "value22", new Object() );
ctx.setVariable( "value23", null );
Map< String, Object > fatherVar = new LinkedHashMap< String, Object >();
fatherVar.put("name", "Joe");
Map< String, Object > personVar = new LinkedHashMap< String, Object >();
personVar.put( "father", fatherVar );
ctx.setVariable( "person", personVar );
List< Object > products = new LinkedList< Object >();
Map< String, Object > product1Var = new LinkedHashMap< String, Object >();
product1Var.put("name", "Lettuce");
product1Var.put("price", "12");
products.add(product1Var);
Map< String, Object > product2Var = new LinkedHashMap< String, Object >();
product2Var.put("name", "Apricot");
product2Var.put("price", "8");
products.add(product2Var);
Map< String, Object > product3Var = new LinkedHashMap< String, Object >();
product3Var.put("name", "Thyme");
product3Var.put("price", "1.23");
products.add(product3Var);
Map< String, Object > product4Var = new LinkedHashMap< String, Object >();
product4Var.put("name", "Carrot");
product4Var.put("price", "2");
products.add(product4Var);
ctx.setVariable( "products", products );
Map< String, String > capitals = new LinkedHashMap< String, String >();
capitals.put("Galicia", "Santiago de Compostela" );
capitals.put("Asturias", "Oviedo" );
capitals.put("Cantabria", "Santander" );
ctx.setVariable( "capitals", capitals );
List< Object > productList = new LinkedList< Object >();
productList.add(product1Var);
productList.add(product2Var);
ctx.setVariable( "productList", productList );
ctx.setVariable( "atext", "Lorem ipsum blah blah" );
// ["aa1", "a"],
// ["aa2", true],
// ["aa3", false],
// ["aa4", "aa"],
// ["ab1", 1],
// ["ab2", "one"],
// ["ac1", 2],
// ["ac2", "two"]
ctx.setVariable( "aa1", 'a' );
ctx.setVariable( "aa2", true );
ctx.setVariable( "aa3", false );
ctx.setVariable( "aa4", "aa" );
ctx.setVariable( "ab1", 1 );
ctx.setVariable( "ab2", "one" );
ctx.setVariable( "ac1", 2 );
ctx.setVariable( "ac2", "two" );
// ["bb1", "not null"],
// ["bb2", null],
// ["bc1", 2],
// ["bc2", "two"]
ctx.setVariable( "bb1", "not null" );
ctx.setVariable( "bb2", null );
ctx.setVariable( "bc1", 2 );
ctx.setVariable( "bc2", "two" );
// ["ca1", true],
// ["ca2", false],
// ["cb1", null],
// ["cb2", "one"]
ctx.setVariable( "ca1", true );
ctx.setVariable( "ca2", false );
ctx.setVariable( "cb1", null );
ctx.setVariable( "cb2", "one" );
// ["value1", "Joe Bloggs"],
// ["value2", "was here!"]
ctx.setVariable( "value1", "Joe Bloggs" );
ctx.setVariable( "value2", "was here!" );
ctx.setVariable( "onevar", "Hello" );
ctx.setVariable( "twovar", "World" );
ctx.setVariable( "planet01", "Mercury" );
ctx.setVariable( "planet02", "Venus" );
ctx.setVariable( "planet03", "Earth" );
ctx.setVariable( "planet04", "Mars" );
ctx.setVariable( "planet05", "Jupiter" );
ctx.setVariable( "planet06", "Saturn" );
ctx.setVariable( "planet07", "Uranus" );
ctx.setVariable( "planet08", "Neptune" );
List< Object > planetList = new LinkedList< Object >();
planetList.add(ctx.getVariables().get("planet01"));
planetList.add(ctx.getVariables().get("planet02"));
planetList.add(ctx.getVariables().get("planet03"));
planetList.add(ctx.getVariables().get("planet04"));
planetList.add(ctx.getVariables().get("planet05"));
planetList.add(ctx.getVariables().get("planet06"));
planetList.add(ctx.getVariables().get("planet07"));
planetList.add(ctx.getVariables().get("planet08"));
ctx.setVariable( "planets", planetList );
ctx.setVariable( "base_url", "
// ["cap1", "#{'city' : 'Madrid', 'country' : 'Spain'}"],
// ["cap2", "#{'city' : 'Lisboa', 'country' : 'Portugal'}"],
// ["cap3", "#{'city' : 'Paris', 'country' : 'France'}"],
// ["caps", "#[ #cap1, #cap2, #cap3 ]"],
// ["msg", "Hello, World!"]
List< Object > caps = new LinkedList< Object >();
Map< String, Object > cap1Var = new LinkedHashMap< String, Object >();
cap1Var.put("city", "Madrid");
cap1Var.put("country", "Spain");
ctx.setVariable( "cap1", "cap1Var" );
caps.add(cap1Var);
Map< String, Object > cap2Var = new LinkedHashMap< String, Object >();
cap2Var.put("city", "Lisboa");
cap2Var.put("country", "Portugal");
ctx.setVariable( "cap2", "cap2Var" );
caps.add(cap2Var);
Map< String, Object > cap3Var = new LinkedHashMap< String, Object >();
cap3Var.put("city", "Paris");
cap3Var.put("country", "France");
ctx.setVariable( "cap3", "cap3Var" );
caps.add(cap3Var);
ctx.setVariable( "caps", caps );
ctx.setVariable( "msg", "Hello, World!" );
ctx.setVariable( "caps0", new LinkedList< Object >() );
ctx.setVariable( "text", "Hello!" );
ctx.setVariable( "condition", true );
ctx.setVariable( "not_condition", false );
ctx.setVariable( "network", "IPTV" );
ctx.setVariable( "onevar01", "something" );
ctx.setVariable( "twovar01", 20 );
Map< String, Object > fourvar01Var = new LinkedHashMap< String, Object >();
fourvar01Var.put("value", 25 );
ctx.setVariable( "fourvar01", fourvar01Var );
ctx.setVariable( "m22", "...and for you too!" );
Map< String, Object > objVar = new LinkedHashMap< String, Object >();
objVar.put("a", "12" );
objVar.put("ba", "lala" );
ctx.setVariable( "obj", objVar );
List< String > userRoles = new LinkedList< String >();
userRoles.add("MANAGER");
userRoles.add("SALES");
ctx.setVariable( "userRoles", userRoles );
ctx.setVariable( "foo", "fooo!" );
ctx.setVariable( "someVar", "Hi there!" );
ctx.setVariable( "value", 23 );
ctx.setVariable( "one", "color:blue;" );
ctx.setVariable( "two", "text-align:center;" );
ctx.setVariable( "three", "intro" );
ctx.setVariable( "eValue1", 100.0 );
ctx.setVariable( "eValue2", 37.397436 );
// ["a1", "a"],
// ["a2", 12]
ctx.setVariable( "a1", "a" );
ctx.setVariable( "a2", 12 );
// ["onevar", false]
ctx.setVariable( "onevar1", false );
ctx.setVariable( "size", 123 );
HttpSession session = ctx.getHttpSession();
session.setAttribute( "a", "Some text" );
session.setAttribute( "b", 123 );
session.setAttribute( "c", "Hello" );
ServletContext servletContext = ctx.getServletContext();
servletContext.setAttribute( "a", "Some text" );
servletContext.setAttribute( "b", 123 );
servletContext.setAttribute( "c", "Hello" );
//onedate = new org.thymeleaf.engine21.conversion.conversion2.Conversion2Date(#dates.create(1492,10,12))
//Conversion2Date c2d = null;
Dates dates = new Dates(Locale.UK);
Calendars calendars = new Calendars(Locale.UK);
Date onedate = dates.create(1992,10,12);
ctx.setVariable( "onedate", onedate );
Date twodate = dates.create(1732,10,12);
ctx.setVariable( "twodate", twodate );
Calendar onecalendar = calendars.create(1992,10,12);
ctx.setVariable( "onecalendar", onecalendar );
Calendar twocalendar = calendars.create(1732,10,12);
ctx.setVariable( "twocalendar", twocalendar );
/*
var date1 = thDatesObject.create(1666,9,2);
var date2 = thDatesObject.create(1835,12,16);
var date3 = thDatesObject.create(1901,5,3);
var date4 = thDatesObject.create(1922,9,13);
var dateArray = [date1,date2,date3,date4];
thymol.applicationContext.createVariable("date1", date1 );
thymol.applicationContext.createVariable("date2", date2 );
thymol.applicationContext.createVariable("date3", date3 );
thymol.applicationContext.createVariable("date4", date4 );
thymol.applicationContext.createVariable("dateArray", dateArray );
thymol.applicationContext.createVariable("dateSet", ThSet.prototype.fromArray(dateArray) );
*/
Date date0 = dates.create(1492,10,12);
Date date1 = dates.create(1666,9,2);
Date date2 = dates.create(1835,12,16);
Date date3 = dates.create(1901,5,3);
Date date4 = dates.create(1922,9,13);
ctx.setVariable( "date0", date0 );
ctx.setVariable( "date1", date1 );
ctx.setVariable( "date2", date2 );
ctx.setVariable( "date3", date3 );
ctx.setVariable( "date4", date4 );
Date[] dateArray = {date0,date1,date2,date3,date4};
ctx.setVariable( "dateArray", dateArray );
Set<Date> dateSet = new HashSet<Date>();
List<Date> dateArrayAsList = Arrays.asList( dateArray );
Collections.sort( dateArrayAsList );
dateSet.addAll( dateArrayAsList );
// dateSet.add( date1 );
// dateSet.add( date2 );
// dateSet.add( date3 );
// dateSet.add( date4 );
ctx.setVariable( "dateSet", dateSet );
/*
var time1 = new Date(1501, 3, 12, 8, 25, 9, 321);
var time2 = new Date(1711, 4, 13, 12, 35, 19, 543);
var time3 = new Date(1921, 5, 14, 14, 45, 29, 765);
var time4 = new Date(2031, 6, 15, 16, 55, 39, 987);
*/
Date time1 = dates.create(1501, 3, 12, 8, 25, 9, 321);
Date time2 = dates.create(1711, 4, 13, 12, 35, 19, 543);
Date time3 = dates.create(1921, 5, 14, 14, 45, 29, 765);
Date time4 = dates.create(2031, 6, 15, 16, 55, 39, 987);
ctx.setVariable( "time1", time1 );
ctx.setVariable( "time2", time2 );
ctx.setVariable( "time3", time3 );
ctx.setVariable( "time4", time4 );
Date[] timeArray = {time1,time2,time3,time4};
ctx.setVariable( "timeArray", timeArray );
Set<Date> timeSet = new HashSet<Date>();
List<Date> timeArrayAsList = Arrays.asList( timeArray );
Collections.sort( timeArrayAsList );
timeSet.addAll( timeArrayAsList );
// timeSet.add( time1 );
// timeSet.add( time2 );
// timeSet.add( time3 );
// timeSet.add( time4 );
ctx.setVariable( "timeSet", timeSet );
Calendar calendarTime1 = calendars.create(1501, 3, 12, 8, 25, 9, 321);
Calendar calendarTime2 = calendars.create(1711, 4, 13, 12, 35, 19, 543);
Calendar calendarTime3 = calendars.create(1921, 5, 14, 14, 45, 29, 765);
Calendar calendarTime4 = calendars.create(2031, 6, 15, 16, 55, 39, 987);
ctx.setVariable( "calendarTime1", calendarTime1 );
ctx.setVariable( "calendarTime2", calendarTime2 );
ctx.setVariable( "calendarTime3", calendarTime3 );
ctx.setVariable( "calendarTime4", calendarTime4 );
Calendar[] calendarTimeArray = {calendarTime1,calendarTime2,calendarTime3,calendarTime4};
ctx.setVariable( "calendarTimeArray", calendarTimeArray );
Set<Calendar> calendarTimeSet = new HashSet<Calendar>();
List<Calendar> calendarTimeArrayAsList = Arrays.asList( calendarTimeArray );
Collections.sort( calendarTimeArrayAsList );
calendarTimeSet.addAll( calendarTimeArrayAsList );
ctx.setVariable( "calendarTimeSet", calendarTimeSet );
Calendar calendar0 = calendars.create(1492,10,12);
Calendar calendar1 = calendars.create(1666,9,2);
Calendar calendar2 = calendars.create(1835,12,16);
Calendar calendar3 = calendars.create(1901,5,3);
Calendar calendar4 = calendars.create(1922,9,13);
ctx.setVariable( "calendar0", calendar0 );
ctx.setVariable( "calendar1", calendar1 );
ctx.setVariable( "calendar2", calendar2 );
ctx.setVariable( "calendar3", calendar3 );
ctx.setVariable( "calendar4", calendar4 );
Calendar[] calendarArray = {calendar0,calendar1,calendar2,calendar3,calendar4};
ctx.setVariable( "calendarArray", calendarArray );
Set<Calendar> calendarSet = new HashSet<Calendar>();
List<Calendar> calendarArrayAsList = Arrays.asList( calendarArray );
Collections.sort( calendarArrayAsList );
calendarSet.addAll( calendarArrayAsList );
ctx.setVariable( "calendarSet", calendarSet );
ctx.setVariable( "a", "Letter A" );
ctx.setVariable( "b", "Letter B" );
ctx.setVariable( "class", "This is a class text" );
VariablesMap<String,Object> variables = ctx.getVariables();
if( variables == null ) {
variables = new VariablesMap<String,Object>();
ctx.setVariables( variables );
}
/*
["onex", 123],
["twox", 254123154123124],
["threex", 0.124],
["fourx", 0.1243541231123123124123125412312],
["fivex", 254123154123124.123125452131243],
["numberListx", "#[#onex, #twox, #threex, #fourx, #fivex]" ],
["integerListx", "#[#onex, #twox]" ],
["decimalListx", "#[#threex, #fourx, #fivex]" ]
*/
Number onex = new java.math.BigInteger("123");
Number twox = new java.math.BigInteger("254123154123124");
Number threex = new java.math.BigDecimal("0.124");
// Number fourx = new java.math.BigDecimal("0.1243541231123123124123125412312");
Number fourx = new java.math.BigDecimal("0.12435412311231231");
// Number fivex = new java.math.BigDecimal("254123154123124.123125452131243");
Number fivex = new java.math.BigDecimal("254123154123124.1250");
ctx.setVariable( "onex", onex );
ctx.setVariable( "twox", twox );
ctx.setVariable( "threex", threex );
ctx.setVariable( "fourx", fourx );
ctx.setVariable( "fivex", fivex );
Number[] numberArray = {onex,twox,threex,fourx,fivex};
List<Number> numberListx = Arrays.asList( numberArray );
ctx.setVariable( "numberListx", numberListx );
Number[] integerArray = {onex,twox};
List<Number> integerListx = Arrays.asList( integerArray );
ctx.setVariable( "integerListx", integerListx );
Number[] decimalArray = {threex,fourx,fivex};
List<Number> decimalListx = Arrays.asList( decimalArray );
ctx.setVariable( "decimalListx", decimalListx );
/*
["oney", "one"],
["twoy", "two"],
["threey", "three"],
["strListy", "#[#oney, #twoy, #threey]" ]
*/
ctx.setVariable( "oney", "one" );
ctx.setVariable( "twoy", "two" );
ctx.setVariable( "threey", "three" );
List<String> strListy = Arrays.asList( new String[] {"one","two","three"} );
ctx.setVariable( "strListy", strListy );
/*
["anotherOney", "one"],
["anotherOne2y", "oneone"],
["anotherTwoy", "TWO"]];
*/
ctx.setVariable( "anotherOney", "one" );
ctx.setVariable( "anotherOne2y", "oneone" );
ctx.setVariable( "anotherTwoy", "TWO" );
ctx.setVariable( "anully", null );
/*
var p1 = new ThParam("Hello world!");
var p2 = new ThParam("Bonjour tout le monde!");
var p3 = new ThParam("Hola mundo!");
var p4 = new ThParam("Kaixo mundua!");
var pArray = [p1,p2,p3,p4];
thymol.applicationContext.createVariable("p1", p1 );
thymol.applicationContext.createVariable("p2", p2 );
thymol.applicationContext.createVariable("p3", p3 );
thymol.applicationContext.createVariable("p4", p4 );
thymol.applicationContext.createVariable("pArray", pArray );
thymol.applicationContext.createVariable("pSet", ThSet.prototype.fromArray(pArray) );
*/
String p1 = "Hello world!";
String p2 = "Bonjour tout le monde!";
String p3 = "Hola mundo!";
String p4 = "Kaixo mundua!";
ctx.setVariable( "p1", p1 );
ctx.setVariable( "p2", p2 );
ctx.setVariable( "p3", p3 );
ctx.setVariable( "p4", p4 );
String[] pArray = {p1,p2,p3,p4};
Arrays.sort( pArray );
ctx.setVariable( "pArray", pArray );
List<String> pList = Arrays.asList( pArray );
ctx.setVariable( "pList", pList );
Set<String> pSet = new TreeSet<String>( pList );
ctx.setVariable( "pSet", pSet );
/*
var b1 = "o";
var b2 = " ";
var b3 = "X";
var bArray = [b1,b2,b3];
thymol.applicationContext.createVariable("bArray", bArray );
var a1 = "O";
var a2 = "";
var a3 = "!";
var aArray = [a1,a2,a3];
thymol.applicationContext.createVariable("aArray", aArray );
*/
String b1 = "o";
String b2 = " ";
String b3 = "X";
String[] bArray = {b1,b2,b3};
ctx.setVariable( "bArray", bArray );
String a1 = "O";
String a2 = "";
String a3 = "!";
String[] aArray = {a1,a2,a3};
ctx.setVariable( "aArray", aArray );
String ps1 = "Bonjour tout le monde! ";
String ps2 = " Hello world! ";
String ps3 = " Hola mundo!";
String ps4 = "\tKaixo mundua!\t\n";
String[] psArray = {ps1,ps2,ps3,ps4};
// psArray = psArray.sort();
ctx.setVariable("ps1", ps1 );
ctx.setVariable("ps2", ps2 );
ctx.setVariable("ps3", ps3 );
ctx.setVariable("ps4", ps4 );
ctx.setVariable("psArray", psArray );
List<String> psList = Arrays.asList( psArray );
ctx.setVariable( "psList", psList );
Set<String> psSet = new TreeSet<String>( psList );
ctx.setVariable( "psSet", psSet );
String s1 = "the quick brown fox jumps over the\nlazy dog";
String s2 = "\t\tevery\tgood\tboy\tdeserves\tfavour\t\t";
// char cr = 13;
// var s3 = "\na\n\"rose\"\nby\nany\n'other'\nname would n'ere smell\vas\fsweet\r"; // Selenium translates the /r to /n and so tests fail
// var s3 = "\na\n\"rose\"\nby\nany\n'other'\nname would n'ere smell\vas\fsweet\n";
// String s3 = "\na\n\"rose\"\nby\nany\n'other'\nname would n'ere smell" + "\u000B" + "as\fsweet" + cr;
String s3 = "\na\n\"rose\"\nby\nany\n'other'\nname would n'ere smell" + "\u000B" + "as\fsweet\n";
ctx.setVariable("s1", s1 );
ctx.setVariable("s2", s2 );
ctx.setVariable("s3", s3 );
String[] sArray = {s1,s2,s3};
Arrays.sort( sArray );
ctx.setVariable("sArray", sArray );
List<String> sList = Arrays.asList( sArray );
ctx.setVariable( "sList", sList );
Set<String> sSet = new TreeSet<String>( sList );
ctx.setVariable( "sSet", sSet );
String sa1 = "the~quick#brown@fox:jumps:@~over#the#lazy#dog";
String sa2 = "~~~every:good@boy~deserves#favour~~~";
String sa3 = "a?rose?by?any?other?name?would?n'ere?smell?as?sweet";
ctx.setVariable("sa1", sa1 );
ctx.setVariable("sa2", sa2 );
ctx.setVariable("sa3", sa3 );
String[] saArray = {sa1,sa2,sa3};
Arrays.sort( saArray );
ctx.setVariable("saArray", saArray );
List<String> saList = Arrays.asList( saArray );
ctx.setVariable( "saList", saList );
Set<String> saSet = new TreeSet<String>( saList );
ctx.setVariable( "saSet", saSet );
String xs1 = "<a>b<c></a>";
ctx.setVariable( "xs1", xs1 );
String xs2 = "Be consistent when you use apostrophes after words that end in \"s.</b><b>\"</b> When someone's name ends with an \"s,\" it is acceptable to use an apostrophe without an \"s\" to show ownership, but linguists with the Chicago Manual of Style, along with others, prefer to add an \"s\" after the apostrophe.";
ctx.setVariable( "xs2", xs2 );
String xs3 = "If the family's last name ends in \"s,\" make it plural before adding an apostrophe. For instance, if you wanted to discuss the Williams family, they would become \"the Williamses\" in a plural sense. If you wanted to reference their dog, you'd say \"the Williamses' dog.\" If the last name seems awkward to say that way, sidestep the issue by saying \"the Williams family\" and \"the Williams family's dog.\"";
ctx.setVariable( "xs3", xs3 );
String xs4 = "<b class=\"whb\">Use apostrophes in contractions.</b> Sometimes, especially in <a href=\"/Avoid-Colloquial-(Informal)-Writing\" title=\"Avoid Colloquial (Informal) Writing\">informal writing</a>, apostrophes are used to indicate one or more missing letters. For example, the word \"don't\" is short for \"do not\"; other examples include \"isn't,\" \"wouldn't,\" and \"can't.\" Contractions can also be made with the verbs \"is,\" \"has,\" and \"have.\" For example, we can write \"She's going to school\" instead of \"She is going to school\"; or \"He's lost the game\" instead of \"He has lost the game.\"<div class=\"clearall\"></div>";
ctx.setVariable( "xs4", xs4 );
String[] xsArray = {xs1,xs2,xs3,xs4};
Arrays.sort( xsArray );
ctx.setVariable("xsArray", xsArray );
List<String> xsList = Arrays.asList( xsArray );
ctx.setVariable( "xsList", xsList );
Set<String> xsSet = new TreeSet<String>( xsList );
ctx.setVariable( "xsSet", xsSet );
String s4 = "silly m\\u009";
String s5 = "someone needs a\\";
String s6 = "silly M\\u09ngo and Midge";
ctx.setVariable( "s4", s4 );
ctx.setVariable( "s5", s5 );
ctx.setVariable( "s6", s6 );
// var sa2Array = ([sa1,null,"",sa2,"",null,sa3]);
// thymol.applicationContext.createVariable("sa2Array", sa2Array );
// var sa3Array = ([sa1,null,"",sa2,"",null,sa3]).sort();
// var sa2Set = ThSet.prototype.fromArray(sa3Array);
// thymol.applicationContext.createVariable("sa2Set", sa2Set );
String[] sa2Array = {sa1,null,"",sa2,"",null,sa3};
ctx.setVariable("sa2Array", sa2Array );
String[] sa3Array = {sa1,"",sa2,"",sa3}; // Don't include the nulls Sets don't like nulls
// Arrays.sort( sa3Array );
List<String> sa3List = Arrays.asList( sa3Array );
Set<String> sa2Set = new TreeSet<String>( sa3List );
ctx.setVariable("sa2Set", sa2Set );
// String fred;
String ox1 = "Hello world!";
String ox2 = "Bonjour tout le monde!";
String ox3 = "Hola mundo!";
String ox4 = "Kaixo mundua!";
String[] oxArray = {ox1,null,null,ox4};
// Arrays.sort( oxArray );
ctx.setVariable( "ox1", ox1 );
ctx.setVariable( "ox2", ox2 );
ctx.setVariable( "ox3", ox3 );
ctx.setVariable( "ox4", ox4 );
ctx.setVariable( "oxArray", oxArray );
List<String> oxList = Arrays.asList( oxArray );
ctx.setVariable( "oxList", oxList );
Set<String> oxSet = new HashSet<String>( oxList );
ctx.setVariable( "oxSet", oxSet );
Object bx1 = "Hello world!";
String bx2 = new String("Hole mundo");
String bx3 = "Bonjour tout le monde!";
double bx4 = 28.2743334/9;
int bx5 = 1;
int bx6 = 0;
Object[] bxArray = {bx1,null,null,bx4,bx5,bx6};
ctx.setVariable( "bx1", bx1 );
ctx.setVariable( "bx2", bx2 );
ctx.setVariable( "bx3", bx3 );
ctx.setVariable( "bx4", bx4 );
ctx.setVariable( "bx5", bx5 );
ctx.setVariable( "bx6", bx6 );
ctx.setVariable( "bxArray", bxArray );
List<Object> bxList = Arrays.asList( bxArray );
ctx.setVariable( "bxList", bxList );
Set<Object> bxSet = new HashSet<Object>( bxList );
ctx.setVariable( "bxSet", bxSet );
Object[] bx2Array = {Boolean.TRUE,Boolean.TRUE,Boolean.TRUE,Boolean.TRUE};
ctx.setVariable( "bx2Array", bx2Array );
List<Object> bx2List = Arrays.asList( bx2Array );
Set<Object> bx2Set = new HashSet<Object>( bx2List );
ctx.setVariable( "bx2Set", bx2Set );
Object[] bx3Array = {Boolean.FALSE,Boolean.FALSE,Boolean.FALSE,Boolean.FALSE};
ctx.setVariable( "bx3Array", bx3Array );
List<Object> bx3List = Arrays.asList( bx3Array );
Set<Object> bx3Set = new HashSet<Object>( bx3List );
ctx.setVariable( "bx3Set", bx3Set );
String target = "<stuff>hello world!</stuff>";
String[] before = {"&"," "};
String[] after = {"%26","+"};
ctx.setVariable( "target", target );
ctx.setVariable( "before", before );
ctx.setVariable( "after", after );
Integer[] ar1 = { new Integer(1), new Integer(3), new Integer(57), new Integer(99) };
// int[] ar1 = { 1, 3, 57, 99 };
// Arrays.sort( ar1 );
Double[] ar2 = { new Double(1.1), new Double(3.3), new Double(57.57), new Double(99.99) };
// Arrays.sort( ar2 );
String[] ar3 = { "1", "3", "57", "99" };
Arrays.sort( ar3 );
String[] ar4 = { new String("1"), new String("3"), new String("57"), new String("99") };
Arrays.sort( ar4 );
String[] ar5 = { "one", "three", "fifty-seven", "ninety-nine" };
Arrays.sort( ar5 );
String[] ar6 = { new String("one"), new String("three"), new String("fifty-seven"), new String("ninety-nine") };
Arrays.sort( ar6 );
Boolean[] ar7 = { Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, Boolean.TRUE };
String[] ar8 = {};
Integer[] ar9 = { 1, 3, 99 };
// Arrays.sort( ar9 );
Integer[] ar10 = { 1, 101, 3, 57, 99 };
// Arrays.sort( ar10 );
String[] ar11 = { "one", "three", "ninety-nine" };
Arrays.sort( ar11 );
String[] ar12 = { "one", "three", "fifty-seven", "ninety-nine", "one-hundred-and-one" };
Arrays.sort( ar12 );
Integer[] ar13 = { 1, 57, 3, 57, 99 };
Arrays.sort( ar13 );
Double[] ar14 = { new Double(1.1), new Double(3.3), new Double(57.57), new Double(3.3), new Double(99.99) };
String[] ar15 = { "1", "99", "3", "57", "99" };
Arrays.sort( ar15 );
String[] ar16 = { new String("1"), new String("3"), new String("57"), new String("99"), new String("1") };
Arrays.sort( ar16 );
String[] ar17 = { "one", "three", "three", "three", "fifty-seven", "fifty-seven", "ninety-nine" };
Arrays.sort( ar17 );
ctx.setVariable( "ar1", ar1 );
ctx.setVariable( "ar2", ar2 );
ctx.setVariable( "ar3", ar3 );
ctx.setVariable( "ar4", ar4 );
ctx.setVariable( "ar5", ar5 );
ctx.setVariable( "ar6", ar6 );
ctx.setVariable( "ar7", ar7 );
ctx.setVariable( "ar8", ar8 );
ctx.setVariable( "ar9", ar9 );
ctx.setVariable( "ar10", ar10 );
ctx.setVariable( "ar11", ar11 );
ctx.setVariable( "ar12", ar12 );
ctx.setVariable( "ar13", ar13 );
ctx.setVariable( "ar14", ar14 );
ctx.setVariable( "ar15", ar15 );
ctx.setVariable( "ar16", ar16 );
ctx.setVariable( "ar17", ar17 );
List<Integer> ar1List = Arrays.asList( ar1 );
List<String> ar5List = Arrays.asList( ar5 );
List<String> ar6List = Arrays.asList( ar6 );
List<String> ar8List = Arrays.asList( ar8 );
List<Integer> ar9List = Arrays.asList( ar9 );
List<Integer> ar10List = Arrays.asList( ar10 );
List<String> ar11List = Arrays.asList( ar11 );
List<String> ar12List = Arrays.asList( ar12 );
List<Integer> ar13List = Arrays.asList( ar13 );
List<Double> ar14List = Arrays.asList( ar14 );
List<String> ar15List = Arrays.asList( ar15 );
List<String> ar16List = Arrays.asList( ar16 );
List<String> ar17List = Arrays.asList( ar17 );
ctx.setVariable( "ar1List", ar1List );
ctx.setVariable( "ar5List", ar5List );
ctx.setVariable( "ar6List", ar6List );
ctx.setVariable( "ar8List", ar8List );
ctx.setVariable( "ar9List", ar9List );
ctx.setVariable( "ar10List", ar10List );
ctx.setVariable( "ar11List", ar11List );
ctx.setVariable( "ar12List", ar12List );
ctx.setVariable( "ar13List", ar13List );
ctx.setVariable( "ar14List", ar14List );
ctx.setVariable( "ar15List", ar15List );
ctx.setVariable( "ar16List", ar16List );
ctx.setVariable( "ar17List", ar17List );
ctx.setVariable( "as1", new TreeSet<Object>( ar1List ) );
ctx.setVariable( "as2", new TreeSet<Object>( Arrays.asList( ar2 ) ) );
ctx.setVariable( "as3", new TreeSet<Object>( Arrays.asList( ar3 ) ) );
ctx.setVariable( "as4", new TreeSet<Object>( Arrays.asList( ar4 ) ) );
ctx.setVariable( "as5", new TreeSet<Object>( ar5List ) );
ctx.setVariable( "as6", new TreeSet<Object>( ar6List ) );
ctx.setVariable( "as7", new TreeSet<Object>( Arrays.asList( ar7 ) ) );
ctx.setVariable( "as8", new TreeSet<Object>( Arrays.asList( ar8 ) ) );
ctx.setVariable( "as9", new TreeSet<Object>( ar9List ) );
ctx.setVariable( "as10", new TreeSet<Object>( ar10List ) );
ctx.setVariable( "as11", new TreeSet<Object>( ar11List ) );
ctx.setVariable( "as12", new TreeSet<Object>( ar12List ) );
ctx.setVariable( "as13", new TreeSet<Object>( ar13List ) );
ctx.setVariable( "as14", new TreeSet<Object>( ar14List ) );
ctx.setVariable( "as15", new TreeSet<Object>( ar15List ) );
ctx.setVariable( "as16", new TreeSet<Object>( ar16List ) );
ctx.setVariable( "as17", new TreeSet<Object>( ar17List ) );
Object junkInstance = new JunkObject("junk");
Class<?> junktype = junkInstance.getClass();
ctx.setVariable( "jt", junktype );
Set<Object> ao1 = new HashSet<Object>();
ao1.add( ar1List );
ao1.add( "two" );
ctx.setVariable( "ao1", ao1 );
Map<String,Object[]> tm1 = new HashMap<String,Object[]>();
tm1.put("ar1",ar1);
tm1.put("ar2",ar2);
tm1.put("ar3",ar3);
tm1.put("ar4",ar4);
ctx.setVariable( "tm1", tm1 );
String[] ka1 = {"ar1","ar2","ar3","ar4"};
ctx.setVariable( "ka1", ka1 );
Object[] va1 = {ar1,ar2,ar3,ar4};
ctx.setVariable( "va1", va1 );
Set< String > ks1 = new HashSet< String >();
ks1.add("ar1");
ks1.add("ar2");
ks1.add("ar3");
ks1.add("ar4");
ctx.setVariable( "ks1", ks1 );
Set< Object[] > vs1 = new HashSet< Object[] >();
vs1.add(ar1);
vs1.add(ar2);
vs1.add(ar3);
vs1.add(ar4);
ctx.setVariable( "vs1", vs1 );
String[] ka2 = {"ar1","ar2","ar3","ar4","ar5"};
ctx.setVariable( "ka2", ka2 );
Object[] va2 = {ar1,ar2,ar3,ar4,ar5};
ctx.setVariable( "va2", va2 );
Set< String > ks2 = new HashSet< String >();
ks2.add("ar1");
ks2.add("ar2");
ks2.add("ar3");
ks2.add("ar4");
ks2.add("ar5");
ctx.setVariable( "ks2", ks2 );
Set< Object[] > vs2 = new HashSet< Object[] >();
vs2.add(ar1);
vs2.add(ar2);
vs2.add(ar3);
vs2.add(ar4);
vs2.add(ar5);
ctx.setVariable( "vs2", vs2 );
String[] ka3 = {"ar1","ar2","ar3"};
ctx.setVariable( "ka3", ka3 );
Object[] va3 = {ar1,ar2,ar3};
ctx.setVariable( "va3", va3 );
Set< String > ks3 = new HashSet< String >();
ks3.add("ar1");
ks3.add("ar2");
ks3.add("ar3");
ctx.setVariable( "ks3", ks3 );
Set< Object[] > vs3 = new HashSet< Object[] >();
vs3.add(ar1);
vs3.add(ar2);
vs3.add(ar3);
ctx.setVariable( "vs3", vs3 );
Set< Object[] > tm2 = new HashSet< Object[] >();
tm2.add(ar1);
tm2.add(ar2);
tm2.add(ar3);
tm2.add(ar4);
ctx.setVariable( "tm2", tm2 );
Map<String,Object[]> tm3 = new HashMap<String,Object[]>();
tm3.put("ar1",ar1);
tm3.put("ar2",ar2);
tm3.put("ar3",ar1);
tm3.put("ar4",null);
ctx.setVariable( "tm3", tm3 );
Object tm4 = new Object();
// Map<String,Object[]> tm4m = new HashMap<String,Object[]>();
// tm4m.put( "ar1", ar1 );
// tm4m.put( "ar2", ar2 );
// tm4m.put( "ar3", ar3 );
// tm4m.put( "ar4", ar4 );
// tm4 = tm4m;
ctx.setVariable( "tm4", tm4 );
Map<String,Object[]> tm5 = new HashMap<String,Object[]>();
ctx.setVariable( "tm5", tm5 );
// aol.
// ao1["one"] = ar1;
// ao1[2] = "two";
ctx.setVariable( "var01", "John Apricot" );
ctx.setVariable( "var02", "John Apricot Jr." );
ctx.setVariable( "var03", "Saturn" );
String[] var04array = {"John Apricot"};
// List<String> var04List = Arrays.asList( var04array );
ctx.setVariable( "var04", var04array );
String[] var05array = {"John Apricot","John Apricot Jr."};
// List<String> var05List = Arrays.asList( var05array );
ctx.setVariable( "var05", var05array );
String[] var06array = {"John Apricot","John Apricot Jr.","Saturn"};
// List<String> var06List = Arrays.asList( var06array );
ctx.setVariable( "var06", var06array );
String[] var07array = {"Joe Bloggs","Grimsby","fish"};
List<String> var07List = Arrays.asList( var07array );
ctx.setVariable( "var07", var07array );
ctx.setVariable( "var07List", var07List );
String[] var08array = {"Marie-Antoinette","France","cake"};
List<String> var08List = Arrays.asList( var08array );
ctx.setVariable( "var08", var08array );
ctx.setVariable( "var08List", var08List );
String[] var09array = {"Wallace","62 West Wallaby Street","cheese"};
List<String> var09List = Arrays.asList( var09array );
ctx.setVariable( "var09", var09array );
ctx.setVariable( "var09List", var09List );
String[] var10array = {"Mr. C. Monster","Sesame Street","cookies"};
List<String> var10List = Arrays.asList( var10array );
ctx.setVariable( "var10", var10array );
ctx.setVariable( "var10List", var10List );
String[] msgArray1 = {"msg05","msg06","msg07"};
List<String> msgList1 = Arrays.asList( msgArray1 );
Set<String> msgSet1 = new TreeSet<String>(msgList1);
ctx.setVariable( "msgArray1", msgArray1 );
ctx.setVariable( "msgList1", msgList1 );
ctx.setVariable( "msgSet1", msgSet1 );
ctx.setVariable( "thing1", 1 );
ctx.setVariable( "thing2", 10 );
ctx.setVariable( "level", "../../" );
Map< String, Object > product5Var = new LinkedHashMap< String, Object >();
product5Var.put("name", "Cucumber");
product5Var.put("price", "1.0");
Map< String, Object > product6Var = new LinkedHashMap< String, Object >();
product6Var.put("name", "Melon");
product6Var.put("price", "6.0");
Map< String, Object > product7Var = new LinkedHashMap< String, Object >();
product7Var.put("name", "Beetroot");
product7Var.put("price", "1.45");
Map< String, Object > product8Var = new LinkedHashMap< String, Object >();
product8Var.put("name", "Peach");
product8Var.put("price", "0.75");
Map< String, Object > product9Var = new LinkedHashMap< String, Object >();
product9Var.put("name", "Celery");
product9Var.put("price", "2.0");
Map< String, Object > product10Var = new LinkedHashMap< String, Object >();
product10Var.put("name", "Pineapple");
product10Var.put("price", "28.0");
List< Object > productList2 = new LinkedList< Object >(products);
productList2.add(product5Var);
productList2.add(product6Var);
productList2.add(product7Var);
productList2.add(product8Var);
productList2.add(product9Var);
productList2.add(product10Var);
ctx.setVariable( "productList2", productList2 );
ctx.setVariable( "product2", product2Var );
ctx.setVariable( "v1", new Integer(3) );
Integer[] numListArray = {5, 3, 9, 4, 1, 6, 2, 10, 8, 7};
List< Integer > numList = Arrays.asList( numListArray );
ctx.setVariable( "numList", numList );
Map<String,Object> affiliate = new HashMap<String,Object>();
affiliate.put("identificationCode1","1234");
affiliate.put("identificationCode2","5678");
ctx.setVariable( "affiliate", affiliate );
ctx.setVariable( "base_url2", "/base/url" );
Map< String, Object > user2Var = new LinkedHashMap< String, Object >();
user2Var.put("name", "John Apricot");
user2Var.put("firstName", "John");
user2Var.put("lastName", "Apricot");
user2Var.put("nationality", "Antarctica");
user2Var.put("age", "(no age specified)");
ctx.setVariable( "user2", user2Var );
ctx.setVariable( "onevar2", "Some text over here" );
ctx.setVariable( "twovar2", "Other text (second)" );
/*
var receipt = {
paymentDetails: [
{
key: "PaymentDetailsMaskedAccount",
label: "Account",
value: "1234"
}, {
key: "PaymentDetailsSource",
label: "Entry Mode",
value: "Magstripe"
}, {
key: "PaymentDetailsCardIssueNumber",
label: "Card Issue No.",
value: "01"
}
]
};
*/
Map<String,Object> details1 = new HashMap<String,Object>();
details1.put("key", "PaymentDetailsMaskedAccount");
details1.put("label", "Account");
details1.put("value", "1234");
Map<String,Object> details2 = new HashMap<String,Object>();
details2.put("key", "PaymentDetailsSource");
details2.put("label", "Entry Mode");
details2.put("value", "Magstripe");
Map<String,Object> details3 = new HashMap<String,Object>();
details3.put("key", "PaymentDetailsCardIssueNumber");
details3.put("label", "Card Issue No.");
details3.put("value", "01");
List<Map<String,Object>> paymentDetails = new LinkedList<Map<String,Object>>();
paymentDetails.add(details1);
paymentDetails.add(details2);
paymentDetails.add(details3);
Map<String,List<Map<String,Object>>> receipt = new HashMap<String,List<Map<String,Object>>>();
receipt.put("paymentDetails",paymentDetails);
ctx.setVariable( "receipt", receipt );
}
public static class JunkObject {
String value;
JunkObject(String thing) {
this.value = thing;
}
}
} |
package org.vaadin.viritin.fields;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.vaadin.viritin.MBeanFieldGroup;
import org.vaadin.viritin.button.MButton;
import com.vaadin.server.FontAwesome;
import com.vaadin.ui.AbstractField;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.Component;
import com.vaadin.ui.Field;
import com.vaadin.ui.GridLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.themes.ValoTheme;
/**
* A field suitable for editing collection of referenced objects tied to parent
* object only. E.g. OneToMany/ElementCollection fields in JPA world.
* <p>
* Some features/restrictions:
* <ul>
* <li>The field is valid when all elements are valid.
* <li>The field is always non buffered
* <li>The element type needs to have an empty parameter constructor or user
* must provide an Instantiator.
* </ul>
*
* Elements in the edited collection are modified with BeanFieldGroup. Fields
* should defined in a class. A simple usage example for editing
* List>Address< adresses:
* <pre><code>
* public static class AddressRow {
* EnumSelect type = new EnumSelect();
* MTextField street = new MTextField();
* MTextField city = new MTextField();
* MTextField zipCode = new MTextField();
* }
*
* public static class PersonForm<Person> extends AbstractForm {
* private final ElementCollectionField<Address> addresses
* = new ElementCollectionField<Address>(Address.class,
* AddressRow.class).withCaption("Addressess");
*
* </code></pre>
*
* <p>
* Components in row model class don't need to match properties in the edited
* entity. So you can add "custom columns" just by introducing them in your
* editor row.
* <p>
* By default the field always contains an empty instance to create new rows. If
* instances are added with some other method (or UI shouldn't add them at all),
* you can configure this with setAllowNewItems. Deletions can be configured
* with setAllowRemovingItems.
* <p>
* If developer needs to do some additional logic during element
* addition/removal, one can subscribe to related events using
* addElementAddedListener/addElementRemovedListener.
*
*
* @author Matti Tahvonen
* @param <ET> The type in the entity collection. The type must have empty
* parameter constructor or you have to provide Instantiator.
*
*/
public class ElementCollectionField<ET> extends AbstractElementCollection<ET> {
List<ET> items = new ArrayList<ET>();
boolean inited = false;
GridLayout layout = new GridLayout();
public ElementCollectionField(Class<ET> elementType,
Class<?> formType) {
super(elementType, formType);
}
public ElementCollectionField(Class<ET> elementType, Instantiator i,
Class<?> formType) {
super(elementType, i, formType);
}
@Override
public void addInternalElement(final ET v) {
ensureInited();
items.add(v);
MBeanFieldGroup<ET> fg = getFieldGroupFor(v);
for (Object property : getVisibleProperties()) {
Component c = fg.getField(property);
if (c == null) {
c = getComponentFor(v, property.toString());
Logger.getLogger(ElementCollectionField.class.getName())
.log(Level.WARNING, "No editor field for{0}", property);
}
layout.addComponent(c);
layout.setComponentAlignment(c, Alignment.MIDDLE_LEFT);
}
if (isAllowRemovingItems()) {
layout.addComponent(new MButton(FontAwesome.TRASH_O).withListener(
new Button.ClickListener() {
@Override
public void buttonClick(Button.ClickEvent event) {
removeElement(v);
}
}).withStyleName(ValoTheme.BUTTON_ICON_ONLY));
}
if (!isAllowEditItems()) {
fg.setReadOnly(true);
}
}
@Override
public void removeInternalElement(ET v) {
int index = itemsIdentityIndexOf(v);
items.remove(index);
int row = index + 1;
layout.removeRow(row);
}
@Override
public GridLayout getLayout() {
return layout;
}
@Override
public void setPersisted(ET v, boolean persisted) {
int row = itemsIdentityIndexOf(v) + 1;
if (isAllowRemovingItems()) {
Button c = (Button) layout.getComponent(getVisibleProperties().
size(),
row);
if (persisted) {
c.setDescription(getDeleteElementDescription());
} else {
for (int i = 0; i < getVisibleProperties().size(); i++) {
try {
AbstractField f = (AbstractField) (Field) layout.
getComponent(i,
row);
f.setValidationVisible(false);
} catch (Exception e) {
}
}
c.setDescription(getDisabledDeleteElementDescription());
}
c.setEnabled(persisted);
}
}
private int itemsIdentityIndexOf(Object o) {
for (int index = 0; index < items.size(); index++) {
if (items.get(index) == o) {
return index;
}
}
return -1;
}
private void ensureInited() {
if (!inited) {
layout.setSpacing(true);
int columns = getVisibleProperties().size();
if (isAllowRemovingItems()) {
columns++;
}
layout.setColumns(columns);
for (Object property : getVisibleProperties()) {
Label header = new Label(getPropertyHeader(property.
toString()));
header.setWidthUndefined();
layout.addComponent(header);
}
if (isAllowRemovingItems()) {
// leave last header slot empty, "actions" colunn
layout.newLine();
}
inited = true;
}
}
public ElementCollectionField<ET> withEditorInstantiator(
Instantiator instantiator) {
setEditorInstantiator(instantiator);
return this;
}
@Override
public void clear() {
if (inited) {
items.clear();
int rows = inited ? 1 : 0;
while (layout.getRows() > rows) {
layout.removeRow(rows);
}
}
}
public String getDisabledDeleteElementDescription() {
return disabledDeleteThisElementDescription;
}
public void setDisabledDeleteThisElementDescription(
String disabledDeleteThisElementDescription) {
this.disabledDeleteThisElementDescription = disabledDeleteThisElementDescription;
}
private String disabledDeleteThisElementDescription = "Fill this row to add a new element, currently ignored";
public String getDeleteElementDescription() {
return deleteThisElementDescription;
}
private String deleteThisElementDescription = "Delete this element";
public void setDeleteThisElementDescription(
String deleteThisElementDescription) {
this.deleteThisElementDescription = deleteThisElementDescription;
}
@Override
public void onElementAdded() {
if (isAllowNewItems()) {
newInstance = createInstance();
addInternalElement(newInstance);
setPersisted(newInstance, false);
}
}
@Override
public ElementCollectionField<ET> setPropertyHeader(String propertyName,
String propertyHeader) {
super.setPropertyHeader(propertyName, propertyHeader);
return this;
}
@Override
public ElementCollectionField<ET> setVisibleProperties(
List<String> properties, List<String> propertyHeaders) {
super.setVisibleProperties(properties, propertyHeaders);
return this;
}
@Override
public ElementCollectionField<ET> setVisibleProperties(
List<String> properties) {
super.setVisibleProperties(properties);
return this;
}
@Override
public ElementCollectionField<ET> setAllowNewElements(
boolean allowNewItems) {
super.setAllowNewElements(allowNewItems);
return this;
}
@Override
public ElementCollectionField<ET> setAllowRemovingItems(
boolean allowRemovingItems) {
super.setAllowRemovingItems(allowRemovingItems);
return this;
}
@Override
public ElementCollectionField<ET> withCaption(String caption) {
super.withCaption(caption);
return this;
}
@Override
public ElementCollectionField<ET> removeElementRemovedListener(
ElementRemovedListener listener) {
super.removeElementRemovedListener(listener);
return this;
}
@Override
public ElementCollectionField<ET> addElementRemovedListener(
ElementRemovedListener<ET> listener) {
super.addElementRemovedListener(listener);
return this;
}
@Override
public ElementCollectionField<ET> removeElementAddedListener(
ElementAddedListener listener) {
super.removeElementAddedListener(listener);
return this;
}
@Override
public ElementCollectionField<ET> addElementAddedListener(
ElementAddedListener<ET> listener) {
super.addElementAddedListener(listener);
return this;
}
/**
* Expands the column with given property id
*
* @param propertyId the id of column that should be expanded in the UI
* @return the element collection field
*/
public ElementCollectionField<ET> expand(String... propertyId) {
for (String propertyId1 : propertyId) {
int index = getVisibleProperties().indexOf(propertyId1);
if (index == -1) {
throw new IllegalArgumentException(
"The expanded property must available");
}
layout.setColumnExpandRatio(index, 1);
}
if (layout.getWidth() == -1) {
layout.setWidth(100, Unit.PERCENTAGE);
}
// TODO should also make width of elements automatically 100%, both
// existing and added, now obsolete config needed for row model
return this;
}
public ElementCollectionField<ET> withFullWidth() {
setWidth(100, Unit.PERCENTAGE);
return this;
}
public ElementCollectionField<ET> withId(String id) {
setId(id);
return this;
}
} |
package prm4j.indexing.realtime;
import prm4j.api.BaseEvent;
import prm4j.api.Event;
import prm4j.api.ParametricMonitor;
import prm4j.indexing.BaseMonitor;
import prm4j.indexing.staticdata.ChainData;
import prm4j.indexing.staticdata.EventContext;
import prm4j.indexing.staticdata.JoinData;
import prm4j.indexing.staticdata.MaxData;
import prm4j.indexing.staticdata.MetaNode;
import prm4j.spec.Spec;
public class DefaultParametricMonitor implements ParametricMonitor {
private final BaseMonitor monitorPrototype;
private final BindingStore bindingStore;
private final NodeStore nodeStore;
private final EventContext eventContext;
private long timestamp = 0L;
public DefaultParametricMonitor(MetaNode metaTree, EventContext eventContext, Spec spec) {
this.eventContext = eventContext;
bindingStore = new DefaultBindingStore(spec.getFullParameterSet(), 1);
nodeStore = new DefaultNodeStore(metaTree);
monitorPrototype = spec.getInitialMonitor();
}
public DefaultParametricMonitor(BindingStore bindingStore, NodeStore nodeStore, BaseMonitor monitorPrototype,
EventContext eventContext) {
this.bindingStore = bindingStore;
this.nodeStore = nodeStore;
this.monitorPrototype = monitorPrototype;
this.eventContext = eventContext;
}
@Override
public void processEvent(Event event) {
final LowLevelBinding[] bindings = bindingStore.getBindings(event.getBoundObjects());
final BaseEvent baseEvent = event.getBaseEvent();
final Node instanceNode = nodeStore.getNode(bindings);
final BaseMonitor instanceMonitor = instanceNode.getMonitor();
if (eventContext.isDisablingEvent(event.getBaseEvent())) {
for (LowLevelBinding binding : bindings) {
binding.setDisabled(true);
}
}
if (instanceMonitor == null) {
findMaxPhase: for (MaxData maxData : eventContext.getMaxData(baseEvent)) {
BaseMonitor m = nodeStore.getNode(bindings, maxData.getNodeMask()).getMonitor();
if (m != null) {
for (int i : maxData.getDiffMask()) {
LowLevelBinding b = bindings[i];
if (b.getTimestamp() < timestamp && (b.getTimestamp() > m.getCreationTime() || b.isDisabled())) {
continue findMaxPhase;
}
}
// inlined DefineTo from 73
BaseMonitor monitor = m.copy(bindings); // 102-105
monitor.processEvent(event); // 103
instanceNode.setMonitor(monitor); // 106
// inlined chain-method
for (ChainData chainData : instanceNode.getMetaNode().getChainDataArray()) { // 110
nodeStore.getNode(bindings, chainData.getNodeMask()).getMonitorSet(chainData.getMonitorSetId())
.add(monitor); // 111
} // 107
break findMaxPhase;
}
}
monitorCreation: if (instanceNode.getMonitor() == null) {
if (eventContext.isCreationEvent(baseEvent)) {
for (LowLevelBinding b : bindings) {
if (b.isDisabled()) {
break monitorCreation;
}
}
// inlined DefineNew from 93
BaseMonitor monitor = monitorPrototype.copy(bindings, timestamp); // 94 - 97
monitor.processEvent(event);
instanceNode.setMonitor(monitor);
// inlined chain-method
for (ChainData chainData : instanceNode.getMetaNode().getChainDataArray()) { // 110
nodeStore.getNode(bindings, chainData.getNodeMask()).getMonitorSet(chainData.getMonitorSetId())
.add(monitor); // 111
}
}
}
// inlined Join from 42
joinPhase: for (JoinData joinData : eventContext.getJoinData(baseEvent)) {
long tmax = 0L;
final int[] copyPattern = joinData.getCopyPattern(); // use the copy pattern as diff mask
for (int i = 0; i < copyPattern.length; i = i + 2) {
final LowLevelBinding b = bindings[copyPattern[i]];
final long bTimestamp = b.getTimestamp();
if (bTimestamp < timestamp) {
if (b.isDisabled()) {
continue joinPhase;
} else if (tmax < bTimestamp) {
tmax = bTimestamp;
}
}
}
final boolean someBindingsAreKnown = tmax < timestamp;
final Node compatibleNode = nodeStore.getNode(bindings, joinData.getNodeMask());
// calculate once the bindings to be joined with the whole monitor set
final LowLevelBinding[] joinableBindings = createJoinableBindings(bindings,
joinData.getExtensionPattern()); // 56 - 61
// join is performed in monitor set
compatibleNode.getMonitorSet(joinData.getMonitorSetId()).join(nodeStore, bindings, event,
joinableBindings, someBindingsAreKnown, tmax, joinData.getCopyPattern());
}
} else {
// update phase
instanceMonitor.processEvent(event);
for (MonitorSet monitorSet : instanceNode.getMonitorSets()) { // 30 - 32
monitorSet.processEvent(event);
}
}
for (LowLevelBinding b : bindings) {
b.setTimestamp(timestamp);
}
timestamp++;
}
/**
* Returns an array of bindings containing "gaps" enabling efficient joins by filling these gaps.
*
* @param bindings
* @param extensionPattern
* allows transformation of the bindings to joinable bindings
* @return joinable bindings
*/
static LowLevelBinding[] createJoinableBindings(LowLevelBinding[] bindings, boolean[] extensionPattern) {
final LowLevelBinding[] joinableBindings = new LowLevelBinding[extensionPattern.length];
int sourceIndex = 0;
for (int i = 0; i < extensionPattern.length; i++) {
if (extensionPattern[i]) {
joinableBindings[i] = bindings[sourceIndex++];
}
}
assert sourceIndex == bindings.length : "All bindings have to be taken into account.";
return joinableBindings;
}
@Override
public void reset() {
// TODO Auto-generated method stub
}
} |
package prm4j.indexing.realtime;
import prm4j.Globals;
import prm4j.api.BaseEvent;
import prm4j.api.Event;
import prm4j.api.MatchHandler;
import prm4j.api.ParametricMonitor;
import prm4j.indexing.BaseMonitor;
import prm4j.indexing.staticdata.ChainData;
import prm4j.indexing.staticdata.EventContext;
import prm4j.indexing.staticdata.JoinData;
import prm4j.indexing.staticdata.MaxData;
import prm4j.indexing.staticdata.MetaNode;
import prm4j.spec.Spec;
public class DefaultParametricMonitor implements ParametricMonitor {
protected final BaseMonitor monitorPrototype;
protected BindingStore bindingStore;
protected NodeStore nodeStore;
protected final EventContext eventContext;
protected long timestamp = 0L;
protected final NodeManager nodeManager;
protected final ParametricMonitorLogger logger;
/**
* Creates a DefaultParametricMonitor using default {@link BindingStore} and {@link NodeStore} implementations (and
* configurations).
*
* @param metaTree
* @param eventContext
* @param spec
*/
public DefaultParametricMonitor(MetaNode metaTree, EventContext eventContext, Spec spec) {
this.eventContext = eventContext;
bindingStore = new DefaultBindingStore(new DefaultBindingFactory(), spec.getFullParameterSet());
monitorPrototype = spec.getInitialMonitor();
nodeManager = new NodeManager();
nodeStore = new DefaultNodeStore(metaTree, nodeManager);
logger = Globals.DEBUG ? new ParametricMonitorLogger(bindingStore, nodeStore, nodeManager) : null;
}
/**
* Creates a DefaultParametricMonitor which externally configurable BindingStore and NodeStore.
*
* @param bindingStore
* @param nodeStore
* @param monitorPrototype
* @param eventContext
*/
public DefaultParametricMonitor(BindingStore bindingStore, NodeStore nodeStore, BaseMonitor monitorPrototype,
EventContext eventContext, NodeManager nodeManager) {
this.bindingStore = bindingStore;
this.nodeStore = nodeStore;
this.monitorPrototype = monitorPrototype;
this.eventContext = eventContext;
this.nodeManager = nodeManager;
logger = Globals.DEBUG ? new ParametricMonitorLogger(bindingStore, nodeStore, nodeManager) : null;
}
@Override
public synchronized void processEvent(Event event) {
final BaseEvent baseEvent = event.getBaseEvent();
// selects all bindings from 'bindings' which are not null
final int[] parameterMask = baseEvent.getParameterMask();
// uncompressed representation of bindings
final LowLevelBinding[] bindings = bindingStore.getBindings(event.getBoundObjects());
// node associated to the current bindings. May be NullNode if binding is encountered the first time
Node instanceNode = nodeStore.getNode(bindings, parameterMask);
// monitor associated with the instance node. May be null if the instance node is a NullNode
BaseMonitor instanceMonitor = instanceNode.getMonitor();
// disable all bindings which are
if (eventContext.isDisablingEvent(baseEvent)) {
for (int i = 0; i < parameterMask.length; i++) {
bindings[parameterMask[i]].setDisabled(true);
}
}
if (instanceMonitor == null) {
// direct update phase
for (MonitorSet monitorSet : instanceNode.getMonitorSets()) { // (30 - 32) new
if (monitorSet != null) {
monitorSet.processEvent(event);
}
}
findMaxPhase: for (MaxData maxData : eventContext.getMaxData(baseEvent)) {
BaseMonitor maxMonitor = nodeStore.getNode(bindings, maxData.getNodeMask()).getMonitor();
if (maxMonitor != null) {
for (int i : maxData.getDiffMask()) {
LowLevelBinding b = bindings[i];
if (b.getTimestamp() < timestamp
&& (b.getTimestamp() > maxMonitor.getCreationTime() || b.isDisabled())) {
continue findMaxPhase;
}
}
if (instanceNode == NullNode.instance) {
instanceNode = nodeStore.getOrCreateNode(bindings, parameterMask); // get real
// instance node
}
// inlined DefineTo from 73
instanceMonitor = maxMonitor.copy(toCompressedBindings(bindings, parameterMask)); // 102-105
instanceMonitor.process(event); // 103
instanceNode.setMonitor(instanceMonitor); // 106
// inlined chain-method
for (ChainData chainData : instanceNode.getMetaNode().getChainDataArray()) { // 110
nodeStore.getOrCreateNode(bindings, chainData.getNodeMask())
.getMonitorSet(chainData.getMonitorSetId()).add(instanceNode.getNodeRef()); // 111
} // 107
break findMaxPhase;
}
}
Node node = null;
monitorCreation: if (instanceMonitor == null) {
if (eventContext.isCreationEvent(baseEvent)) {
for (int i = 0; i < parameterMask.length; i++) {
if (bindings[i].isDisabled()) {
break monitorCreation;
}
}
// inlined DefineNew from 93
instanceMonitor = monitorPrototype.copy(toCompressedBindings(bindings, parameterMask), timestamp);
if (instanceNode == NullNode.instance) {
instanceNode = nodeStore.getOrCreateNode(bindings, parameterMask); // get real
// instance node
}
instanceNode.setMonitor(instanceMonitor);
// since we need some information in the meta node, we cannot process the event first before node
// creation
instanceMonitor.process(event);
// inlined chain-method
for (ChainData chainData : instanceNode.getMetaNode().getChainDataArray()) { // 110
node = nodeStore.getOrCreateNode(bindings, chainData.getNodeMask());
node.getMonitorSet(chainData.getMonitorSetId()).add(instanceNode.getNodeRef()); // 111
}
}
}
// inlined Join from 42
joinPhase: for (JoinData joinData : eventContext.getJoinData(baseEvent)) {
// if node does not exist there can't be any joinable monitors
final Node compatibleNode = nodeStore.getNode(bindings, joinData.getNodeMask());
if (compatibleNode == NullNode.instance) {
continue joinPhase;
}
// if bindings are disabled, the binding will not add to a valid trace
long tmax = 0L;
final int[] diffMask = joinData.getDiffMask();
for (int i = 0; i < diffMask.length; i++) {
final LowLevelBinding b = bindings[diffMask[i]];
final long bTimestamp = b.getTimestamp();
if (bTimestamp < timestamp) {
if (b.isDisabled()) {
continue joinPhase;
} else if (tmax < bTimestamp) {
tmax = bTimestamp;
}
}
}
final boolean someBindingsAreKnown = tmax < timestamp;
// calculate once the bindings to be joined with the whole monitor set
final LowLevelBinding[] joinableBindings = createJoinableBindings(bindings,
joinData.getExtensionPattern()); // 56 - 61
// join is performed in monitor set
compatibleNode.getMonitorSet(joinData.getMonitorSetId()).join(nodeStore, event, joinableBindings,
someBindingsAreKnown, tmax, joinData.getCopyPattern());
}
} else {
// update phase
instanceMonitor.process(event);
for (MonitorSet monitorSet : instanceNode.getMonitorSets()) { // 30 - 32
if (monitorSet != null) {
monitorSet.processEvent(event);
}
}
}
for (int i = 0; i < parameterMask.length; i++) {
bindings[parameterMask[i]].setTimestamp(timestamp);
}
nodeManager.tryToClean(timestamp);
if (logger != null) {
logger.log(timestamp, event);
}
timestamp++;
}
private static LowLevelBinding[] toCompressedBindings(LowLevelBinding[] uncompressedBindings, int[] parameterMask) {
LowLevelBinding[] result = new LowLevelBinding[parameterMask.length];
int j = 0;
for (int i = 0; i < parameterMask.length; i++) {
result[j++] = uncompressedBindings[parameterMask[i]];
}
return result;
}
/**
* Returns an array of bindings containing "gaps" enabling efficient joins by filling these gaps.
*
* @param bindings
* @param extensionPattern
* allows transformation of the bindings to joinable bindings
* @return joinable bindings
*/
static LowLevelBinding[] createJoinableBindings(LowLevelBinding[] bindings, int[] extensionPattern) {
final LowLevelBinding[] joinableBindings = new LowLevelBinding[extensionPattern.length];
for (int i = 0; i < extensionPattern.length; i++) {
final int e = extensionPattern[i];
if (e >= 0) {
joinableBindings[i] = bindings[e];
}
}
return joinableBindings;
}
@Override
public void reset() {
timestamp = 0L;
if (logger != null) {
logger.reset();
}
bindingStore.reset();
nodeStore.reset();
nodeManager.reset();
BaseMonitor.reset();
MatchHandler.reset();
}
} |
package edu.umd.cs.findbugs;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.StringTokenizer;
import org.apache.bcel.Constants;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InvokeInstruction;
import org.apache.bcel.generic.MethodGen;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.ba.AnalysisContext;
import edu.umd.cs.findbugs.ba.ClassContext;
import edu.umd.cs.findbugs.ba.JavaClassAndMethod;
import edu.umd.cs.findbugs.ba.XField;
import edu.umd.cs.findbugs.ba.XMethod;
import edu.umd.cs.findbugs.ba.bcp.FieldVariable;
import edu.umd.cs.findbugs.visitclass.DismantleBytecode;
import edu.umd.cs.findbugs.visitclass.PreorderVisitor;
import edu.umd.cs.findbugs.xml.XMLAttributeList;
import edu.umd.cs.findbugs.xml.XMLOutput;
/**
* An instance of a bug pattern.
* A BugInstance consists of several parts:
* <p/>
* <ul>
* <li> the type, which is a string indicating what kind of bug it is;
* used as a key for the FindBugsMessages resource bundle
* <li> the priority; how likely this instance is to actually be a bug
* <li> a list of <em>annotations</em>
* </ul>
* <p/>
* The annotations describe classes, methods, fields, source locations,
* and other relevant context information about the bug instance.
* Every BugInstance must have at least one ClassAnnotation, which
* describes the class in which the instance was found. This is the
* "primary class annotation".
* <p/>
* <p> BugInstance objects are built up by calling a string of <code>add</code>
* methods. (These methods all "return this", so they can be chained).
* Some of the add methods are specialized to get information automatically from
* a BetterVisitor or DismantleBytecode object.
*
* @author David Hovemeyer
* @see BugAnnotation
*/
public class BugInstance implements Comparable<BugInstance>, XMLWriteableWithMessages, Serializable, Cloneable {
private static final long serialVersionUID = 1L;
private String type;
private int priority;
private ArrayList<BugAnnotation> annotationList;
private int cachedHashCode;
@NonNull private String annotationText;
private BugProperty propertyListHead, propertyListTail;
private String uniqueId;
/*
* The following fields are used for tracking Bug instances across multiple versions of software.
* They are meaningless in a BugCollection for just one version of software.
*/
private long firstVersion = 0;
private long lastVersion = -1;
private boolean introducedByChangeOfExistingClass;
private boolean removedByChangeOfPersistingClass;
/**
* This value is used to indicate that the cached hashcode
* is invalid, and should be recomputed.
*/
private static final int INVALID_HASH_CODE = 0;
/**
* This value is used to indicate whether BugInstances should be reprioritized very low,
* when the BugPattern is marked as experimental
*/
private static boolean adjustExperimental = false;
/**
* Constructor.
*
* @param type the bug type
* @param priority the bug priority
*/
public BugInstance(String type, int priority) {
this.type = type;
this.priority = priority < Detector.HIGH_PRIORITY
? Detector.HIGH_PRIORITY : priority;
annotationList = new ArrayList<BugAnnotation>(4);
cachedHashCode = INVALID_HASH_CODE;
annotationText = "";
if (adjustExperimental && isExperimental())
this.priority = Detector.EXP_PRIORITY;
}
//@Override
public Object clone() {
BugInstance dup;
try {
dup = (BugInstance) super.clone();
// Do deep copying of mutable objects
for (int i = 0; i < dup.annotationList.size(); ++i) {
dup.annotationList.set(i, (BugAnnotation) dup.annotationList.get(i).clone());
}
dup.propertyListHead = dup.propertyListTail = null;
for (Iterator<BugProperty> i = propertyIterator(); i.hasNext(); ) {
dup.addProperty((BugProperty) i.next().clone());
}
return dup;
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("impossible", e);
}
}
/**
* Create a new BugInstance.
* This is the constructor that should be used by Detectors.
*
* @param detector the Detector that is reporting the BugInstance
* @param type the bug type
* @param priority the bug priority
*/
public BugInstance(Detector detector, String type, int priority) {
this(type, priority);
if (detector != null) {
// Adjust priority if required
DetectorFactory factory =
DetectorFactoryCollection.instance().getFactoryByClassName(detector.getClass().getName());
if (factory != null) {
this.priority += factory.getPriorityAdjustment();
if (this.priority < 0)
this.priority = 0;
}
}
if (adjustExperimental && isExperimental())
this.priority = Detector.EXP_PRIORITY;
}
public static void setAdjustExperimental(boolean adjust) {
adjustExperimental = adjust;
}
/**
* Get the bug type.
*/
public String getType() {
return type;
}
/**
* Get the BugPattern.
*/
public BugPattern getBugPattern() {
return I18N.instance().lookupBugPattern(getType());
}
/**
* Get the bug priority.
*/
public int getPriority() {
return priority;
}
/**
* Set the bug priority.
*/
public void setPriority(int p) {
priority = p < Detector.HIGH_PRIORITY
? Detector.HIGH_PRIORITY : p;
}
/**
* Is this bug instance the result of an experimental detector?
*/
public boolean isExperimental() {
BugPattern pattern = I18N.instance().lookupBugPattern(type);
return (pattern != null) && pattern.isExperimental();
}
/**
* Get the primary class annotation, which indicates where the bug occurs.
*/
public ClassAnnotation getPrimaryClass() {
return (ClassAnnotation) findAnnotationOfType(ClassAnnotation.class);
}
/**
* Get the primary method annotation, which indicates where the bug occurs.
*/
public MethodAnnotation getPrimaryMethod() {
return (MethodAnnotation) findAnnotationOfType(MethodAnnotation.class);
}
/**
* Get the primary method annotation, which indicates where the bug occurs.
*/
public FieldAnnotation getPrimaryField() {
return (FieldAnnotation) findAnnotationOfType(FieldAnnotation.class);
}
/**
* Find the first BugAnnotation in the list of annotations
* that is the same type or a subtype as the given Class parameter.
*
* @param cls the Class parameter
* @return the first matching BugAnnotation of the given type,
* or null if there is no such BugAnnotation
*/
private BugAnnotation findAnnotationOfType(Class<? extends BugAnnotation> cls) {
for (Iterator<BugAnnotation> i = annotationIterator(); i.hasNext();) {
BugAnnotation annotation = i.next();
if (cls.isAssignableFrom(annotation.getClass()))
return annotation;
}
return null;
}
/**
* Get the primary source line annotation.
*
* @return the source line annotation, or null if there is
* no source line annotation
*/
public SourceLineAnnotation getPrimarySourceLineAnnotation() {
// Highest priority: return the first top level source line annotation
for (BugAnnotation annotation : annotationList) {
if (annotation instanceof SourceLineAnnotation)
return (SourceLineAnnotation) annotation;
}
// Next: Try primary method, primary field, primary class
SourceLineAnnotation srcLine;
if ((srcLine = inspectPackageMemberSourceLines(getPrimaryMethod())) != null)
return srcLine;
if ((srcLine = inspectPackageMemberSourceLines(getPrimaryField())) != null)
return srcLine;
if ((srcLine = inspectPackageMemberSourceLines(getPrimaryClass())) != null)
return srcLine;
// Last resort: give up and return null.
// This actually should never happen.
return null;
}
/**
* If given PackageMemberAnnotation is non-null,
* return its SourceLineAnnotation.
*
* @param packageMember a PackageMemberAnnotation
* @return the PackageMemberAnnotation's SourceLineAnnotation, or null
* if there is no SourceLineAnnotation
*/
private SourceLineAnnotation inspectPackageMemberSourceLines(PackageMemberAnnotation packageMember) {
return (packageMember != null) ? packageMember.getSourceLines() : null;
}
/**
* Get an Iterator over all bug annotations.
*/
public Iterator<BugAnnotation> annotationIterator() {
return annotationList.iterator();
}
/**
* Get the abbreviation of this bug instance's BugPattern.
* This is the same abbreviation used by the BugCode which
* the BugPattern is a particular species of.
*/
public String getAbbrev() {
BugPattern pattern = I18N.instance().lookupBugPattern(getType());
return pattern != null ? pattern.getAbbrev() : "<unknown bug pattern>";
}
/**
* Set the user annotation text.
*
* @param annotationText the user annotation text
*/
public void setAnnotationText(@NonNull String annotationText) {
this.annotationText = annotationText;
}
/**
* Get the user annotation text.
*
* @return the user annotation text
*/
@NonNull public String getAnnotationText() {
return annotationText;
}
/**
* Determine whether or not the annotation text contains
* the given word.
*
* @param word the word
* @return true if the annotation text contains the word, false otherwise
*/
public boolean annotationTextContainsWord(String word) {
return getTextAnnotationWords().contains(word);
}
/**
* Get set of words in the text annotation.
*/
public Set<String> getTextAnnotationWords() {
HashSet<String> result = new HashSet<String>();
StringTokenizer tok = new StringTokenizer(annotationText, " \t\r\n\f.,:;-");
while (tok.hasMoreTokens()) {
result.add(tok.nextToken());
}
return result;
}
/**
* Get the BugInstance's unique id.
*
* @return the unique id, or null if no unique id has been assigned
*/
public String getUniqueId() {
return uniqueId;
}
/**
* Set the unique id of the BugInstance.
*
* @param uniqueId the unique id
*/
public void setUniqueId(String uniqueId) {
this.uniqueId = uniqueId;
}
private class BugPropertyIterator implements Iterator<BugProperty> {
private BugProperty prev, cur;
private boolean removed;
/* (non-Javadoc)
* @see java.util.Iterator#hasNext()
*/
public boolean hasNext() {
return findNext() != null;
}
/* (non-Javadoc)
* @see java.util.Iterator#next()
*/
public BugProperty next() {
BugProperty next = findNext();
if (next == null)
throw new NoSuchElementException();
prev = cur;
cur = next;
removed = false;
return cur;
}
/* (non-Javadoc)
* @see java.util.Iterator#remove()
*/
public void remove() {
if (cur == null || removed)
throw new IllegalStateException();
if (prev == null) {
propertyListHead = cur.getNext();
} else {
prev.setNext(cur.getNext());
}
if (cur == propertyListTail) {
propertyListTail = prev;
}
removed = true;
}
private BugProperty findNext() {
return cur == null ? propertyListHead : cur.getNext();
}
}
/**
* Get value of given property.
*
* @param name name of the property to get
* @return the value of the named property, or null if
* the property has not been set
*/
public String getProperty(String name) {
BugProperty prop = lookupProperty(name);
return prop != null ? prop.getValue() : null;
}
/**
* Get value of given property, returning given default
* value if the property has not been set.
*
* @param name name of the property to get
* @param defaultValue default value to return if propery is not set
* @return the value of the named property, or the default
* value if the property has not been set
*/
public String getProperty(String name, String defaultValue) {
String value = getProperty(name);
return value != null ? value : defaultValue;
}
/**
* Get an Iterator over the properties defined in this BugInstance.
*
* @return Iterator over properties
*/
public Iterator<BugProperty> propertyIterator() {
return new BugPropertyIterator();
}
/**
* Set value of given property.
*
* @param name name of the property to set
* @param value the value of the property
* @return this object, so calls can be chained
*/
public BugInstance setProperty(String name, String value) {
BugProperty prop = lookupProperty(name);
if (prop != null) {
prop.setValue(value);
} else {
prop = new BugProperty(name, value);
addProperty(prop);
}
return this;
}
/**
* Look up a property by name.
*
* @param name name of the property to look for
* @return the BugProperty with the given name,
* or null if the property has not been set
*/
public BugProperty lookupProperty(String name) {
BugProperty prop = propertyListHead;
while (prop != null) {
if (prop.getName().equals(name))
break;
prop = prop.getNext();
}
return prop;
}
/**
* Delete property with given name.
*
* @param name name of the property to delete
* @return true if a property with that name was deleted,
* or false if there is no such property
*/
public boolean deleteProperty(String name) {
BugProperty prev = null;
BugProperty prop = propertyListHead;
while (prop != null) {
if (prop.getName().equals(name))
break;
prev = prop;
prop = prop.getNext();
}
if (prop != null) {
if (prev != null) {
// Deleted node in interior or at tail of list
prev.setNext(prop.getNext());
} else {
// Deleted node at head of list
propertyListHead = prop.getNext();
}
if (prop.getNext() == null) {
// Deleted node at end of list
propertyListTail = prev;
}
return true;
} else {
// No such property
return false;
}
}
private void addProperty(BugProperty prop) {
if (propertyListTail != null) {
propertyListTail.setNext(prop);
propertyListTail = prop;
} else {
propertyListHead = propertyListTail = prop;
}
prop.setNext(null);
}
/**
* Add a Collection of BugAnnotations.
*
* @param annotationCollection Collection of BugAnnotations
*/
public void addAnnotations(Collection<BugAnnotation> annotationCollection) {
for (BugAnnotation annotation : annotationCollection) {
add(annotation);
}
}
/**
* Add a class annotation and a method annotation for the class and method
* which the given visitor is currently visiting.
*
* @param visitor the BetterVisitor
* @return this object
*/
public BugInstance addClassAndMethod(PreorderVisitor visitor) {
addClass(visitor);
addMethod(visitor);
return this;
}
/**
* Add class and method annotations for given method.
*
* @param methodAnnotation the method
* @return this object
*/
public BugInstance addClassAndMethod(MethodAnnotation methodAnnotation) {
addClass(methodAnnotation.getClassName(), methodAnnotation.getSourceFileName());
addMethod(methodAnnotation);
return this;
}
/**
* Add class and method annotations for given method.
*
* @param methodGen the method
* @param sourceFile source file the method is defined in
* @return this object
*/
public BugInstance addClassAndMethod(MethodGen methodGen, String sourceFile) {
addClass(methodGen.getClassName(), sourceFile);
addMethod(methodGen, sourceFile);
return this;
}
/**
* Add class and method annotations for given class and method.
*
* @param javaClass the class
* @param method the method
* @return this object
*/
public BugInstance addClassAndMethod(JavaClass javaClass, Method method) {
addClass(javaClass.getClassName(), javaClass.getSourceFileName());
addMethod(javaClass, method);
return this;
}
/**
* Add a class annotation. If this is the first class annotation added,
* it becomes the primary class annotation.
*
* @param className the name of the class
* @param sourceFileName the source file of the class
* @return this object
*/
public BugInstance addClass(String className, String sourceFileName) {
ClassAnnotation classAnnotation = new ClassAnnotation(className);
add(classAnnotation);
return this;
}
/**
* Add a class annotation, but
* look up the source file name from the class name (using currentAnalysisContext)
*
* @param className the name of the class
* @return this object
*/
public BugInstance addClass(String className) {
String sourceFileName = AnalysisContext.currentAnalysisContext().lookupSourceFile(className);
return addClass(className, sourceFileName);
}
/**
* Add a class annotation. If this is the first class annotation added,
* it becomes the primary class annotation.
*
* @param jclass the JavaClass object for the class
* @return this object
*/
public BugInstance addClass(JavaClass jclass) {
addClass(jclass.getClassName(), jclass.getSourceFileName());
return this;
}
/**
* Add a class annotation for the class that the visitor is currently visiting.
*
* @param visitor the BetterVisitor
* @return this object
*/
public BugInstance addClass(PreorderVisitor visitor) {
String className = visitor.getDottedClassName();
addClass(className, AnalysisContext.currentAnalysisContext().lookupSourceFile(className));
return this;
}
/**
* Add a class annotation for the superclass of the class the visitor
* is currently visiting.
*
* @param visitor the BetterVisitor
* @return this object
*/
public BugInstance addSuperclass(PreorderVisitor visitor) {
String className = visitor.getSuperclassName();
addClass(className, AnalysisContext.currentAnalysisContext().lookupSourceFile(className));
return this;
}
/**
* Add a field annotation.
*
* @param className name of the class containing the field
* @param fieldName the name of the field
* @param fieldSig type signature of the field
* @param isStatic whether or not the field is static
* @return this object
*/
public BugInstance addField(String className, String fieldName, String fieldSig, boolean isStatic) {
String sourceFileName = AnalysisContext.currentAnalysisContext().lookupSourceFile(className);
addField(new FieldAnnotation(className, fieldName, fieldSig, isStatic));
return this;
}
/**
* Add a field annotation
*
* @param fieldAnnotation the field annotation
* @return this object
*/
public BugInstance addField(FieldAnnotation fieldAnnotation) {
add(fieldAnnotation);
return this;
}
/**
* Add a field annotation for a FieldVariable matched in a ByteCodePattern.
*
* @param field the FieldVariable
* @return this object
*/
public BugInstance addField(FieldVariable field) {
return addField(field.getClassName(), field.getFieldName(), field.getFieldSig(), field.isStatic());
}
/**
* Add a field annotation for an XField.
*
* @param xfield the XField
* @return this object
*/
public BugInstance addField(XField xfield) {
return addField(xfield.getClassName(), xfield.getName(), xfield.getSignature(), xfield.isStatic());
}
/**
* Add a field annotation for the field which has just been accessed
* by the method currently being visited by given visitor.
* Assumes that a getfield/putfield or getstatic/putstatic
* has just been seen.
*
* @param visitor the DismantleBytecode object
* @return this object
*/
public BugInstance addReferencedField(DismantleBytecode visitor) {
FieldAnnotation f = FieldAnnotation.fromReferencedField(visitor);
addField(f);
return this;
}
/**
* Add a field annotation for the field referenced by the FieldAnnotation parameter
*/
public BugInstance addReferencedField(FieldAnnotation fa) {
addField(fa);
return this;
}
/**
* Add a field annotation for the field which is being visited by
* given visitor.
*
* @param visitor the visitor
* @return this object
*/
public BugInstance addVisitedField(PreorderVisitor visitor) {
FieldAnnotation f = FieldAnnotation.fromVisitedField(visitor);
addField(f);
return this;
}
/**
* Add a method annotation. If this is the first method annotation added,
* it becomes the primary method annotation.
*
* @param className name of the class containing the method
* @param methodName name of the method
* @param methodSig type signature of the method
* @param isStatic true if the method is static, false otherwise
* @return this object
*/
public BugInstance addMethod(String className, String methodName, String methodSig, boolean isStatic) {
addMethod(new MethodAnnotation(className, methodName, methodSig, isStatic));
return this;
}
/**
* Add a method annotation. If this is the first method annotation added,
* it becomes the primary method annotation.
* If the method has source line information, then a SourceLineAnnotation
* is added to the method.
*
* @param methodGen the MethodGen object for the method
* @param sourceFile source file method is defined in
* @return this object
*/
public BugInstance addMethod(MethodGen methodGen, String sourceFile) {
String className = methodGen.getClassName();
String sourceFileName = AnalysisContext.currentAnalysisContext().lookupSourceFile(className);
MethodAnnotation methodAnnotation =
new MethodAnnotation(className, methodGen.getName(), methodGen.getSignature(), methodGen.isStatic());
addMethod(methodAnnotation);
addSourceLinesForMethod(methodAnnotation, SourceLineAnnotation.fromVisitedMethod(methodGen, sourceFile));
return this;
}
/**
* Add a method annotation. If this is the first method annotation added,
* it becomes the primary method annotation.
* If the method has source line information, then a SourceLineAnnotation
* is added to the method.
*
* @param javaClass the class the method is defined in
* @param method the method
* @return this object
*/
public BugInstance addMethod(JavaClass javaClass, Method method) {
MethodAnnotation methodAnnotation =
new MethodAnnotation(javaClass.getClassName(), method.getName(), method.getSignature(), method.isStatic());
SourceLineAnnotation methodSourceLines = SourceLineAnnotation.forEntireMethod(
javaClass,
method);
methodAnnotation.setSourceLines(methodSourceLines);
addMethod(methodAnnotation);
return this;
}
/**
* Add a method annotation. If this is the first method annotation added,
* it becomes the primary method annotation.
* If the method has source line information, then a SourceLineAnnotation
* is added to the method.
*
* @param classAndMethod JavaClassAndMethod identifying the method to add
* @return this object
*/
public BugInstance addMethod(JavaClassAndMethod classAndMethod) {
return addMethod(classAndMethod.getJavaClass(), classAndMethod.getMethod());
}
/**
* Add a method annotation for the method which the given visitor is currently visiting.
* If the method has source line information, then a SourceLineAnnotation
* is added to the method.
*
* @param visitor the BetterVisitor
* @return this object
*/
public BugInstance addMethod(PreorderVisitor visitor) {
MethodAnnotation methodAnnotation = MethodAnnotation.fromVisitedMethod(visitor);
addMethod(methodAnnotation);
addSourceLinesForMethod(methodAnnotation, SourceLineAnnotation.fromVisitedMethod(visitor));
return this;
}
/**
* Add a method annotation for the method which has been called
* by the method currently being visited by given visitor.
* Assumes that the visitor has just looked at an invoke instruction
* of some kind.
*
* @param visitor the DismantleBytecode object
* @return this object
*/
public BugInstance addCalledMethod(DismantleBytecode visitor) {
String className = visitor.getDottedClassConstantOperand();
String sourceFileName = AnalysisContext.currentAnalysisContext().lookupSourceFile(className);
String methodName = visitor.getNameConstantOperand();
String methodSig = visitor.getDottedSigConstantOperand();
addMethod(className, methodName, methodSig, visitor.getMethod().isStatic());
describe("METHOD_CALLED");
return this;
}
/**
* Add a method annotation.
*
* @param className name of class containing called method
* @param methodName name of called method
* @param methodSig signature of called method
* @param isStatic true if called method is static, false if not
* @param sourceFileName name of source file of the method's class
* @return this object
*/
public BugInstance addCalledMethod(String className, String methodName, String methodSig, boolean isStatic) {
String sourceFileName = AnalysisContext.currentAnalysisContext().lookupSourceFile(className);
addMethod(className, methodName, methodSig, isStatic);
describe("METHOD_CALLED");
return this;
}
/**
* Add a method annotation for the method which is called by given
* instruction.
*
* @param methodGen the method containing the call
* @param inv the InvokeInstruction
* @return this object
*/
public BugInstance addCalledMethod(MethodGen methodGen, InvokeInstruction inv) {
ConstantPoolGen cpg = methodGen.getConstantPool();
String className = inv.getClassName(cpg);
String sourceFileName = AnalysisContext.currentAnalysisContext().lookupSourceFile(className);
String methodName = inv.getMethodName(cpg);
String methodSig = inv.getSignature(cpg);
addMethod(className, methodName, methodSig, inv.getOpcode() == Constants.INVOKESTATIC);
describe("METHOD_CALLED");
return this;
}
/**
* Add a MethodAnnotation from an XMethod.
*
* @param xmethod the XMethod
* @return this object
*/
public BugInstance addMethod(XMethod xmethod) {
addMethod(MethodAnnotation.fromXMethod(xmethod));
return this;
}
/**
* Add a method annotation. If this is the first method annotation added,
* it becomes the primary method annotation.
*
* @param methodAnnotation the method annotation
* @return this object
*/
public BugInstance addMethod(MethodAnnotation methodAnnotation) {
add(methodAnnotation);
return this;
}
/**
* Add an integer annotation.
*
* @param value the integer value
* @return this object
*/
public BugInstance addInt(int value) {
add(new IntAnnotation(value));
return this;
}
/**
* Add a String annotation.
*
* @param value the String value
* @return this object
*/
public BugInstance addString(String value) {
add(new StringAnnotation(value));
return this;
}
/**
* Add a source line annotation.
*
* @param sourceLine the source line annotation
* @return this object
*/
public BugInstance addSourceLine(SourceLineAnnotation sourceLine) {
add(sourceLine);
return this;
}
/**
* Add a source line annotation for instruction whose PC is given
* in the method that the given visitor is currently visiting.
* Note that if the method does not have line number information, then
* no source line annotation will be added.
*
* @param visitor a BytecodeScanningDetector that is currently visiting the method
* @param pc bytecode offset of the instruction
* @return this object
*/
public BugInstance addSourceLine(BytecodeScanningDetector visitor, int pc) {
SourceLineAnnotation sourceLineAnnotation =
SourceLineAnnotation.fromVisitedInstruction(visitor.getClassContext(), visitor, pc);
if (sourceLineAnnotation != null)
add(sourceLineAnnotation);
return this;
}
/**
* Add a source line annotation for instruction whose PC is given
* in the method that the given visitor is currently visiting.
* Note that if the method does not have line number information, then
* no source line annotation will be added.
*
* @param classContext the ClassContext
* @param visitor a PreorderVisitor that is currently visiting the method
* @param pc bytecode offset of the instruction
* @return this object
*/
public BugInstance addSourceLine(ClassContext classContext, PreorderVisitor visitor, int pc) {
SourceLineAnnotation sourceLineAnnotation =
SourceLineAnnotation.fromVisitedInstruction(classContext, visitor, pc);
if (sourceLineAnnotation != null)
add(sourceLineAnnotation);
return this;
}
/**
* Add a source line annotation for the given instruction in the given method.
* Note that if the method does not have line number information, then
* no source line annotation will be added.
*
* @param classContext the ClassContext
* @param methodGen the method being visited
* @param sourceFile source file the method is defined in
* @param handle the InstructionHandle containing the visited instruction
* @return this object
*/
public BugInstance addSourceLine(ClassContext classContext, MethodGen methodGen, String sourceFile, @NonNull InstructionHandle handle) {
SourceLineAnnotation sourceLineAnnotation =
SourceLineAnnotation.fromVisitedInstruction(classContext, methodGen, sourceFile, handle);
if (sourceLineAnnotation != null)
add(sourceLineAnnotation);
return this;
}
/**
* Add a source line annotation describing a range of instructions.
*
* @param classContext the ClassContext
* @param methodGen the method
* @param sourceFile source file the method is defined in
* @param start the start instruction in the range
* @param end the end instruction in the range (inclusive)
* @return this object
*/
public BugInstance addSourceLine(ClassContext classContext, MethodGen methodGen, String sourceFile, InstructionHandle start, InstructionHandle end) {
// Make sure start and end are really in the right order.
if (start.getPosition() > end.getPosition()) {
InstructionHandle tmp = start;
start = end;
end = tmp;
}
SourceLineAnnotation sourceLineAnnotation =
SourceLineAnnotation.fromVisitedInstructionRange(classContext, methodGen, sourceFile, start, end);
if (sourceLineAnnotation != null)
add(sourceLineAnnotation);
return this;
}
/**
* Add a source line annotation describing the
* source line numbers for a range of instructions in the method being
* visited by the given visitor.
* Note that if the method does not have line number information, then
* no source line annotation will be added.
*
* @param visitor a BetterVisitor which is visiting the method
* @param startPC the bytecode offset of the start instruction in the range
* @param endPC the bytecode offset of the end instruction in the range
* @return this object
*/
public BugInstance addSourceLineRange(BytecodeScanningDetector visitor, int startPC, int endPC) {
SourceLineAnnotation sourceLineAnnotation =
SourceLineAnnotation.fromVisitedInstructionRange(visitor.getClassContext(), visitor, startPC, endPC);
if (sourceLineAnnotation != null)
add(sourceLineAnnotation);
return this;
}
/**
* Add a source line annotation describing the
* source line numbers for a range of instructions in the method being
* visited by the given visitor.
* Note that if the method does not have line number information, then
* no source line annotation will be added.
*
* @param classContext the ClassContext
* @param visitor a BetterVisitor which is visiting the method
* @param startPC the bytecode offset of the start instruction in the range
* @param endPC the bytecode offset of the end instruction in the range
* @return this object
*/
public BugInstance addSourceLineRange(ClassContext classContext, PreorderVisitor visitor, int startPC, int endPC) {
SourceLineAnnotation sourceLineAnnotation =
SourceLineAnnotation.fromVisitedInstructionRange(classContext, visitor, startPC, endPC);
if (sourceLineAnnotation != null)
add(sourceLineAnnotation);
return this;
}
/**
* Add a source line annotation for instruction currently being visited
* by given visitor.
* Note that if the method does not have line number information, then
* no source line annotation will be added.
*
* @param visitor a BytecodeScanningDetector visitor that is currently visiting the instruction
* @return this object
*/
public BugInstance addSourceLine(BytecodeScanningDetector visitor) {
SourceLineAnnotation sourceLineAnnotation =
SourceLineAnnotation.fromVisitedInstruction(visitor);
if (sourceLineAnnotation != null)
add(sourceLineAnnotation);
return this;
}
/**
* Add a non-specific source line annotation.
* This will result in the entire source file being displayed.
*
* @param className the class name
* @param sourceFile the source file name
* @return this object
*/
public BugInstance addUnknownSourceLine(String className, String sourceFile) {
SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.createUnknown(className, sourceFile);
if (sourceLineAnnotation != null)
add(sourceLineAnnotation);
return this;
}
/**
* Format a string describing this bug instance.
*
* @return the description
*/
public String getMessage() {
String pattern = I18N.instance().getMessage(type);
FindBugsMessageFormat format = new FindBugsMessageFormat(pattern);
return format.format(annotationList.toArray(new BugAnnotation[annotationList.size()]));
}
/**
* Add a description to the most recently added bug annotation.
*
* @param description the description to add
* @return this object
*/
public BugInstance describe(String description) {
annotationList.get(annotationList.size() - 1).setDescription(description);
return this;
}
/**
* Convert to String.
* This method returns the "short" message describing the bug,
* as opposed to the longer format returned by getMessage().
* The short format is appropriate for the tree view in a GUI,
* where the annotations are listed separately as part of the overall
* bug instance.
*/
public String toString() {
return I18N.instance().getShortMessage(type);
}
public void writeXML(XMLOutput xmlOutput) throws IOException {
writeXML(xmlOutput, false);
}
public void writeXML(XMLOutput xmlOutput, boolean addMessages) throws IOException {
XMLAttributeList attributeList = new XMLAttributeList()
.addAttribute("type", type)
.addAttribute("priority", String.valueOf(priority));
BugPattern pattern = getBugPattern();
if (pattern != null) {
// The bug abbreviation and pattern category are
// emitted into the XML for informational purposes only.
// (The information is redundant, but might be useful
// for processing tools that want to make sense of
// bug instances without looking at the plugin descriptor.)
attributeList.addAttribute("abbrev", pattern.getAbbrev());
attributeList.addAttribute("category", pattern.getCategory());
}
// Add a uid attribute, if we have a unique id.
if (getUniqueId() != null) {
attributeList.addAttribute("uid", getUniqueId());
}
if (firstVersion > 0) attributeList.addAttribute("first", Long.toString(firstVersion));
if (lastVersion >= 0) attributeList.addAttribute("last", Long.toString(lastVersion));
if (introducedByChangeOfExistingClass)
attributeList.addAttribute("introducedByChange", "true");
if (removedByChangeOfPersistingClass)
attributeList.addAttribute("removedByChange", "true");
xmlOutput.openTag(ELEMENT_NAME, attributeList);
if (!annotationText.equals("")) {
xmlOutput.openTag("UserAnnotation");
xmlOutput.writeCDATA(annotationText);
xmlOutput.closeTag("UserAnnotation");
}
if (addMessages) {
BugPattern bugPattern = getBugPattern();
xmlOutput.openTag("ShortMessage");
xmlOutput.writeText(bugPattern != null ? bugPattern.getShortDescription() : this.toString());
xmlOutput.closeTag("ShortMessage");
xmlOutput.openTag("LongMessage");
xmlOutput.writeText(this.getMessage());
xmlOutput.closeTag("LongMessage");
}
boolean foundSourceAnnotation = false;
for (BugAnnotation annotation : annotationList) {
if (annotation instanceof SourceLineAnnotation)
foundSourceAnnotation = true;
annotation.writeXML(xmlOutput, addMessages);
}
if (!foundSourceAnnotation && addMessages) {
SourceLineAnnotation synth = getPrimarySourceLineAnnotation();
if (synth != null) {
synth.setSynthetic(true);
synth.writeXML(xmlOutput, addMessages);
}
}
if (propertyListHead != null) {
BugProperty prop = propertyListHead;
while (prop != null) {
prop.writeXML(xmlOutput);
prop = prop.getNext();
}
}
xmlOutput.closeTag(ELEMENT_NAME);
}
private static final String ELEMENT_NAME = "BugInstance";
private static final String USER_ANNOTATION_ELEMENT_NAME = "UserAnnotation";
public BugInstance add(BugAnnotation annotation) {
if (annotation == null)
throw new IllegalStateException("Missing BugAnnotation!");
// Add to list
annotationList.add(annotation);
// This object is being modified, so the cached hashcode
// must be invalidated
cachedHashCode = INVALID_HASH_CODE;
return this;
}
private void addSourceLinesForMethod(MethodAnnotation methodAnnotation, SourceLineAnnotation sourceLineAnnotation) {
if (sourceLineAnnotation != null) {
// Note: we don't add the source line annotation directly to
// the bug instance. Instead, we stash it in the MethodAnnotation.
// It is much more useful there, and it would just be distracting
// if it were displayed in the UI, since it would compete for attention
// with the actual bug location source line annotation (which is much
// more important and interesting).
methodAnnotation.setSourceLines(sourceLineAnnotation);
}
}
public int hashCode() {
if (cachedHashCode == INVALID_HASH_CODE) {
int hashcode = type.hashCode() + priority;
Iterator<BugAnnotation> i = annotationIterator();
while (i.hasNext())
hashcode += i.next().hashCode();
if (hashcode == INVALID_HASH_CODE)
hashcode = INVALID_HASH_CODE+1;
cachedHashCode = hashcode;
}
return cachedHashCode;
}
public boolean equals(Object o) {
if (!(o instanceof BugInstance))
return false;
BugInstance other = (BugInstance) o;
if (!type.equals(other.type) || priority != other.priority)
return false;
if (annotationList.size() != other.annotationList.size())
return false;
int numAnnotations = annotationList.size();
for (int i = 0; i < numAnnotations; ++i) {
BugAnnotation lhs = annotationList.get(i);
BugAnnotation rhs = other.annotationList.get(i);
if (!lhs.equals(rhs))
return false;
}
return true;
}
public int compareTo(BugInstance other) {
int cmp;
cmp = type.compareTo(other.type);
if (cmp != 0)
return cmp;
cmp = priority - other.priority;
if (cmp != 0)
return cmp;
// Compare BugAnnotations lexicographically
int pfxLen = Math.min(annotationList.size(), other.annotationList.size());
for (int i = 0; i < pfxLen; ++i) {
BugAnnotation lhs = annotationList.get(i);
BugAnnotation rhs = other.annotationList.get(i);
cmp = lhs.compareTo(rhs);
if (cmp != 0)
return cmp;
}
// All elements in prefix were the same,
// so use number of elements to decide
return annotationList.size() - other.annotationList.size();
}
/**
* @param firstVersion The firstVersion to set.
*/
public void setFirstVersion(long firstVersion) {
this.firstVersion = firstVersion;
if (lastVersion >= 0 && firstVersion > lastVersion)
throw new IllegalArgumentException(
firstVersion + ".." + lastVersion);
}
/**
* @return Returns the firstVersion.
*/
public long getFirstVersion() {
return firstVersion;
}
/**
* @param lastVersion The lastVersion to set.
*/
public void setLastVersion(long lastVersion) {
if (lastVersion >= 0 && firstVersion > lastVersion)
throw new IllegalArgumentException(
firstVersion + ".." + lastVersion);
this.lastVersion = lastVersion;
}
/**
* @return Returns the lastVersion.
*/
public long getLastVersion() {
return lastVersion;
}
/**
* @param introducedByChangeOfExistingClass The introducedByChangeOfExistingClass to set.
*/
public void setIntroducedByChangeOfExistingClass(boolean introducedByChangeOfExistingClass) {
this.introducedByChangeOfExistingClass = introducedByChangeOfExistingClass;
}
/**
* @return Returns the introducedByChangeOfExistingClass.
*/
public boolean isIntroducedByChangeOfExistingClass() {
return introducedByChangeOfExistingClass;
}
/**
* @param removedByChangeOfPersistingClass The removedByChangeOfPersistingClass to set.
*/
public void setRemovedByChangeOfPersistingClass(boolean removedByChangeOfPersistingClass) {
this.removedByChangeOfPersistingClass = removedByChangeOfPersistingClass;
}
/**
* @return Returns the removedByChangeOfPersistingClass.
*/
public boolean isRemovedByChangeOfPersistingClass() {
return removedByChangeOfPersistingClass;
}
}
// vim:ts=4 |
package seedu.bulletjournal.logic.parser;
/**
* Provides variations of commands Note: hard-coded for v0.2, will implement nlp
* for future versions
*
* @@author A0127826Y
*/
public class FlexibleCommand {
private String commandFromUser = "";
private String[] commandGroups = new String[] { "add a adds create creates new", "clear clr c clears empty empties",
"delete d deletes del remove removes rm", "edit edits e", "change cd", "finish done complete",
"exit exits close closes logout logouts quit q", "find finds f search searches lookup", "show showall",
"help helps h manual instruction instructions", "list lists l ls display displays",
"select selects s choose chooses"};
/**
* Constructor must take in a valid string input
*
* @param cfu
*/
public FlexibleCommand(String cfu) {
commandFromUser = cfu;
}
/**
* @return the correct command string that matches COMMAND_WORD of command
* classes
*/
public String getCommandWord() {
for (String commandGroup : commandGroups) {
for (String command : commandGroup.split(" ")) {
if (commandFromUser.equals(command)) {
return commandGroup.split(" ")[0];
}
}
}
return commandFromUser;
}
public boolean isValidCommand() {
for (String commandGroup : commandGroups) {
for (String command : commandGroup.split(" ")) {
if (commandFromUser.equals(command)) {
return true;
}
}
}
return false;
}
} |
package edu.umd.cs.findbugs;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.bcel.Repository;
import org.apache.bcel.classfile.Code;
import org.apache.bcel.classfile.CodeException;
import org.apache.bcel.classfile.Constant;
import org.apache.bcel.classfile.ConstantClass;
import org.apache.bcel.classfile.ConstantDouble;
import org.apache.bcel.classfile.ConstantFloat;
import org.apache.bcel.classfile.ConstantInteger;
import org.apache.bcel.classfile.ConstantLong;
import org.apache.bcel.classfile.ConstantString;
import org.apache.bcel.classfile.ConstantUtf8;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.LocalVariable;
import org.apache.bcel.classfile.LocalVariableTable;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.BasicType;
import org.apache.bcel.generic.Type;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.ba.AnalysisContext;
import edu.umd.cs.findbugs.ba.AnalysisFeatures;
import edu.umd.cs.findbugs.ba.ClassMember;
import edu.umd.cs.findbugs.ba.XFactory;
import edu.umd.cs.findbugs.ba.XField;
import edu.umd.cs.findbugs.ba.XMethod;
import edu.umd.cs.findbugs.visitclass.Constants2;
import edu.umd.cs.findbugs.visitclass.DismantleBytecode;
import edu.umd.cs.findbugs.visitclass.LVTHelper;
import edu.umd.cs.findbugs.visitclass.PreorderVisitor;
/**
* tracks the types and numbers of objects that are currently on the operand stack
* throughout the execution of method. To use, a detector should instantiate one for
* each method, and call <p>stack.sawOpcode(this,seen);</p> at the bottom of their sawOpcode method.
* at any point you can then inspect the stack and see what the types of objects are on
* the stack, including constant values if they were pushed. The types described are of
* course, only the static types.
* There are some outstanding opcodes that have yet to be implemented, I couldn't
* find any code that actually generated these, so i didn't put them in because
* I couldn't test them:
* <ul>
* <li>dup2_x2</li>
* <li>jsr_w</li>
* <li>wide</li>
* </ul>
*/
public class OpcodeStack implements Constants2
{
private static final boolean DEBUG
= SystemProperties.getBoolean("ocstack.debug");
private static final boolean DEBUG2 = DEBUG;
private List<Item> stack;
private List<Item> lvValues;
private List<Integer> lastUpdate;
private boolean seenTransferOfControl = false;
private boolean useIterativeAnalysis
= AnalysisContext.currentAnalysisContext().getBoolProperty(AnalysisFeatures.INTERATIVE_OPCODE_STACK_ANALYSIS);
public static class Item
{
public static final int SIGNED_BYTE = 1;
public static final int RANDOM_INT = 2;
public static final int LOW_8_BITS_CLEAR = 3;
public static final int HASHCODE_INT = 4;
public static final int INTEGER_SUM = 5;
public static final int AVERAGE_COMPUTED_USING_DIVISION = 6;
public static final int FLOAT_MATH = 7;
public static final int RANDOM_INT_REMAINDER = 8;
public static final int HASHCODE_INT_REMAINDER = 9;
public static final int FILE_SEPARATOR_STRING = 10;
public static final int MATH_ABS = 11;
public static final int MASKED_NON_NEGATIVE = 12;
public static final int NASTY_FLOAT_MATH = 13;
private static final int IS_INITIAL_PARAMETER_FLAG=1;
private static final int COULD_BE_ZERO_FLAG = 2;
private static final int IS_NULL_FLAG = 4;
public static final Object UNKNOWN = null;
private int specialKind;
private String signature;
private Object constValue = UNKNOWN;
private @CheckForNull ClassMember source;
private int flags;
// private boolean isNull = false;
private int registerNumber = -1;
// private boolean isInitialParameter = false;
// private boolean couldBeZero = false;
private Object userValue = null;
private int fieldLoadedFromRegister = -1;
public int getSize() {
if (signature.equals("J") || signature.equals("D")) return 2;
return 1;
}
public boolean isWide() {
return getSize() == 2;
}
private static boolean equals(Object o1, Object o2) {
if (o1 == o2) return true;
if (o1 == null || o2 == null) return false;
return o1.equals(o2);
}
@Override
public int hashCode() {
int r = 42 + specialKind;
if (signature != null)
r+= signature.hashCode();
r *= 31;
if (constValue != null)
r+= constValue.hashCode();
r *= 31;
if (source != null)
r+= source.hashCode();
r *= 31;
r += flags;
r *= 31;
r += registerNumber;
return r;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Item)) return false;
Item that = (Item) o;
return equals(this.signature, that.signature)
&& equals(this.constValue, that.constValue)
&& equals(this.source, that.source)
&& this.specialKind == that.specialKind
&& this.registerNumber == that.registerNumber
&& this.flags == that.flags
&& this.userValue == that.userValue
&& this.fieldLoadedFromRegister == that.fieldLoadedFromRegister;
}
@Override
public String toString() {
StringBuffer buf = new StringBuffer("< ");
buf.append(signature);
switch(specialKind) {
case SIGNED_BYTE:
buf.append(", byte_array_load");
break;
case RANDOM_INT:
buf.append(", random_int");
break;
case LOW_8_BITS_CLEAR:
buf.append(", low8clear");
break;
case HASHCODE_INT:
buf.append(", hashcode_int");
break;
case INTEGER_SUM:
buf.append(", int_sum");
break;
case AVERAGE_COMPUTED_USING_DIVISION:
buf.append(", averageComputingUsingDivision");
break;
case FLOAT_MATH:
buf.append(", floatMath");
break;
case NASTY_FLOAT_MATH:
buf.append(", nastyFloatMath");
break;
case HASHCODE_INT_REMAINDER:
buf.append(", hashcode_int_rem");
break;
case RANDOM_INT_REMAINDER:
buf.append(", random_int_rem");
break;
case FILE_SEPARATOR_STRING:
buf.append(", file_separator_string");
break;
case MATH_ABS:
buf.append(", Math.abs");
break;
case MASKED_NON_NEGATIVE:
buf.append(", masked_non_negative");
break;
case 0 :
break;
default:
buf.append(", #" + specialKind);
break;
}
if (constValue != UNKNOWN) {
buf.append(", ");
buf.append(constValue);
}
if (source instanceof XField) {
buf.append(", ");
if (fieldLoadedFromRegister != -1)
buf.append(fieldLoadedFromRegister).append(':');
buf.append(source);
}
if (source instanceof XMethod) {
buf.append(", return value from ");
buf.append(source);
}
if (isInitialParameter()) {
buf.append(", IP");
}
if (isNull()) {
buf.append(", isNull");
}
if (registerNumber != -1) {
buf.append(", r");
buf.append(registerNumber);
}
if (isCouldBeZero()) buf.append(", cbz");
buf.append(" >");
return buf.toString();
}
public static Item merge(Item i1, Item i2) {
if (i1 == null) return i2;
if (i2 == null) return i1;
if (i1.equals(i2)) return i1;
Item m = new Item();
m.flags = i1.flags & i2.flags;
m.setCouldBeZero(i1.isCouldBeZero() || i2.isCouldBeZero());
if (equals(i1.signature,i2.signature))
m.signature = i1.signature;
if (equals(i1.constValue,i2.constValue))
m.constValue = i1.constValue;
if (equals(i1.source,i2.source)) {
m.source = i1.source;
}
if (i1.registerNumber == i2.registerNumber)
m.registerNumber = i1.registerNumber;
if (i1.fieldLoadedFromRegister == i2.fieldLoadedFromRegister)
m.fieldLoadedFromRegister = i1.fieldLoadedFromRegister;
if (i1.specialKind == i2.specialKind)
m.specialKind = i1.specialKind;
else if (i1.specialKind == NASTY_FLOAT_MATH || i2.specialKind == NASTY_FLOAT_MATH)
m.specialKind = NASTY_FLOAT_MATH;
else if (i1.specialKind == FLOAT_MATH || i2.specialKind == FLOAT_MATH)
m.specialKind = FLOAT_MATH;
if (DEBUG) System.out.println("Merge " + i1 + " and " + i2 + " gives " + m);
return m;
}
public Item(String signature, int constValue) {
this(signature, (Object)(Integer)constValue);
}
public Item(String signature) {
this(signature, UNKNOWN);
}
public Item(Item it) {
this.signature = it.signature;
this.constValue = it.constValue;
this.source = it.source;
this.registerNumber = it.registerNumber;
this.userValue = it.userValue;
this.flags = it.flags;
this.specialKind = it.specialKind;
}
public Item(Item it, int reg) {
this(it);
this.registerNumber = reg;
}
public Item(String signature, FieldAnnotation f) {
this.signature = signature;
if (f != null)
source = XFactory.createXField(f);
fieldLoadedFromRegister = -1;
}
public Item(String signature, FieldAnnotation f, int fieldLoadedFromRegister) {
this.signature = signature;
if (f != null)
source = XFactory.createXField(f);
this.fieldLoadedFromRegister = fieldLoadedFromRegister;
}
public int getFieldLoadedFromRegister() {
return fieldLoadedFromRegister;
}
public Item(String signature, Object constantValue) {
this.signature = signature;
constValue = constantValue;
if (constantValue instanceof Integer) {
int value = (Integer) constantValue;
if (value != 0 && (value & 0xff) == 0)
specialKind = LOW_8_BITS_CLEAR;
if (value == 0) setCouldBeZero(true);
}
else if (constantValue instanceof Long) {
long value = (Long) constantValue;
if (value != 0 && (value & 0xff) == 0)
specialKind = LOW_8_BITS_CLEAR;
if (value == 0) setCouldBeZero(true);
}
}
public Item() {
signature = "Ljava/lang/Object;";
constValue = null;
setNull(true);
}
public JavaClass getJavaClass() throws ClassNotFoundException {
String baseSig;
if (isPrimitive())
return null;
if (isArray()) {
baseSig = getElementSignature();
} else {
baseSig = signature;
}
if (baseSig.length() == 0)
return null;
baseSig = baseSig.substring(1, baseSig.length() - 1);
baseSig = baseSig.replace('/', '.');
return Repository.lookupClass(baseSig);
}
public boolean isArray() {
return signature.startsWith("[");
}
public String getElementSignature() {
if (!isArray())
return signature;
else {
int pos = 0;
int len = signature.length();
while (pos < len) {
if (signature.charAt(pos) != '[')
break;
pos++;
}
return signature.substring(pos);
}
}
public boolean isNonNegative() {
if (specialKind == MASKED_NON_NEGATIVE) return true;
if (constValue instanceof Number) {
double value = ((Number) constValue).doubleValue();
return value >= 0;
}
return false;
}
public boolean isPrimitive() {
return !signature.startsWith("L");
}
public int getRegisterNumber() {
return registerNumber;
}
public String getSignature() {
return signature;
}
/**
* Returns a constant value for this Item, if known.
* NOTE: if the value is a constant Class object, the constant value returned is the name of the class.
*/
public Object getConstant() {
return constValue;
}
/** Use getXField instead */
@Deprecated
public FieldAnnotation getFieldAnnotation() {
return FieldAnnotation.fromXField(getXField());
}
public XField getXField() {
if (source instanceof XField) return (XField) source;
return null;
}
/**
* @param specialKind The specialKind to set.
*/
public void setSpecialKind(int specialKind) {
this.specialKind = specialKind;
}
/**
* @return Returns the specialKind.
*/
public int getSpecialKind() {
return specialKind;
}
/**
* attaches a detector specified value to this item
*
* @param value the custom value to set
*/
public void setUserValue(Object value) {
userValue = value;
}
/**
*
* @return if this value is the return value of a method, give the method
* invoked
*/
public @CheckForNull XMethod getReturnValueOf() {
if (source instanceof XMethod) return (XMethod) source;
return null;
}
public boolean couldBeZero() {
return isCouldBeZero();
}
public boolean mustBeZero() {
Object value = getConstant();
return value instanceof Number && ((Number)value).intValue() == 0;
}
/**
* gets the detector specified value for this item
*
* @return the custom value
*/
public Object getUserValue() {
return userValue;
}
public boolean valueCouldBeNegative() {
return (getSpecialKind() == Item.RANDOM_INT
|| getSpecialKind() == Item.SIGNED_BYTE
|| getSpecialKind() == Item.HASHCODE_INT
|| getSpecialKind() == Item.RANDOM_INT_REMAINDER || getSpecialKind() == Item.HASHCODE_INT_REMAINDER);
}
/**
* @param isInitialParameter The isInitialParameter to set.
*/
private void setInitialParameter(boolean isInitialParameter) {
setFlag(isInitialParameter, IS_INITIAL_PARAMETER_FLAG);
}
/**
* @return Returns the isInitialParameter.
*/
public boolean isInitialParameter() {
return (flags & IS_INITIAL_PARAMETER_FLAG) != 0;
}
/**
* @param couldBeZero The couldBeZero to set.
*/
private void setCouldBeZero(boolean couldBeZero) {
setFlag(couldBeZero, COULD_BE_ZERO_FLAG);
}
/**
* @return Returns the couldBeZero.
*/
private boolean isCouldBeZero() {
return (flags & COULD_BE_ZERO_FLAG) != 0;
}
/**
* @param isNull The isNull to set.
*/
private void setNull(boolean isNull) {
setFlag(isNull, IS_NULL_FLAG);
}
private void setFlag(boolean value, int flagBit) {
if (value)
flags |= flagBit;
else
flags &= ~flagBit;
}
/**
* @return Returns the isNull.
*/
public boolean isNull() {
return (flags & IS_NULL_FLAG) != 0;
}
}
@Override
public String toString() {
return stack.toString() + "::" + lvValues.toString();
}
public OpcodeStack()
{
stack = new ArrayList<Item>();
lvValues = new ArrayList<Item>();
lastUpdate = new ArrayList<Integer>();
}
boolean needToMerge = true;
boolean reachOnlyByBranch = false;
public static String getExceptionSig(DismantleBytecode dbc, CodeException e) {
if (e.getCatchType() == 0) return "Ljava/lang/Throwable;";
Constant c = dbc.getConstantPool().getConstant(e.getCatchType());
if (c instanceof ConstantClass)
return "L"+((ConstantClass)c).getBytes(dbc.getConstantPool())+";";
return "Ljava/lang/Throwable;";
}
public void mergeJumps(DismantleBytecode dbc) {
if (!needToMerge) return;
needToMerge = false;
boolean stackUpdated = false;
if (convertJumpToOneZeroState == 3 || convertJumpToZeroOneState == 3) {
pop();
Item top = new Item("I");
top.setCouldBeZero(true);
push(top);
convertJumpToOneZeroState = convertJumpToZeroOneState = 0;
stackUpdated = true;
}
List<Item> jumpEntry = null;
if (jumpEntryLocations.get(dbc.getPC()))
jumpEntry = jumpEntries.get(dbc.getPC());
if (jumpEntry != null) {
List<Item> jumpStackEntry = jumpStackEntries.get(dbc.getPC());
if (DEBUG2) {
System.out.println("XXXXXXX " + reachOnlyByBranch);
System.out.println("merging lvValues at jump target " + dbc.getPC() + " -> " + Integer.toString(System.identityHashCode(jumpEntry),16) + " " + jumpEntry);
System.out.println(" current lvValues " + lvValues);
System.out.println(" merging stack entry " + jumpStackEntry);
System.out.println(" current stack values " + stack);
}
if (reachOnlyByBranch) {
lvValues = new ArrayList<Item>(jumpEntry);
if (!stackUpdated) {
if (jumpStackEntry != null) stack = new ArrayList<Item>(jumpStackEntry);
else stack.clear();
}
}
else {
mergeLists(lvValues, jumpEntry, false);
if (!stackUpdated && jumpStackEntry != null) mergeLists(stack, jumpStackEntry, false);
}
if (DEBUG)
System.out.println(" merged lvValues " + lvValues);
}
else if (reachOnlyByBranch && !stackUpdated) {
stack.clear();
boolean foundException = false;
for(CodeException e : dbc.getCode().getExceptionTable()) {
if (e.getHandlerPC() == dbc.getPC()) {
push(new Item(getExceptionSig(dbc, e)));
foundException = true;
}
}
if (!foundException)
push(new Item("Ljava/lang/Throwable;"));
}
reachOnlyByBranch = false;
}
int convertJumpToOneZeroState = 0;
int convertJumpToZeroOneState = 0;
private void setLastUpdate(int reg, int pc) {
while (lastUpdate.size() <= reg) lastUpdate.add(0);
lastUpdate.set(reg, pc);
}
public int getLastUpdate(int reg) {
if (lastUpdate.size() <= reg) return 0;
return lastUpdate.get(reg);
}
public int getNumLastUpdates() {
return lastUpdate.size();
}
public void sawOpcode(DismantleBytecode dbc, int seen) {
int register;
String signature;
Item it, it2, it3;
Constant cons;
if (dbc.isRegisterStore())
setLastUpdate(dbc.getRegisterOperand(), dbc.getPC());
mergeJumps(dbc);
needToMerge = true;
switch (seen) {
case ICONST_1:
convertJumpToOneZeroState = 1;
break;
case GOTO:
if (convertJumpToOneZeroState == 1 && dbc.getBranchOffset() == 4)
convertJumpToOneZeroState = 2;
else
convertJumpToOneZeroState = 0;
break;
case ICONST_0:
if (convertJumpToOneZeroState == 2)
convertJumpToOneZeroState = 3;
else convertJumpToOneZeroState = 0;
break;
default:convertJumpToOneZeroState = 0;
}
switch (seen) {
case ICONST_0:
convertJumpToZeroOneState = 1;
break;
case GOTO:
if (convertJumpToZeroOneState == 1 && dbc.getBranchOffset() == 4)
convertJumpToZeroOneState = 2;
else
convertJumpToZeroOneState = 0;
break;
case ICONST_1:
if (convertJumpToZeroOneState == 2)
convertJumpToZeroOneState = 3;
else convertJumpToZeroOneState = 0;
break;
default:convertJumpToZeroOneState = 0;
}
try
{
switch (seen) {
case ALOAD:
pushByLocalObjectLoad(dbc, dbc.getRegisterOperand());
break;
case ALOAD_0:
case ALOAD_1:
case ALOAD_2:
case ALOAD_3:
pushByLocalObjectLoad(dbc, seen - ALOAD_0);
break;
case DLOAD:
pushByLocalLoad("D", dbc.getRegisterOperand());
break;
case DLOAD_0:
case DLOAD_1:
case DLOAD_2:
case DLOAD_3:
pushByLocalLoad("D", seen - DLOAD_0);
break;
case FLOAD:
pushByLocalLoad("F", dbc.getRegisterOperand());
break;
case FLOAD_0:
case FLOAD_1:
case FLOAD_2:
case FLOAD_3:
pushByLocalLoad("F", seen - FLOAD_0);
break;
case ILOAD:
pushByLocalLoad("I", dbc.getRegisterOperand());
break;
case ILOAD_0:
case ILOAD_1:
case ILOAD_2:
case ILOAD_3:
pushByLocalLoad("I", seen - ILOAD_0);
break;
case LLOAD:
pushByLocalLoad("J", dbc.getRegisterOperand());
break;
case LLOAD_0:
case LLOAD_1:
case LLOAD_2:
case LLOAD_3:
pushByLocalLoad("J", seen - LLOAD_0);
break;
case GETSTATIC:
{
FieldAnnotation field = FieldAnnotation.fromReferencedField(dbc);
Item i = new Item(dbc.getSigConstantOperand(), field, Integer.MAX_VALUE);
if (field.getFieldName().equals("separator") && field.getClassName().equals("java.io.File")) {
i.setSpecialKind(Item.FILE_SEPARATOR_STRING);
}
push(i);
break;
}
case LDC:
case LDC_W:
case LDC2_W:
cons = dbc.getConstantRefOperand();
pushByConstant(dbc, cons);
break;
case INSTANCEOF:
pop();
push(new Item("I"));
break;
case IFEQ:
case IFNE:
case IFLT:
case IFLE:
case IFGT:
case IFGE:
case IFNONNULL:
case IFNULL:
seenTransferOfControl = true;
{
Item top = pop();
// if we see a test comparing a special negative value with 0,
// reset all other such values on the opcode stack
if (top.valueCouldBeNegative()
&& (seen == IFLT || seen == IFLE || seen == IFGT || seen == IFGE)) {
int specialKind = top.getSpecialKind();
for(Item item : stack) if (item != null && item.getSpecialKind() == specialKind) item.setSpecialKind(0);
for(Item item : lvValues) if (item != null && item.getSpecialKind() == specialKind) item.setSpecialKind(0);
}
}
addJumpValue(dbc.getBranchTarget());
break;
case LOOKUPSWITCH:
case TABLESWITCH:
seenTransferOfControl = true;
pop();
addJumpValue(dbc.getBranchTarget());
int pc = dbc.getBranchTarget() - dbc.getBranchOffset();
for(int offset : dbc.getSwitchOffsets())
addJumpValue(offset+pc);
break;
case ARETURN:
case DRETURN:
case FRETURN:
case IRETURN:
case LRETURN:
seenTransferOfControl = true;
reachOnlyByBranch = true;
pop();
break;
case MONITORENTER:
case MONITOREXIT:
case POP:
case PUTSTATIC:
pop();
break;
case IF_ACMPEQ:
case IF_ACMPNE:
case IF_ICMPEQ:
case IF_ICMPNE:
case IF_ICMPLT:
case IF_ICMPLE:
case IF_ICMPGT:
case IF_ICMPGE:
seenTransferOfControl = true;
pop(2);
addJumpValue(dbc.getBranchTarget());
break;
case POP2:
it = pop();
if (it.getSize() == 1) pop();
break;
case PUTFIELD:
pop(2);
break;
case IALOAD:
case SALOAD:
pop(2);
push(new Item("I"));
break;
case DUP:
handleDup();
break;
case DUP2:
handleDup2();
break;
case DUP_X1:
handleDupX1();
break;
case DUP_X2:
handleDupX2();
break;
case DUP2_X1:
handleDup2X1();
break;
case DUP2_X2:
handleDup2X2();
break;
case IINC:
register = dbc.getRegisterOperand();
it = getLVValue( register );
it2 = new Item("I", dbc.getIntConstant());
pushByIntMath( IADD, it2, it);
pushByLocalStore(register);
break;
case ATHROW:
pop();
seenTransferOfControl = true;
reachOnlyByBranch = true;
break;
case CHECKCAST:
{
String castTo = dbc.getClassConstantOperand();
if (castTo.charAt(0) != '[') castTo = "L" + castTo + ";";
it = new Item(pop());
it.signature = castTo;
push(it);
break;
}
case NOP:
break;
case RET:
case RETURN:
seenTransferOfControl = true;
reachOnlyByBranch = true;
break;
case GOTO:
case GOTO_W: //It is assumed that no stack items are present when
seenTransferOfControl = true;
reachOnlyByBranch = true;
addJumpValue(dbc.getBranchTarget());
stack.clear();
break;
case SWAP:
handleSwap();
break;
case ICONST_M1:
case ICONST_0:
case ICONST_1:
case ICONST_2:
case ICONST_3:
case ICONST_4:
case ICONST_5:
push(new Item("I", (seen-ICONST_0)));
break;
case LCONST_0:
case LCONST_1:
push(new Item("J", (long)(seen-LCONST_0)));
break;
case DCONST_0:
case DCONST_1:
push(new Item("D", (double)(seen-DCONST_0)));
break;
case FCONST_0:
case FCONST_1:
case FCONST_2:
push(new Item("F", (float)(seen-FCONST_0)));
break;
case ACONST_NULL:
push(new Item());
break;
case ASTORE:
case DSTORE:
case FSTORE:
case ISTORE:
case LSTORE:
pushByLocalStore(dbc.getRegisterOperand());
break;
case ASTORE_0:
case ASTORE_1:
case ASTORE_2:
case ASTORE_3:
pushByLocalStore(seen - ASTORE_0);
break;
case DSTORE_0:
case DSTORE_1:
case DSTORE_2:
case DSTORE_3:
pushByLocalStore(seen - DSTORE_0);
break;
case FSTORE_0:
case FSTORE_1:
case FSTORE_2:
case FSTORE_3:
pushByLocalStore(seen - FSTORE_0);
break;
case ISTORE_0:
case ISTORE_1:
case ISTORE_2:
case ISTORE_3:
pushByLocalStore(seen - ISTORE_0);
break;
case LSTORE_0:
case LSTORE_1:
case LSTORE_2:
case LSTORE_3:
pushByLocalStore(seen - LSTORE_0);
break;
case GETFIELD:
{
Item item = pop();
int reg = item.getRegisterNumber();
push(new Item(dbc.getSigConstantOperand(),
FieldAnnotation.fromReferencedField(dbc), reg));
}
break;
case ARRAYLENGTH:
pop();
push(new Item("I"));
break;
case BALOAD:
{
pop(2);
Item v = new Item("I");
v.setSpecialKind(Item.SIGNED_BYTE);
push(v);
break;
}
case CALOAD:
pop(2);
push(new Item("I"));
break;
case DALOAD:
pop(2);
push(new Item("D"));
break;
case FALOAD:
pop(2);
push(new Item("F"));
break;
case LALOAD:
pop(2);
push(new Item("J"));
break;
case AASTORE:
case BASTORE:
case CASTORE:
case DASTORE:
case FASTORE:
case IASTORE:
case LASTORE:
case SASTORE:
pop(3);
break;
case BIPUSH:
case SIPUSH:
push(new Item("I", (Integer)dbc.getIntConstant()));
break;
case IADD:
case ISUB:
case IMUL:
case IDIV:
case IAND:
case IOR:
case IXOR:
case ISHL:
case ISHR:
case IREM:
case IUSHR:
it = pop();
it2 = pop();
pushByIntMath(seen, it2, it);
break;
case INEG:
it = pop();
if (it.getConstant() instanceof Integer) {
push(new Item("I", ( Integer)(-(Integer) it.getConstant())));
} else {
push(new Item("I"));
}
break;
case LNEG:
it = pop();
if (it.getConstant() instanceof Long) {
push(new Item("J", ( Long)(-(Long) it.getConstant())));
} else {
push(new Item("J"));
}
break;
case FNEG:
it = pop();
if (it.getConstant() instanceof Float) {
push(new Item("F", ( Float)(-(Float) it.getConstant())));
} else {
push(new Item("F"));
}
break;
case DNEG:
it = pop();
if (it.getConstant() instanceof Double) {
push(new Item("D", ( Double)(-(Double) it.getConstant())));
} else {
push(new Item("D"));
}
break;
case LADD:
case LSUB:
case LMUL:
case LDIV:
case LAND:
case LOR:
case LXOR:
case LSHL:
case LSHR:
case LREM:
case LUSHR:
it = pop();
it2 = pop();
pushByLongMath(seen, it2, it);
break;
case LCMP:
handleLcmp();
break;
case FCMPG:
case FCMPL: handleFcmp(seen);
break;
case DCMPG:
case DCMPL:
handleDcmp(seen);
break;
case FADD:
case FSUB:
case FMUL:
case FDIV:
case FREM:
it = pop();
it2 = pop();
pushByFloatMath(seen, it, it2);
break;
case DADD:
case DSUB:
case DMUL:
case DDIV:
case DREM:
it = pop();
it2 = pop();
pushByDoubleMath(seen, it, it2);
break;
case I2B:
it = pop();
if (it.getConstant() != null) {
it =new Item("I", (byte)constantToInt(it));
} else {
it = new Item("I");
}
it.setSpecialKind(Item.SIGNED_BYTE);
push(it);
break;
case I2C:
it = pop();
if (it.getConstant() != null) {
it = new Item("I", (char)constantToInt(it));
} else {
it = new Item("I");
}
it.setSpecialKind(Item.MASKED_NON_NEGATIVE);
push(it);
break;
case I2L:
case D2L:
case F2L:{
it = pop();
Item newValue;
if (it.getConstant() != null) {
newValue = new Item("J", constantToLong(it));
} else {
newValue = new Item("J");
}
newValue.setSpecialKind(it.getSpecialKind());
push(newValue);
}
break;
case I2S:
it = pop();
if (it.getConstant() != null) {
push(new Item("I", (short)constantToInt(it)));
} else {
push(new Item("I"));
}
break;
case L2I:
case D2I:
case F2I:
it = pop();
if (it.getConstant() != null) {
push(new Item("I",constantToInt(it)));
} else {
push(new Item("I"));
}
break;
case L2F:
case D2F:
case I2F:
it = pop();
if (it.getConstant() != null) {
push(new Item("F", (Float)(constantToFloat(it))));
} else {
push(new Item("F"));
}
break;
case F2D:
case I2D:
case L2D:
it = pop();
if (it.getConstant() != null) {
push(new Item("D", constantToDouble(it)));
} else {
push(new Item("D"));
}
break;
case NEW:
pushBySignature("L" + dbc.getClassConstantOperand() + ";");
break;
case NEWARRAY:
pop();
signature = "[" + BasicType.getType((byte)dbc.getIntConstant()).getSignature();
pushBySignature(signature);
break;
// According to the VM Spec 4.4.1, anewarray and multianewarray
// can refer to normal class/interface types (encoded in
// "internal form"), or array classes (encoded as signatures
// beginning with "[").
case ANEWARRAY:
pop();
signature = dbc.getClassConstantOperand();
if (!signature.startsWith("[")) {
signature = "[L" + signature + ";";
}
pushBySignature(signature);
break;
case MULTIANEWARRAY:
int dims = dbc.getIntConstant();
while ((dims
pop();
}
signature = dbc.getClassConstantOperand();
if (!signature.startsWith("[")) {
dims = dbc.getIntConstant();
signature = "";
while ((dims
signature += "[";
signature += "L" + signature + ";";
}
pushBySignature(signature);
break;
case AALOAD:
pop();
it = pop();
pushBySignature(it.getElementSignature());
break;
case JSR:
push(new Item(""));
break;
case INVOKEINTERFACE:
case INVOKESPECIAL:
case INVOKESTATIC:
case INVOKEVIRTUAL:
processMethodCall(dbc, seen);
break;
default:
throw new UnsupportedOperationException("OpCode " + OPCODE_NAMES[seen] + " not supported " );
}
}
catch (RuntimeException e) {
//If an error occurs, we clear the stack and locals. one of two things will occur.
//Either the client will expect more stack items than really exist, and so they're condition check will fail,
//or the stack will resync with the code. But hopefully not false positives
AnalysisContext.logError("Error procssing opcode " + OPCODE_NAMES[seen] + " @ " + dbc.getPC() + " in " + dbc.getFullyQualifiedMethodName() , e);
if (DEBUG)
e.printStackTrace();
clear();
}
finally {
if (exceptionHandlers.get(dbc.getNextPC()))
push(new Item());
if (DEBUG) {
System.out.println(dbc.getNextPC() + "pc : " + OPCODE_NAMES[seen] + " stack depth: " + getStackDepth());
System.out.println(this);
}
}
}
/**
* @param it
* @return
*/
private int constantToInt(Item it) {
return ((Number)it.getConstant()).intValue();
}
/**
* @param it
* @return
*/
private float constantToFloat(Item it) {
return ((Number)it.getConstant()).floatValue();
}
/**
* @param it
* @return
*/
private double constantToDouble(Item it) {
return ((Number)it.getConstant()).doubleValue();
}
/**
* @param it
* @return
*/
private long constantToLong(Item it) {
return ((Number)it.getConstant()).longValue();
}
/**
* @param opcode TODO
*
*/
private void handleDcmp(int opcode) {
Item it;
Item it2;
it = pop();
it2 = pop();
if ((it.getConstant() != null) && it2.getConstant() != null) {
double d = (Double) it.getConstant();
double d2 = (Double) it.getConstant();
if (Double.isNaN(d) || Double.isNaN(d2)) {
if (opcode == DCMPG)
push(new Item("I", (Integer)(1)));
else
push(new Item("I", (Integer)(-1)));
}
if (d2 < d)
push(new Item("I", (Integer) (-1) ));
else if (d2 > d)
push(new Item("I", (Integer)1));
else
push(new Item("I", (Integer)0));
} else {
push(new Item("I"));
}
}
/**
* @param opcode TODO
*
*/
private void handleFcmp(int opcode) {
Item it;
Item it2;
it = pop();
it2 = pop();
if ((it.getConstant() != null) && it2.getConstant() != null) {
float f = (Float) it.getConstant();
float f2 = (Float) it.getConstant();
if (Float.isNaN(f) || Float.isNaN(f2)) {
if (opcode == FCMPG)
push(new Item("I", (Integer)(1)));
else
push(new Item("I", (Integer)(-1)));
}
if (f2 < f)
push(new Item("I", (Integer)(-1)));
else if (f2 > f)
push(new Item("I", (Integer)(1)));
else
push(new Item("I", (Integer)(0)));
} else {
push(new Item("I"));
}
}
private void handleLcmp() {
Item it;
Item it2;
it = pop();
it2 = pop();
if ((it.getConstant() != null) && it2.getConstant() != null) {
long l = (Long) it.getConstant();
long l2 = (Long) it.getConstant();
if (l2 < l)
push(new Item("I", (Integer)(-1)));
else if (l2 > l)
push(new Item("I", (Integer)(1)));
else
push(new Item("I", (Integer)(0)));
} else {
push(new Item("I"));
}
}
private void handleSwap() {
Item i1 = pop();
Item i2 = pop();
push(i1);
push(i2);
}
private void handleDup() {
Item it;
it = pop();
push(it);
push(it);
}
private void handleDupX1() {
Item it;
Item it2;
it = pop();
it2 = pop();
push(it);
push(it2);
push(it);
}
private void handleDup2() {
Item it, it2;
it = pop();
if (it.getSize() == 2) {
push(it);
push(it);
}
else {
it2 = pop();
push(it2);
push(it);
push(it2);
push(it);
}
}
private void handleDup2X1() {
String signature;
Item it;
Item it2;
Item it3;
it = pop();
it2 = pop();
signature = it.getSignature();
if (signature.equals("J") || signature.equals("D")) {
push(it);
push(it2);
push(it);
} else {
it3 = pop();
push(it2);
push(it);
push(it3);
push(it2);
push(it);
}
}
private void handleDup2X2() {
String signature;
Item it = pop();
Item it2 = pop();
if (it.isWide()) {
if (it2.isWide()) {
push(it);
push(it2);
push(it);
} else {
Item it3 = pop();
push(it);
push(it3);
push(it2);
push(it);
}
} else {
Item it3 = pop();
if (it3.isWide()) {
push(it2);
push(it);
push(it3);
push(it2);
push(it);
} else {
Item it4 = pop();
push(it2);
push(it);
push(it4);
push(it3);
push(it2);
push(it);
}
}
}
private void handleDupX2() {
String signature;
Item it;
Item it2;
Item it3;
it = pop();
it2 = pop();
signature = it2.getSignature();
if (signature.equals("J") || signature.equals("D")) {
push(it);
push(it2);
push(it);
} else {
it3 = pop();
push(it);
push(it3);
push(it2);
push(it);
}
}
private void processMethodCall(DismantleBytecode dbc, int seen) {
String clsName = dbc.getClassConstantOperand();
String methodName = dbc.getNameConstantOperand();
String signature = dbc.getSigConstantOperand();
String appenderValue = null;
Item sbItem = null;
//TODO: stack merging for trinaries kills the constant.. would be nice to maintain.
if ("java/lang/StringBuffer".equals(clsName)
|| "java/lang/StringBuilder".equals(clsName)) {
if ("<init>".equals(methodName)) {
if ("(Ljava/lang/String;)V".equals(signature)) {
Item i = getStackItem(0);
appenderValue = (String)i.getConstant();
} else if ("()V".equals(signature)) {
appenderValue = "";
}
} else if ("toString".equals(methodName) && getStackDepth() >= 1) {
Item i = getStackItem(0);
appenderValue = (String)i.getConstant();
} else if ("append".equals(methodName) && signature.indexOf("II)") == -1 && getStackDepth() >= 2) {
sbItem = getStackItem(1);
Item i = getStackItem(0);
Object sbVal = sbItem.getConstant();
Object sVal = i.getConstant();
if ((sbVal != null) && (sVal != null)) {
appenderValue = sbVal + sVal.toString();
} else if (sbItem.registerNumber >= 0) {
OpcodeStack.Item item = getLVValue(sbItem.registerNumber);
if (item != null)
item.constValue = null;
}
}
}
pushByInvoke(dbc, seen != INVOKESTATIC);
if (appenderValue != null && getStackDepth() > 0) {
Item i = this.getStackItem(0);
i.constValue = appenderValue;
if (sbItem != null) {
i.registerNumber = sbItem.registerNumber;
i.source = sbItem.source;
i.userValue = sbItem.userValue;
if (sbItem.registerNumber >= 0)
setLVValue(sbItem.registerNumber, i );
}
return;
}
if ((clsName.equals("java/util/Random") || clsName.equals("java/security/SecureRandom")) && methodName.equals("nextInt") && signature.equals("()I")) {
Item i = pop();
i.setSpecialKind(Item.RANDOM_INT);
i.source = XFactory.createReferencedXMethod(dbc);
push(i);
}
if (clsName.equals("java/lang/Math") && methodName.equals("abs")) {
Item i = pop();
i.setSpecialKind(Item.MATH_ABS);
i.source = XFactory.createReferencedXMethod(dbc);
push(i);
}
else if (seen == INVOKEVIRTUAL && methodName.equals("hashCode") && signature.equals("()I")
|| seen == INVOKESTATIC && clsName.equals("java/lang/System") && methodName.equals("identityHashCode") && signature.equals("(Ljava/lang/Object;)I")) {
Item i = pop();
i.setSpecialKind(Item.HASHCODE_INT);
i.source = XFactory.createReferencedXMethod(dbc);
push(i);
} else if (!signature.endsWith(")V")) {
Item i = pop();
i.source = XFactory.createReferencedXMethod(dbc);
push(i);
}
}
private void mergeLists(List<Item> mergeInto, List<Item> mergeFrom, boolean errorIfSizesDoNotMatch) {
// merge stacks
int intoSize = mergeInto.size();
int fromSize = mergeFrom.size();
if (errorIfSizesDoNotMatch && intoSize != fromSize) {
if (DEBUG2) {
System.out.println("Bad merging items");
System.out.println("current items: " + mergeInto);
System.out.println("jump items: " + mergeFrom);
}
} else {
if (DEBUG2) {
System.out.println("Merging items");
System.out.println("current items: " + mergeInto);
System.out.println("jump items: " + mergeFrom);
}
for (int i = 0; i < Math.min(intoSize, fromSize); i++)
mergeInto.set(i, Item.merge(mergeInto.get(i), mergeFrom.get(i)));
if (DEBUG2) {
System.out.println("merged items: " + mergeInto);
}
}
}
public void clear() {
stack.clear();
lvValues.clear();
}
BitSet exceptionHandlers = new BitSet();
private Map<Integer, List<Item>> jumpEntries = new HashMap<Integer, List<Item>>();
private Map<Integer, List<Item>> jumpStackEntries = new HashMap<Integer, List<Item>>();
private BitSet jumpEntryLocations = new BitSet();
private void addJumpValue(int target) {
if (DEBUG)
System.out.println("Set jump entry at " + methodName + ":" + target + "pc to " + stack + " : " + lvValues );
List<Item> atTarget = jumpEntries.get(target);
if (atTarget == null) {
if (DEBUG)
System.out.println("Was null");
jumpEntries.put(target, new ArrayList<Item>(lvValues));
jumpEntryLocations.set(target);
if (stack.size() > 0) {
jumpStackEntries.put(target, new ArrayList<Item>(stack));
}
return;
}
mergeLists(atTarget, lvValues, false);
List<Item> stackAtTarget = jumpStackEntries.get(target);
if (stack.size() > 0 && stackAtTarget != null)
mergeLists(stackAtTarget, stack, false);
if (DEBUG)
System.out.println("merge target for " + methodName + ":" + target + "pc is " + atTarget);
}
private String methodName;
DismantleBytecode v;
public int resetForMethodEntry(final DismantleBytecode v) {
this.v = v;
methodName = v.getMethodName();
jumpEntries.clear();
jumpStackEntries.clear();
jumpEntryLocations.clear();
lastUpdate.clear();
convertJumpToOneZeroState = convertJumpToZeroOneState = 0;
reachOnlyByBranch = false;
int result= resetForMethodEntry0(v);
Code code = v.getMethod().getCode();
if (code == null) return result;
if (useIterativeAnalysis) {
// FIXME: Be clever
if (DEBUG)
System.out.println(" --- Iterative analysis");
DismantleBytecode branchAnalysis = new DismantleBytecode() {
@Override
public void sawOpcode(int seen) {
OpcodeStack.this.sawOpcode(this, seen);
}
// perhaps we don't need this
// @Override
// public void sawBranchTo(int pc) {
// addJumpValue(pc);
};
branchAnalysis.setupVisitorForClass(v.getThisClass());
branchAnalysis.doVisitMethod(v.getMethod());
if (!jumpEntries.isEmpty())
branchAnalysis.doVisitMethod(v.getMethod());
if (DEBUG && !jumpEntries.isEmpty()) {
System.out.println("Found dataflow for jumps in " + v.getMethodName());
for (Integer pc : jumpEntries.keySet()) {
List<Item> list = jumpEntries.get(pc);
System.out.println(pc + " -> " + Integer.toString(System.identityHashCode(list),16) + " " + list);
}
}
resetForMethodEntry0(v);
if (DEBUG)
System.out.println(" --- End of Iterative analysis");
}
return result;
}
private int resetForMethodEntry0(PreorderVisitor v) {
if (DEBUG) System.out.println("
stack.clear();
lvValues.clear();
reachOnlyByBranch = false;
seenTransferOfControl = false;
String className = v.getClassName();
String signature = v.getMethodSig();
exceptionHandlers.clear();
Method m = v.getMethod();
Code code = m.getCode();
if (code != null)
{
CodeException[] exceptionTable = code.getExceptionTable();
if (exceptionTable != null)
for(CodeException ex : exceptionTable)
exceptionHandlers.set(ex.getHandlerPC());
}
if (DEBUG) System.out.println(" --- " + className
+ " " + m.getName() + " " + signature);
Type[] argTypes = Type.getArgumentTypes(signature);
int reg = 0;
if (!m.isStatic()) {
Item it = new Item("L" + className+";");
it.setInitialParameter(true);
it.registerNumber = reg;
setLVValue( reg, it);
reg += it.getSize();
}
for (Type argType : argTypes) {
Item it = new Item(argType.getSignature());
it.registerNumber = reg;
it.setInitialParameter(true);
setLVValue(reg, it);
reg += it.getSize();
}
return reg;
}
public int getStackDepth() {
return stack.size();
}
public Item getStackItem(int stackOffset) {
if (stackOffset < 0 || stackOffset >= stack.size()) {
AnalysisContext.logError("Can't get stack offset " + stackOffset
+ " from " + stack.toString() +" in "
+ v.getFullyQualifiedMethodName(), new IllegalArgumentException());
return new Item("Lfindbugs/OpcodeStackError;");
}
int tos = stack.size() - 1;
int pos = tos - stackOffset;
try {
return stack.get(pos);
} catch (ArrayIndexOutOfBoundsException e) {
throw new ArrayIndexOutOfBoundsException(
"Requested item at offset " + stackOffset + " in a stack of size " + stack.size()
+", made request for position " + pos);
}
}
private Item pop() {
return stack.remove(stack.size()-1);
}
private void pop(int count)
{
while ((count
pop();
}
private void push(Item i) {
stack.add(i);
}
private void pushByConstant(DismantleBytecode dbc, Constant c) {
if (c instanceof ConstantClass)
push(new Item("Ljava/lang/Class;", ((ConstantClass)c).getConstantValue(dbc.getConstantPool())));
else if (c instanceof ConstantInteger)
push(new Item("I", (Integer)(((ConstantInteger) c).getBytes())));
else if (c instanceof ConstantString) {
int s = ((ConstantString) c).getStringIndex();
push(new Item("Ljava/lang/String;", getStringFromIndex(dbc, s)));
}
else if (c instanceof ConstantFloat)
push(new Item("F", (Float)(((ConstantFloat) c).getBytes())));
else if (c instanceof ConstantDouble)
push(new Item("D", (Double)(((ConstantDouble) c).getBytes())));
else if (c instanceof ConstantLong)
push(new Item("J", (Long)(((ConstantLong) c).getBytes())));
else
throw new UnsupportedOperationException("Constant type not expected" );
}
private void pushByLocalObjectLoad(DismantleBytecode dbc, int register) {
Method m = dbc.getMethod();
LocalVariableTable lvt = m.getLocalVariableTable();
if (lvt != null) {
LocalVariable lv = LVTHelper.getLocalVariableAtPC(lvt, register, dbc.getPC());
if (lv != null) {
String signature = lv.getSignature();
pushByLocalLoad(signature, register);
return;
}
}
pushByLocalLoad("", register);
}
private void pushByIntMath(int seen, Item lhs, Item rhs) {
if (DEBUG) System.out.println("pushByIntMath: " + rhs.getConstant() + " " + lhs.getConstant() );
Item newValue = new Item("I");
try {
if ((rhs.getConstant() != null) && lhs.getConstant() != null) {
Integer lhsValue = (Integer) lhs.getConstant();
Integer rhsValue = (Integer) rhs.getConstant();
if (seen == IADD)
newValue = new Item("I",lhsValue + rhsValue);
else if (seen == ISUB)
newValue = new Item("I",lhsValue - rhsValue);
else if (seen == IMUL)
newValue = new Item("I", lhsValue * rhsValue);
else if (seen == IDIV)
newValue = new Item("I", lhsValue / rhsValue);
else if (seen == IAND) {
newValue = new Item("I", lhsValue & rhsValue);
if ((rhsValue&0xff) == 0 && rhsValue != 0 || (lhsValue&0xff) == 0 && lhsValue != 0 )
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
} else if (seen == IOR)
newValue = new Item("I",lhsValue | rhsValue);
else if (seen == IXOR)
newValue = new Item("I",lhsValue ^ rhsValue);
else if (seen == ISHL) {
newValue = new Item("I",lhsValue << rhsValue);
if (rhsValue >= 8) newValue.specialKind = Item.LOW_8_BITS_CLEAR;
}
else if (seen == ISHR)
newValue = new Item("I",lhsValue >> rhsValue);
else if (seen == IREM)
newValue = new Item("I", lhsValue % rhsValue);
else if (seen == IUSHR)
newValue = new Item("I", lhsValue >>> rhsValue);
} else if (rhs.getConstant() != null && seen == ISHL && (Integer) rhs.getConstant() >= 8)
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
else if (lhs.getConstant() != null && seen == IAND) {
int value = (Integer) lhs.getConstant();
if (value == 0)
newValue = new Item("I", 0);
else if ((value & 0xff) == 0)
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
else if (value >= 0)
newValue.specialKind = Item.MASKED_NON_NEGATIVE;
} else if (rhs.getConstant() != null && seen == IAND) {
int value = (Integer) rhs.getConstant();
if (value == 0)
newValue = new Item("I", 0);
else if ((value & 0xff) == 0)
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
else if (value >= 0)
newValue.specialKind = Item.MASKED_NON_NEGATIVE;
}
} catch (RuntimeException e) {
// ignore it
}
if (lhs.specialKind == Item.INTEGER_SUM && rhs.getConstant() != null ) {
int rhsValue = (Integer) rhs.getConstant();
if (seen == IDIV && rhsValue ==2 || seen == ISHR && rhsValue == 1)
newValue.specialKind = Item.AVERAGE_COMPUTED_USING_DIVISION;
}
if (seen == IADD && newValue.specialKind == 0 && lhs.getConstant() == null && rhs.getConstant() == null )
newValue.specialKind = Item.INTEGER_SUM;
if (seen == IREM && lhs.specialKind == Item.HASHCODE_INT)
newValue.specialKind = Item.HASHCODE_INT_REMAINDER;
if (seen == IREM && lhs.specialKind == Item.RANDOM_INT)
newValue.specialKind = Item.RANDOM_INT_REMAINDER;
if (DEBUG) System.out.println("push: " + newValue);
push(newValue);
}
private void pushByLongMath(int seen, Item lhs, Item rhs) {
Item newValue = new Item("J");
try {
if ((rhs.getConstant() != null) && lhs.getConstant() != null) {
Long lhsValue = ((Long) lhs.getConstant());
if (seen == LSHL) {
newValue =new Item("J", lhsValue << ((Number) rhs.getConstant()).intValue());
if (((Number) rhs.getConstant()).intValue() >= 8) newValue.specialKind = Item.LOW_8_BITS_CLEAR;
}
else if (seen == LSHR)
newValue =new Item("J", lhsValue >> ((Number) rhs.getConstant()).intValue());
else if (seen == LUSHR)
newValue =new Item("J", lhsValue >>> ((Number) rhs.getConstant()).intValue());
else {
Long rhsValue = ((Long) rhs.getConstant());
if (seen == LADD)
newValue = new Item("J", lhsValue + rhsValue);
else if (seen == LSUB)
newValue = new Item("J", lhsValue - rhsValue);
else if (seen == LMUL)
newValue = new Item("J", lhsValue * rhsValue);
else if (seen == LDIV)
newValue =new Item("J", lhsValue / rhsValue);
else if (seen == LAND) {
newValue = new Item("J", lhsValue & rhsValue);
if ((rhsValue&0xff) == 0 && rhsValue != 0 || (lhsValue&0xff) == 0 && lhsValue != 0 )
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
}
else if (seen == LOR)
newValue = new Item("J", lhsValue | rhsValue);
else if (seen == LXOR)
newValue =new Item("J", lhsValue ^ rhsValue);
else if (seen == LREM)
newValue =new Item("J", lhsValue % rhsValue);
}
}
else if (rhs.getConstant() != null && seen == LSHL && ((Integer) rhs.getConstant()) >= 8)
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
else if (lhs.getConstant() != null && seen == LAND && (((Long) lhs.getConstant()) & 0xff) == 0)
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
else if (rhs.getConstant() != null && seen == LAND && (((Long) rhs.getConstant()) & 0xff) == 0)
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
} catch (RuntimeException e) {
// ignore it
}
push(newValue);
}
private void pushByFloatMath(int seen, Item it, Item it2) {
Item result;
int specialKind = Item.FLOAT_MATH;
if ((it.getConstant() instanceof Float) && it2.getConstant() instanceof Float) {
if (seen == FADD)
result =new Item("F", ((Float) it2.getConstant()) + ((Float) it.getConstant()));
else if (seen == FSUB)
result =new Item("F", ((Float) it2.getConstant()) - ((Float) it.getConstant()));
else if (seen == FMUL)
result =new Item("F", ((Float) it2.getConstant()) * ((Float) it.getConstant()));
else if (seen == FDIV)
result =new Item("F", ((Float) it2.getConstant()) / ((Float) it.getConstant()));
else if (seen == FREM)
result =new Item("F", ((Float) it2.getConstant()) % ((Float) it.getConstant()));
else result =new Item("F");
} else {
result =new Item("F");
if (seen == DDIV)
specialKind = Item.NASTY_FLOAT_MATH;
}
result.setSpecialKind(specialKind);
push(result);
}
private void pushByDoubleMath(int seen, Item it, Item it2) {
Item result;
int specialKind = Item.FLOAT_MATH;
if ((it.getConstant() instanceof Double) && it2.getConstant() instanceof Double) {
if (seen == DADD)
result = new Item("D", ((Double) it2.getConstant()) + ((Double) it.getConstant()));
else if (seen == DSUB)
result = new Item("D", ((Double) it2.getConstant()) - ((Double) it.getConstant()));
else if (seen == DMUL)
result = new Item("D", ((Double) it2.getConstant()) * ((Double) it.getConstant()));
else if (seen == DDIV)
result = new Item("D", ((Double) it2.getConstant()) / ((Double) it.getConstant()));
else if (seen == DREM)
result = new Item("D", ((Double) it2.getConstant()) % ((Double) it.getConstant()));
else
result = new Item("D");
} else {
result = new Item("D");
if (seen == DDIV)
specialKind = Item.NASTY_FLOAT_MATH;
}
result.setSpecialKind(specialKind);
push(result);
}
private void pushByInvoke(DismantleBytecode dbc, boolean popThis) {
String signature = dbc.getSigConstantOperand();
pop(PreorderVisitor.getNumberArguments(signature)+(popThis ? 1 : 0));
pushBySignature(Type.getReturnType(signature).getSignature());
}
private String getStringFromIndex(DismantleBytecode dbc, int i) {
ConstantUtf8 name = (ConstantUtf8) dbc.getConstantPool().getConstant(i);
return name.getBytes();
}
private void pushBySignature(String s) {
if ("V".equals(s))
return;
push(new Item(s, (Object) null));
}
private void pushByLocalStore(int register) {
Item it = pop();
if (it.getRegisterNumber() != register) {
for(Item i : lvValues) if (i != null) {
if (i.registerNumber == register) i.registerNumber = -1;
if (i.fieldLoadedFromRegister == register) i.fieldLoadedFromRegister = -1;
}
for(Item i : stack) if (i != null) {
if (i.registerNumber == register) i.registerNumber = -1;
if (i.fieldLoadedFromRegister == register) i.fieldLoadedFromRegister = -1;
}
}
setLVValue( register, it );
}
private void pushByLocalLoad(String signature, int register) {
Item it = getLVValue(register);
if (it == null) {
Item item = new Item(signature);
item.registerNumber = register;
push(item);
}
else if (it.getRegisterNumber() >= 0)
push(it);
else {
push(new Item(it, register));
}
}
private void setLVValue(int index, Item value ) {
int addCount = index - lvValues.size() + 1;
while ((addCount
lvValues.add(null);
if (!useIterativeAnalysis && seenTransferOfControl)
value = Item.merge(value, lvValues.get(index) );
lvValues.set(index, value);
}
private Item getLVValue(int index) {
if (index >= lvValues.size())
return null;
return lvValues.get(index);
}
}
// vim:ts=4 |
package soot.jimple.toolkits.typing.integer;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.BooleanType;
import soot.ByteType;
import soot.IntegerType;
import soot.Local;
import soot.PatchingChain;
import soot.ShortType;
import soot.Type;
import soot.Unit;
import soot.jimple.JimpleBody;
import soot.jimple.Stmt;
/**
* This class resolves the type of local variables.
**/
public class TypeResolver {
private static final Logger logger = LoggerFactory.getLogger(TypeResolver.class);
/** All type variable instances **/
private final List<TypeVariable> typeVariableList = new ArrayList<TypeVariable>();
/** Hashtable: [TypeNode or Local] -> TypeVariable **/
private final Map<Object, TypeVariable> typeVariableMap = new HashMap<Object, TypeVariable>();
private final JimpleBody stmtBody;
final TypeVariable BOOLEAN = typeVariable(ClassHierarchy.v().BOOLEAN);
final TypeVariable BYTE = typeVariable(ClassHierarchy.v().BYTE);
final TypeVariable SHORT = typeVariable(ClassHierarchy.v().SHORT);
final TypeVariable CHAR = typeVariable(ClassHierarchy.v().CHAR);
final TypeVariable INT = typeVariable(ClassHierarchy.v().INT);
final TypeVariable TOP = typeVariable(ClassHierarchy.v().TOP);
final TypeVariable R0_1 = typeVariable(ClassHierarchy.v().R0_1);
final TypeVariable R0_127 = typeVariable(ClassHierarchy.v().R0_127);
final TypeVariable R0_32767 = typeVariable(ClassHierarchy.v().R0_32767);
private static final boolean DEBUG = false;
// categories for type variables (solved = hard, unsolved = soft)
private List<TypeVariable> unsolved;
private List<TypeVariable> solved;
/** Get type variable for the given local. **/
TypeVariable typeVariable(Local local) {
TypeVariable result = typeVariableMap.get(local);
if (result == null) {
int id = typeVariableList.size();
typeVariableList.add(null);
result = new TypeVariable(id, this);
typeVariableList.set(id, result);
typeVariableMap.put(local, result);
if (DEBUG) {
logger.debug("[LOCAL VARIABLE \"" + local + "\" -> " + id + "]");
}
}
return result;
}
/** Get type variable for the given type node. **/
public TypeVariable typeVariable(TypeNode typeNode) {
TypeVariable result = typeVariableMap.get(typeNode);
if (result == null) {
int id = typeVariableList.size();
typeVariableList.add(null);
result = new TypeVariable(id, this, typeNode);
typeVariableList.set(id, result);
typeVariableMap.put(typeNode, result);
}
return result;
}
/** Get type variable for the given type. **/
public TypeVariable typeVariable(Type type) {
return typeVariable(ClassHierarchy.v().typeNode(type));
}
/** Get new type variable **/
public TypeVariable typeVariable() {
int id = typeVariableList.size();
typeVariableList.add(null);
TypeVariable result = new TypeVariable(id, this);
typeVariableList.set(id, result);
return result;
}
private TypeResolver(JimpleBody stmtBody) {
this.stmtBody = stmtBody;
}
public static void resolve(JimpleBody stmtBody) {
if (DEBUG) {
logger.debug("" + stmtBody.getMethod());
}
try {
TypeResolver resolver = new TypeResolver(stmtBody);
resolver.resolve_step_1();
} catch (TypeException e1) {
if (DEBUG) {
logger.debug("[integer] Step 1 Exception-->" + e1.getMessage());
}
try {
TypeResolver resolver = new TypeResolver(stmtBody);
resolver.resolve_step_2();
} catch (TypeException e2) {
StringWriter st = new StringWriter();
PrintWriter pw = new PrintWriter(st);
logger.error(e2.getMessage(), e2);
pw.close();
throw new RuntimeException(st.toString());
}
}
}
private void debug_vars(String message) {
if (DEBUG) {
int count = 0;
logger.debug("**** START:" + message);
for (TypeVariable var : typeVariableList) {
logger.debug("" + count++ + " " + var);
}
logger.debug("**** END:" + message);
}
}
private void resolve_step_1() throws TypeException {
collect_constraints_1();
debug_vars("constraints");
compute_approximate_types();
merge_connected_components();
debug_vars("components");
merge_single_constraints();
debug_vars("single");
assign_types_1();
debug_vars("assign");
check_and_fix_constraints();
}
private void resolve_step_2() throws TypeException {
collect_constraints_2();
compute_approximate_types();
assign_types_2();
check_and_fix_constraints();
}
private void collect_constraints_1() {
ConstraintCollector collector = new ConstraintCollector(this, true);
for (Unit u : stmtBody.getUnits()) {
final Stmt stmt = (Stmt) u;
if (DEBUG) {
logger.debug("stmt: ");
}
collector.collect(stmt, stmtBody);
if (DEBUG) {
logger.debug("" + stmt);
}
}
}
private void collect_constraints_2() {
ConstraintCollector collector = new ConstraintCollector(this, false);
for (Unit u : stmtBody.getUnits()) {
final Stmt stmt = (Stmt) u;
if (DEBUG) {
logger.debug("stmt: ");
}
collector.collect(stmt, stmtBody);
if (DEBUG) {
logger.debug("" + stmt);
}
}
}
private void merge_connected_components() throws TypeException {
compute_solved();
List<TypeVariable> list = new LinkedList<TypeVariable>();
list.addAll(solved);
list.addAll(unsolved);
StronglyConnectedComponents.merge(list);
}
private void merge_single_constraints() throws TypeException {
boolean modified = true;
while (modified) {
modified = false;
refresh_solved();
for (TypeVariable var : unsolved) {
List<TypeVariable> children_to_remove = new LinkedList<TypeVariable>();
TypeNode lca = null;
var.fixChildren();
for (TypeVariable child : var.children()) {
TypeNode type = child.type();
if (type != null) {
children_to_remove.add(child);
if (lca == null) {
lca = type;
} else {
lca = lca.lca_1(type);
}
}
}
if (lca != null) {
if (DEBUG) {
if (lca == ClassHierarchy.v().TOP) {
logger.debug("*** TOP *** " + var);
for (TypeVariable typeVariable : children_to_remove) {
logger.debug("-- " + typeVariable);
}
}
}
for (TypeVariable child : children_to_remove) {
var.removeChild(child);
}
var.addChild(typeVariable(lca));
}
if (var.children().size() == 1) {
TypeVariable child = var.children().get(0);
TypeNode type = child.type();
if (type == null || type.type() != null) {
var.union(child);
modified = true;
}
}
}
if (!modified) {
for (TypeVariable var : unsolved) {
List<TypeVariable> parents_to_remove = new LinkedList<TypeVariable>();
TypeNode gcd = null;
var.fixParents();
for (TypeVariable parent : var.parents()) {
TypeNode type = parent.type();
if (type != null) {
parents_to_remove.add(parent);
if (gcd == null) {
gcd = type;
} else {
gcd = gcd.gcd_1(type);
}
}
}
if (gcd != null) {
for (TypeVariable parent : parents_to_remove) {
var.removeParent(parent);
}
var.addParent(typeVariable(gcd));
}
if (var.parents().size() == 1) {
TypeVariable parent = var.parents().get(0);
TypeNode type = parent.type();
if (type == null || type.type() != null) {
var.union(parent);
modified = true;
}
}
}
}
if (!modified) {
for (TypeVariable var : unsolved) {
if (var.type() == null && var.inv_approx() != null && var.inv_approx().type() != null) {
if (DEBUG) {
logger.debug("*** I->" + var.inv_approx().type() + " *** " + var);
}
var.union(typeVariable(var.inv_approx()));
modified = true;
}
}
}
if (!modified) {
for (TypeVariable var : unsolved) {
if (var.type() == null && var.approx() != null && var.approx().type() != null) {
if (DEBUG) {
logger.debug("*** A->" + var.approx().type() + " *** " + var);
}
var.union(typeVariable(var.approx()));
modified = true;
}
}
}
if (!modified) {
for (TypeVariable var : unsolved) {
if (var.type() == null && var.approx() == ClassHierarchy.v().R0_32767) {
if (DEBUG) {
logger.debug("*** R->SHORT *** " + var);
}
var.union(SHORT);
modified = true;
}
}
}
if (!modified) {
for (TypeVariable var : unsolved) {
if (var.type() == null && var.approx() == ClassHierarchy.v().R0_127) {
if (DEBUG) {
logger.debug("*** R->BYTE *** " + var);
}
var.union(BYTE);
modified = true;
}
}
}
if (!modified) {
for (TypeVariable var : R0_1.parents()) {
if (var.type() == null && var.approx() == ClassHierarchy.v().R0_1) {
if (DEBUG) {
logger.debug("*** R->BOOLEAN *** " + var);
}
var.union(BOOLEAN);
modified = true;
}
}
}
}
}
private void assign_types_1() throws TypeException {
for (Iterator<Local> localIt = stmtBody.getLocals().iterator(); localIt.hasNext();) {
final Local local = localIt.next();
if (local.getType() instanceof IntegerType) {
TypeVariable var = typeVariable(local);
if (var.type() == null || var.type().type() == null) {
TypeVariable.error("Type Error(21): Variable without type");
} else {
local.setType(var.type().type());
}
if (DEBUG) {
if ((var != null)
&& (var.approx() != null)
&& (var.approx().type() != null)
&& (local != null)
&& (local.getType() != null)
&& !local.getType().equals(var.approx().type())) {
logger.debug(
"local: " + local + ", type: " + local.getType() + ", approx: " + var.approx().type());
}
}
}
}
}
private void assign_types_2() throws TypeException {
for (Iterator<Local> localIt = stmtBody.getLocals().iterator(); localIt.hasNext();) {
final Local local = localIt.next();
if (local.getType() instanceof IntegerType) {
TypeVariable var = typeVariable(local);
if (var.inv_approx() != null && var.inv_approx().type() != null) {
local.setType(var.inv_approx().type());
} else if (var.approx().type() != null) {
local.setType(var.approx().type());
} else if (var.approx() == ClassHierarchy.v().R0_1) {
local.setType(BooleanType.v());
} else if (var.approx() == ClassHierarchy.v().R0_127) {
local.setType(ByteType.v());
} else {
local.setType(ShortType.v());
}
}
}
}
private void check_constraints() throws TypeException {
ConstraintChecker checker = new ConstraintChecker(this, false);
StringBuffer s = null;
if (DEBUG) {
s = new StringBuffer("Checking:\n");
}
for (Iterator<Unit> stmtIt = stmtBody.getUnits().iterator(); stmtIt.hasNext();) {
final Stmt stmt = (Stmt) stmtIt.next();
if (DEBUG) {
s.append(" " + stmt + "\n");
}
try {
checker.check(stmt, stmtBody);
} catch (TypeException e) {
if (DEBUG) {
logger.debug("" + s);
}
throw e;
}
}
}
private void check_and_fix_constraints() throws TypeException {
ConstraintChecker checker = new ConstraintChecker(this, true);
StringBuffer s = null;
PatchingChain<Unit> units = stmtBody.getUnits();
Stmt[] stmts = new Stmt[units.size()];
units.toArray(stmts);
if (DEBUG) {
s = new StringBuffer("Checking:\n");
}
for (Stmt stmt : stmts) {
if (DEBUG) {
s.append(" " + stmt + "\n");
}
try {
checker.check(stmt, stmtBody);
} catch (TypeException e) {
if (DEBUG) {
logger.debug("" + s);
}
throw e;
}
}
}
private void compute_approximate_types() throws TypeException {
TreeSet<TypeVariable> workList = new TreeSet<TypeVariable>();
for (TypeVariable var : typeVariableList) {
if (var.type() != null) {
workList.add(var);
}
}
TypeVariable.computeApprox(workList);
workList = new TreeSet<TypeVariable>();
for (TypeVariable var : typeVariableList) {
if (var.type() != null) {
workList.add(var);
}
}
TypeVariable.computeInvApprox(workList);
for (TypeVariable var : typeVariableList) {
if (var.approx() == null) {
var.union(INT);
}
}
}
private void compute_solved() {
Set<TypeVariable> unsolved_set = new TreeSet<TypeVariable>();
Set<TypeVariable> solved_set = new TreeSet<TypeVariable>();
for (TypeVariable var : typeVariableList) {
if (var.type() == null) {
unsolved_set.add(var);
} else {
solved_set.add(var);
}
}
solved = new LinkedList<TypeVariable>(solved_set);
unsolved = new LinkedList<TypeVariable>(unsolved_set);
}
private void refresh_solved() throws TypeException {
Set<TypeVariable> unsolved_set = new TreeSet<TypeVariable>();
Set<TypeVariable> solved_set = new TreeSet<TypeVariable>(solved);
for (TypeVariable var : unsolved) {
if (var.type() == null) {
unsolved_set.add(var);
} else {
solved_set.add(var);
}
}
solved = new LinkedList<TypeVariable>(solved_set);
unsolved = new LinkedList<TypeVariable>(unsolved_set);
}
} |
package edu.umd.cs.findbugs;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import java.util.Stack;
import org.apache.bcel.Repository;
import org.apache.bcel.classfile.CodeException;
import org.apache.bcel.classfile.Constant;
import org.apache.bcel.classfile.ConstantClass;
import org.apache.bcel.classfile.ConstantDouble;
import org.apache.bcel.classfile.ConstantFloat;
import org.apache.bcel.classfile.ConstantInteger;
import org.apache.bcel.classfile.ConstantLong;
import org.apache.bcel.classfile.ConstantString;
import org.apache.bcel.classfile.ConstantUtf8;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.LocalVariable;
import org.apache.bcel.classfile.LocalVariableTable;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.BasicType;
import org.apache.bcel.generic.Type;
import edu.umd.cs.findbugs.visitclass.Constants2;
import edu.umd.cs.findbugs.visitclass.DismantleBytecode;
import edu.umd.cs.findbugs.visitclass.LVTHelper;
import edu.umd.cs.findbugs.visitclass.PreorderVisitor;
/**
* tracks the types and numbers of objects that are currently on the operand stack
* throughout the execution of method. To use, a detector should instantiate one for
* each method, and call <p>stack.sawOpcode(this,seen);</p> at the bottom of their sawOpcode method.
* at any point you can then inspect the stack and see what the types of objects are on
* the stack, including constant values if they were pushed. The types described are of
* course, only the static types.
* There are some outstanding opcodes that have yet to be implemented, I couldn't
* find any code that actually generated these, so i didn't put them in because
* I couldn't test them:
* <ul>
* <li>dup2_x2</li>
* <li>jsr_w</li>
* <li>wide</li>
* </ul>
*/
public class OpcodeStack implements Constants2
{
private static final boolean DEBUG
= Boolean.getBoolean("ocstack.debug");
private List<Item> stack;
private List<Item> lvValues;
private int jumpTarget;
private Stack<List<Item>> jumpStack;
private boolean seenTransferOfControl = false;
public static class Item
{
public static final int BYTE_ARRAY_LOAD = 1;
public static final int RANDOM_INT = 2;
public static final int LOW_8_BITS_CLEAR = 3;
public static final Object UNKNOWN = null;
private int specialKind;
private String signature;
private Object constValue = UNKNOWN;
private FieldAnnotation field;
private boolean isNull = false;
private int registerNumber = -1;
private boolean isInitialParameter = false;
public int getSize() {
if (signature.equals("J") || signature.equals("D")) return 2;
return 1;
}
private static boolean equals(Object o1, Object o2) {
if (o1 == o2) return true;
if (o1 == null || o2 == null) return false;
return o1.equals(o2);
}
public int hashCode() {
int r = 42 + specialKind;
if (signature != null)
r+= signature.hashCode();
r *= 31;
if (constValue != null)
r+= constValue.hashCode();
r *= 31;
if (field != null)
r+= field.hashCode();
r *= 31;
if (isInitialParameter)
r += 17;
r += registerNumber;
return r;
}
public boolean equals(Object o) {
if (!(o instanceof Item)) return false;
Item that = (Item) o;
return equals(this.signature, that.signature)
&& equals(this.constValue, that.constValue)
&& equals(this.field, that.field)
&& this.isNull == that.isNull
&& this.specialKind == that.specialKind
&& this.registerNumber == that.registerNumber;
}
public String toString() {
StringBuffer buf = new StringBuffer("< ");
buf.append(signature);
if (specialKind == BYTE_ARRAY_LOAD)
buf.append(", byte_array_load");
else if (specialKind == RANDOM_INT)
buf.append(", random_int");
else if (specialKind == LOW_8_BITS_CLEAR)
buf.append(", low8clear");
if (constValue != UNKNOWN) {
buf.append(", ");
buf.append(constValue);
}
if (field!= UNKNOWN) {
buf.append(", ");
buf.append(field);
}
if (isInitialParameter) {
buf.append(", IP");
}
if (isNull) {
buf.append(", isNull");
}
if (registerNumber != -1) {
buf.append(", r");
buf.append(registerNumber);
}
buf.append(" >");
return buf.toString();
}
public static Item merge(Item i1, Item i2) {
if (i1 == null) return i2;
if (i2 == null) return i1;
if (i1.equals(i2)) return i1;
Item m = new Item();
m.isNull = false;
if (equals(i1.signature,i2.signature))
m.signature = i1.signature;
if (equals(i1.constValue,i2.constValue))
m.constValue = i1.constValue;
if (equals(i1.field,i2.field))
m.field = i1.field;
if (i1.isNull == i2.isNull)
m.isNull = i1.isNull;
if (i1.registerNumber == i2.registerNumber)
m.registerNumber = i1.registerNumber;
if (i1.specialKind == i2.specialKind)
m.specialKind = i1.specialKind;
return m;
}
public Item(String s, int reg) {
signature = s;
registerNumber = reg;
}
public Item(String s) {
this(s, UNKNOWN);
}
public Item(String s, FieldAnnotation f, int reg) {
signature = s;
field = f;
registerNumber = reg;
}
public Item(Item it, int reg) {
this.signature = it.signature;
this.constValue = it.constValue;
this.field = it.field;
this.isNull = it.isNull;
this.registerNumber = reg;
}
public Item(String s, FieldAnnotation f) {
this(s, f, -1);
}
public Item(String s, Object v) {
signature = s;
constValue = v;
if (v instanceof Integer && (((Integer)v).intValue() & 0xff) == 0)
specialKind = LOW_8_BITS_CLEAR;
else if (v instanceof Long && (((Long)v).intValue() & 0xff) == 0)
specialKind = LOW_8_BITS_CLEAR;
}
public Item() {
signature = "Ljava/lang/Object;";
constValue = null;
isNull = true;
}
public JavaClass getJavaClass() throws ClassNotFoundException {
String baseSig;
if (isPrimitive())
return null;
if (isArray()) {
baseSig = getElementSignature();
} else {
baseSig = signature;
}
if (baseSig.length() == 0)
return null;
baseSig = baseSig.substring(1, baseSig.length() - 1);
baseSig = baseSig.replace('/', '.');
return Repository.lookupClass(baseSig);
}
public boolean isArray() {
return signature.startsWith("[");
}
public boolean isInitialParameter() {
return isInitialParameter;
}
public String getElementSignature() {
if (!isArray())
return signature;
else {
int pos = 0;
int len = signature.length();
while (pos < len) {
if (signature.charAt(pos) != '[')
break;
pos++;
}
return signature.substring(pos);
}
}
public boolean isPrimitive() {
return !signature.startsWith("L");
}
public int getRegisterNumber() {
return registerNumber;
}
public String getSignature() {
return signature;
}
public boolean isNull() {
return isNull;
}
public Object getConstant() {
return constValue;
}
public FieldAnnotation getField() {
return field;
}
/**
* @param specialKind The specialKind to set.
*/
public void setSpecialKind(int specialKind) {
this.specialKind = specialKind;
}
/**
* @return Returns the specialKind.
*/
public int getSpecialKind() {
return specialKind;
}
}
public String toString() {
return stack.toString() + "::" + lvValues.toString();
}
public OpcodeStack()
{
stack = new ArrayList<Item>();
lvValues = new ArrayList<Item>();
jumpStack = new Stack<List<Item>>();
}
public void sawOpcode(DismantleBytecode dbc, int seen) {
int register;
String signature;
Item it, it2, it3;
Constant cons;
if (dbc.getPC() == jumpTarget) {
jumpTarget = -1;
if (!jumpStack.empty()) {
List<Item> stackToMerge = jumpStack.pop();
// merge stacks
if (stack.size() != stackToMerge.size()) {
if (DEBUG) {
System.out.println("Bad merging stacks");
System.out.println("current stack: " + stack);
System.out.println("jump stack: " + stackToMerge);
}
} else {
if (DEBUG) {
System.out.println("Merging stacks");
System.out.println("current stack: " + stack);
System.out.println("jump stack: " + stackToMerge);
}
for(int i = 0; i < stack.size(); i++)
stack.set(i, Item.merge(stack.get(i), stackToMerge.get(i)));
if (DEBUG) {
System.out.println("merged stack: " + stack);
}
}
}
}
try
{
switch (seen) {
case ALOAD:
pushByLocalObjectLoad(dbc, dbc.getRegisterOperand());
break;
case ALOAD_0:
case ALOAD_1:
case ALOAD_2:
case ALOAD_3:
pushByLocalObjectLoad(dbc, seen - ALOAD_0);
break;
case DLOAD:
pushByLocalLoad("D", dbc.getRegisterOperand());
break;
case DLOAD_0:
case DLOAD_1:
case DLOAD_2:
case DLOAD_3:
pushByLocalLoad("D", seen - DLOAD_0);
break;
case FLOAD:
pushByLocalLoad("F", dbc.getRegisterOperand());
break;
case FLOAD_0:
case FLOAD_1:
case FLOAD_2:
case FLOAD_3:
pushByLocalLoad("F", seen - FLOAD_0);
break;
case ILOAD:
pushByLocalLoad("I", dbc.getRegisterOperand());
break;
case ILOAD_0:
case ILOAD_1:
case ILOAD_2:
case ILOAD_3:
pushByLocalLoad("I", seen - ILOAD_0);
break;
case LLOAD:
pushByLocalLoad("J", dbc.getRegisterOperand());
break;
case LLOAD_0:
case LLOAD_1:
case LLOAD_2:
case LLOAD_3:
pushByLocalLoad("J", seen - LLOAD_0);
break;
case GETSTATIC:
{
Item i = new Item(dbc.getSigConstantOperand(),
FieldAnnotation.fromReferencedField(dbc));
push(i);
break;
}
case LDC:
case LDC_W:
case LDC2_W:
cons = dbc.getConstantRefOperand();
pushByConstant(dbc, cons);
break;
case INSTANCEOF:
pop();
push(new Item("I"));
break;
case ARETURN:
case DRETURN:
case FRETURN:
case IFEQ:
case IFNE:
case IFLT:
case IFLE:
case IFGT:
case IFGE:
case IFNONNULL:
case IFNULL:
case IRETURN:
case LOOKUPSWITCH:
case LRETURN:
case TABLESWITCH:
seenTransferOfControl = true;
pop();
break;
case MONITORENTER:
case MONITOREXIT:
case POP:
case PUTSTATIC:
pop();
break;
case IF_ACMPEQ:
case IF_ACMPNE:
case IF_ICMPEQ:
case IF_ICMPNE:
case IF_ICMPLT:
case IF_ICMPLE:
case IF_ICMPGT:
case IF_ICMPGE:
seenTransferOfControl = true;
pop(2);
break;
case POP2:
case PUTFIELD:
pop(2);
break;
case IALOAD:
case SALOAD:
pop(2);
push(new Item("I"));
break;
case DUP:
it = pop();
push(it);
push(it);
break;
case DUP2:
it = pop();
if (it.getSize() == 2) {
push(it);
push(it);
}
else {
it2 = pop();
push(it2);
push(it);
push(it2);
push(it);
}
break;
case DUP_X1:
it = pop();
it2 = pop();
push(it);
push(it2);
push(it);
break;
case DUP_X2:
it = pop();
it2 = pop();
signature = it2.getSignature();
if (signature.equals("J") || signature.equals("D")) {
push(it);
push(it2);
push(it);
} else {
it3 = pop();
push(it);
push(it3);
push(it2);
push(it);
}
break;
case DUP2_X1:
it = pop();
it2 = pop();
signature = it.getSignature();
if (signature.equals("J") || signature.equals("D")) {
push(it);
push(it2);
push(it);
} else {
it3 = pop();
push(it2);
push(it);
push(it3);
push(it2);
push(it);
}
break;
case IINC:
register = dbc.getRegisterOperand();
it = getLVValue( register );
it2 = new Item("I", new Integer(dbc.getIntConstant()));
pushByIntMath( IADD, it, it2);
pushByLocalStore(register);
break;
case ATHROW:
pop();
break;
case CHECKCAST:
case NOP:
break;
case RET:
case RETURN:
seenTransferOfControl = true;
break;
case GOTO:
case GOTO_W: //It is assumed that no stack items are present when
seenTransferOfControl = true;
if (getStackDepth() > 0) {
jumpStack.push(new ArrayList<Item>(stack));
pop();
jumpTarget = dbc.getBranchTarget();
}
break;
case SWAP:
Item i1 = pop();
Item i2 = pop();
push(i1);
push(i2);
break;
case ICONST_M1:
case ICONST_0:
case ICONST_1:
case ICONST_2:
case ICONST_3:
case ICONST_4:
case ICONST_5:
push(new Item("I", new Integer(seen-ICONST_0)));
break;
case LCONST_0:
case LCONST_1:
push(new Item("J", new Long(seen-LCONST_0)));
break;
case DCONST_0:
case DCONST_1:
push(new Item("D", new Double(seen-DCONST_0)));
break;
case FCONST_0:
case FCONST_1:
case FCONST_2:
push(new Item("F", new Float(seen-FCONST_0)));
break;
case ACONST_NULL:
push(new Item());
break;
case ASTORE:
case DSTORE:
case FSTORE:
case ISTORE:
case LSTORE:
pushByLocalStore(dbc.getRegisterOperand());
break;
case ASTORE_0:
case ASTORE_1:
case ASTORE_2:
case ASTORE_3:
pushByLocalStore(seen - ASTORE_0);
break;
case DSTORE_0:
case DSTORE_1:
case DSTORE_2:
case DSTORE_3:
pushByLocalStore(seen - DSTORE_0);
break;
case FSTORE_0:
case FSTORE_1:
case FSTORE_2:
case FSTORE_3:
pushByLocalStore(seen - FSTORE_0);
break;
case ISTORE_0:
case ISTORE_1:
case ISTORE_2:
case ISTORE_3:
pushByLocalStore(seen - ISTORE_0);
break;
case LSTORE_0:
case LSTORE_1:
case LSTORE_2:
case LSTORE_3:
pushByLocalStore(seen - LSTORE_0);
break;
case GETFIELD:
pop();
push(new Item(dbc.getSigConstantOperand(),
FieldAnnotation.fromReferencedField(dbc)));
break;
case ARRAYLENGTH:
pop();
push(new Item("I"));
break;
case BALOAD:
{
pop(2);
Item v = new Item("I");
v.setSpecialKind(Item.BYTE_ARRAY_LOAD);
push(v);
break;
}
case CALOAD:
pop(2);
push(new Item("I"));
break;
case DALOAD:
pop(2);
push(new Item("D"));
break;
case FALOAD:
pop(2);
push(new Item("F"));
break;
case LALOAD:
pop(2);
push(new Item("J"));
break;
case AASTORE:
case BASTORE:
case CASTORE:
case DASTORE:
case FASTORE:
case IASTORE:
case LASTORE:
case SASTORE:
pop(3);
break;
case BIPUSH:
case SIPUSH:
push(new Item("I", new Integer(dbc.getIntConstant())));
break;
case IADD:
case ISUB:
case IMUL:
case IDIV:
case IAND:
case IOR:
case IXOR:
case ISHL:
case ISHR:
case IREM:
case IUSHR:
it = pop();
it2 = pop();
pushByIntMath(seen, it, it2);
break;
case INEG:
it = pop();
if (it.getConstant() != null) {
push(new Item("I", new Integer(-((Integer)it.getConstant()).intValue())));
} else {
push(new Item("I"));
}
break;
case LNEG:
it = pop();
if (it.getConstant() != null) {
push(new Item("J", new Long(-((Long)it.getConstant()).longValue())));
} else {
push(new Item("J"));
}
break;
case DNEG:
it = pop();
if (it.getConstant() != null) {
push(new Item("D", new Double(-((Double)it.getConstant()).doubleValue())));
} else {
push(new Item("D"));
}
break;
case LADD:
case LSUB:
case LMUL:
case LDIV:
case LAND:
case LOR:
case LXOR:
case LSHL:
case LSHR:
case LREM:
case LUSHR:
if (DEBUG)
System.out.println("Long math: " + this);
it = pop();
it2 = pop();
try {
pushByLongMath(seen, it, it2);
}
catch (Exception e) {
e.printStackTrace();
} finally {
if (DEBUG)
System.out.println("After long math: " + this);
}
break;
case LCMP:
it = pop();
it2 = pop();
if ((it.getConstant() != null) && it2.getConstant() != null) {
long l = ((Long)it.getConstant()).longValue();
long l2 = ((Long)it.getConstant()).longValue();
if (l2 < l)
push(new Item("I", new Integer(-1)));
else if (l2 > l)
push(new Item("I", new Integer(1)));
else
push(new Item("I", new Integer(0)));
} else {
push(new Item("I"));
}
break;
case FCMPG:
case FCMPL:
it = pop();
it2 = pop();
if ((it.getConstant() != null) && it2.getConstant() != null) {
float f = ((Float)it.getConstant()).floatValue();
float f2 = ((Float)it.getConstant()).floatValue();
if (f2 < f)
push(new Item("I", new Integer(-1)));
else if (f2 > f)
push(new Item("I", new Integer(1)));
else
push(new Item("I", new Integer(0)));
} else {
push(new Item("I"));
}
break;
case DCMPG:
case DCMPL:
it = pop();
it2 = pop();
if ((it.getConstant() != null) && it2.getConstant() != null) {
double d = ((Double)it.getConstant()).doubleValue();
double d2 = ((Double)it.getConstant()).doubleValue();
if (d2 < d)
push(new Item("I", new Integer(-1)));
else if (d2 > d)
push(new Item("I", new Integer(1)));
else
push(new Item("I", new Integer(0)));
} else {
push(new Item("I"));
}
break;
case FADD:
case FSUB:
case FMUL:
case FDIV:
it = pop();
it2 = pop();
pushByFloatMath(seen, it, it2);
break;
case DADD:
case DSUB:
case DMUL:
case DDIV:
case DREM:
it = pop();
it2 = pop();
pushByDoubleMath(seen, it, it2);
break;
case I2B:
it = pop();
if (it.getConstant() != null) {
push(new Item("I", new Integer((int)((byte)((Integer)it.getConstant()).intValue()))));
} else {
push(new Item("I"));
}
break;
case I2C:
it = pop();
if (it.getConstant() != null) {
push(new Item("I", new Integer((int)((char)((Integer)it.getConstant()).intValue()))));
} else {
push(new Item("I"));
}
break;
case I2D:
it = pop();
if (it.getConstant() != null) {
push(new Item("D", new Double((double)((Integer)it.getConstant()).intValue())));
} else {
push(new Item("D"));
}
break;
case I2F:
it = pop();
if (it.getConstant() != null) {
push(new Item("F", new Float((float)((Integer)it.getConstant()).intValue())));
} else {
push(new Item("F"));
}
break;
case I2L:{
it = pop();
Item newValue;
if (it.getConstant() != null) {
newValue = new Item("J", new Long((long)((Integer)it.getConstant()).intValue()));
} else {
newValue = new Item("J");
}
newValue.setSpecialKind(it.getSpecialKind());
push(newValue);
}
break;
case I2S:
it = pop();
if (it.getConstant() != null) {
push(new Item("I", new Integer((int)((short)((Integer)it.getConstant()).intValue()))));
} else {
push(new Item("I"));
}
break;
case D2I:
it = pop();
if (it.getConstant() != null) {
push(new Item("I", new Integer(((Integer)it.getConstant()).intValue())));
} else {
push(new Item("I"));
}
break;
case D2F:
it = pop();
if (it.getConstant() != null) {
push(new Item("F", new Float((float)((Double)it.getConstant()).doubleValue())));
} else {
push(new Item("F"));
}
break;
case D2L:
it = pop();
if (it.getConstant() != null) {
push(new Item("J", new Long((long)((Double)it.getConstant()).doubleValue())));
} else {
push(new Item("J"));
}
break;
case L2I:
it = pop();
if (it.getConstant() != null) {
push(new Item("I", new Integer((int)((Long)it.getConstant()).longValue())));
} else {
push(new Item("I"));
}
break;
case L2D:
it = pop();
if (it.getConstant() != null) {
push(new Item("D", new Double((double)((Long)it.getConstant()).longValue())));
} else {
push(new Item("D"));
}
break;
case L2F:
it = pop();
if (it.getConstant() != null) {
push(new Item("F", new Float((float)((Long)it.getConstant()).longValue())));
} else {
push(new Item("F"));
}
break;
case F2I:
it = pop();
if (it.getConstant() != null) {
push(new Item("I", new Integer((int)((Float)it.getConstant()).floatValue())));
} else {
push(new Item("I"));
}
break;
case F2D:
it = pop();
if (it.getConstant() != null) {
push(new Item("D", new Double((double)((Float)it.getConstant()).floatValue())));
} else {
push(new Item("D"));
}
break;
case NEW:
pushBySignature("L" + dbc.getClassConstantOperand() + ";");
break;
case NEWARRAY:
pop();
signature = "[" + BasicType.getType((byte)dbc.getIntConstant()).getSignature();
pushBySignature(signature);
break;
// According to the VM Spec 4.4.1, anewarray and multianewarray
// can refer to normal class/interface types (encoded in
// "internal form"), or array classes (encoded as signatures
// beginning with "[").
case ANEWARRAY:
pop();
signature = dbc.getClassConstantOperand();
if (!signature.startsWith("[")) {
signature = "L" + signature + ";";
}
pushBySignature(signature);
break;
case MULTIANEWARRAY:
int dims = dbc.getIntConstant();
while ((dims
pop();
}
signature = dbc.getClassConstantOperand();
if (!signature.startsWith("[")) {
signature = "L" + signature + ";";
}
pushBySignature(signature);
break;
case AALOAD:
pop();
it = pop();
pushBySignature(it.getElementSignature());
break;
case JSR:
push(new Item(""));
break;
case INVOKEINTERFACE:
case INVOKESPECIAL:
case INVOKESTATIC:
case INVOKEVIRTUAL:
pushByInvoke(dbc, seen != INVOKESTATIC);
if (dbc.getNameConstantOperand().equals("nextInt")) {
Item i = pop();
i.setSpecialKind(Item.RANDOM_INT);
push(i);
}
break;
default:
throw new UnsupportedOperationException("OpCode not supported yet" );
}
}
/*
// FIXME: This class currently relies on catching runtime exceptions.
// This should be fixed so they don't occur.
catch (RuntimeException e) {
throw e;
}
*/
catch (RuntimeException e) {
//If an error occurs, we clear the stack and locals. one of two things will occur.
//Either the client will expect more stack items than really exist, and so they're condition check will fail,
//or the stack will resync with the code. But hopefully not false positives
clear();
}
finally {
if (exceptionHandlers.get(dbc.getNextPC()))
push(new Item());
if (DEBUG)
System.out.println(OPCODE_NAMES[seen] + " stack depth: " + getStackDepth());
}
}
public void clear() {
stack.clear();
lvValues.clear();
jumpStack.clear();
}
BitSet exceptionHandlers = new BitSet();
public int resetForMethodEntry(PreorderVisitor v) {
if (DEBUG) System.out.println("
stack.clear();
jumpTarget = -1;
lvValues.clear();
jumpStack.clear();
seenTransferOfControl = false;
String className = v.getClassName();
Method m = v.getMethod();
String signature = v.getMethodSig();
exceptionHandlers.clear();
for(CodeException ex : m.getCode().getExceptionTable())
exceptionHandlers.set(ex.getHandlerPC());
if (DEBUG) System.out.println(" --- " + className
+ " " + m.getName() + " " + signature);
Type[] argTypes = Type.getArgumentTypes(signature);
int reg = 0;
if (!m.isStatic()) {
Item it = new Item("L" + className+";");
it.isInitialParameter = true;
it.registerNumber = reg;
setLVValue( reg++, it);
}
for (Type argType : argTypes) {
Item it = new Item(argType.getSignature());
it.registerNumber = reg;
it.isInitialParameter = true;
setLVValue(reg++, it);
}
return reg;
}
public int getStackDepth() {
return stack.size();
}
public Item getStackItem(int stackOffset) {
if (stackOffset < 0 || stackOffset >= stack.size()) {
assert false;
return new Item("Lfindbugs/OpcodeStackError;");
}
int tos = stack.size() - 1;
int pos = tos - stackOffset;
try {
return stack.get(pos);
} catch (ArrayIndexOutOfBoundsException e) {
throw new ArrayIndexOutOfBoundsException(
"Requested item at offset " + stackOffset + " in a stack of size " + stack.size()
+", made request for position " + pos);
}
}
private Item pop() {
return stack.remove(stack.size()-1);
}
private void pop(int count)
{
while ((count
pop();
}
private void push(Item i) {
stack.add(i);
}
private void pushByConstant(DismantleBytecode dbc, Constant c) {
if (c instanceof ConstantClass)
push(new Item("Ljava/lang/Class;", null));
else if (c instanceof ConstantInteger)
push(new Item("I", new Integer(((ConstantInteger) c).getBytes())));
else if (c instanceof ConstantString) {
int s = ((ConstantString) c).getStringIndex();
push(new Item("Ljava/lang/String;", getStringFromIndex(dbc, s)));
}
else if (c instanceof ConstantFloat)
push(new Item("F", new Float(((ConstantFloat) c).getBytes())));
else if (c instanceof ConstantDouble)
push(new Item("D", new Double(((ConstantDouble) c).getBytes())));
else if (c instanceof ConstantLong)
push(new Item("J", new Long(((ConstantLong) c).getBytes())));
else
throw new UnsupportedOperationException("Constant type not expected" );
}
private void pushByLocalObjectLoad(DismantleBytecode dbc, int register) {
Method m = dbc.getMethod();
LocalVariableTable lvt = m.getLocalVariableTable();
if (lvt != null) {
LocalVariable lv = LVTHelper.getLocalVariableAtPC(lvt, register, dbc.getPC());
if (lv != null) {
String signature = lv.getSignature();
pushByLocalLoad(signature, register);
return;
}
}
pushByLocalLoad("", register);
}
private void pushByIntMath(int seen, Item it, Item it2) {
if (DEBUG) System.out.println("pushByIntMath: " + it.getConstant() + " " + it2.getConstant() );
Item newValue = new Item("I");
try {
if ((it.getConstant() != null) && it2.getConstant() != null) {
if (seen == IADD)
newValue = new Item("I", new Integer(((Integer)it2.getConstant()).intValue() + ((Integer)it.getConstant()).intValue()));
else if (seen == ISUB)
newValue = new Item("I", new Integer(((Integer)it2.getConstant()).intValue() - ((Integer)it.getConstant()).intValue()));
else if (seen == IMUL)
newValue = new Item("I", new Integer(((Integer)it2.getConstant()).intValue() * ((Integer)it.getConstant()).intValue()));
else if (seen == IDIV)
newValue = new Item("I", new Integer(((Integer)it2.getConstant()).intValue() / ((Integer)it.getConstant()).intValue()));
else if (seen == IAND)
newValue = new Item("I", new Integer(((Integer)it2.getConstant()).intValue() & ((Integer)it.getConstant()).intValue()));
else if (seen == IOR)
newValue = new Item("I", new Integer(((Integer)it2.getConstant()).intValue() | ((Integer)it.getConstant()).intValue()));
else if (seen == IXOR)
newValue = new Item("I", new Integer(((Integer)it2.getConstant()).intValue() ^ ((Integer)it.getConstant()).intValue()));
else if (seen == ISHL)
newValue = new Item("I", new Integer(((Integer)it2.getConstant()).intValue() << ((Integer)it.getConstant()).intValue()));
else if (seen == ISHR)
newValue = new Item("I", new Integer(((Integer)it2.getConstant()).intValue() >> ((Integer)it.getConstant()).intValue()));
else if (seen == IREM)
newValue = new Item("I", new Integer(((Integer)it2.getConstant()).intValue() % ((Integer)it.getConstant()).intValue()));
else if (seen == IUSHR)
newValue = new Item("I", new Integer(((Integer)it2.getConstant()).intValue() >>> ((Integer)it.getConstant()).intValue()));
} else if (it2.getConstant() != null && seen == ISHL && ((Integer)it2.getConstant()).intValue() >= 8)
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
else if (it2.getConstant() != null && seen == IAND && (((Integer)it2.getConstant()).intValue() & 0xff) == 0)
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
} catch (RuntimeException e) {
// ignore it
}
if (DEBUG) System.out.println("push: " + newValue);
push(newValue);
}
private void pushByLongMath(int seen, Item it, Item it2) {
Item newValue = new Item("J");
try {
if ((it.getConstant() != null) && it2.getConstant() != null) {
if (seen == LADD)
newValue = new Item("J", new Long(((Long)it2.getConstant()).longValue() + ((Long)it.getConstant()).longValue()));
else if (seen == LSUB)
newValue = new Item("J", new Long(((Long)it2.getConstant()).longValue() - ((Long)it.getConstant()).longValue()));
else if (seen == LMUL)
newValue = new Item("J", new Long(((Long)it2.getConstant()).longValue() * ((Long)it.getConstant()).longValue()));
else if (seen == LDIV)
newValue =new Item("J", new Long(((Long)it2.getConstant()).longValue() / ((Long)it.getConstant()).longValue()));
else if (seen == LAND)
newValue = new Item("J", new Long(((Long)it2.getConstant()).longValue() & ((Long)it.getConstant()).longValue()));
else if (seen == LOR)
newValue = new Item("J", new Long(((Long)it2.getConstant()).longValue() | ((Long)it.getConstant()).longValue()));
else if (seen == LXOR)
newValue =new Item("J", new Long(((Long)it2.getConstant()).longValue() ^ ((Long)it.getConstant()).longValue()));
else if (seen == LSHL)
newValue =new Item("J", new Long(((Long)it2.getConstant()).longValue() << ((Number)it.getConstant()).intValue()));
else if (seen == LSHR)
newValue =new Item("J", new Long(((Long)it2.getConstant()).longValue() >> ((Number)it.getConstant()).intValue()));
else if (seen == LREM)
newValue =new Item("J", new Long(((Long)it2.getConstant()).longValue() % ((Long)it.getConstant()).longValue()));
else if (seen == LUSHR)
newValue =new Item("J", new Long(((Long)it2.getConstant()).longValue() >>> ((Number)it.getConstant()).intValue()));
}
else if (it2.getConstant() != null && seen == LSHR && ((Integer)it2.getConstant()).intValue() >= 8)
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
else if (it2.getConstant() != null && seen == LAND && (((Long)it2.getConstant()).longValue() & 0xff) == 0)
newValue.specialKind = Item.LOW_8_BITS_CLEAR;
} catch (RuntimeException e) {
// ignore it
}
push(newValue);
}
private void pushByFloatMath(int seen, Item it, Item it2) {
if ((it.getConstant() != null) && it2.getConstant() != null) {
if (seen == FADD)
push(new Item("F", new Float(((Float)it2.getConstant()).floatValue() + ((Float)it.getConstant()).floatValue())));
else if (seen == FSUB)
push(new Item("F", new Float(((Float)it2.getConstant()).floatValue() - ((Float)it.getConstant()).floatValue())));
else if (seen == FMUL)
push(new Item("F", new Float(((Float)it2.getConstant()).floatValue() * ((Float)it.getConstant()).floatValue())));
else if (seen == FDIV)
push(new Item("F", new Float(((Float)it2.getConstant()).floatValue() / ((Float)it.getConstant()).floatValue())));
} else {
push(new Item("F"));
}
}
private void pushByDoubleMath(int seen, Item it, Item it2) {
if ((it.getConstant() != null) && it2.getConstant() != null) {
if (seen == DADD)
push(new Item("D", new Double(((Double)it2.getConstant()).doubleValue() + ((Double)it.getConstant()).doubleValue())));
else if (seen == DSUB)
push(new Item("D", new Double(((Double)it2.getConstant()).doubleValue() - ((Double)it.getConstant()).doubleValue())));
else if (seen == DMUL)
push(new Item("D", new Double(((Double)it2.getConstant()).doubleValue() * ((Double)it.getConstant()).doubleValue())));
else if (seen == DDIV)
push(new Item("D", new Double(((Double)it2.getConstant()).doubleValue() / ((Double)it.getConstant()).doubleValue())));
else if (seen == DREM)
push(new Item("D"));
} else {
push(new Item("D"));
}
}
private void pushByInvoke(DismantleBytecode dbc, boolean popThis) {
String signature = dbc.getSigConstantOperand();
Type[] argTypes = Type.getArgumentTypes(signature);
pop(argTypes.length+(popThis ? 1 : 0));
pushBySignature(Type.getReturnType(signature).getSignature());
}
private String getStringFromIndex(DismantleBytecode dbc, int i) {
ConstantUtf8 name = (ConstantUtf8) dbc.getConstantPool().getConstant(i);
return name.getBytes();
}
private void pushBySignature(String s) {
if ("V".equals(s))
return;
push(new Item(s, null));
}
private void pushByLocalStore(int register) {
Item it = pop();
setLVValue( register, it );
}
private void pushByLocalLoad(String signature, int register) {
Item it = getLVValue(register);
if (it == null)
push(new Item(signature, register));
else if (it.getRegisterNumber() >= 0)
push(it);
else {
push(new Item(it, register));
}
}
private void setLVValue(int index, Item value ) {
int addCount = index - lvValues.size() + 1;
while ((addCount
lvValues.add(null);
if (seenTransferOfControl)
value = Item.merge(value, lvValues.get(index) );
lvValues.set(index, value);
}
private Item getLVValue(int index) {
if (index >= lvValues.size())
return null;
return lvValues.get(index);
}
}
// vim:ts=4 |
package tigase.server.xmppclient;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.UUID;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import java.util.logging.Level;
import tigase.server.Command;
import tigase.server.ConnectionManager;
import tigase.server.Packet;
import tigase.util.DNSResolver;
import tigase.util.JIDUtils;
import tigase.util.RoutingsContainer;
import tigase.xml.Element;
import tigase.xmpp.StanzaType;
import tigase.xmpp.XMPPIOService;
import tigase.xmpp.XMPPProcessorIfc;
import tigase.xmpp.XMPPResourceConnection;
//import tigase.net.IOService;
import tigase.net.SocketReadThread;
import tigase.server.ReceiverEventHandler;
import tigase.xmpp.Authorization;
import tigase.xmpp.PacketErrorTypeException;
/**
* Class ClientConnectionManager
*
* Created: Tue Nov 22 07:07:11 2005
*
* @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a>
* @version $Rev$
*/
public class ClientConnectionManager extends ConnectionManager<XMPPIOService> {
// implements XMPPService {
/**
* Variable <code>log</code> is a class logger.
*/
private static final Logger log =
Logger.getLogger("tigase.server.xmppclient.ClientConnectionManager");
private static final String XMLNS = "jabber:client";
private static final String ROUTINGS_PROP_KEY = "routings";
private static final String ROUTING_MODE_PROP_KEY = "multi-mode";
private static final boolean ROUTING_MODE_PROP_VAL = true;
private static final String ROUTING_ENTRY_PROP_KEY = ".+";
//private static final String ROUTING_ENTRY_PROP_VAL = DEF_SM_NAME + "@localhost";
//public static final String HOSTNAMES_PROP_KEY = "hostnames";
//public String[] HOSTNAMES_PROP_VAL = {"localhost", "hostname"};
protected RoutingsContainer routings = null;
//protected Set<String> hostnames = new TreeSet<String>();
private Map<String, XMPPProcessorIfc> processors =
new ConcurrentSkipListMap<String, XMPPProcessorIfc>();
private ReceiverEventHandler stoppedHandler = newStoppedHandler();
private ReceiverEventHandler startedHandler = newStartedHandler();
private long lastMinuteDisconnects = 0;
@Override
public void processPacket(final Packet packet) {
if (log.isLoggable(Level.FINER)) {
log.finer("Processing packet: " + packet.getElemName()
+ ", type: " + packet.getType());
}
if (log.isLoggable(Level.FINEST)) {
log.finest("Processing packet: " + packet.getStringData());
}
if (packet.isCommand() && packet.getCommand() != Command.OTHER) {
processCommand(packet);
} else {
if (!writePacketToSocket(packet)) {
// Connection closed or broken, send message back to the SM
try {
Packet error =
Authorization.ITEM_NOT_FOUND.getResponseMessage(packet,
"The user connection is no longer active.", true);
addOutPacket(error);
} catch (PacketErrorTypeException e) {
if (log.isLoggable(Level.FINEST)) {
log.finest(
"Ups, already error packet. Dropping it to prevent infinite loop.");
}
}
// In case the SessionManager lost synchronization for any reason, let's
// notify it that the user connection no longer exists.
Packet command = Command.STREAM_CLOSED.getPacket(null, null,
StanzaType.set, UUID.randomUUID().toString());
command.setFrom(packet.getTo());
command.setTo(packet.getFrom());
addOutPacketWithTimeout(command, stoppedHandler, 5l, TimeUnit.SECONDS);
log.fine("Sending a command to close the remote session for non-existen Bosh connection: " +
command.toString());
}
} // end of else
}
protected void processCommand(final Packet packet) {
XMPPIOService serv = getXMPPIOService(packet);
switch (packet.getCommand()) {
case GETFEATURES:
if (packet.getType() == StanzaType.result) {
List<Element> features = getFeatures(getXMPPSession(packet));
Element elem_features = new Element("stream:features");
elem_features.addChildren(features);
elem_features.addChildren(Command.getData(packet));
Packet result = new Packet(elem_features);
result.setTo(packet.getTo());
writePacketToSocket(result);
} // end of if (packet.getType() == StanzaType.get)
break;
case STARTTLS:
if (serv != null) {
if (log.isLoggable(Level.FINER)) {
log.finer("Starting TLS for connection: " + serv.getUniqueId());
}
try {
// Note:
// If you send <proceed> packet to client you must expect
// instant response from the client with TLS handshaking data
// before you will call startTLS() on server side.
// So the initial handshaking data might be lost as they will
// be processed in another thread reading data from the socket.
// That's why below code first removes service from reading
// threads pool and then sends <proceed> packet and starts TLS.
Element proceed = Command.getData(packet, "proceed", null);
Packet p_proceed = new Packet(proceed);
SocketReadThread readThread = SocketReadThread.getInstance();
readThread.removeSocketService(serv);
// writePacketToSocket(serv, p_proceed);
serv.addPacketToSend(p_proceed);
serv.processWaitingPackets();
serv.startTLS(false);
// serv.call();
readThread.addSocketService(serv);
} catch (IOException e) {
log.warning("Error starting TLS: " + e);
} // end of try-catch
} else {
log.warning("Can't find sevice for STARTTLS command: " +
packet.getStringData());
} // end of else
break;
case REDIRECT:
String command_sessionId = Command.getFieldValue(packet, "session-id");
String newAddress = packet.getFrom();
String old_receiver = changeDataReceiver(packet, newAddress,
command_sessionId, serv);
if (old_receiver != null) {
if (log.isLoggable(Level.FINE)) {
log.fine("Redirecting data for sessionId: " + command_sessionId +
", to: " + newAddress);
}
Packet response = null;
// response = packet.commandResult(null);
// Command.addFieldValue(response, "session-id", command_sessionId);
// Command.addFieldValue(response, "action", "close");
// response.getElement().setAttribute("to", old_receiver);
// addOutPacket(response);
response = packet.commandResult(null);
Command.addFieldValue(response, "session-id", command_sessionId);
Command.addFieldValue(response, "action", "activate");
response.getElement().setAttribute("to", newAddress);
addOutPacket(response);
} else {
if (log.isLoggable(Level.FINEST)) {
log.finest("Connection for REDIRECT command does not exist, ignoring " +
"packet: " + packet.toString());
}
}
break;
case STREAM_CLOSED:
break;
case GETDISCO:
break;
case CLOSE:
if (serv != null) {
serv.stop();
} else {
if (log.isLoggable(Level.FINE)) {
log.fine("Attempt to stop non-existen service for packet: " +
packet.getStringData() + ", Service already stopped?");
}
} // end of if (serv != null) else
break;
case CHECK_USER_CONNECTION:
if (serv != null) {
// It's ok, the session has been found, respond with OK.
addOutPacket(packet.okResult((String) null, 0));
} else {
// Session is no longer active, respond with an error.
try {
addOutPacket(Authorization.ITEM_NOT_FOUND.getResponseMessage(packet,
"Connection gone.", false));
} catch (PacketErrorTypeException e) {
// Hm, error already, ignoring...
log.info("Error packet is not really expected here: " +
packet.toString());
}
}
break;
default:
writePacketToSocket(packet);
break;
} // end of switch (pc.getCommand())
}
protected String changeDataReceiver(Packet packet, String newAddress,
String command_sessionId, XMPPIOService serv) {
if (serv != null) {
String serv_sessionId =
(String)serv.getSessionData().get(XMPPIOService.SESSION_ID_KEY);
if (serv_sessionId.equals(command_sessionId)) {
String old_receiver = serv.getDataReceiver();
serv.setDataReceiver(newAddress);
return old_receiver;
} else {
log.warning("Incorrect session ID, ignoring data redirect for: "
+ newAddress + ", expected: " + serv_sessionId
+ ", received: " + command_sessionId);
}
}
return null;
}
@Override
public Queue<Packet> processSocketData(XMPPIOService serv) {
String id = getUniqueId(serv);
//String hostname = (String)serv.getSessionData().get(serv.HOSTNAME_KEY);
Packet p = null;
while ((p = serv.getReceivedPackets().poll()) != null) {
if (log.isLoggable(Level.FINER)) {
log.finer("Processing packet: " + p.getElemName()
+ ", type: " + p.getType());
}
if (log.isLoggable(Level.FINEST)) {
log.finest("Processing socket data: " + p.getStringData());
}
p.setFrom(getFromAddress(id));
String receiver = serv.getDataReceiver();
if (receiver != null) {
p.setTo(serv.getDataReceiver());
addOutPacket(p);
} else {
// Hm, receiver is not set yet..., ignoring
}
// results.offer(new Packet(new Element("OK")));
} // end of while ()
// return results;
return null;
}
@Override
public Map<String, Object> getDefaults(Map<String, Object> params) {
Map<String, Object> props = super.getDefaults(params);
// if (params.get(GEN_VIRT_HOSTS) != null) {
// HOSTNAMES_PROP_VAL = ((String)params.get(GEN_VIRT_HOSTS)).split(",");
// } else {
// HOSTNAMES_PROP_VAL = DNSResolver.getDefHostNames();
// props.put(HOSTNAMES_PROP_KEY, HOSTNAMES_PROP_VAL);
Boolean r_mode = (Boolean)params.get(getName() + "/" + ROUTINGS_PROP_KEY
+ "/" + ROUTING_MODE_PROP_KEY);
if (r_mode == null) {
props.put(ROUTINGS_PROP_KEY + "/" + ROUTING_MODE_PROP_KEY,
ROUTING_MODE_PROP_VAL);
// If the server is configured as connection manager only node then
// route packets to SM on remote host where is default routing
// for external component.
// Otherwise default routing is to SM on localhost
if (params.get("config-type").equals(GEN_CONFIG_CS)
&& params.get(GEN_EXT_COMP) != null) {
String[] comp_params = ((String)params.get(GEN_EXT_COMP)).split(",");
props.put(ROUTINGS_PROP_KEY + "/" + ROUTING_ENTRY_PROP_KEY,
DEF_SM_NAME + "@" + comp_params[1]);
} else {
props.put(ROUTINGS_PROP_KEY + "/" + ROUTING_ENTRY_PROP_KEY,
DEF_SM_NAME + "@" + DNSResolver.getDefaultHostname());
}
}
return props;
}
@Override
public void setProperties(Map<String, Object> props) {
super.setProperties(props);
boolean routing_mode =
(Boolean)props.get(ROUTINGS_PROP_KEY + "/" + ROUTING_MODE_PROP_KEY);
routings = new RoutingsContainer(routing_mode);
int idx = (ROUTINGS_PROP_KEY + "/").length();
for (Map.Entry<String, Object> entry: props.entrySet()) {
if (entry.getKey().startsWith(ROUTINGS_PROP_KEY + "/")
&& !entry.getKey().equals(ROUTINGS_PROP_KEY + "/" +
ROUTING_MODE_PROP_KEY)) {
routings.addRouting(entry.getKey().substring(idx),
(String)entry.getValue());
} // end of if (entry.getKey().startsWith(ROUTINGS_PROP_KEY + "/"))
} // end of for ()
// String[] hnames = (String[])props.get(HOSTNAMES_PROP_KEY);
// clearRoutings();
// hostnames.clear();
// for (String host: hnames) {
// addRouting(getName() + "@" + host);
// hostnames.add(host);
// } // end of for ()
}
private XMPPResourceConnection getXMPPSession(Packet p) {
XMPPIOService serv = getXMPPIOService(p);
return serv == null ? null :
(XMPPResourceConnection)serv.getSessionData().get("xmpp-session");
}
private List<Element> getFeatures(XMPPResourceConnection session) {
List<Element> results = new LinkedList<Element>();
for (XMPPProcessorIfc proc: processors.values()) {
Element[] features = proc.supStreamFeatures(session);
if (features != null) {
results.addAll(Arrays.asList(features));
} // end of if (features != null)
} // end of for ()
return results;
}
@Override
protected int[] getDefPlainPorts() {
return new int[] {5222};
}
@Override
protected int[] getDefSSLPorts() {
return new int[] {5223};
}
private String getFromAddress(String id) {
return JIDUtils.getJID(getName(), getDefHostName(), id);
}
@Override
public String xmppStreamOpened(XMPPIOService serv,
Map<String, String> attribs) {
if (log.isLoggable(Level.FINER)) {
log.finer("Stream opened: " + attribs.toString());
}
final String hostname = attribs.get("to");
String lang = attribs.get("xml:lang");
if (lang == null) {
lang = "en";
}
String id = (String)serv.getSessionData().get(XMPPIOService.SESSION_ID_KEY);
if (id == null) {
id = UUID.randomUUID().toString();
serv.getSessionData().put(XMPPIOService.SESSION_ID_KEY, id);
serv.setXMLNS(XMLNS);
}
if (hostname == null) {
return "<?xml version='1.0'?><stream:stream"
+ " xmlns='" + XMLNS + "'"
+ " xmlns:stream='http://etherx.jabber.org/streams'"
+ " id='" + id + "'"
+ " from='" + getDefHostName() + "'"
+ " version='1.0' xml:lang='en'>"
+ "<stream:error>"
+ "<improper-addressing xmlns='urn:ietf:params:xml:ns:xmpp-streams'/>"
+ "</stream:error>"
+ "</stream:stream>"
;
} // end of if (hostname == null)
if (!isLocalDomain(hostname)) {
return "<?xml version='1.0'?><stream:stream"
+ " xmlns='" + XMLNS + "'"
+ " xmlns:stream='http://etherx.jabber.org/streams'"
+ " id='" + id + "'"
+ " from='" + getDefHostName() + "'"
+ " version='1.0' xml:lang='en'>"
+ "<stream:error>"
+ "<host-unknown xmlns='urn:ietf:params:xml:ns:xmpp-streams'/>"
+ "</stream:error>"
+ "</stream:stream>"
;
} // end of if (!hostnames.contains(hostname))
// try {
writeRawData(serv, "<?xml version='1.0'?><stream:stream"
+ " xmlns='" + XMLNS + "'"
+ " xmlns:stream='http://etherx.jabber.org/streams'"
+ " from='" + hostname + "'"
+ " id='" + id + "'"
+ " version='1.0' xml:lang='en'>");
serv.getSessionData().put(XMPPIOService.HOSTNAME_KEY, hostname);
serv.setDataReceiver(routings.computeRouting(hostname));
Packet streamOpen = Command.STREAM_OPENED.getPacket(
getFromAddress(getUniqueId(serv)),
serv.getDataReceiver(), StanzaType.set, UUID.randomUUID().toString(),
Command.DataType.submit);
Command.addFieldValue(streamOpen, "session-id", id);
Command.addFieldValue(streamOpen, "hostname", hostname);
Command.addFieldValue(streamOpen, "xml:lang", lang);
addOutPacketWithTimeout(streamOpen, startedHandler, 5l, TimeUnit.SECONDS);
// if (attribs.get("version") != null) {
// addOutPacket(Command.GETFEATURES.getPacket(
// getFromAddress(getUniqueId(serv)),
// serv.getDataReceiver(), StanzaType.get, "sess2", null));
// } // end of if (attribs.get("version") != null)
// } catch (IOException e) {
// serv.stop();
return null;
}
@Override
public void serviceStopped(XMPPIOService service) {
super.serviceStopped(service);
++lastMinuteDisconnects;
// It might be a Bosh service in which case it is ignored here.
if (service.getXMLNS() == XMLNS) {
// XMPPIOService serv = (XMPPIOService)service;
if (service.getDataReceiver() != null) {
Packet command = Command.STREAM_CLOSED.getPacket(
getFromAddress(getUniqueId(service)),
service.getDataReceiver(), StanzaType.set,
UUID.randomUUID().toString());
// In case of mass-disconnects, adjust the timeout properly
addOutPacketWithTimeout(command, stoppedHandler,
5l+(lastMinuteDisconnects/10), TimeUnit.SECONDS);
if (log.isLoggable(Level.FINE)) {
log.fine("Service stopped, sending packet: " + command.getStringData());
}
} else {
if (log.isLoggable(Level.FINE)) {
log.fine("Service stopped, before stream:stream received");
}
}
}
}
@Override
public void everyMinute() {
super.everyMinute();
lastMinuteDisconnects = 0;
}
@Override
public void xmppStreamClosed(XMPPIOService serv) {
if (log.isLoggable(Level.FINER)) {
log.finer("Stream closed: " + serv.getUniqueId());
}
}
/**
* Method <code>getMaxInactiveTime</code> returns max keep-alive time
* for inactive connection. Let's assume user should send something
* at least once every 24 hours....
*
* @return a <code>long</code> value
*/
@Override
protected long getMaxInactiveTime() {
return 24*HOUR;
}
@Override
protected XMPPIOService getXMPPIOServiceInstance() {
return new XMPPIOService();
}
protected ReceiverEventHandler newStoppedHandler() {
return new StoppedHandler();
}
protected ReceiverEventHandler newStartedHandler() {
return new StartedHandler();
}
@Override
protected Integer getMaxQueueSize(int def) {
return def * 10;
}
@Override
public int processingThreads() {
return Runtime.getRuntime().availableProcessors();
}
private class StoppedHandler implements ReceiverEventHandler {
@Override
public void timeOutExpired(Packet packet) {
// Ups, doesn't look good, the server is either oveloaded or lost
// a packet.
log.warning("No response within time limit received for a packet: " +
packet.toString());
addOutPacketWithTimeout(packet, stoppedHandler, 30l, TimeUnit.SECONDS);
}
@Override
public void responseReceived(Packet packet, Packet response) {
// Great, nothing to worry about.
if (log.isLoggable(Level.FINEST)) {
log.finest("Response for stop received...");
}
}
}
private class StartedHandler implements ReceiverEventHandler {
@Override
public void timeOutExpired(Packet packet) {
// If we still haven't received confirmation from the SM then
// the packet either has been lost or the server is overloaded
// In either case we disconnect the connection.
log.warning("No response within time limit received for a packet: " +
packet.toString());
XMPPIOService serv = getXMPPIOService(packet.getFrom());
if (serv != null) {
serv.stop();
} else {
log.fine("Attempt to stop non-existen service for packet: "
+ packet.getStringData() + ", Service already stopped?");
} // end of if (serv != null) else
}
@Override
public void responseReceived(Packet packet, Packet response) {
// We are now ready to ask for features....
addOutPacket(Command.GETFEATURES.getPacket(packet.getFrom(),
packet.getTo(), StanzaType.get, UUID.randomUUID().toString(),
null));
}
}
} |
package tigase.server.xmppserver;
import java.io.IOException;
import java.net.UnknownHostException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.LinkedList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.TreeMap;
import java.util.UUID;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import tigase.db.UserRepository;
import tigase.net.ConnectionType;
import tigase.net.IOService;
import tigase.net.SocketReadThread;
import tigase.net.SocketType;
import tigase.server.ConnectionManager;
import tigase.server.MessageReceiver;
import tigase.server.Packet;
import tigase.disco.XMPPService;
import tigase.util.Algorithms;
import tigase.util.DNSResolver;
import tigase.util.JID;
import tigase.xml.Element;
import tigase.xmpp.StanzaType;
import tigase.xmpp.XMPPIOService;
import tigase.xmpp.Authorization;
import tigase.stats.StatRecord;
/**
* Class ServerConnectionManager
*
*
* Created: Tue Nov 22 07:07:11 2005
*
* @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a>
* @version $Rev$
*/
public class ServerConnectionManager extends ConnectionManager {
/**
* Variable <code>log</code> is a class logger.
*/
private static final Logger log =
Logger.getLogger("tigase.server.xmppserver.ServerConnectionManager");
public static final String HOSTNAMES_PROP_KEY = "hostnames";
public static String[] HOSTNAMES_PROP_VAL = {"localhost", "hostname"};
private String[] hostnames = HOSTNAMES_PROP_VAL;
/**
* Services connected and autorized/autenticated
*/
private Map<String, XMPPIOService> servicesByHost_Type =
new HashMap<String, XMPPIOService>();
/**
* Services which are in process of establishing s2s connection
*/
private Map<String, XMPPIOService> handshakingByHost_Type =
new HashMap<String, XMPPIOService>();
/**
* Connections IDs (cids) of services which are in process of connecting
*/
private Set<String> connectingByHost_Type = new HashSet<String>();
/**
* Normal packets between users on different servers
*/
private Map<String, ServerPacketQueue> waitingPackets =
new ConcurrentSkipListMap<String, ServerPacketQueue>();
/**
* Controll packets for s2s connection establishing
*/
private Map<String, ServerPacketQueue> waitingControlPackets =
new ConcurrentSkipListMap<String, ServerPacketQueue>();
/**
* Data shared between sessions. Some servers (like google for example)
* use different IP address for outgoing and ingoing data and as sessions
* are identified by IP address we have to create 2 separate sessions
* objects for such server. These sessions have to share session ID and
* dialback key.
*/
private Map<String, Object> sharedSessionData =
new ConcurrentSkipListMap<String, Object>();
public void processPacket(Packet packet) {
// log.finer("Processing packet: " + packet.getElemName()
// + ", type: " + packet.getType());
log.finest("Processing packet: " + packet.getStringData());
if (packet.isCommand()) {
processCommand(packet);
} else {
String cid = getConnectionId(packet);
log.finest("Connection ID is: " + cid);
synchronized(servicesByHost_Type) {
XMPPIOService serv = servicesByHost_Type.get(cid);
if (serv != null) {
writePacketToSocket(serv, packet);
} else {
addWaitingPacket(cid, packet, waitingPackets);
} // end of if (serv != null) else
}
} // end of else
}
private void addWaitingPacket(String cid, Packet packet,
Map<String, ServerPacketQueue> waitingPacketsMap) {
synchronized (connectingByHost_Type) {
boolean connecting = connectingByHost_Type.contains(cid);
if (!connecting) {
String localhost = JID.getNodeNick(cid);
String remotehost = JID.getNodeHost(cid);
boolean reconnect = (packet == null);
if (connecting =
openNewServerConnection(localhost, remotehost, reconnect)) {
connectingByHost_Type.add(cid);
} else {
// Can't establish connection...., unknown host??
waitingPacketsMap.remove(cid);
addOutPacket(
Authorization.REMOTE_SERVER_NOT_FOUND.getResponseMessage(packet,
"S2S - destination host not found", true));
}
} // end of if (serv == null)
if (connecting) {
// The packet may be null if first try to connect to remote
// server failed and now Tigase is retrying to connect
if (packet != null) {
ServerPacketQueue queue = waitingPacketsMap.get(cid);
if (queue == null) {
queue = new ServerPacketQueue();
waitingPacketsMap.put(cid, queue);
} // end of if (queue == null)
queue.offer(packet);
}
} // end of if (connecting) else
}
}
// private void dumpCurrentStack(StackTraceElement[] stack) {
// StringBuilder sb = new StringBuilder();
// for (StackTraceElement st_el: stack) {
// sb.append("\n" + st_el.toString());
// log.finest(sb.toString());
private boolean openNewServerConnection(String localhost,
String remotehost, boolean reconnect) {
// dumpCurrentStack(Thread.currentThread().getStackTrace());
try {
String ipAddress = DNSResolver.getHostSRV_IP(remotehost);
Map<String, Object> port_props = new TreeMap<String, Object>();
port_props.put("remote-ip", ipAddress);
port_props.put("local-hostname", localhost);
port_props.put("remote-hostname", remotehost);
port_props.put("ifc", new String[] {ipAddress});
port_props.put("socket", SocketType.plain);
port_props.put("type", ConnectionType.connect);
port_props.put("port-no", 5269);
String cid =
getConnectionId(localhost, remotehost, ConnectionType.connect);
port_props.put("cid", cid);
log.finest("STARTING new connection: " + cid);
if (reconnect) {
reconnectService(port_props, 15*SECOND);
} else {
startService(port_props);
}
return true;
} catch (UnknownHostException e) {
log.warning("UnknownHostException for host: " + remotehost);
return false;
} // end of try-catch
}
private String getConnectionId(String localhost, String remotehost,
ConnectionType connection) {
return JID.getJID(localhost, remotehost, connection.toString());
}
private String getConnectionId(Packet packet) {
return JID.getJID(JID.getNodeHost(packet.getFrom()),
JID.getNodeHost(packet.getTo()),
ConnectionType.connect.toString());
}
private String getConnectionId(XMPPIOService service) {
String local_hostname =
(String)service.getSessionData().get("local-hostname");
String remote_hostname =
(String)service.getSessionData().get("remote-hostname");
String cid = getConnectionId(local_hostname,
(remote_hostname != null ? remote_hostname : "NULL"),
service.connectionType());
return cid;
}
// private String getHandshakingId(String localhost, String remotehost) {
// return JID.getJID(localhost, remotehost, null);
// private String getHandshakingId(Packet packet) {
// return JID.getJID(packet.getFrom(), packet.getTo(), null);
public Queue<Packet> processSocketData(XMPPIOService serv) {
Queue<Packet> packets = serv.getReceivedPackets();
Packet p = null;
while ((p = packets.poll()) != null) {
// log.finer("Processing packet: " + p.getElemName()
// + ", type: " + p.getType());
log.finest("Processing socket data: " + p.getStringData());
if (p.getElement().getXMLNS() != null &&
p.getElement().getXMLNS().equals("jabber:server:dialback")) {
Queue<Packet> results = new LinkedList<Packet>();
processDialback(p, serv, results);
for (Packet res: results) {
String cid = res.getTo();
log.finest("Sending dialback result: " + res.getStringData()
+ " to " + cid);
XMPPIOService sender = handshakingByHost_Type.get(cid);
if (sender == null) {
sender = servicesByHost_Type.get(cid);
}
if (sender != null) {
log.finest("cid: " + cid
+ ", writing packet to socket: " + res.getStringData());
writePacketToSocket(sender, res);
} else {
// I am assuming here that it can't happen that the packet is
// to accept channel and it doesn't exist
addWaitingPacket(cid, res, waitingControlPackets);
} // end of else
} // end of for (Packet p: results)
} else {
if (p.getElemName().equals("stream:error")) {
processStreamError(p, serv);
return null;
} else {
if (checkPacket(p, serv)) {
addOutPacket(p);
} else {
return null;
}
}
} // end of else
} // end of while ()
return null;
}
private void processStreamError(Packet packet, XMPPIOService serv) {
Authorization author = Authorization.RECIPIENT_UNAVAILABLE;
if (packet.getElement().getChild("host-unknown") != null) {
author = Authorization.REMOTE_SERVER_NOT_FOUND;
}
String cid = getConnectionId(serv);
Queue<Packet> waiting = waitingPackets.remove(cid);
if (waiting != null) {
Packet p = null;
while ((p = waiting.poll()) != null) {
log.finest("Sending packet back: " + p.getStringData());
addOutPacket(author.getResponseMessage(p, "S2S - not delivered", true));
} // end of while (p = waitingPackets.remove(ipAddress) != null)
} // end of if (waiting != null)
serv.stop();
}
private boolean checkPacket(Packet packet, XMPPIOService serv) {
String packet_from = packet.getElemFrom();
String packet_to = packet.getElemTo();
if (packet_from == null || packet_to == null) {
generateStreamError("improper-addressing", serv);
return false;
}
String remote_hostname =
(String)serv.getSessionData().get("remote-hostname");
if (!JID.getNodeHost(packet_from).equals(remote_hostname)) {
generateStreamError("invalid-from", serv);
return false;
}
String local_hostname = (String)serv.getSessionData().get("local-hostname");
if (!JID.getNodeHost(packet_to).equals(local_hostname)) {
generateStreamError("host-unknown", serv);
return false;
}
return true;
}
private void processCommand(final Packet packet) {
// XMPPIOService serv = getXMPPIOService(packet);
switch (packet.getCommand()) {
case STARTTLS:
break;
case STREAM_CLOSED:
break;
case GETDISCO:
break;
case CLOSE:
break;
default:
break;
} // end of switch (pc.getCommand())
}
public String xmppStreamOpened(XMPPIOService serv,
Map<String, String> attribs) {
log.finer("Stream opened: " + attribs.toString());
switch (serv.connectionType()) {
case connect: {
// It must be always set for connect connection type
String remote_hostname =
(String)serv.getSessionData().get("remote-hostname");
String local_hostname =
(String)serv.getSessionData().get("local-hostname");
String cid = getConnectionId(local_hostname, remote_hostname,
ConnectionType.connect);
log.finest("Stream opened for: " + cid);
handshakingByHost_Type.put(cid, serv);
String remote_id = attribs.get("id");
sharedSessionData.put(cid+"-session-id", remote_id);
String uuid = UUID.randomUUID().toString();
String key = null;
try {
key = Algorithms.hexDigest(remote_id, uuid, "SHA");
} catch (NoSuchAlgorithmException e) {
key = uuid;
} // end of try-catch
sharedSessionData.put(cid+"-dialback-key", key);
Element elem = new Element("db:result", key);
elem.addAttribute("to", remote_hostname);
elem.addAttribute("from", local_hostname);
StringBuilder sb = new StringBuilder();
// Attach also all controll packets which are wating to send
Packet p = null;
Queue<Packet> waiting = waitingControlPackets.get(cid);
if (waiting != null) {
while ((p = waiting.poll()) != null) {
log.finest("Sending packet: " + p.getStringData());
sb.append(p.getStringData());
} // end of while (p = waitingPackets.remove(ipAddress) != null)
} // end of if (waiting != null)
sb.append(elem.toString());
log.finest("cid: " + (String)serv.getSessionData().get("cid")
+ ", sending: " + sb.toString());
return sb.toString();
}
case accept: {
String remote_hostname =
(String)serv.getSessionData().get("remote-hostname");
String local_hostname =
(String)serv.getSessionData().get("local-hostname");
String cid = getConnectionId(
(local_hostname != null ? local_hostname : "NULL"),
(remote_hostname != null ? remote_hostname : "NULL"),
ConnectionType.accept);
log.finest("Stream opened for: " + cid);
if (remote_hostname != null) {
log.fine("Opening stream for already established connection...., trying to turn on TLS????");
}
String id = UUID.randomUUID().toString();
// We don't know hostname yet so we have to save session-id in
// connection temp data
serv.getSessionData().put(serv.SESSION_ID_KEY, id);
return "<stream:stream"
+ " xmlns:stream='http://etherx.jabber.org/streams'"
+ " xmlns='jabber:server'"
+ " xmlns:db='jabber:server:dialback'"
+ " id='" + id + "'"
+ ">"
;
}
default:
log.severe("Warning, program shouldn't reach that point.");
break;
} // end of switch (serv.connectionType())
return null;
}
public void xmppStreamClosed(XMPPIOService serv) {
log.finer("Stream closed.");
}
public Map<String, Object> getDefaults(Map<String, Object> params) {
Map<String, Object> props = super.getDefaults(params);
if (params.get("--virt-hosts") != null) {
HOSTNAMES_PROP_VAL = ((String)params.get("--virt-hosts")).split(",");
} else {
HOSTNAMES_PROP_VAL = DNSResolver.getDefHostNames();
}
hostnames = HOSTNAMES_PROP_VAL;
props.put(HOSTNAMES_PROP_KEY, HOSTNAMES_PROP_VAL);
return props;
}
protected int[] getDefPlainPorts() {
return new int[] {5269};
}
public void setProperties(Map<String, Object> props) {
super.setProperties(props);
hostnames = (String[])props.get(HOSTNAMES_PROP_KEY);
if (hostnames == null || hostnames.length == 0) {
log.warning("Hostnames definition is empty, setting 'localhost'");
hostnames = new String[] {"localhost"};
} // end of if (hostnames == null || hostnames.length == 0)
Arrays.sort(hostnames);
addRouting("*");
}
public void serviceStarted(final IOService service) {
super.serviceStarted(service);
log.finest("s2s connection opened: " + service.getRemoteAddress()
+ ", type: " + service.connectionType().toString()
+ ", id=" + service.getUniqueId());
switch (service.connectionType()) {
case connect:
// Send init xmpp stream here
XMPPIOService serv = (XMPPIOService)service;
String data = "<stream:stream"
+ " xmlns:stream='http://etherx.jabber.org/streams'"
+ " xmlns='jabber:server'"
+ " xmlns:db='jabber:server:dialback'"
+ ">";
log.finest("cid: " + (String)serv.getSessionData().get("cid")
+ ", sending: " + data);
serv.xmppStreamOpen(data);
break;
default:
// Do nothing, more data should come soon...
break;
} // end of switch (service.connectionType())
}
public List<StatRecord> getStatistics() {
List<StatRecord> stats = super.getStatistics();
stats.add(new StatRecord(getName(), "Open s2s connections", "int",
servicesByHost_Type.size(), Level.INFO));
int waiting = 0;
for (Queue<Packet> q: waitingPackets.values()) {
waiting += q.size();
}
stats.add(new StatRecord(getName(), "Packets queued", "int",
waiting, Level.INFO));
stats.add(new StatRecord(getName(), "Connecting s2s connections", "int",
connectingByHost_Type.size(), Level.FINE));
stats.add(new StatRecord(getName(), "Handshaking s2s connections", "int",
handshakingByHost_Type.size(), Level.FINER));
// StringBuilder sb = new StringBuilder("Handshaking: ");
// for (IOService serv: handshakingByHost_Type.values()) {
// sb.append("\nService ID: " + getUniqueId(serv)
// + ", local-hostname: " + serv.getSessionData().get("local-hostname")
// + ", remote-hostname: " + serv.getSessionData().get("remote-hostname")
// + ", is-connected: " + serv.isConnected()
// + ", connection-type: " + serv.connectionType());
// log.finest(sb.toString());
LinkedList<String> waiting_qs = new LinkedList<String>();
for (Map.Entry<String, ServerPacketQueue> entry: waitingPackets.entrySet()) {
if (entry.getValue().size() > 0) {
waiting_qs.add(entry.getKey() + ": " + entry.getValue().size());
}
}
if (waiting_qs.size() > 0) {
stats.add(new StatRecord(getName(), "Packets queued for each connection",
waiting_qs, Level.FINER));
}
ArrayList<String> all_s2s = new ArrayList<String>(servicesByHost_Type.keySet());
Collections.sort(all_s2s);
stats.add(new StatRecord(getName(), "s2s connections", all_s2s, Level.FINEST));
return stats;
}
public void serviceStopped(final IOService service) {
super.serviceStopped(service);
String local_hostname =
(String)service.getSessionData().get("local-hostname");
String remote_hostname =
(String)service.getSessionData().get("remote-hostname");
if (remote_hostname == null) {
// There is something wrong...
// It may happen only when remote host connecting to Tigase
// closed connection before it send any db:... packet
// so remote domain is not known.
// Let's do nothing for now.
log.info("remote-hostname is NULL, local-hostname: " + local_hostname
+ ", local address: " + service.getLocalAddress()
+ ", remote address: " + service.getRemoteAddress());
return;
}
String cid = getConnectionId(local_hostname, remote_hostname,
service.connectionType());
boolean stopped = false;
IOService serv = servicesByHost_Type.get(cid);
// This checking is necessary due to specific s2s behaviour which
// I don't fully understand yet, possible bug in my s2s implementation
if (serv == service) {
stopped = true;
servicesByHost_Type.remove(cid);
} else {
log.info("Stopped non-active service for CID: " + cid);
}
serv = handshakingByHost_Type.get(cid);
// This checking is necessary due to specific s2s behaviour which
// I don't fully understand yet, possible bug in my s2s implementation
if (!stopped && serv == service) {
stopped = true;
handshakingByHost_Type.remove(cid);
connectingByHost_Type.remove(cid);
waitingControlPackets.remove(cid);
} else {
if (!stopped) {
log.info("Stopped non-handshaking service for CID: " + cid);
}
}
if (!stopped) {
return;
}
log.fine("s2s stopped: " + cid);
// Some servers close just 1 of dialback connections and even though
// other connection is still open they don't accept any data on that
// connections. So the solution is: if one of pair connection is closed
// close the other connection as well.
// Find other connection:
String other_id = null;
switch (service.connectionType()) {
case accept:
other_id = getConnectionId(local_hostname, remote_hostname,
ConnectionType.connect);
break;
case connect:
default:
other_id = getConnectionId(local_hostname, remote_hostname,
ConnectionType.accept);
break;
} // end of switch (service.connectionType())
XMPPIOService other_service = servicesByHost_Type.get(other_id);
if (other_service == null) {
other_service = handshakingByHost_Type.get(other_id);
} // end of if (other_service == null)
if (other_service != null) {
log.fine("Stopping other service: " + other_id);
// servicesByHost_Type.remove(other_id);
// handshakingByHost_Type.remove(other_id);
// connectingByHost_Type.remove(other_id);
other_service.stop();
} // end of if (other_service != null)
Queue<Packet> waiting = waitingPackets.get(cid);
if (waiting != null && waiting.size() > 0) {
addWaitingPacket(cid, null, waitingPackets);
}
}
public void handleDialbackSuccess(final String connect_jid) {
log.finest("handleDialbackSuccess: connect_jid="+connect_jid);
Packet p = null;
XMPPIOService serv = servicesByHost_Type.get(connect_jid);
Queue<Packet> waiting = waitingPackets.remove(connect_jid);
if (waiting != null) {
while ((p = waiting.poll()) != null) {
log.finest("Sending packet: " + p.getStringData());
writePacketToSocket(serv, p);
} // end of while (p = waitingPackets.remove(ipAddress) != null)
} // end of if (waiting != null)
}
private void generateStreamError(String error_el, XMPPIOService serv) {
Packet error = new Packet(new Element("stream:error",
new Element[] {
new Element(error_el,
new String[] {"xmlns"},
new String[] {"urn:ietf:params:xml:ns:xmpp-streams"})
}, null, null));
try {
writePacketToSocket(serv, error);
serv.writeRawData("</stream:stream>");
serv.stop();
} catch (Exception e) {
serv.stop();
}
}
private void initServiceMaping(String local_hostname, String remote_hostname,
String cid, XMPPIOService serv) {
// Assuming this is the first packet from that connection which
// tells us for what domain this connection is we have to map
// somehow this IP address to hostname
XMPPIOService old_serv = (handshakingByHost_Type.get(cid) != null ?
handshakingByHost_Type.get(cid) : servicesByHost_Type.get(cid));
if (old_serv != serv) {
serv.getSessionData().put("local-hostname", local_hostname);
serv.getSessionData().put("remote-hostname", remote_hostname);
handshakingByHost_Type.put(cid, serv);
if (old_serv != null) {
log.finest("Stopping old connection for: " + cid);
old_serv.stop();
}
}
}
public synchronized void processDialback(Packet packet, XMPPIOService serv,
Queue<Packet> results) {
log.finest("DIALBACK - " + packet.getStringData());
String local_hostname = JID.getNodeHost(packet.getElemTo());
// Check whether this is correct local host name...
if (Arrays.binarySearch(hostnames, local_hostname) < 0) {
// Ups, this hostname is not served by this server, return stream
// error and close the connection....
generateStreamError("host-unknown", serv);
return;
}
String remote_hostname = JID.getNodeHost(packet.getElemFrom());
String connect_jid = getConnectionId(local_hostname, remote_hostname,
ConnectionType.connect);
String accept_jid = getConnectionId(local_hostname, remote_hostname,
ConnectionType.accept);
// <db:result>
if (packet.getElemName().equals("db:result")) {
if (packet.getType() == null) {
// db:result with key to validate from accept connection
sharedSessionData.put(accept_jid + "-session-id",
serv.getSessionData().get(serv.SESSION_ID_KEY));
sharedSessionData.put(accept_jid + "-dialback-key",
packet.getElemCData());
initServiceMaping(local_hostname, remote_hostname, accept_jid, serv);
// <db:result> with CDATA containing KEY
Element elem = new Element("db:verify", packet.getElemCData(),
new String[] {"id", "to", "from"},
new String[] {(String)serv.getSessionData().get(serv.SESSION_ID_KEY),
packet.getElemFrom(),
packet.getElemTo()});
Packet result = new Packet(elem);
result.setTo(connect_jid);
results.offer(result);
} else {
// <db:result> with type 'valid' or 'invalid'
// It means that session has been validated now....
XMPPIOService connect_serv = handshakingByHost_Type.get(connect_jid);
switch (packet.getType()) {
case valid:
log.finer("Connection: " + connect_jid
+ " is valid, adding to available services.");
servicesByHost_Type.put(connect_jid, connect_serv);
handshakingByHost_Type.remove(connect_jid);
connectingByHost_Type.remove(connect_jid);
waitingControlPackets.remove(connect_jid);
handleDialbackSuccess(connect_jid);
break;
default:
log.finer("Connection: " + connect_jid + " is invalid!! Stopping...");
connect_serv.stop();
break;
} // end of switch (packet.getType())
} // end of if (packet.getType() != null) else
} // end of if (packet != null && packet.getElemName().equals("db:result"))
// <db:verify> with type 'valid' or 'invalid'
if (packet.getElemName().equals("db:verify")) {
if (packet.getType() == null) {
// When type is NULL then it means this packet contains
// data for verification
if (packet.getElemId() != null && packet.getElemCData() != null) {
// This might be the first dialback packet from remote server
initServiceMaping(local_hostname, remote_hostname, accept_jid, serv);
// Yes data for verification are available in packet
final String id = packet.getElemId();
final String key = packet.getElemCData();
final String local_key =
(String)sharedSessionData.get(connect_jid+"-dialback-key");
log.fine("Local key for cid=" + connect_jid + " is " + local_key);
Packet result = null;
if (key.equals(local_key)) {
log.finer("Verification for " + accept_jid
+ " succeeded, sending valid.");
result = packet.swapElemFromTo(StanzaType.valid);
} else {
log.finer("Verification for " + accept_jid
+ " failed, sending invalid.");
result = packet.swapElemFromTo(StanzaType.invalid);
} // end of if (key.equals(local_key)) else
result.getElement().setCData(null);
result.setTo(accept_jid);
log.finest("Adding result packet: " + result.getStringData()
+ " to " + result.getTo());
results.offer(result);
} // end of if (packet.getElemName().equals("db:verify"))
} else {
// Type is not null so this is packet with verification result.
// If the type is valid it means accept connection has been
// validated and we can now receive data from this channel.
Element elem = new Element("db:result",
new String[] {"type", "to", "from"},
new String[] {packet.getType().toString(),
packet.getElemFrom(), packet.getElemTo()});
XMPPIOService accept_serv = handshakingByHost_Type.remove(accept_jid);
if (accept_serv == null) {
accept_serv = servicesByHost_Type.get(accept_jid);
} else {
connectingByHost_Type.remove(accept_jid);
waitingControlPackets.remove(accept_jid);
}
try {
accept_serv.writeRawData(elem.toString());
switch (packet.getType()) {
case valid:
log.finer("Received " + packet.getType().toString()
+ " validation result, adding connection to active services.");
servicesByHost_Type.put(accept_jid, accept_serv);
break;
default:
// Ups, verification failed, let's stop the service now.
log.finer("Received " + packet.getType().toString()
+ " validation result, stopping service, closing connection.");
accept_serv.writeRawData("</stream:stream>");
accept_serv.stop();
break;
}
} catch (Exception e) {
accept_serv.stop();
}
} // end of if (packet.getType() == null) else
} // end of if (packet != null && packet.getType() != null)
}
private class ServerPacketQueue extends ConcurrentLinkedQueue<Packet> {
private static final long serialVersionUID = 1L;
}
/**
* Method <code>getMaxInactiveTime</code> returns max keep-alive time
* for inactive connection. Let's assume s2s should send something
* at least once every 15 minutes....
*
* @return a <code>long</code> value
*/
protected long getMaxInactiveTime() {
return 15*MINUTE;
}
} |
package tigase.server.xmppserver;
import java.io.IOException;
import java.net.UnknownHostException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.LinkedList;
import java.util.LinkedHashSet;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.TreeMap;
import java.util.UUID;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import tigase.db.UserRepository;
import tigase.net.ConnectionType;
//import tigase.net.IOService;
import tigase.net.SocketType;
import tigase.server.ConnectionManager;
import tigase.server.MessageReceiver;
import tigase.server.Packet;
import tigase.disco.XMPPService;
import tigase.util.Algorithms;
import tigase.util.DNSResolver;
import tigase.util.JIDUtils;
import tigase.xml.Element;
import tigase.xmpp.StanzaType;
import tigase.xmpp.XMPPIOService;
import tigase.xmpp.Authorization;
import tigase.xmpp.PacketErrorTypeException;
import tigase.stats.StatRecord;
/**
* Class ServerConnectionManager
*
*
* Created: Tue Nov 22 07:07:11 2005
*
* @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a>
* @version $Rev$
*/
public class ServerConnectionManager extends ConnectionManager<XMPPIOService>
implements ConnectionHandlerIfc {
/**
* Variable <code>log</code> is a class logger.
*/
private static final Logger log =
Logger.getLogger("tigase.server.xmppserver.ServerConnectionManager");
private static final String XMLNS_DB_ATT = "xmlns:db";
private static final String XMLNS_DB_VAL = "jabber:server:dialback";
private static final String RESULT_EL_NAME = "result";
private static final String DB_RESULT_EL_NAME = "db:result";
private static final String VERIFY_EL_NAME = "verify";
private static final String DB_VERIFY_EL_NAME = "db:verify";
public static final String HOSTNAMES_PROP_KEY = "hostnames";
public String[] HOSTNAMES_PROP_VAL = {"localhost", "hostname"};
public static final String MAX_PACKET_WAITING_TIME_PROP_KEY =
"max-packet-waiting-time";
public static final long MAX_PACKET_WAITING_TIME_PROP_VAL = 5*MINUTE;
private String[] hostnames = HOSTNAMES_PROP_VAL;
/**
* <code>maxPacketWaitingTime</code> keeps the maximum time packets
* can wait for sending in ServerPacketQueue. Packets are put in the
* queue only when connection to remote server is not established so
* effectively this timeout specifies the maximum time for connecting
* to remote server. If this time is exceeded then no more reconnecting
* attempts are performed and packets are sent back with error information.
*
* Default TCP/IP timeout is 300 seconds to we can follow this convention
* but administrator can set different timeout in server configuration.
*/
private long maxPacketWaitingTime = MAX_PACKET_WAITING_TIME_PROP_VAL;
/**
* Services connected and autorized/autenticated
*/
private Map<String, ServerConnections> connectionsByLocalRemote =
new ConcurrentSkipListMap<String, ServerConnections>();
/**
* Incoming (accept) services by sessionId. Some servers (EJabberd) opens
* many connections for each domain, especially when in cluster mode.
*/
private ConcurrentSkipListMap<String, XMPPIOService> incoming =
new ConcurrentSkipListMap<String, XMPPIOService>();
protected ServerConnections getServerConnections(String cid) {
return connectionsByLocalRemote.get(cid);
}
protected ServerConnections removeServerConnections(String cid) {
return connectionsByLocalRemote.remove(cid);
}
public void processPacket(Packet packet) {
if (log.isLoggable(Level.FINEST)) {
log.finest("Processing packet: " + packet.toString());
}
if (!packet.isCommand() || !processCommand(packet)) {
if (packet.getElemTo() == null) {
log.warning("Missing 'to' attribute, ignoring packet..."
+ packet.toString()
+ "\n This most likely happens due to missconfiguration of components domain names.");
return;
}
if (packet.getElemFrom() == null) {
log.warning("Missing 'from' attribute, ignoring packet..."
+ packet.toString());
return;
}
// Check whether addressing is correct:
String to_hostname = JIDUtils.getNodeHost(packet.getElemTo());
// We don't send packets to local domains trough s2s, there
// must be something wrong with configuration
if (Arrays.binarySearch(hostnames, to_hostname) >= 0) {
// Ups, remote hostname is the same as one of local hostname??
// Internal loop possible, we don't want that....
// Let's send the packet back....
log.finest("Packet addresses to localhost, I am not processing it: "
+ packet.getStringData());
try {
addOutPacket(
Authorization.SERVICE_UNAVAILABLE.getResponseMessage(packet,
"S2S - not delivered. Server missconfiguration.", true));
} catch (PacketErrorTypeException e) {
log.warning("Packet processing exception: " + e);
}
return;
}
// I think from_hostname needs to be different from to_hostname at
// this point... or s2s doesn't make sense
String from_hostname = JIDUtils.getNodeHost(packet.getElemFrom());
if (to_hostname.equals(from_hostname)) {
log.warning("Dropping incorrect packet - from_hostname == to_hostname: "
+ packet.toString());
return;
}
String cid = getConnectionId(packet);
log.finest("Connection ID is: " + cid);
ServerConnections serv_conn = getServerConnections(cid);
if (serv_conn == null
|| (!serv_conn.sendPacket(packet) && serv_conn.needsConnection())) {
createServerConnection(cid, packet, serv_conn);
}
} // end of else
}
private ServerConnections createNewServerConnections(String cid, Packet packet) {
ServerConnections conns = new ServerConnections(this);
if (packet != null) {
if (packet.getElement().getXMLNS() == XMLNS_DB_VAL) {
conns.addControlPacket(packet);
} else {
conns.addDataPacket(packet);
}
}
connectionsByLocalRemote.put(cid, conns);
return conns;
}
/**
* Mehtod <code>createServerConnection</code> is called only when a new
* connection is needed for any reason for given hostnames combination.
*
* @param cid a <code>String</code> s2s connection ID (localhost@remotehost)
* @param packet a <code>Packet</code> packet to send, should be passed to the
* ServerConnections only when it was null.
* @param serv_conn a <code>ServerConnections</code> which was called for
* the packet.
*/
private void createServerConnection(String cid, Packet packet,
ServerConnections serv_conn) {
ServerConnections conns = serv_conn;
if (conns == null) {
conns = createNewServerConnections(cid, packet);
}
String localhost = JIDUtils.getNodeNick(cid);
String remotehost = JIDUtils.getNodeHost(cid);
if (openNewServerConnection(localhost, remotehost)) {
conns.setConnecting();
} else {
// Can't establish connection...., unknown host??
Queue<Packet> waitingPackets = conns.getWaitingPackets();
// Well, is somebody injects a packet with the same sender and
// receiver domain and this domain is not valid then we have
// infinite loop here....
// Let's try to handle this by dropping such packet.
// It may happen as well that the source domain is different from
// target domain and both are invalid, what then?
// The best option would be to drop the packet if it is already an
// error - remote-server-not-found....
// For dialback packet just ignore the error completely as it means
// remote server tries to connect from domain which doesn't exist
// in DNS so no further action should be performed.
Packet p = null;
while ((p = waitingPackets.poll()) != null) {
if (p.getElement().getXMLNS() != XMLNS_DB_VAL) {
try {
addOutPacket(
Authorization.REMOTE_SERVER_NOT_FOUND.getResponseMessage(p,
"S2S - destination host not found", true));
} catch (PacketErrorTypeException e) {
log.warning("Packet: " + p.toString() + " processing exception: " + e);
}
}
}
conns.stopAll();
//connectionsByLocalRemote.remove(cid);
}
}
// private void dumpCurrentStack(StackTraceElement[] stack) {
// StringBuilder sb = new StringBuilder();
// for (StackTraceElement st_el: stack) {
// sb.append("\n" + st_el.toString());
// log.finest(sb.toString());
private boolean openNewServerConnection(String localhost, String remotehost) {
// dumpCurrentStack(Thread.currentThread().getStackTrace());
try {
String ipAddress = DNSResolver.getHostSRV_IP(remotehost);
Map<String, Object> port_props = new TreeMap<String, Object>();
port_props.put("remote-ip", ipAddress);
port_props.put("local-hostname", localhost);
port_props.put("remote-hostname", remotehost);
port_props.put("ifc", new String[] {ipAddress});
port_props.put("socket", SocketType.plain);
port_props.put("type", ConnectionType.connect);
port_props.put("port-no", 5269);
String cid =
getConnectionId(localhost, remotehost);
port_props.put("cid", cid);
log.finest("STARTING new connection: " + cid);
reconnectService(port_props, 5*SECOND);
return true;
} catch (UnknownHostException e) {
log.warning("UnknownHostException for host: " + remotehost);
return false;
} // end of try-catch
}
private String getConnectionId(String localhost, String remotehost) {
return JIDUtils.getJID(localhost, remotehost, null);
}
private String getConnectionId(Packet packet) {
return JIDUtils.getJID(JIDUtils.getNodeHost(packet.getElemFrom()),
JIDUtils.getNodeHost(packet.getElemTo()), null);
}
private String getConnectionId(XMPPIOService service) {
String local_hostname =
(String)service.getSessionData().get("local-hostname");
String remote_hostname =
(String)service.getSessionData().get("remote-hostname");
String cid = getConnectionId(local_hostname,
(remote_hostname != null ? remote_hostname : "NULL"));
return cid;
}
public Queue<Packet> processSocketData(XMPPIOService serv) {
Queue<Packet> packets = serv.getReceivedPackets();
Packet p = null;
while ((p = packets.poll()) != null) {
// log.finer("Processing packet: " + p.getElemName()
// + ", type: " + p.getType());
if (p.getElement().getXMLNS() == null) {
p.getElement().setXMLNS("jabber:client");
}
log.finest("Processing socket data: " + p.toString());
if (p.getElement().getXMLNS() == XMLNS_DB_VAL) {
processDialback(p, serv);
} else {
if (p.getElemName() == "error") {
processStreamError(p, serv);
return null;
} else {
if (checkPacket(p, serv)) {
log.finest("Adding packet out: " + p.getStringData());
addOutPacket(p);
} else {
return null;
}
}
} // end of else
} // end of while ()
return null;
}
private void bouncePacketsBack(Authorization author, String cid) {
ServerConnections serv_conns = getServerConnections(cid);
if (serv_conns != null) {
Queue<Packet> waiting = serv_conns.getWaitingPackets();
Packet p = null;
while ((p = waiting.poll()) != null) {
log.finest("Sending packet back: " + p.getStringData());
try {
addOutPacket(author.getResponseMessage(p, "S2S - not delivered", true));
} catch (PacketErrorTypeException e) {
log.warning("Packet processing exception: " + e);
}
} // end of while (p = waitingPackets.remove(ipAddress) != null)
} else {
log.warning("No ServerConnections for cid: " + cid);
}
}
private void processStreamError(Packet packet, XMPPIOService serv) {
Authorization author = Authorization.RECIPIENT_UNAVAILABLE;
if (packet.getElement().getChild("host-unknown") != null) {
author = Authorization.REMOTE_SERVER_NOT_FOUND;
}
String cid = getConnectionId(serv);
bouncePacketsBack(author, cid);
serv.stop();
}
private boolean checkPacket(Packet packet, XMPPIOService serv) {
String packet_from = packet.getElemFrom();
String packet_to = packet.getElemTo();
if (packet_from == null || packet_to == null) {
generateStreamError("improper-addressing", serv);
return false;
}
String remote_hostname =
(String)serv.getSessionData().get("remote-hostname");
if (!JIDUtils.getNodeHost(packet_from).equals(remote_hostname)) {
log.finer("Invalid hostname from the remote server, expected: "
+ remote_hostname);
generateStreamError("invalid-from", serv);
return false;
}
String local_hostname = (String)serv.getSessionData().get("local-hostname");
if (!JIDUtils.getNodeHost(packet_to).equals(local_hostname)) {
log.finer("Invalid hostname of the local server, expected: "
+ local_hostname);
generateStreamError("host-unknown", serv);
return false;
}
String cid = getConnectionId(serv);
String session_id = (String)serv.getSessionData().get(serv.SESSION_ID_KEY);
if (!isIncomingValid(session_id)) {
log.info("Incoming connection hasn't been validated");
return false;
}
return true;
}
public boolean isIncomingValid(String session_id) {
if (session_id == null) {
return false;
}
XMPPIOService serv = incoming.get(session_id);
if (serv == null || serv.getSessionData().get("valid") == null) {
return false;
} else {
return (Boolean)serv.getSessionData().get("valid");
}
}
private boolean processCommand(final Packet packet) {
// XMPPIOService serv = getXMPPIOService(packet);
switch (packet.getCommand()) {
case STARTTLS:
break;
case STREAM_CLOSED:
break;
case GETDISCO:
break;
case CLOSE:
break;
default:
break;
} // end of switch (pc.getCommand())
return false;
}
public String xmppStreamOpened(XMPPIOService serv,
Map<String, String> attribs) {
log.finer("Stream opened: " + attribs.toString());
switch (serv.connectionType()) {
case connect: {
// It must be always set for connect connection type
String remote_hostname =
(String)serv.getSessionData().get("remote-hostname");
String local_hostname =
(String)serv.getSessionData().get("local-hostname");
String cid = getConnectionId(local_hostname, remote_hostname);
log.finest("Stream opened for: " + cid);
ServerConnections serv_conns = getServerConnections(cid);
if (serv_conns == null) {
serv_conns = createNewServerConnections(cid, null);
}
serv_conns.addOutgoing(serv);
log.finest("Counters: ioservices: " + countIOServices()
+ ", s2s connections: " + countOpenConnections());
String remote_id = attribs.get("id");
serv.getSessionData().put(serv.SESSION_ID_KEY, remote_id);
String uuid = UUID.randomUUID().toString();
String key = null;
try {
key = Algorithms.hexDigest(remote_id, uuid, "SHA");
} catch (NoSuchAlgorithmException e) {
key = uuid;
} // end of try-catch
serv_conns.putDBKey(remote_id, key);
Element elem = new Element(DB_RESULT_EL_NAME, key,
new String[] {"from", "to", XMLNS_DB_ATT},
new String[] {local_hostname, remote_hostname, XMLNS_DB_VAL});
serv_conns.addControlPacket(new Packet(elem));
serv_conns.sendAllControlPackets();
return null;
}
case accept: {
String remote_hostname =
(String)serv.getSessionData().get("remote-hostname");
String local_hostname =
(String)serv.getSessionData().get("local-hostname");
String cid = getConnectionId(
(local_hostname != null ? local_hostname : "NULL"),
(remote_hostname != null ? remote_hostname : "NULL"));
log.finest("Stream opened for: " + cid);
if (remote_hostname != null) {
log.fine("Opening stream for already established connection...., trying to turn on TLS????");
}
String id = UUID.randomUUID().toString();
// We don't know hostname yet so we have to save session-id in
// connection temp data
serv.getSessionData().put(serv.SESSION_ID_KEY, id);
incoming.put(id, serv);
return "<stream:stream"
+ " xmlns:stream='http://etherx.jabber.org/streams'"
+ " xmlns='jabber:server'"
+ " xmlns:db='jabber:server:dialback'"
+ " id='" + id + "'"
+ ">"
;
}
default:
log.severe("Warning, program shouldn't reach that point.");
break;
} // end of switch (serv.connectionType())
return null;
}
public void xmppStreamClosed(XMPPIOService serv) {
log.finer("Stream closed: " + getConnectionId(serv));
}
public Map<String, Object> getDefaults(Map<String, Object> params) {
Map<String, Object> props = super.getDefaults(params);
// Usually we want the server to do s2s for the external component too:
if (params.get(GEN_VIRT_HOSTS) != null) {
HOSTNAMES_PROP_VAL = ((String)params.get(GEN_VIRT_HOSTS)).split(",");
} else {
HOSTNAMES_PROP_VAL = DNSResolver.getDefHostNames();
}
ArrayList<String> vhosts =
new ArrayList<String>(Arrays.asList(HOSTNAMES_PROP_VAL));
for (Map.Entry<String, Object> entry: params.entrySet()) {
if (entry.getKey().startsWith(GEN_EXT_COMP)) {
String ext_comp = (String)entry.getValue();
if (ext_comp != null) {
String[] comp_params = ext_comp.split(",");
vhosts.add(comp_params[1]);
}
}
if (entry.getKey().startsWith(GEN_COMP_NAME)) {
String comp_name_suffix = entry.getKey().substring(GEN_COMP_NAME.length());
String c_name = (String)params.get(GEN_COMP_NAME + comp_name_suffix);
for (String vhost: HOSTNAMES_PROP_VAL) {
vhosts.add(c_name + "." + vhost);
}
}
}
HOSTNAMES_PROP_VAL = vhosts.toArray(new String[0]);
hostnames = HOSTNAMES_PROP_VAL;
props.put(HOSTNAMES_PROP_KEY, HOSTNAMES_PROP_VAL);
props.put(MAX_PACKET_WAITING_TIME_PROP_KEY,
MAX_PACKET_WAITING_TIME_PROP_VAL);
return props;
}
protected int[] getDefPlainPorts() {
return new int[] {5269};
}
public void setProperties(Map<String, Object> props) {
super.setProperties(props);
hostnames = (String[])props.get(HOSTNAMES_PROP_KEY);
if (hostnames == null || hostnames.length == 0) {
log.warning("Hostnames definition is empty, setting 'localhost'");
hostnames = new String[] {"localhost"};
} // end of if (hostnames == null || hostnames.length == 0)
Arrays.sort(hostnames);
addRouting("*");
maxPacketWaitingTime = (Long)props.get(MAX_PACKET_WAITING_TIME_PROP_KEY);
}
public void serviceStarted(XMPPIOService serv) {
super.serviceStarted(serv);
log.finest("s2s connection opened: " + serv.getRemoteAddress()
+ ", type: " + serv.connectionType().toString()
+ ", id=" + serv.getUniqueId());
switch (serv.connectionType()) {
case connect:
// Send init xmpp stream here
// XMPPIOService serv = (XMPPIOService)service;
String data = "<stream:stream"
+ " xmlns:stream='http://etherx.jabber.org/streams'"
+ " xmlns='jabber:server'"
+ " xmlns:db='jabber:server:dialback'"
+ ">";
log.finest("cid: " + (String)serv.getSessionData().get("cid")
+ ", sending: " + data);
serv.xmppStreamOpen(data);
break;
default:
// Do nothing, more data should come soon...
break;
} // end of switch (service.connectionType())
}
private int countOpenConnections() {
int open_s2s_connections = incoming.size();
for (Map.Entry<String, ServerConnections> entry:
connectionsByLocalRemote.entrySet()) {
ServerConnections conn = entry.getValue();
if (conn.isOutgoingConnected()) {
++open_s2s_connections;
}
}
return open_s2s_connections;
}
public List<StatRecord> getStatistics() {
List<StatRecord> stats = super.getStatistics();
int waiting_packets = 0;
int open_s2s_connections = incoming.size();
int connected_servers = 0;
int server_connections_instances = connectionsByLocalRemote.size();
for (Map.Entry<String, ServerConnections> entry:
connectionsByLocalRemote.entrySet()) {
ServerConnections conn = entry.getValue();
waiting_packets += conn.getWaitingPackets().size();
if (conn.isOutgoingConnected()) {
++open_s2s_connections;
++connected_servers;
}
log.finest("s2s instance: " + entry.getKey()
+ ", waitingQueue: " + conn.getWaitingPackets().size()
+ ", outgoingActive: " + conn.isOutgoingConnected());
}
stats.add(new StatRecord(getName(), "Open s2s connections", "int",
open_s2s_connections, Level.INFO));
stats.add(new StatRecord(getName(), "Packets queued", "int",
waiting_packets, Level.INFO));
stats.add(new StatRecord(getName(), "Connected servers", "int",
connected_servers, Level.FINE));
stats.add(new StatRecord(getName(), "Connection instances", "int",
server_connections_instances, Level.FINER));
return stats;
}
public void serviceStopped(final XMPPIOService serv) {
super.serviceStopped(serv);
switch (serv.connectionType()) {
case connect:
String local_hostname =
(String)serv.getSessionData().get("local-hostname");
String remote_hostname =
(String)serv.getSessionData().get("remote-hostname");
if (remote_hostname == null) {
// There is something wrong...
// It may happen only when remote host connecting to Tigase
// closed connection before it send any db:... packet
// so remote domain is not known.
// Let's do nothing for now.
log.info("remote-hostname is NULL, local-hostname: " + local_hostname
+ ", local address: " + serv.getLocalAddress()
+ ", remote address: " + serv.getRemoteAddress());
} else {
String cid = getConnectionId(local_hostname, remote_hostname);
ServerConnections serv_conns = getServerConnections(cid);
if (serv_conns == null) {
log.warning("There is no ServerConnections for stopped service: "
+ serv.getUniqueId() + ", cid: " + cid);
log.finest("Counters: ioservices: " + countIOServices()
+ ", s2s connections: " + countOpenConnections());
return;
}
serv_conns.serviceStopped(serv);
Queue<Packet> waiting = serv_conns.getWaitingPackets();
if (waiting.size() > 0) {
if (serv_conns.waitingTime() > maxPacketWaitingTime) {
bouncePacketsBack(Authorization.REMOTE_SERVER_TIMEOUT, cid);
} else {
createServerConnection(cid, null, serv_conns);
}
}
}
break;
case accept:
String session_id = (String)serv.getSessionData().get(serv.SESSION_ID_KEY);
if (session_id != null) {
XMPPIOService rem = incoming.remove(session_id);
if (rem == null) {
log.fine("No service with given SESSION_ID: " + session_id);
} else {
log.finer("Connection removed: " + session_id);
}
} else {
log.fine("session_id is null, didn't remove the connection");
}
break;
default:
log.severe("Warning, program shouldn't reach that point.");
break;
} // end of switch (serv.connectionType())
log.finest("Counters: ioservices: " + countIOServices()
+ ", s2s connections: " + countOpenConnections());
}
private void generateStreamError(String error_el, XMPPIOService serv) {
Element error = new Element("stream:error",
new Element[] {
new Element(error_el,
new String[] {"xmlns"},
new String[] {"urn:ietf:params:xml:ns:xmpp-streams"})
}, null, null);
try {
writeRawData(serv, error.toString());
// serv.writeRawData(error.toString());
// serv.writeRawData("</stream:stream>");
serv.stop();
} catch (Exception e) {
serv.forceStop();
}
}
public synchronized void processDialback(Packet packet, XMPPIOService serv) {
log.finest("DIALBACK - " + packet.getStringData());
String local_hostname = JIDUtils.getNodeHost(packet.getElemTo());
// Check whether this is correct local host name...
if (Arrays.binarySearch(hostnames, local_hostname) < 0) {
// Ups, this hostname is not served by this server, return stream
// error and close the connection....
generateStreamError("host-unknown", serv);
return;
}
String remote_hostname = JIDUtils.getNodeHost(packet.getElemFrom());
// And we don't want to accept any connection which is from remote
// host name the same as one my localnames.......
if (Arrays.binarySearch(hostnames, remote_hostname) >= 0) {
// Ups, remote hostname is the same as one of local hostname??
// fake server or what? internal loop, we don't want that....
// error and close the connection....
generateStreamError("host-unknown", serv);
return;
}
String cid = getConnectionId(local_hostname, remote_hostname);
ServerConnections serv_conns = getServerConnections(cid);
String session_id = (String)serv.getSessionData().get(serv.SESSION_ID_KEY);
String serv_local_hostname =
(String)serv.getSessionData().get("local-hostname");
String serv_remote_hostname =
(String)serv.getSessionData().get("remote-hostname");
String serv_cid = serv_remote_hostname == null ? null
: getConnectionId(serv_local_hostname, serv_remote_hostname);
if (serv_cid != null && !cid.equals(serv_cid)) {
log.info("Somebody tries to reuse connection?"
+ " old_cid: " + serv_cid + ", new_cid: " + cid);
}
// <db:result>
if ((packet.getElemName() == RESULT_EL_NAME) ||
(packet.getElemName() == DB_RESULT_EL_NAME)) {
if (packet.getType() == null) {
// This is incoming connection with dialback key for verification
if (packet.getElemCData() != null) {
// db:result with key to validate from accept connection
String db_key = packet.getElemCData();
//initServiceMapping(local_hostname, remote_hostname, accept_jid, serv);
// <db:result> with CDATA containing KEY
Element elem = new Element(DB_VERIFY_EL_NAME, db_key,
new String[] {"id", "to", "from", XMLNS_DB_ATT},
new String[] {session_id, remote_hostname, local_hostname,
XMLNS_DB_VAL});
Packet result = new Packet(elem);
if (serv_conns == null) {
serv_conns = createNewServerConnections(cid, null);
}
//serv_conns.putDBKey(session_id, db_key);
serv.getSessionData().put("remote-hostname", remote_hostname);
serv.getSessionData().put("local-hostname", local_hostname);
log.finest("cid: " + cid + ", sessionId: " + session_id
+ ", Counters: ioservices: " + countIOServices()
+ ", s2s connections: " + countOpenConnections());
if (!serv_conns.sendControlPacket(result)
&& serv_conns.needsConnection()) {
createServerConnection(cid, result, serv_conns);
}
} else {
// Incorrect dialback packet, it happens for some servers....
// I don't know yet what software they use.
// Let's just disconnect and signal unrecoverable conection error
log.finer("Incorrect diablack packet: " + packet.getStringData());
bouncePacketsBack(Authorization.SERVICE_UNAVAILABLE, cid);
generateStreamError("bad-format", serv);
}
} else {
// <db:result> with type 'valid' or 'invalid'
// It means that session has been validated now....
//XMPPIOService connect_serv = handshakingByHost_Type.get(connect_jid);
switch (packet.getType()) {
case valid:
log.finer("Connection: " + cid
+ " is valid, adding to available services.");
serv_conns.handleDialbackSuccess();
break;
default:
log.finer("Connection: " + cid + " is invalid!! Stopping...");
serv_conns.handleDialbackFailure();
break;
} // end of switch (packet.getType())
} // end of if (packet.getType() != null) else
} // end of if (packet != null && packet.getElemName().equals("db:result"))
// <db:verify> with type 'valid' or 'invalid'
if ((packet.getElemName() == VERIFY_EL_NAME)
|| (packet.getElemName() == DB_VERIFY_EL_NAME)) {
if (packet.getElemId() != null) {
String forkey_session_id = packet.getElemId();
if (packet.getType() == null) {
// When type is NULL then it means this packet contains
// data for verification
if (packet.getElemId() != null && packet.getElemCData() != null) {
String db_key = packet.getElemCData();
// This might be the first dialback packet from remote server
// serv.getSessionData().put("remote-hostname", remote_hostname);
// serv.getSessionData().put("local-hostname", local_hostname);
// serv_conns.addIncoming(session_id, serv);
// log.finest("cid: " + cid + ", sessionId: " + session_id
// + ", Counters: ioservices: " + countIOServices()
// + ", s2s connections: " + countOpenConnections());
//initServiceMapping(local_hostname, remote_hostname, accept_jid, serv);
String local_key = getLocalDBKey(cid, db_key, forkey_session_id,
session_id);
if (local_key == null) {
log.fine("db key is not availablefor session ID: " + forkey_session_id
+ ", key for validation: " + db_key);
} else {
log.fine("Local key for cid=" + cid + " is " + local_key);
sendVerifyResult(local_hostname, remote_hostname, forkey_session_id,
db_key.equals(local_key), serv_conns, session_id);
}
} // end of if (packet.getElemName().equals("db:verify"))
} else {
// Type is not null so this is packet with verification result.
// If the type is valid it means accept connection has been
// validated and we can now receive data from this channel.
Element elem = new Element(DB_RESULT_EL_NAME,
new String[] {"type", "to", "from", XMLNS_DB_ATT},
new String[] {packet.getType().toString(),
remote_hostname, local_hostname,
XMLNS_DB_VAL});
sendToIncoming(forkey_session_id, new Packet(elem));
validateIncoming(forkey_session_id,
(packet.getType() == StanzaType.valid));
} // end of if (packet.getType() == null) else
} else {
// Incorrect dialback packet, it happens for some servers....
// I don't know yet what software they use.
// Let's just disconnect and signal unrecoverable conection error
log.finer("Incorrect diablack packet: " + packet.getStringData());
bouncePacketsBack(Authorization.SERVICE_UNAVAILABLE, cid);
generateStreamError("bad-format", serv);
}
} // end of if (packet != null && packet.getType() != null)
}
public boolean sendToIncoming(String session_id, Packet packet) {
XMPPIOService serv = incoming.get(session_id);
if (serv != null) {
log.finest("Sending to incoming connectin: " + session_id
+ " packet: " + packet.toString());
return writePacketToSocket(serv, packet);
} else {
log.finer("Trying to send packet: " + packet.toString()
+ " to nonexisten connection with sessionId: " + session_id);
return false;
}
}
public void validateIncoming(String session_id, boolean valid) {
XMPPIOService serv = incoming.get(session_id);
if (serv != null) {
serv.getSessionData().put("valid", valid);
if (!valid) {
serv.stop();
}
}
}
protected String getLocalDBKey(String cid, String key, String forkey_sessionId,
String asking_sessionId) {
ServerConnections serv_conns = getServerConnections(cid);
return serv_conns == null ? null : serv_conns.getDBKey(forkey_sessionId);
}
protected void sendVerifyResult(String from, String to, String forkey_sessionId,
boolean valid, ServerConnections serv_conns, String asking_sessionId) {
String type = (valid ? "valid" : "invalid");
Element result_el = new Element(DB_VERIFY_EL_NAME,
new String[] {"from", "to", "id", "type", XMLNS_DB_ATT},
new String[] {from, to, forkey_sessionId, type, XMLNS_DB_VAL});
Packet result = new Packet(result_el);
if (!sendToIncoming(asking_sessionId, result)) {
log.warning("Can not send verification packet back: " + result.toString());
}
}
/**
* Method <code>getMaxInactiveTime</code> returns max keep-alive time
* for inactive connection. Let's assume s2s should send something
* at least once every 15 minutes....
*
* @return a <code>long</code> value
*/
protected long getMaxInactiveTime() {
return 15*MINUTE;
}
protected XMPPIOService getXMPPIOServiceInstance() {
return new XMPPIOService();
}
} |
package top.quantic.sentry.config;
import org.quartz.spi.JobFactory;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.FileSystemResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import top.quantic.sentry.config.scheduler.AutowiringSpringBeanJobFactory;
import java.io.IOException;
import java.util.Properties;
@Configuration
@AutoConfigureAfter(DatabaseConfiguration.class)
public class SchedulerConfiguration {
@Bean
public JobFactory jobFactory(ApplicationContext applicationContext) {
AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
jobFactory.setApplicationContext(applicationContext);
return jobFactory;
}
@Bean
public SchedulerFactoryBean schedulerFactory(JobFactory jobFactory) throws IOException {
SchedulerFactoryBean factory = new SchedulerFactoryBean();
factory.setSchedulerName("Sentry");
factory.setJobFactory(jobFactory);
factory.setQuartzProperties(quartzProperties());
// this allows to update triggers in DB when updating settings in config file:
factory.setOverwriteExistingJobs(true);
return factory;
}
@Bean
public Properties quartzProperties() throws IOException {
PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
propertiesFactoryBean.setLocations(new FileSystemResource("quartz.properties"));
propertiesFactoryBean.afterPropertiesSet();
return propertiesFactoryBean.getObject();
}
} |
package wepa.wepa.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
@Configuration
@Profile("production")
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, proxyTargetClass = true)
public class ProductionSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests() |
package org.jetbrains.plugins.scala.lang.parser.util;
import com.intellij.lang.*;
import com.intellij.lang.impl.PsiBuilderAdapter;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.Ref;
import com.intellij.psi.TokenType;
import com.intellij.psi.impl.source.DummyHolderElement;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.TokenSet;
import com.intellij.util.diff.FlyweightCapableTreeStructure;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
/**
* HIGHLY experimental
*
* @author Dmitry Naydanov
*/
public abstract class LayeredParser implements PsiParser {
private static final Logger LOG = Logger.getInstance("#org.jetbrains.plugins.scala.lang.parser.util.LayeredParser");
private static final ASTNode fakeTreeBuilt = new DummyHolderElement("ololo");
private final List<RegisteredInfo<?, ?>> myParsers = new ArrayList<RegisteredInfo<?, ?>>();
private final List<IElementType> mySubRootElements = new ArrayList<IElementType>();
private TokenSet myEofExtendedElements = TokenSet.EMPTY;
private boolean isDebug = false;
private ConflictResolver myResolver = new DefaultConflictResolver();
@NotNull
@Override
public ASTNode parse(IElementType root, @NotNull PsiBuilder builder) {
LayeredParserPsiBuilder delegateBuilder = new LayeredParserPsiBuilder(builder);
if (isDebug) delegateBuilder.setDebugMode(true);
for (RegisteredInfo<?, ?> parserInfo : myParsers) {
if (delegateBuilder.initParser(parserInfo)) {
parserInfo.parse(delegateBuilder);
while (delegateBuilder.isReparseNeeded()) {
delegateBuilder.subInit();
parserInfo.parse(delegateBuilder);
}
}
}
delegateBuilder.copyMarkersWithRoot(root);
return delegateBuilder.getDelegateTreeBuilt();
}
protected void register(RegisteredInfo<?, ?> info) {
myParsers.add(info);
}
protected void setSubRootElements(Collection<IElementType> elements) {
mySubRootElements.addAll(elements);
}
// protected void clearSubRootElements() {
// mySubRootElements.clear();
protected void setEofExtendedElements(IElementType... elements) {
myEofExtendedElements = TokenSet.create(elements);
}
protected void setDebug(boolean isDebug) {
this.isDebug = isDebug;
}
protected void setConflictResolver(ConflictResolver resolver) {
myResolver = resolver;
}
protected void logError(String message) {
LOG.error("[Scala Layered Parser] " + message);
// System.out.println("[Scala Layered Parser] " + message);
}
private class LayeredParserPsiBuilder extends PsiBuilderAdapter {
private final List<BufferedTokenInfo> originalTokens;
private final BufferedTokenInfo fakeEndToken;
private final TreeMap<Integer, Integer> validNumbersLookUp;
private final BitSet usedTokens = new BitSet();
private final IElementType defaultWhitespaceToken;
private ITokenTypeRemapper myRemapper;
private RegisteredInfo<?, ?> myCurrentParser;
private StateFlusher currentStateFlusher;
private List<Integer> filteredTokens;
private TokenSet commentTokens = TokenSet.EMPTY;
private WhitespaceSkippedCallback myWhitespaceSkippedCallback;
private boolean isDebugMode;
private LinkedList<Integer> stateFlushedNums;
private int currentTokenNumber;
private FakeMarker lastMarker;
private BufferedTokenInfo backStepToken;
private int backStepNumber;
LayeredParserPsiBuilder(PsiBuilder delegate) {
this(delegate, TokenType.WHITE_SPACE);
}
LayeredParserPsiBuilder(PsiBuilder delegate, IElementType defaultWhitespaceToken) {
super(delegate);
this.defaultWhitespaceToken = defaultWhitespaceToken;
fakeEndToken = new BufferedTokenInfo(null, false, delegate.getOriginalText().length(), delegate.getOriginalText().length());
//carefully copypasted from PsiBuilderImpl
final int approxLength = Math.max(10, delegate.getOriginalText().length() / 5);
final Ref<Integer> validTokensCountRef = new Ref<Integer>();
validTokensCountRef.set(0);
delegate.setWhitespaceSkippedCallback(new WhitespaceSkippedCallback() {
@Override
public void onSkip(IElementType type, int start, int end) {
int count = validTokensCountRef.get() + 1;
validNumbersLookUp.put(originalTokens.size(), count);
validTokensCountRef.set(count);
originalTokens.add(new BufferedTokenInfo(type, true, start, end));
}
});
originalTokens = new ArrayList<BufferedTokenInfo>(approxLength);
validNumbersLookUp = new TreeMap<Integer, Integer>();
Marker rollbackMarker = delegate.mark();
while (!delegate.eof()) {
originalTokens.add(
new BufferedTokenInfo(delegate.getTokenType(), false, delegate.getCurrentOffset(), -1)
);
delegate.advanceLexer();
}
rollbackMarker.rollbackTo();
}
/**
* Inits current PsiParser
* @return true if parser should be ran
*/
private boolean initParser(RegisteredInfo<?, ?> currentParser) {
backStepToken = null;
myCurrentParser = currentParser;
filteredTokens = new ArrayList<Integer>();
stateFlushedNums = new LinkedList<Integer>();
stateFlushedNums.add(0);
List<Class<? extends IElementType>> currentTokenTypes = currentParser.getMyRegisteredTokens();
currentStateFlusher = currentParser.getMyStateFlusher();
ListIterator<BufferedTokenInfo> it = originalTokens.listIterator();
while (it.hasNext()) {
final BufferedTokenInfo nextInfo = it.next();
final int index = it.nextIndex() - 1;
final IElementType tokenType = nextInfo.getTokenType();
for (Class<? extends IElementType> elementTypeClass : currentTokenTypes) {
currentParser.processNextTokenWithChooser(tokenType);
if ((elementTypeClass.isInstance(tokenType) && !currentParser.mustRejectOwnToken(tokenType) ||
currentParser.mustTakeForeignToken(tokenType)) && !usedTokens.get(index)) {
if (filteredTokens.isEmpty() && nextInfo.isWhitespace()) continue;
filteredTokens.add(index);
usedTokens.set(index);
if (currentStateFlusher.isFlushOnBuilderNeeded(tokenType)) {
stateFlushedNums.add(index);
}
}
}
}
if (filteredTokens.isEmpty()) return false;
subInit();
return true;
}
@Override
public void setTokenTypeRemapper(ITokenTypeRemapper remapper) {
myRemapper = remapper;
}
@Override
public boolean eof() {
if (stateFlushedNums != null && !stateFlushedNums.isEmpty()) {
return stateFlushedNums.peekFirst() <= currentTokenNumber;
}
return filteredTokens == null || currentTokenNumber >= filteredTokens.size();
}
@Override
public void setDebugMode(boolean dbgMode) {
super.setDebugMode(dbgMode);
this.isDebugMode = dbgMode;
}
@Nullable
@Override
public IElementType getTokenType() {
if (eof()) return null;
int num = filteredTokens.get(currentTokenNumber);
BufferedTokenInfo tokenInfo = originalTokens.get(num).isWhitespace() ?
getValidTokenInfo(currentTokenNumber) : originalTokens.get(num);
if (myRemapper != null) {
tokenInfo.setTokenType(myRemapper.filter(tokenInfo.getTokenType(), myDelegate.rawTokenTypeStart(num),
myDelegate.rawTokenTypeStart(num), myDelegate.getOriginalText()));
}
return tokenInfo.getTokenType();
}
@Override
public void advanceLexer() {
if (eof()) return;
BufferedTokenInfo currentValidInfo = getCurrentTokenInfo().isWhitespace() ? getValidTokenInfo(currentTokenNumber)
: getCurrentTokenInfo(); //because of VERY STRANGE behaviour of PsiBuilderImpl
backStepToken = null;
subAdvanceLexer();
BufferedTokenInfo currentToken = getCurrentTokenInfo();
while (!eof() && (commentTokens.contains(currentToken.getTokenType()) || currentToken.isWhitespace()
|| currentToken == currentValidInfo)) {
if (myWhitespaceSkippedCallback != null) {
myWhitespaceSkippedCallback.onSkip(currentToken.getTokenType(), currentToken.getTokenStart(), currentToken.getTokenEnd());
}
subAdvanceLexer();
currentToken = getCurrentTokenInfo();
}
}
@Override
public void remapCurrentToken(IElementType type) {
if (eof()) return;
getCurrentTokenInfo().setTokenType(type);//todo getValidTokenInfo?
}
@Override
public void setWhitespaceSkippedCallback(WhitespaceSkippedCallback callback) {
myWhitespaceSkippedCallback = callback;
}
@Override
public IElementType lookAhead(int steps) {
final int index = getIndexWithStateFlusher(steps + currentTokenNumber);
return eof() || index >= filteredTokens.size() ? null : getValidTokenInfo(index).getTokenType();
}
@Override
public int rawTokenTypeStart(int steps) {
int lookup = getIndexWithStateFlusher(steps + currentTokenNumber);
if (eof() || lookup < 0) return 0;
return getTokenInfoByRelativeNumber(lookup).getTokenStart();
}
@Override
public IElementType rawLookup(int steps) {
int lookup = getIndexWithStateFlusher(steps + currentTokenNumber);
if (eof() || lookup < 0 || lookup >= filteredTokens.size() - 1) return null;
return originalTokens.get(filteredTokens.get(lookup)).getTokenType(); //todo furhter bugs in the parser can be caused by this fix
}
@NotNull
@Override
public ASTNode getTreeBuilt() {
return fakeTreeBuilt;
}
@NotNull
@Override
public FlyweightCapableTreeStructure<LighterASTNode> getLightTree() {
throw new UnsupportedOperationException();//todo
}
@Override
public void enforceCommentTokens(@NotNull TokenSet tokens) {
commentTokens = tokens;
}
@Override
public int getCurrentOffset() {
if (eof()) return getOriginalText().length();
return getCurrentTokenInfo().getTokenStart();//todo getValidTokenInfo?
}
@NotNull
@Override
public Marker mark() {
FakeStartMarker marker = eof() ? new FakeStartMarker(myDelegate.getOriginalText().length(), originalTokens.size())
: new FakeStartMarker(myDelegate.rawTokenTypeStart(filteredTokens.get(currentTokenNumber)), currentTokenNumber);
BufferedTokenInfo info = getCurrentTokenInfo();
(info.isWhitespace() ? getValidTokenInfo(currentTokenNumber) : info).addProductionMarker(marker);
advanceMarker(marker);
return marker;
}
@Override
public void error(String messageText) {
FakeErrorMarker errorMarker = new FakeErrorMarker(messageText);
getCurrentTokenInfo().setMyErrorMarker(errorMarker);//todo getValidTokenInfo?
advanceMarker(errorMarker);
}
@Nullable
@Override
public LighterASTNode getLatestDoneMarker() {
FakeMarker marker = lastMarker;
while (marker != null && !(marker instanceof FakeEndMarker)) {
marker = marker.getPrevMarker();
}
return (FakeEndMarker) marker;
}
@Nullable
@Override
public String getTokenText() {
if (eof()) return null;
int tokenNumber = getCurrentTokenInfo().isWhitespace() ?
getValidTokenNum(currentTokenNumber) : filteredTokens.get(currentTokenNumber);
return getOriginalText().subSequence(myDelegate.rawTokenTypeStart(tokenNumber),
myDelegate.rawTokenTypeStart(tokenNumber + 1)).toString();
}
boolean isReparseNeeded() {
return stateFlushedNums != null && !stateFlushedNums.isEmpty() && currentTokenNumber < stateFlushedNums.getLast();
}
void subInit() {
if (!stateFlushedNums.isEmpty()) currentTokenNumber = stateFlushedNums.pollFirst();
}
ASTNode getDelegateTreeBuilt() {
return myDelegate.getTreeBuilt();
}
void copyMarkersWithRoot(IElementType rootElementType) {
final PsiBuilder.Marker rootMarker = rootElementType != null ? myDelegate.mark() : null;
final List<Pair<Marker, IElementType>> subRootMarkers = mySubRootElements.isEmpty() ?
Collections.<Pair<Marker, IElementType>>emptyList() :
new ArrayList<Pair<Marker, IElementType>>(mySubRootElements.size());
for (IElementType tpe : mySubRootElements) {
subRootMarkers.add(new Pair<Marker, IElementType>(myDelegate.mark(), tpe));
}
final Stack<FakeStartMarker> openMarkers = new Stack<FakeStartMarker>();
myDelegate.setWhitespaceSkippedCallback(null);
for (BufferedTokenInfo info : originalTokens) {
if (info.isWhitespace()) {
if (info.getTokenType() == myDelegate.getTokenType()) {
myDelegate.advanceLexer(); //because of VERY STRANGE behaviour of PsiBuilderImpl
}
continue;
}
List<FakeMarker> productionMarkerList = info.getAllMarkers();
FakeErrorMarker errorMarker = info.getMyErrorMarker();
IElementType probablyRemappedElementType = info.getTokenType();
if (myDelegate.getTokenType() != probablyRemappedElementType && probablyRemappedElementType != null) {
myDelegate.remapCurrentToken(probablyRemappedElementType);
}
if (errorMarker != null) myDelegate.error(errorMarker.getMessage());
if (productionMarkerList != null)
for (FakeMarker productionMarker : productionMarkerList) {
processFakeMarker(productionMarker, openMarkers);
}
myDelegate.advanceLexer();
}
while (!myDelegate.eof()) myDelegate.advanceLexer();
//reference PsiBuilderImpl allows markers after eof, so we must emulate it
if (fakeEndToken.hasMarkers()) {
if (fakeEndToken.getMyErrorMarker() != null) myDelegate.error(fakeEndToken.getMyErrorMarker().getMessage());
List<FakeMarker> eofMarkers = fakeEndToken.getAllMarkers();
if (eofMarkers != null) {
int endIndex = 0;
while (endIndex < eofMarkers.size() && eofMarkers.get(endIndex) instanceof FakeStartMarker) {
++endIndex;
}
if (endIndex > 0) {
Collections.sort(eofMarkers.subList(0, endIndex), new Comparator<FakeMarker>() {
@Override
public int compare(@NotNull FakeMarker o1, @NotNull FakeMarker o2) {
return o2.getStartOffset() - o1.getStartOffset();
}
});
}
for (FakeMarker marker : eofMarkers) processFakeMarker(marker, openMarkers);
}
}
for (ListIterator<Pair<Marker, IElementType>> iterator = subRootMarkers.listIterator(subRootMarkers.size()); iterator.hasPrevious(); ) {
Pair<Marker, IElementType> listElement = iterator.previous();
listElement.getFirst().done(listElement.getSecond());
}
if (rootMarker != null) rootMarker.done(rootElementType);
}
private void processFakeMarker(FakeMarker fakeMarker, Stack<FakeStartMarker> openMarkers) {
if (!fakeMarker.isValid()) return;
if (fakeMarker instanceof FakeStartMarker) {
final Marker marker = myDelegate.mark();
final FakeStartMarker fakeStartMarker = (FakeStartMarker) fakeMarker;
openMarkers.push(fakeStartMarker);
fakeStartMarker.setDelegateMarker(marker);
if (fakeStartMarker.getEndMarker() != null) fakeStartMarker.getEndMarker().setValid(true);
} else if (fakeMarker instanceof FakeEndMarker) {
final FakeEndMarker endMarker = (FakeEndMarker) fakeMarker;
while (!openMarkers.isEmpty() && openMarkers.peek() != endMarker.getStartMarker()) {
FakeStartMarker markerToClose = openMarkers.pop();
FakeEndMarker endMarkerToClose = markerToClose.getEndMarker();
// if (!(endMarkerToClose instanceof FakeEndWithErrorMarker)) {
// logError("Overlapping markers: {" + markerToClose + "; " + markerToClose.getEndMarker() + "} {" +
// endMarker.getStartMarker() + "; " + endMarker + "}");
endMarkerToClose.doneMarker();
setMarkerCustomEdgeBinder(endMarkerToClose);
endMarkerToClose.setValid(false);
}
if (openMarkers.isEmpty()) {
logError("Attempt to .done not added marker: " + endMarker);
endMarker.setValid(false);
return;
}
openMarkers.pop();
endMarker.doneMarker();
setMarkerCustomEdgeBinder(endMarker);
}
}
private void setMarkerCustomEdgeBinder(FakeEndMarker endMarker) {
FakeStartMarker startMarker = endMarker.getStartMarker();
Pair<WhitespacesAndCommentsBinder, WhitespacesAndCommentsBinder> pair = startMarker.getMyCustomEdgeTokenBinders();
if (pair != null && startMarker.getDelegateMarker() != null) {
startMarker.getDelegateMarker().setCustomEdgeTokenBinders(pair.getFirst(), pair.getSecond());
}
}
private BufferedTokenInfo getTokenInfoByRelativeNumber(int index) {
return index < filteredTokens.size() ? originalTokens.get(filteredTokens.get(index)) : fakeEndToken;
}
private BufferedTokenInfo getCurrentTokenInfo() {
return getTokenInfoByRelativeNumber(currentTokenNumber);
}
private IElementType remapAstElement(IElementType oldType) {
return myCurrentParser.getMyElementRemapper().remap(oldType);
}
private int getValidTokenNum(int filteredTokenNumber) {
if (filteredTokenNumber >= filteredTokens.size()) return originalTokens.size();
final int originalNumber = filteredTokens.get(filteredTokenNumber);
final Integer validNumberFloor = validNumbersLookUp.floorKey(originalNumber);
if (validNumberFloor == null || validNumberFloor >= originalTokens.size()) {
return filteredTokens.get(filteredTokenNumber);
}
final int rawNumber = validNumbersLookUp.get(validNumberFloor) + originalNumber - 1;
return rawNumber > originalTokens.size() ? originalTokens.size() : rawNumber;
}
private BufferedTokenInfo getValidTokenInfo(int filteredTokenNumber) {
final int rawNumber = getValidTokenNum(filteredTokenNumber);
return rawNumber == originalTokens.size() ? fakeEndToken : originalTokens.get(rawNumber);
}
private int getIndexWithStateFlusher(int index) {
return stateFlushedNums != null && !stateFlushedNums.isEmpty() ? Math.min(index, stateFlushedNums.peekFirst()) : index;
}
private FakeEndMarker createEndMarker(FakeStartMarker startMarker, @NotNull IElementType astElementType, int endTokenNum,
@Nullable String errorMessage) {
final int originalNum = endTokenNum < filteredTokens.size() ? filteredTokens.get(endTokenNum) : filteredTokens.get(filteredTokens.size() - 1);
final int tokenEndOffset = originalNum >= originalTokens.size() - 2 ? myDelegate.getOriginalText().length()
: getCurrentOffset();
final FakeEndMarker endMarker = errorMessage == null ? new FakeEndMarker(startMarker, astElementType, tokenEndOffset)
: new FakeEndWithErrorMarker(startMarker, astElementType, tokenEndOffset, errorMessage);
startMarker.setEndMarker(endMarker);
return endMarker;
}
private void advanceMarker(FakeMarker marker) {
if (lastMarker == null) {
lastMarker = marker;
return;
}
lastMarker.setNextMarker(marker);
marker.setPrevMarker(lastMarker);
lastMarker = marker;
}
private boolean checkStartMarker(FakeStartMarker marker, String message) {
if (getTokenInfoByRelativeNumber(marker.getMyTokenNum()).getAllMarkers().contains(marker) && marker.isValid()) {
return true;
}
logError(message);
return false;
}
private boolean checkEndMarker(FakeStartMarker markerToBeDone, IElementType astElementType) {
if (astElementType == null || myCurrentParser.isIgnored(astElementType)) {
markerToBeDone.drop();
return false;
}
return true;
}
/**
* Determines if endMarker with particular `.done` type must be "EOF-extended"
*
* @param startOffset element start
* @param astElementType `.done(...)` IElementType
* @return true if must be extended, false otherwise
*/
private boolean checkEofExtendedElement(IElementType astElementType, int startOffset) {
if (getCurrentTokenInfo() != fakeEndToken ||
!myEofExtendedElements.contains(astElementType)) return false;
int startPoint = backStepNumber;
if (backStepToken == null) {
for (int j = filteredTokens.size() - 1; j > 0; --j) {
if (!getTokenInfoByRelativeNumber(j).isWhitespace()) {
startPoint = filteredTokens.get(j);
break;
}
}
}
for (int i = startPoint; i < originalTokens.size(); ++i) {
if (!checkTokenForEof(originalTokens.get(i), startOffset)) return false;
}
return checkTokenForEof(fakeEndToken, startOffset);
}
private boolean checkTokenForEof(BufferedTokenInfo tokenInfo, int startOffset) {
List<FakeMarker> list = tokenInfo.getAllMarkers();
if (list != null) {
for (FakeMarker marker : list) {
if (marker.isValid() && marker instanceof FakeEndMarker && ((FakeEndMarker) marker).getStartMarker().getStartOffset() < startOffset)
return false;
}
}
return true;
}
private boolean checkBackStepMarker(IElementType astDoneElementType) {
return backStepToken != null &&
myResolver.needDoBackStep(backStepToken.getTokenType(), astDoneElementType, getTokenType(), getTokenText());
}
private void subAdvanceLexer() {
int oldOriginalNumber = filteredTokens.get(currentTokenNumber) + 1;
++currentTokenNumber;
if (currentTokenNumber >= filteredTokens.size()) return;
int newOriginalNumber = filteredTokens.get(currentTokenNumber) - 1;
for (int i = oldOriginalNumber; i <= newOriginalNumber; ++i) {
BufferedTokenInfo tokenInfo = originalTokens.get(i);
if (!tokenInfo.isWhitespace() && backStepToken == null) {
backStepToken = tokenInfo;
backStepNumber = i;
}
if (myWhitespaceSkippedCallback != null) {
if (tokenInfo.isWhitespace()) {
myWhitespaceSkippedCallback.onSkip(tokenInfo.getTokenType(), tokenInfo.getTokenStart(),
tokenInfo.getTokenEnd());
} else {
myWhitespaceSkippedCallback.onSkip(defaultWhitespaceToken, tokenInfo.getTokenStart(),
originalTokens.get(i + 1).getTokenStart());
}
}
}
}
private FakeMarker precede(FakeStartMarker startMarker) {
BufferedTokenInfo tokenInfo = getTokenInfoByRelativeNumber(startMarker.getMyTokenNum());
FakeStartMarker newMarker = new FakeStartMarker(tokenInfo.getTokenStart(), startMarker.getMyTokenNum());
tokenInfo.addProductionMarkerBefore(newMarker, startMarker);
insertMarkerBefore(newMarker, startMarker);
return newMarker;
}
private void rollbackTo(FakeStartMarker marker) {
lastMarker = marker.getPrevMarker();
for (int i = marker.getMyTokenNum(); i <= currentTokenNumber; ++i) { //todo change errors to regular markers and delete this
getTokenInfoByRelativeNumber(i).setMyErrorMarker(null);
}
currentTokenNumber = marker.getMyTokenNum();
FakeMarker current = marker;
while (current != null) {
current.setValid(false);
current = current.getNextMarker();
}
}
private void done(FakeMarker marker, IElementType astElementType, @Nullable String errorMessage) {
astElementType = remapAstElement(astElementType);
final FakeStartMarker fakeStartMarker = (FakeStartMarker) marker;
if (!checkEndMarker(fakeStartMarker, astElementType)) {
return;
}
final FakeEndMarker endMarker = createEndMarker(fakeStartMarker, astElementType, currentTokenNumber, errorMessage);
BufferedTokenInfo currentTokenInfo = getCurrentTokenInfo().isWhitespace() ?
getValidTokenInfo(currentTokenNumber) : getCurrentTokenInfo();
advanceMarker(endMarker);
if (currentTokenInfo == fakeEndToken && checkEofExtendedElement(astElementType, fakeStartMarker.getStartOffset())) {
fakeEndToken.addProductionMarker(endMarker);
return;
}
if (backStepToken != null && fakeStartMarker.getStartOffset() < backStepToken.getTokenStart() /*&&
!(currentTokenInfo == fakeEndToken && myEofExtendedElements.contains(astElementType))*/ && checkBackStepMarker(astElementType)) {
backStepToken.addForeignProductionMarker(endMarker);
endMarker.setEndOffset(backStepToken.getTokenStart());
return;
}
if (currentTokenInfo == fakeEndToken && filteredTokens.get(filteredTokens.size() - 1) < originalTokens.size() - 1 &&
fakeStartMarker.getStartOffset() != fakeEndToken.getTokenStart()) {
int lastNonWsIndex = filteredTokens.size() - 1;//ugly, rewrite
while (getTokenInfoByRelativeNumber(lastNonWsIndex).isWhitespace() &&
fakeStartMarker.getStartOffset() < getTokenInfoByRelativeNumber(lastNonWsIndex).getTokenStart()) {
--lastNonWsIndex;
}
int newEofTokenIndex = filteredTokens.get(lastNonWsIndex) + 1;
while (newEofTokenIndex < originalTokens.size()) {
if (!originalTokens.get(newEofTokenIndex).isWhitespace()) {
backStepToken = originalTokens.get(newEofTokenIndex);
backStepNumber = newEofTokenIndex;
backStepToken.addForeignProductionMarker(endMarker);
return;
}
++newEofTokenIndex;
}
}
currentTokenInfo.addProductionMarker(endMarker);
}
private void collapse(FakeMarker marker, IElementType astElementType) {
FakeStartMarker startMarker = (FakeStartMarker) marker;
if (!checkStartMarker(startMarker, "Attempt to .collapse() invalid marker")) return;
while (lastMarker != null && lastMarker != marker) {
lastMarker.setValid(false);
lastMarker = lastMarker.getPrevMarker();
}
done(marker, astElementType, null);
}
private void doneOrErrorBefore(IElementType astElementType, FakeStartMarker doneMarker, FakeStartMarker beforeMarker,
@Nullable String errorMessage) {
astElementType = remapAstElement(astElementType);
if (!checkEndMarker(doneMarker, astElementType)) return;
if (!checkStartMarker(beforeMarker, "Attempt to .doneBefore() on invalid before-marker")) return;
if (!checkStartMarker(doneMarker, "Attempt to .doneBefore() on invalid marker")) return;
int beforeTokenNum = beforeMarker.getMyTokenNum();
if (doneMarker.getMyTokenNum() > beforeTokenNum) {
logError("Attempt to done next marker before previous marker");
return;
}
if (beforeMarker.getMyTokenNum() > 0) {
for (int i = filteredTokens.get(beforeTokenNum - 1) + 1; i < filteredTokens.get(beforeTokenNum); ++i) {
if (!originalTokens.get(i).isWhitespace()) {
beforeTokenNum = i;
break;
}
}
}
FakeEndMarker endMarker = createEndMarker(doneMarker, astElementType, beforeTokenNum, errorMessage);
insertMarkerBefore(endMarker, beforeMarker);
final List<FakeMarker> allMarkers = getTokenInfoByRelativeNumber(beforeMarker.getMyTokenNum()).getAllMarkers();
if (beforeTokenNum == beforeMarker.getMyTokenNum() || (allMarkers != null && allMarkers.get(0) != beforeMarker)) {
getTokenInfoByRelativeNumber(beforeTokenNum).addProductionMarker(endMarker);
return;
}
originalTokens.get(beforeTokenNum).addForeignProductionMarker(endMarker);
}
private void doneBefore(IElementType astElementType, FakeStartMarker doneMarker, FakeStartMarker beforeMarker,
String errorMessage) {
doneOrErrorBefore(astElementType, doneMarker, beforeMarker, null);
final FakeErrorMarker errorMarker = new FakeErrorMarker(errorMessage);
getValidTokenInfo(beforeMarker.getMyTokenNum() - 1).setMyErrorMarker(errorMarker);
insertMarkerBefore(errorMarker, beforeMarker.getPrevMarker());
}
private void doneWithError(FakeStartMarker marker, String errorMessage) {
done(marker, TokenType.ERROR_ELEMENT, errorMessage);
}
private void errorBefore(FakeStartMarker marker, FakeStartMarker beforeMarker, String errorMessage) {
doneOrErrorBefore(TokenType.ERROR_ELEMENT, marker, beforeMarker, errorMessage);
}
@SuppressWarnings("UnusedDeclaration")
private abstract class FakeMarker implements PsiBuilder.Marker {
private FakeMarker prevMarker;
private FakeMarker nextMarker;
private boolean isValid = true;
private StackTraceElement[] placeOfCreation;
FakeMarker() {
if (LayeredParserPsiBuilder.this.isDebugMode) {
setPlace(new Exception().getStackTrace());
}
}
public void drop() {
throw new UnsupportedOperationException();
}
@NotNull
public PsiBuilder.Marker precede() {
throw new UnsupportedOperationException();
}
public void rollbackTo() {
throw new UnsupportedOperationException();
}
public void done(@NotNull IElementType type) {
throw new UnsupportedOperationException();
}
public void collapse(@NotNull IElementType type) {
throw new UnsupportedOperationException();
}
public void doneBefore(@NotNull IElementType type, @NotNull Marker before) {
throw new UnsupportedOperationException();
}
public void doneBefore(@NotNull IElementType type, @NotNull PsiBuilder.Marker before, String errorMessage) {
throw new UnsupportedOperationException();
}
public void error(String message) {
throw new UnsupportedOperationException();
}
public void errorBefore(String message, @NotNull PsiBuilder.Marker before) {
throw new UnsupportedOperationException();
}
public int getStartOffset() {
throw new UnsupportedOperationException();
}
public void setCustomEdgeTokenBinders(@Nullable WhitespacesAndCommentsBinder left,
@Nullable WhitespacesAndCommentsBinder right) {
throw new UnsupportedOperationException();
}
FakeMarker getPrevMarker() {
return prevMarker;
}
void setPrevMarker(FakeMarker prevMarker) {
this.prevMarker = prevMarker;
}
FakeMarker getNextMarker() {
return nextMarker;
}
void setNextMarker(FakeMarker nextMarker) {
this.nextMarker = nextMarker;
}
public boolean isValid() {
return isValid;
}
public void setValid(boolean valid) {
isValid = valid;
}
public void setPlace(StackTraceElement[] place) {
placeOfCreation = place;
}
}
private class FakeStartMarker extends FakeMarker {
private final int myStart;
private final int myTokenNum;
private FakeEndMarker endMarker;
private Marker delegateMarker;
private Pair<WhitespacesAndCommentsBinder, WhitespacesAndCommentsBinder> myCustomEdgeTokenBinders;
private StackTraceElement[] createdAt;
private FakeStartMarker(int myStart, int myTokenNum) {
if (isDebug) {
createdAt = new Exception().getStackTrace();
}
this.myStart = myStart;
this.myTokenNum = myTokenNum;
}
public StackTraceElement[] getCreatedAt() {
return createdAt;
}
public int getStartOffset() {
return myStart;
}
int getMyTokenNum() {
return myTokenNum;
}
@Override
public void drop() {
setValid(false);
}
@Override
public void rollbackTo() {
LayeredParserPsiBuilder.this.rollbackTo(this);
}
@NotNull
@Override
public Marker precede() {
return LayeredParserPsiBuilder.this.precede(this);
}
@Override
public void done(@NotNull IElementType type) {
LayeredParserPsiBuilder.this.done(this, type, null);
}
@Override
public void collapse(@NotNull IElementType type) {
LayeredParserPsiBuilder.this.collapse(this, type);
}
@Override
public void doneBefore(@NotNull IElementType type, @NotNull Marker before) {
LayeredParserPsiBuilder.this.doneOrErrorBefore(type, this, (FakeStartMarker) before, null);
}
@Override
public void doneBefore(@NotNull IElementType type, @NotNull Marker before, String errorMessage) {
LayeredParserPsiBuilder.this.doneBefore(type, this, (FakeStartMarker) before, errorMessage);
}
@Override
public void error(String message) {
LayeredParserPsiBuilder.this.doneWithError(this, message);
}
@Override
public void errorBefore(String message, @NotNull Marker before) {
LayeredParserPsiBuilder.this.errorBefore(this, (FakeStartMarker) before, message);
}
Marker getDelegateMarker() {
return delegateMarker;
}
void setDelegateMarker(Marker delegateMarker) {
this.delegateMarker = delegateMarker;
}
Pair<WhitespacesAndCommentsBinder, WhitespacesAndCommentsBinder> getMyCustomEdgeTokenBinders() {
return myCustomEdgeTokenBinders;
}
@Override
public void setCustomEdgeTokenBinders(@Nullable WhitespacesAndCommentsBinder left, @Nullable WhitespacesAndCommentsBinder right) {
myCustomEdgeTokenBinders = new Pair<WhitespacesAndCommentsBinder, WhitespacesAndCommentsBinder>(left, right);
}
@Override
public String toString() {
return "FakeStartMarker [TextOffset: " + getStartOffset() + " ; TokenNumber: " + getMyTokenNum() + " ; MyDelegate: " + delegateMarker + "]";
}
public FakeEndMarker getEndMarker() {
return endMarker;
}
public void setEndMarker(FakeEndMarker endMarker) {
this.endMarker = endMarker;
}
}
private class FakeEndMarker extends FakeMarker implements LighterASTNode {
private FakeStartMarker startMarker;
private final IElementType astElementType;
private int endOffset;
private FakeEndMarker(FakeStartMarker startMarker, IElementType astElementType, int endOffset) {
this.startMarker = startMarker;
this.astElementType = astElementType;
this.endOffset = endOffset;
}
@Override
public IElementType getTokenType() {
return astElementType;
}
@Override
public int getStartOffset() {
return getStartMarker().getStartOffset();
}
@Override
public int getEndOffset() {
return endOffset;
}
public FakeStartMarker getStartMarker() {
return startMarker;
}
public void setEndOffset(int endOffset) {
this.endOffset = endOffset;
}
public void doneMarker() {
if (!checkOnDone()) return;
getStartMarker().getDelegateMarker().done(getTokenType());
}
@Override
public String toString() {
return "FakeEndMarker [TextStartOffset: " + getStartOffset() + " ; TextEndOffset: " + getEndOffset() +
" ; IElementType: " + getTokenType() + "]";
}
boolean checkOnDone() {
if (getStartMarker().getDelegateMarker() == null) {
logError("Attempt to .done marker" + toString() + " before .copyWithRoot");
return false;
}
return true;
}
}
private class FakeErrorMarker extends FakeMarker {
private final String message;
private FakeErrorMarker(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
private class FakeEndWithErrorMarker extends FakeEndMarker {
private final String errorMessage;
private FakeEndWithErrorMarker(FakeStartMarker startMarker, IElementType astElementType, int endOffset,
String errorMessage) {
super(startMarker, astElementType, endOffset);
this.errorMessage = errorMessage;
}
public String getErrorMessage() {
return errorMessage;
}
@Override
public void doneMarker() {
if (!checkOnDone()) return;
getStartMarker().getDelegateMarker().error(getErrorMessage());
}
}
}
public interface ContentsParser {
void parseContents(ASTNode chameleon, PsiBuilder builder);
}
/**
* Can be stateful
*/
public interface CustomTokenChooser {
/**
* Processes the next token type. This token type will be then passed to
* {@link CustomTokenChooser#shouldSelectForeignToken(com.intellij.psi.tree.IElementType)}
*/
void processToken(IElementType tokenType);
/**
* Don't put your filtering logic in these methods as it won't be called if tokenType is already of a
* suitable class or already rejected.
*/
boolean shouldSelectForeignToken(IElementType tokenType);
boolean shouldRejectOwnToken(IElementType tokenType);
}
public interface ConflictResolver {
boolean needDoBackStep(IElementType backStepTokenType, IElementType astDoneElementType,
IElementType currentElementType, CharSequence tokenText);
}
private class DefaultConflictResolver implements ConflictResolver {
public boolean needDoBackStep(IElementType backStepTokenType, IElementType astDoneElementType,
IElementType currentElementType, CharSequence tokenText) {
return !("}".equals(tokenText) || ">".equals(tokenText) || "]".equals(tokenText) || ")".equals(tokenText));
}
}
public abstract class RegisteredInfo<E, T> {
protected final E myParser;
final List<Class<? extends IElementType>> myRegisteredTokens;
final StateFlusher myStateFlusher;
private final AstElementRemapper myElementRemapper;
final T myReferenceElement;
final TokenSet myIgnoredTokens;
CustomTokenChooser myTokenChooser;
RegisteredInfo(@NotNull E myParser, @NotNull List<Class<? extends IElementType>> myRegisteredTokens,
@Nullable StateFlusher myStateFlusher, @Nullable T myReferenceElement,
@Nullable TokenSet myIgnoredTokens, @Nullable AstElementRemapper elementRemapper) {
this.myParser = myParser;
this.myRegisteredTokens = myRegisteredTokens;
this.myStateFlusher = myStateFlusher == null? new NullStateFlusher() : myStateFlusher;
this.myIgnoredTokens = myIgnoredTokens == null? TokenSet.EMPTY : myIgnoredTokens;
this.myReferenceElement = myReferenceElement;
this.myElementRemapper = elementRemapper == null? new NullAstElementRemapper() : elementRemapper;
}
public E getMyParser() {
return myParser;
}
List<Class<? extends IElementType>> getMyRegisteredTokens() {
return myRegisteredTokens;
}
StateFlusher getMyStateFlusher() {
return myStateFlusher;
}
T getMyReferenceElement() {
return myReferenceElement;
}
public boolean isIgnored(IElementType elementType) {
return myIgnoredTokens.contains(elementType);
}
AstElementRemapper getMyElementRemapper() {
return myElementRemapper;
}
public RegisteredInfo<E, T> setTokenChooser(CustomTokenChooser myTokenChooser) {
this.myTokenChooser = myTokenChooser;
return this;
}
boolean mustTakeForeignToken(IElementType tokenType) {
return myTokenChooser != null && myTokenChooser.shouldSelectForeignToken(tokenType);
}
boolean mustRejectOwnToken(IElementType tokenType) {
return myTokenChooser != null && myTokenChooser.shouldRejectOwnToken(tokenType);
}
void processNextTokenWithChooser(IElementType tokenType) {
if (myTokenChooser != null) myTokenChooser.processToken(tokenType);
}
abstract void parse(@NotNull PsiBuilder builder);
}
public class RegisteredParserInfo extends RegisteredInfo<PsiParser, IElementType> {
public RegisteredParserInfo(PsiParser myParser, List<Class<? extends IElementType>> myRegisteredTokens,
StateFlusher myStateFlusher, IElementType myReferenceElement,
TokenSet myIgnoredTokens, AstElementRemapper remapper) {
super(myParser, myRegisteredTokens, myStateFlusher, myReferenceElement, myIgnoredTokens, remapper);
}
@Override
void parse(@NotNull PsiBuilder builder) {
getMyParser().parse(getMyReferenceElement(), builder);
}
}
public class RegisteredContentsParserInfo extends RegisteredInfo<ContentsParser, ASTNode> {
public RegisteredContentsParserInfo(ContentsParser myParser, List<Class<? extends IElementType>> myRegisteredTokens,
StateFlusher myStateFlusher, ASTNode myReferenceElement,
TokenSet myIgnoredTokens, AstElementRemapper remapper) {
super(myParser, myRegisteredTokens, myStateFlusher, myReferenceElement, myIgnoredTokens, remapper);
}
@Override
void parse(@NotNull PsiBuilder builder) {
getMyParser().parseContents(getMyReferenceElement(), builder);
}
}
interface StateFlusher {
boolean isFlushOnBuilderNeeded(IElementType currentTokenType);
}
public interface AstElementRemapper {
IElementType remap(IElementType astElementType);
}
private class NullStateFlusher implements StateFlusher {
public boolean isFlushOnBuilderNeeded(IElementType currentTokenType) {
return false;
}
}
private class NullAstElementRemapper implements AstElementRemapper {
@Override
public final IElementType remap(IElementType astElementType) {
return astElementType;
}
}
private class BufferedTokenInfo {
private IElementType tokenType;
private final int tokenEnd;
private final boolean isWhitespace;
private final int tokenStart;
private int foreignMarkerEdge;
private LinkedList<LayeredParserPsiBuilder.FakeMarker> myProductionMarkerList;
private LayeredParserPsiBuilder.FakeErrorMarker myErrorMarker;
private BufferedTokenInfo(IElementType tokenType, boolean whitespace, int tokenStart, int tokenEnd) {
this.tokenType = tokenType;
this.tokenEnd = tokenEnd;
isWhitespace = whitespace;
this.tokenStart = tokenStart;
foreignMarkerEdge = 0;
}
public IElementType getTokenType() {
return tokenType;
}
public void setTokenType(@NotNull IElementType newTokenType) {
tokenType = newTokenType;
}
public int getTokenEnd() {
return tokenEnd;
}
public boolean isWhitespace() {
return isWhitespace;
}
public int getTokenStart() {
return tokenStart;
}
void addForeignProductionMarker(LayeredParserPsiBuilder.FakeMarker productionMarker) {
ensureProduction();
// if (foreignMarkerEdge < myProductionMarkerList.size()) {
// insertMarkerBefore(productionMarker, myProductionMarkerList.get(foreignMarkerEdge));
myProductionMarkerList.add(foreignMarkerEdge++, productionMarker);
}
void addProductionMarker(LayeredParserPsiBuilder.FakeMarker productionMarker) {
ensureProduction();
myProductionMarkerList.add(productionMarker);
}
void addProductionMarkerBefore(LayeredParserPsiBuilder.FakeMarker markerToAdd, LayeredParserPsiBuilder.FakeMarker before) {
ensureProduction();
int indx = myProductionMarkerList.lastIndexOf(before);
if (indx == -1) {
logError("Attempt to .addBefore missing marker:\n " +
"marker to add: " + markerToAdd + "\n" +
"before marker: " + before);
myProductionMarkerList.add(markerToAdd);
return;
}
myProductionMarkerList.add(indx, markerToAdd);
}
List<LayeredParserPsiBuilder.FakeMarker> getAllMarkers() {
return myProductionMarkerList;
}
LayeredParserPsiBuilder.FakeErrorMarker getMyErrorMarker() {
return myErrorMarker;
}
void setMyErrorMarker(LayeredParserPsiBuilder.FakeErrorMarker myErrorMarker) {
this.myErrorMarker = myErrorMarker;
}
boolean hasMarkers() {
if (getMyErrorMarker() != null) return true;
if (getAllMarkers() == null) return false;
for (LayeredParserPsiBuilder.FakeMarker marker : getAllMarkers()) {
if (marker.isValid()) return true;
}
return false;
}
private void ensureProduction() {
if (myProductionMarkerList == null) myProductionMarkerList = new LinkedList<LayeredParserPsiBuilder.FakeMarker>();
}
}
private void insertMarkerBefore(LayeredParserPsiBuilder.FakeMarker markerToInsert,
LayeredParserPsiBuilder.FakeMarker beforeMarker) {
markerToInsert.setNextMarker(beforeMarker);
markerToInsert.setPrevMarker(beforeMarker.getPrevMarker());
if (beforeMarker.getPrevMarker() != null) beforeMarker.getPrevMarker().setNextMarker(markerToInsert);
beforeMarker.setPrevMarker(markerToInsert);
}
} |
package org.jitsi.impl.androidresources;
import android.content.*;
import android.content.res.*;
import android.util.*;
import android.view.*;
import net.java.sip.communicator.service.resources.*;
import net.java.sip.communicator.util.*;
import org.jitsi.service.osgi.*;
import org.osgi.framework.*;
import java.io.*;
import java.net.*;
import java.util.*;
/**
* An Android implementation of the
* {@link org.jitsi.service.resources.ResourceManagementService}.<br/>
* <br/>
* Strings - requests are redirected to the strings defined in "strings.xml"
* file, but in case the string is not found it will try to look for strings
* defined in default string resources.<br/>
* <br/>
* Dots in keys are replaced with "_", as they can not be used for string
* names in "strings.xml". For exmaple the string for key "service.gui.CLOSE"
* should be declared as:<br/>
* <string name="service_gui_CLOSE">Close</string> <br/>
* <br/>
* Requests for other locales are redirected to
* corresponding folders as it's defined in Android localization mechanism.<br/>
* <br/>
* Colors - mapped directly to those defined in /res/values/colors.xml<br/>
* <br/>
* Sounds - are stored in res/raw folder. The mappings are read from
* the sounds.properties or other SoundPack's provided. Properties should point
* to sound file names without the extension. For example:<br/>
* BUSY=busy (points to /res/raw/busy.wav)<br/>
* <br/>
* Images - images work the same as sounds except they are stored in drawable
* folders.<br/>
* <br/>
* For parts of Jitsi source that directly refere to image paths it will map
* the requests to the drawable Android application resource names, so that we
* can take advantage of built-in image size resolving mechanism. The mapping
* must be specified in file {@link #IMAGE_PATH_RESOURCE}.properties.
* <br/>
* Sample entries:<br/>
* resources/images/protocol/sip/sip16x16.png=sip_logo<br/>
* resources/images/protocol/sip/sip32x32.png=sip_logo<br/>
* resources/images/protocol/sip/sip48x48.png=sip_logo<br/>
* resources/images/protocol/sip/sip64x64.png=sip_logo<br/>
* <br/>
*
* @author Pawel Domas
*/
public class AndroidResourceServiceImpl
extends AbstractResourcesService
{
/**
* The <tt>Logger</tt> used by the <tt>AndroidResourceServiceImpl</tt>
* class and its instances for logging output.
*/
private static final Logger logger
= Logger.getLogger(AndroidResourceServiceImpl.class);
/**
* Path to the .properties file containing image path's
* translations to android drawable resources
*/
private static final String IMAGE_PATH_RESOURCE
= "resources.images.image_path";
/**
* Android image path translation resource
* TODO: Remove direct path requests for resources
*/
private ResourceBundle androidImagePathPack = null;
/**
* The {@link Resources} object for application context
*/
private static Resources resources = null;
/**
* The application package name(org.jitsi)
*/
private String packageName = null;
/**
* The Android application context
*/
private Context androidContext = null;
/**
* The {@link Resources} cache for language other than default
*/
private Resources cachedLocaleResources = null;
/**
* The {@link Locale} of cached locale resources
*/
private Locale cachedResLocale = null;
private static boolean factorySet = false;
/**
* Initializes already registered default resource packs.
*/
AndroidResourceServiceImpl()
{
super(AndroidResourceManagementActivator.bundleContext);
androidImagePathPack = ResourceBundle.getBundle(IMAGE_PATH_RESOURCE);
logger.trace("Loaded image path resource: " + androidImagePathPack);
BundleContext bundleContext =
AndroidResourceManagementActivator.bundleContext;
ServiceReference<OSGiService> serviceRef =
bundleContext.getServiceReference(OSGiService.class);
OSGiService osgiService = bundleContext.getService(serviceRef);
resources = osgiService.getResources();
packageName = osgiService.getPackageName();
androidContext = osgiService.getApplicationContext();
if(!factorySet)
{
URL.setURLStreamHandlerFactory(
new AndroidResourceURLHandlerFactory());
factorySet = true;
}
}
@Override
protected void onSkinPackChanged()
{
// Not interested (at least for now)
}
/**
* Gets the resource ID for given color <tt>strKey</tt>.
*
* @param strKey the color text identifier that has to be resolved
*
* @return the resource ID for given color <tt>strKey</tt>
*/
private int getColorId(String strKey)
{
return getResourceId("color", strKey);
}
/**
* Returns the int representation of the color corresponding to the
* given key.
*
* @param key The key of the color in the colors properties file.
* @return the int representation of the color corresponding to the
* given key.
*/
public int getColor(String key)
{
int id = getColorId(key);
if(id == 0)
{
return 0xFFFFFFFF;
}
return resources.getColor(id);
}
/**
* Returns the string representation of the color corresponding to the
* given key.
*
* @param key The key of the color in the colors properties file.
* @return the string representation of the color corresponding to the
* given key.
*/
public String getColorString(String key)
{
int id = getColorId(key);
if(id == 0)
{
return "0xFFFFFFFF";
}
return resources.getString(id);
}
/**
* Returns a drawable resource id for given name.
*
* @param key the name of drawable
*/
private int getDrawableId(String key)
{
return getResourceId("drawable", key);
}
/**
* Returns the resource id for the given name of specified type.
*
* @param typeName the type name (color, drawable, raw, string ...)
* @param key the resource name
*
* @return the resource id for the given name of specified type
*/
private int getResourceId(String typeName, String key)
{
int id = resources.getIdentifier(key, typeName, packageName);
if(id == 0)
logger.error("Unresolved "+typeName+" key: "+key);
return id;
}
/**
* Returns the <tt>InputStream</tt> of the image corresponding to the given
* path.
*
* @param path The path to the image file.
* @return the <tt>InputStream</tt> of the image corresponding to the given
* path.
*/
public InputStream getImageInputStreamForPath(String path)
{
if(logger.isTraceEnabled())
logger.trace("Request for resource path: " + path);
if(androidImagePathPack.containsKey(path))
{
String translatedPath = androidImagePathPack.getString(path);
if(logger.isTraceEnabled())
logger.trace("Translated path: " + translatedPath);
if(translatedPath != null)
{
return getImageInputStream(translatedPath);
}
}
return null;
}
/**
* Returns the <tt>InputStream</tt> of the image corresponding to the given
* key.
*
* @param key The identifier of the image in the resource properties
* file.
* @return the <tt>InputStream</tt> of the image corresponding to the given
* key.
*/
public InputStream getImageInputStream(String key)
{
// Try to lookup images.properties for key mapping
String resolvedPath = super.getImagePath(key);
if(resolvedPath != null)
{
key = resolvedPath;
}
int id = getDrawableId(key);
if(id != 0)
{
return resources.openRawResource(id);
}
return null;
}
/**
* Returns the <tt>URL</tt> of the image corresponding to the given key.
*
* @param key The identifier of the image in the resource properties file.
* @return the <tt>URL</tt> of the image corresponding to the given key
*/
public URL getImageURL(String key)
{
return getImageURLForPath(getImagePath(key));
}
/**
* Returns the <tt>URL</tt> of the image corresponding to the given path.
*
* @param path The path to the given image file.
* @return the <tt>URL</tt> of the image corresponding to the given path.
*/
public URL getImageURLForPath(String path)
{
if(path == null)
return null;
try
{
return new URL(path);
}
catch (MalformedURLException e)
{
throw new RuntimeException(e);
}
}
/**
* Returns the image path corresponding to the given key.
*
* @param key The identifier of the image in the resource properties file.
* @return the image path corresponding to the given key.
*/
public String getImagePath(String key)
{
String reference = super.getImagePath(key);
if(reference == null)
{
// If no mapping found use key directly
reference = key;
}
int id = getDrawableId(reference);
if(id == 0)
return null;
return AndroidResourceURLHandlerFactory.PROTOCOL + ":
}
/**
* Returns the string resource id for given <tt>key</tt>.
*
* @param key the name of string resource as defined in "strings.xml"
* @return the string value for given <tt>key</tt>
*/
private int getStringId(String key)
{
return getResourceId("string", key);
}
@Override
protected String doGetI18String(String key, Locale locale)
{
Resources usedRes = resources;
Locale resourcesLocale = usedRes.getConfiguration().locale;
if(locale != null && !locale.equals(resourcesLocale))
{
if(!locale.equals(cachedResLocale))
{
// Create the Resources object for recently requested locale
// and caches it in case another request may come up
Configuration conf = resources.getConfiguration();
conf.locale = locale;
AssetManager assets = androidContext.getAssets();
DisplayMetrics metrics = new DisplayMetrics();
WindowManager wm = (WindowManager) androidContext
.getSystemService(Context.WINDOW_SERVICE);
wm.getDefaultDisplay().getMetrics(metrics);
cachedLocaleResources = new Resources(assets, metrics, conf);
cachedResLocale = locale;
}
usedRes = cachedLocaleResources;
}
/**
* Does replace the "." with "_" as they do not work in strings.xml,
* they are replaced anyway during the resources generation process
*/
int id = getStringId(key.replace(".", "_"));
if (id == 0)
{
// If not found tries to get from resources.properties
return super.doGetI18String(key, locale);
}
return usedRes.getString(id);
}
/**
* The sound resource identifier. Sounds are stored in res/raw folder.
*
* @param key the name of sound, for busy.wav it will be just busy
* @return the sound resource id for given <tt>key</tt>
*/
private int getSoundId(String key)
{
return getResourceId("raw", key);
}
/**
* Returns the <tt>URL</tt> of the sound corresponding to the given
* property key.
*
* @param key the key string
* @return the <tt>URL</tt> of the sound corresponding to the given
* property key.
*/
public URL getSoundURL(String key)
{
try
{
String path = getSoundPath(key);
if(path == null)
return null;
return new URL(path);
}
catch (MalformedURLException e)
{
throw new RuntimeException(e);
}
}
/**
* Returns the <tt>URL</tt> of the sound corresponding to the given path.
*
* @param path the path, for which we're looking for a sound URL
* @return the <tt>URL</tt> of the sound corresponding to the given path.
*/
public URL getSoundURLForPath(String path)
{
return getSoundURL(path);
}
/**
* Returns the path for given <tt>soundKey</tt>. It's formatted with
* protocol name in the URI format.
*
* @param soundKey the key, for the sound path
*/
@Override
public String getSoundPath(String soundKey)
{
String reference = super.getSoundPath(soundKey);
if(reference == null)
{
// If there's no definition in .properties
// try to access directly by the name
reference = soundKey;
}
int id = getSoundId(reference);
if(id == 0)
{
logger.error("No sound defined for: "+soundKey);
return null;
}
return AndroidResourceURLHandlerFactory.PROTOCOL + ":
}
/**
* Not supported at the moment.
*
* @param file the zip file from which we prepare a skin
* @return the prepared file
* @throws Exception
*/
public File prepareSkinBundleFromZip(File file)
throws Exception
{
throw new UnsupportedOperationException();
}
/**
* Some kind of hack to be able to produce URLs pointing to Android
* resources. It allows to produce URL with protocol name of
* {@link #PROTOCOL} that will be later handled by this factory.
*/
static private class AndroidResourceURLHandlerFactory
implements URLStreamHandlerFactory
{
public static final String PROTOCOL = "jitsi.resource";
public URLStreamHandler createURLStreamHandler(String s)
{
if(s.equals(PROTOCOL))
{
return new AndroidResourceURlHandler();
}
return null;
}
}
/**
* The URL handler that handles Android resource paths redirected to Android
* resources.
*/
static private class AndroidResourceURlHandler
extends URLStreamHandler
{
@Override
protected URLConnection openConnection(URL url)
throws IOException
{
return new AndroidURLConnection(url);
}
}
/**
* It does open {@link InputStream} from URLs that were produced for
* {@link AndroidResourceURLHandlerFactory#PROTOCOL} protocol.
*/
static private class AndroidURLConnection
extends URLConnection
{
private int id = 0;
protected AndroidURLConnection(URL url)
{
super(url);
}
@Override
public void connect()
throws IOException
{
}
@Override
public InputStream getInputStream()
throws IOException
{
String idStr = super.getURL().getHost();
try
{
this.id = Integer.parseInt(idStr);
return resources.openRawResource(id);
}
catch(NumberFormatException exc)
{
throw new IOException("Invalid resource id: "+idStr);
}
}
}
} |
package org.pentaho.agilebi.modeler.propforms;
import org.pentaho.agilebi.modeler.ModelerMessagesHolder;
import org.pentaho.agilebi.modeler.ModelerWorkspace;
import org.pentaho.agilebi.modeler.nodes.DataRole;
import org.pentaho.agilebi.modeler.nodes.TimeRole;
import org.pentaho.agilebi.modeler.geo.GeoContext;
import org.pentaho.agilebi.modeler.geo.GeoRole;
import org.pentaho.agilebi.modeler.nodes.BaseColumnBackedMetaData;
import org.pentaho.agilebi.modeler.nodes.LevelMetaData;
import org.pentaho.agilebi.modeler.nodes.HierarchyMetaData;
import org.pentaho.agilebi.modeler.nodes.annotations.IMemberAnnotation;
import org.pentaho.metadata.model.LogicalColumn;
import org.pentaho.metadata.model.IPhysicalColumn;
import org.pentaho.ui.xul.components.XulButton;
import org.pentaho.ui.xul.components.XulLabel;
import org.pentaho.ui.xul.components.XulMenuList;
import org.pentaho.ui.xul.components.XulTextbox;
import org.pentaho.ui.xul.components.XulCheckbox;
import org.pentaho.ui.xul.XulContainer;
import org.pentaho.ui.xul.containers.XulVbox;
import org.pentaho.ui.xul.stereotype.Bindable;
import org.pentaho.ui.xul.binding.BindingConvertor;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
public class LevelsPropertiesForm extends AbstractModelerNodeForm<BaseColumnBackedMetaData> {
protected XulTextbox name;
protected XulCheckbox hasUniqueMembers;
protected XulLabel sourceLabel;
protected XulLabel ordinalLabel;
//protected XulLabel captionLabel;
protected XulLabel level_message_label;
protected XulVbox messageBox;
protected String colName;
protected String ordinalColName;
protected XulButton clearOrdinalColumnBtn;
protected String captionColName;
protected String locale;
protected XulButton messageBtn;
protected XulMenuList geoList;
protected XulMenuList timeLevelTypeList;
protected XulMenuList timeLevelFormatList;
protected String timeLevelFormat;
protected List<GeoRole> geoRoles = new ArrayList<GeoRole>();
protected GeoRole selectedGeoRole;
protected GeoRole dummyGeoRole = new GeoRole(ModelerMessagesHolder.getMessages().getString("none"), Collections.<String>emptyList());
protected List<TimeRole> timeRoles = new ArrayList<TimeRole>();
protected TimeRole selectedTimeLevelType = TimeRole.DUMMY;
public LevelsPropertiesForm(String panelId, String locale) {
super(panelId);
this.locale = locale;
}
protected PropertyChangeListener validListener = new PropertyChangeListener() {
public void propertyChange( PropertyChangeEvent evt ) {
String propertyName = evt.getPropertyName();
if (propertyName.equals("valid") ||
propertyName.equals("logicalColumn") ||
propertyName.equals("logicalOrdinalColumn") ||
propertyName.equals("ordinalColumnName") ||
propertyName.equals("logicalCaptionColumn") ||
propertyName.equals("timeLevelFormat")
) {
showValidations();
}
}
};
public LevelsPropertiesForm(String locale) {
this("levelprops", locale);
}
public void setObject(BaseColumnBackedMetaData metadata) {
LevelMetaData levelMetaData = (LevelMetaData) metadata;
if (getNode() != null) {
getNode().removePropertyChangeListener(validListener);
}
setNode(levelMetaData);
if (levelMetaData == null) {
return;
}
getNode().addPropertyChangeListener(validListener);
name.setValue(levelMetaData.getName());
setColumnName(getColumnNameFromLogicalColumn(levelMetaData.getLogicalColumn()));
ordinalColName = "";
setOrdinalColumnName(getColumnNameFromLogicalColumn(levelMetaData.getLogicalOrdinalColumn()));
//setCaptionColumnName(getColumnNameFromLogicalColumn(levelMetaData.getLogicalCaptionColumn()));
hasUniqueMembers.setChecked(levelMetaData.isUniqueMembers());
Map<String, IMemberAnnotation> annotations = levelMetaData.getMemberAnnotations();
if (levelMetaData.isTimeLevel()) {
setGeoLevelElementsVisible(false);
setTimeLevelElementsVisible(true);
DataRole dataRole = getNode().getDataRole();
setSelectedTimeLevelType(dataRole instanceof TimeRole ? ((TimeRole)dataRole) : TimeRole.DUMMY);
}
else {
setGeoLevelElementsVisible(true);
setTimeLevelElementsVisible(false);
GeoRole geoRole = (GeoRole) annotations.get(GeoContext.ANNOTATION_GEO_ROLE);
setSelectedGeoRole(geoRole);
if(selectedGeoRole == null){
setSelectedGeoRole(dummyGeoRole);
}
}
showValidations();
}
protected void showValidations() {
if (getNode() == null) {
return;
}
setNotValid(!getNode().isValid());
LogicalColumn logicalColumn;
logicalColumn = getNode().getLogicalColumn();
setBackingColumnAvailable(logicalColumn != null);
setColumnName(getColumnNameFromLogicalColumn(logicalColumn));
logicalColumn = getNode().getLogicalOrdinalColumn();
setOrdinalColumnName(getColumnNameFromLogicalColumn(logicalColumn));
messageBox.setVisible(getNode().getValidationMessages().size() > 0);
setValidMessages(getNode().getValidationMessagesString());
}
protected void setGeoLevelElementsVisible(boolean visible) {
setContainerVisible("geo_level_elements", visible);
}
protected void setTimeLevelElementsVisible(boolean visible) {
setContainerVisible("time_level_elements", visible);
}
public void init(ModelerWorkspace workspace) {
super.init(workspace);
bf.createBinding(this, "notValid", "level_message", "visible");
name = (XulTextbox) document.getElementById("level_name");
hasUniqueMembers = (XulCheckbox) document.getElementById("has_unique_members");
sourceLabel = (XulLabel) document.getElementById("level_source_col");
ordinalLabel = (XulLabel) document.getElementById("level_ordinal_col");
clearOrdinalColumnBtn = (XulButton) document.getElementById("clear_ordinal_column");
//captionLabel = (XulLabel) document.getElementById("level_source_col");
level_message_label = (XulLabel) document.getElementById("level_message_label");
messageBox = (XulVbox) document.getElementById("level_message");
bf.createBinding(this, "backingColumnAvailable", "fixLevelColumnsBtn", "!visible");
bf.createBinding(this, "columnName", sourceLabel, "value");
bf.createBinding(this, "ordinalColumnName", ordinalLabel, "value");
bf.createBinding(this, "ordinalColumnName", clearOrdinalColumnBtn, "image",
new BindingConvertor<String, String>(){
@Override
public String sourceToTarget(String value) {
return "images/" + (value == null ? "blank_button" : "remove") + ".png";
}
@Override
public String targetToSource(String value) {
// TODO Auto-generated method stub
return null;
}
}
);
bf.createBinding(this, "name", name, "value");
bf.createBinding(this, "uniqueMembers", hasUniqueMembers, "checked");
bf.createBinding(this, "validMessages", level_message_label, "value", validMsgTruncatedBinding);
messageBtn = (XulButton) document.getElementById("level_message_btn");
bf.createBinding(this, "validMessages", messageBtn, "visible", showMsgBinding);
geoList = (XulMenuList) document.getElementById("level_geo_role");
geoRoles.clear();
geoRoles.add(dummyGeoRole);
geoRoles.addAll(workspace.getGeoContext());
geoList.setElements(geoRoles);
bf.createBinding(geoList, "selectedItem", this, "selectedGeoRole");
timeLevelTypeList = (XulMenuList) document.getElementById("time_level_type");
timeRoles.clear();
timeRoles.addAll(TimeRole.getAllRoles());
timeLevelTypeList.setElements(timeRoles);
bf.createBinding(timeLevelTypeList, "selectedItem", this, "selectedTimeLevelType");
timeLevelFormatList = (XulMenuList) document.getElementById("time_level_format");
bf.createBinding(timeLevelFormatList, "value", this, "timeLevelFormat");
//bf.createBinding(timeLevelFormatList, "selectedItem", this, "timeLevelFormat");
}
protected String getColumnNameFromLogicalColumn(LogicalColumn col ) {
String columnName = ""; //$NON-NLS-1$
if (col != null) {
IPhysicalColumn physicalColumn = col.getPhysicalColumn();
if (physicalColumn != null ) {
//TODO: GWT locale
columnName = physicalColumn.getName(locale);
}
}
return columnName;
}
@Bindable
public void setColumnName(String name) {
String prevName = colName;
if (prevName == null && name == "") return;
if (prevName != null && name != null && prevName.equals(name)) return;
colName = name;
this.firePropertyChange("columnName", prevName, colName); //$NON-NLS-1$
}
@Bindable
public String getColumnName() {
return colName;
}
@Bindable
public void setOrdinalColumnName(String name) {
String prevName = ordinalColName;
if ("".equals(name)) name = null;
if (prevName == null && name == null) return;
if (prevName != null && name != null && prevName.equals(name)) return;
ordinalColName = name;
this.firePropertyChange("ordinalColumnName", prevName, ordinalColName); //$NON-NLS-1$
}
@Bindable
public String getOrdinalColumnName() {
return ordinalColName;
}
@Bindable
public void setCaptionColumnName(String name) {
String prevName = captionColName;
if (prevName == null && name == "") return;
if (prevName != null && name != null && prevName.equals(name)) return;
captionColName = name;
this.firePropertyChange("captionColumnName", prevName, captionColName); //$NON-NLS-1$
}
@Bindable
public String geCaptionColumnName() {
return captionColName;
}
@Bindable
public void setName( String name ) {
if (getNode() != null) {
getNode().setName(name);
}
this.name.setValue(name);
}
@Bindable
public String getName() {
if (getNode() == null) {
return null;
}
return getNode().getName();
}
@Bindable
public void setUniqueMembers( boolean uniqueMembers) {
if (getNode() != null) {
getNode().setUniqueMembers(uniqueMembers);
}
if (uniqueMembers == hasUniqueMembers.isChecked()) return;
hasUniqueMembers.setChecked(uniqueMembers);
}
@Bindable
public boolean isUniqueMembers() {
if (getNode() == null) {
return false;
}
return getNode().isUniqueMembers();
}
@Bindable
public boolean isNotValid() {
if (getNode() != null) {
return !getNode().isValid();
} else {
return false;
}
}
@Bindable
public void setNotValid( boolean notValid ) {
this.firePropertyChange("notValid", null, notValid);
}
@Bindable
public boolean isBackingColumnAvailable() {
if (getNode() != null) {
return getNode().getLogicalColumn() != null;
} else {
return false;
}
}
@Bindable
public void setBackingColumnAvailable(boolean available) {
this.firePropertyChange("backingColumnAvailable", null, available);
}
@Override
public String getValidMessages() {
if (getNode() != null) {
return getNode().getValidationMessagesString();
} else {
return null;
}
}
@Bindable
public GeoRole getSelectedGeoRole() {
return selectedGeoRole;
}
@Bindable
public void setSelectedGeoRole(GeoRole selectedGeoRole) {
GeoRole prevVal = this.selectedGeoRole;
this.selectedGeoRole = selectedGeoRole;
if(selectedGeoRole != null && selectedGeoRole != dummyGeoRole){
getNode().getMemberAnnotations().put(GeoContext.ANNOTATION_GEO_ROLE, selectedGeoRole);
getNode().getMemberAnnotations().put(GeoContext.ANNOTATION_DATA_ROLE, selectedGeoRole);
} else {
getNode().getMemberAnnotations().remove(GeoContext.ANNOTATION_DATA_ROLE);
getNode().getMemberAnnotations().remove(GeoContext.ANNOTATION_GEO_ROLE);
}
getNode().validateNode();
showValidations();
firePropertyChange("selectedGeoRole", prevVal, selectedGeoRole);
}
@Bindable
public TimeRole getSelectedTimeLevelType() {
return selectedTimeLevelType;
}
@Bindable
public void setSelectedTimeLevelType(TimeRole selectedTimeLevelType) {
TimeRole oldTimeLevelType = this.getSelectedTimeLevelType();
if (selectedTimeLevelType == null) {
selectedTimeLevelType = TimeRole.DUMMY;
}
//if (oldTimeLevelType == null && selectedTimeLevelType == null) return;
//if (oldTimeLevelType != null && selectedTimeLevelType != null && oldTimeLevelType.equals(selectedTimeLevelType)) return;
this.selectedTimeLevelType = selectedTimeLevelType;
getNode().setDataRole(selectedTimeLevelType);
List<String> formatsList = selectedTimeLevelType.getFormatsList();
String value = getTimeLevelFormat();
int selectedIndex = formatsList.indexOf(value);
timeLevelFormatList.setElements(formatsList);
if (selectedIndex == -1) {
if (value == null) value = "";
timeLevelFormatList.setValue(value);
}
else {
timeLevelFormatList.setSelectedIndex(selectedIndex);
}
firePropertyChange("selectedTimeLevelType", oldTimeLevelType, selectedTimeLevelType);
}
@Bindable
public void setTimeLevelFormat(String format) {
if ("".equals(format)) format = null;
if (format == null && timeLevelFormat == null) return;
if (format != null && timeLevelFormat != null && format.equals(timeLevelFormat)) return;
if (getNode() != null) {
getNode().setTimeLevelFormat(format);
}
LevelMetaData levelMetaData = (LevelMetaData)getNode();
HierarchyMetaData hierarchyMetaData = levelMetaData.getHierarchyMetaData();
List<LevelMetaData> levels = hierarchyMetaData.getLevels();
boolean isDescendant = false;
for (LevelMetaData descendant : levels) {
if (!isDescendant) {
if (descendant == levelMetaData) isDescendant = true;
continue;
}
descendant.validateNode();
}
showValidations();
timeLevelFormat = format;
}
@Bindable
public String getTimeLevelFormat() {
if (getNode() == null) {
return null;
}
return getNode().getTimeLevelFormat();
}
} |
package com.datalogics.pdf.samples.printing;
import com.datalogics.pdf.samples.SampleTest;
import mockit.Mock;
import mockit.MockUp;
import org.junit.Test;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.ServiceUIFactory;
import javax.print.attribute.Attribute;
import javax.print.attribute.AttributeSet;
import javax.print.attribute.PrintServiceAttribute;
import javax.print.attribute.PrintServiceAttributeSet;
import javax.print.attribute.ResolutionSyntax;
import javax.print.attribute.standard.PrinterResolution;
import javax.print.event.PrintServiceAttributeListener;
/**
* Tests the PrintPdf sample.
*/
public class PrintPdfTest extends SampleTest {
@Test
public void testMain() throws Exception {
// Mock the PrintServiceLookup.lookupDefaultPrintService() method to return a TestPrintService object
new MockUp<PrintServiceLookup>() {
@Mock
PrintService lookupDefaultPrintService() {
return new TestPrintService();
}
};
// Call the main method
final String[] args = new String[0];
PrintPdf.main(args);
}
/*
* TestPrintService implements a 'fake' PrintService to be returned by our mock PrintServiceLookup.
*/
private static class TestPrintService implements PrintService {
/*
* Return a name for our 'fake' PrintService.
*/
@Override
public String getName() {
return "Virtual Test Printer";
}
/*
* Return default attribute values for our 'fake' PrintService. The only attribute we care about is
* PrinterResolution; all others return null.
*/
@Override
public Object getDefaultAttributeValue(final Class<? extends Attribute> category) {
if (category == PrinterResolution.class) {
return new PrinterResolution(400, 400, ResolutionSyntax.DPI);
} else {
return null;
}
}
/*
* The following methods are not used in the test, and are given stub implementations.
*/
@Override
public DocPrintJob createPrintJob() {
return null;
}
@Override
public void addPrintServiceAttributeListener(final PrintServiceAttributeListener listener) {}
@Override
public void removePrintServiceAttributeListener(final PrintServiceAttributeListener listener) {}
@Override
public PrintServiceAttributeSet getAttributes() {
return null;
}
@Override
public <T extends PrintServiceAttribute> T getAttribute(final Class<T> category) {
return null;
}
@Override
public DocFlavor[] getSupportedDocFlavors() {
return new DocFlavor[0];
}
@Override
public boolean isDocFlavorSupported(final DocFlavor flavor) {
return false;
}
@Override
public Class<?>[] getSupportedAttributeCategories() {
return new Class<?>[0];
}
@Override
public boolean isAttributeCategorySupported(final Class<? extends Attribute> category) {
return false;
}
@Override
public Object getSupportedAttributeValues(final Class<? extends Attribute> category, final DocFlavor flavor,
final AttributeSet attributes) {
return null;
}
@Override
public boolean isAttributeValueSupported(final Attribute attrval, final DocFlavor flavor,
final AttributeSet attributes) {
return false;
}
@Override
public AttributeSet getUnsupportedAttributes(final DocFlavor flavor, final AttributeSet attributes) {
return null;
}
@Override
public ServiceUIFactory getServiceUIFactory() {
return null;
}
}
} |
package com.levelup.java.date;
import static org.junit.Assert.assertNotNull;
import java.util.GregorianCalendar;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import org.apache.log4j.Logger;
import org.junit.Test;
import com.levelup.java.date.format.PredefinedDateFormats;
public class DateToXMLGregorianCalendar {
private static final Logger logger = Logger.getLogger(DateToXMLGregorianCalendar.class);
@Test
public void convert_date_to_XMLGregorianCalendar()
throws DatatypeConfigurationException {
GregorianCalendar gCalendar = new GregorianCalendar();
XMLGregorianCalendar xmlGregorianCalendar = DatatypeFactory
.newInstance().newXMLGregorianCalendar(gCalendar);
logger.info(xmlGregorianCalendar);
assertNotNull(xmlGregorianCalendar);
}
} |
package com.relayrides.pushy.apns;
import static org.junit.Assert.*;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class PushManagerFactoryTest {
protected static final ApnsEnvironment TEST_ENVIRONMENT =
new ApnsEnvironment("127.0.0.1", 2195, "127.0.0.1", 2196);
private static final String CLIENT_KEYSTORE_FILE_NAME = "/pushy-test-client.jks";
private static final String CLIENT_EMPTY_KEYSTORE_FILE_NAME = "/empty-keystore.jks";
private static final String CLIENT_PKCS12_FILE_NAME = "/pushy-test-client.p12";
private static final String CLIENT_EMPTY_PKCS12_FILE_NAME = "/empty.p12";
private static final String KEYSTORE_PASSWORD = "pushy-test";
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void testPushManagerFactory() throws UnrecoverableKeyException, KeyManagementException, KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
// As long as nothing explodes, we're happy
new PushManagerFactory<ApnsPushNotification>(TEST_ENVIRONMENT, SSLTestUtil.createSSLContextForTestClient());
}
@Test(expected = NullPointerException.class)
public void testPushManagerFactoryNullEnvironment() throws UnrecoverableKeyException, KeyManagementException, KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
new PushManagerFactory<ApnsPushNotification>(null, SSLTestUtil.createSSLContextForTestClient());
}
@Test(expected = NullPointerException.class)
public void testPushManagerFactoryNullSslContext() {
new PushManagerFactory<ApnsPushNotification>(TEST_ENVIRONMENT, null);
}
@Test
public void testCreateDefaultSSLContextFromPKCS12File() throws UnrecoverableKeyException, KeyManagementException, KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
assertNotNull(PushManagerFactory.createDefaultSSLContext(
this.getFullPath(CLIENT_PKCS12_FILE_NAME), KEYSTORE_PASSWORD));
}
@Test(expected = FileNotFoundException.class)
public void testCreateDefaultSSLContextFromPKCS12FileMissingFile() throws UnrecoverableKeyException, KeyManagementException, KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
PushManagerFactory.createDefaultSSLContext("/path/to/non-existent-file", KEYSTORE_PASSWORD);
}
@Test(expected = IOException.class)
public void testCreateDefaultSSLContextFromPKCS12FileIncorrectPassword() throws UnrecoverableKeyException, KeyManagementException, KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
PushManagerFactory.createDefaultSSLContext(this.getFullPath(CLIENT_PKCS12_FILE_NAME), "incorrect-password");
}
@Test(expected = GeneralSecurityException.class)
public void testCreateDefaultSSLContextFromPKCS12FileNullPassword() throws UnrecoverableKeyException, KeyManagementException, KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
PushManagerFactory.createDefaultSSLContext(this.getFullPath(CLIENT_PKCS12_FILE_NAME), null);
}
@Test(expected = KeyStoreException.class)
public void testCreateDefaultSSLContextFromEmptyPKCS12File() throws UnrecoverableKeyException, KeyManagementException, KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
PushManagerFactory.createDefaultSSLContext(this.getFullPath(CLIENT_EMPTY_PKCS12_FILE_NAME), KEYSTORE_PASSWORD);
}
@Test
public void testCreateDefaultSSLContextFromJKSFile() throws UnrecoverableKeyException, KeyManagementException, KeyStoreException, NoSuchAlgorithmException, IOException, CertificateException {
final FileInputStream keyStoreInputStream =
new FileInputStream(this.getFullPath(CLIENT_KEYSTORE_FILE_NAME));
try {
final KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(keyStoreInputStream, KEYSTORE_PASSWORD.toCharArray());
assertNotNull(PushManagerFactory.createDefaultSSLContext(keyStore, KEYSTORE_PASSWORD.toCharArray()));
} finally {
keyStoreInputStream.close();
}
}
@Test(expected = UnrecoverableKeyException.class)
public void testCreateDefaultSSLContextFromJKSFileIncorrectPassword() throws UnrecoverableKeyException, KeyManagementException, KeyStoreException, NoSuchAlgorithmException, IOException, CertificateException {
final FileInputStream keyStoreInputStream =
new FileInputStream(this.getFullPath(CLIENT_KEYSTORE_FILE_NAME));
try {
final KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(keyStoreInputStream, KEYSTORE_PASSWORD.toCharArray());
PushManagerFactory.createDefaultSSLContext(keyStore, "incorrect".toCharArray());
} finally {
keyStoreInputStream.close();
}
}
@Test(expected = GeneralSecurityException.class)
public void testCreateDefaultSSLContextFromJKSFileNullPassword() throws UnrecoverableKeyException, KeyManagementException, KeyStoreException, NoSuchAlgorithmException, IOException, CertificateException {
final FileInputStream keyStoreInputStream =
new FileInputStream(this.getFullPath(CLIENT_KEYSTORE_FILE_NAME));
try {
final KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(keyStoreInputStream, KEYSTORE_PASSWORD.toCharArray());
PushManagerFactory.createDefaultSSLContext(keyStore, null);
} finally {
keyStoreInputStream.close();
}
}
@Test
public void testCreateDefaultSSLContextWithInputStream() throws IOException, CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
final FileInputStream keyStoreInputStream =
new FileInputStream(this.getFullPath(CLIENT_PKCS12_FILE_NAME));
try {
assertNotNull(PushManagerFactory.createDefaultSSLContext(keyStoreInputStream, KEYSTORE_PASSWORD));
} finally {
keyStoreInputStream.close();
}
}
@Test(expected = KeyStoreException.class)
public void testCreateDefaultSSLContextFromEmptyJKSFile() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException, KeyManagementException {
final FileInputStream keyStoreInputStream =
new FileInputStream(this.getFullPath(CLIENT_EMPTY_KEYSTORE_FILE_NAME));
try {
final KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(keyStoreInputStream, KEYSTORE_PASSWORD.toCharArray());
PushManagerFactory.createDefaultSSLContext(keyStore, KEYSTORE_PASSWORD.toCharArray());
} finally {
keyStoreInputStream.close();
}
}
private String getFullPath(final String resourcePath) {
return this.getClass().getResource(resourcePath).getPath();
}
} |
package com.salesforce.phoenix.compile;
import static com.salesforce.phoenix.util.TestUtil.PHOENIX_JDBC_URL;
import static org.junit.Assert.assertEquals;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSetMetaData;
import org.junit.Test;
import com.salesforce.phoenix.query.BaseConnectionlessQueryTest;
import com.salesforce.phoenix.util.TestUtil;
/**
*
* Tests for getting PreparedStatement meta data
*
* @author jtaylor
* @since 0.1
*/
public class QueryMetaDataTest extends BaseConnectionlessQueryTest {
@Test
public void testNoParameterMetaData() throws Exception {
String query = "SELECT a_string, b_string FROM atable WHERE organization_id='000000000000000'";
Connection conn = DriverManager.getConnection(getUrl(), TestUtil.TEST_PROPERTIES);
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(0, pmd.getParameterCount());
}
@Test
public void testCaseInsensitive() throws Exception {
String query = "SELECT A_string, b_striNG FROM ataBle WHERE ORGANIZATION_ID='000000000000000'";
Connection conn = DriverManager.getConnection(getUrl(), TestUtil.TEST_PROPERTIES);
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(0, pmd.getParameterCount());
}
@Test
public void testParameterMetaData() throws Exception {
String query = "SELECT a_string, b_string FROM atable WHERE organization_id=? and (a_integer = ? or a_date = ? or b_string = ? or a_string = 'foo')";
Connection conn = DriverManager.getConnection(getUrl(), TestUtil.TEST_PROPERTIES);
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(4, pmd.getParameterCount());
assertEquals(String.class.getName(), pmd.getParameterClassName(1));
assertEquals(Integer.class.getName(), pmd.getParameterClassName(2));
assertEquals(Date.class.getName(), pmd.getParameterClassName(3));
assertEquals(String.class.getName(), pmd.getParameterClassName(4));
}
@Test
public void testUpsertParameterMetaData() throws Exception {
String query = "UPSERT INTO atable VALUES (?, ?, ?, ?, ?)";
Connection conn = DriverManager.getConnection(getUrl(), TestUtil.TEST_PROPERTIES);
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(5, pmd.getParameterCount());
assertEquals(String.class.getName(), pmd.getParameterClassName(1));
assertEquals(String.class.getName(), pmd.getParameterClassName(2));
assertEquals(String.class.getName(), pmd.getParameterClassName(3));
assertEquals(String.class.getName(), pmd.getParameterClassName(4));
assertEquals(Integer.class.getName(), pmd.getParameterClassName(5));
}
@Test
public void testToDateFunctionMetaData() throws Exception {
String query = "SELECT a_string, b_string FROM atable WHERE a_date > to_date(?)";
Connection conn = DriverManager.getConnection(getUrl(), TestUtil.TEST_PROPERTIES);
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(1, pmd.getParameterCount());
assertEquals(String.class.getName(), pmd.getParameterClassName(1));
}
@Test
public void testLimitParameterMetaData() throws Exception {
String query = "SELECT a_string, b_string FROM atable WHERE organization_id=? and a_string = 'foo' LIMIT ?";
Connection conn = DriverManager.getConnection(getUrl(), TestUtil.TEST_PROPERTIES);
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(2, pmd.getParameterCount());
assertEquals(String.class.getName(), pmd.getParameterClassName(1));
assertEquals(Integer.class.getName(), pmd.getParameterClassName(2));
}
@Test
public void testRoundParameterMetaData() throws Exception {
String query = "SELECT a_string, b_string FROM atable WHERE round(a_date,?,?) = ?";
Connection conn = DriverManager.getConnection(getUrl(), TestUtil.TEST_PROPERTIES);
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(3, pmd.getParameterCount());
assertEquals(String.class.getName(), pmd.getParameterClassName(1));
assertEquals(Integer.class.getName(), pmd.getParameterClassName(2));
assertEquals(Date.class.getName(), pmd.getParameterClassName(3));
}
@Test
public void testInListParameterMetaData1() throws Exception {
String query = "SELECT a_string, b_string FROM atable WHERE a_string IN (?, ?)";
Connection conn = DriverManager.getConnection(getUrl(), TestUtil.TEST_PROPERTIES);
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(2, pmd.getParameterCount());
assertEquals(String.class.getName(), pmd.getParameterClassName(1));
assertEquals(String.class.getName(), pmd.getParameterClassName(2));
}
@Test
public void testInListParameterMetaData2() throws Exception {
String query = "SELECT a_string, b_string FROM atable WHERE ? IN (2.2, 3)";
Connection conn = DriverManager.getConnection(getUrl(), TestUtil.TEST_PROPERTIES);
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(1, pmd.getParameterCount());
assertEquals(BigDecimal.class.getName(), pmd.getParameterClassName(1));
}
@Test
public void testInListParameterMetaData3() throws Exception {
String query = "SELECT a_string, b_string FROM atable WHERE ? IN ('foo')";
Connection conn = DriverManager.getConnection(getUrl(), TestUtil.TEST_PROPERTIES);
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(1, pmd.getParameterCount());
assertEquals(String.class.getName(), pmd.getParameterClassName(1));
}
@Test
public void testInListParameterMetaData4() throws Exception {
String query = "SELECT a_string, b_string FROM atable WHERE ? IN (?, ?)";
Connection conn = DriverManager.getConnection(getUrl(), TestUtil.TEST_PROPERTIES);
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(3, pmd.getParameterCount());
assertEquals(null, pmd.getParameterClassName(1));
assertEquals(null, pmd.getParameterClassName(2));
assertEquals(null, pmd.getParameterClassName(3));
}
@Test
public void testCaseMetaData() throws Exception {
String query1 = "SELECT a_string, b_string FROM atable WHERE case when a_integer = 1 then ? when a_integer > 2 then 2 end > 3";
Connection conn = DriverManager.getConnection(getUrl(), TestUtil.TEST_PROPERTIES);
PreparedStatement statement = conn.prepareStatement(query1);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(1, pmd.getParameterCount());
assertEquals(BigDecimal.class.getName(), pmd.getParameterClassName(1));
assertEquals(ParameterMetaData.parameterNullable, pmd.isNullable(1));
String query2 = "SELECT a_string, b_string FROM atable WHERE case when a_integer = 1 then 1 when a_integer > 2 then 2 end > ?";
PreparedStatement statement2 = conn.prepareStatement(query2);
ParameterMetaData pmd2 = statement2.getParameterMetaData();
assertEquals(1, pmd2.getParameterCount());
assertEquals(Integer.class.getName(), pmd2.getParameterClassName(1));
assertEquals(ParameterMetaData.parameterNullable, pmd2.isNullable(1));
}
@Test
public void testSubstrParameterMetaData() throws Exception {
String query = "SELECT a_string, b_string FROM atable WHERE substr(a_string,?,?) = ?";
Connection conn = DriverManager.getConnection(getUrl(), TestUtil.TEST_PROPERTIES);
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(3, pmd.getParameterCount());
assertEquals(Long.class.getName(), pmd.getParameterClassName(1));
assertEquals(Long.class.getName(), pmd.getParameterClassName(2));
assertEquals(String.class.getName(), pmd.getParameterClassName(3));
}
@Test
public void testKeyPrefixParameterMetaData() throws Exception {
String query = "SELECT a_string, b_string FROM atable WHERE organization_id='000000000000000' and substr(entity_id,1,3)=? and a_string = 'foo'";
Connection conn = DriverManager.getConnection(getUrl(), TestUtil.TEST_PROPERTIES);
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(1, pmd.getParameterCount());
assertEquals(String.class.getName(), pmd.getParameterClassName(1));
}
@Test
public void testDateSubstractExpressionMetaData1() throws Exception {
final String DS4 = "1970-01-01 01:45:00";
String query = "SELECT entity_id,a_string FROM atable where a_date-2.5-?=a_date";
Connection conn = DriverManager.getConnection(PHOENIX_JDBC_URL, TestUtil.TEST_PROPERTIES);
PreparedStatement statement = conn.prepareStatement(query);
statement.setString(1, DS4);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(1, pmd.getParameterCount());
assertEquals(BigDecimal.class.getName(), pmd.getParameterClassName(1));
}
@Test
public void testDateSubstractExpressionMetaData2() throws Exception {
final String DS4 = "1970-01-01 01:45:00";
String query = "SELECT entity_id,a_string FROM atable where a_date-?=a_date";
Connection conn = DriverManager.getConnection(PHOENIX_JDBC_URL, TestUtil.TEST_PROPERTIES);
PreparedStatement statement = conn.prepareStatement(query);
statement.setString(1, DS4);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(1, pmd.getParameterCount());
// FIXME: Should really be Date, but we currently don't know if we're
// comparing to a date or a number where this is being calculated
// (which would disambiguate it).
assertEquals(null, pmd.getParameterClassName(1));
}
@Test
public void testDateSubstractExpressionMetaData3() throws Exception {
final String DS4 = "1970-01-01 01:45:00";
String query = "SELECT entity_id,a_string FROM atable where a_date-?=a_integer";
Connection conn = DriverManager.getConnection(PHOENIX_JDBC_URL, TestUtil.TEST_PROPERTIES);
PreparedStatement statement = conn.prepareStatement(query);
statement.setString(1, DS4);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(1, pmd.getParameterCount());
// FIXME: Should really be Integer, but we currently don't know if we're
// comparing to a date or a number where this is being calculated
// (which would disambiguate it).
assertEquals(null, pmd.getParameterClassName(1));
}
@Test
public void testTwoDateSubstractExpressionMetaData() throws Exception {
final String DS4 = "1970-01-01 01:45:00";
String query = "SELECT entity_id,a_string FROM atable where ?-a_date=1";
Connection conn = DriverManager.getConnection(PHOENIX_JDBC_URL, TestUtil.TEST_PROPERTIES);
PreparedStatement statement = conn.prepareStatement(query);
statement.setString(1, DS4);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(1, pmd.getParameterCount());
// We know this must be date - anything else would be an error
assertEquals(Date.class.getName(), pmd.getParameterClassName(1));
}
@Test
public void testDateAdditionExpressionMetaData1() throws Exception {
final String DS4 = "1970-01-01 01:45:00";
String query = "SELECT entity_id,a_string FROM atable where 1+a_date+?>a_date";
Connection conn = DriverManager.getConnection(PHOENIX_JDBC_URL, TestUtil.TEST_PROPERTIES);
PreparedStatement statement = conn.prepareStatement(query);
statement.setString(1, DS4);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(1, pmd.getParameterCount());
assertEquals(BigDecimal.class.getName(), pmd.getParameterClassName(1));
}
@Test
public void testDateAdditionExpressionMetaData2() throws Exception {
final String DS4 = "1970-01-01 01:45:00";
String query = "SELECT entity_id,a_string FROM atable where ?+a_date>a_date";
Connection conn = DriverManager.getConnection(PHOENIX_JDBC_URL, TestUtil.TEST_PROPERTIES);
PreparedStatement statement = conn.prepareStatement(query);
statement.setString(1, DS4);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(1, pmd.getParameterCount());
assertEquals(BigDecimal.class.getName(), pmd.getParameterClassName(1));
}
@Test
public void testCoerceToDecimalArithmeticMetaData() throws Exception {
String[] ops = { "+", "-", "*", "/" };
for (String op : ops) {
String query = "SELECT entity_id,a_string FROM atable where a_integer" + op + "2.5" + op + "?=0";
Connection conn = DriverManager.getConnection(PHOENIX_JDBC_URL, TestUtil.TEST_PROPERTIES);
PreparedStatement statement = conn.prepareStatement(query);
statement.setInt(1, 4);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(1, pmd.getParameterCount());
assertEquals(BigDecimal.class.getName(), pmd.getParameterClassName(1));
}
}
@Test
public void testLongArithmeticMetaData() throws Exception {
String[] ops = { "+", "-", "*", "/" };
for (String op : ops) {
String query = "SELECT entity_id,a_string FROM atable where a_integer" + op + "2" + op + "?=0";
Connection conn = DriverManager.getConnection(PHOENIX_JDBC_URL, TestUtil.TEST_PROPERTIES);
PreparedStatement statement = conn.prepareStatement(query);
statement.setInt(1, 4);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(1, pmd.getParameterCount());
assertEquals(Long.class.getName(), pmd.getParameterClassName(1));
}
}
@Test
public void testBasicResultSetMetaData() throws Exception {
String query = "SELECT organization_id, a_string, b_string, a_integer i, a_date FROM atable WHERE organization_id='000000000000000' and substr(entity_id,1,3)=? and a_string = 'foo'";
Connection conn = DriverManager.getConnection(getUrl(), TestUtil.TEST_PROPERTIES);
PreparedStatement statement = conn.prepareStatement(query);
ResultSetMetaData md = statement.getMetaData();
assertEquals(5, md.getColumnCount());
assertEquals("organization_id".toUpperCase(),md.getColumnName(1));
assertEquals("a_string".toUpperCase(),md.getColumnName(2));
assertEquals("b_string".toUpperCase(),md.getColumnName(3));
assertEquals("i".toUpperCase(),md.getColumnName(4));
assertEquals("a_date".toUpperCase(),md.getColumnName(5));
assertEquals(String.class.getName(),md.getColumnClassName(1));
assertEquals(String.class.getName(),md.getColumnClassName(2));
assertEquals(String.class.getName(),md.getColumnClassName(3));
assertEquals(Integer.class.getName(),md.getColumnClassName(4));
assertEquals(Date.class.getName(),md.getColumnClassName(5));
assertEquals("atable".toUpperCase(),md.getTableName(1));
assertEquals(java.sql.Types.INTEGER,md.getColumnType(4));
assertEquals(true,md.isReadOnly(1));
assertEquals(false,md.isDefinitelyWritable(1));
assertEquals("i".toUpperCase(),md.getColumnLabel(4));
assertEquals("a_date".toUpperCase(),md.getColumnLabel(5));
assertEquals(ResultSetMetaData.columnNoNulls,md.isNullable(1));
assertEquals(ResultSetMetaData.columnNullable,md.isNullable(5));
}
@Test
public void testStringConcatMetaData() throws Exception {
String query = "SELECT entity_id,a_string FROM atable where 2 || a_integer || ? like '2%'";
Connection conn = DriverManager.getConnection(PHOENIX_JDBC_URL, TestUtil.TEST_PROPERTIES);
PreparedStatement statement = conn.prepareStatement(query);
statement.setString(1, "foo");
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(1, pmd.getParameterCount());
assertEquals(String.class.getName(), pmd.getParameterClassName(1));
}
@Test
public void testRowValueConstructorBindParamMetaData() throws Exception {
String query = "SELECT a_integer, x_integer FROM aTable WHERE (a_integer, x_integer, a_string) = (?, ?, ?)";
Connection conn = DriverManager.getConnection(getUrl(), TestUtil.TEST_PROPERTIES);
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(3, pmd.getParameterCount());
assertEquals(Integer.class.getName(), pmd.getParameterClassName(1));
assertEquals(Integer.class.getName(), pmd.getParameterClassName(2));
assertEquals(String.class.getName(), pmd.getParameterClassName(3));
}
@Test
public void testRowValueConstructorBindParamMetaDataWithMoreNumberOfBindArgs() throws Exception {
String query = "SELECT a_integer, x_integer FROM aTable WHERE (a_integer, x_integer) = (?, ?, ?)";
Connection conn = DriverManager.getConnection(getUrl(), TestUtil.TEST_PROPERTIES);
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(3, pmd.getParameterCount());
assertEquals(Integer.class.getName(), pmd.getParameterClassName(1));
assertEquals(Integer.class.getName(), pmd.getParameterClassName(2));
assertEquals(null, pmd.getParameterClassName(3));
}
@Test
public void testRowValueConstructorBindParamMetaDataWithLessNumberOfBindArgs() throws Exception {
String query = "SELECT a_integer, x_integer FROM aTable WHERE (a_integer, x_integer, a_string) = (?, ?)";
Connection conn = DriverManager.getConnection(getUrl(), TestUtil.TEST_PROPERTIES);
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(2, pmd.getParameterCount());
assertEquals(Integer.class.getName(), pmd.getParameterClassName(1));
assertEquals(Integer.class.getName(), pmd.getParameterClassName(2));
}
@Test
public void testRowValueConstructorBindParamMetaDataWithBindArgsAtSamePlacesOnLHSRHS() throws Exception {
String query = "SELECT a_integer, x_integer FROM aTable WHERE (a_integer, ?) = (a_integer, ?)";
Connection conn = DriverManager.getConnection(getUrl(), TestUtil.TEST_PROPERTIES);
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(2, pmd.getParameterCount());
assertEquals(null, pmd.getParameterClassName(1));
assertEquals(null, pmd.getParameterClassName(2));
}
@Test
public void testRowValueConstructorBindParamMetaDataWithBindArgsAtDiffPlacesOnLHSRHS() throws Exception {
String query = "SELECT a_integer, x_integer FROM aTable WHERE (a_integer, ?) = (?, a_integer)";
Connection conn = DriverManager.getConnection(getUrl(), TestUtil.TEST_PROPERTIES);
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(2, pmd.getParameterCount());
assertEquals(Integer.class.getName(), pmd.getParameterClassName(1));
assertEquals(Integer.class.getName(), pmd.getParameterClassName(2));
}
// @Test broken currently, as we'll end up with null = 7 which is never true
public void testRowValueConstructorBindParamMetaDataWithBindArgsOnLHSAndLiteralExprOnRHS() throws Exception {
String query = "SELECT a_integer, x_integer FROM aTable WHERE (?, ?) = 7";
Connection conn = DriverManager.getConnection(getUrl(), TestUtil.TEST_PROPERTIES);
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(2, pmd.getParameterCount());
assertEquals(Integer.class.getName(), pmd.getParameterClassName(1));
assertEquals(null, pmd.getParameterClassName(2));
}
@Test
public void testRowValueConstructorBindParamMetaDataWithBindArgsOnRHSAndLiteralExprOnLHS() throws Exception {
String query = "SELECT a_integer, x_integer FROM aTable WHERE 7 = (?, ?)";
Connection conn = DriverManager.getConnection(getUrl(), TestUtil.TEST_PROPERTIES);
PreparedStatement statement = conn.prepareStatement(query);
ParameterMetaData pmd = statement.getParameterMetaData();
assertEquals(2, pmd.getParameterCount());
assertEquals(Integer.class.getName(), pmd.getParameterClassName(1));
assertEquals(null, pmd.getParameterClassName(2));
}
} |
package com.st.remote.controller;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.st.remote.StockPortolioRemoteApplication;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = StockPortolioRemoteApplication.class)
@WebAppConfiguration
public class StockRestControllerTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Test
public void getTicker() throws Exception {
this.mockMvc.perform(get("/ticker/MCD").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.Symbol").value("MCD"))
.andExpect(jsonPath("$.Status").value("SUCCESS"))
.andExpect(jsonPath("$.Name").value("McDonald's Corp"));
}
@Test
public void getTickerByMaket() throws Exception {
this.mockMvc.perform(get("/market/NYSE/ticker/MCD").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.fields.symbol").value("MCD"))
.andExpect(jsonPath("$.fields.issuer_name").value("McDonald's Corp."))
.andExpect(jsonPath("$.type").value("Quote"));
}
} |
package com.xjeffrose.xio.server;
import com.google.common.collect.ImmutableMap;
import com.google.common.net.HttpHeaders;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.xjeffrose.xio.client.HttpClientChannel;
import com.xjeffrose.xio.client.HttpClientConnector;
import com.xjeffrose.xio.client.Listener;
import com.xjeffrose.xio.client.XioClient;
import com.xjeffrose.xio.client.XioClientChannel;
import com.xjeffrose.xio.client.XioClientConfig;
import com.xjeffrose.xio.client.retry.BoundedExponentialBackoffRetry;
import com.xjeffrose.xio.core.BBtoHttpResponse;
import com.xjeffrose.xio.core.TcpCodec;
import com.xjeffrose.xio.core.XioAggregatorFactory;
import com.xjeffrose.xio.core.XioCodecFactory;
import com.xjeffrose.xio.core.XioException;
import com.xjeffrose.xio.core.XioNoOpHandler;
import com.xjeffrose.xio.core.XioNoOpSecurityFactory;
import com.xjeffrose.xio.core.XioSecurityFactory;
import com.xjeffrose.xio.core.XioSecurityHandlers;
import com.xjeffrose.xio.core.XioTimer;
import com.xjeffrose.xio.core.XioTransportException;
import com.xjeffrose.xio.fixtures.OkHttpUnsafe;
import com.xjeffrose.xio.fixtures.SimpleTestServer;
import com.xjeffrose.xio.fixtures.TcpClient;
import com.xjeffrose.xio.fixtures.XioTestProcessorFactory;
import com.xjeffrose.xio.fixtures.XioTestSecurityFactory;
import com.xjeffrose.xio.processor.XioProcessor;
import com.xjeffrose.xio.processor.XioProcessorFactory;
import io.airlift.units.Duration;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import java.net.InetSocketAddress;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.net.ssl.SSLException;
import org.apache.log4j.Logger;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class XioServerFunctionalTest {
public static final XioTimer timer = new XioTimer("Test Timer", (long) 100, TimeUnit.MILLISECONDS, 100);
private static final Logger log = Logger.getLogger(XioServerFunctionalTest.class.getName());
@Test
public void testComplexServerConfigurationTCP() throws Exception {
XioServerDef serverDef = new XioServerDefBuilder()
.clientIdleTimeout(new Duration((double) 2000, TimeUnit.MILLISECONDS))
.limitConnectionsTo(20)
.limitFrameSizeTo(1024)
.limitQueuedResponsesPerConnection(5)
.listen(new InetSocketAddress(9001))
.name("Xio Tcp Test Server")
.taskTimeout(new Duration((double) 2000, TimeUnit.MILLISECONDS))
.using(Executors.newCachedThreadPool())
.withSecurityFactory(new XioNoOpSecurityFactory())
.withCodecFactory(() -> new TcpCodec())
.withAggregator(() -> new XioNoOpHandler())
.withRoutingFilter(() -> new XioNoOpHandler())
.withProcessorFactory(
new XioProcessorFactory() {
@Override
public XioProcessor getProcessor() {
return new XioProcessor() {
@Override
public void disconnect(ChannelHandlerContext ctx) {
}
@Override
public ListenableFuture<Boolean> process(ChannelHandlerContext ctx, Object request, RequestContext reqCtx) {
ListeningExecutorService service = MoreExecutors.listeningDecorator(ctx.executor());
return service.submit(() -> {
reqCtx.setContextData(reqCtx.getConnectionId(), request);
return true;
});
}
};
}
}
)
.build();
XioServerConfig serverConfig = new XioServerConfigBuilder()
.setBossThreadCount(2)
.setBossThreadExecutor(Executors.newCachedThreadPool())
.setWorkerThreadCount(2)
.setWorkerThreadExecutor(Executors.newCachedThreadPool())
.setTimer(timer)
.setXioName("Xio Name Test")
.build();
DefaultChannelGroup defaultChannelGroup;
if (System.getProperty("os.name") == "Linux") {
defaultChannelGroup = new DefaultChannelGroup(new EpollEventLoopGroup().next());
} else {
defaultChannelGroup = new DefaultChannelGroup(new NioEventLoopGroup().next());
}
// Create the server transport
final XioServerTransport server = new XioServerTransport(serverDef,
serverConfig, defaultChannelGroup);
// Start the server
server.start();
// Use 3rd party client to test proper operation
//TODO(JR): Figure out why \n seems to get chopped off
String expectedResponse = "Working TcpServer";
String response = TcpClient.sendReq("127.0.0.1", 9001, expectedResponse);
assertEquals(expectedResponse, response);
// Arrange to stop the server at shutdown
Runtime.getRuntime().
addShutdownHook(new Thread() {
@Override
public void run() {
try {
server.stop();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
);
}
@Test
public void testComplexServerConfigurationHttp() throws Exception {
XioServerDef serverDef = new XioServerDefBuilder()
.clientIdleTimeout(new Duration((double) 200, TimeUnit.MILLISECONDS))
.limitConnectionsTo(200)
.limitFrameSizeTo(1024)
.limitQueuedResponsesPerConnection(50)
.listen(new InetSocketAddress(8083))
// .listen(new InetSocketAddress("127.0.0.1", 8082))
.name("Xio Test Server")
.taskTimeout(new Duration((double) 20000, TimeUnit.MILLISECONDS))
.using(Executors.newCachedThreadPool())
.withSecurityFactory(new XioNoOpSecurityFactory())
.withRoutingFilter(() -> new XioNoOpHandler())
.withProcessorFactory(new XioTestProcessorFactory())
.withCodecFactory(new XioCodecFactory() {
@Override
public ChannelHandler getCodec() {
return new HttpServerCodec();
}
})
.withAggregator(new XioAggregatorFactory() {
@Override
public ChannelHandler getAggregator() {
return new HttpObjectAggregator(16777216);
}
})
.build();
XioServerConfig serverConfig = new XioServerConfigBuilder()
.setBossThreadCount(2)
.setBossThreadExecutor(Executors.newCachedThreadPool())
.setWorkerThreadCount(2)
.setWorkerThreadExecutor(Executors.newCachedThreadPool())
.setTimer(timer)
.setXioName("Xio Name Test")
.build();
DefaultChannelGroup defaultChannelGroup;
if (System.getProperty("os.name") == "Linux") {
defaultChannelGroup = new DefaultChannelGroup(new EpollEventLoopGroup().next());
} else {
defaultChannelGroup = new DefaultChannelGroup(new NioEventLoopGroup().next());
}
// Create the server transport
final XioServerTransport server = new XioServerTransport(serverDef,
serverConfig, defaultChannelGroup);
// Start the server
server.start();
// Use 3rd party client to test proper operation
Request request = new Request.Builder()
.url("http://127.0.0.1:8083/")
.build();
OkHttpClient client = new OkHttpClient();
Response response = client.newCall(request).execute();
String expectedResponse = "WELCOME TO THE WILD WILD WEB SERVER\r\n" +
"===================================\r\n" +
"VERSION: HTTP/1.1\r\n" +
"HOSTNAME: 127.0.0.1:8083\r\n" +
"REQUEST_URI: /\r\n" +
"\r\n" +
"HEADER: Host = 127.0.0.1:8083\r\n" +
"HEADER: Connection = Keep-Alive\r\n" +
"HEADER: Accept-Encoding = gzip\r\n" +
"HEADER: User-Agent = okhttp/2.4.0\r\n" +
"HEADER: Content-Length = 0\r\n\r\n";
assertTrue(response.isSuccessful());
assertEquals(200, response.code());
assertEquals(expectedResponse, response.body().string());
// Arrange to stop the server at shutdown
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
server.stop();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
});
}
@Test
public void testComplexServerConfigurationHttps() throws Exception {
XioServerDef serverDef = new XioServerDefBuilder()
.clientIdleTimeout(new Duration((double) 200, TimeUnit.MILLISECONDS))
.limitConnectionsTo(200)
.limitFrameSizeTo(1024)
.limitQueuedResponsesPerConnection(50)
.listen(new InetSocketAddress(8087))
// .listen(new InetSocketAddress("127.0.0.1", 8082))
.name("Xio Test Server")
.taskTimeout(new Duration((double) 20000, TimeUnit.MILLISECONDS))
.using(Executors.newCachedThreadPool())
.withSecurityFactory(new XioTestSecurityFactory())
.withProcessorFactory(new XioTestProcessorFactory())
.withRoutingFilter(() -> new XioNoOpHandler())
.withCodecFactory(new XioCodecFactory() {
@Override
public ChannelHandler getCodec() {
return new HttpServerCodec();
}
})
.withAggregator(new XioAggregatorFactory() {
@Override
public ChannelHandler getAggregator() {
return new HttpObjectAggregator(16777216);
}
}).build();
XioServerConfig serverConfig = new XioServerConfigBuilder()
.setBossThreadCount(2)
.setBossThreadExecutor(Executors.newCachedThreadPool())
.setWorkerThreadCount(2)
.setWorkerThreadExecutor(Executors.newCachedThreadPool())
.setTimer(timer)
.setXioName("Xio Name Test")
.build();
DefaultChannelGroup defaultChannelGroup;
if (System.getProperty("os.name") == "Linux") {
defaultChannelGroup = new DefaultChannelGroup(new EpollEventLoopGroup().next());
} else {
defaultChannelGroup = new DefaultChannelGroup(new NioEventLoopGroup().next());
}
// Create the server transport
final XioServerTransport server = new XioServerTransport(serverDef,
serverConfig, defaultChannelGroup);
// Start the server
server.start();
// Use 3rd party client to test proper operation
Request request = new Request.Builder()
.url("https://127.0.0.1:8087/")
.build();
Response response = OkHttpUnsafe.getUnsafeClient().newCall(request).execute();
String expectedResponse = "WELCOME TO THE WILD WILD WEB SERVER\r\n" +
"===================================\r\n" +
"VERSION: HTTP/1.1\r\n" +
"HOSTNAME: 127.0.0.1:8087\r\n" +
"REQUEST_URI: /\r\n" +
"\r\n" +
"HEADER: Host = 127.0.0.1:8087\r\n" +
"HEADER: Connection = Keep-Alive\r\n" +
"HEADER: Accept-Encoding = gzip\r\n" +
"HEADER: User-Agent = okhttp/2.4.0\r\n" +
"HEADER: Content-Length = 0\r\n\r\n";
assertEquals(200, response.code());
assertEquals(expectedResponse, response.body().string());
// Arrange to stop the server at shutdown
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
server.stop();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
});
}
@Test
public void testSimpleProxy() throws Exception {
SimpleTestServer testServer = new SimpleTestServer(8089);
testServer.run();
XioServerDef serverDef = new XioServerDefBuilder()
.clientIdleTimeout(new Duration((double) 200, TimeUnit.MILLISECONDS))
.limitConnectionsTo(200)
.limitFrameSizeTo(1024)
.limitQueuedResponsesPerConnection(50)
.listen(new InetSocketAddress(8088))
// .listen(new InetSocketAddress("127.0.0.1", 8082))
.name("Xio Test Server")
.taskTimeout(new Duration((double) 20000, TimeUnit.MILLISECONDS))
.using(Executors.newCachedThreadPool())
.withSecurityFactory(new XioTestSecurityFactory())
.withRoutingFilter(() -> new XioNoOpHandler())
.withProcessorFactory(new XioProcessorFactory() {
@Override
public XioProcessor getProcessor() {
return new XioProcessor() {
@Override
public void disconnect(ChannelHandlerContext ctx) {
}
@Override
public ListenableFuture<Boolean> process(ChannelHandlerContext ctx, Object request, RequestContext reqCtx) {
final ListeningExecutorService service = MoreExecutors.listeningDecorator(ctx.executor());
ListenableFuture<Boolean> httpResponseFuture = service.submit(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
final Lock lock = new ReentrantLock();
final Condition waitForFinish = lock.newCondition();
final XioClient xioClient = new XioClient();
ListenableFuture<XioClientChannel> responseFuture = null;
responseFuture = xioClient.connectAsync(ctx, new HttpClientConnector(new URI("http://localhost:8089")), new BoundedExponentialBackoffRetry(100, 10000, 3));
XioClientChannel xioClientChannel = null;
if (!responseFuture.isCancelled()) {
xioClientChannel = responseFuture.get((long) 2000, TimeUnit.MILLISECONDS);
}
HttpClientChannel httpClientChannel = (HttpClientChannel) xioClientChannel;
Map<String, String> headerMap = ImmutableMap.of(
HttpHeaders.HOST, "localhost:8089",
HttpHeaders.USER_AGENT, "xio/0.7.8",
HttpHeaders.CONTENT_TYPE, "application/text",
HttpHeaders.ACCEPT_ENCODING, "*/*"
);
httpClientChannel.setHeaders(headerMap);
Listener<ByteBuf> listener = new Listener<ByteBuf>() {
ByteBuf response;
@Override
public void onRequestSent() {
// System.out.println("Request Sent");
}
@Override
public void onResponseReceived(ByteBuf message) {
response = message;
lock.lock();
waitForFinish.signalAll();
lock.unlock();
}
@Override
public void onChannelError(XioException requestException) {
StringBuilder sb = new StringBuilder();
sb.append(HttpVersion.HTTP_1_1)
.append(" ")
.append(HttpResponseStatus.INTERNAL_SERVER_ERROR)
.append("\r\n")
.append("\r\n\r\n")
.append(requestException.getMessage())
.append("\n");
response = Unpooled.wrappedBuffer(sb.toString().getBytes());
lock.lock();
waitForFinish.signalAll();
lock.unlock();
}
@Override
public ByteBuf getResponse() {
return response;
}
};
httpClientChannel.sendAsynchronousRequest(Unpooled.EMPTY_BUFFER, false, listener);
lock.lock();
waitForFinish.await();
lock.unlock();
DefaultFullHttpResponse httpResponse = BBtoHttpResponse.getResponse(listener.getResponse());
assertEquals(HttpResponseStatus.OK, httpResponse.getStatus());
assertEquals("Jetty(9.3.1.v20150714)", httpResponse.headers().get("Server"));
assertEquals("CONGRATS!\n\r\n", httpResponse.content().toString(Charset.defaultCharset()));
reqCtx.setContextData(reqCtx.getConnectionId(), httpResponse);
return true;
}
});
return httpResponseFuture;
}
};
}
})
.withCodecFactory(new XioCodecFactory() {
@Override
public ChannelHandler getCodec() {
return new HttpServerCodec();
}
})
.withAggregator(new XioAggregatorFactory() {
@Override
public ChannelHandler getAggregator() {
return new HttpObjectAggregator(16777216);
}
})
.build();
XioServerConfig serverConfig = new XioServerConfigBuilder()
.setBossThreadCount(2)
.setBossThreadExecutor(Executors.newCachedThreadPool())
.setWorkerThreadCount(2)
.setWorkerThreadExecutor(Executors.newCachedThreadPool())
.setTimer(timer)
.setXioName("Xio Name Test")
.build();
DefaultChannelGroup defaultChannelGroup;
if (System.getProperty("os.name") == "Linux") {
defaultChannelGroup = new DefaultChannelGroup(new EpollEventLoopGroup().next());
} else {
defaultChannelGroup = new DefaultChannelGroup(new NioEventLoopGroup().next());
}
// Create the server transport
final XioServerTransport server = new XioServerTransport(serverDef,
serverConfig, defaultChannelGroup);
// Start the server
server.start();
// Use 3rd party client to test proper operation
Request request = new Request.Builder()
.url("https://127.0.0.1:8088/")
.build();
Response response = OkHttpUnsafe.getUnsafeClient().newCall(request).execute();
assertEquals(200, response.code());
assertEquals("CONGRATS!\n", response.body().string());
// Arrange to stop the server at shutdown
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
server.stop();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
});
}
@Test
public void testComplexProxy() throws Exception {
XioServerDef serverDef = new XioServerDefBuilder()
.clientIdleTimeout(new Duration((double) 200, TimeUnit.MILLISECONDS))
.limitConnectionsTo(200)
.limitFrameSizeTo(1024)
.limitQueuedResponsesPerConnection(50)
.listen(new InetSocketAddress(8090))
// .listen(new InetSocketAddress("127.0.0.1", 8082))
.name("Xio Test Server")
.taskTimeout(new Duration((double) 20000, TimeUnit.MILLISECONDS))
.using(Executors.newCachedThreadPool())
.withSecurityFactory(new XioTestSecurityFactory())
.withRoutingFilter(() -> new XioNoOpHandler())
.withProcessorFactory(new XioProcessorFactory() {
@Override
public XioProcessor getProcessor() {
return new XioProcessor() {
@Override
public void disconnect(ChannelHandlerContext ctx) {
}
@Override
public ListenableFuture<Boolean> process(ChannelHandlerContext ctx, Object request, RequestContext reqCtx) {
final ListeningExecutorService service = MoreExecutors.listeningDecorator(ctx.executor());
ListenableFuture<Boolean> httpResponseFuture = service.submit(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
final Lock lock = new ReentrantLock();
final Condition waitForFinish = lock.newCondition();
final XioClientConfig xioClientConfig = XioClientConfig.newBuilder()
.setSecurityFactory(new XioSecurityFactory() {
@Override
public XioSecurityHandlers getSecurityHandlers(XioServerDef def, XioServerConfig serverConfig) {
return null;
}
@Override
public XioSecurityHandlers getSecurityHandlers() {
return new XioSecurityHandlers() {
@Override
public ChannelHandler getAuthenticationHandler() {
return new XioNoOpHandler();
}
@Override
public ChannelHandler getEncryptionHandler() {
try {
SslContext sslCtx = SslContextBuilder
.forClient()
.trustManager(InsecureTrustManagerFactory.INSTANCE)
.build();
return sslCtx.newHandler(new PooledByteBufAllocator());
} catch (SSLException e) {
e.printStackTrace();
}
return null;
}
};
}
})
.build();
final XioClient xioClient = new XioClient(xioClientConfig);
final ListenableFuture<XioClientChannel> responseFuture = xioClient.connectAsync(ctx, new HttpClientConnector(new URI("https:
XioClientChannel xioClientChannel;
if (!responseFuture.isCancelled()) {
xioClientChannel = responseFuture.get((long) 2000, TimeUnit.MILLISECONDS);
} else {
throw new XioTransportException("Client Timeout");
}
HttpClientChannel httpClientChannel = (HttpClientChannel) xioClientChannel;
Map<String, String> headerMap = ImmutableMap.of(
HttpHeaders.HOST, "www.paypal.com",
HttpHeaders.USER_AGENT, "xio/0.7.8",
HttpHeaders.CONTENT_TYPE, "application/text",
HttpHeaders.ACCEPT_ENCODING, "*/*"
);
httpClientChannel.setHeaders(headerMap);
Listener<ByteBuf> listener = new Listener<ByteBuf>() {
ByteBuf response;
@Override
public void onRequestSent() {
// System.out.println("Request Sent");
}
@Override
public void onResponseReceived(ByteBuf message) {
response = message;
lock.lock();
waitForFinish.signalAll();
lock.unlock();
}
@Override
public void onChannelError(XioException requestException) {
StringBuilder sb = new StringBuilder();
sb.append(HttpVersion.HTTP_1_1)
.append(" ")
.append(HttpResponseStatus.INTERNAL_SERVER_ERROR)
.append("\r\n")
.append("\r\n\r\n")
.append(requestException.getMessage())
.append("\n");
response = Unpooled.wrappedBuffer(sb.toString().getBytes());
lock.lock();
waitForFinish.signalAll();
lock.unlock();
}
@Override
public ByteBuf getResponse() {
return response;
}
};
httpClientChannel.sendAsynchronousRequest(Unpooled.EMPTY_BUFFER, false, listener);
lock.lock();
waitForFinish.await();
lock.unlock();
DefaultFullHttpResponse httpResponse = BBtoHttpResponse.getResponse(listener.getResponse());
assertEquals(HttpResponseStatus.OK, httpResponse.getStatus());
// assertEquals("nginx/1.6.0", httpResponse.headers().get("Server"));
assertTrue(httpResponse.content() != null);
reqCtx.setContextData(reqCtx.getConnectionId(), httpResponse);
return true;
}
});
return httpResponseFuture;
}
};
}
})
.withCodecFactory(new XioCodecFactory() {
@Override
public ChannelHandler getCodec() {
return new HttpServerCodec();
}
})
.withAggregator(new XioAggregatorFactory() {
@Override
public ChannelHandler getAggregator() {
return new HttpObjectAggregator(16777216);
}
})
.build();
XioServerConfig serverConfig = new XioServerConfigBuilder()
.setBossThreadCount(2)
.setBossThreadExecutor(Executors.newCachedThreadPool())
.setWorkerThreadCount(2)
.setWorkerThreadExecutor(Executors.newCachedThreadPool())
.setTimer(timer)
.setXioName("Xio Name Test")
.build();
DefaultChannelGroup defaultChannelGroup;
if (System.getProperty("os.name") == "Linux") {
defaultChannelGroup = new DefaultChannelGroup(new EpollEventLoopGroup().next());
} else {
defaultChannelGroup = new DefaultChannelGroup(new NioEventLoopGroup().next());
}
// Create the server transport
final XioServerTransport server = new XioServerTransport(serverDef,
serverConfig, defaultChannelGroup);
// Start the server
server.start();
// Use 3rd party client to test proper operation
Request request = new Request.Builder()
.url("https://127.0.0.1:8090/")
.build();
Response response = OkHttpUnsafe.getUnsafeClient().newCall(request).execute();
assertEquals(200, response.code());
assertTrue(!response.body().string().isEmpty());
// Arrange to stop the server at shutdown
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
server.stop();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
});
}
} |
package gluu.scim.client;
import static org.testng.Assert.assertEquals;
import gluu.BaseScimTest;
import gluu.scim.client.model.ScimPerson;
import gluu.scim.client.model.ScimPersonAddresses;
import gluu.scim.client.model.ScimPersonEmails;
import gluu.scim.client.model.ScimPersonPhones;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.core.MediaType;
import org.apache.commons.io.FileUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Optional;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class ScimClientPersonWriteObjectTest extends BaseScimTest {
ScimPerson personToAdd;
ScimPerson personToUpdate;
String uid;
ScimClient client;
ScimResponse response;
ScimPerson person;
@Parameters({ "domainURL", "umaMetaDataUrl", "umaAatClientId", "umaAatClientJwks" , "umaAatClientKeyId" })
@BeforeTest
public void init(final String domain, final String umaMetaDataUrl, final String umaAatClientId, final String umaAatClientJwks, @Optional final String umaAatClientKeyId) {
try {
String jwks = FileUtils.readFileToString(new File(umaAatClientJwks));
client = ScimClient.umaInstance(domain, umaMetaDataUrl, umaAatClientId, jwks, umaAatClientKeyId);
response = null;
person = null;
List<String> schema = new ArrayList<String>();
schema.add("urn:scim:schemas:core:1.0");
personToAdd = new ScimPerson();
personToUpdate = new ScimPerson();
personToAdd.setSchemas(schema);
personToAdd.setUserName("scimClientTestPerson");
personToAdd.setPassword("test");
personToAdd.setDisplayName("scimClientTestPerson");
ScimPersonEmails email = new ScimPersonEmails();
email.setValue("scim@gluu.org");
email.setType("Work");
email.setPrimary("true");
personToAdd.getEmails().add(email);
ScimPersonPhones phone = new ScimPersonPhones();
phone.setType("Work");
phone.setValue("654-6509-263");
personToAdd.getPhoneNumbers().add(phone);
ScimPersonAddresses address = new ScimPersonAddresses();
address.setCountry("US");
address.setStreetAddress("random street");
address.setLocality("Austin");
address.setPostalCode("65672");
address.setRegion("TX");
address.setPrimary("true");
address.setType("Work");
address.setFormatted(address.getStreetAddress() + " " + address.getLocality() + " " + address.getPostalCode() + " " + address.getRegion() + " "
+ address.getCountry());
personToAdd.getAddresses().add(address);
personToAdd.setPreferredLanguage("US_en");
personToAdd.getName().setFamilyName("SCIM");
personToAdd.getName().setGivenName("SCIM");
personToUpdate = personToAdd;
personToUpdate.setDisplayName("SCIM");
} catch (IOException e) {
System.out.println("exception in reading fle " + e.getMessage());
}
}
@Test(groups = "a")
public void createPersonTest() throws Exception {
response = client.createPerson(personToAdd, MediaType.APPLICATION_JSON);
assertEquals(response.getStatusCode(), 201, "cold not Add the person, status != 201");
byte[] bytes = response.getResponseBody();
String responseStr = new String(bytes);
person = (ScimPerson) jsonToObject(responseStr, ScimPerson.class);
this.uid = person.getId();
}
@Test(groups = "a")
public void updatePersonTest() throws Exception {
response = client.updatePerson(personToUpdate, this.uid, MediaType.APPLICATION_JSON);
assertEquals(response.getStatusCode(), 200, "cold not update the person, status != 200");
}
@Test(dependsOnGroups = "a")
public void deletePersonTest() throws Exception {
response = client.deletePerson(this.uid);
assertEquals(response.getStatusCode(), 200, "cold not delete the person, status != 200");
}
private Object jsonToObject(String json, Class<?> clazz) throws Exception {
ObjectMapper mapper = new ObjectMapper();
Object clazzObject = mapper.readValue(json, clazz);
return clazzObject;
}
} |
package ua.comparison.image;
import static org.junit.Assert.assertEquals;
import static ua.comparison.image.ImageComparisonTools.createGUI;
import static ua.comparison.image.ImageComparisonTools.readImageFromResources;
import org.junit.Assert;
import org.junit.Test;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
/**
* Unit-level testing for {@link ImageComparisonTools} object.
*/
public class ImageComparisonToolsUnitTest {
@Test
public void testFrameMethod() throws IOException, URISyntaxException {
BufferedImage image = readImageFromResources( "result1.png" );
Frame resultFrame = createGUI( image );
assertEquals( resultFrame.getHeight(), 714 );
assertEquals( resultFrame.getWidth(), image.getWidth() );
}
@Test( expected = IllegalArgumentException.class )
public void testCheckCorrectImageSize() {
BufferedImage image1 = new BufferedImage(10, 10, 10);
BufferedImage image2 = new BufferedImage(12, 12, 10);
ImageComparisonTools.checkCorrectImageSize( image1, image2 );
}
@Test
public void testSaveImage() throws IOException, URISyntaxException {
BufferedImage image = readImageFromResources( "result1.png" );
String path = "build/test/correct/save/image.png";
ImageComparisonTools.saveImage( path, image );
Assert.assertTrue( new File( path ).exists() );
}
} |
package org.apache.commons.collections.iterators;
import java.util.Iterator;
import java.util.NoSuchElementException;
import org.apache.commons.collections.TestObject;
/**
* Base class for tetsing Iterator interface
*
* @author Morgan Delagrange
* @author Stephen Colebourne
*/
public abstract class TestIterator extends TestObject {
public TestIterator(String testName) {
super(testName);
}
public abstract Iterator makeEmptyIterator();
public abstract Iterator makeFullIterator();
/**
* Whether or not we are testing an iterator that can be
* empty. Default is true.
*
* @return true if Iterators can be empty
*/
public boolean supportsEmptyIterator() {
return true;
}
/**
* Whether or not we are testing an iterator that can contain
* elements. Default is true.
*
* @return true if Iterators can be empty
*/
public boolean supportsFullIterator() {
return true;
}
/**
* Whether or not we are testing an iterator that supports
* remove(). Default is true.
*
* @return true if Iterators can be empty
*/
public boolean supportsRemove() {
return true;
}
/**
* Should throw a NoSuchElementException.
*/
public void testEmptyIterator() {
if (supportsEmptyIterator() == false) {
return;
}
Iterator iter = makeEmptyIterator();
assertTrue("hasNext() should return false for empty iterators", iter.hasNext() == false);
try {
iter.next();
fail("NoSuchElementException must be thrown when Iterator is exhausted");
} catch (NoSuchElementException e) {
}
}
/**
* NoSuchElementException (or any other exception)
* should not be thrown for the first element.
* NoSuchElementException must be thrown when
* hasNext() returns false
*/
public void testFullIterator() {
if (supportsFullIterator() == false) {
return;
}
Iterator iter = makeFullIterator();
assertTrue("hasNext() should return true for at least one element", iter.hasNext());
try {
iter.next();
} catch (NoSuchElementException e) {
fail("Full iterators must have at least one element");
}
while (iter.hasNext()) {
iter.next();
}
try {
iter.next();
fail("NoSuchElementException must be thrown when Iterator is exhausted");
} catch (NoSuchElementException e) {
}
}
/**
* Test remove
*/
public void testRemove() {
Iterator it = makeFullIterator();
if (supportsRemove() == false) {
try {
it.remove();
} catch (UnsupportedOperationException ex) {}
return;
}
try {
it.remove();
fail();
} catch (IllegalStateException ex) {}
it.next();
it.remove();
try {
it.remove();
fail();
} catch (IllegalStateException ex) {}
}
} |
package com.ociweb.grove;
import com.ociweb.iot.maker.*;
import static com.ociweb.iot.grove.GroveTwig.*;
import static com.ociweb.iot.maker.Port.*;
public class IoTApp implements IoTSetup
{
private static final Port BUTTON_PORT = D3;
private static final Port RELAY_PORT = D7;
private static final Port BUZZER_PORT = D8;
@Override
public void declareConnections(Hardware c) {
c.connect(Button, BUTTON_PORT);
c.connect(Relay, RELAY_PORT);
c.connect(Buzzer, BUZZER_PORT);
}
@Override
public void declareBehavior(DeviceRuntime runtime) {
final CommandChannel channel1 = runtime.newCommandChannel(DYNAMIC_MESSAGING);
runtime.addDigitalListener((port, connection, time, value)->{
channel1.setValueAndBlock(BUZZER_PORT, value == 1, 500);//500 is the time in milliseconds that any
channel1.setValueAndBlock(RELAY_PORT, value ==1, 500); //further action is blocked
});
}
} |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package interfazdeusuario;
import interfazdeusuario.VistaAdministradorAlumnos;
import interfazdeusuario.VistaAdministradorPlanesDeEstudios;
/**
*
* @author Jorge
*/
public class VistaPrincipal extends javax.swing.JFrame {
/**
* Creates new form VistaPrincipal
*/
public VistaPrincipal() {
initComponents();
}
/**
* 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();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("CEEACCE");
jButton1.setText("Alumnos");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("Planes de Estudio");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setText("Cursos");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jButton4.setText("Calificaciones");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(57, 57, 57)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(72, 72, 72)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGap(193, 193, 193)
.addComponent(jLabel1)))
.addContainerGap(55, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addGap(31, 31, 31)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(43, 43, 43)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(34, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
new VistaAdministradorAlumnos().setVisible(true);
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
new VistaAdministradorPlanesDeEstudios().setVisible(true);
//ya no desaparece la ventana
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
// TODO add your handling code here:
new VistaAdministradorDeCalificaciones().setVisible(true);
}//GEN-LAST:event_jButton4ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
// TODO add your handling code here:
new VistaAdministradorDeCursos().setVisible(true);
}//GEN-LAST:event_jButton3ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/*
* Set the Nimbus look and feel
*/
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(VistaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(VistaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(VistaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(VistaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new VistaPrincipal().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JLabel jLabel1;
// End of variables declaration//GEN-END:variables
} |
package gui.editionView;
import entity.Model;
import gui.AbstractComponentPanel;
import gui.Lang;
import gui.MainFrame;
import gui.State;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ListIterator;
import java.util.Map;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
import solution.NotSatisfiableException;
import solution.SolverExecutionException;
import solution.SolverTestSAT4J;
import translation.TranslationError;
import translation.TranslatorSAT;
/**
*
* @author Skander
*/
public class ParentEditionPanel extends AbstractComponentPanel {
/**
* Creates new form FormulasPanel
*/
public ParentEditionPanel() {
initComponents();
editorPanelFormulas.initPalette(PalettePanel.PaletteType.FORMULA);
editorPanelSets.initPalette(PalettePanel.PaletteType.SET);
jFileChooser1.setCurrentDirectory(new File(".."));
jLabelErrorMessage.setText("");
}
/**
* 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() {
jFileChooser1 = new javax.swing.JFileChooser();
jOptionPane1 = new javax.swing.JOptionPane();
jTabbedPane1 = new javax.swing.JTabbedPane();
editorPanelFormulas = new gui.editionView.EditionPanel();
editorPanelSets = new gui.editionView.EditionPanel();
solverSelectionPanel1 = new gui.editionView.solverSelection.SolverSelectionPanel();
testButton = new javax.swing.JButton();
importButton = new javax.swing.JButton();
jLabelErrorMessage = new javax.swing.JLabel();
jLabelCaretPosition = new javax.swing.JLabel();
jComboBox1 = new javax.swing.JComboBox();
exportButton = new javax.swing.JButton();
jFileChooser1.setFileSelectionMode(JFileChooser.FILES_ONLY);
jFileChooser1.addChoosableFileFilter(new FileNameExtensionFilter("Touistl files(touistl)","touistl"));
jTabbedPane1.setToolTipText("");
jTabbedPane1.addTab("Formulas", editorPanelFormulas);
jTabbedPane1.addTab("Sets", editorPanelSets);
jTabbedPane1.addTab("Solver", solverSelectionPanel1);
testButton.setText("Test");
testButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
testButtonActionPerformed(evt);
}
});
importButton.setText("Import");
importButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
importButtonActionPerformed(evt);
}
});
jLabelErrorMessage.setForeground(new java.awt.Color(255, 0, 0));
jLabelErrorMessage.setText("<Error message>");
jLabelCaretPosition.setText("1:1");
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "SAT", "SMT" }));
exportButton.setText("Export");
exportButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exportButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 713, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabelCaretPosition)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabelErrorMessage)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(exportButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(importButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(testButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 510, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(testButton)
.addComponent(importButton)
.addComponent(jLabelCaretPosition)
.addComponent(jLabelErrorMessage)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(exportButton))
.addContainerGap())
);
}// </editor-fold>//GEN-END:initComponents
private void importButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_importButtonActionPerformed
switch(((MainFrame)(getRootPane().getParent())).state) {
case EDITION :
setState(State.EDITION);
importHandler();
break;
case EDITION_ERROR :
setState(State.EDITION_ERROR);
importHandler();
break;
case NO_RESULT :
// impossible
break;
case SINGLE_RESULT :
// impossible
break;
case FIRST_RESULT :
// impossible
break;
case MIDDLE_RESULT :
// impossible
break;
case LAST_RESULT :
// impossible
break;
default :
System.out.println("Undefined action set for the state : " + getState());
}
}//GEN-LAST:event_importButtonActionPerformed
private void testButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_testButtonActionPerformed
switch(((MainFrame)(getRootPane().getParent())).state) {
case EDITION :
jLabelErrorMessage.setText("");
State state = initResultView();
if (state != State.EDITION) {
setState(state);
getFrame().setViewToResults();
}
break;
case EDITION_ERROR :
// interdit
break;
case NO_RESULT :
// impossible
break;
case SINGLE_RESULT :
// impossible
break;
case FIRST_RESULT :
// impossible
break;
case MIDDLE_RESULT :
// impossible
break;
case LAST_RESULT :
// impossible
break;
default :
System.out.println("Undefined action set for the state : " + getState());
}
}//GEN-LAST:event_testButtonActionPerformed
private void exportButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportButtonActionPerformed
switch(((MainFrame)(getRootPane().getParent())).state) {
case EDITION :
setState(State.EDITION);
exportHandler();
break;
case EDITION_ERROR :
setState(State.EDITION_ERROR);
exportHandler();
break;
case NO_RESULT :
// impossible
break;
case SINGLE_RESULT :
// impossible
break;
case FIRST_RESULT :
// impossible
break;
case MIDDLE_RESULT :
// impossible
break;
case LAST_RESULT :
// impossible
break;
default :
System.out.println("Undefined action set for the state : " + getState());
} }//GEN-LAST:event_exportButtonActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private gui.editionView.EditionPanel editorPanelFormulas;
private gui.editionView.EditionPanel editorPanelSets;
private javax.swing.JButton exportButton;
private javax.swing.JButton importButton;
private javax.swing.JComboBox jComboBox1;
private javax.swing.JFileChooser jFileChooser1;
private javax.swing.JLabel jLabelCaretPosition;
private javax.swing.JLabel jLabelErrorMessage;
private javax.swing.JOptionPane jOptionPane1;
private javax.swing.JTabbedPane jTabbedPane1;
private gui.editionView.solverSelection.SolverSelectionPanel solverSelectionPanel1;
private javax.swing.JButton testButton;
// End of variables declaration//GEN-END:variables
private void importHandler() {
String path = "";
int returnVal;
getFrame().getClause().setFormules("");
getFrame().getClause().setSets("");
returnVal = jFileChooser1.showDialog(this, getFrame().getLang().getWord(Lang.EDITION_FILE_CHOOSER));
if (returnVal == JFileChooser.APPROVE_OPTION && jFileChooser1.getSelectedFile() != null) {
path = jFileChooser1.getSelectedFile().getPath();
try {
getFrame().getClause().uploadFile(path);
} catch(Exception e) {
//TODO handle error message
System.out.println("Error : Failed to load the file : " + path);
e.printStackTrace();
}
String text = getFrame().getClause().getFormules();
editorPanelFormulas.setText(text);
text = getFrame().getClause().getSets();
editorPanelSets.setText(text);
}
}
private void exportHandler() {
getFrame().getClause().setFormules("");
getFrame().getClause().setSets("");
getFrame().getClause().addFormules(editorPanelFormulas.getText());
getFrame().getClause().addSets(editorPanelSets.getText());
int returnVal = jFileChooser1.showOpenDialog(this);
try {
if(returnVal == JFileChooser.APPROVE_OPTION){
getFrame().getClause().saveToFile(jFileChooser1.getSelectedFile().getPath());
}
} catch (IOException e) {
String warningWindowTitle = getFrame().getLang().getWord(Lang.EDITION_EXPORT_FAILURE_TITLE);
String warningWindowText = getFrame().getLang().getWord(Lang.EDITION_EXPORT_FAILURE_TEXT);
JOptionPane.showMessageDialog(this,warningWindowText,warningWindowTitle,JOptionPane.ERROR_MESSAGE);
}
}
private void showErrorMessage(String message, String title) {
jOptionPane1.showMessageDialog(getParent(),
message,
title,
JOptionPane.ERROR_MESSAGE);
}
private void showErrorMessage(Exception e, String message, String title) {
showErrorMessage(message, title);
FileWriter writer = null;
String texte = String.valueOf(e.getStackTrace()) + "\n" + "
try{
writer = new FileWriter("log.txt", true);
writer.write(texte,0,texte.length());
}catch(IOException ex){
ex.printStackTrace();
}finally{
if(writer != null){
try {
writer.close();
} catch (IOException ex) {
e.printStackTrace();
}
}
}
}
private TranslationError guiTranslationErrorAdapter(TranslationError error) {
TranslatorSAT t = new TranslatorSAT("");
TranslationError adaptedError;
int row = error.getRowInCode();
String sets = getFrame().getClause().getSets();
int nbRowsInSets = 1;
int setShift = (getFrame().getClause().getSets().isEmpty()) ? 0 : -1; // -1 pour tenir compte de "begin sets";
int formulasShift = (getFrame().getClause().getSets().isEmpty()) ? 0 : -3; // -3 pour tenir compte de "begin sets", "end sets" et "begin formulas"
for (int i=0; i<sets.length(); i++) {
if (sets.charAt(i) == '\n') {
nbRowsInSets++;
}
}
if (row < nbRowsInSets) {
// l'erreur est dans les sets
adaptedError = new TranslationError(row - setShift,
error.getColumnInCode(),
error.getErrorMessage() + getFrame().getLang().getWord(Lang.ERROR_TRADUCTION_IN_SETS));
} else {
// l'erreur est dans les formules
adaptedError = new TranslationError(row-nbRowsInSets - formulasShift,
error.getColumnInCode(),
error.getErrorMessage() + getFrame().getLang().getWord(Lang.ERROR_TRADUCTION_IN_FORMULAS));
}
return adaptedError;
}
private State initResultView() {
// Initialisation de BaseDeClause
getFrame().getClause().setFormules("");
getFrame().getClause().setSets("");
getFrame().getClause().addFormules(editorPanelFormulas.getText());
getFrame().getClause().addSets(editorPanelSets.getText());
String bigAndFilePath = "bigAndFile-defaultname.txt";
String errorMessage;
try {
getFrame().getClause().saveToFile(bigAndFilePath);
} catch (IOException ex) {
ex.printStackTrace();
errorMessage = "Couldn't create file '" + bigAndFilePath + "'";
showErrorMessage(errorMessage, getFrame().getLang().getWord(Lang.ERROR_TRADUCTION));
System.exit(0);
return State.EDITION;
}
try {
if(! getFrame().getTranslator().translate(bigAndFilePath)) {
errorMessage = "";
for(int i=0; i<getFrame().getTranslator().getErrors().size(); i++) {
TranslationError error = guiTranslationErrorAdapter(getFrame().getTranslator().getErrors().get(i));
errorMessage += error + "\n";
}
jLabelErrorMessage.setText(errorMessage);
System.out.println("Traduction error : " + "\n" + errorMessage + "\n");
showErrorMessage(errorMessage, getFrame().getLang().getWord(Lang.ERROR_TRADUCTION));
return State.EDITION;
}
File f = new File(bigAndFilePath);
f.deleteOnExit();
} catch (IOException ex) {
ex.printStackTrace();
errorMessage = "The translator returned an IOException: \n"+ex.getMessage();
showErrorMessage(ex, errorMessage, getFrame().getLang().getWord(Lang.ERROR_TRADUCTION));
return State.EDITION;
} catch (InterruptedException ex) {
ex.printStackTrace();
errorMessage = "Translator has been interrupted.";
showErrorMessage(ex, errorMessage, getFrame().getLang().getWord(Lang.ERROR_TRADUCTION));
return State.EDITION;
}
//Add CurrentPath/dimacsFile
String translatedFilePath = getFrame().getTranslator().getDimacsFilePath();
Map<Integer, String> literalsMap = getFrame().getTranslator().getLiteralsMap();
getFrame().setSolver(new SolverTestSAT4J(translatedFilePath, literalsMap));
try {
getFrame().getSolver().launch();
} catch (IOException ex) {
ex.printStackTrace();
errorMessage = "Couldn't launch solver.";
showErrorMessage(ex, errorMessage, "Solver error");
return State.EDITION;
}
if(! getFrame().getSolver().isSatisfiable()) {
System.out.println("Error : unsatisfiable");
}
// Si il y a au moins un model
try {
ListIterator<Model> iter = (ListIterator<Model>) getFrame().getSolver().getModelList().iterator();
getFrame().updateResultsPanelIterator(iter);
if (iter.hasNext()) {
getFrame().setResultView(iter.next());
if (iter.hasNext()) {
//iter.previous();
return State.FIRST_RESULT;
} else {
//iter.previous();
return State.SINGLE_RESULT;
}
} else {
return State.SINGLE_RESULT;
}
} catch (NotSatisfiableException ex) {
ex.printStackTrace();
errorMessage = "There is no solution.";
showErrorMessage(ex, errorMessage, "Solver error");
return State.EDITION;
} catch (SolverExecutionException ex) {
ex.printStackTrace();
errorMessage = "The solver encountered a problem.";
showErrorMessage(ex, errorMessage, "Solver error");
return State.EDITION;
}
//return State.NO_RESULT;
}
public void setJLabelCaretPositionText(String text) {
jLabelCaretPosition.setText(text);
}
@Override
public void updateLanguage() {
importButton.setText(getFrame().getLang().getWord(Lang.EDITION_IMPORT));
exportButton.setText(getFrame().getLang().getWord(Lang.EDITION_EXPORT));
testButton.setText(getFrame().getLang().getWord(Lang.EDITION_TEST));
editorPanelFormulas.updateLanguage();
editorPanelSets.updateLanguage();
jTabbedPane1.setTitleAt(0, getFrame().getLang().getWord(Lang.EDITION_TAB_FORMULAS));
jTabbedPane1.setTitleAt(1, getFrame().getLang().getWord(Lang.EDITION_TAB_SETS));
updateUI();
}
} |
package ch.ice.controller;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.json.JSONArray;
import org.json.JSONObject;
import ch.ice.controller.parser.ExcelParser;
import ch.ice.exceptions.IllegalFileExtensionException;
import ch.ice.model.Customer;
import ch.ice.utils.JSONUtil;
/**
* @author Oliver
*
*/
public class MainController {
private static final Logger logger = LogManager
.getLogger(MainController.class.getName());
ExcelParser excelParserInstance;
public static File file;
public void startMainController() {
PropertiesConfiguration config;
List<String> metaTagElements = new ArrayList<String>();
// retrieve all customers from file
logger.info("Retrieve Customers from File posTest.xlsx");
LinkedList<Customer> customerList = retrieveCustomerFromFile(file);
// Core settings
boolean isSearchAvail = false;
URL defaultUrl = null;
/*
* Load Configuration File
*/
try {
config = new PropertiesConfiguration("conf/app.properties");
isSearchAvail = config.getBoolean("core.search.isEnabled");
defaultUrl = new URL(config.getString("core.search.defaultUrl"));
metaTagElements = Arrays.asList(config
.getStringArray("crawler.searchForMetaTags"));
} catch (ConfigurationException | MalformedURLException e) {
logger.error("Faild to load config file");
System.out.println(e.getLocalizedMessage());
e.printStackTrace();
}
WebCrawler wc = new WebCrawler();
for (Customer customer : customerList) {
// only search via SearchEngine if search is enabled. Disable search
// for testing purpose
if (isSearchAvail) {
// Add url for customer
URL retrivedUrl = searchForUrl(customer);
customer.getWebsite().setUrl(retrivedUrl);
} else {
customer.getWebsite().setUrl(defaultUrl);
}
// add metadata
try {
wc.connnect(customer.getWebsite().getUrl().toString());
customer.getWebsite().setMetaTags(
wc.getMetaTags(metaTagElements));
} catch (IOException e) {
e.printStackTrace();
}
logger.info(customer.getWebsite().toString());
}
/*
* Write every enhanced customer object into a new file
*/
this.startWriter(customerList);
logger.info("end");
}
public URL searchForUrl(Customer c) {
ArrayList<String> params = new ArrayList<String>();
params.add(c.getFullName().toLowerCase());
params.add(c.getCountryName().toLowerCase());
String query = BingSearchEngine.buildQuery(params);
logger.info("start searchEngine for URL with query: " + query);
try {
// Start Search
JSONArray results = BingSearchEngine.Search(query);
// logger.debug(results.toString());
// logic to pick the first record ; here should be the search logic!
results = JSONUtil.cleanUp(results);
JSONObject aResult = results.getJSONObject(0);
// return only the URL form first object
return new URL((String) aResult.get("Url"));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* Each Row returns a customer object. These customers are saved in an
* List-Object.
*
* @param file
* @return LinkedList<Customer>
*/
public LinkedList<Customer> retrieveCustomerFromFile(File file) {
this.excelParserInstance = new ExcelParser();
try {
// retrieve all Customers from list
return this.excelParserInstance.readFile(file);
} catch (IOException | IllegalFileExtensionException
| EncryptedDocumentException | InvalidFormatException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
return new LinkedList<Customer>();
}
public void startWriter(List<Customer> customerList) {
// TODO Check if user demands CSV or EXCEL -> if(excel)->getWorkbook,
// Else ->write normal
// ExcelWriter ew = new
// ExcelWriter(this.excelParserInstance.getWorkbook());
logger.info("Start writing customers to File");
ExcelWriter ew = new ExcelWriter();
ew.writeFile(customerList, this.excelParserInstance.getWorkbook());
}
} |
package uk.gov.dvla.domain;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.annotations.Indexed;
import com.google.code.morphia.annotations.Property;
@Entity(value = "drivers", noClassnameStored = true)
public class Driver extends Person {
private List<DriverNumber> dlnHistory;
private List<DriverFlag> flag;
private List<Licence> licence;
private List<Integer> stopMarker;
private List<Integer> restrictionKey;
private List<String> caseType;
private List<String> errorCode;
private Boolean carHireEnqPmt = null;
private String statusCode = null;
private Date photoExpiryDate;
private List<String> disqualificationStatusCodes;
private boolean nslInCorruptedRange;
@Property("dln")
@Indexed(unique = true)
private String currentDriverNumber = null;
public void addLicence(Licence lic) {
if (null == licence) {
licence = new ArrayList<Licence>();
}
licence.add(lic);
}
public void addStopMarker(Integer marker) {
if (null == stopMarker) {
stopMarker = new ArrayList<Integer>();
}
stopMarker.add(marker);
}
public void addRestrictionKey(Integer key) {
if (null == restrictionKey) {
restrictionKey = new ArrayList<Integer>();
}
restrictionKey.add(key);
}
public void addCaseType(String key) {
if (null == caseType) {
caseType = new ArrayList<String>();
}
caseType.add(key);
}
public void addErrorCode(String code) {
if (null == errorCode) {
errorCode = new ArrayList<String>();
}
errorCode.add(code);
}
public void setLicence(List<Licence> lics) {
licence = lics;
}
public List<Licence> getLicence() {
return this.licence;
}
public List<Integer> getStopMarker() {
return stopMarker;
}
public void setStopMarker(List<Integer> markers) {
this.stopMarker = markers;
}
public List<Integer> getRestrictionKey() {
return restrictionKey;
}
public void setRestrictionKey(List<Integer> keys) {
this.restrictionKey = keys;
}
public List<String> getCaseType() {
return this.caseType;
}
public void setCaseType(List<String> caseTypes) {
this.caseType = caseTypes;
}
public List<String> getErrorCode() {
return this.errorCode;
}
public void setErrorCode(List<String> errorCodes) {
this.errorCode = errorCodes;
}
public void setCurrentDriverNumber(String dln) {
this.currentDriverNumber = dln;
}
public String getCurrentDriverNumber() {
return this.currentDriverNumber;
}
public List<DriverNumber> getDriverNumberHistory() {
return dlnHistory;
}
public void setDriverNumberHistory(List<DriverNumber> driverNumber) {
this.dlnHistory = driverNumber;
}
public List<DriverFlag> getFlag() {
return flag;
}
public void setFlag(List<DriverFlag> flag) {
this.flag = flag;
}
public Boolean getCarHireEnqPmt() {
return carHireEnqPmt;
}
public void setCarHireEnqPmt(Boolean carHireEnqPmt) {
this.carHireEnqPmt = carHireEnqPmt;
}
public String getStatusCode() {
return statusCode;
}
public void setStatusCode(String statusCode) {
this.statusCode = statusCode;
}
public Date getPhotoExpiryDate() {
return photoExpiryDate;
}
public void setPhotoExpiryDate(Date photoExpiryDate) {
this.photoExpiryDate = photoExpiryDate;
}
public List<String> getDisqualificationStatusCodes() {
return disqualificationStatusCodes;
}
public void setDisqualificationStatusCodes(List<String> disqualificationStatusCodes) {
this.disqualificationStatusCodes = disqualificationStatusCodes;
}
public Boolean getNslInCorruptedRange() {
return nslInCorruptedRange;
}
public void setNslInCorruptedRange(Boolean nslInCorruptedRange) {
this.nslInCorruptedRange = nslInCorruptedRange;
}
} |
package org.whiteboard.gradebook;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.io.File;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Scanner;
/**
* Handles the user interface of the gradebook
*
* @author Patrick Fox fox.pat@husky.neu.edu
* @version 1.0
*/
public class Console {
/**
* The gradebook representing this class
*/
private MyGradeBook gb;
/**
* The scanner used to receive user input
*/
Scanner s;
/**
* Creates a new Console with a scanner but no gradebook(null)
*/
public Console() {
s = new Scanner(System.in);
gb = null;
}
/**
* Runs the program
*
* @param args
* command line arguments
*/
public static void main(String[] args) {
Console c = new Console();
c.runMain();
}
/**
* Runs the initial prompt for a user
*/
private void runMain() {
String[] prompts = {
"Welcome to the gradebook!",
"Enter 'quit' at any time without the quotes to close the program.",
"Please enter a file name to import a gradebook from,",
"Or type 'empty' to create a new one from scratch",
"Please make a choice and hit enter: " };
for (String s : prompts) {
System.out.println(s);
}
System.out.println();
String gbInit = getInput();
if (gbInit.equalsIgnoreCase("empty")) {
gb = MyGradeBook.initialize();
System.out.println("New empty GradeBook created");
}
else {
System.out.println("Initializing from a file...");
try {
gb = MyGradeBook.initializeWithFile(gbInit);
}
catch (FileNotFoundException e) {
System.out.println("No such file found."
+ " Please re-run the program.");
System.exit(0);
}
}
runOptions();
}
/**
* Runs the secondary list of options to modify a gradebook
*/
private void runOptions() {
String[] prompts = { "(1) Add students", "(2) Add assignments",
"(3) Add a grade", "(4) Change student grades",
"(5) Calculate statistics for an assignment",
"(6) Get information for a student",
"(7) Output entire gradebook to a file",
"(8) Output Assignment information to a file",
"(9) Output Student information to a file",
"(10) Output Grade Information to a file",
"(11) Print entire gradebook to console",
"Please make a choice and hit enter: " };
System.out.println("What would you like to do?");
for (String s : prompts) {
System.out.println(s);
}
int in = getInputInt(1, 11);
switch (in) {
case 1:
addStudents();
break;
case 2:
addAssignments();
break;
case 3:
addGrade();
break;
case 4:
changeGrade();
break;
case 5:
calcStats();
break;
case 6:
getStudentInfo();
break;
case 7:
outputGradeBook();
break;
case 8:
outputAss();
break;
case 9:
outputStudent();
break;
case 10:
outputGrades();
break;
case 11:
printGradeBook();
break;
default:
break;
}
System.out.println("Done! Returning to the main menu...\n\n");
runOptions();
}
/**
* Gets a single line of user input and Closes the program if 'quit' is
* entered (case insensitive)
*
* @return the next line of input as a string
*/
private String getInput() {
String in = s.nextLine();
if (in.equalsIgnoreCase("quit")) {
System.out.println("Goodbye.");
System.exit(0);
}
return in;
}
/**
* Gets user input as an int. Re-prompts the user if the input is not an int
* or is not between min and max
*
* @param min
* the minimum value for the input
* @param max
* the maximum value for the input
* @return the inputed integer
*/
private int getInputInt(int min, int max) {
boolean flag = true;
int in = 0;
do {
try {
String inputString = getInput();
in = Integer.parseInt(inputString);
if (in > max || in < min) {
System.out.println("Invaid input. Please try again");
flag = true;
}
else {
flag = false;
}
}
catch (NumberFormatException e) {
System.out.println("Invaid input. Please try again");
flag = true;
}
}
while (flag);
return in;
}
private double getInputDouble() {
boolean flag = true;
double in = 0.0;
do {
try {
String input = getInput();
in = Double.parseDouble(input);
flag = false;
}
catch (NumberFormatException e) {
System.out.println("Invalid input. Please try again.");
flag = true;
}
}
while (flag);
return in;
}
/**
* Prompts the user to input student information and processes it
*/
private void addStudents() {
System.out.println("Would you like to: \n"
+ "(1) input Student information manually\n"
+ "(2) Import Student information from a file");
int in = getInputInt(1, 2);
if (in == 1) {
//TODO
String newStudent = "STUDENT\n";
System.out.println("Enter the desired Username:");
newStudent += getInput() + "\n";
System.out.println("Enter the first name:");
newStudent += getInput() + "\n";
System.out.println("Enter the last name:");
newStudent += getInput() + "\n";
System.out.println("Enter the advsior's name:");
newStudent += getInput() + "\n";
System.out.println("Enter the graduation year:");
newStudent += getInput() + "\n";
try {
gb.processString(newStudent);
}
catch (RuntimeException e) {
System.out.println("Information is not formatted correctly.");
}
}
else {
System.out.println("Please enter the file name:");
String inString = getInput();
try {
gb.processFile(inString);
}
catch (RuntimeException e) {
System.out.println("Not a valid file name. Please try again.");
}
}
}
/**
* Prompts the user to input assignment information and processes it
*/
private void addAssignments() {
System.out.println("Would you like to: \n"
+ "(1) input Assignment information manually\n"
+ "(2) Import Assigment information from a file");
int in = getInputInt(1, 2);
if (in == 1) {
//TODO
String newAssignment = "ASSIGNMENT_GRADES\n";
System.out.println("Enter the name of the assignment:");
newAssignment += getInput() + "\n";
System.out.println("Enter the total points:");
newAssignment += getInput() + "\n";
System.out.println("Enter the percent of the total grade:");
newAssignment += getInput() + "\n";
newAssignment += "
System.out
.println("Enter each student's username, followed by a tab,"
+ " followed by their grade.");
System.out.println("Then enter 'done': ");
boolean finished = false;
while (!finished) {
String next = s.nextLine();
if (next.equals("done")) {
finished = true;
}
else {
newAssignment += next + "\n";
}
}
newAssignment += "----\nSTATS\n";
System.out.println("Enter the Average:");
newAssignment += "Average\t" + getInputDouble() + "\n";
System.out.println("Enter the Median:");
newAssignment += "Median\t" + getInputDouble() + "\n";
System.out.println("Enter the Max:");
newAssignment += "Max\t" + getInputDouble() + "\n";
System.out.println("Enter the Min:");
newAssignment += "Min\t" + getInputDouble() + "\n";
try {
System.out.println(newAssignment);
gb.processString(newAssignment);
}
catch (RuntimeException e) {
System.out.println("Information is not formatted correctly.");
System.out.println(e.getLocalizedMessage());
}
}
else {
System.out.println("Please enter the file name:");
String inString = getInput();
try {
gb.processFile(inString);
}
catch (RuntimeException e) {
System.out.println("Not a valid file name. Please try again.");
}
}
}
/**
* Prompts the user to input grade information and processes it
*/
private void addGrade() {
System.out.println("Would you like to:\n(1) initialize from a file\n"
+ "(2) Enter grades manually for an assignment\n"
+ "(3) Enter grades manually for a student");
int choice = getInputInt(1, 3);
if (choice == 1) {
//TODO
System.out.println("Please enter the file name:");
try {
gb.processFile(getInput());
}
catch(RuntimeException e) {
System.out.println("Not a valid file name. Please try again.");
}
}
else if (choice == 2) {
//TODO
}
else {
//TODO
}
}
/**
* Prompts the user to input grade information for one student and
* assignment and processes it
*/
private void changeGrade() {
boolean flag = false;
do {
System.out.println("Please enter the student's username:");
String stud = getInput();
System.out.println("Please enter the assignment name:");
String ass = getInput();
double newGrade = 0.0;
System.out
.println("Please enter the new grade, formatted as a decimal(ie 50.0): ");
try {
newGrade = Double.parseDouble(getInput());
gb.changeGrade(ass, stud, newGrade);
flag = false;
//TODO
//Enter wrong username but valid AssName/double -> passes
}
catch (NumberFormatException e) {
System.out.println("The grade was not a valid decimal");
flag = true;
}
catch (NoSuchElementException e) {
System.out.println("Invalid student or assignment name");
flag = true;
}
}
while (flag);
}
private void calcStats() {
System.out.println("Which assignment would you like to know about?");
boolean flag = false;
do {
String assName = getInput();
double average, median, min, max;
try {
min = gb.min(assName);
max = gb.max(assName);
average = gb.average(assName);
median = gb.median(assName);
System.out.println("Here are the stats for " + assName);
System.out.println("Mean: " + average);
System.out.println("Median: " + median);
System.out.println("Min: " + min);
System.out.println("Max: " + max);
flag = false;
}
catch (NoSuchElementException e) {
System.out.println("Not a valid assignment name. Please try again.");
flag = true;
}
}
while (flag);
}
private void getStudentInfo() {
System.out.println("Please enter the student's username: ");
boolean flag = false;
String name;
do {
name = getInput();
try {
System.out.println(gb.outputStudentGrades(name));
flag = false;
}
catch (NoSuchElementException e) {
System.out.println("Not a valid name. Please try again.");
flag = true;
}
}
while (flag);
}
private void writeToFile(String content, String fileName) {
File f = new File(fileName);
try {
PrintStream ps = new PrintStream(f);
ps.println(content);
ps.close();
}
catch (FileNotFoundException e) {
System.out.println("Error in creating the file");
}
}
private void outputGrades() {
System.out
.println("What would you like the file to be called? (no .txt suffix)");
String name = getInput() + ".txt";
String str = gb.outputCurrentGrades();
writeToFile(str, name);
}
private void outputStudent() {
boolean flag = false;
do {
System.out.println("What is the student's name?");
String name = getInput();
System.out.println("What would you like the student's "
+ "file to be called? (no .txt suffix)");
String fileName = getInput() + ".txt";
String str;
try {
str = gb.outputStudentGrades(name);
writeToFile(str, fileName);
flag = false;
}
catch (NoSuchElementException e) {
System.out.println("Not a valid student name. "
+ "Please try again.");
flag = true;
}
}
while (flag);
}
private void outputGradeBook() {
System.out
.println("What would you like the file to be called? (no .txt suffix)");
String name = getInput() + ".txt";
String str = gb.outputGradebook();
writeToFile(str, name);
}
private void outputAss() {
boolean flag = false;
do {
System.out.println("Which assignment are you outputting?");
String ass = getInput();
System.out.println("What would you like the assignment "
+ "file to be called? (no .txt suffix)");
String name = getInput() + ".txt";
try {
String str = gb.outputAssignmentGrades(ass);
writeToFile(str, name);
flag = false;
}
catch (NoSuchElementException e) {
System.out.println("No such file found.");
flag = true;
}
}
while (flag);
}
private void printGradeBook() {
String str = gb.outputGradebook();
System.out.println(str);
}
} |
package com.shopify.buy.model;
import android.text.TextUtils;
import com.google.gson.Gson;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.annotations.SerializedName;
import com.shopify.buy.dataprovider.BuyClientUtils;
import com.shopify.buy.utils.CollectionUtils;
import com.shopify.buy.utils.DateUtility;
import java.lang.reflect.Type;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* A {@code Product} is an individual item for sale in a Shopify store.
*/
public class Product extends ShopifyObject {
@SerializedName("product_id")
protected Long productId;
protected String title;
protected String handle;
@SerializedName("body_html")
protected String bodyHtml;
@SerializedName("published_at")
protected Date publishedAtDate;
@SerializedName("created_at")
protected Date createdAtDate;
@SerializedName("updated_at")
protected Date updatedAtDate;
protected String vendor;
@SerializedName("product_type")
protected String productType;
protected List<ProductVariant> variants;
protected List<Image> images;
protected List<Option> options;
protected String tags;
protected Set<String> tagSet;
protected Boolean available;
protected Boolean published;
protected Set<String> prices;
protected String minimumPrice;
/**
* @return {@code true} if this product has been published on the store, {@code false} otherwise.
*/
public boolean isPublished() {
return published != null && published;
}
/**
* @return The unique identifier for this product.
*/
public Long getProductId() {
return productId;
}
/**
* @return The title of this product.
*/
public String getTitle() {
return title;
}
/**
* @return The handle of the product. Can be used to construct links to the web page for the product.
*/
public String getHandle() {
return handle;
}
/**
* @return The description of the product, complete with HTML formatting.
*/
public String getBodyHtml() {
return bodyHtml;
}
/**
* Use {@link #getPublishedAtDate() getPublishedAtDate()}.
*
* @return The date this product was published.
*/
@Deprecated
public String getPublishedAt() {
return publishedAtDate == null ? null : DateUtility.createDefaultDateFormat().format(publishedAtDate);
}
/**
* Use {@link #getCreatedAtDate() getCreatedAtDate()}.
*
* @return The date this product was created.
*/
@Deprecated
public String getCreatedAt() {
return createdAtDate == null ? null : DateUtility.createDefaultDateFormat().format(createdAtDate);
}
/**
* Use {@link #getUpdatedAtDate() getUpdatedAtDate()}.
*
* @return The date this product was updated.
*/
@Deprecated
public String getUpdatedAt() {
return updatedAtDate == null ? null : DateUtility.createDefaultDateFormat().format(updatedAtDate);
}
/**
* @return The date this product was published.
*/
public Date getPublishedAtDate() {
return publishedAtDate;
}
/**
* @return The date this product was created.
*/
public Date getCreatedAtDate() {
return createdAtDate;
}
/**
* @return The date this product was last updated.
*/
public Date getUpdatedAtDate() {
return updatedAtDate;
}
/**
* @return The name of the vendor of this product.
*/
public String getVendor() {
return vendor;
}
/**
* @return The categorization that this product was tagged with, commonly used for filtering and searching.
*/
public String getProductType() {
return productType;
}
/**
* @return A list of additional categorizations that a product can be tagged with, commonly used for filtering and searching. Each tag has a character limit of 255.
*/
public Set<String> getTags() {
return tagSet;
}
/**
* @return A list {@link ProductVariant} objects, each one representing a different version of this product.
*/
public List<ProductVariant> getVariants() {
return variants;
}
/**
* @return A list of {@link Image} objects, each one representing an image associated with this product.
*/
public List<Image> getImages() {
return images;
}
/**
* @return The first image URL from this Product's list of images.
*/
public String getFirstImageUrl() {
if (hasImage()) {
Image image = images.get(0);
if (image != null) {
return image.getSrc();
}
}
return null;
}
/**
* @return {code true} if this product has at least one image, {@code false} otherwise.
*/
public boolean hasImage() {
return images != null && !images.isEmpty();
}
/**
* @return A list of {@link Option} objects, which can be used to select a specific {@link ProductVariant}.
*/
public List<Option> getOptions() {
return options;
}
/**
* @return {@code true} if this product is in stock and available for purchase, {@code false} otherwise.
*/
public boolean isAvailable() {
return available != null && available;
}
/**
* For internal use only.
*
* @return true if this product has a default variant.
*/
public boolean hasDefaultVariant() {
if (CollectionUtils.isEmpty(variants) || variants.size() != 1) {
return false;
}
final List<OptionValue> optionValues = variants.get(0).getOptionValues();
if (CollectionUtils.isEmpty(optionValues) || optionValues.size() != 1) {
return false;
}
final OptionValue optionValue = optionValues.get(0);
return "Title".equals(optionValue.getName())
&& ("Default Title".equals(optionValue.getValue()) || "Default".equals(optionValue.getValue()));
}
/**
* Returns the {@code Image} for the {@code ProductVariant} with the given id
*
* @param variant the {@link ProductVariant} to find the {@link Image}
* @return the {@link Image} corresponding to the {@link ProductVariant} if one was found, otherwise the {@code Image} for the {@link Product}. This may return null if no applicable images were found.
*/
public Image getImage(ProductVariant variant) {
if (variant == null) {
throw new NullPointerException("variant cannot be null");
}
List<Image> images = getImages();
if (images == null || images.size() < 1) {
// we did not find any images
return null;
}
for (Image image : images) {
if (image.getVariantIds() != null && image.getVariantIds().contains(variant.getId())) {
return image;
}
}
// The variant did not have an image, use the default image in the Product
return images.get(0);
}
/**
* @param optionValues A list of {@link OptionValue} objects that represent a specific variant selection.
* @return The {@link ProductVariant} that matches the given list of the OptionValues, or {@code null} if no such variant exists.
*/
public ProductVariant getVariant(List<OptionValue> optionValues) {
if (optionValues == null) {
return null;
}
int numOptions = optionValues.size();
for (ProductVariant variant : variants) {
for (int i = 0; i < numOptions; i++) {
if (!variant.getOptionValues().get(i).getValue().equals(optionValues.get(i).getValue())) {
break;
} else if (i == numOptions - 1) {
return variant;
}
}
}
return null;
}
/**
* @return A Set containing all the unique prices of the variants.
*/
public Set<String> getPrices() {
if (prices != null) {
return prices;
}
prices = new HashSet<>();
if (!CollectionUtils.isEmpty(variants)) {
for (ProductVariant variant : variants) {
prices.add(variant.getPrice());
}
}
return prices;
}
/**
* @return The minimum price from the variants.
*/
public String getMinimumPrice() {
if (minimumPrice != null) {
return minimumPrice;
}
prices = getPrices();
for (String price : prices) {
if (minimumPrice == null) {
minimumPrice = price;
}
if (Float.valueOf(price) < Float.valueOf(minimumPrice)) {
minimumPrice = price;
}
}
return minimumPrice;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Product)) return false;
Product product = (Product) o;
return productId.equals(product.productId);
}
@Override
public int hashCode() {
return productId.hashCode();
}
public static class ProductDeserializer implements JsonDeserializer<Product> {
@Override
public Product deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return fromJson(json.toString());
}
}
/**
* A product object created using the values in the JSON string.
*
* @param json The json representation of this product.
* @return A {@link Product}
*/
public static Product fromJson(String json) {
Gson gson = BuyClientUtils.createDefaultGson(Product.class);
Product product = gson.fromJson(json, Product.class);
List<ProductVariant> variants = product.getVariants();
if (variants != null) {
for (ProductVariant variant : variants) {
variant.productId = product.productId;
variant.productTitle = product.getTitle();
Image image = product.getImage(variant);
if (image != null) {
variant.imageUrl = image.getSrc();
}
}
}
// Create the tagSet.
product.tagSet = new HashSet<>();
// Populate the tagSet from the comma separated list.
if (!TextUtils.isEmpty(product.tags)) {
for (String tag : product.tags.split(",")) {
String myTag = tag.trim();
product.tagSet.add(myTag);
}
}
return product;
}
} |
import static jouvieje.bass.Bass.BASS_ChannelPlay;
import static jouvieje.bass.Bass.BASS_ChannelSetPosition;
import static jouvieje.bass.Bass.BASS_ChannelSetSync;
import static jouvieje.bass.Bass.BASS_Free;
import static jouvieje.bass.Bass.BASS_GetVersion;
import static jouvieje.bass.Bass.BASS_Init;
import static jouvieje.bass.Bass.BASS_MusicLoad;
import static jouvieje.bass.Bass.BASS_Pause;
import static jouvieje.bass.Bass.BASS_SetVolume;
import static jouvieje.bass.Bass.BASS_Start;
import static jouvieje.bass.Bass.BASS_StreamCreateFile;
import static jouvieje.bass.defines.BASS_MUSIC.BASS_MUSIC_POSRESET;
import static jouvieje.bass.defines.BASS_MUSIC.BASS_MUSIC_PRESCAN;
import static jouvieje.bass.defines.BASS_MUSIC.BASS_MUSIC_RAMPS;
import static jouvieje.bass.defines.BASS_POS.BASS_POS_BYTE;
import static jouvieje.bass.defines.BASS_SYNC.BASS_SYNC_END;
import static jouvieje.bass.defines.BASS_SYNC.BASS_SYNC_MIXTIME;
import static jouvieje.bass.examples.util.Device.forceFrequency;
import static jouvieje.bass.examples.util.Device.forceNoSoundDevice;
import java.io.File;
import jouvieje.bass.BassInit;
import jouvieje.bass.callbacks.SYNCPROC;
import jouvieje.bass.structures.HMUSIC;
import jouvieje.bass.structures.HSTREAM;
import jouvieje.bass.structures.HSYNC;
import jouvieje.bass.utils.Pointer;
class RadicalBASS implements RadicalMusic {
/**
* Displays error messages
*
* @param text The error message to be displayed
*/
private final void error(final String text) {
System.err.println("RadicalBASS error: " + text);
}
/**
* Prints a formatted message then ends playback
*
* @param format String to be formatted
* @param args Formatting arguments
*/
private final void printfExit(final String format, final Object... args) {
System.out.println(String.format(format, args));
end();
}
static boolean init = false;
private boolean deinit = false;
/**
* The channel that NativeBASS will play to
*/
private int chan;
/**
* Loop start & end
*/
private final long[] loop = new long[2];
private final SYNCPROC loopSyncProc = new SYNCPROC() {
@Override
public void SYNCPROC(final HSYNC handle, final int channel, final int data, final Pointer user) {
if (!BASS_ChannelSetPosition(channel, loop[0], BASS_POS_BYTE)) { //Try seeking to loop start
BASS_ChannelSetPosition(channel, 0, BASS_POS_BYTE); //Failed, go to start of file instead
}
}
};
public void run() {
if (!init)
return;
// check the correct BASS was loaded
if ((BASS_GetVersion() & 0xFFFF0000) >> 16 != BassInit.BASSVERSION()) {
printfExit("An incorrect version of BASS.DLL was loaded");
return;
}
//Initialize BASS
if (!BASS_Init(forceNoSoundDevice(-1), forceFrequency(44100), 0, null, null)) {
error("Can't initialize device");
end();
}
if (!playFile()) {
//Start a file playing
end();
}
BASS_SetVolume(0.1F);
//Set update timer (10hz)
//timer.start();
}
private boolean playFile() {
HSTREAM stream = null;
HMUSIC music = null;
if ((stream = BASS_StreamCreateFile(false, file.getPath(), 0, 0, 0)) == null && (music = BASS_MusicLoad(false, file.getPath(), 0, 0, BASS_MUSIC_RAMPS | BASS_MUSIC_POSRESET | BASS_MUSIC_PRESCAN, 0)) == null) {
error("Can't play file");
return false; // Can't load the file
}
chan = stream != null ? stream.asInt() : music != null ? music.asInt() : 0;
BASS_ChannelSetSync(chan, BASS_SYNC_END | BASS_SYNC_MIXTIME, 0, loopSyncProc, null); //Set sync to loop at end
BASS_ChannelPlay(chan, false); //Start playing
return true;
}
public boolean isRunning() {
return deinit;
}
public void end() {
if (!init || deinit)
return;
deinit = true;
BASS_Free();
}
/* Graphical stuff */
private final File file;
private boolean started = false;
private final boolean paused = false;
public RadicalBASS(final File songFile) {
file = songFile;
//run();
}
@Override
public int getType() {
return TYPE_BASS;
}
@Override
public void resume() {
play();
}
@Override
public void unload() {
end();
}
@Override
public void play() {
if (started) {
/* Resume output */
BASS_Start();
} else {
run();
started = true;
}
}
@Override
public void setPaused(final boolean pause) {
if (pause) {
stop();
} else {
resume();
}
}
@Override
public boolean isPaused() {
return paused;
}
@Override
public void stop() {
/* Pause output */
BASS_Pause();
}
/*private JFileChooser getFileChooser() {
if(fileChooser == null) {
fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File("."));
fileChooser.setMultiSelectionEnabled(false);
fileChooser.resetChoosableFileFilters();
//fileChooser.addChoosableFileFilter(FileFilters.allFiles);
//fileChooser.addChoosableFileFilter(FileFilters.playableFiles);
fileChooser.setDialogTitle("Open a music");
}
return fileChooser;
}*/
} |
package org.drooms.api;
import java.util.Collection;
import org.drools.KnowledgeBase;
import org.drools.KnowledgeBaseConfiguration;
import org.drools.KnowledgeBaseFactory;
import org.drools.conf.PermGenThresholdOption;
import org.drools.definition.KnowledgePackage;
/**
* Represents a worm in the {@link Game} on the {@link Playground}.
*/
public class Player {
private final String name;
private final Collection<KnowledgePackage> packages;
private final ClassLoader classLoader;
/**
* Create a player instance.
*
* @param name
* Name of the player.
* @param knowledgePackages
* Rules that implement the player's strategy.
* @param strategyClassLoader
* Class loader used to load player's strategy.
*/
public Player(final String name, final Collection<KnowledgePackage> knowledgePackages, final ClassLoader strategyClassLoader) {
if (name == null || knowledgePackages == null || strategyClassLoader == null) {
throw new IllegalArgumentException(
"None of the parameters can be null.");
}
this.name = name;
this.packages = knowledgePackages;
this.classLoader = strategyClassLoader;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (this.getClass() != obj.getClass()) {
return false;
}
final Player other = (Player) obj;
if (this.name == null) {
if (other.name != null) {
return false;
}
} else if (!this.name.equals(other.name)) {
return false;
}
return true;
}
/**
* Retrieve the player's strategy.
*
* @return The strategy.
*/
public KnowledgeBase constructKnowledgeBase() {
KnowledgeBaseConfiguration kbconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration(null, classLoader);
kbconf.setOption(PermGenThresholdOption.get(0));
KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(kbconf);
kbase.addKnowledgePackages(packages);
return kbase;
}
/**
* Retrieve the player's name.
*
* @return The name.
*/
public String getName() {
return this.name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((this.name == null) ? 0 : this.name.hashCode());
return result;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Player [name=").append(this.name).append("]");
return builder.toString();
}
} |
package Cache;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import com.csvreader.CsvWriter;
import Util.CmdLineParser;
import Cache.CacheItem.CacheReason;
import Database.DatabaseManager;
public class Simulator {
/**
* Database prepared sql statements.
*/
static final String findCommit = "select id, date, is_bug_fix from scmlog "
+ "where repository_id =? and date between ? and ? order by date ASC";
static final String findFile = "select actions.file_id, type from actions, content_loc "
+ "where actions.file_id=content_loc.file_id "
+ "and actions.commit_id=? and content_loc.commit_id=? "
+ "and actions.file_id in( "
+ "select file_id from file_types where type='code') order by loc DESC";
static final String findHunkId = "select id from hunks where file_id =? and commit_id =?";
static final String findBugIntroCdate = "select date from hunk_blames, scmlog "
+ "where hunk_id =? and hunk_blames.bug_commit_id=scmlog.id";
static final String findPid = "select id from repositories where id=?";
static final String findFileCount = "select count(files.id) from files, file_types "
+ "where files.id = file_types.file_id and type = 'code' and repository_id=?";
private static PreparedStatement findCommitQuery;
private static PreparedStatement findFileQuery;
private static PreparedStatement findHunkIdQuery;
static PreparedStatement findBugIntroCdateQuery;
static PreparedStatement findPidQuery;
static PreparedStatement findFileCountQuery;
public enum FileType {
A, M, D, V, C, R
}
/**
* Member fields
*/
final int blocksize; // number of co-change files to import
final int prefetchsize; // number of (new or modified but not buggy) files
// to import
final int cachesize; // size of cache
final int pid; // project (repository) id
final boolean saveToFile; // whether there should be csv output
final CacheReplacement.Policy cacheRep; // cache replacement policy
final Cache cache; // the cache
final static Connection conn = DatabaseManager.getConnection(); // for database
int hit;
int miss;
private int commits;
// For output
// XXX separate class to manage output
String outputDate;
int outputSpacing = 3; // output the hit rate every 3 months
int month = outputSpacing;
CsvWriter csvWriter;
int fileCount; // XXX where is this set? why static?
String filename;
public Simulator(int bsize, int psize, int csize, int projid,
CacheReplacement.Policy rep, String start, String end, Boolean save) {
pid = projid;
int onepercent = getPercentOfFiles(pid);
if (bsize == -1)
blocksize = onepercent*5;
else
blocksize = bsize;
if (csize == -1)
cachesize = onepercent*10;
else
cachesize = csize;
if (psize == -1)
prefetchsize = onepercent;
else
prefetchsize = psize;
cacheRep = rep;
start = findFirstDate(start, pid);
end = findLastDate(end, pid);
cache = new Cache(cachesize, new CacheReplacement(rep), start, end,
projid);
outputDate = cache.startDate;
hit = 0;
miss = 0;
this.saveToFile = save;
if (saveToFile == true) {
filename = pid + "_" + cachesize + "_" + blocksize + "_"
+ prefetchsize + "_" + cacheRep;
csvWriter = new CsvWriter("Results/" + filename + "_hitrate.csv");
csvWriter.setComment('
try {
csvWriter.writeComment("hitrate for every 3 months, "
+ "used to describe the variation of hit rate with time");
csvWriter.writeComment("project: " + pid + ", cachesize: "
+ cachesize + ", blocksize: " + cachesize
+ ", prefetchsize: " + prefetchsize
+ ", cache replacement policy: " + cacheRep);
csvWriter.write("Month");
//csvWriter.write("Range");
csvWriter.write("HitRate");
csvWriter.write("NumCommits");
csvWriter.endRecord();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
findFileQuery = conn.prepareStatement(findFile);
findCommitQuery = conn.prepareStatement(findCommit);
findHunkIdQuery = conn.prepareStatement(findHunkId);
findBugIntroCdateQuery = conn.prepareStatement(findBugIntroCdate);
} catch (SQLException e) {
e.printStackTrace();
}
}
private static int getFileCount(int projid) {
int ret = 0;
try {
findFileCountQuery = conn.prepareStatement(findFileCount);
findFileCountQuery.setInt(1, projid);
ret = Util.Database.getIntResult(findFileCountQuery);
} catch (SQLException e1) {
e1.printStackTrace();
}
return ret;
}
/**
* Prints out the command line options
*/
private static void printUsage() {
System.err
.println("Example Usage: FixCache -b=10000 -c=500 -f=600 -r=\"LRU\" -p=1");
System.err.println("Example Usage: FixCache --blksize=10000 "
+ "--csize=500 --pfsize=600 --cacherep=\"LRU\" --pid=1");
System.err.println("-p/--pid option is required");
}
/**
* Loads an entity containing a bug into the cache.
*
* @param fileId
* @param cid
* -- commit id
* @param commitDate
* -- commit date
* @param intro_cdate
* -- bug introducing commit date
*/
// XXX move hit and miss to the cache?
// could add if (reas == BugEntity) logic to add() code
public void loadBuggyEntity(int fileId, int cid, String commitDate, String intro_cdate) {
if (cache.contains(fileId))
hit++;
else
miss++;
cache.add(fileId, cid, commitDate, CacheItem.CacheReason.BugEntity);
// add the co-changed files as well
ArrayList<Integer> cochanges = CoChange.getCoChangeFileList(fileId,
cache.startDate, intro_cdate, blocksize);
cache.add(cochanges, cid, commitDate, CacheItem.CacheReason.CoChange);
}
/**
* The main simulate loop. This loop processes all revisions starting at
* cache.startDate
*
*/
public void simulate() {
final ResultSet allCommits;
int cid;// means commit_id in actions
String cdate;
boolean isBugFix;
int file_id;
FileType type;
int numprefetch = 0;
// iterate over the selection
try {
findCommitQuery.setInt(1, pid);
findCommitQuery.setString(2, cache.startDate);
findCommitQuery.setString(3, cache.endDate);
// returns all commits to pid after cache.startDate
allCommits = findCommitQuery.executeQuery();
while (allCommits.next()) {
commits++;
cid = allCommits.getInt(1);
cdate = allCommits.getString(2);
isBugFix = allCommits.getBoolean(3);
findFileQuery.setInt(1, cid);
findFileQuery.setInt(2, cid);
final ResultSet files = findFileQuery.executeQuery();
// loop through those file ids
while (files.next()) {
file_id = files.getInt(1);
type = FileType.valueOf(files.getString(2));
numprefetch = processOneFile(cid, cdate, isBugFix, file_id,
type, numprefetch);
}
numprefetch = 0;
if (saveToFile == true) {
if (Util.Dates.getMonthDuration(outputDate, cdate) > outputSpacing
|| cdate.equals(cache.endDate)) {
outputHitRate(cdate);
}
}
}
} catch (Exception e) {
System.out.println(e);
e.printStackTrace();
}
}
private void outputHitRate(String cdate) {
// XXX what if commits are more than 3 months apart?
// XXX eliminate range?
//final String formerOutputDate = outputDate;
if (!cdate.equals(cache.endDate)) {
outputDate = Util.Dates.monthsLater(outputDate, outputSpacing);
} else {
outputDate = cdate;
}
try {
csvWriter.write(Integer.toString(month));
//csvWriter.write(Util.Dates.getRange(formerOutputDate, outputDate));
csvWriter.write(Double.toString(getHitRate()));
csvWriter.write(Integer.toString(getCommitCount()));
csvWriter.endRecord();
} catch (IOException e) {
e.printStackTrace();
}
month += outputSpacing;
}
private int processOneFile(int cid, String cdate, boolean isBugFix,
int file_id, FileType type, int numprefetch) {
switch (type) {
case V:
break;
case R:
case C:
case A:
if (numprefetch < prefetchsize) {
numprefetch++;
cache.add(file_id, cid, cdate, CacheItem.CacheReason.Prefetch);
}
break;
case D:
if(cache.contains(file_id)){
this.cache.remove(file_id, cdate);
}
break;
case M: // modified
if (isBugFix) {
String intro_cdate = this.getBugIntroCdate(file_id, cid);
this.loadBuggyEntity(file_id, cid, cdate, intro_cdate);
} else if (numprefetch < prefetchsize) {
numprefetch++;
cache.add(file_id, cid, cdate, CacheItem.CacheReason.Prefetch);
}
}
return numprefetch;
}
/**
* Gets the current hit rate of the cache
*
* @return hit rate of the cache
*/
public double getHitRate() {
double hitrate = (double) hit / (hit + miss);
return (double) Math.round(hitrate * 10000) / 100;
}
/**
* Database accessors
*/
/**
* Fills cache with pre-fetch size number of top-LOC files from initial
* commit. Only called once per simulation // implicit input: initial commit
* ID // implicit input: LOC for every file in initial commit ID // implicit
* input: pre-fetch size
*/
public void initialPreLoad() {
final String findInitialPreload = "select content_loc.file_id, content_loc.commit_id "
+ "from content_loc, scmlog, actions, file_types "
+ "where repository_id=? and content_loc.commit_id = scmlog.id and date =? "
+ "and content_loc.file_id=actions.file_id "
+ "and content_loc.commit_id=actions.commit_id and actions.type!='D' "
+ "and file_types.file_id=content_loc.file_id and file_types.type='code' order by loc DESC";
final PreparedStatement findInitialPreloadQuery;
ResultSet r = null;
int fileId = 0;
int commitId = 0;
try {
findInitialPreloadQuery = conn.prepareStatement(findInitialPreload);
findInitialPreloadQuery.setInt(1, pid);
findInitialPreloadQuery.setString(2, cache.startDate);
r = findInitialPreloadQuery.executeQuery();
} catch (SQLException e1) {
e1.printStackTrace();
}
for (int size = 0; size < prefetchsize; size++) {
try {
if (r.next()) {
fileId = r.getInt(1);
commitId = r.getInt(2);
cache.add(fileId, commitId, cache.startDate,
CacheItem.CacheReason.Prefetch);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* Finds the first date after the startDate with repository entries. Only
* called once per simulation.
*
* @return The date for the prefetch.
*/
private static String findFirstDate(String start, int pid) {
String findFirstDate = "";
final PreparedStatement findFirstDateQuery;
String firstDate = "";
try {
if (start == null) {
findFirstDate = "select min(date) from scmlog where repository_id=?";
findFirstDateQuery = conn.prepareStatement(findFirstDate);
findFirstDateQuery.setInt(1, pid);
} else {
findFirstDate = "select min(date) from scmlog where repository_id=? and date >=?";
findFirstDateQuery = conn.prepareStatement(findFirstDate);
findFirstDateQuery.setInt(1, pid);
findFirstDateQuery.setString(2, start);
}
firstDate = Util.Database.getStringResult(findFirstDateQuery);
if (firstDate == null) {
System.out.println("Can not find any commit after "
+ start);
System.exit(2);
}
} catch (SQLException e) {
e.printStackTrace();
}
return firstDate;
}
/**
* Finds the last date before the endDate with repository entries. Only
* called once per simulation.
*
* @return The date for the the simulator.
*/
private static String findLastDate(String end, int pid) {
String findLastDate = null;
final PreparedStatement findLastDateQuery;
String lastDate = null;
try {
if (end == null) {
findLastDate = "select max(date) from scmlog where repository_id=?";
findLastDateQuery = conn.prepareStatement(findLastDate);
findLastDateQuery.setInt(1, pid);
} else {
findLastDate = "select max(date) from scmlog where repository_id=? and date <=?";
findLastDateQuery = conn.prepareStatement(findLastDate);
findLastDateQuery.setInt(1, pid);
findLastDateQuery.setString(2, end);
}
lastDate = Util.Database.getStringResult(findLastDateQuery);
} catch (SQLException e) {
e.printStackTrace();
}
if (lastDate == null) {
System.out.println("Can not find any commit before "
+ end);
System.exit(2);
}
return lastDate;
}
/**
* use the fileId and commitId to get a list of changed hunks from the hunk
* table. for each changed hunk, get the blamedHunk from the hunk_blame
* table; get the commit id associated with this blamed hunk take the
* maximum (in terms of date?) commit id and return it
* */
public String getBugIntroCdate(int fileId, int commitId) {
// XXX optimize this code?
String bugIntroCdate = "";
int hunkId;
ResultSet r = null;
ResultSet r1 = null;
try {
findHunkIdQuery.setInt(1, fileId);
findHunkIdQuery.setInt(2, commitId);
r = findHunkIdQuery.executeQuery();
while (r.next()) {
hunkId = r.getInt(1);
findBugIntroCdateQuery.setInt(1, hunkId);
r1 = findBugIntroCdateQuery.executeQuery();
while (r1.next()) {
if (r1.getString(1).compareTo(bugIntroCdate) > 0) {
bugIntroCdate = r1.getString(1);
}
}
}
} catch (Exception e) {
System.out.println(e);
System.exit(0);
}
return bugIntroCdate;
}
/**
* Closes the database connection
*/
private void close() {
DatabaseManager.close();
}
/**
* For Debugging
*/
public int getHit() {
return hit;
}
public int getMiss() {
return miss;
}
public Cache getCache() {
return cache;
}
public void add(int eid, int cid, String cdate, CacheReason reas) {
cache.add(eid, cid, cdate, reas);
}
// XXX move to a different part of the file
public static void checkParameter(String start, String end, int pid) {
if (start != null && end != null) {
if (start.compareTo(end) > 0) {
System.err
.println("Error:Start date must be earlier than end date");
printUsage();
System.exit(2);
}
}
try {
findPidQuery = conn.prepareStatement(findPid);
findPidQuery.setInt(1, pid);
if (Util.Database.getIntResult(findPidQuery) == -1) {
System.out.println("There is no project whose id is " + pid);
System.exit(2);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
/**
* Command line parsing
*/
CmdLineParser parser = new CmdLineParser();
CmdLineParser.Option blksz_opt = parser.addIntegerOption('b', "blksize");
CmdLineParser.Option csz_opt = parser.addIntegerOption('c', "csize");
CmdLineParser.Option pfsz_opt = parser.addIntegerOption('f', "pfsize");
CmdLineParser.Option crp_opt = parser.addStringOption('r', "cacherep");
CmdLineParser.Option pid_opt = parser.addIntegerOption('p', "pid");
CmdLineParser.Option sd_opt = parser.addStringOption('s', "start");
CmdLineParser.Option ed_opt = parser.addStringOption('e', "end");
CmdLineParser.Option save_opt = parser.addBooleanOption('o',"save");
CmdLineParser.Option tune_opt = parser.addBooleanOption('u', "tune");
// CmdLineParser.Option sCId_opt = parser.addIntegerOption('s',"start");
// CmdLineParser.Option eCId_opt = parser.addIntegerOption('e',"end");
try {
parser.parse(args);
} catch (CmdLineParser.OptionException e) {
System.err.println(e.getMessage());
printUsage();
System.exit(2);
}
Integer blksz = (Integer) parser.getOptionValue(blksz_opt, -1);
Integer csz = (Integer) parser.getOptionValue(csz_opt, -1);
Integer pfsz = (Integer) parser.getOptionValue(pfsz_opt, -1);
String crp_string = (String) parser.getOptionValue(crp_opt,
CacheReplacement.REPDEFAULT.toString());
Integer pid = (Integer) parser.getOptionValue(pid_opt);
String start = (String) parser.getOptionValue(sd_opt, null);
String end = (String) parser.getOptionValue(ed_opt, null);
Boolean saveToFile = (Boolean) parser.getOptionValue(save_opt, false);
Boolean tune = (Boolean)parser.getOptionValue(tune_opt, false);
CacheReplacement.Policy crp;
try {
crp = CacheReplacement.Policy.valueOf(crp_string);
} catch (Exception e) {
System.err.println(e.getMessage());
System.err.println("Must specify a valid cache replacement policy");
printUsage();
crp = CacheReplacement.REPDEFAULT;
}
if (pid == null) {
System.err.println("Error: must specify a Project Id");
printUsage();
System.exit(2);
}
checkParameter(start, end, pid);
/**
* Create a new simulator and run simulation.
*/
Simulator sim;
if(tune)
{
System.out.println("tuning...");
sim = tune(pid);
System.out.println(".... finished tuning!");
System.out.println("highest hitrate:"+sim.getHitRate());
}
else
{
sim = new Simulator(blksz, pfsz, csz, pid, crp, start, end, saveToFile);
sim.initialPreLoad();
sim.simulate();
if(sim.saveToFile==true)
{
sim.csvWriter.close();
sim.outputFileDist();
}
}
// should always happen
sim.close();
printSummary(sim);
}
private static void printSummary(Simulator sim) {
System.out.println("Simulator specs:");
System.out.print("Project....");
System.out.println(sim.pid);
System.out.print("Cache size....");
System.out.println(sim.cachesize);
System.out.print("Blk size....");
System.out.println(sim.blocksize);
System.out.print("Prefetch size....");
System.out.println(sim.prefetchsize);
System.out.print("Start date....");
System.out.println(sim.cache.startDate);
System.out.print("End date....");
System.out.println(sim.cache.endDate);
System.out.print("Cache Replacement Policy ....");
System.out.println(sim.cacheRep.toString());
System.out.print("saving to file....");
System.out.println(sim.saveToFile);
System.out.println("\nResults:");
System.out.print("Hit rate...");
System.out.println(sim.getHitRate());
System.out.print("Num commits processed...");
System.out.println(sim.getCommitCount());
System.out.print("Num bug fixes...");
System.out.println(sim.getHit() + sim.getMiss());
}
private static Simulator tune(int pid)
{
Simulator maxsim = null;
double maxhitrate = 0;
int blksz;
int pfsz;
int onepercent = getPercentOfFiles(pid);
System.out.println("One percent of files: " + onepercent);
final int UPPER = 10*onepercent;
CacheReplacement.Policy crp = CacheReplacement.REPDEFAULT;
for(blksz=onepercent;blksz<UPPER;blksz+=onepercent*2){
for(pfsz=onepercent;pfsz<UPPER;pfsz+=onepercent*2){
final Simulator sim = new Simulator(blksz, pfsz,-1, pid, crp, null, null, false);
sim.initialPreLoad();
sim.simulate();
System.out.println(sim.getHitRate());
if(sim.getHitRate()>maxhitrate)
{
maxhitrate = sim.getHitRate();
maxsim = sim;
}
}
}
System.out.println("Trying out different cache replacment policies...");
for(CacheReplacement.Policy crtst :CacheReplacement.Policy.values()){
final Simulator sim =
new Simulator(maxsim.blocksize, maxsim.prefetchsize,
-1, pid, crtst, null, null, false);
sim.initialPreLoad();
sim.simulate();
System.out.println(sim.getHitRate());
if(sim.getHitRate()>maxhitrate)
{
maxhitrate = sim.getHitRate();
maxsim = sim;
}
}
maxsim.close();
return maxsim;
}
private static int getPercentOfFiles(int pid) {
int ret = (int) Math.round(getFileCount(pid)*0.01);
if (ret == 0)
return 1;
else
return ret;
}
public void outputFileDist() {
csvWriter = new CsvWriter("Results/" + filename + "_filedist.csv");
csvWriter.setComment('
try {
// csvWriter.write("# number of hit, misses and time stayed in Cache for every file");
csvWriter.writeComment("number of hit, misses and time stayed in Cache for every file");
csvWriter.writeComment("project: " + pid + ", cachesize: " + cachesize
+ ", blocksize: " + cachesize + ", prefetchsize: "
+ prefetchsize + ", cache replacement policy: " + cacheRep);
csvWriter.write("file_id");
csvWriter.write("loc");
csvWriter.write("num_hits");
csvWriter.write("num_misses");
csvWriter.write("duration");
csvWriter.endRecord();
csvWriter.write("0");
csvWriter.write("0");
csvWriter.write("0");
csvWriter.write("0");
csvWriter.write(Integer.toString(cache.getTotalDuration()));
csvWriter.endRecord();
// else assume that the file already has the correct header line
// write out record
//XXX rewrite with built in iteratable
for (CacheItem ci : cache){
csvWriter.write(Integer.toString(ci.getEntityId()));
csvWriter.write(Integer.toString(ci.getLOC())); // LOC at time
// of last
// update
csvWriter.write(Integer.toString(ci.getHitCount()));
csvWriter.write(Integer.toString(ci.getMissCount()));
csvWriter.write(Integer.toString(ci.getDuration()));
csvWriter.endRecord();
}
csvWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private int getCommitCount() {
return commits;
}
public CsvWriter getCsvWriter() {
return csvWriter;
}
} |
package Cache;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import com.csvreader.CsvWriter;
import Util.CmdLineParser;
import Cache.CacheItem.CacheReason;
import Database.DatabaseManager;
public class Simulator {
/**
* Database prepared sql statements.
*/
static final String findCommit = "select id, date, is_bug_fix from scmlog "
+ "where repository_id =? and date between ? and ? order by date ASC";
static final String findFile = "select file_name, type from actions, content_loc, files "
+ "where actions.file_id=content_loc.file_id and actions.file_id=files.id "
+ "and actions.commit_id=? and content_loc.commit_id=? "
+ "and actions.file_id in( "
+ "select file_id from file_types where type='code') order by loc DESC";
static final String findHunkId = "select hunks.id from hunks, files where hunks.file_id=files.id and " +
"file_name =? and commit_id =?";
static final String findBugIntroCdate = "select date from hunk_blames, scmlog "
+ "where hunk_id =? and hunk_blames.bug_commit_id=scmlog.id";
static final String findPid = "select id from repositories where id=?";
static final String findFileCount = "select count(distinct(file_name)) " +
"from files, file_types "
+ "where files.id = file_types.file_id and type = 'code' and repository_id=?";
static final String findFileCountTime = "select(" +
"(select count(distinct(file_name)) from files, actions, scmlog, " +
"file_types where files.id=file_types.file_id and actions.commit_id = " +
"scmlog.id and actions.file_id = " +
" file_types.file_id and file_types.type = 'code' and scmlog.repository_id = " +
"? and scmlog.date < ?) - (" +
"select count(distinct(file_name)) from files, actions, scmlog, " +
"file_types where files.id=file_types.file_id and actions.commit_id = " +
"scmlog.id and actions.file_id = " +
" file_types.file_id and file_types.type = 'code' and scmlog.repository_id = " +
"? and scmlog.date < ? and actions.type = 'D')) as total_files";
private static PreparedStatement findCommitQuery;
private static PreparedStatement findFileQuery;
private static PreparedStatement findHunkIdQuery;
static PreparedStatement findBugIntroCdateQuery;
static PreparedStatement findPidQuery;
static PreparedStatement findFileCountQuery;
static PreparedStatement findFileCountTimeQuery;
public enum FileType {
A, M, D, V, C, R
}
/**
* Member fields
*/
final int blocksize; // number of co-change files to import
final int prefetchsize; // number of (new or modified but not buggy) files
// to import
final int cachesize; // size of cache
final int pid; // project (repository) id
final boolean saveToFile; // whether there should be csv output
boolean filedistPrintMultiple = false; // whether the filedist output should happen once or more
final CacheReplacement.Policy cacheRep; // cache replacement policy
final Cache cache; // the cache
final static Connection conn = DatabaseManager.getConnection(); // for database
int hit;
int miss;
private int commits;
private int totalcommits;
private int bugcount;
private int filesProcessed;
// For output
// XXX separate class to manage output
String outputDate;
int outputSpacing = 3; // output the hit rate every 3 months
int month = outputSpacing;
CsvWriter csvWriter;
int fileCount;
String filename;
public Simulator(int bsize, int psize, int csize, int projid,
CacheReplacement.Policy rep, String start, String end, Boolean save) {
pid = projid;
int onepercent = getPercentOfFiles(pid);
if (bsize == -1)
blocksize = onepercent*5;
else
blocksize = bsize;
if (csize == -1)
cachesize = onepercent*10;
else
cachesize = csize;
if (psize == -1)
prefetchsize = onepercent;
else
prefetchsize = psize;
cacheRep = rep;
start = findFirstDate(start, pid);
end = findLastDate(end, pid);
cache = new Cache(cachesize, new CacheReplacement(rep), start, end,
projid);
outputDate = cache.startDate;
hit = 0;
miss = 0;
this.saveToFile = save;
if (saveToFile == true) {
filename = pid + "_" + cachesize + "_" + blocksize + "_"
+ prefetchsize + "_" + cacheRep;
csvWriter = new CsvWriter("Results/" + filename + "_hitrate.csv");
csvWriter.setComment('
try {
csvWriter.writeComment("hitrate for every 3 months, "
+ "used to describe the variation of hit rate with time");
csvWriter.writeComment("project: " + pid + ", cachesize: "
+ cachesize + ", blocksize: " + cachesize
+ ", prefetchsize: " + prefetchsize
+ ", cache replacement policy: " + cacheRep);
csvWriter.write("Month");
//csvWriter.write("Range");
csvWriter.write("HitRate");
csvWriter.write("NumCommits");
csvWriter.write("NumAdds");
csvWriter.write("NumNewCacheItems");
// csvWriter.write("NumFiles"); // uncomment if using findfilecountquery
csvWriter.write("NumBugFixes");
csvWriter.write("FilesProcessed");
csvWriter.endRecord();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
findFileQuery = conn.prepareStatement(findFile);
findCommitQuery = conn.prepareStatement(findCommit);
findHunkIdQuery = conn.prepareStatement(findHunkId);
findBugIntroCdateQuery = conn.prepareStatement(findBugIntroCdate);
//findFileCountTimeQuery = conn.prepareStatement(findFileCountTime);
} catch (SQLException e) {
e.printStackTrace();
}
}
void outputMultiple(){
filedistPrintMultiple = true;
}
private static int getFileCount(int projid) {
int ret = 0;
try {
findFileCountQuery = conn.prepareStatement(findFileCount);
findFileCountQuery.setInt(1, projid);
ret = Util.Database.getIntResult(findFileCountQuery);
} catch (SQLException e1) {
e1.printStackTrace();
}
return ret;
}
/**
* Prints out the command line options
*/
private static void printUsage() {
System.err
.println("Example Usage: FixCache -b=10000 -c=500 -f=600 -r=\"LRU\" -p=1");
System.err.println("Example Usage: FixCache --blksize=10000 "
+ "--csize=500 --pfsize=600 --cacherep=\"LRU\" --pid=1");
System.err.println("-p/--pid option is required");
}
/**
* Loads an entity containing a bug into the cache.
*
* @param fileId
* @param cid
* -- commit id
* @param commitDate
* -- commit date
* @param intro_cdate
* -- bug introducing commit date
*/
// XXX move hit and miss to the cache?
// could add if (reas == BugEntity) logic to add() code
public void loadBuggyEntity(String fileId, int cid, String commitDate, String intro_cdate) {
bugcount++;
if (cache.contains(fileId))
hit++;
else
miss++;
cache.add(fileId, cid, commitDate, CacheItem.CacheReason.BugEntity);
// add the co-changed files as well
ArrayList<String> cochanges = CoChange.getCoChangeFileList(fileId,
cache.startDate, intro_cdate, blocksize);
cache.add(cochanges, cid, commitDate, CacheItem.CacheReason.CoChange);
}
/**
* The main simulate loop. This loop processes all revisions starting at
* cache.startDate
*
*/
public void simulate() {
final ResultSet allCommits;
int cid;// means commit_id in actions
String cdate = null;
boolean isBugFix;
String fileName;
FileType type;
int numprefetch = 0;
// iterate over the selection
try {
findCommitQuery.setInt(1, pid);
findCommitQuery.setString(2, cache.startDate);
findCommitQuery.setString(3, cache.endDate);
// returns all commits to pid after cache.startDate
allCommits = findCommitQuery.executeQuery();
while (allCommits.next()) {
incCommits();
cid = allCommits.getInt(1);
cdate = allCommits.getString(2);
isBugFix = allCommits.getBoolean(3);
findFileQuery.setInt(1, cid);
findFileQuery.setInt(2, cid);
final ResultSet files = findFileQuery.executeQuery();
// loop through those file ids
while (files.next()) {
fileName = files.getString(1); //XXX fix query
type = FileType.valueOf(files.getString(2));
numprefetch = processOneFile(cid, cdate, isBugFix, fileName,
type, numprefetch);
}
numprefetch = 0;
if (saveToFile == true) {
if (Util.Dates.getMonthDuration(outputDate, cdate) > outputSpacing
|| cdate.equals(cache.endDate)) {
outputHitRate(cdate);
}
}
}
} catch (Exception e) {
System.out.println(e);
e.printStackTrace();
}
}
private void incCommits() {
commits++;
totalcommits++;
}
private void outputHitRate(String cdate) {
// XXX what if commits are more than 3 months apart?
//final String formerOutputDate = outputDate;
if (filedistPrintMultiple)
outputFileDist();
if (!cdate.equals(cache.endDate)) {
outputDate = Util.Dates.monthsLater(outputDate, outputSpacing);
} else {
outputDate = cdate; // = cache.endDate
}
try {
csvWriter.write(Integer.toString(month));
//csvWriter.write(Util.Dates.getRange(formerOutputDate, outputDate));
csvWriter.write(Double.toString(getHitRate()));
csvWriter.write(Integer.toString(resetCommitCount()));
csvWriter.write(Integer.toString(cache.resetAddCount()));
csvWriter.write(Integer.toString(cache.resetCICount()));
//also prints filecount at time slice, but query is not accurate
//csvWriter.write(Integer.toString(getFileCount(pid,cdate)));
csvWriter.write(Integer.toString(resetBugCount()));
csvWriter.write(Integer.toString(resetFilesProcessedCount()));
csvWriter.endRecord();
} catch (IOException e) {
e.printStackTrace();
}
month += outputSpacing;
if (Util.Dates.getMonthDuration(outputDate, cdate) > outputSpacing){
outputHitRate(cdate);
}
}
private int processOneFile(int cid, String cdate, boolean isBugFix,
String file_id, FileType type, int numprefetch) {
filesProcessed++;
switch (type) {
case V:
break;
case R:
case C:
case A:
if (numprefetch < prefetchsize) {
numprefetch++;
cache.add(file_id, cid, cdate, CacheItem.CacheReason.NewEntity);
}
break;
case D:
if(cache.contains(file_id)){
this.cache.remove(file_id, cdate);
}
break;
case M: // modified
if (isBugFix) {
String intro_cdate = this.getBugIntroCdate(file_id, cid);
this.loadBuggyEntity(file_id, cid, cdate, intro_cdate);
} else if (numprefetch < prefetchsize) {
numprefetch++;
cache.add(file_id, cid, cdate, CacheItem.CacheReason.ModifiedEntity);
}
}
return numprefetch;
}
/**
* Gets the current hit rate of the cache
*
* @return hit rate of the cache
*/
public double getHitRate() {
double hitrate = (double) hit / (hit + miss);
return (double) Math.round(hitrate * 10000) / 100;
}
/**
* Database accessors
*/
/**
* Fills cache with pre-fetch size number of top-LOC files from initial
* commit. Only called once per simulation // implicit input: initial commit
* ID // implicit input: LOC for every file in initial commit ID // implicit
* input: pre-fetch size
*/
public void initialPreLoad() {
final String findInitialPreload = "select files.file_name, content_loc.commit_id "
+ "from content_loc, scmlog, actions, file_types, files "
+ "where files.repository_id=? and content_loc.commit_id = scmlog.id and date =? "
+ "and content_loc.file_id=actions.file_id and files.id=actions.file_id "
+ "and content_loc.commit_id=actions.commit_id and actions.type!='D' "
+ "and file_types.file_id=content_loc.file_id and file_types.type='code' " +
"order by loc DESC";
final PreparedStatement findInitialPreloadQuery;
ResultSet r = null;
String fileName = null;
int commitId = 0;
try {
findInitialPreloadQuery = conn.prepareStatement(findInitialPreload);
findInitialPreloadQuery.setInt(1, pid);
findInitialPreloadQuery.setString(2, cache.startDate);
r = findInitialPreloadQuery.executeQuery();
} catch (SQLException e1) {
e1.printStackTrace();
}
for (int size = 0; size < prefetchsize; size++) {
try {
if (r.next()) {
fileName = r.getString(1); //XXX fix query
commitId = r.getInt(2);
cache.add(fileName, commitId, cache.startDate,
CacheItem.CacheReason.Preload);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* Finds the first date after the startDate with repository entries. Only
* called once per simulation.
*
* @return The date for the prefetch.
*/
private static String findFirstDate(String start, int pid) {
String findFirstDate = "";
final PreparedStatement findFirstDateQuery;
String firstDate = "";
try {
if (start == null) {
findFirstDate = "select min(date) from scmlog where repository_id=?";
findFirstDateQuery = conn.prepareStatement(findFirstDate);
findFirstDateQuery.setInt(1, pid);
} else {
findFirstDate = "select min(date) from scmlog where repository_id=? and date >=?";
findFirstDateQuery = conn.prepareStatement(findFirstDate);
findFirstDateQuery.setInt(1, pid);
findFirstDateQuery.setString(2, start);
}
firstDate = Util.Database.getStringResult(findFirstDateQuery);
if (firstDate == null) {
System.out.println("Can not find any commit after "
+ start);
System.exit(2);
}
} catch (SQLException e) {
e.printStackTrace();
}
return firstDate;
}
/**
* Finds the last date before the endDate with repository entries. Only
* called once per simulation.
*
* @return The date for the the simulator.
*/
private static String findLastDate(String end, int pid) {
String findLastDate = null;
final PreparedStatement findLastDateQuery;
String lastDate = null;
try {
if (end == null) {
findLastDate = "select max(date) from scmlog where repository_id=?";
findLastDateQuery = conn.prepareStatement(findLastDate);
findLastDateQuery.setInt(1, pid);
} else {
findLastDate = "select max(date) from scmlog where repository_id=? and date <=?";
findLastDateQuery = conn.prepareStatement(findLastDate);
findLastDateQuery.setInt(1, pid);
findLastDateQuery.setString(2, end);
}
lastDate = Util.Database.getStringResult(findLastDateQuery);
} catch (SQLException e) {
e.printStackTrace();
}
if (lastDate == null) {
System.out.println("Can not find any commit before "
+ end);
System.exit(2);
}
return lastDate;
}
/**
* use the fileId and commitId to get a list of changed hunks from the hunk
* table. for each changed hunk, get the blamedHunk from the hunk_blame
* table; get the commit id associated with this blamed hunk take the
* maximum (in terms of date?) commit id and return it
* */
public String getBugIntroCdate(String fileName, int commitId) {
// XXX optimize this code?
String bugIntroCdate = "";
int hunkId;
ResultSet r = null;
ResultSet r1 = null;
try {
findHunkIdQuery.setString(1, fileName); // XXX fix query
findHunkIdQuery.setInt(2, commitId);
r = findHunkIdQuery.executeQuery();
while (r.next()) {
hunkId = r.getInt(1);
findBugIntroCdateQuery.setInt(1, hunkId);
r1 = findBugIntroCdateQuery.executeQuery();
while (r1.next()) {
if (r1.getString(1).compareTo(bugIntroCdate) > 0) {
bugIntroCdate = r1.getString(1);
}
}
}
} catch (Exception e) {
System.out.println(e);
System.exit(0);
}
return bugIntroCdate;
}
/**
* Closes the database connection
*/
private void close() {
DatabaseManager.close();
}
/**
* For Debugging
*/
public int getHit() {
return hit;
}
public int getMiss() {
return miss;
}
public Cache getCache() {
return cache;
}
public void add(String eid, int cid, String cdate, CacheReason reas) {
cache.add(eid, cid, cdate, reas);
}
// XXX move to a different part of the file
public static void checkParameter(String start, String end, int pid) {
if (start != null && end != null) {
if (start.compareTo(end) > 0) {
System.err
.println("Error:Start date must be earlier than end date");
printUsage();
System.exit(2);
}
}
try {
findPidQuery = conn.prepareStatement(findPid);
findPidQuery.setInt(1, pid);
if (Util.Database.getIntResult(findPidQuery) == -1) {
System.out.println("There is no project whose id is " + pid);
System.exit(2);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
/**
* Command line parsing
*/
CmdLineParser parser = new CmdLineParser();
CmdLineParser.Option blksz_opt = parser.addIntegerOption('b', "blksize");
CmdLineParser.Option csz_opt = parser.addIntegerOption('c', "csize");
CmdLineParser.Option pfsz_opt = parser.addIntegerOption('f', "pfsize");
CmdLineParser.Option crp_opt = parser.addStringOption('r', "cacherep");
CmdLineParser.Option pid_opt = parser.addIntegerOption('p', "pid");
CmdLineParser.Option sd_opt = parser.addStringOption('s', "start");
CmdLineParser.Option ed_opt = parser.addStringOption('e', "end");
CmdLineParser.Option save_opt = parser.addBooleanOption('o',"save");
CmdLineParser.Option month_opt = parser.addBooleanOption('m',"multiple");
CmdLineParser.Option tune_opt = parser.addBooleanOption('u', "tune");
// CmdLineParser.Option sCId_opt = parser.addIntegerOption('s',"start");
// CmdLineParser.Option eCId_opt = parser.addIntegerOption('e',"end");
try {
parser.parse(args);
} catch (CmdLineParser.OptionException e) {
System.err.println(e.getMessage());
printUsage();
System.exit(2);
}
Integer blksz = (Integer) parser.getOptionValue(blksz_opt, -1);
Integer csz = (Integer) parser.getOptionValue(csz_opt, -1);
Integer pfsz = (Integer) parser.getOptionValue(pfsz_opt, -1);
String crp_string = (String) parser.getOptionValue(crp_opt,
CacheReplacement.REPDEFAULT.toString());
Integer pid = (Integer) parser.getOptionValue(pid_opt);
String start = (String) parser.getOptionValue(sd_opt, null);
String end = (String) parser.getOptionValue(ed_opt, null);
Boolean saveToFile = (Boolean) parser.getOptionValue(save_opt, false);
Boolean tune = (Boolean)parser.getOptionValue(tune_opt, false);
Boolean monthly = (Boolean)parser.getOptionValue(month_opt, false);
CacheReplacement.Policy crp;
try {
crp = CacheReplacement.Policy.valueOf(crp_string);
} catch (Exception e) {
System.err.println(e.getMessage());
System.err.println("Must specify a valid cache replacement policy");
printUsage();
crp = CacheReplacement.REPDEFAULT;
}
if (pid == null) {
System.err.println("Error: must specify a Project Id");
printUsage();
System.exit(2);
}
checkParameter(start, end, pid);
/**
* Create a new simulator and run simulation.
*/
Simulator sim;
if(tune)
{
System.out.println("tuning...");
sim = tune(pid);
System.out.println(".... finished tuning!");
System.out.println("highest hitrate:"+sim.getHitRate());
}
else
{
sim = new Simulator(blksz, pfsz, csz, pid, crp, start, end, saveToFile);
if (monthly) sim.outputMultiple();
sim.initialPreLoad();
sim.simulate();
if(sim.saveToFile==true)
{
sim.csvWriter.close();
sim.outputFileDist();
}
}
// should always happen
sim.close();
printSummary(sim);
}
private static void printSummary(Simulator sim) {
System.out.println("Simulator specs:");
System.out.print("Project....");
System.out.println(sim.pid);
System.out.print("Cache size....");
System.out.println(sim.cachesize);
System.out.print("Blk size....");
System.out.println(sim.blocksize);
System.out.print("Prefetch size....");
System.out.println(sim.prefetchsize);
System.out.print("Start date....");
System.out.println(sim.cache.startDate);
System.out.print("End date....");
System.out.println(sim.cache.endDate);
System.out.print("Cache Replacement Policy ....");
System.out.println(sim.cacheRep.toString());
System.out.print("saving to file....");
System.out.println(sim.saveToFile);
System.out.println("\nResults:");
System.out.print("Hit rate...");
System.out.println(sim.getHitRate());
System.out.print("Num commits processed...");
System.out.println(sim.getTotalCommitCount());
System.out.print("Num bug fixes...");
System.out.println(sim.getHit() + sim.getMiss());
}
private static Simulator tune(int pid)
{
Simulator maxsim = null;
double maxhitrate = 0;
int blksz;
int pfsz;
int onepercent = getPercentOfFiles(pid);
System.out.println("One percent of files: " + onepercent);
final int UPPER = 10*onepercent;
CacheReplacement.Policy crp = CacheReplacement.REPDEFAULT;
for(blksz=onepercent;blksz<UPPER;blksz+=onepercent*2){
for(pfsz=onepercent;pfsz<UPPER;pfsz+=onepercent*2){
final Simulator sim = new Simulator(blksz, pfsz,-1, pid, crp, null, null, false);
sim.initialPreLoad();
sim.simulate();
System.out.println(sim.getHitRate());
if(sim.getHitRate()>maxhitrate)
{
maxhitrate = sim.getHitRate();
maxsim = sim;
}
}
}
System.out.println("Trying out different cache replacment policies...");
for(CacheReplacement.Policy crtst :CacheReplacement.Policy.values()){
final Simulator sim =
new Simulator(maxsim.blocksize, maxsim.prefetchsize,
-1, pid, crtst, null, null, false);
sim.initialPreLoad();
sim.simulate();
System.out.println(sim.getHitRate());
if(sim.getHitRate()>maxhitrate)
{
maxhitrate = sim.getHitRate();
maxsim = sim;
}
}
maxsim.close();
return maxsim;
}
private static int getPercentOfFiles(int pid) {
int ret = (int) Math.round(getFileCount(pid)*0.01);
if (ret == 0)
return 1;
else
return ret;
}
private void outputFileDist() {
String pathname;
if (filedistPrintMultiple)
pathname = "Results/" + month + "-" + filename + "_filedist.csv";
else
pathname = "Results/" + filename + "_filedist.csv";
CsvWriter csv = new CsvWriter(pathname);
csv.setComment('
try {
// csvWriter.write("# number of hit, misses and time stayed in Cache for every file");
csv.writeComment("number of hit, misses and time stayed in Cache for every file");
csv.writeComment("project: " + pid + ", cachesize: " + cachesize
+ ", blocksize: " + cachesize + ", prefetchsize: "
+ prefetchsize + ", cache replacement policy: " + cacheRep);
csv.write("file_id");
csv.write("loc");
csv.write("num_load");
csv.write("num_hits");
csv.write("num_misses");
csv.write("duration");
csv.write("reason");
csv.endRecord();
csv.write("0");
csv.write("0");
csv.write("0");
csv.write("0");
csv.write("0");
csv.write(Integer.toString(cache.getTotalDuration()));
csv.write("0");
csv.endRecord();
// else assume that the file already has the correct header line
// write out record
//XXX rewrite with built in iteratable
for (CacheItem ci : cache){
csv.write((ci.getFileName()));
csv.write(Integer.toString(ci.getLOC())); // LOC at time of last update
csv.write(Integer.toString(ci.getLoadCount()));
csv.write(Integer.toString(ci.getHitCount()));
csv.write(Integer.toString(ci.getMissCount()));
csv.write(Integer.toString(ci.getDuration()));
csv.write(ci.getReason().toString());
csv.endRecord();
}
csv.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private int resetCommitCount() {
int oldcommits = commits;
commits = 0;
return oldcommits;
}
private int resetBugCount() {
int oldbugs = bugcount;
bugcount = 0;
return oldbugs;
}
private int resetFilesProcessedCount() {
int oldfiles = filesProcessed;
filesProcessed = 0;
return oldfiles;
}
private int getTotalCommitCount() {
return totalcommits;
}
public CsvWriter getCsvWriter() {
return csvWriter;
}
} |
package ru.matevosyan.start;
import ru.matevosyan.models.Item;
public class MenuTracker {
private Input input;
private Tracker tracker;
private UserAction[] userAction = new UserAction[9];
public MenuTracker(Input input, Tracker tracker) {
this.input = input;
this.tracker = tracker;
}
public void fillAction() {
this.userAction[0] = new AddItem();
this.userAction[1] = new MenuTracker.ShowItems();
}
public void select(String key) {
this.userAction[Integer.parseInt(key) - 1].execute(this.input, this.tracker);
}
public void show() {
for (UserAction userAction : this.userAction) {
if (userAction != null) {
System.out.println(userAction.info());
}
}
}
private class AddItem implements UserAction {
@Override
public int key(){
return 1;
}
@Override
public void execute(Input input, Tracker tracker) {
String name = input.ask("Please enter the Task's name ");
String description = input.ask("Please enter the Task's description ");
tracker.add(new Item(name, description));
}
@Override
public String info() {
return String.format("%s. %s", this.key(), "Add new Item");
}
}
private static class ShowItems implements UserAction {
@Override
public int key(){
return 2;
}
@Override
public void execute(Input input, Tracker tracker) {
for (Item item : tracker.getAll()) {
System.out.println(String.format("%s. %s. %s ", item.getId(), item.getName(), item.getDescription()));
}
}
@Override
public String info() {
return String.format("%s. %s", this.key(), "Show items");
}
}
} |
/*
* Java Mysql Proxy
* Main binary. Just listen for connections and pass them over
* to the proxy module
*/
import java.io.*;
import java.util.*;
import java.net.ServerSocket;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class JMP {
public static void main(String[] args) throws IOException {
String mysqlHost = System.getProperty("mysqlHost");
int mysqlPort = Integer.parseInt(System.getProperty("mysqlPort"));
int port = Integer.parseInt(System.getProperty("port"));
boolean listening = true;
ServerSocket listener = null;
ArrayList<Proxy_Plugin> plugins = new ArrayList<Proxy_Plugin>();
Logger logger = Logger.getLogger("JMP");
PropertyConfigurator.configure(System.getProperty("logConf"));
try {
listener = new ServerSocket(port);
}
catch (IOException e) {
logger.fatal("Could not listen on port "+port);
System.exit(-1);
}
String[] ps = System.getProperty("plugins").split(",");
while (listening) {
plugins = new ArrayList<Proxy_Plugin>();
for (String p: ps) {
try {
plugins.add((Proxy_Plugin) Proxy_Plugin.class.getClassLoader().loadClass(p).newInstance());
logger.info("Loaded plugin "+p);
}
catch (java.lang.ClassNotFoundException e) {
logger.error("Failed to load plugin "+p);
continue;
}
catch (java.lang.InstantiationException e) {
logger.error("Failed to load plugin "+p);
continue;
}
catch (java.lang.IllegalAccessException e) {
logger.error("Failed to load plugin "+p);
continue;
}
}
new Proxy(listener.accept(), mysqlHost, mysqlPort, plugins).start();
}
listener.close();
}
} |
package VASSAL.tools;
import java.util.Arrays;
/**
* Provides static methods for calculating hash codes.
*
* @since 3.1.0
* @author Joel Uckelman
* @deprecated Use {@link org.apache.commons.lang3.builder.HashCodeBuilder}
* instead.
*/
@Deprecated
public final class HashCode {
private HashCode() {}
public static int hash(final boolean value) {
return value ? 1 : 0;
}
public static int hash(final byte value) {
return value;
}
public static int hash(final char value) {
return value;
}
public static int hash(final short value) {
return value;
}
public static int hash(final int value) {
return value;
}
public static int hash(final long value) {
return (int)(value ^ (value >>> 32));
}
public static int hash(final float value) {
return Float.floatToIntBits(value);
}
public static int hash(final double value) {
final long bits = Double.doubleToLongBits(value);
return (int)(bits ^ (bits >>> 32));
}
public static int hash(final Object value) {
return value == null ? 0 : value.hashCode();
}
public static int hash(final boolean[] a) {
return Arrays.hashCode(a);
}
public static int hash(final byte[] a) {
return Arrays.hashCode(a);
}
public static int hash(final char[] a) {
return Arrays.hashCode(a);
}
public static int hash(final short[] a) {
return Arrays.hashCode(a);
}
public static int hash(final int[] a) {
return Arrays.hashCode(a);
}
public static int hash(final long[] a) {
return Arrays.hashCode(a);
}
public static int hash(final float[] a) {
return Arrays.hashCode(a);
}
public static int hash(final double[] a) {
return Arrays.hashCode(a);
}
public static <T> int hash(final T[] a) {
return Arrays.hashCode(a);
}
} |
package ucar.nc2.iosp.grid;
import ucar.nc2.*;
import ucar.nc2.iosp.mcidas.McIDASLookup;
import ucar.nc2.iosp.gempak.GempakLookup;
import ucar.nc2.constants._Coordinate;
import ucar.nc2.constants.FeatureType;
import ucar.nc2.dt.fmr.FmrcCoordSys;
import ucar.nc2.units.DateFormatter;
import ucar.nc2.util.CancelTask;
import ucar.grib.grib2.Grib2GridTableLookup;
import ucar.grib.grib1.Grib1GridTableLookup;
import ucar.grib.GribGridRecord;
import ucar.unidata.util.StringUtil;
import ucar.grid.*;
import java.io.*;
import java.util.*;
/**
* Create a Netcdf File from a GridIndex
*
* @author caron
*/
public class GridIndexToNC {
/**
* logger
*/
static private org.slf4j.Logger logger =
org.slf4j.LoggerFactory.getLogger(GridIndexToNC.class);
/**
* map of horizontal coordinate systems
*/
private Map<String,GridHorizCoordSys> hcsHash = new HashMap<String,GridHorizCoordSys>(10); // GridHorizCoordSys
/**
* date formattter
*/
private DateFormatter formatter = new DateFormatter();
/**
* debug flag
*/
private boolean debug = false;
/**
* flag for using GridParameter description for variable names
*/
private boolean useDescriptionForVariableName = true;
/**
* Make the level name
*
* @param gr grid record
* @param lookup lookup table
* @return name for the level
*/
public static String makeLevelName(GridRecord gr, GridTableLookup lookup) {
// for grib2, we need to add the layer to disambiguate
if ( lookup instanceof Grib2GridTableLookup ) {
String vname = lookup.getLevelName(gr);
return lookup.isLayer(gr)
? vname + "_layer"
: vname;
} else {
return lookup.getLevelName(gr); // GEMPAK
}
}
/**
* Get suffix name of variable if it exists
*
* @param gr grid record
* @param lookup lookup table
* @return name of the suffix, ensemble, probability, error, etc
*/
public static String makeSuffixName(GridRecord gr, GridTableLookup lookup) {
if ( ! (lookup instanceof Grib2GridTableLookup) )
return "";
Grib2GridTableLookup g2lookup = (Grib2GridTableLookup) lookup;
return g2lookup.makeSuffix( gr );
}
/**
* Make the variable name
*
* @param gr grid record
* @param lookup lookup table
* @return variable name
*/
public String makeVariableName(GridRecord gr, GridTableLookup lookup) {
GridParameter param = lookup.getParameter(gr);
String levelName = makeLevelName(gr, lookup);
String suffixName = makeSuffixName(gr, lookup);
String paramName = (useDescriptionForVariableName)
? param.getDescription()
: param.getName();
paramName = (suffixName.length() == 0)
? paramName : paramName + "_" + suffixName;
paramName = (levelName.length() == 0)
? paramName : paramName + "_" + levelName;
return paramName;
}
/**
* moved to GridVariable = made sense since it knows what it is
* Make a long name for the variable
*
* @param gr grid record
* @param lookup lookup table
*
* @return long variable name
public static String makeLongName(GridRecord gr, GridTableLookup lookup) {
GridParameter param = lookup.getParameter(gr);
String levelName = makeLevelName(gr, lookup);
return (levelName.length() == 0)
? param.getDescription()
: param.getDescription() + " @ " + makeLevelName(gr, lookup);
}
*/
/**
* Fill in the netCDF file
*
* @param index grid index
* @param lookup lookup table
* @param version version of data
* @param ncfile netCDF file to fill in
* @param fmrcCoordSys forecast model run CS
* @param cancelTask cancel task
* @throws IOException Problem reading from the file
*/
public void open(GridIndex index, GridTableLookup lookup, int version,
NetcdfFile ncfile, FmrcCoordSys fmrcCoordSys,
CancelTask cancelTask)
throws IOException {
// create the HorizCoord Systems : one for each gds
List<GridDefRecord> hcsList = index.getHorizCoordSys();
boolean needGroups = (hcsList.size() > 1);
for (GridDefRecord gds : hcsList) {
Group g = null;
if (needGroups) {
g = new Group(ncfile, null, gds.getGroupName());
ncfile.addGroup(null, g);
}
// (GridDefRecord gdsIndex, String grid_name, String shape_name, Group g)
GridHorizCoordSys hcs = new GridHorizCoordSys(gds, lookup, g);
hcsHash.put(gds.getParam(GridDefRecord.GDS_KEY), hcs);
}
// run through each record
GridRecord firstRecord = null;
List<GridRecord> records = index.getGridRecords();
if (GridServiceProvider.debugOpen) {
System.out.println(" number of products = " + records.size());
}
for (GridRecord gribRecord : records) {
if (firstRecord == null) {
firstRecord = gribRecord;
}
GridHorizCoordSys hcs = hcsHash.get(gribRecord.getGridDefRecordId());
String name = makeVariableName(gribRecord, lookup);
// combo gds, param name and level name
GridVariable pv = (GridVariable) hcs.varHash.get(name);
if (null == pv) {
String pname =
lookup.getParameter(gribRecord).getDescription();
pv = new GridVariable(name, pname, hcs, lookup);
hcs.varHash.put(name, pv);
// keep track of all products with same parameter name
List<GridVariable> plist = hcs.productHash.get(pname);
if (null == plist) {
plist = new ArrayList<GridVariable>();
hcs.productHash.put(pname, plist);
}
plist.add(pv);
}
pv.addProduct(gribRecord);
}
// global stuff
ncfile.addAttribute(null, new Attribute("Conventions", "CF-1.0"));
String creator = null;
if ( lookup instanceof Grib2GridTableLookup ) {
Grib2GridTableLookup g2lookup = (Grib2GridTableLookup) lookup;
creator = g2lookup.getFirstCenterName()
+ " subcenter = " + g2lookup.getFirstSubcenterId();
if (creator != null)
ncfile.addAttribute(null, new Attribute("Originating_center", creator));
String genType = g2lookup.getTypeGenProcessName(firstRecord);
if (genType != null)
ncfile.addAttribute(null, new Attribute("Generating_Process_or_Model", genType));
if (null != g2lookup.getFirstProductStatusName())
ncfile.addAttribute(null, new Attribute("Product_Status", g2lookup.getFirstProductStatusName()));
ncfile.addAttribute(null, new Attribute("Product_Type", g2lookup.getFirstProductTypeName()));
} else if ( lookup instanceof Grib1GridTableLookup ) {
Grib1GridTableLookup g1lookup = (Grib1GridTableLookup) lookup;
creator = g1lookup.getFirstCenterName()
+ " subcenter = " + g1lookup.getFirstSubcenterId();
if (creator != null)
ncfile.addAttribute(null, new Attribute("Originating_center", creator));
String genType = g1lookup.getTypeGenProcessName(firstRecord);
if (genType != null)
ncfile.addAttribute(null, new Attribute("Generating_Process_or_Model", genType));
if (null != g1lookup.getFirstProductStatusName())
ncfile.addAttribute(null, new Attribute("Product_Status", g1lookup.getFirstProductStatusName()));
ncfile.addAttribute(null, new Attribute("Product_Type", g1lookup.getFirstProductTypeName()));
}
// dataset discovery
ncfile.addAttribute(null, new Attribute("cdm_data_type", FeatureType.GRID.toString()));
if ( creator != null)
ncfile.addAttribute(null, new Attribute("creator_name", creator));
ncfile.addAttribute(null, new Attribute("file_format", lookup.getGridType()));
ncfile.addAttribute(null,
new Attribute("location", ncfile.getLocation()));
ncfile.addAttribute(null, new Attribute(
"history", "Direct read of "+ lookup.getGridType() +" into NetCDF-Java 4.0 API"));
ncfile.addAttribute(
null,
new Attribute(
_Coordinate.ModelRunDate,
formatter.toDateTimeStringISO(lookup.getFirstBaseTime())));
if (fmrcCoordSys != null) {
makeDefinedCoordSys(ncfile, lookup, fmrcCoordSys);
} else {
makeDenseCoordSys(ncfile, lookup, cancelTask);
}
if (GridServiceProvider.debugMissing) {
int count = 0;
Collection<GridHorizCoordSys> hcset = hcsHash.values();
for (GridHorizCoordSys hcs : hcset) {
List<GridVariable> gribvars = new ArrayList<GridVariable>(hcs.varHash.values());
for (GridVariable gv : gribvars) {
count += gv.dumpMissingSummary();
}
}
System.out.println(" total missing= " + count);
}
if (GridServiceProvider.debugMissingDetails) {
Collection<GridHorizCoordSys> hcset = hcsHash.values();
for (GridHorizCoordSys hcs : hcset) {
System.out.println("******** Horiz Coordinate= " + hcs.getGridName());
String lastVertDesc = null;
List<GridVariable> gribvars = new ArrayList<GridVariable>(hcs.varHash.values());
Collections.sort(gribvars, new CompareGridVariableByVertName());
for (GridVariable gv : gribvars) {
String vertDesc = gv.getVertName();
if (!vertDesc.equals(lastVertDesc)) {
System.out.println("---Vertical Coordinate= " + vertDesc);
lastVertDesc = vertDesc;
}
gv.dumpMissing();
}
}
}
// clean out stuff we dont need anymore
//for (GridHorizCoordSys ghcs : hcsHash.values()) {
// ghcs.empty();
}
// debugging
public GridHorizCoordSys getHorizCoordSys(GridRecord gribRecord) {
return hcsHash.get(gribRecord.getGridDefRecordId());
}
public Map<String,GridHorizCoordSys> getHorizCoordSystems() {
return hcsHash;
}
/**
* Make coordinate system without missing data - means that we
* have to make a coordinate axis for each unique set
* of time or vertical levels.
*
* @param ncfile netCDF file
* @param lookup lookup table
* @param cancelTask cancel task
* @throws IOException problem reading file
*/
private void makeDenseCoordSys(NetcdfFile ncfile, GridTableLookup lookup, CancelTask cancelTask) throws IOException {
List<GridTimeCoord> timeCoords = new ArrayList<GridTimeCoord>();
List<GridVertCoord> vertCoords = new ArrayList<GridVertCoord>();
List<Integer> ensembleDimension = new ArrayList<Integer>();
// loop over HorizCoordSys
Collection<GridHorizCoordSys> hcset = hcsHash.values();
for (GridHorizCoordSys hcs : hcset) {
if ((cancelTask != null) && cancelTask.isCancel()) break;
// loop over GridVariables in the HorizCoordSys
// create the time and vertical coordinates
List<GridVariable> gribvars = new ArrayList<GridVariable>(hcs.varHash.values());
for (GridVariable pv : gribvars) {
if ((cancelTask != null) && cancelTask.isCancel()) break;
List<GridRecord> recordList = pv.getRecords();
GridRecord record = recordList.get(0);
String vname = makeLevelName(record, lookup);
// look to see if vertical already exists
GridVertCoord useVertCoord = null;
for (GridVertCoord gvcs : vertCoords) {
if (vname.equals(gvcs.getLevelName())) {
if (gvcs.matchLevels(recordList)) { // must have the same levels
useVertCoord = gvcs;
}
}
}
if (useVertCoord == null) { // nope, got to create it
useVertCoord = new GridVertCoord(recordList, vname, lookup);
vertCoords.add(useVertCoord);
}
pv.setVertCoord(useVertCoord);
// look to see if time coord already exists
GridTimeCoord useTimeCoord = null;
for (GridTimeCoord gtc : timeCoords) {
if (gtc.matchLevels(recordList)) { // must have the same levels
useTimeCoord = gtc;
}
}
if (useTimeCoord == null) { // nope, got to create it
useTimeCoord = new GridTimeCoord(recordList, lookup);
timeCoords.add(useTimeCoord);
}
pv.setTimeCoord(useTimeCoord);
// check for ensemble members
int ensemble = 0;
GridRecord first = recordList.get( 0 );
if ( first instanceof GribGridRecord ) { // check for ensemble
GribGridRecord ggr = (GribGridRecord) first;
int key = ggr.getRecordKey();
for( int i = 1; i < recordList.size(); i++) {
ggr = (GribGridRecord) recordList.get( i );
if (key == ggr.getRecordKey() ) {
ensemble++;
}
}
ensembleDimension.add( new Integer( ensemble ));
}
}
//// assign time coordinate names
// find time dimensions with largest length
GridTimeCoord tcs0 = null;
int maxTimes = 0;
for (GridTimeCoord tcs : timeCoords) {
if (tcs.getNTimes() > maxTimes) {
tcs0 = tcs;
maxTimes = tcs.getNTimes();
}
}
// add time dimensions, give time dimensions unique names
int seqno = 1;
for (GridTimeCoord tcs : timeCoords) {
if (tcs != tcs0) {
tcs.setSequence(seqno++);
}
tcs.addDimensionsToNetcdfFile(ncfile, hcs.getGroup());
}
// add x, y dimensions
hcs.addDimensionsToNetcdfFile(ncfile);
// add vertical dimensions, give them unique names
Collections.sort(vertCoords);
int vcIndex = 0;
String listName = null;
int start = 0;
for (vcIndex = 0; vcIndex < vertCoords.size(); vcIndex++) {
GridVertCoord gvcs = (GridVertCoord) vertCoords.get(vcIndex);
String vname = gvcs.getLevelName();
if (listName == null) {
listName = vname; // initial
}
if (!vname.equals(listName)) {
makeVerticalDimensions(vertCoords.subList(start, vcIndex), ncfile, hcs.getGroup());
listName = vname;
start = vcIndex;
}
}
makeVerticalDimensions(vertCoords.subList(start, vcIndex), ncfile, hcs.getGroup());
// create a variable for each entry, but check for other products with same desc
// to disambiguate by vertical coord
List<List<GridVariable>> products = new ArrayList<List<GridVariable>>(hcs.productHash.values());
Collections.sort( products, new CompareGridVariableListByName());
for (List<GridVariable> plist : products) {
if ((cancelTask != null) && cancelTask.isCancel()) break;
if (plist.size() == 1) {
GridVariable pv = plist.get(0);
Variable v;
if ( (lookup instanceof GempakLookup) || (lookup instanceof McIDASLookup )) {
v = pv.makeVariable(ncfile, hcs.getGroup(), false );
} else {
v = pv.makeVariable(ncfile, hcs.getGroup(), true);
}
ncfile.addVariable(hcs.getGroup(), v);
} else {
Collections.sort(plist, new CompareGridVariableByNumberVertLevels());
boolean isGrib2 = false;
Grib2GridTableLookup g2lookup = null;
if ( (lookup instanceof Grib2GridTableLookup) ) {
g2lookup = (Grib2GridTableLookup) lookup;
isGrib2 = true;
}
// finally, add the variables
for (int k = 0; k < plist.size(); k++) {
GridVariable pv = plist.get(k);
if (isGrib2 && g2lookup.isEnsemble( pv.getFirstRecord()) ||
(lookup instanceof GempakLookup) || (lookup instanceof McIDASLookup ) ) {
ncfile.addVariable(hcs.getGroup(), pv.makeVariable(ncfile, hcs.getGroup(), false));
} else {
ncfile.addVariable(hcs.getGroup(), pv.makeVariable(ncfile, hcs.getGroup(), (k == 0)));
}
}
} // multipe vertical levels
} // create variable
// add coordinate variables at the end
for (GridTimeCoord tcs : timeCoords) {
tcs.addToNetcdfFile(ncfile, hcs.getGroup());
}
hcs.addToNetcdfFile(ncfile);
for (GridVertCoord gvcs : vertCoords) {
gvcs.addToNetcdfFile(ncfile, hcs.getGroup());
}
} // loop over hcs
// TODO: check this, in ToolsUI
//for (GridVertCoord gvcs : vertCoords) {
// gvcs.empty();
}
/**
* Make a vertical dimensions
*
* @param vertCoordList vertCoords all with the same name
* @param ncfile netCDF file to add to
* @param group group in ncfile
*/
private void makeVerticalDimensions(List<GridVertCoord> vertCoordList, NetcdfFile ncfile, Group group) {
// find biggest vert coord
GridVertCoord gvcs0 = null;
int maxLevels = 0;
for (GridVertCoord gvcs : vertCoordList) {
if (gvcs.getNLevels() > maxLevels) {
gvcs0 = gvcs;
maxLevels = gvcs.getNLevels();
}
}
int seqno = 1;
for (GridVertCoord gvcs : vertCoordList) {
if (gvcs != gvcs0) {
gvcs.setSequence(seqno++);
}
gvcs.addDimensionsToNetcdfFile(ncfile, group);
}
}
/**
* Make coordinate system from a Definition object
*
* @param ncfile netCDF file to add to
* @param lookup lookup table
* @param fmr FmrcCoordSys
* @throws IOException problem reading from file
*/
private void makeDefinedCoordSys(NetcdfFile ncfile,
GridTableLookup lookup, FmrcCoordSys fmr) throws IOException {
List<GridTimeCoord> timeCoords = new ArrayList<GridTimeCoord>();
List<GridVertCoord> vertCoords = new ArrayList<GridVertCoord>();
List<String> removeVariables = new ArrayList<String>();
// loop over HorizCoordSys
Collection<GridHorizCoordSys> hcset = hcsHash.values();
for (GridHorizCoordSys hcs : hcset) {
// loop over GridVariables in the HorizCoordSys
// create the time and vertical coordinates
Set<String> keys = hcs.varHash.keySet();
for (String key : keys) {
GridVariable pv = hcs.varHash.get(key);
GridRecord record = pv.getFirstRecord();
// we dont know the name for sure yet, so have to try several
String searchName = findVariableName(ncfile, record, lookup, fmr);
if (searchName == null) { // cant find - just remove
removeVariables.add(key); // cant remove (concurrentModException) so save for later
continue;
}
pv.setVarName( searchName);
// get the vertical coordinate for this variable, if it exists
FmrcCoordSys.VertCoord vc_def = fmr.findVertCoordForVariable( searchName);
if (vc_def != null) {
String vc_name = vc_def.getName();
// look to see if GridVertCoord already made
GridVertCoord useVertCoord = null;
for (GridVertCoord gvcs : vertCoords) {
if (vc_name.equals(gvcs.getLevelName()))
useVertCoord = gvcs;
}
if (useVertCoord == null) { // nope, got to create it
useVertCoord = new GridVertCoord(record, vc_name, lookup, vc_def.getValues1(), vc_def.getValues2());
useVertCoord.addDimensionsToNetcdfFile( ncfile, hcs.getGroup());
vertCoords.add( useVertCoord);
}
pv.setVertCoord( useVertCoord);
} else {
pv.setVertCoord( new GridVertCoord(searchName)); // fake
}
// get the time coordinate for this variable
FmrcCoordSys.TimeCoord tc_def = fmr.findTimeCoordForVariable( searchName, lookup.getFirstBaseTime());
String tc_name = tc_def.getName();
// look to see if GridTimeCoord already made
GridTimeCoord useTimeCoord = null;
for (GridTimeCoord gtc : timeCoords) {
if (tc_name.equals(gtc.getName()))
useTimeCoord = gtc;
}
if (useTimeCoord == null) { // nope, got to create it
useTimeCoord = new GridTimeCoord(tc_name, tc_def.getOffsetHours(), lookup);
useTimeCoord.addDimensionsToNetcdfFile( ncfile, hcs.getGroup());
timeCoords.add( useTimeCoord);
}
pv.setTimeCoord( useTimeCoord);
}
// any need to be removed?
for (String key : removeVariables) {
hcs.varHash.remove(key);
}
// add x, y dimensions
hcs.addDimensionsToNetcdfFile( ncfile);
// create a variable for each entry
Collection<GridVariable> vars = hcs.varHash.values();
for (GridVariable pv : vars) {
Group g = hcs.getGroup() == null ? ncfile.getRootGroup() : hcs.getGroup();
Variable v = pv.makeVariable(ncfile, g, true);
if (g.findVariable( v.getShortName()) != null) { // already got. can happen when a new vert level is added
logger.warn("GribGridServiceProvider.GridIndexToNC: FmrcCoordSys has 2 variables mapped to ="+v.getShortName()+
" for file "+ncfile.getLocation());
} else
g.addVariable( v);
}
// add coordinate variables at the end
for (GridTimeCoord tcs : timeCoords) {
tcs.addToNetcdfFile(ncfile, hcs.getGroup());
}
hcs.addToNetcdfFile( ncfile);
for (GridVertCoord gvcs : vertCoords) {
gvcs.addToNetcdfFile(ncfile, hcs.getGroup());
}
} // loop over hcs
if (debug) System.out.println("GridIndexToNC.makeDefinedCoordSys for "+ncfile.getLocation());
}
/**
* Find the variable name for the grid
*
* @param ncfile netCDF file
* @param gr grid record
* @param lookup lookup table
* @param fmr FmrcCoordSys
* @return name for the grid
*
private String findVariableName(NetcdfFile ncfile, GridRecord gr, GridTableLookup lookup, FmrcCoordSys fmr) {
// first lookup with name & vert name
String name = AbstractIOServiceProvider.createValidNetcdfObjectName(makeVariableName(gr, lookup));
if (fmr.hasVariable(name)) {
return name;
}
// now try just the name
String pname = AbstractIOServiceProvider.createValidNetcdfObjectName( lookup.getParameter(gr).getDescription());
if (fmr.hasVariable(pname)) {
return pname;
}
logger.warn( "GridIndexToNC: FmrcCoordSys does not have the variable named ="
+ name + " or " + pname + " for file " + ncfile.getLocation());
return null;
} */
private String findVariableName(NetcdfFile ncfile, GridRecord gr, GridTableLookup lookup, FmrcCoordSys fmr) {
// first lookup with name & vert name
String name = makeVariableName(gr, lookup);
if (debug)
System.out.println( "name ="+ name );
if (fmr.hasVariable( name))
return name;
// now try just the name
String pname = lookup.getParameter(gr).getDescription();
if (debug)
System.out.println( "pname ="+ pname );
if (fmr.hasVariable( pname))
return pname;
// try replacing the blanks
String nameWunder = StringUtil.replace(name, ' ', "_");
if (debug)
System.out.println( "nameWunder ="+ nameWunder );
if (fmr.hasVariable( nameWunder))
return nameWunder;
String pnameWunder = StringUtil.replace(pname, ' ', "_");
if (debug)
System.out.println( "pnameWunder ="+ pnameWunder );
if (fmr.hasVariable( pnameWunder))
return pnameWunder;
logger.warn("GridServiceProvider.GridIndexToNC: FmrcCoordSys does not have the variable named ="+name+" or "+pname+" or "+
nameWunder+" or "+pnameWunder+" for file "+ncfile.getLocation());
return null;
}
/**
* Comparable object for grid variable
*
* @author IDV Development Team
* @version $Revision: 1.3 $
*/
private class CompareGridVariableListByName implements Comparator {
/**
* Compare the two lists of names
*
* @param o1 first list
* @param o2 second list
* @return comparison
*/
public int compare(Object o1, Object o2) {
ArrayList list1 = (ArrayList) o1;
ArrayList list2 = (ArrayList) o2;
GridVariable gv1 = (GridVariable) list1.get(0);
GridVariable gv2 = (GridVariable) list2.get(0);
return gv1.getName().compareToIgnoreCase(gv2.getName());
}
}
/**
* Comparator for grids by vertical variable name
*
* @author IDV Development Team
* @version $Revision: 1.3 $
*/
private class CompareGridVariableByVertName implements Comparator {
/**
* Compare the two lists of names
*
* @param o1 first list
* @param o2 second list
* @return comparison
*/
public int compare(Object o1, Object o2) {
GridVariable gv1 = (GridVariable) o1;
GridVariable gv2 = (GridVariable) o2;
return gv1.getVertName().compareToIgnoreCase(gv2.getVertName());
}
}
/**
* Comparator for grid variables by number of vertical levels
*
* @author IDV Development Team
* @version $Revision: 1.3 $
*/
private class CompareGridVariableByNumberVertLevels implements Comparator {
/**
* Compare the two lists of names
*
* @param o1 first list
* @param o2 second list
* @return comparison
*/
public int compare(Object o1, Object o2) {
GridVariable gv1 = (GridVariable) o1;
GridVariable gv2 = (GridVariable) o2;
int n1 = gv1.getVertCoord().getNLevels();
int n2 = gv2.getVertCoord().getNLevels();
if (n1 == n2) { // break ties for consistency
return gv1.getVertCoord().getLevelName().compareTo(
gv2.getVertCoord().getLevelName());
} else {
return n2 - n1; // highest number first
}
}
}
/**
* Should use the description for the variable name.
*
* @param value false to use name instead of description
*/
public void setUseDescriptionForVariableName(boolean value) {
useDescriptionForVariableName = value;
}
} |
package com.badlogic.gdx.scenes.scene2d.ui;
import static com.badlogic.gdx.scenes.scene2d.actions.Actions.*;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Interpolation;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Group;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle;
import com.badlogic.gdx.scenes.scene2d.utils.Align;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.badlogic.gdx.scenes.scene2d.utils.FocusListener;
import com.badlogic.gdx.scenes.scene2d.utils.FocusListener.FocusEvent;
import com.badlogic.gdx.utils.ObjectMap;
/** Displays a dialog, which is a modal window containing a content table with a button table underneath it. Methods are provided
* to add a label to the content table and buttons to the button table, but any widgets can be added. When a button is clicked,
* {@link #result(Object)} is called and the dialog is removed from the stage.
* @author Nathan Sweet */
public class Dialog extends Window {
/** The time in seconds that dialogs will fade in and out. Set to zero to disable fading. */
static public float fadeDuration = 0.4f;
Table contentTable, buttonTable;
private Skin skin;
ObjectMap<Actor, Object> values = new ObjectMap();
boolean cancelHide;
Actor previousKeyboardFocus, previousScrollFocus;
public Dialog (String title, Skin skin) {
super(title, skin.get(WindowStyle.class));
this.skin = skin;
initialize();
}
public Dialog (String title, Skin skin, String windowStyleName) {
super(title, skin.get(windowStyleName, WindowStyle.class));
this.skin = skin;
initialize();
}
public Dialog (String title, WindowStyle windowStyle) {
super(title, windowStyle);
initialize();
}
private void initialize () {
setModal(true);
defaults().space(6);
add(contentTable = new Table(skin)).expand().fill();
row();
add(buttonTable = new Table(skin));
contentTable.defaults().space(6);
buttonTable.defaults().space(6);
buttonTable.addListener(new ChangeListener() {
public void changed (ChangeEvent event, Actor actor) {
while (actor.getParent() != buttonTable)
actor = actor.getParent();
result(values.get(actor));
if (!cancelHide) hide();
cancelHide = false;
}
});
addListener(new FocusListener() {
public void keyboardFocusChanged (FocusEvent event, Actor actor, boolean focused) {
if (!focused) focusChanged(event);
}
public void scrollFocusChanged (FocusEvent event, Actor actor, boolean focused) {
if (!focused) focusChanged(event);
}
private void focusChanged (FocusEvent event) {
Stage stage = getStage();
if (isModal && stage != null && stage.getRoot().getChildren().peek() == Dialog.this) { // Dialog is top most actor.
Actor newFocusedActor = event.getRelatedActor();
if (newFocusedActor == null || !newFocusedActor.isDescendantOf(Dialog.this)) event.cancel();
}
}
});
}
public Table getContentTable () {
return contentTable;
}
public Table getButtonTable () {
return buttonTable;
}
/** Adds a label to the content table. The dialog must have been constructed with a skin to use this method. */
public Dialog text (String text) {
if (skin == null)
throw new IllegalStateException("This method may only be used if the dialog was constructed with a Skin.");
return text(text, skin.get(LabelStyle.class));
}
/** Adds a label to the content table. */
public Dialog text (String text, LabelStyle labelStyle) {
return text(new Label(text, labelStyle));
}
/** Adds the given Label to the content table */
public Dialog text (Label label) {
contentTable.add(label);
return this;
}
/** Adds a text button to the button table. Null will be passed to {@link #result(Object)} if this button is clicked. The dialog
* must have been constructed with a skin to use this method. */
public Dialog button (String text) {
return button(text, null);
}
/** Adds a text button to the button table. The dialog must have been constructed with a skin to use this method.
* @param object The object that will be passed to {@link #result(Object)} if this button is clicked. May be null. */
public Dialog button (String text, Object object) {
if (skin == null)
throw new IllegalStateException("This method may only be used if the dialog was constructed with a Skin.");
return button(text, object, skin.get(TextButtonStyle.class));
}
/** Adds a text button to the button table.
* @param object The object that will be passed to {@link #result(Object)} if this button is clicked. May be null. */
public Dialog button (String text, Object object, TextButtonStyle buttonStyle) {
return button(new TextButton(text, buttonStyle), object);
}
/** Adds the given button to the button table. */
public Dialog button (Button button) {
return button(button, null);
}
/** Adds the given button to the button table.
* @param object The object that will be passed to {@link #result(Object)} if this button is clicked. May be null. */
public Dialog button (Button button, Object object) {
buttonTable.add(button);
setObject(button, object);
return this;
}
/** {@link #pack() Packs} the dialog and adds it to the stage, centered. */
public Dialog show (Stage stage) {
previousKeyboardFocus = stage.getKeyboardFocus();
previousScrollFocus = stage.getScrollFocus();
stage.setKeyboardFocus(this);
stage.setScrollFocus(this);
pack();
setPosition(Math.round((stage.getWidth() - getWidth()) / 2), Math.round((stage.getHeight() - getHeight()) / 2));
stage.addActor(this);
if (fadeDuration > 0) {
getColor().a = 0;
addAction(Actions.fadeIn(fadeDuration, Interpolation.fade));
}
return this;
}
/** Hides the dialog. Called automatically when a button is clicked. The default implementation fades out the dialog over
* {@link #fadeDuration} seconds and then removes it from the stage. */
public void hide () {
addAction(sequence(fadeOut(fadeDuration, Interpolation.fade), Actions.removeActor()));
}
protected void setParent (Group parent) {
super.setParent(parent);
if (parent == null) {
Stage stage = getStage();
if (stage != null) {
Actor actor = stage.getKeyboardFocus();
if (actor == this || actor == null) stage.setKeyboardFocus(previousKeyboardFocus);
actor = stage.getScrollFocus();
if (actor == this || actor == null) stage.setScrollFocus(previousScrollFocus);
}
}
}
public void setObject (Actor actor, Object object) {
values.put(actor, object);
}
/** If this key is pressed, {@link #result(Object)} is called with the specified object.
* @see Keys */
public Dialog key (final int keycode, final Object object) {
addListener(new InputListener() {
public boolean keyDown (InputEvent event, int keycode2) {
if (keycode == keycode2) {
result(object);
if (!cancelHide) hide();
cancelHide = false;
}
return false;
}
});
return this;
}
/** Called when a button is clicked. The dialog will be hidden after this method returns unless {@link #cancel()} is called.
* @param object The object specified when the button was added. */
protected void result (Object object) {
}
public void cancel () {
cancelHide = true;
}
} |
package org.ggp.base.apps.server;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
import org.ggp.base.apps.server.error.ErrorPanel;
import org.ggp.base.apps.server.history.HistoryPanel;
import org.ggp.base.apps.server.publishing.PublishingPanel;
import org.ggp.base.apps.server.states.StatesPanel;
import org.ggp.base.apps.server.visualization.VisualizationPanel;
import org.ggp.base.server.GameServer;
import org.ggp.base.util.game.Game;
import org.ggp.base.util.gdl.grammar.GdlPool;
import org.ggp.base.util.match.Match;
import org.ggp.base.util.statemachine.Role;
import org.ggp.base.util.statemachine.StateMachine;
import org.ggp.base.util.statemachine.implementation.prover.ProverStateMachine;
import org.ggp.base.util.ui.GameSelector;
import org.ggp.base.util.ui.NativeUI;
@SuppressWarnings("serial")
public final class ServerPanel extends JPanel implements ActionListener
{
private static void createAndShowGUI(ServerPanel serverPanel)
{
JFrame frame = new JFrame("Game Server");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(1200, 900));
frame.getContentPane().add(serverPanel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args)
{
NativeUI.setNativeUI();
GdlPool.caseSensitive = false;
final ServerPanel serverPanel = new ServerPanel();
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI(serverPanel);
}
});
}
private Game theGame;
private final List<JTextField> hostportTextFields;
private final JPanel managerPanel;
private final JTabbedPane matchesTabbedPane;
private final JTextField playClockTextField;
private final List<JTextField> playerNameTextFields;
private final List<JLabel> roleLabels;
private final JButton runButton;
private final JTextField startClockTextField;
private final GameSelector gameSelector;
public ServerPanel()
{
super(new GridBagLayout());
runButton = new JButton(runButtonMethod(this));
startClockTextField = new JTextField("30");
playClockTextField = new JTextField("15");
managerPanel = new JPanel(new GridBagLayout());
matchesTabbedPane = new JTabbedPane();
roleLabels = new ArrayList<JLabel>();
hostportTextFields = new ArrayList<JTextField>();
playerNameTextFields = new ArrayList<JTextField>();
theGame = null;
runButton.setEnabled(false);
startClockTextField.setColumns(15);
playClockTextField.setColumns(15);
gameSelector = new GameSelector();
int nRowCount = 0;
managerPanel.setBorder(new TitledBorder("Manager"));
managerPanel.add(new JLabel("Repository:"), new GridBagConstraints(0, nRowCount, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 5, 5));
managerPanel.add(gameSelector.getRepositoryList(), new GridBagConstraints(1, nRowCount++, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 5, 5));
managerPanel.add(new JLabel("Game:"), new GridBagConstraints(0, nRowCount, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 5, 5));
managerPanel.add(gameSelector.getGameList(), new GridBagConstraints(1, nRowCount++, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 5, 5));
managerPanel.add(new JSeparator(), new GridBagConstraints(0, nRowCount++, 2, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 5, 5));
managerPanel.add(new JLabel("Start Clock:"), new GridBagConstraints(0, nRowCount, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 5, 5));
managerPanel.add(startClockTextField, new GridBagConstraints(1, nRowCount++, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 5, 5));
managerPanel.add(new JLabel("Play Clock:"), new GridBagConstraints(0, nRowCount, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 5, 5));
managerPanel.add(playClockTextField, new GridBagConstraints(1, nRowCount++, 1, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 5, 5));
managerPanel.add(new JSeparator(), new GridBagConstraints(0, nRowCount++, 2, 1, 0.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 5, 5));
managerPanel.add(runButton, new GridBagConstraints(1, nRowCount, 1, 1, 0.0, 1.0, GridBagConstraints.SOUTH, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
JPanel matchesPanel = new JPanel(new GridBagLayout());
matchesPanel.setBorder(new TitledBorder("Matches"));
matchesPanel.add(matchesTabbedPane, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 5, 5));
this.add(managerPanel, new GridBagConstraints(0, 0, 1, 1, 0.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 5, 5));
this.add(matchesPanel, new GridBagConstraints(1, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 5, 5));
gameSelector.getGameList().addActionListener(this);
gameSelector.repopulateGameList();
}
private AbstractAction runButtonMethod(final ServerPanel serverPanel)
{
return new AbstractAction("Run")
{
public void actionPerformed(ActionEvent evt)
{
try
{
String matchId = "BaseServer." + serverPanel.theGame.getKey() + "." + System.currentTimeMillis();
int startClock = Integer.valueOf(serverPanel.startClockTextField.getText());
int playClock = Integer.valueOf(serverPanel.playClockTextField.getText());
Match match = new Match(matchId, -1, startClock, playClock, serverPanel.theGame);
List<String> hosts = new ArrayList<String>(serverPanel.hostportTextFields.size());
List<Integer> ports = new ArrayList<Integer>(serverPanel.hostportTextFields.size());
for (JTextField textField : serverPanel.hostportTextFields)
{
try {
String[] splitAddress = textField.getText().split(":");
String hostname = splitAddress[0];
int port = Integer.parseInt(splitAddress[1]);
hosts.add(hostname);
ports.add(port);
} catch(Exception ex) {
ex.printStackTrace();
return;
}
}
List<String> playerNames = new ArrayList<String>(serverPanel.playerNameTextFields.size());
for (JTextField textField : serverPanel.playerNameTextFields)
{
playerNames.add(textField.getText());
}
HistoryPanel historyPanel = new HistoryPanel();
ErrorPanel errorPanel = new ErrorPanel();
VisualizationPanel visualizationPanel = new VisualizationPanel(theGame);
StatesPanel statesPanel = new StatesPanel();
JTabbedPane tab = new JTabbedPane();
tab.addTab("History", historyPanel);
tab.addTab("Error", errorPanel);
tab.addTab("Visualization", visualizationPanel);
tab.addTab("States", statesPanel);
serverPanel.matchesTabbedPane.addTab(matchId, tab);
serverPanel.matchesTabbedPane.setSelectedIndex(serverPanel.matchesTabbedPane.getTabCount()-1);
GameServer gameServer = new GameServer(match, hosts, ports, playerNames);
gameServer.addObserver(errorPanel);
gameServer.addObserver(historyPanel);
gameServer.addObserver(visualizationPanel);
gameServer.addObserver(statesPanel);
gameServer.start();
tab.addTab("Publishing", new PublishingPanel(gameServer));
}
catch (Exception e)
{
// Do nothing.
}
}
};
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == gameSelector.getGameList()) {
theGame = gameSelector.getSelectedGame();
for (int i = 0; i < roleLabels.size(); i++)
{
managerPanel.remove(roleLabels.get(i));
managerPanel.remove(hostportTextFields.get(i));
managerPanel.remove(playerNameTextFields.get(i));
}
roleLabels.clear();
hostportTextFields.clear();
playerNameTextFields.clear();
validate();
runButton.setEnabled(false);
if (theGame == null)
return;
StateMachine stateMachine = new ProverStateMachine();
stateMachine.initialize(theGame.getRules());
List<Role> roles = stateMachine.getRoles();
int newRowCount = 7;
for (int i = 0; i < roles.size(); i++) {
roleLabels.add(new JLabel(roles.get(i).getName().toString() + ":"));
hostportTextFields.add(new JTextField("localhost:" + (i + 9147)));
playerNameTextFields.add(new JTextField("defaultPlayerName"));
hostportTextFields.get(i).setColumns(15);
playerNameTextFields.get(i).setColumns(15);
managerPanel.add(roleLabels.get(i), new GridBagConstraints(0, newRowCount, 1, 1, 1.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 5, 5));
managerPanel.add(hostportTextFields.get(i), new GridBagConstraints(1, newRowCount++, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 5, 5));
managerPanel.add(playerNameTextFields.get(i), new GridBagConstraints(1, newRowCount++, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 5, 5));
}
managerPanel.add(runButton, new GridBagConstraints(1, newRowCount, 1, 1, 0.0, 1.0, GridBagConstraints.SOUTH, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
validate();
runButton.setEnabled(true);
}
}
} |
package com.neno0o.ubersdk;
public class UberURLs {
public static final String SCOPE_PROFILE = "profile";
public static final String SCOPE_HISTORY_LITE = "history_lite";
public static final String SCOPE_REQUEST = "request";
public static final String OAUTH_URL = "https://login.uber.com";
public static final String AUTHORIZE_URL = "https://login.uber.com/oauth/v2/authorize";
public static final String API_URL = "https://api.uber.com";
public static final String SANDBOX_URL = "https://sandbox-api.uber.com";
} |
// AWTCursors.java
package imagej.awt;
import imagej.display.MouseCursor;
import java.awt.Cursor;
/**
* Translates ImageJ {@link MouseCursor}s into AWT {@link Cursor}s.
*
* @author Grant Harris
* @author Curtis Rueden
*/
public final class AWTCursors {
private AWTCursors() {
// prevent instantiation of utility class
}
/**
* Gets the AWT {@link Cursor} corresponding to the given ImageJ
* {@link MouseCursor}.
*/
public static Cursor getCursor(final MouseCursor cursorCode) {
return Cursor.getPredefinedCursor(getCursorCode(cursorCode));
}
/**
* Gets the AWT cursor code corresponding to the given ImageJ
* {@link MouseCursor}.
*/
public static int getCursorCode(final MouseCursor cursorCode) {
switch (cursorCode) {
case DEFAULT:
return Cursor.DEFAULT_CURSOR;
case OFF:
return Cursor.CUSTOM_CURSOR;
case HAND:
return Cursor.HAND_CURSOR;
case CROSSHAIR:
return Cursor.CROSSHAIR_CURSOR;
case MOVE:
return Cursor.MOVE_CURSOR;
case TEXT:
return Cursor.TEXT_CURSOR;
case WAIT:
return Cursor.WAIT_CURSOR;
case N_RESIZE:
return Cursor.N_RESIZE_CURSOR;
case S_RESIZE:
return Cursor.S_RESIZE_CURSOR;
case W_RESIZE:
return Cursor.W_RESIZE_CURSOR;
case E_RESIZE:
return Cursor.E_RESIZE_CURSOR;
case NW_RESIZE:
return Cursor.NW_RESIZE_CURSOR;
case NE_RESIZE:
return Cursor.NE_RESIZE_CURSOR;
case SW_RESIZE:
return Cursor.SW_RESIZE_CURSOR;
case SE_RESIZE:
return Cursor.SE_RESIZE_CURSOR;
default:
return Cursor.DEFAULT_CURSOR;
}
}
} |
package ru.job4j.maximum;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* MaxTest class.
* @author Yury Chuksin (chuksin.yury@gmail.com)
* @since 18.01.2017
*/
public class MaxTest {
/**
* maximum value of maximum from two variables.
*/
private final int mTest = 10;
/**
* Making new empty object Max.
* @see Max
*/
private Max max = new Max();
/**
* WhenDoMaxFromTwoThenSearchMaximum checks is this method returns maximum from two variables.
*/
@Test
public void whenDoMaxFromTwoThenSearchMaximum() {
assertThat(this.mTest, is(this.max.maxFromTwo(10, 5)));
}
/**
* WhenDoMaxFromTwoThenSearchMaximum checks is this method returns maximum from two variables.
*/
@Test
public void whenDoMaxFromThreeThenSearchMaximum() {
assertThat(this.mTest, is(this.max.maxFromThree(1, 10, 5)));
}
} |
package com.heartbeat.pin;
import com.heartbeat.pin.command.PinCommand;
import com.heartbeat.pin.command.PinCommandException;
import java.io.File;
/**
* A class for Pin. Stores necessary data and some pin lifecycle methods like
* <ul>
* <li>enable</li>
* <li>disable</li>
* <li>write</li>
* <li>read</li>
* <li>setMode</li>
* </ul>
* Holds code forex. "408" and path "/sys/class/gpio/gpio408
*/
public class Pin {
/* Pins
*
* X10-P0: 408
* X10-P1: 409
* X10-P2: 410
* X10-P3: 411
* X10-P4: 412
* X10-P5: 413
* X10-P6: 414
* X10-P7: 415
*/
private final String code;
private final File path;
protected Mode mode;
private final PinCommand command;
private boolean enabled;
protected Pin(String code, Mode mode, PinCommand command) throws PinCommandException {
this.code = code;
this.path = command.path(this);
this.enabled = false;
this.command = command;
enable();
setMode(mode);
}
protected Pin(String code, File path, Mode mode, PinCommand command) throws PinCommandException {
this.code = code;
this.path = path;
this.enabled = false;
this.command = command;
enable();
setMode(mode);
}
protected Pin(String code, PinCommand command) throws PinCommandException {
this.code = code;
this.path = command.path(this);
this.enabled = false;
this.command = command;
enable();
readMode();
}
protected Pin(String code, File path, PinCommand command) throws PinCommandException {
this.code = code;
this.path = path;
this.enabled = false;
this.command = command;
enable();
readMode();
}
public String getCode() {
return code;
}
public File getPath() {
return path;
}
private void readMode() throws PinCommandException {
checkEnabled();
this.mode = command.getMode(this);
}
public Mode getMode() {
return mode;
}
public void setMode(Mode mode) throws PinCommandException {
checkEnabled();
command.setMode(this, mode);
this.mode = mode;
}
public void write(boolean value) throws PinCommandException {
checkEnabled();
if (Mode.IN.equals(mode)) {
throw new PinCommandException("Pin value can't be written pin mode: IN");
} else {
command.write(this, value);
}
}
public boolean read() throws PinCommandException {
checkEnabled();
if (Mode.OUT.equals(mode)) {
throw new PinCommandException("Pin value can't be read pin mode: OUT");
} else {
return command.read(this);
}
}
public void enable() throws PinCommandException {
command.enable(this);
this.enabled = true;
}
public void disable() throws PinCommandException {
command.disable(this);
this.enabled = false;
}
private void checkEnabled() throws PinCommandException {
if (!enabled)
throw new PinCommandException("Pin is Disabled :" + code);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Pin)) return false;
Pin pin = (Pin) o;
if (code != null ? !code.equals(pin.code) : pin.code != null) return false;
if (path != null ? !path.equals(pin.path) : pin.path != null) return false;
return mode == pin.mode;
}
@Override
public int hashCode() {
int result = code != null ? code.hashCode() : 0;
result = 31 * result + (path != null ? path.hashCode() : 0);
result = 31 * result + (mode != null ? mode.hashCode() : 0);
return result;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("Pin{");
sb.append("code='").append(code).append('\'');
sb.append(", path=").append(path.getPath());
sb.append(", mode=").append(mode);
sb.append(", enabled=").append(enabled);
sb.append('}');
return sb.toString();
}
public enum Mode {
IN,
OUT
}
} |
package org.mskcc.portal.remote;
import org.apache.commons.httpclient.NameValuePair;
import org.mskcc.portal.model.CaseSet;
import org.mskcc.portal.util.XDebug;
import java.io.IOException;
import java.rmi.RemoteException;
import java.util.ArrayList;
/**
* Gets all Case Sets Associated with a specific Cancer Type.
*/
public class GetCaseSets {
// TODO: Later: ACCESS CONTROL: change to cancer study, etc.
/**
* Gets all Case Sets Associated with a specific Cancer type.
*
* @param cancerTypeId Cancer Type ID.
* @return ArrayList of CaseSet Objects.
* @throws RemoteException Remote / Network IO Error.
*/
// TODO: Later: ACCESS CONTROL: change to cancer study, etc.
public static ArrayList<CaseSet> getCaseSets(String cancerTypeId, XDebug xdebug)
throws RemoteException {
ArrayList<CaseSet> caseList = new ArrayList<CaseSet>();
String content = "";
try {
// Create Query Parameters
NameValuePair[] data = {
new NameValuePair(CgdsProtocol.CMD, "getCaseLists"),
new NameValuePair(CgdsProtocol.CANCER_STUDY_ID, cancerTypeId)
};
// Parse Text Response
CgdsProtocol protocol = new CgdsProtocol(xdebug);
content = protocol.connect(data, xdebug);
String lines[] = content.split("\n");
if (lines.length > 2) {
for (int i = 2; i < lines.length; i++) {
String parts[] = lines[i].split("\t");
String id = parts[0];
String name = parts[1];
String desc = parts[2];
String cases = parts[4];
CaseSet caseSet = new CaseSet();
caseSet.setId(id);
caseSet.setName(name);
caseSet.setDescription(desc);
caseSet.setCaseList(cases);
caseList.add(caseSet);
xdebug.logMsg(GetCaseSets.class, "Case Set Retrieved: " + id);
}
}
} catch (ArrayIndexOutOfBoundsException e) {
throw new RemoteException("Remote Access Error: Got line: " + content, e);
} catch (IOException e) {
throw new RemoteException("Remote Access Error", e);
}
return caseList;
}
} |
package io.spacedog.test.data;
import org.junit.Test;
import io.spacedog.client.SpaceDog;
import io.spacedog.client.elastic.ESQueryBuilders;
import io.spacedog.client.elastic.ESSearchSourceBuilder;
import io.spacedog.client.schema.Schema;
import io.spacedog.test.SpaceTest;
import io.spacedog.utils.ClassResources;
import io.spacedog.utils.Json;
public class SearchRestyFrenchTest extends SpaceTest {
private SpaceDog superadmin;
@Test
public void prefixSearchWithFrenchSpecificAnalyzer() {
prepareTest(true, true);
superadmin = clearServer();
byte[] mapping = ClassResources.loadAsBytes(this, "message.mapping.json");
superadmin.schemas().set(Json.toPojo(mapping, Schema.class));
index("Google");
matchPrefix("g");
matchPrefix("G");
matchPrefix("go");
matchPrefix("Go");
matchPrefix("goo");
matchPrefix("GOO");
matchPrefix("goog");
matchPrefix("googl");
matchPrefix("google");
matchPrefix("goOgLe");
noMatchPrefix("googles");
index("L'étable de Marie");
matchPrefix("l");
matchPrefix("l'");
matchPrefix("l'ét");
matchPrefix("l'etAb");
matchPrefix("etab");
matchPrefix("d");
matchPrefix("de");
matchPrefix("maR");
noMatchPrefix("le");
noMatchPrefix("létable");
noMatchPrefix("tabler");
noMatchPrefix("marier");
noMatchPrefix("maa");
noMatchPrefix("tabe");
index("j' zi");
matchPrefix("j");
matchPrefix("j'z");
matchPrefix("j z");
noMatchPrefix("jz");
index("17F11");
matchPrefix("1");
matchPrefix("17");
matchPrefix("17f");
matchPrefix("17f11");
// noMatchPrefix("11");
// noMatchPrefix("F");
// noMatchPrefix("F11");
}
@Test
public void searchWithFrenchMaxAnalyser() {
prepareTest();
superadmin = clearServer();
superadmin.schemas().set(Schema.builder("message")
.text("text").frenchMax().build());
index("Les écoles enseignent");
match("ecole");
match("école");
match("EcoLes");
match("écolles");
match("écol");
match("enseignent");
match("enSEIgnènt");
noMatch("enseigne");
index("les Bœufs ruminent");
match("BoEuf");
match("Bœuf");
match("boeufs");
index("Je suis :), tu es :(");
match("heureux");
match("heureu");
match("triste");
match("tristes");
match(":)");
match(":(");
noMatch(":-)");
index("1234.567");
match("1234");
match("1234.");
match("1234,");
match("1234.567");
match("1234,567");
match("1234567");
match("567");
match(".567");
match(",567");
// match because default operator is OR
// and at least one token match
match("1234.56");
match("234.567");
noMatch("234.56");
}
private void index(String text) {
superadmin.data().save("message", Json.object("text", text));
}
private void match(String text) {
assertEquals(1, search(text, "text"));
}
private void matchPrefix(String text) {
assertEquals(1, searchPrefix(text, "text"));
}
private void noMatch(String text) {
assertEquals(0, search(text, "text"));
}
private void noMatchPrefix(String text) {
assertEquals(0, searchPrefix(text, "text"));
}
private long search(String text, String field) {
ESSearchSourceBuilder source = ESSearchSourceBuilder.searchSource()
.query(ESQueryBuilders.matchQuery(field, text));
return superadmin.data().prepareSearch().refresh(true).source(source.toString()).go().total;
}
private long searchPrefix(String text, String field) {
ESSearchSourceBuilder source = ESSearchSourceBuilder.searchSource()
.query(ESQueryBuilders.matchPhrasePrefixQuery(field, text));
return superadmin.data().prepareSearch().refresh(true).source(source.toString()).go().total;
}
} |
/*
* Thibaut Colar Jan 29, 2010
*/
package net.colar.netbeans.fan.test;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.Future;
import net.colar.netbeans.fan.FanParserResult;
import net.colar.netbeans.fan.NBFanParser;
import net.colar.netbeans.fan.test.mock.MockLookup;
import net.colar.netbeans.fan.ast.FanLexAstUtils;
import net.colar.netbeans.fan.indexer.FanIndexer;
import net.colar.netbeans.fan.indexer.FanIndexerFactory;
import net.colar.netbeans.fan.platform.FanPlatform;
import net.colar.netbeans.fan.platform.FanPlatformSettings;
import net.jot.JOTInitializer;
import net.jot.testing.JOTTestable;
import net.jot.testing.JOTTester;
import org.netbeans.api.project.Project;
import org.netbeans.modules.parsing.api.Snapshot;
import org.netbeans.modules.parsing.api.Source;
import org.netbeans.modules.project.uiapi.OpenProjectsTrampoline;
import org.openide.filesystems.FileUtil;
import org.openide.util.lookup.Lookups;
/**
* Large, Slow test.
* Parse most Fantom disctribution source files to make sure the parser can deal with them properly
* @author thibautc
*/
public class FantomSrcParsingTest implements JOTTestable
{
public void jotTest() throws Throwable
{
setUp();
try
{
String folder = "/home/thibautc/fantom-1.0.49/src/";
File file = new File(folder);
Vector<File> files = getFanFiles(file);
for (File f : files)
{
JOTTester.tag(f.getPath());
boolean result = parseFile(f);
JOTTester.checkIf("Parsing " + f.getAbsolutePath(), result);
}
}
catch(Throwable e){e.printStackTrace();}
tearDown();
}
protected void setUp() throws Exception
{
System.setProperty("netbeans.full.hack", "true"); // NOI18N
System.setProperty("netbeans.user", System.getProperty("user.dir")); // NOI18N
//This has to be before touching ClassPath class (createSnapshot does)
MockLookup.setInstances(new MockTrampoline(), Lookups.metaInfServices(MockLookup.class.getClassLoader()), Lookups.singleton(MockLookup.class.getClassLoader()));
JOTInitializer.getInstance().setTestMode(true);
JOTInitializer.getInstance().init();
FanPlatformSettings.getInstance().put(FanPlatformSettings.PREF_FAN_HOME, "/home/thibautc/fantom/");
JOTTester.checkIf("Fan home setup check ", FanPlatformSettings.getInstance().get(FanPlatformSettings.PREF_FAN_HOME) != null);
FanPlatform.getInstance(false).readSettings();
// Do it in the foreground .. waitFor()
FanIndexerFactory.getIndexer().indexAll(false);
//TODO: this causes indexing ... so maybe we can add some index unit tests here (using golden source files)
}
protected void tearDown() throws Exception
{
FanIndexer.shutdown();
Thread.sleep(500);
JOTInitializer.getInstance().destroy();
}
private boolean parseFile(File f)
{
NBFanParser parser = new NBFanParser();
try
{
Source source = Source.create(FileUtil.toFileObject(f));
Snapshot snapshot = source.createSnapshot();
parser.parse(snapshot);
FanParserResult result = (FanParserResult) parser.getResult();
List<? extends org.netbeans.modules.csl.api.Error> errors = result.getDiagnostics();
// Look for failed parsing (antlr)
if (errors != null && errors.size() > 0)
{
for (org.netbeans.modules.csl.api.Error error : errors)
{
System.err.println("Error: " + error);
}
FanLexAstUtils.dumpTree(result.getTree(), 0);
return false;
}
// TODO: look for unresolved items
//result.getAntlrErrors();
} catch (Throwable e)
{
System.err.println("Parsing failed for: " + f.getPath());
e.printStackTrace();
return false;
}
return true;
}
private Vector<File> getFanFiles(File file)
{
Vector<File> files = new Vector<File>();
if (file.isFile())
{
// single file
if (file.getName().toLowerCase().endsWith(".fan"))
{
files.add(file);
}
} else
{
File[] children = file.listFiles();
for (int i = 0; i != children.length; i++)
{
files.addAll(getFanFiles(children[i]));
}
}
return files;
}
public class MockTrampoline implements OpenProjectsTrampoline
{
public Project[] getOpenProjectsAPI()
{
System.out.println("getOpenPrjApis");
return null;
}
public void openAPI(Project[] prjcts, boolean bln, boolean bln1)
{
}
public void closeAPI(Project[] prjcts)
{
}
public void addPropertyChangeListenerAPI(PropertyChangeListener pl, Object o)
{
}
public Future<Project[]> openProjectsAPI()
{
System.out.println("apis");
return null;
}
public void removePropertyChangeListenerAPI(PropertyChangeListener pl)
{
}
public Project getMainProject()
{
System.out.println("getMainProject");
return null;
}
public void setMainProject(Project prjct)
{
}
}
} |
package dk.netarkivet.archive.checksum;
import java.io.File;
import java.util.List;
import dk.netarkivet.archive.ArchiveSettings;
import dk.netarkivet.common.CommonSettings;
import dk.netarkivet.common.distribute.RemoteFile;
import dk.netarkivet.common.distribute.RemoteFileFactory;
import dk.netarkivet.common.exceptions.IllegalState;
import dk.netarkivet.common.utils.FileUtils;
import dk.netarkivet.common.utils.Settings;
import dk.netarkivet.testutils.TestFileUtils;
import dk.netarkivet.testutils.preconfigured.ReloadSettings;
import dk.netarkivet.testutils.preconfigured.UseTestRemoteFile;
import junit.framework.TestCase;
/**
* Tester class for the FileChecksumArchive.
*
*/
public class FileChecksumArchiveTester extends TestCase {
FileChecksumArchive fca;
ReloadSettings rs = new ReloadSettings();
UseTestRemoteFile utrf = new UseTestRemoteFile();
public void setUp() {
rs.setUp();
utrf.setUp();
FileUtils.removeRecursively(TestInfo.WORKING_DIR);
FileUtils.removeRecursively(TestInfo.TMP_DIR);
TestFileUtils.copyDirectoryNonCVS(TestInfo.ORIGINAL_DIR,
TestInfo.WORKING_DIR);
Settings.set(ArchiveSettings.CHECKSUM_BASEDIR, TestInfo.CHECKSUM_DIR.getAbsolutePath());
Settings.set(CommonSettings.USE_REPLICA_ID, "THREE");
fca = FileChecksumArchive.getInstance();
}
public void tearDown() {
FileUtils.removeRecursively(TestInfo.WORKING_DIR);
FileUtils.removeRecursively(TestInfo.TMP_DIR);
rs.tearDown();
utrf.tearDown();
fca.cleanup();
}
/**
* Ensure that there is enough space.
*/
public void testChecksum() {
assert(fca.hasEnoughSpace());
}
/**
* Checks whether the filename for the checksum file is defined correct in
* the settings.
*/
public void testFilename() {
String filename = Settings.get(ArchiveSettings.CHECKSUM_BASEDIR) + "/checksum_THREE.md5";
assertEquals("The files should have the same name. ", fca.getFilename(), filename);
}
/**
* Check the following:
* 1. FileChecksumArchiev can perform Upload.
* 2. The correct checksums are retrieved from the upload.
* 3. The correct file can be retrieved.
* 4. That the Correct function can be performed.
* 5. That the data also is changed appropriately.
* 6. The old and 'wrong' entries have been move to the backup file.
*
* @throws Exception So it is unnecessary to catch IOExceptions, since the
* test should fail.
*/
public void testContent() throws Exception {
RemoteFile arcfile1 = RemoteFileFactory.getInstance(TestInfo.UPLOAD_FILE_1, false, false, false);
fca.upload(arcfile1, "TEST1.arc");
RemoteFile arcfile2 = RemoteFileFactory.getInstance(TestInfo.UPLOAD_FILE_2, false, false, false);
fca.upload(arcfile2, "TEST2.arc");
List<String> filenames = FileUtils.readListFromFile(fca.getAllFilenames());
// Make check for whether the correct files exist in the archive.
assertEquals("The expected number of filenames in the archive.", 2,
filenames.size());
assertTrue("TEST1.arc should be amongst the filenames", filenames.contains("TEST1.arc"));
assertTrue("TEST2.arc should be amongst the filenames", filenames.contains("TEST2.arc"));
// Make check for whether the correct checksums are stored in the archive.
assertEquals("The stored value and the checksum calculated through the method.",
fca.getChecksum("TEST1.arc"), fca.calculateChecksum(TestInfo.UPLOAD_FILE_1));
assertEquals("The value stored in the checksum archive and a precalculated value of the file",
fca.getChecksum("TEST1.arc"), TestInfo.TEST1_CHECKSUM);
assertEquals("The stored value and the checksum calculated through the method.",
fca.getChecksum("TEST2.arc"), fca.calculateChecksum(TestInfo.UPLOAD_FILE_2));
assertEquals("The value stored in the checksum archive and a precalculated value of the file",
fca.getChecksum("TEST2.arc"), TestInfo.TEST2_CHECKSUM);
// Check whether the archive file is identical to the retrieved archive
List<String> archiveChecksums = FileUtils.readListFromFile(fca.getArchiveAsFile());
List<String> fileChecksums = FileUtils.readListFromFile(new File(fca.getFilename()));
assertEquals("The amount of checksums should be identical in the file and from the archive.",
fileChecksums.size(), archiveChecksums.size());
assertEquals("The amount of checksum should be 2", 2, fileChecksums.size());
for(int i = 0; i < fileChecksums.size(); i++) {
assertEquals("The checksum entry in the file should be identical to the one in the archive",
archiveChecksums.get(i), fileChecksums.get(i));
}
// Check the correct function, both good and bad examples.
try {
fca.correct("ERROR!", TestInfo.UPLOAD_FILE_1);
fail("It is not allowed for 'correct' to correct a wrong 'incorrectChecksum'.");
} catch(IllegalState e) {
assertTrue("The correct error message should be sent.",
e.getMessage().contains("No file entry for file 'ERROR!'"));
}
fca.correct("TEST1.arc", TestInfo.UPLOAD_FILE_2);
assertEquals("The new checksum for 'TEST1.arc' should now be the checksum for 'TEST2.arc'.",
fca.getChecksum("TEST1.arc"), TestInfo.TEST2_CHECKSUM);
fca.correct("TEST2.arc", TestInfo.UPLOAD_FILE_1);
assertEquals("The new checksum for 'TEST2.arc' should now be the checksum for 'TEST1.arc'.",
fca.getChecksum("TEST2.arc"), TestInfo.TEST1_CHECKSUM);
// Check that the correct function has changed the archive file.
String correctChecksums = FileUtils.readFile(new File(fca.getFilename()));
assertTrue("The new checksums should be reversed.",
correctChecksums.contains("TEST1.arc" + "##" + TestInfo.TEST2_CHECKSUM));
assertTrue("The new checksums should be reversed",
correctChecksums.contains("TEST2.arc" + "##" + TestInfo.TEST1_CHECKSUM));
// Check that the correct function has put the old record into the
// wrong entry file.
String wrongEntryContent = FileUtils.readFile(new File(fca.getWrongEntryFilename()));
assertTrue("The old checksums should be store here.",
wrongEntryContent.contains("TEST1.arc" + "##" + TestInfo.TEST1_CHECKSUM));
assertTrue("The old checksums should be store here.",
wrongEntryContent.contains("TEST2.arc" + "##" + TestInfo.TEST2_CHECKSUM));
}
} |
package example;
//-*- mode:java; encoding:utf8n; coding:utf-8 -*-
// vim:set fileencoding=utf-8:
//@homepage@
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MainPanel extends JPanel {
public MainPanel() {
super(new BorderLayout());
final SplitPaneWrapper sp = new SplitPaneWrapper();
final JCheckBox check = new JCheckBox("MAXIMIZED_BOTH: keep the same splitting ratio");
check.setSelected(true);
check.addActionListener(new ActionListener() {
@Override public void actionPerformed(ActionEvent e) {
sp.setTestFlag(check.isSelected());
}
});
add(check, BorderLayout.NORTH);
add(sp);
setPreferredSize(new Dimension(320, 240));
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
try{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}catch(Exception e) {
e.printStackTrace();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class SplitPaneWrapper extends JPanel {
private final static JTextArea log = new JTextArea();
// private final JSplitPane splitPane = new JSplitPane() {
// @Override public void setDividerLocation(double proportionalLocation) {
// if(proportionalLocation < 0.0 || proportionalLocation > 1.0) {
// int s = ((getOrientation() == VERTICAL_SPLIT) ? getHeight() : getWidth()) - getDividerSize();
// setDividerLocation((int)Math.round(s * proportionalLocation));
// // public void setDividerLocation(double proportionalLocation) {
// // if (proportionalLocation < 0.0 ||
// // proportionalLocation > 1.0) {
// // "be between 0.0 and 1.0.");
// // if (getOrientation() == VERTICAL_SPLIT) {
// // setDividerLocation((int)((double)(getHeight() - getDividerSize()) *
// // proportionalLocation));
// // } else {
// // setDividerLocation((int)((double)(getWidth() - getDividerSize()) *
// // proportionalLocation));
private final JSplitPane sp;
public SplitPaneWrapper() {
this(new JSplitPane(JSplitPane.VERTICAL_SPLIT, new JScrollPane(log), new JScrollPane(new JTree())));
}
public SplitPaneWrapper(JSplitPane splitPane) {
super(new BorderLayout());
this.sp = splitPane;
add(sp);
EventQueue.invokeLater(new Runnable() {
@Override public void run() {
sp.setDividerLocation(0.5);
}
});
}
private boolean flag = true;
public void setTestFlag(boolean flag) {
this.flag = flag;
}
private static int getOrientedSize(JSplitPane sp) {
return (sp.getOrientation() == JSplitPane.VERTICAL_SPLIT)
? sp.getHeight() - sp.getDividerSize()
: sp.getWidth() - sp.getDividerSize();
}
private int prev_state = Frame.NORMAL;
@Override public void doLayout() {
int size = getOrientedSize(sp);
final double proportionalLocation = sp.getDividerLocation()/(double)size;
super.doLayout();
if(!flag) return;
int state = ((Frame)SwingUtilities.getWindowAncestor(sp)).getExtendedState();
if(sp.isShowing() && state!=prev_state) {
EventQueue.invokeLater(new Runnable() {
@Override public void run() {
int s = getOrientedSize(sp);
int iv = (int)Math.round(s * proportionalLocation);
log.append(String.format("DividerLocation: %d\n", iv));
sp.setDividerLocation(iv);
}
});
prev_state = state;
}
}
} |
package osmTileMachine;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class Geography {
public static TileSet getTileSetForRegion(String nameOfRegion)
{
TileSet tileSet = new TileSet();
nameOfRegion = nameOfRegion.trim();
if (nameOfRegion.equalsIgnoreCase("dalarna"))
{
BoundingBox bbox = new BoundingBox(12.12, 59.85, 16.75, 62.28);
tileSet = getTileSetForRegion(bbox);
}
else if (nameOfRegion.equalsIgnoreCase("vnern"))
{
BoundingBox bbox = new BoundingBox(12.306, 58.38, 14.094, 59.42);
tileSet = getTileSetForRegion(bbox);
}
else if (nameOfRegion.equalsIgnoreCase("Niemisel"))
{
BoundingBox bbox = new BoundingBox(21.6, 65.9, 22.41, 66.9);
tileSet = getTileSetForRegion(bbox);
}
else if (nameOfRegion.equalsIgnoreCase("germany"))
{
BoundingBox bbox = new BoundingBox(5, 47, 16, 55);
tileSet = getTileSetForRegion(bbox);
}
else if (nameOfRegion.equalsIgnoreCase("scandinavia"))
{
BoundingBox bbox = new BoundingBox(4.8, 54.54, 31.6, 71.11);
tileSet = getTileSetForRegion(bbox);
}
else if (nameOfRegion.equalsIgnoreCase("vanernvatternmalarentest"))
{
BoundingBox bbox = new BoundingBox(12, 57.6, 19, 59.9);
tileSet = getTileSetForRegion(bbox);
}
else if (nameOfRegion.equalsIgnoreCase("bodensee"))
{
BoundingBox bbox = new BoundingBox(8.75, 47.3, 9.77, 47.9);
tileSet = getTileSetForRegion(bbox);
}
else if (nameOfRegion.equalsIgnoreCase("frankfurt"))
{
BoundingBox bbox = new BoundingBox(7.7, 49.8, 10, 50.6);
tileSet = getTileSetForRegion(bbox);
}
else if (nameOfRegion.equalsIgnoreCase("holland"))
{
BoundingBox bbox = new BoundingBox(3, 50.7, 8, 53.7);
tileSet = getTileSetForRegion(bbox);
}
else if (nameOfRegion.equalsIgnoreCase("falun"))
{
BoundingBox bbox = new BoundingBox(15.1364136,60.3812903, 16.1553955, 60.7591595);
tileSet = getTileSetForRegion(bbox);
}
else if (nameOfRegion.equalsIgnoreCase("LKP")) //Linkping
{
BoundingBox bbox = new BoundingBox(15.0430, 58.1185, 16.0579, 58.6634);
tileSet = getTileSetForRegion(bbox);
}
else if (nameOfRegion.startsWith("box="))
{
int separator1 = nameOfRegion.indexOf(";", 0);
int separator2 = nameOfRegion.indexOf(";", separator1+1);
int separator3 = nameOfRegion.indexOf(";", separator2+1);
String minLonString = nameOfRegion.substring(4, separator1);
String minLatString = nameOfRegion.substring(separator1+1, separator2);
String maxLonString = nameOfRegion.substring(separator2+1, separator3);
String maxLatString = nameOfRegion.substring(separator3+1, nameOfRegion.length());
BoundingBox bbox = new BoundingBox(Double.parseDouble(minLonString), Double.parseDouble(minLatString),Double.parseDouble(maxLonString), Double.parseDouble(maxLatString));
tileSet = getTileSetForRegion(bbox);
}
else if (nameOfRegion.startsWith("file="))
{
String fileName = nameOfRegion.substring(5, nameOfRegion.length());
try {
tileSet = getTileSetForFileArea(fileName);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return tileSet;
}
private static TileSet getTileSetForFileArea(String fileName) throws IOException {
TileSet tileSet = new TileSet();
// Open the file
FileInputStream fstream = new FileInputStream(fileName);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
//determine if is is a node
if (strLine.trim().substring(0, 6).equals("<node "))
{
double lat = 0;
double lon = 0;
String remainingLine = strLine.trim().substring(6, strLine.trim().length());
//extract one parameter at a time
while (remainingLine.length()>4)
{
int firstQuotePos = remainingLine.indexOf('"', 0);
int secondQuotePos = remainingLine.indexOf('"', firstQuotePos+1);
String ParameterKey = remainingLine.substring(0, firstQuotePos-1);
String ParameterValue = remainingLine.substring(firstQuotePos+1, secondQuotePos);
// System.out.println ("key:"+ParameterKey + "ENDKEY... Value:" + ParameterValue + "ENDVALUE");
if (ParameterKey.equals("lat")) lat = Double.parseDouble(ParameterValue);
if (ParameterKey.equals("lon")) lon = Double.parseDouble(ParameterValue);
remainingLine = remainingLine.substring(secondQuotePos+1, remainingLine.length()).trim();
}
if (lat != 0 && lon != 0)
{
// System.out.println("Node detected at lat=" + lat + " lon=" +lon);
Tile t = Tile.getTile(lon, lat, SplitAndRenderStrategy.getLowestRenderLevel());
int tX = t.getX();
int tY = t.getY();
int tZ = t.getZ();
tileSet.add(t);
//Add surrounding tiles as well
tileSet.add(new Tile(tX+1,tY+1 ,tZ,"surrounding"));
tileSet.add(new Tile(tX+1,tY ,tZ,"surrounding"));
tileSet.add(new Tile(tX+1,tY-1 ,tZ,"surrounding"));
tileSet.add(new Tile(tX ,tY+1 ,tZ,"surrounding"));
tileSet.add(new Tile(tX ,tY-1 ,tZ,"surrounding"));
tileSet.add(new Tile(tX-1,tY+1 ,tZ,"surrounding"));
tileSet.add(new Tile(tX-1,tY ,tZ,"surrounding"));
tileSet.add(new Tile(tX-1,tY-1 ,tZ,"surrounding"));
}
}
//Extract lat
//Extract lon
//Create tile from lat,lon pair
//Add to tile to tileset
}
br.close();
return tileSet;
}
public static TileSet getTileSetForRegion(BoundingBox boundingBox)
{
TileSet tileSet = new TileSet();
Tile t;
double xMinCoord = boundingBox.getMinLon();
double xMaxCoord = boundingBox.getMaxLon();
double yMinCoord = boundingBox.getMaxLat();
double yMaxCoord = boundingBox.getMinLat();
Tile topLeftTile = Tile.getTile(xMinCoord, yMinCoord, SplitAndRenderStrategy.getLowestRenderLevel());
Tile bottomRightTile = Tile.getTile(xMaxCoord, yMaxCoord, SplitAndRenderStrategy.getLowestRenderLevel());
int xMin = topLeftTile.getX();
int xMax = bottomRightTile.getX();
int yMin = topLeftTile.getY();
int yMax = bottomRightTile.getY();
for (int x = xMin ;x<=xMax;x++)
{
for (int y = yMin;y<=yMax;y++)
{
t = new Tile(x, y, SplitAndRenderStrategy.getLowestRenderLevel(), "");
tileSet.add(t);
}
}
return tileSet;
}
} |
package com.idunnolol.ragefaces.data;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.util.LruCache;
public class Cache {
private static final int MAX_MEMORY = (int) (Runtime.getRuntime().maxMemory() / 1024);
private static final LruCache<Integer, Bitmap> sMemoryCache = new LruCache<Integer, Bitmap>(MAX_MEMORY / 3) {
@Override
protected int sizeOf(Integer key, Bitmap bitmap) {
return (bitmap.getRowBytes() * bitmap.getHeight()) / 1024;
}
};
public static Bitmap getBitmap(Resources res, Integer id) {
Bitmap bitmap = sMemoryCache.get(id);
if (bitmap == null) {
bitmap = BitmapFactory.decodeResource(res, id);
sMemoryCache.put(id, bitmap);
}
return bitmap;
}
} |
package com.crawljax.core;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.By;
import com.crawljax.condition.NotRegexCondition;
import com.crawljax.condition.NotXPathCondition;
import com.crawljax.condition.RegexCondition;
import com.crawljax.condition.XPathCondition;
import com.crawljax.condition.browserwaiter.ExpectedVisibleCondition;
import com.crawljax.condition.invariant.Invariant;
import com.crawljax.core.configuration.CrawlSpecification;
import com.crawljax.core.configuration.CrawljaxConfiguration;
import com.crawljax.core.configuration.Form;
import com.crawljax.core.configuration.InputSpecification;
import com.crawljax.core.plugin.OnInvariantViolationPlugin;
import com.crawljax.core.plugin.PostCrawlingPlugin;
import com.crawljax.core.state.Eventable;
import com.crawljax.core.state.StateFlowGraph;
import com.crawljax.core.state.StateVertix;
import com.crawljax.oraclecomparator.comparators.DateComparator;
import com.crawljax.oraclecomparator.comparators.StyleComparator;
/**
* Large test for Crawljax. Crawls a test site and then inspects whether it is crawled correctly See
* src/test/site for the web site
*
* @author dannyroest@gmail.com (Danny Roest)
* @version $Id$
*/
public class LargeCrawljaxTest {
private static CrawlSession session;
private static final int CLICKED_CLICK_ME_ELEMENTS = 6;
private static final String CLICK_TEXT = "CLICK_ME";
private static final String DONT_CLICK_TEXT = "DONT_CLICK_ME";
private static final String ATTRIBUTE = "class";
private static final String CLICK_UNDER_XPATH_ID = "CLICK_IN_HERE";
private static final String DONT_CLICK_UNDER_XPATH_ID = "DONT_CLICK_IN_HERE";
private static final String ILLEGAL_STATE = "FORBIDDEN_PAGE";
private static List<Invariant> violatedInvariants = new ArrayList<Invariant>();
private static final int VIOLATED_INVARIANTS = 1;
private static final String VIOLATED_INVARIANT_DESCRIPTION = "expectedInvariantViolation";
private static final RegexCondition REGEX_CONDITION_TRUE =
new RegexCondition("REGEX_CONDITION_TRUE");
private static final NotRegexCondition ALLOW_BUTTON_CLICK =
new NotRegexCondition("DONT_CLICK_BUTTONS_ON_THIS_PAGE");
private static final String INDEX = "src/test/site/index.html";
private static final String TITLE_RESULT_RANDOM_INPUT = "RESULT_RANDOM_INPUT";
private static final String REGEX_RESULT_RANDOM_INPUT =
"[a-zA-Z]{8};" + "[a-zA-Z]{8};" + "(true|false);" + "(true|false);" + "OPTION[1234];"
+ "[a-zA-Z]{8}";
// manual values
private static final String TITLE_MANUAL_INPUT_RESULT = "RESULT_MANUAL_INPUT";
private static final String MANUAL_INPUT_TEXT = "foo";
private static final String MANUAL_INPUT_TEXT2 = "crawljax";
private static final boolean MANUAL_INPUT_CHECKBOX = true;
private static final boolean MANUAL_INPUT_RADIO = false;
private static final String MANUAL_INPUT_SELECT = "OPTION4";
private static final String MANUAL_INPUT_TEXTAREA = "bar";
private static final String MANUAL_INPUT_RESULT = "foo;crawljax;true;false;OPTION4;bar";
// multiple values
private static final String[] MULTIPLE_INPUT_TEXT = { "first", "second", "" };
private static final String[] MULTIPLE_INPUT_TEXT2 = { "foo", "bar" };
private static final boolean[] MULTIPLE_INPUT_CHECKBOX = { true, false };
private static final boolean[] MULTIPLE_INPUT_RADIO = { false, true };
private static final String[] MULTIPLE_INPUT_SELECT = { "OPTION1", "OPTION2" };
private static final String[] MULTIPLE_INPUT_TEXTAREA = { "same" };
private static final String TITLE_MULTIPLE_INPUT_RESULT = "RESULT_MULTIPLE_INPUT";
private static final String[] MULTIPLE_INPUT_RESULTS =
{ "first;foo;true;false;OPTION1;same", "second;bar;false;true;OPTION2;same",
";foo;true;false;OPTION1;same" };
/**
* Runs crawljax.
*
* @throws java.lang.Exception
* when error while crawling
*/
@BeforeClass
public static void setUpBeforeClass() throws Exception {
CrawljaxConfiguration crawljaxConfiguration = new CrawljaxConfiguration();
crawljaxConfiguration.setCrawlSpecification(getCrawlSpecification());
addPlugins(crawljaxConfiguration);
CrawljaxController crawljax = new CrawljaxController(crawljaxConfiguration);
crawljax.run();
}
/**
* Tests random input.
*/
@Test
public void testRandomFormInput() {
for (StateVertix state : getStateFlowGraph().getAllStates()) {
if (state.getDom().contains(TITLE_RESULT_RANDOM_INPUT)) {
Pattern p = Pattern.compile(REGEX_RESULT_RANDOM_INPUT);
Matcher m = p.matcher(state.getDom());
assertTrue("Found correct random result", m.find());
return;
}
}
// should never reach this point
assertTrue("Result random input found", false);
}
/**
* Test manual form input.
*/
@Test
public void testManualFormInput() {
for (StateVertix state : getStateFlowGraph().getAllStates()) {
if (state.getDom().contains(TITLE_MANUAL_INPUT_RESULT)) {
assertTrue("Result contains the correct data", state.getDom().contains(
MANUAL_INPUT_RESULT));
return;
}
}
// should never reach this point
assertTrue("Result manual input found", false);
}
/**
* Tests whether all the different form values are submitted and found.
*/
@Test
public void testMultipleFormInput() {
List<String> resultsFound = new ArrayList<String>();
for (StateVertix state : getStateFlowGraph().getAllStates()) {
if (state.getDom().contains(TITLE_MULTIPLE_INPUT_RESULT)) {
for (String result : MULTIPLE_INPUT_RESULTS) {
if (state.getDom().contains(result) && !resultsFound.contains(result)) {
resultsFound.add(result);
}
}
}
}
assertTrue("All results are found", resultsFound.size() == MULTIPLE_INPUT_RESULTS.length);
}
@Test
public void testCrawledElements() {
int clickMeFound = 0;
for (Eventable eventable : getStateFlowGraph().getAllEdges()) {
// elements with DONT_CLICK_TEXT should never be clicked
assertTrue("No illegal element is clicked: " + eventable, !eventable.getElement()
.getText().startsWith(DONT_CLICK_TEXT));
if (eventable.getElement().getText().startsWith(CLICK_TEXT)) {
clickMeFound++;
}
}
assertTrue(CLICKED_CLICK_ME_ELEMENTS + " CLICK_TEXT elements are clicked ",
clickMeFound == CLICKED_CLICK_ME_ELEMENTS);
}
@Test
public void testForIllegalStates() {
for (StateVertix state : getStateFlowGraph().getAllStates()) {
assertTrue("Only legal states: " + state.getName(), !state.getDom().contains(
ILLEGAL_STATE));
}
}
/**
* this tests whether the oracle comparators are working correctly the home page is different
* every load, but is equivalent when the oracle comparators are functioning.
*/
@Test
public void testOracleComparators() {
int countHomeStates = 0;
for (StateVertix state : getStateFlowGraph().getAllStates()) {
if (state.getDom().contains("HOMEPAGE")) {
countHomeStates++;
}
}
assertTrue("Only one home page. Found: " + countHomeStates, countHomeStates == 1);
}
/**
* Tests invariants.
*/
@Test
public void testInvariants() {
// two invariants were added, but only one should fail!
assertTrue(VIOLATED_INVARIANTS + " Invariants violated",
violatedInvariants.size() == VIOLATED_INVARIANTS);
// test whether the right invariant failed
assertTrue(VIOLATED_INVARIANT_DESCRIPTION + " failed", violatedInvariants.get(0)
.getDescription().equals(VIOLATED_INVARIANT_DESCRIPTION));
}
/**
* Tests waitconditions with a slow widget.
*/
@Test
public void testWaitCondition() {
boolean foundSlowWidget = false;
for (StateVertix state : getStateFlowGraph().getAllStates()) {
if (state.getDom().contains("TEST_WAITCONDITION")
&& state.getDom().contains("LOADED_SLOW_WIDGET")) {
foundSlowWidget = true;
}
}
assertTrue("SLOW_WIDGET is found", foundSlowWidget);
boolean foundLinkInSlowWidget = false;
for (Eventable eventable : getStateFlowGraph().getAllEdges()) {
if (eventable.getElement().getText().equals("SLOW_WIDGET_HOME")) {
foundLinkInSlowWidget = true;
}
}
assertTrue("Link in SLOW_WIDGET is found", foundLinkInSlowWidget);
}
/**
* Tests the limit for the Crawl Depth. The current crawl depth in this test is limited to 3! It
* test a not to deep path (path a), a to deep path (path b), a path which has a CLONE (path c),
* a to deep path after a CLONE found (path d), a to deep path with a branch in it (path e), a
* to deep path with a nop operations that results in a DOM is not changed event. The test was
* created after a bug found when the depth limit was not applied after a CLONE has been
* detected.
*/
@Test
public void testDepth() {
boolean crawlToDeep = false;
int level1 = 0;
int level2 = 0;
for (Eventable eventable : getStateFlowGraph().getAllEdges()) {
String txt = eventable.getElement().getText();
if (txt.startsWith("Depth")) {
// Its a depth eventable were interested in that!
String lastPart = txt.substring(5);
int nr = Integer.valueOf(lastPart.substring(lastPart.length() - 1));
// String id = lastPart.substring(0, lastPart.length() - 1);
if (nr == 1) {
level1++;
} else if (nr == 2) {
level2++;
} else {
crawlToDeep = true;
}
}
}
assertTrue("Crawling was to deep, not limited by the setDepth parameter", !crawlToDeep);
assertTrue("Too many nodes found at level 1 number of nodes: " + level1 + " Required: "
+ 6, level1 <= 6);
assertTrue("Too less nodes found at level 1 number of nodes: " + level1 + " Required: "
+ 6, level1 >= 6);
assertTrue("Too many nodes found at level 2 number of nodes: " + level2 + " Required: "
+ 5, level2 <= 5);
assertTrue("Too less nodes found at level 2 number of nodes: " + level2 + " Required: "
+ 5, level2 >= 5);
}
/* setting up */
private static CrawlSpecification getCrawlSpecification() {
File index = new File(INDEX);
CrawlSpecification crawler = new CrawlSpecification("file://" + index.getAbsolutePath());
crawler.setWaitTimeAfterEvent(100);
crawler.setWaitTimeAfterReloadUrl(100);
crawler.setDepth(3);
crawler.setClickOnce(true);
addCrawlElements(crawler);
crawler.setInputSpecification(getInputSpecification());
addCrawlConditions(crawler);
addOracleComparators(crawler);
addInvariants(crawler);
addWaitConditions(crawler);
return crawler;
}
private static InputSpecification getInputSpecification() {
InputSpecification input = new InputSpecification();
input.field("textManual").setValue(MANUAL_INPUT_TEXT);
input.field("text2Manual").setValue(MANUAL_INPUT_TEXT2);
input.field("checkboxManual").setValue(MANUAL_INPUT_CHECKBOX);
input.field("radioManual").setValue(MANUAL_INPUT_RADIO);
input.field("selectManual").setValue(MANUAL_INPUT_SELECT);
input.field("textareaManual").setValue(MANUAL_INPUT_TEXTAREA);
Form form = new Form();
form.field("textMultiple").setValues(MULTIPLE_INPUT_TEXT);
form.field("text2Multiple").setValues(MULTIPLE_INPUT_TEXT2);
form.field("checkboxMultiple").setValues(MULTIPLE_INPUT_CHECKBOX);
form.field("radioMultiple").setValues(MULTIPLE_INPUT_RADIO);
form.field("selectMultiple").setValues(MULTIPLE_INPUT_SELECT);
form.field("textareaMultiple").setValues(MULTIPLE_INPUT_TEXTAREA);
input.setValuesInForm(form).beforeClickElement("a").withText("Submit Multiple");
return input;
}
private static void addWaitConditions(CrawlSpecification crawler) {
crawler.waitFor("testWaitCondition.html", 2000, new ExpectedVisibleCondition(By
.id("SLOW_WIDGET")));
}
private static void addInvariants(CrawlSpecification crawler) {
// should always fail on test invariant page
NotXPathCondition neverDivWithInvariantViolationId =
new NotXPathCondition("//DIV[@id='INVARIANT_VIOLATION']");
crawler.addInvariant(VIOLATED_INVARIANT_DESCRIPTION, neverDivWithInvariantViolationId);
// should never fail
RegexCondition onInvariantsPagePreCondition = new RegexCondition("TEST_INVARIANTS");
XPathCondition expectElement =
new XPathCondition("//DIV[@id='SHOULD_ALWAYS_BE_ON_THIS_PAGE']");
crawler.addInvariant("testInvariantWithPrecondiions", expectElement,
onInvariantsPagePreCondition);
}
private static void addCrawlElements(CrawlSpecification crawler) {
crawler.click("a");
crawler.click("div").withText(CLICK_TEXT);
crawler.click("div").underXPath("//SPAN[@id='" + CLICK_UNDER_XPATH_ID + "']");
crawler.when(ALLOW_BUTTON_CLICK).click("button");
crawler.when(REGEX_CONDITION_TRUE).click("div").withAttribute(ATTRIBUTE, "condition");
crawler.dontClick("a").withText(DONT_CLICK_TEXT);
crawler.dontClick("a").withAttribute(ATTRIBUTE, DONT_CLICK_TEXT);
crawler.dontClick("a").underXPath("//DIV[@id='" + DONT_CLICK_UNDER_XPATH_ID + "']");
}
private static void addOracleComparators(CrawlSpecification crawler) {
crawler.addOracleComparator("style", new StyleComparator());
crawler.addOracleComparator("date", new DateComparator());
}
private static void addCrawlConditions(CrawlSpecification crawler) {
crawler.addCrawlCondition("DONT_CRAWL_ME", new NotRegexCondition("DONT_CRAWL_ME"));
}
private static void addPlugins(CrawljaxConfiguration crawljaxConfiguration) {
// plugin to retrieve session data
crawljaxConfiguration.addPlugin(new PostCrawlingPlugin() {
@Override
public void postCrawling(CrawlSession session) {
LargeCrawljaxTest.session = session;
}
});
crawljaxConfiguration.addPlugin(new OnInvariantViolationPlugin() {
@Override
public void onInvariantViolation(Invariant invariant, CrawlSession session) {
LargeCrawljaxTest.violatedInvariants.add(invariant);
}
});
}
private StateFlowGraph getStateFlowGraph() {
return session.getStateMachine().getStateFlowGraph();
}
} |
package com.eaglesakura.util;
import org.junit.Test;
import java.util.HashSet;
import java.util.Set;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
public class StringUtilTest {
@Test
public void base64() throws Exception {
byte[] buffer = "this is test".getBytes();
String encoded = StringUtil.toString(buffer);
assertNotNull(encoded);
assertNotEquals(encoded, "");
byte[] decoded = StringUtil.toByteArray(encoded);
assertArrayEquals(buffer, decoded);
}
@Test
public void () throws Exception {
{
final Set<Long> ALL_HASH = new HashSet<>();
final int LOOP_NUM = 4096;
for (int i = 0; i < LOOP_NUM; ++i) {
ALL_HASH.add(StringUtil.getHash64(RandomUtil.randString()));
}
assertEquals(ALL_HASH.size(), LOOP_NUM);
}
{
final Set<Long> ALL_HASH = new HashSet<>();
final int LOOP_NUM = 4096;
for (int i = 0; i < LOOP_NUM; ++i) {
String str = StringUtil.format("Value[%07d]", i);
long hash = StringUtil.getHash64(str);
// LogUtil.log("Str(%s) Hash(%X)", str, hash);
ALL_HASH.add(hash);
}
assertEquals(ALL_HASH.size(), LOOP_NUM);
}
}
} |
package com.notnoop.apns;
import static org.junit.Assert.*;
import java.util.Arrays;
import org.junit.Test;
public class PayloadBuilderTest {
@Test
public void testEmpty() {
PayloadBuilder builder = new PayloadBuilder();
String expected = "{\"aps\":{}}";
String actual = builder.toString();
assertEquals(expected, actual);
}
@Test
public void testOneAps() {
PayloadBuilder builder = new PayloadBuilder();
builder.alertBody("test");
String expected = "{\"aps\":{\"alert\":\"test\"}}";
String actual = builder.toString();
assertEquals(expected, actual);
}
@Test
public void testTwoAps() {
PayloadBuilder builder = new PayloadBuilder();
builder.alertBody("test");
builder.badge(9);
String expected = "{\"aps\":{\"alert\":\"test\",\"badge\":9}}";
String actual = builder.toString();
assertEquals(expected, actual);
}
@Test
public void testTwoApsMultipleBuilds() {
PayloadBuilder builder = new PayloadBuilder();
builder.alertBody("test");
builder.badge(9);
String expected = "{\"aps\":{\"alert\":\"test\",\"badge\":9}}";
assertEquals(expected, builder.build());
assertEquals(expected, builder.build());
}
@Test
public void testIncludeBadge() {
String badge0 = APNS.newPayload().badge(0).toString();
String badgeNo = APNS.newPayload().clearBadge().toString();
String expected = "{\"aps\":{\"badge\":0}}";
assertEquals(expected, badge0);
assertEquals(expected, badgeNo);
}
@Test
public void localizedOneWithArray() {
PayloadBuilder builder = new PayloadBuilder()
.localizedKey("GAME_PLAY_REQUEST_FORMAT")
.localizedArguments(new String[] { "Jenna", "Frank" });
builder.sound("chime");
String expected = "{\"aps\":{\"sound\":\"chime\",\"alert\":{\"loc-key\":\"GAME_PLAY_REQUEST_FORMAT\",\"loc-args\":[\"Jenna\",\"Frank\"]}}}";
String actual = builder.toString();
assertEquals(expected, actual);
}
@Test
public void localizedOneWithVarargs() {
PayloadBuilder builder = new PayloadBuilder()
.localizedKey("GAME_PLAY_REQUEST_FORMAT")
.localizedArguments("Jenna", "Frank");
builder.sound("chime");
String expected = "{\"aps\":{\"sound\":\"chime\",\"alert\":{\"loc-key\":\"GAME_PLAY_REQUEST_FORMAT\",\"loc-args\":[\"Jenna\",\"Frank\"]}}}";
String actual = builder.toString();
assertEquals(expected, actual);
}
@Test
public void localizedTwo() {
PayloadBuilder builder =
new PayloadBuilder()
.sound("chime")
.localizedKey("GAME_PLAY_REQUEST_FORMAT")
.localizedArguments(new String[] { "Jenna", "Frank" });
String expected = "{\"aps\":{\"sound\":\"chime\",\"alert\":{\"loc-key\":\"GAME_PLAY_REQUEST_FORMAT\",\"loc-args\":[\"Jenna\",\"Frank\"]}}}";
String actual = builder.toString();
assertEquals(expected, actual);
}
@Test
public void customFieldSimple() {
PayloadBuilder builder = new PayloadBuilder();
builder.alertBody("test");
builder.customField("ache1", "what");
builder.customField("ache2", 2);
String expected = "{\"ache1\":\"what\",\"ache2\":2,\"aps\":{\"alert\":\"test\"}}";
String actual = builder.toString();
assertEquals(expected, actual);
}
@Test
public void customFieldArray() {
PayloadBuilder builder = new PayloadBuilder();
builder.alertBody("test");
builder.customField("ache1", Arrays.asList("a1", "a2"));
builder.customField("ache2", new int[] { 1, 2 } );
String expected = "{\"ache1\":[\"a1\",\"a2\"],\"ache2\":[1,2],\"aps\":{\"alert\":\"test\"}}";
String actual = builder.toString();
assertEquals(expected, actual);
}
@Test
public void customBody() {
PayloadBuilder builder = new PayloadBuilder();
builder.alertBody("what").actionKey("Cancel");
String expected = "{\"aps\":{\"alert\":{\"action-loc-key\":\"Cancel\",\"body\":\"what\"}}}";
String actual = builder.toString();
assertEquals(expected, actual);
}
@Test
public void multipleBuildCallsWithCustomBody() {
PayloadBuilder builder = new PayloadBuilder();
builder.alertBody("what").actionKey("Cancel");
String expected = "{\"aps\":{\"alert\":{\"action-loc-key\":\"Cancel\",\"body\":\"what\"}}}";
assertEquals(expected, builder.build());
assertEquals(expected, builder.build());
}
@Test
public void customBodyReverseOrder() {
PayloadBuilder builder = new PayloadBuilder();
builder.actionKey("Cancel").alertBody("what");
String expected = "{\"aps\":{\"alert\":{\"action-loc-key\":\"Cancel\",\"body\":\"what\"}}}";
String actual = builder.toString();
assertEquals(expected, actual);
}
@Test
public void alertNoView() {
PayloadBuilder builder = new PayloadBuilder();
builder.actionKey(null).alertBody("what");
String expected = "{\"aps\":{\"alert\":{\"action-loc-key\":null,\"body\":\"what\"}}}";
String actual = builder.toString();
assertEquals(expected, actual);
}
@Test
public void alertNoViewSimpler() {
PayloadBuilder builder = new PayloadBuilder();
builder.noActionButton().alertBody("what");
String expected = "{\"aps\":{\"alert\":{\"action-loc-key\":null,\"body\":\"what\"}}}";
String actual = builder.toString();
assertEquals(expected, actual);
}
@Test
public void emptyApsWithFields() {
PayloadBuilder builder = new PayloadBuilder();
builder.customField("achme2", new int[] { 5, 8 } );
String expected = "{\"achme2\":[5,8],\"aps\":{}}";
String actual = builder.toString();
assertEquals(expected, actual);
}
@Test
public void abitComplicated() {
PayloadBuilder builder = new PayloadBuilder();
builder.customField("achme", "foo");
builder.sound("chime");
builder.localizedKey("GAME_PLAY_REQUEST_FORMAT")
.localizedArguments(new String[] { "Jenna", "Frank"});
String expected = "{\"achme\":\"foo\",\"aps\":{\"sound\":\"chime\",\"alert\":{\"loc-key\":\"GAME_PLAY_REQUEST_FORMAT\",\"loc-args\":[\"Jenna\",\"Frank\"]}}}";
String actual = builder.toString();
assertEquals(expected, actual);
}
@Test
public void multipleBuildAbitComplicated() {
PayloadBuilder builder = new PayloadBuilder();
builder.customField("achme", "foo");
builder.sound("chime");
builder.localizedKey("GAME_PLAY_REQUEST_FORMAT")
.localizedArguments(new String[] { "Jenna", "Frank"});
String expected = "{\"achme\":\"foo\",\"aps\":{\"sound\":\"chime\",\"alert\":{\"loc-key\":\"GAME_PLAY_REQUEST_FORMAT\",\"loc-args\":[\"Jenna\",\"Frank\"]}}}";
assertEquals(expected, builder.build());
assertEquals(expected, builder.build());
}
} |
package io.spine.client;
import com.google.common.annotations.VisibleForTesting;
import io.grpc.stub.StreamObserver;
import java.util.ArrayList;
import java.util.List;
import static com.google.common.base.Preconditions.checkNotNull;
final class ActiveSubscriptions {
private final List<Subscription> subscriptions = new ArrayList<>();
/** Remembers the passed subscription for future use. */
void remember(Subscription s) {
subscriptions.add(checkNotNull(s));
}
/** Forgets the passed subscription. */
void forget(Subscription s) {
subscriptions.remove(checkNotNull(s));
}
/** Cancels all the remembered subscriptions. */
void cancelAll(Client client) {
// Use the loop approach to avoid concurrent modification because the `Client` modifies
// active subscriptions when canceling.
while (!subscriptions.isEmpty()) {
Subscription subscription = subscriptions.get(0);
client.cancel(subscription);
}
}
@VisibleForTesting
boolean contains(Subscription s) {
return subscriptions.contains(s);
}
@VisibleForTesting
boolean isEmpty() {
return subscriptions.isEmpty();
}
} |
package com.turn.ttorrent.client;
import com.sun.org.apache.xpath.internal.SourceTree;
import com.turn.ttorrent.ClientFactory;
import com.turn.ttorrent.TempFiles;
import com.turn.ttorrent.Utils;
import com.turn.ttorrent.WaitFor;
import com.turn.ttorrent.client.peer.SharingPeer;
import com.turn.ttorrent.common.PeerUID;
import com.turn.ttorrent.common.Torrent;
import com.turn.ttorrent.tracker.TrackedPeer;
import com.turn.ttorrent.tracker.TrackedTorrent;
import com.turn.ttorrent.tracker.Tracker;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.*;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.io.*;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.channels.ByteChannel;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.zip.CRC32;
import java.util.zip.Checksum;
import static com.turn.ttorrent.ClientFactory.DEFAULT_POOL_SIZE;
import static org.testng.Assert.*;
@Test(timeOut = 600000)
public class ClientTest {
private ClientFactory clientFactory;
private List<Client> clientList;
private static final String TEST_RESOURCES = "src/test/resources";
private Tracker tracker;
private TempFiles tempFiles;
public ClientTest(){
clientFactory = new ClientFactory();
if (Logger.getRootLogger().getAllAppenders().hasMoreElements())
return;
BasicConfigurator.configure(new ConsoleAppender(new PatternLayout("[%d{MMdd HH:mm:ss,SSS} %t] %6p - %20.20c - %m %n")));
Torrent.setHashingThreadsCount(1);
}
@BeforeMethod
public void setUp() throws IOException {
tempFiles = new TempFiles();
clientList = new ArrayList<Client>();
Logger.getRootLogger().setLevel(Utils.getLogLevel());
startTracker();
}
// @Test(invocationCount = 50)
public void download_multiple_files() throws IOException, NoSuchAlgorithmException, InterruptedException, URISyntaxException {
int numFiles = 50;
this.tracker.setAcceptForeignTorrents(true);
final File srcDir = tempFiles.createTempDir();
final File downloadDir = tempFiles.createTempDir();
Client seeder = createClient("seeder");
seeder.start(InetAddress.getLocalHost());
Client leech = null;
try {
URL announce = new URL("http://127.0.0.1:6969/announce");
URI announceURI = announce.toURI();
final Set<String> names = new HashSet<String>();
List<File> filesToShare = new ArrayList<File>();
for (int i = 0; i < numFiles; i++) {
File tempFile = tempFiles.createTempFile(513 * 1024);
File srcFile = new File(srcDir, tempFile.getName());
assertTrue(tempFile.renameTo(srcFile));
Torrent torrent = Torrent.create(srcFile, announceURI, "Test");
File torrentFile = new File(srcFile.getParentFile(), srcFile.getName() + ".torrent");
torrent.save(torrentFile);
filesToShare.add(srcFile);
names.add(srcFile.getName());
}
for (File f : filesToShare) {
File torrentFile = new File(f.getParentFile(), f.getName() + ".torrent");
seeder.addTorrent(torrentFile.getAbsolutePath(), f.getParent());
}
leech = createClient("leecher");
leech.start(new InetAddress[]{InetAddress.getLocalHost()}, 5, null);
for (File f : filesToShare) {
File torrentFile = new File(f.getParentFile(), f.getName() + ".torrent");
leech.addTorrent(torrentFile.getAbsolutePath(), downloadDir.getAbsolutePath());
}
new WaitFor(60 * 1000) {
@Override
protected boolean condition() {
final Set<String> strings = listFileNames(downloadDir);
int count = 0;
final List<String> partItems = new ArrayList<String>();
for (String s : strings) {
if (s.endsWith(".part")){
count++;
partItems.add(s);
}
}
if (count < 5){
System.err.printf("Count: %d. Items: %s%n", count, Arrays.toString(partItems.toArray()));
}
return strings.containsAll(names);
}
};
assertEquals(listFileNames(downloadDir), names);
} finally {
leech.stop();
seeder.stop();
}
}
private Set<String> listFileNames(File downloadDir) {
if (downloadDir == null) return Collections.emptySet();
Set<String> names = new HashSet<String>();
File[] files = downloadDir.listFiles();
if (files == null) return Collections.emptySet();
for (File f : files) {
names.add(f.getName());
}
return names;
}
// @Test(invocationCount = 50)
public void large_file_download() throws IOException, URISyntaxException, NoSuchAlgorithmException, InterruptedException {
this.tracker.setAcceptForeignTorrents(true);
File tempFile = tempFiles.createTempFile(201 * 1025 * 1024);
URL announce = new URL("http://127.0.0.1:6969/announce");
URI announceURI = announce.toURI();
Torrent torrent = Torrent.create(tempFile, announceURI, "Test");
File torrentFile = new File(tempFile.getParentFile(), tempFile.getName() + ".torrent");
torrent.save(torrentFile);
Client seeder = createClient();
seeder.addTorrent(torrentFile.getAbsolutePath(), tempFile.getParent());
final File downloadDir = tempFiles.createTempDir();
Client leech = createClient();
leech.addTorrent(torrentFile.getAbsolutePath(), downloadDir.getAbsolutePath());
try {
seeder.start(InetAddress.getLocalHost());
leech.start(InetAddress.getLocalHost());
waitForFileInDir(downloadDir, tempFile.getName());
assertFilesEqual(tempFile, new File(downloadDir, tempFile.getName()));
} finally {
seeder.stop();
leech.stop();
}
}
public void more_than_one_seeder_for_same_torrent() throws IOException, NoSuchAlgorithmException, InterruptedException, URISyntaxException {
this.tracker.setAcceptForeignTorrents(true);
assertEquals(0, this.tracker.getTrackedTorrents().size());
int numSeeders = 5;
List<Client> seeders = new ArrayList<Client>();
for (int i = 0; i < numSeeders; i++) {
seeders.add(createClient());
}
try {
File tempFile = tempFiles.createTempFile(100 * 1024);
Torrent torrent = Torrent.create(tempFile, this.tracker.getAnnounceURI(), "Test");
File torrentFile = new File(tempFile.getParentFile(), tempFile.getName() + ".torrent");
torrent.save(torrentFile);
for (int i = 0; i < numSeeders; i++) {
Client client = seeders.get(i);
client.addTorrent(torrentFile.getAbsolutePath(), tempFile.getParent());
client.start(InetAddress.getLocalHost());
}
Utils.waitForPeers(numSeeders, tracker.getTrackedTorrents());
Collection<TrackedTorrent> torrents = this.tracker.getTrackedTorrents();
assertEquals(torrents.size(), 1);
assertEquals(numSeeders, torrents.iterator().next().seeders());
} finally {
for (Client client : seeders) {
client.stop();
}
}
}
public void no_full_seeder_test() throws IOException, URISyntaxException, InterruptedException, NoSuchAlgorithmException {
this.tracker.setAcceptForeignTorrents(true);
final int pieceSize = 48*1024; // lower piece size to reduce disk usage
final int numSeeders = 6;
final int piecesCount = numSeeders * 3 + 15;
final List<Client> clientsList;
clientsList = new ArrayList<Client>(piecesCount);
final MessageDigest md5 = MessageDigest.getInstance("MD5");
try {
File tempFile = tempFiles.createTempFile(piecesCount * pieceSize);
createMultipleSeedersWithDifferentPieces(tempFile, piecesCount, pieceSize, numSeeders, clientsList);
String baseMD5 = getFileMD5(tempFile, md5);
validateMultipleClientsResults(clientsList, md5, tempFile, baseMD5);
} finally {
for (Client client : clientsList) {
client.stop();
}
}
}
// @Test(invocationCount = 50)
public void corrupted_seeder_repair() throws NoSuchAlgorithmException, IOException, URISyntaxException, InterruptedException {
this.tracker.setAcceptForeignTorrents(true);
final int pieceSize = 48*1024; // lower piece size to reduce disk usage
final int numSeeders = 6;
final int piecesCount = numSeeders +7;
final List<Client> clientsList;
clientsList = new ArrayList<Client>(piecesCount);
final MessageDigest md5 = MessageDigest.getInstance("MD5");
try {
File baseFile = tempFiles.createTempFile(piecesCount * pieceSize);
createMultipleSeedersWithDifferentPieces(baseFile, piecesCount, pieceSize, numSeeders, clientsList);
String baseMD5 = getFileMD5(baseFile, md5);
Client firstClient = clientsList.get(0);
final SharedTorrent torrent = firstClient.getTorrents().iterator().next();
final File file = new File(torrent.getParentFile(), torrent.getFilenames().get(0));
final int oldByte;
{
RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.seek(0);
oldByte = raf.read();
raf.seek(0);
// replacing the byte
if (oldByte != 35) {
raf.write(35);
} else {
raf.write(45);
}
raf.close();
}
final WaitFor waitFor = new WaitFor(60 * 1000) {
@Override
protected boolean condition() {
for (Client client : clientsList) {
final SharedTorrent next = client.getTorrents().iterator().next();
if (next.getCompletedPieces().cardinality() < next.getPieceCount()-1){
return false;
}
}
return true;
}
};
if (!waitFor.isMyResult()){
fail("All seeders didn't get their files");
}
Thread.sleep(10*1000);
{
byte[] piece = new byte[pieceSize];
FileInputStream fin = new FileInputStream(baseFile);
fin.read(piece);
fin.close();
RandomAccessFile raf;
try {
raf = new RandomAccessFile(file, "rw");
raf.seek(0);
raf.write(oldByte);
raf.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
validateMultipleClientsResults(clientsList, md5, baseFile, baseMD5);
} finally {
for (Client client : clientsList) {
client.stop();
}
}
}
public void testThatTorrentsHaveLazyInitAndRemovingAfterDownload()
throws IOException, InterruptedException, NoSuchAlgorithmException, URISyntaxException {
Client seeder = createClient();
File tempFile = tempFiles.createTempFile(100 * 1025 * 1024);
URL announce = new URL("http://127.0.0.1:6969/announce");
URI announceURI = announce.toURI();
Torrent torrent = Torrent.create(tempFile, announceURI, "Test");
File torrentFile = new File(tempFile.getParentFile(), tempFile.getName() + ".torrent");
torrent.save(torrentFile);
seeder.addTorrent(torrentFile.getAbsolutePath(), tempFile.getParentFile().getAbsolutePath());
final ExecutorService es = Executors.newFixedThreadPool(8);
final AtomicBoolean newPeerIsCreated = new AtomicBoolean(false);
final AtomicBoolean peerIsDisconnected = new AtomicBoolean(false);
Client leecher = new Client(es) {
@Override
public SharingPeer createSharingPeer(String host, int port, ByteBuffer peerId, SharedTorrent torrent, ByteChannel channel) {
newPeerIsCreated.set(true);
return super.createSharingPeer(host, port, peerId, torrent, channel);
}
@Override
public void handlePeerDisconnected(SharingPeer peer) {
super.handlePeerDisconnected(peer);
peerIsDisconnected.set(true);
}
@Override
public void stop() {
super.stop();
es.shutdown();
}
};
clientList.add(leecher);
File downloadDir = tempFiles.createTempDir();
leecher.addTorrent(torrentFile.getAbsolutePath(), downloadDir.getAbsolutePath());
seeder.start(InetAddress.getLocalHost());
assertEquals(1, seeder.getTorrentsStorage().announceableTorrents().size());
assertEquals(0, seeder.getTorrentsStorage().activeTorrents().size());
assertEquals(0, leecher.getTorrentsStorage().activeTorrents().size());
leecher.start(InetAddress.getLocalHost());
new WaitFor(10*1000) {
@Override
protected boolean condition() {
return newPeerIsCreated.get();
}
};
assertEquals(1, seeder.getTorrentsStorage().activeTorrents().size());
assertEquals(1, leecher.getTorrentsStorage().activeTorrents().size());
waitForFileInDir(downloadDir, tempFile.getName());
assertFilesEqual(tempFile, new File(downloadDir, tempFile.getName()));
new WaitFor(10*1000) {
@Override
protected boolean condition() {
return peerIsDisconnected.get();
}
};
assertEquals(0, seeder.getTorrentsStorage().activeTorrents().size());
assertEquals(0, leecher.getTorrentsStorage().activeTorrents().size());
}
public void corrupted_seeder() throws NoSuchAlgorithmException, IOException, URISyntaxException, InterruptedException {
this.tracker.setAcceptForeignTorrents(true);
final int pieceSize = 48*1024; // lower piece size to reduce disk usage
final int piecesCount = 35;
final List<Client> clientsList;
clientsList = new ArrayList<Client>(piecesCount);
final MessageDigest md5 = MessageDigest.getInstance("MD5");
try {
final File baseFile = tempFiles.createTempFile(piecesCount * pieceSize);
final File badFile = tempFiles.createTempFile(piecesCount * pieceSize);
final Client client2 = createAndStartClient();
final File client2Dir = tempFiles.createTempDir();
final File client2File = new File(client2Dir, baseFile.getName());
FileUtils.copyFile(badFile, client2File);
final Torrent torrent = Torrent.create(baseFile, null, this.tracker.getAnnounceURI(), null, "Test", pieceSize);
final File torrentFile = tempFiles.createTempFile();
torrent.save(torrentFile);
client2.addTorrent(torrentFile.getAbsolutePath(), client2Dir.getAbsolutePath());
final String baseMD5 = getFileMD5(baseFile, md5);
final Client leech = createAndStartClient();
final File leechDestDir = tempFiles.createTempDir();
final AtomicReference<Exception> thrownException = new AtomicReference<Exception>();
final Thread th = new Thread(new Runnable() {
@Override
public void run() {
try {
leech.downloadUninterruptibly(torrentFile.getAbsolutePath(), leechDestDir.getAbsolutePath(), 7);
} catch (Exception e) {
thrownException.set(e);
throw new RuntimeException(e);
}
}
});
th.start();
final WaitFor waitFor = new WaitFor(30 * 1000) {
@Override
protected boolean condition() {
return th.getState() == Thread.State.TERMINATED;
}
};
final Map<Thread, StackTraceElement[]> allStackTraces = Thread.getAllStackTraces();
for (Map.Entry<Thread, StackTraceElement[]> entry : allStackTraces.entrySet()) {
System.out.printf("%s:%n", entry.getKey().getName());
for (StackTraceElement elem : entry.getValue()) {
System.out.println(elem.toString());
}
}
assertTrue(waitFor.isMyResult());
assertNotNull(thrownException.get());
assertTrue(thrownException.get().getMessage().contains("Unable to download torrent completely"));
} finally {
for (Client client : clientsList) {
client.stop();
}
}
}
public void unlock_file_when_no_leechers() throws InterruptedException, NoSuchAlgorithmException, IOException {
Client seeder = createClient();
tracker.setAcceptForeignTorrents(true);
final File dwnlFile = tempFiles.createTempFile(513 * 1024 * 7);
final Torrent torrent = Torrent.create(dwnlFile, null, tracker.getAnnounceURI(), "Test");
final File torrentFile = tempFiles.createTempFile();
torrent.save(torrentFile);
seeder.addTorrent(torrentFile.getAbsolutePath(), dwnlFile.getParent());
seeder.start(InetAddress.getLocalHost());
downloadAndStop(torrent, 15*1000, createClient());
Thread.sleep(2 * 1000);
assertTrue(dwnlFile.exists() && dwnlFile.isFile());
final boolean delete = dwnlFile.delete();
assertTrue(delete && !dwnlFile.exists());
}
public void download_many_times() throws InterruptedException, NoSuchAlgorithmException, IOException {
Client seeder = createClient();
tracker.setAcceptForeignTorrents(true);
final File dwnlFile = tempFiles.createTempFile(513 * 1024 * 7);
final Torrent torrent = Torrent.create(dwnlFile, null, tracker.getAnnounceURI(), "Test");
final File torrentFile = tempFiles.createTempFile();
torrent.save(torrentFile);
seeder.addTorrent(torrentFile.getAbsolutePath(), dwnlFile.getParent());
seeder.start(InetAddress.getLocalHost());
for(int i=0; i<5; i++) {
downloadAndStop(torrent, 250*1000, createClient());
Thread.sleep(3*1000);
}
}
public void testConnectToAllDiscoveredPeers() throws Exception {
tracker.setAcceptForeignTorrents(true);
final ExecutorService executorService = Executors.newFixedThreadPool(8);
Client leecher = new Client(executorService);
leecher.setMaxInConnectionsCount(10);
leecher.setMaxOutConnectionsCount(10);
final File dwnlFile = tempFiles.createTempFile(513 * 1024 * 34);
final Torrent torrent = Torrent.create(dwnlFile, null, tracker.getAnnounceURI(), "Test");
final File torrentFile = tempFiles.createTempFile();
torrent.save(torrentFile);
final SharedTorrent sharedTorrent = new SharedTorrent(torrent, tempFiles.createTempDir(), true);
final String hexInfoHash = sharedTorrent.getHexInfoHash();
leecher.addTorrent(torrentFile.getAbsolutePath(), tempFiles.createTempDir().getAbsolutePath());
final List<ServerSocket> serverSockets = new ArrayList<ServerSocket>();
final int startPort = 6885;
int port = startPort;
PeerUID[] peerUids = new PeerUID[]{
new PeerUID(new InetSocketAddress("127.0.0.1", port++), hexInfoHash),
new PeerUID(new InetSocketAddress("127.0.0.1", port++), hexInfoHash),
new PeerUID(new InetSocketAddress("127.0.0.1", port), hexInfoHash)
};
final ExecutorService es = Executors.newSingleThreadExecutor();
try {
leecher.start(InetAddress.getLocalHost());
WaitFor waitFor = new WaitFor(5000) {
@Override
protected boolean condition() {
return tracker.getTrackedTorrent(hexInfoHash) != null;
}
};
assertTrue(waitFor.isMyResult());
final TrackedTorrent trackedTorrent = tracker.getTrackedTorrent(hexInfoHash);
Map<PeerUID, TrackedPeer> trackedPeerMap = new HashMap<PeerUID, TrackedPeer>();
port = startPort;
for (PeerUID uid : peerUids) {
trackedPeerMap.put(uid, new TrackedPeer(trackedTorrent, "127.0.0.1", port, ByteBuffer.wrap("id".getBytes(Torrent.BYTE_ENCODING))));
serverSockets.add(new ServerSocket(port));
port++;
}
trackedTorrent.getPeers().putAll(trackedPeerMap);
//wait until all server sockets accept connection from leecher
for (final ServerSocket ss : serverSockets) {
final Future<?> future = es.submit(new Runnable() {
@Override
public void run() {
try {
final Socket socket = ss.accept();
socket.close();
} catch (IOException e) {
throw new RuntimeException("can not accept connection");
}
}
});
try {
future.get(5, TimeUnit.SECONDS);
} catch (ExecutionException e) {
fail("get execution exception on accept connection", e);
} catch (TimeoutException e) {
fail("not received connection from leecher in specified timeout", e);
}
}
} finally {
for (ServerSocket ss : serverSockets) {
try {
ss.close();
} catch (IOException e) {
fail("can not close server socket", e);
}
}
es.shutdown();
leecher.stop();
}
}
public void download_io_error() throws InterruptedException, NoSuchAlgorithmException, IOException{
tracker.setAcceptForeignTorrents(true);
Client seeder = createClient();
final File dwnlFile = tempFiles.createTempFile(513 * 1024 * 34);
final Torrent torrent = Torrent.create(dwnlFile, null, tracker.getAnnounceURI(), "Test");
final File torrentFile = tempFiles.createTempFile();
torrent.save(torrentFile);
seeder.addTorrent(torrentFile.getAbsolutePath(), dwnlFile.getParent());
seeder.start(InetAddress.getLocalHost());
final AtomicInteger interrupts = new AtomicInteger(0);
final ExecutorService es = Executors.newFixedThreadPool(DEFAULT_POOL_SIZE);
final Client leech = new Client(es){
@Override
public void handlePieceCompleted(SharingPeer peer, Piece piece) throws IOException {
super.handlePieceCompleted(peer, piece);
if (piece.getIndex()%4==0 && interrupts.incrementAndGet() <= 2){
peer.unbind(true);
}
}
@Override
public void stop(int timeout, TimeUnit timeUnit) {
super.stop(timeout, timeUnit);
es.shutdown();
}
};
//manually add leech here for graceful shutdown.
clientList.add(leech);
downloadAndStop(torrent, 45 * 1000, leech);
Thread.sleep(2*1000);
}
public void download_uninterruptibly_positive() throws InterruptedException, NoSuchAlgorithmException, IOException {
tracker.setAcceptForeignTorrents(true);
Client seeder = createClient();
final File dwnlFile = tempFiles.createTempFile(513 * 1024 * 24);
final Torrent torrent = Torrent.create(dwnlFile, null, tracker.getAnnounceURI(), "Test");
final File torrentFile = tempFiles.createTempFile();
torrent.save(torrentFile);
seeder.start(InetAddress.getLocalHost());
seeder.addTorrent(torrentFile.getAbsolutePath(), dwnlFile.getParent());
Client leecher = createClient();
leecher.start(InetAddress.getLocalHost());
leecher.downloadUninterruptibly(torrentFile.getAbsolutePath(), tempFiles.createTempDir().getAbsolutePath(), 10);
}
public void download_uninterruptibly_negative() throws InterruptedException, NoSuchAlgorithmException, IOException {
tracker.setAcceptForeignTorrents(true);
final AtomicInteger downloadedPiecesCount = new AtomicInteger(0);
final Client seeder = createClient();
final File dwnlFile = tempFiles.createTempFile(513 * 1024 * 24);
final Torrent torrent = Torrent.create(dwnlFile, null, tracker.getAnnounceURI(), "Test");
final File torrentFile = tempFiles.createTempFile();
torrent.save(torrentFile);
seeder.start(InetAddress.getLocalHost());
seeder.addTorrent(torrentFile.getAbsolutePath(), dwnlFile.getParent());
final ExecutorService es = Executors.newFixedThreadPool(DEFAULT_POOL_SIZE);
final Client leecher = new Client(es){
@Override
public void stop(int timeout, TimeUnit timeUnit) {
super.stop(timeout, timeUnit);
es.shutdown();
}
@Override
public void handlePieceCompleted(SharingPeer peer, Piece piece) throws IOException {
super.handlePieceCompleted(peer, piece);
if (downloadedPiecesCount.incrementAndGet() > 10){
seeder.stop();
}
}
};
clientList.add(leecher);
leecher.start(InetAddress.getLocalHost());
final File destDir = tempFiles.createTempDir();
try {
leecher.downloadUninterruptibly(torrentFile.getAbsolutePath(), destDir.getAbsolutePath(), 5);
fail("Must fail, because file wasn't downloaded completely");
} catch (IOException ex){
// ensure .part was deleted:
assertEquals(0, destDir.list().length);
}
}
public void download_uninterruptibly_timeout() throws InterruptedException, NoSuchAlgorithmException, IOException {
tracker.setAcceptForeignTorrents(true);
Client seeder = createClient();
final File dwnlFile = tempFiles.createTempFile(513 * 1024 * 24);
final Torrent torrent = Torrent.create(dwnlFile, null, tracker.getAnnounceURI(), "Test");
final File torrentFile = tempFiles.createTempFile();
torrent.save(torrentFile);
seeder.start(InetAddress.getLocalHost());
seeder.addTorrent(torrentFile.getAbsolutePath(), dwnlFile.getParent());
final AtomicInteger piecesDownloaded = new AtomicInteger(0);
final ExecutorService es = Executors.newFixedThreadPool(DEFAULT_POOL_SIZE);
Client leecher = new Client(es){
@Override
public void handlePieceCompleted(SharingPeer peer, Piece piece) throws IOException {
piecesDownloaded.incrementAndGet();
try {
Thread.sleep(piecesDownloaded.get()*500);
} catch (InterruptedException e) {
}
}
@Override
public void stop(int timeout, TimeUnit timeUnit) {
super.stop(timeout, timeUnit);
es.shutdown();
}
};
clientList.add(leecher);
leecher.start(InetAddress.getLocalHost());
try {
leecher.downloadUninterruptibly(torrentFile.getAbsolutePath(), tempFiles.createTempDir().getAbsolutePath(), 5);
fail("Must fail, because file wasn't downloaded completely");
} catch (IOException ex){
}
}
public void canStartAndStopClientTwice() throws Exception {
ExecutorService es = Executors.newFixedThreadPool(DEFAULT_POOL_SIZE);
final Client client = new Client(es);
clientList.add(client);
try {
client.start(InetAddress.getLocalHost());
client.stop();
client.start(InetAddress.getLocalHost());
client.stop();
} finally {
es.shutdown();
}
}
public void peer_dies_during_download() throws InterruptedException, NoSuchAlgorithmException, IOException {
tracker.setAnnounceInterval(5);
final Client seed1 = createClient();
final Client seed2 = createClient();
final File dwnlFile = tempFiles.createTempFile(513 * 1024 * 240);
final Torrent torrent = Torrent.create(dwnlFile, tracker.getAnnounceURI(), "Test");
final File torrentFile = tempFiles.createTempFile();
torrent.save(torrentFile);
seed1.addTorrent(torrentFile.getAbsolutePath(), dwnlFile.getParent());
seed1.start(InetAddress.getLocalHost());
seed1.setAnnounceInterval(5);
seed2.addTorrent(torrentFile.getAbsolutePath(), dwnlFile.getParent());
seed2.start(InetAddress.getLocalHost());
seed2.setAnnounceInterval(5);
Client leecher = createClient();
leecher.start(InetAddress.getLocalHost());
leecher.setAnnounceInterval(5);
final ExecutorService service = Executors.newFixedThreadPool(1);
final Future<?> future = service.submit(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(5 * 1000);
seed1.removeTorrent(torrent);
Thread.sleep(3*1000);
seed1.addTorrent(torrentFile.getAbsolutePath(), dwnlFile.getParent());
seed2.removeTorrent(torrent);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
try {
leecher.downloadUninterruptibly(torrentFile.getAbsolutePath(), tempFiles.createTempDir().getAbsolutePath(), 60);
} finally {
future.cancel(true);
service.shutdown();
}
}
public void interrupt_download() throws IOException, InterruptedException, NoSuchAlgorithmException {
tracker.setAcceptForeignTorrents(true);
final Client seeder = createClient();
final File dwnlFile = tempFiles.createTempFile(513 * 1024 * 60);
final Torrent torrent = Torrent.create(dwnlFile, null, tracker.getAnnounceURI(), "Test");
final File torrentFile = tempFiles.createTempFile();
torrent.save(torrentFile);
seeder.start(InetAddress.getLocalHost());
seeder.addTorrent(torrentFile.getAbsolutePath(), dwnlFile.getParent());
final Client leecher = createClient();
leecher.start(InetAddress.getLocalHost());
final AtomicBoolean interrupted = new AtomicBoolean();
final Thread th = new Thread(){
@Override
public void run() {
try {
leecher.downloadUninterruptibly(torrentFile.getAbsolutePath(), tempFiles.createTempDir().getAbsolutePath(), 30);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
interrupted.set(true);
return;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return;
}
}
};
th.start();
Thread.sleep(400);
th.interrupt();
new WaitFor(10*1000){
@Override
protected boolean condition() {
return !th.isAlive();
}
};
assertTrue(interrupted.get());
}
public void test_connect_to_unknown_host() throws InterruptedException, NoSuchAlgorithmException, IOException {
final File torrent = new File("src/test/resources/torrents/file1.jar.torrent");
final TrackedTorrent tt = TrackedTorrent.load(torrent);
final Client seeder = createAndStartClient();
final Client leecher = createAndStartClient();
final TrackedTorrent announce = tracker.announce(tt);
final Random random = new Random();
final File leechFolder = tempFiles.createTempDir();
for (int i=0; i<40; i++) {
byte[] data = new byte[20];
random.nextBytes(data);
announce.addPeer(new TrackedPeer(tt, "my_unknown_and_unreachablehost" + i, 6881, ByteBuffer.wrap(data)));
}
File torrentFile = new File(TEST_RESOURCES + "/torrents", "file1.jar.torrent");
File parentFiles = new File(TEST_RESOURCES + "/parentFiles");
seeder.addTorrent(torrentFile.getAbsolutePath(), parentFiles.getAbsolutePath());
leecher.addTorrent(torrentFile.getAbsolutePath(), leechFolder.getAbsolutePath());
waitForFileInDir(leechFolder, "file1.jar");
}
public void test_seeding_does_not_change_file_modification_date() throws IOException, InterruptedException, NoSuchAlgorithmException {
File srcFile = tempFiles.createTempFile(1024);
long time = srcFile.lastModified();
Thread.sleep(1000);
Client seeder = createAndStartClient();
final Torrent torrent = Torrent.create(srcFile, null, tracker.getAnnounceURI(), "Test");
File torrentFile = tempFiles.createTempFile();
torrent.save(torrentFile);
seeder.addTorrent(torrentFile.getAbsolutePath(), srcFile.getParent(), true);
final File downloadDir = tempFiles.createTempDir();
Client leech = createClient();
leech.addTorrent(torrentFile.getAbsolutePath(), downloadDir.getAbsolutePath());
leech.start(InetAddress.getLocalHost());
waitForFileInDir(downloadDir, srcFile.getName());
assertEquals(time, srcFile.lastModified());
}
private void downloadAndStop(Torrent torrent, long timeout, final Client leech) throws IOException, NoSuchAlgorithmException, InterruptedException {
final File tempDir = tempFiles.createTempDir();
File torrentFile = tempFiles.createTempFile();
torrent.save(torrentFile);
leech.addTorrent(torrentFile.getAbsolutePath(), tempDir.getAbsolutePath());
leech.start(InetAddress.getLocalHost());
waitForFileInDir(tempDir, torrent.getFilenames().get(0));
leech.stop();
}
private void validateMultipleClientsResults(final List<Client> clientsList, MessageDigest md5, File baseFile, String baseMD5) throws IOException {
final WaitFor waitFor = new WaitFor(75 * 1000) {
@Override
protected boolean condition() {
boolean retval = true;
for (Client client : clientsList) {
if (!retval) return false;
final boolean torrentState = client.getTorrents().iterator().next().getClientState() == ClientState.SEEDING;
retval = retval && torrentState;
}
return retval;
}
};
assertTrue(waitFor.isMyResult(), "All seeders didn't get their files");
// check file contents here:
for (Client client : clientsList) {
final SharedTorrent st = client.getTorrents().iterator().next();
final File file = new File(st.getParentFile(), st.getFilenames().get(0));
assertEquals(baseMD5, getFileMD5(file, md5), String.format("MD5 hash is invalid. C:%s, O:%s ",
file.getAbsolutePath(), baseFile.getAbsolutePath()));
}
}
private void createMultipleSeedersWithDifferentPieces(File baseFile, int piecesCount, int pieceSize, int numSeeders,
List<Client> clientList) throws IOException, InterruptedException, NoSuchAlgorithmException, URISyntaxException {
List<byte[]> piecesList = new ArrayList<byte[]>(piecesCount);
FileInputStream fin = new FileInputStream(baseFile);
for (int i=0; i<piecesCount; i++){
byte[] piece = new byte[pieceSize];
fin.read(piece);
piecesList.add(piece);
}
fin.close();
final long torrentFileLength = baseFile.length();
Torrent torrent = Torrent.create(baseFile, null, this.tracker.getAnnounceURI(), null, "Test", pieceSize);
File torrentFile = new File(baseFile.getParentFile(), baseFile.getName() + ".torrent");
torrent.save(torrentFile);
for (int i=0; i<numSeeders; i++){
final File baseDir = tempFiles.createTempDir();
final File seederPiecesFile = new File(baseDir, baseFile.getName());
RandomAccessFile raf = new RandomAccessFile(seederPiecesFile, "rw");
raf.setLength(torrentFileLength);
for (int pieceIdx=i; pieceIdx<piecesCount; pieceIdx += numSeeders){
raf.seek(pieceIdx*pieceSize);
raf.write(piecesList.get(pieceIdx));
}
Client client = createClient(" client idx " + i);
clientList.add(client);
client.addTorrent(torrentFile.getAbsolutePath(), baseDir.getAbsolutePath());
client.start(InetAddress.getLocalHost());
}
}
private String getFileMD5(File file, MessageDigest digest) throws IOException {
DigestInputStream dIn = new DigestInputStream(new FileInputStream(file), digest);
while (dIn.read() >= 0);
return dIn.getMessageDigest().toString();
}
private void waitForFileInDir(final File downloadDir, final String fileName) {
new WaitFor() {
@Override
protected boolean condition() {
return new File(downloadDir, fileName).isFile();
}
};
assertTrue(new File(downloadDir, fileName).isFile());
}
@AfterMethod
protected void tearDown() throws Exception {
for (Client client : clientList) {
client.stop();
}
stopTracker();
tempFiles.cleanup();
}
private void startTracker() throws IOException {
this.tracker = new Tracker(6969);
tracker.setAnnounceInterval(5);
this.tracker.start(true);
}
private Client createAndStartClient() throws IOException, NoSuchAlgorithmException, InterruptedException {
Client client = createClient();
client.start(InetAddress.getLocalHost());
return client;
}
private Client createClient(String name) throws IOException, NoSuchAlgorithmException, InterruptedException {
final Client client = clientFactory.getClient(name);
clientList.add(client);
return client;
}
private Client createClient() throws IOException, NoSuchAlgorithmException, InterruptedException {
return createClient("");
}
private SharedTorrent completeTorrent(String name) throws IOException, NoSuchAlgorithmException {
File torrentFile = new File(TEST_RESOURCES + "/torrents", name);
File parentFiles = new File(TEST_RESOURCES + "/parentFiles");
return SharedTorrent.fromFile(torrentFile, parentFiles, false);
}
private SharedTorrent incompleteTorrent(String name, File destDir) throws IOException, NoSuchAlgorithmException {
File torrentFile = new File(TEST_RESOURCES + "/torrents", name);
return SharedTorrent.fromFile(torrentFile, destDir, false);
}
private void stopTracker() {
this.tracker.stop();
}
private void assertFilesEqual(File f1, File f2) throws IOException {
assertEquals(f1.length(), f2.length(), "Files sizes differ");
Checksum c1 = FileUtils.checksum(f1, new CRC32());
Checksum c2 = FileUtils.checksum(f2, new CRC32());
assertEquals(c1.getValue(), c2.getValue());
}
} |
package com.vryba.selenium;
import com.vryba.selenium.pageObjects.HomePage;
import com.vryba.selenium.pageObjects.QuestionsPage;
import com.vryba.selenium.utilities.TestBase;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.testng.Assert;
import org.testng.annotations.Test;
public class QuestionsPage_TC extends TestBase {
private Logger LOG = LogManager.getLogger(QuestionsPage_TC.class);
} |
package de.retest.recheck.util;
import static de.retest.recheck.util.FileUtil.convertListOfFiles2SemicolonJoinedString;
import static de.retest.recheck.util.FileUtil.convertSemicolonSeparatedString2ListOfFiles;
import static de.retest.recheck.util.FileUtil.getFileSizeInMB;
import static de.retest.recheck.util.FileUtil.removeExtension;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.offset;
import java.io.File;
import java.io.FileFilter;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.SystemUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.mockito.Mockito;
import de.retest.recheck.ioerror.ReTestSaveException;
public class FileUtilTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder( SystemUtils.IS_OS_MAC
? new File( "/private/" + System.getProperty( "java.io.tmpdir" ) )
: new File( System.getProperty( "java.io.tmpdir" ) ) );
private File getExecDir() {
return new File( System.getProperty( "user.dir" ) );
}
@Test
public void testConvertFileList2ListOfFiles_empty() throws IOException {
assertThat( convertSemicolonSeparatedString2ListOfFiles( getExecDir(), "" ) ).hasSize( 0 );
assertThat( convertSemicolonSeparatedString2ListOfFiles( getExecDir(), null ) ).hasSize( 0 );
}
@Test
public void testConvertFileList2ListOfFiles_single_file() throws IOException {
final List<File> result =
convertSemicolonSeparatedString2ListOfFiles( getExecDir(), "src/test/resources/ImageUtilsTest.png" );
assertThat( result.size() ).isEqualTo( 1 );
assertThat( result.get( 0 ).getName() ).isEqualTo( "ImageUtilsTest.png" );
}
@Test
public void testConvertFileList2ListOfFiles_multiple_files() throws IOException {
final List<File> result = convertSemicolonSeparatedString2ListOfFiles( getExecDir(),
"src/test/resources/ImageUtilsTest.png;src/test/resources/de/retest/image/img1.png" );
assertThat( result.size() ).isEqualTo( 2 );
assertThat( result.get( 0 ).getName() ).isEqualTo( "ImageUtilsTest.png" );
assertThat( result.get( 1 ).getName() ).isEqualTo( "img1.png" );
}
@Test
public void testConvertListOfFiles2FileList_empty_Files() throws IOException {
assertThat( convertListOfFiles2SemicolonJoinedString( new File( "target" ), new ArrayList<File>() ) )
.isEqualTo( "" );
assertThat( convertListOfFiles2SemicolonJoinedString( new File( "src/test/resources" ), null ) )
.isEqualTo( "" );
}
@Test
public void testConvertListOfFiles2FileList_single_File() throws IOException {
final List<File> files = new ArrayList<>();
files.add( new File( "src/test/resources/version.txt" ) );
assertThat( convertListOfFiles2SemicolonJoinedString( new File( "src" ), files ) )
.isEqualTo( "test" + File.separator + "resources" + File.separator + "version.txt" );
assertThat( convertListOfFiles2SemicolonJoinedString( new File( "src/test/resources" ), files ) )
.isEqualTo( "version.txt" );
// assertEquals( "version.txt",
// convertListOfFiles2SemicolonJoinedString( new File( "src/test/resources"), files ) );
}
@Test
public void testConvertListOfFiles2FileList_multiple_Files() throws IOException {
final List<File> files = new ArrayList<>();
files.add( new File( "src/test/resources/version.txt" ) );
files.add( new File( "src/test/resources/de/retest/util/login.png" ) );
assertThat( convertListOfFiles2SemicolonJoinedString( new File( "src" ), files ) )
.isEqualTo( "test/resources/version.txt;test/resources/de/retest/util/login.png" );
assertThat( convertListOfFiles2SemicolonJoinedString( new File( "src/test/resources" ), files ) )
.isEqualTo( "version.txt;de/retest/util/login.png" );
}
@Test
public void test_removeExtension() throws IOException {
assertThat( removeExtension( "" ) ).isEqualTo( "" );
assertThat( removeExtension( ".test" ) ).isEqualTo( "" );
assertThat( removeExtension( "me" ) ).isEqualTo( "me" );
assertThat( removeExtension( "me.test" ) ).isEqualTo( "me" );
assertThat( removeExtension( "me.too.test" ) ).isEqualTo( "me.too" );
assertThat( removeExtension( "me." ) ).isEqualTo( "me" );
}
@Test
public void test_getFileSizeInMB() throws Exception {
final URL resourceUrl = FileUtilTest.class.getResource( "/ImageUtilsTestResize.png" );
final String path = resourceUrl.toURI().getSchemeSpecificPart();
final File login = new File( path );
assertThat( getFileSizeInMB( login ) ).isEqualTo( 0.39267635345458984d, offset( 0.00000001d ) );
}
@Test
public void writeFile_should_write_File() throws Exception {
final File contendFolder = temp.newFolder();
final File fileToBeWritten = new File( contendFolder, "fileToBeWritten" );
FileUtil.writeToFile( fileToBeWritten, new FileUtil.Writer() {
@Override
public void write( final FileOutputStream out ) throws IOException {
out.write( 0x41 );
}
} );
assertThat( fileToBeWritten ).exists();
assertThat( FileUtil.readFileToString( fileToBeWritten ) ).isEqualTo( "A" );
}
@Test
public void writeFile_should_write_File_even_is_parentFolder_do_not_exsist() throws Exception {
final File contendFolder = temp.newFolder();
final File fileToBeWritten = new File( contendFolder, "nonExsistingFolder/fileToBeWritten.txt" );
FileUtil.writeToFile( fileToBeWritten, new FileUtil.Writer() {
@Override
public void write( final FileOutputStream out ) throws IOException {
out.write( 0x41 );
}
} );
assertThat( fileToBeWritten ).exists();
assertThat( FileUtil.readFileToString( fileToBeWritten ) ).isEqualTo( "A" );
}
@Test
public void writeFile_should_write_File_even_File_already_exsists() throws Exception {
final File contendFolder = temp.newFolder();
final File fileToBeWritten = new File( contendFolder, "fileToBeWritten" );
FileUtil.writeToFile( fileToBeWritten, new FileUtil.Writer() {
@Override
public void write( final FileOutputStream out ) throws IOException {
out.write( 0x43 );
}
} );
FileUtil.writeToFile( fileToBeWritten, new FileUtil.Writer() {
@Override
public void write( final FileOutputStream out ) throws IOException {
out.write( 0x41 );
}
} );
assertThat( fileToBeWritten ).exists();
assertThat( FileUtil.readFileToString( fileToBeWritten ) ).isEqualTo( "A" );
}
@Test( expected = ReTestSaveException.class )
public void writeFile_should_throw_exception_if_error_occurs() throws Exception {
FileUtil.writeToFile( new File( "." ), new FileUtil.Writer() {
@Override
public void write( final FileOutputStream out ) throws IOException {
throw new IOException( "Something bad happened" );
}
} );
}
@Test( expected = ReTestSaveException.class )
public void writeFile_should_throw_exception_if_writer_is_null() throws Exception {
final File contendFolder = temp.newFolder();
final File fileToBeWritten = new File( contendFolder, "nonExsistingFolder/fileToBeWritten.txt" );
FileUtil.writeToFile( fileToBeWritten, null );
}
@Test( expected = ReTestSaveException.class )
public void writeFile_should_throw_exception_if_file_is_a_directory() throws Exception {
final File contendFolder = temp.newFolder();
FileUtil.writeToFile( contendFolder, new FileUtil.Writer() {
@Override
public void write( final FileOutputStream out ) throws IOException {
out.write( 0x41 );
}
} );
}
@Test( expected = NullPointerException.class )
public void listFilesRecursively_should_throw_exception_list_if_folder_is_null() throws Exception {
final javax.swing.filechooser.FileNameExtensionFilter filter =
new javax.swing.filechooser.FileNameExtensionFilter( "textfiles", "txt" );
FileUtil.listFilesRecursively( null, filter );
}
@Test( expected = IllegalArgumentException.class )
public void listFilesRecursively_should_throw_exception_if_folder_does_not_exsist() throws Exception {
final javax.swing.filechooser.FileNameExtensionFilter filter =
new javax.swing.filechooser.FileNameExtensionFilter( "textfiles", "txt" );
FileUtil.listFilesRecursively( new File( "notExsistingFolder" ), filter );
}
@Test
public void listFilesRecursively_should_get_only_files_with_filter() throws Exception {
final File contendFolder = temp.newFolder( "testfolder" );
final File testFolder1 = new File( contendFolder.getAbsolutePath() + File.separator + "testFolder1" );
testFolder1.mkdirs();
final File testFolder11 = new File( testFolder1.getAbsolutePath() + File.separator + "testFolder11" );
testFolder11.mkdirs();
final File testFolder2 = new File( contendFolder.getAbsolutePath() + File.separator + "testFolder2" );
testFolder2.mkdirs();
final File testFile0 = File.createTempFile( "testFile0", ".txt", contendFolder );
final File testFile1 = File.createTempFile( "testFile1", ".txt", testFolder1 );
final File testFile11 = File.createTempFile( "testFile11", ".txt", testFolder11 );
final File testFile2 = File.createTempFile( "testFile2", ".txt", testFolder2 );
File.createTempFile( "testFile0_", ".png", contendFolder );
File.createTempFile( "testFile1_", ".exe", testFolder1 );
File.createTempFile( "testFile11_", ".pdf", testFolder11 );
File.createTempFile( "testFile2_", ".doc", testFolder2 );
final javax.swing.filechooser.FileNameExtensionFilter filter =
new javax.swing.filechooser.FileNameExtensionFilter( "textfiles", "txt" );
final List<File> result = FileUtil.listFilesRecursively( contendFolder, filter );
assertThat( result ).containsOnly( testFile0, testFile1, testFile11, testFile2, testFolder1, testFolder11,
testFolder2 );
}
@Test
public void listFiles_with_null_should_return_zero_files() throws Exception {
final File file = Mockito.mock( File.class );
Mockito.when( file.listFiles() ).thenReturn( null );
Mockito.when( file.isDirectory() ).thenReturn( true );
FileUtil.listFilesRecursively( file, new FileFilter() {
@Override
public boolean accept( final File arg0 ) {
return false;
}
} );
FileUtil.listFilesRecursively( file, new FilenameFilter() {
@Override
public boolean accept( final File file, final String s ) {
return false;
}
} );
FileUtil.listFilesRecursively( file, new javax.swing.filechooser.FileFilter() {
@Override
public String getDescription() {
return null;
}
@Override
public boolean accept( final File file ) {
return false;
}
} );
}
// readableCanonicalFileOrNull
@Test
public void readableCanonicalFileOrNull_return_file() throws Exception {
final File file = temp.newFile();
assertThat( FileUtil.readableCanonicalFileOrNull( file ) ).isEqualTo( file );
}
@Test
public void readableCanonicalFileOrNull_dont_return_unreadable_file() throws Exception {
final File file = temp.newFile();
file.setReadable( false );
assertThat( FileUtil.readableCanonicalFileOrNull( file ) ).isNull();
}
@Test
public void readableCanonicalFileOrNull_dont_return_unexisting_file() throws Exception {
final File file = temp.newFile();
file.delete();
assertThat( FileUtil.readableCanonicalFileOrNull( file ) ).isNull();
}
// readableWriteableCanonicalDirectoryOrNull
@Test
public void readableWriteableCanonicalDirectoryOrNull_return_directory() throws Exception {
final File file = temp.newFolder();
assertThat( FileUtil.readableWriteableCanonicalDirectoryOrNull( file ) ).isEqualTo( file );
}
@Test
public void readableWriteableCanonicalDirectoryOrNull_dont_returns_unreadable() throws Exception {
final File file = temp.newFolder();
file.setReadable( false );
assertThat( FileUtil.readableWriteableCanonicalDirectoryOrNull( file ) ).isNull();
}
@Test
public void readableWriteableCanonicalDirectoryOrNull_dont_returns_unwriteable() throws Exception {
final File file = temp.newFolder();
file.setWritable( false );
assertThat( FileUtil.readableWriteableCanonicalDirectoryOrNull( file ) ).isNull();
}
@Test
public void readableWriteableCanonicalDirectoryOrNull_dont_returns_unexecutable() throws Exception {
final File file = temp.newFolder();
file.setExecutable( false );
assertThat( FileUtil.readableWriteableCanonicalDirectoryOrNull( file ) ).isNull();
}
@Test
public void readableWriteableCanonicalDirectoryOrNull_return_directory_if_parent_is_read_write_and_executable()
throws Exception {
final File parent = temp.newFolder();
final File directory = new File( parent, "child" );
assertThat( FileUtil.readableWriteableCanonicalDirectoryOrNull( directory ) ).isEqualTo( directory );
}
@Test
public void readableWriteableCanonicalDirectoryOrNull_dont_returns_unreadable_parent() throws Exception {
final File parent = temp.newFolder();
final File directory = new File( parent, "child" );
parent.setReadable( false );
assertThat( FileUtil.readableWriteableCanonicalDirectoryOrNull( directory ) ).isNull();
}
@Test
public void readableWriteableCanonicalDirectoryOrNull_dont_returns_unwriteable_parent() throws Exception {
final File parent = temp.newFolder();
final File directory = new File( parent, "child" );
parent.setWritable( false );
assertThat( FileUtil.readableWriteableCanonicalDirectoryOrNull( directory ) ).isNull();
}
@Test
public void readableWriteableCanonicalDirectoryOrNull_dont_returns_unexecutable_parent() throws Exception {
final File parent = temp.newFolder();
final File directory = new File( parent, "child" );
parent.setExecutable( false );
assertThat( FileUtil.readableWriteableCanonicalDirectoryOrNull( directory ) ).isNull();
}
} |
package diergo.csv;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
import java.util.Collection;
import java.util.List;
import java.util.stream.LongStream;
import java.util.stream.Stream;
import static diergo.csv.CsvParserBuilder.csvParser;
import static diergo.csv.ErrorHandlers.ignoreErrors;
import static diergo.csv.Readers.asLines;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.stream.IntStream.rangeClosed;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.lessThan;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
@RunWith(DataProviderRunner.class)
public class CsvReaderPerformanceTest {
public static final String MAXMIND_WORLD_CITIES_POP = "/worldcitiespop.txt";
@Test
@DataProvider({"true,false,2500","false,false,2500","true,true,100","false,true,100"})
public void readMillions(boolean usingFlatMap, boolean parallel, long maxTime) throws IOException {
String kind = (usingFlatMap ? "using flat map" : "using filter and map")
+ ", " + (parallel ? "parallel" : "sequential");
System.out.println("starting dry run " + kind + "…");
runOnce(usingFlatMap, parallel);
long[] times = new long[6];
rangeClosed(1, times.length).forEachOrdered(loop -> {
try {
System.out.print(String.format("loop %d", loop));
long[] timeAndCount = runOnce(usingFlatMap, parallel);
times[loop - 1] = timeAndCount[0];
System.out.println(String.format(" took %dms to read %d rows", timeAndCount[0], timeAndCount[1]));
assertThat(timeAndCount[1], greaterThan(3000000L));
} catch (IOException e) {
fail(e.getMessage());
}
});
double average = LongStream.of(times).average().getAsDouble();
System.out.println(String.format("average %s is %.0fms", kind, average));
assertThat("acceptable average[ms] for " + kind, average, lessThan((double)maxTime));
}
private long[] runOnce(boolean usingFlatMap, boolean parallel) throws IOException {
InputStreamReader worldCitiesPopulation = new InputStreamReader(getClass().getResourceAsStream(MAXMIND_WORLD_CITIES_POP), UTF_8);
ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
long start = threadMXBean.getCurrentThreadCpuTime();
Stream<String> lines = asLines(worldCitiesPopulation);
if (parallel) {
lines = lines.parallel();
}
Stream<List<Row>> intermediate = lines
.map(csvParser().separatedBy(',').handlingErrors(ignoreErrors()).build());
long count = (usingFlatMap ? intermediate.flatMap(Collection::stream) :
intermediate.filter(rows -> !rows.isEmpty()).map(rows -> rows.get(0)))
.count();
long durations = (threadMXBean.getCurrentThreadCpuTime() - start) / 1000000L;
try {
return new long[]{durations, count};
} finally {
worldCitiesPopulation.close();
}
}
} |
package ee.pardiralli;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import java.text.SimpleDateFormat;
import java.util.Date;
import static junit.framework.TestCase.assertTrue;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestPropertySource(locations = "classpath:test.properties")
@RunWith(SpringRunner.class)
public class PardiralliSearchTests {
@LocalServerPort
private int port;
@Autowired
private TestRestTemplate restTemplate;
@Test
public void exactItemSearchIdsArePresent() throws Exception {
String page = this.restTemplate.getForObject("http://localhost:" + port + "/search", String.class);
assertTrue(page.contains("id=\"search_quick_id\""));
assertTrue(page.contains("id=\"search\""));
assertTrue(page.contains("id=\"search_quick_date\""));
}
@Test
public void moreGeneralItemSearchIdsArePresent() throws Exception {
String page = this.restTemplate.getForObject("http://localhost:" + port + "/search", String.class);
assertTrue(page.contains("id=\"search_long\""));
assertTrue(page.contains("id=\"first_name_long\""));
assertTrue(page.contains("id=\"last_name_long\""));
assertTrue(page.contains("id=\"email_long\""));
assertTrue(page.contains("id=\"phone_number_long\""));
assertTrue(page.contains("id=\"search_date_long\""));
}
@Ignore
@Test
public void checkAjaxQuerySending() {
WebDriver driver = new FirefoxDriver();
String url = "http://localhost:" + port + "/search";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
driver.get(url);
// Find the text input element by its name
WebElement dateSelect = driver.findElement(By.id("search_date_long"));
dateSelect.sendKeys(formatter.format(new Date()));
WebElement search = driver.findElement(By.id("search_long"));
search.click();
Boolean isJqueryUsed = (Boolean) ((JavascriptExecutor) driver).executeScript("return (typeof(jQuery) != 'undefined')");
if (isJqueryUsed) {
while (true) {
// JavaScript test to verify jQuery is active or not
Boolean ajaxIsComplete = (Boolean) (((JavascriptExecutor) driver).executeScript("return jQuery.active == 0"));
if (ajaxIsComplete) break;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
} else throw new RuntimeException();
driver.quit();
}
} |
package is.ru.coolpeople.tictactoe;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import static org.junit.Assert.*;
@SpringBootTest
public class GameTest {
@Test
public void testMakesGame() {
Player p1 = new Player("Anna", "X");
Player p2 = new Player("Hafsteinn", "O");
Queue<Player> players = new ArrayBlockingQueue<Player>(2);
players.add(p1);
players.add(p2);
Game g = new Game(players);
assertTrue(g != null);
}
@Test
public void testMakesCustomGameSize() {
Player p1 = new Player("Anna", "X");
Player p2 = new Player("Hafsteinn", "O");
Queue<Player> players = new ArrayBlockingQueue<Player>(2);
players.add(p1);
players.add(p2);
int boardWith = 3;
int boardHeight = 5;
Game g = new Game(players, boardWith, boardHeight);
assertTrue(g != null);
assertEquals((boardWith * boardHeight), g.getBoard().getGrid().length);
}
@Test
public void testDefaultWinConditionValue() {
Player p1 = new Player("Anna", "X");
Queue<Player> players = new ArrayBlockingQueue<Player>(2);
players.add(p1);
Game g = new Game(players);
assertTrue(g != null);
assertEquals(3, g.getWinCondition());
}
@Test
public void testCustomWinConditionValue() {
Player p1 = new Player("Anna", "X");
Queue<Player> players = new ArrayBlockingQueue<Player>(2);
players.add(p1);
Game g = new Game(players);
assertTrue(g != null);
g.setWinCondition(5);
assertEquals(5, g.getWinCondition());
}
@Test
public void testInvalidWinConditionException() {
Player p1 = new Player("Anna", "X");
Queue<Player> players = new ArrayBlockingQueue<Player>(2);
players.add(p1);
Game g = new Game(players);
assertTrue(g != null);
boolean caughtExceptionOne = false;
boolean caughtExceptionTwo = false;
try {
g.setWinCondition(1);
} catch (IllegalArgumentException e) {
caughtExceptionOne = true;
}
try {
g.setWinCondition(2);
} catch (IllegalArgumentException e) {
caughtExceptionTwo = true;
}
assertTrue(caughtExceptionOne && caughtExceptionTwo);
}
@Test
public void testPlayers() {
Player p1 = new Player("Anna", "X");
Player p2 = new Player("Hafsteinn", "O");
Queue<Player> players = new ArrayBlockingQueue<Player>(2);
players.add(p1);
players.add(p2);
Game g = new Game(players);
assertEquals("Anna", g.currentPlayerName());
assertEquals("Anna", g.currentPlayerName());
}
@Test
public void testDoTurn() {
Player p1 = new Player("Anna", "X");
Player p2 = new Player("Hafsteinn", "O");
Queue<Player> players = new ArrayBlockingQueue<Player>(2);
players.add(p1);
players.add(p2);
Game g = new Game(players);
assertEquals("Anna", g.currentPlayerName());
assertEquals(TurnResult.valid, g.doTurn(0)); //Anna
assertEquals("Hafsteinn", g.currentPlayerName());
assertEquals(TurnResult.valid, g.doTurn(1)); //Hafsteinn
assertEquals("Anna", g.currentPlayerName());
assertEquals(TurnResult.invalid, g.doTurn(1)); //Anna
assertEquals("Anna", g.currentPlayerName());
assertEquals(TurnResult.valid, g.doTurn(2)); //Anna
assertEquals("Hafsteinn", g.currentPlayerName());
assertEquals(TurnResult.invalid, g.doTurn(1)); //Hafsteinn
Board b = g.getBoard();
String[] grid = b.getGrid();
assertEquals("X",grid[0]);
assertEquals("O",grid[1]);
assertEquals("X",grid[2]);
}
@Test
public void testDoTurnGameOver() {
Player p1 = new Player("Anna", "X");
Player p2 = new Player("Hafsteinn", "O");
Queue<Player> players = new ArrayBlockingQueue<Player>(2);
players.add(p1);
players.add(p2);
//Test winning with cells on 0 - 1 - 2, test that do turn returns gameOver enum
Game g = new Game(players);
g.doTurn(0); //Anna
g.doTurn(4); //Hafsteinn
g.doTurn(1); //Anna
g.doTurn(5); //Hafsteinn
assertEquals(TurnResult.gameOver, g.doTurn(2)); //Anna Wins
}
@Test
public void testDoTurnGameOverCustomSizeAndWinCondition() {
Player p1 = new Player("Anna", "X");
Player p2 = new Player("Hafsteinn", "O");
Queue<Player> players = new ArrayBlockingQueue<Player>(2);
players.add(p1);
players.add(p2);
//Test winning with cells on 0 - 1 - 2, test that do turn returns gameOver enum
Game g = new Game(players,5,5);
g.setWinCondition(5);
g.doTurn(0); //Anna
g.doTurn(4); //Hafsteinn
g.doTurn(6); //Anna
g.doTurn(9); //Hafsteinn
g.doTurn(12); //Anna
assertFalse(g.isGameOver());
g.doTurn(3); //Hafsteinn
g.doTurn(18); //Anna
assertFalse(g.isGameOver());
g.doTurn(2); //Hafsteinn
assertEquals(TurnResult.gameOver, g.doTurn(24)); //Anna
assertTrue(g.isGameOver()); //Anna Wins
}
@Test
public void testIsGameOver() {
Player p1 = new Player("Anna", "X");
Player p2 = new Player("Hafsteinn", "O");
Queue<Player> players = new ArrayBlockingQueue<Player>(2);
players.add(p1);
players.add(p2);
//Test that if the top horizontal line is all the same symbol, game is over.
Game g = new Game(players);
g.doTurn(0); //Anna
assertFalse(g.isGameOver());
g.doTurn(4); //Hafsteinn
assertFalse(g.isGameOver());
g.doTurn(1); //Anna
assertFalse(g.isGameOver());
g.doTurn(5); //Hafsteinn
assertFalse(g.isGameOver());
g.doTurn(2); //Anna
assertTrue(g.isGameOver());
//Test that if the middle horizontal line is the same symbol, game is over
Game g2 = new Game(players);
g2.doTurn(1); //Anna
assertFalse(g2.isGameOver());
g2.doTurn(3); //Hafsteinn
assertFalse(g2.isGameOver());
g2.doTurn(0); //Anna
assertFalse(g2.isGameOver());
g2.doTurn(5); //Hafsteinn
assertFalse(g2.isGameOver());
g2.doTurn(8); //Anna
assertFalse(g2.isGameOver());
g2.doTurn(4); //Hafsteinn
assertTrue(g2.isGameOver());
//Test that if the middle horizontal line is the same symbol, game is over
Game g3 = new Game(players);
g3.doTurn(1); //Anna
assertFalse(g3.isGameOver());
g3.doTurn(6); //Hafsteinn
assertFalse(g3.isGameOver());
g3.doTurn(0); //Anna
assertFalse(g3.isGameOver());
g3.doTurn(7); //Hafsteinn
assertFalse(g3.isGameOver());
g3.doTurn(5); //Anna
assertFalse(g3.isGameOver());
g3.doTurn(8); //Hafsteinn
assertTrue(g3.isGameOver());
//Test that the left vertical line has the same symbol in all cells, the game is over
Game g4 = new Game(players);
g4.doTurn(0); //Anna
assertFalse(g4.isGameOver());
g4.doTurn(4); //Hafsteinn
assertFalse(g4.isGameOver());
g4.doTurn(3); //Anna
assertFalse(g4.isGameOver());
g4.doTurn(7); //Hafsteinn
assertFalse(g4.isGameOver());
g4.doTurn(6); //Anna
assertTrue(g4.isGameOver());
//Test that the middle vertical line has the same symbol in all cells, the game is over
Game g5 = new Game(players);
g5.doTurn(1); //Anna
assertFalse(g5.isGameOver());
g5.doTurn(0); //Hafsteinn
assertFalse(g5.isGameOver());
g5.doTurn(4); //Anna
assertFalse(g5.isGameOver());
g5.doTurn(2); //Hafsteinn
assertFalse(g5.isGameOver());
g5.doTurn(7); //Anna
assertTrue(g5.isGameOver());
//Test that the right vertical line has the same symbol in all cells, the game is over
Game g6 = new Game(players);
g6.doTurn(1); //Anna
assertFalse(g6.isGameOver());
g6.doTurn(2); //Hafsteinn
assertFalse(g6.isGameOver());
g6.doTurn(0); //Anna
assertFalse(g6.isGameOver());
g6.doTurn(5); //Hafsteinn
assertFalse(g6.isGameOver());
g6.doTurn(7); //Anna
assertFalse(g6.isGameOver());
g6.doTurn(8); //Hafsteinn
assertTrue(g6.isGameOver());
//Test winning with cells 0-4-8
Game g7 = new Game(players);
g7.doTurn(0); //Anna
assertFalse(g7.isGameOver());
g7.doTurn(1); //Hafsteinn
assertFalse(g7.isGameOver());
g7.doTurn(4); //Anna
assertFalse(g7.isGameOver());
g7.doTurn(2); //Hafsteinn
assertFalse(g7.isGameOver());
g7.doTurn(8); //Anna
assertTrue(g7.isGameOver());
//Test winning with cells 2-4-6
Game g8 = new Game(players);
g8.doTurn(2); //Anna
assertFalse(g8.isGameOver());
g8.doTurn(1); //Hafsteinn
assertFalse(g8.isGameOver());
g8.doTurn(4); //Anna
assertFalse(g8.isGameOver());
g8.doTurn(0); //Hafsteinn
assertFalse(g8.isGameOver());
g8.doTurn(6); //Anna
assertTrue(g8.isGameOver());
}
@Test
public void testLastValidMove() {
Player p1 = new Player("Anna", "X");
Player p2 = new Player("Hafsteinn", "O");
Queue<Player> players = new ArrayBlockingQueue<Player>(2);
players.add(p1);
players.add(p2);
//Test winning with cells on 0 - 1 - 2, test that do turn returns gameOver enum
Game g = new Game(players);
g.doTurn(0); //Anna
assertEquals(0, g.getLastValidMove());
g.doTurn(4); //Hafsteinn
assertEquals(4, g.getLastValidMove());
g.doTurn(0); //Anna
assertEquals(4, g.getLastValidMove());
g.doTurn(1); //Anna
assertEquals(1, g.getLastValidMove());
g.doTurn(5); //Hafsteinn
assertEquals(5, g.getLastValidMove());
g.doTurn(2); //Anna
assertEquals(2, g.getLastValidMove());
}
@Test
public void testLastSymbol() {
Player p1 = new Player("Anna", "X");
Player p2 = new Player("Hafsteinn", "O");
Queue<Player> players = new ArrayBlockingQueue<Player>(2);
players.add(p1);
players.add(p2);
//Test winning with cells on 0 - 1 - 2, test that do turn returns gameOver enum
Game g = new Game(players);
g.doTurn(0); //Anna
assertEquals("X", g.getLastSymbol());
g.doTurn(4); //Hafsteinn
assertEquals("O", g.getLastSymbol());
g.doTurn(0); //Anna
assertEquals("O", g.getLastSymbol());
g.doTurn(1); //Anna
assertEquals("X", g.getLastSymbol());
g.doTurn(5); //Hafsteinn
assertEquals("O", g.getLastSymbol());
g.doTurn(2); //Anna
assertEquals("X", g.getLastSymbol());
}
} |
package mho.qbar.objects;
import mho.wheels.io.Readers;
import org.jetbrains.annotations.NotNull;
import org.junit.Test;
import java.util.List;
import static mho.qbar.objects.RationalMatrix.*;
import static mho.wheels.iterables.IterableUtils.toList;
import static mho.wheels.testing.Testing.*;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.fail;
public class RationalMatrixTest {
private static void rows_helper(@NotNull String input, @NotNull String output) {
aeq(toList(readStrict(input).get().rows()), output);
}
@Test
public void testRows() {
rows_helper("[]
rows_helper("[]
rows_helper("[]
rows_helper("[[]]", "[[]]");
rows_helper("[[], [], []]", "[[], [], []]");
rows_helper("[[-2/3]]", "[[-2/3]]");
rows_helper("[[-2/3, -8], [0, 5/7]]", "[[-2/3, -8], [0, 5/7]]");
rows_helper("[[1, 9, -13], [20, 5, -6]]", "[[1, 9, -13], [20, 5, -6]]");
}
private static void columns_helper(@NotNull String input, @NotNull String output) {
aeq(toList(readStrict(input).get().columns()), output);
}
@Test
public void testColumns() {
columns_helper("[]
columns_helper("[]
columns_helper("[]
columns_helper("[[]]", "[]");
columns_helper("[[], [], []]", "[]");
columns_helper("[[-2/3]]", "[[-2/3]]");
columns_helper("[[-2/3, -8], [0, 5/7]]", "[[-2/3, 0], [-8, 5/7]]");
columns_helper("[[1, 9, -13], [20, 5, -6]]", "[[1, 20], [9, 5], [-13, -6]]");
}
private static void row_helper(@NotNull String input, int i, @NotNull String output) {
aeq(readStrict(input).get().row(i), output);
}
private static void row_fail_helper(@NotNull String input, int i) {
try {
readStrict(input).get().row(i);
fail();
} catch (IndexOutOfBoundsException ignored) {}
}
@Test
public void testRow() {
row_helper("[[]]", 0, "[]");
row_helper("[[], [], []]", 0, "[]");
row_helper("[[], [], []]", 2, "[]");
row_helper("[[1, 9, -13], [20, 5, -6]]", 0, "[1, 9, -13]");
row_helper("[[1, 9, -13], [20, 5, -6]]", 1, "[20, 5, -6]");
row_fail_helper("[]#0", 0);
row_fail_helper("[]#3", 0);
row_fail_helper("[[]]", 1);
row_fail_helper("[[1, 9, -13], [20, 5, -6]]", 2);
row_fail_helper("[]#0", -1);
row_fail_helper("[]#1", -1);
row_fail_helper("[[]]", -1);
row_fail_helper("[[1, 9, -13], [20, 5, -6]]", -1);
}
private static void column_helper(@NotNull String input, int j, @NotNull String output) {
aeq(readStrict(input).get().column(j), output);
}
private static void column_fail_helper(@NotNull String input, int j) {
try {
readStrict(input).get().column(j);
fail();
} catch (IndexOutOfBoundsException ignored) {}
}
@Test
public void testColumn() {
column_helper("[]#3", 0, "[]");
column_helper("[]#3", 2, "[]");
column_helper("[[1, 9, -13], [20, 5, -6]]", 0, "[1, 20]");
column_helper("[[1, 9, -13], [20, 5, -6]]", 1, "[9, 5]");
column_helper("[[1, 9, -13], [20, 5, -6]]", 2, "[-13, -6]");
column_fail_helper("[]#0", 0);
column_fail_helper("[[]]", 0);
column_fail_helper("[[], [], []]", 0);
column_fail_helper("[[]]", 1);
column_fail_helper("[[1, 9, -13], [20, 5, -6]]", 3);
column_fail_helper("[]#0", -1);
column_fail_helper("[]#1", -1);
column_fail_helper("[[]]", -1);
column_fail_helper("[[1, 9, -13], [20, 5, -6]]", -1);
}
private static void onlyHasIntegralElements_helper(@NotNull String input, boolean output) {
aeq(readStrict(input).get().onlyHasIntegralElements(), output);
}
@Test
public void testHasIntegralElements() {
onlyHasIntegralElements_helper("[]#0", true);
onlyHasIntegralElements_helper("[]#1", true);
onlyHasIntegralElements_helper("[]#3", true);
onlyHasIntegralElements_helper("[[]]", true);
onlyHasIntegralElements_helper("[[], [], []]", true);
onlyHasIntegralElements_helper("[[-2/3]]", false);
onlyHasIntegralElements_helper("[[-2/3, -8], [0, 5/7]]", false);
onlyHasIntegralElements_helper("[[1, 9, -13], [20, 5, -6]]", true);
}
private static void toMatrix_helper(@NotNull String input) {
aeq(readStrict(input).get().toMatrix(), input);
}
private static void toMatrix_fail_helper(@NotNull String input) {
try {
readStrict(input).get().toMatrix();
fail();
} catch (ArithmeticException ignored) {}
}
@Test
public void testToMatrix() {
toMatrix_helper("[]
toMatrix_helper("[]
toMatrix_helper("[]
toMatrix_helper("[[]]");
toMatrix_helper("[[], [], []]");
toMatrix_helper("[[1, 9, -13], [20, 5, -6]]");
toMatrix_fail_helper("[[-2/3]]");
toMatrix_fail_helper("[[-2/3, -8], [0, 5/7]]");
}
private static void get_helper(@NotNull String input, int i, int j, @NotNull String output) {
aeq(readStrict(input).get().get(i, j), output);
}
private static void get_fail_helper(@NotNull String input, int i, int j) {
try {
readStrict(input).get().get(i, j);
fail();
} catch (IndexOutOfBoundsException ignored) {}
}
@Test
public void testGet() {
get_helper("[[1, 9, -13], [20, 5, -6]]", 0, 0, "1");
get_helper("[[1, 9, -13], [20, 5, -6]]", 0, 2, "-13");
get_helper("[[1, 9, -13], [20, 5, -6]]", 1, 0, "20");
get_helper("[[1, 9, -13], [20, 5, -6]]", 1, 2, "-6");
get_fail_helper("[]#0", 0, 0);
get_fail_helper("[]#1", 0, 0);
get_fail_helper("[[]]", 0, 0);
get_fail_helper("[[1, 9, -13], [20, 5, -6]]", 2, 0);
get_fail_helper("[[1, 9, -13], [20, 5, -6]]", 0, 3);
}
private static void fromRows_helper(@NotNull String input, @NotNull String output) {
aeq(fromRows(readRationalVectorList(input)), output);
}
private static void fromRows_fail_helper(@NotNull String input) {
try {
fromRows(readRationalVectorListWithNulls(input));
} catch (NullPointerException | IllegalArgumentException ignored) {}
}
@Test
public void testFromRows() {
fromRows_helper("[]", "[]
fromRows_helper("[[]]", "[[]]");
fromRows_helper("[[-2/3]]", "[[-2/3]]");
fromRows_helper("[[-2/3, -8], [0, 5/7]]", "[[-2/3, -8], [0, 5/7]]");
fromRows_helper("[[1, 9, -13], [20, 5, -6]]", "[[1, 9, -13], [20, 5, -6]]");
fromRows_fail_helper("[[-2/3, -8], null, [0, 5/7]]");
fromRows_fail_helper("[[-2/3, -8], [0], [0, 5/7]]");
}
private static void fromColumns_helper(@NotNull String input, @NotNull String output) {
aeq(fromColumns(readRationalVectorList(input)), output);
}
private static void fromColumns_fail_helper(@NotNull String input) {
try {
fromColumns(readRationalVectorListWithNulls(input));
} catch (NullPointerException | IllegalArgumentException ignored) {}
}
@Test
public void testFromColumns() {
fromColumns_helper("[]", "[]
fromColumns_helper("[[]]", "[]
fromColumns_helper("[[-2/3]]", "[[-2/3]]");
fromColumns_helper("[[-2/3, -8], [0, 5/7]]", "[[-2/3, 0], [-8, 5/7]]");
fromColumns_helper("[[1, 9, -13], [20, 5, -6]]", "[[1, 20], [9, 5], [-13, -6]]");
fromColumns_fail_helper("[[-2/3, -8], null, [0, 5/7]]");
fromColumns_fail_helper("[[-2/3, -8], [0], [0, 5/7]]");
}
private static void maxElementBitLength_helper(@NotNull String input, int output) {
aeq(readStrict(input).get().maxElementBitLength(), output);
}
@Test
public void testMaxElementBitLength() {
maxElementBitLength_helper("[]#0", 0);
maxElementBitLength_helper("[]#1", 0);
maxElementBitLength_helper("[]#3", 0);
maxElementBitLength_helper("[[]]", 0);
maxElementBitLength_helper("[[], [], []]", 0);
maxElementBitLength_helper("[[-2/3]]", 4);
maxElementBitLength_helper("[[-2/3, -8], [0, 5/7]]", 6);
maxElementBitLength_helper("[[1, 9, -13], [20, 5, -6]]", 6);
}
private static void height_helper(@NotNull String input, int output) {
aeq(readStrict(input).get().height(), output);
}
@Test
public void testHeight() {
height_helper("[]#0", 0);
height_helper("[]#1", 0);
height_helper("[]#3", 0);
height_helper("[[]]", 1);
height_helper("[[], [], []]", 3);
height_helper("[[-2/3]]", 1);
height_helper("[[-2/3, -8], [0, 5/7]]", 2);
height_helper("[[1, 9, -13], [20, 5, -6]]", 2);
}
private static void width_helper(@NotNull String input, int output) {
aeq(readStrict(input).get().width(), output);
}
@Test
public void testWidth() {
width_helper("[]#0", 0);
width_helper("[]#1", 1);
width_helper("[]#3", 3);
width_helper("[[]]", 0);
width_helper("[[], [], []]", 0);
width_helper("[[-2/3]]", 1);
width_helper("[[-2/3, -8], [0, 5/7]]", 2);
width_helper("[[1, 9, -13], [20, 5, -6]]", 3);
}
private static void isSquare_helper(@NotNull String input, boolean output) {
aeq(readStrict(input).get().isSquare(), output);
}
@Test
public void testIsSquare() {
isSquare_helper("[]#0", true);
isSquare_helper("[]#1", false);
isSquare_helper("[]#3", false);
isSquare_helper("[[]]", false);
isSquare_helper("[[], [], []]", false);
isSquare_helper("[[-2/3]]", true);
isSquare_helper("[[0, 0, 0], [0, 0, 1], [0, 0, 0]]", true);
isSquare_helper("[[0, 0, 0], [0, 0, 1]]", false);
isSquare_helper("[[0, 0], [0, 1], [0, 0]]", false);
}
private static void isZero_helper(@NotNull String input, boolean output) {
aeq(readStrict(input).get().isZero(), output);
}
@Test
public void testIsZero() {
isZero_helper("[]#0", true);
isZero_helper("[]#1", true);
isZero_helper("[]#3", true);
isZero_helper("[[]]", true);
isZero_helper("[[0]]", true);
isZero_helper("[[], [], []]", true);
isZero_helper("[[0, 0, 0], [0, 0, 0], [0, 0, 0]]", true);
isZero_helper("[[0, 0, 0], [0, 0, 1], [0, 0, 0]]", false);
isZero_helper("[[-2/3]]", false);
isZero_helper("[[-2/3, -8], [0, 5/7]]", false);
isZero_helper("[[1, 9, -13], [20, 5, -6]]", false);
}
private static void zero_helper(int height, int width, @NotNull String output) {
aeq(zero(height, width), output);
}
private static void zero_fail_helper(int height, int width) {
try {
zero(height, width);
fail();
} catch (IllegalArgumentException ignored) {}
}
@Test
public void testZero() {
zero_helper(0, 0, "[]
zero_helper(0, 3, "[]
zero_helper(3, 0, "[[], [], []]");
zero_helper(1, 1, "[[0]]");
zero_helper(2, 2, "[[0, 0], [0, 0]]");
zero_helper(3, 4, "[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]");
zero_fail_helper(-1, 0);
zero_fail_helper(-1, 3);
zero_fail_helper(0, -1);
zero_fail_helper(3, -1);
zero_fail_helper(-1, -1);
}
private static void isIdentity_helper(@NotNull String input, boolean output) {
aeq(readStrict(input).get().isIdentity(), output);
}
@Test
public void testIsIdentity() {
isIdentity_helper("[]#0", true);
isIdentity_helper("[]#1", false);
isIdentity_helper("[]#3", false);
isIdentity_helper("[[]]", false);
isIdentity_helper("[[], [], []]", false);
isIdentity_helper("[[-2/3]]", false);
isIdentity_helper("[[0]]", false);
isIdentity_helper("[[1]]", true);
isIdentity_helper("[[1], [2]]", false);
isIdentity_helper("[[1, 0], [0, 1]]", true);
isIdentity_helper("[[1, 1/5], [0, 1]]", false);
isIdentity_helper("[[0, 1], [1, 0]]", false);
isIdentity_helper("[[1, 1], [1, 1]]", false);
isIdentity_helper("[[1, 0, 0], [0, 1, 0], [0, 0, 1]]", true);
}
private static void identity_helper(int dimension, @NotNull String output) {
aeq(identity(dimension), output);
}
private static void identity_fail_helper(int dimension) {
try {
identity(dimension);
fail();
} catch (IllegalArgumentException ignored) {}
}
@Test
public void testIdentity() {
identity_helper(0, "[]
identity_helper(1, "[[1]]");
identity_helper(3, "[[1, 0, 0], [0, 1, 0], [0, 0, 1]]");
identity_helper(5, "[[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]]");
identity_fail_helper(-1);
}
private static void trace_helper(@NotNull String input, @NotNull String output) {
aeq(readStrict(input).get().trace(), output);
}
private static void trace_fail_helper(@NotNull String input) {
try {
readStrict(input).get().trace();
fail();
} catch (IllegalArgumentException ignored) {}
}
@Test
public void testTrace() {
trace_helper("[]#0", "0");
trace_helper("[[-2/3]]", "-2/3");
trace_helper("[[-2/3, -8], [0, 5/7]]", "1/21");
trace_fail_helper("[]
trace_fail_helper("[]
trace_fail_helper("[[]]");
trace_fail_helper("[[], [], []]");
trace_fail_helper("[[1, 9, -13], [20, 5, -6]]");
}
private static void submatrix_helper(
@NotNull String m,
@NotNull String rowIndices,
@NotNull String columnIndices,
@NotNull String output
) {
aeq(readStrict(m).get().submatrix(readIntegerList(rowIndices), readIntegerList(columnIndices)), output);
}
private static void submatrix_fail_helper(
@NotNull String m,
@NotNull String rowIndices,
@NotNull String columnIndices
) {
try {
readStrict(m).get()
.submatrix(readIntegerListWithNulls(rowIndices), readIntegerListWithNulls(columnIndices));
fail();
} catch (IllegalArgumentException | NullPointerException ignored) {}
}
@Test
public void testSubmatrix() {
submatrix_helper("[]#0", "[]", "[]", "[]#0");
submatrix_helper("[]#3", "[]", "[]", "[]#0");
submatrix_helper("[]#3", "[]", "[0, 2]", "[]#2");
submatrix_helper("[]#3", "[]", "[0, 1, 2]", "[]#3");
submatrix_helper("[[], [], []]", "[]", "[]", "[]
submatrix_helper("[[], [], []]", "[0, 2]", "[]", "[[], []]");
submatrix_helper("[[], [], []]", "[0, 1, 2]", "[]", "[[], [], []]");
submatrix_helper("[[1, 9, -13], [20, 5, -6]]", "[]", "[]", "[]
submatrix_helper("[[1, 9, -13], [20, 5, -6]]", "[]", "[1, 2]", "[]
submatrix_helper("[[1, 9, -13], [20, 5, -6]]", "[0, 1]", "[]", "[[], []]");
submatrix_helper("[[1, 9, -13], [20, 5, -6]]", "[1]", "[0, 2]", "[[20, -6]]");
submatrix_fail_helper("[[0]]", "[null]", "[]");
submatrix_fail_helper("[[1, 9, -13], [20, 5, -6]]", "[1]", "[0, null]");
submatrix_fail_helper("[[1, 9, -13], [20, 5, -6]]", "[1]", "[2, 0]");
submatrix_fail_helper("[[1, 9, -13], [20, 5, -6]]", "[1]", "[0, 0, 2]");
submatrix_fail_helper("[[1, 9, -13], [20, 5, -6]]", "[1, 0]", "[0, 2]");
submatrix_fail_helper("[[1, 9, -13], [20, 5, -6]]", "[1, 1]", "[0, 2]");
submatrix_fail_helper("[[1, 9, -13], [20, 5, -6]]", "[-1]", "[0, 2]");
submatrix_fail_helper("[[1, 9, -13], [20, 5, -6]]", "[1]", "[-1, 2]");
submatrix_fail_helper("[[1, 9, -13], [20, 5, -6]]", "[2]", "[0, 2]");
submatrix_fail_helper("[[1, 9, -13], [20, 5, -6]]", "[1]", "[0, 3]");
}
private static void transpose_helper(@NotNull String input, @NotNull String output) {
aeq(readStrict(input).get().transpose(), output);
}
@Test
public void testTranspose() {
transpose_helper("[]#0", "[]#0");
transpose_helper("[]
transpose_helper("[]
transpose_helper("[[]]", "[]
transpose_helper("[[], [], []]", "[]
transpose_helper("[[-2/3]]", "[[-2/3]]");
transpose_helper("[[-2/3, -8], [0, 5/7]]", "[[-2/3, 0], [-8, 5/7]]");
transpose_helper("[[1, 9, -13], [20, 5, -6]]", "[[1, 20], [9, 5], [-13, -6]]");
}
private static void concat_helper(@NotNull String a, @NotNull String b, @NotNull String output) {
aeq(readStrict(a).get().concat(readStrict(b).get()), output);
}
private static void concat_fail_helper(@NotNull String a, @NotNull String b) {
try {
readStrict(a).get().concat(readStrict(b).get());
fail();
} catch (IllegalArgumentException ignored) {}
}
@Test
public void testConcat() {
concat_helper("[]#0", "[]#0", "[]#0");
concat_helper("[[]]", "[[], []]", "[[], [], []]");
concat_helper("[[1/2]]", "[[1/3], [1/4]]", "[[1/2], [1/3], [1/4]]");
concat_helper(
"[[1, 3, 2], [2, 0, 1], [5, 2, 2]]",
"[[4, 3, 1]]",
"[[1, 3, 2], [2, 0, 1], [5, 2, 2], [4, 3, 1]]"
);
concat_fail_helper("[]#0", "[]#1");
concat_fail_helper("[]#3", "[]#4");
concat_fail_helper("[[]]", "[[2]]");
concat_fail_helper("[[2]]", "[[]]");
concat_fail_helper("[[1/2]]", "[[1/3, 1/4]]");
}
private static void augment_helper(@NotNull String a, @NotNull String b, @NotNull String output) {
aeq(readStrict(a).get().augment(readStrict(b).get()), output);
}
private static void augment_fail_helper(@NotNull String a, @NotNull String b) {
try {
readStrict(a).get().augment(readStrict(b).get());
fail();
} catch (IllegalArgumentException ignored) {}
}
@Test
public void testAugment() {
augment_helper("[]#0", "[]#0", "[]#0");
augment_helper("[]#3", "[]#4", "[]#7");
augment_helper("[[]]", "[[2]]", "[[2]]");
augment_helper("[[2]]", "[[]]", "[[2]]");
augment_helper("[[1/2]]", "[[1/3, 1/4]]", "[[1/2, 1/3, 1/4]]");
augment_helper(
"[[1, 3, 2], [2, 0, 1], [5, 2, 2]]",
"[[4], [3], [1]]",
"[[1, 3, 2, 4], [2, 0, 1, 3], [5, 2, 2, 1]]"
);
augment_fail_helper("[]
augment_fail_helper("[[]]", "[[], []]");
augment_fail_helper("[[1/2]]", "[[1/3], [1/4]]");
}
private static void add_helper(@NotNull String a, @NotNull String b, @NotNull String output) {
aeq(readStrict(a).get().add(readStrict(b).get()), output);
}
private static void add_fail_helper(@NotNull String a, @NotNull String b) {
try {
readStrict(a).get().add(readStrict(b).get());
fail();
} catch (ArithmeticException ignored) {}
}
@Test
public void testAdd() {
add_helper("[]#0", "[]#0", "[]#0");
add_helper("[]#1", "[]#1", "[]#1");
add_helper("[]#3", "[]#3", "[]#3");
add_helper("[[]]", "[[]]", "[[]]");
add_helper("[[], [], []]", "[[], [], []]", "[[], [], []]");
add_helper("[[2/3]]", "[[4/5]]", "[[22/15]]");
add_helper("[[1, 3], [1, 0], [1, 2]]", "[[0, 0], [7, 5], [2, 1]]", "[[1, 3], [8, 5], [3, 3]]");
add_fail_helper("[]#0", "[]#1");
add_fail_helper("[]
add_fail_helper("[[2/3]]", "[[2/3], [4/5]]");
}
private static void negate_helper(@NotNull String input, @NotNull String output) {
aeq(readStrict(input).get().negate(), output);
}
@Test
public void testNegate() {
negate_helper("[]#0", "[]#0");
negate_helper("[]#1", "[]#1");
negate_helper("[]#3", "[]#3");
negate_helper("[[]]", "[[]]");
negate_helper("[[], [], []]", "[[], [], []]");
negate_helper("[[-2/3]]", "[[2/3]]");
negate_helper("[[-2/3, -8], [0, 5/7]]", "[[2/3, 8], [0, -5/7]]");
negate_helper("[[1, 9, -13], [20, 5, -6]]", "[[-1, -9, 13], [-20, -5, 6]]");
}
private static void subtract_helper(@NotNull String a, @NotNull String b, @NotNull String output) {
aeq(readStrict(a).get().subtract(readStrict(b).get()), output);
}
private static void subtract_fail_helper(@NotNull String a, @NotNull String b) {
try {
readStrict(a).get().subtract(readStrict(b).get());
fail();
} catch (ArithmeticException ignored) {}
}
@Test
public void testSubtract() {
subtract_helper("[]#0", "[]#0", "[]#0");
subtract_helper("[]#1", "[]#1", "[]#1");
subtract_helper("[]#3", "[]#3", "[]#3");
subtract_helper("[[]]", "[[]]", "[[]]");
subtract_helper("[[], [], []]", "[[], [], []]", "[[], [], []]");
subtract_helper("[[2/3]]", "[[4/5]]", "[[-2/15]]");
subtract_helper("[[1, 3], [1, 0], [1, 2]]", "[[0, 0], [7, 5], [2, 1]]", "[[1, 3], [-6, -5], [-1, 1]]");
subtract_fail_helper("[]#0", "[]#1");
subtract_fail_helper("[]
subtract_fail_helper("[[2/3]]", "[[2/3], [4/5]]");
}
private static void multiply_Rational_helper(@NotNull String a, @NotNull String b, @NotNull String output) {
aeq(readStrict(a).get().multiply(Rational.readStrict(b).get()), output);
}
@Test
public void testMultiply_Rational() {
multiply_Rational_helper("[]#0", "0", "[]#0");
multiply_Rational_helper("[]#0", "1", "[]#0");
multiply_Rational_helper("[]#0", "-3/2", "[]#0");
multiply_Rational_helper("[]#3", "0", "[]#3");
multiply_Rational_helper("[]#3", "1", "[]#3");
multiply_Rational_helper("[]#3", "-3/2", "[]#3");
multiply_Rational_helper("[[], [], []]", "0", "[[], [], []]");
multiply_Rational_helper("[[], [], []]", "1", "[[], [], []]");
multiply_Rational_helper("[[], [], []]", "-3/2", "[[], [], []]");
multiply_Rational_helper("[[-2/3]]", "0", "[[0]]");
multiply_Rational_helper("[[-2/3]]", "1", "[[-2/3]]");
multiply_Rational_helper("[[-2/3]]", "-3/2", "[[1]]");
multiply_Rational_helper("[[-2/3, -8], [0, 5/7]]", "0", "[[0, 0], [0, 0]]");
multiply_Rational_helper("[[-2/3, -8], [0, 5/7]]", "1", "[[-2/3, -8], [0, 5/7]]");
multiply_Rational_helper("[[-2/3, -8], [0, 5/7]]", "-3/2", "[[1, 12], [0, -15/14]]");
}
private static void multiply_BigInteger_helper(@NotNull String a, @NotNull String b, @NotNull String output) {
aeq(readStrict(a).get().multiply(Readers.readBigIntegerStrict(b).get()), output);
}
@Test
public void testMultiply_BigInteger() {
multiply_BigInteger_helper("[]#0", "0", "[]#0");
multiply_BigInteger_helper("[]#0", "1", "[]#0");
multiply_BigInteger_helper("[]#0", "5", "[]#0");
multiply_BigInteger_helper("[]#3", "0", "[]#3");
multiply_BigInteger_helper("[]#3", "1", "[]#3");
multiply_BigInteger_helper("[]#3", "5", "[]#3");
multiply_BigInteger_helper("[[], [], []]", "0", "[[], [], []]");
multiply_BigInteger_helper("[[], [], []]", "1", "[[], [], []]");
multiply_BigInteger_helper("[[], [], []]", "5", "[[], [], []]");
multiply_BigInteger_helper("[[-2/3]]", "0", "[[0]]");
multiply_BigInteger_helper("[[-2/3]]", "1", "[[-2/3]]");
multiply_BigInteger_helper("[[-2/3]]", "5", "[[-10/3]]");
multiply_BigInteger_helper("[[-2/3, -8], [0, 5/7]]", "0", "[[0, 0], [0, 0]]");
multiply_BigInteger_helper("[[-2/3, -8], [0, 5/7]]", "1", "[[-2/3, -8], [0, 5/7]]");
multiply_BigInteger_helper("[[-2/3, -8], [0, 5/7]]", "5", "[[-10/3, -40], [0, 25/7]]");
}
private static void multiply_int_helper(@NotNull String a, int b, @NotNull String output) {
aeq(readStrict(a).get().multiply(b), output);
}
@Test
public void testMultiply_int() {
multiply_int_helper("[]#0", 0, "[]#0");
multiply_int_helper("[]#0", 1, "[]#0");
multiply_int_helper("[]#0", 5, "[]#0");
multiply_int_helper("[]#3", 0, "[]#3");
multiply_int_helper("[]#3", 1, "[]#3");
multiply_int_helper("[]#3", 5, "[]#3");
multiply_int_helper("[[], [], []]", 0, "[[], [], []]");
multiply_int_helper("[[], [], []]", 1, "[[], [], []]");
multiply_int_helper("[[], [], []]", 5, "[[], [], []]");
multiply_int_helper("[[-2/3]]", 0, "[[0]]");
multiply_int_helper("[[-2/3]]", 1, "[[-2/3]]");
multiply_int_helper("[[-2/3]]", 5, "[[-10/3]]");
multiply_int_helper("[[-2/3, -8], [0, 5/7]]", 0, "[[0, 0], [0, 0]]");
multiply_int_helper("[[-2/3, -8], [0, 5/7]]", 1, "[[-2/3, -8], [0, 5/7]]");
multiply_int_helper("[[-2/3, -8], [0, 5/7]]", 5, "[[-10/3, -40], [0, 25/7]]");
}
private static void divide_Rational_helper(@NotNull String a, @NotNull String b, @NotNull String output) {
aeq(readStrict(a).get().divide(Rational.readStrict(b).get()), output);
}
private static void divide_Rational_fail_helper(@NotNull String a, @NotNull String b) {
try {
readStrict(a).get().divide(Rational.readStrict(b).get());
fail();
} catch (ArithmeticException ignored) {}
}
@Test
public void testDivide_Rational() {
divide_Rational_helper("[]#0", "1", "[]#0");
divide_Rational_helper("[]#0", "-3/2", "[]#0");
divide_Rational_helper("[]#3", "1", "[]#3");
divide_Rational_helper("[]#3", "-3/2", "[]#3");
divide_Rational_helper("[[], [], []]", "1", "[[], [], []]");
divide_Rational_helper("[[], [], []]", "-3/2", "[[], [], []]");
divide_Rational_helper("[[-2/3]]", "1", "[[-2/3]]");
divide_Rational_helper("[[-2/3]]", "-3/2", "[[4/9]]");
divide_Rational_helper("[[-2/3, -8], [0, 5/7]]", "1", "[[-2/3, -8], [0, 5/7]]");
divide_Rational_helper("[[-2/3, -8], [0, 5/7]]", "-3/2", "[[4/9, 16/3], [0, -10/21]]");
divide_Rational_fail_helper("[]#0", "0");
divide_Rational_fail_helper("[]#3", "0");
divide_Rational_fail_helper("[[], [], []]", "0");
divide_Rational_fail_helper("[[-2/3]]", "0");
divide_Rational_fail_helper("[[-2/3, -8], [0, 5/7]]", "0");
}
private static void divide_BigInteger_helper(@NotNull String a, @NotNull String b, @NotNull String output) {
aeq(readStrict(a).get().divide(Readers.readBigIntegerStrict(b).get()), output);
}
private static void divide_BigInteger_fail_helper(@NotNull String a, @NotNull String b) {
try {
readStrict(a).get().divide(Readers.readBigIntegerStrict(b).get());
fail();
} catch (ArithmeticException ignored) {}
}
@Test
public void testDivide_BigInteger() {
divide_BigInteger_helper("[]#0", "1", "[]#0");
divide_BigInteger_helper("[]#0", "5", "[]#0");
divide_BigInteger_helper("[]#3", "1", "[]#3");
divide_BigInteger_helper("[]#3", "5", "[]#3");
divide_BigInteger_helper("[[], [], []]", "1", "[[], [], []]");
divide_BigInteger_helper("[[], [], []]", "5", "[[], [], []]");
divide_BigInteger_helper("[[-2/3]]", "1", "[[-2/3]]");
divide_BigInteger_helper("[[-2/3]]", "5", "[[-2/15]]");
divide_BigInteger_helper("[[-2/3, -8], [0, 5/7]]", "1", "[[-2/3, -8], [0, 5/7]]");
divide_BigInteger_helper("[[-2/3, -8], [0, 5/7]]", "5", "[[-2/15, -8/5], [0, 1/7]]");
divide_BigInteger_fail_helper("[]#0", "0");
divide_BigInteger_fail_helper("[]#3", "0");
divide_BigInteger_fail_helper("[[], [], []]", "0");
divide_BigInteger_fail_helper("[[-2/3]]", "0");
divide_BigInteger_fail_helper("[[-2/3, -8], [0, 5/7]]", "0");
}
private static void divide_int_helper(@NotNull String a, int b, @NotNull String output) {
aeq(readStrict(a).get().divide(b), output);
}
private static void divide_int_fail_helper(@NotNull String a, int b) {
try {
readStrict(a).get().divide(b);
fail();
} catch (ArithmeticException ignored) {}
}
@Test
public void testDivide_int() {
divide_int_helper("[]#0", 1, "[]#0");
divide_int_helper("[]#0", 5, "[]#0");
divide_int_helper("[]#3", 1, "[]#3");
divide_int_helper("[]#3", 5, "[]#3");
divide_int_helper("[[], [], []]", 1, "[[], [], []]");
divide_int_helper("[[], [], []]", 5, "[[], [], []]");
divide_int_helper("[[-2/3]]", 1, "[[-2/3]]");
divide_int_helper("[[-2/3]]", 5, "[[-2/15]]");
divide_int_helper("[[-2/3, -8], [0, 5/7]]", 1, "[[-2/3, -8], [0, 5/7]]");
divide_int_helper("[[-2/3, -8], [0, 5/7]]", 5, "[[-2/15, -8/5], [0, 1/7]]");
divide_int_fail_helper("[]#0", 0);
divide_int_fail_helper("[]#3", 0);
divide_int_fail_helper("[[], [], []]", 0);
divide_int_fail_helper("[[-2/3]]", 0);
divide_int_fail_helper("[[-2/3, -8], [0, 5/7]]", 0);
}
private static void multiply_RationalVector_helper(@NotNull String a, @NotNull String b, @NotNull String output) {
aeq(readStrict(a).get().multiply(RationalVector.readStrict(b).get()), output);
}
private static void multiply_RationalVector_fail_helper(@NotNull String a, @NotNull String b) {
try {
readStrict(a).get().multiply(RationalVector.readStrict(b).get());
fail();
} catch (ArithmeticException ignored) {}
}
@Test
public void testMultiply_RationalVector() {
multiply_RationalVector_helper("[]
multiply_RationalVector_helper("[]#1", "[4/3]", "[]");
multiply_RationalVector_helper("[]#3", "[4/3, 0, -3]", "[]");
multiply_RationalVector_helper("[[]]", "[]", "[0]");
multiply_RationalVector_helper("[[], [], []]", "[]", "[0, 0, 0]");
multiply_RationalVector_helper("[[5]]", "[-1/3]", "[-5/3]");
multiply_RationalVector_helper("[[0, 0], [0, 0]]", "[3, 2]", "[0, 0]");
multiply_RationalVector_helper("[[1, 0], [0, 1]]", "[3, 2]", "[3, 2]");
multiply_RationalVector_helper("[[1, -1, 2], [0, -3, 1]]", "[2, 1, 0]", "[1, -3]");
multiply_RationalVector_fail_helper("[]#0", "[0]");
multiply_RationalVector_fail_helper("[]#3", "[1, 2]");
multiply_RationalVector_fail_helper("[[1, 0], [0, 1]]", "[1, 2, 3]");
}
private static void multiply_RationalMatrix_helper(@NotNull String a, @NotNull String b, @NotNull String output) {
aeq(readStrict(a).get().multiply(readStrict(b).get()), output);
}
private static void multiply_RationalMatrix_fail_helper(@NotNull String a, @NotNull String b) {
try {
readStrict(a).get().multiply(readStrict(b).get());
fail();
} catch (ArithmeticException ignored) {}
}
@Test
public void testMultiply_RationalMatrix() {
multiply_RationalMatrix_helper("[]#0", "[]#0", "[]#0");
multiply_RationalMatrix_helper("[]#1", "[[2/3, 4]]", "[]#2");
multiply_RationalMatrix_helper("[[], [], []]", "[]#5", "[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]");
multiply_RationalMatrix_helper("[[1], [2], [3], [4]]", "[[]]", "[[], [], [], []]");
multiply_RationalMatrix_helper("[[5/3, 4, 0]]", "[[-2], [1], [3]]", "[[2/3]]");
multiply_RationalMatrix_helper("[[-2/3, -8], [0, 5/7]]", "[[0, 0], [0, 0]]", "[[0, 0], [0, 0]]");
multiply_RationalMatrix_helper("[[-2/3, -8], [0, 5/7]]", "[[1, 0], [0, 1]]", "[[-2/3, -8], [0, 5/7]]");
multiply_RationalMatrix_helper("[[1, 3], [-1, 2]]", "[[3], [4]]", "[[15], [5]]");
multiply_RationalMatrix_helper(
"[[1, 2], [3, 4], [5, 6]]",
"[[1, 2, 3, 4], [5, 6, 7, 8]]",
"[[11, 14, 17, 20], [23, 30, 37, 44], [35, 46, 57, 68]]"
);
multiply_RationalMatrix_fail_helper("[]
multiply_RationalMatrix_fail_helper("[[1, 2, 3, 4], [5, 6, 7, 8]]", "[[1, 2], [3, 4], [5, 6]]");
}
private static void shiftLeft_helper(@NotNull String a, int bits, @NotNull String output) {
aeq(readStrict(a).get().shiftLeft(bits), output);
}
@Test
public void testShiftLeft() {
shiftLeft_helper("[]#0", 0, "[]#0");
shiftLeft_helper("[]#0", 1, "[]#0");
shiftLeft_helper("[]#0", 2, "[]#0");
shiftLeft_helper("[]#0", 3, "[]#0");
shiftLeft_helper("[]#0", 4, "[]#0");
shiftLeft_helper("[]#0", -1, "[]#0");
shiftLeft_helper("[]#0", -2, "[]#0");
shiftLeft_helper("[]#0", -3, "[]#0");
shiftLeft_helper("[]#0", -4, "[]#0");
shiftLeft_helper("[]#3", 0, "[]#3");
shiftLeft_helper("[]#3", 1, "[]#3");
shiftLeft_helper("[]#3", 2, "[]#3");
shiftLeft_helper("[]#3", 3, "[]#3");
shiftLeft_helper("[]#3", 4, "[]#3");
shiftLeft_helper("[]#3", -1, "[]#3");
shiftLeft_helper("[]#3", -2, "[]#3");
shiftLeft_helper("[]#3", -3, "[]#3");
shiftLeft_helper("[]#3", -4, "[]#3");
shiftLeft_helper("[[], [], []]", 0, "[[], [], []]");
shiftLeft_helper("[[], [], []]", 1, "[[], [], []]");
shiftLeft_helper("[[], [], []]", 2, "[[], [], []]");
shiftLeft_helper("[[], [], []]", 3, "[[], [], []]");
shiftLeft_helper("[[], [], []]", 4, "[[], [], []]");
shiftLeft_helper("[[], [], []]", -1, "[[], [], []]");
shiftLeft_helper("[[], [], []]", -2, "[[], [], []]");
shiftLeft_helper("[[], [], []]", -3, "[[], [], []]");
shiftLeft_helper("[[], [], []]", -4, "[[], [], []]");
shiftLeft_helper("[[2/3]]", 0, "[[2/3]]");
shiftLeft_helper("[[2/3]]", 1, "[[4/3]]");
shiftLeft_helper("[[2/3]]", 2, "[[8/3]]");
shiftLeft_helper("[[2/3]]", 3, "[[16/3]]");
shiftLeft_helper("[[2/3]]", 4, "[[32/3]]");
shiftLeft_helper("[[2/3]]", -1, "[[1/3]]");
shiftLeft_helper("[[2/3]]", -2, "[[1/6]]");
shiftLeft_helper("[[2/3]]", -3, "[[1/12]]");
shiftLeft_helper("[[2/3]]", -4, "[[1/24]]");
shiftLeft_helper("[[-2/3, -8], [0, 5/7]]", 0, "[[-2/3, -8], [0, 5/7]]");
shiftLeft_helper("[[-2/3, -8], [0, 5/7]]", 1, "[[-4/3, -16], [0, 10/7]]");
shiftLeft_helper("[[-2/3, -8], [0, 5/7]]", 2, "[[-8/3, -32], [0, 20/7]]");
shiftLeft_helper("[[-2/3, -8], [0, 5/7]]", 3, "[[-16/3, -64], [0, 40/7]]");
shiftLeft_helper("[[-2/3, -8], [0, 5/7]]", 4, "[[-32/3, -128], [0, 80/7]]");
shiftLeft_helper("[[-2/3, -8], [0, 5/7]]", -1, "[[-1/3, -4], [0, 5/14]]");
shiftLeft_helper("[[-2/3, -8], [0, 5/7]]", -2, "[[-1/6, -2], [0, 5/28]]");
shiftLeft_helper("[[-2/3, -8], [0, 5/7]]", -3, "[[-1/12, -1], [0, 5/56]]");
shiftLeft_helper("[[-2/3, -8], [0, 5/7]]", -4, "[[-1/24, -1/2], [0, 5/112]]");
}
private static void shiftRight_helper(@NotNull String a, int bits, @NotNull String output) {
aeq(readStrict(a).get().shiftRight(bits), output);
}
@Test
public void testShiftRight() {
shiftRight_helper("[]#0", 0, "[]#0");
shiftRight_helper("[]#0", 1, "[]#0");
shiftRight_helper("[]#0", 2, "[]#0");
shiftRight_helper("[]#0", 3, "[]#0");
shiftRight_helper("[]#0", 4, "[]#0");
shiftRight_helper("[]#0", -1, "[]#0");
shiftRight_helper("[]#0", -2, "[]#0");
shiftRight_helper("[]#0", -3, "[]#0");
shiftRight_helper("[]#0", -4, "[]#0");
shiftRight_helper("[]#3", 0, "[]#3");
shiftRight_helper("[]#3", 1, "[]#3");
shiftRight_helper("[]#3", 2, "[]#3");
shiftRight_helper("[]#3", 3, "[]#3");
shiftRight_helper("[]#3", 4, "[]#3");
shiftRight_helper("[]#3", -1, "[]#3");
shiftRight_helper("[]#3", -2, "[]#3");
shiftRight_helper("[]#3", -3, "[]#3");
shiftRight_helper("[]#3", -4, "[]#3");
shiftRight_helper("[[], [], []]", 0, "[[], [], []]");
shiftRight_helper("[[], [], []]", 1, "[[], [], []]");
shiftRight_helper("[[], [], []]", 2, "[[], [], []]");
shiftRight_helper("[[], [], []]", 3, "[[], [], []]");
shiftRight_helper("[[], [], []]", 4, "[[], [], []]");
shiftRight_helper("[[], [], []]", -1, "[[], [], []]");
shiftRight_helper("[[], [], []]", -2, "[[], [], []]");
shiftRight_helper("[[], [], []]", -3, "[[], [], []]");
shiftRight_helper("[[], [], []]", -4, "[[], [], []]");
shiftRight_helper("[[2/3]]", 0, "[[2/3]]");
shiftRight_helper("[[2/3]]", 1, "[[1/3]]");
shiftRight_helper("[[2/3]]", 2, "[[1/6]]");
shiftRight_helper("[[2/3]]", 3, "[[1/12]]");
shiftRight_helper("[[2/3]]", 4, "[[1/24]]");
shiftRight_helper("[[2/3]]", -1, "[[4/3]]");
shiftRight_helper("[[2/3]]", -2, "[[8/3]]");
shiftRight_helper("[[2/3]]", -3, "[[16/3]]");
shiftRight_helper("[[2/3]]", -4, "[[32/3]]");
shiftRight_helper("[[-2/3, -8], [0, 5/7]]", 0, "[[-2/3, -8], [0, 5/7]]");
shiftRight_helper("[[-2/3, -8], [0, 5/7]]", 1, "[[-1/3, -4], [0, 5/14]]");
shiftRight_helper("[[-2/3, -8], [0, 5/7]]", 2, "[[-1/6, -2], [0, 5/28]]");
shiftRight_helper("[[-2/3, -8], [0, 5/7]]", 3, "[[-1/12, -1], [0, 5/56]]");
shiftRight_helper("[[-2/3, -8], [0, 5/7]]", 4, "[[-1/24, -1/2], [0, 5/112]]");
shiftRight_helper("[[-2/3, -8], [0, 5/7]]", -1, "[[-4/3, -16], [0, 10/7]]");
shiftRight_helper("[[-2/3, -8], [0, 5/7]]", -2, "[[-8/3, -32], [0, 20/7]]");
shiftRight_helper("[[-2/3, -8], [0, 5/7]]", -3, "[[-16/3, -64], [0, 40/7]]");
shiftRight_helper("[[-2/3, -8], [0, 5/7]]", -4, "[[-32/3, -128], [0, 80/7]]");
}
private static void isInRowEchelonForm_helper(@NotNull String input, boolean output) {
aeq(readStrict(input).get().isInRowEchelonForm(), output);
}
@Test
public void testIsInRowEchelonForm() {
isInRowEchelonForm_helper("[]#0", true);
isInRowEchelonForm_helper("[]#3", true);
isInRowEchelonForm_helper("[[], [], []]", true);
isInRowEchelonForm_helper("[[-2/3]]", false);
isInRowEchelonForm_helper("[[-1]]", false);
isInRowEchelonForm_helper("[[1]]", true);
isInRowEchelonForm_helper("[[-2/3, -8], [0, 5/7]]", false);
isInRowEchelonForm_helper("[[1, 9, -13], [20, 5, -6]]", false);
isInRowEchelonForm_helper("[[1, 9, -13], [0, 1, -6]]", true);
isInRowEchelonForm_helper(
"[[0, -3, -6, 4, 9], [-1, -2, -1, 3, 1], [-2, -3, 0, 3, -1], [1, 4, 5, -9, -7]]",
false
);
isInRowEchelonForm_helper(
"[[1, 2, 1, -3, -1], [0, 1, 2, -4/3, -3], [0, 0, 0, 1, 0], [0, 0, 0, 0, 0]]",
true
);
}
private static void rowEchelonForm_helper(@NotNull String input, @NotNull String output) {
aeq(readStrict(input).get().rowEchelonForm(), output);
}
@Test
public void testRowEchelonForm() {
rowEchelonForm_helper("[]#0", "[]#0");
rowEchelonForm_helper("[]#3", "[]#3");
rowEchelonForm_helper("[[], [], []]", "[[], [], []]");
rowEchelonForm_helper("[[-2/3]]", "[[1]]");
rowEchelonForm_helper("[[-2/3, -8], [0, 5/7]]", "[[1, 12], [0, 1]]");
rowEchelonForm_helper("[[1, 9, -13], [20, 5, -6]]", "[[1, 9, -13], [0, 1, -254/175]]");
rowEchelonForm_helper(
"[[0, -3, -6, 4, 9], [-1, -2, -1, 3, 1], [-2, -3, 0, 3, -1], [1, 4, 5, -9, -7]]",
"[[1, 2, 1, -3, -1], [0, 1, 2, -4/3, -3], [0, 0, 0, 1, 0], [0, 0, 0, 0, 0]]"
);
}
private static void rank_helper(@NotNull String input, int output) {
aeq(readStrict(input).get().rank(), output);
}
@Test
public void testRank() {
rank_helper("[]#0", 0);
rank_helper("[]#1", 0);
rank_helper("[]#3", 0);
rank_helper("[[]]", 0);
rank_helper("[[], [], []]", 0);
rank_helper("[[-2/3]]", 1);
rank_helper("[[-2/3, -8], [0, 5/7]]", 2);
rank_helper("[[1, 9, -13], [20, 5, -6]]", 2);
rank_helper("[[1, 2, 1], [-2, -3, 1], [3, 5, 0]]", 2);
rank_helper("[[1, 1, 0, 2], [-1, -1, 0, -2]]", 1);
rank_helper("[[1, -1], [1, -1], [0, 0], [2, -2]]", 1);
}
private static void isInvertible_helper(@NotNull String input, boolean output) {
aeq(readStrict(input).get().isInvertible(), output);
}
private static void isInvertible_fail_helper(@NotNull String input) {
try {
readStrict(input).get().isInvertible();
fail();
} catch (IllegalArgumentException ignored) {}
}
@Test
public void testIsInvertible() {
isInvertible_helper("[]#0", true);
isInvertible_helper("[[-2/3]]", true);
isInvertible_helper("[[-2/3, -8], [0, 5/7]]", true);
isInvertible_helper("[[1, 2, 1], [-2, -3, 1], [3, 5, 0]]", false);
isInvertible_helper("[[1, 1], [-1, -1]]", false);
isInvertible_fail_helper("[]
isInvertible_fail_helper("[]
isInvertible_fail_helper("[[]]");
isInvertible_fail_helper("[[], [], []]");
isInvertible_fail_helper("[[1, 9, -13], [20, 5, -6]]");
}
private static void isInReducedRowEchelonForm_helper(@NotNull String input, boolean output) {
aeq(readStrict(input).get().isInReducedRowEchelonForm(), output);
}
@Test
public void testIsInReducedRowEchelonForm() {
isInReducedRowEchelonForm_helper("[]#0", true);
isInReducedRowEchelonForm_helper("[]#3", true);
isInReducedRowEchelonForm_helper("[[], [], []]", true);
isInReducedRowEchelonForm_helper("[[-2/3]]", false);
isInReducedRowEchelonForm_helper("[[-1]]", false);
isInReducedRowEchelonForm_helper("[[1]]", true);
isInReducedRowEchelonForm_helper("[[-2/3, -8], [0, 5/7]]", false);
isInReducedRowEchelonForm_helper("[[1, 9, -13], [20, 5, -6]]", false);
isInReducedRowEchelonForm_helper("[[1, 9, -13], [0, 1, -6]]", false);
isInReducedRowEchelonForm_helper("[[1, 0, -13], [0, 1, -6]]", true);
isInReducedRowEchelonForm_helper(
"[[0, -3, -6, 4, 9], [-1, -2, -1, 3, 1], [-2, -3, 0, 3, -1], [1, 4, 5, -9, -7]]",
false
);
isInReducedRowEchelonForm_helper(
"[[1, 2, 1, -3, -1], [0, 1, 2, -4/3, -3], [0, 0, 0, 1, 0], [0, 0, 0, 0, 0]]",
false
);
isInReducedRowEchelonForm_helper(
"[[1, 0, -3, 0, 5], [0, 1, 2, 0, -3], [0, 0, 0, 1, 0], [0, 0, 0, 0, 0]]",
true
);
}
private static void reducedRowEchelonForm_helper(@NotNull String input, @NotNull String output) {
aeq(readStrict(input).get().reducedRowEchelonForm(), output);
}
@Test
public void testReducedRowEchelonForm() {
reducedRowEchelonForm_helper("[]#0", "[]#0");
reducedRowEchelonForm_helper("[]#3", "[]#3");
reducedRowEchelonForm_helper("[[], [], []]", "[[], [], []]");
reducedRowEchelonForm_helper("[[-2/3]]", "[[1]]");
reducedRowEchelonForm_helper("[[-2/3, -8], [0, 5/7]]", "[[1, 0], [0, 1]]");
reducedRowEchelonForm_helper("[[1, 9, -13], [20, 5, -6]]", "[[1, 0, 11/175], [0, 1, -254/175]]");
reducedRowEchelonForm_helper(
"[[0, -3, -6, 4, 9], [-1, -2, -1, 3, 1], [-2, -3, 0, 3, -1], [1, 4, 5, -9, -7]]",
"[[1, 0, -3, 0, 5], [0, 1, 2, 0, -3], [0, 0, 0, 1, 0], [0, 0, 0, 0, 0]]"
);
}
private static void solveLinearSystem_helper(@NotNull String m, @NotNull String v, @NotNull String output) {
aeq(readStrict(m).get().solveLinearSystem(RationalVector.readStrict(v).get()), output);
}
private static void solveLinearSystem_fail_helper(@NotNull String m, @NotNull String v) {
try {
readStrict(m).get().solveLinearSystem(RationalVector.readStrict(v).get());
fail();
} catch (IllegalArgumentException ignored) {}
}
@Test
public void testSolveLinearSystem() {
solveLinearSystem_helper("[]#0", "[]", "Optional[[]]");
solveLinearSystem_helper("[]#3", "[]", "Optional.empty");
solveLinearSystem_helper("[[], [], []]", "[0, 0, 0]", "Optional[[]]");
solveLinearSystem_helper("[[], [], []]", "[0, 3, 0]", "Optional.empty");
solveLinearSystem_helper("[[-2/3]]", "[0]", "Optional[[0]]");
solveLinearSystem_helper("[[-2/3]]", "[-2/3]", "Optional[[1]]");
solveLinearSystem_helper("[[-2/3]]", "[5/7]", "Optional[[-15/14]]");
solveLinearSystem_helper("[[1, 1]]", "[0]", "Optional.empty");
solveLinearSystem_helper("[[1, 1, 1]]", "[0]", "Optional.empty");
solveLinearSystem_helper("[[1, 1, 1]]", "[2]", "Optional.empty");
solveLinearSystem_helper("[[1, 1], [1, -1]]", "[10, 5]", "Optional[[15/2, 5/2]]");
solveLinearSystem_helper("[[1, 1], [1, -1], [2, 2]]", "[10, 5, 20]", "Optional[[15/2, 5/2]]");
solveLinearSystem_helper("[[1, 1], [1, -1], [2, 2]]", "[10, 5, 19]", "Optional.empty");
solveLinearSystem_helper("[[2, 3], [4, 9]]", "[6, 15]", "Optional[[3/2, 1]]");
solveLinearSystem_helper("[[3, 2, -1], [2, -2, 4], [-1, 1/2, -1]]", "[1, -2, 0]", "Optional[[1, -2, -2]]");
solveLinearSystem_fail_helper("[]#0", "[0]");
solveLinearSystem_fail_helper("[[2, 3], [4, 9]]", "[6, 15, 3]");
}
private static void solveLinearSystemPermissive_helper(
@NotNull String m,
@NotNull String v,
@NotNull String output
) {
aeq(readStrict(m).get().solveLinearSystemPermissive(RationalVector.readStrict(v).get()), output);
}
private static void solveLinearSystemPermissive_fail_helper(@NotNull String m, @NotNull String v) {
try {
readStrict(m).get().solveLinearSystemPermissive(RationalVector.readStrict(v).get());
fail();
} catch (IllegalArgumentException ignored) {}
}
@Test
public void testSolveLinearSystemPermissive() {
solveLinearSystemPermissive_helper("[]#0", "[]", "Optional[[]]");
solveLinearSystemPermissive_helper("[]#3", "[]", "Optional[[0, 0, 0]]");
solveLinearSystemPermissive_helper("[[], [], []]", "[0, 0, 0]", "Optional[[]]");
solveLinearSystemPermissive_helper("[[], [], []]", "[0, 3, 0]", "Optional.empty");
solveLinearSystemPermissive_helper("[[-2/3]]", "[0]", "Optional[[0]]");
solveLinearSystemPermissive_helper("[[-2/3]]", "[-2/3]", "Optional[[1]]");
solveLinearSystemPermissive_helper("[[-2/3]]", "[5/7]", "Optional[[-15/14]]");
solveLinearSystemPermissive_helper("[[1, 1]]", "[0]", "Optional[[0, 0]]");
solveLinearSystemPermissive_helper("[[1, 1, 1]]", "[0]", "Optional[[0, 0, 0]]");
solveLinearSystemPermissive_helper("[[1, 1, 1]]", "[2]", "Optional[[2, 0, 0]]");
solveLinearSystemPermissive_helper("[[1, 1], [1, -1]]", "[10, 5]", "Optional[[15/2, 5/2]]");
solveLinearSystemPermissive_helper("[[1, 1], [1, -1], [2, 2]]", "[10, 5, 20]", "Optional[[15/2, 5/2]]");
solveLinearSystemPermissive_helper("[[1, 1], [1, -1], [2, 2]]", "[10, 5, 19]", "Optional.empty");
solveLinearSystemPermissive_helper("[[2, 3], [4, 9]]", "[6, 15]", "Optional[[3/2, 1]]");
solveLinearSystemPermissive_helper("[[3, 2, -1], [2, -2, 4], [-1, 1/2, -1]]", "[1, -2, 0]",
"Optional[[1, -2, -2]]");
solveLinearSystemPermissive_fail_helper("[]#0", "[0]");
solveLinearSystemPermissive_fail_helper("[[2, 3], [4, 9]]", "[6, 15, 3]");
}
private static void invert_helper(@NotNull String input, @NotNull String output) {
aeq(readStrict(input).get().invert(), output);
}
private static void invert_fail_helper(@NotNull String input) {
try {
readStrict(input).get().invert();
fail();
} catch (IllegalArgumentException ignored) {}
}
@Test
public void testInvert() {
invert_helper("[]#0", "Optional[[]#0]");
invert_helper("[[1]]", "Optional[[[1]]]");
invert_helper("[[-1]]", "Optional[[[-1]]]");
invert_helper("[[-2/3]]", "Optional[[[-3/2]]]");
invert_helper("[[1, 0], [0, 1]]", "Optional[[[1, 0], [0, 1]]]");
invert_helper("[[0, 1], [1, 0]]", "Optional[[[0, 1], [1, 0]]]");
invert_helper("[[-2/3, -8], [0, 5/7]]", "Optional[[[-3/2, -84/5], [0, 7/5]]]");
invert_helper("[[1, 3, 3], [1, 4, 3], [1, 3, 4]]", "Optional[[[7, -3, -3], [-1, 1, 0], [-1, 0, 1]]]");
invert_fail_helper("[]
invert_fail_helper("[[], [], []]");
invert_fail_helper("[[1, 9, -13], [20, 5, -6]]");
}
private static void determinant_helper(@NotNull String input, @NotNull String output) {
aeq(readStrict(input).get().determinant(), output);
}
private static void determinant_fail_helper(@NotNull String input) {
try {
readStrict(input).get().determinant();
fail();
} catch (IllegalArgumentException ignored) {}
}
@Test
public void testDeterminant() {
determinant_helper("[]#0", "1");
determinant_helper("[[1]]", "1");
determinant_helper("[[-1]]", "-1");
determinant_helper("[[-2/3]]", "-2/3");
determinant_helper("[[1, 0], [0, 1]]", "1");
determinant_helper("[[0, 1], [1, 0]]", "-1");
determinant_helper("[[-2/3, -8], [0, 5/7]]", "-10/21");
determinant_helper("[[-2, 2, -3], [-1, 1, 3], [2, 0, -1]]", "18");
determinant_fail_helper("[]
determinant_fail_helper("[[], [], []]");
determinant_fail_helper("[[1, 9, -13], [20, 5, -6]]");
}
private static void characteristicPolynomial_helper(@NotNull String input, @NotNull String output) {
aeq(readStrict(input).get().characteristicPolynomial(), output);
}
private static void characteristicPolynomial_fail_helper(@NotNull String input) {
try {
readStrict(input).get().characteristicPolynomial();
fail();
} catch (IllegalArgumentException ignored) {}
}
@Test
public void testCharacteristicPolynomial() {
characteristicPolynomial_helper("[]#0", "1");
characteristicPolynomial_helper("[[1]]", "x-1");
characteristicPolynomial_helper("[[-1]]", "x+1");
characteristicPolynomial_helper("[[-2/3]]", "x+2/3");
characteristicPolynomial_helper("[[1, 0], [0, 1]]", "x^2-2*x+1");
characteristicPolynomial_helper("[[0, 1], [1, 0]]", "x^2-1");
characteristicPolynomial_helper("[[2, 1], [-1, 0]]", "x^2-2*x+1");
characteristicPolynomial_helper("[[-2/3, -8], [0, 5/7]]", "x^2-1/21*x-10/21");
characteristicPolynomial_helper("[[-2, 2, -3], [-1, 1, 3], [2, 0, -1]]", "x^3+2*x^2+7*x-18");
characteristicPolynomial_fail_helper("[]
characteristicPolynomial_fail_helper("[[], [], []]");
characteristicPolynomial_fail_helper("[[1, 9, -13], [20, 5, -6]]");
}
private static void kroneckerMultiply_helper(@NotNull String a, @NotNull String b, @NotNull String output) {
aeq(readStrict(a).get().kroneckerMultiply(readStrict(b).get()), output);
}
@Test
public void testKroneckerMultiply() {
kroneckerMultiply_helper("[]#0", "[]#0", "[]#0");
kroneckerMultiply_helper("[]#0", "[[]]", "[]#0");
kroneckerMultiply_helper("[[]]", "[]#0", "[]#0");
kroneckerMultiply_helper("[]#1", "[[1/2, 4]]", "[]#2");
kroneckerMultiply_helper("[[1/2, 4]]", "[]#1", "[]#2");
kroneckerMultiply_helper("[[], [], []]", "[]#5", "[]#0");
kroneckerMultiply_helper("[]#5", "[[], [], []]", "[]#0");
kroneckerMultiply_helper("[[1], [2/3], [3], [4]]", "[[]]", "[[], [], [], []]");
kroneckerMultiply_helper("[[1, 2, 3/5, 4], [5, 6, 7, 8]]", "[[1, 2], [3, 4], [5, 6]]",
"[[1, 2, 2, 4, 3/5, 6/5, 4, 8], [3, 4, 6, 8, 9/5, 12/5, 12, 16], [5, 6, 10, 12, 3, 18/5, 20, 24]," +
" [5, 10, 6, 12, 7, 14, 8, 16], [15, 20, 18, 24, 21, 28, 24, 32], [25, 30, 30, 36, 35, 42, 40, 48]]");
kroneckerMultiply_helper("[[3, 4, 0]]", "[[-2], [1], [3]]", "[[-6, -8, 0], [3, 4, 0], [9, 12, 0]]");
kroneckerMultiply_helper("[[-3, -8], [0, 1/7]]", "[[0, 0], [0, 0]]",
"[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]");
kroneckerMultiply_helper("[[-3, -8], [0, 1/7]]", "[[1, 0], [0, 1]]",
"[[-3, 0, -8, 0], [0, -3, 0, -8], [0, 0, 1/7, 0], [0, 0, 0, 1/7]]");
}
private static void kroneckerAdd_helper(@NotNull String a, @NotNull String b, @NotNull String output) {
aeq(readStrict(a).get().kroneckerAdd(readStrict(b).get()), output);
}
private static void kroneckerAdd_fail_helper(@NotNull String a, @NotNull String b) {
try {
readStrict(a).get().kroneckerAdd(readStrict(b).get());
fail();
} catch (IllegalArgumentException ignored) {}
}
@Test
public void testKroneckerAdd() {
kroneckerAdd_helper("[]#0", "[]#0", "[]#0");
kroneckerAdd_helper("[]#0", "[[0, 0, 0], [0, 0, 0], [0, 0, 0]]", "[]#0");
kroneckerAdd_helper("[[0, 0, 0], [0, 0, 0], [0, 0, 0]]", "[]#0", "[]#0");
kroneckerAdd_helper("[[1, 2/3], [3, 4]]", "[[-3]]", "[[-2, 2/3], [3, 1]]");
kroneckerAdd_helper("[[1, 2/3], [3, 4]]", "[[7, 4], [2, 0]]",
"[[8, 4, 2/3, 0], [2, 1, 0, 2/3], [3, 0, 11, 4], [0, 3, 2, 4]]");
kroneckerAdd_helper("[[1, 2], [3, 4]]", "[[0, 0], [0, 0]]",
"[[1, 0, 2, 0], [0, 1, 0, 2], [3, 0, 4, 0], [0, 3, 0, 4]]");
kroneckerAdd_helper("[[1, 2], [3, 4]]", "[[1, 0], [0, 1]]",
"[[2, 0, 2, 0], [0, 2, 0, 2], [3, 0, 5, 0], [0, 3, 0, 5]]");
kroneckerAdd_fail_helper("[]
kroneckerAdd_fail_helper("[[], [], []]", "[]
}
private static void realEigenvalues_helper(@NotNull String input, @NotNull String output) {
aeq(readStrict(input).get().realEigenvalues(), output);
}
private static void realEigenvalues_fail_helper(@NotNull String input) {
try {
readStrict(input).get().realEigenvalues();
fail();
} catch (IllegalArgumentException ignored) {}
}
@Test
public void testRealEigenvalues() {
realEigenvalues_helper("[]
realEigenvalues_helper("[[1]]", "[1]");
realEigenvalues_helper("[[-1]]", "[-1]");
realEigenvalues_helper("[[-2/3]]", "[-2/3]");
realEigenvalues_helper("[[1, 0], [0, 1]]", "[1]");
realEigenvalues_helper("[[0, 1], [1, 0]]", "[-1, 1]");
realEigenvalues_helper("[[-2/3, -8], [0, 5/7]]", "[-2/3, 5/7]");
realEigenvalues_helper("[[-2, 2, -3], [-1, 1, 3], [2, 0, -1]]", "[root 0 of x^3+2*x^2+7*x-18]");
realEigenvalues_fail_helper("[]
realEigenvalues_fail_helper("[[], [], []]");
realEigenvalues_fail_helper("[[1, 9, -13], [20, 5, -6]]");
}
@Test
public void testEquals() {
testEqualsHelper(
readRationalMatrixList("[[]#0, []#1, []#3, [[]], [[], [], []], [[-2/3]], [[-2/3, -8], [0, 5/7]]," +
" [[1, 9, -13], [20, 5, -6]]]"),
readRationalMatrixList("[[]#0, []#1, []#3, [[]], [[], [], []], [[-2/3]], [[-2/3, -8], [0, 5/7]]," +
" [[1, 9, -13], [20, 5, -6]]]")
);
}
private static void hashCode_helper(@NotNull String input, int hashCode) {
aeq(readStrict(input).get().hashCode(), hashCode);
}
@Test
public void testHashCode() {
hashCode_helper("[]#0", 31);
hashCode_helper("[]#1", 32);
hashCode_helper("[]#3", 34);
hashCode_helper("[[]]", 992);
hashCode_helper("[[], [], []]", 954304);
hashCode_helper("[[-2/3]]", 94);
hashCode_helper("[[-2/3, -8], [0, 5/7]]", -1005948);
hashCode_helper("[[1, 9, -13], [20, 5, -6]]", 85734688);
}
@Test
public void testCompareTo() {
testCompareToHelper(readRationalMatrixList("[[]#0, []#1, []#3, [[]], [[-2/3]], [[-2/3, -8], [0, 5/7]]," +
" [[1, 9, -13], [20, 5, -6]], [[], [], []]]"));
}
private static void readStrict_helper(@NotNull String input) {
aeq(readStrict(input).get(), input);
}
private static void readStrict_fail_helper(@NotNull String input) {
assertFalse(readStrict(input).isPresent());
}
@Test
public void testReadStrict() {
readStrict_helper("[]
readStrict_helper("[]
readStrict_helper("[]
readStrict_helper("[[]]");
readStrict_helper("[[], [], []]");
readStrict_helper("[[-2/3]]");
readStrict_helper("[[-2/3, -8], [0, 5/7]]");
readStrict_helper("[[1, 9, -13], [20, 5, -6]]");
readStrict_fail_helper("");
readStrict_fail_helper("[]");
readStrict_fail_helper("[]
readStrict_fail_helper("[]
readStrict_fail_helper("[[]]
readStrict_fail_helper("[[4]]
readStrict_fail_helper("[2]");
readStrict_fail_helper("[[ ]]");
readStrict_fail_helper("[[],]");
readStrict_fail_helper("[[1/0]]");
readStrict_fail_helper("[[2/4]]");
readStrict_fail_helper("[[1/3], null]");
readStrict_fail_helper("[[1/3], [2/3, 5/3]]");
readStrict_fail_helper("[[]]]");
readStrict_fail_helper("[[[]]");
readStrict_fail_helper("hello");
readStrict_fail_helper("vdfvfmsl;dfbv");
}
private static @NotNull List<Integer> readIntegerList(@NotNull String s) {
return Readers.readListStrict(Readers::readIntegerStrict).apply(s).get();
}
private static @NotNull List<Integer> readIntegerListWithNulls(@NotNull String s) {
return Readers.readListWithNullsStrict(Readers::readIntegerStrict).apply(s).get();
}
private static @NotNull List<RationalVector> readRationalVectorList(@NotNull String s) {
return Readers.readListStrict(RationalVector::readStrict).apply(s).get();
}
private static @NotNull List<RationalVector> readRationalVectorListWithNulls(@NotNull String s) {
return Readers.readListWithNullsStrict(RationalVector::readStrict).apply(s).get();
}
private static @NotNull List<RationalMatrix> readRationalMatrixList(@NotNull String s) {
return Readers.readListStrict(RationalMatrix::readStrict).apply(s).get();
}
} |
package tlc2.tool.distributed;
import java.io.EOFException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URI;
import java.rmi.RemoteException;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
import tlc2.TLCGlobals;
import tlc2.output.EC;
import tlc2.output.MP;
import tlc2.tool.TLCState;
import tlc2.tool.TLCStateVec;
import tlc2.tool.WorkerException;
import tlc2.tool.distributed.selector.IBlockSelector;
import tlc2.tool.fp.FPSet;
import tlc2.tool.queue.IStateQueue;
import tlc2.tool.queue.StateQueue;
import tlc2.util.BitVector;
import tlc2.util.IdThread;
import tlc2.util.LongVec;
public class TLCServerThread extends IdThread {
private static int COUNT = 0;
/**
* Identifies the worker
*/
private int receivedStates, sentStates;
private double cacheRateRatio;
private final IBlockSelector selector;
private final Timer keepAliveTimer;
/**
* Synchronized flag used to indicate the correct amount of workers to
* TCLGlobals.
*
* Either {@link TLCServerThread#run()} or
* {@link TLCServerThread#keepAliveTimer} will flip to false causing
* subsequent calls to
* {@link TLCServerThread#handleRemoteWorkerLost(StateQueue)} to be a noop.
*
* Synchronization is required because {@link TLCServerThread#run()} and
* {@link TLCTimerTask#run()} are executed as two separate threads.
*/
private final AtomicBoolean cleanupGlobals = new AtomicBoolean(true);
/**
* An {@link ExecutorService} used to parallelize calls to the _distributed_
* fingerprint set servers ({@link FPSet}).
* <p>
* The fingerprint space is partitioned across all {@link FPSet} servers and
* thus can be accessed concurrently.
*/
private ExecutorService executorService;
public TLCServerThread(TLCWorkerRMI worker, TLCServer tlc, ExecutorService es, IBlockSelector aSelector) {
super(COUNT++);
this.executorService = es;
this.setWorker(worker);
this.tlcServer = tlc;
this.selector = aSelector;
// schedule a timer to periodically (60s) check server aliveness
keepAliveTimer = new Timer("TLCWorker KeepAlive Timer ["
+ uri.toASCIIString() + "]", true);
keepAliveTimer.schedule(new TLCTimerTask(), 10000, 60000);
}
private TLCWorkerRMI worker;
private final TLCServer tlcServer;
private URI uri;
private long lastInvocation;
/**
* Current unit of work or null
*/
private TLCState[] states = new TLCState[0];
public final TLCWorkerRMI getWorker() {
return this.worker;
}
public final void setWorker(TLCWorkerRMI worker) {
this.worker = new TLCWorkerSmartProxy(worker);
try {
this.uri = worker.getURI();
} catch (RemoteException e) {
// TODO handle more gracefully
MP.printError(EC.GENERAL, e);
}
// update thread name
final String i = String.format("%03d", myGetId());
setName(TLCServer.THREAD_NAME_PREFIX + i + "-[" + uri.toASCIIString() + "]");
}
/**
* This method gets a state from the queue, generates all the possible next
* states of the state, checks the invariants, and updates the state set and
* state queue.
*/
public void run() {
TLCGlobals.incNumWorkers();
TLCStateVec[] newStates = null;
LongVec[] newFps = null;
final IStateQueue stateQueue = this.tlcServer.stateQueue;
try {
START: while (true) {
// blocks until more states available or all work is done
states = selector.getBlocks(stateQueue, worker);
if (states == null) {
synchronized (this.tlcServer) {
this.tlcServer.setDone();
this.tlcServer.notify();
}
stateQueue.finishAll();
return;
}
// without initial states no need to bother workers
if (states.length == 0) {
continue;
}
// count statistics
sentStates += states.length;
// real work happens here:
// worker computes next states for states
boolean workDone = false;
while (!workDone) {
try {
final Object[] res = this.worker.getNextStates(states);
newStates = (TLCStateVec[]) res[0];
receivedStates += newStates[0].size();
newFps = (LongVec[]) res[1];
workDone = true;
lastInvocation = System.currentTimeMillis();
} catch (RemoteException e) {
// If a (remote) {@link TLCWorkerRMI} fails due to the
// amount of new states we have sent it, try to lower
// the amount of states
// and re-send (until we just send a single state)
if (isRecoverable(e) && states.length > 1) {
MP.printMessage(
EC.TLC_DISTRIBUTED_EXCEED_BLOCKSIZE,
Integer.toString(states.length / 2));
// states[] exceeds maximum transferable size
// (add states back to queue and retry)
stateQueue.sEnqueue(states);
// half the maximum size and use it as a limit from
// now on
selector.setMaxTXSize(states.length / 2);
// go back to beginning
continue START;
} else {
// non recoverable errors, exit...
MP.printMessage(EC.TLC_DISTRIBUTED_WORKER_DEREGISTERED, getUri().toString());
return;
}
} catch (NullPointerException e) {
MP.printMessage(EC.TLC_DISTRIBUTED_WORKER_LOST,
throwableToString(e));
handleRemoteWorkerLost(stateQueue);
return;
}
}
// add fingerprints to fingerprint manager (delegates to
// corresponding fingerprint server)
// (Why isn't this done by workers directly?
// -> because if the worker crashes while computing states, the
// fp set would be inconsistent => making it an "atomic"
// operation)
BitVector[] visited = this.tlcServer.fpSetManager
.putBlock(newFps, executorService);
// recreate newly computed states and add them to queue
for (int i = 0; i < visited.length; i++) {
BitVector.Iter iter = new BitVector.Iter(visited[i]);
int index;
while ((index = iter.next()) != -1) {
TLCState state = newStates[i].elementAt(index);
// write state id and state fp to .st file for
// checkpointing
long fp = newFps[i].elementAt(index);
state.uid = this.tlcServer.trace.writeState(state, fp);
// add state to state queue for further processing
stateQueue.sEnqueue(state);
}
}
cacheRateRatio = this.worker.getCacheRateRatio();
}
} catch (Throwable e) {
TLCState state1 = null, state2 = null;
if (e instanceof WorkerException) {
state1 = ((WorkerException) e).state1;
state2 = ((WorkerException) e).state2;
}
if (this.tlcServer.setErrState(state1, true)) {
MP.printError(EC.GENERAL, e);
if (state1 != null) {
try {
this.tlcServer.trace.printTrace(state1, state2);
} catch (Exception e1) {
MP.printError(EC.GENERAL, e1);
}
}
stateQueue.finishAll();
synchronized (this.tlcServer) {
this.tlcServer.notify();
}
}
} finally {
keepAliveTimer.cancel();
states = new TLCState[0];
// not calling TLCGlobals#decNumWorkers here because at this point
// TLCServer is shutting down anyway
}
}
/**
* A recoverable error/exception is defined to be a case where the
* {@link TLCWorkerRMI} can continue to work if {@link TLCServer} sends less
* new states to process.
*
* @param e
* @return
*/
private boolean isRecoverable(final Exception e) {
final Throwable cause = e.getCause();
return ((cause instanceof EOFException && cause.getMessage() == null) || (cause instanceof RemoteException && cause
.getCause() instanceof OutOfMemoryError));
}
private String throwableToString(final Exception e) {
final Writer result = new StringWriter();
final PrintWriter printWriter = new PrintWriter(result);
e.printStackTrace(printWriter);
return result.toString();
}
/**
* Handles the case of a disconnected remote worker
*
* @param stateQueue
*/
private void handleRemoteWorkerLost(final IStateQueue stateQueue) {
// Cancel the keepAliveTimer which might still be running if an
// exception in the this run() method has caused handleRemoteWorkerLost
// to be called.
keepAliveTimer.cancel();
// De-register TLCServerThread at the main server thread locally
tlcServer.removeTLCServerThread(this);
// Return the undone worklist (if any)
stateQueue.sEnqueue(states != null ? states : new TLCState[0]);
// Reset states to empty array to signal to TLCServer that we are not
// processing any new states. Otherwise statistics will incorrectly
// count this TLCServerThread as actively calculating states.
states = new TLCState[0];
// This call has to be idempotent, otherwise we see bugs as in
if (cleanupGlobals.compareAndSet(true, false)) {
// Before decrementing the worker count, notify all waiters on
// stateQueue to re-evaluate the while loop in isAvail(). The demise
// of this worker (who potentially was the lock owner) might causes
// another consumer to leave the while loop (become a consumer).
// This has to happen _prior_ to calling decNumWorkers. Otherwise
// we decrement the total number and the active count by one
// simultaneously, leaving isAvail without effect.
// This is to work around a design bug in
// tlc2.tool.queue.StateQueue's impl. Other IStateQueue impls should
// hopefully not be affected by calling notifyAll on them though.
synchronized (stateQueue) {
stateQueue.notifyAll();
}
TLCGlobals.decNumWorkers();
}
}
/**
* @return The current amount of states the corresponding worker is
* computing on
*/
public int getCurrentSize() {
return states.length;
}
/**
* @return the url
*/
public URI getUri() {
return this.uri;
}
/**
* @return the receivedStates
*/
public int getReceivedStates() {
return receivedStates;
}
/**
* @return the sentStates
*/
public int getSentStates() {
return sentStates;
}
/**
* @return The worker local cache hit ratio
*/
public double getCacheRateRatio() {
return cacheRateRatio;
}
private class TLCTimerTask extends TimerTask {
/*
* (non-Javadoc)
*
* @see java.util.TimerTask#run()
*/
public void run() {
long now = new Date().getTime();
if (lastInvocation == 0 || (now - lastInvocation) > 60000) {
try {
if (!worker.isAlive()) {
handleRemoteWorkerLost(tlcServer.stateQueue);
}
} catch (RemoteException e) {
handleRemoteWorkerLost(tlcServer.stateQueue);
}
}
}
}
} |
package org.ajabshahar.api;
import org.ajabshahar.core.Songs;
import org.ajabshahar.platform.models.Song;
import org.ajabshahar.platform.resources.SongResource;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import javax.ws.rs.core.Response;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class SongResourceTest {
private static final int SINGER_ID = 1001;
private static final int POET_ID = 2001;
private static final int START_FROM = 1;
private static final String FILTERED_LETTER = "";
private static final int SONG_ID = 101;
private SongResource songResource;
@Mock
private Songs songs;
@Mock
private SongsRepresentationFactory songsRepresentationFactory;
@Mock
private List<Song> songList;
@Mock
private SongsRepresentation songsRepresentation;
@Mock
private Song song;
@Mock
private SongRepresentation songRepresentation;
@Mock
private SongTextRepresentationFactory songTextRepresentationFactory;
@Before
public void setUp() {
songResource = new SongResource(null, songs, songsRepresentationFactory, songTextRepresentationFactory);
}
@Test
public void shouldGetSongsFilteredBySingerAndPoet() {
when(songList.size()).thenReturn(1);
when(songs.findBy(SINGER_ID, POET_ID, START_FROM, FILTERED_LETTER)).thenReturn(songList);
when(songsRepresentationFactory.createSongsRepresentation(songList)).thenReturn(songsRepresentation);
Response response = songResource.getPublishedSongs(SINGER_ID, POET_ID, 1, FILTERED_LETTER);
assertEquals(songsRepresentation, response.getEntity());
assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
}
@Test
public void shouldGet404IfSongsNotFound() {
when(songList.size()).thenReturn(0);
when(songs.findBy(SINGER_ID, POET_ID, START_FROM, FILTERED_LETTER)).thenReturn(songList);
Response response = songResource.getPublishedSongs(SINGER_ID, POET_ID, START_FROM, FILTERED_LETTER);
assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus());
}
@Test
public void shouldGetSongById() {
when(songs.findBy(SONG_ID)).thenReturn(song);
when(songsRepresentationFactory.create(song)).thenReturn(songRepresentation);
Response response = songResource.getPublishedSong(SONG_ID);
assertEquals(songRepresentation, response.getEntity());
assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
}
@Test
public void shouldGet404IfSongNotFound() throws Exception {
when(songs.findBy(SONG_ID)).thenReturn(null);
Response response = songResource.getPublishedSong(SONG_ID);
assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus());
}
@Test
public void shouldUpdateSong() throws Exception {
String jsonSong = "Song";
when(songsRepresentationFactory.create(jsonSong)).thenReturn(song);
Response response = songResource.updateSong(jsonSong);
verify(songs).update(song);
assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
}
@Test
public void shouldGetSongVersions() throws Exception {
SongsRepresentation expectedResult = new SongsRepresentation();
when(songs.getVersions(SONG_ID)).thenReturn(songList);
when(songsRepresentationFactory.createSongsRepresentation(songList)).thenReturn(expectedResult);
Response actualResult = songResource.getSongVersions(SONG_ID);
assertEquals(expectedResult, actualResult.getEntity());
}
@Test
public void shouldSaveSong() throws Exception {
String jsonSong = "Song";
Song song = new Song();
when(songsRepresentationFactory.create(jsonSong)).thenReturn(song);
Response response = songResource.saveSong(jsonSong);
assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
verify(songs).save(song);
}
@Test
public void shouldGetAllSongs() throws Exception {
SongsRepresentation expectedResult = new SongsRepresentation();
when(songs.findAll()).thenReturn(songList);
when(songsRepresentationFactory.createSongsRepresentation(songList)).thenReturn(expectedResult);
Response actualResult = songResource.getSongs();
assertEquals(expectedResult, actualResult.getEntity());
}
} |
package org.basex.test.data;
import static org.junit.Assert.*;
import org.basex.core.BaseXException;
import org.basex.core.Context;
import org.basex.core.Prop;
import org.basex.core.cmd.CreateDB;
import org.basex.core.cmd.DropDB;
import org.basex.core.cmd.XQuery;
import org.basex.util.Util;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public final class FastReplaceTest {
/** Database context. */
public static final Context CONTEXT = new Context();
/** Test document. */
public static final String DOC = "etc/xml/xmark.xml";
/** Test database name. */
public static final String DBNAME = Util.name(FastReplaceTest.class);
/**
* Creates the db based on xmark.xml.
* @throws Exception exception
*/
@Before
public void setUp() throws Exception {
new CreateDB(DBNAME, DOC).execute(CONTEXT);
new XQuery("let $items := /site/regions//item " +
"for $i in 1 to 10 " +
"return (insert node $items into /site/regions, " +
"insert node $items before /site/regions, " +
"insert node $items after /site/closed_auctions)").execute(CONTEXT);
}
/**
* Replaces blocks of equal size distributed over the document.
*/
@Test
public void replaceEqualBlocks() {
try {
new XQuery("for $i in //item/location/text() " +
"return replace node $i with $i").
execute(CONTEXT);
new XQuery("count(//item)").execute(CONTEXT);
} catch(final BaseXException e) {
fail(e.getMessage());
}
}
/**
* Replaces blocks of equal size distributed over the document.
*/
@Test
public void replaceEqualBlocks2() {
try {
new XQuery("for $i in //item return replace node $i with $i").
execute(CONTEXT);
new XQuery("count(//item)").execute(CONTEXT);
} catch(final BaseXException e) {
fail(e.getMessage());
}
}
/**
* Replaces blocks where the new subtree is smaller than the old one. Find
* the smallest //item node in the database and replace each //item with
* this.
*/
@Test
public void replaceWithSmallerTree() {
try {
final String newID =
new XQuery("let $newitem := (let $c := min(for $i in //item " +
"return count($i/descendant-or-self::node())) " +
"return for $i in //item where " +
"(count($i/descendant-or-self::node()) = $c) " +
"return $i)[1] return $newitem/@id/data()").
execute(CONTEXT);
final int itemCount = Integer.parseInt(
new XQuery("count(//item)").execute(CONTEXT));
new XQuery("for $i in //item return replace node $i " +
"with (//item[@id='" + newID + "'])[1]").
execute(CONTEXT);
final int newIDItemCount = Integer.parseInt(
new XQuery("count(//item[@id='" + newID + "'])").execute(CONTEXT));
assertEquals(itemCount, newIDItemCount);
} catch(final BaseXException e) {
fail(e.getMessage());
}
}
/**
* Replaces blocks where the new subtree is bigger than the old one. Find
* the biggest //item node in the database and replace each //item with
* this.
*/
@Test
public void replaceWithBiggerTree() {
try {
new XQuery("let $newitem := (let $c := max(for $i in //item " +
"return count($i/descendant-or-self::node())) " +
"return for $i in //item where " +
"(count($i/descendant-or-self::node()) = $c) " +
"return $i)[1] return for $i in //item " +
"return replace node $i with $newitem").
execute(CONTEXT);
new XQuery("count(//item)").execute(CONTEXT);
} catch(final BaseXException e) {
fail(e.getMessage());
}
}
/**
* Replaces blocks where the new subtree is bigger than the old one. Find
* the biggest //item node in the database and replace the last item in the
* database with this.
*/
@Test
public void replaceSingleWithBiggerTree() {
try {
new XQuery("let $newitem := (let $c := max(for $i in //item " +
"return count($i/descendant-or-self::node())) " +
"return for $i in //item where " +
"(count($i/descendant-or-self::node()) = $c) " +
"return $i)[1] return replace node (//item)[last()] with $newitem").
execute(CONTEXT);
new XQuery("count(//item)").execute(CONTEXT);
} catch(final BaseXException e) {
fail(e.getMessage());
}
}
/**
* Replaces blocks where the new subtree is bigger than the old one. Find
* the biggest //item node in the database and replace the last item in the
* database with this.
*/
@Test
public void replaceSingleWithSmallerTree() {
try {
final String newID =
new XQuery("let $newitem := (let $c := min(for $i in //item " +
"return count($i/descendant-or-self::node())) " +
"return for $i in //item where " +
"(count($i/descendant-or-self::node()) = $c) " +
"return $i)[1] return $newitem/@id/data()").
execute(CONTEXT);
new XQuery("replace node (//item)[last()] with " +
"(//item[@id='" + newID + "'])[1]").
execute(CONTEXT);
new XQuery("count(//item)").execute(CONTEXT);
} catch(final BaseXException e) {
fail(e.getMessage());
}
}
/**
* Replaces a single attribute with two attributes. Checks for correct
* updating of the parent's attribute size.
*/
@Test
public void replaceAttributes() {
try {
new XQuery("replace node (//item)[1]/attribute() with " +
"(attribute att1 {'0'}, attribute att2 {'1'})").
execute(CONTEXT);
final String r = new XQuery("(//item)[1]/attribute()").execute(CONTEXT);
assertEquals(r.trim(), "att1=\"0\" att2=\"1\"");
} catch(final BaseXException e) {
fail(e.getMessage());
}
}
/**
* Replaces a single attribute with two attributes for each item. Checks for
* correct updating of the parent's attribute size.
*/
@Test
public void replaceAttributes2() {
try {
new XQuery("for $i in //item return replace node $i/attribute() with " +
"(attribute att1 {'0'}, attribute att2 {'1'})").
execute(CONTEXT);
new XQuery("//item/attribute()").execute(CONTEXT);
} catch(final BaseXException e) {
fail(e.getMessage());
}
}
/**
* Test setup.
*/
@BeforeClass
public static void start() {
final Prop p = CONTEXT.prop;
p.set(Prop.TEXTINDEX, false);
p.set(Prop.ATTRINDEX, false);
/* Running this junit test in main memory doesn't make that much sense as
* updates in main memory are non persistent - assertions will fail.
Just for debugging purposes. */
// p.set(Prop.MAINMEM, true);
}
/**
* Deletes the test db.
*/
@AfterClass
public static void end() {
try {
new DropDB(DBNAME).execute(CONTEXT);
} catch(final BaseXException e) {
e.printStackTrace();
}
CONTEXT.close();
}
} |
package org.cactoos.text;
import java.io.IOException;
import org.cactoos.TextHasString;
import org.hamcrest.MatcherAssert;
import org.junit.Test;
/**
* Test case for {@link NormalizedText}.
* @author Fabricio Cabral (fabriciofx@gmail.com)
* @version $Id$
* @since 0.4
* @checkstyle JavadocMethodCheck (500 lines)
*/
public final class NormalizedTextTest {
@Test
public void normalizesText() throws IOException {
MatcherAssert.assertThat(
"Can't normalize a text",
new NormalizedText(" \t hello \t\tworld \t"),
new TextHasString("hello world")
);
}
} |
package org.numenta.nupic.network;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.turbo.TurboFilter;
import ch.qos.logback.core.spi.FilterReply;
import ch.qos.logback.core.util.StatusPrinter;
import org.junit.Test;
import org.numenta.nupic.Parameters;
import org.numenta.nupic.Parameters.KEY;
import org.numenta.nupic.SDR;
import org.numenta.nupic.algorithms.Anomaly;
import org.numenta.nupic.algorithms.Anomaly.Mode;
import org.numenta.nupic.algorithms.CLAClassifier;
import org.numenta.nupic.algorithms.SpatialPooler;
import org.numenta.nupic.algorithms.TemporalMemory;
import org.numenta.nupic.datagen.ResourceLocator;
import org.numenta.nupic.encoders.MultiEncoder;
import org.numenta.nupic.network.sensor.FileSensor;
import org.numenta.nupic.network.sensor.HTMSensor;
import org.numenta.nupic.network.sensor.ObservableSensor;
import org.numenta.nupic.network.sensor.Publisher;
import org.numenta.nupic.network.sensor.Sensor;
import org.numenta.nupic.network.sensor.SensorParams;
import org.numenta.nupic.network.sensor.SensorParams.Keys;
import org.numenta.nupic.util.ArrayUtils;
import org.numenta.nupic.util.MersenneTwister;
import org.slf4j.LoggerFactory;
import org.slf4j.Marker;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.functions.Func1;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.numenta.nupic.algorithms.Anomaly.KEY_MODE;
import static org.numenta.nupic.algorithms.Anomaly.KEY_USE_MOVING_AVG;
import static org.numenta.nupic.algorithms.Anomaly.KEY_WINDOW_SIZE;
/**
* Tests the "heart and soul" of the Network API
*
* @author DavidRay
*
*/
public class LayerTest {
/** Total used for spatial pooler priming tests */
private int TOTAL = 0;
@Test
public void testMasking() {
byte algo_content_mask = 0;
// -- Build up mask
algo_content_mask |= Layer.CLA_CLASSIFIER;
assertEquals(4, algo_content_mask);
algo_content_mask |= Layer.SPATIAL_POOLER;
assertEquals(5, algo_content_mask);
algo_content_mask |= Layer.TEMPORAL_MEMORY;
assertEquals(7, algo_content_mask);
algo_content_mask |= Layer.ANOMALY_COMPUTER;
assertEquals(15, algo_content_mask);
// -- Now Peel Off
algo_content_mask ^= Layer.ANOMALY_COMPUTER;
assertEquals(7, algo_content_mask);
assertEquals(0, algo_content_mask & Layer.ANOMALY_COMPUTER);
assertEquals(2, algo_content_mask & Layer.TEMPORAL_MEMORY);
algo_content_mask ^= Layer.TEMPORAL_MEMORY;
assertEquals(5, algo_content_mask);
algo_content_mask ^= Layer.SPATIAL_POOLER;
assertEquals(4, algo_content_mask);
algo_content_mask ^= Layer.CLA_CLASSIFIER;
assertEquals(0, algo_content_mask);
}
@Test
public void testGetAllValues() {
Parameters p = NetworkTestHarness.getParameters().copy();
p = p.union(NetworkTestHarness.getDayDemoTestEncoderParams());
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
MultiEncoder me = MultiEncoder.builder().name("").build();
Layer<Map<String, Object>> l = new Layer<>(p, me, new SpatialPooler(), new TemporalMemory(), Boolean.TRUE, null);
// Test that we get the expected exception if there hasn't been any processing.
try {
l.getAllValues("dayOfWeek", 1);
fail();
}catch(Exception e) {
assertEquals("Predictions not available. Either classifiers unspecified or inferencing has not yet begun.", e.getMessage());
}
l.subscribe(new Observer<Inference>() {
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { System.out.println("error: " + e.getMessage()); e.printStackTrace();}
@Override
public void onNext(Inference i) {
assertNotNull(i);
assertEquals(36, i.getSDR().length);
}
});
// Now push some fake data through so that "onNext" is called above
Map<String, Object> multiInput = new HashMap<>();
multiInput.put("dayOfWeek", 0.0);
l.compute(multiInput);
Object[] values = l.getAllValues("dayOfWeek", 1);
assertNotNull(values);
assertTrue(values.length == 1);
assertEquals(0.0D, values[0]);
}
@Test
public void testResetMethod() {
Parameters p = NetworkTestHarness.getParameters().copy();
Layer<?> l = Network.createLayer("l1", p).add(new TemporalMemory());
try {
l.reset();
assertTrue(l.hasTemporalMemory());
}catch(Exception e) {
fail();
}
Layer<?> l2 = Network.createLayer("l2", p).add(new SpatialPooler());
try {
l2.reset();
assertFalse(l2.hasTemporalMemory());
}catch(Exception e) {
fail();
}
}
@Test
public void testResetRecordNum() {
Parameters p = NetworkTestHarness.getParameters().copy();
@SuppressWarnings("unchecked")
Layer<int[]> l = (Layer<int[]>)Network.createLayer("l1", p).add(new TemporalMemory());
l.subscribe(new Observer<Inference>() {
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { e.printStackTrace(); }
@Override public void onNext(Inference output) {
// System.out.println("output = " + Arrays.toString(output.getSDR()));
}
});
l.compute(new int[] { 2,3,4 });
l.compute(new int[] { 2,3,4 });
assertEquals(1, l.getRecordNum());
l.resetRecordNum();
assertEquals(0, l.getRecordNum());
}
boolean isHalted = false;
@Test
public void testHalt() {
Sensor<File> sensor = Sensor.create(
FileSensor::create,
SensorParams.create(
Keys::path, "", ResourceLocator.path("rec-center-hourly-small.csv")));
Parameters p = NetworkTestHarness.getParameters().copy();
p = p.union(NetworkTestHarness.getHotGymTestEncoderParams());
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
p.setParameterByKey(KEY.AUTO_CLASSIFY, Boolean.TRUE);
HTMSensor<File> htmSensor = (HTMSensor<File>)sensor;
Network n = Network.create("test network", p);
final Layer<int[]> l = new Layer<>(n);
l.add(htmSensor);
l.start();
l.subscribe(new Observer<Inference>() {
@Override public void onCompleted() {
assertTrue(l.isHalted());
isHalted = true;
}
@Override public void onError(Throwable e) { e.printStackTrace(); }
@Override public void onNext(Inference output) {}
});
try {
l.halt();
l.getLayerThread().join();
assertTrue(isHalted);
}catch(Exception e) {
e.printStackTrace();
fail();
}
}
int trueCount = 0;
@Test
public void testReset() {
Sensor<File> sensor = Sensor.create(
FileSensor::create,
SensorParams.create(
Keys::path, "", ResourceLocator.path("rec-center-hourly-4reset.csv")));
Parameters p = NetworkTestHarness.getParameters().copy();
p = p.union(NetworkTestHarness.getHotGymTestEncoderParams());
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
p.setParameterByKey(KEY.AUTO_CLASSIFY, Boolean.TRUE);
HTMSensor<File> htmSensor = (HTMSensor<File>)sensor;
Network n = Network.create("test network", p);
final Layer<int[]> l = new Layer<>(n);
l.add(htmSensor);
l.start();
l.subscribe(new Observer<Inference>() {
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { e.printStackTrace(); }
@Override public void onNext(Inference output) {
if(l.getSensor().getMetaInfo().isReset()) {
trueCount++;
}
}
});
try {
l.getLayerThread().join();
assertEquals(3, trueCount);
}catch(Exception e) {
e.printStackTrace();
fail();
}
}
int seqResetCount = 0;
@Test
public void testSequenceChangeReset() {
Sensor<File> sensor = Sensor.create(
FileSensor::create,
SensorParams.create(
Keys::path, "", ResourceLocator.path("rec-center-hourly-4seqReset.csv")));
Parameters p = NetworkTestHarness.getParameters().copy();
p = p.union(NetworkTestHarness.getHotGymTestEncoderParams());
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
p.setParameterByKey(KEY.AUTO_CLASSIFY, Boolean.TRUE);
HTMSensor<File> htmSensor = (HTMSensor<File>)sensor;
Network n = Network.create("test network", p);
final Layer<int[]> l = new Layer<>(n);
l.add(htmSensor);
l.start();
l.subscribe(new Observer<Inference>() {
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { e.printStackTrace(); }
@Override public void onNext(Inference output) {
if(l.getSensor().getMetaInfo().isReset()) {
seqResetCount++;
}
}
});
try {
l.getLayerThread().join();
assertEquals(3, seqResetCount);
}catch(Exception e) {
e.printStackTrace();
fail();
}
}
@Test
public void testLayerWithObservableInput() {
Publisher manual = Publisher.builder()
.addHeader("timestamp,consumption")
.addHeader("datetime,float")
.addHeader("B")
.build();
Sensor<ObservableSensor<String[]>> sensor = Sensor.create(
ObservableSensor::create,
SensorParams.create(
Keys::obs, new Object[] {"name", manual}));
Parameters p = NetworkTestHarness.getParameters().copy();
p = p.union(NetworkTestHarness.getHotGymTestEncoderParams());
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
p.setParameterByKey(KEY.AUTO_CLASSIFY, Boolean.TRUE);
HTMSensor<ObservableSensor<String[]>> htmSensor = (HTMSensor<ObservableSensor<String[]>>)sensor;
Network n = Network.create("test network", p);
final Layer<int[]> l = new Layer<>(n);
l.add(htmSensor);
l.start();
l.subscribe(new Observer<Inference>() {
int idx = 0;
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { e.printStackTrace(); }
@Override public void onNext(Inference output) {
switch(idx) {
case 0: assertEquals("[0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1]", Arrays.toString(output.getSDR()));
break;
case 1: assertEquals("[0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]", Arrays.toString(output.getSDR()));
break;
case 2: assertEquals("[1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]", Arrays.toString(output.getSDR()));
break;
}
++idx;
}
});
try {
String[] entries = {
"7/2/10 0:00,21.2",
"7/2/10 1:00,34.0",
"7/2/10 2:00,40.4",
};
// Send inputs through the observable
for(String s : entries) {
manual.onNext(s);
}
Thread.sleep(100);
}catch(Exception e) {
e.printStackTrace();
fail();
}
}
@Test
public void testLayerWithObservableInputIntegerArray() {
Publisher manual = Publisher.builder()
.addHeader("sdr_in")
.addHeader("darr")
.addHeader("B")
.build();
Sensor<ObservableSensor<String[]>> sensor = Sensor.create(
ObservableSensor::create,
SensorParams.create(
Keys::obs, new Object[] {"name", manual}));
Parameters p = Parameters.getAllDefaultParameters();
p = p.union(getArrayTestParams());
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
HTMSensor<ObservableSensor<String[]>> htmSensor = (HTMSensor<ObservableSensor<String[]>>)sensor;
Network n = Network.create("test network", p);
final Layer<int[]> l = new Layer<>(n);
l.add(htmSensor);
l.start();
String input = "[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, "
+ "1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, "
+ "0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
+ "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
+ "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
+ "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
+ "1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, "
+ "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, "
+ "1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
+ "0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, "
+ "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, "
+ "1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
+ "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
+ "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
+ "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
+ "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
+ "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
+ "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
+ "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
+ "0, 0, 0, 0, 0, 0, 0, 0, 0, 0]";
l.subscribe(new Observer<Inference>() {
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { e.printStackTrace(); }
@Override public void onNext(Inference output) {
assertEquals(input, Arrays.toString((int[])output.getLayerInput()));
}
});
try {
String[] entries = {
input
};
// Send inputs through the observable
for(String s : entries) {
manual.onNext(s);
manual.onComplete();
}
l.getLayerThread().join();
}catch(Exception e) {
e.printStackTrace();
fail();
}
}
@Test
public void testLayerWithGenericObservable() {
Parameters p = NetworkTestHarness.getParameters().copy();
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
int[][] inputs = new int[7][8];
inputs[0] = new int[] { 1, 1, 0, 0, 0, 0, 0, 1 };
inputs[1] = new int[] { 1, 1, 1, 0, 0, 0, 0, 0 };
inputs[2] = new int[] { 0, 1, 1, 1, 0, 0, 0, 0 };
inputs[3] = new int[] { 0, 0, 1, 1, 1, 0, 0, 0 };
inputs[4] = new int[] { 0, 0, 0, 1, 1, 1, 0, 0 };
inputs[5] = new int[] { 0, 0, 0, 0, 1, 1, 1, 0 };
inputs[6] = new int[] { 0, 0, 0, 0, 0, 1, 1, 1 };
final int[] expected0 = new int[] { 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0 };
final int[] expected1 = new int[] { 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0 };
Func1<ManualInput, ManualInput> addedFunc = l -> {
return l.customObject("Interposed: " + Arrays.toString(l.getSDR()));
};
Network n = Network.create("Generic Test", p)
.add(Network.createRegion("R1")
.add(Network.createLayer("L1", p)
.add(addedFunc)
.add(new SpatialPooler())));
@SuppressWarnings("unchecked")
Layer<int[]> l = (Layer<int[]>)n.lookup("R1").lookup("L1");
l.subscribe(new Observer<Inference>() {
int test = 0;
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { e.printStackTrace(); }
@Override
public void onNext(Inference i) {
if(test == 0) {
assertTrue(Arrays.equals(expected0, i.getSDR()));
assertEquals("Interposed: [0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0]", i.getCustomObject());
}
if(test == 1) {
assertTrue(Arrays.equals(expected1, i.getSDR()));
assertEquals("Interposed: [0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0]", i.getCustomObject());
}
++test;
}
});
// SHOULD RECEIVE BOTH
// Now push some fake data through so that "onNext" is called above
l.compute(inputs[0]);
l.compute(inputs[1]);
}
@Test
public void testBasicSetupEncoder_UsingSubscribe() {
Parameters p = NetworkTestHarness.getParameters().copy();
p = p.union(NetworkTestHarness.getDayDemoTestEncoderParams());
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
MultiEncoder me = MultiEncoder.builder().name("").build();
Layer<Map<String, Object>> l = new Layer<>(p, me, null, null, null, null);
final int[][] expected = new int[7][8];
expected[0] = new int[] { 1, 1, 0, 0, 0, 0, 0, 1 };
expected[1] = new int[] { 1, 1, 1, 0, 0, 0, 0, 0 };
expected[2] = new int[] { 0, 1, 1, 1, 0, 0, 0, 0 };
expected[3] = new int[] { 0, 0, 1, 1, 1, 0, 0, 0 };
expected[4] = new int[] { 0, 0, 0, 1, 1, 1, 0, 0 };
expected[5] = new int[] { 0, 0, 0, 0, 1, 1, 1, 0 };
expected[6] = new int[] { 0, 0, 0, 0, 0, 1, 1, 1 };
l.subscribe(new Observer<Inference>() {
int seq = 0;
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { e.printStackTrace(); }
@Override public void onNext(Inference output) {
assertTrue(Arrays.equals(expected[seq++], output.getSDR()));
}
});
Map<String, Object> inputs = new HashMap<String, Object>();
for(double i = 0;i < 7;i++) {
inputs.put("dayOfWeek", i);
l.compute(inputs);
}
}
@Test
public void testBasicSetupEncoder_UsingObserve() {
Parameters p = NetworkTestHarness.getParameters().copy();
p = p.union(NetworkTestHarness.getDayDemoTestEncoderParams());
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
MultiEncoder me = MultiEncoder.builder().name("").build();
Layer<Map<String, Object>> l = new Layer<>(p, me, null, null, null, null);
final int[][] expected = new int[7][8];
expected[0] = new int[] { 1, 1, 0, 0, 0, 0, 0, 1 };
expected[1] = new int[] { 1, 1, 1, 0, 0, 0, 0, 0 };
expected[2] = new int[] { 0, 1, 1, 1, 0, 0, 0, 0 };
expected[3] = new int[] { 0, 0, 1, 1, 1, 0, 0, 0 };
expected[4] = new int[] { 0, 0, 0, 1, 1, 1, 0, 0 };
expected[5] = new int[] { 0, 0, 0, 0, 1, 1, 1, 0 };
expected[6] = new int[] { 0, 0, 0, 0, 0, 1, 1, 1 };
Observable<Inference> o = l.observe();
o.subscribe(new Observer<Inference>() {
int seq = 0;
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { e.printStackTrace(); }
@Override public void onNext(Inference output) {
assertTrue(Arrays.equals(expected[seq++], output.getSDR()));
}
});
Map<String, Object> inputs = new HashMap<String, Object>();
for(double i = 0;i < 7;i++) {
inputs.put("dayOfWeek", i);
l.compute(inputs);
}
}
@Test
public void testBasicSetupEncoder_AUTO_MODE() {
Sensor<File> sensor = Sensor.create(
FileSensor::create,
SensorParams.create(
Keys::path, "", ResourceLocator.path("rec-center-hourly-small.csv")));
Parameters p = NetworkTestHarness.getParameters().copy();
p = p.union(NetworkTestHarness.getHotGymTestEncoderParams());
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
p.setParameterByKey(KEY.AUTO_CLASSIFY, Boolean.TRUE);
HTMSensor<File> htmSensor = (HTMSensor<File>)sensor;
Network n = Network.create("test network", p);
Layer<int[]> l = new Layer<>(n);
l.add(htmSensor);
final int[][] expected = new int[][] {
{ 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1},
{ 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0}
};
// Test with 2 subscribers //
l.observe().subscribe(new Observer<Inference>() {
int seq = 0;
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { e.printStackTrace(); }
@Override public void onNext(Inference output) {
// System.out.println(" seq = " + seq + ", recNum = " + output.getRecordNum() + ", expected = " + Arrays.toString(expected[seq]));
// System.out.println(" seq = " + seq + ", recNum = " + output.getRecordNum() + ", output = " + Arrays.toString(output.getSDR()));
assertTrue(Arrays.equals(expected[seq], output.getSDR()));
seq++;
}
});
l.observe().subscribe(new Observer<Inference>() {
int seq2 = 0;
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { e.printStackTrace(); }
@Override public void onNext(Inference output) {
// System.out.println(" seq = " + seq2 + ", recNum = " + output.getRecordNum() + ", expected = " + Arrays.toString(expected[seq2]));
// System.out.println(" seq = " + seq2 + ", recNum = " + output.getRecordNum() + ", output = " + Arrays.toString(output.getSDR()));
assertTrue(Arrays.equals(expected[seq2], output.getSDR()));
seq2++;
}
});
l.start();
try {
l.getLayerThread().join();
}catch(Exception e) {
e.printStackTrace();
}
}
/**
* Temporary test to test basic sequence mechanisms
*/
@Test
public void testBasicSetup_SpatialPooler_MANUAL_MODE() {
Parameters p = NetworkTestHarness.getParameters().copy();
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
int[][] inputs = new int[7][8];
inputs[0] = new int[] { 1, 1, 0, 0, 0, 0, 0, 1 };
inputs[1] = new int[] { 1, 1, 1, 0, 0, 0, 0, 0 };
inputs[2] = new int[] { 0, 1, 1, 1, 0, 0, 0, 0 };
inputs[3] = new int[] { 0, 0, 1, 1, 1, 0, 0, 0 };
inputs[4] = new int[] { 0, 0, 0, 1, 1, 1, 0, 0 };
inputs[5] = new int[] { 0, 0, 0, 0, 1, 1, 1, 0 };
inputs[6] = new int[] { 0, 0, 0, 0, 0, 1, 1, 1 };
final int[] expected0 = new int[] { 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0 };
final int[] expected1 = new int[] { 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0 };
Layer<int[]> l = new Layer<>(p, null, new SpatialPooler(), null, null, null);
l.subscribe(new Observer<Inference>() {
int test = 0;
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { e.printStackTrace(); }
@Override
public void onNext(Inference spatialPoolerOutput) {
if(test == 0) {
assertTrue(Arrays.equals(expected0, spatialPoolerOutput.getSDR()));
}
if(test == 1) {
assertTrue(Arrays.equals(expected1, spatialPoolerOutput.getSDR()));
}
++test;
}
});
// Now push some fake data through so that "onNext" is called above
l.compute(inputs[0]);
l.compute(inputs[1]);
}
/**
* Temporary test to test basic sequence mechanisms
*/
@Test
public void testBasicSetup_SpatialPooler_AUTO_MODE() {
Sensor<File> sensor = Sensor.create(
FileSensor::create,
SensorParams.create(
Keys::path, "", ResourceLocator.path("days-of-week.csv")));
Parameters p = NetworkTestHarness.getParameters().copy();
p = p.union(NetworkTestHarness.getDayDemoTestEncoderParams());
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
p.setParameterByKey(KEY.AUTO_CLASSIFY, Boolean.TRUE);
HTMSensor<File> htmSensor = (HTMSensor<File>)sensor;
Network n = Network.create("test network", p);
Layer<int[]> l = new Layer<>(n);
l.add(htmSensor).add(new SpatialPooler());
final int[] expected0 = new int[] { 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0 };
final int[] expected1 = new int[] { 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0 };
l.subscribe(new Observer<Inference>() {
int test = 0;
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { e.printStackTrace(); }
@Override
public void onNext(Inference spatialPoolerOutput) {
if(test == 0) {
assertTrue(Arrays.equals(expected0, spatialPoolerOutput.getSDR()));
}
if(test == 1) {
assertTrue(Arrays.equals(expected1, spatialPoolerOutput.getSDR()));
}
++test;
}
});
l.start();
try {
l.getLayerThread().join();
}catch(Exception e) {
e.printStackTrace();
}
}
/**
* Temporary test to test basic sequence mechanisms
*/
int seq = 0;
@Test
public void testBasicSetup_TemporalMemory_MANUAL_MODE() {
Parameters p = NetworkTestHarness.getParameters().copy();
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
final int[] input1 = new int[] { 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0 };
final int[] input2 = new int[] { 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0 };
final int[] input3 = new int[] { 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
final int[] input4 = new int[] { 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0 };
final int[] input5 = new int[] { 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0 };
final int[] input6 = new int[] { 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1 };
final int[] input7 = new int[] { 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0 };
final int[][] inputs = { input1, input2, input3, input4, input5, input6, input7 };
Layer<int[]> l = new Layer<>(p, null, null, new TemporalMemory(), null, null);
int timeUntilStable = 600;
l.subscribe(new Observer<Inference>() {
int test = 0;
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { e.printStackTrace(); }
@Override
public void onNext(Inference output) {
if(seq / 7 >= timeUntilStable) {
// System.out.println("seq: " + (seq) + " --> " + (test) + " output = " + Arrays.toString(output.getSDR()) +
// ", \t\t\t\t cols = " + Arrays.toString(SDR.asColumnIndices(output.getSDR(), l.getConnections().getCellsPerColumn())));
assertTrue(output.getSDR().length >= 8);
}
if(test == 6) test = 0;
else test++;
}
});
// Now push some warm up data through so that "onNext" is called above
for(int j = 0;j < timeUntilStable;j++) {
for(int i = 0;i < inputs.length;i++) {
l.compute(inputs[i]);
}
}
for(int j = 0;j < 2;j++) {
for(int i = 0;i < inputs.length;i++) {
l.compute(inputs[i]);
}
}
}
@Test
public void testBasicSetup_SPandTM() {
Parameters p = NetworkTestHarness.getParameters().copy();
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
int[][] inputs = new int[7][8];
inputs[0] = new int[] { 1, 1, 0, 0, 0, 0, 0, 1 };
inputs[1] = new int[] { 1, 1, 1, 0, 0, 0, 0, 0 };
inputs[2] = new int[] { 0, 1, 1, 1, 0, 0, 0, 0 };
inputs[3] = new int[] { 0, 0, 1, 1, 1, 0, 0, 0 };
inputs[4] = new int[] { 0, 0, 0, 1, 1, 1, 0, 0 };
inputs[5] = new int[] { 0, 0, 0, 0, 1, 1, 1, 0 };
inputs[6] = new int[] { 0, 0, 0, 0, 0, 1, 1, 1 };
Layer<int[]> l = new Layer<>(p, null, new SpatialPooler(), new TemporalMemory(), null, null);
l.subscribe(new Observer<Inference>() {
@Override public void onCompleted() {}
@Override public void onError(Throwable e) {}
@Override
public void onNext(Inference i) {
assertNotNull(i);
assertEquals(0, i.getSDR().length);
}
});
// Now push some fake data through so that "onNext" is called above
l.compute(inputs[0]);
l.compute(inputs[1]);
}
@Test
public void testSpatialPoolerPrimerDelay() {
Parameters p = NetworkTestHarness.getParameters().copy();
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
int[][] inputs = new int[7][8];
inputs[0] = new int[] { 1, 1, 0, 0, 0, 0, 0, 1 };
inputs[1] = new int[] { 1, 1, 1, 0, 0, 0, 0, 0 };
inputs[2] = new int[] { 0, 1, 1, 1, 0, 0, 0, 0 };
inputs[3] = new int[] { 0, 0, 1, 1, 1, 0, 0, 0 };
inputs[4] = new int[] { 0, 0, 0, 1, 1, 1, 0, 0 };
inputs[5] = new int[] { 0, 0, 0, 0, 1, 1, 1, 0 };
inputs[6] = new int[] { 0, 0, 0, 0, 0, 1, 1, 1 };
final int[] expected0 = new int[] { 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0 };
final int[] expected1 = new int[] { 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0 };
// First test without prime directive :-P
Layer<int[]> l = new Layer<>(p, null, new SpatialPooler(), null, null, null);
l.subscribe(new Observer<Inference>() {
int test = 0;
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { e.printStackTrace(); }
@Override
public void onNext(Inference i) {
if(test == 0) {
assertTrue(Arrays.equals(expected0, i.getSDR()));
}
if(test == 1) {
assertTrue(Arrays.equals(expected1, i.getSDR()));
}
++test;
}
});
// SHOULD RECEIVE BOTH
// Now push some fake data through so that "onNext" is called above
l.compute(inputs[0]);
l.compute(inputs[1]);
// NOW TEST WITH prime directive
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42)); // due to static RNG we have to reset the sequence
p.setParameterByKey(KEY.SP_PRIMER_DELAY, 1);
Layer<int[]> l2 = new Layer<>(p, null, new SpatialPooler(), null, null, null);
l2.subscribe(new Observer<Inference>() {
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { e.printStackTrace(); }
@Override
public void onNext(Inference i) {
// should be one and only onNext() called
assertTrue(Arrays.equals(expected1, i.getSDR()));
}
});
// SHOULD RECEIVE BOTH
// Now push some fake data through so that "onNext" is called above
l2.compute(inputs[0]);
l2.compute(inputs[1]);
}
/**
* Simple test to verify data gets passed through the {@link CLAClassifier}
* configured within the chain of components.
*/
@Test
public void testBasicClassifierSetup() {
Parameters p = NetworkTestHarness.getParameters().copy();
p = p.union(NetworkTestHarness.getDayDemoTestEncoderParams());
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
MultiEncoder me = MultiEncoder.builder().name("").build();
Layer<Map<String, Object>> l = new Layer<>(p, me, new SpatialPooler(), new TemporalMemory(), Boolean.TRUE, null);
l.subscribe(new Observer<Inference>() {
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { System.out.println("error: " + e.getMessage()); e.printStackTrace();}
@Override
public void onNext(Inference i) {
assertNotNull(i);
assertEquals(36, i.getSDR().length);
}
});
// Now push some fake data through so that "onNext" is called above
Map<String, Object> multiInput = new HashMap<>();
multiInput.put("dayOfWeek", 0.0);
l.compute(multiInput);
}
/**
* The {@link SpatialPooler} sometimes needs to have data run through it
* prior to passing the data on to subsequent algorithmic components. This
* tests the ability to specify exactly the number of input records for
* the SpatialPooler to consume before passing records on.
*/
@Test
public void testMoreComplexSpatialPoolerPriming() {
final int PRIME_COUNT = 35;
final int NUM_CYCLES = 20;
final int INPUT_GROUP_COUNT = 7; // Days of Week
TOTAL = 0;
Parameters p = NetworkTestHarness.getParameters().copy();
p = p.union(NetworkTestHarness.getDayDemoTestEncoderParams());
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
p.setParameterByKey(KEY.SP_PRIMER_DELAY, PRIME_COUNT);
MultiEncoder me = MultiEncoder.builder().name("").build();
Layer<Map<String, Object>> l = new Layer<>(p, me, new SpatialPooler(), new TemporalMemory(), Boolean.TRUE, null);
l.subscribe(new Observer<Inference>() {
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { System.out.println("error: " + e.getMessage()); e.printStackTrace();}
@Override
public void onNext(Inference i) {
assertNotNull(i);
TOTAL++;
}
});
// Now push some fake data through so that "onNext" is called above
Map<String, Object> multiInput = new HashMap<>();
for(int i = 0;i < NUM_CYCLES;i++) {
for(double j = 0;j < INPUT_GROUP_COUNT;j++) {
multiInput.put("dayOfWeek", j);
l.compute(multiInput);
}
}
// Assert we can accurately specify how many inputs to "prime" the spatial pooler
// and subtract that from the total input to get the total entries sent through
// the event chain from bottom to top.
assertEquals((NUM_CYCLES * INPUT_GROUP_COUNT) - PRIME_COUNT, TOTAL);
}
/**
* Tests the ability for multiple subscribers to receive copies of
* a given {@link Layer}'s computed values.
*/
@Test
public void test2ndAndSubsequentSubscribersPossible() {
final int PRIME_COUNT = 35;
final int NUM_CYCLES = 50;
final int INPUT_GROUP_COUNT = 7; // Days of Week
TOTAL = 0;
Parameters p = NetworkTestHarness.getParameters().copy();
p = p.union(NetworkTestHarness.getDayDemoTestEncoderParams());
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
p.setParameterByKey(KEY.SP_PRIMER_DELAY, PRIME_COUNT);
MultiEncoder me = MultiEncoder.builder().name("").build();
Layer<Map<String, Object>> l = new Layer<>(p, me, new SpatialPooler(), new TemporalMemory(), Boolean.TRUE, null);
int[][] inputs = new int[7][8];
inputs[0] = new int[] { 1, 1, 0, 0, 0, 0, 0, 1 };
inputs[1] = new int[] { 1, 1, 1, 0, 0, 0, 0, 0 };
inputs[2] = new int[] { 0, 1, 1, 1, 0, 0, 0, 0 };
inputs[3] = new int[] { 0, 0, 1, 1, 1, 0, 0, 0 };
inputs[4] = new int[] { 0, 0, 0, 1, 1, 1, 0, 0 };
inputs[5] = new int[] { 0, 0, 0, 0, 1, 1, 1, 0 };
inputs[6] = new int[] { 0, 0, 0, 0, 0, 1, 1, 1 };
l.subscribe(new Observer<Inference>() {
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { System.out.println("error: " + e.getMessage()); e.printStackTrace();}
@Override
public void onNext(Inference i) {
assertNotNull(i);
TOTAL++;
}
});
l.subscribe(new Observer<Inference>() {
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { System.out.println("error: " + e.getMessage()); e.printStackTrace();}
@Override
public void onNext(Inference i) {
assertNotNull(i);
TOTAL++;
}
});
l.subscribe(new Observer<Inference>() {
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { System.out.println("error: " + e.getMessage()); e.printStackTrace();}
@Override
public void onNext(Inference i) {
assertNotNull(i);
TOTAL++;
}
});
// Now push some fake data through so that "onNext" is called above
Map<String, Object> multiInput = new HashMap<>();
for(int i = 0;i < NUM_CYCLES;i++) {
for(double j = 0;j < INPUT_GROUP_COUNT;j++) {
multiInput.put("dayOfWeek", j);
l.compute(multiInput);
}
}
int NUM_SUBSCRIBERS = 3;
// Assert we can accurately specify how many inputs to "prime" the spatial pooler
// and subtract that from the total input to get the total entries sent through
// the event chain from bottom to top.
assertEquals( ((NUM_CYCLES * INPUT_GROUP_COUNT) - PRIME_COUNT) * NUM_SUBSCRIBERS, TOTAL);
}
@Test
public void testGetAllPredictions() {
final int PRIME_COUNT = 35;
final int NUM_CYCLES = 120;
final int INPUT_GROUP_COUNT = 7; // Days of Week
TOTAL = 0;
Parameters p = NetworkTestHarness.getParameters().copy();
p = p.union(NetworkTestHarness.getDayDemoTestEncoderParams());
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
p.setParameterByKey(KEY.SP_PRIMER_DELAY, PRIME_COUNT);
final int cellsPerColumn = (int)p.getParameterByKey(KEY.CELLS_PER_COLUMN);
assertTrue(cellsPerColumn > 0);
MultiEncoder me = MultiEncoder.builder().name("").build();
final Layer<Map<String, Object>> l = new Layer<>(p, me, new SpatialPooler(), new TemporalMemory(), Boolean.TRUE, null);
l.subscribe(new Observer<Inference>() {
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { System.out.println("error: " + e.getMessage()); e.printStackTrace();}
@Override
public void onNext(Inference i) {
assertNotNull(i);
TOTAL++;
if(l.getPreviousPredictiveCells() != null) {
//UNCOMMENT TO VIEW STABILIZATION OF PREDICTED FIELDS
// System.out.println("recordNum: " + i.getRecordNum() + " Day: " + ((Map<String, Object>)i.getLayerInput()).get("dayOfWeek") + " - " +
// Arrays.toString(ArrayUtils.where(l.getFeedForwardActiveColumns(), ArrayUtils.WHERE_1)) +
// " - " + Arrays.toString(SDR.cellsAsColumnIndices(l.getPreviousPredictiveCells(), cellsPerColumn)));
}
}
});
// Now push some fake data through so that "onNext" is called above
Map<String, Object> multiInput = new HashMap<>();
for(int i = 0;i < NUM_CYCLES;i++) {
for(double j = 0;j < INPUT_GROUP_COUNT;j++) {
multiInput.put("dayOfWeek", j);
l.compute(multiInput);
}
l.reset();
}
// Assert we can accurately specify how many inputs to "prime" the spatial pooler
// and subtract that from the total input to get the total entries sent through
// the event chain from bottom to top.
assertEquals((NUM_CYCLES * INPUT_GROUP_COUNT) - PRIME_COUNT, TOTAL);
double[] all = l.getAllPredictions("dayOfWeek", 1);
double highestVal = Double.NEGATIVE_INFINITY;
int highestIdx = -1;
int i = 0;
for(double d : all) {
if(d > highestVal) {
highestIdx = i;
highestVal = d;
}
i++;
}
assertEquals(highestIdx, l.getMostProbableBucketIndex("dayOfWeek", 1));
assertEquals(7, l.getAllPredictions("dayOfWeek", 1).length);
assertTrue(Arrays.equals(
ArrayUtils.where(l.getFeedForwardActiveColumns(), ArrayUtils.WHERE_1),
SDR.cellsAsColumnIndices(l.getPreviousPredictiveCells(), cellsPerColumn)));
}
/**
* Test that a given layer can return an {@link Observable} capable of
* service multiple subscribers.
*/
@Test
public void testObservableRetrieval() {
Parameters p = NetworkTestHarness.getParameters().copy();
p = p.union(NetworkTestHarness.getDayDemoTestEncoderParams());
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
MultiEncoder me = MultiEncoder.builder().name("").build();
final Layer<Map<String, Object>> l = new Layer<>(p, me, new SpatialPooler(), new TemporalMemory(), Boolean.TRUE, null);
final List<int[]> emissions = new ArrayList<int[]>();
Observable<Inference> o = l.observe();
o.subscribe(new Subscriber<Inference>() {
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { System.out.println("error: " + e.getMessage()); e.printStackTrace();}
@Override public void onNext(Inference i) {
emissions.add(l.getFeedForwardActiveColumns());
}
});
o.subscribe(new Subscriber<Inference>() {
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { System.out.println("error: " + e.getMessage()); e.printStackTrace();}
@Override public void onNext(Inference i) {
emissions.add(l.getFeedForwardActiveColumns());
}
});
o.subscribe(new Subscriber<Inference>() {
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { System.out.println("error: " + e.getMessage()); e.printStackTrace();}
@Override public void onNext(Inference i) {
emissions.add(l.getFeedForwardActiveColumns());
}
});
Map<String, Object> multiInput = new HashMap<>();
multiInput.put("dayOfWeek", 0.0);
l.compute(multiInput);
assertEquals(3, emissions.size());
int[] e1 = emissions.get(0);
for(int[] ia : emissions) {
assertTrue(ia == e1);//test same object propagated
}
}
/**
* Simple test to verify data gets passed through the {@link CLAClassifier}
* configured within the chain of components.
*/
boolean flowReceived = false;
@Test
public void testFullLayerFluentAssembly() {
Parameters p = NetworkTestHarness.getParameters().copy();
p = p.union(NetworkTestHarness.getHotGymTestEncoderParams());
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
p.setParameterByKey(KEY.COLUMN_DIMENSIONS, new int[] { 2048 });
p.setParameterByKey(KEY.POTENTIAL_RADIUS, 200);
p.setParameterByKey(KEY.INHIBITION_RADIUS, 50);
p.setParameterByKey(KEY.GLOBAL_INHIBITION, true);
// System.out.println(p);
Map<String, Object> params = new HashMap<>();
params.put(KEY_MODE, Mode.PURE);
params.put(KEY_WINDOW_SIZE, 3);
params.put(KEY_USE_MOVING_AVG, true);
Anomaly anomalyComputer = Anomaly.create(params);
Layer<?> l = Network.createLayer("TestLayer", p)
.alterParameter(KEY.AUTO_CLASSIFY, true)
.add(anomalyComputer)
.add(new TemporalMemory())
.add(new SpatialPooler())
.add(Sensor.create(
FileSensor::create,
SensorParams.create(
Keys::path, "", ResourceLocator.path("rec-center-hourly-small.csv"))));
l.getConnections().printParameters();
l.subscribe(new Observer<Inference>() {
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { System.out.println("error: " + e.getMessage()); e.printStackTrace();}
@Override
public void onNext(Inference i) {
if(flowReceived) return; // No need to set this value multiple times
flowReceived = i.getClassifiers().size() == 4 &&
i.getClassifiers().get("timestamp") != null &&
i.getClassifiers().get("consumption") != null;
}
});
l.start();
try {
l.getLayerThread().join();
assertTrue(flowReceived);
}catch(Exception e) {
e.printStackTrace();
}
}
@Test
public void testMissingEncoderMap() {
Parameters p = NetworkTestHarness.getParameters().copy();
//p = p.union(NetworkTestHarness.getHotGymTestEncoderParams());
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
p.setParameterByKey(KEY.COLUMN_DIMENSIONS, new int[] { 2048 });
p.setParameterByKey(KEY.POTENTIAL_RADIUS, 200);
p.setParameterByKey(KEY.INHIBITION_RADIUS, 50);
p.setParameterByKey(KEY.GLOBAL_INHIBITION, true);
// System.out.println(p);
Map<String, Object> params = new HashMap<>();
params.put(KEY_MODE, Mode.PURE);
params.put(KEY_WINDOW_SIZE, 3);
params.put(KEY_USE_MOVING_AVG, true);
Anomaly anomalyComputer = Anomaly.create(params);
Layer<?> l = Network.createLayer("TestLayer", p)
.alterParameter(KEY.AUTO_CLASSIFY, true)
.add(anomalyComputer)
.add(new TemporalMemory())
.add(new SpatialPooler())
.add(Sensor.create(
FileSensor::create,
SensorParams.create(
Keys::path, "", ResourceLocator.path("rec-center-hourly-small.csv"))));
l.getConnections().printParameters();
l.subscribe(new Observer<Inference>() {
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { System.out.println("error: " + e.getMessage()); e.printStackTrace();}
@Override
public void onNext(Inference i) {
if(flowReceived) return; // No need to set this value multiple times
flowReceived = i.getClassifiers().size() == 4 &&
i.getClassifiers().get("timestamp") != null &&
i.getClassifiers().get("consumption") != null;
}
});
try {
l.close();
fail();
}catch(Exception e) {
assertEquals("Cannot initialize this Sensor's MultiEncoder with a null settings", e.getMessage());
}
try {
assertFalse(flowReceived);
}catch(Exception e) {
e.printStackTrace();
}
////////////////// Test catch with no Sensor ////////////////////
p = NetworkTestHarness.getParameters().copy();
//p = p.union(NetworkTestHarness.getHotGymTestEncoderParams());
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
p.setParameterByKey(KEY.COLUMN_DIMENSIONS, new int[] { 2048 });
p.setParameterByKey(KEY.POTENTIAL_RADIUS, 200);
p.setParameterByKey(KEY.INHIBITION_RADIUS, 50);
p.setParameterByKey(KEY.GLOBAL_INHIBITION, true);
params = new HashMap<>();
params.put(KEY_MODE, Mode.PURE);
params.put(KEY_WINDOW_SIZE, 3);
params.put(KEY_USE_MOVING_AVG, true);
anomalyComputer = Anomaly.create(params);
l = Network.createLayer("TestLayer", p)
.alterParameter(KEY.AUTO_CLASSIFY, true)
.add(anomalyComputer)
.add(new TemporalMemory())
.add(new SpatialPooler())
.add(anomalyComputer)
.add(MultiEncoder.builder().name("").build());
l.getConnections().printParameters();
l.subscribe(new Observer<Inference>() {
@Override public void onCompleted() {}
@Override public void onError(Throwable e) { System.out.println("error: " + e.getMessage()); e.printStackTrace();}
@Override
public void onNext(Inference i) {
if(flowReceived) return; // No need to set this value multiple times
flowReceived = i.getClassifiers().size() == 4 &&
i.getClassifiers().get("timestamp") != null &&
i.getClassifiers().get("consumption") != null;
}
});
try {
l.close();
fail();
}catch(Exception e) {
assertEquals("No field encoding map found for specified MultiEncoder", e.getMessage());
}
try {
assertFalse(flowReceived);
}catch(Exception e) {
e.printStackTrace();
}
}
private Parameters getArrayTestParams() {
Map<String, Map<String, Object>> fieldEncodings = setupMap(
null,
884,
0,
0, 0, 0, 0, null, null, null,
"sdr_in", "darr", "SDRPassThroughEncoder");
Parameters p = Parameters.empty();
p.setParameterByKey(KEY.FIELD_ENCODING_MAP, fieldEncodings);
return p;
}
private Map<String, Map<String, Object>> setupMap(
Map<String, Map<String, Object>> map,
int n, int w, double min, double max, double radius, double resolution, Boolean periodic,
Boolean clip, Boolean forced, String fieldName, String fieldType, String encoderType) {
if(map == null) {
map = new HashMap<String, Map<String, Object>>();
}
Map<String, Object> inner = null;
if((inner = map.get(fieldName)) == null) {
map.put(fieldName, inner = new HashMap<String, Object>());
}
inner.put("n", n);
inner.put("w", w);
inner.put("minVal", min);
inner.put("maxVal", max);
inner.put("radius", radius);
inner.put("resolution", resolution);
if(periodic != null) inner.put("periodic", periodic);
if(clip != null) inner.put("clip", clip);
if(forced != null) inner.put("forced", forced);
if(fieldName != null) inner.put("fieldName", fieldName);
if(fieldType != null) inner.put("fieldType", fieldType);
if(encoderType != null) inner.put("encoderType", encoderType);
return map;
}
@Test
public void testEquality() {
Parameters p = Parameters.getAllDefaultParameters();
Layer<Map<String, Object>> l = new Layer<>(p, null, new SpatialPooler(), new TemporalMemory(), Boolean.TRUE, null);
Layer<Map<String, Object>> l2 = new Layer<>(p, null, new SpatialPooler(), new TemporalMemory(), Boolean.TRUE, null);
assertTrue(l.equals(l));
assertFalse(l.equals(null));
assertTrue(l.equals(l2));
l2.name("I'm different");
assertFalse(l.equals(l2));
l2.name(null);
assertTrue(l.equals(l2));
Network n = new Network("TestNetwork", p);
Region r = new Region("r1", n);
l.setRegion(r);
assertFalse(l.equals(l2));
l2.setRegion(r);
assertTrue(l.equals(l2));
Region r2 = new Region("r2", n);
l2.setRegion(r2);
assertFalse(l.equals(l2));
}
@Test
public void testInferInputDimensions() {
Parameters p = Parameters.getAllDefaultParameters();
Layer<Map<String, Object>> l = new Layer<>(p, null, new SpatialPooler(), new TemporalMemory(), Boolean.TRUE, null);
int[] dims = l.inferInputDimensions(16384, 2);
assertTrue(Arrays.equals(new int[] { 128, 128 }, dims));
dims = l.inferInputDimensions(8000, 3);
assertTrue(Arrays.equals(new int[] { 20, 20, 20 }, dims));
// Now test non-square dimensions
dims = l.inferInputDimensions(450, 2);
assertTrue(Arrays.equals(new int[] { 1, 450 }, dims));
}
String filterMessage = null;
@Test
public void testExplicitCloseFailure() {
Parameters p = NetworkTestHarness.getParameters();
p = p.union(NetworkTestHarness.getNetworkDemoTestEncoderParams());
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
Network network = Network.create("test network", p)
.add(Network.createRegion("r1")
.add(Network.createLayer("2", p)
.add(Anomaly.create())
.add(new SpatialPooler())
.close()));
// Set up a log filter to grab the next message.
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
StatusPrinter.print(lc);
lc.addTurboFilter(new TurboFilter() {
@Override
public FilterReply decide(Marker arg0, Logger arg1, Level arg2, String arg3, Object[] arg4, Throwable arg5) {
filterMessage = arg3;
return FilterReply.ACCEPT;
}
});
network.lookup("r1").lookup("2").close();
// Test that the close() method exited after logging the correct message
assertEquals("Close called on Layer r1:2 which is already closed.", filterMessage);
// Make sure not to slow the entire test phase down by removing the filter
lc.resetTurboFilterList();
}
@Test(expected = IllegalStateException.class)
public void isClosedAddSensorTest() {
Parameters p = NetworkTestHarness.getParameters();
p = p.union(NetworkTestHarness.getNetworkDemoTestEncoderParams());
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
Layer l = Network.createLayer("l", p);
l.close();
Sensor<File> sensor = Sensor.create(
FileSensor::create,
SensorParams.create(
Keys::path, "", ResourceLocator.path("rec-center-hourly-small.csv")));
l.add(sensor);
}
@Test(expected = IllegalStateException.class)
public void isClosedAddMultiEncoderTest() {
Parameters p = NetworkTestHarness.getParameters();
p = p.union(NetworkTestHarness.getNetworkDemoTestEncoderParams());
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
Layer l = Network.createLayer("l", p);
l.close();
l.add(MultiEncoder.builder().name("").build());
}
@Test(expected = IllegalStateException.class)
public void isClosedAddSpatialPoolerTest() {
Parameters p = NetworkTestHarness.getParameters();
p = p.union(NetworkTestHarness.getNetworkDemoTestEncoderParams());
p.setParameterByKey(KEY.RANDOM, new MersenneTwister(42));
Layer l = Network.createLayer("l", p);
l.close();
l.add(new SpatialPooler());
}
} |
package org.jfree.chart.renderer.xy.junit;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.jfree.data.xy.DefaultTableXYDataset;
import org.jfree.data.xy.TableXYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
public class RendererXYPackageTests extends TestCase {
/**
* Returns a test suite to the JUnit test runner.
*
* @return The test suite.
*/
public static Test suite() {
TestSuite suite = new TestSuite("org.jfree.chart.renderer.xy");
suite.addTestSuite(AbstractXYItemRendererTests.class);
suite.addTestSuite(CandlestickRendererTests.class);
suite.addTestSuite(ClusteredXYBarRendererTests.class);
suite.addTestSuite(DeviationRendererTests.class);
suite.addTestSuite(HighLowRendererTests.class);
suite.addTestSuite(StackedXYAreaRendererTests.class);
suite.addTestSuite(StackedXYAreaRenderer2Tests.class);
suite.addTestSuite(StackedXYBarRendererTests.class);
suite.addTestSuite(StandardXYItemRendererTests.class);
suite.addTestSuite(VectorRendererTests.class);
suite.addTestSuite(WindItemRendererTests.class);
suite.addTestSuite(XYAreaRendererTests.class);
suite.addTestSuite(XYAreaRenderer2Tests.class);
suite.addTestSuite(XYBarRendererTests.class);
suite.addTestSuite(XYBlockRendererTests.class);
suite.addTestSuite(XYBoxAndWhiskerRendererTests.class);
suite.addTestSuite(XYBubbleRendererTests.class);
suite.addTestSuite(XYDifferenceRendererTests.class);
suite.addTestSuite(XYDotRendererTests.class);
suite.addTestSuite(XYErrorRendererTests.class);
suite.addTestSuite(XYLineAndShapeRendererTests.class);
suite.addTestSuite(XYLine3DRendererTests.class);
suite.addTestSuite(XYSplineRendererTests.class);
suite.addTestSuite(XYStepRendererTests.class);
suite.addTestSuite(XYStepAreaRendererTests.class);
suite.addTestSuite(YIntervalRendererTests.class);
return suite;
}
/**
* Constructs the test suite.
*
* @param name the suite name.
*/
public RendererXYPackageTests(String name) {
super(name);
}
/**
* Creates and returns a sample dataset for testing purposes.
*
* @return A sample dataset.
*/
public static XYSeriesCollection createTestXYSeriesCollection() {
XYSeriesCollection result = new XYSeriesCollection();
XYSeries series1 = new XYSeries("Series 1", false, false);
series1.add(1.0, 2.0);
series1.add(2.0, 5.0);
XYSeries series2 = new XYSeries("Series 2", false, false);
series2.add(1.0, 4.0);
series2.add(2.0, 3.0);
result.addSeries(series1);
result.addSeries(series2);
return result;
}
/**
* Creates and returns a sample dataset for testing purposes.
*
* @return A sample dataset.
*/
public static TableXYDataset createTestTableXYDataset() {
DefaultTableXYDataset result = new DefaultTableXYDataset();
XYSeries series1 = new XYSeries("Series 1", false, false);
series1.add(1.0, 2.0);
series1.add(2.0, 5.0);
XYSeries series2 = new XYSeries("Series 2", false, false);
series2.add(1.0, 4.0);
series2.add(2.0, 3.0);
result.addSeries(series1);
result.addSeries(series2);
return result;
}
/**
* Runs the test suite using JUnit's text-based runner.
*
* @param args ignored.
*/
public static void main(String[] args) {
junit.textui.TestRunner.run(suite());
}
} |
package com.jme3.app;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.NinePatchDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.*;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import com.jme3.audio.AudioRenderer;
import com.jme3.audio.android.AndroidAudioRenderer;
import com.jme3.input.JoyInput;
import com.jme3.input.TouchInput;
import com.jme3.input.android.AndroidSensorJoyInput;
import com.jme3.input.controls.TouchListener;
import com.jme3.input.controls.TouchTrigger;
import com.jme3.input.event.TouchEvent;
import com.jme3.renderer.android.AndroidGLSurfaceView;
import com.jme3.system.AppSettings;
import com.jme3.system.SystemListener;
import com.jme3.system.android.AndroidConfigChooser;
import com.jme3.system.android.AndroidConfigChooser.ConfigType;
import com.jme3.system.android.JmeAndroidSystem;
import com.jme3.system.android.OGLESContext;
import com.jme3.util.AndroidLogHandler;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
/**
* <code>AndroidHarness</code> wraps a jme application object and runs it on
* Android
*
* @author Kirill
* @author larynx
*/
public class AndroidHarness extends Activity implements TouchListener, DialogInterface.OnClickListener, SystemListener {
protected final static Logger logger = Logger.getLogger(AndroidHarness.class.getName());
/**
* The application class to start
*/
protected String appClass = "jme3test.android.Test";
/**
* The jme3 application object
*/
protected Application app = null;
/**
* ConfigType.FASTEST is RGB565, GLSurfaceView default ConfigType.BEST is
* RGBA8888 or better if supported by the hardware
*/
protected ConfigType eglConfigType = ConfigType.FASTEST;
/**
* If true all valid and not valid egl configs are logged
* @deprecated this has no use
*/
@Deprecated
protected boolean eglConfigVerboseLogging = false;
/**
* set to 2, 4 to enable multisampling.
*/
protected int antiAliasingSamples = 0;
/**
* If true Android Sensors are used as simulated Joysticks Users can use the
* Android sensor feedback through the RawInputListener or by registering
* JoyAxisTriggers.
*/
protected boolean joystickEventsEnabled = false;
/**
* If true MouseEvents are generated from TouchEvents
*/
protected boolean mouseEventsEnabled = true;
/**
* Flip X axis
*/
protected boolean mouseEventsInvertX = false;
/**
* Flip Y axis
*/
protected boolean mouseEventsInvertY = false;
/**
* if true finish this activity when the jme app is stopped
*/
protected boolean finishOnAppStop = true;
/**
* set to false if you don't want the harness to handle the exit hook
*/
protected boolean handleExitHook = true;
/**
* Title of the exit dialog, default is "Do you want to exit?"
*/
protected String exitDialogTitle = "Do you want to exit?";
/**
* Message of the exit dialog, default is "Use your home key to bring this
* app into the background or exit to terminate it."
*/
protected String exitDialogMessage = "Use your home key to bring this app into the background or exit to terminate it.";
/**
* Set the screen window mode. If screenFullSize is true, then the
* notification bar and title bar are removed and the screen covers the
* entire display. If screenFullSize is false, then the notification bar
* remains visible if screenShowTitle is true while screenFullScreen is
* false, then the title bar is also displayed under the notification bar.
*/
protected boolean screenFullScreen = true;
/**
* if screenShowTitle is true while screenFullScreen is false, then the
* title bar is also displayed under the notification bar
*/
protected boolean screenShowTitle = true;
/**
* Splash Screen picture Resource ID. If a Splash Screen is desired, set
* splashPicID to the value of the Resource ID (i.e. R.drawable.picname). If
* splashPicID = 0, then no splash screen will be displayed.
*/
protected int splashPicID = 0;
/**
* Set the screen orientation, default is SENSOR
* ActivityInfo.SCREEN_ORIENTATION_* constants package
* android.content.pm.ActivityInfo
*
* SCREEN_ORIENTATION_UNSPECIFIED SCREEN_ORIENTATION_LANDSCAPE
* SCREEN_ORIENTATION_PORTRAIT SCREEN_ORIENTATION_USER
* SCREEN_ORIENTATION_BEHIND SCREEN_ORIENTATION_SENSOR (default)
* SCREEN_ORIENTATION_NOSENSOR
*/
protected int screenOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR;
protected OGLESContext ctx;
protected AndroidGLSurfaceView view = null;
protected boolean isGLThreadPaused = true;
protected ImageView splashImageView = null;
protected FrameLayout frameLayout = null;
final private String ESCAPE_EVENT = "TouchEscape";
private boolean firstDrawFrame = true;
private boolean inConfigChange = false;
private class DataObject {
protected Application app = null;
}
@Override
public Object onRetainNonConfigurationInstance() {
logger.log(Level.FINE, "onRetainNonConfigurationInstance");
final DataObject data = new DataObject();
data.app = this.app;
inConfigChange = true;
return data;
}
@Override
public void onCreate(Bundle savedInstanceState) {
initializeLogHandler();
logger.fine("onCreate");
super.onCreate(savedInstanceState);
JmeAndroidSystem.setActivity(this);
if (screenFullScreen) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
} else {
if (!screenShowTitle) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
}
}
setRequestedOrientation(screenOrientation);
final DataObject data = (DataObject) getLastNonConfigurationInstance();
if (data != null) {
logger.log(Level.FINE, "Using Retained App");
this.app = data.app;
} else {
// Discover the screen reolution
//TODO try to find a better way to get a hand on the resolution
WindowManager wind = this.getWindowManager();
Display disp = wind.getDefaultDisplay();
Log.d("AndroidHarness", "Resolution from Window, width:" + disp.getWidth() + ", height: " + disp.getHeight());
// Create Settings
logger.log(Level.FINE, "Creating settings");
AppSettings settings = new AppSettings(true);
settings.setEmulateMouse(mouseEventsEnabled);
settings.setEmulateMouseFlipAxis(mouseEventsInvertX, mouseEventsInvertY);
settings.setUseJoysticks(joystickEventsEnabled);
settings.setSamples(antiAliasingSamples);
settings.setResolution(disp.getWidth(), disp.getHeight());
settings.put(AndroidConfigChooser.SETTINGS_CONFIG_TYPE, eglConfigType);
// Create application instance
try {
if (app == null) {
@SuppressWarnings("unchecked")
Class<? extends Application> clazz = (Class<? extends Application>) Class.forName(appClass);
app = clazz.newInstance();
}
app.setSettings(settings);
app.start();
} catch (Exception ex) {
handleError("Class " + appClass + " init failed", ex);
setContentView(new TextView(this));
}
}
ctx = (OGLESContext) app.getContext();
view = ctx.createView();
// AndroidHarness wraps the app as a SystemListener.
ctx.setSystemListener(this);
layoutDisplay();
}
@Override
protected void onRestart() {
logger.fine("onRestart");
super.onRestart();
if (app != null) {
app.restart();
}
}
@Override
protected void onStart() {
logger.fine("onStart");
super.onStart();
}
@Override
protected void onResume() {
logger.fine("onResume");
super.onResume();
if (view != null) {
view.onResume();
}
if (app != null) {
//resume the audio
AudioRenderer result = app.getAudioRenderer();
if (result != null) {
if (result instanceof AndroidAudioRenderer) {
AndroidAudioRenderer renderer = (AndroidAudioRenderer) result;
renderer.resumeAll();
}
}
//resume the sensors (aka joysticks)
if (app.getContext() != null) {
JoyInput joyInput = app.getContext().getJoyInput();
if (joyInput != null) {
if (joyInput instanceof AndroidSensorJoyInput) {
AndroidSensorJoyInput androidJoyInput = (AndroidSensorJoyInput) joyInput;
androidJoyInput.resumeSensors();
}
}
}
}
isGLThreadPaused = false;
gainFocus();
}
@Override
protected void onPause() {
loseFocus();
logger.fine("onPause");
super.onPause();
if (view != null) {
view.onPause();
}
if (app != null) {
//pause the audio
AudioRenderer result = app.getAudioRenderer();
if (result != null) {
logger.log(Level.FINE, "pause: {0}", result.getClass().getSimpleName());
if (result instanceof AndroidAudioRenderer) {
AndroidAudioRenderer renderer = (AndroidAudioRenderer) result;
renderer.pauseAll();
}
}
//pause the sensors (aka joysticks)
if (app.getContext() != null) {
JoyInput joyInput = app.getContext().getJoyInput();
if (joyInput != null) {
if (joyInput instanceof AndroidSensorJoyInput) {
AndroidSensorJoyInput androidJoyInput = (AndroidSensorJoyInput) joyInput;
androidJoyInput.pauseSensors();
}
}
}
}
isGLThreadPaused = true;
}
@Override
protected void onStop() {
logger.fine("onStop");
super.onStop();
}
@Override
protected void onDestroy() {
logger.fine("onDestroy");
final DataObject data = (DataObject) getLastNonConfigurationInstance();
if (data != null || inConfigChange) {
logger.fine("In Config Change, not stopping app.");
} else {
if (app != null) {
app.stop(!isGLThreadPaused);
}
}
setContentView(new TextView(this));
JmeAndroidSystem.setActivity(null);
ctx = null;
app = null;
view = null;
super.onDestroy();
}
public Application getJmeApplication() {
return app;
}
/**
* Called when an error has occurred. By default, will show an error message
* to the user and print the exception/error to the log.
*/
@Override
public void handleError(final String errorMsg, final Throwable t) {
String stackTrace = "";
String title = "Error";
if (t != null) {
// Convert exception to string
StringWriter sw = new StringWriter(100);
t.printStackTrace(new PrintWriter(sw));
stackTrace = sw.toString();
title = t.toString();
}
final String finalTitle = title;
final String finalMsg = (errorMsg != null ? errorMsg : "Uncaught Exception")
+ "\n" + stackTrace;
logger.log(Level.SEVERE, finalMsg);
runOnUiThread(new Runnable() {
@Override
public void run() {
AlertDialog dialog = new AlertDialog.Builder(AndroidHarness.this) // .setIcon(R.drawable.alert_dialog_icon)
.setTitle(finalTitle).setPositiveButton("Kill", AndroidHarness.this).setMessage(finalMsg).create();
dialog.show();
}
});
}
/**
* Called by the android alert dialog, terminate the activity and OpenGL
* rendering
*
* @param dialog
* @param whichButton
*/
public void onClick(DialogInterface dialog, int whichButton) {
if (whichButton != -2) {
if (app != null) {
app.stop(true);
}
app = null;
this.finish();
}
}
/**
* Gets called by the InputManager on all touch/drag/scale events
*/
@Override
public void onTouch(String name, TouchEvent evt, float tpf) {
if (name.equals(ESCAPE_EVENT)) {
switch (evt.getType()) {
case KEY_UP:
runOnUiThread(new Runnable() {
@Override
public void run() {
AlertDialog dialog = new AlertDialog.Builder(AndroidHarness.this) // .setIcon(R.drawable.alert_dialog_icon)
.setTitle(exitDialogTitle).setPositiveButton("Yes", AndroidHarness.this).setNegativeButton("No", AndroidHarness.this).setMessage(exitDialogMessage).create();
dialog.show();
}
});
break;
default:
break;
}
}
}
public void layoutDisplay() {
logger.log(Level.FINE, "Splash Screen Picture Resource ID: {0}", splashPicID);
if (view == null) {
logger.log(Level.FINE, "view is null!");
}
if (splashPicID != 0) {
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT,
Gravity.CENTER);
frameLayout = new FrameLayout(this);
splashImageView = new ImageView(this);
Drawable drawable = this.getResources().getDrawable(splashPicID);
if (drawable instanceof NinePatchDrawable) {
splashImageView.setBackgroundDrawable(drawable);
} else {
splashImageView.setImageResource(splashPicID);
}
if (view.getParent() != null) {
((ViewGroup) view.getParent()).removeView(view);
}
frameLayout.addView(view);
if (splashImageView.getParent() != null) {
((ViewGroup) splashImageView.getParent()).removeView(splashImageView);
}
frameLayout.addView(splashImageView, lp);
setContentView(frameLayout);
logger.log(Level.FINE, "Splash Screen Created");
} else {
logger.log(Level.FINE, "Splash Screen Skipped.");
setContentView(view);
}
}
public void removeSplashScreen() {
logger.log(Level.FINE, "Splash Screen Picture Resource ID: {0}", splashPicID);
if (splashPicID != 0) {
if (frameLayout != null) {
if (splashImageView != null) {
this.runOnUiThread(new Runnable() {
@Override
public void run() {
splashImageView.setVisibility(View.INVISIBLE);
frameLayout.removeView(splashImageView);
}
});
} else {
logger.log(Level.FINE, "splashImageView is null");
}
} else {
logger.log(Level.FINE, "frameLayout is null");
}
}
}
/**
* Removes the standard Android log handler due to an issue with not logging
* entries lower than INFO level and adds a handler that produces
* JME formatted log messages.
*/
protected void initializeLogHandler() {
Logger log = LogManager.getLogManager().getLogger("");
for (Handler handler : log.getHandlers()) {
if (log.getLevel() != null && log.getLevel().intValue() <= Level.FINE.intValue()) {
Log.v("AndroidHarness", "Removing Handler class: " + handler.getClass().getName());
}
log.removeHandler(handler);
}
Handler handler = new AndroidLogHandler();
log.addHandler(handler);
handler.setLevel(Level.ALL);
}
public void initialize() {
app.initialize();
if (handleExitHook) {
app.getInputManager().addMapping(ESCAPE_EVENT, new TouchTrigger(TouchInput.KEYCODE_BACK));
app.getInputManager().addListener(this, new String[]{ESCAPE_EVENT});
}
}
public void reshape(int width, int height) {
app.reshape(width, height);
}
public void update() {
app.update();
// call to remove the splash screen, if present.
// call after app.update() to make sure no gap between
// splash screen going away and app display being shown.
if (firstDrawFrame) {
removeSplashScreen();
firstDrawFrame = false;
}
}
public void requestClose(boolean esc) {
app.requestClose(esc);
}
public void destroy() {
if (app != null) {
app.destroy();
}
if (finishOnAppStop) {
finish();
}
}
public void gainFocus() {
if (app != null) {
app.gainFocus();
}
}
public void loseFocus() {
if (app != null) {
app.loseFocus();
}
}
} |
package org.royaldev.royalcommands;
import com.griefcraft.lwc.LWCPlugin;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import org.apache.commons.lang.text.StrBuilder;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandMap;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.craftbukkit.libs.com.google.gson.Gson;
import org.bukkit.craftbukkit.libs.com.google.gson.reflect.TypeToken;
import org.bukkit.entity.Player;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.SimplePluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitScheduler;
import org.kitteh.tag.TagAPI;
import org.kitteh.vanish.VanishPlugin;
import org.royaldev.royalcommands.api.RApiMain;
import org.royaldev.royalcommands.configuration.ConfManager;
import org.royaldev.royalcommands.configuration.PConfManager;
import org.royaldev.royalcommands.listeners.MonitorListener;
import org.royaldev.royalcommands.listeners.RoyalCommandsBlockListener;
import org.royaldev.royalcommands.listeners.RoyalCommandsEntityListener;
import org.royaldev.royalcommands.listeners.RoyalCommandsPlayerListener;
import org.royaldev.royalcommands.listeners.ServerListener;
import org.royaldev.royalcommands.listeners.SignListener;
import org.royaldev.royalcommands.listeners.TagAPIListener;
import org.royaldev.royalcommands.nms.api.NMSFace;
import org.royaldev.royalcommands.rcommands.*;
import org.royaldev.royalcommands.runners.AFKWatcher;
import org.royaldev.royalcommands.runners.BanWatcher;
import org.royaldev.royalcommands.runners.FreezeWatcher;
import org.royaldev.royalcommands.runners.MailRunner;
import org.royaldev.royalcommands.runners.UserdataRunner;
import org.royaldev.royalcommands.runners.WarnWatcher;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RoyalCommands extends JavaPlugin {
public static ConfigurationSection commands = null;
public static File dataFolder;
public static ItemNameManager inm;
public static WorldManager wm = null;
public static RoyalCommands instance;
public ConfManager whl;
public Logger log = Logger.getLogger("Minecraft");
public String version = null;
public String newVersion = null;
public Metrics m = null;
public NMSFace nmsFace;
public Config c;
private final int minVersion = 2645;
private CommandMap cm = null;
private YamlConfiguration pluginYml = null;
private final RoyalCommandsPlayerListener playerListener = new RoyalCommandsPlayerListener(this);
private final RoyalCommandsBlockListener blockListener = new RoyalCommandsBlockListener(this);
private final RoyalCommandsEntityListener entityListener = new RoyalCommandsEntityListener(this);
private final SignListener signListener = new SignListener(this);
private final MonitorListener monitorListener = new MonitorListener(this);
private final ServerListener serverListener = new ServerListener(this);
private final Pattern versionPattern = Pattern.compile("(\\d+\\.\\d+\\.\\d+)(\\-SNAPSHOT)?(\\-local\\-(\\d{8}\\.\\d{6})|\\-(\\d+))?");
private RApiMain api;
public final AuthorizationHandler ah = new AuthorizationHandler(this);
public final VaultHandler vh = new VaultHandler(this);
private VanishPlugin vp = null;
private WorldGuardPlugin wg = null;
private LWCPlugin lwc = null;
public static MultiverseCore mvc = null;
@SuppressWarnings("unused")
public RApiMain getAPI() {
return api;
}
@SuppressWarnings("unused")
public boolean canBuild(Player p, Location l) {
return wg == null || wg.canBuild(p, l);
}
public boolean canBuild(Player p, Block b) {
return wg == null || wg.canBuild(p, b);
}
public boolean canAccessChest(Player p, Block b) {
return lwc == null || lwc.getLWC().canAccessProtection(p, b);
}
public boolean isVanished(Player p) {
if (!Config.useVNP) return false;
if (vp == null) {
vp = (VanishPlugin) Bukkit.getServer().getPluginManager().getPlugin("VanishNoPacket");
return false;
} else return vp.getManager().isVanished(p);
}
public boolean isVanished(Player p, CommandSender cs) {
if (!Config.useVNP) return false;
if (vp == null) {
vp = (VanishPlugin) Bukkit.getServer().getPluginManager().getPlugin("VanishNoPacket");
return false;
}
return !ah.isAuthorized(cs, "rcmds.seehidden") && vp.getManager().isVanished(p);
}
public int getNumberVanished() {
int hid = 0;
for (Player p : getServer().getOnlinePlayers()) if (isVanished(p)) hid++;
return hid;
}
//-- Static methods --//
/**
* Joins an array of strings with spaces
*
* @param array Array to join
* @param position Position to start joining from
* @return Joined string
*/
public static String getFinalArg(String[] array, int position) {
StrBuilder sb = new StrBuilder();
for (int i = position; i < array.length; i++) {
sb.append(array[i]);
sb.append(" ");
}
return sb.substring(0, sb.length() - 1);
}
private CommandMap getCommandMap() {
if (cm != null) return cm;
Field map;
try {
map = getServer().getPluginManager().getClass().getDeclaredField("commandMap");
map.setAccessible(true);
cm = (CommandMap) map.get(getServer().getPluginManager());
return cm;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private ConfigurationSection getCommands() {
return pluginYml.getConfigurationSection("reflectcommands");
}
private ConfigurationSection getCommandInfo(String command) {
final ConfigurationSection ci = getCommands().getConfigurationSection(command);
if (ci == null) throw new IllegalArgumentException("No such command registered!");
return ci;
}
private String[] getAliases(String command) {
final List<String> aliasesList = getCommandInfo(command).getStringList("aliases");
if (aliasesList == null) return new String[0];
final String[] aliases = new String[aliasesList.size()];
for (int index = 0; index < aliasesList.size(); index++) {
final String s = aliasesList.get(index);
aliases[index] = s;
}
return aliases;
}
private String getUsage(String command) {
return getCommandInfo(command).getString("usage", "/<command>");
}
private String getDescription(String command) {
return getCommandInfo(command).getString("description", command);
}
/*private boolean unregisterCommand(String command) {
final Command c = getCommandMap().getCommand(command);
return c != null && c.unregister(getCommandMap());
} save for overriding commands in the config*/
/**
* Registers a command in the server's CommandMap.
*
* @param ce CommandExecutor to be registered
* @param command Command name as specified in plugin.yml
*/
private void registerCommand(CommandExecutor ce, String command) {
if (Config.disabledCommands.contains(command.toLowerCase())) return;
final DynamicCommand dc = new DynamicCommand(getAliases(command), command, getDescription(command), getUsage(command), new String[0], "", ce, this, this);
try {
getCommandMap().register(getDescription().getName(), dc);
} catch (IllegalArgumentException e) {
getLogger().warning("Could not register command \"" + command + "\" - an error occurred: " + e.getMessage() + ".");
}
}
private boolean versionCheck() {
// If someone happens to be looking through this and knows a better way, let me know.
if (!Config.checkVersion) return true;
Pattern p = Pattern.compile(".+b(\\d+)jnks.+");
Matcher m = p.matcher(getServer().getVersion());
if (!m.matches() || m.groupCount() < 1) {
log.warning("[RoyalCommands] Could not get CraftBukkit version! No version checking will take place.");
return true;
}
Integer currentVersion = RUtils.getInt(m.group(1));
return currentVersion == null || currentVersion >= minVersion;
}
private Map<String, String> getNewestVersions() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(new URL("https://cdn.royaldev.org/rcmdsversion.php").openStream()));
StringBuilder data = new StringBuilder();
String input;
while ((input = br.readLine()) != null) data.append(input);
return new Gson().fromJson(data.toString(), new TypeToken<Map<String, String>>() {}.getType());
}
public void loadConfiguration() {
if (!new File(getDataFolder(), "config.yml").exists()) saveDefaultConfig();
if (!new File(getDataFolder(), "items.csv").exists()) saveResource("items.csv", false);
if (!new File(getDataFolder(), "rules.txt").exists()) saveResource("rules.txt", false);
if (!new File(getDataFolder(), "help.txt").exists()) saveResource("help.txt", false);
if (!new File(getDataFolder(), "warps.yml").exists()) saveResource("warps.yml", false);
final File file = new File(getDataFolder(), "userdata");
if (!file.exists()) {
try {
boolean success = file.mkdir();
if (success) log.info("[RoyalCommands] Created userdata directory.");
} catch (Exception e) {
log.severe("[RoyalCommands] Failed to make userdata directory!");
log.severe(e.getMessage());
}
}
}
@Override
public void onEnable() {
//-- Set globals --//
instance = this;
pluginYml = YamlConfiguration.loadConfiguration(getResource("plugin.yml"));
dataFolder = getDataFolder();
whl = ConfManager.getConfManager("whitelist.yml");
commands = pluginYml.getConfigurationSection("reflectcommands");
version = getDescription().getVersion();
//-- Initialize ConfManagers if not made --//
String[] cms = new String[]{"whitelist.yml", "warps.yml", "publicassignments.yml"};
for (String name : cms) {
ConfManager cm = ConfManager.getConfManager(name);
if (!cm.exists()) cm.createFile();
cm.forceSave();
}
//-- Work out NMS magic using mbaxter's glorious methods --//
// Get full package string of CraftServer.
// org.bukkit.craftbukkit.versionstring (or for pre-refactor, just org.bukkit.craftbukkit
String packageName = getServer().getClass().getPackage().getName();
// Get the last element of the package
// If the last element of the package was "craftbukkit" we are now pre-refactor
String versionNMS = packageName.substring(packageName.lastIndexOf('.') + 1);
if (versionNMS.equals("craftbukkit")) versionNMS = "PreSafeGuard";
try {
// Check if we have a NMSHandler class at that location.
final Class<?> clazz = Class.forName("org.royaldev.royalcommands.nms." + versionNMS + ".NMSHandler");
// Make sure it actually implements NMS and set our handler
if (NMSFace.class.isAssignableFrom(clazz)) nmsFace = (NMSFace) clazz.getConstructor().newInstance();
} catch (final Exception e) {
getLogger().warning("Could not find support for this CraftBukkit version.");
getLogger().info("The BukkitDev page has links to the newest development builds to fix this.");
getLogger().info("For now, NMS/CB internal support will be disabled.");
nmsFace = new org.royaldev.royalcommands.nms.NoSupport.NMSHandler();
}
if (nmsFace.hasSupport()) getLogger().info("Loaded support for " + nmsFace.getVersion() + ".");
//-- Hidendra's Metrics --//
try {
Matcher matcher = versionPattern.matcher(version);
matcher.matches();
// 1 = base version
// 2 = -SNAPSHOT
// 5 = build
String versionMinusBuild = (matcher.group(1) == null) ? "Unknown" : matcher.group(1);
String build = (matcher.group(5) == null) ? "local build" : matcher.group(5);
if (matcher.group(2) == null) build = "release";
m = new Metrics(this);
Metrics.Graph g = m.createGraph("Version"); // get our custom version graph
g.addPlotter(
new Metrics.Plotter(versionMinusBuild + "~=~" + build) {
@Override
public int getValue() {
return 1; // this value doesn't matter
}
}
); // add the donut graph with major version inside and build outside
m.addGraph(g); // add the graph
if (!m.start())
getLogger().info("You have Metrics off! I like to keep accurate usage statistics, but okay. :(");
else getLogger().info("Metrics enabled. Thank you!");
} catch (Exception ignore) {
getLogger().warning("Could not start Metrics!");
}
//-- Get configs --//
loadConfiguration();
c = new Config(this);
c.reloadConfiguration();
//-- Check CB version --//
if (!versionCheck()) {
log.severe("[RoyalCommands] This version of CraftBukkit is too old to run RoyalCommands!");
log.severe("[RoyalCommands] This version of RoyalCommands needs at least CraftBukkit " + minVersion + ".");
log.severe("[RoyalCommands] Disabling plugin. You can turn this check off in the config.");
setEnabled(false);
return;
}
//-- Set up Vault --//
vh.setupVault();
//-- Schedule tasks --//
BukkitScheduler bs = getServer().getScheduler();
bs.runTaskTimerAsynchronously(this, new Runnable() {
@Override
public void run() {
if (!Config.updateCheck) return;
try {
Matcher m = versionPattern.matcher(version);
m.matches();
StringBuilder useVersion = new StringBuilder();
if (m.group(1) != null) useVersion.append(m.group(1)); // add base version
if (m.group(2) != null) useVersion.append(m.group(2)); // add SNAPSHOT status
/*
This does not need to compare build numbers. Everyone would be out of date all the time if it did.
This method will compare root versions.
*/
Map<String, String> jo = getNewestVersions();
String stable = jo.get("stable");
String dev = jo.get("dev");
String currentVersion = useVersion.toString().toLowerCase();
if (!dev.equalsIgnoreCase(currentVersion) && currentVersion.contains("-SNAPSHOT")) {
getLogger().warning("A newer version of RoyalCommands is available!");
getLogger().warning("Currently installed: v" + currentVersion + ", newest: v" + dev);
getLogger().warning("Development builds are available at http://ci.royaldev.org/");
} else if (!stable.equalsIgnoreCase(currentVersion) && !currentVersion.equalsIgnoreCase(dev)) {
getLogger().warning("A newer version of RoyalCommands is available!");
getLogger().warning("Currently installed: v" + currentVersion + ", newest: v" + stable);
getLogger().warning("Stable builds are available at http://dev.bukkit.org/server-mods/royalcommands");
} else if (!stable.equalsIgnoreCase(currentVersion) && currentVersion.replace("-SNAPSHOT", "").equalsIgnoreCase(stable)) {
getLogger().warning("A newer version of RoyalCommands is available!");
getLogger().warning("Currently installed: v" + currentVersion + ", newest: v" + stable);
getLogger().warning("Stable builds are available at http://dev.bukkit.org/server-mods/royalcommands");
}
} catch (Exception ignored) {
// ignore exceptions
}
}
}, 0L, 36000L);
bs.runTaskTimerAsynchronously(this, new AFKWatcher(this), 0L, 200L);
bs.runTaskTimerAsynchronously(this, new BanWatcher(this), 20L, 600L);
bs.runTaskTimerAsynchronously(this, new WarnWatcher(this), 20L, 12000L);
bs.scheduleSyncRepeatingTask(this, new FreezeWatcher(this), 20L, 100L);
long mail = RUtils.timeFormatToSeconds(Config.mailCheckTime);
if (mail > 0L) bs.scheduleSyncRepeatingTask(this, new MailRunner(this), 20L, mail * 20L);
long every = RUtils.timeFormatToSeconds(Config.saveInterval);
if (every < 1L) every = 600L; // 600s = 10m
bs.runTaskTimerAsynchronously(this, new UserdataRunner(this), 20L, every * 20L); // tick = 1/20s
//-- Get dependencies --//
vp = (VanishPlugin) getServer().getPluginManager().getPlugin("VanishNoPacket");
wg = (WorldGuardPlugin) getServer().getPluginManager().getPlugin("WorldGuard");
lwc = (LWCPlugin) getServer().getPluginManager().getPlugin("LWC");
mvc = (MultiverseCore) getServer().getPluginManager().getPlugin("Multiverse-Core");
TagAPI ta = (TagAPI) getServer().getPluginManager().getPlugin("TagAPI");
//-- Register events --//
PluginManager pm = getServer().getPluginManager();
pm.registerEvents(playerListener, this);
pm.registerEvents(entityListener, this);
pm.registerEvents(blockListener, this);
pm.registerEvents(signListener, this);
pm.registerEvents(monitorListener, this);
pm.registerEvents(serverListener, this);
if (ta != null && Config.changeNameTag) pm.registerEvents(new TagAPIListener(this), this);
//-- Register commands --//
registerCommand(new CmdLevel(this), "level");
registerCommand(new CmdSetlevel(this), "setlevel");
registerCommand(new CmdSci(this), "sci");
registerCommand(new CmdSpeak(this), "speak");
registerCommand(new CmdFacepalm(this), "facepalm");
registerCommand(new CmdSlap(this), "slap");
registerCommand(new CmdHarm(this), "harm");
registerCommand(new CmdStarve(this), "starve");
registerCommand(new CmdSetarmor(this), "setarmor");
registerCommand(new CmdGetIP(this), "getip");
registerCommand(new CmdCompareIP(this), "compareip");
registerCommand(new CmdRageQuit(this), "ragequit");
registerCommand(new CmdQuit(this), "quit");
registerCommand(new CmdRank(this), "rank");
registerCommand(new CmdFreeze(this), "freeze");
registerCommand(new CmdFakeop(this), "fakeop");
registerCommand(new CmdVtp(this), "vtp");
registerCommand(new CmdVtphere(this), "vtphere");
registerCommand(new CmdMegaStrike(this), "megastrike");
registerCommand(new CmdPext(this), "pext");
registerCommand(new CmdItem(this), "item");
registerCommand(new CmdClearInventory(this), "clearinventory");
registerCommand(new CmdWeather(this), "weather");
registerCommand(new CmdFixChunk(this), "fixchunk");
registerCommand(new CmdGive(this), "give");
registerCommand(new CmdMessage(this), "message");
registerCommand(new CmdReply(this), "reply");
registerCommand(new CmdGamemode(this), "gamemode");
registerCommand(new CmdMute(this), "mute");
registerCommand(new CmdBan(this), "ban");
registerCommand(new CmdKick(this), "kick");
registerCommand(new CmdTime(this), "time");
registerCommand(new CmdHome(this), "home");
registerCommand(new CmdSetHome(this), "sethome");
registerCommand(new CmdDelHome(this), "delhome");
registerCommand(new CmdListHome(this), "listhome");
registerCommand(new CmdStrike(this), "strike");
registerCommand(new CmdJump(this), "jump");
registerCommand(new CmdWarn(this), "warn");
registerCommand(new CmdClearWarns(this), "clearwarns");
registerCommand(new CmdWarp(this), "warp");
registerCommand(new CmdSetWarp(this), "setwarp");
registerCommand(new CmdDelWarp(this), "delwarp");
registerCommand(new CmdRepair(this), "repair");
registerCommand(new CmdUnban(this), "unban");
registerCommand(new CmdHeal(this), "heal");
registerCommand(new CmdFeed(this), "feed");
registerCommand(new CmdGod(this), "god");
registerCommand(new CmdSetSpawn(this), "setspawn");
registerCommand(new CmdSpawn(this), "spawn");
registerCommand(new CmdBanIP(this), "banip");
registerCommand(new CmdUnbanIP(this), "unbanip");
registerCommand(new CmdList(this), "list");
registerCommand(new CmdBack(this), "back");
registerCommand(new CmdTeleport(this), "teleport");
registerCommand(new CmdTeleportHere(this), "teleporthere");
registerCommand(new CmdTeleportRequest(this), "teleportrequest");
registerCommand(new CmdTpAccept(this), "tpaccept");
registerCommand(new CmdTpDeny(this), "tpdeny");
registerCommand(new CmdListWarns(this), "listwarns");
registerCommand(new CmdMore(this), "more");
registerCommand(new CmdTeleportRequestHere(this), "teleportrequesthere");
registerCommand(new CmdSpy(this), "spy");
registerCommand(new CmdSpawnMob(this), "spawnmob");
registerCommand(new CmdAfk(this), "afk");
registerCommand(new CmdAssign(this), "assign");
registerCommand(new CmdOneHitKill(this), "onehitkill");
registerCommand(new CmdBurn(this), "burn");
registerCommand(new CmdKickAll(this), "kickall");
registerCommand(new CmdWorld(this), "world");
registerCommand(new CmdJail(this), "jail");
registerCommand(new CmdSetJail(this), "setjail");
registerCommand(new CmdLess(this), "less");
registerCommand(new CmdSpawner(this), "spawner");
registerCommand(new CmdTp2p(this), "tp2p");
registerCommand(new CmdMotd(this), "motd");
registerCommand(new CmdDelJail(this), "deljail");
registerCommand(new CmdForce(this), "force");
registerCommand(new CmdPing(this), "ping");
registerCommand(new CmdInvsee(this), "invsee");
registerCommand(new CmdRealName(this), "realname");
registerCommand(new CmdNick(this), "nick");
registerCommand(new CmdIngot2Block(this), "ingot2block");
registerCommand(new CmdNear(this), "near");
registerCommand(new CmdKill(this), "kill");
registerCommand(new CmdSuicide(this), "suicide");
registerCommand(new CmdKillAll(this), "killall");
registerCommand(new CmdMuteAll(this), "muteall");
registerCommand(new CmdKit(this), "kit");
registerCommand(new CmdRules(this), "rules");
registerCommand(new CmdBroadcast(this), "broadcast");
registerCommand(new CmdHug(this), "hug");
registerCommand(new CmdExplode(this), "explode");
registerCommand(new CmdRide(this), "ride");
registerCommand(new CmdTppos(this), "tppos");
registerCommand(new CmdIgnore(this), "ignore");
registerCommand(new CmdHelp(this), "help");
registerCommand(new CmdCoords(this), "coords");
registerCommand(new CmdTpAll(this), "tpall");
registerCommand(new CmdTpaAll(this), "tpaall");
registerCommand(new CmdVip(this), "vip");
registerCommand(new CmdDump(this), "dump");
registerCommand(new CmdSeen(this), "seen");
registerCommand(new CmdTempban(this), "tempban");
registerCommand(new CmdTpToggle(this), "tptoggle");
registerCommand(new CmdKits(this), "kits");
registerCommand(new CmdLag(this), "lag");
registerCommand(new CmdMem(this), "mem");
registerCommand(new CmdEntities(this), "entities");
registerCommand(new CmdInvmod(this), "invmod");
registerCommand(new CmdWorkbench(this), "workbench");
registerCommand(new CmdEnchantingTable(this), "enchantingtable");
registerCommand(new CmdTrade(this), "trade");
registerCommand(new CmdFurnace(this), "furnace");
registerCommand(new CmdEnchant(this), "enchant");
registerCommand(new CmdWhitelist(this), "wl");
registerCommand(new CmdFireball(this), "fireball");
registerCommand(new CmdFly(this), "fly");
registerCommand(new CmdPlayerTime(this), "playertime");
registerCommand(new CmdCompass(this), "compass");
registerCommand(new CmdHelmet(this), "helmet");
registerCommand(new CmdWorldManager(this), "worldmanager");
registerCommand(new CmdBiome(this), "biome");
registerCommand(new CmdGetID(this), "getid");
registerCommand(new CmdBuddha(this), "buddha");
registerCommand(new CmdErase(this), "erase");
registerCommand(new CmdWhois(this), "whois");
registerCommand(new CmdMobIgnore(this), "mobignore");
registerCommand(new CmdMonitor(this), "monitor");
registerCommand(new CmdGarbageCollector(this), "garbagecollector");
registerCommand(new CmdBackpack(this), "backpack");
registerCommand(new CmdUsage(this), "usage");
registerCommand(new CmdPluginManager(this), "pluginmanager");
registerCommand(new CmdFreezeTime(this), "freezetime");
registerCommand(new CmdBanInfo(this), "baninfo");
registerCommand(new CmdBanList(this), "banlist");
registerCommand(new CmdFlySpeed(this), "flyspeed");
registerCommand(new CmdWalkSpeed(this), "walkspeed");
registerCommand(new CmdAccountStatus(this), "accountstatus");
registerCommand(new CmdPlayerSearch(this), "playersearch");
registerCommand(new CmdDeafen(this), "deafen");
registerCommand(new CmdRename(this), "rename");
registerCommand(new CmdLore(this), "lore");
registerCommand(new CmdSetUserdata(this), "setuserdata");
registerCommand(new CmdFirework(this), "firework");
registerCommand(new CmdRocket(this), "rocket");
registerCommand(new CmdEffect(this), "effect");
registerCommand(new CmdBanHistory(this), "banhistory");
registerCommand(new CmdMail(this), "mail");
registerCommand(new CmdSignEdit(this), "signedit");
registerCommand(new CmdPotion(this), "potion");
registerCommand(new CmdSetCharacteristic(this), "setcharacteristic");
registerCommand(new CmdNameEntity(this), "nameentity");
registerCommand(new CmdHead(this), "head");
registerCommand(new CmdFindIP(this), "findip");
registerCommand(new CmdMap(this), "map");
registerCommand(new CmdDeleteBanHistory(this), "deletebanhistory");
registerCommand(new CmdPublicAssign(this), "publicassign");
registerCommand(new CmdEnderChest(this), "enderchest");
registerCommand(new CmdRcmds(this), "rcmds");
//-- Make the API --//
api = new RApiMain();
//-- We're done! --//
log.info("[RoyalCommands] RoyalCommands v" + version + " initiated.");
}
@Override
public void onDisable() {
//-- Cancel scheduled tasks --//
getServer().getScheduler().cancelTasks(this);
//-- Save inventories --//
WorldManager.il.saveAllInventories();
//-- Save all userdata --//
getLogger().info("Saving userdata and configurations (" + (PConfManager.managersCreated() + ConfManager.managersCreated()) + " files in all)...");
PConfManager.saveAllManagers();
ConfManager.saveAllManagers();
getLogger().info("Userdata saved.");
//-- We're done! --//
log.info("[RoyalCommands] RoyalCommands v" + version + " disabled.");
}
} |
class Centroid {
double[] data;
int size, ntrains;
int MAXTRAINS=100;
double MINLRATE=1d/MAXTRAINS;
public Centroid(int size) {
this.size = size;
this.ntrains = 1;
this.data = new double[size];
// TESTING WHITE CENTROIDS - MATCH ALL!!
// for (int i = 0; i < size; i++) { data[i] = 1d; }
for (int i = 0; i < size; i++) { data[i] = Math.random(); }
}
// Quick error check for vector size consistency
public void checkSize(double[] vec) {
if (vec.length != size) {
throw new RuntimeException(
"Input vector length does not match centroid size.");
}
}
// Per-centroid learning rate
public double lrate() {
if (ntrains<MAXTRAINS) {
// linearly decaying
return 1d/ntrains;
} else {
// lower bound
return MINLRATE;
}
}
public void train(double[] vec) {
checkSize(vec);
for (int i=0; i<size; i++) {
data[i] = (1-lrate())*data[i] + lrate()*vec[i];
}
ntrains++;
}
public double[] getData() {
return data;
}
public double similarity(Centroid c) {
return similarity(c.getData());
}
public double similarity(double[] vec) {
checkSize(vec);
return simpleDotProduct(vec);
// return squareError(vec);
}
// SIMILARITY MEASURES
public double simpleDotProduct(double[] vec) {
double ret = 0;
for (int i=0; i<size; i++) {
ret += data[i] * vec[i];
}
return ret/vec.length;
}
public double squareError(double[] vec) {
double ret = 0;
for (int i=0; i<size; i++) {
ret += Math.pow(data[i] - vec[i], 2);
}
return ret/vec.length;
}
} |
package org.royaldev.royalcommands;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import org.bukkit.command.RemoteConsoleCommandSender;
import org.bukkit.entity.Player;
public class AuthorizationHandler {
private final RoyalCommands plugin;
public AuthorizationHandler(RoyalCommands instance) {
plugin = instance;
}
private boolean permissionsLoaded() {
return plugin.vh.usingVault() && plugin.vh.getPermission() != null;
}
private boolean chatLoaded() {
return plugin.vh.usingVault() && plugin.vh.getChat() != null;
}
private boolean economyLoaded() {
return plugin.vh.usingVault() && plugin.vh.getEconomy() != null;
}
public boolean isAuthorized(Object o, String node) {
if (o instanceof RemoteConsoleCommandSender)
return iARemoteConsoleCommandSender((RemoteConsoleCommandSender) o, node);
else if (o instanceof Player) return iAPlayer((Player) o, node);
else if (o instanceof OfflinePlayer) return iAOfflinePlayer((OfflinePlayer) o, node);
else if (o instanceof CommandSender) return iACommandSender((CommandSender) o, node);
else throw new IllegalArgumentException("Object was not a valid authorizable!");
}
private boolean iAPlayer(Player p, String node) {
if (plugin.vh.usingVault() && permissionsLoaded()) return plugin.vh.getPermission().has(p, node);
return p.hasPermission(node);
}
private boolean iAOfflinePlayer(OfflinePlayer op, String node) {
if (op.isOnline()) return iAPlayer(op.getPlayer(), node);
if (plugin.vh.usingVault() && permissionsLoaded()) {
final String world = plugin.getServer().getWorlds().get(0).getName();
return plugin.vh.getPermission().has(world, op.getName(), node);
}
return false;
}
private boolean iARemoteConsoleCommandSender(RemoteConsoleCommandSender rccs, String node) {
return true;
}
private boolean iACommandSender(CommandSender cs, String node) {
if (plugin.vh.usingVault() && permissionsLoaded()) plugin.vh.getPermission().has(cs, node);
return cs.hasPermission(node);
}
} |
package com.habboi.tns.utils;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.controllers.Controller;
import com.badlogic.gdx.controllers.Controllers;
import com.badlogic.gdx.controllers.ControllerAdapter;
import com.badlogic.gdx.controllers.PovDirection;
import com.badlogic.gdx.utils.SharedLibraryLoader;
import com.habboi.tns.ui.Menu;
/**
* Map virtual buttons to controller or keyboard real buttons/keys
*/
public class InputManager extends ControllerAdapter implements InputProcessor {
// buttons
public static final int Select = 0;
public static final int Jump = 1;
public static final int Up = 2;
public static final int Down = 3;
public static final int Left = 4;
public static final int Right = 5;
public static final int Back = 6;
public static final int Pause = 7;
// axes
public static final int Horizontal = 0;
public static final int Vertical = 1;
public static final int Acceleration = 2;
public static final float DEAD_ZONE = 0.2f;
public static final int NUM_BUTTONS = 8;
public static final int NUM_AXIS = 3;
private static InputManager instance;
private int[] buttons = new int[NUM_BUTTONS];
private int[] prevButtons = new int[NUM_BUTTONS];
private float[] axis = new float[NUM_AXIS];
private boolean[] axisMenu = new boolean[NUM_AXIS];
private Controller currentController;
public static InputManager getInstance() {
if (instance == null) {
instance = new InputManager();
}
return instance;
}
public static float axisDeadZoneValue(float value) {
if (Math.abs(value) > DEAD_ZONE) {
return value;
}
return 0;
}
private InputManager() {
Gdx.input.setInputProcessor(this);
Controllers.addListener(this);
}
public boolean isButtonDown(int button) {
return buttons[button] > 0;
}
public boolean isButtonJustDown(int button) {
return isButtonDown(button) && !(prevButtons[button] > 0);
}
public boolean isAnyButtonDown() {
for (int i = 0; i < buttons.length; i++) {
if (buttons[i] > 0) {
return true;
}
}
return false;
}
public float getAxis(int axisIndex) {
return axis[axisIndex];
}
public void reset() {
for (int i = 0; i < buttons.length; i++) {
buttons[i] = 0;
prevButtons[i] = 0;
}
for (int i = 0; i < axis.length; i++) {
axis[i] = 0;
}
}
public void update() {
System.arraycopy(buttons, 0, prevButtons, 0, buttons.length);
}
public void menuInteraction(Menu menu) {
if (axis[Horizontal] == 0) {
axisMenu[Horizontal] = false;
}
if (axis[Vertical] == 0) {
axisMenu[Vertical] = false;
}
if (!axisMenu[Horizontal]) {
if (axis[Horizontal] >= 0.8f) {
menu.buttonDown(Right);
axisMenu[Horizontal] = true;
} else if (axis[Horizontal] <= -0.8f) {
menu.buttonDown(Left);
axisMenu[Horizontal] = true;
}
}
if (!axisMenu[Vertical]) {
if (axis[Vertical] >= 0.8f) {
menu.buttonDown(Up);
axisMenu[Vertical] = true;
} else if (axis[Vertical] <= -0.8f) {
menu.buttonDown(Down);
axisMenu[Vertical] = true;
}
}
if (isButtonJustDown(Select)) {
menu.buttonDown(Select);
} else if (isButtonJustDown(Back)) {
menu.buttonDown(Back);
}
}
@Override
public void connected(Controller controller) {
if (currentController == null) {
currentController = controller;
}
}
@Override
public void disconnected(Controller controller) {
if (currentController == controller) {
currentController = null;
}
}
@Override
public boolean axisMoved(Controller controller, int axisCode, float value) {
value = axisDeadZoneValue(value);
if (value != 0)
System.out.println("axis: " + axisCode + " = " + value);
if (axisCode == Xbox.L_STICK_HORIZONTAL_AXIS) {
axis[Horizontal] = value;
}
if (axisCode == Xbox.L_STICK_VERTICAL_AXIS) {
axis[Vertical] = -value;
}
if (axisCode == Xbox.R_TRIGGER || axisCode == Xbox.L_TRIGGER) {
axis[Acceleration] = -value;
}
return true;
}
@Override
public boolean buttonDown(Controller controller, int buttonCode) {
System.out.println("button: " + buttonCode);
if (buttonCode == Xbox.A) {
buttons[Jump]++;
buttons[Select]++;
return true;
}
if (buttonCode == Xbox.B) {
buttons[Back]++;
return true;
}
if (buttonCode == Xbox.START) {
buttons[Pause]++;
return true;
}
return false;
}
@Override
public boolean buttonUp(Controller controller, int buttonCode) {
if (buttonCode == Xbox.A) {
buttons[Jump] = 0;
buttons[Select] = 0;
return true;
}
if (buttonCode == Xbox.B) {
buttons[Back] = 0;
return true;
}
if (buttonCode == Xbox.START) {
buttons[Pause] = 0;
return true;
}
return false;
}
@Override
public boolean keyDown(int keycode) {
switch (keycode) {
case Input.Keys.LEFT:
buttons[Left]++;
axis[Horizontal] = -1;
return true;
case Input.Keys.RIGHT:
buttons[Right]++;
axis[Horizontal] = 1;
return true;
case Input.Keys.UP:
buttons[Up]++;
axis[Vertical] = 1;
return true;
case Input.Keys.DOWN:
buttons[Down]++;
axis[Vertical] = -1;
return true;
case Input.Keys.SPACE:
buttons[Jump]++;
return true;
case Input.Keys.ENTER:
buttons[Select]++;
return true;
case Input.Keys.ESCAPE:
buttons[Back]++;
buttons[Pause]++;
return true;
}
return false;
}
@Override
public boolean keyUp(int keycode) {
switch (keycode) {
case Input.Keys.LEFT:
buttons[Left] = 0;
axis[Horizontal] = 0;
return true;
case Input.Keys.RIGHT:
buttons[Right] = 0;
axis[Horizontal] = 0;
return true;
case Input.Keys.UP:
buttons[Up] = 0;
axis[Vertical] = 0;
return true;
case Input.Keys.DOWN:
buttons[Down] = 0;
axis[Vertical] = 0;
return true;
case Input.Keys.SPACE:
buttons[Jump] = 0;
return true;
case Input.Keys.ENTER:
buttons[Select] = 0;
return true;
case Input.Keys.ESCAPE:
buttons[Back] = 0;
buttons[Pause] = 0;
return true;
}
return false;
}
@Override
public boolean povMoved(Controller controller, int povCode, PovDirection value) {
System.out.println("pov: " + povCode + " = " + value);
if (povCode == 0) {
if (value == PovDirection.center) {
buttons[Left] = 0;
buttons[Right] = 0;
buttons[Up] = 0;
buttons[Down] = 0;
axis[Horizontal] = 0;
axis[Vertical] = 0;
}
if (value == PovDirection.east) {
buttons[Right]++;
axis[Horizontal] = 1;
}
if (value == PovDirection.west) {
buttons[Left]++;
axis[Horizontal] = -1;
}
if (value == PovDirection.north) {
buttons[Up]++;
axis[Vertical] = 1;
}
if (value == PovDirection.south) {
buttons[Down]++;
axis[Vertical] = -1;
}
if (value == PovDirection.northEast) {
buttons[Right]++;
axis[Horizontal] = 1;
buttons[Up]++;
axis[Vertical] = 1;
}
if (value == PovDirection.northWest) {
buttons[Left]++;
axis[Horizontal] = -1;
buttons[Up]++;
axis[Vertical] = 1;
}
if (value == PovDirection.southEast) {
buttons[Right]++;
axis[Horizontal] = 1;
buttons[Down]++;
axis[Vertical] = -1;
}
if (value == PovDirection.southWest) {
buttons[Left]++;
axis[Horizontal] = -1;
buttons[Down]++;
axis[Vertical] = -1;
}
}
return false;
}
@Override
public boolean keyTyped(char character) {
return false;
}
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
return false;
}
@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
return false;
}
@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
return false;
}
@Override
public boolean mouseMoved(int screenX, int screenY) {
return false;
}
@Override
public boolean scrolled(int amount) {
return false;
}
public static class Xbox {
// Buttons
public static final int A;
public static final int B;
public static final int X;
public static final int Y;
public static final int GUIDE;
public static final int L_BUMPER;
public static final int R_BUMPER;
public static final int BACK;
public static final int START;
public static final int DPAD_UP;
public static final int DPAD_DOWN;
public static final int DPAD_LEFT;
public static final int DPAD_RIGHT;
// Axes
/** left trigger, -1 if not pressed, 1 if pressed **/
public static final int L_TRIGGER;
/** right trigger, -1 if not pressed, 1 if pressed **/
public static final int R_TRIGGER;
/** left stick vertical axis, -1 if up, 1 if down **/
public static final int L_STICK_VERTICAL_AXIS;
/** left stick horizontal axis, -1 if left, 1 if right **/
public static final int L_STICK_HORIZONTAL_AXIS;
/** right stick vertical axis, -1 if up, 1 if down **/
public static final int R_STICK_VERTICAL_AXIS;
/** right stick horizontal axis, -1 if left, 1 if right **/
public static final int R_STICK_HORIZONTAL_AXIS;
static {
if (SharedLibraryLoader.isWindows) {
A = 0;
B = 1;
X = 2;
Y = 3;
GUIDE = -1;
L_BUMPER = 4;
R_BUMPER = 5;
BACK = 6;
START = 7;
DPAD_UP = -1;
DPAD_DOWN = -1;
DPAD_LEFT = -1;
DPAD_RIGHT = -1;
L_TRIGGER = 4;
R_TRIGGER = 4;
L_STICK_VERTICAL_AXIS = 0;
L_STICK_HORIZONTAL_AXIS = 1;
R_STICK_VERTICAL_AXIS = 2;
R_STICK_HORIZONTAL_AXIS = 3;
} else if (SharedLibraryLoader.isLinux) {
A = 0;
B = 1;
X = 2;
Y = 3;
GUIDE = -1;
L_BUMPER = -1;
R_BUMPER = -1;
BACK = -1;
START = -1;
DPAD_UP = -1;
DPAD_DOWN = -1;
DPAD_LEFT = -1;
DPAD_RIGHT = -1;
L_TRIGGER = -1;
R_TRIGGER = -1;
L_STICK_VERTICAL_AXIS = -1;
L_STICK_HORIZONTAL_AXIS = -1;
R_STICK_VERTICAL_AXIS = -1;
R_STICK_HORIZONTAL_AXIS = -1;
} else if (SharedLibraryLoader.isMac) {
A = 11;
B = 12;
X = 13;
Y = 14;
GUIDE = 10;
L_BUMPER = 8;
R_BUMPER = 9;
BACK = 5;
START = 4;
DPAD_UP = 0;
DPAD_DOWN = 1;
DPAD_LEFT = 2;
DPAD_RIGHT = 3;
L_TRIGGER = 0;
R_TRIGGER = 1;
L_STICK_VERTICAL_AXIS = 3;
L_STICK_HORIZONTAL_AXIS = 2;
R_STICK_VERTICAL_AXIS = 5;
R_STICK_HORIZONTAL_AXIS = 4;
} else {
A = -1;
B = -1;
X = -1;
Y = -1;
GUIDE = -1;
L_BUMPER = -1;
R_BUMPER = -1;
L_TRIGGER = -1;
R_TRIGGER = -1;
BACK = -1;
START = -1;
DPAD_UP = -1;
DPAD_DOWN = -1;
DPAD_LEFT = -1;
DPAD_RIGHT = -1;
L_STICK_VERTICAL_AXIS = -1;
L_STICK_HORIZONTAL_AXIS = -1;
R_STICK_VERTICAL_AXIS = -1;
R_STICK_HORIZONTAL_AXIS = -1;
}
}
/** @return whether the {@link Controller} is an Xbox controller
*/
public static boolean isXboxController(Controller controller) {
return controller.getName().contains("Xbox");
}
}
} |
package com.pqbyte.coherence;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.ScreenAdapter;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Button;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
public class WinnerScreen extends ScreenAdapter {
private Stage stage;
private Coherence game;
public WinnerScreen(Coherence game) {
this.game = game;
Skin skin = new Skin(Gdx.files.internal("skin/uiskin.json"));
Button restartButton = createRestartButton(skin);
Button exitButton = createExitButton(skin);
Button menuButton = createMenuButton(skin);
Label titleLabel = createTitleLabel(skin);
stage = new Stage();
stage.addActor(restartButton);
stage.addActor(exitButton);
stage.addActor(menuButton);
stage.addActor(titleLabel);
Gdx.input.setInputProcessor(stage);
}
@Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.draw();
}
@Override
public void dispose() {
stage.dispose();
}
private Label createTitleLabel(Skin skin) {
Label label = new Label("GAME IS OVER", skin);
// Double font size
label.setSize(label.getWidth() * 2, label.getHeight());
label.setFontScale(2);
int width = Gdx.graphics.getWidth();
int height = Gdx.graphics.getHeight();
label.setPosition(
(width - label.getWidth()) / 2,
(height - label.getHeight()) / 2 + height / 4
);
return label;
}
private Button createRestartButton(Skin skin) {
TextButton button = new TextButton("RESTART GAME", skin, "default");
int buttonWidth = 300;
int buttonHeight = 60;
button.setWidth(buttonWidth);
button.setHeight(buttonHeight);
int width = Gdx.graphics.getWidth();
int height = Gdx.graphics.getHeight();
button.setPosition(
(width - buttonWidth) / 2,
(height - buttonHeight) / 2 - height / 4
);
button.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float xPos, float yPos) {
game.setScreen(new GameScreen(game));
dispose();
}
});
return button;
}
private Button createExitButton(Skin skin) {
TextButton button = new TextButton("EXIT THE GAME", skin, "default");
int buttonWidth = 300;
int buttonHeight = 60;
button.setWidth(buttonWidth);
button.setHeight(buttonHeight);
int width = Gdx.graphics.getWidth();
int height = Gdx.graphics.getHeight();
button.setPosition(
(width - buttonWidth) / 2,
(height - buttonHeight) / 2 - height / 3
);
button.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float xPos, float yPos) {
Gdx.app.exit();
dispose();
}
});
return button;
}
private Button createMenuButton(Skin skin) {
TextButton button = new TextButton("RETURN TO MAIN MENU", skin, "default");
int buttonWidth = 300;
int buttonHeight = 60;
button.setWidth(buttonWidth);
button.setHeight(buttonHeight);
int width = Gdx.graphics.getWidth();
int height = Gdx.graphics.getHeight();
button.setPosition(
(width - buttonWidth) / 2,
(height - buttonHeight) / 2 - height / 6
);
button.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float xPos, float yPos) {
game.setScreen(new MenuScreen(game));
dispose();
}
});
return button;
}
} |
package com.tacktic.inbudget;
import com.badlogic.gdx.graphics.Color;
import java.math.BigDecimal;
public class ResultScreen extends BaseScreen {
private final BigDecimal budget;
private final BigDecimal totalPrice;
private final BigDecimal percentage;
public ResultScreen(InBudget game, BigDecimal budget, BigDecimal totalPrice) {
super(game);
this.budget = budget;
this.totalPrice = totalPrice;
this.percentage = totalPrice.divide(budget, 3, BigDecimal.ROUND_HALF_UP);
}
@Override
public void renderBatch() {
drawResultBackground();
write("1", Color.WHITE, 3, VIEWPORT_WIDTH/2 + 100, VIEWPORT_HEIGHT - 170);
write("$" + String.valueOf(budget), Color.DARK_GRAY, 2, VIEWPORT_WIDTH/2 + 100, VIEWPORT_HEIGHT - 250);
write("$" + totalPrice.toString(), Color.WHITE, 2, VIEWPORT_WIDTH/2 + 100, VIEWPORT_HEIGHT - 320);
write("" + percentage.movePointRight(2) + "%", Color.WHITE, 2, VIEWPORT_WIDTH/2 + 100, VIEWPORT_HEIGHT - 400);
}
@Override
public void renderActions() {
}
@Override
public void resize(int width, int height) {
}
@Override
public void show() {
}
@Override
public void hide() {
}
@Override
public void pause() {
}
@Override
public void resume() {
}
@Override
public void dispose() {
}
} |
package bisq.core.dao;
import bisq.core.btc.exceptions.TransactionVerificationException;
import bisq.core.btc.exceptions.WalletException;
import bisq.core.dao.governance.ballot.BallotListPresentation;
import bisq.core.dao.governance.ballot.BallotListService;
import bisq.core.dao.governance.blindvote.BlindVoteConsensus;
import bisq.core.dao.governance.blindvote.MyBlindVoteListService;
import bisq.core.dao.governance.bond.Bond;
import bisq.core.dao.governance.bond.lockup.LockupReason;
import bisq.core.dao.governance.bond.lockup.LockupTxService;
import bisq.core.dao.governance.bond.reputation.BondedReputationRepository;
import bisq.core.dao.governance.bond.reputation.MyBondedReputation;
import bisq.core.dao.governance.bond.reputation.MyBondedReputationRepository;
import bisq.core.dao.governance.bond.role.BondedRole;
import bisq.core.dao.governance.bond.role.BondedRolesRepository;
import bisq.core.dao.governance.bond.unlock.UnlockTxService;
import bisq.core.dao.governance.myvote.MyVote;
import bisq.core.dao.governance.myvote.MyVoteListService;
import bisq.core.dao.governance.param.Param;
import bisq.core.dao.governance.period.PeriodService;
import bisq.core.dao.governance.proposal.MyProposalListService;
import bisq.core.dao.governance.proposal.ProposalConsensus;
import bisq.core.dao.governance.proposal.ProposalListPresentation;
import bisq.core.dao.governance.proposal.ProposalService;
import bisq.core.dao.governance.proposal.ProposalValidationException;
import bisq.core.dao.governance.proposal.ProposalWithTransaction;
import bisq.core.dao.governance.proposal.TxException;
import bisq.core.dao.governance.proposal.compensation.CompensationConsensus;
import bisq.core.dao.governance.proposal.compensation.CompensationProposalFactory;
import bisq.core.dao.governance.proposal.confiscatebond.ConfiscateBondProposalFactory;
import bisq.core.dao.governance.proposal.generic.GenericProposalFactory;
import bisq.core.dao.governance.proposal.param.ChangeParamProposalFactory;
import bisq.core.dao.governance.proposal.reimbursement.ReimbursementConsensus;
import bisq.core.dao.governance.proposal.reimbursement.ReimbursementProposalFactory;
import bisq.core.dao.governance.proposal.removeAsset.RemoveAssetProposalFactory;
import bisq.core.dao.governance.proposal.role.RoleProposalFactory;
import bisq.core.dao.state.DaoStateListener;
import bisq.core.dao.state.DaoStateService;
import bisq.core.dao.state.model.blockchain.BaseTx;
import bisq.core.dao.state.model.blockchain.BaseTxOutput;
import bisq.core.dao.state.model.blockchain.Block;
import bisq.core.dao.state.model.blockchain.Tx;
import bisq.core.dao.state.model.blockchain.TxOutput;
import bisq.core.dao.state.model.blockchain.TxType;
import bisq.core.dao.state.model.governance.Ballot;
import bisq.core.dao.state.model.governance.BondedRoleType;
import bisq.core.dao.state.model.governance.Cycle;
import bisq.core.dao.state.model.governance.DaoPhase;
import bisq.core.dao.state.model.governance.IssuanceType;
import bisq.core.dao.state.model.governance.Proposal;
import bisq.core.dao.state.model.governance.Role;
import bisq.core.dao.state.model.governance.RoleProposal;
import bisq.core.dao.state.model.governance.Vote;
import bisq.core.dao.state.storage.DaoStateStorageService;
import bisq.asset.Asset;
import bisq.common.config.Config;
import bisq.common.handlers.ErrorMessageHandler;
import bisq.common.handlers.ExceptionHandler;
import bisq.common.handlers.ResultHandler;
import bisq.common.util.Tuple2;
import org.bitcoinj.core.Coin;
import org.bitcoinj.core.InsufficientMoneyException;
import org.bitcoinj.core.Transaction;
import javax.inject.Inject;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.ReadOnlyObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import java.io.File;
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 java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkArgument;
/**
* Provides a facade to interact with the Dao domain. Hides complexity and domain details to clients (e.g. UI or APIs)
* by providing a reduced API and/or aggregating subroutines.
*/
@Slf4j
public class DaoFacade implements DaoSetupService {
private final ProposalListPresentation proposalListPresentation;
private final ProposalService proposalService;
private final BallotListService ballotListService;
private final BallotListPresentation ballotListPresentation;
private final MyProposalListService myProposalListService;
private final DaoStateService daoStateService;
private final PeriodService periodService;
private final MyBlindVoteListService myBlindVoteListService;
private final MyVoteListService myVoteListService;
private final CompensationProposalFactory compensationProposalFactory;
private final ReimbursementProposalFactory reimbursementProposalFactory;
private final ChangeParamProposalFactory changeParamProposalFactory;
private final ConfiscateBondProposalFactory confiscateBondProposalFactory;
private final RoleProposalFactory roleProposalFactory;
private final GenericProposalFactory genericProposalFactory;
private final RemoveAssetProposalFactory removeAssetProposalFactory;
private final BondedRolesRepository bondedRolesRepository;
private final BondedReputationRepository bondedReputationRepository;
private final MyBondedReputationRepository myBondedReputationRepository;
private final LockupTxService lockupTxService;
private final UnlockTxService unlockTxService;
private final DaoStateStorageService daoStateStorageService;
private final ObjectProperty<DaoPhase.Phase> phaseProperty = new SimpleObjectProperty<>(DaoPhase.Phase.UNDEFINED);
@Inject
public DaoFacade(MyProposalListService myProposalListService,
ProposalListPresentation proposalListPresentation,
ProposalService proposalService,
BallotListService ballotListService,
BallotListPresentation ballotListPresentation,
DaoStateService daoStateService,
PeriodService periodService,
MyBlindVoteListService myBlindVoteListService,
MyVoteListService myVoteListService,
CompensationProposalFactory compensationProposalFactory,
ReimbursementProposalFactory reimbursementProposalFactory,
ChangeParamProposalFactory changeParamProposalFactory,
ConfiscateBondProposalFactory confiscateBondProposalFactory,
RoleProposalFactory roleProposalFactory,
GenericProposalFactory genericProposalFactory,
RemoveAssetProposalFactory removeAssetProposalFactory,
BondedRolesRepository bondedRolesRepository,
BondedReputationRepository bondedReputationRepository,
MyBondedReputationRepository myBondedReputationRepository,
LockupTxService lockupTxService,
UnlockTxService unlockTxService,
DaoStateStorageService daoStateStorageService) {
this.proposalListPresentation = proposalListPresentation;
this.proposalService = proposalService;
this.ballotListService = ballotListService;
this.ballotListPresentation = ballotListPresentation;
this.myProposalListService = myProposalListService;
this.daoStateService = daoStateService;
this.periodService = periodService;
this.myBlindVoteListService = myBlindVoteListService;
this.myVoteListService = myVoteListService;
this.compensationProposalFactory = compensationProposalFactory;
this.reimbursementProposalFactory = reimbursementProposalFactory;
this.changeParamProposalFactory = changeParamProposalFactory;
this.confiscateBondProposalFactory = confiscateBondProposalFactory;
this.roleProposalFactory = roleProposalFactory;
this.genericProposalFactory = genericProposalFactory;
this.removeAssetProposalFactory = removeAssetProposalFactory;
this.bondedRolesRepository = bondedRolesRepository;
this.bondedReputationRepository = bondedReputationRepository;
this.myBondedReputationRepository = myBondedReputationRepository;
this.lockupTxService = lockupTxService;
this.unlockTxService = unlockTxService;
this.daoStateStorageService = daoStateStorageService;
}
// DaoSetupService
@Override
public void addListeners() {
daoStateService.addDaoStateListener(new DaoStateListener() {
@Override
public void onNewBlockHeight(int blockHeight) {
if (blockHeight > 0 && periodService.getCurrentCycle() != null)
periodService.getCurrentCycle().getPhaseForHeight(blockHeight).ifPresent(phaseProperty::set);
}
});
}
@Override
public void start() {
}
public void addBsqStateListener(DaoStateListener listener) {
daoStateService.addDaoStateListener(listener);
}
public void removeBsqStateListener(DaoStateListener listener) {
daoStateService.removeDaoStateListener(listener);
}
// Phase: Proposal
// Use case: Present lists
public ObservableList<Proposal> getActiveOrMyUnconfirmedProposals() {
return proposalListPresentation.getActiveOrMyUnconfirmedProposals();
}
// Use case: Create proposal
// Creation of Proposal and proposalTransaction
public ProposalWithTransaction getCompensationProposalWithTransaction(String name,
String link,
Coin requestedBsq)
throws ProposalValidationException, InsufficientMoneyException, TxException {
return compensationProposalFactory.createProposalWithTransaction(name,
link,
requestedBsq);
}
public ProposalWithTransaction getReimbursementProposalWithTransaction(String name,
String link,
Coin requestedBsq)
throws ProposalValidationException, InsufficientMoneyException, TxException {
return reimbursementProposalFactory.createProposalWithTransaction(name,
link,
requestedBsq);
}
public ProposalWithTransaction getParamProposalWithTransaction(String name,
String link,
Param param,
String paramValue)
throws ProposalValidationException, InsufficientMoneyException, TxException {
return changeParamProposalFactory.createProposalWithTransaction(name,
link,
param,
paramValue);
}
public ProposalWithTransaction getConfiscateBondProposalWithTransaction(String name,
String link,
String lockupTxId)
throws ProposalValidationException, InsufficientMoneyException, TxException {
return confiscateBondProposalFactory.createProposalWithTransaction(name,
link,
lockupTxId);
}
public ProposalWithTransaction getBondedRoleProposalWithTransaction(Role role)
throws ProposalValidationException, InsufficientMoneyException, TxException {
return roleProposalFactory.createProposalWithTransaction(role);
}
public ProposalWithTransaction getGenericProposalWithTransaction(String name,
String link)
throws ProposalValidationException, InsufficientMoneyException, TxException {
return genericProposalFactory.createProposalWithTransaction(name, link);
}
public ProposalWithTransaction getRemoveAssetProposalWithTransaction(String name,
String link,
Asset asset)
throws ProposalValidationException, InsufficientMoneyException, TxException {
return removeAssetProposalFactory.createProposalWithTransaction(name, link, asset);
}
public ObservableList<BondedRole> getBondedRoles() {
return bondedRolesRepository.getBonds();
}
public List<BondedRole> getAcceptedBondedRoles() {
return bondedRolesRepository.getAcceptedBonds();
}
// Show fee
public Coin getProposalFee(int chainHeight) {
return ProposalConsensus.getFee(daoStateService, chainHeight);
}
// Publish proposal tx, proposal payload and persist it to myProposalList
public void publishMyProposal(Proposal proposal, Transaction transaction, ResultHandler resultHandler,
ErrorMessageHandler errorMessageHandler) {
myProposalListService.publishTxAndPayload(proposal, transaction, resultHandler, errorMessageHandler);
}
// Check if it is my proposal
public boolean isMyProposal(Proposal proposal) {
return myProposalListService.isMine(proposal);
}
// Remove my proposal
public boolean removeMyProposal(Proposal proposal) {
return myProposalListService.remove(proposal);
}
// Phase: Blind Vote
// Use case: Present lists
public ObservableList<Ballot> getAllBallots() {
return ballotListPresentation.getAllBallots();
}
public List<Ballot> getAllValidBallots() {
return ballotListPresentation.getAllValidBallots();
}
public FilteredList<Ballot> getBallotsOfCycle() {
return ballotListPresentation.getBallotsOfCycle();
}
public Tuple2<Long, Long> getMeritAndStakeForProposal(String proposalTxId) {
return myVoteListService.getMeritAndStakeForProposal(proposalTxId, myBlindVoteListService);
}
public long getAvailableMerit() {
return myBlindVoteListService.getCurrentlyAvailableMerit();
}
public List<MyVote> getMyVoteListForCycle() {
return myVoteListService.getMyVoteListForCycle();
}
// Use case: Vote
// Vote on ballot
public void setVote(Ballot ballot, @Nullable Vote vote) {
ballotListService.setVote(ballot, vote);
}
// Use case: Create blindVote
// When creating blind vote we present fee
public Coin getBlindVoteFeeForCycle() {
return BlindVoteConsensus.getFee(daoStateService, daoStateService.getChainHeight());
}
public Tuple2<Coin, Integer> getBlindVoteMiningFeeAndTxSize(Coin stake)
throws WalletException, InsufficientMoneyException, TransactionVerificationException {
return myBlindVoteListService.getMiningFeeAndTxSize(stake);
}
// Publish blindVote tx and broadcast blindVote to p2p network and store to blindVoteList.
public void publishBlindVote(Coin stake, ResultHandler resultHandler, ExceptionHandler exceptionHandler) {
myBlindVoteListService.publishBlindVote(stake, resultHandler, exceptionHandler);
}
// Generic
// Use case: Presentation of phases
// Because last block in request and voting phases must not be used for making a tx as it will get confirmed in the
// next block which would be already the next phase we hide that last block to the user and add it to the break.
public int getFirstBlockOfPhaseForDisplay(int height, DaoPhase.Phase phase) {
int firstBlock = periodService.getFirstBlockOfPhase(height, phase);
switch (phase) {
case UNDEFINED:
break;
case PROPOSAL:
break;
case BREAK1:
firstBlock
break;
case BLIND_VOTE:
break;
case BREAK2:
firstBlock
break;
case VOTE_REVEAL:
break;
case BREAK3:
firstBlock
break;
case RESULT:
break;
}
return firstBlock;
}
public Map<Integer, Date> getBlockStartDateByCycleIndex() {
AtomicInteger index = new AtomicInteger();
Map<Integer, Date> map = new HashMap<>();
periodService.getCycles()
.forEach(cycle -> daoStateService.getBlockAtHeight(cycle.getHeightOfFirstBlock())
.ifPresent(block -> map.put(index.getAndIncrement(), new Date(block.getTime()))));
return map;
}
// Because last block in request and voting phases must not be used for making a tx as it will get confirmed in the
// next block which would be already the next phase we hide that last block to the user and add it to the break.
public int getLastBlockOfPhaseForDisplay(int height, DaoPhase.Phase phase) {
int lastBlock = periodService.getLastBlockOfPhase(height, phase);
switch (phase) {
case UNDEFINED:
break;
case PROPOSAL:
lastBlock
break;
case BREAK1:
break;
case BLIND_VOTE:
lastBlock
break;
case BREAK2:
break;
case VOTE_REVEAL:
lastBlock
break;
case BREAK3:
break;
case RESULT:
break;
}
return lastBlock;
}
// Because last block in request and voting phases must not be used for making a tx as it will get confirmed in the
// next block which would be already the next phase we hide that last block to the user and add it to the break.
public int getDurationForPhaseForDisplay(DaoPhase.Phase phase) {
int duration = periodService.getDurationForPhase(phase, daoStateService.getChainHeight());
switch (phase) {
case UNDEFINED:
break;
case PROPOSAL:
duration
break;
case BREAK1:
duration++;
break;
case BLIND_VOTE:
duration
break;
case BREAK2:
duration++;
break;
case VOTE_REVEAL:
duration
break;
case BREAK3:
duration++;
break;
case RESULT:
break;
}
return duration;
}
public int getCurrentCycleDuration() {
Cycle currentCycle = periodService.getCurrentCycle();
return currentCycle != null ? currentCycle.getDuration() : 0;
}
// listeners for phase change
public ReadOnlyObjectProperty<DaoPhase.Phase> phaseProperty() {
return phaseProperty;
}
public int getChainHeight() {
return daoStateService.getChainHeight();
}
public Optional<Block> getBlockAtChainHeight() {
return getBlockAtHeight(getChainHeight());
}
public Optional<Block> getBlockAtHeight(int chainHeight) {
return daoStateService.getBlockAtHeight(chainHeight);
}
// Use case: Bonding
public void publishLockupTx(Coin lockupAmount, int lockTime, LockupReason lockupReason, byte[] hash,
Consumer<String> resultHandler, ExceptionHandler exceptionHandler) {
lockupTxService.publishLockupTx(lockupAmount, lockTime, lockupReason, hash, resultHandler, exceptionHandler);
}
public Tuple2<Coin, Integer> getLockupTxMiningFeeAndTxSize(Coin lockupAmount,
int lockTime,
LockupReason lockupReason,
byte[] hash)
throws InsufficientMoneyException, IOException, TransactionVerificationException, WalletException {
return lockupTxService.getMiningFeeAndTxSize(lockupAmount, lockTime, lockupReason, hash);
}
public void publishUnlockTx(String lockupTxId, Consumer<String> resultHandler,
ExceptionHandler exceptionHandler) {
unlockTxService.publishUnlockTx(lockupTxId, resultHandler, exceptionHandler);
}
public Tuple2<Coin, Integer> getUnlockTxMiningFeeAndTxSize(String lockupTxId)
throws InsufficientMoneyException, TransactionVerificationException, WalletException {
return unlockTxService.getMiningFeeAndTxSize(lockupTxId);
}
public long getTotalLockupAmount() {
return daoStateService.getTotalLockupAmount();
}
public long getTotalAmountOfUnLockingTxOutputs() {
return daoStateService.getTotalAmountOfUnLockingTxOutputs();
}
public long getTotalAmountOfUnLockedTxOutputs() {
return daoStateService.getTotalAmountOfUnLockedTxOutputs();
}
public long getTotalAmountOfConfiscatedTxOutputs() {
return daoStateService.getTotalAmountOfConfiscatedTxOutputs();
}
public long getTotalAmountOfInvalidatedBsq() {
return daoStateService.getTotalAmountOfInvalidatedBsq();
}
// Contains burned fee and invalidated bsq due invalid txs
public long getTotalAmountOfBurntBsq() {
return daoStateService.getTotalAmountOfBurntBsq();
}
public List<Tx> getInvalidTxs() {
return daoStateService.getInvalidTxs();
}
public List<Tx> getIrregularTxs() {
return daoStateService.getIrregularTxs();
}
public long getTotalAmountOfUnspentTxOutputs() {
// Does not consider confiscated outputs (they stay as utxo)
return daoStateService.getUnspentTxOutputMap().values().stream().mapToLong(BaseTxOutput::getValue).sum();
}
public Optional<Integer> getLockTime(String txId) {
return daoStateService.getLockTime(txId);
}
public List<Bond> getAllBonds() {
List<Bond> bonds = new ArrayList<>(bondedReputationRepository.getBonds());
bonds.addAll(bondedRolesRepository.getBonds());
return bonds;
}
public List<Bond> getAllActiveBonds() {
List<Bond> bonds = new ArrayList<>(bondedReputationRepository.getActiveBonds());
bonds.addAll(bondedRolesRepository.getActiveBonds());
return bonds;
}
public ObservableList<MyBondedReputation> getMyBondedReputations() {
return myBondedReputationRepository.getMyBondedReputations();
}
// Use case: Present transaction related state
public Optional<Tx> getTx(String txId) {
return daoStateService.getTx(txId);
}
public int getGenesisBlockHeight() {
return daoStateService.getGenesisBlockHeight();
}
public String getGenesisTxId() {
return daoStateService.getGenesisTxId();
}
public Coin getGenesisTotalSupply() {
return daoStateService.getGenesisTotalSupply();
}
public int getNumIssuanceTransactions(IssuanceType issuanceType) {
return daoStateService.getIssuanceSet(issuanceType).size();
}
public Set<Tx> getBurntFeeTxs() {
return daoStateService.getBurntFeeTxs();
}
public Set<TxOutput> getUnspentTxOutputs() {
return daoStateService.getUnspentTxOutputs();
}
public int getNumTxs() {
return daoStateService.getNumTxs();
}
public Optional<TxOutput> getLockupTxOutput(String txId) {
return daoStateService.getLockupTxOutput(txId);
}
public long getTotalBurntFee() {
return daoStateService.getTotalBurntFee();
}
public long getTotalIssuedAmount(IssuanceType issuanceType) {
return daoStateService.getTotalIssuedAmount(issuanceType);
}
public long getBlockTime(int issuanceBlockHeight) {
return daoStateService.getBlockTime(issuanceBlockHeight);
}
public int getIssuanceBlockHeight(String txId) {
return daoStateService.getIssuanceBlockHeight(txId);
}
public boolean isIssuanceTx(String txId, IssuanceType issuanceType) {
return daoStateService.isIssuanceTx(txId, issuanceType);
}
public boolean hasTxBurntFee(String hashAsString) {
return daoStateService.hasTxBurntFee(hashAsString);
}
public Optional<TxType> getOptionalTxType(String txId) {
return daoStateService.getOptionalTxType(txId);
}
public TxType getTxType(String txId) {
return daoStateService.getTx(txId).map(Tx::getTxType).orElse(TxType.UNDEFINED_TX_TYPE);
}
public boolean isInPhaseButNotLastBlock(DaoPhase.Phase phase) {
return periodService.isInPhaseButNotLastBlock(phase);
}
public boolean isTxInCorrectCycle(int txHeight, int chainHeight) {
return periodService.isTxInCorrectCycle(txHeight, chainHeight);
}
public boolean isTxInCorrectCycle(String txId, int chainHeight) {
return periodService.isTxInCorrectCycle(txId, chainHeight);
}
public Coin getMinCompensationRequestAmount() {
return CompensationConsensus.getMinCompensationRequestAmount(daoStateService, periodService.getChainHeight());
}
public Coin getMaxCompensationRequestAmount() {
return CompensationConsensus.getMaxCompensationRequestAmount(daoStateService, periodService.getChainHeight());
}
public Coin getMinReimbursementRequestAmount() {
return ReimbursementConsensus.getMinReimbursementRequestAmount(daoStateService, periodService.getChainHeight());
}
public Coin getMaxReimbursementRequestAmount() {
return ReimbursementConsensus.getMaxReimbursementRequestAmount(daoStateService, periodService.getChainHeight());
}
public String getParamValue(Param param) {
return getParamValue(param, periodService.getChainHeight());
}
public String getParamValue(Param param, int blockHeight) {
return daoStateService.getParamValue(param, blockHeight);
}
public void resyncDaoStateFromGenesis(Runnable resultHandler) {
daoStateStorageService.resyncDaoStateFromGenesis(resultHandler);
}
public void resyncDaoStateFromResources(File storageDir) throws IOException {
daoStateStorageService.resyncDaoStateFromResources(storageDir);
}
public boolean isMyRole(Role role) {
return bondedRolesRepository.isMyRole(role);
}
public Optional<Bond> getBondByLockupTxId(String lockupTxId) {
return getAllBonds().stream().filter(e -> lockupTxId.equals(e.getLockupTxId())).findAny();
}
public double getRequiredThreshold(Proposal proposal) {
return proposalService.getRequiredThreshold(proposal);
}
public Coin getRequiredQuorum(Proposal proposal) {
return proposalService.getRequiredQuorum(proposal);
}
public long getRequiredBond(Optional<RoleProposal> roleProposal) {
Optional<BondedRoleType> bondedRoleType = roleProposal.map(e -> e.getRole().getBondedRoleType());
checkArgument(bondedRoleType.isPresent(), "bondedRoleType must be present");
int height = roleProposal.flatMap(p -> daoStateService.getTx(p.getTxId()))
.map(BaseTx::getBlockHeight)
.orElse(daoStateService.getChainHeight());
long requiredBondUnit = roleProposal.map(RoleProposal::getRequiredBondUnit)
.orElse(bondedRoleType.get().getRequiredBondUnit());
long baseFactor = daoStateService.getParamValueAsCoin(Param.BONDED_ROLE_FACTOR, height).value;
return requiredBondUnit * baseFactor;
}
public long getRequiredBond(RoleProposal roleProposal) {
return getRequiredBond(Optional.of(roleProposal));
}
public long getRequiredBond(BondedRoleType bondedRoleType) {
int height = daoStateService.getChainHeight();
long requiredBondUnit = bondedRoleType.getRequiredBondUnit();
long baseFactor = daoStateService.getParamValueAsCoin(Param.BONDED_ROLE_FACTOR, height).value;
return requiredBondUnit * baseFactor;
}
public Set<String> getAllPastParamValues(Param param) {
Set<String> set = new HashSet<>();
periodService.getCycles().forEach(cycle -> {
set.add(getParamValue(param, cycle.getHeightOfFirstBlock()));
});
return set;
}
public Set<String> getAllDonationAddresses() {
// We support any of the past addresses as well as in case the peer has not enabled the DAO or is out of sync we
// do not want to break validation.
Set<String> allPastParamValues = getAllPastParamValues(Param.RECIPIENT_BTC_ADDRESS);
// If Dao is deactivated we need to add the default address as getAllPastParamValues will not return us any.
if (allPastParamValues.isEmpty()) {
allPastParamValues.add(Param.RECIPIENT_BTC_ADDRESS.getDefaultValue());
}
if (Config.baseCurrencyNetwork().isMainnet()) {
// If Dao is deactivated we need to add the past addresses used as well.
// This list need to be updated once a new address gets defined.
allPastParamValues.add("3EtUWqsGThPtjwUczw27YCo6EWvQdaPUyp"); // burning man 2019
allPastParamValues.add("3A8Zc1XioE2HRzYfbb5P8iemCS72M6vRJV"); // burningman2
allPastParamValues.add("34VLFgtFKAtwTdZ5rengTT2g2zC99sWQLC"); // burningman3 (https://github.com/bisq-network/roles/issues/80#issuecomment-723577776)
}
return allPastParamValues;
}
} |
package erica.beakon;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.Profile;
import com.facebook.ProfileTracker;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import erica.beakon.Adapters.FirebaseHandler;
public class LoginPage extends Activity {
private CallbackManager callbackManager;
String databaseURL = "https://beakon-5fa96.firebaseio.com/";
private FirebaseDatabase db = FirebaseDatabase.getInstance();
private DatabaseReference ref = db.getReferenceFromUrl(databaseURL);
FirebaseHandler firebaseHandler = new FirebaseHandler(db,ref);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.login_fragment);
final Intent intent = new Intent(this, MainActivity.class);
if (Profile.getCurrentProfile() != null) {
startActivity(intent);
}
LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions("email");
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
private ProfileTracker profileTracker;
@Override
public void onSuccess(LoginResult loginResult) {
if (Profile.getCurrentProfile() == null){
profileTracker = new ProfileTracker() {
@Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {
profileTracker.stopTracking();
Profile.setCurrentProfile(currentProfile);
}
};
startActivity(intent);
} else {
firebaseHandler.getUser(Profile.getCurrentProfile().getId(), new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
startActivity(intent);
} else {
firebaseHandler.addUser(Profile.getCurrentProfile().getId(),Profile.getCurrentProfile().getFirstName());
startActivity(intent);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Log.d("FacebookLogin", "onSuccess" + loginResult);
}
@Override
public void onCancel() {
Log.d("FacebookLogin", "Login attempt cancelled");
}
@Override
public void onError(FacebookException e) {
Log.d("FacebookLogin", e.getMessage());
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
}
public String getCurrentUserID(){
return Profile.getCurrentProfile().getId();
}
} |
package lucee.runtime.tag;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.TimeZone;
import lucee.commons.io.log.Log;
import lucee.commons.lang.ClassException;
import lucee.commons.lang.StringUtil;
import lucee.loader.engine.CFMLEngine;
import lucee.runtime.PageContext;
import lucee.runtime.PageContextImpl;
import lucee.runtime.PageSource;
import lucee.runtime.cache.tag.CacheHandler;
import lucee.runtime.cache.tag.CacheHandlerCollectionImpl;
import lucee.runtime.cache.tag.CacheHandlerPro;
import lucee.runtime.cache.tag.CacheItem;
import lucee.runtime.cache.tag.query.QueryResultCacheItem;
import lucee.runtime.config.Config;
import lucee.runtime.config.ConfigImpl;
import lucee.runtime.config.ConfigWeb;
import lucee.runtime.config.ConfigWebImpl;
import lucee.runtime.config.Constants;
import lucee.runtime.db.DataSource;
import lucee.runtime.db.DataSourceImpl;
import lucee.runtime.db.DatasourceConnection;
import lucee.runtime.db.DatasourceManagerImpl;
import lucee.runtime.db.HSQLDBHandler;
import lucee.runtime.db.SQL;
import lucee.runtime.db.SQLImpl;
import lucee.runtime.db.SQLItem;
import lucee.runtime.debug.DebuggerImpl;
import lucee.runtime.exp.ApplicationException;
import lucee.runtime.exp.DatabaseException;
import lucee.runtime.exp.PageException;
import lucee.runtime.ext.tag.BodyTagTryCatchFinallyImpl;
import lucee.runtime.functions.displayFormatting.DecimalFormat;
import lucee.runtime.listener.AppListenerUtil;
import lucee.runtime.op.Caster;
import lucee.runtime.op.Decision;
import lucee.runtime.orm.ORMSession;
import lucee.runtime.orm.ORMUtil;
import lucee.runtime.tag.util.QueryParamConverter;
import lucee.runtime.type.Array;
import lucee.runtime.type.ArrayImpl;
import lucee.runtime.type.Collection;
import lucee.runtime.type.Collection.Key;
import lucee.runtime.type.KeyImpl;
import lucee.runtime.type.QueryColumn;
import lucee.runtime.type.QueryImpl;
import lucee.runtime.type.Struct;
import lucee.runtime.type.StructImpl;
import lucee.runtime.type.dt.DateTime;
import lucee.runtime.type.dt.TimeSpan;
import lucee.runtime.type.dt.TimeSpanImpl;
import lucee.runtime.type.query.QueryArray;
import lucee.runtime.type.query.QueryResult;
import lucee.runtime.type.query.QueryStruct;
import lucee.runtime.type.query.SimpleQuery;
import lucee.runtime.type.scope.Argument;
import lucee.runtime.type.util.CollectionUtil;
import lucee.runtime.type.util.KeyConstants;
import lucee.runtime.type.util.ListUtil;
import lucee.runtime.util.PageContextUtil;
import org.osgi.framework.BundleException;
/**
* Passes SQL statements to a data source. Not limited to queries.
**/
public final class Query extends BodyTagTryCatchFinallyImpl {
private static final Collection.Key SQL_PARAMETERS = KeyImpl.intern("sqlparameters");
private static final Collection.Key CFQUERY = KeyImpl.intern("cfquery");
private static final Collection.Key GENERATEDKEY = KeyImpl.intern("generatedKey");
private static final Collection.Key MAX_RESULTS = KeyImpl.intern("maxResults");
private static final Collection.Key TIMEOUT = KeyConstants._timeout;
private static final int RETURN_TYPE_UNDEFINED = 0;
private static final int RETURN_TYPE_QUERY = 1;
private static final int RETURN_TYPE_ARRAY = 2;
private static final int RETURN_TYPE_STRUCT = 3;
public static final int RETURN_TYPE_STORED_PROC = 4;
/** If specified, password overrides the password value specified in the data source setup. */
private String password;
/** The name of the data source from which this query should retrieve data. */
private DataSource datasource = null;
/**
* The maximum number of milliseconds for the query to execute before returning an error indicating that the query has timed-out. This attribute is not
* supported by most ODBC drivers. timeout is supported by the SQL Server 6.x or above driver. The minimum and maximum allowable values vary, depending on
* the driver.
*/
private TimeSpan timeout = null;
/** This is the age of which the query data can be */
private Object cachedWithin;
/**
* Specifies the maximum number of rows to fetch at a time from the server. The range is 1, default to 100. This parameter applies to ORACLE native database
* drivers and to ODBC drivers. Certain ODBC drivers may dynamically reduce the block factor at runtime.
*/
private int blockfactor = -1;
/** The database driver type. */
private String dbtype;
/**
* Used for debugging queries. Specifying this attribute causes the SQL statement submitted to the data source and the number of records returned from the
* query to be returned.
*/
private boolean debug = true;
/* This is specific to JTags, and allows you to give the cache a specific name */
// private String cachename;
/** Specifies the maximum number of rows to return in the record set. */
private int maxrows = -1;
/** If specified, username overrides the username value specified in the data source setup. */
private String username;
private DateTime cachedAfter;
/**
* The name query. Must begin with a letter and may consist of letters, numbers, and the underscore character, spaces are not allowed. The query name is
* used later in the page to reference the query's record set.
*/
private String name;
private String result = null;
// private static HSQLDBHandler hsql=new HSQLDBHandler();
private boolean orgPSQ;
private boolean hasChangedPSQ;
ArrayList<SQLItem> items = new ArrayList<SQLItem>();
private boolean unique;
private Struct ormoptions;
private int returntype = RETURN_TYPE_UNDEFINED;
private TimeZone timezone;
private TimeZone tmpTZ;
private boolean lazy;
private Object params;
private int nestingLevel = 0;
private boolean setReturnVariable = false;
private Object rtn;
private Key columnName;
private boolean literalTimestampWithTSOffset;
private boolean previousLiteralTimestampWithTSOffset;
private String[] tags = null;
@Override
public void release() {
super.release();
items.clear();
password = null;
datasource = null;
timeout = null;
cachedWithin = null;
cachedAfter = null;
// cachename="";
blockfactor = -1;
dbtype = null;
debug = true;
maxrows = -1;
username = null;
name = "";
result = null;
orgPSQ = false;
hasChangedPSQ = false;
unique = false;
ormoptions = null;
returntype = RETURN_TYPE_UNDEFINED;
timezone = null;
tmpTZ = null;
lazy = false;
params = null;
nestingLevel = 0;
rtn = null;
setReturnVariable = false;
columnName = null;
literalTimestampWithTSOffset = false;
previousLiteralTimestampWithTSOffset = false;
tags = null;
}
public void setTags(Object oTags) throws PageException {
if(StringUtil.isEmpty(oTags))
return;
// to Array
Array arr;
if(Decision.isArray(oTags))
arr = Caster.toArray(oTags);
else
arr = ListUtil.listToArrayRemoveEmpty(Caster.toString(oTags), ',');
// to String[]
Iterator<Object> it = arr.valueIterator();
List<String> list = new ArrayList<String>();
String str;
while(it.hasNext()) {
str = Caster.toString(it.next());
if(!StringUtil.isEmpty(str))
list.add(str);
}
tags = list.toArray(new String[list.size()]);
}
public void setOrmoptions(Struct ormoptions) {
this.ormoptions = ormoptions;
}
public void setReturntype(String strReturntype) throws ApplicationException {
if(StringUtil.isEmpty(strReturntype))
return;
strReturntype = strReturntype.toLowerCase().trim();
if(strReturntype.equals("query"))
returntype = RETURN_TYPE_QUERY;
// mail.setType(lucee.runtime.mail.Mail.TYPE_TEXT);
else if(strReturntype.equals("struct"))
returntype = RETURN_TYPE_STRUCT;
else if(strReturntype.equals("array") || strReturntype.equals("array_of_struct") || strReturntype.equals("array-of-struct")
|| strReturntype.equals("arrayofstruct") || strReturntype.equals("array_of_entity") || strReturntype.equals("array-of-entity")
|| strReturntype.equals("arrayofentities") || strReturntype.equals("array_of_entities") || strReturntype.equals("array-of-entities")
|| strReturntype.equals("arrayofentities"))
returntype = RETURN_TYPE_ARRAY;
else
throw new ApplicationException("attribute returntype of tag query has an invalid value",
"valid values are [query,array] but value is now [" + strReturntype + "]");
}
public void setUnique(boolean unique) {
this.unique = unique;
}
/**
* @param result
* the result to set
*/
public void setResult(String result) {
this.result = result;
}
/**
* @param psq
* set preserver single quote
*/
public void setPsq(boolean psq) {
orgPSQ = pageContext.getPsq();
if(orgPSQ != psq) {
pageContext.setPsq(psq);
hasChangedPSQ = true;
}
}
/**
* set the value password If specified, password overrides the password value specified in the data source setup.
*
* @param password
* value to set
**/
public void setPassword(String password) {
this.password = password;
}
/**
* set the value datasource The name of the data source from which this query should retrieve data.
*
* @param datasource
* value to set
* @throws ClassException
* @throws BundleException
**/
public void setDatasource(Object datasource) throws PageException, ClassException, BundleException {
if(Decision.isStruct(datasource)) {
this.datasource = AppListenerUtil.toDataSource(pageContext.getConfig(), "__temp__", Caster.toStruct(datasource),
pageContext.getConfig().getLog("application"));
}
else if(Decision.isString(datasource)) {
this.datasource = pageContext.getDataSource(Caster.toString(datasource));
}
else {
throw new ApplicationException("attribute [datasource] must be datasource name or a datasource definition(struct)");
}
}
/**
* set the value timeout The maximum number of milliseconds for the query to execute before returning an error indicating that the query has timed-out. This
* attribute is not supported by most ODBC drivers. timeout is supported by the SQL Server 6.x or above driver. The minimum and maximum allowable values
* vary, depending on the driver.
*
* @param timeout
* value to set
* @throws PageException
**/
public void setTimeout(Object timeout) throws PageException {
if(timeout instanceof TimeSpan)
this.timeout = (TimeSpan)timeout;
// seconds
else {
int i = Caster.toIntValue(timeout);
if(i < 0)
throw new ApplicationException("invalid value [" + i + "] for attribute timeout, value must be a positive integer greater or equal than 0");
this.timeout = new TimeSpanImpl(0, 0, 0, i);
}
}
/**
* set the value cachedafter This is the age of which the query data can be
*
* @param cachedafter
* value to set
**/
public void setCachedafter(DateTime cachedafter) {
this.cachedAfter = cachedafter;
}
/**
* set the value cachename This is specific to JTags, and allows you to give the cache a specific name
*
* @param cachename
* value to set
**/
public void setCachename(String cachename) {
// DeprecatedUtil.tagAttribute(pageContext,"query", "cachename");
// this.cachename=cachename;
}
public void setColumnkey(String columnKey) {
if(StringUtil.isEmpty(columnKey, true))
return;
this.columnName = KeyImpl.init(columnKey);
}
public void setCachedwithin(Object cachedwithin) {
if(StringUtil.isEmpty(cachedwithin))
return;
this.cachedWithin = cachedwithin;
}
public void setLazy(boolean lazy) {
this.lazy = lazy;
}
/**
* set the value providerdsn Data source name for the COM provider, OLE-DB only.
*
* @param providerdsn
* value to set
* @throws ApplicationException
**/
public void setProviderdsn(String providerdsn) throws ApplicationException {
// DeprecatedUtil.tagAttribute(pageContext,"Query", "providerdsn");
}
/**
* set the value connectstring
*
* @param connectstring
* value to set
* @throws ApplicationException
**/
public void setConnectstring(String connectstring) throws ApplicationException {
// DeprecatedUtil.tagAttribute(pageContext,"Query", "connectstring");
}
public void setTimezone(TimeZone tz) {
if(tz == null)
return;
this.timezone = tz;
}
/**
* set the value blockfactor Specifies the maximum number of rows to fetch at a time from the server. The range is 1, default to 100. This parameter applies
* to ORACLE native database drivers and to ODBC drivers. Certain ODBC drivers may dynamically reduce the block factor at runtime.
*
* @param blockfactor
* value to set
**/
public void setBlockfactor(double blockfactor) {
this.blockfactor = (int)blockfactor;
}
/**
* set the value dbtype The database driver type.
*
* @param dbtype
* value to set
**/
public void setDbtype(String dbtype) {
this.dbtype = dbtype.toLowerCase();
}
/**
* set the value debug Used for debugging queries. Specifying this attribute causes the SQL statement submitted to the data source and the number of records
* returned from the query to be returned.
*
* @param debug
* value to set
**/
public void setDebug(boolean debug) {
this.debug = debug;
}
/**
* set the value dbname The database name, Sybase System 11 driver and SQLOLEDB provider only. If specified, dbName overrides the default database specified
* in the data source.
*
* @param dbname
* value to set
* @throws ApplicationException
**/
public void setDbname(String dbname) {
// DeprecatedUtil.tagAttribute(pageContext,"Query", "dbname");
}
/**
* set the value maxrows Specifies the maximum number of rows to return in the record set.
*
* @param maxrows
* value to set
**/
public void setMaxrows(double maxrows) {
this.maxrows = (int)maxrows;
}
/**
* set the value username If specified, username overrides the username value specified in the data source setup.
*
* @param username
* value to set
**/
public void setUsername(String username) {
if(!StringUtil.isEmpty(username))
this.username = username;
}
/**
* set the value provider COM provider, OLE-DB only.
*
* @param provider
* value to set
* @throws ApplicationException
**/
public void setProvider(String provider) {
// DeprecatedUtil.tagAttribute(pageContext,"Query", "provider");
}
/**
* set the value dbserver For native database drivers and the SQLOLEDB provider, specifies the name of the database server computer. If specified, dbServer
* overrides the server specified in the data source.
*
* @param dbserver
* value to set
* @throws ApplicationException
**/
public void setDbserver(String dbserver) {
// DeprecatedUtil.tagAttribute(pageContext,"Query", "dbserver");
}
/**
* set the value name The name query. Must begin with a letter and may consist of letters, numbers, and the underscore character, spaces are not allowed.
* The query name is used later in the page to reference the query's record set.
*
* @param name
* value to set
**/
public void setName(String name) {
this.name = name;
}
public String getName() {
return name == null ? "query" : name;
}
/**
* @param item
*/
public void setParam(SQLItem item) {
items.add(item);
}
public void setParams(Object params) {
this.params = params;
}
public void setNestinglevel(double nestingLevel) {
this.nestingLevel = (int)nestingLevel;
}
@Override
public int doStartTag() throws PageException {
// default datasource
if(datasource == null && (dbtype == null || !dbtype.equals("query"))) {
Object obj = pageContext.getApplicationContext().getDefDataSource();
if(StringUtil.isEmpty(obj)) {
boolean isCFML = pageContext.getRequestDialect() == CFMLEngine.DIALECT_CFML;
throw new ApplicationException(
"attribute [datasource] is required when attribute [dbtype] is not [query] and no default datasource is defined",
"you can define a default datasource as attribute [defaultdatasource] of the tag "
+ (isCFML ? Constants.CFML_APPLICATION_TAG_NAME : Constants.LUCEE_APPLICATION_TAG_NAME) + " or as data member of the "
+ (isCFML ? Constants.CFML_APPLICATION_EVENT_HANDLER : Constants.LUCEE_APPLICATION_EVENT_HANDLER)
+ " (this.defaultdatasource=\"mydatasource\";)");
}
datasource = obj instanceof DataSource ? (DataSource)obj : pageContext.getDataSource(Caster.toString(obj));
}
// timeout
if(datasource instanceof DataSourceImpl && ((DataSourceImpl)datasource).getAlwaysSetTimeout()) {
TimeSpan remaining = PageContextUtil.remainingTime(pageContext, true);
if(this.timeout == null || ((int)this.timeout.getSeconds()) <= 0 || timeout.getSeconds() > remaining.getSeconds()) { // not set
this.timeout = remaining;
}
}
// timezone
if(timezone != null || (datasource != null && (timezone = datasource.getTimeZone()) != null)) {
tmpTZ = pageContext.getTimeZone();
pageContext.setTimeZone(timezone);
}
PageContextImpl pci = ((PageContextImpl)pageContext);
// cache within
if(StringUtil.isEmpty(cachedWithin)) {
Object tmp = (pageContext).getCachedWithin(ConfigWeb.CACHEDWITHIN_QUERY);
if(tmp != null)
setCachedwithin(tmp);
}
// literal timestamp with TSOffset
if(datasource instanceof DataSourceImpl)
literalTimestampWithTSOffset = ((DataSourceImpl)datasource).getLiteralTimestampWithTSOffset();
else
literalTimestampWithTSOffset = false;
previousLiteralTimestampWithTSOffset = pci.getTimestampWithTSOffset();
pci.setTimestampWithTSOffset(literalTimestampWithTSOffset);
return EVAL_BODY_BUFFERED;
}
@Override
public int doEndTag() throws PageException {
if(hasChangedPSQ)
pageContext.setPsq(orgPSQ);
String strSQL = bodyContent.getString().trim();
if(strSQL.isEmpty())
throw new DatabaseException("no sql string defined, inside query tag", null, null, null);
try {
// cannot use attribute params and queryparam tag
if(!items.isEmpty() && params != null)
throw new DatabaseException("you cannot use the attribute params and sub tags queryparam at the same time", null, null, null);
// create SQL
SQL sql;
if(params != null) {
if(params instanceof Argument)
sql = QueryParamConverter.convert(strSQL, (Argument)params);
else if(Decision.isArray(params))
sql = QueryParamConverter.convert(strSQL, Caster.toArray(params));
else if(Decision.isStruct(params))
sql = QueryParamConverter.convert(strSQL, Caster.toStruct(params));
else
throw new DatabaseException("value of the attribute [params] has to be a struct or a array", null, null, null);
}
else {
sql = items.isEmpty() ? new SQLImpl(strSQL) : new SQLImpl(strSQL, items.toArray(new SQLItem[items.size()]));
}
// lucee.runtime.type.Query query=null;
QueryResult queryResult = null;
String cacheHandlerId = null;
String cacheId = null;
long exe = 0;
boolean useCache = (cachedWithin != null) || (cachedAfter != null);
CacheHandler cacheHandler = null;
if(useCache) {
cacheId = CacheHandlerCollectionImpl.createId(sql, datasource != null ? datasource.getName() : null, username, password, returntype);
CacheHandlerCollectionImpl coll = (CacheHandlerCollectionImpl)pageContext.getConfig().getCacheHandlerCollection(Config.CACHE_TYPE_QUERY, null);
cacheHandler = coll.getInstanceMatchingObject(cachedWithin, null);
if(cacheHandler == null && cachedAfter != null)
cacheHandler = coll.getTimespanInstance(null);
if(cacheHandler != null) {
cacheHandlerId = cacheHandler.id(); // cacheHandlerId specifies to queryResult the cacheType and therefore whether the query is cached or
// not
if(cacheHandler instanceof CacheHandlerPro) {
CacheItem cacheItem = ((CacheHandlerPro)cacheHandler).get(pageContext, cacheId, (cachedWithin != null) ? cachedWithin : cachedAfter);
if(cacheItem instanceof QueryResultCacheItem)
queryResult = ((QueryResultCacheItem)cacheItem).getQueryResult();
}
else { // FUTURE this else block can be removed when all cache handlers implement CacheHandlerPro
CacheItem cacheItem = cacheHandler.get(pageContext, cacheId);
if(cacheItem instanceof QueryResultCacheItem) {
QueryResultCacheItem queryCachedItem = (QueryResultCacheItem)cacheItem;
Date cacheLimit = cachedAfter;
/*if(cacheLimit == null && cacheHandler in) {
TimeSpan ts = Caster.toTimespan(cachedWithin,null);
cacheLimit = new Date(System.currentTimeMillis() - Caster.toTimeSpan(cachedWithin).getMillis());
}*/
if(cacheLimit==null || queryCachedItem.isCachedAfter(cacheLimit))
queryResult = queryCachedItem.getQueryResult();
}
}
}
else {
List<String> patterns = pageContext.getConfig().getCacheHandlerCollection(Config.CACHE_TYPE_QUERY, null).getPatterns();
throw new ApplicationException(
"cachedwithin value [" + cachedWithin + "] is invalid, valid values are for example [" + ListUtil.listToList(patterns, ", ") + "]");
}
// query=pageContext.getQueryCache().getQuery(pageContext,sql,datasource!=null?datasource.getName():null,username,password,cachedafter);
}
// cache not found, process and cache result if needed
if(queryResult == null) {
// QoQ
if("query".equals(dbtype)) {
lucee.runtime.type.Query q = executeQoQ(sql);
if(returntype == RETURN_TYPE_ARRAY)
queryResult = QueryArray.toQueryArray(q); // TODO this should be done in queryExecute itself so we not have to convert afterwards
else if(returntype == RETURN_TYPE_STRUCT) {
if(columnName == null)
throw new ApplicationException("attribute columnKey is required when return type is set to struct");
queryResult = QueryStruct.toQueryStruct(q, columnName); // TODO this should be done in queryExecute itself so we not have to convert
// afterwards
}
else
queryResult = (QueryResult)q;
}
// ORM and Datasource
else {
long start = System.nanoTime();
Object obj;
if("orm".equals(dbtype) || "hql".equals(dbtype))
obj = executeORM(sql, returntype, ormoptions);
else
obj = executeDatasoure(sql, result != null, pageContext.getTimeZone());
if(obj instanceof QueryResult) {
queryResult = (QueryResult)obj;
}
else {
if(setReturnVariable) {
rtn = obj;
}
else if(!StringUtil.isEmpty(name)) {
pageContext.setVariable(name, obj);
}
if(result != null) {
Struct sct = new StructImpl();
sct.setEL(KeyConstants._cached, Boolean.FALSE);
long time = System.nanoTime() - start;
sct.setEL(KeyConstants._executionTime, Caster.toDouble(time / 1000000));
sct.setEL(KeyConstants._executionTimeNano, Caster.toDouble(time));
sct.setEL(KeyConstants._SQL, sql.getSQLString());
if(Decision.isArray(obj)) {
}
else
sct.setEL(KeyConstants._RECORDCOUNT, Caster.toDouble(1));
pageContext.setVariable(result, sct);
}
else
setExecutionTime((System.nanoTime() - start) / 1000000);
return EVAL_PAGE;
}
}
// else query=executeDatasoure(sql,result!=null,pageContext.getTimeZone());
if(cachedWithin != null) {
CacheItem cacheItem = QueryResultCacheItem.newInstance(queryResult, tags, datasource, null);
if(cacheItem != null)
cacheHandler.set(pageContext, cacheId, cachedWithin, cacheItem);
}
exe = queryResult.getExecutionTime();
}
else {
queryResult.setCacheType(cacheHandlerId);
}
if(pageContext.getConfig().debug() && debug) {
boolean logdb = ((ConfigImpl)pageContext.getConfig()).hasDebugOptions(ConfigImpl.DEBUG_DATABASE);
if(logdb) {
boolean debugUsage = DebuggerImpl.debugQueryUsage(pageContext, queryResult);
DebuggerImpl di = (DebuggerImpl)pageContext.getDebugger();
di.addQuery(debugUsage ? queryResult : null, datasource != null ? datasource.getName() : null, name, sql, queryResult.getRecordcount(),
getPageSource(), exe);
}
}
if(setReturnVariable) {
rtn = queryResult;
}
else if((queryResult.getColumncount() + queryResult.getRecordcount()) > 0 && !StringUtil.isEmpty(name)) {
pageContext.setVariable(name, queryResult);
}
// Result
if(result != null) {
Struct sct = new StructImpl();
sct.setEL(KeyConstants._cached, Caster.toBoolean(queryResult.isCached()));
if((queryResult.getColumncount() + queryResult.getRecordcount()) > 0) {
String list = ListUtil.arrayToList(
queryResult instanceof lucee.runtime.type.Query ? ((lucee.runtime.type.Query)queryResult).getColumnNamesAsString()
: CollectionUtil.toString(queryResult.getColumnNames(), false),
",");
sct.setEL(KeyConstants._COLUMNLIST, list);
}
int rc = queryResult.getRecordcount();
if(rc == 0)
rc = queryResult.getUpdateCount();
sct.setEL(KeyConstants._RECORDCOUNT, Caster.toDouble(rc));
sct.setEL(KeyConstants._executionTime, Caster.toDouble(queryResult.getExecutionTime() / 1000000));
sct.setEL(KeyConstants._executionTimeNano, Caster.toDouble(queryResult.getExecutionTime()));
sct.setEL(KeyConstants._SQL, sql.getSQLString());
// GENERATED KEYS
lucee.runtime.type.Query qi = Caster.toQuery(queryResult, null);
if(qi != null) {
lucee.runtime.type.Query qryKeys = qi.getGeneratedKeys();
if(qryKeys != null) {
StringBuilder generatedKey = new StringBuilder(), sb;
Collection.Key[] columnNames = qryKeys.getColumnNames();
QueryColumn column;
for (int c = 0; c < columnNames.length; c++) {
column = qryKeys.getColumn(columnNames[c]);
sb = new StringBuilder();
int size = column.size();
for (int row = 1; row <= size; row++) {
if(row > 1)
sb.append(',');
sb.append(Caster.toString(column.get(row, null)));
}
if(sb.length() > 0) {
sct.setEL(columnNames[c], sb.toString());
if(generatedKey.length() > 0)
generatedKey.append(',');
generatedKey.append(sb);
}
}
if(generatedKey.length() > 0)
sct.setEL(GENERATEDKEY, generatedKey.toString());
}
}
// sqlparameters
SQLItem[] params = sql.getItems();
if(params != null && params.length > 0) {
Array arr = new ArrayImpl();
sct.setEL(SQL_PARAMETERS, arr);
for (int i = 0; i < params.length; i++) {
arr.append(params[i].getValue());
}
}
pageContext.setVariable(result, sct);
}
// cfquery.executiontime
else {
setExecutionTime(exe / 1000000);
}
// listener
((ConfigWebImpl)pageContext.getConfig()).getActionMonitorCollector().log(pageContext, "query", "Query", exe, queryResult);
// log
Log log = pageContext.getConfig().getLog("datasource");
if(log.getLogLevel() >= Log.LEVEL_INFO) {
log.info("query tag", "executed [" + sql.toString().trim() + "] in " + DecimalFormat.call(pageContext, exe / 1000000D) + " ms");
}
}
catch (PageException pe) {
// log
pageContext.getConfig().getLog("datasource").error("query tag", pe);
throw pe;
} finally {
((PageContextImpl)pageContext).setTimestampWithTSOffset(previousLiteralTimestampWithTSOffset);
if(tmpTZ != null) {
pageContext.setTimeZone(tmpTZ);
}
}
return EVAL_PAGE;
}
private PageSource getPageSource() {
if(nestingLevel > 0) {
PageContextImpl pci = (PageContextImpl)pageContext;
List<PageSource> list = pci.getPageSourceList();
int index = list.size() - 1 - nestingLevel;
if(index >= 0)
return list.get(index);
}
return pageContext.getCurrentPageSource();
}
private void setExecutionTime(long exe) {
Struct sct = new StructImpl();
sct.setEL(KeyConstants._executionTime, new Double(exe));
pageContext.undefinedScope().setEL(CFQUERY, sct);
}
private Object executeORM(SQL sql, int returnType, Struct ormoptions) throws PageException {
ORMSession session = ORMUtil.getSession(pageContext);
if(ormoptions == null)
ormoptions = new StructImpl();
String dsn = null;
if(ormoptions != null)
dsn = Caster.toString(ormoptions.get(KeyConstants._datasource, null), null);
if(StringUtil.isEmpty(dsn, true))
dsn = ORMUtil.getDefaultDataSource(pageContext).getName();
// params
SQLItem[] _items = sql.getItems();
Array params = new ArrayImpl();
for (int i = 0; i < _items.length; i++) {
params.appendEL(_items[i]);
}
// query options
if(maxrows != -1 && !ormoptions.containsKey(MAX_RESULTS))
ormoptions.setEL(MAX_RESULTS, new Double(maxrows));
if(timeout != null && ((int)timeout.getSeconds()) > 0 && !ormoptions.containsKey(TIMEOUT))
ormoptions.setEL(TIMEOUT, new Double(timeout.getSeconds()));
/*
* MUST offset: Specifies the start index of the resultset from where it has to start the retrieval. cacheable: Whether the result of this query is to
* be cached in the secondary cache. Default is false. cachename: Name of the cache in secondary cache.
*/
Object res = session.executeQuery(pageContext, dsn, sql.getSQLString(), params, unique, ormoptions);
if(returnType == RETURN_TYPE_ARRAY || returnType == RETURN_TYPE_UNDEFINED)
return res;
return session.toQuery(pageContext, res, null);
}
public static Object _call(PageContext pc, String hql, Object params, boolean unique, Struct queryOptions) throws PageException {
ORMSession session = ORMUtil.getSession(pc);
String dsn = Caster.toString(queryOptions.get(KeyConstants._datasource, null), null);
if(StringUtil.isEmpty(dsn, true))
dsn = ORMUtil.getDefaultDataSource(pc).getName();
if(Decision.isCastableToArray(params))
return session.executeQuery(pc, dsn, hql, Caster.toArray(params), unique, queryOptions);
else if(Decision.isCastableToStruct(params))
return session.executeQuery(pc, dsn, hql, Caster.toStruct(params), unique, queryOptions);
else
return session.executeQuery(pc, dsn, hql, (Array)params, unique, queryOptions);
}
private lucee.runtime.type.Query executeQoQ(SQL sql) throws PageException {
try {
return new HSQLDBHandler().execute(pageContext, sql, maxrows, blockfactor, timeout);
}
catch (Exception e) {
throw Caster.toPageException(e);
}
}
private QueryResult executeDatasoure(SQL sql, boolean createUpdateData, TimeZone tz) throws PageException {
DatasourceManagerImpl manager = (DatasourceManagerImpl)pageContext.getDataSourceManager();
DatasourceConnection dc = manager.getConnection(pageContext, datasource, username, password);
try {
if(lazy && !createUpdateData && cachedWithin == null && cachedAfter == null && result == null) {
if(returntype != RETURN_TYPE_QUERY)
throw new DatabaseException("only return type query is allowed when lazy is set to true", null, sql, dc);
return new SimpleQuery(pageContext, dc, sql, maxrows, blockfactor, timeout, getName(), getPageSource().getDisplayPath(), tz);
}
if(returntype == RETURN_TYPE_ARRAY)
return QueryImpl.toArray(pageContext, dc, sql, maxrows, blockfactor, timeout, getName(), getPageSource().getDisplayPath(), createUpdateData,
true);
if(returntype == RETURN_TYPE_STRUCT) {
if(columnName == null)
throw new ApplicationException("attribute columnKey is required when return type is set to struct");
return QueryImpl.toStruct(pageContext, dc, sql, columnName, maxrows, blockfactor, timeout, getName(), getPageSource().getDisplayPath(),
createUpdateData, true);
}
return new QueryImpl(pageContext, dc, sql, maxrows, blockfactor, timeout, getName(), getPageSource().getDisplayPath(), createUpdateData, true);
} finally {
manager.releaseConnection(pageContext, dc);
}
}
@Override
public void doInitBody() {
}
@Override
public int doAfterBody() {
return SKIP_BODY;
}
public void setReturnVariable(boolean setReturnVariable) {
this.setReturnVariable = setReturnVariable;
}
public Object getReturnVariable() {
return rtn;
}
} |
package org.royaldev.royalcommands.serializable;
import org.bukkit.craftbukkit.inventory.CraftItemStack;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemStack;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* Serializable ItemStack
* <p/>
* Needed for SerializableCraftInventory
*
* @author jkcclemens
* @see SerializableCraftInventory
* @see SerializableCraftEnchantment
* @since 0.2.4pre
*/
public class SerializableItemStack implements Serializable {
static final long serialVersionUID = -5056202252395200062L;
/**
* Amount of items in the ItemStack - defaults to 0
*/
private int amount = 0;
/**
* Durability, or damage, of the items in the ItemStack - defaults to 0
*/
private short durability = 0;
/**
* Item ID of the ItemStack - defaults to 0
*/
private int type = 0;
/**
* Map containing enchantments and their respective levels on this ItemStack - defaults to an empty map
*/
private Map<SerializableCraftEnchantment, Integer> enchantments = new HashMap<SerializableCraftEnchantment, Integer>();
/**
* Material data on this ItemStack - defaults to 0
*/
private byte materialData = 0;
private SerializableNBTTagCompound tag;
/**
* Serializable ItemStack for saving to files.
*
* @param i ItemStack to convert
*/
public SerializableItemStack(ItemStack i) {
if (i == null) return;
amount = i.getAmount();
durability = i.getDurability();
for (Enchantment e : i.getEnchantments().keySet())
enchantments.put(new SerializableCraftEnchantment(e), i.getEnchantments().get(e));
type = i.getTypeId();
materialData = i.getData().getData();
tag = new SerializableNBTTagCompound(((CraftItemStack) i).getHandle().getTag());
}
/**
* Returns a SIS to an ItemStack (keeps enchantments, amount, data, and durability)
*
* @return Original ItemStack
*/
public ItemStack getItemStack() {
CraftItemStack cis = new CraftItemStack(type, amount, durability, materialData);
cis.setDurability(durability);
for (SerializableCraftEnchantment sce : enchantments.keySet())
cis.addUnsafeEnchantment(sce.getEnchantment(), enchantments.get(sce));
if (tag != null) cis.getHandle().setTag(tag.getNBTTagCompound());
return cis;
}
} |
package com.intellij.openapi.vcs.changes.ui;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vcs.VcsBundle;
import com.intellij.openapi.vcs.changes.ChangeListManager;
import com.intellij.openapi.vcs.changes.ChangesUtil;
import com.intellij.openapi.vcs.changes.IgnoredFileBean;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.DocumentAdapter;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class IgnoreUnversionedDialog extends DialogWrapper {
private JRadioButton myIgnoreSpecifiedFileRadioButton;
private JRadioButton myIgnoreAllFilesUnderRadioButton;
private TextFieldWithBrowseButton myIgnoreDirectoryTextField;
private JRadioButton myIgnoreAllFilesMatchingRadioButton;
private JTextField myIgnoreMaskTextField;
private JPanel myPanel;
private TextFieldWithBrowseButton myIgnoreFileTextField;
private List<VirtualFile> myFilesToIgnore;
private final Project myProject;
private boolean myInternalChange;
public IgnoreUnversionedDialog(final Project project) {
super(project, false);
myProject = project;
setTitle(VcsBundle.message("ignored.edit.title"));
init();
myIgnoreFileTextField.addBrowseFolderListener("Select File to Ignore",
"Select the file which will not be tracked for changes",
project,
new FileChooserDescriptor(true, false, false, true, false, false));
myIgnoreFileTextField.getTextField().getDocument().addDocumentListener(new DocumentAdapter() {
protected void textChanged(final DocumentEvent e) {
// on text change, clear remembered files to ignore
if (!myInternalChange) {
myFilesToIgnore = null;
}
}
});
myIgnoreDirectoryTextField.addBrowseFolderListener("Select Directory to Ignore",
"Select the directory which will not be tracked for changes",
project,
new FileChooserDescriptor(false, true, false, false, false, false));
ActionListener listener = new ActionListener() {
public void actionPerformed(final ActionEvent e) {
updateControls();
}
};
myIgnoreAllFilesUnderRadioButton.addActionListener(listener);
myIgnoreAllFilesMatchingRadioButton.addActionListener(listener);
myIgnoreSpecifiedFileRadioButton.addActionListener(listener);
updateControls();
}
private void updateControls() {
myIgnoreDirectoryTextField.setEnabled(myIgnoreAllFilesUnderRadioButton.isSelected());
myIgnoreMaskTextField.setEnabled(myIgnoreAllFilesMatchingRadioButton.isSelected());
myIgnoreFileTextField.setEnabled(myIgnoreSpecifiedFileRadioButton.isSelected() &&
(myFilesToIgnore == null || (myFilesToIgnore.size() == 1 && !myFilesToIgnore.get(0).isDirectory())));
}
@Nullable
protected JComponent createCenterPanel() {
return myPanel;
}
private void setFilesToIgnore(List<VirtualFile> virtualFiles) {
assert virtualFiles.size() > 0;
myFilesToIgnore = virtualFiles;
myInternalChange = true;
try {
if (virtualFiles.size() == 1) {
VirtualFile projectDir = myProject.getBaseDir();
String path = FileUtil.getRelativePath(new File(projectDir.getPresentableUrl()), new File(virtualFiles.get(0).getPresentableUrl()));
myIgnoreFileTextField.setText(path);
}
else {
myIgnoreFileTextField.setText(VcsBundle.message("ignored.edit.multiple.files", virtualFiles.size()));
}
}
finally {
myInternalChange = false;
}
for(VirtualFile file: virtualFiles) {
if (file.isDirectory()) {
myIgnoreAllFilesUnderRadioButton.setSelected(true);
myIgnoreSpecifiedFileRadioButton.setEnabled(false);
myIgnoreFileTextField.setEnabled(false);
}
}
updateControls();
final VirtualFile[] ancestors = VfsUtil.getCommonAncestors(virtualFiles.toArray(new VirtualFile[virtualFiles.size()]));
if (ancestors.length > 0) {
myIgnoreDirectoryTextField.setText(ancestors [0].getPresentableUrl());
}
else {
myIgnoreDirectoryTextField.setText(virtualFiles.get(0).getParent().getPresentableUrl());
}
final Set<String> extensions = new HashSet<String>();
for(VirtualFile vf: virtualFiles) {
final String extension = vf.getExtension();
if (extension != null) {
extensions.add(extension);
}
}
if (extensions.size() > 0) {
final String[] extensionArray = extensions.toArray(new String[extensions.size()]);
myIgnoreMaskTextField.setText("*." + extensionArray [0]);
}
else {
myIgnoreMaskTextField.setText(virtualFiles.get(0).getPresentableName());
}
}
public void setIgnoredFile(final IgnoredFileBean bean) {
if (bean.getPath() != null) {
String path = bean.getPath().replace('/', File.separatorChar);
if (path.endsWith(File.separator)) {
myIgnoreAllFilesUnderRadioButton.setSelected(true);
myIgnoreDirectoryTextField.setText(path);
}
else {
myIgnoreSpecifiedFileRadioButton.setSelected(true);
myIgnoreFileTextField.setText(path);
}
}
else {
myIgnoreAllFilesMatchingRadioButton.setSelected(true);
myIgnoreMaskTextField.setText(bean.getMask());
}
}
public IgnoredFileBean[] getSelectedIgnoredFiles() {
if (myIgnoreSpecifiedFileRadioButton.isSelected()) {
if (myFilesToIgnore == null) {
IgnoredFileBean bean = new IgnoredFileBean();
bean.setPath(myIgnoreFileTextField.getText().replace(File.separatorChar, '/'));
return new IgnoredFileBean[] { bean };
}
IgnoredFileBean[] result = new IgnoredFileBean[myFilesToIgnore.size()];
for(int i=0; i<myFilesToIgnore.size(); i++) {
result [i] = new IgnoredFileBean();
result [i].setPath(ChangesUtil.getProjectRelativePath(myProject, new File(myFilesToIgnore.get(i).getPresentableUrl())));
}
return result;
}
if (myIgnoreAllFilesUnderRadioButton.isSelected()) {
IgnoredFileBean result = new IgnoredFileBean();
String path = myIgnoreDirectoryTextField.getText();
if (new File(path).isAbsolute()) {
final String relPath = ChangesUtil.getProjectRelativePath(myProject, new File(path));
if (relPath != null) {
path = relPath;
}
}
if (!path.endsWith("/") && !path.endsWith(File.separator)) {
path += File.separator;
}
result.setPath(FileUtil.toSystemIndependentName(path));
return new IgnoredFileBean[] { result };
}
if (myIgnoreAllFilesMatchingRadioButton.isSelected()) {
IgnoredFileBean result = new IgnoredFileBean();
result.setMask(myIgnoreMaskTextField.getText());
return new IgnoredFileBean[] { result };
}
return new IgnoredFileBean[0];
}
@Override @NonNls
protected String getDimensionServiceKey() {
return "IgnoreUnversionedDialog";
}
public static void ignoreSelectedFiles(final Project project, final List<VirtualFile> files) {
IgnoreUnversionedDialog dlg = new IgnoreUnversionedDialog(project);
dlg.setFilesToIgnore(files);
dlg.show();
if (!dlg.isOK()) {
return;
}
final IgnoredFileBean[] ignoredFiles = dlg.getSelectedIgnoredFiles();
if (ignoredFiles.length > 0) {
ChangeListManager.getInstance(project).addFilesToIgnore(ignoredFiles);
}
}
} |
package imj3.draft.processing;
import static imj3.tools.AwtImage2D.awtRead;
import static imj3.tools.CommonSwingTools.limitHeight;
import static imj3.tools.CommonSwingTools.setModel;
import static java.lang.Math.max;
import static net.sourceforge.aprog.swing.SwingTools.horizontalBox;
import static net.sourceforge.aprog.swing.SwingTools.horizontalSplit;
import static net.sourceforge.aprog.swing.SwingTools.scrollable;
import static net.sourceforge.aprog.swing.SwingTools.verticalBox;
import static net.sourceforge.aprog.tools.Tools.append;
import static net.sourceforge.aprog.tools.Tools.array;
import static net.sourceforge.aprog.tools.Tools.baseName;
import static net.sourceforge.aprog.tools.Tools.join;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.StaxDriver;
import imj2.tools.Canvas;
import imj3.draft.processing.VisualAnalysis.Context.Refresh;
import imj3.draft.segmentation.ImageComponent;
import imj3.draft.segmentation.ImageComponent.Layer;
import imj3.draft.segmentation.ImageComponent.Painter;
import imj3.tools.CommonSwingTools.NestedList;
import imj3.tools.CommonSwingTools.PropertyGetter;
import imj3.tools.CommonSwingTools.PropertySetter;
import imj3.tools.CommonSwingTools.StringGetter;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.io.UncheckedIOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.prefs.Preferences;
import javax.imageio.ImageIO;
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.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import net.sourceforge.aprog.swing.SwingTools;
import net.sourceforge.aprog.tools.IllegalInstantiationException;
import net.sourceforge.aprog.tools.Tools;
/**
* @author codistmonk (creation 2015-02-13)
*/
public final class VisualAnalysis {
private VisualAnalysis() {
throw new IllegalInstantiationException();
}
static final Preferences preferences = Preferences.userNodeForPackage(VisualAnalysis.class);
static final XStream xstream = new XStream(new StaxDriver());
public static final String IMAGE_PATH = "image.path";
public static final String GROUND_TRUTH = "groundtruth";
public static final String EXPERIMENT = "experiment";
/**
* @param commandLineArguments
* <br>Unused
*/
public static final void main(final String[] commandLineArguments) {
SwingTools.useSystemLookAndFeel();
final Context context = new Context();
SwingUtilities.invokeLater(new Runnable() {
@Override
public final void run() {
SwingTools.show(new MainPanel(context), VisualAnalysis.class.getSimpleName(), false);
context.setImage(new File(preferences.get(IMAGE_PATH, "")));
context.setGroundTruth(preferences.get(GROUND_TRUTH, "gt"));
context.setExperiment(new File(preferences.get(EXPERIMENT, "experiment.xml")));
}
});
}
public static final Component label(final String text, final Component... components) {
return limitHeight(horizontalBox(append(array((Component) new JLabel(text)), components)));
}
public static final <C extends JComponent> C centerX(final C component) {
component.setAlignmentX(Component.CENTER_ALIGNMENT);
return component;
}
public static final JTextField textView(final String text) {
final JTextField result = new JTextField(text);
result.setEditable(false);
return result;
}
public static final JButton button(final String type) {
final JButton result = new JButton(new ImageIcon(Tools.getResourceURL("lib/tango/" + type + ".png")));
final int size = max(result.getIcon().getIconWidth(), result.getIcon().getIconHeight());
result.setPreferredSize(new Dimension(size + 2, size + 2));
return result;
}
/**
* @author codistmonk (creation 2015-02-19)
*/
public static final class FileSelector extends JButton {
private final List<File> files = new ArrayList<>();
private File selectedFile;
private ActionListener fileListener;
{
this.addActionListener(new ActionListener() {
@Override
public final void actionPerformed(final ActionEvent event) {
FileSelector.this.showPopup();
}
});
this.setMaximumSize(new Dimension(Integer.MAX_VALUE, 26));
this.setHorizontalAlignment(SwingConstants.LEFT);
}
public final ActionListener getFileListener() {
return this.fileListener;
}
public final void setFileListener(final ActionListener fileListener) {
this.fileListener = fileListener;
}
public final File getSelectedFile() {
return this.selectedFile;
}
public final FileSelector setFile(final File file) {
this.files.remove(file);
this.files.add(0, file);
final boolean changed = !file.equals(this.getSelectedFile());
if (changed) {
this.selectedFile = file;
this.setText(file.getName());
if (this.fileListener != null) {
this.fileListener.actionPerformed(new ActionEvent(this, -1, null));
}
}
return this;
}
final void showPopup() {
final JPopupMenu popup = new JPopupMenu();
for (final File file : this.files) {
popup.add(new JMenuItem(new AbstractAction(file.getPath()) {
@Override
public final void actionPerformed(final ActionEvent event) {
FileSelector.this.setFile(file);
}
private static final long serialVersionUID = 8311454620470586686L;
}));
}
popup.show(this, 0, 0);
}
private static final long serialVersionUID = 7227165282556980768L;
}
/**
* @author codistmonk (creation 2015-02-13)
*/
public static final class MainPanel extends JPanel {
private final Context context;
private final FileSelector imageSelector;
private final JCheckBox imageVisibilitySelector;
private final FileSelector groundTruthSelector;
private final JCheckBox groundTruthVisibilitySelector;
private final FileSelector experimentSelector;
private final JTextField trainingTimeView;
private final JTextField classificationTimeView;
private final JCheckBox classificationVisibilitySelector;
private final JTextField scoreView;
private final JTree tree;
private final JSplitPane mainSplitPane;
private ImageComponent imageComponent;
private Experiment experiment;
public MainPanel(final Context context) {
super(new BorderLayout());
this.context = context;
this.imageSelector = new FileSelector();
this.imageVisibilitySelector = new JCheckBox("", true);
this.groundTruthSelector = new FileSelector();
this.groundTruthVisibilitySelector = new JCheckBox();
this.experimentSelector = new FileSelector();
this.trainingTimeView = textView("-");
this.classificationTimeView = textView("-");
this.classificationVisibilitySelector = new JCheckBox();
this.scoreView = textView("-");
this.tree = new JTree(new DefaultTreeModel(new DefaultMutableTreeNode("No experiment")));
final int padding = this.imageVisibilitySelector.getPreferredSize().width;
final JButton openImageButton = button("open");
final JButton newGroundTruthButton = button("new");
final JButton saveGroundTruthButton = button("save");
final JButton refreshGroundTruthButton = button("refresh");
final JButton newExperimentButton = button("new");
final JButton openExperimentButton = button("open");
final JButton runExperimentButton = button("process");
final JButton saveExperimentButton = button("save");
final JButton refreshExperimentButton = button("refresh");
this.mainSplitPane = horizontalSplit(verticalBox(
label(" Image: ", this.imageSelector, openImageButton, this.imageVisibilitySelector),
label(" Ground truth: ", this.groundTruthSelector, newGroundTruthButton, saveGroundTruthButton, refreshGroundTruthButton, this.groundTruthVisibilitySelector),
label(" Experiment: ", this.experimentSelector, newExperimentButton, openExperimentButton, runExperimentButton, saveExperimentButton, refreshExperimentButton, Box.createHorizontalStrut(padding)),
label(" Training (s): ", this.trainingTimeView, button("process"), Box.createHorizontalStrut(padding)),
label(" Classification (s): ", this.classificationTimeView, button("process"), button("save"), button("refresh"), this.classificationVisibilitySelector),
label(" F1: ", this.scoreView, Box.createHorizontalStrut(padding)),
centerX(new JButton("Confusion matrix...")),
scrollable(this.tree)), scrollable(new JLabel("Drop file here")));
this.mainSplitPane.getLeftComponent().setMaximumSize(new Dimension(128, Integer.MAX_VALUE));
this.add(this.mainSplitPane, BorderLayout.CENTER);
openImageButton.addActionListener(new ActionListener() {
@Override
public final void actionPerformed(final ActionEvent event) {
final JFileChooser fileChooser = new JFileChooser(new File(preferences.get(IMAGE_PATH, "")).getParent());
if (JFileChooser.APPROVE_OPTION == fileChooser.showOpenDialog(MainPanel.this)) {
context.setImage(fileChooser.getSelectedFile());
}
}
});
this.imageSelector.setFileListener(new ActionListener() {
@Override
public final void actionPerformed(final ActionEvent event) {
context.setImage(MainPanel.this.getImageSelector().getSelectedFile());
}
});
this.groundTruthSelector.setFileListener(new ActionListener() {
@Override
public final void actionPerformed(final ActionEvent event) {
context.refreshGroundTruthAndClassification(Refresh.FROM_FILE);
}
});
newGroundTruthButton.addActionListener(e -> {
final String name = JOptionPane.showInputDialog("Ground truth name:");
if (name != null && context.getImage() != null) {
try {
ImageIO.write(context.formatGroundTruth().getGroundTruth().getImage(), "png", new File(context.getGroundTruthPath(name)));
} catch (final IOException exception) {
throw new UncheckedIOException(exception);
}
context.setGroundTruth(name);
}
});
saveGroundTruthButton.addActionListener(e -> Tools.debugPrint("TODO"));
this.experimentSelector.setFileListener(new ActionListener() {
@Override
public final void actionPerformed(final ActionEvent event) {
context.setExperiment(MainPanel.this.getExperimentSelector().getSelectedFile());
}
});
newExperimentButton.addActionListener(e -> {
final JFileChooser fileChooser = new JFileChooser(new File(preferences.get(EXPERIMENT, "")).getParentFile());
if (JFileChooser.APPROVE_OPTION == fileChooser.showSaveDialog(this)) {
final File selectedFile = fileChooser.getSelectedFile();
try (final OutputStream output = new FileOutputStream(selectedFile)) {
xstream.toXML(new Experiment(), output);
} catch (final IOException exception) {
throw new UncheckedIOException(exception);
}
context.setExperiment(selectedFile);
}
});
openExperimentButton.addActionListener(e -> Tools.debugPrint("TODO"));
saveExperimentButton.addActionListener(e -> Tools.debugPrint("TODO"));
this.imageVisibilitySelector.addActionListener(new ActionListener() {
@Override
public final void actionPerformed(final ActionEvent event) {
final Layer imageLayer = MainPanel.this.getImageComponent().getLayers().get(0);
final Painter imagePainter = imageLayer.getPainters().get(0);
final boolean imageVisible = MainPanel.this.getImageVisibilitySelector().isSelected();
if (!imageVisible) {
imageLayer.getCanvas().clear(Color.GRAY);
}
imagePainter.getActive().set(imageVisible);
imagePainter.getUpdateNeeded().set(true);
MainPanel.this.getImageComponent().repaint();
}
});
this.groundTruthVisibilitySelector.addActionListener(new ActionListener() {
@Override
public final void actionPerformed(final ActionEvent event) {
final Layer groundTruthLayer = MainPanel.this.getImageComponent().getLayers().get(1);
final Painter groundTruthPainter = groundTruthLayer.getPainters().get(0);
final boolean groundTruthVisible = MainPanel.this.getGroundTruthVisibilitySelector().isSelected();
groundTruthPainter.getActive().set(groundTruthVisible);
groundTruthPainter.getUpdateNeeded().set(true);
MainPanel.this.getImageComponent().repaint();
}
});
this.classificationVisibilitySelector.addActionListener(new ActionListener() {
@Override
public final void actionPerformed(final ActionEvent event) {
final Layer classificationLayer = MainPanel.this.getImageComponent().getLayers().get(2);
final Painter classificationPainter = classificationLayer.getPainters().get(0);
final boolean classificationVisible = MainPanel.this.getClassificationVisibilitySelector().isSelected();
classificationPainter.getActive().set(classificationVisible);
classificationPainter.getUpdateNeeded().set(true);
MainPanel.this.getImageComponent().repaint();
}
});
this.setDropTarget(new DropTarget() {
@Override
public final synchronized void drop(final DropTargetDropEvent event) {
final File file = SwingTools.getFiles(event).get(0);
if (file.getName().toLowerCase(Locale.ENGLISH).endsWith(".xml")) {
} else {
context.setImage(file);
}
}
/**
* {@value}.
*/
private static final long serialVersionUID = 5442000733451223725L;
});
this.setPreferredSize(new Dimension(800, 600));
context.setMainPanel(this);
}
public final Context getContext() {
return this.context;
}
public final Experiment getExperiment() {
return this.experiment;
}
public final void setExperiment(final Experiment experiment) {
this.experiment = experiment;
setModel(this.tree, experiment, "Experiment");
}
public final ImageComponent getImageComponent() {
return this.imageComponent;
}
final void setImage(final String path) {
this.imageComponent = new ImageComponent(awtRead(path));
this.getImageComponent().addLayer().getPainters().add(new Painter.Abstract() {
@Override
public final void paint(final Canvas canvas) {
canvas.getGraphics().drawImage(MainPanel.this.getContext().getGroundTruth().getImage(), 0, 0, null);
}
private static final long serialVersionUID = 4700895082820237288L;
});
this.getImageComponent().addLayer().getPainters().add(new Painter.Abstract() {
@Override
public final void paint(final Canvas canvas) {
canvas.getGraphics().drawImage(MainPanel.this.getContext().getClassification().getImage(), 0, 0, null);
}
private static final long serialVersionUID = 7941391067177261093L;
});
this.setContents(this.getImageComponent());
}
public final FileSelector getImageSelector() {
return this.imageSelector;
}
public final JTree getTree() {
return this.tree;
}
public final JCheckBox getImageVisibilitySelector() {
return this.imageVisibilitySelector;
}
public final FileSelector getGroundTruthSelector() {
return this.groundTruthSelector;
}
public final JCheckBox getGroundTruthVisibilitySelector() {
return this.groundTruthVisibilitySelector;
}
public final FileSelector getExperimentSelector() {
return this.experimentSelector;
}
public final JTextField getTrainingTimeView() {
return this.trainingTimeView;
}
public final JTextField getClassificationTimeView() {
return this.classificationTimeView;
}
public final JCheckBox getClassificationVisibilitySelector() {
return this.classificationVisibilitySelector;
}
public final JTextField getScoreView() {
return this.scoreView;
}
public final void setContents(final Component component) {
this.mainSplitPane.setRightComponent(scrollable(component));
}
private static final long serialVersionUID = 2173077945563031333L;
public static final int IMAGE_SELECTOR_RESERVED_SLOTS = 2;
}
/**
* @author codistmonk (creation 2015-02-13)
*/
public static final class Context implements Serializable {
private MainPanel mainPanel;
private final Canvas groundTruth = new Canvas();
private final Canvas classification = new Canvas();
public final MainPanel getMainPanel() {
return this.mainPanel;
}
public final void setMainPanel(final MainPanel mainPanel) {
this.mainPanel = mainPanel;
}
public final File getExperimentFile() {
return this.getMainPanel().getExperimentSelector().getSelectedFile();
}
public final String getGroundTruthName() {
return this.getMainPanel().getGroundTruthSelector().getText();
}
public final Context setGroundTruthName(final String groundTruthName) {
this.getMainPanel().getGroundTruthSelector().setFile(new File(groundTruthName));
return this;
}
public final BufferedImage getImage() {
final MainPanel mainPanel = this.getMainPanel();
final ImageComponent imageComponent = mainPanel == null ? null : mainPanel.getImageComponent();
return imageComponent == null ? null : imageComponent.getImage();
}
public final Canvas getGroundTruth() {
return this.groundTruth;
}
public final Context formatGroundTruth() {
return format(this.getGroundTruth());
}
public final Canvas getClassification() {
return this.classification;
}
public final String getExperimentName() {
final File experimentFile = this.getExperimentFile();
return experimentFile == null ? null : baseName(experimentFile.getName());
}
public final File getImageFile() {
return new File(this.getMainPanel().getImageSelector().getText());
}
public final String getGroundTruthPath() {
return this.getGroundTruthPath(this.getGroundTruthName());
}
public final String getGroundTruthPath(final String name) {
return baseName(this.getImageFile().getPath()) + "_groundtruth_" + name + ".png";
}
public final String getClassificationPath() {
return baseName(this.getImageFile().getPath()) + "_classification_" + this.getGroundTruthName() + "_" + this.getExperimentName() + ".png";
}
public final void refreshGroundTruthAndClassification(final Refresh refresh) {
final BufferedImage image = this.getImage();
if (image == null) {
return;
}
System.out.println(Tools.debug(Tools.DEBUG_STACK_OFFSET + 1));
Tools.debugPrint(this.getGroundTruthName());
final int imageWidth = image.getWidth();
final int imageHeight = image.getHeight();
this.getGroundTruth().setFormat(imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB);
this.getClassification().setFormat(imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB);
switch (refresh) {
case CLEAR:
this.getGroundTruth().clear(CLEAR);
this.getClassification().clear(CLEAR);
break;
case FROM_FILE:
{
{
final String groundTruthPath = this.getGroundTruthPath();
if (new File(groundTruthPath).isFile()) {
this.getGroundTruth().getGraphics().drawImage(awtRead(groundTruthPath), 0, 0, null);
} else {
this.getGroundTruth().clear(CLEAR);
}
}
{
final String classificationPath = this.getClassificationPath();
if (new File(classificationPath).isFile()) {
this.getClassification().getGraphics().drawImage(awtRead(classificationPath), 0, 0, null);
} else {
this.getClassification().clear(CLEAR);
}
}
break;
}
case NOP:
break;
}
}
public final Context setImage(final File imageFile) {
System.out.println(Tools.debug(Tools.DEBUG_STACK_OFFSET + 1, imageFile));
final File oldImageFile = this.getImageFile();
if (imageFile.isFile() && !imageFile.equals(oldImageFile)) {
this.getMainPanel().setImage(imageFile.getPath());
this.getMainPanel().getImageSelector().setFile(imageFile);
this.refreshGroundTruthAndClassification(Refresh.FROM_FILE);
preferences.put(IMAGE_PATH, imageFile.getPath());
}
return this;
}
public final Context setGroundTruth(final String name) {
if (new File(this.getGroundTruthPath(name)).isFile()) {
this.getMainPanel().getGroundTruthSelector().setFile(new File(name));
preferences.put(GROUND_TRUTH, name);
}
return this;
}
public final Context setExperiment(final File experimentFile) {
if (experimentFile.isFile()) {
this.getMainPanel().setExperiment((Experiment) xstream.fromXML(experimentFile));
this.getMainPanel().getExperimentSelector().setFile(experimentFile);
preferences.put(EXPERIMENT, experimentFile.getPath());
}
return this;
}
private final Context format(final Canvas canvas) {
final BufferedImage image = this.getImage();
if (image != null) {
canvas.setFormat(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);
} else {
canvas.setFormat(1, 1, BufferedImage.TYPE_INT_ARGB);
}
canvas.clear(CLEAR);
return this;
}
private static final long serialVersionUID = -2487965125442868238L;
public static final Color CLEAR = new Color(0, true);
/**
* @author codistmonk (creation 2015-02-17)
*/
public static enum Refresh {
NOP, CLEAR, FROM_FILE;
}
}
/**
* @author codistmonk (creation 2015-02-16)
*/
public static final class Experiment implements Serializable {
private final List<ClassDescription> classDescriptions = new ArrayList<>();
private final List<TrainingField> trainingFields = new ArrayList<>();
@Override
public final String toString() {
return "Experiment";
}
@NestedList(name="classes", element="class", elementClass=ClassDescription.class)
public final List<ClassDescription> getClassDescriptions() {
return this.classDescriptions;
}
@NestedList(name="training", element="training field", elementClass=TrainingField.class)
public final List<TrainingField> getTrainingFields() {
return this.trainingFields;
}
private static final long serialVersionUID = -4539259556658072410L;
/**
* @author codistmonk (creation 2015-02-16)
*/
public static final class ClassDescription implements Serializable {
private String name = "class";
private int label = 0xFF000000;
@StringGetter
@PropertyGetter("name")
public final String getName() {
return this.name;
}
@PropertySetter("name")
public final ClassDescription setName(final String name) {
this.name = name;
return this;
}
public final int getLabel() {
return this.label;
}
public final ClassDescription setLabel(final int label) {
this.label = label;
return this;
}
@PropertyGetter("label")
public final String getLabelAsString() {
return "#" + Integer.toHexString(this.getLabel()).toUpperCase(Locale.ENGLISH);
}
@PropertySetter("label")
public final ClassDescription setLabel(final String labelAsString) {
return this.setLabel((int) Long.parseLong(labelAsString.substring(1), 16));
}
private static final long serialVersionUID = 4974707407567297906L;
}
/**
* @author codistmonk (creation 2015-02-17)
*/
public static final class TrainingField implements Serializable {
private String imagePath = "";
private final Rectangle bounds = new Rectangle();
@PropertyGetter("image")
public final String getImagePath() {
return this.imagePath;
}
@PropertySetter("image")
public final TrainingField setImagePath(final String imagePath) {
this.imagePath = imagePath;
return this;
}
public final Rectangle getBounds() {
return this.bounds;
}
@PropertyGetter("bounds")
public final String getBoundsAsString() {
return join(",", this.getBounds().x, this.getBounds().y, this.getBounds().width, this.getBounds().height);
}
@PropertySetter("bounds")
public final TrainingField setBounds(final String boundsAsString) {
final int[] bounds = Arrays.stream(boundsAsString.split(",")).mapToInt(Integer::parseInt).toArray();
this.getBounds().setBounds(bounds[0], bounds[1], bounds[2], bounds[3]);
return this;
}
@Override
public final String toString() {
return new File(this.getImagePath()).getName() + "[" + this.getBoundsAsString() + "]";
}
private static final long serialVersionUID = 847822079141878928L;
}
}
} |
package com.hockeyhurd.hcorelib.api.math.expressions;
import com.hockeyhurd.hcorelib.mod.HCoreLibMain;
import java.util.Scanner;
import java.util.Stack;
/**
* Class for interpreting mathematical expressions.
*
* @author hockeyhurd
* @version 10/14/2016.
*/
public final class Interpreter {
private ETree tree;
/**
* Constructs the interpreter and initializes an empty expression tree.
*/
public Interpreter() {
tree = new ETree();
}
/**
* Helper function used for parsing strings into doubles.
*
* @param string String to parse.
* @return DoubleResult result.
*/
private static DoubleResult isValidDouble(String string) {
if (string == null || string.isEmpty())
return DoubleResult.getFailCondition();
else if (string.length() == 1 && EnumOp.isOp(string.charAt(0)))
return DoubleResult.getFailCondition();
try {
double result = Double.parseDouble(string);
return new DoubleResult(true, result);
}
catch (NumberFormatException e) {
if (HCoreLibMain.configHandler.isDebugMode()) {
// e.printStackTrace();
HCoreLibMain.logHelper.warn("Caught exception while parsing input:", string);
}
}
return DoubleResult.getFailCondition();
}
private static boolean isValidVariable(String string) {
char[] arr = string.toCharArray();
for (char c : arr) {
if (!Expression.ExpressionBuilder.isValidChar(c))
return false;
}
return true;
}
/**
* Attempts to process an expression to a double result.
*
* @param expression Expression to interpret.
* @param accessID Access ID used for retrieving data stored in the expression table per ID.
* @return double result.
*/
public double processExpressionDouble(Expression expression, int accessID) {
Stack<ENode> randStack = new Stack<ENode>();
Stack<ENode.OperatorNode> opStack = new Stack<ENode.OperatorNode>();
ENode.OperatorNode lastNode = null;
boolean firstPass = true;
boolean errored = false;
String buf;
Expression.ExpressionBuilder expressionBuilder = new Expression.ExpressionBuilder();
expressionBuilder.addString(expression.toString());
Expression.ExpressionBuilder.ExpressionResult expressionResult = expressionBuilder.preProcessInput();
Scanner scanner = new Scanner(expressionResult.string);
// double valBuf = 0.0;
while (scanner.hasNext()) {
buf = scanner.next();
boolean pushResult = true;
if (firstPass) {
if (!tree.isEmpty())
tree.clear();
firstPass = false;
}
DoubleResult doubleResult = isValidDouble(buf);
if (doubleResult.result) {
randStack.push(new ENode.ConstantNode(new Constant(doubleResult.value)));
}
else if (buf.length() == 1) {
final char c = buf.charAt(0);
if (c == '(' || c == '[' || c == '{') {
ENode.OperatorNode operatorNode = new ENode.OperatorNode(new Operator(EnumOp.getOperatorFromString(buf)));
if (tree.isEmpty())
tree.add(operatorNode);
else if (tree.isRootAVariable())
tree.setRoot(operatorNode);
lastNode = operatorNode;
opStack.push(operatorNode);
}
else if (c == ')' || c == ']' || c == '}') {
while (!((Operator) opStack.peek().value).isParenthesisLeft() && pushResult) {
// lastNode = opStack.pop();
pushResult = pushOpNode(randStack, opStack.peek());
opStack.pop();
}
opStack.pop();
}
else if (EnumOp.isOp(c)) {
Operator operator = new Operator(EnumOp.getOperatorFromString(buf));
while (!opStack.isEmpty() && ((Operator) opStack.peek().getValue()).getOperator().getPrecedence() <=
operator.getOperator().getPrecedence() && pushResult) {
lastNode = opStack.pop();
pushResult = pushOpNode(randStack, lastNode);
}
ENode.OperatorNode operatorNode = new ENode.OperatorNode(operator);
if (tree.isEmpty())
tree.add(operatorNode);
else if (tree.isRootAVariable())
tree.setRoot(operatorNode);
opStack.push(operatorNode);
}
// Must be variable?
else if (isValidVariable(buf)) {
// example (from above constant): randStack.push(new ENode.ConstantNode(new Constant(doubleResult.value)));
Variable var = VariableTable.getInstance().getVariable(accessID, buf);
if (var == null) {
var = new Variable(buf);
VariableTable.getInstance().put(accessID, var);
}
final ENode.VariableNode variableNode = new ENode.VariableNode(var);
if (tree.isEmpty())
tree.add(variableNode);
randStack.push(variableNode);
}
}
// An error has occurred!?!?
else {
HCoreLibMain.logHelper.severe(buf);
errored = true;
break;
}
}
while (!opStack.isEmpty()) {
pushOpNode(randStack, opStack.pop());
}
boolean wasAssignmentPre = false;
Variable variablePre = null;
if (lastNode != null) {
if (!tree.isEmpty()) {
if (tree.isAssignment()) {
wasAssignmentPre = true;
variablePre = (Variable) tree.getRootNode().left.getValue();
}
ENode node = randStack.pop();
tree.setRoot(node);
}
}
else if (randStack.size() == 1) {
tree.setRoot(randStack.peek());
}
if (tree != null) {
if (!errored) {
double result = tree.evaluate();
if (result == Double.NaN)
result = 0.0d;
if (wasAssignmentPre || tree.isAssignment()) {
final Variable var = wasAssignmentPre ? variablePre : (Variable) tree.getRootNode().left.getValue();
var.setValue(result);
VariableTable.getInstance().put(accessID, var);
}
return result;
}
else HCoreLibMain.logHelper.severe("Errored and aborted!");
// tree.clear();
errored = false;
}
return 0.0;
}
/**
* Attempts to process an expression to a String result.
*
* @param expression Expression to interpret.
* @param accessID Access ID used for retrieving data stored in the expression table per ID.
* @return InterpreterResult result.
*/
public InterpreterResult processExpressionString(Expression expression, int accessID) {
final double result = processExpressionDouble(expression, accessID);
return new InterpreterResult(expression.toString() + " = " + result, result);
}
/**
* Helper function to push operator nodes onto an operand stack.
*
* @param randStack Operand stack.
* @param n OperatorNode to push.
* @return boolean result.
*/
private static boolean pushOpNode(Stack<ENode> randStack, ENode.OperatorNode n) {
if (n == null || randStack == null || randStack.size() < 2) return false;
n.right = randStack.pop();
n.left = randStack.pop();
randStack.push(n);
return true;
}
/**
* Helper struct for DoubleResult.
*
* @author hockeyhurd
* @version 10/13/2016
*/
private static class DoubleResult {
boolean result;
double value;
DoubleResult(boolean result, double value) {
this.result = result;
this.value = value;
}
static DoubleResult getFailCondition() {
return new DoubleResult(false, Double.NaN);
}
}
} |
package uk.ac.ic.wlgitbridge.writelatex;
import uk.ac.ic.wlgitbridge.bridge.CandidateSnapshot;
import uk.ac.ic.wlgitbridge.bridge.RawDirectoryContents;
import uk.ac.ic.wlgitbridge.bridge.WritableRepositoryContents;
import uk.ac.ic.wlgitbridge.bridge.WriteLatexDataSource;
import uk.ac.ic.wlgitbridge.writelatex.api.request.exception.FailedConnectionException;
import uk.ac.ic.wlgitbridge.writelatex.api.request.getdoc.SnapshotGetDocRequest;
import uk.ac.ic.wlgitbridge.writelatex.api.request.getdoc.exception.InvalidProjectException;
import uk.ac.ic.wlgitbridge.writelatex.api.request.push.PostbackManager;
import uk.ac.ic.wlgitbridge.writelatex.api.request.push.SnapshotPushRequest;
import uk.ac.ic.wlgitbridge.writelatex.api.request.push.UnexpectedPostbackException;
import uk.ac.ic.wlgitbridge.writelatex.model.WLDataModel;
import java.io.IOException;
import java.util.List;
public class WriteLatexAPI implements WriteLatexDataSource {
private final WLDataModel dataModel;
private final PostbackManager postbackManager;
public WriteLatexAPI(WLDataModel dataModel) {
this.dataModel = dataModel;
postbackManager = new PostbackManager();
}
@Override
public boolean repositoryExists(String projectName) throws FailedConnectionException {
SnapshotGetDocRequest snapshotGetDocRequest = new SnapshotGetDocRequest(projectName);
snapshotGetDocRequest.request();
try {
snapshotGetDocRequest.getResult().getVersionID();
} catch (InvalidProjectException e) {
return false;
}
return true;
}
@Override
public List<WritableRepositoryContents> getWritableRepositories(String projectName) throws FailedConnectionException, InvalidProjectException {
return dataModel.updateProjectWithName(projectName);
}
@Override
public void putDirectoryContentsToProjectWithName(String projectName, RawDirectoryContents directoryContents, String hostname) throws SnapshotPostException, IOException, FailedConnectionException {
CandidateSnapshot candidate = dataModel.createCandidateSnapshotFromProjectWithContents(projectName, directoryContents, hostname);
new SnapshotPushRequest(candidate).request();
candidate.approveWithVersionID(postbackManager.getVersionID(projectName));
}
/* Called by postback thread. */
@Override
public void postbackReceivedSuccessfully(String projectName, int versionID) throws UnexpectedPostbackException {
postbackManager.postVersionIDForProject(projectName, versionID);
}
@Override
public void postbackReceivedWithException(String projectName, SnapshotPostException exception) throws UnexpectedPostbackException {
postbackManager.postExceptionForProject(projectName, exception);
}
} |
package vg.civcraft.mc.civchat2.command.commands;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import vg.civcraft.mc.civchat2.CivChat2;
import vg.civcraft.mc.civchat2.CivChat2Manager;
import vg.civcraft.mc.civchat2.command.CivChat2CommandHandler;
import vg.civcraft.mc.civchat2.utility.CivChat2Log;
import vg.civcraft.mc.civmodcore.command.PlayerCommand;
import vg.civcraft.mc.mercury.MercuryAPI;
import vg.civcraft.mc.mercury.MercuryPlugin;
import vg.civcraft.mc.namelayer.NameLayerPlugin;
public class Tell extends PlayerCommand{
private CivChat2 plugin = CivChat2.getInstance();
private CivChat2Manager chatMan;
private CivChat2Log logger = CivChat2.getCivChat2Log();
private CivChat2CommandHandler handler = (CivChat2CommandHandler) plugin.getCivChat2CommandHandler();
public Tell(String name) {
super(name);
setIdentifier("tell");
setDescription("This command is used to send a message or chat with another player");
setUsage("/tell <PlayerName> (message)");
setArguments(0,100);
}
@Override
public boolean execute(CommandSender sender, String[] args){
chatMan = plugin.getCivChat2Manager();
if(!(sender instanceof Player)){
//console man sending chat...
sender.sendMessage(ChatColor.YELLOW + "You must be a player to perform that command.");
return true;
}
Player player = (Player) sender;
if (args.length == 0){
String chattingWith = chatMan.getChannel(player.getName());
if (chattingWith != null) {
chatMan.removeChannel(player.getName());
player.sendMessage(ChatColor.GREEN + "You have been removed from private chat.");
}
else {
player.sendMessage(ChatColor.RED + "You are not in a private chat");
}
return true;
}
if (CivChat2.getInstance().isMercuryEnabled()){
for(String s : MercuryAPI.getAllPlayers()) {
if (s.equalsIgnoreCase(args[0])) {
if(args.length == 1){
chatMan.addChatChannel(player.getName(), args[0].toLowerCase());
player.sendMessage(ChatColor.GREEN + "You are now chatting with " + args[0] + " on another server.");
return true;
} else if(args.length >=2){
StringBuilder builder = new StringBuilder();
for (int x = 1; x < args.length; x++)
builder.append(args[x] + " ");
//This separator needs to be changed to load from config.
String sep = "|";
MercuryAPI.sendMessage(MercuryAPI.getServerforPlayer(args[0].toLowerCase()).getServerName(), "pm"+sep+player.getName()+sep+args[0].trim()+sep+builder.toString().replace(sep, ""), "civchat2");
player.sendMessage(ChatColor.LIGHT_PURPLE+"To "+args[0]+": "+builder.toString());
return true;
}
break;
}
}
}
UUID receiverUUID = chatMan.getPlayerUUID(args[0].trim());
Player receiver = Bukkit.getPlayer(receiverUUID);
if(receiver == null){
sender.sendMessage(ChatColor.RED + "There is no player with that name.");
return true;
}
if(! (receiver.isOnline()) ){
String offlinemsg = ChatColor.RED + "Error: Player is offline.";
sender.sendMessage(offlinemsg);
logger.debug(offlinemsg);
return true;
}
if(player.getName().equals(receiver.getName())){
sender.sendMessage(ChatColor.RED + "Error: You cannot send a message to yourself.");
return true;
}
if(args.length >= 2){
//player and message
StringBuilder builder = new StringBuilder();
for (int x = 1; x < args.length; x++)
builder.append(args[x] + " ");
chatMan.sendPrivateMsg(player, receiver, builder.toString());
return true;
}
else if(args.length == 1){
if (chatMan.isIgnoringPlayer(player.getName(), receiver.getName()) ){
player.sendMessage(ChatColor.YELLOW+"You need to unignore "+receiver.getName());
return true;
}
chatMan.addChatChannel(player.getName(), receiver.getName());
player.sendMessage(ChatColor.GREEN + "You are now chatting with " + receiver.getName() + ".");
return true;
}
handler.helpPlayer(this, sender);
return true;
}
@Override
public List<String> tabComplete(CommandSender sender, String[] args) {
if (args.length != 1)
return null;
List<String> namesToReturn = new ArrayList<String>();
if (plugin.isMercuryEnabled()) {
Set<String> players = MercuryAPI.instance.getAllPlayers();
for (String x: players) {
if (x.toLowerCase().startsWith(args[0].toLowerCase()))
namesToReturn.add(x);
}
}
else {
for (Player p: Bukkit.getOnlinePlayers()) {
if (p.getName().toLowerCase().startsWith(args[0].toLowerCase()))
namesToReturn.add(p.getName());
}
}
return namesToReturn;
}
} |
package org.spine3.test;
import org.junit.Test;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkNotNull;
import static junit.framework.TestCase.assertFalse;
import static junit.framework.TestCase.assertTrue;
/**
* @author Illia Shepilov
*/
public class NullToleranceTestShould {
private static final Object DEFAULT_VALUE = new Object();
@Test
public void return_false_for_class_with_methods_accepting_non_declared_null_parameters() {
final NullToleranceTest nullToleranceTest =
NullToleranceTest.newBuilder()
.setClass(UtilityClassWithReferenceParameters.class)
.addDefaultValue(new Object())
.build();
final boolean passed = nullToleranceTest.check();
assertFalse(passed);
}
@Test
public void return_true_for_class_with_ignored_method_without_check() {
final NullToleranceTest nullToleranceTest =
NullToleranceTest.newBuilder()
.setClass(UtilityClassWithReferenceParameters.class)
.excludeMethod("methodWithoutCheck")
.addDefaultValue(DEFAULT_VALUE)
.build();
final boolean passed = nullToleranceTest.check();
assertTrue(passed);
}
@Test
public void return_true_for_class_with_methods_with_primitive_parameters() {
final NullToleranceTest nullToleranceTest =
NullToleranceTest.newBuilder()
.setClass(UtilityClassWithPrimitiveParameters.class)
.build();
final boolean passed = nullToleranceTest.check();
assertTrue(passed);
}
@Test
public void return_false_for_class_with_method_with_primitive_and_reference_parameters_without_check() {
final NullToleranceTest nullToleranceTest = NullToleranceTest.newBuilder()
.setClass(UtilityClassWithMixedParameters.class)
.addDefaultValue(DEFAULT_VALUE)
.build();
final boolean passed = nullToleranceTest.check();
assertFalse(passed);
}
@Test
public void return_true_for_class_with_method_with_primitive_and_reference_types_with_check() {
final NullToleranceTest nullToleranceTest =
NullToleranceTest.newBuilder()
.setClass(UtilityClassWithMixedParameters.class)
.excludeMethod("methodWithMixedParameterTypesWithoutCheck")
.addDefaultValue(new Object())
.build();
final boolean passed = nullToleranceTest.check();
assertTrue(passed);
}
@Test(expected = RuntimeException.class)
public void throw_exception_when_invoke_method_which_throws_exception() {
final NullToleranceTest nullToleranceTest =
NullToleranceTest.newBuilder()
.setClass(UtilityClassWithThrownExceptionInTheMethod.class)
.build();
nullToleranceTest.check();
}
@Test
public void return_true_when_check_class_with_util_and_non_util_method() {
final NullToleranceTest nullToleranceTest = NullToleranceTest.newBuilder()
.setClass(ClassWithNonUtilMethod.class)
.addDefaultValue(DEFAULT_VALUE)
.build();
final boolean passed = nullToleranceTest.check();
assertTrue(passed);
}
@Test
public void pass_the_check_when_invoke_method_with_private_modifier() {
final NullToleranceTest nullToleranceTest = NullToleranceTest.newBuilder()
.setClass(UtilityClassWithPrivateMethod.class)
.addDefaultValue(DEFAULT_VALUE)
.build();
final boolean passed = nullToleranceTest.check();
assertTrue(passed);
}
@Test
public void ignore_the_method_with_nullable_parameters() {
final NullToleranceTest nullToleranceTest = NullToleranceTest.newBuilder()
.setClass(ClassWithNullableMethodParameters.class)
.excludeMethod("methodWithMixedParameters")
.build();
final boolean passed = nullToleranceTest.check();
assertTrue(passed);
}
@Test
public void pass_the_check_when_method_contains_nullable_and_not_nullable_parameters() {
final NullToleranceTest nullToleranceTest = NullToleranceTest.newBuilder()
.setClass(ClassWithNullableMethodParameters.class)
.addDefaultValue("default value")
.addDefaultValue(DEFAULT_VALUE)
.build();
final boolean passed = nullToleranceTest.check();
assertTrue(passed);
}
@Test(expected = NullPointerException.class)
public void throw_exception_when_parameter_of_invokable_method_does_not_have_default_value() {
final NullToleranceTest nullToleranceTest = NullToleranceTest.newBuilder()
.setClass(ClassWithNullableMethodParameters.class)
.build();
nullToleranceTest.check();
}
@SuppressWarnings("unused") // accessed via reflection
private static class UtilityClassWithReferenceParameters {
public static void methodWithoutCheck(Object param) {
}
public static void methodWithCheck(Object first, Object second) {
checkNotNull(first);
checkNotNull(second);
}
}
@SuppressWarnings("unused") // accessed via reflection
private static class UtilityClassWithPrimitiveParameters {
public static void methodWithPrimitiveParams(int first, double second) {
}
}
@SuppressWarnings("unused") // accessed via reflection
private static class UtilityClassWithMixedParameters {
public static void methodWithMixedParameterTypesWithoutCheck(long first, Object second) {
}
public static void methodWithMixedParameterTypesWithCheck(float first, Object second) {
checkNotNull(second);
}
}
@SuppressWarnings("unused") // accessed via reflection
private static class UtilityClassWithThrownExceptionInTheMethod {
public static void methodWhichThrowsException(Object param) {
throw new RuntimeException("Occurred exception.");
}
}
@SuppressWarnings("unused") // accessed via reflection
private static class ClassWithNonUtilMethod {
public void nonUtilMethod(Object param) {
}
public static void utilMethod(Object param) {
checkNotNull(param);
}
}
@SuppressWarnings("unused") // accessed via reflection
private static class UtilityClassWithPrivateMethod {
private static void privateMethod(Object first, Object second) {
}
public static void nonPrivateMethod(Object first, Object second) {
checkNotNull(first);
checkNotNull(second);
}
}
@SuppressWarnings("unused") // accessed via reflection
private static class ClassWithNullableMethodParameters {
public static void nullableParamsMethod(@Nullable Object first, @Nullable Object second) {
}
public static void methodWithMixedParameters(@Nullable Object first, String second) {
checkNotNull(second);
}
}
} |
package arez.component;
import arez.Arez;
import arez.ArezContext;
import arez.Component;
import arez.Disposable;
import arez.Observable;
import arez.Observer;
import arez.annotations.ComponentNameRef;
import arez.annotations.ComponentRef;
import arez.annotations.ContextRef;
import arez.annotations.ObservableRef;
import arez.annotations.PreDispose;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Stream;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.realityforge.anodoc.TestOnly;
import org.realityforge.braincheck.Guards;
import static org.realityforge.braincheck.Guards.*;
/**
* Abstract base class for observable Arez components that contain other components.
*
* <p>When multiple results are returned as a list, they are passed through {@link CollectionsUtil#asList(Stream)} or
* {@link CollectionsUtil#wrap(List)} and this will convert the result set to an unmodifiable variant if
* {@link Arez#areCollectionsPropertiesUnmodifiable()} returns true. Typically this means that in
* development mode these will be made immutable but that the lists will be passed through as-is
* in production mode for maximum performance.</p>
*/
public abstract class AbstractContainer<K, T>
{
/**
* A map of all the entities ArezId to entity.
*/
private final HashMap<K, EntityReference<T>> _entities = new HashMap<>();
/**
* Attach specified entity to the set of entities managed by the container.
* This should not be invoked if the entity is already attached to the repository.
*
* @param entity the entity to register.
*/
@SuppressWarnings( "SuspiciousMethodCalls" )
protected void attach( @Nonnull final T entity )
{
if ( Arez.shouldCheckApiInvariants() )
{
apiInvariant( () -> !_entities.containsKey( Identifiable.getArezId( entity ) ),
() -> "Arez-0136: Called attach() passing an entity that ia already attached " +
"to the container. Entity: " + entity );
}
getEntitiesObservable().preReportChanged();
final EntityReference<T> entry = new EntityReference<>( entity );
final K arezId = Identifiable.getArezId( entity );
final Observer monitor =
getContext().when( Arez.areNativeComponentsEnabled() ? component() : null,
Arez.areNamesEnabled() ? getContainerName() + ".EntityWatcher." + arezId : null,
true,
() -> ComponentObservable.notObserved( entity ),
() -> detach( entity ),
true,
true );
entry.setMonitor( monitor );
_entities.put( arezId, entry );
getEntitiesObservable().reportChanged();
}
/**
* Return true if disposing the container should result in disposing contained entities or just detaching the entities.
*
* @return true to dispose entities on container dispose, false to detach entities on container disposed.
*/
protected abstract boolean shouldDisposeEntryOnDispose();
/**
* Dispose all the entities associated with the container.
*/
@PreDispose
protected void preDispose()
{
_entities.values().forEach( entry -> detachEntry( entry, shouldDisposeEntryOnDispose() ) );
_entities.clear();
}
/**
* Return true if the specified entity is contained in the container.
*
* @param entity the entity.
* @return true if the specified entity is contained in the container, false otherwise.
*/
protected boolean contains( @Nonnull final T entity )
{
getEntitiesObservable().reportObserved();
return Disposable.isNotDisposed( entity ) && _entities.containsKey( Identifiable.<K>getArezId( entity ) );
}
/**
* Detach the entity from the container and dispose the entity.
* The entity must be attached to the container.
*
* @param entity the entity to destroy.
*/
protected void destroy( @Nonnull final T entity )
{
detach( entity, true );
}
/**
* Detach entity from container without disposing entity.
* The entity must be attached to the container.
*
* @param entity the entity to detach.
*/
protected void detach( @Nonnull final T entity )
{
detach( entity, false );
}
/**
* Detach entity from container without disposing entity.
* The entity must be attached to the container.
*
* @param entity the entity to detach.
*/
private void detach( @Nonnull final T entity, final boolean disposeEntity )
{
// This method has been extracted to try and avoid GWT inlining into invoker
final EntityReference<T> entry = _entities.remove( Identifiable.<K>getArezId( entity ) );
if ( null != entry )
{
getEntitiesObservable().preReportChanged();
detachEntry( entry, disposeEntity );
getEntitiesObservable().reportChanged();
}
else
{
Guards.fail( () -> "Arez-0157: Called detach() passing an entity that was not attached to the container. Entity: " +
entity );
}
}
private void detachEntry( @Nonnull final EntityReference<T> entry, final boolean shouldDisposeEntity )
{
if ( shouldDisposeEntity )
{
Disposable.dispose( entry );
}
else
{
final Observer monitor = entry.getMonitor();
if ( null != monitor )
{
Disposable.dispose( monitor );
}
}
}
/**
* Return the entity with the specified ArezId or null if no such entity.
*
* @param arezId the id of entity.
* @return the entity or null if no such entity.
*/
@Nullable
protected T findByArezId( @Nonnull final K arezId )
{
final EntityReference<T> entry = _entities.get( arezId );
if ( null != entry && Disposable.isNotDisposed( entry ) )
{
final T entity = entry.getEntity();
ComponentObservable.observe( entity );
return entity;
}
else
{
getEntitiesObservable().reportObserved();
return null;
}
}
/**
* Return the entity with the specified ArezId else throw an exception.
*
* @param arezId the id of entity.
* @return the entity.
* @throws NoSuchEntityException if unable to locate entity with specified ArezId.
*/
@Nonnull
protected T getByArezId( @Nonnull final K arezId )
throws NoSuchEntityException
{
final T entity = findByArezId( arezId );
if ( null == entity )
{
throw new NoSuchEntityException( arezId );
}
return entity;
}
/**
* Return the component associated with the container if native components enabled.
*
* @return the component associated with the container if native components enabled.
*/
@ComponentRef
@Nonnull
protected abstract Component component();
/**
* Return the context associated with the container.
*
* @return the context associated with the container.
*/
@ContextRef
@Nonnull
protected abstract ArezContext getContext();
/**
* Return the name associated with the container.
*
* @return the name associated with the container.
*/
@ComponentNameRef
@Nonnull
protected abstract String getContainerName();
/**
* Return the observable associated with entities.
* This template method is implemented by the Arez annotation processor and is used internally
* to container. It should not be invoked by extensions.
*
* @return the Arez observable associated with entities observable property.
*/
@ObservableRef
@Nonnull
protected abstract Observable getEntitiesObservable();
/**
* Return a stream of all entities in the container.
*
* @return the underlying entities.
*/
@arez.annotations.Observable( expectSetter = false )
@Nonnull
public Stream<T> entities()
{
return _entities.values().stream().filter( Disposable::isNotDisposed ).map( EntityReference::getEntity );
}
@TestOnly
final HashMap<K, EntityReference<T>> getEntities()
{
return _entities;
}
} |
package arez.component;
import arez.Arez;
import arez.ArezContext;
import arez.Component;
import arez.Disposable;
import arez.Observable;
import arez.Observer;
import arez.annotations.ComponentNameRef;
import arez.annotations.ComponentRef;
import arez.annotations.ContextRef;
import arez.annotations.ObservableRef;
import arez.annotations.PreDispose;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Stream;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.realityforge.anodoc.TestOnly;
import org.realityforge.braincheck.Guards;
/**
* Abstract base class for observable Arez components that contain other components.
*
* <p>When multiple results are returned as a list, they are passed through {@link CollectionsUtil#asList(Stream)} or
* {@link CollectionsUtil#wrap(List)} and this will convert the result set to an unmodifiable variant if
* {@link Arez#areCollectionsPropertiesUnmodifiable()} returns true. Typically this means that in
* development mode these will be made immutable but that the lists will be passed through as-is
* in production mode for maximum performance.</p>
*/
public abstract class AbstractContainer<K, T>
{
/**
* A map of all the entities ArezId to entity.
*/
private final HashMap<K, RepositoryEntry<T>> _entities = new HashMap<>();
/**
* Return the component associated with the container if native components enabled.
*
* @return the component associated with the container if native components enabled.
*/
@ComponentRef
@Nonnull
protected abstract Component component();
/**
* Register specified entity in list of entities managed by the container.
* The expectation that this is invoked after the entity has been created but before it is returned
* to the container user.
*
* @param entity the entity to register.
*/
protected final void registerEntity( @Nonnull final T entity )
{
getEntitiesObservable().preReportChanged();
final RepositoryEntry<T> entry = new RepositoryEntry<>( entity );
final K arezId = Identifiable.getArezId( entity );
_entities.put( arezId, entry );
final Observer monitor =
getContext().when( Arez.areNativeComponentsEnabled() ? component() : null,
Arez.areNamesEnabled() ? getContainerName() + ".EntityWatcher." + arezId : null,
true,
() -> !ComponentObservable.observe( entity ),
() -> destroy( entity ),
true,
true );
entry.setMonitor( monitor );
getEntitiesObservable().reportChanged();
}
/**
* Dispose all the entities associated with the container.
*/
@PreDispose
protected void preDispose()
{
_entities.values().forEach( e -> Disposable.dispose( e ) );
_entities.clear();
}
/**
* Return true if the specified entity is contained in the container.
*
* @param entity the entity.
* @return true if the specified entity is contained in the container, false otherwise.
*/
protected boolean contains( @Nonnull final T entity )
{
getEntitiesObservable().reportObserved();
return Disposable.isNotDisposed( entity ) && _entities.containsKey( Identifiable.<K>getArezId( entity ) );
}
/**
* Remove the supplied entity from the container and dispose the entity.
* The entity must have been associated with this container either via {@link #registerEntity(Object)}
* and must not have been removed from container.
*
* @param entity the entity to destroy.
*/
protected void destroy( @Nonnull final T entity )
{
final RepositoryEntry<T> entry = _entities.remove( Identifiable.<K>getArezId( entity ) );
if ( null != entry )
{
getEntitiesObservable().preReportChanged();
Disposable.dispose( entry );
getEntitiesObservable().reportChanged();
}
else
{
Guards.fail( () -> "Arez-0136: Called destroy() passing an entity that was not in the container. Entity: " + entity );
}
}
/**
* Return the entity with the specified ArezId or null if no such entity.
*
* @param arezId the id of entity.
* @return the entity or null if no such entity.
*/
@Nullable
protected T findByArezId( @Nonnull final K arezId )
{
final RepositoryEntry<T> entry = _entities.get( arezId );
if ( null != entry && Disposable.isNotDisposed( entry ) )
{
final T entity = entry.getEntity();
ComponentObservable.observe( entity );
return entity;
}
else
{
getEntitiesObservable().reportObserved();
return null;
}
}
/**
* Return the entity with the specified ArezId else throw an exception.
*
* @param arezId the id of entity.
* @return the entity.
* @throws NoSuchEntityException if unable to locate entity with specified ArezId.
*/
@Nonnull
protected T getByArezId( @Nonnull final K arezId )
throws NoSuchEntityException
{
final T entity = findByArezId( arezId );
if ( null == entity )
{
throw new NoSuchEntityException( arezId );
}
return entity;
}
/**
* Return the context associated with the container.
*
* @return the context associated with the container.
*/
@ContextRef
@Nonnull
protected abstract ArezContext getContext();
/**
* Return the name associated with the container.
*
* @return the name associated with the container.
*/
@ComponentNameRef
@Nonnull
protected abstract String getContainerName();
/**
* Return the observable associated with entities.
* This template method is implemented by the Arez annotation processor and is used internally
* to container. It should not be invoked by extensions.
*
* @return the Arez observable associated with entities observable property.
*/
@ObservableRef
@Nonnull
protected abstract Observable getEntitiesObservable();
/**
* Return a stream of all entities in the container.
*
* @return the underlying entities.
*/
@arez.annotations.Observable( expectSetter = false )
@Nonnull
public Stream<T> entities()
{
return _entities.values().stream().filter( Disposable::isNotDisposed ).map( RepositoryEntry::getEntity );
}
@TestOnly
final HashMap<K, RepositoryEntry<T>> getEntities()
{
return _entities;
}
} |
package com.intellij.uiDesigner.designSurface;
import com.intellij.uiDesigner.FormEditingUtil;
import com.intellij.uiDesigner.RadComponent;
import com.intellij.uiDesigner.RadContainer;
import com.intellij.uiDesigner.core.GridConstraints;
import com.intellij.uiDesigner.core.GridLayoutManager;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
/**
* @author Anton Katilin
* @author Vladimir Kondratyev
*/
public final class Painter {
/**
* This color is used to paint decoration of non selected components
*/
private static final Color NON_SELECTED_BOUNDARY_COLOR = new Color(114, 126, 143);
/**
* This color is used to paint decoration of selected components
*/
private static final Color SELECTED_BOUNDARY_COLOR = new Color(8, 8, 108);
/**
* This color is used to paint grid cell for selected container
*/
private static final Color SELECTED_GRID_COLOR = new Color(47, 67, 96);
/**
* This color is used to paint grid cell for non selected container
*/
private static final Color NON_SELECTED_GRID_COLOR = new Color(130, 140, 155);
public final static int WEST_MASK = 1;
public final static int EAST_MASK = 2;
public final static int NORTH_MASK = 4;
public final static int SOUTH_MASK = 8;
private final static int R = 2;
private final static int GAP = R;
private static final int NW = 0;
private static final int N = 1;
private static final int NE = 2;
private static final int E = 3;
private static final int SE = 4;
private static final int S = 5;
private static final int SW = 6;
private static final int W = 7;
private Painter() {
}
public static void paintComponentDecoration(final GuiEditor editor, final RadComponent component, final Graphics g){
// Collect selected components and paint decoration for non selected components
final ArrayList<RadComponent> selection = new ArrayList<RadComponent>();
final Rectangle layeredPaneRect = editor.getLayeredPane().getVisibleRect();
FormEditingUtil.iterate(
component,
new FormEditingUtil.ComponentVisitor<RadComponent>() {
public boolean visit(final RadComponent component) {
if(!component.getDelegee().isShowing()){ // Skip invisible components
return true;
}
final Shape oldClip = g.getClip();
final RadContainer parent = component.getParent();
if(parent != null){
final Point p = SwingUtilities.convertPoint(component.getDelegee(), 0, 0, editor.getLayeredPane());
final Rectangle visibleRect = layeredPaneRect.intersection(new Rectangle(p.x, p.y, parent.getWidth(), parent.getHeight()));
g.setClip(visibleRect);
}
if(component.isSelected()){ // we will paint selection later
selection.add(component);
}
else{
paintComponentBoundsImpl(editor, component, g);
}
paintGridOutline(editor, component, g);
if(parent != null){
g.setClip(oldClip);
}
return true;
}
}
);
// Let's paint decoration for selected components
for(int i = selection.size() - 1; i >= 0; i
final Shape oldClip = g.getClip();
final RadComponent c = selection.get(i);
final RadContainer parent = c.getParent();
if(parent != null){
final Point p = SwingUtilities.convertPoint(c.getDelegee(), 0, 0, editor.getLayeredPane());
final Rectangle visibleRect = layeredPaneRect.intersection(new Rectangle(p.x, p.y, parent.getWidth(), parent.getHeight()));
g.setClip(visibleRect);
}
paintComponentBoundsImpl(editor, c, g);
if(parent != null){
g.setClip(oldClip);
}
}
}
/**
* Paints container border. For grids the method also paints vertical and
* horizontal lines that indicate bounds of the rows and columns.
* Method does nothing if the <code>component</code> is not an instance
* of <code>RadContainer</code>.
*/
private static void paintComponentBoundsImpl(final GuiEditor editor, final RadComponent component, final Graphics g){
if (component == null) {
//noinspection HardCodedStringLiteral
throw new IllegalArgumentException("component cannot be null");
}
if (!(component instanceof RadContainer)){
return;
}
final Point point = SwingUtilities.convertPoint(
component.getDelegee(),
0,
0,
editor.getRootContainer().getDelegee()
);
g.translate(point.x, point.y);
try{
if (component.isSelected()) {
g.setColor(SELECTED_BOUNDARY_COLOR);
}
else {
g.setColor(NON_SELECTED_BOUNDARY_COLOR);
}
g.drawRect(0, 0, component.getWidth() - 1, component.getHeight() - 1);
}finally{
g.translate(-point.x, -point.y);
}
}
/**
* This method paints grid bounds for "grid" containers
*/
public static void paintGridOutline(final GuiEditor editor, @NotNull final RadComponent component, final Graphics g){
if (component == null) {
throw new IllegalArgumentException("component cannot be null");
}
if (!(component instanceof RadContainer)){
return;
}
final RadContainer container = (RadContainer)component;
if(!container.isGrid()){
return;
}
final Point point = SwingUtilities.convertPoint(
component.getDelegee(),
0,
0,
editor.getRootContainer().getDelegee()
);
g.translate(point.x, point.y);
try{
// Paint grid
final GridLayoutManager gridLayout = (GridLayoutManager)container.getLayout();
if (component.isSelected()) {
g.setColor(SELECTED_GRID_COLOR);
}
else {
g.setColor(NON_SELECTED_GRID_COLOR);
}
// Horizontal lines
final int width = component.getWidth();
final int[] horzGridLines = gridLayout.getHorizontalGridLines();
final int height = component.getHeight();
final int[] vertGridLines = gridLayout.getVerticalGridLines();
boolean[][] horzSkippedLineSegments = null;
boolean[][] vertSkippedLineSegments = null;
for(RadComponent childComponent: container.getComponents()) {
final GridConstraints constraints = childComponent.getConstraints();
if (constraints.getColSpan() > 1) {
if (vertSkippedLineSegments == null) {
vertSkippedLineSegments = new boolean[vertGridLines.length][height+4];
}
for(int col = constraints.getColumn()+1; col < constraints.getColumn() + constraints.getColSpan(); col++) {
for(int y=horzGridLines [constraints.getRow()]+4;
y<horzGridLines [constraints.getRow() + constraints.getRowSpan()]-4;
y++) {
vertSkippedLineSegments [col][y] = true;
}
}
}
if (constraints.getRowSpan() > 1) {
if (horzSkippedLineSegments == null) {
horzSkippedLineSegments = new boolean[horzGridLines.length][width+4];
}
for(int row = constraints.getRow()+1; row < constraints.getRow() + constraints.getRowSpan(); row++) {
for(int x=vertGridLines [constraints.getColumn()]+4;
x<vertGridLines [constraints.getColumn() + constraints.getColSpan()]-4;
x++) {
horzSkippedLineSegments [row][x] = true;
}
}
}
}
for (int i = 1; i < horzGridLines.length - 1; i++) {
final int y = horzGridLines [i];
// Draw dotted horizontal line
for(int x = 0; x < width; x+=4) {
if (horzSkippedLineSegments == null || (!horzSkippedLineSegments[i][x] && !horzSkippedLineSegments[i][x+1] && !horzSkippedLineSegments[i][x+2])) {
UIUtil.drawLine(g, x, y, Math.min(x + 2, width - 1), y);
}
}
}
// Vertical lines
for (int i = 1; i < vertGridLines.length - 1; i++) {
final int x = vertGridLines [i];
// Draw dotted vertical line
for(int y = 0; y < height; y+=4) {
if (vertSkippedLineSegments == null || (!vertSkippedLineSegments[i][y] && !vertSkippedLineSegments[i][y+1] && !vertSkippedLineSegments[i][y+2])) {
UIUtil.drawLine(g, x, y, x, Math.min(y + 2, height - 1));
}
}
}
}finally{
g.translate(-point.x, -point.y);
}
}
/**
* Paints selection for the specified <code>component</code>.
*/
public static void paintSelectionDecoration(final RadComponent component, final Graphics g){
if (component == null) {
//noinspection HardCodedStringLiteral
throw new IllegalArgumentException("component cannot be null");
}
if (component.isSelected()) {
g.setColor(Color.BLUE);
final Point[] points = getPoints(component.getWidth(), component.getHeight());
for (final Point point : points) {
g.fillRect(point.x - R, point.y - R, 2 * R + 1, 2 * R + 1);
}
}
}
/**
* @param x in component's coord system
* @param y in component's coord system
*/
public static int getResizeMask(@NotNull final RadComponent component, final int x, final int y) {
//noinspection ConstantConditions
if (component == null) {
throw new IllegalArgumentException("component cannot be null");
}
if (component.getParent() == null || !component.isSelected()) {
return 0;
}
// only components in XY can be resized...
/*
if (!component.getParent().isXY()) {
return 0;
}
*/
final int width=component.getWidth();
final int height=component.getHeight();
final Point[] points = getPoints(width, height);
if (isInside(x, y, points[SE])) {
return EAST_MASK | SOUTH_MASK;
}
else if (isInside(x,y,points[NW])) {
return WEST_MASK | NORTH_MASK;
}
else if(isInside(x,y,points[N])){
return NORTH_MASK;
}
else if(isInside(x,y,points[NE])){
return EAST_MASK | NORTH_MASK;
}
else if (isInside(x, y, points[W])){
return WEST_MASK;
}
else if (isInside(x, y, points[E])){
return EAST_MASK;
}
else if (isInside(x, y, points[SW])){
return WEST_MASK | SOUTH_MASK;
}
else if (isInside(x, y, points[S])){
return SOUTH_MASK;
}
else{
return 0;
}
}
private static boolean isInside(final int x, final int y, final Point r) {
return x >= r.x - R && x <= r.x + R && y >= r.y - R && y <= r.y + R;
}
public static int getResizeCursor(final int resizeMask){
if (resizeMask == (WEST_MASK | NORTH_MASK)) {
return Cursor.NW_RESIZE_CURSOR;
}
else if (resizeMask == NORTH_MASK) {
return Cursor.N_RESIZE_CURSOR;
}
else if (resizeMask == (EAST_MASK | NORTH_MASK)) {
return Cursor.NE_RESIZE_CURSOR;
}
else if (resizeMask == WEST_MASK) {
return Cursor.W_RESIZE_CURSOR;
}
else if (resizeMask == EAST_MASK) {
return Cursor.E_RESIZE_CURSOR;
}
else if (resizeMask == (WEST_MASK | SOUTH_MASK)) {
return Cursor.SW_RESIZE_CURSOR;
}
else if (resizeMask == SOUTH_MASK) {
return Cursor.S_RESIZE_CURSOR;
}
else if (resizeMask == (EAST_MASK | SOUTH_MASK)) {
return Cursor.SE_RESIZE_CURSOR;
}
else {
//noinspection HardCodedStringLiteral
throw new IllegalArgumentException("unknown resizeMask: " + resizeMask);
}
}
public static Point[] getPoints(final int width, final int height) {
final Point[] points = new Point[8];
points[NW] = new Point(GAP, GAP);
points[N] = new Point(width / 2, GAP);
points[NE] = new Point(width - GAP - 1, GAP);
points[E] = new Point(width - GAP - 1, height / 2);
points[SE] = new Point(width - GAP - 1, height - GAP - 1);
points[S] = new Point(width / 2, height - GAP - 1);
points[SW] = new Point(GAP, height - GAP - 1);
points[W] = new Point(GAP, height / 2);
return points;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.